Skip to content
Python

feat: SMPL-space benchmarks (EMDB-1, mesh conversion, PVE), fixed a compact pair index that ends the host-RAM OOM, and provided HGNetv2 vs Repvit verdict

mohamdev0edf74d6a888
diff --git a/CLAUDE.md b/CLAUDE.md
index 85fc5e9..2788db7 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -167,6 +167,34 @@ steps. Use `--anomaly-safe-fallback`, which steps on the non-FK terms instead
divergence here by lowering the LR alone: `OneCycleLR(pct_start=0.1)` peaks at
10% of the run, so a lower peak only moves *when* it dies.
+**The pair index is a host-RAM bomb, and it kills jobs with no traceback.**
+Four generation-6 jobs were OOM-killed at 74-76 GiB per node between epochs 14
+and 33 on 2026-09-08. Not CUDA -- `sacct` says `OUT_OF_ME+`, exit `0:125`,
+`Detected N oom_kill events`, and the only Python output is a dataloader worker
+dying of `ConnectionResetError`, which is the symptom. Measured: a list of
+`(PosixPath, PosixPath)` pairs costs **694 bytes per pair**, so 4.2 M crops is
+2.94 GB per process; `build_jz_loaders` runs `persistent_workers=True` with 9
+workers per rank, i.e. 40 processes per node, and CPython writes a refcount into
+an object header just to *read* it, so every worker steadily converts its
+copy-on-write share into a private copy. It grows over epochs, which is why the
+kill lands hours in. `PairIndex` in `train_distill_jz.py` stores the index as
+three contiguous numpy byte arrays instead (87 bytes/pair, 8.0x smaller,
+verified identical on all 961,139 local pairs and in iteration order). Do
+**not** call `list()` on it -- `SAM3DStudentDataset` copies only real lists for
+exactly this reason. Two corollaries: adding *any* per-node memory (the
+`--w-verts` subset costs ~2 GiB across 4 ranks) decides only which arm dies
+first, not whether one does; and `sacct` MaxRSS undersamples at ~30 s, so a
+number well under the `mem=160000M` cgroup limit does not mean you are safe.
+
+**rsync to the cluster lands files where you point it, and a misplaced trainer
+fails silently.** `rsync ... a/b.py c/d.slurm host:REPO/` puts BOTH in
+`REPO/`, not in `REPO/a/` and `REPO/c/`. A stray `train_distill_jz.py` in the
+repo root is simply never imported, so the job runs the old code and raises
+nothing -- on 2026-09-08 that silently discarded both a
+`--constraint=v100-32g` fix and a logging change for a full generation. Check
+the destination directory per file, and verify on the cluster with `grep -c
+'<a string only the new version has>'` before submitting.
+
**Body shape is invisible to every geometric loss, and the fix is a vertex
term.** `MHRForwardPass.get_joints` zeroes the 45 `shape_params`, and that is
not a shortcut: they move the 127-joint skeleton by *exactly* `0.000e+00 cm`.
diff --git a/benchmark/METRICS.md b/benchmark/METRICS.md
new file mode 100644
index 0000000..2a5eaad
--- /dev/null
+++ b/benchmark/METRICS.md
@@ -0,0 +1,293 @@
+# What we measure, and in what space
+
+InstantHMR predicts **MHR**. Every published 3DPW and EMDB number is defined on
+**SMPL**. This document explains how we get from one to the other, exactly
+which space each metric lives in, and why the reported numbers are comparable
+to a published table.
+
+Read this before quoting a number, and before adding a new one.
+
+---
+
+## 1. The problem in one paragraph
+
+The model outputs 204 MHR model parameters plus 45 identity coefficients. Those
+drive a 127-joint skeleton and an 18,439-vertex mesh. The benchmarks want the
+**24 SMPL joints** (MPJPE, PA-MPJPE) and the **6,890 SMPL vertices** (PVE).
+These are different rigs: different joint definitions, different topology, no
+shared vertex. Nothing can be compared until one side is moved into the other's
+space. **Which side you move is the whole ballgame** — see §5.
+
+---
+
+## 2. How MHR becomes SMPL
+
+Three stages. Stage 2 is the one that makes it work.
+
+```
+ student ──▶ MHR params (204 + 45)
+ │
+ │ ① rig forward: identity blendshapes,
+ │ pose correctives, linear blend skinning
+ ▼
+ MHR mesh (18,439 verts)
+ │
+ │ ② official barycentric surface map
+ │ SMPL vertex i = w₁·v_a + w₂·v_b + w₃·v_c
+ │ on MHR triangle t(i)
+ ▼
+ target vertices (6,890, SMPL topology)
+ │
+ │ ③ labelled fit for θ (72), β (10), t (3)
+ │ global orientation solved in closed form
+ ▼
+ SMPL params ──▶ 24 joints + 6,890 vertices
+```
+
+### ① The rig forward
+
+`MHRRig.vertices` calls the TorchScript rig's own top-level forward, so the
+mesh includes identity blendshapes and pose correctives — the same mesh the
+dataset annotations describe. Not the trainer's skeleton-only path, and not its
+595-vertex training subset.
+
+Note this stage consumes the **45 `shape_params`**. Those move the 127-joint
+skeleton by exactly `0.00e+00 cm`, so every joint metric in this repo is blind
+to them. They *do* move the mesh, which is why PVE is the first number here
+that responds to body shape at all.
+
+### ② The surface map — where the correspondence comes from
+
+`mhr2smpl_mapping.npz` from
+[facebookresearch/MHR](https://github.com/facebookresearch/MHR/tree/main/tools/mhr_smpl_conversion)
+(`tools/mhr_smpl_conversion/assets`, Apache-2.0). For each of the 6,890 SMPL
+vertices it stores **one MHR triangle id and three barycentric weights**. So
+each SMPL vertex is a fixed point on the MHR surface, and pushing a posed MHR
+mesh through it resamples that same surface in SMPL topology.
+
+It is a topology constant — indices and weights, no coordinate frame, no units
+— so it applies in whatever frame you hand it.
+
+**Why not derive it ourselves?** We tried, three ways, and all three failed:
+
+| attempt | residual | why it fails |
+|---|---|---|
+| nearest MHR vertex + mean offset in camera space | 60 mm | the offset rotates with the person; it is not a constant |
+| affine combination of the K nearest MHR vertices | 65 mm, weights to ±405 | a local neighbourhood on a smooth mesh spans a tangent plane, leaving the normal direction unresolved |
+| offset in a local surface frame (normal + tangents) | ~10 mm std | works in principle, but sensitive to under-converged fits upstream |
+
+**Verify the map against the rig before trusting it** (`mhr_smpl.py` does):
+triangle ids top out at 36,871 against the rig's 36,874 faces, barycentric rows
+sum to 1, and the reconstructed SMPL-topology mesh has a mean nearest-vertex
+spacing of **13.88 mm** against real SMPL's **14.37 mm**. A map built for a
+different mesh would scatter neighbouring vertices onto unrelated triangles and
+that number would blow up.
+
+### ③ The fit
+
+Now every SMPL vertex has a known target, so this is a plain labelled
+regression: minimise `‖SMPL(θ,β,t) − target‖²` plus an edge term (edge
+*vectors*, which constrain local shape independently of position, down-weighted
+after 30 % of the schedule so absolute positions drive the endgame).
+
+Two details that are not optional:
+
+- **Correspondence must be known.** Fitting the surface by ICP instead — letting
+ nearest-neighbour search discover the pairing — has a local minimum that its
+ own residual cannot see: the mesh settles overlapping the target while limbs
+ are matched to the **wrong limbs**. Measured: 12 mm surface residual, 76 mm
+ PA-MPJPE. The surface looks fine and the pose is wrong.
+- **Global orientation is solved in closed form**, by Procrustes between SMPL's
+ rest mesh and the target. Known correspondence makes that a three-line SVD.
+ Without it the fit starts at identity and has to walk to an arbitrary
+ camera-space orientation through axis-angle: it stalls at **40–51 mm** of
+ vertex residual instead of **13 mm**.
+
+Typical fit residual on real predictions: **14–16 mm** surface distance.
+
+---
+
+## 3. Which space each metric is computed in
+
+**Everything is computed in SMPL space.** Predictions are converted; the ground
+truth is never touched.
+
+| metric | space | prediction side | GT side | alignment |
+|---|---|---|---|---|
+| **MPJPE** (SMPL24) | SMPL | 24 kinematic joints of the fitted SMPL | 24 kinematic joints of GT SMPL | mid-hip (joints 1 & 2) |
+| **PA-MPJPE** (SMPL24) | SMPL | same | same | Procrustes (rotation + translation + **scale**) |
+| **PVE** | SMPL | 6,890 fitted vertices | 6,890 GT vertices | mid-hip |
+| **PA-PVE** | SMPL | same | same | Procrustes |
+| **J14 (H36M)** | SMPL | `J_regressor_h36m` @ fitted vertices → 14 | `J_regressor_h36m` @ GT vertices → 14 | mid-hip / Procrustes |
+
+Nothing is computed in MHR space. See §5.
+
+### How the 24 joints are obtained — there is no regression
+
+This is the part people expect to be complicated, and it is not. Once SMPL is
+fitted, **both sides come out of the same SMPL model by the same code path**:
+`SMPLModel.forward` returns the 24 kinematic-tree joints carried by the global
+transforms, and it is called on the fitted parameters for the prediction and on
+the GT parameters for the ground truth. No adapter, no learned map, nothing
+fitted per checkpoint.
+
+We use the **kinematic** joints, not `J_regressor @ posed vertices`. That is not
+a shortcut — it is EMDB's own definition. EMDB ships a `kp2d` field, and it
+reprojects the kinematic joints to **0.00 px** and the regressed ones to
+**1.04 px**; in 3D the two sit 3.8 mm apart on average. 3DPW's `jointPositions`
+field is the same kinematic set.
+
+### How the 14 joints are obtained — and why an adapter is not a compromise
+
+3DPW's published protocol is 14 joints in the Human3.6M convention. **There is
+no route from MHR to that convention without a conversion, and no such route
+exists for SMPL-native methods either.** This is the single most important
+thing to be clear about, because it is easy to state backwards.
+
+`J_regressor_h36m.npy` — the file NLF, CameraHMR, SPIN, HMR2.0 and everyone else
+uses — **is itself a fitted linear regressor**, 17 x 6890, mapping SMPL vertices
+to H36M joints. Those methods do not skip a conversion; they use one that ships
+with the benchmark ecosystem, because their meshes are already SMPL. We predict
+MHR, so we need one more step. That is a property of the rig, not a weakness in
+the protocol, and a linear map from our native output to the benchmark's joint
+convention is the same class of object theirs is.
+
+So we report two routes, and **neither is "adapter-free"** — that phrase should
+never appear next to either number:
+
+| row | path | what it needs |
+|---|---|---|
+| **J14 + joint adapter** (primary) | MHR70 keypoints → fixed 14x70 linear map → J14 | the adapter, fitted once on 3DPW *train* from the dataset's own MHR annotations, never from a student, rank-truncated (`RCOND`) |
+| **J14 via mesh fit** | MHR mesh → barycentric map → fitted SMPL → `J_regressor_h36m` → J14 | Meta's surface map + the standard H36M regressor |
+
+Both convert MHR into the H36M convention. They differ only in *where* the
+conversion happens — joint space or mesh space.
+
+Evidence the joint adapter is a rig conversion and not an error sponge, which
+is the only real objection to it:
+
+- it is fitted from **dataset annotations, never from a student**, so it is one
+ fixed map for every checkpoint and cannot absorb a particular model's error;
+- it reads anatomically — `right_hip = +1.16 right_hip - 0.32 left_hip`
+ (widening SMPL's 120 mm hips toward H36M's 292 mm), `right_knee = +0.84
+ right_knee`, nearly identity because the knee is the same point in both;
+- the **SMPL24 version transfers across datasets**: fitted on 3DPW train,
+ applied unchanged to EMDB, where it was never fitted. A map that had
+ overfitted 3DPW would not survive that.
+
+The mesh route exists because it is the only one that also yields **PVE** and
+the SMPL24 joint set, not because the adapter is suspect. Expect the two J14
+numbers to differ by a few mm; report the adapter row as the headline and the
+mesh row alongside it, each labelled by its path.
+
+## 4. What PVE means (checked against the papers)
+
+**PVE is pelvis-aligned, not Procrustes-aligned.** CameraHMR §4.3:
+
+> "…MPJPE, PA-MPJPE, and PVE (Per Vertex Error), which measures the Euclidean
+> distance (in mm) between predicted and actual 3D vertices and joints **after
+> aligning the pelvis**."
+
+NLF's appendix confirms the naming: *"MVE is analogous to MPJPE but for mesh
+vertices instead of joints, similarly **P-MVE** is the Procrustes-aligned
+version of it."*
+
+So the column to put next to a published PVE is our **`PVE_mm`**, not
+`PA_PVE_mm`. We report PA-PVE too, because it isolates shape from pose, but it
+belongs in a different column and must be labelled `P-MVE` / `PA-PVE` if quoted.
+
+The reference point is the **midpoint of the two hips**, not SMPL joint 0. NLF:
+*"on 3DPW and EMDB the reference point is the midpoint between the two hip
+joints."*
+
+---
+
+## 5. The direction rule — read this before inventing a new metric
+
+The conversion runs **prediction → SMPL**. Never the other way for a reported
+number.
+
+Solving an MHR ground truth for EMDB and scoring predictions on MHR joints
+would remove the conversion cost entirely, and it is *not* a comparable number:
+
+1. **MPJPE is not rig-independent.** The published column is defined on SMPL's
+ joints and SMPL's vertices. A number on MHR's 70 keypoints is a different
+ quantity, not a tighter measurement of the same one.
+2. **40 of MHR's 70 keypoints are finger joints millimetres apart.** Averaging
+ error over them drags the mean down regardless of body accuracy.
+3. **The reference would be something we generated**, with an optimiser told to
+ look like an MHR model. Whatever MHR cannot represent silently leaves the
+ error term.
+
+The MHR ground truth is still worth having — `make_mhr_gt.py` builds and caches
+it — but for the **oracle row**: fit MHR to the GT surface, convert it back
+through the forward path, and score it. That is the best any MHR-rigged model
+could achieve here, and it decomposes the error into rig cost and model error.
+It is an upper bound, labelled as one.
+
+---
+
+## 6. Conversion floors — quote these next to results
+
+Measured as a round trip through the rig (GT SMPL → fit MHR to that surface →
+convert back → score against the untouched GT), cold-started at every stage:
+
+| route | MPJPE floor | PA-MPJPE floor | PVE floor |
+|---|---|---|---|
+| linear MHR70 → SMPL24 joint adapter | 25.11 mm | 18.77 mm | not possible |
+| **mesh conversion** | **11.44 mm** | **10.66 mm** | **13.61 mm** |
+
+A floor does not subtract from a result linearly. Treating model error and
+conversion error as independent, dropping the floor from 18.8 to 10.7 mm at a
+~50 mm model error predicts √(50²+18.8²)=53.4 → √(50²+10.7²)=51.1, about 2.3 mm
+— which is what is observed. The mesh route's real win is that **PVE exists**.
+
+---
+
+## 7. Running it
+
+One command per dataset. Both write JSON to `benchmark/results/`.
+
+```bash
+# EMDB-1 in SMPL space (24,103 frames, ~25 min on an RTX 4070)
+python benchmark/eval_smpl_fit.py --dataset emdb \
+ --ckpt <run>/best_student_model_v3.pth \
+ --emdb-root /path/to/EMDB \
+ --out benchmark/results/emdb1_smplfit.json
+
+# 3DPW test in SMPL space (35,463 person-frames, ~30 min)
+python benchmark/eval_smpl_fit.py --dataset 3dpw --split test \
+ --ckpt <run>/best_student_model_v3.pth \
+ --sequence-dir /path/to/3DPW/sequenceFiles \
+ --image-root /path/to/3DPW/imageFiles \
+ --out benchmark/results/3dpw_test_smplfit.json
+```
+
+`--ckpt` takes several checkpoints and evaluates them in one pass; the config
+(`--bound-scales`, `--cliff-focal`) is restored **per checkpoint** from the
+weights and `run_config.json`, so checkpoints with different flags can share an
+invocation safely. Results are written after *each* checkpoint.
+
+The legacy joint-adapter rows come from `eval_emdb_ckpt.py` and
+`eval_3dpw_ckpt.py`; `eval_all.py` runs everything and prints the combined
+table.
+
+### One-time setup
+
+```bash
+# Meta's surface maps -> benchmark/data/mhr_smpl_conversion/
+# {mhr2smpl,smpl2mhr}_mapping.npz from facebookresearch/MHR (Apache-2.0)
+
+# EMDB 24-joint GT cache (7 MB); --check must print ~0.00 px against kp2d
+python benchmark/make_emdb_gt.py --emdb-root /path/to/EMDB \
+ --smpl-dir benchmark/data/smpl --check
+
+# 3DPW H36M GT cache, for the J14 adapter rows
+python benchmark/make_3dpw_gt.py --sequence-dir /path/to/3DPW/sequenceFiles \
+ --smpl-dir benchmark/data/smpl --check
+
+# MHR ground truth, cached so it is never recomputed (~25 MB each)
+python benchmark/make_mhr_gt.py --dataset emdb --emdb-root /path/to/EMDB
+python benchmark/make_mhr_gt.py --dataset 3dpw --split test \
+ --sequence-dir /path/to/3DPW/sequenceFiles
+```
diff --git a/benchmark/README.md b/benchmark/README.md
index 2def996..cea93be 100644
--- a/benchmark/README.md
+++ b/benchmark/README.md
@@ -2,15 +2,15 @@
Evaluation harness for publishing numbers on `models/instanthmr_mhr_only_ckpt90.onnx`.
-Two benchmarks are implemented, chosen because they are the two cheapest paths
-to a credible table — one 3D, one 2D:
+Three benchmarks are implemented — two 3D, one 2D:
| Benchmark | What it measures | Data cost | Status |
|---|---|---|---|
| **3DPW** test | MPJPE / PA-MPJPE, the standard in-the-wild 3D HMR metric | 4.6 GB images + 30 MB GT + 500 MB SMPL | ready — published-protocol GT; **check contamination below** |
+| **EMDB-1** | MPJPE / PA-MPJPE on the 24 SMPL joints, the "EMDB (24)" column | 16 GB images (of a 50 GB download) + 7 MB GT | ready — **and genuinely clean**, see below |
| **COCO** val2017 | OKS AP / PCK, 2D keypoint localisation in the wild | 820 MB, direct download, no registration | ready — clean |
-## Why these two
+## Why these three
**3DPW** is the benchmark essentially every monocular HMR paper reports, so it
is the one that makes your numbers comparable. The GT pickles store
@@ -20,6 +20,14 @@ tempting and wrong — published numbers use SMPL run *forward* on the GT
references are **46 mm apart in J12 PA-MPJPE**, so the harness builds the real
one once with `make_3dpw_gt.py` and scores against that.
+**EMDB-1** is the newer of the two 3D benchmarks and the one this repo can
+report honestly. Every recent paper carries an "EMDB (24)" column (SAM 3D Body
+Table 2, NLF Table 3, Fast SAM 3D Body Table 1), it is out-of-domain for almost
+all of them, and — unlike 3DPW — **no EMDB frame appears in any corpus this
+repo trains on**, so it is the only 3D number here with no contamination
+caveat attached. It is structurally a simpler 3DPW: one subject per sequence,
+provided person boxes, real calibration.
+
**COCO val2017** needs no registration at all and the joint mapping is free:
MHR70 indices 0–14 already follow COCO's ordering, with the wrists at 41/62.
@@ -36,15 +44,12 @@ MHR70 indices 0–14 already follow COCO's ordering, with the wrists at 41/62.
out-of-domain for every method in it.
- **MPII** — 2D only, so it adds little once COCO is in.
-### Next: EMDB — waiting on registration (asked 2026-09-05)
-
-**Status: blocked on the application at `emdb.ait.ethz.ch`** (a form, approved
-by email). Nothing else is missing — the two blockers this file used to list,
-the SMPL body model and their toolkit, are gone: `benchmark/data/smpl/` holds
-the gendered models and the toolkit is only a viewer, not a format we need.
+### EMDB-1 — the joint convention, settled against the data
-Use **EMDB-1** (17 sequences, 13.5 min), the camera-frame pose split every paper
-reports. EMDB-2 (25 sequences) is global-trajectory and not what this model does.
+Use **EMDB-1** (17 sequences, 24,323 frames), the camera-frame pose split every
+paper reports. EMDB-2 (25 sequences) is global-trajectory and not what this
+model does. Three sequences are in both; `benchlib/emdb.py` selects on the
+pickles' own `emdb1` flag and asserts it finds exactly 17.
It is structurally a simpler 3DPW, one subject per sequence:
@@ -56,33 +61,119 @@ It is structurally a simpler 3DPW, one subject per sequence:
| `bboxes` (N,4) xyxy — **provided** | derived from projected joints |
`betas` is 10-dim, exactly the count the published protocol uses, so
-`make_3dpw_gt.py`'s forward pass drops in unchanged.
+`make_3dpw_gt.py`'s forward pass drops in unchanged, and EMDB's `gender` field
+picks the same gendered pair 3DPW needs.
**The protocol is the 24 SMPL joints, mid-hip aligned — not the H36M
regressor.** NLF's Table 3 reads "Results on EMDB1 (24j)" and its metrics
section states that "on 3DPW and EMDB the reference point is the midpoint
between the two hip joints"; SAM 3D Body's Table 2 column header is "EMDB (24)".
-Those 24 joints are what `smpl_forward` already returns as its second output.
-
-Two things already done, so the integration is a loader and nothing else:
-
-- `benchmark/results/adapter_smpl24_teacher.npz` — the MHR70 → SMPL-24
- conversion, fitted the same student-free way as the J14 one, from 22,209
- teacher/GT pairs on 3DPW train (where `jointPositions` **is** the SMPL-24 set,
- verified to 0.001 mm). Reads anatomically: `pelvis = 0.38 right_hip + 0.34
- left_hip`, `left_knee = 0.93 left_knee`, `left_ankle` from heel + ankle + toe.
-- **The conversion floor: 25.11 mm MPJPE / 18.77 mm PA-MPJPE** on a held-out
- half. That is what an MHR-rigged model carries on a 24-joint benchmark before
- it makes a single mistake — an *upper* bound, since it also contains the
- teacher's own 3DPW error, which cannot be separated without perfect MHR GT.
- Quote it next to the result: the table it joins runs 61.7 (SAM 3D Body) to
- 118.5 (HMR2.0b) MPJPE, so ~25 mm of rig overhead is material.
-
-What is left is `benchlib/emdb.py`, ~80 lines mirroring `threedpw.py`. It was
-deliberately **not** written ahead of the data: `dataset.md` does not say
-whether `extrinsics` is world→camera or camera→world, and guessing wrong gives
-quietly wrong numbers rather than a crash. Thirty seconds with a real pkl
-settles it.
+
+**Which 24, though — and which way the extrinsics point — came from the data,
+not the docs.** Both would have produced quietly wrong numbers rather than a
+crash, and EMDB's own `kp2d` field settles both at once, because it is the 24
+joints already projected:
+
+| hypothesis | reprojection error vs `kp2d` |
+|---|---|
+| `extrinsics` as world→camera, **kinematic** joints | **0.00 px** ✅ |
+| `extrinsics` as world→camera, `J_regressor @ vertices` | 1.04 px |
+| `inv(extrinsics)` as world→camera | 3477 px, every joint behind the camera |
+
+So `extrinsics` is world→camera (3DPW's sense), and "EMDB (24)" means the SMPL
+**kinematic-tree** joints — `smpl_forward`'s second output — not the regressed
+ones, which sit 3.8 mm away on average and 19.3 mm at worst. This is the same
+distinction that bites on 3DPW, pointing the other way: there the published GT
+*is* the regressed one.
+
+`make_emdb_gt.py --check` re-runs that comparison over all 24,323 frames and
+reports **0.0024 px mean / 0.095 px max**, which certifies the SMPL forward, the
+gendered model choice, the beta padding and the world frame in one number.
+
+**The MHR70 → SMPL-24 adapter is required, not optional.** Ten of SMPL's 24
+joints — the three spines, the collars, the feet, the hands — have no MHR
+landmark at all, so there is no raw row to fall back on.
+`benchmark/results/adapter_smpl24_teacher.npz` is the student-free conversion,
+fitted by `fit_adapter_mhr.py --target smpl24` from 22,209 annotation/GT pairs
+on 3DPW **train** (where `jointPositions` **is** the SMPL-24 kinematic set,
+verified to 0.001 mm). EMDB is a different dataset, so it is a real holdout.
+It reads anatomically: `pelvis = 0.38 right_hip + 0.34 left_hip`, `left_knee =
+0.93 left_knee`, `left_ankle` from heel + ankle + toe.
+
+**The conversion floor: 25.11 mm MPJPE / 18.77 mm PA-MPJPE** on a held-out half.
+That is what an MHR-rigged model carries on a 24-joint benchmark before it makes
+a single mistake, using this linear conversion. Quote it next to the result: the table it joins runs 61.7 (SAM 3D Body) to 118.5 (HMR2.0b)
+MPJPE, so ~25 mm of rig overhead is material.
+
+### Two routes into SMPL space, and why the mesh one wins
+
+The linear adapter above converts *joints*. `benchmark/eval_smpl_fit.py`
+converts the **mesh** instead — the route SAM 3D Body and Fast SAM 3D Body use
+for this same rig — which lowers the conversion floor ~2x and is the only way
+to reach PVE at all:
+
+| conversion | MPJPE floor | PA-MPJPE floor | PVE floor |
+|---|---|---|---|
+| linear MHR70 → SMPL24 adapter | 25.11 | 18.77 | not possible |
+| **mesh fit** (`eval_smpl_fit.py`) | **11.44** | **10.66** | **13.61** |
+
+Measured as a round trip through the rig: GT SMPL → fit MHR to that surface →
+convert back → score against the untouched GT. Every stage is cold-started, so
+this is the floor the evaluator actually operates at, not a best case.
+
+**The direction is the part that makes it publishable.** The prediction is
+fitted into SMPL and the ground truth is left exactly as the benchmark defines
+it, so MPJPE/PA-MPJPE/PVE mean what they mean in every published table. The
+tempting inverse — solving an MHR ground truth for EMDB and scoring in MHR
+space — removes the conversion entirely and is **not** a comparable number: it
+changes the joint set (MPJPE is not rig-independent), it averages error over 40
+finger joints millimetres apart, and it scores against a reference we generated
+with an optimiser told to look like an MHR model, so whatever MHR cannot
+represent silently leaves the error term. Keep that as a diagnostic if you want
+it; do not put it in the table.
+
+**Three components, and the one that was hard.**
+
+1. The student's MHR parameters → the rig's own 18,439-vertex mesh.
+2. **Meta's official barycentric surface map**
+ (`facebookresearch/MHR`, `tools/mhr_smpl_conversion/assets`, Apache-2.0) →
+ the same surface resampled in SMPL topology. Copy
+ `{mhr2smpl,smpl2mhr}_mapping.npz` into
+ `benchmark/data/mhr_smpl_conversion/`.
+3. A labelled fit for SMPL `theta`/`beta`/`trans`.
+
+Step 2 is what makes step 3 tractable, and it is worth being explicit about
+why. Fitting the surface by ICP has to *discover* the correspondence, and its
+search has a local minimum that its own residual cannot detect: the mesh
+settles overlapping the target while limbs are matched to the **wrong limbs**,
+which measured a healthy-looking 12 mm surface residual alongside 76 mm
+PA-MPJPE. Three attempts to build a correspondence here all failed — a mean
+offset in camera space is not pose-invariant (60 mm), an affine combination of
+the K nearest MHR vertices is ill-conditioned because a local neighbourhood on
+a smooth mesh spans a tangent plane and leaves the normal unresolved (65 mm,
+weights reaching 405), and a surface-frame offset is sensitive to
+under-converged fits. With the official map, correspondence is **known** —
+vertex i pairs with vertex i — and the failure mode does not exist.
+
+Verify the map against this rig before trusting it: triangle ids top out at
+36,871 against the rig's 36,874 faces, barycentric rows sum to 1, and the
+reconstructed SMPL-topology mesh has a mean nearest-vertex spacing of 13.88 mm
+against real SMPL's 14.37 mm. A map built for a different mesh would scatter
+neighbouring vertices onto unrelated triangles.
+
+**PVE is the first metric in this repo that can see body shape at all.** The
+45 MHR `shape_params` move the 127-joint skeleton by exactly `0.00e+00 cm`, so
+every joint metric here — MPJPE, PA-MPJPE, the adapter rows, the training
+losses — is blind to identity by construction (see the note in `CLAUDE.md`).
+The mesh conversion feeds those parameters into `MHRRig.vertices`, so they
+reach the SMPL surface and PVE responds to them. If `--w-verts` is doing
+anything, this is the benchmark row where it shows up.
+
+One more detail in step 3: **solve the global orientation in closed form.**
+Known correspondence makes that a plain Procrustes between SMPL's rest mesh and
+the target. Without it, Adam starts from identity and has to walk the whole way
+through axis-angle, and the same fit stalls at 40-51 mm of vertex residual
+instead of 13 mm.
## Setup
@@ -125,7 +216,51 @@ this is a one-time step, not something to repeat per checkpoint:
```bash
python benchmark/fit_adapter_mhr.py \
--sequence-dir /path/to/3DPW/sequenceFiles \
- --out benchmark/results/adapter_j14_h36m_teacher.npz
+ --target j14 --out benchmark/results/adapter_j14_h36m_teacher.npz
+```
+
+### EMDB
+
+Registration is a form at `emdb.ait.ethz.ch`, approved by email; the download is
+ten per-subject zips, 50 GB. **Only EMDB-1 is needed** — 17 of the 81 sequences,
+16 GB of images — so unpack selectively rather than extracting all ten zips:
+
+```python
+# python3, from the download directory
+import zipfile, pickle
+out = '/path/to/EMDB'
+for p in range(10):
+ z = zipfile.ZipFile(f'P{p}.zip')
+ for n in z.namelist(): # pass 1: the annotations
+ if n.endswith('.pkl'):
+ z.extract(n, out)
+want = {'/'.join(f.split('/')[-3:-1])
+ for f in __import__('glob').glob(out + '/P*/*/*.pkl')
+ if pickle.load(open(f, 'rb'))['emdb1']}
+for p in range(10): # pass 2: only EMDB-1 frames
+ z = zipfile.ZipFile(f'P{p}.zip')
+ for i in z.infolist():
+ if i.filename.endswith('.jpg') and '/'.join(i.filename.split('/')[:2]) in want:
+ z.extract(i, out)
+```
+
+Then build the GT — the same gendered SMPL models as 3DPW, nothing new to fetch:
+
+```bash
+python benchmark/make_emdb_gt.py --emdb-root /path/to/EMDB \
+ --smpl-dir benchmark/data/smpl --check
+```
+
+That writes `<EMDB root>/gt_smpl24/emdb1.npz` (7 MB, 24 world joints per frame).
+`--check` must print a reprojection error of ~0.00 px against EMDB's `kp2d`; a
+larger number means the extrinsics or the joint convention moved.
+
+The MHR70 → SMPL-24 adapter is fitted once, from 3DPW train, student-free:
+
+```bash
+python benchmark/fit_adapter_mhr.py \
+ --sequence-dir /path/to/3DPW/sequenceFiles \
+ --target smpl24 --out benchmark/results/adapter_smpl24_teacher.npz
```
## Running
@@ -152,7 +287,30 @@ python benchmark/eval_3dpw_ckpt.py \
--adapter benchmark/results/adapter_j14_h36m_teacher.npz
```
-Both write a JSON report to `benchmark/results/`.
+```bash
+# EMDB-1, all 17 sequences (~4 min on an RTX 4070). --adapter defaults to the
+# committed SMPL-24 map, so the short form is the full protocol.
+python benchmark/eval_emdb_ckpt.py \
+ --ckpt instanthmr_distill_train/runs/*/*/best_student_model_v3.pth \
+ --emdb-root /path/to/EMDB \
+ --out benchmark/results/emdb1.json
+
+# ...and again with EMDB's own person boxes, which is what published
+# "Oracle: annotated bounding boxes" rows use. State which one you quote.
+python benchmark/eval_emdb_ckpt.py --ckpt <ckpt> --emdb-root /path/to/EMDB \
+ --bbox annotated
+```
+
+```bash
+# EMDB-1 in SMPL space via the mesh conversion: MPJPE, PA-MPJPE and PVE.
+# ~25 min for all 24,103 frames on an RTX 4070 (fit is 16 min of that).
+python benchmark/eval_smpl_fit.py \
+ --ckpt instanthmr_distill_train/runs/*/*/best_student_model_v3.pth \
+ --emdb-root /path/to/EMDB --fit-batch 128 \
+ --out benchmark/results/emdb1_smplfit.json
+```
+
+All four write a JSON report to `benchmark/results/`.
### The evaluator configures itself from the checkpoint (fixed 2026-09-06)
@@ -189,7 +347,9 @@ landscape ones) — not a heuristic. The naive `sqrt(H^2+W^2)` stand-in would be
2202.9 px, 12% high. `eval_3dpw.py` (the ONNX path) now passes the same
per-frame focal through `benchlib/runner.py`.
-## Current numbers (2026-09-05)
+## Current numbers
+
+### 3DPW (2026-09-05)
3DPW **test**, all 35,463 person-frames, published-protocol GT, the two Jean Zay
checkpoints pulled at ~epoch 130. Full reports in
@@ -212,6 +372,104 @@ Jean Zay, whose corpus is coco/mpii/aic/sa1b/harmony4d with `3dpw_train`
annotations-only, so all 24 test sequences are unseen. The local `data/` corpus
is **not** clean — see the contamination section.
+### EMDB-1 (2026-09-07)
+
+All 17 EMDB-1 sequences, all 24,103 evaluatable frames (24,323 total, minus 206
+where `good_frames_mask` is 0 and 14 where the subject is under 60 % inside the
+frame), `b3_s1` at epoch 137 — the same checkpoint as the 3DPW table above.
+Reports in `benchmark/results/emdb1_b3_s1_{gt-joints,annotated}.json`.
+
+| person box | **SMPL24+adapter PA** | SMPL24+adapter MPJPE | PCK@50 | PCK@100 |
+|---|---|---|---|---|
+| projected GT joints ×1.2 (this repo's 3DPW convention) | **53.82** | 79.90 | 0.632 | 0.900 |
+| EMDB's own `bboxes` (published "Oracle" protocol) | **60.69** | 87.51 | 0.582 | 0.863 |
+| *rig conversion floor (teacher, held-out half)* | *18.77* | *25.11* | | |
+
+Where that sits in the published EMDB (24) table — Fast SAM 3D Body Table 1,
+which is the most recent one carrying every baseline:
+
+| method | PA-MPJPE | MPJPE |
+|---|---|---|
+| Fast SAM 3D Body (oracle) | 37.3 | 64.3 |
+| SAM 3D Body (oracle) | 38.2 | 61.7 |
+| NLF-L +fit | 40.9 | 68.4 |
+| PromptHMR | 41.0 | 71.7 |
+| GENMO | 42.5 | 73.0 |
+| CameraHMR | 43.3 | 70.3 |
+| TRAM | 45.7 | 74.4 |
+| WHAM | 50.4 | 79.7 |
+| **InstantHMR b3_s1** | **53.8 / 60.7** | **79.9 / 87.5** |
+| SMPLer-X-H | 64.5 | 92.7 |
+| HMR2.0b | 79.2 | 118.5 |
+
+Read that with the 18.8 mm conversion floor in mind: those baselines all predict
+SMPL directly and pay no rig-conversion cost, and the floor already contains the
+teacher's own error. It is not separable from the model's error without perfect
+MHR ground truth, so the honest statement is "53.8 mm, of which up to 18.8 mm is
+the MHR→SMPL conversion", not a corrected number.
+
+**The box convention is worth 6.9 mm, so state it.** EMDB's own boxes are 17.5 %
+larger than the projected-joint boxes (mean crop side 1248 vs 1069 px) and their
+centre sits 5.7 % of a crop away, so the person lands ~15 % smaller and
+off-centre in a 224² crop the model was trained to see filled. That is framing
+sensitivity, not a modelling difference — but it means the row that belongs next
+to the published "Oracle" numbers is the 60.69 one, and the 53.82 one is what
+compares to this repo's own 3DPW numbers.
+
+**The whole EMDB path was cross-checked against 3DPW.** Scoring the same
+checkpoint on 3DPW test under the *same* GT convention (`--gt jointpositions`,
+i.e. SMPL kinematic joints) gives J14 PA 55.81 / J12 PA 49.26, against EMDB-1's
+60.17 / 55.55 on the identical rows. A 4-6 mm gap is what a harder dataset
+looks like — EMDB has handstands, cartwheels and dancing where 3DPW mostly
+walks. A wrong extrinsics sense or a mismatched joint convention would show up
+as hundreds of millimetres, not four.
+
+**EMDB is the one clean 3D number here.** The corpus is coco / mpii / aic / sa1b
+/ harmony4d / 3dpw; no EMDB frame appears in any of it, at any split. Contrast
+the 3DPW section below, where the local corpus contains crops from all 24 test
+sequences.
+
+Hardest sequences are the ones you would guess: `P5_42_indoor_dancing` (75.4 mm)
+and `P8_68_outdoor_handstand` (75.0 mm), against 44.5 mm on `P1_14_outdoor_climb`.
+Per-joint, the error is concentrated in the extremities the adapter has to
+extrapolate — `left/right_hand` at 97-98 mm and the wrists at 79-82 mm, against
+30-40 mm at the collars, neck, pelvis and hips.
+
+### EMDB-1, SMPL space via mesh conversion (2026-09-08)
+
+All 17 sequences, all 24,103 frames, projected-GT-joint boxes, `--fit-iters 400`.
+Report in `benchmark/results/emdb1_smplfit_gt-joints.json`.
+
+| run | epoch | MPJPE | **PA-MPJPE** | PVE | PA-PVE | mean fit residual |
+|---|---|---|---|---|---|---|
+| b3_s1 (baseline) | 137 | 77.38 | **52.00** | 92.25 | 62.57 | 14.61 |
+| bno_s0 (v2, `--cliff-focal --bound-scales`) | 85 | 79.55 | **54.23** | 94.44 | 64.82 | 14.72 |
+| *conversion floor (round trip)* | | *11.44* | *10.66* | *13.61* | | |
+
+**The two runs are not comparable to each other.** bno_s0 is at epoch 85 against
+b3_s1's 137, so this is a maturity difference as much as a configuration one —
+and with one seed per arm it would prove nothing even at matched epochs (seed
+spread in this repo is 34-49 mm on the 70-keypoint metric).
+
+Against the published EMDB (24) table (Fast SAM 3D Body Table 1), b3_s1 lands
+next to **WHAM** — ahead of it on MPJPE (77.4 vs 79.7) and PVE (92.3 vs 94.4),
+just behind on PA-MPJPE (52.0 vs 50.4) — and well ahead of SMPLer-X-H (64.5 PA)
+and HMR2.0b (79.2 PA). WHAM is a *video* method; this is single-frame.
+
+**The mesh route beats the linear adapter on 16 of 17 sequences**, mean
+−1.73 mm, with per-sequence Pearson r = 0.989 and Spearman r = 0.961 between
+the two. Two conversions sharing no machinery agreeing that closely on the
+ranking is the evidence that neither distorts the result. The gain is largest
+where the pose is unusual — `outdoor_sitting` −4.9 mm, `outdoor_climb`
+−3.8 mm — which is where a fixed linear joint map is furthest from its fitting
+distribution.
+
+Note the headline gain is only ~1.8 mm even though the conversion floor drops
+18.8 -> 10.7 mm. That is arithmetic, not disappointment: floors do not subtract
+linearly. Treating model and conversion error as independent, sqrt(50^2 +
+18.8^2) = 53.4 against sqrt(50^2 + 10.7^2) = 51.1, so ~2.3 mm predicted against
+1.8 mm observed. The real win is that **PVE exists at all**.
+
### What these metrics cannot see
Both headline metrics are alignment-invariant, and that hides exactly the
@@ -253,6 +511,14 @@ the loop. MPJPE is mid-hip-aligned; PA-MPJPE is Procrustes (scale + rotation +
translation). Predictions use `joints_3d_local`, the rig-local pose, so the
camera translation never enters the metric.
+**EMDB-1.** All 17 sequences of the `emdb1` split, every frame where
+`good_frames_mask` is set and the subject is at least 60 % inside the image.
+Metrics are over the 24 SMPL kinematic joints, aligned at the midpoint of the
+two hips (SMPL indices 1 and 2, not the `pelvis` joint), reached through the
+fixed MHR70 → SMPL-24 map fitted on 3DPW train teacher labels. PA-MPJPE is
+Procrustes with uniform scale. Person boxes: say which of the two conventions
+above you used. PVE is not reported — see the EMDB section for why.
+
**COCO val2017.** Top-down with **ground-truth boxes**, one crop per annotated
person with `num_keypoints ≥ 1` and `iscrowd = 0`. These AP numbers are *not*
comparable to COCO-leaderboard AP, which includes detection. InstantHMR emits no
@@ -334,13 +600,17 @@ nothing to do with model quality. The harness therefore reports three rows:
specific to one model *and* one GT convention: applying b3_s1's to another
checkpoint, or an `h36m` one to `jointpositions`, is meaningless.
- **Fit it from the teacher, not from the student.** `--fit-adapter` uses one
+ **Fit it from the dataset annotations, not from the student.** `--fit-adapter` uses one
checkpoint's own predictions as the input side, so the map can absorb that
checkpoint's systematic error along with the rig offset — a different adapter
per checkpoint, and a fair reader will call it tuning.
- `benchmark/fit_adapter_mhr.py` instead pairs the **teacher's** MHR labels in
- `data/sam3d_gt_3dpw` with the H36M GT on the same 3DPW train frames, giving
- one adapter for every checkpoint that never saw a student:
+ `benchmark/fit_adapter_mhr.py` instead pairs the **released dataset's** MHR
+ labels in `data/sam3d_gt_3dpw` with the H36M GT on the same 3DPW train
+ frames, giving one adapter for every checkpoint that never saw a student.
+ (Those are `facebook/sam-3d-body-dataset` annotations built by
+ `datasets_pipeline/build_split.py`; only `data/sam3d_distill_mix` is teacher
+ inference. Earlier revisions of this file called them teacher labels — wrong,
+ and it changed what the residual below means.)
```bash
python benchmark/fit_adapter_mhr.py --sequence-dir /path/to/3DPW/sequenceFiles \
@@ -348,7 +618,7 @@ nothing to do with model quality. The harness therefore reports three rows:
```
That it is a rig conversion rather than an error sponge is visible two ways.
- The teacher's own J14 error against the GT drops from **44.90 mm to 14.83 mm**
+ The annotations' own J14 error against the GT drops from **44.90 mm to 14.83 mm**
on a held-out half — near the teacher's accuracy floor, which absorbing error
could not reach. And every row reads anatomically:
`right_hip = +1.16 right_hip - 0.32 left_hip` (widening SMPL's 120 mm hips
@@ -368,7 +638,13 @@ nothing to do with model quality. The harness therefore reports three rows:
val2017 is a 5k subset of val2014, which is disjoint from train2014. Verified by
image-id intersection: **0 of 5000** val2017 images appear in training.
-**3DPW test is contaminated.** `data/sam3d_gt_3dpw` holds only train sequences,
+**3DPW test is clean for every checkpoint trained on Jean Zay** — that corpus
+is coco/mpii/aic/sa1b/harmony4d plus `3dpw_train`, so the 24 test sequences are
+unseen for `b3_s1`, `v3_s1` and everything after them. The paragraph below
+applies to the **local** corpus and to `distill_mhr_only_ckpt90`, which was
+trained from it.
+
+**The local `data/` corpus is contaminated.** `data/sam3d_gt_3dpw` holds only train sequences,
but `data/sam3d_distill_mix` contains teacher-distilled crops from **all 60**
3DPW sequences — including all 24 test sequences (9,060 person-crops, ~28.5k
distinct frames across the dataset). `--exclude-seen` quantifies this: it splits
@@ -386,13 +662,18 @@ report tells you how large the effect is in the meantime.
benchmark/
download.py COCO fetcher + 3DPW presence check
make_3dpw_gt.py SMPL forward + H36M regressor -> <3DPW root>/gt_h36m/
- fit_adapter_mhr.py MHR70 -> J14 adapter from TEACHER labels (student-free)
+ make_emdb_gt.py SMPL forward -> <EMDB root>/gt_smpl24/ (+ a kp2d check)
+ fit_adapter_mhr.py MHR70 -> J14 / SMPL24 adapter from TEACHER labels
eval_3dpw.py 3D from an ONNX graph: MPJPE, PA-MPJPE, PCK3D, AUC
eval_3dpw_ckpt.py the same, for a .pth straight out of runs/
+ eval_emdb_ckpt.py EMDB-1 for a .pth; reuses the 3DPW crop and metrics
+ eval_smpl_fit.py EMDB-1 in SMPL space via mesh conversion: +PVE, lower floor
+ mhr_smpl.py the MHR rig, differentiable SMPL, and both fit directions
eval_coco.py 2D: OKS AP/AR, mean OKS, PCK, NME, per-keypoint breakdown
benchlib/
joints.py MHR70 <-> COCO17 / SMPL24 / H36M17 maps, J14 & J12 sets
metrics.py Procrustes alignment and the metric definitions
threedpw.py 3DPW pickle loading, the GT switch, projection, boxes
+ emdb.py EMDB-1 loading; extrinsics sense and the 24-joint choice
runner.py batched ONNX inference with overlapped image decoding
```
diff --git a/benchmark/benchlib/emdb.py b/benchmark/benchlib/emdb.py
new file mode 100644
index 0000000..f07a12a
--- /dev/null
+++ b/benchmark/benchlib/emdb.py
@@ -0,0 +1,135 @@
+"""EMDB-1 ground truth loading -- the 3DPW loader's structure, one subject.
+
+EMDB ships one pickle per sequence under ``<root>/P<n>/<seq>/<name>_data.pkl``
+with the frames beside it in ``images/<frame:05d>.jpg``. The fields we use:
+
+ smpl{poses_root (F,3), poses_body (F,69), betas (10,), trans (F,3)}
+ camera{intrinsics (3,3), extrinsics (F,4,4), width, height}
+ good_frames_mask (F,) reliable-GT mask, 3DPW's ``campose_valid``
+ bboxes{bboxes (F,4) xyxy, invalid_idxs} person boxes, **provided**
+ kp2d (F,24,2) the 24 joints projected -- see below
+ emdb1 / emdb2 split membership
+
+Two conventions were settled against the data rather than the docs, because
+guessing either gives quietly wrong numbers instead of a crash:
+
+* ``extrinsics`` is **world -> camera** (the same sense as 3DPW's
+ ``cam_poses``). Applied as-is it reprojects the GT joints onto ``kp2d`` to
+ 0.002 px; inverted, every joint lands behind the camera.
+* ``kp2d`` is the projection of the SMPL **kinematic-tree** joints, not
+ ``J_regressor @ posed vertices`` -- the latter reprojects ~1 px off and sits
+ 3.8 mm away in 3D. So "EMDB (24)" means the kinematic joints, which is what
+ ``make_emdb_gt.py`` caches into ``<root>/gt_smpl24/emdb1.npz``.
+
+Person boxes come in two flavours, because published tables use both:
+``gt-joints`` reproduces this repo's 3DPW protocol (projected GT joints padded
+by ``bbox_scale``, no detector in the loop) and ``annotated`` uses EMDB's own
+``bboxes`` field, which is what the "Oracle: evaluated with annotated bounding
+boxes" rows report.
+"""
+
+from __future__ import annotations
+
+import pickle
+from pathlib import Path
+
+import numpy as np
+
+from .threedpw import bbox_from_points, project
+
+EMDB1_SEQUENCES = 17 # sanity check: the EMDB-1 split has 17 sequences
+
+
+def gt_path(emdb_root: str | Path, gt_dir: str | Path | None = None) -> Path:
+ base = Path(gt_dir) if gt_dir else Path(emdb_root) / "gt_smpl24"
+ return base / "emdb1.npz"
+
+
+def load_gt(emdb_root: str | Path, gt_dir: str | Path | None = None) -> dict:
+ path = gt_path(emdb_root, gt_dir)
+ if not path.is_file():
+ raise FileNotFoundError(
+ f"EMDB ground truth not found: {path}\n"
+ "Build it once with benchmark/make_emdb_gt.py.")
+ with np.load(path) as z:
+ return {k: z[k] for k in z.files if k != "layout"}
+
+
+def build_samples(emdb_root: str | Path, stride: int = 1,
+ bbox: str = "gt-joints", bbox_scale: float = 1.2,
+ min_visible_frac: float = 0.6,
+ gt_dir: str | Path | None = None):
+ """Enumerate every evaluatable frame of EMDB-1.
+
+ Args:
+ emdb_root: directory holding ``P0/ ... P9/``.
+ stride: keep every Nth frame (1 = the full protocol).
+ bbox: ``gt-joints`` (projected GT joints padded by ``bbox_scale``, this
+ repo's 3DPW convention) or ``annotated`` (EMDB's own boxes).
+ min_visible_frac: drop a frame when fewer than this fraction of the
+ projected joints fall inside the image.
+
+ Returns:
+ ``(samples, gt)`` -- a list of dicts and an (N, 24, 3) array of
+ camera-space SMPL joints in metres, index-aligned.
+ """
+ if bbox not in ("gt-joints", "annotated"):
+ raise ValueError(f"unknown bbox source: {bbox}")
+ root = Path(emdb_root)
+ table = load_gt(root, gt_dir)
+
+ samples: list[dict] = []
+ gts: list[np.ndarray] = []
+ n_seq = 0
+
+ for pkl in sorted(root.glob("P*/*/*_data.pkl")):
+ with open(pkl, "rb") as f:
+ seq = pickle.load(f)
+ if not seq["emdb1"]:
+ continue
+ n_seq += 1
+ name = str(seq["name"])
+ K = np.asarray(seq["camera"]["intrinsics"], dtype=np.float64)
+ T_all = np.asarray(seq["camera"]["extrinsics"], dtype=np.float64)
+ W = int(seq["camera"]["width"])
+ H = int(seq["camera"]["height"])
+ good = np.asarray(seq["good_frames_mask"]).astype(bool)
+ joints_w = np.asarray(table[name], dtype=np.float64)
+ boxes = np.asarray(seq["bboxes"]["bboxes"], dtype=np.float64)
+ # EMDB flags the frames whose provided box is unusable; they only
+ # matter for bbox="annotated", where there is nothing to crop around.
+ bad_box = set(np.asarray(seq["bboxes"]["invalid_idxs"]).ravel().tolist())
+ img_dir = pkl.parent / "images"
+
+ for f in range(0, joints_w.shape[0], stride):
+ if not good[f]:
+ continue
+ if bbox == "annotated" and f in bad_box:
+ continue
+ T = T_all[f]
+ joints_cam = joints_w[f] @ T[:3, :3].T + T[:3, 3]
+ if (joints_cam[:, 2] <= 0).any(): # behind the camera
+ continue
+ uv = project(joints_cam, K)
+ inside = ((uv[:, 0] >= 0) & (uv[:, 0] < W)
+ & (uv[:, 1] >= 0) & (uv[:, 1] < H))
+ if inside.mean() < min_visible_frac:
+ continue
+ box = (bbox_from_points(uv, bbox_scale) if bbox == "gt-joints"
+ else boxes[f].astype(np.float32))
+ samples.append(dict(
+ image_path=str(img_dir / f"{f:05d}.jpg"),
+ bbox=box, uv=uv.astype(np.float32),
+ sequence=name, person=0, frame=f,
+ gender=str(seq["gender"]),
+ # EMDB is calibrated, so this is the real focal.
+ focal=float(K[1, 1]),
+ ))
+ gts.append(joints_cam)
+
+ if n_seq != EMDB1_SEQUENCES:
+ raise RuntimeError(f"found {n_seq} EMDB-1 sequences under {root}, "
+ f"expected {EMDB1_SEQUENCES}")
+ if not samples:
+ raise RuntimeError(f"no valid EMDB-1 samples found in {root}")
+ return samples, np.stack(gts)
diff --git a/benchmark/eval_all.py b/benchmark/eval_all.py
new file mode 100644
index 0000000..db036a5
--- /dev/null
+++ b/benchmark/eval_all.py
@@ -0,0 +1,212 @@
+#!/usr/bin/env python3
+"""One command per checkpoint: run every benchmark route, print one table.
+
+ python benchmark/eval_all.py --ckpt <run>/best_student_model_v3.pth
+
+Runs four evaluations and consolidates them:
+
+ 3DPW test J14 (H36M) + adapter eval_3dpw_ckpt.py
+ 3DPW test SMPL24 + PVE, J14 adapter-free eval_smpl_fit.py
+ EMDB-1 SMPL24 + adapter eval_emdb_ckpt.py
+ EMDB-1 SMPL24 + PVE eval_smpl_fit.py
+
+``--table-only`` skips the compute and re-prints the table from whatever is
+already in ``benchmark/results/``, which is what you want after a run or when
+adding a checkpoint to an existing comparison.
+
+Paths default to this machine's layout; override per site. See METRICS.md for
+what each row means and which space it is computed in.
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+import subprocess
+import sys
+from pathlib import Path
+
+ROOT = Path(__file__).resolve().parent.parent
+RESULTS = ROOT / "benchmark" / "results"
+
+
+def parse_args():
+ p = argparse.ArgumentParser(description=__doc__,
+ formatter_class=argparse.RawDescriptionHelpFormatter)
+ p.add_argument("--ckpt", nargs="*", default=[])
+ p.add_argument("--emdb-root", default="/home/madjel/Downloads/EMDB_root")
+ p.add_argument("--sequence-dir",
+ default="/home/madjel/Downloads/sequenceFiles/sequenceFiles")
+ p.add_argument("--image-root", default="/home/madjel/Downloads/imageFiles")
+ p.add_argument("--stride", type=int, default=1)
+ p.add_argument("--fit-iters", type=int, default=400)
+ p.add_argument("--fit-batch", type=int, default=128)
+ p.add_argument("--table-only", action="store_true")
+ p.add_argument("--skip", nargs="*", default=[],
+ choices=["3dpw-adapter", "3dpw-mesh", "emdb-adapter", "emdb-mesh"])
+ return p.parse_args()
+
+
+def run(cmd: list[str]) -> None:
+ print(f"\n$ {' '.join(cmd)}\n", flush=True)
+ subprocess.run(cmd, cwd=ROOT, check=True)
+
+
+def group_by_conditioning(ckpts: list[str]) -> list[list[str]]:
+ """Split checkpoints into groups that can share one crop pipeline.
+
+ ``eval_3dpw_ckpt.py`` and ``eval_emdb_ckpt.py`` build the dataset once for
+ all their checkpoints, so they refuse a mix of ``--cliff-focal`` settings --
+ the conditioning vector means something different in each, and feeding the
+ wrong one raises nothing, it just mis-places the person in depth. Runs from
+ before and after 2026-09-06 therefore have to go in separate invocations,
+ which this works out automatically instead of making the caller notice.
+ """
+ import torch
+ sys.path.insert(0, str(ROOT / "instanthmr_distill_train"))
+ import train_distill_mhr_only as T
+ groups: dict[bool, list[str]] = {}
+ for c in ckpts:
+ st = torch.load(c, map_location="cpu", weights_only=False)
+ cfg, _ = T.config_from_checkpoint(st.get("model_state_dict", st), c)
+ groups.setdefault(bool(cfg.cliff_focal), []).append(c)
+ del st
+ return list(groups.values())
+
+
+def merge_json(parts: list[Path], dest: Path) -> None:
+ """Concatenate per-group reports into the one file the table reads."""
+ out: dict = {}
+ for f in parts:
+ if f.is_file():
+ out.update(json.loads(f.read_text()))
+ f.unlink()
+ dest.parent.mkdir(parents=True, exist_ok=True)
+ dest.write_text(json.dumps(out, indent=2))
+
+
+def _load(name: str) -> dict:
+ f = RESULTS / name
+ return json.loads(f.read_text()) if f.is_file() else {}
+
+
+def _run_name(key: str) -> str:
+ parts = key.split("|")[0].split("/")
+ return parts[-3] if len(parts) >= 3 else key
+
+
+def table() -> None:
+ """The full comparison, one row per checkpoint per dataset."""
+ dpw_ad = _load("3dpw_test_alladapter.json")
+ dpw_me = _load("3dpw_test_smplfit.json")
+ emdb_ad = _load("emdb1_alladapter.json")
+ emdb_me = _load("emdb1_smplfit_gt-joints.json")
+
+ runs: list[str] = []
+ for src in (dpw_me, emdb_me, dpw_ad, emdb_ad):
+ for k in src:
+ n = _run_name(k)
+ if n not in runs:
+ runs.append(n)
+
+ def pick(src, name, *fields):
+ for k, v in src.items():
+ if _run_name(k) == name:
+ out = []
+ for f in fields:
+ if f.startswith("@"): # a joint_set row
+ r = next((r for r in v.get("results", [])
+ if r["joint_set"] == f[1:]), None)
+ out.append(r)
+ else:
+ out.append(v.get(f))
+ return out
+ return [None] * len(fields)
+
+ def fmt(v, nd=2):
+ return "-" if v is None else f"{v:.{nd}f}"
+
+ print("\n" + "=" * 108)
+ print("3DPW test — all 24 sequences, published-protocol GT")
+ print("=" * 108)
+ print(f"{'run':<12}{'ep':>5} | {'J14 PA':>8}{'J14 MPJPE':>11} (adapter)"
+ f" | {'J14 PA':>8}{'J14 MPJPE':>11} (via mesh fit)"
+ f" | {'SMPL24 PA':>10}{'MPJPE':>8}{'PVE':>8}")
+ for n in runs:
+ (ep,) = pick(dpw_me, n, "epoch")
+ a, = pick(dpw_ad, n, "@J14+adapter")
+ m = pick(dpw_me, n, "J14_h36m_viamesh_PA_MPJPE_mm", "J14_h36m_viamesh_MPJPE_mm",
+ "PA_MPJPE_mm", "MPJPE_mm", "PVE_mm")
+ print(f"{n:<12}{fmt(ep,0):>5} | "
+ f"{fmt(a['PA_MPJPE_mm']) if a else '-':>8}"
+ f"{fmt(a['MPJPE_mm']) if a else '-':>11} "
+ f" | {fmt(m[0]):>8}{fmt(m[1]):>11} "
+ f" | {fmt(m[2]):>10}{fmt(m[3]):>8}{fmt(m[4]):>8}")
+
+ print("\n" + "=" * 108)
+ print("EMDB-1 — all 17 sequences, the 'EMDB (24)' protocol")
+ print("=" * 108)
+ print(f"{'run':<12}{'ep':>5} | {'SMPL24 PA':>10}{'MPJPE':>9} (joint adapter)"
+ f" | {'SMPL24 PA':>10}{'MPJPE':>9}{'PVE':>8}{'PA-PVE':>9} (mesh fit)")
+ for n in runs:
+ (ep,) = pick(emdb_me, n, "epoch")
+ a, = pick(emdb_ad, n, "@SMPL24+adapter")
+ m = pick(emdb_me, n, "PA_MPJPE_mm", "MPJPE_mm", "PVE_mm", "PA_PVE_mm")
+ print(f"{n:<12}{fmt(ep,0):>5} | "
+ f"{fmt(a['PA_MPJPE_mm']) if a else '-':>10}"
+ f"{fmt(a['MPJPE_mm']) if a else '-':>9} "
+ f" | {fmt(m[0]):>10}{fmt(m[1]):>9}{fmt(m[2]):>8}{fmt(m[3]):>9}")
+ print("=" * 108)
+ print("Both J14 columns convert MHR->H36M; neither is adapter-free. We predict")
+ print("MHR, so a conversion is mandatory -- the joint adapter is the primary row.")
+ print("PVE is pelvis-aligned (the published definition); PA-PVE is the")
+ print("Procrustes variant and is NOT what papers call PVE. See METRICS.md.")
+ print("Conversion floors — mesh: 11.44 MPJPE / 10.66 PA / 13.61 PVE;")
+ print(" adapter: 25.11 MPJPE / 18.77 PA / no PVE.\n")
+
+
+def main():
+ args = parse_args()
+ if not args.table_only:
+ if not args.ckpt:
+ raise SystemExit("--ckpt is required unless --table-only")
+ py = [sys.executable]
+ common = ["--stride", str(args.stride)]
+ groups = group_by_conditioning(args.ckpt)
+ if "3dpw-adapter" not in args.skip:
+ parts = []
+ for gi, grp in enumerate(groups):
+ dst = RESULTS / f"_dpw_ad_{gi}.json"
+ run(py + ["benchmark/eval_3dpw_ckpt.py", "--ckpt", *grp,
+ "--sequence-dir", args.sequence_dir,
+ "--image-root", args.image_root, "--split", "test",
+ "--adapter", "benchmark/results/adapter_j14_h36m_teacher.npz",
+ "--out", str(dst)] + common)
+ parts.append(dst)
+ merge_json(parts, RESULTS / "3dpw_test_alladapter.json")
+ if "emdb-adapter" not in args.skip:
+ parts = []
+ for gi, grp in enumerate(groups):
+ dst = RESULTS / f"_emdb_ad_{gi}.json"
+ run(py + ["benchmark/eval_emdb_ckpt.py", "--ckpt", *grp,
+ "--emdb-root", args.emdb_root, "--out", str(dst)] + common)
+ parts.append(dst)
+ merge_json(parts, RESULTS / "emdb1_alladapter.json")
+ mesh = ["--fit-iters", str(args.fit_iters), "--fit-batch", str(args.fit_batch)]
+ if "3dpw-mesh" not in args.skip:
+ run(py + ["benchmark/eval_smpl_fit.py", "--dataset", "3dpw",
+ "--split", "test", "--ckpt", *args.ckpt,
+ "--sequence-dir", args.sequence_dir,
+ "--image-root", args.image_root,
+ "--out", "benchmark/results/3dpw_test_smplfit.json"]
+ + common + mesh)
+ if "emdb-mesh" not in args.skip:
+ run(py + ["benchmark/eval_smpl_fit.py", "--dataset", "emdb",
+ "--ckpt", *args.ckpt, "--emdb-root", args.emdb_root,
+ "--out", "benchmark/results/emdb1_smplfit_gt-joints.json"]
+ + common + mesh)
+ table()
+
+
+if __name__ == "__main__":
+ main()
diff --git a/benchmark/eval_emdb_ckpt.py b/benchmark/eval_emdb_ckpt.py
new file mode 100644
index 0000000..b696aee
--- /dev/null
+++ b/benchmark/eval_emdb_ckpt.py
@@ -0,0 +1,242 @@
+#!/usr/bin/env python3
+"""EMDB-1 evaluation for a training checkpoint (.pth).
+
+EMDB-1 is the 17-sequence, camera-frame split every paper reports as
+"EMDB (24)": 24 SMPL joints, the reference point the midpoint between the two
+hips, MPJPE and PA-MPJPE. (EMDB-2 is the global-trajectory split and is not
+what this model does.) One subject per sequence, so this is structurally a
+simpler 3DPW and reuses its crop, its forward pass and its metrics.
+
+ python benchmark/eval_emdb_ckpt.py \
+ --ckpt instanthmr_distill_train/runs/b3_s1/b3_s1/best_student_model_v3.pth \
+ --emdb-root /path/to/EMDB \
+ --adapter benchmark/results/adapter_smpl24_teacher.npz
+
+**Quote the SMPL24+adapter row.** InstantHMR regresses the 70 MHR keypoints,
+and 10 of SMPL's 24 joints (the three spines, the collars, the feet, the hands)
+have no MHR landmark at all, so a raw row does not exist for this joint set --
+the conversion has to be a fitted linear map. ``--adapter`` supplies the
+student-free one from ``fit_adapter_mhr.py --target smpl24``, fitted on 3DPW
+train teacher labels; EMDB is a different dataset, so it is a real holdout.
+Its conversion floor is 25.11 mm MPJPE / 18.77 mm PA-MPJPE -- quote that next
+to the result.
+
+The J14 and J12 rows below are the same 12/14 limb landmarks read straight off
+the MHR rig against SMPL's. They are internally comparable to this repo's 3DPW
+``--gt jointpositions`` numbers and to nothing published.
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+import sys
+from pathlib import Path
+
+import cv2
+import numpy as np
+import torch
+
+ROOT = Path(__file__).resolve().parent.parent
+sys.path.insert(0, str(ROOT / "instanthmr_distill_train"))
+sys.path.insert(0, str(ROOT / "benchmark"))
+
+import eval_3dpw as E # noqa: E402
+import train_distill_mhr_only as T # noqa: E402
+import val3dpw # noqa: E402
+from benchlib import emdb as D # noqa: E402
+from benchlib import joints as J # noqa: E402
+from benchlib import metrics as M # noqa: E402
+from eval_3dpw_ckpt import predict # noqa: E402
+
+MM = 1000.0
+SMPL24_HIPS = (J.SMPL["left_hip"], J.SMPL["right_hip"])
+
+
+def parse_args():
+ p = argparse.ArgumentParser(description=__doc__,
+ formatter_class=argparse.RawDescriptionHelpFormatter)
+ p.add_argument("--ckpt", nargs="+", required=True)
+ p.add_argument("--emdb-root", required=True)
+ p.add_argument("--stride", type=int, default=1)
+ p.add_argument("--bbox", default="gt-joints",
+ choices=["gt-joints", "annotated"],
+ help="gt-joints: projected GT joints padded by --bbox-scale, "
+ "this repo's 3DPW convention. annotated: EMDB's own "
+ "boxes, the published 'Oracle' protocol.")
+ p.add_argument("--bbox-scale", type=float, default=1.2)
+ p.add_argument("--gt-dir", default=None)
+ p.add_argument("--adapter", default="benchmark/results/adapter_smpl24_teacher.npz",
+ help="npz with the MHR70 -> SMPL24 regressor")
+ p.add_argument("--backbone", default=None)
+ p.add_argument("--cliff-focal", dest="cliff_focal", action="store_true",
+ default=None)
+ p.add_argument("--no-cliff-focal", dest="cliff_focal", action="store_false")
+ p.add_argument("--batch-size", type=int, default=64)
+ p.add_argument("--num-workers", type=int, default=8)
+ p.add_argument("--device", default="cuda")
+ p.add_argument("--out", default=None)
+ return p.parse_args()
+
+
+class EMDBValSet(torch.utils.data.Dataset):
+ """(crop, cliff_cond, ok) for every evaluatable EMDB-1 frame.
+
+ The crop and the conditioning vector come from ``val3dpw._preprocess``, not
+ a copy of it: that function is the transcription of the training dataset's
+ own crop, and the three places that build the CLIFF vector must agree or
+ the person is silently mis-placed in depth.
+ """
+
+ def __init__(self, emdb_root, stride=1, bbox="gt-joints", bbox_scale=1.2,
+ gt_dir=None, cliff_focal=False):
+ self.samples, gt = D.build_samples(
+ emdb_root, stride=stride, bbox=bbox, bbox_scale=bbox_scale,
+ gt_dir=gt_dir)
+ self.gt = np.asarray(gt, dtype=np.float32)
+ self.cliff_focal = cliff_focal
+
+ def __len__(self):
+ return len(self.samples)
+
+ def __getitem__(self, i):
+ s = self.samples[i]
+ bgr = cv2.imread(s["image_path"], cv2.IMREAD_COLOR)
+ if bgr is None:
+ return {"image": torch.zeros(3, val3dpw.INPUT_SIZE, val3dpw.INPUT_SIZE),
+ "cliff_cond": torch.zeros(3), "ok": torch.tensor(0.0)}
+ rgb = cv2.cvtColor(bgr, cv2.COLOR_BGR2RGB)
+ h, w = rgb.shape[:2]
+ crop, cliff = val3dpw._preprocess(
+ rgb, s["bbox"], h, w, s["focal"] if self.cliff_focal else None)
+ return {"image": torch.from_numpy(crop),
+ "cliff_cond": torch.from_numpy(cliff),
+ "ok": torch.tensor(1.0)}
+
+
+def evaluate_smpl24(pred_mhr: np.ndarray, gt: np.ndarray,
+ W: np.ndarray) -> tuple[dict, np.ndarray]:
+ """The published EMDB row, plus the per-sample PA error for the breakdown.
+
+ ``W`` was fitted on centred keypoints, so it is applied to centred
+ keypoints; both metrics are translation-invariant, so this costs nothing.
+ """
+ pred = np.einsum("jk,nkc->njc", W,
+ pred_mhr - pred_mhr.mean(axis=1, keepdims=True))
+ root_p = 0.5 * (pred[:, SMPL24_HIPS[0]] + pred[:, SMPL24_HIPS[1]])
+ root_g = 0.5 * (gt[:, SMPL24_HIPS[0]] + gt[:, SMPL24_HIPS[1]])
+ e_mpjpe = M.mpjpe(pred, gt, root=(root_p, root_g))
+ e_pa = M.pa_mpjpe(pred, gt)
+ return dict(
+ joint_set="SMPL24+adapter", num_joints=24,
+ num_samples=int(pred.shape[0]),
+ MPJPE_mm=float(e_mpjpe.mean()),
+ PA_MPJPE_mm=float(e_pa.mean()),
+ PCK3D_50mm=M.pck3d(e_pa, 50.0),
+ PCK3D_100mm=M.pck3d(e_pa, 100.0),
+ AUC_0_150mm=M.auc3d(e_pa),
+ per_joint_PA_MPJPE_mm={n: float(v) for n, v
+ in zip(J.SMPL24_NAMES, e_pa.mean(axis=0))},
+ ), e_pa.mean(axis=1)
+
+
+def main():
+ args = parse_args()
+ device = torch.device(args.device)
+
+ # Same rule as eval_3dpw_ckpt.py: rebuild each checkpoint's real training
+ # configuration. --bound-scales changes the forward pass, --cliff-focal
+ # changes what the conditioning vector means, and the defaults are wrong
+ # for both.
+ cfgs = {}
+ for ck_path in args.ckpt:
+ st = torch.load(ck_path, map_location="cpu", weights_only=False)
+ st = st.get("model_state_dict", st)
+ cfgs[ck_path], prov = T.config_from_checkpoint(
+ st, ck_path, backbone=args.backbone, cliff_focal=args.cliff_focal)
+ print(f"[cfg] {Path(ck_path).parent.name}/{Path(ck_path).name}: "
+ f"backbone={cfgs[ck_path].backbone} "
+ f"bound_scales={cfgs[ck_path].bound_scales} "
+ f"cliff_focal={cfgs[ck_path].cliff_focal} "
+ f"[{prov.get('cliff_focal', 'default')}]")
+ del st
+
+ focals = {c.cliff_focal for c in cfgs.values()}
+ if len(focals) > 1:
+ raise SystemExit(
+ "the checkpoints disagree on --cliff-focal, and the crop/"
+ "conditioning is built once for all of them.\n"
+ "Evaluate the two groups in separate invocations.")
+ cliff_focal = focals.pop()
+
+ cfg = next(iter(cfgs.values()))
+ mhr = T.MHRForwardPass(cfg.mhr_model_path, device,
+ kp_regressor=np.load(cfg.kp_regressor_path))
+ ad = np.load(args.adapter)
+ if str(ad["gt"]) != "smpl24":
+ raise SystemExit(f"{args.adapter} targets '{ad['gt']}', not smpl24; "
+ "fit one with fit_adapter_mhr.py --target smpl24")
+ W_adapt = ad["W"]
+
+ ds = EMDBValSet(args.emdb_root, stride=args.stride, bbox=args.bbox,
+ bbox_scale=args.bbox_scale, gt_dir=args.gt_dir,
+ cliff_focal=cliff_focal)
+ seqs = sorted({s["sequence"] for s in ds.samples})
+ print(f"[EMDB1] {len(ds):,} frames across {len(seqs)} sequences "
+ f"(stride {args.stride}, boxes: {args.bbox}), CLIFF conditioning "
+ f"{'angular (real per-sequence focal)' if cliff_focal else 'pixel-normalised'}",
+ flush=True)
+ loader = torch.utils.data.DataLoader(
+ ds, batch_size=args.batch_size, shuffle=False,
+ num_workers=args.num_workers, pin_memory=True)
+
+ report = {}
+ print(f"\n {'run':<24s} {'ckpt':<6s} {'ep':>4s} "
+ f"{'SMPL24+ad PA':>13s} {'SMPL24+ad MPJPE':>16s} "
+ f"{'J14 PA':>8s} {'J12 PA':>8s}")
+
+ for ck_path in args.ckpt:
+ model = T.InstantHMRStudent(cfgs[ck_path], pretrained=False).to(device)
+ ck = torch.load(ck_path, map_location="cpu", weights_only=False)
+ model.load_state_dict(ck["model_state_dict"])
+ pred, idx, n_dropped = predict(model, loader, mhr, device, cfg.use_amp)
+ del model
+ torch.cuda.empty_cache()
+
+ gt_arr = np.asarray(ds.gt, dtype=np.float64)[idx] * MM
+ head, e_sample = evaluate_smpl24(pred, gt_arr, W_adapt)
+ # The GT is the 24 SMPL joints, i.e. threedpw's "jointpositions" layout.
+ rows = [head] + [E.evaluate(pred, gt_arr, s, "jointpositions")
+ for s in ("J14", "J12")]
+
+ kept = [ds.samples[i] for i in idx]
+ per_seq = {}
+ for name in seqs:
+ m = np.array([s["sequence"] == name for s in kept])
+ if m.any():
+ per_seq[name] = dict(n=int(m.sum()),
+ PA_MPJPE_mm=float(e_sample[m].mean()))
+
+ report[ck_path] = dict(
+ ckpt=ck_path, dataset="EMDB1", split="emdb1", stride=args.stride,
+ bbox=args.bbox, adapter=str(args.adapter),
+ epoch=ck.get("epoch"), source=ck.get("source"),
+ n=int(pred.shape[0]), n_dropped=n_dropped,
+ num_sequences=len(seqs), results=rows,
+ per_sequence_SMPL24_adapter=per_seq)
+
+ run = Path(ck_path).parts[-3]
+ name = Path(ck_path).stem.replace("best_student_model_", "")
+ print(f" {run:<24s} {name:<6s} {str(ck.get('epoch')):>4s} "
+ f"{head['PA_MPJPE_mm']:13.2f} {head['MPJPE_mm']:16.2f} "
+ f"{rows[1]['PA_MPJPE_mm']:8.2f} {rows[2]['PA_MPJPE_mm']:8.2f}"
+ + (f" ({n_dropped} dropped)" if n_dropped else ""), flush=True)
+
+ if args.out:
+ Path(args.out).parent.mkdir(parents=True, exist_ok=True)
+ Path(args.out).write_text(json.dumps(report, indent=2))
+ print(f"\nwritten to {args.out}")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/benchmark/eval_smpl_fit.py b/benchmark/eval_smpl_fit.py
new file mode 100644
index 0000000..77e65b7
--- /dev/null
+++ b/benchmark/eval_smpl_fit.py
@@ -0,0 +1,411 @@
+#!/usr/bin/env python3
+"""EMDB-1 / 3DPW in SMPL space: MPJPE, PA-MPJPE and PVE via mesh conversion.
+
+The joint-adapter evaluators (``eval_emdb_ckpt.py``, ``eval_3dpw_ckpt.py``)
+score a linear MHR70 -> SMPL24 map, which carries an 18.8 mm PA-MPJPE floor and
+cannot produce vertices, so it cannot reach PVE at all. This converts the
+predicted **mesh** instead, which is what SAM 3D Body and Fast SAM 3D Body do
+for this same rig.
+
+Direction matters and only one is publishable: the prediction is fitted into
+SMPL, and the ground truth is left exactly as the benchmark defines it. Fitting
+the GT to the MHR rig instead would change the joint set, the mesh and the
+reference all at once, and no such number belongs in a published table however
+small it comes out.
+
+Three stages, none of which sees the ground truth:
+
+1. the student's MHR parameters -> the rig's own 18,439-vertex mesh;
+2. Meta's official barycentric surface map -> the same surface sampled in SMPL
+ topology, so every SMPL vertex has a KNOWN target (``mhr_smpl.py`` explains
+ why that matters: ICP has to discover the correspondence and reliably finds
+ a wrong-limb minimum its own residual cannot see);
+3. a labelled fit for SMPL theta/beta/trans, global orientation solved in
+ closed form by Procrustes.
+
+Measured end to end on a round trip through the rig, the conversion floor is
+**11.4 mm MPJPE / 10.7 mm PA-MPJPE / 13.6 mm PVE**, against 25.1 / 18.8 / n/a
+for the linear adapter. Quote it next to the result.
+
+ python benchmark/eval_smpl_fit.py \\
+ --ckpt instanthmr_distill_train/runs/b3_s1/b3_s1/best_student_model_v3.pth \\
+ --emdb-root /path/to/EMDB --out benchmark/results/emdb1_smplfit.json
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+import pickle
+import sys
+from pathlib import Path
+
+import cv2
+import numpy as np
+import torch
+
+ROOT = Path(__file__).resolve().parent.parent
+sys.path.insert(0, str(ROOT / "instanthmr_distill_train"))
+sys.path.insert(0, str(ROOT / "benchmark"))
+
+import train_distill_mhr_only as T # noqa: E402
+import val3dpw # noqa: E402
+from benchlib import emdb as D # noqa: E402
+from benchlib import joints as J # noqa: E402
+from benchlib import metrics as M # noqa: E402
+from eval_emdb_ckpt import EMDBValSet # noqa: E402
+from mhr_smpl import (MHRRig, SMPLModel, barycentric_transfer, # noqa: E402
+ fit_smpl_to_targets, load_surface_map)
+
+MM = 1000.0
+HIPS = (1, 2) # SMPL left/right hip; the mid-hip is the reference point
+
+
+def _chunked_mean(fn, A, B, chunk: int = 256) -> float:
+ """Mean of ``fn(A, B)`` computed in slices along the sample axis.
+
+ PVE runs over 6890 vertices per frame, and ``metrics.similarity_transform``
+ casts to float64 for the SVD -- at 24,103 frames that is ~4 GB per array
+ and ~16 GB of intermediates, which exhausted system memory and killed the
+ process (twice) right after the last fit batch, with all the expensive work
+ already done. Chunking bounds it to ~40 MB per slice and changes no number:
+ the metric is a mean over independent samples.
+ """
+ tot, n = 0.0, 0
+ for i in range(0, A.shape[0], chunk):
+ e = fn(A[i:i + chunk], B[i:i + chunk], i)
+ tot += float(e.sum())
+ n += e.size
+ return tot / n
+
+
+def parse_args():
+ p = argparse.ArgumentParser(description=__doc__,
+ formatter_class=argparse.RawDescriptionHelpFormatter)
+ p.add_argument("--ckpt", nargs="+", required=True)
+ p.add_argument("--dataset", default="emdb", choices=["emdb", "3dpw"])
+ p.add_argument("--emdb-root", default=None, help="EMDB: dir holding P0/../P9/")
+ p.add_argument("--sequence-dir", default=None, help="3DPW: sequenceFiles/")
+ p.add_argument("--image-root", default=None, help="3DPW: imageFiles/")
+ p.add_argument("--split", default="test", help="3DPW split")
+ p.add_argument("--stride", type=int, default=1)
+ p.add_argument("--bbox", default="gt-joints", choices=["gt-joints", "annotated"],
+ help="EMDB only; 3DPW always uses projected-GT-joint boxes")
+ p.add_argument("--fit-iters", type=int, default=400,
+ help="400 is within 0.3 mm of 550 on the round trip")
+ p.add_argument("--fit-batch", type=int, default=64)
+ p.add_argument("--batch-size", type=int, default=64)
+ p.add_argument("--num-workers", type=int, default=10)
+ p.add_argument("--smpl-dir", default="benchmark/data/smpl")
+ p.add_argument("--h36m-regressor",
+ default="benchmark/data/smpl/J_regressor_h36m.npy")
+ p.add_argument("--device", default="cuda")
+ p.add_argument("--out", default=None)
+ return p.parse_args()
+
+
+def predict_params(model, loader, device, use_amp=True):
+ """(N, 204) MHR model params, (N, 45) shape params, and the kept indices."""
+ model.eval()
+ mp, sh, keeps, base = [], [], [], 0
+ for b in loader:
+ img = b["image"].to(device, non_blocking=True)
+ cc = b["cliff_cond"].to(device, non_blocking=True)
+ with torch.amp.autocast(device_type="cuda", dtype=torch.float16, enabled=use_amp):
+ out = model(img, cc)
+ p = out["mhr_params"].float()
+ s = out["shape_params"].float()
+ finite = (torch.isfinite(p).all(1) & torch.isfinite(s).all(1)).cpu()
+ keep = b["ok"].bool() & finite
+ if bool(keep.any()):
+ k = keep.to(p.device)
+ mp.append(p[k].cpu())
+ sh.append(s[k].cpu())
+ keeps.append(base + np.nonzero(keep.numpy())[0])
+ base += int(keep.shape[0])
+ return torch.cat(mp), torch.cat(sh), np.concatenate(keeps)
+
+
+def emdb_gt_smpl(emdb_root: Path, samples, smpl_dir, device):
+ """GT SMPL joints and vertices in camera space, metres, per sample.
+
+ ``make_emdb_gt.py`` caches only the 24 joints (7 MB); the 6890 vertices PVE
+ needs would be 2 GB, so they are rebuilt here from the sequence parameters
+ instead of stored.
+ """
+ seq_info = {}
+ for pkl in sorted(Path(emdb_root).glob("P*/*/*_data.pkl")):
+ with open(pkl, "rb") as f:
+ d = pickle.load(f)
+ if d["emdb1"]:
+ seq_info[str(d["name"])] = d
+
+ idx_by_seq: dict[str, list[int]] = {n: [] for n in seq_info}
+ for i, s in enumerate(samples):
+ idx_by_seq[s["sequence"]].append(i)
+
+ J = torch.zeros(len(samples), 24, 3)
+ V = torch.zeros(len(samples), 6890, 3)
+ genders = [""] * len(samples)
+ models = {}
+ for name, d in seq_info.items():
+ ii = idx_by_seq[name]
+ if not ii:
+ continue
+ g = "male" if str(d["gender"]).lower().startswith("m") else "female"
+ if g not in models:
+ models[g] = SMPLModel(smpl_dir, g, device)
+ sm = models[g]
+ frames = np.array([samples[i]["frame"] for i in ii])
+ s = d["smpl"]
+ poses = np.concatenate([s["poses_root"], s["poses_body"]], axis=1)[frames]
+ trans = np.asarray(s["trans"], np.float32)[frames]
+ beta = np.asarray(s["betas"], np.float32).ravel()[:10]
+ Ecam = np.asarray(d["camera"]["extrinsics"], np.float64)[frames]
+ for k in range(0, len(ii), 64):
+ sl = slice(k, k + 64)
+ th = torch.as_tensor(poses[sl], dtype=torch.float32, device=device)
+ tr = torch.as_tensor(trans[sl], dtype=torch.float32, device=device)
+ be = torch.as_tensor(beta, dtype=torch.float32,
+ device=device)[None].expand(th.shape[0], 10)
+ v, j = sm.forward(th, be, tr)
+ Tc = torch.as_tensor(Ecam[sl], dtype=torch.float32, device=device)
+ R, t = Tc[:, :3, :3], Tc[:, :3, 3]
+ v = torch.einsum("nij,nvj->nvi", R, v) + t[:, None, :]
+ j = torch.einsum("nij,nvj->nvi", R, j) + t[:, None, :]
+ tgt = torch.tensor(ii[sl])
+ J[tgt] = j.cpu()
+ V[tgt] = v.cpu()
+ for i in ii:
+ genders[i] = g
+ return J, V, genders
+
+
+def threedpw_gt_smpl(sequence_dir, split, samples, smpl_dir, device):
+ """GT SMPL joints and vertices in camera space for 3DPW, metres.
+
+ The joints are the 24 SMPL **kinematic** ones -- the same convention EMDB
+ uses, and the same thing 3DPW stores in ``jointPositions`` -- so both
+ datasets are scored identically here. This deliberately does not use the
+ H36M regressor: that is the 14-joint 3DPW convention reported by
+ ``eval_3dpw_ckpt.py``, and it has no vertex analogue, so PVE could not be
+ defined against it.
+ """
+ import pickle as _pk
+ by_seq: dict[str, list[int]] = {}
+ for i, s in enumerate(samples):
+ by_seq.setdefault(s["sequence"], []).append(i)
+
+ J = torch.zeros(len(samples), 24, 3)
+ V = torch.zeros(len(samples), 6890, 3)
+ genders = [""] * len(samples)
+ models = {}
+ for name, ii in by_seq.items():
+ with open(Path(sequence_dir) / split / f"{name}.pkl", "rb") as f:
+ seq = _pk.load(f, encoding="latin1")
+ cam = np.asarray(seq["cam_poses"], np.float64)
+ for pid in sorted({samples[i]["person"] for i in ii}):
+ jj = [i for i in ii if samples[i]["person"] == pid]
+ g = str(seq["genders"][pid])
+ g = "male" if g.lower().startswith("m") else "female"
+ if g not in models:
+ models[g] = SMPLModel(smpl_dir, g, device)
+ sm = models[g]
+ frames = np.array([samples[i]["frame"] for i in jj])
+ poses = np.asarray(seq["poses"][pid], np.float32)[frames]
+ trans = np.asarray(seq["trans"][pid], np.float32)[frames]
+ beta = np.asarray(seq["betas"][pid], np.float32).ravel()[:10]
+ for k in range(0, len(jj), 64):
+ sl = slice(k, k + 64)
+ th = torch.as_tensor(poses[sl], dtype=torch.float32, device=device)
+ tr = torch.as_tensor(trans[sl], dtype=torch.float32, device=device)
+ be = torch.as_tensor(beta, dtype=torch.float32,
+ device=device)[None].expand(th.shape[0], 10)
+ v, j = sm.forward(th, be, tr)
+ Tc = torch.as_tensor(cam[frames[sl]], dtype=torch.float32, device=device)
+ R, t = Tc[:, :3, :3], Tc[:, :3, 3]
+ v = torch.einsum("nij,nvj->nvi", R, v) + t[:, None, :]
+ j = torch.einsum("nij,nvj->nvi", R, j) + t[:, None, :]
+ tgt = torch.tensor(jj[sl])
+ J[tgt] = j.cpu()
+ V[tgt] = v.cpu()
+ for i in jj:
+ genders[i] = g
+ return J, V, genders
+
+
+class ThreeDPWSet(torch.utils.data.Dataset):
+ """3DPW crops, built by the same ``val3dpw._preprocess`` EMDB uses."""
+
+ def __init__(self, sequence_dir, image_root, split, stride, cliff_focal):
+ from benchlib import threedpw as P3
+ self.samples, _ = P3.build_samples(
+ sequence_dir, image_root, split=split, stride=stride,
+ gt="jointpositions")
+ self.cliff_focal = cliff_focal
+
+ def __len__(self):
+ return len(self.samples)
+
+ def __getitem__(self, i):
+ s = self.samples[i]
+ bgr = cv2.imread(s["image_path"], cv2.IMREAD_COLOR)
+ if bgr is None:
+ return {"image": torch.zeros(3, val3dpw.INPUT_SIZE, val3dpw.INPUT_SIZE),
+ "cliff_cond": torch.zeros(3), "ok": torch.tensor(0.0)}
+ rgb = cv2.cvtColor(bgr, cv2.COLOR_BGR2RGB)
+ h, w = rgb.shape[:2]
+ crop, cliff = val3dpw._preprocess(
+ rgb, s["bbox"], h, w, s["focal"] if self.cliff_focal else None)
+ return {"image": torch.from_numpy(crop),
+ "cliff_cond": torch.from_numpy(cliff),
+ "ok": torch.tensor(1.0)}
+
+
+def main():
+ args = parse_args()
+ device = torch.device(args.device)
+ rig = MHRRig("checkpoints/mhr_model.pt", device)
+ tri, bary = load_surface_map("mhr2smpl", device)
+
+ report = {}
+ for ck_path in args.ckpt:
+ st = torch.load(ck_path, map_location="cpu", weights_only=False)
+ cfg, prov = T.config_from_checkpoint(st.get("model_state_dict", st), ck_path)
+ print(f"[cfg] {Path(ck_path).parts[-3]}: bound_scales={cfg.bound_scales} "
+ f"cliff_focal={cfg.cliff_focal}", flush=True)
+
+ if args.dataset == "emdb":
+ ds = EMDBValSet(args.emdb_root, stride=args.stride, bbox=args.bbox,
+ cliff_focal=cfg.cliff_focal)
+ else:
+ ds = ThreeDPWSet(args.sequence_dir, args.image_root, args.split,
+ args.stride, cfg.cliff_focal)
+ loader = torch.utils.data.DataLoader(
+ ds, batch_size=args.batch_size, shuffle=False,
+ num_workers=args.num_workers, pin_memory=True)
+ tag = "EMDB1" if args.dataset == "emdb" else f"3DPW/{args.split}"
+ print(f"[{tag}] {len(ds):,} frames, boxes={args.bbox}", flush=True)
+
+ model = T.InstantHMRStudent(cfg, pretrained=False).to(device)
+ model.load_state_dict(st["model_state_dict"])
+ mp, sh, idx = predict_params(model, loader, device, cfg.use_amp)
+ del model
+ torch.cuda.empty_cache()
+ print(f"[{tag}] {len(idx):,} predictions", flush=True)
+
+ kept = [ds.samples[i] for i in idx]
+ if args.dataset == "emdb":
+ Jgt, Vgt, genders = emdb_gt_smpl(Path(args.emdb_root), kept,
+ args.smpl_dir, device)
+ else:
+ Jgt, Vgt, genders = threedpw_gt_smpl(args.sequence_dir, args.split,
+ kept, args.smpl_dir, device)
+
+ # Fit per gender group, so one SMPL model serves each batch.
+ Jp = torch.zeros_like(Jgt)
+ Vp = torch.zeros_like(Vgt)
+ resid = torch.zeros(len(kept))
+ for g in ("male", "female"):
+ gi = np.array([i for i, x in enumerate(genders) if x == g])
+ if not len(gi):
+ continue
+ sm = SMPLModel(args.smpl_dir, g, device)
+ for k in range(0, len(gi), args.fit_batch):
+ sel = gi[k:k + args.fit_batch]
+ verts = rig.vertices(mp[sel].to(device), sh[sel].to(device))
+ tgt = barycentric_transfer(verts, rig.faces, tri, bary)
+ th, be, tr, r = fit_smpl_to_targets(sm, tgt, iters=args.fit_iters)
+ v, j = sm.forward(th, be, tr)
+ Jp[sel] = j.cpu()
+ Vp[sel] = v.cpu()
+ resid[sel] = r.mean(1).cpu()
+ if (k // args.fit_batch) % 20 == 0:
+ print(f" {g} {k:6d}/{len(gi)} residual "
+ f"{r.mean() * MM:5.2f} mm", flush=True)
+
+ jp, jg = Jp.numpy() * MM, Jgt.numpy() * MM # (N, 24, 3), small
+ rp = 0.5 * (jp[:, HIPS[0]] + jp[:, HIPS[1]])
+ rg = 0.5 * (jg[:, HIPS[0]] + jg[:, HIPS[1]])
+
+ # Everything vertex-shaped is done in ONE chunked pass, scaling inside
+ # the slice. The obvious version -- materialise `Vp.numpy() * MM` and
+ # `Vgt.numpy() * MM`, then einsum the H36M regressor over them -- needs
+ # ~17.6 GB at 35,463 frames and killed the process twice, right after
+ # the last fit batch with all the expensive work already done. Two
+ # separate causes, both fixed here: the scaled copies double 5.9 GB of
+ # float32, and `J_regressor_h36m.npy` is float64, so the einsum upcasts
+ # the entire (N, 6890, 3) array to a 5.9 GB float64 intermediate.
+ Jreg = np.load(args.h36m_regressor).astype(np.float32) # (17, 6890)
+ sel = J.J14_FROM_H36M17
+ CH = 256
+ pve_sum = pve_n = pa_pve_sum = 0.0
+ hp_parts, hg_parts = [], []
+ for i in range(0, Vp.shape[0], CH):
+ a = Vp[i:i + CH].numpy() * MM
+ b = Vgt[i:i + CH].numpy() * MM
+ n = a.shape[0]
+ e = M.mpjpe(a, b, root=(rp[i:i + n], rg[i:i + n]))
+ pve_sum += float(e.sum()); pve_n += e.size
+ pa_pve_sum += float(M.pa_mpjpe(a, b).sum())
+ hp_parts.append(np.einsum("jv,nvc->njc", Jreg, a)[:, sel])
+ hg_parts.append(np.einsum("jv,nvc->njc", Jreg, b)[:, sel])
+ h_p = np.concatenate(hp_parts) # already mm
+ h_g = np.concatenate(hg_parts)
+ del hp_parts, hg_parts
+ hp_r, hg_r = J.pelvis(h_p), J.pelvis(h_g)
+
+ res = dict(
+ ckpt=ck_path, dataset=tag, bbox=args.bbox, stride=args.stride,
+ n=int(len(kept)), fit_iters=args.fit_iters,
+ epoch=st.get("epoch"), source=st.get("source"),
+ fit_residual_mm=float(resid.mean() * MM),
+ MPJPE_mm=float(M.mpjpe(jp, jg, root=(rp, rg)).mean()),
+ PA_MPJPE_mm=float(M.pa_mpjpe(jp, jg).mean()),
+ PVE_mm=pve_sum / pve_n,
+ PA_PVE_mm=pa_pve_sum / pve_n,
+ # The published 3DPW protocol is 14 joints in the H36M convention,
+ # reached here THROUGH the mesh conversion: MHR mesh -> barycentric
+ # map -> fitted SMPL -> J_regressor_h36m, against the same
+ # regressor on the GT mesh.
+ #
+ # This is NOT an "adapter-free" number and must never be labelled
+ # one. We predict MHR, so a conversion to SMPL is mandatory; the
+ # only question is which conversion, never whether. This route puts
+ # it in mesh space, `eval_3dpw_ckpt.py --adapter` puts it in joint
+ # space. Both are legitimate, and note that J_regressor_h36m is
+ # itself a fitted linear map (SMPL vertices -> H36M joints) -- SMPL-
+ # native methods use it for exactly the same reason we need ours.
+ J14_h36m_viamesh_MPJPE_mm=float(M.mpjpe(h_p, h_g, root=(hp_r, hg_r)).mean()),
+ J14_h36m_viamesh_PA_MPJPE_mm=float(M.pa_mpjpe(h_p, h_g).mean()),
+ )
+
+ e = M.pa_mpjpe(jp, jg).mean(1)
+ res["per_sequence_PA_MPJPE_mm"] = {
+ n: float(e[[i for i, s in enumerate(kept) if s["sequence"] == n]].mean())
+ for n in sorted({s["sequence"] for s in kept})}
+ report[ck_path] = res
+ print(f"\n {Path(ck_path).parts[-3]:<10s} SMPL24: MPJPE {res['MPJPE_mm']:6.2f} "
+ f"PA {res['PA_MPJPE_mm']:6.2f} PVE {res['PVE_mm']:6.2f} "
+ f"PA-PVE {res['PA_PVE_mm']:6.2f} | J14/H36M via mesh: MPJPE "
+ f"{res['J14_h36m_viamesh_MPJPE_mm']:6.2f} "
+ f"PA {res['J14_h36m_viamesh_PA_MPJPE_mm']:6.2f}"
+ f" (fit residual {res['fit_residual_mm']:.2f} mm)\n", flush=True)
+ # Written after every checkpoint, not at the end: a full sweep is ~20
+ # minutes per checkpoint and losing all of it to a crash in the last
+ # one has already happened once.
+ if args.out:
+ # Merge, never clobber: adding one checkpoint later must not throw
+ # away the others, and a crash mid-sweep must not cost the runs
+ # that already finished.
+ dst = Path(args.out)
+ dst.parent.mkdir(parents=True, exist_ok=True)
+ merged = json.loads(dst.read_text()) if dst.is_file() else {}
+ merged.update(report)
+ dst.write_text(json.dumps(merged, indent=2))
+ print(f"written to {args.out}", flush=True)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/benchmark/fit_adapter_mhr.py b/benchmark/fit_adapter_mhr.py
index 3618372..34b343e 100644
--- a/benchmark/fit_adapter_mhr.py
+++ b/benchmark/fit_adapter_mhr.py
@@ -1,22 +1,40 @@
#!/usr/bin/env python3
-"""Fit the MHR70 -> J14 adapter from teacher labels, independent of any student.
+"""Fit an MHR70 -> SMPL/H36M joint adapter from dataset labels, student-free.
``eval_3dpw_ckpt.py --fit-adapter`` fits the map against one checkpoint's own
predictions, which lets it absorb that checkpoint's systematic error along with
-the skeleton difference. This fits the same map against the **teacher's** MHR
-labels in ``data/sam3d_gt_3dpw`` instead, so the result is one adapter for every
-checkpoint and describes only the rig conversion.
-
-Both sides come from the same 3DPW frame: the teacher's 70 MHR keypoints, and
+the skeleton difference. This fits the same map against the **dataset's own**
+MHR annotations in ``data/sam3d_gt_3dpw`` instead, so the result is one adapter
+for every checkpoint and describes only the rig conversion.
+
+Those annotations are the released ``facebook/sam-3d-body-dataset`` labels for
+``3dpw_train``, built by ``datasets_pipeline/build_split.py``. They are NOT
+teacher inference -- only ``data/sam3d_distill_mix`` is that, via
+``tools/annotate_dataset.py``. The distinction matters for what the numbers
+below mean: the residual after fitting is a rig-conversion floor, not a
+teacher's error.
+
+Both sides come from the same 3DPW frame: the dataset's 70 MHR keypoints, and
the H36M joints regressed from GT SMPL by ``make_3dpw_gt.py``. The annotation
filename carries the person index, and it matches 3DPW's own (verified: the
correct pairing sits at 0.5-2.4 deg of residual rotation, the wrong one at
7-108 deg).
+Two targets, both fitted on 3DPW train and both reported on a different split
+or a different dataset:
+
+ j14 the 14 LSP joints in the H36M convention, from the
+ ``make_3dpw_gt.py`` cache -- the 3DPW row.
+ smpl24 the 24 SMPL kinematic joints, straight out of the pickles'
+ ``jointPositions``. That field *is* the kinematic joint set
+ (verified to 0.001 mm by ``make_3dpw_gt.py --check``), which is
+ also what EMDB's ``kp2d`` projects -- so this adapter transfers to
+ EMDB unchanged, and 3DPW train is a clean holdout for it.
+
python benchmark/fit_adapter_mhr.py \\
--annotations data/sam3d_gt_3dpw/annotations \\
--sequence-dir /path/to/3DPW/sequenceFiles \\
- --out benchmark/results/adapter_j14_h36m_teacher.npz
+ --target j14 --out benchmark/results/adapter_j14_h36m_teacher.npz
"""
from __future__ import annotations
@@ -39,9 +57,14 @@ from benchlib import threedpw as P # noqa: E402
NAME_RX = re.compile(r"3dpw_(?P<seq>.+?)_image_(?P<frame>\d+)_p(?P<pid>\d+)\.npz$")
-def build_pairs(ann_dir: Path, sequence_dir: Path, split: str, stride: int):
- """(N, 70, 3) teacher MHR keypoints and (N, 17, 3) H36M GT, camera space, mm."""
- table = P.load_gt_h36m(sequence_dir, split)
+def build_pairs(ann_dir: Path, sequence_dir: Path, split: str, stride: int,
+ target: str):
+ """(N, 70, 3) annotated MHR keypoints and the paired GT, camera space, mm.
+
+ The GT is (N, 17, 3) H36M joints for ``target="j14"`` and (N, 24, 3) SMPL
+ kinematic joints for ``target="smpl24"``.
+ """
+ table = P.load_gt_h36m(sequence_dir, split) if target == "j14" else None
seqs: dict[str, dict] = {}
mhr, gt = [], []
skipped = 0
@@ -51,7 +74,7 @@ def build_pairs(ann_dir: Path, sequence_dir: Path, split: str, stride: int):
m = NAME_RX.match(f.name)
seq, frame, pid = m["seq"], int(m["frame"]), int(m["pid"])
key = f"{seq}|{pid}"
- if key not in table:
+ if table is not None and key not in table:
skipped += 1
continue
if seq not in seqs:
@@ -59,7 +82,9 @@ def build_pairs(ann_dir: Path, sequence_dir: Path, split: str, stride: int):
s = pickle.load(fh, encoding="latin1")
seqs[seq] = dict(cam=np.asarray(s["cam_poses"]),
valid=[np.asarray(v).astype(bool)
- for v in s["campose_valid"]])
+ for v in s["campose_valid"]],
+ jp=[np.asarray(j, np.float64).reshape(-1, 24, 3)
+ for j in s["jointPositions"]])
s = seqs[seq]
if frame >= len(s["cam"]) or not s["valid"][pid][frame]:
skipped += 1
@@ -67,7 +92,8 @@ def build_pairs(ann_dir: Path, sequence_dir: Path, split: str, stride: int):
z = np.load(f)
T = s["cam"][frame]
- g = table[key][frame] @ T[:3, :3].T + T[:3, 3] # world -> camera
+ gt_w = table[key][frame] if table is not None else s["jp"][pid][frame]
+ g = gt_w @ T[:3, :3].T + T[:3, 3] # world -> camera
mhr.append(z["joints_3d"])
gt.append(g)
@@ -81,32 +107,53 @@ def main():
ap.add_argument("--sequence-dir", required=True)
ap.add_argument("--split", default="train")
ap.add_argument("--stride", type=int, default=1)
- ap.add_argument("--out", default="benchmark/results/adapter_j14_h36m_teacher.npz")
+ ap.add_argument("--target", default="j14", choices=["j14", "smpl24"])
+ ap.add_argument("--out", default=None,
+ help="default: adapter_{j14_h36m,smpl24}_teacher.npz")
args = ap.parse_args()
+ out = Path(args.out) if args.out else Path(
+ "benchmark/results/adapter_"
+ + ("j14_h36m" if args.target == "j14" else "smpl24") + "_teacher.npz")
+
mhr, gt, n_files, skipped = build_pairs(
- Path(args.annotations), Path(args.sequence_dir), args.split, args.stride)
- print(f"[adapter] {len(mhr)} teacher/GT pairs from {n_files} annotations "
+ Path(args.annotations), Path(args.sequence_dir), args.split,
+ args.stride, args.target)
+ print(f"[adapter] {len(mhr)} annotation/GT pairs from {n_files} annotations "
f"({skipped} skipped: no GT track or campose_valid=0)")
- # How far apart the two skeletons are before any conversion. This is the
- # teacher's own J14 error plus the rig offset, and the adapter's job is the
- # second part.
- before = M.pa_mpjpe(mhr[:, J.J14_FROM_MHR70, :], gt[:, J.J14_FROM_H36M17, :]).mean()
-
+ # Target-side joints the adapter must reproduce, and the metric to read it
+ # by. j14 also has a raw row -- the same 14 landmarks taken straight off the
+ # MHR rig -- which is the annotation's deviation plus the rig offset; the
+ # adapter's job is the second part. smpl24 has no raw row: 10 of the 24
+ # (spines, collars, feet, hands) have no MHR landmark at all, which is
+ # exactly why the conversion has to be a fitted map.
+ if args.target == "j14":
+ Y = gt[:, J.J14_FROM_H36M17, :]
+ gt_name, hips = "h36m", J.J14_HIP_IDX
+ before = M.pa_mpjpe(mhr[:, J.J14_FROM_MHR70, :], Y).mean()
+ print(f"[adapter] annotation vs GT J14 PA-MPJPE, no adapter: {before:.2f} mm")
+ else:
+ Y = gt
+ gt_name = "smpl24"
+ hips = (J.SMPL["left_hip"], J.SMPL["right_hip"])
+
+ # Fit on one half, score on the other: the conversion floor an MHR-rigged
+ # model carries into this joint convention before it makes any mistake.
half = len(mhr) // 2
- W_half = E.fit_adapter(mhr[:half], gt[:half], "h36m")
- held = M.pa_mpjpe(
- np.einsum("jk,nkc->njc", W_half,
- mhr[half:] - mhr[half:].mean(axis=1, keepdims=True)),
- gt[half:, J.J14_FROM_H36M17, :]).mean()
- print(f"[adapter] teacher vs GT J14 PA-MPJPE: {before:.2f} mm raw, "
- f"{held:.2f} mm with a half-fit adapter on the held-out half")
-
- W = E.fit_adapter(mhr, gt, "h36m")
- Path(args.out).parent.mkdir(parents=True, exist_ok=True)
- np.savez(args.out, W=W, split=args.split, gt="h36m", source="teacher_mhr")
- print(f"[adapter] |W|max {np.abs(W).max():.2f} -> {args.out}")
+ W_half = E.fit_linear_adapter(mhr[:half], Y[:half])
+ P_held = np.einsum("jk,nkc->njc", W_half,
+ mhr[half:] - mhr[half:].mean(axis=1, keepdims=True))
+ root_p = 0.5 * (P_held[:, hips[0]] + P_held[:, hips[1]])
+ root_g = 0.5 * (Y[half:, hips[0]] + Y[half:, hips[1]])
+ print(f"[adapter] held-out half, adapter applied: "
+ f"{M.mpjpe(P_held, Y[half:], root=(root_p, root_g)).mean():.2f} mm MPJPE, "
+ f"{M.pa_mpjpe(P_held, Y[half:]).mean():.2f} mm PA-MPJPE")
+
+ W = E.fit_linear_adapter(mhr, Y)
+ out.parent.mkdir(parents=True, exist_ok=True)
+ np.savez(out, W=W, split=args.split, gt=gt_name, source="dataset_mhr")
+ print(f"[adapter] W {W.shape}, |W|max {np.abs(W).max():.2f} -> {out}")
if __name__ == "__main__":
diff --git a/benchmark/make_emdb_gt.py b/benchmark/make_emdb_gt.py
new file mode 100644
index 0000000..93f335b
--- /dev/null
+++ b/benchmark/make_emdb_gt.py
@@ -0,0 +1,119 @@
+#!/usr/bin/env python3
+"""Build EMDB ground truth: gendered SMPL forward -> the 24 kinematic joints.
+
+EMDB-1 (17 sequences, the camera-frame split every paper reports) ships SMPL
+parameters, not joints, so the reference has to be produced once. Unlike 3DPW
+there is no convention to choose: the dataset's own ``kp2d`` field is the
+projection of the **kinematic-tree** joints -- ``J_regressor @ posed vertices``
+reprojects 1.0 px off, the kinematic joints 0.00 px -- so those are what EMDB
+means by "24 joints", and they are ``smpl_forward``'s second output already.
+
+Writes ``<emdb-root>/gt_smpl24/emdb1.npz``, one (F, 24, 3) array of **world**
+joints per sequence, in the same frame the ``camera.extrinsics`` map from.
+
+ python benchmark/make_emdb_gt.py --emdb-root /path/to/EMDB \
+ --smpl-dir benchmark/data/smpl --check
+
+``--check`` reprojects with the sequence's own intrinsics/extrinsics and
+compares against ``kp2d``; it also prints how far the regressed joints sit from
+the kinematic ones, which is the only convention question EMDB leaves open.
+"""
+
+from __future__ import annotations
+
+import argparse
+import pickle
+from pathlib import Path
+
+import numpy as np
+import torch
+
+from make_3dpw_gt import load_smpl, smpl_forward
+
+
+def emdb1_sequences(root: Path) -> list[tuple[str, Path]]:
+ """(name, sequence directory) for every EMDB-1 sequence under ``root``."""
+ out = []
+ for pkl in sorted(root.glob("P*/*/*_data.pkl")):
+ with open(pkl, "rb") as f:
+ d = pickle.load(f)
+ if d["emdb1"]:
+ out.append((str(d["name"]), pkl.parent))
+ return out
+
+
+def main():
+ ap = argparse.ArgumentParser(description=__doc__,
+ formatter_class=argparse.RawDescriptionHelpFormatter)
+ ap.add_argument("--emdb-root", required=True)
+ ap.add_argument("--smpl-dir", default="benchmark/data/smpl")
+ ap.add_argument("--out", default=None,
+ help="default <emdb-root>/gt_smpl24")
+ ap.add_argument("--device", default="cuda")
+ ap.add_argument("--chunk", type=int, default=256)
+ ap.add_argument("--check", action="store_true")
+ args = ap.parse_args()
+
+ device = torch.device(args.device if torch.cuda.is_available() else "cpu")
+ root = Path(args.emdb_root)
+ out_dir = Path(args.out) if args.out else root / "gt_smpl24"
+ out_dir.mkdir(parents=True, exist_ok=True)
+
+ models = {g: load_smpl(Path(args.smpl_dir) / f"SMPL_{g.upper()}.pkl", device)
+ for g in ("male", "female")}
+ n_dirs = models["male"]["shapedirs"].shape[-1]
+
+ data: dict[str, np.ndarray] = {}
+ px_err, kin_vs_reg = [], []
+ for name, seq_dir in emdb1_sequences(root):
+ with open(next(seq_dir.glob("*_data.pkl")), "rb") as f:
+ d = pickle.load(f)
+ m = models["male" if d["gender"].lower().startswith("m") else "female"]
+ s = d["smpl"]
+ poses = np.concatenate([s["poses_root"], s["poses_body"]], axis=1)
+ # EMDB stores exactly 10 betas -- the count the published protocol uses --
+ # so the zero-pad to the model's shapedirs is lossless.
+ b = np.zeros(n_dirs, np.float32)
+ raw = np.asarray(s["betas"], np.float32).ravel()
+ b[:raw.shape[0]] = raw
+ b = torch.as_tensor(b, device=device)
+ p = torch.as_tensor(np.asarray(poses, np.float32), device=device)
+ t = torch.as_tensor(np.asarray(s["trans"], np.float32), device=device)
+
+ kin, reg = [], []
+ for i in range(0, p.shape[0], args.chunk):
+ V, Jk = smpl_forward(m, p[i:i + args.chunk], b, t[i:i + args.chunk])
+ kin.append(Jk.cpu().numpy())
+ if args.check:
+ reg.append((m["J_regressor"] @ V).cpu().numpy())
+ J = np.concatenate(kin).astype(np.float32)
+ data[name] = J
+ print(f" {name:<34s} {J.shape[0]:5d} frames {d['gender']}", flush=True)
+
+ if args.check:
+ R = np.concatenate(reg)
+ kin_vs_reg.append(np.linalg.norm(R - J, axis=-1).ravel())
+ K = np.asarray(d["camera"]["intrinsics"])
+ T = np.asarray(d["camera"]["extrinsics"])
+ Jc = np.einsum("nij,nkj->nki", T[:, :3, :3], J) + T[:, None, :3, 3]
+ uv = (Jc[..., :2] / Jc[..., 2:3]) * np.array([K[0, 0], K[1, 1]]) \
+ + np.array([K[0, 2], K[1, 2]])
+ px_err.append(np.linalg.norm(uv - d["kp2d"], axis=-1).ravel())
+
+ dst = out_dir / "emdb1.npz"
+ np.savez_compressed(dst, layout="smpl24_kinematic", **data)
+ n = sum(v.shape[0] for v in data.values())
+ print(f"[EMDB] {len(data)} sequences, {n} frames -> {dst}")
+
+ if args.check:
+ e = np.concatenate(px_err)
+ print(f"[check] reprojection vs kp2d: mean {e.mean():.4f} px, "
+ f"max {e.max():.4f} px")
+ d = np.concatenate(kin_vs_reg) * 1000.0
+ print(f"[check] J_regressor @ vertices vs kinematic joints: "
+ f"mean {d.mean():.3f} mm, max {d.max():.3f} mm "
+ f"(kp2d picks the kinematic ones)")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/benchmark/make_mhr_gt.py b/benchmark/make_mhr_gt.py
new file mode 100644
index 0000000..255dc8f
--- /dev/null
+++ b/benchmark/make_mhr_gt.py
@@ -0,0 +1,154 @@
+#!/usr/bin/env python3
+"""Solve and cache an MHR ground truth for EMDB-1 and 3DPW, once.
+
+Each benchmark's ground truth is a SMPL body. This fits the MHR rig to that
+exact surface and stores the resulting parameters, so the expensive part -- an
+optimisation per frame -- is paid once instead of on every checkpoint.
+
+ <root>/gt_mhr/<tag>.npz model_params (N, 204), shape_params (N, 45),
+ trans (N, 3), residual_mm (N,), keys (N,)
+
+Only 249 floats per frame, so both datasets together are ~60 MB.
+
+**What this is for, and what it is not for.** It gives two things:
+
+* the **oracle row** -- push this MHR body back through the forward conversion
+ and score it, and you have the best result any MHR-rigged model could
+ possibly achieve on this benchmark. That separates rig cost from model error
+ honestly, and it is an upper bound, labelled as such.
+* the MHR-space diagnostic, if you want to look at error on the rig's own 70
+ keypoints.
+
+It is **not** a ground truth to report against. Scoring predictions on MHR
+joints against this reference would change the joint set (MPJPE is not
+rig-independent), average error over 40 finger joints millimetres apart, and
+compare against a surface we produced with an optimiser told to look like an
+MHR model -- so whatever MHR cannot represent silently leaves the error. Report
+in SMPL space; see ``eval_smpl_fit.py``.
+
+ python benchmark/make_mhr_gt.py --dataset emdb --emdb-root /path/to/EMDB
+ python benchmark/make_mhr_gt.py --dataset 3dpw --split test \\
+ --sequence-dir /path/to/3DPW/sequenceFiles
+"""
+
+from __future__ import annotations
+
+import argparse
+import pickle
+import sys
+from pathlib import Path
+
+import numpy as np
+import torch
+
+sys.path.insert(0, str(Path(__file__).resolve().parent))
+
+from mhr_smpl import (MHRRig, SMPLModel, barycentric_transfer, # noqa: E402
+ fit_mhr_to_targets, load_surface_map)
+
+
+def emdb_frames(root: Path):
+ """(key, gender, poses, betas, trans) per EMDB-1 sequence."""
+ for pkl in sorted(root.glob("P*/*/*_data.pkl")):
+ with open(pkl, "rb") as f:
+ d = pickle.load(f)
+ if not d["emdb1"]:
+ continue
+ s = d["smpl"]
+ good = np.asarray(d["good_frames_mask"]).astype(bool)
+ idx = np.nonzero(good)[0]
+ yield (str(d["name"]), idx,
+ "male" if str(d["gender"]).lower().startswith("m") else "female",
+ np.concatenate([s["poses_root"], s["poses_body"]], axis=1)[idx],
+ np.asarray(s["betas"], np.float32).ravel()[:10],
+ np.asarray(s["trans"], np.float32)[idx])
+
+
+def threedpw_frames(seq_dir: Path, split: str):
+ for pkl in sorted((seq_dir / split).glob("*.pkl")):
+ with open(pkl, "rb") as f:
+ seq = pickle.load(f, encoding="latin1")
+ name = str(seq["sequence"])
+ for pid, poses in enumerate(seq["poses"]):
+ valid = np.asarray(seq["campose_valid"][pid]).astype(bool)
+ idx = np.nonzero(valid)[0]
+ g = str(seq["genders"][pid])
+ yield (f"{name}|{pid}", idx,
+ "male" if g.lower().startswith("m") else "female",
+ np.asarray(poses, np.float32)[idx],
+ np.asarray(seq["betas"][pid], np.float32).ravel()[:10],
+ np.asarray(seq["trans"][pid], np.float32)[idx])
+
+
+def main():
+ ap = argparse.ArgumentParser(description=__doc__,
+ formatter_class=argparse.RawDescriptionHelpFormatter)
+ ap.add_argument("--dataset", required=True, choices=["emdb", "3dpw"])
+ ap.add_argument("--emdb-root", default=None)
+ ap.add_argument("--sequence-dir", default=None)
+ ap.add_argument("--split", default="test")
+ ap.add_argument("--smpl-dir", default="benchmark/data/smpl")
+ ap.add_argument("--mhr", default="checkpoints/mhr_model.pt")
+ ap.add_argument("--iters", type=int, default=400)
+ ap.add_argument("--batch", type=int, default=96)
+ ap.add_argument("--stride", type=int, default=1)
+ ap.add_argument("--device", default="cuda")
+ ap.add_argument("--out", default=None)
+ args = ap.parse_args()
+
+ device = torch.device(args.device)
+ rig = MHRRig(args.mhr, device)
+ tri, bary = load_surface_map("smpl2mhr", device)
+ models: dict[str, SMPLModel] = {}
+
+ if args.dataset == "emdb":
+ root = Path(args.emdb_root)
+ src = emdb_frames(root)
+ out = Path(args.out) if args.out else root / "gt_mhr" / "emdb1.npz"
+ else:
+ root = Path(args.sequence_dir)
+ src = threedpw_frames(root, args.split)
+ out = Path(args.out) if args.out else root.parent / "gt_mhr" / f"{args.split}.npz"
+
+ store: dict[str, np.ndarray] = {}
+ all_res = []
+ for key, idx, gender, poses, beta, trans in src:
+ idx, poses, trans = idx[::args.stride], poses[::args.stride], trans[::args.stride]
+ if gender not in models:
+ models[gender] = SMPLModel(args.smpl_dir, gender, device)
+ sm = models[gender]
+ MP, SH, TR, RS = [], [], [], []
+ for k in range(0, len(idx), args.batch):
+ sl = slice(k, k + args.batch)
+ th = torch.as_tensor(poses[sl], dtype=torch.float32, device=device)
+ tr = torch.as_tensor(trans[sl], dtype=torch.float32, device=device)
+ be = torch.as_tensor(beta, dtype=torch.float32,
+ device=device)[None].expand(th.shape[0], 10)
+ with torch.no_grad():
+ V, _ = sm.forward(th, be, tr)
+ # GT SMPL surface, resampled in MHR topology.
+ tgt = barycentric_transfer(V, sm.faces, tri, bary)
+ mp, sh, t, res = fit_mhr_to_targets(rig, tgt, iters=args.iters)
+ MP.append(mp.cpu().numpy()); SH.append(sh.cpu().numpy())
+ TR.append(t.cpu().numpy()); RS.append(res.mean(1).cpu().numpy())
+ store[f"{key}|model_params"] = np.concatenate(MP).astype(np.float32)
+ store[f"{key}|shape_params"] = np.concatenate(SH).astype(np.float32)
+ store[f"{key}|trans"] = np.concatenate(TR).astype(np.float32)
+ store[f"{key}|frames"] = idx.astype(np.int32)
+ r = np.concatenate(RS)
+ store[f"{key}|residual_mm"] = (r * 1000).astype(np.float32)
+ all_res.append(r)
+ print(f" {key:<36s} {len(idx):5d} frames residual "
+ f"{r.mean() * 1000:6.2f} mm", flush=True)
+
+ a = np.concatenate(all_res) * 1000
+ out.parent.mkdir(parents=True, exist_ok=True)
+ np.savez_compressed(out, dataset=args.dataset, split=args.split,
+ iters=args.iters, **store)
+ print(f"[mhr-gt] {len(all_res)} tracks, {a.shape[0]} frames | "
+ f"surface residual mean {a.mean():.2f} mm, p95 {np.percentile(a, 95):.2f} mm")
+ print(f"[mhr-gt] -> {out}")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/benchmark/mhr_smpl.py b/benchmark/mhr_smpl.py
new file mode 100644
index 0000000..ee9a45f
--- /dev/null
+++ b/benchmark/mhr_smpl.py
@@ -0,0 +1,412 @@
+"""MHR <-> SMPL mesh conversion: the two rigs, and a solver that fits either to
+the other's surface.
+
+Why this exists. InstantHMR regresses MHR, and every published 3DPW/EMDB number
+is defined on SMPL -- 24 joints for MPJPE, 6890 vertices for PVE. The linear
+MHR70 -> SMPL24 joint adapter carries an 18.8 mm floor and cannot produce
+vertices at all, so it cannot reach PVE. Converting the *mesh* instead is what
+SAM 3D Body and Fast SAM 3D Body do for this same rig (their "iterative
+fitting"), and NLF does the equivalent for its nonparametric points.
+
+Direction matters, and both are used here for different jobs:
+
+``fit_mhr_to_smpl`` MHR params that reproduce a given SMPL surface. Used to
+ build matched-surface pairs for calibration, and to
+ compute the ORACLE row -- the best any MHR-rigged model
+ could score on a SMPL benchmark.
+``fit_smpl_to_targets`` SMPL params reproducing a predicted MHR surface, via
+ Meta's official barycentric map. This is the reported
+ path: it puts the prediction in the benchmark's own
+ space, where the GT is untouched.
+
+Never fit anything per-frame against the ground truth of a split being
+reported. Calibration runs on 3DPW *train*; the oracle row is labelled as an
+upper bound, not as a result.
+
+Units. The rig is centimetres, Y-up/Z-back; annotations and SMPL are metres,
+Y-down/Z-forward. ``MHRRig.vertices`` returns the vision frame, so everything
+in this module is metres unless a name says otherwise.
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+import numpy as np
+import torch
+
+MHR_NUM_VERTS = 18439
+MHR_NUM_MODEL_PARAMS = 204
+MHR_NUM_SHAPE_PARAMS = 45
+SMPL_NUM_VERTS = 6890
+
+
+class MHRRig:
+ """The TorchScript MHR rig, full 18,439-vertex mesh.
+
+ ``MHRForwardPass`` in the trainer evaluates the skeleton branch only, and
+ its optional vertex subset exists to keep a training step cheap. Conversion
+ needs the whole surface, so this calls the rig's own top-level forward --
+ identity blendshapes, pose correctives and skinning included, which is the
+ mesh the dataset's annotations describe.
+ """
+
+ def __init__(self, path: str | Path, device):
+ self.device = device
+ self.m = torch.jit.load(str(path), map_location=device).eval()
+ for p in self.m.parameters():
+ p.requires_grad_(False)
+ self.faces = self.m.character_torch.mesh.faces.long().to(device)
+
+ def vertices(self, model_params: torch.Tensor, shape_params: torch.Tensor,
+ correctives: bool = True) -> torch.Tensor:
+ """(B, 18439, 3) skin in the vision frame, metres, body-centred.
+
+ ``model_params[:, :3]`` is the rig's global translation. The corpus
+ converter zeroes it and carries the translation in ``cam_trans``
+ instead, so a caller that wants camera space adds that separately.
+ """
+ B = model_params.shape[0]
+ face = torch.zeros(B, 72, device=model_params.device,
+ dtype=model_params.dtype)
+ v, _ = self.m(shape_params, model_params, face, correctives)
+ v = v / 100.0
+ return torch.stack([v[..., 0], -v[..., 1], -v[..., 2]], dim=-1)
+
+
+def _chunked_nearest(A: torch.Tensor, B: torch.Tensor, chunk: int = 512):
+ """Per-point nearest neighbour of A in B: (distances, indices).
+
+ Chunked over A because the full (6890, 18439) matrix is 500 MB per sample
+ and the backward pass through it will not fit on an 11 GB card.
+ """
+ ds, ix = [], []
+ for i in range(0, A.shape[1], chunk):
+ d = torch.cdist(A[:, i:i + chunk], B)
+ m = d.min(-1)
+ ds.append(m.values)
+ ix.append(m.indices)
+ return torch.cat(ds, 1), torch.cat(ix, 1)
+
+
+def fit_mhr_to_smpl(rig: MHRRig, smpl_verts: torch.Tensor,
+ init_model: torch.Tensor, init_shape: torch.Tensor,
+ init_trans: torch.Tensor, iters: int = 600,
+ reassoc: int = 25, verbose: bool = False):
+ """Solve MHR parameters that reproduce ``smpl_verts``.
+
+ Point-to-point ICP: the correspondence is re-associated every ``reassoc``
+ steps under ``no_grad`` and held fixed in between, so the gradient never
+ flows through an argmin and the (6890, 18439) distance matrix is built once
+ per re-association rather than once per step.
+
+ Args:
+ smpl_verts: (B, 6890, 3) target surface, metres, any frame.
+ init_*: starting parameters; the dataset's own MHR annotation is the
+ natural choice and starts ~50 mm out.
+
+ Returns:
+ ``(model_params, shape_params, trans, residual)`` -- residual is the
+ (B, 6890) per-vertex distance from each SMPL vertex to the fitted MHR
+ surface, in metres.
+ """
+ P = init_model.clone().requires_grad_(True)
+ S = init_shape.clone().requires_grad_(True)
+ T = init_trans.clone().requires_grad_(True)
+ opt = torch.optim.Adam([{"params": [P], "lr": 3e-3},
+ {"params": [S], "lr": 1e-2},
+ {"params": [T], "lr": 3e-3}])
+ idx = None
+ for it in range(iters):
+ if it % reassoc == 0:
+ with torch.no_grad():
+ v = rig.vertices(P, S) + T[:, None, :]
+ dist, idx = _chunked_nearest(smpl_verts, v)
+ if verbose and it % (reassoc * 6) == 0:
+ print(f" it {it:4d} mean {dist.mean() * 1000:6.2f} mm", flush=True)
+ v = rig.vertices(P, S) + T[:, None, :]
+ tgt = torch.gather(v, 1, idx[..., None].expand(-1, -1, 3))
+ loss = ((smpl_verts - tgt) ** 2).sum(-1).mean()
+ opt.zero_grad()
+ loss.backward()
+ opt.step()
+
+ with torch.no_grad():
+ v = rig.vertices(P, S) + T[:, None, :]
+ dist, _ = _chunked_nearest(smpl_verts, v)
+ return P.detach(), S.detach(), T.detach(), dist
+
+
+class SMPLModel:
+ """Gendered SMPL as a differentiable layer over (theta, beta, trans).
+
+ ``make_3dpw_gt.smpl_forward`` cannot be reused here for two reasons: it
+ builds the kinematic chain with in-place writes into one tensor (fine for
+ the no-grad GT cache it was written for, but autograd refuses it), and it
+ takes a single shape vector for the whole batch. This version stacks the
+ chain instead and carries per-sample betas, so a whole batch fits in one
+ call. It is verified against that function to float precision below.
+ """
+
+ def __init__(self, smpl_dir: str | Path, gender: str, device):
+ import pickle
+ from make_3dpw_gt import _install_chumpy_stub, load_smpl
+ path = Path(smpl_dir) / f"SMPL_{gender.upper()}.pkl"
+ self.m = load_smpl(path, device)
+ self.n_dirs = self.m["shapedirs"].shape[-1]
+ self.device = device
+ _install_chumpy_stub()
+ with open(path, "rb") as f:
+ self.faces = torch.as_tensor(
+ np.asarray(pickle.load(f, encoding="latin1")["f"], np.int64),
+ device=device)
+ # Unique undirected edges, for the edge term in fit_smpl_to_targets.
+ e = torch.cat([self.faces[:, [0, 1]], self.faces[:, [1, 2]],
+ self.faces[:, [2, 0]]], dim=0)
+ e = torch.unique(torch.stack([e.min(1).values, e.max(1).values], 1), dim=0)
+ self.edges = (e[:, 0], e[:, 1])
+
+ def forward(self, theta: torch.Tensor, beta10: torch.Tensor,
+ trans: torch.Tensor):
+ """(B, 6890, 3) vertices and (B, 24, 3) kinematic joints, metres.
+
+ ``beta10`` is the 10 coefficients the published protocol uses; the rest
+ of the shape space stays zero, which is lossless on 3DPW and EMDB
+ (both store exactly those 10 as non-zero).
+ """
+ from make_3dpw_gt import rodrigues
+ m = self.m
+ N = theta.shape[0]
+ b = torch.zeros(N, self.n_dirs, device=theta.device, dtype=theta.dtype)
+ b = torch.cat([beta10, b[:, beta10.shape[1]:]], dim=1)
+
+ v_shaped = m["v_template"] + torch.einsum("vck,nk->nvc", m["shapedirs"], b)
+ J = torch.einsum("jv,nvc->njc", m["J_regressor"], v_shaped) # (N,24,3)
+ R = rodrigues(theta.reshape(N, 24, 3))
+ eye = torch.eye(3, device=theta.device).expand(N, 23, 3, 3)
+ pose_feature = (R[:, 1:] - eye).reshape(N, 207)
+ v_posed = v_shaped + torch.einsum("vck,nk->nvc", m["posedirs"], pose_feature)
+
+ def rt(rot, t):
+ bottom = torch.zeros(N, 1, 4, device=theta.device, dtype=theta.dtype)
+ bottom[..., 3] = 1.0
+ return torch.cat([torch.cat([rot, t[..., None]], dim=-1), bottom], dim=1)
+
+ parents = m["parents"]
+ Gs = [rt(R[:, 0], J[:, 0])]
+ for i in range(1, 24):
+ Gs.append(Gs[parents[i]] @ rt(R[:, i], J[:, i] - J[:, parents[i]]))
+ G = torch.stack(Gs, dim=1) # (N,24,4,4)
+ J_posed = G[:, :, :3, 3] + trans[:, None, :]
+
+ Jh = torch.cat([J, torch.zeros(N, 24, 1, device=theta.device,
+ dtype=theta.dtype)], dim=-1)
+ G = G - torch.nn.functional.pad(G @ Jh[..., None], (3, 0, 0, 0))
+ T = torch.einsum("vj,njab->nvab", m["weights"], G)
+ v_h = torch.cat([v_posed, torch.ones(N, v_posed.shape[1], 1,
+ device=theta.device,
+ dtype=theta.dtype)], dim=-1)
+ verts = torch.einsum("nvab,nvb->nva", T, v_h)[..., :3]
+ return verts + trans[:, None, :], J_posed
+
+
+# --------------------------------------------------------------------------
+# facebookresearch/MHR, tools/mhr_smpl_conversion/assets (Apache-2.0). Each
+# target vertex is a barycentric point on a source triangle, so the map is a
+# topology constant: indices and weights, no coordinate frame baked in.
+#
+# This is what makes the conversion tractable. Fitting by ICP has to *discover*
+# the correspondence, and its search has a local minimum whose own residual
+# cannot see it -- the mesh overlaps the target while limbs match the wrong
+# limbs (measured: 12 mm surface residual, 76 mm PA-MPJPE). With the mapping,
+# correspondence is KNOWN, vertex i pairs with vertex i, and the fit is
+# well-posed from a cold start.
+#
+# Verified against this repo's rig before use: triangle ids max at 36,871
+# against the rig's 36,874 faces, barycentric rows sum to 1, and the
+# reconstructed SMPL-topology mesh has a mean nearest-vertex spacing of
+# 13.88 mm against real SMPL's 14.37 mm -- a mapping built for a different mesh
+# would scatter neighbouring vertices onto unrelated triangles.
+
+MAP_DIR = Path(__file__).resolve().parent / "data" / "mhr_smpl_conversion"
+
+
+def load_surface_map(direction: str, device, map_dir: Path | None = None):
+ """(triangle_ids, barycentric weights) for ``mhr2smpl`` or ``smpl2mhr``."""
+ d = Path(map_dir) if map_dir else MAP_DIR
+ path = d / f"{direction}_mapping.npz"
+ if not path.is_file():
+ raise FileNotFoundError(
+ f"{path} not found. Copy it from facebookresearch/MHR, "
+ "tools/mhr_smpl_conversion/assets/ (Apache-2.0).")
+ z = np.load(path)
+ return (torch.as_tensor(z["triangle_ids"], dtype=torch.long, device=device),
+ torch.as_tensor(z["baryc_coords"], dtype=torch.float32, device=device))
+
+
+def barycentric_transfer(src_verts: torch.Tensor, src_faces: torch.Tensor,
+ tri: torch.Tensor, bary: torch.Tensor) -> torch.Tensor:
+ """(B, T, 3) target-topology vertices sampled off the source surface.
+
+ Frame-agnostic: it is a weighted sum of source vertices, so whatever frame
+ and units go in come out. No centimetre conversion here -- ``MHRRig`` has
+ already put the rig in metres.
+ """
+ corners = src_verts[:, src_faces[tri], :] # (B, T, 3, 3)
+ return (corners * bary[None, :, :, None]).sum(dim=2)
+
+
+def _matrix_to_axis_angle(R: torch.Tensor) -> torch.Tensor:
+ """(B, 3, 3) rotation matrices -> (B, 3) axis-angle."""
+ c = ((R[:, 0, 0] + R[:, 1, 1] + R[:, 2, 2] - 1) / 2).clamp(-1, 1)
+ ang = torch.acos(c)
+ ax = torch.stack([R[:, 2, 1] - R[:, 1, 2],
+ R[:, 0, 2] - R[:, 2, 0],
+ R[:, 1, 0] - R[:, 0, 1]], dim=-1)
+ return ax / (2 * torch.sin(ang).clamp_min(1e-8))[:, None] * ang[:, None]
+
+
+def fit_smpl_to_targets(smpl: SMPLModel, targets: torch.Tensor,
+ iters: int = 300, w_edge: float = 1.0,
+ edge_until: float = 0.3, verbose: bool = False):
+ """SMPL parameters reproducing ``targets``, which are IN SMPL TOPOLOGY.
+
+ ``targets[:, i]`` is the position vertex i should take, so this is a plain
+ labelled regression -- no correspondence search, no local minimum of the
+ kind that defeats ICP, and safe to start from the mean pose.
+
+ The edge term compares edge *vectors* rather than positions, which
+ constrains local shape independently of where the body is, and is weighted
+ down after ``edge_until`` of the schedule so the endgame is driven by
+ absolute vertex positions. This mirrors the staged weighting in Meta's own
+ PyTorch backend.
+ """
+ N = targets.shape[0]
+ dev = targets.device
+
+ # Closed-form global orientation. Known correspondence makes this a plain
+ # Procrustes between SMPL's rest mesh and the target, and it matters a lot:
+ # the body can be facing anywhere in camera space, and Adam started from
+ # identity has to walk the whole way there through axis-angle. Without it
+ # the same fit stalls at 40-51 mm of vertex residual.
+ with torch.no_grad():
+ z3 = torch.zeros(N, 3, device=dev)
+ v0, J0 = smpl.forward(torch.zeros(N, 72, device=dev),
+ torch.zeros(N, 10, device=dev), z3)
+ A = v0 - v0.mean(1, keepdim=True)
+ B = targets - targets.mean(1, keepdim=True)
+ U, _, Vt = torch.linalg.svd(A.transpose(1, 2) @ B)
+ d = torch.sign(torch.linalg.det(Vt.transpose(1, 2) @ U.transpose(1, 2)))
+ D = torch.eye(3, device=dev).expand(N, 3, 3).clone()
+ D[:, 2, 2] = d
+ R = Vt.transpose(1, 2) @ D @ U.transpose(1, 2)
+ root = _matrix_to_axis_angle(R)
+ th0 = torch.zeros(N, 72, device=dev)
+ th0[:, :3] = root
+ v1, _ = smpl.forward(th0, torch.zeros(N, 10, device=dev), z3)
+ tr0 = targets.mean(1) - v1.mean(1)
+
+ th = th0.clone().requires_grad_(True)
+ be = torch.zeros(N, 10, device=dev, requires_grad=True)
+ tr = tr0.clone().requires_grad_(True)
+ opt = torch.optim.Adam([{"params": [th], "lr": 5e-2},
+ {"params": [be], "lr": 2e-2},
+ {"params": [tr], "lr": 2e-2}])
+ sched = torch.optim.lr_scheduler.MultiStepLR(
+ opt, milestones=[int(iters * 0.5), int(iters * 0.8)], gamma=0.1)
+ e0, e1 = smpl.edges
+ tgt_edge = targets[:, e1] - targets[:, e0]
+ for it in range(iters):
+ v, _ = smpl.forward(th, be, tr)
+ loss = ((v - targets) ** 2).sum(-1).mean()
+ w = w_edge if it < edge_until * iters else 0.1 * w_edge
+ loss = loss + w * (((v[:, e1] - v[:, e0]) - tgt_edge) ** 2).sum(-1).mean()
+ opt.zero_grad()
+ loss.backward()
+ opt.step()
+ sched.step()
+ if verbose and it % 50 == 0:
+ with torch.no_grad():
+ print(f" it {it:4d} vertex {(v - targets).norm(dim=-1).mean() * 1000:6.2f} mm",
+ flush=True)
+ with torch.no_grad():
+ v, J = smpl.forward(th, be, tr)
+ resid = (v - targets).norm(dim=-1)
+ return th.detach(), be.detach(), tr.detach(), resid
+
+
+def _matrix_to_mhr_root(R: torch.Tensor) -> torch.Tensor:
+ """(B, 3, 3) vision-frame rotations -> the rig's ``model_params[3:6]``.
+
+ The rig drives its root through an extrinsic-XYZ Euler triple, and in the
+ vision frame the last two axes are negated -- determined empirically, not
+ assumed: setting ``params[3:6] = [0.2, -0.3, 0.4]`` produces a mesh whose
+ recovered extrinsic-XYZ Euler is ``[0.2, 0.3, -0.4]``. So the map is
+ ``[e_x, -e_y, -e_z]``.
+ """
+ sy = (-R[:, 2, 0]).clamp(-1, 1)
+ y = torch.asin(sy)
+ x = torch.atan2(R[:, 2, 1], R[:, 2, 2])
+ z = torch.atan2(R[:, 1, 0], R[:, 0, 0])
+ return torch.stack([x, -y, -z], dim=-1)
+
+
+def fit_mhr_to_targets(rig: MHRRig, targets: torch.Tensor, iters: int = 400,
+ verbose: bool = False):
+ """MHR parameters reproducing ``targets``, which are IN MHR TOPOLOGY.
+
+ The mirror of ``fit_smpl_to_targets``: ``targets[:, i]`` is where MHR vertex
+ i should be, so correspondence is known and the fit is cold-startable. Feed
+ it a GT SMPL mesh pushed through the official ``smpl2mhr`` barycentric map.
+
+ Used to build the ORACLE reference -- the MHR body that best reproduces the
+ benchmark's ground-truth surface. Scoring that back through the forward
+ conversion gives the best score any MHR-rigged model could achieve, which
+ is the honest way to separate rig cost from model error. It is an upper
+ bound and must be labelled as one; it is not a result.
+
+ ``model_params[:3]`` (the rig's own global translation) is held at zero and
+ a separate translation is fitted instead, matching how the corpus stores
+ pose and placement separately.
+ """
+ N = targets.shape[0]
+ dev = targets.device
+ with torch.no_grad():
+ V0 = rig.vertices(torch.zeros(N, MHR_NUM_MODEL_PARAMS, device=dev),
+ torch.zeros(N, MHR_NUM_SHAPE_PARAMS, device=dev))
+ A = V0 - V0.mean(1, keepdim=True)
+ B = targets - targets.mean(1, keepdim=True)
+ U, _, Vt = torch.linalg.svd(A.transpose(1, 2) @ B)
+ d = torch.sign(torch.linalg.det(Vt.transpose(1, 2) @ U.transpose(1, 2)))
+ D = torch.eye(3, device=dev).expand(N, 3, 3).clone()
+ D[:, 2, 2] = d
+ p0 = torch.zeros(N, MHR_NUM_MODEL_PARAMS, device=dev)
+ p0[:, 3:6] = _matrix_to_mhr_root(Vt.transpose(1, 2) @ D @ U.transpose(1, 2))
+ v1 = rig.vertices(p0, torch.zeros(N, MHR_NUM_SHAPE_PARAMS, device=dev))
+ t0 = targets.mean(1) - v1.mean(1)
+
+ free = p0[:, 3:].clone().requires_grad_(True) # [:3] stays zero
+ sh = torch.zeros(N, MHR_NUM_SHAPE_PARAMS, device=dev, requires_grad=True)
+ tr = t0.clone().requires_grad_(True)
+ opt = torch.optim.Adam([{"params": [free], "lr": 3e-2},
+ {"params": [sh], "lr": 2e-2},
+ {"params": [tr], "lr": 2e-2}])
+ sched = torch.optim.lr_scheduler.MultiStepLR(
+ opt, milestones=[int(iters * 0.5), int(iters * 0.8)], gamma=0.1)
+ zeros3 = torch.zeros(N, 3, device=dev)
+ for it in range(iters):
+ mp = torch.cat([zeros3, free], dim=1)
+ v = rig.vertices(mp, sh) + tr[:, None, :]
+ loss = ((v - targets) ** 2).sum(-1).mean()
+ opt.zero_grad()
+ loss.backward()
+ opt.step()
+ sched.step()
+ if verbose and it % 100 == 0:
+ print(f" it {it:4d} {(v - targets).norm(dim=-1).mean() * 1000:6.2f} mm",
+ flush=True)
+ with torch.no_grad():
+ mp = torch.cat([zeros3, free], dim=1)
+ v = rig.vertices(mp, sh) + tr[:, None, :]
+ resid = (v - targets).norm(dim=-1)
+ return mp.detach(), sh.detach(), tr.detach(), resid
diff --git a/benchmark/results/3dpw_test_alladapter.json b/benchmark/results/3dpw_test_alladapter.json
new file mode 100644
index 0000000..5143458
--- /dev/null
+++ b/benchmark/results/3dpw_test_alladapter.json
@@ -0,0 +1,146 @@
+{
+ "instanthmr_distill_train/runs/b3_s1/b3_s1/best_student_model_v3.pth|h36m": {
+ "ckpt": "instanthmr_distill_train/runs/b3_s1/b3_s1/best_student_model_v3.pth",
+ "gt": "h36m",
+ "split": "test",
+ "stride": 1,
+ "epoch": 137,
+ "source": "ema",
+ "n": 35463,
+ "n_dropped": 0,
+ "results": [
+ {
+ "joint_set": "J14",
+ "num_joints": 14,
+ "num_samples": 35463,
+ "MPJPE_mm": 104.63785012091508,
+ "PA_MPJPE_mm": 67.89201715239723,
+ "PCK3D_50mm": 0.386628316837267,
+ "PCK3D_100mm": 0.8279313248013019,
+ "AUC_0_150mm": 0.555249314824265,
+ "per_joint_PA_MPJPE_mm": {
+ "right_ankle": 66.1026158925688,
+ "right_knee": 48.77531527426408,
+ "right_hip": 98.43968262009881,
+ "left_hip": 86.54123107665853,
+ "left_knee": 46.110874847033735,
+ "left_ankle": 67.11189987887853,
+ "right_wrist": 70.71902986402077,
+ "right_elbow": 57.68874380634787,
+ "right_shoulder": 51.452820373726844,
+ "left_shoulder": 53.46686079217727,
+ "left_elbow": 66.61272199119497,
+ "left_wrist": 74.65868335746043,
+ "neck": 31.322680447479044,
+ "head": 131.48507991165152
+ }
+ },
+ {
+ "joint_set": "J12",
+ "num_joints": 12,
+ "num_samples": 35463,
+ "MPJPE_mm": 102.43934163084393,
+ "PA_MPJPE_mm": 62.492379121774945,
+ "PCK3D_50mm": 0.43160947090394686,
+ "PCK3D_100mm": 0.8874202220154339,
+ "AUC_0_150mm": 0.5877625294150285,
+ "per_joint_PA_MPJPE_mm": {
+ "right_ankle": 62.453416312484485,
+ "right_knee": 50.619841347293885,
+ "right_hip": 98.35461927230007,
+ "left_hip": 85.97593910675288,
+ "left_knee": 47.09601993678759,
+ "left_ankle": 62.49923408065495,
+ "right_wrist": 66.505798652139,
+ "right_elbow": 48.842995632922765,
+ "right_shoulder": 51.30888543605562,
+ "left_shoulder": 51.65398595718133,
+ "left_elbow": 54.28141719363774,
+ "left_wrist": 70.316396533089
+ }
+ },
+ {
+ "joint_set": "J14+adapter",
+ "num_joints": 14,
+ "num_samples": 35463,
+ "MPJPE_mm": 69.02998274054096,
+ "PA_MPJPE_mm": 41.82524856095757,
+ "PCK3D_50mm": 0.7230534037487764,
+ "PCK3D_100mm": 0.9491320934092273,
+ "AUC_0_150mm": 0.7205023578153955
+ }
+ ]
+ },
+ "instanthmr_distill_train/runs/bno_s0/bno_s0/best_student_model_v3.pth|h36m": {
+ "ckpt": "instanthmr_distill_train/runs/bno_s0/bno_s0/best_student_model_v3.pth",
+ "gt": "h36m",
+ "split": "test",
+ "stride": 1,
+ "epoch": 85,
+ "source": "ema",
+ "n": 35463,
+ "n_dropped": 0,
+ "results": [
+ {
+ "joint_set": "J14",
+ "num_joints": 14,
+ "num_samples": 35463,
+ "MPJPE_mm": 105.59075208981304,
+ "PA_MPJPE_mm": 68.65276639038719,
+ "PCK3D_50mm": 0.38712380307846006,
+ "PCK3D_100mm": 0.8200015307705012,
+ "AUC_0_150mm": 0.5514413607692109,
+ "per_joint_PA_MPJPE_mm": {
+ "right_ankle": 68.6002112208962,
+ "right_knee": 47.796202194113405,
+ "right_hip": 98.89813178363754,
+ "left_hip": 86.54804326749168,
+ "left_knee": 47.93220834357654,
+ "left_ankle": 70.43573883389739,
+ "right_wrist": 70.9671299706096,
+ "right_elbow": 59.931862055983714,
+ "right_shoulder": 48.88554359499399,
+ "left_shoulder": 50.86661346152063,
+ "left_elbow": 70.13890219496395,
+ "left_wrist": 74.72033982944755,
+ "neck": 34.32004777862704,
+ "head": 131.09775493566124
+ }
+ },
+ {
+ "joint_set": "J12",
+ "num_joints": 12,
+ "num_samples": 35463,
+ "MPJPE_mm": 103.55279371039903,
+ "PA_MPJPE_mm": 63.212442975844404,
+ "PCK3D_50mm": 0.42238389307165214,
+ "PCK3D_100mm": 0.8809745368412147,
+ "AUC_0_150mm": 0.5840778621607435,
+ "per_joint_PA_MPJPE_mm": {
+ "right_ankle": 64.31700202915948,
+ "right_knee": 49.58846684843106,
+ "right_hip": 97.74150472679717,
+ "left_hip": 85.53733176084349,
+ "left_knee": 48.44964497448344,
+ "left_ankle": 64.69117986025115,
+ "right_wrist": 67.87638478520945,
+ "right_elbow": 50.475248931588496,
+ "right_shoulder": 51.10462090980213,
+ "left_shoulder": 51.255945550101416,
+ "left_elbow": 56.66098902303212,
+ "left_wrist": 70.8509963104334
+ }
+ },
+ {
+ "joint_set": "J14+adapter",
+ "num_joints": 14,
+ "num_samples": 35463,
+ "MPJPE_mm": 70.63804778208632,
+ "PA_MPJPE_mm": 43.80571997315016,
+ "PCK3D_50mm": 0.6998984857457068,
+ "PCK3D_100mm": 0.9421328467094476,
+ "AUC_0_150mm": 0.7086226431104736
+ }
+ ]
+ }
+}
\ No newline at end of file
diff --git a/benchmark/results/3dpw_test_smplfit.json b/benchmark/results/3dpw_test_smplfit.json
new file mode 100644
index 0000000..ae04c95
--- /dev/null
+++ b/benchmark/results/3dpw_test_smplfit.json
@@ -0,0 +1,88 @@
+{
+ "instanthmr_distill_train/runs/b3_s1/b3_s1/best_student_model_v3.pth": {
+ "ckpt": "instanthmr_distill_train/runs/b3_s1/b3_s1/best_student_model_v3.pth",
+ "dataset": "3DPW/test",
+ "bbox": "gt-joints",
+ "stride": 1,
+ "n": 35463,
+ "fit_iters": 400,
+ "epoch": 137,
+ "source": "ema",
+ "fit_residual_mm": 17.004608154296875,
+ "MPJPE_mm": 70.12309265136719,
+ "PA_MPJPE_mm": 49.299208058306824,
+ "PVE_mm": 83.93521674934446,
+ "PA_PVE_mm": 59.70094080149259,
+ "per_sequence_PA_MPJPE_mm": {
+ "downtown_arguing_00": 55.128664281708716,
+ "downtown_bar_00": 60.09846807136917,
+ "downtown_bus_00": 57.47289959628734,
+ "downtown_cafe_00": 46.52143377778766,
+ "downtown_car_00": 53.570638641576814,
+ "downtown_crossStreets_00": 49.85964262237165,
+ "downtown_downstairs_00": 41.02150680058183,
+ "downtown_enterShop_00": 36.96853688737289,
+ "downtown_rampAndStairs_00": 45.00065479850545,
+ "downtown_runForBus_00": 45.257167005245286,
+ "downtown_runForBus_01": 58.42430960101843,
+ "downtown_sitOnStairs_00": 47.7291710517197,
+ "downtown_stairs_00": 57.84252563548758,
+ "downtown_upstairs_00": 39.42688494174954,
+ "downtown_walkBridge_01": 40.05517954627335,
+ "downtown_walkUphill_00": 37.15261530936371,
+ "downtown_walking_00": 47.660608196674175,
+ "downtown_warmWelcome_00": 53.35867689309556,
+ "downtown_weeklyMarket_00": 41.23658721494934,
+ "downtown_windowShopping_00": 38.65736838805555,
+ "flat_guitar_01": 63.87007688526666,
+ "flat_packBags_00": 55.583542431958634,
+ "office_phoneCall_00": 42.071492928142334,
+ "outdoors_fencing_01": 50.52562153596208
+ },
+ "J14_h36m_viamesh_MPJPE_mm": 69.96729793143032,
+ "J14_h36m_viamesh_PA_MPJPE_mm": 46.13575630968572
+ },
+ "instanthmr_distill_train/runs/bno_s0/bno_s0/best_student_model_v3.pth": {
+ "ckpt": "instanthmr_distill_train/runs/bno_s0/bno_s0/best_student_model_v3.pth",
+ "dataset": "3DPW/test",
+ "bbox": "gt-joints",
+ "stride": 1,
+ "n": 35463,
+ "fit_iters": 400,
+ "epoch": 85,
+ "source": "ema",
+ "fit_residual_mm": 16.382274627685547,
+ "MPJPE_mm": 71.3781509399414,
+ "PA_MPJPE_mm": 50.89205090035432,
+ "PVE_mm": 84.60048436590854,
+ "PA_PVE_mm": 61.25163162048173,
+ "per_sequence_PA_MPJPE_mm": {
+ "downtown_arguing_00": 55.51393117547959,
+ "downtown_bar_00": 60.513748658835624,
+ "downtown_bus_00": 59.656931380784485,
+ "downtown_cafe_00": 46.960072212207756,
+ "downtown_car_00": 58.120584069229224,
+ "downtown_crossStreets_00": 51.57475394673719,
+ "downtown_downstairs_00": 43.31706603789759,
+ "downtown_enterShop_00": 41.44317245415561,
+ "downtown_rampAndStairs_00": 47.67656300606207,
+ "downtown_runForBus_00": 45.31364935332185,
+ "downtown_runForBus_01": 57.0176377230583,
+ "downtown_sitOnStairs_00": 49.564813096273184,
+ "downtown_stairs_00": 57.30311493027224,
+ "downtown_upstairs_00": 40.619809459390126,
+ "downtown_walkBridge_01": 39.999748915846226,
+ "downtown_walkUphill_00": 38.30589736074419,
+ "downtown_walking_00": 47.66982111316505,
+ "downtown_warmWelcome_00": 57.76132724620347,
+ "downtown_weeklyMarket_00": 46.6148834939354,
+ "downtown_windowShopping_00": 42.05428317264101,
+ "flat_guitar_01": 59.238372173536504,
+ "flat_packBags_00": 61.617872574583046,
+ "office_phoneCall_00": 43.61936431501065,
+ "outdoors_fencing_01": 50.118543453226955
+ },
+ "J14_h36m_viamesh_MPJPE_mm": 70.8501205444336,
+ "J14_h36m_viamesh_PA_MPJPE_mm": 47.68866579180827
+ }
+}
\ No newline at end of file
diff --git a/benchmark/results/emdb1_alladapter.json b/benchmark/results/emdb1_alladapter.json
new file mode 100644
index 0000000..d275942
--- /dev/null
+++ b/benchmark/results/emdb1_alladapter.json
@@ -0,0 +1,344 @@
+{
+ "instanthmr_distill_train/runs/b3_s1/b3_s1/best_student_model_v3.pth": {
+ "ckpt": "instanthmr_distill_train/runs/b3_s1/b3_s1/best_student_model_v3.pth",
+ "dataset": "EMDB1",
+ "split": "emdb1",
+ "stride": 1,
+ "bbox": "gt-joints",
+ "adapter": "benchmark/results/adapter_smpl24_teacher.npz",
+ "epoch": 137,
+ "source": "ema",
+ "n": 24103,
+ "n_dropped": 0,
+ "num_sequences": 17,
+ "results": [
+ {
+ "joint_set": "SMPL24+adapter",
+ "num_joints": 24,
+ "num_samples": 24103,
+ "MPJPE_mm": 79.89899497418331,
+ "PA_MPJPE_mm": 53.81798394620607,
+ "PCK3D_50mm": 0.6322069175344701,
+ "PCK3D_100mm": 0.900053935194789,
+ "AUC_0_150mm": 0.6589641163661865,
+ "per_joint_PA_MPJPE_mm": {
+ "pelvis": 37.38875643902142,
+ "left_hip": 38.58502567465045,
+ "right_hip": 38.64374049286347,
+ "spine1": 43.75229274731907,
+ "left_knee": 54.25041422518342,
+ "right_knee": 54.1425459887338,
+ "spine2": 43.637535615918374,
+ "left_ankle": 61.87196282700251,
+ "right_ankle": 62.62819743536405,
+ "spine3": 41.83282129953466,
+ "left_foot": 69.52197418470328,
+ "right_foot": 70.2120609591868,
+ "neck": 34.26217727492899,
+ "left_collar": 29.577013017049016,
+ "right_collar": 30.66917362317821,
+ "head": 39.570892402613865,
+ "left_shoulder": 39.64857745770012,
+ "right_shoulder": 41.82903043998137,
+ "left_elbow": 53.31573380982405,
+ "right_elbow": 50.12875326034317,
+ "left_wrist": 81.75573306282612,
+ "right_wrist": 79.08061992194783,
+ "left_hand": 96.88062749117694,
+ "right_hand": 98.44595505789538
+ }
+ },
+ {
+ "joint_set": "J14",
+ "num_joints": 14,
+ "num_samples": 24103,
+ "MPJPE_mm": 90.72479809063141,
+ "PA_MPJPE_mm": 60.16621895590192,
+ "PCK3D_50mm": 0.5267808986433224,
+ "PCK3D_100mm": 0.8703866145885811,
+ "AUC_0_150mm": 0.6129356328093468,
+ "per_joint_PA_MPJPE_mm": {
+ "right_ankle": 63.84055062203499,
+ "right_knee": 52.78757477579679,
+ "right_hip": 49.741148343188165,
+ "left_hip": 47.454675146924686,
+ "left_knee": 53.824850575924025,
+ "left_ankle": 65.37445015384029,
+ "right_wrist": 80.73570274834391,
+ "right_elbow": 45.04158922948974,
+ "right_shoulder": 55.16986767345743,
+ "left_shoulder": 43.801427220783474,
+ "left_elbow": 50.0949029673105,
+ "left_wrist": 86.1400763275341,
+ "neck": 44.892623032925655,
+ "head": 103.42762656507293
+ }
+ },
+ {
+ "joint_set": "J12",
+ "num_joints": 12,
+ "num_samples": 24103,
+ "MPJPE_mm": 85.68860096199708,
+ "PA_MPJPE_mm": 55.54807307469167,
+ "PCK3D_50mm": 0.5913268057918102,
+ "PCK3D_100mm": 0.899746227993749,
+ "AUC_0_150mm": 0.644360403983085,
+ "per_joint_PA_MPJPE_mm": {
+ "right_ankle": 61.701581175567185,
+ "right_knee": 53.355717753595975,
+ "right_hip": 47.103644910914305,
+ "left_hip": 44.961480475975875,
+ "left_knee": 54.17709666329682,
+ "left_ankle": 62.46243257507469,
+ "right_wrist": 77.97302519602071,
+ "right_elbow": 42.233270361387255,
+ "right_shoulder": 48.56697075655756,
+ "left_shoulder": 42.793863660337045,
+ "left_elbow": 48.05990297063805,
+ "left_wrist": 83.18789039693452
+ }
+ }
+ ],
+ "per_sequence_SMPL24_adapter": {
+ "P1_14_outdoor_climb": {
+ "n": 1270,
+ "PA_MPJPE_mm": 44.44573927833153
+ },
+ "P2_23_outdoor_hug_tree": {
+ "n": 1086,
+ "PA_MPJPE_mm": 50.07407797193647
+ },
+ "P3_31_outdoor_workout": {
+ "n": 1216,
+ "PA_MPJPE_mm": 53.7116134427868
+ },
+ "P3_32_outdoor_soccer_warmup_a": {
+ "n": 1084,
+ "PA_MPJPE_mm": 54.05099939228138
+ },
+ "P3_33_outdoor_soccer_warmup_b": {
+ "n": 1433,
+ "PA_MPJPE_mm": 47.68807307972911
+ },
+ "P5_42_indoor_dancing": {
+ "n": 1291,
+ "PA_MPJPE_mm": 75.35818170729262
+ },
+ "P5_44_indoor_rom": {
+ "n": 1381,
+ "PA_MPJPE_mm": 49.274601114210945
+ },
+ "P6_49_outdoor_big_stairs_down": {
+ "n": 1559,
+ "PA_MPJPE_mm": 58.39621370386727
+ },
+ "P6_50_outdoor_workout": {
+ "n": 1532,
+ "PA_MPJPE_mm": 46.46998460391101
+ },
+ "P6_51_outdoor_dancing": {
+ "n": 1427,
+ "PA_MPJPE_mm": 44.54244714508236
+ },
+ "P7_57_outdoor_rock_chair": {
+ "n": 1558,
+ "PA_MPJPE_mm": 51.04704954722545
+ },
+ "P7_59_outdoor_rom": {
+ "n": 1839,
+ "PA_MPJPE_mm": 50.79030469061686
+ },
+ "P7_60_outdoor_workout": {
+ "n": 1693,
+ "PA_MPJPE_mm": 46.45811541891769
+ },
+ "P8_64_outdoor_skateboard": {
+ "n": 1704,
+ "PA_MPJPE_mm": 54.80319982067974
+ },
+ "P8_68_outdoor_handstand": {
+ "n": 1606,
+ "PA_MPJPE_mm": 75.03112152950358
+ },
+ "P8_69_outdoor_cartwheel": {
+ "n": 656,
+ "PA_MPJPE_mm": 64.85139366363609
+ },
+ "P9_76_outdoor_sitting": {
+ "n": 1768,
+ "PA_MPJPE_mm": 53.71147187108503
+ }
+ }
+ },
+ "instanthmr_distill_train/runs/bno_s0/bno_s0/best_student_model_v3.pth": {
+ "ckpt": "instanthmr_distill_train/runs/bno_s0/bno_s0/best_student_model_v3.pth",
+ "dataset": "EMDB1",
+ "split": "emdb1",
+ "stride": 1,
+ "bbox": "gt-joints",
+ "adapter": "benchmark/results/adapter_smpl24_teacher.npz",
+ "epoch": 85,
+ "source": "ema",
+ "n": 24103,
+ "n_dropped": 0,
+ "num_sequences": 17,
+ "results": [
+ {
+ "joint_set": "SMPL24+adapter",
+ "num_joints": 24,
+ "num_samples": 24103,
+ "MPJPE_mm": 82.16065099955965,
+ "PA_MPJPE_mm": 55.825338706859185,
+ "PCK3D_50mm": 0.6148646779792281,
+ "PCK3D_100mm": 0.8940138848552739,
+ "AUC_0_150mm": 0.6506397387734272,
+ "per_joint_PA_MPJPE_mm": {
+ "pelvis": 39.70396733646249,
+ "left_hip": 41.072286545463925,
+ "right_hip": 40.58765229043174,
+ "spine1": 46.46333685183644,
+ "left_knee": 58.32141425285344,
+ "right_knee": 56.989772761846005,
+ "spine2": 43.355409456514096,
+ "left_ankle": 66.60249721625911,
+ "right_ankle": 66.47063521157392,
+ "spine3": 40.91482345371773,
+ "left_foot": 72.94529885905705,
+ "right_foot": 72.4786906097902,
+ "neck": 37.233127996944575,
+ "left_collar": 31.747304809215237,
+ "right_collar": 31.876652034764007,
+ "head": 43.86986225417686,
+ "left_shoulder": 42.42372187894316,
+ "right_shoulder": 42.3622200550824,
+ "left_elbow": 55.729122225866355,
+ "right_elbow": 51.488487100984884,
+ "left_wrist": 83.37699882632741,
+ "right_wrist": 78.6395288964919,
+ "left_hand": 97.93653692171387,
+ "right_hand": 97.21878111830387
+ }
+ },
+ {
+ "joint_set": "J14",
+ "num_joints": 14,
+ "num_samples": 24103,
+ "MPJPE_mm": 92.61108651904796,
+ "PA_MPJPE_mm": 61.927314981267074,
+ "PCK3D_50mm": 0.5202968213796741,
+ "PCK3D_100mm": 0.8618014355059536,
+ "AUC_0_150mm": 0.6073539806410698,
+ "per_joint_PA_MPJPE_mm": {
+ "right_ankle": 68.57235357611404,
+ "right_knee": 54.33595960450975,
+ "right_hip": 50.526315138235056,
+ "left_hip": 47.84138836982132,
+ "left_knee": 56.92537511368124,
+ "left_ankle": 70.61200686646174,
+ "right_wrist": 80.12905500727975,
+ "right_elbow": 46.838162649020745,
+ "right_shoulder": 54.52294203786921,
+ "left_shoulder": 44.46141139571641,
+ "left_elbow": 52.90357655334994,
+ "left_wrist": 87.68342051742559,
+ "neck": 45.56855188312777,
+ "head": 106.06189102512643
+ }
+ },
+ {
+ "joint_set": "J12",
+ "num_joints": 12,
+ "num_samples": 24103,
+ "MPJPE_mm": 87.29156555160438,
+ "PA_MPJPE_mm": 57.31832852318586,
+ "PCK3D_50mm": 0.5813384226029955,
+ "PCK3D_100mm": 0.8932982063090348,
+ "AUC_0_150mm": 0.6388870300801355,
+ "per_joint_PA_MPJPE_mm": {
+ "right_ankle": 65.6110898068444,
+ "right_knee": 54.38292599948846,
+ "right_hip": 47.6902899756637,
+ "left_hip": 45.7720338767824,
+ "left_knee": 57.13106223561326,
+ "left_ankle": 67.23894697013618,
+ "right_wrist": 77.86331140249156,
+ "right_elbow": 44.199689767243605,
+ "right_shoulder": 49.40597095256337,
+ "left_shoulder": 45.15945622082252,
+ "left_elbow": 49.80201024945468,
+ "left_wrist": 83.5631548211261
+ }
+ }
+ ],
+ "per_sequence_SMPL24_adapter": {
+ "P1_14_outdoor_climb": {
+ "n": 1270,
+ "PA_MPJPE_mm": 43.98543497401005
+ },
+ "P2_23_outdoor_hug_tree": {
+ "n": 1086,
+ "PA_MPJPE_mm": 52.091088721749536
+ },
+ "P3_31_outdoor_workout": {
+ "n": 1216,
+ "PA_MPJPE_mm": 53.583596666258245
+ },
+ "P3_32_outdoor_soccer_warmup_a": {
+ "n": 1084,
+ "PA_MPJPE_mm": 55.92338370551133
+ },
+ "P3_33_outdoor_soccer_warmup_b": {
+ "n": 1433,
+ "PA_MPJPE_mm": 51.08274846782155
+ },
+ "P5_42_indoor_dancing": {
+ "n": 1291,
+ "PA_MPJPE_mm": 78.11362474445052
+ },
+ "P5_44_indoor_rom": {
+ "n": 1381,
+ "PA_MPJPE_mm": 53.839872627535655
+ },
+ "P6_49_outdoor_big_stairs_down": {
+ "n": 1559,
+ "PA_MPJPE_mm": 61.59408499334506
+ },
+ "P6_50_outdoor_workout": {
+ "n": 1532,
+ "PA_MPJPE_mm": 51.93820655996959
+ },
+ "P6_51_outdoor_dancing": {
+ "n": 1427,
+ "PA_MPJPE_mm": 45.12661562019302
+ },
+ "P7_57_outdoor_rock_chair": {
+ "n": 1558,
+ "PA_MPJPE_mm": 51.956708404866745
+ },
+ "P7_59_outdoor_rom": {
+ "n": 1839,
+ "PA_MPJPE_mm": 53.03109592282591
+ },
+ "P7_60_outdoor_workout": {
+ "n": 1693,
+ "PA_MPJPE_mm": 45.752346278928854
+ },
+ "P8_64_outdoor_skateboard": {
+ "n": 1704,
+ "PA_MPJPE_mm": 52.18738325398466
+ },
+ "P8_68_outdoor_handstand": {
+ "n": 1606,
+ "PA_MPJPE_mm": 87.26453095273783
+ },
+ "P8_69_outdoor_cartwheel": {
+ "n": 656,
+ "PA_MPJPE_mm": 62.152433163627016
+ },
+ "P9_76_outdoor_sitting": {
+ "n": 1768,
+ "PA_MPJPE_mm": 52.703730588090174
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/benchmark/results/emdb1_b3_s1_annotated.json b/benchmark/results/emdb1_b3_s1_annotated.json
new file mode 100644
index 0000000..108e590
--- /dev/null
+++ b/benchmark/results/emdb1_b3_s1_annotated.json
@@ -0,0 +1,173 @@
+{
+ "instanthmr_distill_train/runs/b3_s1/b3_s1/best_student_model_v3.pth": {
+ "ckpt": "instanthmr_distill_train/runs/b3_s1/b3_s1/best_student_model_v3.pth",
+ "dataset": "EMDB1",
+ "split": "emdb1",
+ "stride": 1,
+ "bbox": "annotated",
+ "adapter": "benchmark/results/adapter_smpl24_teacher.npz",
+ "epoch": 137,
+ "source": "ema",
+ "n": 24103,
+ "n_dropped": 0,
+ "num_sequences": 17,
+ "results": [
+ {
+ "joint_set": "SMPL24+adapter",
+ "num_joints": 24,
+ "num_samples": 24103,
+ "MPJPE_mm": 87.5145198705048,
+ "PA_MPJPE_mm": 60.68695037973602,
+ "PCK3D_50mm": 0.5824395994966048,
+ "PCK3D_100mm": 0.8630167060808475,
+ "AUC_0_150mm": 0.6278615988997042,
+ "per_joint_PA_MPJPE_mm": {
+ "pelvis": 40.86098621792327,
+ "left_hip": 41.79013147929267,
+ "right_hip": 41.16490895868687,
+ "spine1": 48.40987721094612,
+ "left_knee": 58.16313551683889,
+ "right_knee": 57.22590059890525,
+ "spine2": 46.81683316737049,
+ "left_ankle": 69.84579402852766,
+ "right_ankle": 69.70267345558224,
+ "spine3": 45.18799735489693,
+ "left_foot": 76.68425821217114,
+ "right_foot": 77.31345782617193,
+ "neck": 42.938995983362986,
+ "left_collar": 37.18888642853474,
+ "right_collar": 37.55237455507592,
+ "head": 48.43977502391476,
+ "left_shoulder": 43.78942526296338,
+ "right_shoulder": 45.138807870567796,
+ "left_elbow": 58.9530251328787,
+ "right_elbow": 55.218168805087,
+ "left_wrist": 94.77740166022281,
+ "right_wrist": 92.7091943098265,
+ "left_hand": 112.59585738228681,
+ "right_hand": 114.01894267162925
+ }
+ },
+ {
+ "joint_set": "J14",
+ "num_joints": 14,
+ "num_samples": 24103,
+ "MPJPE_mm": 98.12348511185374,
+ "PA_MPJPE_mm": 65.5655235547273,
+ "PCK3D_50mm": 0.48783790992229775,
+ "PCK3D_100mm": 0.8378150911860408,
+ "AUC_0_150mm": 0.5875892459225012,
+ "per_joint_PA_MPJPE_mm": {
+ "right_ankle": 70.26933843183772,
+ "right_knee": 54.829084865597956,
+ "right_hip": 51.412027756054854,
+ "left_hip": 48.73087643103119,
+ "left_knee": 56.7033084565791,
+ "left_ankle": 72.41752237552517,
+ "right_wrist": 94.73684429306688,
+ "right_elbow": 51.668938476699914,
+ "right_shoulder": 56.772514583590144,
+ "left_shoulder": 46.49234777994068,
+ "left_elbow": 56.461653215982516,
+ "left_wrist": 99.10996551016746,
+ "neck": 53.15409908635089,
+ "head": 105.15880850375798
+ }
+ },
+ {
+ "joint_set": "J12",
+ "num_joints": 12,
+ "num_samples": 24103,
+ "MPJPE_mm": 93.66851373450805,
+ "PA_MPJPE_mm": 61.76109450753499,
+ "PCK3D_50mm": 0.5403269302576442,
+ "PCK3D_100mm": 0.8634125765810619,
+ "AUC_0_150mm": 0.6135420611988245,
+ "per_joint_PA_MPJPE_mm": {
+ "right_ankle": 68.49097778731077,
+ "right_knee": 55.341688859316235,
+ "right_hip": 50.346738035900245,
+ "left_hip": 47.99181424877826,
+ "left_knee": 57.16501452499131,
+ "left_ankle": 70.0484272084777,
+ "right_wrist": 90.96316636646812,
+ "right_elbow": 48.39876355325566,
+ "right_shoulder": 54.60786812013797,
+ "left_shoulder": 49.63662210397929,
+ "left_elbow": 53.613263181921,
+ "left_wrist": 94.52879009988325
+ }
+ }
+ ],
+ "per_sequence_SMPL24_adapter": {
+ "P1_14_outdoor_climb": {
+ "n": 1270,
+ "PA_MPJPE_mm": 63.95078685745811
+ },
+ "P2_23_outdoor_hug_tree": {
+ "n": 1086,
+ "PA_MPJPE_mm": 62.80989428662845
+ },
+ "P3_31_outdoor_workout": {
+ "n": 1216,
+ "PA_MPJPE_mm": 54.788964020413744
+ },
+ "P3_32_outdoor_soccer_warmup_a": {
+ "n": 1084,
+ "PA_MPJPE_mm": 55.025884444805776
+ },
+ "P3_33_outdoor_soccer_warmup_b": {
+ "n": 1433,
+ "PA_MPJPE_mm": 52.066525759678704
+ },
+ "P5_42_indoor_dancing": {
+ "n": 1291,
+ "PA_MPJPE_mm": 84.33874324494832
+ },
+ "P5_44_indoor_rom": {
+ "n": 1381,
+ "PA_MPJPE_mm": 57.08465013107306
+ },
+ "P6_49_outdoor_big_stairs_down": {
+ "n": 1559,
+ "PA_MPJPE_mm": 67.55319596038812
+ },
+ "P6_50_outdoor_workout": {
+ "n": 1532,
+ "PA_MPJPE_mm": 49.19546174141772
+ },
+ "P6_51_outdoor_dancing": {
+ "n": 1427,
+ "PA_MPJPE_mm": 54.248099071883765
+ },
+ "P7_57_outdoor_rock_chair": {
+ "n": 1558,
+ "PA_MPJPE_mm": 55.74420089059678
+ },
+ "P7_59_outdoor_rom": {
+ "n": 1839,
+ "PA_MPJPE_mm": 58.74884027499412
+ },
+ "P7_60_outdoor_workout": {
+ "n": 1693,
+ "PA_MPJPE_mm": 51.620113245460516
+ },
+ "P8_64_outdoor_skateboard": {
+ "n": 1704,
+ "PA_MPJPE_mm": 61.38240839177174
+ },
+ "P8_68_outdoor_handstand": {
+ "n": 1606,
+ "PA_MPJPE_mm": 84.0380008365223
+ },
+ "P8_69_outdoor_cartwheel": {
+ "n": 656,
+ "PA_MPJPE_mm": 66.56964635175764
+ },
+ "P9_76_outdoor_sitting": {
+ "n": 1768,
+ "PA_MPJPE_mm": 57.1854288712578
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/benchmark/results/emdb1_b3_s1_gt-joints.json b/benchmark/results/emdb1_b3_s1_gt-joints.json
new file mode 100644
index 0000000..7b447ac
--- /dev/null
+++ b/benchmark/results/emdb1_b3_s1_gt-joints.json
@@ -0,0 +1,173 @@
+{
+ "instanthmr_distill_train/runs/b3_s1/b3_s1/best_student_model_v3.pth": {
+ "ckpt": "instanthmr_distill_train/runs/b3_s1/b3_s1/best_student_model_v3.pth",
+ "dataset": "EMDB1",
+ "split": "emdb1",
+ "stride": 1,
+ "bbox": "gt-joints",
+ "adapter": "benchmark/results/adapter_smpl24_teacher.npz",
+ "epoch": 137,
+ "source": "ema",
+ "n": 24103,
+ "n_dropped": 0,
+ "num_sequences": 17,
+ "results": [
+ {
+ "joint_set": "SMPL24+adapter",
+ "num_joints": 24,
+ "num_samples": 24103,
+ "MPJPE_mm": 79.89899497418331,
+ "PA_MPJPE_mm": 53.81798394620607,
+ "PCK3D_50mm": 0.6322069175344701,
+ "PCK3D_100mm": 0.900053935194789,
+ "AUC_0_150mm": 0.6589641163661865,
+ "per_joint_PA_MPJPE_mm": {
+ "pelvis": 37.38875643902142,
+ "left_hip": 38.58502567465045,
+ "right_hip": 38.64374049286347,
+ "spine1": 43.75229274731907,
+ "left_knee": 54.25041422518342,
+ "right_knee": 54.1425459887338,
+ "spine2": 43.637535615918374,
+ "left_ankle": 61.87196282700251,
+ "right_ankle": 62.62819743536405,
+ "spine3": 41.83282129953466,
+ "left_foot": 69.52197418470328,
+ "right_foot": 70.2120609591868,
+ "neck": 34.26217727492899,
+ "left_collar": 29.577013017049016,
+ "right_collar": 30.66917362317821,
+ "head": 39.570892402613865,
+ "left_shoulder": 39.64857745770012,
+ "right_shoulder": 41.82903043998137,
+ "left_elbow": 53.31573380982405,
+ "right_elbow": 50.12875326034317,
+ "left_wrist": 81.75573306282612,
+ "right_wrist": 79.08061992194783,
+ "left_hand": 96.88062749117694,
+ "right_hand": 98.44595505789538
+ }
+ },
+ {
+ "joint_set": "J14",
+ "num_joints": 14,
+ "num_samples": 24103,
+ "MPJPE_mm": 90.72479809063141,
+ "PA_MPJPE_mm": 60.16621895590192,
+ "PCK3D_50mm": 0.5267808986433224,
+ "PCK3D_100mm": 0.8703866145885811,
+ "AUC_0_150mm": 0.6129356328093468,
+ "per_joint_PA_MPJPE_mm": {
+ "right_ankle": 63.84055062203499,
+ "right_knee": 52.78757477579679,
+ "right_hip": 49.741148343188165,
+ "left_hip": 47.454675146924686,
+ "left_knee": 53.824850575924025,
+ "left_ankle": 65.37445015384029,
+ "right_wrist": 80.73570274834391,
+ "right_elbow": 45.04158922948974,
+ "right_shoulder": 55.16986767345743,
+ "left_shoulder": 43.801427220783474,
+ "left_elbow": 50.0949029673105,
+ "left_wrist": 86.1400763275341,
+ "neck": 44.892623032925655,
+ "head": 103.42762656507293
+ }
+ },
+ {
+ "joint_set": "J12",
+ "num_joints": 12,
+ "num_samples": 24103,
+ "MPJPE_mm": 85.68860096199708,
+ "PA_MPJPE_mm": 55.54807307469167,
+ "PCK3D_50mm": 0.5913268057918102,
+ "PCK3D_100mm": 0.899746227993749,
+ "AUC_0_150mm": 0.644360403983085,
+ "per_joint_PA_MPJPE_mm": {
+ "right_ankle": 61.701581175567185,
+ "right_knee": 53.355717753595975,
+ "right_hip": 47.103644910914305,
+ "left_hip": 44.961480475975875,
+ "left_knee": 54.17709666329682,
+ "left_ankle": 62.46243257507469,
+ "right_wrist": 77.97302519602071,
+ "right_elbow": 42.233270361387255,
+ "right_shoulder": 48.56697075655756,
+ "left_shoulder": 42.793863660337045,
+ "left_elbow": 48.05990297063805,
+ "left_wrist": 83.18789039693452
+ }
+ }
+ ],
+ "per_sequence_SMPL24_adapter": {
+ "P1_14_outdoor_climb": {
+ "n": 1270,
+ "PA_MPJPE_mm": 44.44573927833153
+ },
+ "P2_23_outdoor_hug_tree": {
+ "n": 1086,
+ "PA_MPJPE_mm": 50.07407797193647
+ },
+ "P3_31_outdoor_workout": {
+ "n": 1216,
+ "PA_MPJPE_mm": 53.7116134427868
+ },
+ "P3_32_outdoor_soccer_warmup_a": {
+ "n": 1084,
+ "PA_MPJPE_mm": 54.05099939228138
+ },
+ "P3_33_outdoor_soccer_warmup_b": {
+ "n": 1433,
+ "PA_MPJPE_mm": 47.68807307972911
+ },
+ "P5_42_indoor_dancing": {
+ "n": 1291,
+ "PA_MPJPE_mm": 75.35818170729262
+ },
+ "P5_44_indoor_rom": {
+ "n": 1381,
+ "PA_MPJPE_mm": 49.274601114210945
+ },
+ "P6_49_outdoor_big_stairs_down": {
+ "n": 1559,
+ "PA_MPJPE_mm": 58.39621370386727
+ },
+ "P6_50_outdoor_workout": {
+ "n": 1532,
+ "PA_MPJPE_mm": 46.46998460391101
+ },
+ "P6_51_outdoor_dancing": {
+ "n": 1427,
+ "PA_MPJPE_mm": 44.54244714508236
+ },
+ "P7_57_outdoor_rock_chair": {
+ "n": 1558,
+ "PA_MPJPE_mm": 51.04704954722545
+ },
+ "P7_59_outdoor_rom": {
+ "n": 1839,
+ "PA_MPJPE_mm": 50.79030469061686
+ },
+ "P7_60_outdoor_workout": {
+ "n": 1693,
+ "PA_MPJPE_mm": 46.45811541891769
+ },
+ "P8_64_outdoor_skateboard": {
+ "n": 1704,
+ "PA_MPJPE_mm": 54.80319982067974
+ },
+ "P8_68_outdoor_handstand": {
+ "n": 1606,
+ "PA_MPJPE_mm": 75.03112152950358
+ },
+ "P8_69_outdoor_cartwheel": {
+ "n": 656,
+ "PA_MPJPE_mm": 64.85139366363609
+ },
+ "P9_76_outdoor_sitting": {
+ "n": 1768,
+ "PA_MPJPE_mm": 53.71147187108503
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/benchmark/results/emdb1_smplfit_gt-joints.json b/benchmark/results/emdb1_smplfit_gt-joints.json
new file mode 100644
index 0000000..f22bee7
--- /dev/null
+++ b/benchmark/results/emdb1_smplfit_gt-joints.json
@@ -0,0 +1,70 @@
+{
+ "instanthmr_distill_train/runs/b3_s1/b3_s1/best_student_model_v3.pth": {
+ "ckpt": "instanthmr_distill_train/runs/b3_s1/b3_s1/best_student_model_v3.pth",
+ "dataset": "EMDB1",
+ "bbox": "gt-joints",
+ "stride": 1,
+ "n": 24103,
+ "fit_iters": 400,
+ "epoch": 137,
+ "source": "ema",
+ "fit_residual_mm": 14.610766410827637,
+ "MPJPE_mm": 77.38072967529297,
+ "PA_MPJPE_mm": 51.999232991718365,
+ "PVE_mm": 92.24835687335322,
+ "PA_PVE_mm": 62.57454616195972,
+ "per_sequence_PA_MPJPE_mm": {
+ "P1_14_outdoor_climb": 40.679812730232776,
+ "P2_23_outdoor_hug_tree": 48.46140407281954,
+ "P3_31_outdoor_workout": 53.641220567187126,
+ "P3_32_outdoor_soccer_warmup_a": 53.625993557350874,
+ "P3_33_outdoor_soccer_warmup_b": 48.168861427570775,
+ "P5_42_indoor_dancing": 74.88580298687171,
+ "P5_44_indoor_rom": 48.84046610706719,
+ "P6_49_outdoor_big_stairs_down": 56.64582810483881,
+ "P6_50_outdoor_workout": 44.77893859356306,
+ "P6_51_outdoor_dancing": 43.987160466263575,
+ "P7_57_outdoor_rock_chair": 48.498681297758864,
+ "P7_59_outdoor_rom": 49.07154407413522,
+ "P7_60_outdoor_workout": 43.90422666512502,
+ "P8_64_outdoor_skateboard": 52.09684144342112,
+ "P8_68_outdoor_handstand": 72.55139613251777,
+ "P8_69_outdoor_cartwheel": 62.702449073220386,
+ "P9_76_outdoor_sitting": 48.80991828197765
+ }
+ },
+ "instanthmr_distill_train/runs/bno_s0/bno_s0/best_student_model_v3.pth": {
+ "ckpt": "instanthmr_distill_train/runs/bno_s0/bno_s0/best_student_model_v3.pth",
+ "dataset": "EMDB1",
+ "bbox": "gt-joints",
+ "stride": 1,
+ "n": 24103,
+ "fit_iters": 400,
+ "epoch": 85,
+ "source": "ema",
+ "fit_residual_mm": 14.715494155883789,
+ "MPJPE_mm": 79.54940795898438,
+ "PA_MPJPE_mm": 54.234037765862624,
+ "PVE_mm": 94.44203375607358,
+ "PA_PVE_mm": 64.8163185715288,
+ "per_sequence_PA_MPJPE_mm": {
+ "P1_14_outdoor_climb": 40.38579015681633,
+ "P2_23_outdoor_hug_tree": 50.952089101184306,
+ "P3_31_outdoor_workout": 52.97866412872431,
+ "P3_32_outdoor_soccer_warmup_a": 55.258014050152454,
+ "P3_33_outdoor_soccer_warmup_b": 51.0758103503119,
+ "P5_42_indoor_dancing": 77.7890516978954,
+ "P5_44_indoor_rom": 53.694246453659666,
+ "P6_49_outdoor_big_stairs_down": 59.71285853164975,
+ "P6_50_outdoor_workout": 50.39122909218151,
+ "P6_51_outdoor_dancing": 44.74699902324005,
+ "P7_57_outdoor_rock_chair": 49.20744661036477,
+ "P7_59_outdoor_rom": 51.584609243641225,
+ "P7_60_outdoor_workout": 43.26185962015645,
+ "P8_64_outdoor_skateboard": 50.56812695561018,
+ "P8_68_outdoor_handstand": 87.12619774976028,
+ "P8_69_outdoor_cartwheel": 59.58728879933646,
+ "P9_76_outdoor_sitting": 47.7313144333539
+ }
+ }
+}
\ No newline at end of file
diff --git a/docs/todo.md b/docs/todo.md
index 3847459..3020818 100644
--- a/docs/todo.md
+++ b/docs/todo.md
@@ -339,34 +339,175 @@ angle, and check that the conditioning the dataset emits equals the conditioning
that rolled camera would produce for the same box. Until then, do not "fix" the
rotation — the current form is not shown to be wrong.
-### 12. Benchmark HGNetv2 against RepViT — after the baseline lands
-
-Not to be run now. `repvit_m2_3` is the incumbent and generation 6 exists to
-give it a solid, uncontaminated baseline on the five-split corpus; swapping the
-trunk at the same time would confound both questions.
-
-When it is time, the comparison has to cover all four axes, because a backbone
-that wins on one can lose the deployment:
-
-* **Model sizes** — which HGNetv2 variants exist and their parameter counts
- against `repvit_m2_3`'s. `--backbone` already takes any timm name, and
- `config_from_checkpoint` reads it back out of `run_config.json`, so no code
- change is needed to try one.
-* **Accuracy** — J14 PA-MPJPE with the adapter, 2 to 3 seeds. The documented
- seed spread is 34–49 mm on the 70-keypoint metric, so a single run proves
- nothing.
-* **Speed** — ONNX latency on the deployment target, not PyTorch training
- throughput. `tools/bench_student_arch.py` is the existing harness.
-* **Capabilities** — HGNetv2 is a plain conv stack where RepViT is
- reparameterisable. Check that the export path survives (`tools/pth_to_onnx.py`
- has a torch↔ONNX parity gate that exits if the worst output differs by more
- than 1e-3) and that `backbone.forward_features` returns something the
- `feat_proj` reshape accepts — the trainer handles both 4-D and 3-D feature
- maps, but the channel count feeds `backbone_feat_dim` and that is a config
- field, not inferred.
-* **On our data, locally** — the local corpus plus `checkpoints/mhr_model.pt` is
- enough to run the 1-batch overfit test and a short run per backbone before
- spending cluster time. Judge the overfit at ~1k steps.
+### 12. HGNetv2 vs RepViT — measured 2026-09-08; `hgnetv2_b4` is the challenger
+
+**Verdict: adopt `hgnetv2_b4` as the challenger trunk, not the biggest variant.**
+It beats `repvit_m2_3` on every axis measured, with fewer parameters (17.75 M vs
+22.40 M) and less compute (2.728 vs 4.520 GMAC in the backbone). `hgnetv2_b6`
+fits better on larger data but costs 2.9x the training time, 4.2x the mobile-CPU
+latency and quantises worse, so it is a server-side option, not a phone one.
+
+All numbers below are local, on this corpus and `checkpoints/mhr_model.pt`. The
+cluster run that decides the accuracy question has not been done — see the plan
+at the end.
+
+**Accuracy — the 1-batch overfit test, run with the gen-6 `g6v_s` config**
+(`--preset v2 --losses rebalanced --cliff-focal --bound-scales
+--anomaly-safe-fallback --crop-centre-fix`), 1000 steps, best Mesh PA-MPJPE over
+the 70 MHR keypoints. Three seeds, because a single run is inside the documented
+34–49 mm spread.
+
+| backbone | 8 crops, 3 seeds | mean | 64 crops, 2 seeds | mean |
+|---|---|---|---|---|
+| `repvit_m2_3` | 47.0 / 51.3 / 43.6 | **47.3** | 28.4 / 29.0 | **28.7** |
+| `hgnetv2_b2` | 40.3 / 43.1 / 37.6 | **40.3** | 26.7 / 24.7 | **25.7** |
+| `hgnetv2_b4` | 39.1 / 30.3 / 34.6 | **34.7** | 24.9 / 24.2 | **24.6** |
+| `hgnetv2_b6` | 34.0 / 45.6 / 35.0 | **38.2** | 23.8 / 20.5 | **22.2** |
+
+The 8-crop and 64-crop orderings disagree at the top: 8 crops is too small to
+need b6's capacity and its fixed-LR trajectory is noisy there. On 64 crops
+capacity orders monotonically. Both agree that every HGNetv2 variant tested
+fits better than `repvit_m2_3`, including b2 at 2.4x fewer parameters and 4x
+less compute.
+
+**The accuracy margin is mostly the checkpoint, not the topology.** Same test
+from random init instead of ImageNet:
+
+| backbone | ImageNet init | random init (2 seeds) |
+|---|---|---|
+| `repvit_m2_3` | 47.3 mm | 42.3 mm (43.1 / 41.4) |
+| `hgnetv2_b4` | 34.7 mm | 40.7 mm (40.5 / 40.8) |
+
+From scratch the two are 1.6 mm apart, inside seed noise. HGNetv2's timm weights
+are Baidu **SSLD** (ImageNet-22k → 1k distillation); RepViT's are the paper's.
+That is a real, free asset — it is the configuration we would train — but the
+honest claim is "better initialisation", not "better architecture for accuracy".
+Note also that RepViT fit *better* from scratch than pretrained: on an 8-crop
+memorisation task a pretrained trunk has to unlearn, which is one more reason
+this test does not settle generalisation.
+
+**Speed.** Whole student, 224 input, RTX 4070. Training is fwd+bwd+AdamW at
+batch 64; the CPU column is single-thread ONNX fp32, the closest mobile-shaped
+number available without a phone.
+
+| backbone | train B64 | peak GPU | ONNX fp16/CUDA B1 | CPU 1-thread |
+|---|---|---|---|---|
+| `repvit_m2_3` (as shipped) | 193.6 ms | 8549 MiB | 4.76 ms | 115.2 ms |
+| `repvit_m2_3` + `.fuse()` | 142.5 ms | 5347 MiB | 3.55 ms | 110.7 ms |
+| `hgnetv2_b2` | 96.5 ms | 2824 MiB | 3.98 ms | 46.9 ms |
+| `hgnetv2_b4` | **97.4 ms** | **3498 MiB** | **3.00 ms** | **72.5 ms** |
+| `hgnetv2_b6` | 315.2 ms | 9444 MiB | 4.16 ms | 302.3 ms |
+
+**Mechanism, since 2x faster on 40% fewer MACs looks wrong.** `repvit_m2_3`
+spends 105 of its convolutions on depthwise kernels that carry only 0.050 of its
+4.520 GMAC. A depthwise convolution moves a whole feature map to do one multiply
+per element, so it is bandwidth-bound and leaves tensor cores — and an NPU's MAC
+array — idle. HGNetv2 is dense 3x3 convolutions in parallel branches that get
+concatenated: high arithmetic per byte moved, which is what the silicon is built
+for.
+
+**Deployability — this is the axis where it is not close.** Backbone-only ONNX
+op counts, after folding the traced shape ops at batch 1:
+
+| | Conv | `Erf` (GELU) | `ReduceMean`+`Sigmoid` (SE) | `BatchNormalization` | nodes |
+|---|---|---|---|---|---|
+| `repvit_m2_3` | 266 | 55 | 24 + 24 | 51 | 789 |
+| `repvit_m2_3` fused | 215 | 55 | 24 + 24 | 0 | 585 |
+| `hgnetv2_b4` | 80 | **0** | **0** | 0 | **144** |
+
+`hgnetv2_b4`'s trunk is `Conv` / `Relu` / `Concat` / `MaxPool` / `Pad` and
+nothing else — the intersection of every accelerator's op set. `Erf` is absent
+from several NPU op sets, so it falls back to CPU or gets approximated.
+Squeeze-excite needs a *global* spatial reduce, which breaks tile-local dataflow
+and forces a full-feature-map round trip through memory.
+
+int8 post-training quantisation, measured as SQNR on the trunk's own feature map
+(ORT `quantize_static`, QDQ, uint8 activations, 64 real COCO crops to calibrate,
+32 held out). SQNR = `10 log10(var(fp32) / var(fp32 - int8))`; higher is better.
+
+| backbone | per-tensor dB / cos | per-channel dB / cos |
+|---|---|---|
+| `repvit_m2_3` | −0.49 / 0.465 | 0.22 / 0.504 |
+| `repvit_m2_3` fused | −0.38 / 0.492 | 0.58 / 0.588 |
+| `hgnetv2_b0` | 3.50 / 0.732 | 5.89 / 0.847 |
+| `hgnetv2_b2` | 2.22 / 0.646 | 9.95 / 0.939 |
+| `hgnetv2_b4` | 7.92 / 0.918 | **15.14 / 0.984** |
+| `hgnetv2_b6` | 5.66 / 0.889 | 9.55 / 0.954 |
+
+A 14.6 dB gap, and fusing barely moves RepViT. At cosine 0.588 the int8 feature
+map is essentially uncorrelated with the fp32 one — RepViT would need
+quantisation-aware training to ship in int8; `hgnetv2_b4` at 0.984 would not.
+**Mechanism:** HGNetv2's activations are all ReLU, so they are non-negative and
+an unsigned int8 grid covers them exactly. RepViT's depthwise kernels have
+per-channel norms spanning orders of magnitude, and its GELU and SE-gate outputs
+are long-tailed, so one scale cannot cover them. These are deliberately naive
+PTQ settings — min/max calibration, 64 images — because that is what a mobile
+toolchain does first; the absolute values are low for everyone and the *gap* is
+the finding.
+
+**The export path survives unchanged.** Built a synthetic `hgnetv2_b4`
+checkpoint plus `run_config.json` and ran `tools/pth_to_onnx.py` on it with no
+edits: torch↔ONNX parity **5.96e-08** against its 1e-3 gate, `cliff_focal` and
+`bound_scales` read back correctly, metadata stamped. `backbone_feat_dim` is
+informational only — `InstantHMRStudent` reads the real width from
+`backbone.num_features` — so the 2048-channel HGNetv2 map needs no config edit.
+
+**Separate finding, independent of which backbone wins: nothing in this repo
+calls `RepViT.fuse()`.** timm ships the multi-branch training graph and the
+exporter never reparameterises it, so every ONNX we have shipped carries 51
+un-foldable `BatchNormalization` nodes and 204 extra nodes. Fusing is free:
+193.6 → 142.5 ms per training step and 4.76 → 3.55 ms ONNX B1. Worth taking even
+if we stay on RepViT.
+
+**Integration cost: zero code.** `--backbone` already exists in
+`train_distill_jz.py`, `run_config.json` records it, and
+`config_from_checkpoint` reads it back, so `benchmark/eval_3dpw_ckpt.py`,
+`benchmark/eval_emdb_ckpt.py`, `tools/pth_to_onnx.py` and
+`instanthmr/inference.py` all need nothing. Two operational steps only:
+
+```sh
+# 1. warm the timm cache on prepost — compute nodes run HF_HUB_OFFLINE=1
+sbatch --partition=prepost --time=03:00:00 --job-name=warm --output=warm_%j.out \
+ --account=vsi@v100 --wrap \
+ "source \$WORK/InstantHMR/datasets_pipeline/jeanzay/jz_env.sh && \
+ python -u instanthmr_distill_train/train_distill_jz.py --warm-cache \
+ --backbone hgnetv2_b4 --data_root \$DATA_ROOT"
+
+# 2. add the flag to EXTRA_TRAIN_ARGS; everything else stays at gen-6
+EXTRA_TRAIN_ARGS="--preset v2 $COMMON6 --backbone hgnetv2_b4"
+```
+
+If the proxy refuses `cdn-lfs.hf.co`, the weights are 76 MB and already on the
+laptop — `rsync` `models--timm--hgnetv2_b4.ssld_stage2_ft_in1k` the same way
+`JEAN_ZAY.md` describes for RepViT.
+
+**Memory goes down, so the partition question does not reopen.** `hgnetv2_b4`
+peaks at 3498 MiB at batch 64 against `repvit_m2_3`'s 8549 (synthetic step, no
+MHR forward kinematics and no `--w-verts`), so `v100-16g` stays comfortable and
+CLAUDE.md's "re-add `--constraint=v100-32g` if a bigger backbone pushes past
+~12 GiB" does not trigger. `hgnetv2_b6` at 9444 MiB would need watching.
+
+**Plan.** Generation 6 finishes first — it is the `--w-verts` on/off comparison
+and that is the loss baseline; swapping the trunk underneath it would confound
+both questions. Then the backbone comparison runs as its own axis: **3 seeds per
+backbone** (`repvit_m2_3` and `hgnetv2_b4`) on the **full corpus including
+SA-1B**, everything else held at gen-6.
+
+Two things SA-1B changes, both already handled but both easy to get wrong:
+
+* **The mixture must be named explicitly.** `sqrt` hands SA-1B 0.692 of every
+ batch on the strength of 3.4 M crops. Extend `MIX6` rather than falling back
+ to a rule.
+* **`joints_2d_vis` is mandatory.** SA-1B stores unobserved 2D keypoints as
+ literal `(0, 0)`; only 8% of its hand keypoints are real. The mask is already
+ consumed by `loss_2d_native`, `loss_2d_simcc` and `loss_reproj` and defaults
+ to all-ones elsewhere, so nothing else changes — but a folder built without it
+ would drag every predicted hand keypoint to the top-left corner. See "The
+ SA-1B label trap" in `datasets_pipeline/README.md`.
+
+The reported number stays **J14 PA-MPJPE, adapter-applied, on the H36M GT**. The
+overfit test above measures fitting, not generalisation, and does not substitute
+for it.
### 13. PVE has no metric yet — only a loss
@@ -435,6 +576,58 @@ cost is gradient damping, `1 - tanh²`, and on the teacher distribution that is
far from that, depth is wrong — `--focal PX` overrides it.
+### 15. Host-RAM OOM from the pair index — fixed 2026-09-08
+
+Four generation-6 jobs (1857969/70/73/75, then 1884647/48/50) were OOM-killed
+between epochs 14 and 33, at 73.9-76.0 GiB per node against a `mem=160000M`
+cgroup. **Host RAM, not CUDA**: `State=OUT_OF_ME+`, `ExitCode 0:125`,
+`Detected N oom_kill events`, `tasks 0-3: Out Of Memory`. The only Python output
+was a dataloader worker dying of `ConnectionResetError` in
+`multiprocessing/resource_sharer.py` — the symptom of the killer, not a cause.
+
+**Cause.** A list of `(PosixPath, PosixPath)` pairs measures **694 bytes per
+pair**, so the 4,231,947-crop index is 2.94 GB per process.
+`build_jz_loaders` sets `persistent_workers=True` with `num_workers=9` per rank,
+so a node holds 4 parents + 36 workers = 40 processes. Fork shares those pages
+copy-on-write, but CPython writes a refcount into an object header to *read* it,
+so each worker converts the shared index into a private copy as it samples —
+gradually, which is why the kill lands hours in rather than at startup.
+
+**Fix.** `PairIndex` stores the index as three contiguous numpy byte arrays and
+rebuilds the two `Path`s on access (~2 us against a ~6 ms `__getitem__`):
+
+| | bytes/pair | 4.23 M crops |
+|---|---|---|
+| `list` of `Path` pairs | 694 | 2.94 GB/process |
+| `PairIndex` | **87** | **0.37 GB/process** |
+
+8.0x smaller, and numpy arrays carry no per-element refcounts so forks stay
+shared. Verified: 961,139 pairs compared, **0 mismatches**, iteration order
+identical, mixture table unchanged (45.0 / 22.5 / 25.0 / 7.5), slices stay
+compact. `SAM3DStudentDataset` copies only real lists, never a `PairIndex`.
+
+**Two things this cost a day to learn.**
+
+*The `--w-verts` arms died first and that was a red herring.* The surface term
+adds ~2 GiB per node (measured +0.108 GiB/rank at construction, +0.16 GiB steady
+state), so at 74 GiB it decided the *ordering* of four deaths, not whether they
+happened. A 400-step local test showed no leak at all: allocated 1.276 /
+reserved 4.250 / peak 4.123 GiB GPU and 2.67 GiB host, flat from step 50 to 400
+and matching the no-verts arm to three decimals. Correlation with a change is
+not causation by it when every arm shares the real cause.
+
+*`sacct` MaxRSS undersamples.* It reports ~74 GiB against a 156 GiB limit and
+the OOM-killer still fires, both because it samples at ~30 s and because RSS
+double-counts pages shared between a rank and its workers. Do not read "half the
+limit" as "safe".
+
+**Related, same session**: `--constraint=v100-32g` is now in
+`52_train_ddp.slurm` itself, not on the sbatch line — the self-chain resubmits
+with only `--job-name`, so a CLI constraint survives exactly one job. And the
+epoch log now reports peak GPU as the max over all ranks; the "9.3 GiB" figure
+that justified running unconstrained was rank 0's alone, while the ranks that
+OOM'd on 16 GB cards were at 14.99 GiB.
+
---
## Evaluation hygiene the audit raised
diff --git a/instanthmr_distill_train/train_distill_jz.py b/instanthmr_distill_train/train_distill_jz.py
index 9d3d380..89c5c0d 100755
--- a/instanthmr_distill_train/train_distill_jz.py
+++ b/instanthmr_distill_train/train_distill_jz.py
@@ -139,6 +139,59 @@ def dataset_of(npz_path: Path) -> str:
INDEX_VERSION = 2
+class PairIndex:
+ """(image, npz) pairs held as numpy byte arrays instead of Path objects.
+
+ A plain ``list`` of 4.2 M ``(PosixPath, PosixPath)`` tuples is ~2 GB of
+ Python objects, and `build_jz_loaders` runs `persistent_workers=True` with
+ 9 workers per rank -- 36 forked processes per node. Fork gives them
+ copy-on-write pages, but CPython writes a refcount into an object's header
+ just to *read* it, so every worker steadily converts the shared index into
+ a private copy of itself. Measured on Jean Zay: 74-76 GiB resident per node
+ against a 160 GB cgroup, and the OOM-killer firing mid-epoch at epochs
+ 14-33 with no Python traceback.
+
+ Three contiguous numpy arrays carry no per-element refcounts, so a fork
+ shares them and keeps sharing them. Paths are rebuilt on access -- ~2 us
+ against a ~6 ms __getitem__, i.e. free.
+
+ Indexing and iteration yield the same ``(Path, Path)`` tuples the list did,
+ so `build_mixture_weights`, `__len__` and `__getitem__` are unchanged.
+ """
+ __slots__ = ("root", "_sub", "_stem", "_ext")
+
+ def __init__(self, root, entries):
+ self.root = Path(root)
+ # 'S' (bytes) not 'U': numpy stores UTF-32 for 'U', 4x the memory, and
+ # these are filesystem paths that round-trip through UTF-8 exactly.
+ self._sub = np.array([e[0] for e in entries], dtype="S")
+ self._stem = np.array([e[1] for e in entries], dtype="S")
+ self._ext = np.array([e[2] for e in entries], dtype="S")
+
+ def __len__(self):
+ return len(self._stem)
+
+ def __getitem__(self, i):
+ if isinstance(i, slice):
+ # Stay compact through --max_images too, or the one configuration
+ # that slices is the one that reintroduces the Path list.
+ out = PairIndex.__new__(PairIndex)
+ out.root = self.root
+ out._sub, out._stem, out._ext = self._sub[i], self._stem[i], self._ext[i]
+ return out
+ sub = self._sub[i].decode(); stem = self._stem[i].decode()
+ d = self.root / sub
+ return (d / "images" / f"{stem}{self._ext[i].decode()}",
+ d / "annotations" / f"{stem}.npz")
+
+ def __iter__(self):
+ for i in range(len(self)):
+ yield self[i]
+
+ def nbytes(self):
+ return self._sub.nbytes + self._stem.nbytes + self._ext.nbytes
+
+
def _index_fingerprint(data_root: Path) -> list:
"""Cheap identity for the corpus: the sub-folders and their mtimes.
@@ -173,9 +226,7 @@ def build_pair_index(data_root: str, cache: Path | None = None,
with cache.open("rb") as fh:
blob = pickle.load(fh)
if blob.get("version") == INDEX_VERSION and blob.get("fingerprint") == fp:
- pairs = [(root / sub / "images" / f"{stem}{ext}",
- root / sub / "annotations" / f"{stem}.npz")
- for sub, stem, ext in blob["entries"]]
+ pairs = PairIndex(root, blob["entries"])
# One stat() against millions saved. Catches a cache written by
# an older build whose stored sub-folder does not round-trip
# under this data_root -- silently wrong paths would otherwise
@@ -186,7 +237,8 @@ def build_pair_index(data_root: str, cache: Path | None = None,
f"{root} (first entry {pairs[0][0]}) — rebuilding")
raise FileNotFoundError(cache)
log_fn(f" pair index: {len(pairs):,} crops from cache {cache} "
- f"(built {blob.get('built', '?')})")
+ f"(built {blob.get('built', '?')}, "
+ f"{pairs.nbytes()/2**20:.0f} MiB resident)")
return pairs
log_fn(f" pair index: {cache} is stale (corpus changed) — rebuilding")
except Exception as e: # truncated / half-written
@@ -217,7 +269,9 @@ def build_pair_index(data_root: str, cache: Path | None = None,
# again next time. Say so rather than dying an hour into startup.
log_fn(f" pair index: could NOT cache to {cache} ({e}); "
f"every job will repeat the scan")
- return ds.pairs
+ # Return the compact form, not ds.pairs: a cold start must not be the one
+ # configuration that still hands 4.2 M Path objects to 36 forked workers.
+ return PairIndex(root, entries)
def build_mixture_weights(dataset, mix: str | None) -> tuple[torch.Tensor, str]:
@@ -848,8 +902,26 @@ def train(args, cfg, rank, local_rank, world):
raw["Mesh_MPJPE"], em["Mesh_MPJPE"] = (
dpw_raw["J14_MPJPE"], dpw_em["J14_MPJPE"])
+ # Peak GPU across ALL ranks, not just rank 0. Rank 0 is not the
+ # hungriest rank: on 2026-09-08 four gen-6 jobs died of CUDA OOM on a
+ # 16 GB V100 reporting 14.99 GiB allocated, while this line -- rank 0
+ # only -- printed a flat 9.3 GiB for 32 straight epochs. The "measured
+ # peak use is 9.3 GiB" note that justified running without
+ # --constraint=v100-32g came from exactly this blind number.
+ _pk = torch.cuda.max_memory_allocated() / 2**30
+ pk_max, pk_rank = _pk, 0
+ if dist.is_initialized() and world > 1:
+ t = torch.tensor([_pk], device=device)
+ dist.all_reduce(t, op=dist.ReduceOp.MAX)
+ pk_max = float(t.item())
+ # Which rank owns the max, so a lopsided rank is named not guessed.
+ r = torch.tensor([rank if abs(_pk - pk_max) < 1e-6 else world],
+ device=device)
+ dist.all_reduce(r, op=dist.ReduceOp.MIN)
+ pk_rank = int(r.item())
log(f"\n📈 epoch {epoch+1}/{args.epochs} | lr {scheduler.get_last_lr()[0]:.2e}"
- f" | peak GPU {torch.cuda.max_memory_allocated() / 2**30:.1f} GiB")
+ f" | peak GPU {pk_max:.1f} GiB (max over {world} rank(s), "
+ f"rank {pk_rank}; rank 0 {_pk:.1f})")
log(f" train total {tr['total']:.4f} | 3d {tr['3d']:.4f} | "
f"2d {tr['2d']:.4f} | simcc {tr['simcc']:.3f} | "
f"reproj {tr['reproj']:.4f} | cam {tr['cam']:.4f} "
diff --git a/instanthmr_distill_train/train_distill_mhr_only.py b/instanthmr_distill_train/train_distill_mhr_only.py
index 34649ae..39f13f9 100644
--- a/instanthmr_distill_train/train_distill_mhr_only.py
+++ b/instanthmr_distill_train/train_distill_mhr_only.py
@@ -545,7 +545,13 @@ class SAM3DStudentDataset(Dataset):
# startup, so having every DDP rank redo it is the largest fixed cost of
# a cluster run. See build_pair_index() in train_distill_jz.py.
if pairs is not None:
- self.pairs = list(pairs)
+ # Keep a compact index (train_distill_jz.PairIndex) AS IS. Calling
+ # list() on it would materialise 4.2 M Path pairs -- ~2 GB of Python
+ # objects that 36 forked dataloader workers then copy page by page
+ # through refcount writes, which is what OOM-killed four Jean Zay
+ # jobs at 74-76 GiB. Only copy a real list, which is the local /
+ # single-process path and small.
+ self.pairs = list(pairs) if isinstance(pairs, (list, tuple)) else pairs
print(f" Prebuilt index: {len(self.pairs)} (image, npz) pairs "
f"(augment={augment}).")
return
diff --git a/tools/pth_to_onnx.py b/tools/pth_to_onnx.py
index 1fee455..01295ab 100644
--- a/tools/pth_to_onnx.py
+++ b/tools/pth_to_onnx.py
@@ -35,8 +35,8 @@ Usage
# or point at a specific checkpoint / output
python ./tools/pth_to_onnx.py \
- --ckpt ./instanthmr_distill_train/runs/bno_s0/bno_s0/best_student_model_v3.pth \
- --output ./models/instanthmr_mhr_only.onnx
+ --ckpt ./instanthmr_distill_train/runs/g6vv_s/g6vv_s/best_student_model_v3.pth \
+ --output ./models/instanthmr.onnx
"""
import argparse
import importlib