Skip to content
Python

wip

mohamdev835432221360
diff --git a/benchmark/purge_3dpw_test.sh b/benchmark/purge_3dpw_test.sh
new file mode 100755
index 0000000..6dc5b56
--- /dev/null
+++ b/benchmark/purge_3dpw_test.sh
@@ -0,0 +1,61 @@
+#!/usr/bin/env bash
+# Remove every 3DPW *test* sequence crop from a distillation folder, so the
+# 3DPW test split can be used as a real benchmark.
+#
+# Dry run (default — prints what it would remove, deletes nothing):
+# ./benchmark/purge_3dpw_test.sh /path/to/data/sam3d_distill_mix
+# Actually delete:
+# ./benchmark/purge_3dpw_test.sh /path/to/data/sam3d_distill_mix --delete
+#
+# Crops are named imageFiles_<sequence>_image_<frame>_p<n>.{npz,png}
+# and the pattern anchors on the literal "_image_" that follows the sequence
+# name, so no sequence can match another one's files by prefix.
+
+set -euo pipefail
+
+ROOT="${1:?usage: $0 <distill_dir> [--delete]}"
+MODE="${2:---dry-run}"
+
+# The 24 official 3DPW test sequences.
+TEST_SEQS="
+downtown_arguing_00 downtown_bar_00 downtown_bus_00 downtown_cafe_00
+downtown_car_00 downtown_crossStreets_00 downtown_downstairs_00
+downtown_enterShop_00 downtown_rampAndStairs_00 downtown_runForBus_00
+downtown_runForBus_01 downtown_sitOnStairs_00 downtown_stairs_00
+downtown_upstairs_00 downtown_walkBridge_01 downtown_walking_00
+downtown_walkUphill_00 downtown_warmWelcome_00 downtown_weeklyMarket_00
+downtown_windowShopping_00 flat_guitar_01 flat_packBags_00
+office_phoneCall_00 outdoors_fencing_01
+"
+
+ANN="$ROOT/annotations"
+IMG="$ROOT/images"
+[[ -d "$ANN" && -d "$IMG" ]] || { echo "ERROR: $ROOT needs annotations/ and images/"; exit 1; }
+
+before_a=$(find "$ANN" -maxdepth 1 -type f | wc -l)
+before_i=$(find "$IMG" -maxdepth 1 -type f | wc -l)
+total=0
+
+for s in $TEST_SEQS; do
+ n=$(find "$ANN" -maxdepth 1 -name "imageFiles_${s}_image_*" | wc -l)
+ total=$((total + n))
+ printf ' %-30s %6d\n' "$s" "$n"
+ if [[ "$MODE" == "--delete" ]]; then
+ find "$ANN" -maxdepth 1 -name "imageFiles_${s}_image_*" -delete
+ find "$IMG" -maxdepth 1 -name "imageFiles_${s}_image_*" -delete
+ fi
+done
+
+echo
+echo " test-sequence crops found: $total"
+if [[ "$MODE" == "--delete" ]]; then
+ after_a=$(find "$ANN" -maxdepth 1 -type f | wc -l)
+ after_i=$(find "$IMG" -maxdepth 1 -type f | wc -l)
+ echo " annotations: $before_a -> $after_a"
+ echo " images : $before_i -> $after_i"
+ [[ "$after_a" -eq "$after_i" ]] \
+ && echo " OK: annotations and images still paired" \
+ || echo " WARNING: counts diverged — inspect before training"
+else
+ echo " DRY RUN — nothing deleted. Re-run with --delete to apply."
+fi
diff --git a/instanthmr_distill_train/submit_train_distill.sh b/instanthmr_distill_train/submit_train_distill.sh
deleted file mode 100755
index 1e11cd5..0000000
--- a/instanthmr_distill_train/submit_train_distill.sh
+++ /dev/null
@@ -1,49 +0,0 @@
-#!/bin/sh -e
-
-echo "example: $0 --gpu 1"
-
-# if `requirements.txt` is present, virtual environment is installed and used
-EXEC="python3 train_distill.py"
-
-GPU_REQUIRED=true
-
-. /pfcalcul/tools/sbatchHelpers5.sh
-
-# --data_root points at the dataset synced by datasynch_perso (see below).
-# It is synced next to this project folder, i.e. ../instanthmr_data once we
-# cd into instanthmr_distill_train.
-EXEC="python3 -u train_distill.py --data_root /datasets/instanthmr_data --num_workers 8 --batch_size 128 $useropt"
-
-# SBATCH --output/--error paths are relative to the submission directory, so
-# create the log folder before submitting.
-mkdir -p instanthmr_distill
-
-jobMessage=$(
-######################### SBATCH launcher
-######################### #SBATCH --option # <= this is an enabled paramater
-######################### ##SBATCH --option # <= this is a disabled parameter
-sbatch ${sbatchopt} << eof
-#!/bin/bash
-#SBATCH --job-name="instanthmr_distill"
-#SBATCH --mail-type=ALL
-#SBATCH --ntasks=1
-#SBATCH --cpus-per-task=8
-#SBATCH --output=instanthmr_distill/stdout.txt
-#SBATCH --error=instanthmr_distill/stderr.txt
-#SBATCH --account=dept_rob
-#SBATCH --partition=robgpu
-#SBATCH --gres=gpu:1
-#SBATCH --mem-per-gpu=50000
-#SBATCH --time=4-00:00:00
-
-. /pfcalcul/tools/sbatchHelpers5.sh
-
-/pfcalcul/tools/datasync /datasets/instanthmr_data
-
-
-time $EXEC
-
-eof
-)
-
-showSubmitted
diff --git a/instanthmr_distill_train/submit_train_distill_finetune_dolcino.sh b/instanthmr_distill_train/submit_train_distill_finetune_dolcino.sh
deleted file mode 100755
index 7229f93..0000000
--- a/instanthmr_distill_train/submit_train_distill_finetune_dolcino.sh
+++ /dev/null
@@ -1,71 +0,0 @@
-#!/bin/sh -e
-
-echo "example: $0 --gpu 1"
-
-# if `requirements.txt` is present, virtual environment is installed and used
-EXEC="python3 train_distill_optimized_correctives_fine_tune.py"
-
-GPU_REQUIRED=true
-
-. /pfcalcul/tools/sbatchHelpers5.sh
-
-# --data_root points at the dataset synced by datasynch_perso (see below).
-# It is synced next to this project folder, i.e. ../instanthmr_data once we
-# cd into instanthmr_distill_train.
-#
-# Fine-tune to repair the 2D keypoint head after the flip-label fix
-# (joints_2d[FLIP_PERM] was missing from the geometric augmentation).
-# --init_ckpt is the checkpoint we START FROM; results land in --output_dir.
-# --reset_2d_head is important: the existing 2D head encodes the OLD left/right
-# convention, so fine-tuning it in place has to unlearn that on ~40% of samples
-# and thrashes. Resetting it makes the head learn the corrected convention from
-# scratch on frozen-quality features, which converges cleanly.
-# trunk lr 1e-5 / head lr 3e-4; --pa_tolerance rejects any checkpoint whose
-# Mesh PA-MPJPE regresses more than 2 mm from the measured baseline.
-EXEC="python3 -u train_distill_optimized_correctives_fine_tune.py \
- --data_root /datasets/instanthmr_data \
- --init_ckpt runs/distill_optimized_v2/best_student_model_ema.pth \
- --output_dir runs/distill_optimized_v2_ft \
- --num_workers 8 --batch_size 128 \
- --reset_2d_head \
- --epochs 15 --lr 1e-5 --head_2d_lr_mult 30 \
- --pa_tolerance 2.0 --early_stop_patience 4 $useropt"
-
-# Zero-risk fallback if the PA guard blocks everything: freezes all but head_2d_*,
-# so the 3D pose provably cannot change (measured: PA held to 0.0 mm over 8 epochs).
-# Slower to converge — the decoder cannot adapt with it.
-# ... --train_2d_only --reset_2d_head --lr 3e-4 --head_2d_lr_mult 1 --epochs 30
-
-# SBATCH --output/--error paths are relative to the submission directory, so
-# create the log folder before submitting.
-mkdir -p instanthmr_distill
-
-jobMessage=$(
-######################### SBATCH launcher
-######################### #SBATCH --option # <= this is an enabled paramater
-######################### ##SBATCH --option # <= this is a disabled parameter
-sbatch ${sbatchopt} << eof
-#!/bin/bash
-#SBATCH --job-name="instanthmr_finetune"
-#SBATCH --mail-type=ALL
-#SBATCH --ntasks=1
-#SBATCH --cpus-per-task=8
-#SBATCH --output=instanthmr_distill/stdout_finetune_dolcino.txt
-#SBATCH --error=instanthmr_distill/stderr_finetune_dolcino.txt
-#SBATCH --account=dept_rob
-#SBATCH --partition=robgpu
-#SBATCH --gres=gpu:1
-#SBATCH --mem-per-gpu=50000
-#SBATCH --time=2-00:00:00
-
-. /pfcalcul/tools/sbatchHelpers5.sh
-
-/pfcalcul/tools/datasync /datasets/instanthmr_data
-
-
-time $EXEC
-
-eof
-)
-
-showSubmitted
diff --git a/instanthmr_distill_train/submit_train_distill_pose3d.sh b/instanthmr_distill_train/submit_train_distill_pose3d.sh
deleted file mode 100755
index dda9c6b..0000000
--- a/instanthmr_distill_train/submit_train_distill_pose3d.sh
+++ /dev/null
@@ -1,49 +0,0 @@
-#!/bin/sh -e
-
-echo "example: $0 --gpu 1"
-
-# if `requirements.txt` is present, virtual environment is installed and used
-EXEC="python3 train_distill_pose3d.py"
-
-GPU_REQUIRED=true
-
-. /pfcalcul/tools/sbatchHelpers5.sh
-
-# --data_root points at the dataset synced by datasynch_perso (see below).
-# It is synced next to this project folder, i.e. ../instanthmr_data once we
-# cd into instanthmr_distill_train.
-EXEC="python3 -u train_distill_pose3d.py --data_root /datasets/instanthmr_data --num_workers 8 --batch_size 128 $useropt"
-
-# SBATCH --output/--error paths are relative to the submission directory, so
-# create the log folder before submitting.
-mkdir -p instanthmr_distill
-
-jobMessage=$(
-######################### SBATCH launcher
-######################### #SBATCH --option # <= this is an enabled paramater
-######################### ##SBATCH --option # <= this is a disabled parameter
-sbatch ${sbatchopt} << eof
-#!/bin/bash
-#SBATCH --job-name="instanthmr_distill"
-#SBATCH --mail-type=ALL
-#SBATCH --ntasks=1
-#SBATCH --cpus-per-task=8
-#SBATCH --output=instanthmr_distill/stdout.txt
-#SBATCH --error=instanthmr_distill/stderr.txt
-#SBATCH --account=dept_rob
-#SBATCH --partition=robgpu
-#SBATCH --gres=gpu:1
-#SBATCH --mem-per-gpu=50000
-#SBATCH --time=4-00:00:00
-
-. /pfcalcul/tools/sbatchHelpers5.sh
-
-/pfcalcul/tools/datasync /datasets/instanthmr_data
-
-
-time $EXEC
-
-eof
-)
-
-showSubmitted
diff --git a/instanthmr_distill_train/submit_train_distill_pose3d_dolcino.sh b/instanthmr_distill_train/submit_train_distill_pose3d_dolcino.sh
deleted file mode 100755
index d76ed0c..0000000
--- a/instanthmr_distill_train/submit_train_distill_pose3d_dolcino.sh
+++ /dev/null
@@ -1,49 +0,0 @@
-#!/bin/sh -e
-
-echo "example: $0 --gpu 1"
-
-# if `requirements.txt` is present, virtual environment is installed and used
-EXEC="python3 train_distill_optimized_correctives.py"
-
-GPU_REQUIRED=true
-
-. /pfcalcul/tools/sbatchHelpers5.sh
-
-# --data_root points at the dataset synced by datasynch_perso (see below).
-# It is synced next to this project folder, i.e. ../instanthmr_data once we
-# cd into instanthmr_distill_train.
-EXEC="python3 -u train_distill_optimized_correctives.py --data_root /datasets/instanthmr_data --num_workers 8 --batch_size 128 $useropt"
-
-# SBATCH --output/--error paths are relative to the submission directory, so
-# create the log folder before submitting.
-mkdir -p instanthmr_distill
-
-jobMessage=$(
-######################### SBATCH launcher
-######################### #SBATCH --option # <= this is an enabled paramater
-######################### ##SBATCH --option # <= this is a disabled parameter
-sbatch ${sbatchopt} << eof
-#!/bin/bash
-#SBATCH --job-name="instanthmr_distill"
-#SBATCH --mail-type=ALL
-#SBATCH --ntasks=1
-#SBATCH --cpus-per-task=8
-#SBATCH --output=instanthmr_distill/stdout_dolcino.txt
-#SBATCH --error=instanthmr_distill/stderr_dolcino.txt
-#SBATCH --account=dept_rob
-#SBATCH --partition=robgpu
-#SBATCH --gres=gpu:1
-#SBATCH --mem-per-gpu=50000
-#SBATCH --time=4-00:00:00
-
-. /pfcalcul/tools/sbatchHelpers5.sh
-
-/pfcalcul/tools/datasync /datasets/instanthmr_data
-
-
-time $EXEC
-
-eof
-)
-
-showSubmitted
diff --git a/instanthmr_distill_train/submit_train_distill_pose3d_optimized.sh b/instanthmr_distill_train/submit_train_distill_pose3d_optimized.sh
deleted file mode 100755
index 10d0e15..0000000
--- a/instanthmr_distill_train/submit_train_distill_pose3d_optimized.sh
+++ /dev/null
@@ -1,48 +0,0 @@
-#!/bin/sh -e
-
-echo "example: $0 --gpu 1"
-
-# if `requirements.txt` is present, virtual environment is installed and used
-EXEC="python3 train_distill_pose3d_optimized.py"
-
-GPU_REQUIRED=true
-
-. /pfcalcul/tools/sbatchHelpers5.sh
-
-# --data_root points at the dataset synced by datasynch_perso (see below).
-# It is synced next to this project folder, i.e. ../instanthmr_data once we
-# cd into instanthmr_distill_train.
-EXEC="python3 -u train_distill_pose3d_optimized.py --data_root /datasets/instanthmr_data --num_workers 8 --batch_size 128 $useropt"
-
-# SBATCH --output/--error paths are relative to the submission directory, so
-# create the log folder before submitting.
-mkdir -p instanthmr_distill
-
-jobMessage=$(
-######################### SBATCH launcher
-######################### #SBATCH --option # <= this is an enabled paramater
-######################### ##SBATCH --option # <= this is a disabled parameter
-sbatch ${sbatchopt} << eof
-#!/bin/bash
-#SBATCH --job-name="instanthmr_distill"
-#SBATCH --mail-type=ALL
-#SBATCH --ntasks=1
-#SBATCH --cpus-per-task=8
-#SBATCH --output=instanthmr_distill/stdout.txt
-#SBATCH --error=instanthmr_distill/stderr.txt
-#SBATCH --partition=gpu
-#SBATCH --gres=gpu:1
-#SBATCH --mem-per-gpu=35000
-#SBATCH --time=4-00:00:00
-
-. /pfcalcul/tools/sbatchHelpers5.sh
-
-/pfcalcul/tools/datasync /datasets/instanthmr_data
-
-
-time $EXEC
-
-eof
-)
-
-showSubmitted
diff --git a/instanthmr_distill_train/submit_train_levjepa_lora_dolcino.sh b/instanthmr_distill_train/submit_train_levjepa_lora_dolcino.sh
deleted file mode 100755
index b19a956..0000000
--- a/instanthmr_distill_train/submit_train_levjepa_lora_dolcino.sh
+++ /dev/null
@@ -1,55 +0,0 @@
-#!/bin/sh -e
-
-echo "example: $0 --gpu 1"
-
-# if `requirements.txt` is present, virtual environment is installed and used
-EXEC="python3 train_levjepa_lora.py"
-
-GPU_REQUIRED=true
-
-. /pfcalcul/tools/sbatchHelpers5.sh
-
-# --data_root points at the dataset synced by datasynch_perso (see below).
-#
-# batch_size is in CLIPS, not frames: 4 clips x 16 frames = 64 frames/step, and
-# with --accum_steps 4 that is 256 frames per optimiser update. LoRA cannot use
-# a feature cache (the encoder moves every step), so every clip is re-encoded
-# every epoch -- this job is ~30x the wall-clock of the frozen probe on the same
-# data. Raise --batch_size if the GPU has the memory; grad checkpointing is on
-# by default and roughly halves activation memory for ~30% more compute.
-#
-# --max_hours 92 stops cleanly and checkpoints before SLURM's 4-day SIGKILL.
-EXEC="python3 -u train_levjepa_lora.py --data_root /datasets/instanthmr_data --num_workers 8 --batch_size 4 --accum_steps 4 --max_hours 92 $useropt"
-
-# SBATCH --output/--error paths are relative to the submission directory, so
-# create the log folder before submitting.
-mkdir -p instanthmr_levjepa_lora
-
-jobMessage=$(
-######################### SBATCH launcher
-######################### #SBATCH --option # <= this is an enabled paramater
-######################### ##SBATCH --option # <= this is a disabled parameter
-sbatch ${sbatchopt} << eof
-#!/bin/bash
-#SBATCH --job-name="instanthmr_levjepa_lora"
-#SBATCH --mail-type=ALL
-#SBATCH --ntasks=1
-#SBATCH --cpus-per-task=8
-#SBATCH --output=instanthmr_levjepa_lora/stdout_levjepa_dolcino.txt
-#SBATCH --error=instanthmr_levjepa_lora/stderr_levjepa_dolcino.txt
-#SBATCH --partition=gpu
-#SBATCH --gres=gpu:1
-#SBATCH --mem-per-gpu=50000
-#SBATCH --time=4-00:00:00
-
-. /pfcalcul/tools/sbatchHelpers5.sh
-
-/pfcalcul/tools/datasync /datasets/instanthmr_data
-
-
-time $EXEC
-
-eof
-)
-
-showSubmitted
diff --git a/instanthmr_distill_train/train_distill_optimized.py b/instanthmr_distill_train/train_distill_optimized.py
deleted file mode 100644
index 6bfc78d..0000000
--- a/instanthmr_distill_train/train_distill_optimized.py
+++ /dev/null
@@ -1,1782 +0,0 @@
-#!/usr/bin/env python3
-# ============================================================
-# OPTIMIZED full-MHR distillation: train_distill.py + geometric
-# augmentation + SimCC soft-argmax 2D head, MHR-consistent.
-# ------------------------------------------------------------
-# Keeps the ENTIRE MHR pipeline (params / shape / cam heads, MHR
-# forward pass, structural / feet / reprojection losses) — the
-# auxiliary supervision that made train_distill.py generalize
-# better than the pose3d variants — and adds:
-#
-# (1) GEOMETRIC AUG (applied with prob geom_p; else identity):
-# rotation / scale / translation + horizontal flip, propagated
-# to 2D (exact affine), 3D + cam_trans (verified rotation), and
-# cliff_cond (flip: mirror cx; rotation: rotate bbox centre).
-# MHR-branch consistency (probed empirically on mhr_model.pt —
-# root orient is NOT composable in param space; params[3]/[5]
-# deform the rig non-rigidly):
-# * loss_mhr_joints : target MHR joints rotated in JOINT space
-# (MHR frame: x'=c·x−s·y, y'=s·x+c·y ⇔ vision-frame R).
-# * loss_pose : masked to identity samples (root orient
-# is baked into params and cannot be rotated safely).
-# * loss_scale/shape: rotation-invariant → active unless flipped
-# (L/R scale chains can't be swapped in param space).
-# * loss_structural / loss_feet: pred-vs-pred → always active.
-# * reprojection losses: predictions are counter-rotated, then
-# projected through the ORIGINAL camera/bbox, then the sample's
-# aug affine M is applied → matches warped 2D targets exactly.
-# Masked on flipped samples.
-# (2) SimCC soft-argmax 2D head: per-joint 1D bin logits over
-# [-kp2d_range, +kp2d_range] (covers out-of-crop joints, unlike a
-# [-1,1]-clamped soft-argmax) + Gaussian-label CE (w_simcc) +
-# SmoothL1 on the soft-argmax coordinates. NOTE: the CE term has an
-# irreducible label-entropy floor (~2.1 nats at sigma=2 bins) — the
-# TOTAL loss plateauing near that value is expected, not divergence.
-#
-# Known approximations (standard in HMR training, documented here):
-# * image rotation is about the crop centre, cam rotation about the
-# optical axis → small cam-label mismatch for off-centre crops;
-# * scale/translate aug does not resample cam_trans/cliff geometry.
-# Identity samples (1−geom_p of the data) + the direct cam loss anchor
-# the cam head with clean labels.
-#
-# Sanity: python3 train_distill_optimized.py --self-test --data_root ../data/sam3d_gt_mpii
-# python3 train_distill_optimized.py --overfit-test --data_root ../data/sam3d_gt_mpii
-# Full: python3 -u train_distill_optimized.py --data_root /datasets/instanthmr_data --num_workers 8
-# ============================================================
-import os
-
-# Must be set before the first CUDA allocation (read lazily by the allocator).
-os.environ.setdefault("PYTORCH_CUDA_ALLOC_CONF", "expandable_segments:True")
-
-import argparse
-import math
-import random
-import gc
-from dataclasses import dataclass, field
-from pathlib import Path
-
-import numpy as np
-from PIL import Image
-
-import torch
-import torch.nn as nn
-import torch.nn.functional as F
-import torch.optim as optim
-import torch.optim.lr_scheduler as lr_scheduler
-from torch.utils.data import Dataset, DataLoader, random_split
-from torch.optim.swa_utils import AveragedModel, get_ema_multi_avg_fn
-
-import torchvision.transforms as transforms
-import torchvision.transforms.functional as F_t
-from torchvision.transforms import InterpolationMode
-
-import timm
-from tqdm import tqdm
-
-# --- Notebook Cell 0 setup (headless-safe) ---
-import matplotlib
-matplotlib.use("Agg")
-import matplotlib.pyplot as plt
-import cv2
-import onnxruntime as ort
-
-print(ort.get_available_providers())
-
-device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
-print(f"Using device: {device}")
-
-# The project root is wherever this script lives, e.g.
-# /pfcalcul/work/kchalabi/envs/lstm/instanthmr_distill_train/
-PROJECT_ROOT = Path(__file__).resolve().parent
-# datasynch_perso syncs /datasets/instanthmr_data next to the project folder.
-DEFAULT_DATA_ROOT = "/pfcalcul/datasets/instanthmr_data/"
-
-# MHR70 joint ordering (mirror of instanthmr/skeleton.py; embedded so the
-# script is self-contained on the cluster). Drives the horizontal-flip
-# left<->right permutation of the 70 NATIVE joints.
-JOINT_NAMES = [
- "nose", "left_eye", "right_eye", "left_ear", "right_ear",
- "left_shoulder", "right_shoulder", "left_elbow", "right_elbow",
- "left_hip", "right_hip", "left_knee", "right_knee", "left_ankle", "right_ankle",
- "left_big_toe_tip", "left_small_toe_tip", "left_heel",
- "right_big_toe_tip", "right_small_toe_tip", "right_heel",
- "right_thumb_tip", "right_thumb_first_joint", "right_thumb_second_joint", "right_thumb_third_joint",
- "right_index_tip", "right_index_first_joint", "right_index_second_joint", "right_index_third_joint",
- "right_middle_tip", "right_middle_first_joint", "right_middle_second_joint", "right_middle_third_joint",
- "right_ring_tip", "right_ring_first_joint", "right_ring_second_joint", "right_ring_third_joint",
- "right_pinky_tip", "right_pinky_first_joint", "right_pinky_second_joint", "right_pinky_third_joint",
- "right_wrist",
- "left_thumb_tip", "left_thumb_first_joint", "left_thumb_second_joint", "left_thumb_third_joint",
- "left_index_tip", "left_index_first_joint", "left_index_second_joint", "left_index_third_joint",
- "left_middle_tip", "left_middle_first_joint", "left_middle_second_joint", "left_middle_third_joint",
- "left_ring_tip", "left_ring_first_joint", "left_ring_second_joint", "left_ring_third_joint",
- "left_pinky_tip", "left_pinky_first_joint", "left_pinky_second_joint", "left_pinky_third_joint",
- "left_wrist",
- "left_olecranon", "right_olecranon", "left_cubital_fossa", "right_cubital_fossa",
- "left_acromion", "right_acromion", "neck",
-]
-
-
-def _build_flip_perm(names):
- idx = {n: i for i, n in enumerate(names)}
- perm = list(range(len(names)))
- for i, n in enumerate(names):
- if n.startswith("left_"):
- perm[i] = idx.get("right_" + n[5:], i)
- elif n.startswith("right_"):
- perm[i] = idx.get("left_" + n[6:], i)
- perm = np.array(perm, dtype=np.int64)
- assert (perm[perm] == np.arange(len(perm))).all(), "flip permutation is not an involution"
- return perm
-
-
-FLIP_PERM = _build_flip_perm(JOINT_NAMES)
-
-
-# ============================================================
-# Cell 1 — Configuration
-# ============================================================
-@dataclass
-class DistillConfig:
- """All hyperparameters in one place."""
- # --- Paths ---
- # Single entry-point folder containing one or more sub-folders,
- # each with its own annotations/ and images/ directories.
- data_root: str = str(DEFAULT_DATA_ROOT)
- mhr_model_path: str = str(PROJECT_ROOT / "checkpoints/mhr_model.pt") # path to MHR model
- log_dir: str = str(PROJECT_ROOT / "runs/distill_optimized_v1") # MHR + geom aug + SimCC head
-
- # --- Data ---
- image_size: int = 224
- max_images: int | None = None # None = use every crop; a number truncates (path-biased)
- # Per-dataset crop caps: sub-folder name -> max crops kept. The subset is
- # RANDOMLY sampled (seed 42), not the first N, so it stays representative.
- # Harmony4D is ~53% of the corpus and a narrow domain -> cap it for balance.
- per_dataset_caps: dict = field(default_factory=lambda: {"sam3d_gt_harmony4d": 300_000})
- val_split: float = 0.1
- num_workers: int = 4
- augment: bool = True
-
- # --- Geometric augmentation (train split only) ---
- geom_p: float = 0.8 # prob a sample is geometrically augmented (else identity)
- geom_rot_deg: float = 30.0 # random in-plane rotation ±deg
- geom_scale_range: float = 0.25 # random scale in [1-r, 1+r]
- geom_trans: float = 0.08 # random translation, fraction of half-crop
- geom_flip_p: float = 0.5 # horizontal flip prob (within augmented samples)
-
- # --- SimCC soft-argmax 2D head ---
- kp2d_bins: int = 96 # bins per axis
- kp2d_range: float = 1.5 # bins span [-range, range]: covers out-of-crop joints
-
- # --- Model (Transformer + CLIFF) ---
- backbone: str = "repvit_m2_3"
- backbone_feat_dim: int = 640 # RepViT m2_3 usually outputs 640
- d_model: int = 512
- n_heads: int = 8
- n_decoder_layers: int = 4
- dropout: float = 0.1
-
- # --- Output dimensions ---
- pose_dim: int = 136
- scale_dim: int = 68
- shape_dim: int = 45
- cam_dim: int = 3
- cliff_dim: int = 3
- num_joints: int = 70 # We track 70 joints
-
- @property
- def model_params_dim(self) -> int:
- return self.pose_dim + self.scale_dim # 204
-
- # --- Training ---
- batch_size: int = 64
- lr: float = 3e-4
- weight_decay: float = 1e-4
- epochs: int = 400
- warmup_epochs: int = 3
- grad_clip: float = 1.0 # tighter clip: 5.0 let a bad step blow up the MHR loss
- anomaly_loss_threshold: float = 100.0 # skip a batch whose loss exceeds this (normal is <2)
- use_amp: bool = True
- ema_decay: float = 0.9998 # EMA shadow-weights decay (Cell 11)
- early_stop_patience: int = 150 # stop after N epochs where NEITHER raw nor ema improved (Cell 11)
- resume: bool = True # resume from best_student_model_v3.pth if present
-
- # --- Loss weights (UPDATED for HMR Balance) ---
- w_pose: float = 1.0
- w_scale: float = 0.1
- w_shape: float = 1.0
- w_cam: float = 0.1
- w_keypoints3d: float = 10.0 # Bumped up: 3D joints are the strongest spatial anchor
- w_keypoints2d: float = 10.0 # Bumped up: Forces pixel-perfect alignment
- w_3d_joints: float = 1e-3
- w_structural: float = 0.01
- w_reproj_3d: float = 0.01 # High weight to enforce strict scale/camera alignment
- w_reproj_mhr: float = 0.01 # High weight to enforce strict scale/camera alignment
- w_simcc: float = 1.0 # SimCC bin-CE (has a ~2.1-nat label-entropy floor)
-
- # ==========================================================
- # Feet Barycenter Anchors
- # ==========================================================
- w_feet = 0.01 # Soft prior weight, matching w_structural
-
- # Native 70-joint format indices
- native_left_foot = [15, 16, 17]
- native_right_foot = [18, 19, 20]
-
- # MHR 127-joint format indices
- mhr_left_foot = [6, 7, 8]
- mhr_right_foot = [22, 23, 24]
-
- # Data-Driven Topology Mapping (Native 70 <-> MHR 127)
- native_mapping_ids = [ 1, 2, 5, 6, 9, 10, 11, 12, 13, 14, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62 ]
- mhr_mapping_ids = [ 125, 123, 75, 39, 2, 18, 3, 19, 5, 21, 64, 63, 62, 61, 59, 58, 57, 56, 55, 54, 53, 52, 51, 50, 49, 48, 47, 46, 45, 44, 41, 100, 99, 98, 97, 95, 94, 93, 92, 91, 90, 89, 88, 87, 86, 85, 84, 83, 82, 81, 80, 77 ]
-
-
-# ============================================================
-# Cell 3 — Dataset and Data Augmentation
-# ============================================================
-class RandomPixelate:
- """Simulates low-quality webcams or low-bandwidth video."""
- def __init__(self, p=0.2, min_res=32, max_res=112):
- self.p = p
- self.min_res = min_res
- self.max_res = max_res
-
- def __call__(self, img):
- if random.random() < self.p:
- orig_w, orig_h = img.size
- degraded_h = random.randint(self.min_res, self.max_res)
- degraded_w = int(orig_w * (degraded_h / orig_h))
- # Downsample then upsample to create pixelation effect
- img = F_t.resize(img, [degraded_h, degraded_w], interpolation=InterpolationMode.NEAREST)
- img = F_t.resize(img, [orig_h, orig_w], interpolation=InterpolationMode.NEAREST)
- return img
-
-
-class SAM3DStudentDataset(Dataset):
- def __init__(self, data_root: str,
- image_size: int = 224, max_images: int | None = None,
- augment: bool = True, per_dataset_caps: dict | None = None,
- geom_p: float = 0.8, geom_rot_deg: float = 30.0,
- geom_scale_range: float = 0.25, geom_trans: float = 0.08,
- geom_flip_p: float = 0.5):
- super().__init__()
- self.image_size = image_size
- self.data_root = Path(data_root)
- # geometric augmentation only on the train split (augment=True)
- self.augment = augment
- self.geom_p = geom_p
- self.geom_rot_deg = geom_rot_deg
- self.geom_scale_range = geom_scale_range
- self.geom_trans = geom_trans
- self.geom_flip_p = geom_flip_p
-
- # --- 1. Build Transform Pipeline (PHOTOMETRIC only; geometric aug is
- # applied jointly on image + targets inside __getitem__) ---
- # The images on disk are already 224x224, but Resize guarantees safety.
- tfm_list = [transforms.Resize((image_size, image_size))]
-
- if augment:
- tfm_list.extend([
- # ColorJitter (esp. hue -> RGB/HSV round-trip) is the priciest CPU op in
- # the pipeline. Applying it on EVERY image was starving the GPU, so run it
- # half the time via RandomApply — still solid colour regularisation.
- transforms.RandomApply([transforms.ColorJitter(
- brightness=0.2, contrast=0.2, saturation=0.2, hue=0.1)], p=0.5),
- RandomPixelate(p=0.2, min_res=48, max_res=112),
- transforms.RandomApply([transforms.GaussianBlur(kernel_size=5)], p=0.2),
- ])
-
- tfm_list.extend([
- transforms.ToTensor(),
- # Standard ImageNet Normalization
- transforms.Normalize(mean=[0.485, 0.456, 0.406],
- std=[0.229, 0.224, 0.225]),
- ])
-
- if augment:
- tfm_list.append(transforms.RandomErasing(p=0.2, scale=(0.02, 0.15)))
-
- self.transform = transforms.Compose(tfm_list)
-
- # --- 2. Pair Discovery Across Sub-folders ---
- # `data_root` contains one or more sub-folders, each with its own
- # annotations/ and images/ directories. We pair the npz with its image
- # WITHIN each sub-folder, so identical file names in different
- # sub-folders never collide (pairs are stored as full paths).
- self.pairs = []
- dataset_dirs = self._find_dataset_dirs(self.data_root)
- if not dataset_dirs:
- raise FileNotFoundError(
- f"No annotations/images sub-folders found under '{self.data_root}'. "
- f"Expected <data_root>/<subset>/annotations/*.npz and "
- f"<data_root>/<subset>/images/*.{{jpg,png}}."
- )
-
- # Seeded RNG so the per-dataset random subset is IDENTICAL across the
- # augmented and clean dataset instances -> the train/val split stays
- # consistent between them.
- cap_rng = random.Random(42)
- caps = per_dataset_caps or {}
-
- for ann_dir, img_dir in dataset_dirs:
- sub_name = ann_dir.parent.name
- sub_pairs = []
- for npz_path in sorted(ann_dir.glob("*.npz")):
- stem = npz_path.stem
- # Check for jpg or png
- img_path = img_dir / f"{stem}.jpg"
- if not img_path.exists():
- img_path = img_dir / f"{stem}.png"
-
- if img_path.exists():
- sub_pairs.append((img_path, npz_path))
-
- # Per-dataset cap: randomly sample a REPRESENTATIVE subset (not the
- # first N, which would bias toward alphabetically-early sequences).
- cap = caps.get(sub_name)
- if cap is not None and len(sub_pairs) > cap:
- n_before = len(sub_pairs)
- sub_pairs.sort(key=lambda p: (str(p[1]), str(p[0]))) # deterministic pool
- sub_pairs = cap_rng.sample(sub_pairs, cap)
- print(f" [cap] {sub_name}: sampled {cap:,} of {n_before:,} crops")
- self.pairs.extend(sub_pairs)
-
- # Deterministic global order so the train/val split is reproducible.
- self.pairs.sort(key=lambda p: (str(p[1]), str(p[0])))
-
- if max_images is not None:
- self.pairs = self.pairs[:max_images]
-
- print(f" Found {len(dataset_dirs)} sub-folder(s) under {self.data_root}; "
- f"{len(self.pairs)} valid (image, npz) pairs (augment={augment}).")
-
- @staticmethod
- def _find_dataset_dirs(root: Path):
- """Return [(annotations_dir, images_dir), ...] for every dataset folder.
-
- Handles both layouts:
- * root itself directly contains annotations/ and images/
- * root contains sub-folders, each with annotations/ and images/
- """
- dirs = []
- if (root / "annotations").is_dir() and (root / "images").is_dir():
- dirs.append((root / "annotations", root / "images"))
-
- if root.is_dir():
- for sub in sorted(root.iterdir()):
- if not sub.is_dir():
- continue
- ann, img = sub / "annotations", sub / "images"
- if ann.is_dir() and img.is_dir():
- dirs.append((ann, img))
- return dirs
-
- def __len__(self):
- return len(self.pairs)
-
- def __getitem__(self, idx):
- img_path, npz_path = self.pairs[idx]
- W = H = self.image_size
-
- img_pil = Image.open(img_path).convert("RGB")
-
- # --- 4. Load Annotations ---
- ann = np.load(npz_path)
- orig_h, orig_w = ann["orig_shape"]
-
- # --- 5. Correct Mathematical Rescaling for 2D Joints ---
- sq_bbox = ann["bbox_square"]
- sq_x1, sq_y1 = sq_bbox[0], sq_bbox[1]
- orig_crop_size = sq_bbox[2] - sq_bbox[0]
- true_scale = self.image_size / max(orig_crop_size, 1.0)
-
- joints_2d = ann["joints_2d"].copy().astype(np.float32)
- joints_2d[:, 0] = (joints_2d[:, 0] - sq_x1) * true_scale
- joints_2d[:, 1] = (joints_2d[:, 1] - sq_y1) * true_scale
- joints_2d[:, 0] = (joints_2d[:, 0] / self.image_size) * 2.0 - 1.0
- joints_2d[:, 1] = (joints_2d[:, 1] / self.image_size) * 2.0 - 1.0
-
- joints_3d = ann["joints_3d"].astype(np.float32).copy()
- cam_trans = ann["cam_trans"].astype(np.float32).copy()
-
- # --- 6. CLIFF Conditioning (pixel-space; adjusted by the aug below) ---
- tight_bbox = ann["bbox"]
- cx = (tight_bbox[0] + tight_bbox[2]) / 2.0
- cy = (tight_bbox[1] + tight_bbox[3]) / 2.0
- b_size = max(tight_bbox[2] - tight_bbox[0], tight_bbox[3] - tight_bbox[1])
- b_scale = b_size / max(orig_w, orig_h)
-
- # --- 6.5 GEOMETRIC AUGMENTATION (train only, prob geom_p) ---
- # One composed affine M_total = M_rst ∘ M_flip applied to image AND 2D;
- # 3D + cam get the matching mirror / in-plane rotation; cliff is adjusted.
- aug_flip, cos_t, sin_t = 0.0, 1.0, 0.0
- M_total = np.array([[1.0, 0.0, 0.0], [0.0, 1.0, 0.0]], dtype=np.float64)
- aug_active = 0.0
- if self.augment and random.random() < self.geom_p:
- aug_active = 1.0
- img_np = np.asarray(img_pil.resize((W, H)))
-
- # flip as an affine (x' = W - x), so ONE warp handles everything
- if random.random() < self.geom_flip_p:
- aug_flip = 1.0
- M_flip = np.array([[-1.0, 0.0, float(W)], [0.0, 1.0, 0.0]])
- else:
- M_flip = np.array([[1.0, 0.0, 0.0], [0.0, 1.0, 0.0]])
-
- angle = random.uniform(-self.geom_rot_deg, self.geom_rot_deg)
- scale = random.uniform(1.0 - self.geom_scale_range, 1.0 + self.geom_scale_range)
- dx = random.uniform(-self.geom_trans, self.geom_trans)
- dy = random.uniform(-self.geom_trans, self.geom_trans)
- M_rst = cv2.getRotationMatrix2D((W / 2.0, H / 2.0), angle, scale)
- M_rst[0, 2] += dx * (W / 2.0)
- M_rst[1, 2] += dy * (H / 2.0)
-
- # compose: M_total = M_rst ∘ M_flip
- A2, t2 = M_rst[:, :2], M_rst[:, 2]
- A1, t1 = M_flip[:, :2], M_flip[:, 2]
- M_total = np.hstack([A2 @ A1, (A2 @ t1 + t2)[:, None]])
-
- img_np = cv2.warpAffine(img_np, M_total, (W, H), flags=cv2.INTER_LINEAR,
- borderMode=cv2.BORDER_CONSTANT, borderValue=(0, 0, 0))
- img_pil = Image.fromarray(img_np)
-
- # 2D: same composed affine, in pixel space, back to [-1, 1]
- px = (joints_2d[:, 0] + 1.0) * 0.5 * W
- py = (joints_2d[:, 1] + 1.0) * 0.5 * H
- px2 = M_total[0, 0] * px + M_total[0, 1] * py + M_total[0, 2]
- py2 = M_total[1, 0] * px + M_total[1, 1] * py + M_total[1, 2]
- joints_2d[:, 0] = (px2 / (0.5 * W) - 1.0).astype(np.float32)
- joints_2d[:, 1] = (py2 / (0.5 * H) - 1.0).astype(np.float32)
-
- # 3D + cam: mirror first (matches M_flip), then in-plane rotation R_v
- if aug_flip > 0.5:
- joints_3d[:, 0] = -joints_3d[:, 0]
- joints_3d = joints_3d[FLIP_PERM]
- # joints_2d was already mirrored geometrically by M_total, but a
- # mirrored image LOOKS like the opposite-handed person, so the
- # left/right labels must be swapped too - exactly as for joints_3d.
- # Without this the 2D head gets contradictory left/right supervision
- # and collapses symmetric joints toward the body midline.
- joints_2d = joints_2d[FLIP_PERM]
- cam_trans[0] = -cam_trans[0]
- cx = orig_w - cx # mirror bbox centre in full frame
- rad = math.radians(angle)
- cos_t, sin_t = math.cos(rad), math.sin(rad)
- R_v = np.array([[cos_t, sin_t], [-sin_t, cos_t]], dtype=np.float32)
- joints_3d[:, :2] = joints_3d[:, :2] @ R_v.T
- cam_trans[:2] = R_v @ cam_trans[:2]
- # cliff bbox centre: rotate about the frame centre (camera-roll story)
- dxy = np.array([cx - orig_w / 2.0, cy - orig_h / 2.0], dtype=np.float64)
- dxy = R_v.astype(np.float64) @ dxy
- cx, cy = orig_w / 2.0 + dxy[0], orig_h / 2.0 + dxy[1]
-
- image = self.transform(img_pil) # photometric + ToTensor + Normalize
-
- cx_norm = 2.0 * (cx / orig_w) - 1.0
- cy_norm = 2.0 * (cy / orig_h) - 1.0
- cliff_cond = torch.tensor([cx_norm, cy_norm, b_scale], dtype=torch.float32)
-
- return {
- "image": image, # [3, 224, 224]
- "cliff_cond": cliff_cond, # [3]
- "mhr_model_params": torch.from_numpy(ann["mhr_model_params"]).float(), # [204]
- "shape_params": torch.from_numpy(ann["shape_params"]).float(), # [45]
- "cam_trans": torch.from_numpy(cam_trans).float(), # [3] (augmented)
- "cam_focal": torch.from_numpy(ann["cam_focal_length"]).float(), # [2]
- "joints_2d": torch.from_numpy(joints_2d).float(), # [70, 2] (augmented)
- "joints_3d": torch.from_numpy(joints_3d).float(), # [70, 3] (augmented)
- "orig_shape": torch.tensor([orig_h, orig_w], dtype=torch.float32), # [2]
- "bbox_square": sq_bbox, # [4] ORIGINAL crop bbox
- # --- augmentation metadata for the loss ---
- "aug_active": torch.tensor(aug_active, dtype=torch.float32), # 1 = augmented
- "aug_flip": torch.tensor(aug_flip, dtype=torch.float32), # 1 = flipped
- "aug_cos": torch.tensor(cos_t, dtype=torch.float32),
- "aug_sin": torch.tensor(sin_t, dtype=torch.float32),
- "aug_M": torch.from_numpy(M_total.astype(np.float32).reshape(-1)), # [6] px-space affine
- }
-
-
-def build_dataloaders(cfg):
- """Build train/val datasets and loaders (Cell 3 bottom)."""
- geom = dict(geom_p=cfg.geom_p, geom_rot_deg=cfg.geom_rot_deg,
- geom_scale_range=cfg.geom_scale_range,
- geom_trans=cfg.geom_trans, geom_flip_p=cfg.geom_flip_p)
- full_dataset = SAM3DStudentDataset(
- cfg.data_root,
- augment=cfg.augment,
- max_images=cfg.max_images,
- per_dataset_caps=cfg.per_dataset_caps,
- **geom,
- )
-
- val_dataset_clean = SAM3DStudentDataset(
- cfg.data_root,
- augment=False,
- max_images=cfg.max_images,
- per_dataset_caps=cfg.per_dataset_caps,
- **geom,
- )
-
- n_val = int(len(full_dataset) * cfg.val_split)
- n_train = len(full_dataset) - n_val
-
- # Use a generator for reproducible splits
- generator = torch.Generator().manual_seed(42)
- train_dataset, _ = random_split(full_dataset, [n_train, n_val], generator=generator)
-
- generator = torch.Generator().manual_seed(42)
- _, val_dataset = random_split(val_dataset_clean, [n_train, n_val], generator=generator)
-
- # Keep workers alive across epochs and prefetch more batches so the GPU
- # stays fed (helps the ~40% idle time seen in nvidia-smi).
- loader_kwargs = dict(num_workers=cfg.num_workers, pin_memory=True)
- if cfg.num_workers > 0:
- loader_kwargs["persistent_workers"] = True
- loader_kwargs["prefetch_factor"] = 4
-
- train_loader = DataLoader(
- train_dataset,
- batch_size=cfg.batch_size,
- shuffle=True,
- drop_last=True,
- **loader_kwargs,
- )
-
- val_loader = DataLoader(
- val_dataset,
- batch_size=cfg.batch_size,
- shuffle=False,
- **loader_kwargs,
- )
-
- print(f"Dataset Loaded! Train batches: {len(train_loader)} | Val batches: {len(val_loader)}")
- return train_loader, val_loader, full_dataset
-
-
-# ============================================================
-# Cell 7 — Student Architecture (Mini-SAM3D with PE)
-# ============================================================
-def get_2d_sincos_pos_embed(embed_dim, grid_size):
- """Generate 2D sine-cosine positional embedding for preserving spatial topology."""
- grid_h, grid_w = grid_size, grid_size
- grid_y, grid_x = torch.meshgrid(torch.arange(grid_h), torch.arange(grid_w), indexing='ij')
-
- omega = torch.arange(embed_dim // 4).float() / (embed_dim // 4)
- omega = 1.0 / (10000 ** omega)
-
- out_y = grid_y.flatten().unsqueeze(1) * omega.unsqueeze(0)
- out_x = grid_x.flatten().unsqueeze(1) * omega.unsqueeze(0)
-
- pe_y = torch.cat([torch.sin(out_y), torch.cos(out_y)], dim=1)
- pe_x = torch.cat([torch.sin(out_x), torch.cos(out_x)], dim=1)
-
- pos_embed = torch.cat([pe_y, pe_x], dim=1) # (H*W, embed_dim)
- return pos_embed.unsqueeze(0) # (1, H*W, embed_dim)
-
-
-class InstantHMRStudent(nn.Module):
- def __init__(self, cfg, pretrained=True):
- super().__init__()
- self.cfg = cfg
-
- # 1. The Vision Backbone (RepViT)
- self.backbone = timm.create_model(cfg.backbone, pretrained=pretrained, num_classes=0)
- embed_dim = self.backbone.num_features
- self.feat_proj = nn.Linear(embed_dim, cfg.d_model)
-
- # --- NEW: Positional Embedding for Transformer Memory ---
- # RepViT naturally downsamples by 32x. For a 224x224 image, the grid is 7x7.
- self.grid_size = cfg.image_size // 32
- pos_embed = get_2d_sincos_pos_embed(cfg.d_model, self.grid_size)
- # register_buffer ensures it moves to GPU automatically but isn't updated by the optimizer
- self.register_buffer("mem_pos_embed", pos_embed)
-
- # 2. Learnable Query Tokens (1 Global + 70 2D + 70 3D = 141 Queries)
- self.num_global = 1
- self.num_2d = cfg.num_joints
- self.num_3d = cfg.num_joints
- self.total_queries = self.num_global + self.num_2d + self.num_3d
-
- # self.query_embed = nn.Parameter(torch.randn(1, self.total_queries, cfg.d_model))
- self.query_embed = nn.Parameter(torch.randn(1, self.total_queries, cfg.d_model) * 0.02)
-
- # CLIFF Conditioning Injector
- self.cond_proj = nn.Sequential(
- nn.Linear(cfg.cliff_dim, 128),
- nn.GELU(),
- nn.Linear(128, cfg.d_model)
- )
-
- # 3. Transformer Cross-Attention Decoder
- decoder_layer = nn.TransformerDecoderLayer(
- d_model=cfg.d_model,
- nhead=cfg.n_heads,
- dim_feedforward=cfg.d_model * 4,
- dropout=cfg.dropout,
- activation="gelu",
- batch_first=True,
- norm_first=True
- )
- self.transformer = nn.TransformerDecoder(decoder_layer, num_layers=cfg.n_decoder_layers)
-
- # 4. The Output Heads
-
- # Head A: Global Head (Token 0 -> MHR Params + Shape Params + Camera)
- self.global_out_dim = cfg.model_params_dim + cfg.shape_dim + cfg.cam_dim
- self.head_global = nn.Linear(cfg.d_model, self.global_out_dim)
-
- # --- SimCC soft-argmax 2D Head ---
- # Each 2D token emits 1D bin logits for x and y over [-range, range];
- # soft-argmax gives continuous coords, the logits get a Gaussian-label CE.
- self.kp2d_bins = getattr(cfg, 'kp2d_bins', 96)
- self.kp2d_range = getattr(cfg, 'kp2d_range', 1.5)
- self.head_2d_feat = nn.Sequential(
- nn.Linear(cfg.d_model, 256),
- nn.GELU()
- )
- self.head_2d_logits = nn.Linear(256, 2 * self.kp2d_bins)
- self.register_buffer(
- "kp2d_bin_centers",
- torch.linspace(-self.kp2d_range, self.kp2d_range, self.kp2d_bins))
-
- # Head C: 3D Keypoint Head (No Tanh here, 3D meters can exceed [-1, 1])
- self.dim_3d = 3
- self.head_3d = nn.Sequential(
- nn.Linear(cfg.d_model, 256),
- nn.GELU(),
- nn.Linear(256, self.dim_3d)
- )
-
- # Initialize camera Z translation
- nn.init.constant_(self.head_global.bias[-1], 2.0)
- nn.init.constant_(self.head_global.bias[-2], 0.0)
- nn.init.constant_(self.head_global.bias[-3], 0.0)
-
- # ==========================================================
- # HMR-Standard Zero-Initialization for Stability
- # ==========================================================
- # 1. Global Head (MHR Params) - Must start near neutral pose!
- nn.init.normal_(self.head_global.weight, mean=0.0, std=1e-4)
- # Zero out the biases (except the last 3 camera params we just set)
- nn.init.constant_(self.head_global.bias[:-3], 0.0)
-
- # 2. 2D Spatial Head - Start with tiny weights (uniform bin distribution)
- nn.init.normal_(self.head_2d_logits.weight, mean=0.0, std=1e-4)
- nn.init.constant_(self.head_2d_logits.bias, 0.0)
-
- # 3. 3D Spatial Head - Start with tiny weights
- nn.init.normal_(self.head_3d[-1].weight, mean=0.0, std=1e-4)
- nn.init.constant_(self.head_3d[-1].bias, 0.0)
-
- def forward(self, images, cliff_cond):
- B = images.shape[0]
-
- # 1. Extract spatial image features
- img_feats = self.backbone.forward_features(images)
-
- # Defensive flattening
- if img_feats.dim() == 4:
- img_feats = img_feats.flatten(2).transpose(1, 2) # [B, H*W, C]
-
- memory = self.feat_proj(img_feats)
-
- # --- NEW: Inject Spatial Topology into Memory ---
- # Broadcasting [1, H*W, d_model] across Batch size
- memory = memory + self.mem_pos_embed
-
- # 2. Prepare Query Tokens [B, 141, d_model]
- queries = self.query_embed.expand(B, -1, -1)
-
- cond = self.cond_proj(cliff_cond).unsqueeze(1)
- queries = queries + cond
-
- # 3. Cross Attention
- shared_feats = self.transformer(tgt=queries, memory=memory)
-
- # 4. Route tokens to their dedicated heads
- feat_global = shared_feats[:, 0, :]
- feat_2d = shared_feats[:, 1 : 1 + self.num_2d, :]
- feat_3d = shared_feats[:, 1 + self.num_2d :, :]
-
- # --- Decode Global Token ---
- global_preds = self.head_global(feat_global)
-
- idx_mhr = self.cfg.model_params_dim
- idx_shape = idx_mhr + self.cfg.shape_dim
-
- pred_mhr_params = global_preds[:, :idx_mhr]
- pred_shape_params = global_preds[:, idx_mhr : idx_shape]
- pred_cam_trans = global_preds[:, idx_shape :]
-
- # --- Decode 2D Spatial Tokens (SimCC soft-argmax) ---
- feat_2d_processed = self.head_2d_feat(feat_2d)
- logits_2d = self.head_2d_logits(feat_2d_processed) # [B, 70, 2*bins]
- logits_2d = logits_2d.unflatten(-1, (2, self.kp2d_bins)) # [B, 70, 2, bins]
- prob_2d = torch.softmax(logits_2d, dim=-1)
- pred_joints_2d = (prob_2d * self.kp2d_bin_centers).sum(dim=-1) # [B, 70, 2]
-
- # --- Decode 3D Spatial Tokens ---
- pred_joints_3d = self.head_3d(feat_3d)
-
- return {
- "mhr_params": pred_mhr_params,
- "shape_params": pred_shape_params,
- "cam_trans": pred_cam_trans,
- "joints_2d": pred_joints_2d,
- "joints_2d_logits": logits_2d,
- "joints_3d": pred_joints_3d
- }
-
-
-# ============================================================
-# Cell 8 — The Distillation Loss Module (Foolproof Edition)
-# ============================================================
-class MHRForwardPass:
- """Modified, differentiable forward pass over the MHR rig."""
- def __init__(self, mhr_path, device):
- self.device = device
- self.mhr = torch.jit.load(mhr_path, map_location=device).eval()
- for p in self.mhr.parameters():
- p.requires_grad_(False)
-
- def get_joints(self, model_params, shape_params):
- B = model_params.shape[0]
- dummy_identity = torch.zeros(B, 45, device=model_params.device, dtype=model_params.dtype)
- concat_params = torch.cat([model_params, dummy_identity], dim=1)
-
- joint_params = self.mhr.character_torch.model_parameters_to_joint_parameters(concat_params.to(self.device))
- skel_state = self.mhr.character_torch.joint_parameters_to_skeleton_state(joint_params)
-
- return skel_state.to(model_params.device)
-
-
-class DistillationLoss(nn.Module):
- def __init__(self, cfg, mhr_module):
- super().__init__()
- self.cfg = cfg
- self.mhr_module = mhr_module
- self.mse = nn.MSELoss()
- self.l1 = nn.SmoothL1Loss()
- self.strict_l1 = nn.L1Loss()
- # SimCC Gaussian soft-label width: ~2 bins
- bin_w = 2.0 * cfg.kp2d_range / (cfg.kp2d_bins - 1)
- self.simcc_sigma = 2.0 * bin_w
-
- # ---------------- per-sample masked reductions ----------------
- @staticmethod
- def _mmean(per_sample, mask):
- return (per_sample * mask).sum() / mask.sum().clamp_min(1.0)
-
- def m_smooth_l1(self, pred, tgt, mask):
- e = F.smooth_l1_loss(pred, tgt, reduction='none').flatten(1).mean(1)
- return self._mmean(e, mask)
-
- def m_mse(self, pred, tgt, mask):
- e = F.mse_loss(pred, tgt, reduction='none').flatten(1).mean(1)
- return self._mmean(e, mask)
-
- def m_l1(self, pred, tgt, mask):
- e = (pred - tgt).abs().flatten(1).mean(1)
- return self._mmean(e, mask)
-
- def _simcc_ce(self, logits, tgt_2d):
- """CE between predicted bin distributions and a Gaussian soft-label.
- NOTE: has an irreducible label-entropy floor (~2.1 nats)."""
- bins = torch.linspace(-self.cfg.kp2d_range, self.cfg.kp2d_range,
- self.cfg.kp2d_bins, device=logits.device)
- tgt = tgt_2d.clamp(-self.cfg.kp2d_range, self.cfg.kp2d_range)
- d = bins.view(1, 1, 1, -1) - tgt.unsqueeze(-1) # [B,70,2,bins]
- label = torch.exp(-(d ** 2) / (2.0 * self.simcc_sigma ** 2))
- label = label / label.sum(dim=-1, keepdim=True).clamp_min(1e-8)
- logp = F.log_softmax(logits, dim=-1)
- return -(label * logp).sum(dim=-1).mean()
-
- def _project_3d_to_norm_2d(self, j3d, pred_cam_trans, targets):
- """Helper to project 3D points (in meters) to normalized [-1, 1] 2D crop space."""
- # A. Move to Camera Space
- j3d_cam = j3d + pred_cam_trans.unsqueeze(1)
-
- # Prevent 1/Z^2 Gradient Explosions
- # 0.01 allows a gradient multiplier of 10,000.
- # 0.4 meters (40cm) limits the multiplier to a safe limit, protecting the kinematic tree.
- z_cam = torch.clamp(j3d_cam[..., 2], min=0.4)
-
- # B. Extract Intrinsics
- fx = targets["cam_focal"][:, 0:1] # Shape: [B, 1]
- fy = targets["cam_focal"][:, 1:2] # Shape: [B, 1]
- cx = targets["orig_shape"][:, 1:2] / 2.0 # Shape: [B, 1]
- cy = targets["orig_shape"][:, 0:1] / 2.0 # Shape: [B, 1]
-
- # C. Full-Frame Projection
- u_full = (fx * j3d_cam[..., 0] / z_cam) + cx
- v_full = (fy * j3d_cam[..., 1] / z_cam) + cy
-
- # D. Map to Crop Space
- bbox = targets["bbox_square"]
- sq_x1 = bbox[:, 0:1] # [B, 1]
- sq_y1 = bbox[:, 1:2] # [B, 1]
- crop_w = torch.clamp(bbox[:, 2:3] - bbox[:, 0:1], min=1.0) # [B, 1]
-
- true_scale = self.cfg.image_size / crop_w
- u_crop = (u_full - sq_x1) * true_scale
- v_crop = (v_full - sq_y1) * true_scale
-
- # D2. Apply the sample's geometric-aug affine (identity when unaugmented),
- # so the projection lands in the SAME warped crop space as the 2D targets.
- M = targets["aug_M"] # [B, 6]
- u_aug = M[:, 0:1] * u_crop + M[:, 1:2] * v_crop + M[:, 2:3]
- v_aug = M[:, 3:4] * u_crop + M[:, 4:5] * v_crop + M[:, 5:6]
-
- # E. Normalize to [-1, 1]
- u_norm = (u_aug / self.cfg.image_size) * 2.0 - 1.0
- v_norm = (v_aug / self.cfg.image_size) * 2.0 - 1.0
-
- return torch.stack([u_norm, v_norm], dim=-1) # Shape: [B, J, 2]
-
- def forward(self, preds, targets):
- losses = {}
- idx_pose = self.cfg.pose_dim
- B = preds["mhr_params"].shape[0]
-
- # ---- per-sample masks from the augmentation metadata ----
- ones = torch.ones(B, device=preds["mhr_params"].device)
- aug_active = targets.get("aug_active", 1.0 - ones) # default: all identity
- aug_flip = targets.get("aug_flip", 0.0 * ones)
- m_ident = 1.0 - aug_active # pose params can't be rotated in param space
- m_noflip = 1.0 - aug_flip # MHR L/R chains can't be swapped in param space
-
- pred_pose = preds["mhr_params"][:, :idx_pose]
- pred_scale = preds["mhr_params"][:, idx_pose:]
- tgt_pose = targets["mhr_model_params"][:, :idx_pose]
- tgt_scale = targets["mhr_model_params"][:, idx_pose:]
-
- # --- 1. Base Parameters ---
- # pose: identity samples only (root orient is baked into the params and the
- # Momentum rig distributes it non-rigidly -> no safe param-space rotation).
- losses['loss_pose'] = self.m_smooth_l1(pred_pose, tgt_pose, m_ident) * self.cfg.w_pose
- # scale/shape: rotation-invariant, but not flip-safe -> mask flipped samples.
- losses['loss_scale'] = self.m_mse(pred_scale, tgt_scale, m_noflip) * self.cfg.w_scale
- losses['loss_shape'] = self.m_mse(preds["shape_params"], targets["shape_params"], m_noflip) * self.cfg.w_shape
- # cam target was rotated/mirrored by the dataset -> always supervised.
- losses['loss_cam'] = self.mse(preds["cam_trans"], targets["cam_trans"]) * self.cfg.w_cam
-
- # --- 2. Differentiable 3D Joint Alignment (Centimeter space corrected!) ---
- pred_mhr_joints = self.mhr_module.get_joints(preds["mhr_params"], preds["shape_params"])[..., :3]
- with torch.no_grad():
- tgt_mhr_joints = self.mhr_module.get_joints(targets["mhr_model_params"], targets["shape_params"])[..., :3]
- # Rotate the TARGET MHR joints in JOINT space to match the augmented view.
- # Vision-frame R_v=[[c,s],[-s,c]] maps to MHR frame (x_m=x_v, y_m=-y_v):
- # x' = c·x − s·y ; y' = s·x + c·y. Identity samples: c=1,s=0 -> no-op.
- c = targets["aug_cos"].view(-1, 1) if "aug_cos" in targets else torch.ones(B, 1, device=ones.device)
- s = targets["aug_sin"].view(-1, 1) if "aug_sin" in targets else torch.zeros(B, 1, device=ones.device)
- xm, ym = tgt_mhr_joints[..., 0], tgt_mhr_joints[..., 1]
- tgt_mhr_joints = torch.stack(
- [c * xm - s * ym, s * xm + c * ym, tgt_mhr_joints[..., 2]], dim=-1)
-
- # flipped samples masked: no L/R permutation exists for the 127 MHR joints.
- losses['loss_mhr_joints'] = self.m_smooth_l1(
- pred_mhr_joints, tgt_mhr_joints.detach(), m_noflip) * self.cfg.w_3d_joints
-
- # --- Base MHR Vision Coordinates (Needed for Structural & Reprojection) ---
- pred_mhr_vision = pred_mhr_joints.clone() / 100.0
- pred_mhr_vision[..., 1] = -pred_mhr_vision[..., 1]
- pred_mhr_vision[..., 2] = -pred_mhr_vision[..., 2]
-
- # ==============================================================================
- # 2.5 Structural Consistency Loss (MHR mesh vs Native Keypoints)
- # ==============================================================================
- if hasattr(self.cfg, 'native_mapping_ids') and hasattr(self.cfg, 'mhr_mapping_ids'):
- pred_native_anchors = preds["joints_3d"][:, self.cfg.native_mapping_ids, :3]
- pred_mhr_anchors = pred_mhr_vision[:, self.cfg.mhr_mapping_ids, :3]
- losses['loss_structural'] = self.l1(pred_native_anchors, pred_mhr_anchors) * self.cfg.w_structural
-
- # ==============================================================================
- # Feet Barycenter Alignment Loss
- # ==============================================================================
- if hasattr(self.cfg, 'native_left_foot') and hasattr(self.cfg, 'w_feet'):
- nat_lf_pts = preds["joints_3d"][:, self.cfg.native_left_foot, :3]
- nat_rf_pts = preds["joints_3d"][:, self.cfg.native_right_foot, :3]
-
- mhr_lf_pts = pred_mhr_vision[:, self.cfg.mhr_left_foot, :3]
- mhr_rf_pts = pred_mhr_vision[:, self.cfg.mhr_right_foot, :3]
-
- nat_lf_bary = nat_lf_pts.mean(dim=1)
- nat_rf_bary = nat_rf_pts.mean(dim=1)
- mhr_lf_bary = mhr_lf_pts.mean(dim=1)
- mhr_rf_bary = mhr_rf_pts.mean(dim=1)
-
- losses['loss_feet'] = (self.strict_l1(nat_lf_bary, mhr_lf_bary) + self.strict_l1(nat_rf_bary, mhr_rf_bary)) * self.cfg.w_feet
-
- # --- 3. DYNAMIC Native Keypoints ---
- pred_2d = preds["joints_2d"]
- tgt_2d = targets["joints_2d"]
- losses['loss_2d_native'] = self.l1(pred_2d[..., :2], tgt_2d) * self.cfg.w_keypoints2d
- # SimCC bin-classification: sharpens the soft-argmax distributions.
- if "joints_2d_logits" in preds:
- losses['loss_2d_simcc'] = self._simcc_ce(preds["joints_2d_logits"], tgt_2d) * self.cfg.w_simcc
-
- pred_3d = preds["joints_3d"]
- tgt_3d = targets["joints_3d"]
- losses['loss_3d_native'] = self.l1(pred_3d[..., :3], tgt_3d) * self.cfg.w_keypoints3d
-
- # ==============================================================================
- # 4. 2D Reprojection Loss (Camera-Pose Consistency)
- # ==============================================================================
- # Predictions live in the AUGMENTED (rotated) frame. Counter-rotate them by
- # R_v^T, project through the ORIGINAL camera/bbox, and let the projection
- # helper apply the sample's aug affine M -> lands exactly on the warped 2D
- # targets. Masked on flipped samples (mirror isn't a rigid camera motion).
- cc = targets["aug_cos"].view(-1, 1)
- ss = targets["aug_sin"].view(-1, 1)
-
- def _counter_rot_pts(pts): # R_v^T on [..., :2]
- x, y = pts[..., 0], pts[..., 1]
- return torch.stack([cc * x - ss * y, ss * x + cc * y, pts[..., 2]], dim=-1)
-
- def _counter_rot_cam(cam): # [B, 3]
- x, y = cam[:, 0:1], cam[:, 1:2]
- return torch.cat([cc * x - ss * y, ss * x + cc * y, cam[:, 2:3]], dim=1)
-
- cam_cr = _counter_rot_cam(preds["cam_trans"])
-
- # A. Native 3D Head Reprojection (All 70 Joints)
- pred_reproj_native = self._project_3d_to_norm_2d(
- _counter_rot_pts(preds["joints_3d"][..., :3]), cam_cr, targets)
- losses['loss_reproj_native'] = self.m_l1(pred_reproj_native, tgt_2d, m_noflip) * self.cfg.w_reproj_3d
-
- # B. MHR Mesh Anchors Reprojection (52 Anchors)
- if hasattr(self.cfg, 'native_mapping_ids') and hasattr(self.cfg, 'mhr_mapping_ids'):
- pred_mhr_anchors_vision = pred_mhr_vision[:, self.cfg.mhr_mapping_ids, :3]
- pred_reproj_mhr = self._project_3d_to_norm_2d(
- _counter_rot_pts(pred_mhr_anchors_vision), cam_cr, targets)
- tgt_2d_anchors = tgt_2d[:, self.cfg.native_mapping_ids, :]
- losses['loss_reproj_mhr'] = self.m_l1(pred_reproj_mhr, tgt_2d_anchors, m_noflip) * self.cfg.w_reproj_mhr
-
- losses['total_loss'] = sum(losses.values())
- return losses
-
-
-# ============================================================
-# Cell 10 — HMR Evaluation Metrics (MPJPE & PA-MPJPE)
-# ============================================================
-def batched_procrustes_alignment(pred_pts, gt_pts):
- """
- Computes the optimal Similarity Transform (Scale, Rotation, Translation)
- to align pred_pts to gt_pts using Batched SVD.
- """
- B, N, D = pred_pts.shape
-
- # 1. Mean center the point clouds
- mu_pred = pred_pts.mean(dim=1, keepdim=True)
- mu_gt = gt_pts.mean(dim=1, keepdim=True)
-
- pred_centered = pred_pts - mu_pred
- gt_centered = gt_pts - mu_gt
-
- # 2. Calculate scale (Frobenius norm)
- norm_pred = torch.linalg.norm(pred_centered, dim=(1, 2), keepdim=True)
- norm_gt = torch.linalg.norm(gt_centered, dim=(1, 2), keepdim=True)
-
- pred_normalized = pred_centered / torch.clamp(norm_pred, min=1e-8)
- gt_normalized = gt_centered / torch.clamp(norm_gt, min=1e-8)
-
- # 3. Compute covariance matrix H (X^T Y)
- H = torch.bmm(pred_normalized.transpose(1, 2), gt_normalized)
-
- # 4. Singular Value Decomposition (SVD)
- # PyTorch returns U, S, and Vh (where Vh is V^T)
- U, S, Vh = torch.linalg.svd(H)
-
- # 5. Compute Rotation matrix R (U * V^T) - FIXED!
- R = torch.bmm(U, Vh)
-
- # 6. Fix reflection (Strict SO(3) rotation)
- det = torch.linalg.det(R)
-
- # If det < 0, we must flip the sign of the 3rd column of U
- # Shape of det_sign is [B, 1]
- det_sign = torch.where(det < 0, torch.tensor(-1.0, device=pred_pts.device), torch.tensor(1.0, device=pred_pts.device)).unsqueeze(-1)
-
- U_fixed = U.clone()
- U_fixed[:, :, 2] *= det_sign
-
- # Recompute R with the reflection fix
- R_fixed = torch.bmm(U_fixed, Vh)
-
- # 7. Optimal Scale
- # We must apply the same sign fix to the 3rd singular value!
- S_fixed = S.clone()
- S_fixed[:, 2] *= det_sign.squeeze(-1)
-
- scale = S_fixed.sum(dim=-1, keepdim=True).unsqueeze(-1) * (norm_gt / torch.clamp(norm_pred, min=1e-8))
-
- # 8. Apply the transformation
- pred_aligned = scale * torch.bmm(pred_centered, R_fixed) + mu_gt
-
- return pred_aligned
-
-
-def evaluate_hmr_batch(preds, targets, cfg, mhr_module):
- """
- Calculates MPJPE and PA-MPJPE for both the 3D Keypoints Head and the MHR Mesh.
- Returns errors in MILLIMETERS (mm).
- """
- metrics = {}
-
- # ---------------------------------------------------------
- # 1. Evaluate the Native 3D Spatial Head (70 Joints)
- # ---------------------------------------------------------
- pred_3d_native = preds["joints_3d"][..., :3]
- gt_3d_native = targets["joints_3d"][..., :3]
-
- # MPJPE requires root-relative alignment (usually joint 0 is the root/pelvis)
- pred_3d_root_rel = pred_3d_native - pred_3d_native[:, 0:1, :]
- gt_3d_root_rel = gt_3d_native - gt_3d_native[:, 0:1, :]
-
- # MPJPE in mm (* 1000)
- err_native = torch.linalg.norm(pred_3d_root_rel - gt_3d_root_rel, dim=-1)
- metrics['Head_3D_MPJPE'] = err_native.mean().item() * 1000.0
-
- # PA-MPJPE in mm
- pred_3d_aligned = batched_procrustes_alignment(pred_3d_native, gt_3d_native)
- err_native_pa = torch.linalg.norm(pred_3d_aligned - gt_3d_native, dim=-1)
- metrics['Head_3D_PA_MPJPE'] = err_native_pa.mean().item() * 1000.0
-
- # ---------------------------------------------------------
- # 2. Evaluate the MHR Mesh Head (Using the 52 Anchors)
- # ---------------------------------------------------------
- if hasattr(cfg, 'native_mapping_ids') and hasattr(cfg, 'mhr_mapping_ids'):
- # Generate 3D mesh joints in cm
- pred_mhr_raw = mhr_module.get_joints(preds["mhr_params"], preds["shape_params"])[..., :3]
-
- # Convert to Meters and align axes
- pred_mhr_meters = pred_mhr_raw / 100.0
- pred_mhr_meters[..., 1] = -pred_mhr_meters[..., 1]
- pred_mhr_meters[..., 2] = -pred_mhr_meters[..., 2]
-
- # Extract the 52 matching anchors
- pred_mesh_anchors = pred_mhr_meters[:, cfg.mhr_mapping_ids, :]
- gt_mesh_anchors = gt_3d_native[:, cfg.native_mapping_ids, :]
-
- # Mean-Center for MPJPE (To bypass differing origin definitions between rigs)
- pred_mesh_centered = pred_mesh_anchors - pred_mesh_anchors.mean(dim=1, keepdim=True)
- gt_mesh_centered = gt_mesh_anchors - gt_mesh_anchors.mean(dim=1, keepdim=True)
-
- # Mesh MPJPE in mm
- err_mesh = torch.linalg.norm(pred_mesh_centered - gt_mesh_centered, dim=-1)
- metrics['Mesh_MPJPE'] = err_mesh.mean().item() * 1000.0
-
- # Mesh PA-MPJPE in mm (Procrustes naturally handles translation offsets!)
- pred_mesh_aligned = batched_procrustes_alignment(pred_mesh_anchors, gt_mesh_anchors)
- err_mesh_pa = torch.linalg.norm(pred_mesh_aligned - gt_mesh_anchors, dim=-1)
- metrics['Mesh_PA_MPJPE'] = err_mesh_pa.mean().item() * 1000.0
-
- return metrics
-
-
-# ============================================================
-# Cell 11 — Full Distillation Training Loop (EMA + Early-Stopping)
-# ============================================================
-def make_ema_avg_fn(max_decay):
- """EMA with a decay WARMUP: decay = min(max_decay, (1+n)/(10+n)).
- Early on (small n) decay is small so the shadow TRACKS the model instead of
- sitting near random init -> removes the early 'mean-pose mush' that gamed PA-MPJPE."""
- @torch.no_grad()
- def avg_fn(ema_params, model_params, num_averaged):
- # Integer buffers (e.g. BatchNorm num_batches_tracked) can't be lerp'd -> copy them,
- # mirroring torch's get_ema_multi_avg_fn. Without this, _foreach_lerp_ errors on Long.
- if not (torch.is_floating_point(ema_params[0]) or torch.is_complex(ema_params[0])):
- for e, m in zip(ema_params, model_params):
- e.copy_(m)
- return
- n = num_averaged.item() if torch.is_tensor(num_averaged) else float(num_averaged)
- decay = min(max_decay, (1.0 + n) / (10.0 + n))
- torch._foreach_lerp_(ema_params, model_params, 1.0 - decay)
- return avg_fn
-
-
-def train_instant_hmr():
- EMA_DECAY = getattr(cfg, "ema_decay", 0.9998)
- EARLY_STOP_PATIENCE = getattr(cfg, "early_stop_patience", 50) # epochs where NEITHER raw nor ema improved
-
- print(f"--- Training {cfg.backbone} | EMA decay={EMA_DECAY} | early-stop patience={EARLY_STOP_PATIENCE} ---")
- os.makedirs(cfg.log_dir, exist_ok=True)
-
- # Set to True to enable resuming
- RESUME_FROM_CHECKPOINT = getattr(cfg, "resume", True)
-
- # 1. Model + EMA shadow + loss
- model = InstantHMRStudent(cfg, pretrained=True).to(device)
- criterion = DistillationLoss(cfg, mhr_module)
-
- # 2. Optimizer & AMP
- optimizer = optim.AdamW(model.parameters(), lr=cfg.lr, weight_decay=cfg.weight_decay)
- scaler = torch.amp.GradScaler(device='cuda', enabled=cfg.use_amp)
-
- # 3. LR schedule
- steps_per_epoch = len(train_loader)
- scheduler = lr_scheduler.OneCycleLR(
- optimizer, max_lr=cfg.lr, epochs=cfg.epochs,
- steps_per_epoch=steps_per_epoch, pct_start=0.1,
- )
-
- best_raw_path = os.path.join(cfg.log_dir, "best_student_model_raw.pth")
- best_ema_path = os.path.join(cfg.log_dir, "best_student_model_ema.pth")
- best_ckpt_path = os.path.join(cfg.log_dir, "best_student_model_v3.pth") # best overall
-
- # Tracking variables
- start_epoch = 0
- best_raw_pa = float('inf')
- best_ema_pa = float('inf')
- best_overall_pa = float('inf')
- epochs_no_improve = 0
-
- # 4. Resume from Checkpoint Logic
- if RESUME_FROM_CHECKPOINT and os.path.exists(best_ckpt_path):
- print(f"🔄 Resuming from checkpoint: {best_ckpt_path}")
- # weights_only=False is often required to load optimizer/scheduler dicts safely in newer PyTorch versions
- ckpt = torch.load(best_ckpt_path, map_location=device, weights_only=False)
-
- # Load states
- model.load_state_dict(ckpt["model_state_dict"], strict=False)
- if "optimizer_state_dict" in ckpt:
- optimizer.load_state_dict(ckpt["optimizer_state_dict"])
- if "scaler_state_dict" in ckpt:
- scaler.load_state_dict(ckpt["scaler_state_dict"])
- if "scheduler_state_dict" in ckpt:
- scheduler.load_state_dict(ckpt["scheduler_state_dict"])
-
- start_epoch = ckpt.get("epoch", -1) + 1
- best_overall_pa = ckpt.get("val_pa_mpjpe", float('inf'))
- best_raw_pa = best_overall_pa
- best_ema_pa = best_overall_pa
- print(f"✅ Resumed successfully from Epoch {start_epoch}. Best PA-MPJPE was {best_overall_pa:.1f}mm.")
- else:
- print("🚀 Starting training from scratch with fresh weights.")
-
- # Initialize EMA *after* potential checkpoint loading so it inherits the resumed weights
- ema_model = AveragedModel(model, multi_avg_fn=make_ema_avg_fn(EMA_DECAY), use_buffers=True)
-
- # --- validation helper: evaluate ANY model over val_loader (closes over criterion/loaders) ---
- @torch.no_grad()
- def run_validation(eval_model, tag, epoch):
- eval_model.eval()
- vloss = {'total': 0.0, '2d': 0.0, '3d': 0.0, 'mhr': 0.0, 'struct': 0.0}
- hmr = {'Head_3D_MPJPE': 0.0, 'Head_3D_PA_MPJPE': 0.0, 'Mesh_MPJPE': 0.0, 'Mesh_PA_MPJPE': 0.0}
- n = 0
- vbar = tqdm(val_loader, desc=f"Epoch {epoch+1}/{cfg.epochs} [Val:{tag}]", leave=False)
- for batch in vbar:
- batch = {k: v.to(device) if isinstance(v, torch.Tensor) else v for k, v in batch.items()}
- with torch.amp.autocast(device_type='cuda', dtype=torch.float16, enabled=cfg.use_amp):
- preds_fp16 = eval_model(batch["image"], batch["cliff_cond"])
- preds = {k: v.float() for k, v in preds_fp16.items()}
- losses = criterion(preds, batch)
- if math.isnan(losses['total_loss'].item()) or math.isinf(losses['total_loss'].item()):
- continue
- vloss['total'] += losses['total_loss'].item()
- vloss['2d'] += losses.get('loss_2d_native', torch.tensor(0)).item()
- vloss['3d'] += losses.get('loss_3d_native', torch.tensor(0)).item()
- vloss['mhr'] += losses.get('loss_mhr_joints', torch.tensor(0)).item()
- vloss['struct'] += losses.get('loss_structural', torch.tensor(0)).item()
- bm = evaluate_hmr_batch(preds, batch, cfg, mhr_module)
- for k in hmr:
- hmr[k] += bm.get(k, 0.0)
- n += 1
- vbar.set_postfix({'PA-MPJPE': f"{hmr['Mesh_PA_MPJPE']/max(n,1):.1f}mm"})
- vbar.close()
- vloss = {k: v / max(n, 1) for k, v in vloss.items()}
- hmr = {k: v / max(n, 1) for k, v in hmr.items()}
- return vloss, hmr, n
-
- # Note the loop now starts at `start_epoch`
- for epoch in range(start_epoch, cfg.epochs):
- # ---------------- TRAIN ----------------
- model.train()
- tm = {'total': 0.0, '2d': 0.0, 'simcc': 0.0, '3d': 0.0, 'pose': 0.0, 'scale': 0.0, 'shape': 0.0, 'mhr': 0.0, 'struct': 0.0}
- nb = 0
- pbar = tqdm(train_loader, desc=f"Epoch {epoch+1}/{cfg.epochs} [Train]")
- for batch in pbar:
- batch = {k: v.to(device) if isinstance(v, torch.Tensor) else v for k, v in batch.items()}
- optimizer.zero_grad(set_to_none=True)
- with torch.amp.autocast(device_type='cuda', dtype=torch.float16, enabled=cfg.use_amp):
- preds_fp16 = model(batch["image"], batch["cliff_cond"])
- preds_fp32 = {k: v.float() for k, v in preds_fp16.items()}
- losses = criterion(preds_fp32, batch)
- loss = losses['total_loss']
- loss_val = loss.item()
- # Skip NaN/Inf AND anomalously large (but finite) batches — a single
- # ~1e14 MHR-loss batch would otherwise take a step and diverge training.
- if math.isnan(loss_val) or math.isinf(loss_val):
- print("⚠️ WARNING: NaN/Inf loss detected! Skipping step.")
- continue
- if loss_val > cfg.anomaly_loss_threshold:
- print(f"⚠️ WARNING: anomalous loss {loss_val:.1f} > {cfg.anomaly_loss_threshold} — skipping step.")
- continue
- scaler.scale(loss).backward()
- scaler.unscale_(optimizer)
- torch.nn.utils.clip_grad_norm_(model.parameters(), cfg.grad_clip)
- scale_before = scaler.get_scale()
- scaler.step(optimizer)
- scaler.update()
- scale_after = scaler.get_scale()
- if scale_before <= scale_after:
- scheduler.step()
- ema_model.update_parameters(model)
- tm['total'] += loss.item()
- tm['2d'] += losses.get('loss_2d_native', torch.tensor(0)).item()
- tm['simcc'] += losses.get('loss_2d_simcc', torch.tensor(0)).item()
- tm['3d'] += losses.get('loss_3d_native', torch.tensor(0)).item()
- tm['pose'] += losses.get('loss_pose', torch.tensor(0)).item()
- tm['scale'] += losses.get('loss_scale', torch.tensor(0)).item()
- tm['mhr'] += losses.get('loss_mhr_joints', torch.tensor(0)).item()
- tm['struct'] += losses.get('loss_structural', torch.tensor(0)).item()
- nb += 1
- pbar.set_postfix({'Tot': f"{loss.item():.3f}",
- 'MHR': f"{losses.get('loss_mhr_joints', torch.tensor(0)).item():.3f}"})
- pbar.close()
- avg_train = {k: v / max(nb, 1) for k, v in tm.items()}
-
- # ---------------- VALIDATE: raw model AND EMA model ----------------
- raw_val, raw_hmr, n_raw = run_validation(model, "raw", epoch)
- ema_val, ema_hmr, n_ema = run_validation(ema_model, "ema", epoch)
-
- # ---------------- SUMMARY ----------------
- print(f"\n📈 Epoch {epoch+1} Summary | LR: {scheduler.get_last_lr()[0]:.2e}")
- print(f" [Train] Tot: {avg_train['total']:.4f} | MHR: {avg_train['mhr']:.4f} | 2D: {avg_train['2d']:.4f} "
- f"| 3D: {avg_train['3d']:.4f} | simcc: {avg_train['simcc']:.3f} (CE floor ~2.1 = normal)")
- print(f" [Val RAW] Tot: {raw_val['total']:.4f} | Mesh PA-MPJPE: {raw_hmr['Mesh_PA_MPJPE']:.1f} | Mesh MPJPE: {raw_hmr['Mesh_MPJPE']:.1f} | Head PA: {raw_hmr['Head_3D_PA_MPJPE']:.1f} mm")
- print(f" [Val EMA] Tot: {ema_val['total']:.4f} | Mesh PA-MPJPE: {ema_hmr['Mesh_PA_MPJPE']:.1f} | Mesh MPJPE: {ema_hmr['Mesh_MPJPE']:.1f} | Head PA: {ema_hmr['Head_3D_PA_MPJPE']:.1f} mm")
- delta = raw_hmr['Mesh_PA_MPJPE'] - ema_hmr['Mesh_PA_MPJPE']
- print(f" 🔬 EMA vs RAW (Mesh PA-MPJPE): {'EMA better' if delta > 0 else 'RAW better'} by {abs(delta):.1f} mm")
-
- # ---------------- CHECKPOINTS ----------------
-
- # Save standard states dict for all checkpoints to allow resuming from any of them
- def get_save_dict(model_to_save, val_metric, source_name):
- return {
- 'epoch': epoch,
- 'model_state_dict': model_to_save.state_dict(),
- 'optimizer_state_dict': optimizer.state_dict(),
- 'scaler_state_dict': scaler.state_dict(),
- 'scheduler_state_dict': scheduler.state_dict(),
- 'val_pa_mpjpe': val_metric,
- 'source': source_name
- }
-
- # ---------------- CHECKPOINTS + EARLY-STOP BOOKKEEPING ----------------
- # Did each model improve its OWN best this epoch?
- improved_raw = n_raw > 0 and raw_hmr['Mesh_PA_MPJPE'] < best_raw_pa
- improved_ema = n_ema > 0 and ema_hmr['Mesh_PA_MPJPE'] < best_ema_pa
-
- if improved_raw:
- best_raw_pa = raw_hmr['Mesh_PA_MPJPE']
- torch.save(get_save_dict(model, best_raw_pa, 'raw'), best_raw_path)
- if improved_ema:
- best_ema_pa = ema_hmr['Mesh_PA_MPJPE']
- torch.save(get_save_dict(ema_model.module, best_ema_pa, 'ema'), best_ema_path)
-
- # Canonical "best overall" checkpoint (loaded by the export/eval cells)
- current = min(raw_hmr['Mesh_PA_MPJPE'], ema_hmr['Mesh_PA_MPJPE'])
- if current < best_overall_pa - 1e-4:
- best_overall_pa = current
- use_ema = ema_hmr['Mesh_PA_MPJPE'] <= raw_hmr['Mesh_PA_MPJPE']
- better = ema_model.module if use_ema else model
- torch.save(get_save_dict(better, best_overall_pa, 'ema' if use_ema else 'raw'), best_ckpt_path)
- print(f"\U0001f4be New best overall: {best_overall_pa:.1f} mm ({'EMA' if use_ema else 'RAW'}) -> {os.path.basename(best_ckpt_path)}")
-
- # ---------------- EARLY STOPPING ----------------
- # Stop ONLY after EARLY_STOP_PATIENCE epochs where NEITHER raw NOR ema improved its own best.
- if improved_raw or improved_ema:
- epochs_no_improve = 0
- else:
- epochs_no_improve += 1
- print(f" ⏳ Neither RAW nor EMA improved: {epochs_no_improve}/{EARLY_STOP_PATIENCE} (best raw {best_raw_pa:.1f} / ema {best_ema_pa:.1f} mm)")
- if epochs_no_improve >= EARLY_STOP_PATIENCE:
- print(f"\n\U0001f6d1 Early stopping at epoch {epoch+1}: neither RAW nor EMA improved for {EARLY_STOP_PATIENCE} epochs.")
- break
-
- print(f"\n🎉 Training complete! Best overall Mesh PA-MPJPE: {best_overall_pa:.1f} mm")
- print(f" best RAW: {best_raw_pa:.1f} mm -> {best_raw_path}")
- print(f" best EMA: {best_ema_pa:.1f} mm -> {best_ema_path}")
-
-
-# ============================================================
-# Cell 15 — Export & Static Quantization (FP32, FP16, INT8)
-# ============================================================
-class HMRDeployWrapper(nn.Module):
- """Deploy wrapper that returns the full output tuple."""
- def __init__(self, model):
- super().__init__()
- self.model = model
-
- def forward(self, image, cliff_cond):
- out = self.model(image, cliff_cond)
- return (out["mhr_params"], out["shape_params"], out["cam_trans"],
- out["joints_2d"], out["joints_3d"])
-
-
-def topological_sort_onnx(model):
- """Sort ONNX graph nodes in topological order.
-
- The ORT float16 converter with keep_io_types=True inserts Cast nodes at graph
- inputs but doesn't re-sort the graph, breaking topological order. This fixes it.
- """
- available = set()
- for inp in model.graph.input:
- available.add(inp.name)
- for init in model.graph.initializer:
- available.add(init.name)
-
- remaining = list(model.graph.node)
- sorted_nodes = []
-
- while remaining:
- progress = False
- for node in remaining:
- if all(inp in available or inp == '' for inp in node.input):
- sorted_nodes.append(node)
- remaining.remove(node)
- for out in node.output:
- available.add(out)
- progress = True
- break
- if not progress:
- sorted_nodes.extend(remaining)
- break
-
- del model.graph.node[:]
- model.graph.node.extend(sorted_nodes)
- return model
-
-
-def export_and_quantize():
- print("--- Exporting and Quantizing Full Model for Deployment ---")
-
- # --- INT8 Calibration Data Reader ---
- try:
- from onnxruntime.quantization import (
- CalibrationDataReader, quantize_static,
- QuantType, QuantFormat, CalibrationMethod,
- )
-
- class HMRCalibrationDataReader(CalibrationDataReader):
- def __init__(self, dataloader, max_samples=100):
- self.data_list = []
-
- print(f"Extracting {max_samples} individual images for INT8 calibration...")
- for batch in dataloader:
- images = batch["image"].numpy().astype(np.float32)
- cliffs = batch["cliff_cond"].numpy().astype(np.float32)
-
- for b_idx in range(images.shape[0]):
- if len(self.data_list) >= max_samples:
- break
- self.data_list.append({
- "image": images[b_idx:b_idx + 1],
- "cliff_cond": cliffs[b_idx:b_idx + 1]
- })
- if len(self.data_list) >= max_samples:
- break
-
- self.enum_data = iter(self.data_list)
-
- def get_next(self):
- return next(self.enum_data, None)
-
- except ImportError:
- print("⚠️ 'onnxruntime' is not installed. INT8 quantization will fail.")
- HMRCalibrationDataReader = None
-
- # --- Export & Quantize ---
- export_dir = Path(cfg.log_dir) / "export"
- export_dir.mkdir(parents=True, exist_ok=True)
-
- onnx_fp32_path = export_dir / "sam3d_full_fp32.onnx"
- onnx_fp16_path = export_dir / "sam3d_full_fp16.onnx"
- onnx_int8_path = export_dir / "sam3d_full_int8.onnx"
-
- output_keys = ["mhr_params", "shape_params", "cam_trans", "joints_2d", "joints_3d"]
-
- export_target_model = InstantHMRStudent(cfg, pretrained=False).to(device)
-
- best_ckpt_path = os.path.join(cfg.log_dir, "best_student_model_v3.pth")
-
- if os.path.exists(best_ckpt_path):
- ckpt = torch.load(best_ckpt_path, map_location=device, weights_only=True)
- clean_state_dict = {k.replace('_orig_mod.', ''): v for k, v in ckpt['model_state_dict'].items()}
- export_target_model.load_state_dict(clean_state_dict, strict=False)
- print(f"✅ Loaded best model from epoch {ckpt.get('epoch', 0)+1}.\n")
-
- deploy_model = HMRDeployWrapper(export_target_model)
- deploy_model.eval()
-
- dummy_img = torch.randn(1, 3, cfg.image_size, cfg.image_size, device=device)
- dummy_cliff = torch.randn(1, 3, device=device)
-
- dynamic_axes = {"image": {0: "batch"}, "cliff_cond": {0: "batch"}}
- for k in output_keys:
- dynamic_axes[k] = {0: "batch"}
-
- # A. Export FP32
- try:
- import onnx
- torch.onnx.export(
- deploy_model, (dummy_img, dummy_cliff), str(onnx_fp32_path),
- input_names=["image", "cliff_cond"], output_names=output_keys,
- dynamic_axes=dynamic_axes, opset_version=17
- )
- print(f"✅ FP32 saved: {onnx_fp32_path.name} | Size: {onnx_fp32_path.stat().st_size / 1e6:.1f} MB")
- except Exception as e:
- print(f"❌ FP32 export failed: {e}")
-
- # B. Export FP16 — uses ORT's converter which correctly updates Cast node `to` attributes
- # + topological sort to fix node ordering after keep_io_types Cast insertion
- try:
- from onnxruntime.transformers.float16 import convert_float_to_float16
- import warnings
- with warnings.catch_warnings():
- warnings.simplefilter("ignore")
- model_fp32 = onnx.load(str(onnx_fp32_path))
- model_fp16 = convert_float_to_float16(model_fp32, keep_io_types=True)
- model_fp16 = topological_sort_onnx(model_fp16)
- onnx.save(model_fp16, str(onnx_fp16_path))
- onnx.checker.check_model(onnx.load(str(onnx_fp16_path)), full_check=True)
- print(f"✅ FP16 saved: {onnx_fp16_path.name} | Size: {onnx_fp16_path.stat().st_size / 1e6:.1f} MB")
- except ImportError:
- print("⚠️ FP16 skipped (onnxruntime.transformers not available)")
- except Exception as e:
- print(f"❌ FP16 conversion failed: {e}")
-
- # C. Export INT8 — selective: only quantize Conv ops (backbone), skip transformer/heads
- # Naive quantization of all ops destroys accuracy (Softmax, LayerNorm, attention MatMuls
- # need FP32 precision) and is slower due to unfused QDQ overhead blocking NCHWc optimization.
- try:
- calib_reader = HMRCalibrationDataReader(train_loader, max_samples=100)
- calib_reader.enum_data = iter(calib_reader.data_list)
-
- # Collect transformer + head + projection node names to exclude from quantization
- # (defense-in-depth: op_types_to_quantize=['Conv'] already excludes them since they
- # have zero Conv ops, but explicit exclusion prevents issues if the model changes)
- fp32_model = onnx.load(str(onnx_fp32_path))
- nodes_to_exclude = []
- for node in fp32_model.graph.node:
- name = node.name or ''
- if any(kw in name for kw in ['/model/transformer/', '/model/head_',
- '/model/feat_proj', '/model/cond_proj']):
- nodes_to_exclude.append(name)
- del fp32_model
- print(f" Excluding {len(nodes_to_exclude)} transformer/head nodes from quantization")
-
- quantize_static(
- model_input=str(onnx_fp32_path),
- model_output=str(onnx_int8_path),
- calibration_data_reader=calib_reader,
- quant_format=QuantFormat.QDQ,
- op_types_to_quantize=['Conv'], # Only quantize Conv (backbone)
- per_channel=True, # Better accuracy for Conv weights
- reduce_range=False, # Not needed with VNNI
- activation_type=QuantType.QInt8,
- weight_type=QuantType.QInt8,
- nodes_to_exclude=nodes_to_exclude,
- calibrate_method=CalibrationMethod.Percentile,
- extra_options={
- 'CalibTensorRangeSymmetric': True,
- },
- )
- print(f"✅ INT8 saved: {onnx_int8_path.name} | Size: {onnx_int8_path.stat().st_size / 1e6:.1f} MB")
- except NameError:
- print("⚠️ INT8 skipped (train_loader not available)")
- except Exception as e:
- import traceback
- print(f"❌ INT8 conversion failed: {e}")
- traceback.print_exc()
-
- # D. Save PyTorch state dict
- sd_path = export_dir / "sam3d_student_state_dict.pth"
- torch.save(export_target_model.state_dict(), sd_path)
- print(f"\n✅ PyTorch state dict saved: {sd_path.name}")
-
- else:
- print("⚠️ No checkpoint found at:", best_ckpt_path)
-
-
-# ============================================================
-# Self-tests: geometry + MHR-consistency + perfect-student
-# ============================================================
-def _mock_preds_from(batch):
- return {
- "mhr_params": batch["mhr_model_params"].clone(),
- "shape_params": batch["shape_params"].clone(),
- "cam_trans": batch["cam_trans"].clone(),
- "joints_2d": batch["joints_2d"].clone(),
- "joints_3d": batch["joints_3d"].clone(),
- }
-
-
-def run_self_tests():
- print("--- Architecture Output Shapes ---")
- test_model = InstantHMRStudent(cfg, pretrained=False)
- out = test_model(torch.randn(2, 3, 224, 224), torch.randn(2, 3))
- for k, v in out.items():
- print(f" {k}: {tuple(v.shape)}")
-
- criterion = DistillationLoss(cfg, mhr_module)
-
- # ---- 1. Perfect-student on a CLEAN batch (original Cell-8 guarantee) ----
- print("\n--- Perfect Student (identity batch) ---")
- clean_ds = SAM3DStudentDataset(cfg.data_root, augment=False,
- max_images=256, per_dataset_caps=cfg.per_dataset_caps)
- clean_loader = DataLoader(clean_ds, batch_size=32, shuffle=False, num_workers=0)
- cb = {k: v.to(device) for k, v in next(iter(clean_loader)).items()}
- l_clean = criterion(_mock_preds_from(cb), cb)
- for k, v in l_clean.items():
- print(f" {k:<20}: {v.item():.6f}")
-
- # ---- 2. MHR-consistency on an AUGMENTED batch ----
- # Rotate the whole target set, then check that the pieces the masked losses
- # rely on stay mutually consistent (same residuals as the clean batch).
- print("\n--- MHR consistency under geometric augmentation ---")
- aug_ds = SAM3DStudentDataset(cfg.data_root, augment=True,
- max_images=256, per_dataset_caps=cfg.per_dataset_caps,
- geom_p=1.0, geom_rot_deg=cfg.geom_rot_deg,
- geom_scale_range=cfg.geom_scale_range,
- geom_trans=cfg.geom_trans, geom_flip_p=0.0)
- aug_loader = DataLoader(aug_ds, batch_size=32, shuffle=False, num_workers=0)
- ab = {k: v.to(device) for k, v in next(iter(aug_loader)).items()}
-
- with torch.no_grad():
- # a) target MHR joints rotated in MHR frame -> vision frame
- tgt_mhr = mhr_module.get_joints(ab["mhr_model_params"], ab["shape_params"])[..., :3]
- cth = ab["aug_cos"].view(-1, 1)
- sth = ab["aug_sin"].view(-1, 1)
- xm, ym = tgt_mhr[..., 0], tgt_mhr[..., 1]
- tgt_mhr_rot = torch.stack([cth * xm - sth * ym, sth * xm + cth * ym, tgt_mhr[..., 2]], dim=-1)
- mhr_vis = tgt_mhr_rot / 100.0
- mhr_vis[..., 1] = -mhr_vis[..., 1]
- mhr_vis[..., 2] = -mhr_vis[..., 2]
- # structural alignment: rotated tgt MHR anchors vs rotated tgt native anchors
- d_aug = (ab["joints_3d"][:, cfg.native_mapping_ids, :]
- - mhr_vis[:, cfg.mhr_mapping_ids, :]).abs().mean().item()
- # clean reference
- tgt_mhr_c = mhr_module.get_joints(cb["mhr_model_params"], cb["shape_params"])[..., :3]
- mhr_vis_c = tgt_mhr_c / 100.0
- mhr_vis_c[..., 1] = -mhr_vis_c[..., 1]
- mhr_vis_c[..., 2] = -mhr_vis_c[..., 2]
- d_clean = (cb["joints_3d"][:, cfg.native_mapping_ids, :]
- - mhr_vis_c[:, cfg.mhr_mapping_ids, :]).abs().mean().item()
- print(f" native<->MHR anchor residual: clean {d_clean*1000:.2f} mm | augmented {d_aug*1000:.2f} mm")
- ok_struct = d_aug < d_clean * 1.5 + 1e-3
-
- # b) reprojection path: counter-rotate augmented targets, project, apply M
- cc, ss = cth, sth
-
- def counter(pts):
- x, y = pts[..., 0], pts[..., 1]
- return torch.stack([cc * x - ss * y, ss * x + cc * y, pts[..., 2]], dim=-1)
-
- cam_cr = torch.cat([cc * ab["cam_trans"][:, 0:1] - ss * ab["cam_trans"][:, 1:2],
- ss * ab["cam_trans"][:, 0:1] + cc * ab["cam_trans"][:, 1:2],
- ab["cam_trans"][:, 2:3]], dim=1)
- reproj_aug = criterion._project_3d_to_norm_2d(counter(ab["joints_3d"]), cam_cr, ab)
- r_aug = (reproj_aug - ab["joints_2d"]).abs().mean().item()
- reproj_clean = criterion._project_3d_to_norm_2d(cb["joints_3d"], cb["cam_trans"], cb)
- r_clean = (reproj_clean - cb["joints_2d"]).abs().mean().item()
- print(f" reproj(counter-rot + M) residual: clean {r_clean:.4f} | augmented {r_aug:.4f} (normalised units)")
- ok_reproj = r_aug < r_clean * 1.5 + 5e-3
-
- # ---- 3. Perfect-student LOSS on the augmented batch (masked path) ----
- print("\n--- Perfect Student (augmented batch, masked losses) ---")
- l_aug = criterion(_mock_preds_from(ab), ab)
- for k, v in l_aug.items():
- print(f" {k:<20}: {v.item():.6f}")
- # Only the terms the mock CAN satisfy are asserted ~0: the mock reuses the
- # ORIGINAL mhr_params (they cannot be rotated in param space — that is the
- # documented limitation), so FK(mock params) is the UNROTATED body and the
- # MHR-pred-derived terms (mhr_joints / structural / reproj_mhr) are expected
- # non-zero here. Their correctness is proven by the anchor-residual test
- # above (rotated targets align to 0.09 mm): a model that outputs the rotated
- # body scores ~0 on them.
- keys = ['loss_2d_native', 'loss_3d_native', 'loss_cam', 'loss_reproj_native']
- ok_loss = all(l_aug[k].item() < max(5 * l_clean[k].item(), 1e-3) for k in keys if k in l_aug)
-
- print()
- print(f" structural-consistency : {'✅' if ok_struct else '❌'}")
- print(f" reprojection-pathway : {'✅' if ok_reproj else '❌'}")
- print(f" masked perfect-student : {'✅' if ok_loss else '❌'}")
- if ok_struct and ok_reproj and ok_loss:
- print("\n✅ SELF-TEST PASSED: augmentation is consistent with the MHR pipeline.")
- else:
- print("\n❌ SELF-TEST FAILED — do not launch a long run.")
-
-
-# ============================================================
-# 1-batch overfit test (regression criterion; simcc CE has an
-# irreducible ~2.1-nat label-entropy floor and is reported apart)
-# ============================================================
-def run_overfit_test(steps=600, subset=8, lr=5e-4):
- print(f"--- 1-Batch Overfit Test ({subset} images, {steps} steps) ---")
- model = InstantHMRStudent(cfg, pretrained=True).to(device)
- criterion = DistillationLoss(cfg, mhr_module)
- optimizer = optim.AdamW(model.parameters(), lr=lr, weight_decay=0.0)
- scaler = torch.amp.GradScaler(device='cuda', enabled=cfg.use_amp)
-
- batch = next(iter(train_loader))
- batch = {k: (v[:subset].to(device) if isinstance(v, torch.Tensor) else v) for k, v in batch.items()}
-
- def reg(ls):
- return (ls['loss_2d_native'].item() + ls['loss_3d_native'].item()
- + ls['loss_cam'].item() + ls['loss_pose'].item())
-
- first_reg = last_reg = last_pa = None
- n_skipped = 0
- model.train()
- for step in range(steps):
- optimizer.zero_grad(set_to_none=True)
- with torch.amp.autocast(device_type='cuda', dtype=torch.float16, enabled=cfg.use_amp):
- preds = model(batch["image"], batch["cliff_cond"])
- preds = {k: v.float() for k, v in preds.items()}
- losses = criterion(preds, batch)
- lv = losses['total_loss'].item()
- # Same guards as the training loop: one anomalous MHR-FK batch taken as a
- # step would poison the weights and cascade to NaN.
- if math.isnan(lv) or math.isinf(lv) or lv > cfg.anomaly_loss_threshold:
- n_skipped += 1
- continue
- scaler.scale(losses['total_loss']).backward()
- scaler.unscale_(optimizer)
- torch.nn.utils.clip_grad_norm_(model.parameters(), cfg.grad_clip)
- scaler.step(optimizer)
- scaler.update()
- if first_reg is None:
- first_reg = reg(losses)
- last_reg = reg(losses)
- if step % 50 == 0 or step == steps - 1:
- model.eval()
- with torch.no_grad():
- p = {k: v.float() for k, v in model(batch["image"], batch["cliff_cond"]).items()}
- m = evaluate_hmr_batch(p, batch, cfg, mhr_module)
- model.train()
- last_pa = m['Head_3D_PA_MPJPE']
- print(f" step {step:04d} | tot {losses['total_loss'].item():.3f} "
- f"| 2d {losses['loss_2d_native'].item():.4f} | simcc {losses.get('loss_2d_simcc', torch.tensor(0)).item():.3f} "
- f"| 3d {losses['loss_3d_native'].item():.4f} | pose {losses['loss_pose'].item():.4f} "
- f"| mhr {losses['loss_mhr_joints'].item():.4f} | HeadPA {m['Head_3D_PA_MPJPE']:.1f} mm "
- f"| MeshPA {m['Mesh_PA_MPJPE']:.1f} mm")
-
- ok = (last_reg < first_reg * 0.10) and (last_pa is not None and last_pa < 40.0)
- print(f"\n{'✅ SUCCESS' if ok else '❌ FAIL'}: regression loss {first_reg:.4f} -> {last_reg:.5f} "
- f"| final Head PA-MPJPE {last_pa:.1f} mm | anomalous steps skipped: {n_skipped}")
- return ok
-
-
-# ============================================================
-# Entry point
-# ============================================================
-# Module-level globals populated by main() so the cell code above
-# (which references them directly) keeps working unchanged.
-cfg = None
-train_loader = None
-val_loader = None
-full_dataset = None
-mhr_module = None
-
-
-def parse_args():
- p = argparse.ArgumentParser(description="Standalone InstantHMR distillation training.")
- p.add_argument("--data_root", type=str, default=None,
- help="Entry-point folder containing sub-folders with annotations/ + images/.")
- p.add_argument("--output_dir", type=str, default=None,
- help="Where checkpoints/logs/exports are written (cfg.log_dir).")
- p.add_argument("--mhr_model_path", type=str, default=None,
- help="Path to the TorchScript MHR model (mhr_model.pt).")
- p.add_argument("--epochs", type=int, default=None)
- p.add_argument("--batch_size", type=int, default=None)
- p.add_argument("--lr", type=float, default=None)
- p.add_argument("--num_workers", type=int, default=None)
- p.add_argument("--max_images", type=int, default=None)
- p.add_argument("--harmony4d_cap", type=int, default=None,
- help="Max Harmony4D crops kept (randomly sampled). 0 = uncapped/use all.")
- p.add_argument("--no-resume", dest="no_resume", action="store_true",
- help="Ignore any existing checkpoint and train from scratch.")
- p.add_argument("--self-test", dest="self_test", action="store_true",
- help="Run the geometry/MHR-consistency checks and exit.")
- p.add_argument("--overfit-test", dest="overfit_test", action="store_true",
- help="Run the 1-batch overfit sanity check and exit.")
- p.add_argument("--no-export", dest="no_export", action="store_true",
- help="Skip the ONNX export / quantization step after training.")
- # Accepted for platform compatibility (sbatchHelpers may forward this); unused.
- p.add_argument("--gpu", type=int, default=None, help="GPU count (informational).")
- # Ignore any extra platform-injected flags rather than crashing.
- args, unknown = p.parse_known_args()
- if unknown:
- print(f"⚠️ Ignoring unrecognized arguments: {unknown}")
- return args
-
-
-def main():
- global cfg, train_loader, val_loader, full_dataset, mhr_module
-
- args = parse_args()
-
- cfg = DistillConfig()
- if args.data_root is not None: cfg.data_root = args.data_root
- if args.output_dir is not None: cfg.log_dir = args.output_dir
- if args.mhr_model_path is not None: cfg.mhr_model_path = args.mhr_model_path
- if args.epochs is not None: cfg.epochs = args.epochs
- if args.batch_size is not None: cfg.batch_size = args.batch_size
- if args.lr is not None: cfg.lr = args.lr
- if args.num_workers is not None: cfg.num_workers = args.num_workers
- if args.max_images is not None: cfg.max_images = args.max_images
- if args.harmony4d_cap is not None:
- if args.harmony4d_cap <= 0:
- cfg.per_dataset_caps.pop("sam3d_gt_harmony4d", None) # 0 = uncapped
- else:
- cfg.per_dataset_caps["sam3d_gt_harmony4d"] = args.harmony4d_cap
- if args.no_resume: cfg.resume = False
-
- print("=" * 60)
- print(f"Project root : {PROJECT_ROOT}")
- print(f"Data root : {cfg.data_root}")
- print(f"Output dir : {cfg.log_dir}")
- print(f"MHR model : {cfg.mhr_model_path}")
- print(f"Backbone : {cfg.backbone} | epochs={cfg.epochs} | batch={cfg.batch_size} | lr={cfg.lr}")
- print(f"max_images : {cfg.max_images if cfg.max_images is not None else 'unlimited (all crops)'}")
- print(f"dataset caps : {cfg.per_dataset_caps if cfg.per_dataset_caps else 'none'}")
- print(f"geom aug : p={cfg.geom_p} rot±{cfg.geom_rot_deg}° scale±{cfg.geom_scale_range} "
- f"trans±{cfg.geom_trans} flip={cfg.geom_flip_p}")
- print(f"2D head : SimCC soft-argmax, {cfg.kp2d_bins} bins over ±{cfg.kp2d_range} (w_simcc={cfg.w_simcc})")
- print("=" * 60)
-
- if not Path(cfg.mhr_model_path).exists():
- raise FileNotFoundError(
- f"MHR model not found at '{cfg.mhr_model_path}'. "
- f"Place mhr_model.pt in the checkpoints/ folder or pass --mhr_model_path."
- )
-
- # Build data (Cell 3), MHR module (Cell 8)
- train_loader, val_loader, full_dataset = build_dataloaders(cfg)
- mhr_module = MHRForwardPass(cfg.mhr_model_path, device)
-
- if args.self_test:
- run_self_tests()
- return
- if args.overfit_test:
- run_overfit_test()
- return
-
- # Train (Cell 11)
- gc.collect()
- if torch.cuda.is_available():
- torch.cuda.empty_cache()
- train_instant_hmr()
-
- # Export + quantize (Cell 15)
- if not args.no_export:
- export_and_quantize()
-
-
-if __name__ == "__main__":
- main()
diff --git a/instanthmr_distill_train/train_distill_optimized_correctives.py b/instanthmr_distill_train/train_distill_optimized_correctives.py
deleted file mode 100644
index e57563b..0000000
--- a/instanthmr_distill_train/train_distill_optimized_correctives.py
+++ /dev/null
@@ -1,1475 +0,0 @@
-#!/usr/bin/env python3
-# ============================================================
-# OPTIMIZED full-MHR distillation: train_distill.py + geometric
-# augmentation + SimCC soft-argmax 2D head + Soft Bone-Length Loss.
-# ------------------------------------------------------------
-# Keeps the ENTIRE MHR pipeline (params / shape / cam heads, MHR
-# forward pass, structural / feet / reprojection losses) — the
-# auxiliary supervision that made train_distill.py generalize
-# better than the pose3d variants — and adds:
-#
-# (1) GEOMETRIC AUG (applied with prob geom_p; else identity)
-# (2) SimCC soft-argmax 2D head: per-joint 1D bin logits over
-# [-kp2d_range, +kp2d_range].
-# (3) SOFT BONE-LENGTH CONSISTENCY: Enforces kinematic rigidity
-# on the 3D coordinate regression head without restricting
-# rotational degrees of freedom for OOD poses.
-#
-# Sanity: python3 train_distill_optimized.py --self-test --data_root ../data/sam3d_gt_mpii
-# python3 train_distill_optimized.py --overfit-test --data_root ../data/sam3d_gt_mpii
-# Full: python3 -u train_distill_optimized.py --data_root /datasets/instanthmr_data --num_workers 8
-# ============================================================
-import os
-
-# Must be set before the first CUDA allocation (read lazily by the allocator).
-os.environ.setdefault("PYTORCH_CUDA_ALLOC_CONF", "expandable_segments:True")
-
-import argparse
-import math
-import random
-import gc
-from dataclasses import dataclass, field
-from pathlib import Path
-
-import numpy as np
-from PIL import Image
-
-import torch
-import torch.nn as nn
-import torch.nn.functional as F
-import torch.optim as optim
-import torch.optim.lr_scheduler as lr_scheduler
-from torch.utils.data import Dataset, DataLoader, random_split
-from torch.optim.swa_utils import AveragedModel, get_ema_multi_avg_fn
-
-import torchvision.transforms as transforms
-import torchvision.transforms.functional as F_t
-from torchvision.transforms import InterpolationMode
-
-import timm
-from tqdm import tqdm
-
-# --- Notebook Cell 0 setup (headless-safe) ---
-import matplotlib
-matplotlib.use("Agg")
-import matplotlib.pyplot as plt
-import cv2
-import onnxruntime as ort
-
-print(ort.get_available_providers())
-
-device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
-print(f"Using device: {device}")
-
-PROJECT_ROOT = Path(__file__).resolve().parent
-DEFAULT_DATA_ROOT = "/pfcalcul/datasets/instanthmr_data/"
-
-# MHR70 joint ordering
-JOINT_NAMES = [
- "nose", "left_eye", "right_eye", "left_ear", "right_ear",
- "left_shoulder", "right_shoulder", "left_elbow", "right_elbow",
- "left_hip", "right_hip", "left_knee", "right_knee", "left_ankle", "right_ankle",
- "left_big_toe_tip", "left_small_toe_tip", "left_heel",
- "right_big_toe_tip", "right_small_toe_tip", "right_heel",
- "right_thumb_tip", "right_thumb_first_joint", "right_thumb_second_joint", "right_thumb_third_joint",
- "right_index_tip", "right_index_first_joint", "right_index_second_joint", "right_index_third_joint",
- "right_middle_tip", "right_middle_first_joint", "right_middle_second_joint", "right_middle_third_joint",
- "right_ring_tip", "right_ring_first_joint", "right_ring_second_joint", "right_ring_third_joint",
- "right_pinky_tip", "right_pinky_first_joint", "right_pinky_second_joint", "right_pinky_third_joint",
- "right_wrist",
- "left_thumb_tip", "left_thumb_first_joint", "left_thumb_second_joint", "left_thumb_third_joint",
- "left_index_tip", "left_index_first_joint", "left_index_second_joint", "left_index_third_joint",
- "left_middle_tip", "left_middle_first_joint", "left_middle_second_joint", "left_middle_third_joint",
- "left_ring_tip", "left_ring_first_joint", "left_ring_second_joint", "left_ring_third_joint",
- "left_pinky_tip", "left_pinky_first_joint", "left_pinky_second_joint", "left_pinky_third_joint",
- "left_wrist",
- "left_olecranon", "right_olecranon", "left_cubital_fossa", "right_cubital_fossa",
- "left_acromion", "right_acromion", "neck",
-]
-
-def _build_flip_perm(names):
- idx = {n: i for i, n in enumerate(names)}
- perm = list(range(len(names)))
- for i, n in enumerate(names):
- if n.startswith("left_"):
- perm[i] = idx.get("right_" + n[5:], i)
- elif n.startswith("right_"):
- perm[i] = idx.get("left_" + n[6:], i)
- perm = np.array(perm, dtype=np.int64)
- assert (perm[perm] == np.arange(len(perm))).all(), "flip permutation is not an involution"
- return perm
-
-FLIP_PERM = _build_flip_perm(JOINT_NAMES)
-
-# ============================================================
-# Cell 1 — Configuration
-# ============================================================
-@dataclass
-class DistillConfig:
- """All hyperparameters in one place."""
- data_root: str = str(DEFAULT_DATA_ROOT)
- mhr_model_path: str = str(PROJECT_ROOT / "checkpoints/mhr_model.pt")
- log_dir: str = str(PROJECT_ROOT / "runs/distill_optimized_v2")
-
- image_size: int = 224
- max_images: int | None = None
- per_dataset_caps: dict = field(default_factory=lambda: {"sam3d_gt_harmony4d": 300_000})
- val_split: float = 0.1
- num_workers: int = 4
- augment: bool = True
-
- geom_p: float = 0.8
- geom_rot_deg: float = 30.0
- geom_scale_range: float = 0.25
- geom_trans: float = 0.08
- geom_flip_p: float = 0.5
-
- kp2d_bins: int = 96
- kp2d_range: float = 1.5
-
- backbone: str = "repvit_m2_3"
- backbone_feat_dim: int = 640
- d_model: int = 512
- n_heads: int = 8
- n_decoder_layers: int = 4
- dropout: float = 0.1
-
- pose_dim: int = 136
- scale_dim: int = 68
- shape_dim: int = 45
- cam_dim: int = 3
- cliff_dim: int = 3
- num_joints: int = 70
-
- @property
- def model_params_dim(self) -> int:
- return self.pose_dim + self.scale_dim
-
- batch_size: int = 64
- lr: float = 3e-4
- weight_decay: float = 1e-4
- epochs: int = 400
- warmup_epochs: int = 3
- grad_clip: float = 1.0
- anomaly_loss_threshold: float = 100.0
- use_amp: bool = True
- ema_decay: float = 0.9998
- early_stop_patience: int = 150
- resume: bool = True
-
- w_pose: float = 1.0
- w_scale: float = 0.1
- w_shape: float = 1.0
- w_cam: float = 0.1
- w_keypoints3d: float = 10.0
- w_keypoints2d: float = 10.0
- w_3d_joints: float = 1e-3
- w_structural: float = 0.01
- w_reproj_3d: float = 0.01
- w_reproj_mhr: float = 0.01
- w_simcc: float = 1.0
- w_bone_length: float = 0.5 # NEW: Soft Prior for bone length consistency
-
- w_feet = 0.01
-
- native_left_foot = [15, 16, 17]
- native_right_foot = [18, 19, 20]
-
- mhr_left_foot = [6, 7, 8]
- mhr_right_foot = [22, 23, 24]
-
- native_mapping_ids = [ 1, 2, 5, 6, 9, 10, 11, 12, 13, 14, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62 ]
- mhr_mapping_ids = [ 125, 123, 75, 39, 2, 18, 3, 19, 5, 21, 64, 63, 62, 61, 59, 58, 57, 56, 55, 54, 53, 52, 51, 50, 49, 48, 47, 46, 45, 44, 41, 100, 99, 98, 97, 95, 94, 93, 92, 91, 90, 89, 88, 87, 86, 85, 84, 83, 82, 81, 80, 77 ]
-
- # NEW: Major bone connections to enforce spatial rigidity on native 3D joints
- # Format: (parent_idx, child_idx) based on JOINT_NAMES
- major_bones = [
- (5, 7), # Left Shoulder -> Left Elbow
- (7, 62), # Left Elbow -> Left Wrist (62 = left_wrist, NOT 41 = right_wrist)
- (6, 8), # Right Shoulder -> Right Elbow
- (8, 41), # Right Elbow -> Right Wrist (41 = right_wrist, NOT 42 = left_thumb_tip)
- (9, 11), # Left Hip -> Left Knee
- (11, 13), # Left Knee -> Left Ankle
- (10, 12), # Right Hip -> Right Knee
- (12, 14), # Right Knee -> Right Ankle
- ]
-
-# ============================================================
-# Cell 3 — Dataset and Data Augmentation
-# ============================================================
-class RandomPixelate:
- def __init__(self, p=0.2, min_res=32, max_res=112):
- self.p = p
- self.min_res = min_res
- self.max_res = max_res
-
- def __call__(self, img):
- if random.random() < self.p:
- orig_w, orig_h = img.size
- degraded_h = random.randint(self.min_res, self.max_res)
- degraded_w = int(orig_w * (degraded_h / orig_h))
- img = F_t.resize(img, [degraded_h, degraded_w], interpolation=InterpolationMode.NEAREST)
- img = F_t.resize(img, [orig_h, orig_w], interpolation=InterpolationMode.NEAREST)
- return img
-
-class SAM3DStudentDataset(Dataset):
- def __init__(self, data_root: str,
- image_size: int = 224, max_images: int | None = None,
- augment: bool = True, per_dataset_caps: dict | None = None,
- geom_p: float = 0.8, geom_rot_deg: float = 30.0,
- geom_scale_range: float = 0.25, geom_trans: float = 0.08,
- geom_flip_p: float = 0.5):
- super().__init__()
- self.image_size = image_size
- self.data_root = Path(data_root)
- self.augment = augment
- self.geom_p = geom_p
- self.geom_rot_deg = geom_rot_deg
- self.geom_scale_range = geom_scale_range
- self.geom_trans = geom_trans
- self.geom_flip_p = geom_flip_p
-
- tfm_list = [transforms.Resize((image_size, image_size))]
-
- if augment:
- tfm_list.extend([
- transforms.RandomApply([transforms.ColorJitter(
- brightness=0.2, contrast=0.2, saturation=0.2, hue=0.1)], p=0.5),
- RandomPixelate(p=0.2, min_res=48, max_res=112),
- transforms.RandomApply([transforms.GaussianBlur(kernel_size=5)], p=0.2),
- ])
-
- tfm_list.extend([
- transforms.ToTensor(),
- transforms.Normalize(mean=[0.485, 0.456, 0.406],
- std=[0.229, 0.224, 0.225]),
- ])
-
- if augment:
- tfm_list.append(transforms.RandomErasing(p=0.2, scale=(0.02, 0.15)))
-
- self.transform = transforms.Compose(tfm_list)
-
- self.pairs = []
- dataset_dirs = self._find_dataset_dirs(self.data_root)
- if not dataset_dirs:
- raise FileNotFoundError(
- f"No annotations/images sub-folders found under '{self.data_root}'."
- )
-
- cap_rng = random.Random(42)
- caps = per_dataset_caps or {}
-
- for ann_dir, img_dir in dataset_dirs:
- sub_name = ann_dir.parent.name
- sub_pairs = []
- for npz_path in sorted(ann_dir.glob("*.npz")):
- stem = npz_path.stem
- img_path = img_dir / f"{stem}.jpg"
- if not img_path.exists():
- img_path = img_dir / f"{stem}.png"
-
- if img_path.exists():
- sub_pairs.append((img_path, npz_path))
-
- cap = caps.get(sub_name)
- if cap is not None and len(sub_pairs) > cap:
- n_before = len(sub_pairs)
- sub_pairs.sort(key=lambda p: (str(p[1]), str(p[0])))
- sub_pairs = cap_rng.sample(sub_pairs, cap)
- print(f" [cap] {sub_name}: sampled {cap:,} of {n_before:,} crops")
- self.pairs.extend(sub_pairs)
-
- self.pairs.sort(key=lambda p: (str(p[1]), str(p[0])))
-
- if max_images is not None:
- self.pairs = self.pairs[:max_images]
-
- print(f" Found {len(dataset_dirs)} sub-folder(s) under {self.data_root}; "
- f"{len(self.pairs)} valid (image, npz) pairs (augment={augment}).")
-
- @staticmethod
- def _find_dataset_dirs(root: Path):
- dirs = []
- if (root / "annotations").is_dir() and (root / "images").is_dir():
- dirs.append((root / "annotations", root / "images"))
-
- if root.is_dir():
- for sub in sorted(root.iterdir()):
- if not sub.is_dir():
- continue
- ann, img = sub / "annotations", sub / "images"
- if ann.is_dir() and img.is_dir():
- dirs.append((ann, img))
- return dirs
-
- def __len__(self):
- return len(self.pairs)
-
- def __getitem__(self, idx):
- img_path, npz_path = self.pairs[idx]
- W = H = self.image_size
-
- img_pil = Image.open(img_path).convert("RGB")
- ann = np.load(npz_path)
- orig_h, orig_w = ann["orig_shape"]
-
- sq_bbox = ann["bbox_square"]
- sq_x1, sq_y1 = sq_bbox[0], sq_bbox[1]
- orig_crop_size = sq_bbox[2] - sq_bbox[0]
- true_scale = self.image_size / max(orig_crop_size, 1.0)
-
- joints_2d = ann["joints_2d"].copy().astype(np.float32)
- joints_2d[:, 0] = (joints_2d[:, 0] - sq_x1) * true_scale
- joints_2d[:, 1] = (joints_2d[:, 1] - sq_y1) * true_scale
- joints_2d[:, 0] = (joints_2d[:, 0] / self.image_size) * 2.0 - 1.0
- joints_2d[:, 1] = (joints_2d[:, 1] / self.image_size) * 2.0 - 1.0
-
- joints_3d = ann["joints_3d"].astype(np.float32).copy()
- cam_trans = ann["cam_trans"].astype(np.float32).copy()
-
- tight_bbox = ann["bbox"]
- cx = (tight_bbox[0] + tight_bbox[2]) / 2.0
- cy = (tight_bbox[1] + tight_bbox[3]) / 2.0
- b_size = max(tight_bbox[2] - tight_bbox[0], tight_bbox[3] - tight_bbox[1])
- b_scale = b_size / max(orig_w, orig_h)
-
- aug_flip, cos_t, sin_t = 0.0, 1.0, 0.0
- M_total = np.array([[1.0, 0.0, 0.0], [0.0, 1.0, 0.0]], dtype=np.float64)
- aug_active = 0.0
- if self.augment and random.random() < self.geom_p:
- aug_active = 1.0
- img_np = np.asarray(img_pil.resize((W, H)))
-
- if random.random() < self.geom_flip_p:
- aug_flip = 1.0
- M_flip = np.array([[-1.0, 0.0, float(W)], [0.0, 1.0, 0.0]])
- else:
- M_flip = np.array([[1.0, 0.0, 0.0], [0.0, 1.0, 0.0]])
-
- angle = random.uniform(-self.geom_rot_deg, self.geom_rot_deg)
- scale = random.uniform(1.0 - self.geom_scale_range, 1.0 + self.geom_scale_range)
- dx = random.uniform(-self.geom_trans, self.geom_trans)
- dy = random.uniform(-self.geom_trans, self.geom_trans)
- M_rst = cv2.getRotationMatrix2D((W / 2.0, H / 2.0), angle, scale)
- M_rst[0, 2] += dx * (W / 2.0)
- M_rst[1, 2] += dy * (H / 2.0)
-
- A2, t2 = M_rst[:, :2], M_rst[:, 2]
- A1, t1 = M_flip[:, :2], M_flip[:, 2]
- M_total = np.hstack([A2 @ A1, (A2 @ t1 + t2)[:, None]])
-
- img_np = cv2.warpAffine(img_np, M_total, (W, H), flags=cv2.INTER_LINEAR,
- borderMode=cv2.BORDER_CONSTANT, borderValue=(0, 0, 0))
- img_pil = Image.fromarray(img_np)
-
- px = (joints_2d[:, 0] + 1.0) * 0.5 * W
- py = (joints_2d[:, 1] + 1.0) * 0.5 * H
- px2 = M_total[0, 0] * px + M_total[0, 1] * py + M_total[0, 2]
- py2 = M_total[1, 0] * px + M_total[1, 1] * py + M_total[1, 2]
- joints_2d[:, 0] = (px2 / (0.5 * W) - 1.0).astype(np.float32)
- joints_2d[:, 1] = (py2 / (0.5 * H) - 1.0).astype(np.float32)
-
- if aug_flip > 0.5:
- joints_3d[:, 0] = -joints_3d[:, 0]
- joints_3d = joints_3d[FLIP_PERM]
- # joints_2d was already mirrored geometrically by M_total, but a
- # mirrored image LOOKS like the opposite-handed person, so the
- # left/right labels must be swapped too - exactly as for joints_3d.
- # Without this the 2D head gets contradictory left/right supervision
- # and collapses symmetric joints toward the body midline.
- joints_2d = joints_2d[FLIP_PERM]
- cam_trans[0] = -cam_trans[0]
- cx = orig_w - cx
- rad = math.radians(angle)
- cos_t, sin_t = math.cos(rad), math.sin(rad)
- R_v = np.array([[cos_t, sin_t], [-sin_t, cos_t]], dtype=np.float32)
- joints_3d[:, :2] = joints_3d[:, :2] @ R_v.T
- cam_trans[:2] = R_v @ cam_trans[:2]
-
- dxy = np.array([cx - orig_w / 2.0, cy - orig_h / 2.0], dtype=np.float64)
- dxy = R_v.astype(np.float64) @ dxy
- cx, cy = orig_w / 2.0 + dxy[0], orig_h / 2.0 + dxy[1]
-
- image = self.transform(img_pil)
-
- cx_norm = 2.0 * (cx / orig_w) - 1.0
- cy_norm = 2.0 * (cy / orig_h) - 1.0
- cliff_cond = torch.tensor([cx_norm, cy_norm, b_scale], dtype=torch.float32)
-
- return {
- "image": image,
- "cliff_cond": cliff_cond,
- "mhr_model_params": torch.from_numpy(ann["mhr_model_params"]).float(),
- "shape_params": torch.from_numpy(ann["shape_params"]).float(),
- "cam_trans": torch.from_numpy(cam_trans).float(),
- "cam_focal": torch.from_numpy(ann["cam_focal_length"]).float(),
- "joints_2d": torch.from_numpy(joints_2d).float(),
- "joints_3d": torch.from_numpy(joints_3d).float(),
- "orig_shape": torch.tensor([orig_h, orig_w], dtype=torch.float32),
- "bbox_square": sq_bbox,
- "aug_active": torch.tensor(aug_active, dtype=torch.float32),
- "aug_flip": torch.tensor(aug_flip, dtype=torch.float32),
- "aug_cos": torch.tensor(cos_t, dtype=torch.float32),
- "aug_sin": torch.tensor(sin_t, dtype=torch.float32),
- "aug_M": torch.from_numpy(M_total.astype(np.float32).reshape(-1)),
- }
-
-def build_dataloaders(cfg):
- geom = dict(geom_p=cfg.geom_p, geom_rot_deg=cfg.geom_rot_deg,
- geom_scale_range=cfg.geom_scale_range,
- geom_trans=cfg.geom_trans, geom_flip_p=cfg.geom_flip_p)
- full_dataset = SAM3DStudentDataset(
- cfg.data_root,
- augment=cfg.augment,
- max_images=cfg.max_images,
- per_dataset_caps=cfg.per_dataset_caps,
- **geom,
- )
-
- val_dataset_clean = SAM3DStudentDataset(
- cfg.data_root,
- augment=False,
- max_images=cfg.max_images,
- per_dataset_caps=cfg.per_dataset_caps,
- **geom,
- )
-
- n_val = int(len(full_dataset) * cfg.val_split)
- n_train = len(full_dataset) - n_val
-
- generator = torch.Generator().manual_seed(42)
- train_dataset, _ = random_split(full_dataset, [n_train, n_val], generator=generator)
-
- generator = torch.Generator().manual_seed(42)
- _, val_dataset = random_split(val_dataset_clean, [n_train, n_val], generator=generator)
-
- loader_kwargs = dict(num_workers=cfg.num_workers, pin_memory=True)
- if cfg.num_workers > 0:
- loader_kwargs["persistent_workers"] = True
- loader_kwargs["prefetch_factor"] = 4
-
- train_loader = DataLoader(
- train_dataset,
- batch_size=cfg.batch_size,
- shuffle=True,
- drop_last=True,
- **loader_kwargs,
- )
-
- val_loader = DataLoader(
- val_dataset,
- batch_size=cfg.batch_size,
- shuffle=False,
- **loader_kwargs,
- )
-
- print(f"Dataset Loaded! Train batches: {len(train_loader)} | Val batches: {len(val_loader)}")
- return train_loader, val_loader, full_dataset
-
-# ============================================================
-# Cell 7 — Student Architecture (Mini-SAM3D with PE)
-# ============================================================
-def get_2d_sincos_pos_embed(embed_dim, grid_size):
- grid_h, grid_w = grid_size, grid_size
- grid_y, grid_x = torch.meshgrid(torch.arange(grid_h), torch.arange(grid_w), indexing='ij')
-
- omega = torch.arange(embed_dim // 4).float() / (embed_dim // 4)
- omega = 1.0 / (10000 ** omega)
-
- out_y = grid_y.flatten().unsqueeze(1) * omega.unsqueeze(0)
- out_x = grid_x.flatten().unsqueeze(1) * omega.unsqueeze(0)
-
- pe_y = torch.cat([torch.sin(out_y), torch.cos(out_y)], dim=1)
- pe_x = torch.cat([torch.sin(out_x), torch.cos(out_x)], dim=1)
-
- pos_embed = torch.cat([pe_y, pe_x], dim=1)
- return pos_embed.unsqueeze(0)
-
-class InstantHMRStudent(nn.Module):
- def __init__(self, cfg, pretrained=True):
- super().__init__()
- self.cfg = cfg
-
- self.backbone = timm.create_model(cfg.backbone, pretrained=pretrained, num_classes=0)
- embed_dim = self.backbone.num_features
- self.feat_proj = nn.Linear(embed_dim, cfg.d_model)
-
- self.grid_size = cfg.image_size // 32
- pos_embed = get_2d_sincos_pos_embed(cfg.d_model, self.grid_size)
- self.register_buffer("mem_pos_embed", pos_embed)
-
- self.num_global = 1
- self.num_2d = cfg.num_joints
- self.num_3d = cfg.num_joints
- self.total_queries = self.num_global + self.num_2d + self.num_3d
-
- self.query_embed = nn.Parameter(torch.randn(1, self.total_queries, cfg.d_model) * 0.02)
-
- self.cond_proj = nn.Sequential(
- nn.Linear(cfg.cliff_dim, 128),
- nn.GELU(),
- nn.Linear(128, cfg.d_model)
- )
-
- decoder_layer = nn.TransformerDecoderLayer(
- d_model=cfg.d_model,
- nhead=cfg.n_heads,
- dim_feedforward=cfg.d_model * 4,
- dropout=cfg.dropout,
- activation="gelu",
- batch_first=True,
- norm_first=True
- )
- self.transformer = nn.TransformerDecoder(decoder_layer, num_layers=cfg.n_decoder_layers)
-
- self.global_out_dim = cfg.model_params_dim + cfg.shape_dim + cfg.cam_dim
- self.head_global = nn.Linear(cfg.d_model, self.global_out_dim)
-
- self.kp2d_bins = getattr(cfg, 'kp2d_bins', 96)
- self.kp2d_range = getattr(cfg, 'kp2d_range', 1.5)
- self.head_2d_feat = nn.Sequential(
- nn.Linear(cfg.d_model, 256),
- nn.GELU()
- )
- self.head_2d_logits = nn.Linear(256, 2 * self.kp2d_bins)
- self.register_buffer(
- "kp2d_bin_centers",
- torch.linspace(-self.kp2d_range, self.kp2d_range, self.kp2d_bins))
-
- self.dim_3d = 3
- self.head_3d = nn.Sequential(
- nn.Linear(cfg.d_model, 256),
- nn.GELU(),
- nn.Linear(256, self.dim_3d)
- )
-
- nn.init.constant_(self.head_global.bias[-1], 2.0)
- nn.init.constant_(self.head_global.bias[-2], 0.0)
- nn.init.constant_(self.head_global.bias[-3], 0.0)
-
- nn.init.normal_(self.head_global.weight, mean=0.0, std=1e-4)
- nn.init.constant_(self.head_global.bias[:-3], 0.0)
- nn.init.normal_(self.head_2d_logits.weight, mean=0.0, std=1e-4)
- nn.init.constant_(self.head_2d_logits.bias, 0.0)
- nn.init.normal_(self.head_3d[-1].weight, mean=0.0, std=1e-4)
- nn.init.constant_(self.head_3d[-1].bias, 0.0)
-
- def forward(self, images, cliff_cond):
- B = images.shape[0]
- img_feats = self.backbone.forward_features(images)
-
- if img_feats.dim() == 4:
- img_feats = img_feats.flatten(2).transpose(1, 2)
-
- memory = self.feat_proj(img_feats)
- memory = memory + self.mem_pos_embed
- queries = self.query_embed.expand(B, -1, -1)
- cond = self.cond_proj(cliff_cond).unsqueeze(1)
- queries = queries + cond
- shared_feats = self.transformer(tgt=queries, memory=memory)
-
- feat_global = shared_feats[:, 0, :]
- feat_2d = shared_feats[:, 1 : 1 + self.num_2d, :]
- feat_3d = shared_feats[:, 1 + self.num_2d :, :]
-
- global_preds = self.head_global(feat_global)
-
- idx_mhr = self.cfg.model_params_dim
- idx_shape = idx_mhr + self.cfg.shape_dim
-
- pred_mhr_params = global_preds[:, :idx_mhr]
- pred_shape_params = global_preds[:, idx_mhr : idx_shape]
- pred_cam_trans = global_preds[:, idx_shape :]
-
- feat_2d_processed = self.head_2d_feat(feat_2d)
- logits_2d = self.head_2d_logits(feat_2d_processed)
- logits_2d = logits_2d.unflatten(-1, (2, self.kp2d_bins))
- # softmax in fp32 (autocast already promotes it; explicit for no-autocast/bf16/export paths)
- prob_2d = torch.softmax(logits_2d.float(), dim=-1)
- pred_joints_2d = (prob_2d * self.kp2d_bin_centers.float()).sum(dim=-1)
-
- pred_joints_3d = self.head_3d(feat_3d)
-
- return {
- "mhr_params": pred_mhr_params,
- "shape_params": pred_shape_params,
- "cam_trans": pred_cam_trans,
- "joints_2d": pred_joints_2d,
- "joints_2d_logits": logits_2d,
- "joints_3d": pred_joints_3d
- }
-
-# ============================================================
-# Cell 8 — The Distillation Loss Module (Foolproof Edition)
-# ============================================================
-class MHRForwardPass:
- def __init__(self, mhr_path, device):
- self.device = device
- self.mhr = torch.jit.load(mhr_path, map_location=device).eval()
- for p in self.mhr.parameters():
- p.requires_grad_(False)
-
- def get_joints(self, model_params, shape_params):
- B = model_params.shape[0]
- dummy_identity = torch.zeros(B, 45, device=model_params.device, dtype=model_params.dtype)
- concat_params = torch.cat([model_params, dummy_identity], dim=1)
- joint_params = self.mhr.character_torch.model_parameters_to_joint_parameters(concat_params.to(self.device))
- skel_state = self.mhr.character_torch.joint_parameters_to_skeleton_state(joint_params)
- return skel_state.to(model_params.device)
-
-class DistillationLoss(nn.Module):
- def __init__(self, cfg, mhr_module):
- super().__init__()
- self.cfg = cfg
- self.mhr_module = mhr_module
- self.mse = nn.MSELoss()
- self.l1 = nn.SmoothL1Loss()
- self.strict_l1 = nn.L1Loss()
- bin_w = 2.0 * cfg.kp2d_range / (cfg.kp2d_bins - 1)
- self.simcc_sigma = 2.0 * bin_w
-
- @staticmethod
- def _mmean(per_sample, mask):
- return (per_sample * mask).sum() / mask.sum().clamp_min(1.0)
-
- def m_smooth_l1(self, pred, tgt, mask):
- e = F.smooth_l1_loss(pred, tgt, reduction='none').flatten(1).mean(1)
- return self._mmean(e, mask)
-
- def m_mse(self, pred, tgt, mask):
- e = F.mse_loss(pred, tgt, reduction='none').flatten(1).mean(1)
- return self._mmean(e, mask)
-
- def m_l1(self, pred, tgt, mask):
- e = (pred - tgt).abs().flatten(1).mean(1)
- return self._mmean(e, mask)
-
- def _simcc_ce(self, logits, tgt_2d):
- bins = torch.linspace(-self.cfg.kp2d_range, self.cfg.kp2d_range,
- self.cfg.kp2d_bins, device=logits.device)
- tgt = tgt_2d.clamp(-self.cfg.kp2d_range, self.cfg.kp2d_range)
- d = bins.view(1, 1, 1, -1) - tgt.unsqueeze(-1)
- label = torch.exp(-(d ** 2) / (2.0 * self.simcc_sigma ** 2))
- label = label / label.sum(dim=-1, keepdim=True).clamp_min(1e-8)
- logp = F.log_softmax(logits, dim=-1)
- return -(label * logp).sum(dim=-1).mean()
-
- def _project_3d_to_norm_2d(self, j3d, pred_cam_trans, targets):
- j3d_cam = j3d + pred_cam_trans.unsqueeze(1)
- z_cam = torch.clamp(j3d_cam[..., 2], min=0.4)
-
- fx = targets["cam_focal"][:, 0:1]
- fy = targets["cam_focal"][:, 1:2]
- cx = targets["orig_shape"][:, 1:2] / 2.0
- cy = targets["orig_shape"][:, 0:1] / 2.0
-
- u_full = (fx * j3d_cam[..., 0] / z_cam) + cx
- v_full = (fy * j3d_cam[..., 1] / z_cam) + cy
-
- bbox = targets["bbox_square"]
- sq_x1 = bbox[:, 0:1]
- sq_y1 = bbox[:, 1:2]
- crop_w = torch.clamp(bbox[:, 2:3] - bbox[:, 0:1], min=1.0)
-
- true_scale = self.cfg.image_size / crop_w
- u_crop = (u_full - sq_x1) * true_scale
- v_crop = (v_full - sq_y1) * true_scale
-
- M = targets["aug_M"]
- u_aug = M[:, 0:1] * u_crop + M[:, 1:2] * v_crop + M[:, 2:3]
- v_aug = M[:, 3:4] * u_crop + M[:, 4:5] * v_crop + M[:, 5:6]
-
- u_norm = (u_aug / self.cfg.image_size) * 2.0 - 1.0
- v_norm = (v_aug / self.cfg.image_size) * 2.0 - 1.0
-
- return torch.stack([u_norm, v_norm], dim=-1)
-
- def forward(self, preds, targets):
- losses = {}
- idx_pose = self.cfg.pose_dim
- B = preds["mhr_params"].shape[0]
-
- ones = torch.ones(B, device=preds["mhr_params"].device)
- aug_active = targets.get("aug_active", 1.0 - ones)
- aug_flip = targets.get("aug_flip", 0.0 * ones)
- m_ident = 1.0 - aug_active
- m_noflip = 1.0 - aug_flip
-
- pred_pose = preds["mhr_params"][:, :idx_pose]
- pred_scale = preds["mhr_params"][:, idx_pose:]
- tgt_pose = targets["mhr_model_params"][:, :idx_pose]
- tgt_scale = targets["mhr_model_params"][:, idx_pose:]
-
- losses['loss_pose'] = self.m_smooth_l1(pred_pose, tgt_pose, m_ident) * self.cfg.w_pose
- losses['loss_scale'] = self.m_mse(pred_scale, tgt_scale, m_noflip) * self.cfg.w_scale
- losses['loss_shape'] = self.m_mse(preds["shape_params"], targets["shape_params"], m_noflip) * self.cfg.w_shape
- losses['loss_cam'] = self.mse(preds["cam_trans"], targets["cam_trans"]) * self.cfg.w_cam
-
- pred_mhr_joints = self.mhr_module.get_joints(preds["mhr_params"], preds["shape_params"])[..., :3]
- with torch.no_grad():
- tgt_mhr_joints = self.mhr_module.get_joints(targets["mhr_model_params"], targets["shape_params"])[..., :3]
- c = targets["aug_cos"].view(-1, 1) if "aug_cos" in targets else torch.ones(B, 1, device=ones.device)
- s = targets["aug_sin"].view(-1, 1) if "aug_sin" in targets else torch.zeros(B, 1, device=ones.device)
- xm, ym = tgt_mhr_joints[..., 0], tgt_mhr_joints[..., 1]
- tgt_mhr_joints = torch.stack(
- [c * xm - s * ym, s * xm + c * ym, tgt_mhr_joints[..., 2]], dim=-1)
-
- losses['loss_mhr_joints'] = self.m_smooth_l1(
- pred_mhr_joints, tgt_mhr_joints.detach(), m_noflip) * self.cfg.w_3d_joints
-
- pred_mhr_vision = pred_mhr_joints.clone() / 100.0
- pred_mhr_vision[..., 1] = -pred_mhr_vision[..., 1]
- pred_mhr_vision[..., 2] = -pred_mhr_vision[..., 2]
-
- if hasattr(self.cfg, 'native_mapping_ids') and hasattr(self.cfg, 'mhr_mapping_ids'):
- pred_native_anchors = preds["joints_3d"][:, self.cfg.native_mapping_ids, :3]
- pred_mhr_anchors = pred_mhr_vision[:, self.cfg.mhr_mapping_ids, :3]
- losses['loss_structural'] = self.l1(pred_native_anchors, pred_mhr_anchors) * self.cfg.w_structural
-
- if hasattr(self.cfg, 'native_left_foot') and hasattr(self.cfg, 'w_feet'):
- nat_lf_pts = preds["joints_3d"][:, self.cfg.native_left_foot, :3]
- nat_rf_pts = preds["joints_3d"][:, self.cfg.native_right_foot, :3]
-
- mhr_lf_pts = pred_mhr_vision[:, self.cfg.mhr_left_foot, :3]
- mhr_rf_pts = pred_mhr_vision[:, self.cfg.mhr_right_foot, :3]
-
- nat_lf_bary = nat_lf_pts.mean(dim=1)
- nat_rf_bary = nat_rf_pts.mean(dim=1)
- mhr_lf_bary = mhr_lf_pts.mean(dim=1)
- mhr_rf_bary = mhr_rf_pts.mean(dim=1)
-
- losses['loss_feet'] = (self.strict_l1(nat_lf_bary, mhr_lf_bary) + self.strict_l1(nat_rf_bary, mhr_rf_bary)) * self.cfg.w_feet
-
- # ==============================================================================
- # NEW: Soft Bone-Length Consistency Loss
- # ==============================================================================
- if hasattr(self.cfg, 'major_bones') and hasattr(self.cfg, 'w_bone_length'):
- pred_3d = preds["joints_3d"]
- tgt_3d = targets["joints_3d"]
-
- p_idx = [b[0] for b in self.cfg.major_bones]
- c_idx = [b[1] for b in self.cfg.major_bones]
-
- pred_bones = pred_3d[:, c_idx, :3] - pred_3d[:, p_idx, :3]
- tgt_bones = tgt_3d[:, c_idx, :3] - tgt_3d[:, p_idx, :3]
-
- pred_bone_lens = torch.norm(pred_bones, dim=-1)
- tgt_bone_lens = torch.norm(tgt_bones, dim=-1)
-
- losses['loss_bone_length'] = self.l1(pred_bone_lens, tgt_bone_lens) * self.cfg.w_bone_length
-
- pred_2d = preds["joints_2d"]
- tgt_2d = targets["joints_2d"]
- losses['loss_2d_native'] = self.l1(pred_2d[..., :2], tgt_2d) * self.cfg.w_keypoints2d
- if "joints_2d_logits" in preds:
- losses['loss_2d_simcc'] = self._simcc_ce(preds["joints_2d_logits"], tgt_2d) * self.cfg.w_simcc
-
- pred_3d = preds["joints_3d"]
- tgt_3d = targets["joints_3d"]
- losses['loss_3d_native'] = self.l1(pred_3d[..., :3], tgt_3d) * self.cfg.w_keypoints3d
-
- cc = targets["aug_cos"].view(-1, 1)
- ss = targets["aug_sin"].view(-1, 1)
-
- def _counter_rot_pts(pts):
- x, y = pts[..., 0], pts[..., 1]
- return torch.stack([cc * x - ss * y, ss * x + cc * y, pts[..., 2]], dim=-1)
-
- def _counter_rot_cam(cam):
- x, y = cam[:, 0:1], cam[:, 1:2]
- return torch.cat([cc * x - ss * y, ss * x + cc * y, cam[:, 2:3]], dim=1)
-
- cam_cr = _counter_rot_cam(preds["cam_trans"])
-
- pred_reproj_native = self._project_3d_to_norm_2d(
- _counter_rot_pts(preds["joints_3d"][..., :3]), cam_cr, targets)
- losses['loss_reproj_native'] = self.m_l1(pred_reproj_native, tgt_2d, m_noflip) * self.cfg.w_reproj_3d
-
- if hasattr(self.cfg, 'native_mapping_ids') and hasattr(self.cfg, 'mhr_mapping_ids'):
- pred_mhr_anchors_vision = pred_mhr_vision[:, self.cfg.mhr_mapping_ids, :3]
- pred_reproj_mhr = self._project_3d_to_norm_2d(
- _counter_rot_pts(pred_mhr_anchors_vision), cam_cr, targets)
- tgt_2d_anchors = tgt_2d[:, self.cfg.native_mapping_ids, :]
- losses['loss_reproj_mhr'] = self.m_l1(pred_reproj_mhr, tgt_2d_anchors, m_noflip) * self.cfg.w_reproj_mhr
-
- losses['total_loss'] = sum(losses.values())
- return losses
-
-# ============================================================
-# Cell 10 — HMR Evaluation Metrics (MPJPE & PA-MPJPE)
-# ============================================================
-def batched_procrustes_alignment(pred_pts, gt_pts):
- B, N, D = pred_pts.shape
- mu_pred = pred_pts.mean(dim=1, keepdim=True)
- mu_gt = gt_pts.mean(dim=1, keepdim=True)
- pred_centered = pred_pts - mu_pred
- gt_centered = gt_pts - mu_gt
- norm_pred = torch.linalg.norm(pred_centered, dim=(1, 2), keepdim=True)
- norm_gt = torch.linalg.norm(gt_centered, dim=(1, 2), keepdim=True)
- pred_normalized = pred_centered / torch.clamp(norm_pred, min=1e-8)
- gt_normalized = gt_centered / torch.clamp(norm_gt, min=1e-8)
- H = torch.bmm(pred_normalized.transpose(1, 2), gt_normalized)
- U, S, Vh = torch.linalg.svd(H)
- R = torch.bmm(U, Vh)
- det = torch.linalg.det(R)
- det_sign = torch.where(det < 0, torch.tensor(-1.0, device=pred_pts.device), torch.tensor(1.0, device=pred_pts.device)).unsqueeze(-1)
- U_fixed = U.clone()
- U_fixed[:, :, 2] *= det_sign
- R_fixed = torch.bmm(U_fixed, Vh)
- S_fixed = S.clone()
- S_fixed[:, 2] *= det_sign.squeeze(-1)
- scale = S_fixed.sum(dim=-1, keepdim=True).unsqueeze(-1) * (norm_gt / torch.clamp(norm_pred, min=1e-8))
- pred_aligned = scale * torch.bmm(pred_centered, R_fixed) + mu_gt
- return pred_aligned
-
-def evaluate_hmr_batch(preds, targets, cfg, mhr_module):
- metrics = {}
- pred_3d_native = preds["joints_3d"][..., :3]
- gt_3d_native = targets["joints_3d"][..., :3]
- pred_3d_root_rel = pred_3d_native - pred_3d_native[:, 0:1, :]
- gt_3d_root_rel = gt_3d_native - gt_3d_native[:, 0:1, :]
- err_native = torch.linalg.norm(pred_3d_root_rel - gt_3d_root_rel, dim=-1)
- metrics['Head_3D_MPJPE'] = err_native.mean().item() * 1000.0
- pred_3d_aligned = batched_procrustes_alignment(pred_3d_native, gt_3d_native)
- err_native_pa = torch.linalg.norm(pred_3d_aligned - gt_3d_native, dim=-1)
- metrics['Head_3D_PA_MPJPE'] = err_native_pa.mean().item() * 1000.0
-
- if hasattr(cfg, 'native_mapping_ids') and hasattr(cfg, 'mhr_mapping_ids'):
- pred_mhr_raw = mhr_module.get_joints(preds["mhr_params"], preds["shape_params"])[..., :3]
- pred_mhr_meters = pred_mhr_raw / 100.0
- pred_mhr_meters[..., 1] = -pred_mhr_meters[..., 1]
- pred_mhr_meters[..., 2] = -pred_mhr_meters[..., 2]
- pred_mesh_anchors = pred_mhr_meters[:, cfg.mhr_mapping_ids, :]
- gt_mesh_anchors = gt_3d_native[:, cfg.native_mapping_ids, :]
- pred_mesh_centered = pred_mesh_anchors - pred_mesh_anchors.mean(dim=1, keepdim=True)
- gt_mesh_centered = gt_mesh_anchors - gt_mesh_anchors.mean(dim=1, keepdim=True)
- err_mesh = torch.linalg.norm(pred_mesh_centered - gt_mesh_centered, dim=-1)
- metrics['Mesh_MPJPE'] = err_mesh.mean().item() * 1000.0
- pred_mesh_aligned = batched_procrustes_alignment(pred_mesh_anchors, gt_mesh_anchors)
- err_mesh_pa = torch.linalg.norm(pred_mesh_aligned - gt_mesh_anchors, dim=-1)
- metrics['Mesh_PA_MPJPE'] = err_mesh_pa.mean().item() * 1000.0
- return metrics
-
-# ============================================================
-# Cell 11 — Full Distillation Training Loop
-# ============================================================
-def make_ema_avg_fn(max_decay):
- @torch.no_grad()
- def avg_fn(ema_params, model_params, num_averaged):
- if not (torch.is_floating_point(ema_params[0]) or torch.is_complex(ema_params[0])):
- for e, m in zip(ema_params, model_params):
- e.copy_(m)
- return
- n = num_averaged.item() if torch.is_tensor(num_averaged) else float(num_averaged)
- decay = min(max_decay, (1.0 + n) / (10.0 + n))
- torch._foreach_lerp_(ema_params, model_params, 1.0 - decay)
- return avg_fn
-
-def train_instant_hmr():
- EMA_DECAY = getattr(cfg, "ema_decay", 0.9998)
- EARLY_STOP_PATIENCE = getattr(cfg, "early_stop_patience", 50)
-
- print(f"--- Training {cfg.backbone} | EMA decay={EMA_DECAY} | early-stop patience={EARLY_STOP_PATIENCE} ---")
- os.makedirs(cfg.log_dir, exist_ok=True)
- RESUME_FROM_CHECKPOINT = getattr(cfg, "resume", True)
-
- model = InstantHMRStudent(cfg, pretrained=True).to(device)
- criterion = DistillationLoss(cfg, mhr_module)
- optimizer = optim.AdamW(model.parameters(), lr=cfg.lr, weight_decay=cfg.weight_decay)
- scaler = torch.amp.GradScaler(device='cuda', enabled=cfg.use_amp)
-
- steps_per_epoch = len(train_loader)
- scheduler = lr_scheduler.OneCycleLR(
- optimizer, max_lr=cfg.lr, epochs=cfg.epochs,
- steps_per_epoch=steps_per_epoch, pct_start=0.1,
- )
-
- best_raw_path = os.path.join(cfg.log_dir, "best_student_model_raw.pth")
- best_ema_path = os.path.join(cfg.log_dir, "best_student_model_ema.pth")
- best_ckpt_path = os.path.join(cfg.log_dir, "best_student_model_v3.pth")
-
- start_epoch = 0
- best_raw_pa = float('inf')
- best_ema_pa = float('inf')
- best_overall_pa = float('inf')
- epochs_no_improve = 0
-
- if RESUME_FROM_CHECKPOINT and os.path.exists(best_ckpt_path):
- print(f"🔄 Resuming from checkpoint: {best_ckpt_path}")
- ckpt = torch.load(best_ckpt_path, map_location=device, weights_only=False)
- model.load_state_dict(ckpt["model_state_dict"], strict=False)
- if "optimizer_state_dict" in ckpt:
- optimizer.load_state_dict(ckpt["optimizer_state_dict"])
- if "scaler_state_dict" in ckpt:
- scaler.load_state_dict(ckpt["scaler_state_dict"])
- if "scheduler_state_dict" in ckpt:
- scheduler.load_state_dict(ckpt["scheduler_state_dict"])
- start_epoch = ckpt.get("epoch", -1) + 1
- best_overall_pa = ckpt.get("val_pa_mpjpe", float('inf'))
- best_raw_pa = best_overall_pa
- best_ema_pa = best_overall_pa
- print(f"✅ Resumed successfully from Epoch {start_epoch}. Best PA-MPJPE was {best_overall_pa:.1f}mm.")
- else:
- print("🚀 Starting training from scratch with fresh weights.")
-
- ema_model = AveragedModel(model, multi_avg_fn=make_ema_avg_fn(EMA_DECAY), use_buffers=True)
-
- @torch.no_grad()
- def run_validation(eval_model, tag, epoch):
- eval_model.eval()
- vloss = {'total': 0.0, '2d': 0.0, '3d': 0.0, 'mhr': 0.0, 'struct': 0.0, 'bone': 0.0}
- hmr = {'Head_3D_MPJPE': 0.0, 'Head_3D_PA_MPJPE': 0.0, 'Mesh_MPJPE': 0.0, 'Mesh_PA_MPJPE': 0.0}
- n = 0
- vbar = tqdm(val_loader, desc=f"Epoch {epoch+1}/{cfg.epochs} [Val:{tag}]", leave=False)
- for batch in vbar:
- batch = {k: v.to(device) if isinstance(v, torch.Tensor) else v for k, v in batch.items()}
- with torch.amp.autocast(device_type='cuda', dtype=torch.float16, enabled=cfg.use_amp):
- preds_fp16 = eval_model(batch["image"], batch["cliff_cond"])
- preds = {k: v.float() for k, v in preds_fp16.items()}
- losses = criterion(preds, batch)
- if math.isnan(losses['total_loss'].item()) or math.isinf(losses['total_loss'].item()):
- continue
- vloss['total'] += losses['total_loss'].item()
- vloss['2d'] += losses.get('loss_2d_native', torch.tensor(0)).item()
- vloss['3d'] += losses.get('loss_3d_native', torch.tensor(0)).item()
- vloss['mhr'] += losses.get('loss_mhr_joints', torch.tensor(0)).item()
- vloss['struct'] += losses.get('loss_structural', torch.tensor(0)).item()
- vloss['bone'] += losses.get('loss_bone_length', torch.tensor(0)).item()
- bm = evaluate_hmr_batch(preds, batch, cfg, mhr_module)
- for k in hmr:
- hmr[k] += bm.get(k, 0.0)
- n += 1
- vbar.set_postfix({'PA-MPJPE': f"{hmr['Mesh_PA_MPJPE']/max(n,1):.1f}mm"})
- vbar.close()
- vloss = {k: v / max(n, 1) for k, v in vloss.items()}
- hmr = {k: v / max(n, 1) for k, v in hmr.items()}
- return vloss, hmr, n
-
- for epoch in range(start_epoch, cfg.epochs):
- model.train()
- tm = {'total': 0.0, '2d': 0.0, 'simcc': 0.0, '3d': 0.0, 'pose': 0.0, 'scale': 0.0, 'shape': 0.0, 'mhr': 0.0, 'struct': 0.0, 'bone': 0.0}
- nb = 0
- pbar = tqdm(train_loader, desc=f"Epoch {epoch+1}/{cfg.epochs} [Train]")
- for batch in pbar:
- batch = {k: v.to(device) if isinstance(v, torch.Tensor) else v for k, v in batch.items()}
- optimizer.zero_grad(set_to_none=True)
- with torch.amp.autocast(device_type='cuda', dtype=torch.float16, enabled=cfg.use_amp):
- preds_fp16 = model(batch["image"], batch["cliff_cond"])
- preds_fp32 = {k: v.float() for k, v in preds_fp16.items()}
- losses = criterion(preds_fp32, batch)
- loss = losses['total_loss']
- loss_val = loss.item()
- if math.isnan(loss_val) or math.isinf(loss_val):
- print("⚠️ WARNING: NaN/Inf loss detected! Skipping step.")
- continue
- if loss_val > cfg.anomaly_loss_threshold:
- print(f"⚠️ WARNING: anomalous loss {loss_val:.1f} > {cfg.anomaly_loss_threshold} — skipping step.")
- continue
- scaler.scale(loss).backward()
- scaler.unscale_(optimizer)
- torch.nn.utils.clip_grad_norm_(model.parameters(), cfg.grad_clip)
- scale_before = scaler.get_scale()
- scaler.step(optimizer)
- scaler.update()
- scale_after = scaler.get_scale()
- if scale_before <= scale_after:
- scheduler.step()
- ema_model.update_parameters(model)
- tm['total'] += loss.item()
- tm['2d'] += losses.get('loss_2d_native', torch.tensor(0)).item()
- tm['simcc'] += losses.get('loss_2d_simcc', torch.tensor(0)).item()
- tm['3d'] += losses.get('loss_3d_native', torch.tensor(0)).item()
- tm['pose'] += losses.get('loss_pose', torch.tensor(0)).item()
- tm['scale'] += losses.get('loss_scale', torch.tensor(0)).item()
- tm['mhr'] += losses.get('loss_mhr_joints', torch.tensor(0)).item()
- tm['struct'] += losses.get('loss_structural', torch.tensor(0)).item()
- tm['bone'] += losses.get('loss_bone_length', torch.tensor(0)).item()
- nb += 1
- pbar.set_postfix({'Tot': f"{loss.item():.3f}",
- 'MHR': f"{losses.get('loss_mhr_joints', torch.tensor(0)).item():.3f}"})
- pbar.close()
- avg_train = {k: v / max(nb, 1) for k, v in tm.items()}
-
- raw_val, raw_hmr, n_raw = run_validation(model, "raw", epoch)
- ema_val, ema_hmr, n_ema = run_validation(ema_model, "ema", epoch)
-
- print(f"\n📈 Epoch {epoch+1} Summary | LR: {scheduler.get_last_lr()[0]:.2e}")
- print(f" [Train] Tot: {avg_train['total']:.4f} | MHR: {avg_train['mhr']:.4f} | 2D: {avg_train['2d']:.4f} "
- f"| 3D: {avg_train['3d']:.4f} | Bone: {avg_train['bone']:.4f} | simcc: {avg_train['simcc']:.3f}")
- print(f" [Val RAW] Tot: {raw_val['total']:.4f} | Mesh PA-MPJPE: {raw_hmr['Mesh_PA_MPJPE']:.1f} | Mesh MPJPE: {raw_hmr['Mesh_MPJPE']:.1f} | Head PA: {raw_hmr['Head_3D_PA_MPJPE']:.1f} | Head MPJPE: {raw_hmr['Head_3D_MPJPE']:.1f} mm")
- print(f" [Val EMA] Tot: {ema_val['total']:.4f} | Mesh PA-MPJPE: {ema_hmr['Mesh_PA_MPJPE']:.1f} | Mesh MPJPE: {ema_hmr['Mesh_MPJPE']:.1f} | Head PA: {ema_hmr['Head_3D_PA_MPJPE']:.1f} | Head MPJPE: {ema_hmr['Head_3D_MPJPE']:.1f} mm")
- delta = raw_hmr['Mesh_PA_MPJPE'] - ema_hmr['Mesh_PA_MPJPE']
- print(f" 🔬 EMA vs RAW (Mesh PA-MPJPE): {'EMA better' if delta > 0 else 'RAW better'} by {abs(delta):.1f} mm")
-
- def get_save_dict(model_to_save, val_metric, source_name):
- return {
- 'epoch': epoch,
- 'model_state_dict': model_to_save.state_dict(),
- 'optimizer_state_dict': optimizer.state_dict(),
- 'scaler_state_dict': scaler.state_dict(),
- 'scheduler_state_dict': scheduler.state_dict(),
- 'val_pa_mpjpe': val_metric,
- 'source': source_name
- }
-
- improved_raw = n_raw > 0 and raw_hmr['Mesh_PA_MPJPE'] < best_raw_pa
- improved_ema = n_ema > 0 and ema_hmr['Mesh_PA_MPJPE'] < best_ema_pa
-
- if improved_raw:
- best_raw_pa = raw_hmr['Mesh_PA_MPJPE']
- torch.save(get_save_dict(model, best_raw_pa, 'raw'), best_raw_path)
- if improved_ema:
- best_ema_pa = ema_hmr['Mesh_PA_MPJPE']
- torch.save(get_save_dict(ema_model.module, best_ema_pa, 'ema'), best_ema_path)
-
- current = min(raw_hmr['Mesh_PA_MPJPE'], ema_hmr['Mesh_PA_MPJPE'])
- if current < best_overall_pa - 1e-4:
- best_overall_pa = current
- use_ema = ema_hmr['Mesh_PA_MPJPE'] <= raw_hmr['Mesh_PA_MPJPE']
- better = ema_model.module if use_ema else model
- torch.save(get_save_dict(better, best_overall_pa, 'ema' if use_ema else 'raw'), best_ckpt_path)
- print(f"💾 New best overall: {best_overall_pa:.1f} mm ({'EMA' if use_ema else 'RAW'}) -> {os.path.basename(best_ckpt_path)}")
-
- if improved_raw or improved_ema:
- epochs_no_improve = 0
- else:
- epochs_no_improve += 1
- print(f" ⏳ Neither RAW nor EMA improved: {epochs_no_improve}/{EARLY_STOP_PATIENCE} (best raw {best_raw_pa:.1f} / ema {best_ema_pa:.1f} mm)")
- if epochs_no_improve >= EARLY_STOP_PATIENCE:
- print(f"\n🛑 Early stopping at epoch {epoch+1}: neither RAW nor EMA improved for {EARLY_STOP_PATIENCE} epochs.")
- break
-
- print(f"\n🎉 Training complete! Best overall Mesh PA-MPJPE: {best_overall_pa:.1f} mm")
- print(f" best RAW: {best_raw_pa:.1f} mm -> {best_raw_path}")
- print(f" best EMA: {best_ema_pa:.1f} mm -> {best_ema_path}")
-
-# ============================================================
-# Cell 15 — Export & Static Quantization
-# ============================================================
-class HMRDeployWrapper(nn.Module):
- def __init__(self, model):
- super().__init__()
- self.model = model
-
- def forward(self, image, cliff_cond):
- out = self.model(image, cliff_cond)
- return (out["mhr_params"], out["shape_params"], out["cam_trans"],
- out["joints_2d"], out["joints_3d"])
-
-def topological_sort_onnx(model):
- available = set()
- for inp in model.graph.input:
- available.add(inp.name)
- for init in model.graph.initializer:
- available.add(init.name)
-
- remaining = list(model.graph.node)
- sorted_nodes = []
-
- while remaining:
- progress = False
- for node in remaining:
- if all(inp in available or inp == '' for inp in node.input):
- sorted_nodes.append(node)
- remaining.remove(node)
- for out in node.output:
- available.add(out)
- progress = True
- break
- if not progress:
- sorted_nodes.extend(remaining)
- break
-
- del model.graph.node[:]
- model.graph.node.extend(sorted_nodes)
- return model
-
-def export_and_quantize():
- print("--- Exporting and Quantizing Full Model for Deployment ---")
- try:
- from onnxruntime.quantization import (
- CalibrationDataReader, quantize_static,
- QuantType, QuantFormat, CalibrationMethod,
- )
-
- class HMRCalibrationDataReader(CalibrationDataReader):
- def __init__(self, dataloader, max_samples=100):
- self.data_list = []
- print(f"Extracting {max_samples} individual images for INT8 calibration...")
- for batch in dataloader:
- images = batch["image"].numpy().astype(np.float32)
- cliffs = batch["cliff_cond"].numpy().astype(np.float32)
- for b_idx in range(images.shape[0]):
- if len(self.data_list) >= max_samples:
- break
- self.data_list.append({
- "image": images[b_idx:b_idx + 1],
- "cliff_cond": cliffs[b_idx:b_idx + 1]
- })
- if len(self.data_list) >= max_samples:
- break
- self.enum_data = iter(self.data_list)
-
- def get_next(self):
- return next(self.enum_data, None)
-
- except ImportError:
- print("⚠️ 'onnxruntime' is not installed. INT8 quantization will fail.")
- HMRCalibrationDataReader = None
-
- export_dir = Path(cfg.log_dir) / "export"
- export_dir.mkdir(parents=True, exist_ok=True)
-
- onnx_fp32_path = export_dir / "sam3d_full_fp32.onnx"
- onnx_fp16_path = export_dir / "sam3d_full_fp16.onnx"
- onnx_int8_path = export_dir / "sam3d_full_int8.onnx"
-
- output_keys = ["mhr_params", "shape_params", "cam_trans", "joints_2d", "joints_3d"]
- export_target_model = InstantHMRStudent(cfg, pretrained=False).to(device)
- best_ckpt_path = os.path.join(cfg.log_dir, "best_student_model_v3.pth")
-
- if os.path.exists(best_ckpt_path):
- ckpt = torch.load(best_ckpt_path, map_location=device, weights_only=True)
- clean_state_dict = {k.replace('_orig_mod.', ''): v for k, v in ckpt['model_state_dict'].items()}
- export_target_model.load_state_dict(clean_state_dict, strict=False)
- print(f"✅ Loaded best model from epoch {ckpt.get('epoch', 0)+1}.\n")
-
- deploy_model = HMRDeployWrapper(export_target_model)
- deploy_model.eval()
-
- dummy_img = torch.randn(1, 3, cfg.image_size, cfg.image_size, device=device)
- dummy_cliff = torch.randn(1, 3, device=device)
-
- dynamic_axes = {"image": {0: "batch"}, "cliff_cond": {0: "batch"}}
- for k in output_keys:
- dynamic_axes[k] = {0: "batch"}
-
- try:
- import onnx
- torch.onnx.export(
- deploy_model, (dummy_img, dummy_cliff), str(onnx_fp32_path),
- input_names=["image", "cliff_cond"], output_names=output_keys,
- dynamic_axes=dynamic_axes, opset_version=17
- )
- print(f"✅ FP32 saved: {onnx_fp32_path.name} | Size: {onnx_fp32_path.stat().st_size / 1e6:.1f} MB")
- except Exception as e:
- print(f"❌ FP32 export failed: {e}")
-
- try:
- from onnxruntime.transformers.float16 import convert_float_to_float16
- import warnings
- with warnings.catch_warnings():
- warnings.simplefilter("ignore")
- model_fp32 = onnx.load(str(onnx_fp32_path))
- model_fp16 = convert_float_to_float16(model_fp32, keep_io_types=True)
- model_fp16 = topological_sort_onnx(model_fp16)
- onnx.save(model_fp16, str(onnx_fp16_path))
- onnx.checker.check_model(onnx.load(str(onnx_fp16_path)), full_check=True)
- print(f"✅ FP16 saved: {onnx_fp16_path.name} | Size: {onnx_fp16_path.stat().st_size / 1e6:.1f} MB")
- except ImportError:
- print("⚠️ FP16 skipped (onnxruntime.transformers not available)")
- except Exception as e:
- print(f"❌ FP16 conversion failed: {e}")
-
- try:
- calib_reader = HMRCalibrationDataReader(train_loader, max_samples=100)
- calib_reader.enum_data = iter(calib_reader.data_list)
- fp32_model = onnx.load(str(onnx_fp32_path))
- nodes_to_exclude = []
- for node in fp32_model.graph.node:
- name = node.name or ''
- if any(kw in name for kw in ['/model/transformer/', '/model/head_',
- '/model/feat_proj', '/model/cond_proj']):
- nodes_to_exclude.append(name)
- del fp32_model
- print(f" Excluding {len(nodes_to_exclude)} transformer/head nodes from quantization")
-
- quantize_static(
- model_input=str(onnx_fp32_path),
- model_output=str(onnx_int8_path),
- calibration_data_reader=calib_reader,
- quant_format=QuantFormat.QDQ,
- op_types_to_quantize=['Conv'],
- per_channel=True,
- reduce_range=False,
- activation_type=QuantType.QInt8,
- weight_type=QuantType.QInt8,
- nodes_to_exclude=nodes_to_exclude,
- calibrate_method=CalibrationMethod.Percentile,
- extra_options={'CalibTensorRangeSymmetric': True},
- )
- print(f"✅ INT8 saved: {onnx_int8_path.name} | Size: {onnx_int8_path.stat().st_size / 1e6:.1f} MB")
- except NameError:
- print("⚠️ INT8 skipped (train_loader not available)")
- except Exception as e:
- import traceback
- print(f"❌ INT8 conversion failed: {e}")
- traceback.print_exc()
-
- sd_path = export_dir / "sam3d_student_state_dict.pth"
- torch.save(export_target_model.state_dict(), sd_path)
- print(f"\n✅ PyTorch state dict saved: {sd_path.name}")
- else:
- print("⚠️ No checkpoint found at:", best_ckpt_path)
-
-# ============================================================
-# Self-tests
-# ============================================================
-def _mock_preds_from(batch):
- return {
- "mhr_params": batch["mhr_model_params"].clone(),
- "shape_params": batch["shape_params"].clone(),
- "cam_trans": batch["cam_trans"].clone(),
- "joints_2d": batch["joints_2d"].clone(),
- "joints_3d": batch["joints_3d"].clone(),
- }
-
-def run_self_tests():
- print("--- Architecture Output Shapes ---")
- test_model = InstantHMRStudent(cfg, pretrained=False)
- out = test_model(torch.randn(2, 3, 224, 224), torch.randn(2, 3))
- for k, v in out.items():
- print(f" {k}: {tuple(v.shape)}")
-
- criterion = DistillationLoss(cfg, mhr_module)
- print("\n--- Perfect Student (identity batch) ---")
- clean_ds = SAM3DStudentDataset(cfg.data_root, augment=False,
- max_images=256, per_dataset_caps=cfg.per_dataset_caps)
- clean_loader = DataLoader(clean_ds, batch_size=32, shuffle=False, num_workers=0)
- cb = {k: v.to(device) for k, v in next(iter(clean_loader)).items()}
- l_clean = criterion(_mock_preds_from(cb), cb)
- for k, v in l_clean.items():
- print(f" {k:<20}: {v.item():.6f}")
-
- print("\n--- MHR consistency under geometric augmentation ---")
- aug_ds = SAM3DStudentDataset(cfg.data_root, augment=True,
- max_images=256, per_dataset_caps=cfg.per_dataset_caps,
- geom_p=1.0, geom_rot_deg=cfg.geom_rot_deg,
- geom_scale_range=cfg.geom_scale_range,
- geom_trans=cfg.geom_trans, geom_flip_p=0.0)
- aug_loader = DataLoader(aug_ds, batch_size=32, shuffle=False, num_workers=0)
- ab = {k: v.to(device) for k, v in next(iter(aug_loader)).items()}
-
- with torch.no_grad():
- tgt_mhr = mhr_module.get_joints(ab["mhr_model_params"], ab["shape_params"])[..., :3]
- cth = ab["aug_cos"].view(-1, 1)
- sth = ab["aug_sin"].view(-1, 1)
- xm, ym = tgt_mhr[..., 0], tgt_mhr[..., 1]
- tgt_mhr_rot = torch.stack([cth * xm - sth * ym, sth * xm + cth * ym, tgt_mhr[..., 2]], dim=-1)
- mhr_vis = tgt_mhr_rot / 100.0
- mhr_vis[..., 1] = -mhr_vis[..., 1]
- mhr_vis[..., 2] = -mhr_vis[..., 2]
- d_aug = (ab["joints_3d"][:, cfg.native_mapping_ids, :]
- - mhr_vis[:, cfg.mhr_mapping_ids, :]).abs().mean().item()
- tgt_mhr_c = mhr_module.get_joints(cb["mhr_model_params"], cb["shape_params"])[..., :3]
- mhr_vis_c = tgt_mhr_c / 100.0
- mhr_vis_c[..., 1] = -mhr_vis_c[..., 1]
- mhr_vis_c[..., 2] = -mhr_vis_c[..., 2]
- d_clean = (cb["joints_3d"][:, cfg.native_mapping_ids, :]
- - mhr_vis_c[:, cfg.mhr_mapping_ids, :]).abs().mean().item()
- print(f" native<->MHR anchor residual: clean {d_clean*1000:.2f} mm | augmented {d_aug*1000:.2f} mm")
- ok_struct = d_aug < d_clean * 1.5 + 1e-3
-
- cc, ss = cth, sth
- def counter(pts):
- x, y = pts[..., 0], pts[..., 1]
- return torch.stack([cc * x - ss * y, ss * x + cc * y, pts[..., 2]], dim=-1)
-
- cam_cr = torch.cat([cc * ab["cam_trans"][:, 0:1] - ss * ab["cam_trans"][:, 1:2],
- ss * ab["cam_trans"][:, 0:1] + cc * ab["cam_trans"][:, 1:2],
- ab["cam_trans"][:, 2:3]], dim=1)
- reproj_aug = criterion._project_3d_to_norm_2d(counter(ab["joints_3d"]), cam_cr, ab)
- r_aug = (reproj_aug - ab["joints_2d"]).abs().mean().item()
- reproj_clean = criterion._project_3d_to_norm_2d(cb["joints_3d"], cb["cam_trans"], cb)
- r_clean = (reproj_clean - cb["joints_2d"]).abs().mean().item()
- print(f" reproj(counter-rot + M) residual: clean {r_clean:.4f} | augmented {r_aug:.4f} (normalised units)")
- ok_reproj = r_aug < r_clean * 1.5 + 5e-3
-
- print("\n--- Perfect Student (augmented batch, masked losses) ---")
- l_aug = criterion(_mock_preds_from(ab), ab)
- for k, v in l_aug.items():
- print(f" {k:<20}: {v.item():.6f}")
- keys = ['loss_2d_native', 'loss_3d_native', 'loss_cam', 'loss_reproj_native', 'loss_bone_length']
- ok_loss = all(l_aug[k].item() < max(5 * l_clean.get(k, torch.tensor(1e-3)).item(), 1e-3) for k in keys if k in l_aug)
-
- print()
- print(f" structural-consistency : {'✅' if ok_struct else '❌'}")
- print(f" reprojection-pathway : {'✅' if ok_reproj else '❌'}")
- print(f" masked perfect-student : {'✅' if ok_loss else '❌'}")
- if ok_struct and ok_reproj and ok_loss:
- print("\n✅ SELF-TEST PASSED: augmentation is consistent with the MHR pipeline.")
- else:
- print("\n❌ SELF-TEST FAILED — do not launch a long run.")
-
-def run_overfit_test(steps=1000, subset=8, lr=5e-4):
- print(f"--- 1-Batch Overfit Test ({subset} images, {steps} steps) ---")
- print("Notice: Geometric augmentations are FORCED OFF to allow loss_pose to stabilize the mesh.")
-
- model = InstantHMRStudent(cfg, pretrained=True).to(device)
- criterion = DistillationLoss(cfg, mhr_module)
- optimizer = optim.AdamW(model.parameters(), lr=lr, weight_decay=0.0)
- scaler = torch.amp.GradScaler(device='cuda', enabled=cfg.use_amp)
-
- # 1. SURGICAL INSERTION: Create a dedicated, non-augmented dataset for the overfit test
- overfit_dataset = SAM3DStudentDataset(
- cfg.data_root,
- augment=True, # Keep color/blur augs to prevent total collapse
- max_images=subset,
- per_dataset_caps=cfg.per_dataset_caps,
- geom_p=0.0, # STRICTLY DISABLE SPATIAL AUGS
- geom_flip_p=0.0 # STRICTLY DISABLE FLIPS
- )
- overfit_loader = DataLoader(overfit_dataset, batch_size=subset, shuffle=False, num_workers=0)
- batch = next(iter(overfit_loader))
- batch = {k: v.to(device) if isinstance(v, torch.Tensor) else v for k, v in batch.items()}
-
- def reg(ls):
- return (ls['loss_2d_native'].item() + ls['loss_3d_native'].item()
- + ls['loss_cam'].item() + ls['loss_pose'].item() + ls.get('loss_bone_length', torch.tensor(0)).item())
-
- first_reg = last_reg = last_pa = None
- best_pa = float('inf') # 8-sample overfit is noisy at constant LR; judge the best fit reached
- n_skipped = 0
- model.train()
-
- for step in range(steps):
- optimizer.zero_grad(set_to_none=True)
- with torch.amp.autocast(device_type='cuda', dtype=torch.float16, enabled=cfg.use_amp):
- preds = model(batch["image"], batch["cliff_cond"])
- preds = {k: v.float() for k, v in preds.items()}
- losses = criterion(preds, batch)
-
- lv = losses['total_loss'].item()
- if math.isnan(lv) or math.isinf(lv) or lv > cfg.anomaly_loss_threshold:
- n_skipped += 1
- continue
-
- scaler.scale(losses['total_loss']).backward()
- scaler.unscale_(optimizer)
- torch.nn.utils.clip_grad_norm_(model.parameters(), cfg.grad_clip)
- scaler.step(optimizer)
- scaler.update()
-
- if first_reg is None:
- first_reg = reg(losses)
- last_reg = reg(losses)
-
- if step % 50 == 0 or step == steps - 1:
- model.eval()
- with torch.no_grad():
- p = {k: v.float() for k, v in model(batch["image"], batch["cliff_cond"]).items()}
- m = evaluate_hmr_batch(p, batch, cfg, mhr_module)
- model.train()
- last_pa = m['Head_3D_PA_MPJPE']
- best_pa = min(best_pa, last_pa)
-
- print(f" step {step:04d} | tot {losses['total_loss'].item():.3f} "
- f"| 3d {losses['loss_3d_native'].item():.4f} "
- f"| pose {losses['loss_pose'].item():.4f} "
- f"| shape {losses.get('loss_shape', torch.tensor(0)).item():.4f} "
- f"| mhr {losses['loss_mhr_joints'].item():.4f} "
- f"| Head [MPJPE: {m['Head_3D_MPJPE']:.1f} | PA: {m['Head_3D_PA_MPJPE']:.1f}] mm "
- f"| Mesh [MPJPE: {m['Mesh_MPJPE']:.1f} | PA: {m['Mesh_PA_MPJPE']:.1f}] mm")
-
- ok = (last_reg < first_reg * 0.10) and (best_pa < 40.0)
- print(f"\n{'✅ SUCCESS' if ok else '❌ FAIL'}: regression loss {first_reg:.4f} -> {last_reg:.5f} "
- f"| best Head PA-MPJPE {best_pa:.1f} mm (final {last_pa:.1f}) | anomalous steps skipped: {n_skipped}")
- return ok
-
-def parse_args():
- p = argparse.ArgumentParser(description="Standalone InstantHMR distillation training.")
- p.add_argument("--data_root", type=str, default=None,
- help="Entry-point folder containing sub-folders with annotations/ + images/.")
- p.add_argument("--output_dir", type=str, default=None,
- help="Where checkpoints/logs/exports are written (cfg.log_dir).")
- p.add_argument("--mhr_model_path", type=str, default=None,
- help="Path to the TorchScript MHR model (mhr_model.pt).")
- p.add_argument("--epochs", type=int, default=None)
- p.add_argument("--batch_size", type=int, default=None)
- p.add_argument("--lr", type=float, default=None)
- p.add_argument("--num_workers", type=int, default=None)
- p.add_argument("--max_images", type=int, default=None)
- p.add_argument("--harmony4d_cap", type=int, default=None,
- help="Max Harmony4D crops kept (randomly sampled). 0 = uncapped/use all.")
- p.add_argument("--no-resume", dest="no_resume", action="store_true",
- help="Ignore any existing checkpoint and train from scratch.")
- p.add_argument("--self-test", dest="self_test", action="store_true",
- help="Run the geometry/MHR-consistency checks and exit.")
- p.add_argument("--overfit-test", dest="overfit_test", action="store_true",
- help="Run the 1-batch overfit sanity check and exit.")
- p.add_argument("--no-export", dest="no_export", action="store_true",
- help="Skip the ONNX export / quantization step after training.")
- p.add_argument("--gpu", type=int, default=None, help="GPU count (informational).")
- args, unknown = p.parse_known_args()
- if unknown:
- print(f"⚠️ Ignoring unrecognized arguments: {unknown}")
- return args
-
-cfg = None
-train_loader = None
-val_loader = None
-full_dataset = None
-mhr_module = None
-
-def main():
- global cfg, train_loader, val_loader, full_dataset, mhr_module
-
- args = parse_args()
- cfg = DistillConfig()
- if args.data_root is not None: cfg.data_root = args.data_root
- if args.output_dir is not None: cfg.log_dir = args.output_dir
- if args.mhr_model_path is not None: cfg.mhr_model_path = args.mhr_model_path
- if args.epochs is not None: cfg.epochs = args.epochs
- if args.batch_size is not None: cfg.batch_size = args.batch_size
- if args.lr is not None: cfg.lr = args.lr
- if args.num_workers is not None: cfg.num_workers = args.num_workers
- if args.max_images is not None: cfg.max_images = args.max_images
- if args.harmony4d_cap is not None:
- if args.harmony4d_cap <= 0:
- cfg.per_dataset_caps.pop("sam3d_gt_harmony4d", None)
- else:
- cfg.per_dataset_caps["sam3d_gt_harmony4d"] = args.harmony4d_cap
- if args.no_resume: cfg.resume = False
-
- print("=" * 60)
- print(f"Project root : {PROJECT_ROOT}")
- print(f"Data root : {cfg.data_root}")
- print(f"Output dir : {cfg.log_dir}")
- print(f"MHR model : {cfg.mhr_model_path}")
- print(f"Backbone : {cfg.backbone} | epochs={cfg.epochs} | batch={cfg.batch_size} | lr={cfg.lr}")
- print(f"max_images : {cfg.max_images if cfg.max_images is not None else 'unlimited (all crops)'}")
- print(f"dataset caps : {cfg.per_dataset_caps if cfg.per_dataset_caps else 'none'}")
- print(f"geom aug : p={cfg.geom_p} rot±{cfg.geom_rot_deg}° scale±{cfg.geom_scale_range} "
- f"trans±{cfg.geom_trans} flip={cfg.geom_flip_p}")
- print(f"2D head : SimCC soft-argmax, {cfg.kp2d_bins} bins over ±{cfg.kp2d_range} (w_simcc={cfg.w_simcc})")
- print(f"Bone Length : Soft Prior weight (w_bone_length={cfg.w_bone_length}) active on {len(cfg.major_bones)} links")
- print("=" * 60)
-
- if not Path(cfg.mhr_model_path).exists():
- raise FileNotFoundError(
- f"MHR model not found at '{cfg.mhr_model_path}'. "
- f"Place mhr_model.pt in the checkpoints/ folder or pass --mhr_model_path."
- )
-
- train_loader, val_loader, full_dataset = build_dataloaders(cfg)
- mhr_module = MHRForwardPass(cfg.mhr_model_path, device)
-
- if args.self_test:
- run_self_tests()
- return
- if args.overfit_test:
- run_overfit_test()
- return
-
- gc.collect()
- if torch.cuda.is_available():
- torch.cuda.empty_cache()
- train_instant_hmr()
-
- if not args.no_export:
- export_and_quantize()
-
-if __name__ == "__main__":
- main()
\ No newline at end of file
diff --git a/instanthmr_distill_train/train_distill_optimized_correctives_fine_tune.py b/instanthmr_distill_train/train_distill_optimized_correctives_fine_tune.py
deleted file mode 100644
index e14be7c..0000000
--- a/instanthmr_distill_train/train_distill_optimized_correctives_fine_tune.py
+++ /dev/null
@@ -1,556 +0,0 @@
-#!/usr/bin/env python3
-"""
-Fine-tune an InstantHMR student to repair the 2D keypoint head.
-
-Why this script exists
-----------------------
-The geometric augmentation in ``train_distill_optimized_correctives.py`` mirrored
-``joints_2d`` with ``M_total`` but never applied ``FLIP_PERM`` to it, while
-``joints_3d`` *was* permuted. On flipped samples the 2D head was therefore told
-that a joint which LOOKS like a right shoulder is the left shoulder. Since
-``loss_2d_native`` is an L1 on the decoded coordinate at w=10 (vs the SimCC CE at
-w=1), the L1-optimal answer to two contradictory targets is their midpoint, so
-left/right symmetric joints collapsed toward the body midline — the "shoulders
-joining at the neck" artefact. Only x is affected (the mirror is about the
-vertical axis) and only the 2D head, because every MHR/pose/shape loss is masked
-by ``m_noflip``/``m_ident`` and ``loss_3d_native`` uses correctly permuted targets.
-
-That label bug is now fixed at its source. This script does NOT redefine the
-model, dataset or losses — it imports them from
-``train_distill_optimized_correctives.py`` so the fix and every future change stay
-in exactly one place. What it adds is a fine-tuning regime built for this repair:
-
- * starts from an existing checkpoint instead of ImageNet weights;
- * discriminative learning rates — a high LR on ``head_2d_*`` to pull it out of
- the collapsed minimum, a low LR everywhere else so the (good) 3D head, MHR
- params and backbone are not disturbed;
- * **2D validation metrics**, because the stock loop selects checkpoints on
- ``Mesh_PA_MPJPE`` — a 3D metric that is blind to exactly the thing being
- repaired. Selection here is on 2D error, guarded by a hard limit on how far
- ``Mesh_PA_MPJPE`` may regress;
- * a ``SymCollapse_%`` metric that measures the actual symptom (symmetric joint
- pairs whose predicted x-width is under 70% of ground truth), so you can watch
- the artefact disappear;
- * crash/preemption-safe resume from ``last_finetune.pth``.
-
-Checkpoints are written in the same format the stock loop uses, so
-``tools/pth_to_onnx.py`` consumes them unchanged.
-
-What was measured (RTX 4070, balanced 36k-crop subset, 40 val batches)
----------------------------------------------------------------------
-A probe feeding each image and its mirror shows which convention each head
-learned. The 3D head is cleanly equivariant under the left/right swap
-(residual 0.018, 11.9x margin) — it already uses the "apparent" convention.
-The 2D head follows the opposite convention and only weakly (1.4x margin,
-6x larger residual): it is stuck between the two, which is the collapse.
-
-Fine-tuning the existing 2D head in place therefore has to REVERSE its
-handedness on the ~40% of samples that get flipped, and it thrashes:
-
- in-place, lr 5e-5, 4 epochs 2D 2.05 -> 8.75 px SymCollapse 2% -> 67%
-
-Resetting the head first, so it learns the corrected convention from scratch
-instead of unlearning the old one, converges monotonically:
-
- --train_2d_only --reset_2d_head, 8 epochs 2D 8.01 -> 4.98 px Sym 44% -> 14%
- --reset_2d_head (decoder adapts), 3 epochs 2D 2.32 -> 2.18 px Sym 2.6% -> 2.2%
-
-Letting the transformer decoder adapt is ~10x more sample-efficient — its 2D
-query tokens carry the old convention as well, so freezing them caps how far
-the head can recover. Hence the default recipe: --reset_2d_head, a high LR on
-head_2d_*, a low LR on the trunk, and the PA guard to catch 3D drift.
---train_2d_only remains the zero-risk fallback: with it, Mesh PA-MPJPE held at
-exactly 23.9 mm for all 8 epochs.
-
-Note these numbers come from a 36k-crop subset, which is ~1/24th of the corpus
-and cannot reach the accuracy of the 359-epoch full-corpus baseline. They show
-direction and stability, not the final quality of a full run.
-
-Usage
------
- python3 -u train_distill_optimized_correctives_fine_tune.py \
- --data_root /datasets/instanthmr_data --batch_size 128 --num_workers 8 \
- --reset_2d_head
-"""
-import argparse
-import gc
-import math
-import os
-from pathlib import Path
-
-import numpy as np
-import torch
-import torch.optim as optim
-import torch.optim.lr_scheduler as lr_scheduler
-from torch.optim.swa_utils import AveragedModel
-from tqdm import tqdm
-
-# Model / dataset / losses / metrics all come from the main training script so
-# there is exactly one definition of each.
-import train_distill_optimized_correctives as T
-
-PROJECT_ROOT = Path(__file__).resolve().parent
-device = T.device
-
-# Left/right joint pairs, derived from the same permutation the augmentation uses.
-SYM_PAIRS = [(i, int(T.FLIP_PERM[i])) for i in range(len(T.JOINT_NAMES))
- if i < int(T.FLIP_PERM[i])]
-SYM_A = [a for a, _ in SYM_PAIRS]
-SYM_B = [b for _, b in SYM_PAIRS]
-
-
-# ============================================================
-# 2D metrics — what the stock loop is missing
-# ============================================================
-def evaluate_2d_batch(preds, targets, cfg):
- """2D accuracy + a direct measurement of the symmetric-collapse artefact.
-
- ``joints_2d`` lives in normalised [-1, 1] crop space, so one unit is
- ``image_size / 2`` pixels of the 224x224 crop.
- """
- p2 = preds["joints_2d"][..., :2].float()
- t2 = targets["joints_2d"][..., :2].float()
-
- px_per_unit = cfg.image_size / 2.0
- err_px = torch.linalg.norm(p2 - t2, dim=-1) * px_per_unit # [B, J]
-
- m = {
- "KP2D_L2_px": err_px.mean().item(),
- "[email protected]": (err_px < 0.05 * cfg.image_size).float().mean().item() * 100.0,
- }
-
- # Symmetric-pair x-width: the quantity that collapses when left/right
- # supervision is contradictory. Pairs that genuinely overlap in x (limbs
- # crossed, person in profile) carry no signal, so they are excluded.
- wp = (p2[:, SYM_A, 0] - p2[:, SYM_B, 0]).abs()
- wt = (t2[:, SYM_A, 0] - t2[:, SYM_B, 0]).abs()
- valid = wt > 0.05
- n_valid = valid.sum().clamp_min(1)
- ratio = wp / wt.clamp_min(1e-6)
- m["SymWidth_ratio"] = (ratio * valid).sum().item() / n_valid.item()
- m["SymCollapse_%"] = (((ratio < 0.7) & valid).sum().item() / n_valid.item()) * 100.0
- return m
-
-
-# ============================================================
-# Parameter groups
-# ============================================================
-def build_param_groups(model, base_lr, head_2d_lr_mult, freeze_backbone, train_2d_only):
- """High LR on the 2D head, low LR on everything else.
-
- The 3D head, the MHR/shape/camera head and the backbone are already good —
- they only need enough LR to stay consistent with the repaired 2D head.
-
- ``train_2d_only`` freezes every parameter the flip bug could not have
- touched, leaving just ``head_2d_*``. Because the backbone, decoder, 3D head
- and MHR head are then bit-identical to the input checkpoint, Mesh/Head
- PA-MPJPE cannot move at all — the repair is structurally incapable of
- regressing the 3D pose. It is the safest mode and the fastest per step.
- """
- head_2d, trunk, frozen = [], [], []
- for name, p in model.named_parameters():
- if not p.requires_grad:
- continue
- is_2d = name.startswith("head_2d_")
- if is_2d:
- head_2d.append(p)
- elif train_2d_only or (freeze_backbone and name.startswith("backbone.")):
- p.requires_grad_(False)
- frozen.append(name)
- else:
- trunk.append(p)
-
- groups = [{"params": head_2d, "lr": base_lr * head_2d_lr_mult, "name": "head_2d"}]
- if trunk:
- groups.append({"params": trunk, "lr": base_lr, "name": "trunk"})
- n_head = sum(p.numel() for p in head_2d)
- n_trunk = sum(p.numel() for p in trunk)
- msg = f" param groups: head_2d {n_head/1e6:.2f}M @ lr {base_lr*head_2d_lr_mult:.2e}"
- if trunk:
- msg += f" | trunk {n_trunk/1e6:.2f}M @ lr {base_lr:.2e}"
- if frozen:
- msg += f" | FROZEN {len(frozen)} tensors"
- if train_2d_only:
- msg += " (train_2d_only: 3D pose cannot change)"
- print(msg)
- return groups
-
-
-def load_init_checkpoint(model, path):
- ckpt = torch.load(path, map_location=device, weights_only=False)
- state = ckpt.get("model_state_dict", ckpt)
- state = {k.replace("_orig_mod.", ""): v for k, v in state.items()}
- missing, unexpected = model.load_state_dict(state, strict=False)
- if missing:
- raise SystemExit(
- f"[error] {len(missing)} parameter(s) missing from {path}:\n"
- f" {missing[:8]}\n"
- f" The checkpoint does not match this architecture — refusing to "
- f"fine-tune from randomly initialised weights."
- )
- if unexpected:
- print(f" ⚠️ ignoring {len(unexpected)} unexpected key(s): {unexpected[:6]}")
- print(f" init from {path}")
- print(f" (epoch {ckpt.get('epoch', '?')} | PA-MPJPE {ckpt.get('val_pa_mpjpe', '?')} "
- f"| source {ckpt.get('source', '?')})")
- return ckpt
-
-
-# ============================================================
-# Fine-tuning loop
-# ============================================================
-def finetune(cfg, args, train_loader, val_loader, mhr_module):
- os.makedirs(cfg.log_dir, exist_ok=True)
-
- best_raw_path = os.path.join(cfg.log_dir, "best_finetune_raw.pth")
- best_ema_path = os.path.join(cfg.log_dir, "best_finetune_ema.pth")
- best_path = os.path.join(cfg.log_dir, "best_finetune.pth")
- last_path = os.path.join(cfg.log_dir, "last_finetune.pth")
-
- model = T.InstantHMRStudent(cfg, pretrained=False).to(device)
- load_init_checkpoint(model, args.init_ckpt)
- criterion = T.DistillationLoss(cfg, mhr_module)
- scaler = torch.amp.GradScaler(device="cuda", enabled=cfg.use_amp)
-
- @torch.no_grad()
- def run_validation(eval_model, tag, epoch):
- eval_model.eval()
- acc, n = {}, 0
- limit = args.val_max_batches if args.val_max_batches > 0 else len(val_loader)
- vbar = tqdm(val_loader, total=min(limit, len(val_loader)),
- desc=f"Epoch {epoch+1}/{cfg.epochs} [Val:{tag}]", leave=False)
- for i, batch in enumerate(vbar):
- if i >= limit:
- break
- batch = {k: v.to(device) if isinstance(v, torch.Tensor) else v
- for k, v in batch.items()}
- with torch.amp.autocast(device_type="cuda", dtype=torch.float16, enabled=cfg.use_amp):
- preds_fp16 = eval_model(batch["image"], batch["cliff_cond"])
- preds = {k: v.float() for k, v in preds_fp16.items()}
- losses = criterion(preds, batch)
- tot = losses["total_loss"].item()
- if math.isnan(tot) or math.isinf(tot):
- continue
- m = T.evaluate_hmr_batch(preds, batch, cfg, mhr_module)
- m.update(evaluate_2d_batch(preds, batch, cfg))
- m["loss"] = tot
- for k, v in m.items():
- acc[k] = acc.get(k, 0.0) + v
- n += 1
- vbar.set_postfix({"2D px": f"{acc.get('KP2D_L2_px',0)/max(n,1):.2f}",
- "PA": f"{acc.get('Mesh_PA_MPJPE',0)/max(n,1):.1f}"})
- vbar.close()
- return {k: v / max(n, 1) for k, v in acc.items()}, n
-
- def fmt(tag, m):
- return (f" [{tag}] 2D: {m.get('KP2D_L2_px', 0):.2f} px | [email protected]: {m.get('[email protected]', 0):.1f}% "
- f"| SymCollapse: {m.get('SymCollapse_%', 0):.2f}% | SymW: {m.get('SymWidth_ratio', 0):.3f} "
- f"| Mesh PA: {m.get('Mesh_PA_MPJPE', 0):.1f} | Head PA: {m.get('Head_3D_PA_MPJPE', 0):.1f} mm")
-
- # ---- Baseline: measure the starting point before touching the weights ----
- start_epoch = 0
- best_2d = float("inf")
- best_raw_2d = float("inf")
- best_ema_2d = float("inf")
- epochs_no_improve = 0
-
- resuming = args.resume and os.path.exists(last_path)
-
- if not resuming:
- print("\n📏 Baseline (before fine-tuning):")
- baseline, nb = run_validation(model, "baseline", -1)
- print(fmt("BASE", baseline))
- if nb == 0:
- raise SystemExit("[error] baseline validation produced no batches.")
- if args.reset_2d_head:
- # Done AFTER the baseline so the printed starting point is the real
- # model, and BEFORE the EMA is built so the shadow starts from the
- # reset head rather than the collapsed one.
- print(" 🔄 re-initialising head_2d_logits — the 2D head relearns "
- "left/right from scratch instead of unlearning the old convention")
- torch.nn.init.normal_(model.head_2d_logits.weight, mean=0.0, std=1e-4)
- torch.nn.init.constant_(model.head_2d_logits.bias, 0.0)
-
- groups = build_param_groups(model, cfg.lr, args.head_2d_lr_mult,
- args.freeze_backbone, args.train_2d_only)
- optimizer = optim.AdamW(groups, lr=cfg.lr, weight_decay=cfg.weight_decay)
- scheduler = lr_scheduler.OneCycleLR(
- optimizer, max_lr=[g["lr"] for g in groups],
- epochs=cfg.epochs, steps_per_epoch=len(train_loader),
- pct_start=args.pct_start,
- )
- ema_model = AveragedModel(model, multi_avg_fn=T.make_ema_avg_fn(args.ema_decay),
- use_buffers=True)
-
- if resuming:
- ck = torch.load(last_path, map_location=device, weights_only=False)
- model.load_state_dict(ck["model_state_dict"])
- ema_model.module.load_state_dict(ck["ema_state_dict"])
- optimizer.load_state_dict(ck["optimizer_state_dict"])
- scheduler.load_state_dict(ck["scheduler_state_dict"])
- scaler.load_state_dict(ck["scaler_state_dict"])
- start_epoch = ck["epoch"] + 1
- best_2d = ck.get("best_2d", float("inf"))
- best_raw_2d = ck.get("best_raw_2d", float("inf"))
- best_ema_2d = ck.get("best_ema_2d", float("inf"))
- epochs_no_improve = ck.get("epochs_no_improve", 0)
- baseline = ck["baseline"]
- print(f"🔄 Resumed fine-tune from epoch {start_epoch} (best 2D {best_2d:.3f} px)")
-
- pa_ceiling = baseline["Mesh_PA_MPJPE"] + args.pa_tolerance
- print(f"\n selection metric : KP2D_L2_px (lower is better)")
- print(f" guard : Mesh PA-MPJPE must stay <= {pa_ceiling:.1f} mm "
- f"(baseline {baseline['Mesh_PA_MPJPE']:.1f} + tol {args.pa_tolerance})\n")
-
- def set_train_mode(m):
- """Frozen params are not enough: BatchNorm running stats and dropout still
- move in train() mode, which would drift the 3D pose. Under
- --train_2d_only keep every other module in eval()."""
- if args.train_2d_only:
- m.eval()
- m.head_2d_feat.train()
- m.head_2d_logits.train()
- else:
- m.train()
-
- for epoch in range(start_epoch, cfg.epochs):
- set_train_mode(model)
- tm, nb = {}, 0
- pbar = tqdm(train_loader, desc=f"Epoch {epoch+1}/{cfg.epochs} [Train]")
- for batch in pbar:
- batch = {k: v.to(device) if isinstance(v, torch.Tensor) else v
- for k, v in batch.items()}
- optimizer.zero_grad(set_to_none=True)
- with torch.amp.autocast(device_type="cuda", dtype=torch.float16, enabled=cfg.use_amp):
- preds_fp16 = model(batch["image"], batch["cliff_cond"])
- preds = {k: v.float() for k, v in preds_fp16.items()}
- losses = criterion(preds, batch)
- loss = losses["total_loss"]
- lv = loss.item()
- if math.isnan(lv) or math.isinf(lv):
- print("⚠️ NaN/Inf loss — skipping step.")
- continue
- if lv > cfg.anomaly_loss_threshold:
- print(f"⚠️ anomalous loss {lv:.1f} — skipping step.")
- continue
- scaler.scale(loss).backward()
- scaler.unscale_(optimizer)
- torch.nn.utils.clip_grad_norm_(model.parameters(), cfg.grad_clip)
- s_before = scaler.get_scale()
- scaler.step(optimizer)
- scaler.update()
- if s_before <= scaler.get_scale():
- scheduler.step()
- ema_model.update_parameters(model)
- for k in ("total_loss", "loss_2d_native", "loss_2d_simcc", "loss_3d_native"):
- tm[k] = tm.get(k, 0.0) + losses.get(k, torch.tensor(0.0)).item()
- nb += 1
- pbar.set_postfix({"Tot": f"{lv:.3f}", "2D": f"{losses.get('loss_2d_native', torch.tensor(0.0)).item():.3f}"})
- pbar.close()
- tr = {k: v / max(nb, 1) for k, v in tm.items()}
-
- raw, n_raw = run_validation(model, "raw", epoch)
- ema, n_ema = run_validation(ema_model, "ema", epoch)
-
- lrs = scheduler.get_last_lr()
- print(f"\n📈 Epoch {epoch+1}/{cfg.epochs} | LR head_2d {lrs[0]:.2e} / trunk {lrs[-1]:.2e}")
- print(f" [Train] Tot: {tr['total_loss']:.4f} | 2D: {tr['loss_2d_native']:.4f} "
- f"| simcc: {tr['loss_2d_simcc']:.4f} | 3D: {tr['loss_3d_native']:.4f}")
- print(fmt("Val RAW", raw))
- print(fmt("Val EMA", ema))
- print(f" Δ vs baseline: 2D {raw['KP2D_L2_px']-baseline['KP2D_L2_px']:+.2f} px (raw) / "
- f"{ema['KP2D_L2_px']-baseline['KP2D_L2_px']:+.2f} px (ema) | "
- f"SymCollapse {baseline['SymCollapse_%']:.2f}% → "
- f"{min(raw['SymCollapse_%'], ema['SymCollapse_%']):.2f}%")
-
- def save_dict(m_to_save, metrics, source):
- return {
- "epoch": epoch,
- "model_state_dict": m_to_save.state_dict(),
- "optimizer_state_dict": optimizer.state_dict(),
- "scaler_state_dict": scaler.state_dict(),
- "scheduler_state_dict": scheduler.state_dict(),
- "val_pa_mpjpe": metrics["Mesh_PA_MPJPE"],
- "val_kp2d_px": metrics["KP2D_L2_px"],
- "val_metrics": metrics,
- "source": source,
- "finetune_of": str(args.init_ckpt),
- }
-
- # A checkpoint only counts if the 3D head has not regressed past the guard.
- raw_ok = n_raw > 0 and raw["Mesh_PA_MPJPE"] <= pa_ceiling
- ema_ok = n_ema > 0 and ema["Mesh_PA_MPJPE"] <= pa_ceiling
- if not raw_ok and not ema_ok:
- print(f" ⚠️ PA guard blocked both: raw {raw['Mesh_PA_MPJPE']:.1f} / "
- f"ema {ema['Mesh_PA_MPJPE']:.1f} mm > {pa_ceiling:.1f} mm")
-
- improved_raw = raw_ok and raw["KP2D_L2_px"] < best_raw_2d
- improved_ema = ema_ok and ema["KP2D_L2_px"] < best_ema_2d
- if improved_raw:
- best_raw_2d = raw["KP2D_L2_px"]
- torch.save(save_dict(model, raw, "raw"), best_raw_path)
- if improved_ema:
- best_ema_2d = ema["KP2D_L2_px"]
- torch.save(save_dict(ema_model.module, ema, "ema"), best_ema_path)
-
- cands = [(raw["KP2D_L2_px"], model, raw, "raw")] if raw_ok else []
- if ema_ok:
- cands.append((ema["KP2D_L2_px"], ema_model.module, ema, "ema"))
- if cands:
- val, mdl, met, src = min(cands, key=lambda c: c[0])
- if val < best_2d - 1e-4:
- best_2d = val
- torch.save(save_dict(mdl, met, src), best_path)
- print(f"💾 New best 2D: {best_2d:.3f} px ({src.upper()}, "
- f"Mesh PA {met['Mesh_PA_MPJPE']:.1f} mm) -> {os.path.basename(best_path)}")
-
- torch.save({**save_dict(model, raw, "last"),
- "ema_state_dict": ema_model.module.state_dict(),
- "baseline": baseline, "best_2d": best_2d,
- "best_raw_2d": best_raw_2d, "best_ema_2d": best_ema_2d,
- "epochs_no_improve": epochs_no_improve}, last_path)
-
- if improved_raw or improved_ema:
- epochs_no_improve = 0
- else:
- epochs_no_improve += 1
- print(f" ⏳ no 2D improvement: {epochs_no_improve}/{args.early_stop_patience}")
- if epochs_no_improve >= args.early_stop_patience:
- print(f"\n🛑 Early stopping at epoch {epoch+1}.")
- break
-
- print(f"\n🎉 Fine-tuning complete.")
- print(f" baseline 2D : {baseline['KP2D_L2_px']:.3f} px | "
- f"SymCollapse {baseline['SymCollapse_%']:.2f}% | Mesh PA {baseline['Mesh_PA_MPJPE']:.1f} mm")
- print(f" best 2D : {best_2d:.3f} px -> {best_path}")
- print(f"\n Export with:\n"
- f" python tools/pth_to_onnx.py --ckpt {best_path} --output models/instanthmr.onnx")
-
-
-# ============================================================
-# CLI
-# ============================================================
-def parse_args():
- p = argparse.ArgumentParser(
- description="Fine-tune InstantHMR to repair the 2D head after the flip-label fix.")
- p.add_argument("--data_root", type=str, default=None)
- p.add_argument("--output_dir", type=str,
- default=str(PROJECT_ROOT / "runs/distill_optimized_v2_ft"))
- p.add_argument("--init_ckpt", type=str,
- default=str(PROJECT_ROOT / "runs/distill_optimized_v2/best_student_model_ema.pth"),
- help="Checkpoint to fine-tune FROM (not the output).")
- p.add_argument("--mhr_model_path", type=str, default=None)
-
- p.add_argument("--epochs", type=int, default=15)
- p.add_argument("--batch_size", type=int, default=None)
- p.add_argument("--num_workers", type=int, default=None)
- p.add_argument("--lr", type=float, default=1e-5,
- help="Trunk LR. The 2D head gets lr * --head_2d_lr_mult.")
- p.add_argument("--head_2d_lr_mult", type=float, default=30.0,
- help="LR multiplier for head_2d_* (default 30 -> 3e-4 at the default lr).")
- p.add_argument("--pct_start", type=float, default=0.05, help="OneCycle warmup fraction.")
- p.add_argument("--ema_decay", type=float, default=0.9995)
- p.add_argument("--early_stop_patience", type=int, default=4)
-
- p.add_argument("--train_2d_only", action="store_true",
- help="Train ONLY head_2d_* and freeze everything else. The 3D pose then "
- "cannot change at all — safest way to repair the 2D head.")
- p.add_argument("--freeze_backbone", action="store_true",
- help="Freeze the RepViT backbone (faster, more conservative).")
- p.add_argument("--reset_2d_head", action="store_true",
- help="Re-initialise head_2d_logits instead of fine-tuning it.")
- p.add_argument("--pa_tolerance", type=float, default=2.0,
- help="Max Mesh PA-MPJPE regression (mm) allowed vs baseline before a "
- "checkpoint is rejected.")
- p.add_argument("--val_max_batches", type=int, default=150,
- help="Cap validation batches per pass for speed (0 = full val set).")
-
- p.add_argument("--per_dataset_cap", type=int, default=None,
- help="Cap EVERY sub-dataset to N randomly-sampled crops, for a BALANCED "
- "subset. Prefer this over --max_images for quick runs.")
- p.add_argument("--max_images", type=int, default=None,
- help="Truncate to the first N crops. NOTE: this is a path-sorted PREFIX, so "
- "it draws from one sub-dataset only — it biases any short run. Use "
- "--per_dataset_cap instead unless you specifically want a prefix.")
- p.add_argument("--harmony4d_cap", type=int, default=None)
- p.add_argument("--no-resume", dest="resume", action="store_false",
- help="Ignore last_finetune.pth and restart the fine-tune.")
- p.add_argument("--gpu", type=int, default=None, help="GPU count (informational).")
- args, unknown = p.parse_known_args()
- if unknown:
- print(f"⚠️ Ignoring unrecognized arguments: {unknown}")
- return args
-
-
-def main():
- args = parse_args()
- cfg = T.DistillConfig()
-
- if args.data_root is not None: cfg.data_root = args.data_root
- if args.mhr_model_path is not None: cfg.mhr_model_path = args.mhr_model_path
- if args.batch_size is not None: cfg.batch_size = args.batch_size
- if args.num_workers is not None: cfg.num_workers = args.num_workers
- if args.max_images is not None:
- cfg.max_images = args.max_images
- print("⚠️ --max_images takes a PATH-SORTED PREFIX (one sub-dataset), which biases "
- "training. Use --per_dataset_cap for a balanced subset.")
- if args.per_dataset_cap is not None:
- subs = sorted(d.name for d in Path(cfg.data_root).iterdir()
- if (d / "annotations").is_dir() and (d / "images").is_dir())
- cfg.per_dataset_caps = {s_: args.per_dataset_cap for s_ in subs}
- print(f" balanced subset: {args.per_dataset_cap:,} crops max from each of "
- f"{len(subs)} sub-dataset(s)")
- if args.harmony4d_cap is not None:
- if args.harmony4d_cap <= 0:
- cfg.per_dataset_caps.pop("sam3d_gt_harmony4d", None)
- else:
- cfg.per_dataset_caps["sam3d_gt_harmony4d"] = args.harmony4d_cap
- cfg.log_dir = args.output_dir
- cfg.epochs = args.epochs
- cfg.lr = args.lr
- cfg.resume = False # this script manages its own resume via last_finetune.pth
-
- print("=" * 70)
- print("InstantHMR 2D-head repair fine-tune")
- print("=" * 70)
- print(f"Data root : {cfg.data_root}")
- print(f"Init ckpt : {args.init_ckpt}")
- print(f"Output dir : {cfg.log_dir}")
- print(f"MHR model : {cfg.mhr_model_path}")
- print(f"epochs={cfg.epochs} | batch={cfg.batch_size} | trunk_lr={cfg.lr} "
- f"| head_2d_lr={cfg.lr * args.head_2d_lr_mult:.2e}")
- print(f"geom aug : p={cfg.geom_p} rot±{cfg.geom_rot_deg}° scale±{cfg.geom_scale_range} "
- f"trans±{cfg.geom_trans} flip={cfg.geom_flip_p}")
- print(f"flip fix : joints_2d[FLIP_PERM] applied "
- f"({len(SYM_PAIRS)} left/right pairs, "
- f"{int((T.FLIP_PERM != np.arange(len(T.FLIP_PERM))).sum())}/{len(T.FLIP_PERM)} joints swapped)")
- print(f"train_2d_only={args.train_2d_only} | freeze_bb={args.freeze_backbone} "
- f"| reset_2d_head={args.reset_2d_head} | pa_tolerance={args.pa_tolerance} mm")
- print("=" * 70)
-
- if not args.reset_2d_head:
- print("⚠️ --reset_2d_head is NOT set. The existing 2D head encodes the OLD "
- "left/right convention,\n so fine-tuning it in place must UNLEARN that on "
- "~40% of samples; measured runs thrash\n (2D error and symmetric collapse both "
- "got worse) instead of converging. Strongly recommended.\n")
-
- if not Path(args.init_ckpt).exists():
- raise SystemExit(f"[error] init checkpoint not found: {args.init_ckpt}")
- if not Path(cfg.mhr_model_path).exists():
- raise SystemExit(
- f"[error] MHR model not found at '{cfg.mhr_model_path}'. "
- f"Pass --mhr_model_path.")
-
- train_loader, val_loader, _ = T.build_dataloaders(cfg)
- mhr_module = T.MHRForwardPass(cfg.mhr_model_path, device)
-
- gc.collect()
- if torch.cuda.is_available():
- torch.cuda.empty_cache()
-
- finetune(cfg, args, train_loader, val_loader, mhr_module)
-
-
-if __name__ == "__main__":
- main()
diff --git a/instanthmr_distill_train/train_distill_pose3d.py b/instanthmr_distill_train/train_distill_pose3d.py
deleted file mode 100644
index 6ff06a3..0000000
--- a/instanthmr_distill_train/train_distill_pose3d.py
+++ /dev/null
@@ -1,708 +0,0 @@
-#!/usr/bin/env python3
-# ============================================================
-# Keypoint + camera student — NO MHR mesh model / params.
-# ------------------------------------------------------------
-# A stripped-down sibling of train_distill.py. It predicts and
-# supervises the 70 native 2D + 3D keypoints AND the camera
-# translation (cam_trans) — which is NOT an MHR parameter and is
-# required by the demo (joints_3d_cam = joints_3d + cam_trans).
-#
-# Removed vs train_distill.py: the MHR body rig (mhr_model.pt),
-# the mhr_params / shape_params heads, and every MHR-derived loss
-# (mhr_joints / structural / feet / reproj_mhr / mesh metrics) —
-# i.e. exactly the terms that were causing the periodic loss spikes.
-#
-# Model out: cam_trans [B,3], joints_2d [B,70,2] ([-1,1] crop),
-# joints_3d [B,70,3] (root-centred metres).
-# Loss: SmoothL1(2D) + SmoothL1(3D) + MSE(cam) + L1(reproj).
-# Metrics: MPJPE / PA-MPJPE on the 3D head.
-# Export: 5 ONNX outputs in demo order (mhr_params & shape_params
-# zero-filled) so it works with the existing demo.py.
-#
-# Sanity: python3 train_distill_pose3d.py --overfit-test --data_root ../data
-# Full: python3 train_distill_pose3d.py --data_root /datasets/instanthmr_data --num_workers 8
-# ============================================================
-import os
-os.environ.setdefault("PYTORCH_CUDA_ALLOC_CONF", "expandable_segments:True")
-
-import argparse
-import math
-import random
-import gc
-from dataclasses import dataclass, field
-from pathlib import Path
-
-import numpy as np
-from PIL import Image
-
-import torch
-import torch.nn as nn
-import torch.optim as optim
-import torch.optim.lr_scheduler as lr_scheduler
-from torch.utils.data import Dataset, DataLoader, random_split
-from torch.optim.swa_utils import AveragedModel
-
-import torchvision.transforms as transforms
-import torchvision.transforms.functional as F_t
-from torchvision.transforms import InterpolationMode
-
-import timm
-from tqdm import tqdm
-
-device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
-print(f"Using device: {device}")
-
-PROJECT_ROOT = Path(__file__).resolve().parent
-DEFAULT_DATA_ROOT = "/pfcalcul/datasets/instanthmr_data/"
-
-
-# ============================================================
-# Configuration
-# ============================================================
-@dataclass
-class PoseConfig:
- data_root: str = str(DEFAULT_DATA_ROOT)
- log_dir: str = str(PROJECT_ROOT / "runs/distill_pose3d_v1")
-
- # --- Data ---
- image_size: int = 224
- max_images: int | None = None
- per_dataset_caps: dict = field(default_factory=lambda: {"sam3d_gt_harmony4d": 300_000})
- val_split: float = 0.1
- num_workers: int = 4
- augment: bool = True
-
- # --- Model ---
- backbone: str = "repvit_m2_3"
- d_model: int = 512
- n_heads: int = 8
- n_decoder_layers: int = 4
- dropout: float = 0.1
- cliff_dim: int = 3
- cam_dim: int = 3
- num_joints: int = 70
-
- # --- Training ---
- batch_size: int = 64
- lr: float = 3e-4
- weight_decay: float = 1e-4
- epochs: int = 150
- grad_clip: float = 1.0
- anomaly_loss_threshold: float = 100.0
- use_amp: bool = True
- ema_decay: float = 0.9998
- early_stop_patience: int = 150
- resume: bool = True
-
- # --- Loss weights ---
- w_keypoints2d: float = 10.0
- w_keypoints3d: float = 10.0
- w_cam: float = 0.1 # direct MSE supervision on cam_trans (stable; no 1/z reprojection)
-
-
-# ============================================================
-# Dataset (same crops as train_distill.py; keeps cam_trans + camera intrinsics)
-# ============================================================
-class RandomPixelate:
- def __init__(self, p=0.2, min_res=32, max_res=112):
- self.p, self.min_res, self.max_res = p, min_res, max_res
-
- def __call__(self, img):
- if random.random() < self.p:
- orig_w, orig_h = img.size
- degraded_h = random.randint(self.min_res, self.max_res)
- degraded_w = int(orig_w * (degraded_h / orig_h))
- img = F_t.resize(img, [degraded_h, degraded_w], interpolation=InterpolationMode.NEAREST)
- img = F_t.resize(img, [orig_h, orig_w], interpolation=InterpolationMode.NEAREST)
- return img
-
-
-class SAM3DStudentDataset(Dataset):
- def __init__(self, data_root: str, image_size: int = 224, max_images: int | None = None,
- augment: bool = True, per_dataset_caps: dict | None = None):
- super().__init__()
- self.image_size = image_size
- self.data_root = Path(data_root)
-
- tfm_list = [transforms.Resize((image_size, image_size))]
- if augment:
- tfm_list.extend([
- transforms.RandomApply([transforms.ColorJitter(
- brightness=0.2, contrast=0.2, saturation=0.2, hue=0.1)], p=0.5),
- RandomPixelate(p=0.2, min_res=48, max_res=112),
- transforms.RandomApply([transforms.GaussianBlur(kernel_size=5)], p=0.2),
- ])
- tfm_list.extend([
- transforms.ToTensor(),
- transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
- ])
- if augment:
- tfm_list.append(transforms.RandomErasing(p=0.2, scale=(0.02, 0.15)))
- self.transform = transforms.Compose(tfm_list)
-
- self.pairs = []
- dataset_dirs = self._find_dataset_dirs(self.data_root)
- if not dataset_dirs:
- raise FileNotFoundError(f"No annotations/images sub-folders under '{self.data_root}'.")
-
- cap_rng = random.Random(42)
- caps = per_dataset_caps or {}
- for ann_dir, img_dir in dataset_dirs:
- sub_name = ann_dir.parent.name
- sub_pairs = []
- for npz_path in sorted(ann_dir.glob("*.npz")):
- stem = npz_path.stem
- img_path = img_dir / f"{stem}.jpg"
- if not img_path.exists():
- img_path = img_dir / f"{stem}.png"
- if img_path.exists():
- sub_pairs.append((img_path, npz_path))
- cap = caps.get(sub_name)
- if cap is not None and len(sub_pairs) > cap:
- n_before = len(sub_pairs)
- sub_pairs.sort(key=lambda p: (str(p[1]), str(p[0])))
- sub_pairs = cap_rng.sample(sub_pairs, cap)
- print(f" [cap] {sub_name}: sampled {cap:,} of {n_before:,} crops")
- self.pairs.extend(sub_pairs)
-
- self.pairs.sort(key=lambda p: (str(p[1]), str(p[0])))
- if max_images is not None:
- self.pairs = self.pairs[:max_images]
- print(f" Found {len(dataset_dirs)} sub-folder(s) under {self.data_root}; "
- f"{len(self.pairs)} valid (image, npz) pairs (augment={augment}).")
-
- @staticmethod
- def _find_dataset_dirs(root: Path):
- dirs = []
- if (root / "annotations").is_dir() and (root / "images").is_dir():
- dirs.append((root / "annotations", root / "images"))
- if root.is_dir():
- for sub in sorted(root.iterdir()):
- if not sub.is_dir():
- continue
- ann, img = sub / "annotations", sub / "images"
- if ann.is_dir() and img.is_dir():
- dirs.append((ann, img))
- return dirs
-
- def __len__(self):
- return len(self.pairs)
-
- def __getitem__(self, idx):
- img_path, npz_path = self.pairs[idx]
- image = self.transform(Image.open(img_path).convert("RGB"))
-
- ann = np.load(npz_path)
- orig_h, orig_w = ann["orig_shape"]
-
- sq_bbox = ann["bbox_square"]
- sq_x1, sq_y1 = sq_bbox[0], sq_bbox[1]
- orig_crop_size = sq_bbox[2] - sq_bbox[0]
- true_scale = self.image_size / max(orig_crop_size, 1.0)
-
- joints_2d = ann["joints_2d"].copy()
- joints_2d[:, 0] = (joints_2d[:, 0] - sq_x1) * true_scale
- joints_2d[:, 1] = (joints_2d[:, 1] - sq_y1) * true_scale
- joints_2d[:, 0] = (joints_2d[:, 0] / self.image_size) * 2.0 - 1.0
- joints_2d[:, 1] = (joints_2d[:, 1] / self.image_size) * 2.0 - 1.0
- joints_2d = torch.from_numpy(joints_2d).float()
-
- tight_bbox = ann["bbox"]
- cx = (tight_bbox[0] + tight_bbox[2]) / 2.0
- cy = (tight_bbox[1] + tight_bbox[3]) / 2.0
- cx_norm = 2.0 * (cx / orig_w) - 1.0
- cy_norm = 2.0 * (cy / orig_h) - 1.0
- b_size = max(tight_bbox[2] - tight_bbox[0], tight_bbox[3] - tight_bbox[1])
- b_scale = b_size / max(orig_w, orig_h)
- cliff_cond = torch.tensor([cx_norm, cy_norm, b_scale], dtype=torch.float32)
-
- return {
- "image": image, # [3,224,224]
- "cliff_cond": cliff_cond, # [3]
- "joints_2d": joints_2d, # [70,2] crop [-1,1]
- "joints_3d": torch.from_numpy(ann["joints_3d"]).float(), # [70,3] root-centred
- "cam_trans": torch.from_numpy(ann["cam_trans"]).float(), # [3] camera translation
- }
-
-
-def build_dataloaders(cfg):
- full_dataset = SAM3DStudentDataset(cfg.data_root, augment=cfg.augment,
- max_images=cfg.max_images, per_dataset_caps=cfg.per_dataset_caps)
- val_dataset_clean = SAM3DStudentDataset(cfg.data_root, augment=False,
- max_images=cfg.max_images, per_dataset_caps=cfg.per_dataset_caps)
- n_val = int(len(full_dataset) * cfg.val_split)
- n_train = len(full_dataset) - n_val
- g = torch.Generator().manual_seed(42)
- train_dataset, _ = random_split(full_dataset, [n_train, n_val], generator=g)
- g = torch.Generator().manual_seed(42)
- _, val_dataset = random_split(val_dataset_clean, [n_train, n_val], generator=g)
-
- loader_kwargs = dict(num_workers=cfg.num_workers, pin_memory=True)
- if cfg.num_workers > 0:
- loader_kwargs["persistent_workers"] = True
- loader_kwargs["prefetch_factor"] = 4
- train_loader = DataLoader(train_dataset, batch_size=cfg.batch_size, shuffle=True,
- drop_last=True, **loader_kwargs)
- val_loader = DataLoader(val_dataset, batch_size=cfg.batch_size, shuffle=False, **loader_kwargs)
- print(f"Dataset Loaded! Train batches: {len(train_loader)} | Val batches: {len(val_loader)}")
- return train_loader, val_loader, full_dataset
-
-
-# ============================================================
-# Model — RepViT + decoder + cam head + 2D/3D heads (no MHR head)
-# ============================================================
-def get_2d_sincos_pos_embed(embed_dim, grid_size):
- grid_h, grid_w = grid_size, grid_size
- grid_y, grid_x = torch.meshgrid(torch.arange(grid_h), torch.arange(grid_w), indexing='ij')
- omega = torch.arange(embed_dim // 4).float() / (embed_dim // 4)
- omega = 1.0 / (10000 ** omega)
- out_y = grid_y.flatten().unsqueeze(1) * omega.unsqueeze(0)
- out_x = grid_x.flatten().unsqueeze(1) * omega.unsqueeze(0)
- pe_y = torch.cat([torch.sin(out_y), torch.cos(out_y)], dim=1)
- pe_x = torch.cat([torch.sin(out_x), torch.cos(out_x)], dim=1)
- return torch.cat([pe_y, pe_x], dim=1).unsqueeze(0)
-
-
-class InstantHMRPoseStudent(nn.Module):
- def __init__(self, cfg, pretrained=True):
- super().__init__()
- self.cfg = cfg
- self.backbone = timm.create_model(cfg.backbone, pretrained=pretrained, num_classes=0)
- embed_dim = self.backbone.num_features
- self.feat_proj = nn.Linear(embed_dim, cfg.d_model)
-
- self.grid_size = cfg.image_size // 32
- self.register_buffer("mem_pos_embed", get_2d_sincos_pos_embed(cfg.d_model, self.grid_size))
-
- # 1 global (camera) + 70 2D + 70 3D query tokens
- self.num_global = 1
- self.num_2d = cfg.num_joints
- self.num_3d = cfg.num_joints
- self.total_queries = self.num_global + self.num_2d + self.num_3d
- self.query_embed = nn.Parameter(torch.randn(1, self.total_queries, cfg.d_model) * 0.02)
-
- self.cond_proj = nn.Sequential(
- nn.Linear(cfg.cliff_dim, 128), nn.GELU(), nn.Linear(128, cfg.d_model))
-
- decoder_layer = nn.TransformerDecoderLayer(
- d_model=cfg.d_model, nhead=cfg.n_heads, dim_feedforward=cfg.d_model * 4,
- dropout=cfg.dropout, activation="gelu", batch_first=True, norm_first=True)
- self.transformer = nn.TransformerDecoder(decoder_layer, num_layers=cfg.n_decoder_layers)
-
- # Camera head (translation only) + 2D head + 3D head
- self.head_cam = nn.Linear(cfg.d_model, cfg.cam_dim)
- self.head_2d_feat = nn.Sequential(nn.Linear(cfg.d_model, 256), nn.GELU())
- self.head_2d_xy = nn.Sequential(nn.Linear(256, 2))
- self.head_3d = nn.Sequential(nn.Linear(cfg.d_model, 256), nn.GELU(), nn.Linear(256, 3))
-
- # Init camera near (0, 0, 2m) depth; tiny init on spatial heads for stability
- nn.init.normal_(self.head_cam.weight, mean=0.0, std=1e-4)
- nn.init.constant_(self.head_cam.bias, 0.0)
- nn.init.constant_(self.head_cam.bias[-1], 2.0)
- nn.init.normal_(self.head_2d_xy[0].weight, mean=0.0, std=1e-4)
- nn.init.constant_(self.head_2d_xy[0].bias, 0.0)
- nn.init.normal_(self.head_3d[-1].weight, mean=0.0, std=1e-4)
- nn.init.constant_(self.head_3d[-1].bias, 0.0)
-
- def forward(self, images, cliff_cond):
- B = images.shape[0]
- img_feats = self.backbone.forward_features(images)
- if img_feats.dim() == 4:
- img_feats = img_feats.flatten(2).transpose(1, 2)
- memory = self.feat_proj(img_feats) + self.mem_pos_embed
-
- queries = self.query_embed.expand(B, -1, -1) + self.cond_proj(cliff_cond).unsqueeze(1)
- shared = self.transformer(tgt=queries, memory=memory)
-
- feat_global = shared[:, 0, :]
- feat_2d = shared[:, 1:1 + self.num_2d, :]
- feat_3d = shared[:, 1 + self.num_2d:, :]
-
- pred_cam = self.head_cam(feat_global)
- pred_2d = self.head_2d_xy(self.head_2d_feat(feat_2d))
- pred_3d = self.head_3d(feat_3d)
- return {"cam_trans": pred_cam, "joints_2d": pred_2d, "joints_3d": pred_3d}
-
-
-# ============================================================
-# Loss — keypoints + camera (no MHR)
-# ============================================================
-class Pose3DLoss(nn.Module):
- def __init__(self, cfg):
- super().__init__()
- self.cfg = cfg
- self.l1 = nn.SmoothL1Loss()
- self.mse = nn.MSELoss()
-
- def forward(self, preds, targets):
- losses = {}
- losses['loss_2d'] = self.l1(preds["joints_2d"][..., :2], targets["joints_2d"]) * self.cfg.w_keypoints2d
- losses['loss_3d'] = self.l1(preds["joints_3d"][..., :3], targets["joints_3d"]) * self.cfg.w_keypoints3d
- # Direct camera supervision only — SmoothL1 (bounded gradient, robust to large
- # depth targets); MSE here diverges at the overfit LR, no 1/z reprojection term.
- losses['loss_cam'] = self.l1(preds["cam_trans"], targets["cam_trans"]) * self.cfg.w_cam
- losses['total_loss'] = losses['loss_2d'] + losses['loss_3d'] + losses['loss_cam']
- return losses
-
-
-# ============================================================
-# Metrics — MPJPE / PA-MPJPE on the 3D head (mm)
-# ============================================================
-def batched_procrustes_alignment(pred_pts, gt_pts):
- mu_pred = pred_pts.mean(dim=1, keepdim=True)
- mu_gt = gt_pts.mean(dim=1, keepdim=True)
- pred_c, gt_c = pred_pts - mu_pred, gt_pts - mu_gt
- norm_pred = torch.linalg.norm(pred_c, dim=(1, 2), keepdim=True)
- norm_gt = torch.linalg.norm(gt_c, dim=(1, 2), keepdim=True)
- pred_n = pred_c / torch.clamp(norm_pred, min=1e-8)
- gt_n = gt_c / torch.clamp(norm_gt, min=1e-8)
- H = torch.bmm(pred_n.transpose(1, 2), gt_n)
- U, S, Vh = torch.linalg.svd(H)
- R = torch.bmm(U, Vh)
- det = torch.linalg.det(R)
- det_sign = torch.where(det < 0, torch.tensor(-1.0, device=pred_pts.device),
- torch.tensor(1.0, device=pred_pts.device)).unsqueeze(-1)
- U_fixed = U.clone()
- U_fixed[:, :, 2] *= det_sign
- R_fixed = torch.bmm(U_fixed, Vh)
- S_fixed = S.clone()
- S_fixed[:, 2] *= det_sign.squeeze(-1)
- scale = S_fixed.sum(dim=-1, keepdim=True).unsqueeze(-1) * (norm_gt / torch.clamp(norm_pred, min=1e-8))
- return scale * torch.bmm(pred_c, R_fixed) + mu_gt
-
-
-def evaluate_pose_batch(preds, targets):
- metrics = {}
- pred_3d = preds["joints_3d"][..., :3]
- gt_3d = targets["joints_3d"][..., :3]
- pred_rr = pred_3d - pred_3d[:, 0:1, :]
- gt_rr = gt_3d - gt_3d[:, 0:1, :]
- metrics['MPJPE'] = torch.linalg.norm(pred_rr - gt_rr, dim=-1).mean().item() * 1000.0
- pred_al = batched_procrustes_alignment(pred_3d, gt_3d)
- metrics['PA_MPJPE'] = torch.linalg.norm(pred_al - gt_3d, dim=-1).mean().item() * 1000.0
- return metrics
-
-
-# ============================================================
-# 1-batch overfit test — proves gradients flow / model can learn
-# ============================================================
-def run_overfit_test(cfg, train_loader, steps=800, subset=8, lr=1e-3):
- print(f"--- 1-Batch Overfit Test ({subset} images, {steps} steps) ---")
- model = InstantHMRPoseStudent(cfg, pretrained=True).to(device)
- criterion = Pose3DLoss(cfg)
- optimizer = optim.AdamW(model.parameters(), lr=lr, weight_decay=0.0)
- scaler = torch.amp.GradScaler(device='cuda', enabled=cfg.use_amp)
-
- batch = next(iter(train_loader))
- batch = {k: (v[:subset].to(device) if isinstance(v, torch.Tensor) else v) for k, v in batch.items()}
-
- first_loss, last_loss = None, None
- model.train()
- for step in range(steps):
- optimizer.zero_grad(set_to_none=True)
- with torch.amp.autocast(device_type='cuda', dtype=torch.float16, enabled=cfg.use_amp):
- preds = model(batch["image"], batch["cliff_cond"])
- preds = {k: v.float() for k, v in preds.items()}
- losses = criterion(preds, batch)
- loss = losses['total_loss']
- scaler.scale(loss).backward()
- scaler.unscale_(optimizer)
- torch.nn.utils.clip_grad_norm_(model.parameters(), cfg.grad_clip)
- scaler.step(optimizer)
- scaler.update()
- if first_loss is None:
- first_loss = loss.item()
- last_loss = loss.item()
- if step % 50 == 0 or step == steps - 1:
- model.eval()
- with torch.no_grad():
- p = {k: v.float() for k, v in model(batch["image"], batch["cliff_cond"]).items()}
- m = evaluate_pose_batch(p, batch)
- model.train()
- print(f" step {step:04d} | loss {loss.item():.5f} | 2d {losses['loss_2d'].item():.4f} "
- f"| 3d {losses['loss_3d'].item():.4f} | cam {losses['loss_cam'].item():.4f} "
- f"| MPJPE {m['MPJPE']:.1f} mm | PA {m['PA_MPJPE']:.1f} mm")
-
- ok = last_loss < first_loss * 0.05
- print(f"\n{'✅ SUCCESS' if ok else '❌ FAIL'}: loss {first_loss:.4f} -> {last_loss:.5f} "
- f"({'overfit, gradients flow' if ok else 'did NOT drop enough — check the setup'})")
- return ok
-
-
-# ============================================================
-# EMA helper (decay warmup)
-# ============================================================
-def make_ema_avg_fn(max_decay):
- @torch.no_grad()
- def avg_fn(ema_params, model_params, num_averaged):
- if not (torch.is_floating_point(ema_params[0]) or torch.is_complex(ema_params[0])):
- for e, m in zip(ema_params, model_params):
- e.copy_(m)
- return
- n = num_averaged.item() if torch.is_tensor(num_averaged) else float(num_averaged)
- decay = min(max_decay, (1.0 + n) / (10.0 + n))
- torch._foreach_lerp_(ema_params, model_params, 1.0 - decay)
- return avg_fn
-
-
-# ============================================================
-# Training loop — EMA + early stopping + guards, keypoints + camera
-# ============================================================
-def train_pose3d(cfg, train_loader, val_loader):
- print(f"--- Training {cfg.backbone} (pose3d) | EMA={cfg.ema_decay} | patience={cfg.early_stop_patience} ---")
- os.makedirs(cfg.log_dir, exist_ok=True)
-
- model = InstantHMRPoseStudent(cfg, pretrained=True).to(device)
- criterion = Pose3DLoss(cfg)
- optimizer = optim.AdamW(model.parameters(), lr=cfg.lr, weight_decay=cfg.weight_decay)
- scaler = torch.amp.GradScaler(device='cuda', enabled=cfg.use_amp)
- steps_per_epoch = len(train_loader)
- scheduler = lr_scheduler.OneCycleLR(optimizer, max_lr=cfg.lr, epochs=cfg.epochs,
- steps_per_epoch=steps_per_epoch, pct_start=0.1)
-
- best_raw_path = os.path.join(cfg.log_dir, "best_pose3d_raw.pth")
- best_ema_path = os.path.join(cfg.log_dir, "best_pose3d_ema.pth")
- best_ckpt_path = os.path.join(cfg.log_dir, "best_pose3d.pth")
-
- start_epoch = 0
- best_raw_pa = best_ema_pa = best_overall_pa = float('inf')
- epochs_no_improve = 0
-
- if cfg.resume and os.path.exists(best_ckpt_path):
- print(f"🔄 Resuming from {best_ckpt_path}")
- ckpt = torch.load(best_ckpt_path, map_location=device, weights_only=False)
- model.load_state_dict(ckpt["model_state_dict"], strict=False)
- for k, obj in [("optimizer_state_dict", optimizer), ("scaler_state_dict", scaler),
- ("scheduler_state_dict", scheduler)]:
- if k in ckpt:
- obj.load_state_dict(ckpt[k])
- start_epoch = ckpt.get("epoch", -1) + 1
- best_overall_pa = best_raw_pa = best_ema_pa = ckpt.get("val_pa_mpjpe", float('inf'))
- print(f"✅ Resumed at epoch {start_epoch}. Best PA-MPJPE {best_overall_pa:.1f} mm.")
- else:
- print("🚀 Training from scratch.")
-
- ema_model = AveragedModel(model, multi_avg_fn=make_ema_avg_fn(cfg.ema_decay), use_buffers=True)
-
- @torch.no_grad()
- def run_validation(eval_model, tag, epoch):
- eval_model.eval()
- agg = {'total': 0.0, '2d': 0.0, '3d': 0.0, 'cam': 0.0, 'MPJPE': 0.0, 'PA_MPJPE': 0.0}
- n = 0
- vbar = tqdm(val_loader, desc=f"Epoch {epoch+1}/{cfg.epochs} [Val:{tag}]", leave=False)
- for batch in vbar:
- batch = {k: v.to(device) if isinstance(v, torch.Tensor) else v for k, v in batch.items()}
- with torch.amp.autocast(device_type='cuda', dtype=torch.float16, enabled=cfg.use_amp):
- preds = eval_model(batch["image"], batch["cliff_cond"])
- preds = {k: v.float() for k, v in preds.items()}
- losses = criterion(preds, batch)
- if math.isnan(losses['total_loss'].item()) or math.isinf(losses['total_loss'].item()):
- continue
- agg['total'] += losses['total_loss'].item()
- agg['2d'] += losses['loss_2d'].item()
- agg['3d'] += losses['loss_3d'].item()
- agg['cam'] += losses['loss_cam'].item()
- bm = evaluate_pose_batch(preds, batch)
- agg['MPJPE'] += bm['MPJPE']
- agg['PA_MPJPE'] += bm['PA_MPJPE']
- n += 1
- vbar.set_postfix({'PA-MPJPE': f"{agg['PA_MPJPE']/max(n,1):.1f}mm"})
- vbar.close()
- return {k: v / max(n, 1) for k, v in agg.items()}, n
-
- for epoch in range(start_epoch, cfg.epochs):
- model.train()
- tm = {'total': 0.0, '2d': 0.0, '3d': 0.0, 'cam': 0.0}
- nb = 0
- pbar = tqdm(train_loader, desc=f"Epoch {epoch+1}/{cfg.epochs} [Train]")
- for batch in pbar:
- batch = {k: v.to(device) if isinstance(v, torch.Tensor) else v for k, v in batch.items()}
- optimizer.zero_grad(set_to_none=True)
- with torch.amp.autocast(device_type='cuda', dtype=torch.float16, enabled=cfg.use_amp):
- preds_fp16 = model(batch["image"], batch["cliff_cond"])
- preds = {k: v.float() for k, v in preds_fp16.items()}
- losses = criterion(preds, batch)
- loss = losses['total_loss']
- loss_val = loss.item()
- if math.isnan(loss_val) or math.isinf(loss_val):
- print("⚠️ WARNING: NaN/Inf loss detected! Skipping step.")
- continue
- if loss_val > cfg.anomaly_loss_threshold:
- print(f"⚠️ WARNING: anomalous loss {loss_val:.1f} > {cfg.anomaly_loss_threshold} — skipping step.")
- continue
- scaler.scale(loss).backward()
- scaler.unscale_(optimizer)
- torch.nn.utils.clip_grad_norm_(model.parameters(), cfg.grad_clip)
- scale_before = scaler.get_scale()
- scaler.step(optimizer)
- scaler.update()
- if scale_before <= scaler.get_scale():
- scheduler.step()
- ema_model.update_parameters(model)
- tm['total'] += loss_val
- tm['2d'] += losses['loss_2d'].item()
- tm['3d'] += losses['loss_3d'].item()
- tm['cam'] += losses['loss_cam'].item()
- nb += 1
- pbar.set_postfix({'Tot': f"{loss_val:.4f}"})
- pbar.close()
- avg_train = {k: v / max(nb, 1) for k, v in tm.items()}
-
- raw_val, n_raw = run_validation(model, "raw", epoch)
- ema_val, n_ema = run_validation(ema_model, "ema", epoch)
-
- print(f"\n📈 Epoch {epoch+1} Summary | LR: {scheduler.get_last_lr()[0]:.2e}")
- print(f" [Train] Tot: {avg_train['total']:.4f} | 2D: {avg_train['2d']:.4f} | 3D: {avg_train['3d']:.4f} | cam: {avg_train['cam']:.4f}")
- print(f" [Val RAW] Tot: {raw_val['total']:.4f} | PA-MPJPE: {raw_val['PA_MPJPE']:.1f} | MPJPE: {raw_val['MPJPE']:.1f} mm")
- print(f" [Val EMA] Tot: {ema_val['total']:.4f} | PA-MPJPE: {ema_val['PA_MPJPE']:.1f} | MPJPE: {ema_val['MPJPE']:.1f} mm")
-
- def save_dict(m, val_metric, source):
- return {'epoch': epoch, 'model_state_dict': m.state_dict(),
- 'optimizer_state_dict': optimizer.state_dict(),
- 'scaler_state_dict': scaler.state_dict(),
- 'scheduler_state_dict': scheduler.state_dict(),
- 'val_pa_mpjpe': val_metric, 'source': source}
-
- improved_raw = n_raw > 0 and raw_val['PA_MPJPE'] < best_raw_pa
- improved_ema = n_ema > 0 and ema_val['PA_MPJPE'] < best_ema_pa
- if improved_raw:
- best_raw_pa = raw_val['PA_MPJPE']
- torch.save(save_dict(model, best_raw_pa, 'raw'), best_raw_path)
- if improved_ema:
- best_ema_pa = ema_val['PA_MPJPE']
- torch.save(save_dict(ema_model.module, best_ema_pa, 'ema'), best_ema_path)
-
- current = min(raw_val['PA_MPJPE'], ema_val['PA_MPJPE'])
- if current < best_overall_pa - 1e-4:
- best_overall_pa = current
- use_ema = ema_val['PA_MPJPE'] <= raw_val['PA_MPJPE']
- better = ema_model.module if use_ema else model
- torch.save(save_dict(better, best_overall_pa, 'ema' if use_ema else 'raw'), best_ckpt_path)
- print(f"💾 New best overall: {best_overall_pa:.1f} mm ({'EMA' if use_ema else 'RAW'}) -> {os.path.basename(best_ckpt_path)}")
-
- if improved_raw or improved_ema:
- epochs_no_improve = 0
- else:
- epochs_no_improve += 1
- print(f" ⏳ Neither RAW nor EMA improved: {epochs_no_improve}/{cfg.early_stop_patience} "
- f"(best raw {best_raw_pa:.1f} / ema {best_ema_pa:.1f} mm)")
- if epochs_no_improve >= cfg.early_stop_patience:
- print(f"\n🛑 Early stopping at epoch {epoch+1}.")
- break
-
- print(f"\n🎉 Training complete! Best PA-MPJPE: {best_overall_pa:.1f} mm")
-
-
-# ============================================================
-# ONNX export — 5 outputs in demo order (MHR slots zero-filled)
-# ============================================================
-class PoseDeployWrapper(nn.Module):
- """Emits the demo's 5-output contract so the ONNX drops into demo.py.
- mhr_params/shape_params are zeros (this model has no MHR mesh); the demo
- only reads them when --mhr-assets is set, which you won't use here."""
- def __init__(self, model):
- super().__init__()
- self.model = model
-
- def forward(self, image, cliff_cond):
- out = self.model(image, cliff_cond)
- cam = out["cam_trans"]
- B = cam.shape[0]
- mhr_params = cam.new_zeros(B, 204)
- shape_params = cam.new_zeros(B, 45)
- return mhr_params, shape_params, cam, out["joints_2d"], out["joints_3d"]
-
-
-def export_onnx(cfg):
- import onnx # noqa: F401
- export_dir = Path(cfg.log_dir) / "export"
- export_dir.mkdir(parents=True, exist_ok=True)
- onnx_path = export_dir / "instanthmr_pose3d.onnx"
- ckpt_path = os.path.join(cfg.log_dir, "best_pose3d.pth")
- if not os.path.exists(ckpt_path):
- print("⚠️ No checkpoint to export at", ckpt_path)
- return
- model = InstantHMRPoseStudent(cfg, pretrained=False).to(device)
- ckpt = torch.load(ckpt_path, map_location=device, weights_only=True)
- state = {k.replace('_orig_mod.', ''): v for k, v in ckpt['model_state_dict'].items()}
- model.load_state_dict(state, strict=False)
- deploy = PoseDeployWrapper(model).eval()
-
- keys = ["mhr_params", "shape_params", "cam_trans", "joints_2d", "joints_3d"]
- dummy_img = torch.randn(1, 3, cfg.image_size, cfg.image_size, device=device)
- dummy_cliff = torch.randn(1, 3, device=device)
- dyn = {"image": {0: "batch"}, "cliff_cond": {0: "batch"}}
- for k in keys:
- dyn[k] = {0: "batch"}
- torch.onnx.export(deploy, (dummy_img, dummy_cliff), str(onnx_path),
- input_names=["image", "cliff_cond"], output_names=keys,
- dynamic_axes=dyn, opset_version=17)
- print(f"✅ Exported {onnx_path} ({onnx_path.stat().st_size/1e6:.1f} MB)")
- print(f" Run the demo with: python demo.py --camera 0 --model {onnx_path}")
-
-
-# ============================================================
-# Entry point
-# ============================================================
-def parse_args():
- p = argparse.ArgumentParser(description="Keypoint + camera student (no MHR mesh).")
- p.add_argument("--data_root", type=str, default=None)
- p.add_argument("--output_dir", type=str, default=None)
- p.add_argument("--epochs", type=int, default=None)
- p.add_argument("--batch_size", type=int, default=None)
- p.add_argument("--lr", type=float, default=None)
- p.add_argument("--num_workers", type=int, default=None)
- p.add_argument("--max_images", type=int, default=None)
- p.add_argument("--harmony4d_cap", type=int, default=None, help="Max Harmony4D crops (0 = uncapped).")
- p.add_argument("--overfit-test", dest="overfit_test", action="store_true",
- help="Run the 1-batch overfit sanity check and exit.")
- p.add_argument("--no-resume", dest="no_resume", action="store_true")
- p.add_argument("--no-export", dest="no_export", action="store_true")
- p.add_argument("--gpu", type=int, default=None)
- args, unknown = p.parse_known_args()
- if unknown:
- print(f"⚠️ Ignoring unrecognized arguments: {unknown}")
- return args
-
-
-def main():
- args = parse_args()
- cfg = PoseConfig()
- if args.data_root is not None: cfg.data_root = args.data_root
- if args.output_dir is not None: cfg.log_dir = args.output_dir
- if args.epochs is not None: cfg.epochs = args.epochs
- if args.batch_size is not None: cfg.batch_size = args.batch_size
- if args.lr is not None: cfg.lr = args.lr
- if args.num_workers is not None: cfg.num_workers = args.num_workers
- if args.max_images is not None: cfg.max_images = args.max_images
- if args.harmony4d_cap is not None:
- if args.harmony4d_cap <= 0:
- cfg.per_dataset_caps.pop("sam3d_gt_harmony4d", None)
- else:
- cfg.per_dataset_caps["sam3d_gt_harmony4d"] = args.harmony4d_cap
- if args.no_resume: cfg.resume = False
-
- print("=" * 60)
- print(f"Data root : {cfg.data_root}")
- print(f"Output dir : {cfg.log_dir}")
- print(f"Backbone : {cfg.backbone} | epochs={cfg.epochs} | batch={cfg.batch_size} | lr={cfg.lr}")
- print(f"Loss : 2D + 3D keypoints + camera (NO MHR mesh)")
- print("=" * 60)
-
- train_loader, val_loader, _ = build_dataloaders(cfg)
-
- if args.overfit_test:
- run_overfit_test(cfg, train_loader)
- return
-
- gc.collect()
- if torch.cuda.is_available():
- torch.cuda.empty_cache()
- train_pose3d(cfg, train_loader, val_loader)
- if not args.no_export:
- export_onnx(cfg)
-
-
-if __name__ == "__main__":
- main()
diff --git a/instanthmr_distill_train/train_distill_pose3d_optimized.py b/instanthmr_distill_train/train_distill_pose3d_optimized.py
deleted file mode 100644
index 4beab30..0000000
--- a/instanthmr_distill_train/train_distill_pose3d_optimized.py
+++ /dev/null
@@ -1,861 +0,0 @@
-#!/usr/bin/env python3
-# ============================================================
-# Keypoint + camera student — OPTIMIZED (geometric aug + soft-argmax).
-# ------------------------------------------------------------
-# Same task as train_distill_pose3d.py (70 2D + 3D keypoints + cam_trans,
-# NO MHR), with two SOTA changes:
-#
-# (1) GEOMETRIC AUGMENTATION — random rotation / scale / translation +
-# horizontal flip, propagated CORRECTLY to the 2D targets, the 3D
-# targets, and cam_trans (verified: image<->2D warp matches to the
-# pixel; rotating 3D XY + cam by R=[[c,s],[-s,c]] reprojects onto the
-# rotated 2D to 1e-7; flip mirrors X and swaps left<->right joints).
-# (2) SOFT-ARGMAX 2D HEAD — the 2D tokens emit 1D bin distributions
-# (SimCC-style) and soft-argmax to coordinates: a light heatmap-style
-# spatial prior at ~the same compute as the old MLP regression.
-#
-# Loss: SmoothL1(2D coords) + SimCC-CE(2D bins) + SmoothL1(3D) + SmoothL1(cam).
-# Metrics: MPJPE / PA-MPJPE on the 3D head.
-# Export: 5 ONNX outputs in demo order (mhr_params & shape_params zero-filled).
-#
-# Sanity: python3 train_distill_pose3d_optimized.py --overfit-test --data_root ../data
-# Full: python3 train_distill_pose3d_optimized.py --data_root /datasets/instanthmr_data --num_workers 8
-# ============================================================
-import os
-os.environ.setdefault("PYTORCH_CUDA_ALLOC_CONF", "expandable_segments:True")
-
-import argparse
-import math
-import random
-import gc
-from dataclasses import dataclass, field
-from pathlib import Path
-
-import numpy as np
-import cv2
-from PIL import Image
-
-import torch
-import torch.nn as nn
-import torch.nn.functional as F
-import torch.optim as optim
-import torch.optim.lr_scheduler as lr_scheduler
-from torch.utils.data import Dataset, DataLoader, random_split
-from torch.optim.swa_utils import AveragedModel
-
-import torchvision.transforms as transforms
-import torchvision.transforms.functional as F_t
-from torchvision.transforms import InterpolationMode
-
-import timm
-from tqdm import tqdm
-
-device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
-print(f"Using device: {device}")
-
-PROJECT_ROOT = Path(__file__).resolve().parent
-DEFAULT_DATA_ROOT = "/pfcalcul/datasets/instanthmr_data/"
-
-# MHR70 joint ordering (mirror of instanthmr/skeleton.py, embedded so this
-# script is self-contained on the cluster). Used to build the horizontal-flip
-# left<->right permutation by name.
-JOINT_NAMES = [
- "nose", "left_eye", "right_eye", "left_ear", "right_ear",
- "left_shoulder", "right_shoulder", "left_elbow", "right_elbow",
- "left_hip", "right_hip", "left_knee", "right_knee", "left_ankle", "right_ankle",
- "left_big_toe_tip", "left_small_toe_tip", "left_heel",
- "right_big_toe_tip", "right_small_toe_tip", "right_heel",
- "right_thumb_tip", "right_thumb_first_joint", "right_thumb_second_joint", "right_thumb_third_joint",
- "right_index_tip", "right_index_first_joint", "right_index_second_joint", "right_index_third_joint",
- "right_middle_tip", "right_middle_first_joint", "right_middle_second_joint", "right_middle_third_joint",
- "right_ring_tip", "right_ring_first_joint", "right_ring_second_joint", "right_ring_third_joint",
- "right_pinky_tip", "right_pinky_first_joint", "right_pinky_second_joint", "right_pinky_third_joint",
- "right_wrist",
- "left_thumb_tip", "left_thumb_first_joint", "left_thumb_second_joint", "left_thumb_third_joint",
- "left_index_tip", "left_index_first_joint", "left_index_second_joint", "left_index_third_joint",
- "left_middle_tip", "left_middle_first_joint", "left_middle_second_joint", "left_middle_third_joint",
- "left_ring_tip", "left_ring_first_joint", "left_ring_second_joint", "left_ring_third_joint",
- "left_pinky_tip", "left_pinky_first_joint", "left_pinky_second_joint", "left_pinky_third_joint",
- "left_wrist",
- "left_olecranon", "right_olecranon", "left_cubital_fossa", "right_cubital_fossa",
- "left_acromion", "right_acromion", "neck",
-]
-
-
-def _build_flip_perm(names):
- """Left<->right joint index permutation for horizontal flip (central joints fixed)."""
- idx = {n: i for i, n in enumerate(names)}
- perm = list(range(len(names)))
- for i, n in enumerate(names):
- if n.startswith("left_"):
- perm[i] = idx.get("right_" + n[5:], i)
- elif n.startswith("right_"):
- perm[i] = idx.get("left_" + n[6:], i)
- perm = np.array(perm, dtype=np.int64)
- assert (perm[perm] == np.arange(len(perm))).all(), "flip permutation is not an involution"
- return perm
-
-
-FLIP_PERM = _build_flip_perm(JOINT_NAMES)
-
-
-# ============================================================
-# Configuration
-# ============================================================
-@dataclass
-class PoseConfig:
- data_root: str = str(DEFAULT_DATA_ROOT)
- log_dir: str = str(PROJECT_ROOT / "runs/distill_pose3d_v1")
-
- # --- Data ---
- image_size: int = 224
- max_images: int | None = None
- per_dataset_caps: dict = field(default_factory=lambda: {"sam3d_gt_harmony4d": 300_000})
- val_split: float = 0.1
- num_workers: int = 4
- augment: bool = True
-
- # --- Geometric augmentation (change #1) ---
- geom_rot_deg: float = 30.0 # random in-plane rotation ±deg
- geom_scale_range: float = 0.25 # random scale in [1-r, 1+r]
- geom_trans: float = 0.08 # random translation, fraction of half-crop
- geom_flip_p: float = 0.5 # horizontal flip probability (with L/R joint swap)
-
- # --- Model ---
- backbone: str = "repvit_m2_3"
- d_model: int = 512
- n_heads: int = 8
- n_decoder_layers: int = 4
- dropout: float = 0.1
- cliff_dim: int = 3
- cam_dim: int = 3
- num_joints: int = 70
- kp2d_bins: int = 64 # soft-argmax 2D head bins per axis (change #2)
-
- # --- Training ---
- batch_size: int = 64
- lr: float = 3e-4
- weight_decay: float = 1e-4
- epochs: int = 150
- grad_clip: float = 1.0
- anomaly_loss_threshold: float = 100.0
- use_amp: bool = True
- ema_decay: float = 0.9998
- early_stop_patience: int = 150
- resume: bool = True
-
- # --- Loss weights ---
- w_keypoints2d: float = 10.0
- w_keypoints3d: float = 10.0
- w_cam: float = 0.1 # direct SmoothL1 supervision on cam_trans
- w_simcc: float = 1.0 # SimCC bin-classification weight (has an entropy floor)
-
-
-# ============================================================
-# Dataset (same crops as train_distill.py; keeps cam_trans + camera intrinsics)
-# ============================================================
-class RandomPixelate:
- def __init__(self, p=0.2, min_res=32, max_res=112):
- self.p, self.min_res, self.max_res = p, min_res, max_res
-
- def __call__(self, img):
- if random.random() < self.p:
- orig_w, orig_h = img.size
- degraded_h = random.randint(self.min_res, self.max_res)
- degraded_w = int(orig_w * (degraded_h / orig_h))
- img = F_t.resize(img, [degraded_h, degraded_w], interpolation=InterpolationMode.NEAREST)
- img = F_t.resize(img, [orig_h, orig_w], interpolation=InterpolationMode.NEAREST)
- return img
-
-
-class SAM3DStudentDataset(Dataset):
- def __init__(self, data_root: str, image_size: int = 224, max_images: int | None = None,
- augment: bool = True, per_dataset_caps: dict | None = None,
- geom_rot_deg: float = 30.0, geom_scale_range: float = 0.25,
- geom_trans: float = 0.08, geom_flip_p: float = 0.5):
- super().__init__()
- self.image_size = image_size
- self.data_root = Path(data_root)
- # geometric augmentation only on the train split (augment=True)
- self.augment = augment
- self.geom_rot_deg = geom_rot_deg
- self.geom_scale_range = geom_scale_range
- self.geom_trans = geom_trans
- self.geom_flip_p = geom_flip_p
-
- # `self.transform` is now PHOTOMETRIC only — geometric aug happens in
- # __getitem__ jointly on the image + 2D/3D/cam targets (before ToTensor).
- tfm_list = [transforms.Resize((image_size, image_size))]
- if augment:
- tfm_list.extend([
- transforms.RandomApply([transforms.ColorJitter(
- brightness=0.2, contrast=0.2, saturation=0.2, hue=0.1)], p=0.5),
- RandomPixelate(p=0.2, min_res=48, max_res=112),
- transforms.RandomApply([transforms.GaussianBlur(kernel_size=5)], p=0.2),
- ])
- tfm_list.extend([
- transforms.ToTensor(),
- transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
- ])
- if augment:
- tfm_list.append(transforms.RandomErasing(p=0.2, scale=(0.02, 0.15)))
- self.transform = transforms.Compose(tfm_list)
-
- self.pairs = []
- dataset_dirs = self._find_dataset_dirs(self.data_root)
- if not dataset_dirs:
- raise FileNotFoundError(f"No annotations/images sub-folders under '{self.data_root}'.")
-
- cap_rng = random.Random(42)
- caps = per_dataset_caps or {}
- for ann_dir, img_dir in dataset_dirs:
- sub_name = ann_dir.parent.name
- sub_pairs = []
- for npz_path in sorted(ann_dir.glob("*.npz")):
- stem = npz_path.stem
- img_path = img_dir / f"{stem}.jpg"
- if not img_path.exists():
- img_path = img_dir / f"{stem}.png"
- if img_path.exists():
- sub_pairs.append((img_path, npz_path))
- cap = caps.get(sub_name)
- if cap is not None and len(sub_pairs) > cap:
- n_before = len(sub_pairs)
- sub_pairs.sort(key=lambda p: (str(p[1]), str(p[0])))
- sub_pairs = cap_rng.sample(sub_pairs, cap)
- print(f" [cap] {sub_name}: sampled {cap:,} of {n_before:,} crops")
- self.pairs.extend(sub_pairs)
-
- self.pairs.sort(key=lambda p: (str(p[1]), str(p[0])))
- if max_images is not None:
- self.pairs = self.pairs[:max_images]
- print(f" Found {len(dataset_dirs)} sub-folder(s) under {self.data_root}; "
- f"{len(self.pairs)} valid (image, npz) pairs (augment={augment}).")
-
- @staticmethod
- def _find_dataset_dirs(root: Path):
- dirs = []
- if (root / "annotations").is_dir() and (root / "images").is_dir():
- dirs.append((root / "annotations", root / "images"))
- if root.is_dir():
- for sub in sorted(root.iterdir()):
- if not sub.is_dir():
- continue
- ann, img = sub / "annotations", sub / "images"
- if ann.is_dir() and img.is_dir():
- dirs.append((ann, img))
- return dirs
-
- def __len__(self):
- return len(self.pairs)
-
- def _geometric_aug(self, img_np, j2, j3, cam):
- """Jointly warp image + 2D/3D/cam. Verified: image<->2D warp matches to the
- pixel; 3D XY & cam rotate by R=[[c,s],[-s,c]] consistently with the 2D."""
- W = H = self.image_size
-
- # --- horizontal flip: mirror X + swap left/right joints ---
- if random.random() < self.geom_flip_p:
- img_np = np.ascontiguousarray(img_np[:, ::-1, :])
- j2[:, 0] = -j2[:, 0]
- j3[:, 0] = -j3[:, 0]
- cam[0] = -cam[0]
- j2 = j2[FLIP_PERM]
- j3 = j3[FLIP_PERM]
-
- # --- rotation + scale + translation (single cv2 affine) ---
- angle = random.uniform(-self.geom_rot_deg, self.geom_rot_deg)
- scale = random.uniform(1.0 - self.geom_scale_range, 1.0 + self.geom_scale_range)
- dx = random.uniform(-self.geom_trans, self.geom_trans)
- dy = random.uniform(-self.geom_trans, self.geom_trans)
-
- M = cv2.getRotationMatrix2D((W / 2.0, H / 2.0), angle, scale)
- M[0, 2] += dx * (W / 2.0)
- M[1, 2] += dy * (H / 2.0)
- img_np = cv2.warpAffine(img_np, M, (W, H), flags=cv2.INTER_LINEAR,
- borderMode=cv2.BORDER_CONSTANT, borderValue=(0, 0, 0))
-
- # 2D: apply the SAME affine M in pixel space, back to normalised [-1,1]
- px = (j2[:, 0] + 1.0) * 0.5 * W
- py = (j2[:, 1] + 1.0) * 0.5 * H
- px2 = M[0, 0] * px + M[0, 1] * py + M[0, 2]
- py2 = M[1, 0] * px + M[1, 1] * py + M[1, 2]
- j2[:, 0] = px2 / (0.5 * W) - 1.0
- j2[:, 1] = py2 / (0.5 * H) - 1.0
-
- # 3D: rotate the XY plane about the optical axis (scale/translate don't touch 3D)
- rad = math.radians(angle)
- c, s = math.cos(rad), math.sin(rad)
- R = np.array([[c, s], [-s, c]], dtype=np.float32) # matches cv2 rotation (scale=1)
- j3[:, :2] = j3[:, :2] @ R.T
- cam[:2] = R @ cam[:2]
- return img_np, j2, j3, cam
-
- def __getitem__(self, idx):
- img_path, npz_path = self.pairs[idx]
- img_pil = Image.open(img_path).convert("RGB")
-
- ann = np.load(npz_path)
- orig_h, orig_w = ann["orig_shape"]
-
- sq_bbox = ann["bbox_square"]
- sq_x1, sq_y1 = sq_bbox[0], sq_bbox[1]
- orig_crop_size = sq_bbox[2] - sq_bbox[0]
- true_scale = self.image_size / max(orig_crop_size, 1.0)
-
- joints_2d = ann["joints_2d"].copy().astype(np.float32)
- joints_2d[:, 0] = (joints_2d[:, 0] - sq_x1) * true_scale
- joints_2d[:, 1] = (joints_2d[:, 1] - sq_y1) * true_scale
- joints_2d[:, 0] = (joints_2d[:, 0] / self.image_size) * 2.0 - 1.0
- joints_2d[:, 1] = (joints_2d[:, 1] / self.image_size) * 2.0 - 1.0
-
- joints_3d = ann["joints_3d"].astype(np.float32).copy()
- cam_trans = ann["cam_trans"].astype(np.float32).copy()
-
- # --- geometric augmentation (train only), jointly on image + targets ---
- if self.augment:
- img_np = np.asarray(img_pil.resize((self.image_size, self.image_size)))
- img_np, joints_2d, joints_3d, cam_trans = self._geometric_aug(img_np, joints_2d, joints_3d, cam_trans)
- img_pil = Image.fromarray(img_np)
-
- image = self.transform(img_pil) # photometric + ToTensor + Normalize
-
- tight_bbox = ann["bbox"]
- cx = (tight_bbox[0] + tight_bbox[2]) / 2.0
- cy = (tight_bbox[1] + tight_bbox[3]) / 2.0
- cx_norm = 2.0 * (cx / orig_w) - 1.0
- cy_norm = 2.0 * (cy / orig_h) - 1.0
- b_size = max(tight_bbox[2] - tight_bbox[0], tight_bbox[3] - tight_bbox[1])
- b_scale = b_size / max(orig_w, orig_h)
- cliff_cond = torch.tensor([cx_norm, cy_norm, b_scale], dtype=torch.float32)
-
- return {
- "image": image, # [3,224,224]
- "cliff_cond": cliff_cond, # [3]
- "joints_2d": torch.from_numpy(joints_2d).float(), # [70,2] crop [-1,1]
- "joints_3d": torch.from_numpy(joints_3d).float(), # [70,3] root-centred
- "cam_trans": torch.from_numpy(cam_trans).float(), # [3] camera translation
- }
-
-
-def build_dataloaders(cfg):
- geom = dict(geom_rot_deg=cfg.geom_rot_deg, geom_scale_range=cfg.geom_scale_range,
- geom_trans=cfg.geom_trans, geom_flip_p=cfg.geom_flip_p)
- full_dataset = SAM3DStudentDataset(cfg.data_root, augment=cfg.augment,
- max_images=cfg.max_images, per_dataset_caps=cfg.per_dataset_caps, **geom)
- val_dataset_clean = SAM3DStudentDataset(cfg.data_root, augment=False,
- max_images=cfg.max_images, per_dataset_caps=cfg.per_dataset_caps, **geom)
- n_val = int(len(full_dataset) * cfg.val_split)
- n_train = len(full_dataset) - n_val
- g = torch.Generator().manual_seed(42)
- train_dataset, _ = random_split(full_dataset, [n_train, n_val], generator=g)
- g = torch.Generator().manual_seed(42)
- _, val_dataset = random_split(val_dataset_clean, [n_train, n_val], generator=g)
-
- loader_kwargs = dict(num_workers=cfg.num_workers, pin_memory=True)
- if cfg.num_workers > 0:
- loader_kwargs["persistent_workers"] = True
- loader_kwargs["prefetch_factor"] = 4
- train_loader = DataLoader(train_dataset, batch_size=cfg.batch_size, shuffle=True,
- drop_last=True, **loader_kwargs)
- val_loader = DataLoader(val_dataset, batch_size=cfg.batch_size, shuffle=False, **loader_kwargs)
- print(f"Dataset Loaded! Train batches: {len(train_loader)} | Val batches: {len(val_loader)}")
- return train_loader, val_loader, full_dataset
-
-
-# ============================================================
-# Model — RepViT + decoder + cam head + 2D/3D heads (no MHR head)
-# ============================================================
-def get_2d_sincos_pos_embed(embed_dim, grid_size):
- grid_h, grid_w = grid_size, grid_size
- grid_y, grid_x = torch.meshgrid(torch.arange(grid_h), torch.arange(grid_w), indexing='ij')
- omega = torch.arange(embed_dim // 4).float() / (embed_dim // 4)
- omega = 1.0 / (10000 ** omega)
- out_y = grid_y.flatten().unsqueeze(1) * omega.unsqueeze(0)
- out_x = grid_x.flatten().unsqueeze(1) * omega.unsqueeze(0)
- pe_y = torch.cat([torch.sin(out_y), torch.cos(out_y)], dim=1)
- pe_x = torch.cat([torch.sin(out_x), torch.cos(out_x)], dim=1)
- return torch.cat([pe_y, pe_x], dim=1).unsqueeze(0)
-
-
-class SoftArgmax2DHead(nn.Module):
- """SimCC-style 2D head: each joint token emits 1D bin distributions for x and y,
- then soft-argmax to a continuous [-1,1] coordinate. A light heatmap-style spatial
- prior at ~the same compute as an MLP regressor. Fully ONNX-exportable."""
- def __init__(self, d_in, num_bins=64):
- super().__init__()
- self.num_bins = num_bins
- self.proj = nn.Sequential(nn.Linear(d_in, 256), nn.GELU())
- self.to_logits = nn.Linear(256, 2 * num_bins)
- self.register_buffer("bin_centers", torch.linspace(-1.0, 1.0, num_bins))
-
- def forward(self, feat): # feat: [B, J, d_in]
- logits = self.to_logits(self.proj(feat)) # [B, J, 2*bins]
- logits = logits.unflatten(-1, (2, self.num_bins)) # [B, J, 2, bins]
- prob = torch.softmax(logits, dim=-1)
- coords = (prob * self.bin_centers).sum(dim=-1) # [B, J, 2] in [-1,1]
- return coords, logits # logits used by the SimCC loss
-
-
-class InstantHMRPoseStudent(nn.Module):
- def __init__(self, cfg, pretrained=True):
- super().__init__()
- self.cfg = cfg
- self.backbone = timm.create_model(cfg.backbone, pretrained=pretrained, num_classes=0)
- embed_dim = self.backbone.num_features
- self.feat_proj = nn.Linear(embed_dim, cfg.d_model)
-
- self.grid_size = cfg.image_size // 32
- self.register_buffer("mem_pos_embed", get_2d_sincos_pos_embed(cfg.d_model, self.grid_size))
-
- # 1 global (camera) + 70 2D + 70 3D query tokens
- self.num_global = 1
- self.num_2d = cfg.num_joints
- self.num_3d = cfg.num_joints
- self.total_queries = self.num_global + self.num_2d + self.num_3d
- self.query_embed = nn.Parameter(torch.randn(1, self.total_queries, cfg.d_model) * 0.02)
-
- self.cond_proj = nn.Sequential(
- nn.Linear(cfg.cliff_dim, 128), nn.GELU(), nn.Linear(128, cfg.d_model))
-
- decoder_layer = nn.TransformerDecoderLayer(
- d_model=cfg.d_model, nhead=cfg.n_heads, dim_feedforward=cfg.d_model * 4,
- dropout=cfg.dropout, activation="gelu", batch_first=True, norm_first=True)
- self.transformer = nn.TransformerDecoder(decoder_layer, num_layers=cfg.n_decoder_layers)
-
- # Camera head (translation only) + soft-argmax 2D head + 3D head
- self.head_cam = nn.Linear(cfg.d_model, cfg.cam_dim)
- self.head_2d = SoftArgmax2DHead(cfg.d_model, cfg.kp2d_bins)
- self.head_3d = nn.Sequential(nn.Linear(cfg.d_model, 256), nn.GELU(), nn.Linear(256, 3))
-
- # Init camera near (0, 0, 2m) depth; tiny init on the 3D head for stability
- nn.init.normal_(self.head_cam.weight, mean=0.0, std=1e-4)
- nn.init.constant_(self.head_cam.bias, 0.0)
- nn.init.constant_(self.head_cam.bias[-1], 2.0)
- nn.init.normal_(self.head_3d[-1].weight, mean=0.0, std=1e-4)
- nn.init.constant_(self.head_3d[-1].bias, 0.0)
-
- def forward(self, images, cliff_cond):
- B = images.shape[0]
- img_feats = self.backbone.forward_features(images)
- if img_feats.dim() == 4:
- img_feats = img_feats.flatten(2).transpose(1, 2)
- memory = self.feat_proj(img_feats) + self.mem_pos_embed
-
- queries = self.query_embed.expand(B, -1, -1) + self.cond_proj(cliff_cond).unsqueeze(1)
- shared = self.transformer(tgt=queries, memory=memory)
-
- feat_global = shared[:, 0, :]
- feat_2d = shared[:, 1:1 + self.num_2d, :]
- feat_3d = shared[:, 1 + self.num_2d:, :]
-
- pred_cam = self.head_cam(feat_global)
- pred_2d, logits_2d = self.head_2d(feat_2d)
- pred_3d = self.head_3d(feat_3d)
- return {"cam_trans": pred_cam, "joints_2d": pred_2d,
- "joints_2d_logits": logits_2d, "joints_3d": pred_3d}
-
-
-# ============================================================
-# Loss — keypoints + camera (no MHR)
-# ============================================================
-class Pose3DLoss(nn.Module):
- def __init__(self, cfg):
- super().__init__()
- self.cfg = cfg
- self.l1 = nn.SmoothL1Loss()
- bins = torch.linspace(-1.0, 1.0, cfg.kp2d_bins)
- self.register_buffer("bin_centers", bins)
- self.simcc_sigma = 2.0 * (2.0 / (cfg.kp2d_bins - 1)) # ~2 bins wide Gaussian label
-
- def _simcc_ce(self, logits, tgt_2d):
- """SimCC classification loss: CE between the predicted bin distribution and a
- Gaussian soft-label centred on the target coordinate (sharpens the soft-argmax)."""
- # logits: [B,J,2,bins] tgt_2d: [B,J,2] in [-1,1]
- d = self.bin_centers.view(1, 1, 1, -1) - tgt_2d.unsqueeze(-1) # [B,J,2,bins]
- label = torch.exp(-(d ** 2) / (2.0 * self.simcc_sigma ** 2))
- label = label / label.sum(dim=-1, keepdim=True).clamp_min(1e-8)
- logp = F.log_softmax(logits, dim=-1)
- return -(label * logp).sum(dim=-1).mean()
-
- def forward(self, preds, targets):
- losses = {}
- # 2D: soft-argmax coordinate SmoothL1 (accurate read-out) + SimCC classification (sharpen)
- losses['loss_2d'] = self.l1(preds["joints_2d"][..., :2], targets["joints_2d"]) * self.cfg.w_keypoints2d
- losses['loss_2d_simcc'] = self._simcc_ce(preds["joints_2d_logits"], targets["joints_2d"]) * self.cfg.w_simcc
- losses['loss_3d'] = self.l1(preds["joints_3d"][..., :3], targets["joints_3d"]) * self.cfg.w_keypoints3d
- # Direct camera supervision — SmoothL1 (bounded gradient, robust to large depths).
- losses['loss_cam'] = self.l1(preds["cam_trans"], targets["cam_trans"]) * self.cfg.w_cam
- losses['total_loss'] = (losses['loss_2d'] + losses['loss_2d_simcc']
- + losses['loss_3d'] + losses['loss_cam'])
- return losses
-
-
-# ============================================================
-# Metrics — MPJPE / PA-MPJPE on the 3D head (mm)
-# ============================================================
-def batched_procrustes_alignment(pred_pts, gt_pts):
- mu_pred = pred_pts.mean(dim=1, keepdim=True)
- mu_gt = gt_pts.mean(dim=1, keepdim=True)
- pred_c, gt_c = pred_pts - mu_pred, gt_pts - mu_gt
- norm_pred = torch.linalg.norm(pred_c, dim=(1, 2), keepdim=True)
- norm_gt = torch.linalg.norm(gt_c, dim=(1, 2), keepdim=True)
- pred_n = pred_c / torch.clamp(norm_pred, min=1e-8)
- gt_n = gt_c / torch.clamp(norm_gt, min=1e-8)
- H = torch.bmm(pred_n.transpose(1, 2), gt_n)
- U, S, Vh = torch.linalg.svd(H)
- R = torch.bmm(U, Vh)
- det = torch.linalg.det(R)
- det_sign = torch.where(det < 0, torch.tensor(-1.0, device=pred_pts.device),
- torch.tensor(1.0, device=pred_pts.device)).unsqueeze(-1)
- U_fixed = U.clone()
- U_fixed[:, :, 2] *= det_sign
- R_fixed = torch.bmm(U_fixed, Vh)
- S_fixed = S.clone()
- S_fixed[:, 2] *= det_sign.squeeze(-1)
- scale = S_fixed.sum(dim=-1, keepdim=True).unsqueeze(-1) * (norm_gt / torch.clamp(norm_pred, min=1e-8))
- return scale * torch.bmm(pred_c, R_fixed) + mu_gt
-
-
-def evaluate_pose_batch(preds, targets):
- metrics = {}
- pred_3d = preds["joints_3d"][..., :3]
- gt_3d = targets["joints_3d"][..., :3]
- pred_rr = pred_3d - pred_3d[:, 0:1, :]
- gt_rr = gt_3d - gt_3d[:, 0:1, :]
- metrics['MPJPE'] = torch.linalg.norm(pred_rr - gt_rr, dim=-1).mean().item() * 1000.0
- pred_al = batched_procrustes_alignment(pred_3d, gt_3d)
- metrics['PA_MPJPE'] = torch.linalg.norm(pred_al - gt_3d, dim=-1).mean().item() * 1000.0
- return metrics
-
-
-# ============================================================
-# 1-batch overfit test — proves gradients flow / model can learn
-# ============================================================
-def run_overfit_test(cfg, train_loader, steps=800, subset=8, lr=1e-3):
- print(f"--- 1-Batch Overfit Test ({subset} images, {steps} steps) ---")
- model = InstantHMRPoseStudent(cfg, pretrained=True).to(device)
- criterion = Pose3DLoss(cfg).to(device)
- optimizer = optim.AdamW(model.parameters(), lr=lr, weight_decay=0.0)
- scaler = torch.amp.GradScaler(device='cuda', enabled=cfg.use_amp)
-
- batch = next(iter(train_loader))
- batch = {k: (v[:subset].to(device) if isinstance(v, torch.Tensor) else v) for k, v in batch.items()}
-
- # Judge overfit on the REGRESSION losses (2D coord + 3D + cam), which reach ~0.
- # The SimCC cross-entropy has an irreducible entropy floor, so the *total* can't.
- def reg_loss(ls):
- return ls['loss_2d'].item() + ls['loss_3d'].item() + ls['loss_cam'].item()
-
- first_reg, last_reg, last_pa = None, None, None
- model.train()
- for step in range(steps):
- optimizer.zero_grad(set_to_none=True)
- with torch.amp.autocast(device_type='cuda', dtype=torch.float16, enabled=cfg.use_amp):
- preds = model(batch["image"], batch["cliff_cond"])
- preds = {k: v.float() for k, v in preds.items()}
- losses = criterion(preds, batch)
- loss = losses['total_loss']
- scaler.scale(loss).backward()
- scaler.unscale_(optimizer)
- torch.nn.utils.clip_grad_norm_(model.parameters(), cfg.grad_clip)
- scaler.step(optimizer)
- scaler.update()
- if first_reg is None:
- first_reg = reg_loss(losses)
- last_reg = reg_loss(losses)
- if step % 50 == 0 or step == steps - 1:
- model.eval()
- with torch.no_grad():
- p = {k: v.float() for k, v in model(batch["image"], batch["cliff_cond"]).items()}
- m = evaluate_pose_batch(p, batch)
- model.train()
- last_pa = m['PA_MPJPE']
- print(f" step {step:04d} | total {loss.item():.4f} | 2d {losses['loss_2d'].item():.4f} "
- f"| simcc {losses['loss_2d_simcc'].item():.3f} | 3d {losses['loss_3d'].item():.4f} "
- f"| cam {losses['loss_cam'].item():.4f} | MPJPE {m['MPJPE']:.1f} mm | PA {m['PA_MPJPE']:.1f} mm")
-
- ok = (last_reg < first_reg * 0.05) and (last_pa is not None and last_pa < 40.0)
- print(f"\n{'✅ SUCCESS' if ok else '❌ FAIL'}: regression loss {first_reg:.4f} -> {last_reg:.5f}"
- f" | final PA-MPJPE {last_pa:.1f} mm "
- f"({'overfit, gradients flow' if ok else 'did NOT fit — check the setup'})")
- return ok
-
-
-# ============================================================
-# EMA helper (decay warmup)
-# ============================================================
-def make_ema_avg_fn(max_decay):
- @torch.no_grad()
- def avg_fn(ema_params, model_params, num_averaged):
- if not (torch.is_floating_point(ema_params[0]) or torch.is_complex(ema_params[0])):
- for e, m in zip(ema_params, model_params):
- e.copy_(m)
- return
- n = num_averaged.item() if torch.is_tensor(num_averaged) else float(num_averaged)
- decay = min(max_decay, (1.0 + n) / (10.0 + n))
- torch._foreach_lerp_(ema_params, model_params, 1.0 - decay)
- return avg_fn
-
-
-# ============================================================
-# Training loop — EMA + early stopping + guards, keypoints + camera
-# ============================================================
-def train_pose3d(cfg, train_loader, val_loader):
- print(f"--- Training {cfg.backbone} (pose3d) | EMA={cfg.ema_decay} | patience={cfg.early_stop_patience} ---")
- os.makedirs(cfg.log_dir, exist_ok=True)
-
- model = InstantHMRPoseStudent(cfg, pretrained=True).to(device)
- criterion = Pose3DLoss(cfg).to(device)
- optimizer = optim.AdamW(model.parameters(), lr=cfg.lr, weight_decay=cfg.weight_decay)
- scaler = torch.amp.GradScaler(device='cuda', enabled=cfg.use_amp)
- steps_per_epoch = len(train_loader)
- scheduler = lr_scheduler.OneCycleLR(optimizer, max_lr=cfg.lr, epochs=cfg.epochs,
- steps_per_epoch=steps_per_epoch, pct_start=0.1)
-
- best_raw_path = os.path.join(cfg.log_dir, "best_pose3d_raw.pth")
- best_ema_path = os.path.join(cfg.log_dir, "best_pose3d_ema.pth")
- best_ckpt_path = os.path.join(cfg.log_dir, "best_pose3d.pth")
-
- start_epoch = 0
- best_raw_pa = best_ema_pa = best_overall_pa = float('inf')
- epochs_no_improve = 0
-
- if cfg.resume and os.path.exists(best_ckpt_path):
- print(f"🔄 Resuming from {best_ckpt_path}")
- ckpt = torch.load(best_ckpt_path, map_location=device, weights_only=False)
- model.load_state_dict(ckpt["model_state_dict"], strict=False)
- for k, obj in [("optimizer_state_dict", optimizer), ("scaler_state_dict", scaler),
- ("scheduler_state_dict", scheduler)]:
- if k in ckpt:
- obj.load_state_dict(ckpt[k])
- start_epoch = ckpt.get("epoch", -1) + 1
- best_overall_pa = best_raw_pa = best_ema_pa = ckpt.get("val_pa_mpjpe", float('inf'))
- print(f"✅ Resumed at epoch {start_epoch}. Best PA-MPJPE {best_overall_pa:.1f} mm.")
- else:
- print("🚀 Training from scratch.")
-
- ema_model = AveragedModel(model, multi_avg_fn=make_ema_avg_fn(cfg.ema_decay), use_buffers=True)
-
- @torch.no_grad()
- def run_validation(eval_model, tag, epoch):
- eval_model.eval()
- agg = {'total': 0.0, '2d': 0.0, '3d': 0.0, 'cam': 0.0, 'MPJPE': 0.0, 'PA_MPJPE': 0.0}
- n = 0
- vbar = tqdm(val_loader, desc=f"Epoch {epoch+1}/{cfg.epochs} [Val:{tag}]", leave=False)
- for batch in vbar:
- batch = {k: v.to(device) if isinstance(v, torch.Tensor) else v for k, v in batch.items()}
- with torch.amp.autocast(device_type='cuda', dtype=torch.float16, enabled=cfg.use_amp):
- preds = eval_model(batch["image"], batch["cliff_cond"])
- preds = {k: v.float() for k, v in preds.items()}
- losses = criterion(preds, batch)
- if math.isnan(losses['total_loss'].item()) or math.isinf(losses['total_loss'].item()):
- continue
- agg['total'] += losses['total_loss'].item()
- agg['2d'] += losses['loss_2d'].item()
- agg['3d'] += losses['loss_3d'].item()
- agg['cam'] += losses['loss_cam'].item()
- bm = evaluate_pose_batch(preds, batch)
- agg['MPJPE'] += bm['MPJPE']
- agg['PA_MPJPE'] += bm['PA_MPJPE']
- n += 1
- vbar.set_postfix({'PA-MPJPE': f"{agg['PA_MPJPE']/max(n,1):.1f}mm"})
- vbar.close()
- return {k: v / max(n, 1) for k, v in agg.items()}, n
-
- for epoch in range(start_epoch, cfg.epochs):
- model.train()
- tm = {'total': 0.0, '2d': 0.0, '3d': 0.0, 'cam': 0.0}
- nb = 0
- pbar = tqdm(train_loader, desc=f"Epoch {epoch+1}/{cfg.epochs} [Train]")
- for batch in pbar:
- batch = {k: v.to(device) if isinstance(v, torch.Tensor) else v for k, v in batch.items()}
- optimizer.zero_grad(set_to_none=True)
- with torch.amp.autocast(device_type='cuda', dtype=torch.float16, enabled=cfg.use_amp):
- preds_fp16 = model(batch["image"], batch["cliff_cond"])
- preds = {k: v.float() for k, v in preds_fp16.items()}
- losses = criterion(preds, batch)
- loss = losses['total_loss']
- loss_val = loss.item()
- if math.isnan(loss_val) or math.isinf(loss_val):
- print("⚠️ WARNING: NaN/Inf loss detected! Skipping step.")
- continue
- if loss_val > cfg.anomaly_loss_threshold:
- print(f"⚠️ WARNING: anomalous loss {loss_val:.1f} > {cfg.anomaly_loss_threshold} — skipping step.")
- continue
- scaler.scale(loss).backward()
- scaler.unscale_(optimizer)
- torch.nn.utils.clip_grad_norm_(model.parameters(), cfg.grad_clip)
- scale_before = scaler.get_scale()
- scaler.step(optimizer)
- scaler.update()
- if scale_before <= scaler.get_scale():
- scheduler.step()
- ema_model.update_parameters(model)
- tm['total'] += loss_val
- tm['2d'] += losses['loss_2d'].item()
- tm['3d'] += losses['loss_3d'].item()
- tm['cam'] += losses['loss_cam'].item()
- nb += 1
- pbar.set_postfix({'Tot': f"{loss_val:.4f}"})
- pbar.close()
- avg_train = {k: v / max(nb, 1) for k, v in tm.items()}
-
- raw_val, n_raw = run_validation(model, "raw", epoch)
- ema_val, n_ema = run_validation(ema_model, "ema", epoch)
-
- print(f"\n📈 Epoch {epoch+1} Summary | LR: {scheduler.get_last_lr()[0]:.2e}")
- print(f" [Train] Tot: {avg_train['total']:.4f} | 2D: {avg_train['2d']:.4f} | 3D: {avg_train['3d']:.4f} | cam: {avg_train['cam']:.4f}")
- print(f" [Val RAW] Tot: {raw_val['total']:.4f} | PA-MPJPE: {raw_val['PA_MPJPE']:.1f} | MPJPE: {raw_val['MPJPE']:.1f} mm")
- print(f" [Val EMA] Tot: {ema_val['total']:.4f} | PA-MPJPE: {ema_val['PA_MPJPE']:.1f} | MPJPE: {ema_val['MPJPE']:.1f} mm")
-
- def save_dict(m, val_metric, source):
- return {'epoch': epoch, 'model_state_dict': m.state_dict(),
- 'optimizer_state_dict': optimizer.state_dict(),
- 'scaler_state_dict': scaler.state_dict(),
- 'scheduler_state_dict': scheduler.state_dict(),
- 'val_pa_mpjpe': val_metric, 'source': source}
-
- improved_raw = n_raw > 0 and raw_val['PA_MPJPE'] < best_raw_pa
- improved_ema = n_ema > 0 and ema_val['PA_MPJPE'] < best_ema_pa
- if improved_raw:
- best_raw_pa = raw_val['PA_MPJPE']
- torch.save(save_dict(model, best_raw_pa, 'raw'), best_raw_path)
- if improved_ema:
- best_ema_pa = ema_val['PA_MPJPE']
- torch.save(save_dict(ema_model.module, best_ema_pa, 'ema'), best_ema_path)
-
- current = min(raw_val['PA_MPJPE'], ema_val['PA_MPJPE'])
- if current < best_overall_pa - 1e-4:
- best_overall_pa = current
- use_ema = ema_val['PA_MPJPE'] <= raw_val['PA_MPJPE']
- better = ema_model.module if use_ema else model
- torch.save(save_dict(better, best_overall_pa, 'ema' if use_ema else 'raw'), best_ckpt_path)
- print(f"💾 New best overall: {best_overall_pa:.1f} mm ({'EMA' if use_ema else 'RAW'}) -> {os.path.basename(best_ckpt_path)}")
-
- if improved_raw or improved_ema:
- epochs_no_improve = 0
- else:
- epochs_no_improve += 1
- print(f" ⏳ Neither RAW nor EMA improved: {epochs_no_improve}/{cfg.early_stop_patience} "
- f"(best raw {best_raw_pa:.1f} / ema {best_ema_pa:.1f} mm)")
- if epochs_no_improve >= cfg.early_stop_patience:
- print(f"\n🛑 Early stopping at epoch {epoch+1}.")
- break
-
- print(f"\n🎉 Training complete! Best PA-MPJPE: {best_overall_pa:.1f} mm")
-
-
-# ============================================================
-# ONNX export — 5 outputs in demo order (MHR slots zero-filled)
-# ============================================================
-class PoseDeployWrapper(nn.Module):
- """Emits the demo's 5-output contract so the ONNX drops into demo.py.
- mhr_params/shape_params are zeros (this model has no MHR mesh); the demo
- only reads them when --mhr-assets is set, which you won't use here."""
- def __init__(self, model):
- super().__init__()
- self.model = model
-
- def forward(self, image, cliff_cond):
- out = self.model(image, cliff_cond)
- cam = out["cam_trans"]
- B = cam.shape[0]
- mhr_params = cam.new_zeros(B, 204)
- shape_params = cam.new_zeros(B, 45)
- return mhr_params, shape_params, cam, out["joints_2d"], out["joints_3d"]
-
-
-def export_onnx(cfg):
- import onnx # noqa: F401
- export_dir = Path(cfg.log_dir) / "export"
- export_dir.mkdir(parents=True, exist_ok=True)
- onnx_path = export_dir / "instanthmr_pose3d.onnx"
- ckpt_path = os.path.join(cfg.log_dir, "best_pose3d.pth")
- if not os.path.exists(ckpt_path):
- print("⚠️ No checkpoint to export at", ckpt_path)
- return
- model = InstantHMRPoseStudent(cfg, pretrained=False).to(device)
- ckpt = torch.load(ckpt_path, map_location=device, weights_only=True)
- state = {k.replace('_orig_mod.', ''): v for k, v in ckpt['model_state_dict'].items()}
- model.load_state_dict(state, strict=False)
- deploy = PoseDeployWrapper(model).eval()
-
- keys = ["mhr_params", "shape_params", "cam_trans", "joints_2d", "joints_3d"]
- dummy_img = torch.randn(1, 3, cfg.image_size, cfg.image_size, device=device)
- dummy_cliff = torch.randn(1, 3, device=device)
- dyn = {"image": {0: "batch"}, "cliff_cond": {0: "batch"}}
- for k in keys:
- dyn[k] = {0: "batch"}
- torch.onnx.export(deploy, (dummy_img, dummy_cliff), str(onnx_path),
- input_names=["image", "cliff_cond"], output_names=keys,
- dynamic_axes=dyn, opset_version=17)
- print(f"✅ Exported {onnx_path} ({onnx_path.stat().st_size/1e6:.1f} MB)")
- print(f" Run the demo with: python demo.py --camera 0 --model {onnx_path}")
-
-
-# ============================================================
-# Entry point
-# ============================================================
-def parse_args():
- p = argparse.ArgumentParser(description="Keypoint + camera student (no MHR mesh).")
- p.add_argument("--data_root", type=str, default=None)
- p.add_argument("--output_dir", type=str, default=None)
- p.add_argument("--epochs", type=int, default=None)
- p.add_argument("--batch_size", type=int, default=None)
- p.add_argument("--lr", type=float, default=None)
- p.add_argument("--num_workers", type=int, default=None)
- p.add_argument("--max_images", type=int, default=None)
- p.add_argument("--harmony4d_cap", type=int, default=None, help="Max Harmony4D crops (0 = uncapped).")
- p.add_argument("--overfit-test", dest="overfit_test", action="store_true",
- help="Run the 1-batch overfit sanity check and exit.")
- p.add_argument("--no-resume", dest="no_resume", action="store_true")
- p.add_argument("--no-export", dest="no_export", action="store_true")
- p.add_argument("--gpu", type=int, default=None)
- args, unknown = p.parse_known_args()
- if unknown:
- print(f"⚠️ Ignoring unrecognized arguments: {unknown}")
- return args
-
-
-def main():
- args = parse_args()
- cfg = PoseConfig()
- if args.data_root is not None: cfg.data_root = args.data_root
- if args.output_dir is not None: cfg.log_dir = args.output_dir
- if args.epochs is not None: cfg.epochs = args.epochs
- if args.batch_size is not None: cfg.batch_size = args.batch_size
- if args.lr is not None: cfg.lr = args.lr
- if args.num_workers is not None: cfg.num_workers = args.num_workers
- if args.max_images is not None: cfg.max_images = args.max_images
- if args.harmony4d_cap is not None:
- if args.harmony4d_cap <= 0:
- cfg.per_dataset_caps.pop("sam3d_gt_harmony4d", None)
- else:
- cfg.per_dataset_caps["sam3d_gt_harmony4d"] = args.harmony4d_cap
- if args.no_resume: cfg.resume = False
-
- print("=" * 60)
- print(f"Data root : {cfg.data_root}")
- print(f"Output dir : {cfg.log_dir}")
- print(f"Backbone : {cfg.backbone} | epochs={cfg.epochs} | batch={cfg.batch_size} | lr={cfg.lr}")
- print(f"Loss : 2D + 3D keypoints + camera (NO MHR mesh)")
- print("=" * 60)
-
- train_loader, val_loader, _ = build_dataloaders(cfg)
-
- if args.overfit_test:
- run_overfit_test(cfg, train_loader)
- return
-
- gc.collect()
- if torch.cuda.is_available():
- torch.cuda.empty_cache()
- train_pose3d(cfg, train_loader, val_loader)
- if not args.no_export:
- export_onnx(cfg)
-
-
-if __name__ == "__main__":
- main()
diff --git a/instanthmr_distill_train/train_levjepa_cloud.py b/instanthmr_distill_train/train_levjepa_cloud.py
deleted file mode 100644
index be00e98..0000000
--- a/instanthmr_distill_train/train_levjepa_cloud.py
+++ /dev/null
@@ -1,457 +0,0 @@
-#!/usr/bin/env python3
-"""Frozen-LeVJEPA MHR regression on the FULL corpus, 90/10 train/val. No LoRA.
-
-Differences from train_levjepa_lora.py (which this replaces for cluster runs):
-
- * NO LoRA. The encoder is frozen end to end, so there is no backward pass
- through 305 M parameters -- ~7x cheaper per clip and no adapter state.
- * ALL SIX datasets, not just the video ones. 90/10 random split over the
- combined pool with a fixed seed, so val is in-domain (use your own held-out
- samples for the real generalisation check).
- * Still images are encoded as T=1 clips, NOT by repeating the frame 16x.
- RoPE + tubelet_size=1 make the frame count free, so a still costs 197 tokens
- instead of 3137 for the same single label -- 16x less compute. Video and
- still batches alternate; both go through the same decoder.
- * OFFLINE-SAFE. --encoder_path loads a pre-downloaded snapshot directory, so
- the compute node never needs to reach huggingface.co. See the submit script
- for how to stage it.
-
-WHY NO LoRA
------------
-The local frozen probe (10k Harmony4D clips, 20 epochs) reached 101.8 mm train
-but plateaued at ~181 mm val on 3DPW with the val loss RISING after epoch 10 --
-classic overfitting. The bottleneck was training-domain diversity, not encoder
-capacity, so adding trainable encoder parameters was the wrong lever. Feeding
-the model all 961 k crops instead of 10 k Harmony4D clips is the right one.
-
-ATTENTION MODE -- DO NOT CHANGE
--------------------------------
-attn_mode stays "block_causal" as shipped. Full attention raises no error and
-silently returns worse features.
-"""
-from __future__ import annotations
-
-import argparse
-import contextlib
-import io
-import math
-import os
-import random
-import sys
-import time
-from collections import defaultdict
-from dataclasses import asdict, dataclass, field
-from pathlib import Path
-
-import numpy as np
-import torch
-import torch.nn as nn
-from torch.utils.data import DataLoader, Dataset, Subset
-from tqdm import tqdm
-
-HERE = Path(__file__).resolve().parent
-sys.path.insert(0, str(HERE))
-with contextlib.redirect_stdout(io.StringIO()):
- import train_distill_mhr_only as base
- import train_levjepa_probe as probe
-
-device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
-
-
-@dataclass
-class CloudConfig:
- data_root: str = str(base.DEFAULT_DATA_ROOT)
- mhr_model_path: str = str(base.PROJECT_ROOT / "checkpoints/mhr_model.pt")
- kp_regressor_path: str = str(base.PROJECT_ROOT / "assets/mhr_j127_to_kp70.npy")
- log_dir: str = str(base.PROJECT_ROOT / "runs/levjepa_cloud")
-
- encoder_id: str = probe.ENCODER_ID
- encoder_path: str | None = None # local snapshot dir -> no network needed
- image_size: int = 224
- clip_len: int = 16
- clip_stride: int = 4
- frame_stride: dict = field(default_factory=lambda: {
- "sam3d_gt_harmony4d": 1, "sam3d_gt_3dpw": 4, "sam3d_distill_mix": 1})
- # every dataset with usable temporal structure
- video_datasets: tuple = ("sam3d_gt_harmony4d", "sam3d_distill_mix", "sam3d_gt_3dpw")
- # every dataset without it -> encoded as T=1
- static_datasets: tuple = ("sam3d_gt_coco", "sam3d_gt_aic", "sam3d_gt_mpii")
- use_static: bool = True
- val_split: float = 0.1
- split_seed: int = 42
- max_video_clips: int | None = None
- max_static: int | None = None
-
- d_model: int = 512
- n_heads: int = 8
- n_decoder_layers: int = 4
- dropout: float = 0.1
- decoder_mode: str = "perframe"
- pose_dim: int = 136
- scale_dim: int = 68
- shape_dim: int = 45
- cam_dim: int = 3
- cliff_dim: int = 3
- num_joints: int = 70
- kp2d_bins: int = 96
- kp2d_range: float = 1.5
-
- @property
- def model_params_dim(self) -> int:
- return self.pose_dim + self.scale_dim
-
- batch_size: int = 8 # video clips per batch
- static_batch_mult: int = 8 # still batches are 16x cheaper -> bigger
- lr: float = 3e-4
- weight_decay: float = 1e-4
- epochs: int = 30
- warmup_pct: float = 0.05
- grad_clip: float = 1.0
- use_amp: bool = True
- num_workers: int = 8
- anomaly_loss_threshold: float = 100.0
- early_stop_patience: int = 8
- resume: bool = True
- max_hours: float = 92.0
- save_every_steps: int = 2000
- # Print a progress line every N batches. tqdm is disabled when stderr is not
- # a tty (i.e. every SLURM job) and an epoch here is HOURS long, so without
- # this the log stays empty until the first epoch ends and the run looks hung.
- log_every: int = 200
-
- w_pose: float = 1.0
- w_scale: float = 0.1
- w_shape: float = 1.0
- w_cam: float = 0.1
- w_keypoints3d: float = 2.0
- w_keypoints2d: float = 10.0
- w_simcc: float = 1.0
- w_3d_joints: float = 1e-3
- w_reproj: float = 0.01
- kp3d_warmup_steps: int = 2000
-
- native_mapping_ids: list = field(default_factory=lambda: base.DistillConfig().native_mapping_ids)
- mhr_mapping_ids: list = field(default_factory=lambda: base.DistillConfig().mhr_mapping_ids)
-
-
-class FrozenEncoder(nn.Module):
- def __init__(self, cfg: CloudConfig):
- super().__init__()
- from transformers import AutoModel
- src = cfg.encoder_path or cfg.encoder_id
- if cfg.encoder_path and not Path(cfg.encoder_path).exists():
- raise FileNotFoundError(
- f"--encoder_path '{cfg.encoder_path}' does not exist. Stage the "
- f"snapshot next to the data (see submit_train_levjepa_cloud_*.sh); "
- f"compute nodes usually cannot reach huggingface.co.")
- print(f" loading encoder from: {src}")
- self.net = AutoModel.from_pretrained(
- src, trust_remote_code=True, local_files_only=bool(cfg.encoder_path)
- ).eval().to(torch.float16).to(device)
- for p in self.net.parameters():
- p.requires_grad_(False)
- self.embed_dim = int(self.net.config.embed_dim)
- self.grid = int(self.net.config.img_size // self.net.config.patch_size)
-
- @torch.no_grad()
- def forward(self, images):
- """(B,T,3,H,W) -> (B,T,grid^2,C). T is free: 16 for clips, 1 for stills."""
- B, T = images.shape[:2]
- out = self.net(images.permute(0, 2, 1, 3, 4).to(torch.float16))
- tok = out[0] if isinstance(out, (tuple, list)) else getattr(out, "last_hidden_state", out)
- return tok[:, 1:].reshape(B, T, self.grid ** 2, -1).float()
-
-
-
-class CompactPairs:
- """List-like view over two numpy byte buffers, replacing a list of Paths.
-
- 961 k (Path, Path) tuples cost ~1.6 GB resident. Worse, CPython refcounts
- every one of those objects, so a forked DataLoader worker dirties the pages
- holding them and copy-on-write quietly turns into copy-everything -- with
- several workers that is tens of GB and a host-RAM OOM kill, which is exactly
- how job 23815712 died after 117 minutes.
-
- Two numpy arrays are single allocations with no per-element refcounts, so
- forks genuinely share them.
- """
-
- __slots__ = ("a", "b")
-
- def __init__(self, pairs):
- self.a = np.array([str(x[0]) for x in pairs], dtype="S")
- self.b = np.array([str(x[1]) for x in pairs], dtype="S")
-
- def __len__(self):
- return len(self.a)
-
- def __getitem__(self, i):
- return Path(self.a[i].decode()), Path(self.b[i].decode())
-
-
-def make_base_dataset(cfg):
- """One scan of the corpus, with the path list compacted, shared by everyone."""
- with contextlib.redirect_stdout(io.StringIO()):
- ds = base.SAM3DStudentDataset(cfg.data_root, augment=False,
- image_size=cfg.image_size,
- max_images=None, per_dataset_caps=None)
- n = len(ds.pairs)
- ds.pairs = CompactPairs(ds.pairs)
- print(f" corpus: {n:,} crops (path list compacted for fork-safety)")
- return ds
-
-
-class StaticFrameDataset(Dataset):
- """Still images as T=1 clips -- 197 tokens, not 3137. Same labels, same losses."""
-
- def __init__(self, cfg, datasets, max_items=None, base_ds=None):
- self.base = base_ds if base_ds is not None else make_base_dataset(cfg)
- keep = set(datasets)
- self.idx = [i for i, (_, n) in enumerate(self.base.pairs)
- if n.parent.parent.name in keep]
- if max_items and len(self.idx) > max_items:
- rng = np.random.RandomState(0)
- self.idx = [self.idx[i] for i in sorted(rng.choice(len(self.idx), max_items, False))]
- print(f" static {'/'.join(datasets)}: {len(self.idx):,} images as T=1 clips")
-
- def __len__(self):
- return len(self.idx)
-
- def __getitem__(self, i):
- f = self.base[self.idx[i]]
- out = {}
- for k, v in f.items():
- v = v if torch.is_tensor(v) else torch.as_tensor(np.asarray(v))
- out[k] = v.unsqueeze(0).float() # (1, ...) -> T=1
- return out
-
-
-def split_90_10(ds, val_frac, seed):
- n = len(ds)
- g = np.random.RandomState(seed)
- perm = g.permutation(n)
- nv = int(n * val_frac)
- return Subset(ds, perm[nv:].tolist()), Subset(ds, perm[:nv].tolist())
-
-
-def run_split(enc, dec, crit, cfg, mhr, loaders, opt=None, scaler=None, sched=None,
- gstep=0, tag="train", t_start=None):
- train = opt is not None
- dec.train(train)
- m, h, nb = defaultdict(float), defaultdict(float), 0
- stop = False
- for name, loader in loaders:
- if loader is None:
- continue
- bar = tqdm(loader, desc=f"{tag}:{name}", disable=not sys.stderr.isatty(),
- mininterval=60.0)
- nl = 0 # per-loader counter; nb runs across loaders
- for b in bar:
- b = {k: v.to(device, non_blocking=True) for k, v in b.items()}
- flat = probe.flatten_clip(b)
- patch = enc(b["image"])
- ctx = contextlib.nullcontext() if train else torch.no_grad()
- with ctx:
- with torch.amp.autocast(device_type="cuda", dtype=torch.float16,
- enabled=cfg.use_amp):
- preds16 = dec(patch, b["cliff_cond"])
- preds = {k: v.float() for k, v in preds16.items()}
- losses = crit(preds, flat)
- total = losses["total_loss"]
- if train:
- if not torch.isfinite(total) or total.item() > cfg.anomaly_loss_threshold:
- m["skipped"] += 1
- opt.zero_grad(set_to_none=True)
- continue
- opt.zero_grad(set_to_none=True)
- scaler.scale(total).backward()
- scaler.unscale_(opt)
- torch.nn.utils.clip_grad_norm_(dec.parameters(), cfg.grad_clip)
- scaler.step(opt); scaler.update()
- if sched.last_epoch < sched.total_steps - 1:
- sched.step()
- gstep += 1
- crit.set_step(gstep)
- for k, v in losses.items():
- m[k] += float(v.detach())
- for k, v in base.evaluate_hmr_batch(preds, flat, cfg, mhr).items():
- h[k] += v
- nb += 1
- nl += 1
- if train and cfg.log_every and nl % cfg.log_every == 0:
- el = (time.time() - t_start) / 60.0 if t_start else 0.0
- print(f" [{tag}:{name}] batch {nl}/{len(loader)} | {el:6.1f} min "
- f"| tot {m['total_loss']/nb:.4f} "
- f"| Mesh PA {h['Mesh_PA_MPJPE']/nb:.1f} mm "
- f"| lr {sched.get_last_lr()[0]:.2e}", flush=True)
- if train and t_start and (time.time() - t_start) / 3600.0 > cfg.max_hours:
- stop = True
- break
- bar.close()
- if stop:
- break
- return ({k: v / max(nb, 1) for k, v in m.items()},
- {k: v / max(nb, 1) for k, v in h.items()}, gstep, stop)
-
-
-def main():
- p = argparse.ArgumentParser(description=__doc__,
- formatter_class=argparse.RawDescriptionHelpFormatter)
- p.add_argument("--data_root", default=None)
- p.add_argument("--output_dir", default=None)
- p.add_argument("--mhr_model_path", default=None)
- p.add_argument("--kp_regressor_path", default=None)
- p.add_argument("--encoder_path", default=None,
- help="Local HF snapshot dir for the encoder (offline nodes).")
- p.add_argument("--clip_len", type=int, default=None)
- p.add_argument("--clip_stride", type=int, default=None)
- p.add_argument("--batch_size", type=int, default=None, help="video CLIPS per batch")
- p.add_argument("--static_batch_mult", type=int, default=None)
- p.add_argument("--epochs", type=int, default=None)
- p.add_argument("--lr", type=float, default=None)
- p.add_argument("--num_workers", type=int, default=None)
- p.add_argument("--max_video_clips", type=int, default=None)
- p.add_argument("--max_static", type=int, default=None)
- p.add_argument("--no-static", dest="no_static", action="store_true")
- p.add_argument("--val_split", type=float, default=None)
- p.add_argument("--max_hours", type=float, default=None)
- p.add_argument("--log_every", type=int, default=None,
- help="Batches between progress lines (0 disables).")
- p.add_argument("--no-resume", dest="no_resume", action="store_true")
- p.add_argument("--seed", type=int, default=0)
- p.add_argument("--self-test", dest="self_test", action="store_true")
- args = p.parse_args()
-
- torch.manual_seed(args.seed); np.random.seed(args.seed); random.seed(args.seed)
- cfg = CloudConfig()
- for k in ("data_root", "mhr_model_path", "kp_regressor_path", "encoder_path",
- "clip_len", "clip_stride", "batch_size", "static_batch_mult", "epochs",
- "lr", "num_workers", "max_video_clips", "max_static", "val_split",
- "max_hours", "log_every"):
- v = getattr(args, k)
- if v is not None:
- setattr(cfg, k, v)
- if args.output_dir: cfg.log_dir = args.output_dir
- if args.no_static: cfg.use_static = False
- if args.no_resume: cfg.resume = False
-
- print("=" * 74)
- print(f"encoder : {cfg.encoder_path or cfg.encoder_id} FROZEN (no LoRA)")
- print(f"data : video {cfg.video_datasets}")
- print(f" static {cfg.static_datasets if cfg.use_static else '(disabled)'} as T=1")
- print(f"split : {100*(1-cfg.val_split):.0f}/{100*cfg.val_split:.0f} random, seed {cfg.split_seed}")
- print(f"batch : {cfg.batch_size} clips (T={cfg.clip_len}) | "
- f"{cfg.batch_size*cfg.static_batch_mult} stills (T=1)")
- print(f"budget : {cfg.epochs} epochs, stop at {cfg.max_hours} h, resume={cfg.resume}")
- if torch.cuda.is_available():
- pr = torch.cuda.get_device_properties(0)
- print(f"GPU : {pr.name} {pr.total_memory/2**30:.1f} GiB")
- if pr.total_memory / 2**30 < 10: # 6 GB MIG slice, not a real card
- print("WARNING : that looks like a small MIG slice. perelha advertises "
- "gpu:nvidia_a30_1g.6gb:4 next to the A6000 / 6000-Ada, and a bare "
- "--gres=gpu:1 can land on one. Request the card explicitly, "
- "e.g. --gres=gpu:rtx_a6000:1")
- print("=" * 74)
-
- for pth, what in ((cfg.kp_regressor_path, "(70,127) keypoint regressor"),
- (cfg.mhr_model_path, "MHR TorchScript model")):
- if not Path(pth).exists():
- raise FileNotFoundError(f"{what} not found at '{pth}'. It must be rsynced "
- f"to the cluster alongside the training scripts.")
- W = np.load(cfg.kp_regressor_path)
- mhr = base.MHRForwardPass(cfg.mhr_model_path, device, kp_regressor=W)
- enc = FrozenEncoder(cfg)
- dec = probe.ClipPoseDecoder(cfg, enc.embed_dim, enc.grid).to(device)
- crit = base.DistillationLoss(cfg, mhr).to(device)
- print(f" encoder {sum(q.numel() for q in enc.parameters())/1e6:.1f} M frozen | "
- f"decoder {sum(q.numel() for q in dec.parameters())/1e6:.2f} M trainable")
-
- shared = make_base_dataset(cfg)
- vid = probe.ClipDataset(cfg, cfg.video_datasets, max_clips=cfg.max_video_clips,
- base_ds=shared)
- vtr, vva = split_90_10(vid, cfg.val_split, cfg.split_seed)
- stat = (StaticFrameDataset(cfg, cfg.static_datasets, cfg.max_static, base_ds=shared)
- if cfg.use_static else None)
- if stat is not None:
- str_, sva = split_90_10(stat, cfg.val_split, cfg.split_seed)
- else:
- str_ = sva = None
- print(f" train: {len(vtr):,} clips + {len(str_) if str_ else 0:,} stills | "
- f"val: {len(vva):,} clips + {len(sva) if sva else 0:,} stills")
-
- # persistent_workers=False on purpose: this script runs FOUR loaders
- # (train/val x clips/stills). Persistent pools keep all four sets of workers
- # alive simultaneously, so the resident dataset is duplicated ~4x more than
- # necessary. Non-persistent workers exist only while their loader iterates.
- kw = dict(num_workers=cfg.num_workers, pin_memory=True)
- if cfg.num_workers > 0:
- kw.update(persistent_workers=False, prefetch_factor=2)
- mk = lambda d, bs, sh: (DataLoader(d, batch_size=bs, shuffle=sh, drop_last=sh, **kw)
- if d is not None and len(d) else None)
- sbs = cfg.batch_size * cfg.static_batch_mult
- train_loaders = [("clips", mk(vtr, cfg.batch_size, True)), ("stills", mk(str_, sbs, True))]
- val_loaders = [("clips", mk(vva, cfg.batch_size, False)), ("stills", mk(sva, sbs, False))]
-
- if args.self_test:
- for nm, l in train_loaders:
- if l is None: continue
- b = next(iter(l)); b = {k: v.to(device) for k, v in b.items()}
- f = enc(b["image"])
- o = dec(f, b["cliff_cond"])
- ls = crit({k: v.float() for k, v in o.items()}, probe.flatten_clip(b))
- print(f" {nm}: image{tuple(b['image'].shape)} -> feat{tuple(f.shape)} "
- f"-> mhr{tuple(o['mhr_params'].shape)} | loss {float(ls['total_loss']):.4f}")
- assert torch.isfinite(ls["total_loss"])
- print(" SELF-TEST PASSED"); return
-
- opt = torch.optim.AdamW(dec.parameters(), lr=cfg.lr, weight_decay=cfg.weight_decay)
- scaler = torch.amp.GradScaler(device="cuda", enabled=cfg.use_amp)
- spe = sum(len(l) for _, l in train_loaders if l is not None)
- sched = torch.optim.lr_scheduler.OneCycleLR(
- opt, max_lr=cfg.lr, epochs=cfg.epochs, steps_per_epoch=max(1, spe),
- pct_start=cfg.warmup_pct)
-
- os.makedirs(cfg.log_dir, exist_ok=True)
- last_p = os.path.join(cfg.log_dir, "levjepa_cloud_last.pth")
- best_p = os.path.join(cfg.log_dir, "levjepa_cloud_best.pth")
- start_ep, best, no_imp, gstep = 0, float("inf"), 0, 0
- if cfg.resume and os.path.exists(last_p):
- ck = torch.load(last_p, map_location=device, weights_only=False)
- dec.load_state_dict(ck["decoder"]); opt.load_state_dict(ck["optimizer"])
- scaler.load_state_dict(ck["scaler"]); sched.load_state_dict(ck["scheduler"])
- start_ep, best, gstep = ck["epoch"] + 1, ck.get("best", float("inf")), ck.get("gstep", 0)
- print(f" resumed from epoch {start_ep} (best val PA {best:.1f} mm)")
-
- def save(path, ep):
- torch.save({"decoder": dec.state_dict(), "optimizer": opt.state_dict(),
- "scaler": scaler.state_dict(), "scheduler": sched.state_dict(),
- "epoch": ep, "best": best, "gstep": gstep,
- "cfg": asdict(cfg)}, path)
-
- t0 = time.time()
- for ep in range(start_ep, cfg.epochs):
- tm, th, gstep, stop = run_split(enc, dec, crit, cfg, mhr, train_loaders,
- opt, scaler, sched, gstep, f"ep{ep+1}", t0)
- vm, vh, _, _ = run_split(enc, dec, crit, cfg, mhr, val_loaders, tag=f"ep{ep+1}val")
- el = (time.time() - t0) / 3600.0
- print(f"\nEpoch {ep+1}/{cfg.epochs} | {el:.2f} h | lr {sched.get_last_lr()[0]:.2e} "
- f"| skipped {int(tm.get('skipped',0))}")
- print(f" [train] tot {tm['total_loss']:.4f} | 3d {tm.get('loss_3d_native',0):.4f} "
- f"| 2d {tm.get('loss_2d_native',0):.4f} | Mesh PA {th['Mesh_PA_MPJPE']:.1f} mm")
- print(f" [val ] tot {vm['total_loss']:.4f} | Mesh PA {vh['Mesh_PA_MPJPE']:.1f} "
- f"| Mesh MPJPE {vh['Mesh_MPJPE']:.1f} | Mesh52 PA {vh['Mesh52_PA_MPJPE']:.1f} mm")
- save(last_p, ep)
- if vh["Mesh_PA_MPJPE"] < best:
- best, no_imp = vh["Mesh_PA_MPJPE"], 0
- save(best_p, ep); print(f" new best {best:.1f} mm")
- else:
- no_imp += 1
- if no_imp >= cfg.early_stop_patience:
- print(f" early stop after {no_imp} epochs without improvement"); break
- if stop:
- print(f" time budget {cfg.max_hours} h reached -- stopped cleanly"); break
- print(f"\nBest val Mesh PA-MPJPE: {best:.1f} mm ({(time.time()-t0)/3600:.2f} h)")
-
-
-if __name__ == "__main__":
- main()
diff --git a/instanthmr_distill_train/train_levjepa_lora.py b/instanthmr_distill_train/train_levjepa_lora.py
deleted file mode 100644
index 95d0428..0000000
--- a/instanthmr_distill_train/train_levjepa_lora.py
+++ /dev/null
@@ -1,500 +0,0 @@
-#!/usr/bin/env python3
-"""LoRA fine-tuning of LeVJEPA-VideoMix-Large for clip-level MHR regression.
-
-Cluster counterpart to train_levjepa_probe.py. The probe freezes the encoder and
-caches its features; this script adapts the encoder with LoRA, which changes the
-economics completely and is worth stating plainly before you queue a 4-day job:
-
- * FEATURE CACHING IS IMPOSSIBLE HERE. The encoder's weights move every step, so
- its outputs do too. Every clip is re-encoded on every epoch.
- * Measured on an RTX 4070: 551 ms/clip for LoRA (r=16, qkv+proj, 24 blocks)
- against 79 ms/clip for a frozen forward -- 7x -- and the frozen path then
- gets a further 6x from caching. End to end LoRA is ~30x the wall-clock of
- the cached probe on identical data.
- * So run the probe first. Spend this budget only if the frozen features
- already show signal worth improving.
-
-WHAT IT TRAINS
---------------
-LoRA adapters (fp32) on the frozen fp16 encoder's attention projections, plus
-the full pose decoder. At r=16 on qkv+proj that is ~2.4 M encoder params (0.8%)
-+ ~17.8 M decoder. The base encoder weights never change, so the released EMA
-checkpoint stays intact and the adapters are a small artefact to ship.
-
-ATTENTION MODE -- DO NOT CHANGE
--------------------------------
-attn_mode stays "block_causal" as shipped. Full attention raises no error and
-silently returns worse features. The dense (B,1,N,N) mask that block-causal
-needs disqualifies SDPA's flash kernel; PyTorch falls back to the
-memory-efficient backend, which handles it at ~5% extra memory (measured), not
-the 4x a materialised N^2 matrix would cost.
-
-DATA
-----
-Video-structured sets provide real clips. Static sets (COCO/AIC/MPII) have no
-temporal axis; with --include_static each image becomes a clip by temporal
-repetition, exactly as the model card prescribes for single images. That buys
-in-the-wild diversity Harmony4D badly lacks -- but it costs a full T-frame
-encode for ONE label, so it is off by default and rate-limited by
---static_frac when on.
-
-RESUMING
---------
-A 4-day wall is shorter than this job wants. Checkpoints carry LoRA + decoder +
-optimiser + scheduler + scaler + EMA + epoch, --resume is on by default, and
---max_hours stops cleanly before SLURM's SIGKILL so the last epoch is never
-lost. Set it below the SBATCH --time.
-"""
-from __future__ import annotations
-
-import argparse
-import contextlib
-import io
-import math
-import os
-import sys
-import time
-from collections import defaultdict
-from dataclasses import asdict, dataclass, field
-from pathlib import Path
-
-import numpy as np
-import torch
-import torch.nn as nn
-import torch.nn.functional as F
-from torch.utils.data import DataLoader, Dataset, ConcatDataset
-from torch.utils.checkpoint import checkpoint as ckpt_fn
-from tqdm import tqdm
-
-HERE = Path(__file__).resolve().parent
-sys.path.insert(0, str(HERE))
-with contextlib.redirect_stdout(io.StringIO()):
- import train_distill_mhr_only as base
- import train_levjepa_probe as probe
-
-device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
-
-
-# ============================================================
-# Config
-# ============================================================
-@dataclass
-class LoRAConfig:
- data_root: str = str(base.DEFAULT_DATA_ROOT)
- mhr_model_path: str = str(base.PROJECT_ROOT / "checkpoints/mhr_model.pt")
- kp_regressor_path: str = str(base.PROJECT_ROOT / "assets/mhr_j127_to_kp70.npy")
- log_dir: str = str(base.PROJECT_ROOT / "runs/levjepa_lora")
-
- encoder_id: str = probe.ENCODER_ID
- image_size: int = 224
- clip_len: int = 16
- clip_stride: int = 4 # denser than the probe's 8: more data
- frame_stride: dict = field(default_factory=lambda: {
- "sam3d_gt_harmony4d": 1, "sam3d_gt_3dpw": 4, "sam3d_distill_mix": 1})
- train_datasets: tuple = ("sam3d_gt_harmony4d", "sam3d_distill_mix")
- val_datasets: tuple = ("sam3d_gt_3dpw",)
- static_datasets: tuple = ("sam3d_gt_coco", "sam3d_gt_aic", "sam3d_gt_mpii")
- include_static: bool = False
- static_frac: float = 0.25 # cap static clips at this share of the epoch
- max_clips: int | None = None
- val_max_clips: int | None = 600
-
- # LoRA
- lora_r: int = 16
- lora_alpha: float = 32.0
- lora_dropout: float = 0.05
- lora_targets: tuple = ("qkv", "proj") # add "fc1","fc2" to reach the MLP
- lora_lr: float = 1e-4 # encoder adapters: deliberately << decoder lr
- grad_ckpt: bool = True # LeVJEPAModel has no native support; we add it
-
- # decoder (mirrors the probe so results are comparable)
- d_model: int = 512
- n_heads: int = 8
- n_decoder_layers: int = 4
- dropout: float = 0.1
- decoder_mode: str = "perframe"
- pose_dim: int = 136
- scale_dim: int = 68
- shape_dim: int = 45
- cam_dim: int = 3
- cliff_dim: int = 3
- num_joints: int = 70
- kp2d_bins: int = 96
- kp2d_range: float = 1.5
-
- @property
- def model_params_dim(self) -> int:
- return self.pose_dim + self.scale_dim
-
- batch_size: int = 4 # CLIPS. 4 needs ~24 GB with grad_ckpt off
- lr: float = 3e-4 # decoder
- weight_decay: float = 1e-4
- epochs: int = 20
- warmup_pct: float = 0.05
- grad_clip: float = 1.0
- accum_steps: int = 1
- use_amp: bool = True
- ema_decay: float = 0.999
- num_workers: int = 8
- anomaly_loss_threshold: float = 100.0
- early_stop_patience: int = 8
- resume: bool = True
- max_hours: float = 92.0 # < SBATCH --time=4-00:00:00
- save_every_steps: int = 2000
-
- w_pose: float = 1.0
- w_scale: float = 0.1
- w_shape: float = 1.0
- w_cam: float = 0.1
- w_keypoints3d: float = 2.0
- w_keypoints2d: float = 10.0
- w_simcc: float = 1.0
- w_3d_joints: float = 1e-3
- w_reproj: float = 0.01
- kp3d_warmup_steps: int = 2000
-
- native_mapping_ids: list = field(default_factory=lambda: base.DistillConfig().native_mapping_ids)
- mhr_mapping_ids: list = field(default_factory=lambda: base.DistillConfig().mhr_mapping_ids)
- cache_dir: str | None = None # unused; LoRA cannot cache. Kept for signature parity.
- cache_pool: int = 0
-
-
-# ============================================================
-# LoRA
-# ============================================================
-class LoRALinear(nn.Module):
- """y = W0 x + (alpha/r) * B A x, with W0 frozen (fp16) and A,B trainable (fp32).
-
- fp32 adapters over an fp16 base is not cosmetic: GradScaler refuses to
- unscale fp16 gradients, so fp16 adapters fail outright.
- """
-
- def __init__(self, lin: nn.Linear, r=16, alpha=32.0, dropout=0.05):
- super().__init__()
- self.lin = lin
- for p in self.lin.parameters():
- p.requires_grad_(False)
- self.r, self.scale = r, alpha / r
- self.A = nn.Parameter(torch.zeros(r, lin.in_features, dtype=torch.float32))
- self.B = nn.Parameter(torch.zeros(lin.out_features, r, dtype=torch.float32))
- nn.init.kaiming_uniform_(self.A, a=math.sqrt(5)) # B stays 0 -> identity at init
- self.drop = nn.Dropout(dropout)
-
- def forward(self, x):
- d = F.linear(F.linear(self.drop(x).float(), self.A), self.B) * self.scale
- return self.lin(x) + d.to(x.dtype)
-
-
-def inject_lora(net, cfg: LoRAConfig):
- for p in net.parameters():
- p.requires_grad_(False)
- n = 0
- for blk in net.encoder.blocks:
- for name in cfg.lora_targets:
- for owner in (blk.attn, blk.mlp):
- if hasattr(owner, name) and isinstance(getattr(owner, name), nn.Linear):
- setattr(owner, name,
- LoRALinear(getattr(owner, name), cfg.lora_r,
- cfg.lora_alpha, cfg.lora_dropout).to(device))
- n += 1
- tr = sum(p.numel() for p in net.parameters() if p.requires_grad)
- tot = sum(p.numel() for p in net.parameters())
- print(f" LoRA r={cfg.lora_r} a={cfg.lora_alpha} on {cfg.lora_targets}: "
- f"{n} adapted Linears, {tr/1e6:.2f} M trainable ({100*tr/tot:.2f}% of {tot/1e6:.0f} M)")
- return net
-
-
-def enable_grad_ckpt(net):
- """LeVJEPAModel.gradient_checkpointing_enable() raises, so wrap Blocks here.
-
- Roughly halves activation memory for ~30% more compute -- the difference
- between batch 2 and batch 8 on a fixed card.
- """
- for blk in net.encoder.blocks:
- if getattr(blk, "_ckpt_wrapped", False):
- continue
- orig = blk.forward
-
- def wrapped(*a, __orig=orig, **kw):
- if not torch.is_grad_enabled():
- return __orig(*a, **kw)
- return ckpt_fn(lambda *x: __orig(*x, **kw), *a, use_reentrant=False)
-
- blk.forward = wrapped
- blk._ckpt_wrapped = True
- print(" gradient checkpointing: ON (manual Block wrap)")
-
-
-class TrainableEncoder(nn.Module):
- """Like probe.LeVJEPAEncoder but WITHOUT no_grad -- gradients must flow."""
-
- def __init__(self, cfg: LoRAConfig):
- super().__init__()
- from transformers import AutoModel
- self.net = AutoModel.from_pretrained(cfg.encoder_id,
- trust_remote_code=True).to(torch.float16)
- self.embed_dim = int(self.net.config.embed_dim)
- self.grid = int(self.net.config.img_size // self.net.config.patch_size)
- self.net = inject_lora(self.net.to(device), cfg)
- if cfg.grad_ckpt:
- enable_grad_ckpt(self.net)
-
- def forward(self, images):
- B, T = images.shape[:2]
- x = images.permute(0, 2, 1, 3, 4).to(torch.float16)
- out = self.net(x)
- tok = out[0] if isinstance(out, (tuple, list)) else getattr(out, "last_hidden_state", out)
- patch = tok[:, 1:]
- return patch.reshape(B, T, self.grid ** 2, -1).float()
-
-
-# ============================================================
-# Static-image clips
-# ============================================================
-class StaticClipDataset(Dataset):
- """One still image -> a T-frame clip by temporal repetition.
-
- This is what the model card prescribes for single images. It costs a full
- T-frame encode to supervise ONE pose, so it is a diversity purchase, not an
- efficiency one -- hence --static_frac.
- """
-
- def __init__(self, cfg, datasets, max_items=None):
- with contextlib.redirect_stdout(io.StringIO()):
- self.base = base.SAM3DStudentDataset(
- cfg.data_root, augment=False, image_size=cfg.image_size,
- max_images=None, per_dataset_caps=None)
- keep = set(datasets)
- self.idx = [i for i, (_, npz) in enumerate(self.base.pairs)
- if npz.parent.parent.name in keep]
- if max_items and len(self.idx) > max_items:
- rng = np.random.RandomState(0)
- self.idx = [self.idx[i] for i in
- sorted(rng.choice(len(self.idx), max_items, replace=False))]
- self.T = cfg.clip_len
- print(f" static {'/'.join(datasets)}: {len(self.idx)} images "
- f"-> repeated to {self.T}-frame clips")
-
- def __len__(self):
- return len(self.idx)
-
- def __getitem__(self, i):
- f = self.base[self.idx[i]]
- out = {}
- for k, v in f.items():
- v = v if torch.is_tensor(v) else torch.as_tensor(np.asarray(v))
- out[k] = v.unsqueeze(0).repeat(*([self.T] + [1] * v.dim())).float()
- return out
-
-
-# ============================================================
-# Train
-# ============================================================
-def build_loaders(cfg):
- train = probe.ClipDataset(cfg, cfg.train_datasets, max_clips=cfg.max_clips)
- val = probe.ClipDataset(cfg, cfg.val_datasets, max_clips=cfg.val_max_clips)
- if cfg.include_static:
- n_static = int(len(train) * cfg.static_frac / max(1e-6, 1 - cfg.static_frac))
- train = ConcatDataset([train, StaticClipDataset(cfg, cfg.static_datasets, n_static)])
- print(f" train set: {len(train)} clips total ({cfg.static_frac:.0%} static)")
- kw = dict(num_workers=cfg.num_workers, pin_memory=True)
- if cfg.num_workers > 0:
- kw.update(persistent_workers=True, prefetch_factor=4)
- return (DataLoader(train, batch_size=cfg.batch_size, shuffle=True, drop_last=True, **kw),
- DataLoader(val, batch_size=cfg.batch_size, shuffle=False, **kw))
-
-
-def main():
- p = argparse.ArgumentParser(description=__doc__,
- formatter_class=argparse.RawDescriptionHelpFormatter)
- p.add_argument("--data_root", default=None)
- p.add_argument("--output_dir", default=None)
- p.add_argument("--mhr_model_path", default=None)
- p.add_argument("--kp_regressor_path", default=None)
- p.add_argument("--clip_len", type=int, default=None)
- p.add_argument("--clip_stride", type=int, default=None)
- p.add_argument("--batch_size", type=int, default=None, help="CLIPS per batch")
- p.add_argument("--accum_steps", type=int, default=None)
- p.add_argument("--epochs", type=int, default=None)
- p.add_argument("--lr", type=float, default=None, help="decoder LR")
- p.add_argument("--lora_lr", type=float, default=None, help="encoder-adapter LR")
- p.add_argument("--lora_r", type=int, default=None)
- p.add_argument("--lora_alpha", type=float, default=None)
- p.add_argument("--lora_targets", nargs="+", default=None,
- help="qkv proj [fc1 fc2] -- adding the MLP roughly doubles trainable params")
- p.add_argument("--no-grad-ckpt", dest="no_grad_ckpt", action="store_true")
- p.add_argument("--num_workers", type=int, default=None)
- p.add_argument("--max_clips", type=int, default=None)
- p.add_argument("--val_max_clips", type=int, default=None)
- p.add_argument("--include_static", action="store_true")
- p.add_argument("--static_frac", type=float, default=None)
- p.add_argument("--train_datasets", nargs="+", default=None)
- p.add_argument("--val_datasets", nargs="+", default=None)
- p.add_argument("--max_hours", type=float, default=None)
- p.add_argument("--no-resume", dest="no_resume", action="store_true")
- p.add_argument("--seed", type=int, default=0)
- p.add_argument("--self-test", dest="self_test", action="store_true")
- args = p.parse_args()
-
- torch.manual_seed(args.seed); np.random.seed(args.seed)
- cfg = LoRAConfig()
- for k in ("data_root", "mhr_model_path", "kp_regressor_path", "clip_len",
- "clip_stride", "batch_size", "accum_steps", "epochs", "lr", "lora_lr",
- "lora_r", "lora_alpha", "num_workers", "max_clips", "val_max_clips",
- "static_frac", "max_hours"):
- v = getattr(args, k)
- if v is not None:
- setattr(cfg, k, v)
- if args.output_dir: cfg.log_dir = args.output_dir
- if args.lora_targets: cfg.lora_targets = tuple(args.lora_targets)
- if args.train_datasets: cfg.train_datasets = tuple(args.train_datasets)
- if args.val_datasets: cfg.val_datasets = tuple(args.val_datasets)
- if args.include_static: cfg.include_static = True
- if args.no_grad_ckpt: cfg.grad_ckpt = False
- if args.no_resume: cfg.resume = False
-
- print("=" * 72)
- print(f"encoder : {cfg.encoder_id} LoRA r={cfg.lora_r} on {cfg.lora_targets}")
- print(f"clip : T={cfg.clip_len} stride={cfg.clip_stride} batch={cfg.batch_size} clips "
- f"x accum {cfg.accum_steps} = {cfg.batch_size*cfg.accum_steps*cfg.clip_len} frames/update")
- print(f"lr : decoder {cfg.lr} | adapters {cfg.lora_lr} | wd {cfg.weight_decay}")
- print(f"train : {cfg.train_datasets} | static={cfg.include_static} | val {cfg.val_datasets}")
- print(f"budget : {cfg.epochs} epochs, stop at {cfg.max_hours} h, "
- f"grad_ckpt={cfg.grad_ckpt}, resume={cfg.resume}")
- print(f"NOTE : no feature cache is possible with LoRA -- the encoder moves.")
- print("=" * 72)
-
- W = np.load(cfg.kp_regressor_path)
- mhr = base.MHRForwardPass(cfg.mhr_model_path, device, kp_regressor=W)
- enc = TrainableEncoder(cfg)
- dec = probe.ClipPoseDecoder(cfg, enc.embed_dim, enc.grid).to(device)
- criterion = base.DistillationLoss(cfg, mhr).to(device)
- print(f" decoder {sum(q.numel() for q in dec.parameters())/1e6:.2f} M trainable")
-
- train_loader, val_loader = build_loaders(cfg)
-
- enc_params = [q for q in enc.parameters() if q.requires_grad]
- opt = torch.optim.AdamW(
- [{"params": enc_params, "lr": cfg.lora_lr, "weight_decay": 0.0},
- {"params": list(dec.parameters()), "lr": cfg.lr, "weight_decay": cfg.weight_decay}])
- scaler = torch.amp.GradScaler(device="cuda", enabled=cfg.use_amp)
- spe = max(1, len(train_loader) // cfg.accum_steps)
- sched = torch.optim.lr_scheduler.OneCycleLR(
- opt, max_lr=[cfg.lora_lr, cfg.lr], epochs=cfg.epochs,
- steps_per_epoch=spe, pct_start=cfg.warmup_pct)
-
- os.makedirs(cfg.log_dir, exist_ok=True)
- ckpt_path = os.path.join(cfg.log_dir, "levjepa_lora_last.pth")
- best_path = os.path.join(cfg.log_dir, "levjepa_lora_best.pth")
- start_ep, best, no_imp, gstep = 0, float("inf"), 0, 0
-
- if cfg.resume and os.path.exists(ckpt_path):
- ck = torch.load(ckpt_path, map_location=device, weights_only=False)
- enc.load_state_dict(ck["encoder"], strict=False) # LoRA only; base is frozen
- dec.load_state_dict(ck["decoder"])
- opt.load_state_dict(ck["optimizer"]); scaler.load_state_dict(ck["scaler"])
- sched.load_state_dict(ck["scheduler"])
- start_ep, best, gstep = ck["epoch"] + 1, ck.get("best", float("inf")), ck.get("gstep", 0)
- print(f" resumed from epoch {start_ep} (best val PA {best:.1f} mm)")
-
- def save(path, ep):
- torch.save({"encoder": {k: v for k, v in enc.state_dict().items()
- if (".A" in k or ".B" in k)}, # adapters only, ~10 MB
- "decoder": dec.state_dict(), "optimizer": opt.state_dict(),
- "scaler": scaler.state_dict(), "scheduler": sched.state_dict(),
- "epoch": ep, "best": best, "gstep": gstep,
- # plain dict, not the dataclass: a pickled LoRAConfig cannot be
- # unpickled without importing this module, which makes the
- # checkpoint unreadable from an inference/eval script.
- "cfg": asdict(cfg)}, path)
-
- t_start = time.time()
- stop = False
- for ep in range(start_ep, cfg.epochs):
- enc.train(); dec.train()
- tm, th, nb = defaultdict(float), defaultdict(float), 0
- bar = tqdm(train_loader, desc=f"ep{ep+1}/{cfg.epochs}",
- disable=not sys.stderr.isatty(), mininterval=60.0)
- opt.zero_grad(set_to_none=True)
- for it, b in enumerate(bar):
- b = {k: v.to(device, non_blocking=True) for k, v in b.items()}
- flat = probe.flatten_clip(b)
- with torch.amp.autocast(device_type="cuda", dtype=torch.float16, enabled=cfg.use_amp):
- patch = enc(b["image"])
- preds16 = dec(patch, b["cliff_cond"])
- preds = {k: v.float() for k, v in preds16.items()}
- losses = criterion(preds, flat)
- total = losses["total_loss"]
- if not torch.isfinite(total) or total.item() > cfg.anomaly_loss_threshold:
- tm["skipped"] += 1
- opt.zero_grad(set_to_none=True)
- continue
- scaler.scale(total / cfg.accum_steps).backward()
- if (it + 1) % cfg.accum_steps == 0:
- scaler.unscale_(opt)
- torch.nn.utils.clip_grad_norm_(enc_params + list(dec.parameters()), cfg.grad_clip)
- scaler.step(opt); scaler.update()
- opt.zero_grad(set_to_none=True)
- if sched.last_epoch < sched.total_steps - 1:
- sched.step()
- gstep += 1
- criterion.set_step(gstep)
- if cfg.save_every_steps and gstep % cfg.save_every_steps == 0:
- save(ckpt_path, ep - 1)
- for k, v in losses.items():
- tm[k] += float(v)
- nb += 1
- if (time.time() - t_start) / 3600.0 > cfg.max_hours:
- print(f"\n time budget {cfg.max_hours} h reached -- checkpointing and stopping")
- stop = True
- break
- bar.close()
-
- enc.eval(); dec.eval()
- vm, vh, n = defaultdict(float), defaultdict(float), 0
- with torch.no_grad():
- for b in tqdm(val_loader, desc="val", disable=not sys.stderr.isatty(),
- mininterval=60.0):
- b = {k: v.to(device, non_blocking=True) for k, v in b.items()}
- flat = probe.flatten_clip(b)
- with torch.amp.autocast(device_type="cuda", dtype=torch.float16, enabled=cfg.use_amp):
- preds16 = dec(enc(b["image"]), b["cliff_cond"])
- preds = {k: v.float() for k, v in preds16.items()}
- l = criterion(preds, flat)
- if not torch.isfinite(l["total_loss"]):
- continue
- for k, v in l.items():
- vm[k] += float(v)
- for k, v in base.evaluate_hmr_batch(preds, flat, cfg, mhr).items():
- vh[k] += v
- n += 1
- vm = {k: v / max(n, 1) for k, v in vm.items()}
- vh = {k: v / max(n, 1) for k, v in vh.items()}
- tm = {k: v / max(nb, 1) for k, v in tm.items()}
-
- el = (time.time() - t_start) / 3600.0
- print(f"\nEpoch {ep+1}/{cfg.epochs} | {el:.2f} h elapsed | lr "
- f"{sched.get_last_lr()[0]:.2e}/{sched.get_last_lr()[1]:.2e} "
- f"| skipped {int(tm.get('skipped',0))}")
- print(f" [train] tot {tm['total_loss']:.4f} | 3d {tm.get('loss_3d_native',0):.4f} "
- f"| 2d {tm.get('loss_2d_native',0):.4f} | pose {tm.get('loss_pose',0):.4f}")
- print(f" [val ] tot {vm['total_loss']:.4f} | Mesh PA {vh['Mesh_PA_MPJPE']:.1f} "
- f"| Mesh MPJPE {vh['Mesh_MPJPE']:.1f} | Mesh52 PA {vh['Mesh52_PA_MPJPE']:.1f} mm")
- save(ckpt_path, ep)
- if vh["Mesh_PA_MPJPE"] < best:
- best, no_imp = vh["Mesh_PA_MPJPE"], 0
- save(best_path, ep)
- print(f" new best {best:.1f} mm -> {os.path.basename(best_path)}")
- else:
- no_imp += 1
- if no_imp >= cfg.early_stop_patience:
- print(f" early stop: no improvement for {no_imp} epochs")
- break
- if stop:
- break
-
- print(f"\nBest val Mesh PA-MPJPE: {best:.1f} mm ({(time.time()-t_start)/3600:.2f} h)")
-
-
-if __name__ == "__main__":
- main()
diff --git a/instanthmr_distill_train/train_levjepa_probe.py b/instanthmr_distill_train/train_levjepa_probe.py
deleted file mode 100644
index 99b4e32..0000000
--- a/instanthmr_distill_train/train_levjepa_probe.py
+++ /dev/null
@@ -1,756 +0,0 @@
-#!/usr/bin/env python3
-"""Frozen-LeVJEPA probe for clip-level MHR regression.
-
-WHAT THIS IS
-------------
-The cheapest honest test of "does a video world model represent human motion
-better than a per-frame CNN". A frozen LeVJEPA-VideoMix-Large encoder turns a
-16-frame clip into spatiotemporal tokens; a small cross-attention decoder reads
-those tokens and emits one MHR parameter set per frame. The encoder never gets
-a gradient.
-
-Everything downstream of the decoder is imported verbatim from
-train_distill_mhr_only.py -- DistillationLoss, MHRForwardPass, the (70,127)
-skeleton->keypoint regressor, evaluate_hmr_batch. That is deliberate: the loss
-and metric contract is per-sample along dim 0, so a (B,T,...) clip flattens to
-(B*T,...) and every existing term applies with no modification. A number from
-this script is directly comparable to a number from the single-image script.
-
-WHAT IT REUSES FROM YOUR DATA
------------------------------
-Nothing needs regenerating. The stored crops are already 224 px with ImageNet
-normalisation, which is LeVJEPA's native input, and every crop already carries
-a full per-frame MHR label. Clips are built by grouping annotations/ on the
-track prefix and walking the 5-digit frame index:
-
- * Harmony4D is stored every 5th source frame (~6 fps), so frame_stride 1 over
- the stored crops gives ~6 fps -- close to the ~7.5 fps LeVJEPA trained on.
- * 3DPW is stored contiguously (~30 fps), so frame_stride 4 gives ~7.5 fps,
- which is exactly on-distribution. 3DPW is the in-the-wild eval set;
- Harmony4D is the training set.
-
-Crops are re-centred per frame, so the pixels lose global translation -- but
-cliff_cond = [cx_norm, cy_norm, b_scale] carries the per-frame box trajectory,
-so the decoder can recover it. That is why no tube-cropping is needed to start.
-
-ATTENTION MODE -- DO NOT CHANGE
--------------------------------
-The weights are the EMA encoder trained with attn_mode="block_causal"
-(bidirectional within a frame, causal across frames, CLS a read-only sink).
-Running them under full attention raises no error and silently returns worse
-features. The dense (B,1,N,N) mask this requires also disqualifies SDPA's flash
-kernel, so peak memory is higher than a full-attention ViT-L at equal batch --
-that is expected, not a bug. Use --clip_len to trade it down.
-"""
-from __future__ import annotations
-
-import argparse
-import contextlib
-import io
-import math
-import os
-import re
-import sys
-import time
-from collections import defaultdict
-from dataclasses import dataclass, field
-from pathlib import Path
-
-import numpy as np
-import torch
-import torch.nn as nn
-from torch.utils.data import DataLoader, Dataset
-from tqdm import tqdm
-
-HERE = Path(__file__).resolve().parent
-sys.path.insert(0, str(HERE))
-
-# The base module prints a banner and probes ORT providers at import time.
-with contextlib.redirect_stdout(io.StringIO()):
- import train_distill_mhr_only as base
-
-device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
-
-ENCODER_ID = "galilai-group/LeVJEPA-VideoMix-Large"
-# ImageNet stats -- identical to what SAM3DStudentDataset already applies, so
-# the stored crops need no re-normalisation.
-PATCH = 16
-
-
-# ============================================================
-# Config
-# ============================================================
-@dataclass
-class ProbeConfig:
- data_root: str = str(base.DEFAULT_DATA_ROOT)
- mhr_model_path: str = str(base.PROJECT_ROOT / "checkpoints/mhr_model.pt")
- kp_regressor_path: str = str(base.PROJECT_ROOT / "assets/mhr_j127_to_kp70.npy")
- log_dir: str = str(base.PROJECT_ROOT / "runs/levjepa_probe")
-
- encoder_id: str = ENCODER_ID
- image_size: int = 224
- clip_len: int = 16 # T; RoPE + tubelet 1 means this is free
- clip_stride: int = 8 # temporal stride between successive clips
- # per-dataset stride over the STORED crops, chosen to land near 7.5 fps
- frame_stride: dict = field(default_factory=lambda: {
- "sam3d_gt_harmony4d": 1, # stored @ ~6 fps already
- "sam3d_gt_3dpw": 4, # stored @ ~30 fps -> 7.5 fps
- "sam3d_distill_mix": 1,
- })
- train_datasets: tuple = ("sam3d_gt_harmony4d",)
- val_datasets: tuple = ("sam3d_gt_3dpw",)
- max_clips: int | None = None
- val_max_clips: int | None = 400
-
- # decoder
- d_model: int = 512
- n_heads: int = 8
- n_decoder_layers: int = 4
- dropout: float = 0.1
- decoder_mode: str = "perframe" # "perframe" | "global"
-
- # dims mirrored from the single-image student so the heads/losses match
- pose_dim: int = 136
- scale_dim: int = 68
- shape_dim: int = 45
- cam_dim: int = 3
- cliff_dim: int = 3
- num_joints: int = 70
- kp2d_bins: int = 96
- kp2d_range: float = 1.5
-
- @property
- def model_params_dim(self) -> int:
- return self.pose_dim + self.scale_dim
-
- # optimisation
- batch_size: int = 2 # clips, not frames
- lr: float = 3e-4
- weight_decay: float = 1e-4
- epochs: int = 20
- grad_clip: float = 1.0
- use_amp: bool = True
- num_workers: int = 4
- anomaly_loss_threshold: float = 100.0
-
- # loss weights -- identical to train_distill_mhr_only defaults
- w_pose: float = 1.0
- w_scale: float = 0.1
- w_shape: float = 1.0
- w_cam: float = 0.1
- w_keypoints3d: float = 2.0
- w_keypoints2d: float = 10.0
- w_simcc: float = 1.0
- w_3d_joints: float = 1e-3
- w_reproj: float = 0.01
- kp3d_warmup_steps: int = 500
-
- # only consulted for the legacy Mesh52_* metric
- native_mapping_ids: list = field(default_factory=lambda: base.DistillConfig().native_mapping_ids)
- mhr_mapping_ids: list = field(default_factory=lambda: base.DistillConfig().mhr_mapping_ids)
-
- cache_dir: str | None = None
- cache_clips: int = 0
- # Average-pool the cached 14x14 token grid to PxP before storing. 7 cuts the
- # cache 4x (64 GB -> 16 GB for 10k clips), which matters more than it looks:
- # a memmap larger than RAM is read randomly every epoch, thrashes page cache
- # and gets the job killed by systemd-oomd. 7x7 also happens to match the
- # RepViT student's memory resolution, making the comparison apples-to-apples.
- cache_pool: int = 7
-
-
-# ============================================================
-# Clip index + dataset
-# ============================================================
-# Non-greedy prefix + open-ended index: hardcoding \d{5} silently dropped every
-# family numbering frames with 6 digits (pilates/workout/dance inside
-# sam3d_distill_mix -- ~25k frames of real video).
-TRACK_RE = re.compile(r"^(.+?)_(\d+)_p(\d+)$")
-
-# Families that sit inside a "video" folder but are STILL IMAGES. With the
-# looser regex above they would otherwise chain consecutive COCO image ids into
-# fake tracks, feeding the model 16 unrelated photos as one clip. They are also
-# already in sam3d_gt_coco (8,514 of 10,656 crop ids identical), so skipping
-# them here loses no data.
-STATIC_IN_VIDEO_PREFIXES = ("train2014_COCO",)
-
-
-def build_clip_index(pairs, frame_stride, clip_len, clip_stride, datasets=None):
- """Group (img, npz) pairs into temporally ordered clips.
-
- Returns a list of lists of indices into `pairs`, each of length clip_len.
- """
- tracks = defaultdict(list)
- for i, (img_path, npz_path) in enumerate(pairs):
- sub = npz_path.parent.parent.name
- if datasets is not None and sub not in datasets:
- continue
- if npz_path.stem.startswith(STATIC_IN_VIDEO_PREFIXES):
- continue
- m = TRACK_RE.match(npz_path.stem)
- if not m:
- continue
- tracks[(sub, m.group(1), m.group(3))].append((int(m.group(2)), i))
-
- clips = []
- for (sub, _, _), frames in tracks.items():
- frames.sort()
- step = frame_stride.get(sub, 1)
- idx = [i for _, i in frames][::step]
- if len(idx) < clip_len:
- continue
- for s in range(0, len(idx) - clip_len + 1, clip_stride):
- clips.append(idx[s:s + clip_len])
- return clips
-
-
-class ClipDataset(Dataset):
- """Wraps SAM3DStudentDataset and returns T consecutive frames as one item.
-
- Every per-frame label (cliff_cond, joints_2d in crop space, MHR params, the
- augmentation bookkeeping) comes from the base dataset unchanged, so a frame
- here is byte-identical to a sample in the single-image pipeline.
- """
-
- def __init__(self, cfg: ProbeConfig, datasets, max_clips=None, augment=False,
- base_ds=None):
- self.cfg = cfg
- # base_ds lets callers share ONE scan of the corpus. Building a second
- # SAM3DStudentDataset costs another ~1.6 GB of resident Path objects,
- # which every forked DataLoader worker then copies.
- if base_ds is not None:
- self.base = base_ds
- else:
- with contextlib.redirect_stdout(io.StringIO()):
- self.base = base.SAM3DStudentDataset(
- cfg.data_root, augment=augment, image_size=cfg.image_size,
- max_images=None, per_dataset_caps=None)
- self.clips = build_clip_index(
- self.base.pairs, cfg.frame_stride, cfg.clip_len, cfg.clip_stride,
- datasets=set(datasets))
- if max_clips is not None and len(self.clips) > max_clips:
- rng = np.random.RandomState(0)
- sel = rng.choice(len(self.clips), max_clips, replace=False)
- self.clips = [self.clips[i] for i in sorted(sel)]
- print(f" {'/'.join(datasets)}: {len(self.clips)} clips "
- f"of {cfg.clip_len} frames (stride {cfg.clip_stride})")
-
- def __len__(self):
- return len(self.clips)
-
- def __getitem__(self, i):
- frames = [self.base[j] for j in self.clips[i]]
- out = {}
- for k in frames[0]:
- vals = [f[k] for f in frames]
- # the base dataset returns bbox_square as a raw np.ndarray while
- # everything else is already a tensor -- normalise before stacking.
- vals = [v if torch.is_tensor(v) else torch.as_tensor(np.asarray(v))
- for v in vals]
- out[k] = torch.stack(vals, 0).float()
- return out
-
-
-def flatten_clip(batch):
- """(B,T,...) -> (B*T,...) so the single-image losses/metrics apply as-is."""
- return {k: v.flatten(0, 1) if isinstance(v, torch.Tensor) and v.dim() >= 2
- else v for k, v in batch.items()}
-
-
-
-# ============================================================
-# Feature cache
-# ============================================================
-LABEL_KEYS = ("cliff_cond", "mhr_model_params", "shape_params", "cam_trans",
- "cam_focal", "joints_2d", "joints_3d", "orig_shape", "bbox_square",
- "aug_active", "aug_flip", "aug_cos", "aug_sin", "aug_M")
-
-
-def build_cache(cfg, enc, ds, out_dir, tag, batch=4):
- """Encode every clip once and memmap the result.
-
- Only valid because the encoder is frozen AND augment=False, so a clip's
- features are deterministic. Labels are cached alongside (a few hundred MB)
- so the training loop never has to decode a PNG again -- that is what turns
- an 82 min epoch into a 2 min one.
- """
- out_dir = Path(out_dir); out_dir.mkdir(parents=True, exist_ok=True)
- g_out = cfg.cache_pool or enc.grid
- n, T, N, C = len(ds), cfg.clip_len, g_out ** 2, enc.embed_dim
- fpath = out_dir / f"feats_{tag}.npy"
- lpath = out_dir / f"labels_{tag}.pt"
- if fpath.exists() and lpath.exists():
- print(f" cache hit: {fpath.name} ({fpath.stat().st_size/2**30:.1f} GiB)")
- return fpath, lpath
- gb = n * T * N * C * 2 / 2**30
- print(f" building cache {tag}: {n} clips -> {fpath.name} ({gb:.1f} GiB)")
- feats = np.lib.format.open_memmap(fpath, mode="w+", dtype=np.float16,
- shape=(n, T, N, C))
- loader = DataLoader(ds, batch_size=batch, shuffle=False,
- num_workers=cfg.num_workers, pin_memory=True)
- labels = {k: [] for k in LABEL_KEYS}
- i = 0
- for b in tqdm(loader, desc=f"encode {tag}",
- disable=not sys.stderr.isatty(), mininterval=30.0):
- img = b["image"].to(device, non_blocking=True)
- with torch.no_grad():
- patch, _ = enc(img)
- k = patch.shape[0]
- if g_out != enc.grid:
- pt = patch.reshape(k * T, enc.grid, enc.grid, C).permute(0, 3, 1, 2)
- pt = torch.nn.functional.adaptive_avg_pool2d(pt, g_out)
- patch = pt.permute(0, 2, 3, 1).reshape(k, T, N, C)
- feats[i:i + k] = patch.to(torch.float16).cpu().numpy()
- for key in LABEL_KEYS:
- if key in b:
- labels[key].append(b[key].clone())
- i += k
- feats.flush(); del feats
- torch.save({k: torch.cat(v) for k, v in labels.items() if v}, lpath)
- print(f" cached {i} clips -> {fpath} ({gb:.1f} GiB) + {lpath.name}")
- return fpath, lpath
-
-
-class CachedClipDataset(Dataset):
- """Serves precomputed LeVJEPA features + labels. No image I/O at all."""
-
- def __init__(self, feats_path, labels_path):
- self.feats = np.load(feats_path, mmap_mode="r")
- self.labels = torch.load(labels_path, weights_only=False)
- self.n = self.feats.shape[0]
-
- def __len__(self):
- return self.n
-
- def __getitem__(self, i):
- out = {k: v[i] for k, v in self.labels.items()}
- out["feat"] = torch.from_numpy(np.array(self.feats[i])) # fp16; cast on GPU
- return out
-
-
-# ============================================================
-# Frozen encoder
-# ============================================================
-class LeVJEPAEncoder(nn.Module):
- """Frozen LeVJEPA-L. Returns per-frame patch tokens and the CLS register."""
-
- def __init__(self, encoder_id=ENCODER_ID, dtype=torch.float16):
- super().__init__()
- from transformers import AutoModel
- self.net = AutoModel.from_pretrained(
- encoder_id, trust_remote_code=True).eval().to(dtype)
- # attn_mode is left exactly as shipped ("block_causal"). Overriding it
- # to full attention does not error, it silently degrades the features.
- self.dtype = dtype
- self.embed_dim = int(self.net.config.embed_dim)
- self.grid = int(self.net.config.img_size // self.net.config.patch_size)
- for p in self.net.parameters():
- p.requires_grad_(False)
-
- @torch.no_grad()
- def forward(self, images):
- """images (B,T,3,H,W) -> patch (B,T,grid*grid,C), cls (B,C)."""
- B, T = images.shape[:2]
- x = images.permute(0, 2, 1, 3, 4).to(self.dtype) # (B,3,T,H,W)
- out = self.net(x)
- tok = out[0] if isinstance(out, (tuple, list)) else \
- getattr(out, "last_hidden_state", out)
- cls, patch = tok[:, :1], tok[:, 1:]
- n = self.grid * self.grid
- assert patch.shape[1] == T * n, \
- f"expected {T*n} patch tokens, got {patch.shape[1]}"
- return patch.reshape(B, T, n, -1).float(), cls[:, 0].float()
-
-
-# ============================================================
-# Decoder
-# ============================================================
-def sincos_1d(dim, pos):
- omega = torch.arange(dim // 2, dtype=torch.float32) / (dim / 2.0)
- omega = 1.0 / (10000 ** omega)
- out = pos.float().unsqueeze(1) * omega.unsqueeze(0)
- return torch.cat([torch.sin(out), torch.cos(out)], dim=1)
-
-
-def sincos_3d(dim, T, H, W):
- """(T*H*W, dim) sin-cos embedding split across the time/height/width axes."""
- dt = dim // 4
- dh = dw = (dim - dt) // 2
- dt = dim - dh - dw
- t = torch.arange(T).repeat_interleave(H * W)
- h = torch.arange(H).repeat_interleave(W).repeat(T)
- w = torch.arange(W).repeat(T * H)
- return torch.cat([sincos_1d(dt, t), sincos_1d(dh, h), sincos_1d(dw, w)], 1)
-
-
-class ClipPoseDecoder(nn.Module):
- """Cross-attention decoder over frozen LeVJEPA tokens -> per-frame MHR.
-
- decoder_mode:
- "perframe" (default) -- each frame's queries attend to that frame's 196
- tokens only. The encoder has already fused time (block-causal), so this
- keeps the decoder a direct analogue of the single-image model's 7x7
- memory, at 14x14 resolution and a fraction of the cost.
- "global" -- queries attend to all T*196 tokens at once. Strictly more
- expressive, ~T times the cross-attention cost.
- """
-
- def __init__(self, cfg: ProbeConfig, embed_dim, grid):
- super().__init__()
- self.cfg, self.grid = cfg, grid
- self.mode = cfg.decoder_mode
- self.num_2d = cfg.num_joints
- self.num_q = 1 + cfg.num_joints # 71, same as the student
-
- self.feat_proj = nn.Linear(embed_dim, cfg.d_model)
- if self.mode == "perframe":
- pe = base.get_2d_sincos_pos_embed(cfg.d_model, grid)
- else:
- pe = sincos_3d(cfg.d_model, cfg.clip_len, grid, grid).unsqueeze(0)
- self.register_buffer("mem_pos_embed", pe)
-
- self.query_embed = nn.Parameter(torch.randn(1, self.num_q, cfg.d_model) * 0.02)
- self.temporal_embed = nn.Parameter(
- torch.randn(1, cfg.clip_len, 1, cfg.d_model) * 0.02)
- self.cond_proj = nn.Sequential(
- nn.Linear(cfg.cliff_dim, 128), nn.GELU(), nn.Linear(128, cfg.d_model))
-
- layer = nn.TransformerDecoderLayer(
- d_model=cfg.d_model, nhead=cfg.n_heads,
- dim_feedforward=cfg.d_model * 4, dropout=cfg.dropout,
- activation="gelu", batch_first=True, norm_first=True)
- self.transformer = nn.TransformerDecoder(layer, num_layers=cfg.n_decoder_layers)
-
- self.global_out_dim = cfg.model_params_dim + cfg.shape_dim + cfg.cam_dim
- self.head_global = nn.Linear(cfg.d_model, self.global_out_dim)
- self.head_2d_feat = nn.Sequential(nn.Linear(cfg.d_model, 256), nn.GELU())
- self.head_2d_logits = nn.Linear(256, 2 * cfg.kp2d_bins)
- self.register_buffer("kp2d_bin_centers",
- torch.linspace(-cfg.kp2d_range, cfg.kp2d_range, cfg.kp2d_bins))
-
- # identical init to InstantHMRStudent: near-zero heads, cam z bias 2.0
- nn.init.normal_(self.head_global.weight, mean=0.0, std=1e-4)
- nn.init.constant_(self.head_global.bias[:-3], 0.0)
- nn.init.constant_(self.head_global.bias[-1], 2.0)
- nn.init.constant_(self.head_global.bias[-2], 0.0)
- nn.init.constant_(self.head_global.bias[-3], 0.0)
- nn.init.normal_(self.head_2d_logits.weight, mean=0.0, std=1e-4)
- nn.init.constant_(self.head_2d_logits.bias, 0.0)
-
- def forward(self, patch_tokens, cliff_cond):
- """patch (B,T,N,C), cliff (B,T,3) -> dict of (B*T, ...)."""
- B, T, N, _ = patch_tokens.shape
- mem = self.feat_proj(patch_tokens) # (B,T,N,d)
-
- q = self.query_embed.expand(B * T, -1, -1)
- # slice, don't assume T == cfg.clip_len: still images are encoded as
- # T=1 clips, which costs 197 tokens instead of 3137 for the same single
- # label -- 16x cheaper than repeating the frame to fill the clip.
- q = q + self.temporal_embed[:, :T].expand(B, -1, -1, -1).reshape(B * T, 1, -1)
- q = q + self.cond_proj(cliff_cond).reshape(B * T, 1, -1)
-
- if self.mode == "perframe":
- m = (mem + self.mem_pos_embed).reshape(B * T, N, -1)
- else:
- m = (mem.reshape(B, T * N, -1) + self.mem_pos_embed)
- m = m.unsqueeze(1).expand(B, T, T * N, m.shape[-1]).reshape(B * T, T * N, -1)
- feats = self.transformer(tgt=q, memory=m)
-
- g = self.head_global(feats[:, 0, :])
- i_mhr = self.cfg.model_params_dim
- i_shape = i_mhr + self.cfg.shape_dim
-
- logits = self.head_2d_logits(self.head_2d_feat(feats[:, 1:1 + self.num_2d, :]))
- logits = logits.reshape(B * T, self.num_2d, 2, self.cfg.kp2d_bins)
- joints_2d = (logits.softmax(-1) * self.kp2d_bin_centers).sum(-1)
-
- return {
- "mhr_params": g[:, :i_mhr],
- "shape_params": g[:, i_mhr:i_shape],
- "cam_trans": g[:, i_shape:],
- "joints_2d": joints_2d,
- "joints_2d_logits": logits,
- }
-
-
-# ============================================================
-# Train / eval
-# ============================================================
-def run_epoch(enc, dec, loader, criterion, cfg, mhr, optimizer=None,
- scaler=None, step0=0, tag="train"):
- train = optimizer is not None
- dec.train(train)
- meters = defaultdict(float)
- hmr = defaultdict(float)
- n = 0
- step = step0
- bar = tqdm(loader, desc=f"[{tag}]", leave=False,
- disable=not sys.stderr.isatty(), mininterval=30.0)
- for batch in bar:
- batch = {k: v.to(device, non_blocking=True) for k, v in batch.items()}
- flat = flatten_clip({k: v for k, v in batch.items() if k != "feat"})
- if "feat" in batch: # cached path: no encoder call
- patch = batch["feat"].float()
- else:
- with torch.amp.autocast(device_type="cuda", dtype=torch.float16, enabled=cfg.use_amp):
- patch, _ = enc(batch["image"])
- ctx = contextlib.nullcontext() if train else torch.no_grad()
- with ctx:
- with torch.amp.autocast(device_type="cuda", dtype=torch.float16, enabled=cfg.use_amp):
- preds16 = dec(patch, batch["cliff_cond"])
- preds = {k: v.float() for k, v in preds16.items()}
- losses = criterion(preds, flat)
- total = losses["total_loss"]
- if train:
- if not torch.isfinite(total) or total.item() > cfg.anomaly_loss_threshold:
- meters["skipped"] += 1
- optimizer.zero_grad(set_to_none=True)
- continue
- optimizer.zero_grad(set_to_none=True)
- scaler.scale(total).backward()
- scaler.unscale_(optimizer)
- torch.nn.utils.clip_grad_norm_(dec.parameters(), cfg.grad_clip)
- scaler.step(optimizer)
- scaler.update()
- step += 1
- criterion.set_step(step)
- for k, v in losses.items():
- meters[k] += float(v)
- bm = base.evaluate_hmr_batch(preds, flat, cfg, mhr)
- for k, v in bm.items():
- hmr[k] += v
- n += 1
- bar.set_postfix({"tot": f"{float(total):.3f}",
- "PA": f"{hmr.get('Mesh_PA_MPJPE',0)/max(n,1):.1f}"})
- bar.close()
- return ({k: v / max(n, 1) for k, v in meters.items()},
- {k: v / max(n, 1) for k, v in hmr.items()}, step)
-
-
-def main():
- p = argparse.ArgumentParser(description=__doc__,
- formatter_class=argparse.RawDescriptionHelpFormatter)
- p.add_argument("--data_root", default=None)
- p.add_argument("--output_dir", default=None)
- p.add_argument("--mhr_model_path", default=None)
- p.add_argument("--kp_regressor_path", default=None)
- p.add_argument("--clip_len", type=int, default=None,
- help="Frames per clip (T). Lower it if memory is tight: RoPE + "
- "tubelet 1 make T a free parameter.")
- p.add_argument("--clip_stride", type=int, default=None)
- p.add_argument("--batch_size", type=int, default=None, help="CLIPS per batch.")
- p.add_argument("--epochs", type=int, default=None)
- p.add_argument("--lr", type=float, default=None)
- p.add_argument("--num_workers", type=int, default=None)
- p.add_argument("--max_clips", type=int, default=None)
- p.add_argument("--decoder_mode", choices=["perframe", "global"], default=None)
- p.add_argument("--train_datasets", nargs="+", default=None)
- p.add_argument("--val_datasets", nargs="+", default=None)
- p.add_argument("--self-test", dest="self_test", action="store_true",
- help="Shape/contract checks on a couple of clips, then exit.")
- p.add_argument("--overfit-test", dest="overfit_test", action="store_true")
- p.add_argument("--overfit-steps", dest="overfit_steps", type=int, default=300)
- p.add_argument("--cache_dir", default=None,
- help="Precompute and memmap encoder features here. Only valid with a "
- "FROZEN encoder and augment=False; turns an 82 min epoch into ~2 min.")
- p.add_argument("--cache_pool", type=int, default=None,
- help="Pool the cached token grid to PxP (default 7). 0/14 keeps 14x14 "
- "but a >RAM cache thrashes page cache and invites the OOM killer.")
- p.add_argument("--seed", type=int, default=0)
- args = p.parse_args()
-
- torch.manual_seed(args.seed); np.random.seed(args.seed)
- cfg = ProbeConfig()
- for k in ("data_root", "mhr_model_path", "kp_regressor_path", "clip_len",
- "clip_stride", "batch_size", "epochs", "lr", "num_workers",
- "max_clips", "decoder_mode"):
- v = getattr(args, k)
- if v is not None:
- setattr(cfg, k, v)
- if args.cache_dir: cfg.cache_dir = args.cache_dir
- if args.cache_pool is not None: cfg.cache_pool = args.cache_pool
- if args.output_dir: cfg.log_dir = args.output_dir
- if args.train_datasets: cfg.train_datasets = tuple(args.train_datasets)
- if args.val_datasets: cfg.val_datasets = tuple(args.val_datasets)
-
- print("=" * 66)
- print(f"encoder : {cfg.encoder_id} (FROZEN, fp16, attn_mode untouched)")
- print(f"clip : T={cfg.clip_len} stride={cfg.clip_stride} "
- f"decoder={cfg.decoder_mode} batch={cfg.batch_size} clips "
- f"({cfg.batch_size*cfg.clip_len} frames)")
- print(f"train : {cfg.train_datasets} val: {cfg.val_datasets}")
- print(f"frame_stride : {cfg.frame_stride}")
- print("=" * 66)
-
- W = np.load(cfg.kp_regressor_path)
- mhr = base.MHRForwardPass(cfg.mhr_model_path, device, kp_regressor=W)
- enc = LeVJEPAEncoder(cfg.encoder_id).to(device)
- dec_grid = (cfg.cache_pool if (cfg.cache_dir and cfg.cache_pool) else enc.grid)
- dec = ClipPoseDecoder(cfg, enc.embed_dim, dec_grid).to(device)
- print(f" encoder {sum(p.numel() for p in enc.parameters())/1e6:.1f} M frozen | "
- f"decoder {sum(p.numel() for p in dec.parameters())/1e6:.2f} M trainable")
-
- criterion = base.DistillationLoss(cfg, mhr).to(device)
-
- if args.self_test:
- run_self_test(cfg, enc, dec, mhr, criterion)
- return
-
- train_ds = ClipDataset(cfg, cfg.train_datasets, max_clips=cfg.max_clips)
- val_ds = ClipDataset(cfg, cfg.val_datasets, max_clips=cfg.val_max_clips)
-
- if cfg.cache_dir:
- ftr, ltr = build_cache(cfg, enc, train_ds, cfg.cache_dir, "train")
- fva, lva = build_cache(cfg, enc, val_ds, cfg.cache_dir, "val")
- train_ds, val_ds = CachedClipDataset(ftr, ltr), CachedClipDataset(fva, lva)
- # the encoder is dead weight from here on -- free ~600 MiB of VRAM
- enc.net.to("cpu"); torch.cuda.empty_cache()
- print(f" training from cache: {len(train_ds)} train / {len(val_ds)} val clips "
- f"(encoder moved to CPU)")
-
- bs = cfg.batch_size if not cfg.cache_dir else max(cfg.batch_size, 8)
- dl = lambda ds, sh: DataLoader(ds, batch_size=bs, shuffle=sh,
- num_workers=cfg.num_workers, pin_memory=True,
- drop_last=sh)
- train_loader, val_loader = dl(train_ds, True), dl(val_ds, False)
-
- opt = torch.optim.AdamW(dec.parameters(), lr=cfg.lr, weight_decay=cfg.weight_decay)
- scaler = torch.amp.GradScaler(device="cuda", enabled=cfg.use_amp)
-
- if args.overfit_test:
- run_overfit(cfg, enc, dec, mhr, criterion, train_loader, opt, scaler,
- args.overfit_steps)
- return
-
- os.makedirs(cfg.log_dir, exist_ok=True)
- best = float("inf")
- step = 0
- for ep in range(cfg.epochs):
- tm, th, step = run_epoch(enc, dec, train_loader, criterion, cfg, mhr,
- opt, scaler, step, f"ep{ep+1} train")
- vm, vh, _ = run_epoch(enc, dec, val_loader, criterion, cfg, mhr,
- tag=f"ep{ep+1} val")
- print(f"\nEpoch {ep+1}/{cfg.epochs}")
- print(f" [train] tot {tm['total_loss']:.4f} | 3d {tm.get('loss_3d_native',0):.4f} "
- f"| 2d {tm.get('loss_2d_native',0):.4f} | Mesh PA {th['Mesh_PA_MPJPE']:.1f} mm")
- print(f" [val ] tot {vm['total_loss']:.4f} | Mesh PA {vh['Mesh_PA_MPJPE']:.1f} "
- f"| Mesh MPJPE {vh['Mesh_MPJPE']:.1f} | Mesh52 PA {vh['Mesh52_PA_MPJPE']:.1f} mm")
- if vh["Mesh_PA_MPJPE"] < best:
- best = vh["Mesh_PA_MPJPE"]
- torch.save({"decoder": dec.state_dict(), "cfg": cfg, "epoch": ep,
- "val_pa": best}, os.path.join(cfg.log_dir, "best_decoder.pth"))
- print(f" new best {best:.1f} mm -> best_decoder.pth")
- print(f"\nBest val Mesh PA-MPJPE: {best:.1f} mm")
-
-
-def run_self_test(cfg, enc, dec, mhr, criterion):
- print("\n--- self-test: clip index, encoder contract, loss contract ---")
- ds = ClipDataset(cfg, cfg.train_datasets, max_clips=8)
- assert len(ds) > 0, "no clips built -- check frame_stride / clip_len"
- item = ds[0]
- print(f" clip item: image {tuple(item['image'].shape)} "
- f"cliff {tuple(item['cliff_cond'].shape)} "
- f"mhr {tuple(item['mhr_model_params'].shape)}")
- assert item["image"].shape[0] == cfg.clip_len
-
- batch = {k: torch.stack([ds[0][k], ds[1][k]]).to(device) for k in item}
- with torch.amp.autocast(device_type="cuda", dtype=torch.float16):
- patch, cls = enc(batch["image"])
- B, T = batch["image"].shape[:2]
- print(f" encoder out: patch {tuple(patch.shape)} cls {tuple(cls.shape)} "
- f"(expect ({B},{T},{enc.grid**2},{enc.embed_dim}))")
- assert patch.shape == (B, T, enc.grid ** 2, enc.embed_dim)
-
- with torch.amp.autocast(device_type="cuda", dtype=torch.float16):
- preds16 = dec(patch, batch["cliff_cond"])
- preds = {k: v.float() for k, v in preds16.items()}
- flat = flatten_clip(batch)
- print(f" decoder out: " + " ".join(f"{k}{tuple(v.shape)}" for k, v in preds.items()))
- assert preds["mhr_params"].shape[0] == B * T, "flattening contract broken"
- assert "joints_3d" not in preds, "3D head must not exist (MHR-derived only)"
-
- # Exercise the FK-path losses at full weight: with the warm-up ramp at
- # step 0 they read exactly 0.0 and the test would not cover them at all.
- criterion.warmup_steps = 0
- losses = criterion(preds, flat)
- assert float(losses["loss_3d_native"]) > 0, "FK path not exercised"
- assert float(losses["loss_reproj"]) > 0, "reprojection path not exercised"
- print(" losses (FK warm-up disabled so the MHR path is covered):")
- for k, v in losses.items():
- print(f" {k:20s} {float(v):.6f}")
- assert torch.isfinite(losses["total_loss"])
- m = base.evaluate_hmr_batch(preds, flat, cfg, mhr)
- print(" metrics (untrained decoder, so large is expected):")
- for k, v in m.items():
- print(f" {k:20s} {v:.1f} mm")
- print("\n SELF-TEST PASSED")
-
-
-def run_overfit(cfg, enc, dec, mhr, criterion, loader, opt, scaler, steps):
- print(f"\n--- overfit one clip batch for {steps} steps ---")
- batch = next(iter(loader))
- batch = {k: v.to(device) for k, v in batch.items()}
- flat = flatten_clip(batch)
- with torch.no_grad(), torch.amp.autocast(device_type="cuda", dtype=torch.float16):
- patch, _ = enc(batch["image"]) # frozen -> encode once
- dec.train()
-
- def reg(ls):
- """Same four terms train_distill_mhr_only.run_overfit_test scores on, so
- the two verdicts are comparable. Excludes loss_2d_simcc, whose CE floor
- (~2.1 nats) never goes to zero and would mask the regression fit."""
- return (float(ls['loss_2d_native']) + float(ls['loss_3d_native'])
- + float(ls['loss_cam']) + float(ls['loss_pose']))
-
- first_reg = last_reg = last_pa = None
- best_pa = best_pa52 = float('inf')
- n_skipped = 0
- first = None
- for s in range(steps):
- criterion.set_step(s)
- opt.zero_grad(set_to_none=True)
- with torch.amp.autocast(device_type="cuda", dtype=torch.float16):
- preds16 = dec(patch, batch["cliff_cond"])
- preds = {k: v.float() for k, v in preds16.items()}
- losses = criterion(preds, flat)
- scaler.scale(losses["total_loss"]).backward()
- scaler.unscale_(opt)
- torch.nn.utils.clip_grad_norm_(dec.parameters(), cfg.grad_clip)
- scaler.step(opt); scaler.update()
- if not torch.isfinite(losses["total_loss"]) or \
- float(losses["total_loss"]) > cfg.anomaly_loss_threshold:
- n_skipped += 1
- continue
- if first is None:
- first, first_reg = float(losses["total_loss"]), reg(losses)
- last_reg = reg(losses)
- if s % 50 == 0 or s == steps - 1:
- m = base.evaluate_hmr_batch(preds, flat, cfg, mhr)
- last_pa = m['Mesh_PA_MPJPE']
- best_pa = min(best_pa, last_pa)
- best_pa52 = min(best_pa52, m['Mesh52_PA_MPJPE'])
- print(f" step {s:04d} | tot {float(losses['total_loss']):.3f} "
- f"| reg {last_reg:.4f} "
- f"| 3d {float(losses['loss_3d_native']):.4f} "
- f"| pose {float(losses['loss_pose']):.4f} "
- f"| mhr {float(losses['loss_mhr_joints']):.4f} "
- f"| Mesh [MPJPE: {m['Mesh_MPJPE']:.1f} | PA: {m['Mesh_PA_MPJPE']:.1f}] mm "
- f"| Mesh52 [MPJPE: {m['Mesh52_MPJPE']:.1f} | PA: {m['Mesh52_PA_MPJPE']:.1f}] mm")
-
- # Same 10x-reduction rule as the single-image script. The PA bar is NOT
- # reused: that 55 mm was calibrated for a trainable backbone on 8 stills.
- # Here the encoder is FROZEN, so the decoder can only fit what LeVJEPA's
- # features already linearly expose -- a frozen probe is not expected to
- # drive a batch to zero, and the honest reading is the regression ratio.
- ok = last_reg < first_reg * 0.10
- print(f"\n{'PASS' if ok else 'INCOMPLETE'}: regression loss {first_reg:.4f} -> {last_reg:.5f} "
- f"(ratio {last_reg/max(first_reg,1e-9):.3f}, bar 0.100) "
- f"| best Mesh PA-MPJPE {best_pa:.1f} mm (final {last_pa:.1f}) "
- f"| best Mesh52 PA-MPJPE {best_pa52:.1f} mm "
- f"| total {first:.4f} -> {float(losses['total_loss']):.4f} "
- f"(of which ~{float(losses['loss_2d_simcc']):.2f} is the irreducible SimCC CE) "
- f"| anomalous steps skipped: {n_skipped}")
-
-
-if __name__ == "__main__":
- main()