Skip to content
Python

feat: added kebjepa probe and lora training

mohamdevcde01f4f9af3
diff --git a/instanthmr_distill_train/submit_train_levjepa_lora_dolcino.sh b/instanthmr_distill_train/submit_train_levjepa_lora_dolcino.sh
new file mode 100755
index 0000000..b19a956
--- /dev/null
+++ b/instanthmr_distill_train/submit_train_levjepa_lora_dolcino.sh
@@ -0,0 +1,55 @@
+#!/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_mhr_only.py b/instanthmr_distill_train/train_distill_mhr_only.py
index 74a2394..1e00486 100644
--- a/instanthmr_distill_train/train_distill_mhr_only.py
+++ b/instanthmr_distill_train/train_distill_mhr_only.py
@@ -173,6 +173,10 @@ class DistillConfig:
batch_size: int = 64
lr: float = 3e-4
weight_decay: float = 1e-4
+ # Exclude depthwise-conv kernels, norm params and biases from weight decay
+ # (see build_param_groups). Off by default so existing runs are unchanged;
+ # enable with --split-wd. Applies to every backbone, not just MobileNet.
+ split_weight_decay: bool = False
epochs: int = 400
warmup_epochs: int = 3
grad_clip: float = 1.0
@@ -297,7 +301,11 @@ class SAM3DStudentDataset(Dataset):
if img_path.exists():
sub_pairs.append((img_path, npz_path))
- cap = caps.get(sub_name)
+ # "*" is a default cap applied to every sub-folder that has no
+ # explicit entry — used to build a *balanced* subset for small-scale
+ # ablations. (max_images can't: it slices a path-sorted list, so it
+ # would return a single dataset.)
+ cap = caps.get(sub_name, caps.get("*"))
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])))
@@ -893,6 +901,57 @@ def evaluate_hmr_batch(preds, targets, cfg, mhr_module):
# ============================================================
# Cell 11 — Full Distillation Training Loop
# ============================================================
+def build_param_groups(model, weight_decay, split_wd=True):
+ """AdamW param groups with weight decay removed from the params that should
+ never see it.
+
+ Applying a single weight_decay to `model.parameters()` penalises every
+ tensor equally, which is wrong for three families:
+
+ * **norm parameters** (BatchNorm/LayerNorm weight and bias) — decaying a
+ BN gamma toward 0 shrinks the layer's output scale, which the following
+ layer has to keep re-learning.
+ * **biases** — a bias is an offset, not a capacity knob; decay just
+ re-centres it toward 0 for no regularisation benefit.
+ * **depthwise convolution kernels** — a depthwise filter has only
+ k*k weights per channel (9 for 3x3) instead of C_in*k*k, so an L2
+ penalty of the same magnitude is a far larger *relative* pull on it.
+ MobileNet-family backbones are mostly depthwise, so uniform wd hits
+ them much harder than it hits a conventional/hybrid backbone.
+
+ This is a general recipe fix, not a MobileNet-specific hack -- the same
+ exclusions are standard for RepViT too (both are BN-heavy and RepViT's
+ token mixer is itself depthwise). Use it for every backbone or none, or
+ the comparison just moves the bias to the other side.
+
+ Returns the two-group list AdamW expects.
+ """
+ if not split_wd:
+ return [{"params": list(model.parameters()), "weight_decay": weight_decay}]
+
+ # Names of depthwise conv weights: groups == in_channels (and > 1).
+ depthwise = set()
+ for mod_name, mod in model.named_modules():
+ if isinstance(mod, nn.modules.conv._ConvNd) and mod.groups > 1 \
+ and mod.groups == mod.in_channels:
+ depthwise.add(f"{mod_name}.weight" if mod_name else "weight")
+
+ decay, no_decay = [], []
+ for name, param in model.named_parameters():
+ if not param.requires_grad:
+ continue
+ if name in depthwise or name.endswith(".bias") or param.ndim <= 1:
+ # ndim <= 1 catches every BN/LayerNorm weight and every bias,
+ # including the ones inside nn.TransformerDecoderLayer.
+ no_decay.append(param)
+ else:
+ decay.append(param)
+ return [
+ {"params": decay, "weight_decay": weight_decay},
+ {"params": no_decay, "weight_decay": 0.0},
+ ]
+
+
def make_ema_avg_fn(max_decay):
@torch.no_grad()
def avg_fn(ema_params, model_params, num_averaged):
@@ -915,7 +974,14 @@ def train_instant_hmr():
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)
+ split_wd = getattr(cfg, "split_weight_decay", False)
+ param_groups = build_param_groups(model, cfg.weight_decay, split_wd=split_wd)
+ optimizer = optim.AdamW(param_groups, lr=cfg.lr, weight_decay=cfg.weight_decay)
+ if split_wd:
+ n_dec = sum(p.numel() for p in param_groups[0]["params"])
+ n_nod = sum(p.numel() for p in param_groups[1]["params"])
+ print(f" param groups: wd={cfg.weight_decay} on {n_dec/1e6:.2f} M params | "
+ f"wd=0 on {n_nod/1e6:.2f} M (depthwise kernels, norms, biases)")
scaler = torch.amp.GradScaler(device='cuda', enabled=cfg.use_amp)
steps_per_epoch = len(train_loader)
@@ -1629,6 +1695,10 @@ def parse_args():
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("--cap_all", type=int, default=None,
+ help="Cap EVERY sub-dataset to this many crops (seeded, reproducible). "
+ "Gives a domain-balanced subset for small-scale ablations, unlike "
+ "--max_images, which slices a path-sorted list.")
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",
@@ -1648,6 +1718,15 @@ def parse_args():
help="Weight of the MHR-derived 3D keypoint loss (FK path).")
p.add_argument("--seed", type=int, default=None,
help="Seed torch/numpy/random (for reproducible sanity runs).")
+ p.add_argument("--split-wd", dest="split_wd", action="store_true",
+ help="Exclude depthwise-conv weights, norm params and biases from "
+ "weight decay (standard for BN/depthwise-heavy backbones).")
+ p.add_argument("--backbone", type=str, default=None,
+ help="timm backbone name. Any model whose forward_features() returns a "
+ "stride-32 (B,C,H,W) map works unchanged (the channel count is read "
+ "from .num_features). Tested: repvit_m2_3, repvit_m1_5, "
+ "mobilenetv4_conv_medium, mobilenetv4_hybrid_medium, "
+ "mobilenetv4_conv_large.")
args, unknown = p.parse_known_args()
if unknown:
print(f"⚠️ Ignoring unrecognized arguments: {unknown}")
@@ -1673,6 +1752,8 @@ def main():
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.cap_all is not None:
+ cfg.per_dataset_caps = {"*": args.cap_all}
if args.harmony4d_cap is not None:
if args.harmony4d_cap <= 0:
cfg.per_dataset_caps.pop("sam3d_gt_harmony4d", None)
@@ -1681,6 +1762,17 @@ def main():
if args.no_resume: cfg.resume = False
if args.kp3d_warmup_steps is not None: cfg.kp3d_warmup_steps = args.kp3d_warmup_steps
if args.w_keypoints3d is not None: cfg.w_keypoints3d = args.w_keypoints3d
+ if args.split_wd: cfg.split_weight_decay = True
+ if args.backbone is not None:
+ cfg.backbone = args.backbone
+ # backbone_feat_dim is informational only: InstantHMRStudent reads the real
+ # width from backbone.num_features. Keep it in sync so the printout is honest.
+ try:
+ import timm as _timm
+ cfg.backbone_feat_dim = _timm.create_model(
+ cfg.backbone, pretrained=False, num_classes=0).num_features
+ except Exception:
+ pass
if args.seed is not None:
random.seed(args.seed); np.random.seed(args.seed); torch.manual_seed(args.seed)
torch.cuda.manual_seed_all(args.seed)
@@ -1692,6 +1784,8 @@ def main():
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"weight decay : {cfg.weight_decay} | "
+ f"{'split (no wd on depthwise/norm/bias)' if cfg.split_weight_decay else 'uniform on all params'}")
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} "
diff --git a/instanthmr_distill_train/train_levjepa_lora.py b/instanthmr_distill_train/train_levjepa_lora.py
new file mode 100644
index 0000000..95d0428
--- /dev/null
+++ b/instanthmr_distill_train/train_levjepa_lora.py
@@ -0,0 +1,500 @@
+#!/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
new file mode 100644
index 0000000..c201982
--- /dev/null
+++ b/instanthmr_distill_train/train_levjepa_probe.py
@@ -0,0 +1,734 @@
+#!/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
+# ============================================================
+TRACK_RE = re.compile(r"^(.*)_(\d{5})_p(\d+)$")
+
+
+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
+ 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):
+ self.cfg = cfg
+ 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)
+ q = q + self.temporal_embed.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()
diff --git a/tools/bench_backbone.py b/tools/bench_backbone.py
new file mode 100644
index 0000000..74ec540
--- /dev/null
+++ b/tools/bench_backbone.py
@@ -0,0 +1,261 @@
+#!/usr/bin/env python3
+"""Backbone A/B for the MHR-only InstantHMR student: RepViT vs MobileNetV4.
+
+The student is backbone-agnostic -- InstantHMRStudent reads the feature width
+from `backbone.num_features` and assumes a stride-32 (B,C,H,W) map, which every
+MobileNetV4 variant satisfies -- so this measures the cost side of the swap on
+the *whole* student, not on the backbone in isolation.
+
+ python tools/bench_backbone.py [--batches 1 8 32] [--iters 50] [--no-onnx]
+"""
+from __future__ import annotations
+
+import argparse
+import contextlib
+import io
+import sys
+import time
+from pathlib import Path
+
+import numpy as np
+import torch
+
+ROOT = Path(__file__).resolve().parent.parent
+TRAIN_DIR = ROOT / "instanthmr_distill_train"
+sys.path.insert(0, str(TRAIN_DIR))
+
+DEV = torch.device("cuda" if torch.cuda.is_available() else "cpu")
+
+CANDIDATES = [
+ "repvit_m1_5",
+ "repvit_m2_3",
+ "mobilenetv4_conv_medium",
+ "mobilenetv4_hybrid_medium",
+ "mobilenetv4_conv_large",
+]
+
+
+def timeit(fn, iters, warmup=10):
+ for _ in range(warmup):
+ fn()
+ if DEV.type == "cuda":
+ torch.cuda.synchronize()
+ t0 = time.perf_counter()
+ for _ in range(iters):
+ fn()
+ if DEV.type == "cuda":
+ torch.cuda.synchronize()
+ return (time.perf_counter() - t0) / iters * 1000.0
+
+
+def load_module():
+ buf = io.StringIO()
+ with contextlib.redirect_stdout(buf):
+ import train_distill_mhr_only as M
+ return M
+
+
+def build(M, name, pretrained=False):
+ cfg = M.DistillConfig()
+ cfg.backbone = name
+ model = M.InstantHMRStudent(cfg, pretrained=pretrained).to(DEV).eval()
+ return cfg, model
+
+
+def bench_torch(model, cfg, batch, iters, amp):
+ img = torch.randn(batch, 3, cfg.image_size, cfg.image_size, device=DEV)
+ cliff = torch.randn(batch, 3, device=DEV)
+
+ def step():
+ with torch.no_grad(), torch.amp.autocast(
+ device_type="cuda", dtype=torch.float16, enabled=amp):
+ model(img, cliff)
+
+ def bb():
+ with torch.no_grad(), torch.amp.autocast(
+ device_type="cuda", dtype=torch.float16, enabled=amp):
+ model.backbone.forward_features(img)
+
+ return timeit(step, iters), timeit(bb, iters)
+
+
+def bench_train_step(M, name, batch, iters):
+ """fwd+bwd on the regression heads only (no data, no MHR) + peak memory."""
+ cfg, model = build(M, name, pretrained=False)
+ model.train()
+ opt = torch.optim.AdamW(model.parameters(), lr=1e-4)
+ scaler = torch.amp.GradScaler(device="cuda")
+ img = torch.randn(batch, 3, cfg.image_size, cfg.image_size, device=DEV)
+ cliff = torch.randn(batch, 3, device=DEV)
+ torch.cuda.reset_peak_memory_stats()
+
+ def step():
+ opt.zero_grad(set_to_none=True)
+ with torch.amp.autocast(device_type="cuda", dtype=torch.float16):
+ out = model(img, cliff)
+ loss = sum(v.float().square().mean() for v in out.values())
+ scaler.scale(loss).backward()
+ scaler.step(opt)
+ scaler.update()
+
+ ms = timeit(step, iters, warmup=5)
+ peak = torch.cuda.max_memory_allocated() / 2**20
+ del model, opt, img, cliff
+ torch.cuda.empty_cache()
+ return ms, peak
+
+
+def export_onnx(M, name, cfg, model, out_dir):
+ """Export + fp16-convert the student. Returns the fp16 .onnx path."""
+ import onnx
+ # Same converter the training script's export_and_quantize() uses.
+ # onnxconverter_common's version mistypes the decoder's attention Cast nodes
+ # and the resulting graph fails to load in ORT.
+ from onnxruntime.transformers.float16 import convert_float_to_float16
+
+ class Wrap(torch.nn.Module):
+ def __init__(self, m, c):
+ super().__init__()
+ self.m, self.c = m, c
+
+ def forward(self, image, cliff_cond):
+ o = self.m(image, cliff_cond)
+ return (o["mhr_params"], o["shape_params"],
+ o["cam_trans"], o["joints_2d"])
+
+ w = Wrap(model, cfg).eval().to(DEV)
+ f32 = out_dir / f"{name}_fp32.onnx"
+ f16 = out_dir / f"{name}_fp16.onnx"
+ dummy = (torch.randn(1, 3, cfg.image_size, cfg.image_size, device=DEV),
+ torch.randn(1, 3, device=DEV))
+ with contextlib.redirect_stdout(io.StringIO()):
+ torch.onnx.export(
+ w, dummy, str(f32), input_names=["image", "cliff_cond"],
+ output_names=["mhr_params", "shape_params", "cam_trans", "joints_2d"],
+ dynamic_axes={"image": {0: "B"}, "cliff_cond": {0: "B"},
+ "mhr_params": {0: "B"}, "shape_params": {0: "B"},
+ "cam_trans": {0: "B"}, "joints_2d": {0: "B"}},
+ opset_version=17, do_constant_folding=True)
+ m16 = convert_float_to_float16(onnx.load(str(f32)), keep_io_types=True)
+ onnx.save(m16, str(f16))
+ return f16
+
+
+def bench_ort(path, cfg, batches, iters):
+ import onnxruntime as ort
+ so = ort.SessionOptions()
+ so.log_severity_level = 3
+ sess = ort.InferenceSession(str(path), so, providers=["CUDAExecutionProvider"])
+ assert "CUDAExecutionProvider" in sess.get_providers(), "ORT fell back to CPU"
+ res = {}
+ for b in batches:
+ feed = {"image": np.random.randn(b, 3, cfg.image_size, cfg.image_size).astype(np.float32),
+ "cliff_cond": np.random.randn(b, 3).astype(np.float32)}
+ for _ in range(10):
+ sess.run(None, feed)
+ t0 = time.perf_counter()
+ for _ in range(iters):
+ sess.run(None, feed)
+ res[b] = (time.perf_counter() - t0) / iters * 1000.0
+ del sess
+ return res
+
+
+def main():
+ ap = argparse.ArgumentParser()
+ ap.add_argument("--batches", type=int, nargs="+", default=[1, 8, 32])
+ ap.add_argument("--iters", type=int, default=50)
+ ap.add_argument("--train-batch", type=int, default=64)
+ ap.add_argument("--no-onnx", action="store_true")
+ ap.add_argument("--models", type=str, nargs="+", default=CANDIDATES)
+ args = ap.parse_args()
+
+ M = load_module()
+ out_dir = Path("/tmp/claude-1000/bench_backbone")
+ out_dir.mkdir(parents=True, exist_ok=True)
+
+ if DEV.type == "cuda":
+ print(f"device: {torch.cuda.get_device_name(0)} torch {torch.__version__}")
+ print()
+
+ rows = []
+ for name in args.models:
+ cfg, model = build(M, name)
+ nb = sum(p.numel() for p in model.backbone.parameters()) / 1e6
+ nt = sum(p.numel() for p in model.parameters()) / 1e6
+ with torch.no_grad():
+ f = model.backbone.forward_features(
+ torch.randn(1, 3, cfg.image_size, cfg.image_size, device=DEV))
+ r = {"name": name, "bb_params": nb, "tot_params": nt,
+ "feat": tuple(f.shape[1:]), "torch": {}, "bb": {}}
+ for b in args.batches:
+ r["torch"][b], r["bb"][b] = bench_torch(model, cfg, b, args.iters, amp=True)
+ del model
+ torch.cuda.empty_cache()
+ r["train_ms"], r["train_mem"] = bench_train_step(M, name, args.train_batch, 20)
+ rows.append(r)
+
+ if not args.no_onnx:
+ for r in rows:
+ cfg, model = build(M, r["name"])
+ try:
+ p = export_onnx(M, r["name"], cfg, model, out_dir)
+ del model
+ torch.cuda.empty_cache()
+ r["ort"] = bench_ort(p, cfg, args.batches, args.iters)
+ except Exception as e:
+ r["ort"] = None
+ r["ort_err"] = f"{type(e).__name__}: {e}"
+ finally:
+ torch.cuda.empty_cache()
+
+ bs = args.batches
+ print("=" * 118)
+ print("PARAMETERS / FEATURE MAP")
+ print("-" * 118)
+ print(f"{'backbone':30s} {'bb params(M)':>13s} {'total(M)':>10s} {'feat map':>16s}")
+ for r in rows:
+ print(f"{r['name']:30s} {r['bb_params']:13.2f} {r['tot_params']:10.2f} {str(r['feat']):>16s}")
+
+ print()
+ print("=" * 118)
+ print(f"TORCH fp16 autocast, FULL student forward (ms/iter) -- backbone-only in ()")
+ print("-" * 118)
+ hdr = "".join(f"{'B=' + str(b):>22s}" for b in bs)
+ print(f"{'backbone':30s}{hdr}")
+ for r in rows:
+ cells = "".join(f"{r['torch'][b]:>13.2f} ({r['bb'][b]:5.2f})" for b in bs)
+ print(f"{r['name']:30s}{cells}")
+
+ print()
+ print("=" * 118)
+ print(f"TRAINING STEP fwd+bwd+AdamW @ batch {args.train_batch} (ms) / peak GPU mem (MiB)")
+ print("-" * 118)
+ print(f"{'backbone':30s} {'ms/step':>10s} {'peak MiB':>10s}")
+ for r in rows:
+ print(f"{r['name']:30s} {r['train_ms']:10.1f} {r['train_mem']:10.0f}")
+
+ if not args.no_onnx:
+ print()
+ print("=" * 118)
+ print("ONNX fp16 / onnxruntime CUDAExecutionProvider (ms/iter)")
+ print("-" * 118)
+ print(f"{'backbone':30s}" + "".join(f"{'B=' + str(b):>12s}" for b in bs))
+ for r in rows:
+ if r.get("ort") is None:
+ print(f"{r['name']:30s} EXPORT FAILED: {r.get('ort_err','')[:70]}")
+ else:
+ print(f"{r['name']:30s}" + "".join(f"{r['ort'][b]:12.2f}" for b in bs))
+ base = next((r for r in rows if r["name"] == "repvit_m2_3" and r.get("ort")), None)
+ if base:
+ print()
+ print(f"{'speedup vs repvit_m2_3':30s}" + "".join(f"{'B=' + str(b):>12s}" for b in bs))
+ for r in rows:
+ if r.get("ort"):
+ print(f"{r['name']:30s}"
+ + "".join(f"{base['ort'][b] / r['ort'][b]:11.2f}x" for b in bs))
+ print("=" * 118)
+
+
+if __name__ == "__main__":
+ main()