Python
fix: carry bound_scales and cliff_focal from the checkpoint into export, evaluation and deployment
mohamdevf9c9289f8c39
diff --git a/CLAUDE.md b/CLAUDE.mdindex 497a53a..8bcf048 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -108,6 +108,7 @@ Docs are the source of truth; the code is bigger than any context window.| 4 | `benchmark/README.md` | how published numbers are produced; the 3DPW GT (SMPL forward + H36M regressor), the MHR->J14 adapter, and why **J14+adapter** is the row to quote || 5 | `datasets_pipeline/README.md` | how the corpus is built, including the SA-1B visibility mask || 6 | `docs/architecture.md` | the student model |+| 7 | `docs/todo.md` | open defects and opportunities from the 2026-09-06 audit, each with the measurement behind it |`datasets_pipeline/jeanzay/` and `JEAN_ZAY.md` are in `.git/info/exclude` onpurpose — they carry the login name, jump host and project code. Keep@@ -208,6 +209,20 @@ mandatory for new runs, because the rebuilt corpus carries real per-imagefocals spanning `f/diag` 0.6-1.8 where the pixel form is ambiguous; the oldcorpus was constant at 1.000. See `instanthmr_distill_train/README.md`.+**Never rebuild a config from `DistillConfig()` defaults to load a checkpoint.**+Two 2026-09-06 flags make the defaults wrong, in opposite ways.+`--bound-scales` puts a `tanh` remap inside `forward()`, so a default-config+export reads the head's raw pre-`tanh` numbers as bone scales — measured 21.0+mm MPJPE / 14.4 mm PA-MPJPE of silent corruption. `--cliff-focal` changes what+the conditioning vector *means*, not the graph, so a mismatch raises nothing.+Use `T.config_from_checkpoint()`: it reads the bounds out of the weights+(`scale_lo`/`scale_hi` are the flag) and the conditioning form out of the+`run_config.json` beside the checkpoint, and `tools/pth_to_onnx.py` stamps the+latter into the ONNX metadata so `instanthmr.inference` configures itself.+Deployment has no annotation to read a focal from, so it falls back to+`1.05 x diag` for focal-aware graphs and `1.00 x diag` for pixel-conditioned+ones (that IS the old corpus's synthetic focal); `demo.py --focal` overrides.+**One reported number: J14 PA-MPJPE, adapter-applied, on the H36M GT.** Thetraining log, `summarize_runs.py` and `benchmark/eval_3dpw_ckpt.py` all printit and they agree to the decimal. J12 was removed on 2026-09-06 — it was thediff --git a/README.md b/README.mdindex 03e83cb..5220f09 100644--- a/README.md+++ b/README.md@@ -212,6 +212,7 @@ per frame than InstantHMR. The two flags below target that bottleneck.| `--device coreml` | On macOS, route the InstantHMR ONNX through `CoreMLExecutionProvider`. || `--max-persons N` | Maximum number of persons processed per frame (default: **2**). See below. || `--no-batch-persons` | Disable batched multi-person HMR (one ONNX call per person). The default is batched. |+| `--focal PX` | Your camera's focal length **in pixels**, when you know it. Models exported from a `--cliff-focal` checkpoint are conditioned on *angles*, so they need a focal; without one the demo falls back to `1.05 x` the image diagonal, which is a reasonable phone/webcam stand-in but mis-places the person in depth on any camera whose true focal differs. Older pixel-conditioned graphs ignore it and are unaffected. |### `--max-persons` and why it mattersdiff --git a/benchmark/README.md b/benchmark/README.mdindex 2fbbe62..2def996 100644--- a/benchmark/README.md+++ b/benchmark/README.md@@ -154,6 +154,41 @@ python benchmark/eval_3dpw_ckpt.py \Both write a JSON report to `benchmark/results/`.+### The evaluator configures itself from the checkpoint (fixed 2026-09-06)++`eval_3dpw_ckpt.py` used to build a **default** `DistillConfig`, which silently+disagreed with any run that used one of the 2026-09-06 flags:++* `--bound-scales` puts a `tanh` remap of the 77 body-size parameters inside+ `forward()`. Exporting or scoring without it reads the head's raw pre-`tanh`+ numbers as bone scales — **21.0 mm MPJPE / 14.4 mm PA-MPJPE** of corruption,+ measured on 64 COCO teacher targets.+* `--cliff-focal` changes what the conditioning vector *means*, not the graph,+ so feeding the wrong form raises nothing.++Both are now restored per checkpoint by `T.config_from_checkpoint()`: the+bounds from the weights (`scale_lo` / `scale_hi` are the flag), the+conditioning form from the `run_config.json` beside the checkpoint. The script+prints what it inferred:++```+[cfg] bno_s0/best_student_model_v3.pth: backbone=repvit_m2_3 bound_scales=True cliff_focal=True [run_config.json]+[3DPW] test / GT=h36m: 35,463 person-frames (stride 1), CLIFF conditioning angular (real per-sequence focal)+```++Check that line. `cliff_focal=False [DEFAULT ...]` on a run you launched with+`--cliff-focal` means `run_config.json` did not travel with the checkpoint —+pass `--cliff-focal` by hand. The checkpoint load is **strict**, so a bounded+checkpoint scored through the wrong config raises instead of quietly producing+a number. Checkpoints that disagree on the conditioning cannot share one+invocation, because the crops are built once; the script says so and exits.++The focal itself comes from 3DPW's own calibration (`cam_intrinsics`,+`K[1,1]` = 1969.23 px on 10 of the 12 validation sequences, 1961.85 on the two+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)3DPW **test**, all 35,463 person-frames, published-protocol GT, the two Jean Zaydiff --git a/benchmark/benchlib/runner.py b/benchmark/benchlib/runner.pyindex cf88fbb..50a9bc5 100644--- a/benchmark/benchlib/runner.py+++ b/benchmark/benchlib/runner.py@@ -106,7 +106,12 @@ def run_samples(model: InstantHMR, samples: list[Sample],if image is None:continuedets = [{"bbox": samples[i].bbox, "confidence": 1.0} for i in idxs]- out = model.predict_batch(image, dets)+ # The dataset's own focal when it has one (3DPW is calibrated), so+ # a graph exported from a --cliff-focal checkpoint is conditioned+ # on the real camera rather than a diagonal-derived stand-in. Every+ # sample in a group is the same frame, hence the same focal.+ out = model.predict_batch(image, dets,+ focal=samples[idxs[0]].meta.get("focal"))for i, p in zip(idxs, out):preds[i] = pdiff --git a/benchmark/eval_3dpw_ckpt.py b/benchmark/eval_3dpw_ckpt.pyindex 9a5fc33..97ea8e6 100644--- a/benchmark/eval_3dpw_ckpt.py+++ b/benchmark/eval_3dpw_ckpt.py@@ -54,7 +54,15 @@ def parse_args():p.add_argument("--fit-adapter", default=None,help="fit that regressor on THIS split and write it here ""(run on train, never on test)")- p.add_argument("--backbone", default="repvit_m2_3")+ p.add_argument("--backbone", default=None,+ help="override the backbone; normally read from the "+ "run_config.json beside the checkpoint")+ p.add_argument("--cliff-focal", dest="cliff_focal", action="store_true",+ default=None,+ help="force the focal-aware CLIFF conditioning; normally "+ "read from run_config.json")+ p.add_argument("--no-cliff-focal", dest="cliff_focal", action="store_false",+ help="force the pixel-normalised CLIFF conditioning")p.add_argument("--batch-size", type=int, default=64)p.add_argument("--num-workers", type=int, default=6)p.add_argument("--device", default="cuda")@@ -94,7 +102,35 @@ def predict(model, loader, mhr_module, device, use_amp: bool = True):def main():args = parse_args()device = torch.device(args.device)- cfg = T.DistillConfig(backbone=args.backbone)++ # Rebuild each checkpoint's real training configuration instead of the+ # defaults: `--bound-scales` changes the forward pass and `--cliff-focal`+ # changes what the conditioning vector means. Getting either wrong scores+ # a different model than the one that was trained. See+ # T.config_from_checkpoint.+ 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++ # One shared 3DPW loader, so every checkpoint must agree on the conditioning.+ 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))W_adapt = W_adapt_gt = None@@ -108,10 +144,13 @@ def main():for gt in args.gt:ds = val3dpw.ThreeDPWValSet(args.sequence_dir, args.image_root,split=args.split, stride=args.stride,- gt=gt, gt_dir=args.gt_dir)+ gt=gt, gt_dir=args.gt_dir,+ cliff_focal=cliff_focal)sets[gt] = dsprint(f"[3DPW] {args.split} / GT={gt}: {len(ds):,} person-frames "- f"(stride {args.stride})", flush=True)+ f"(stride {args.stride}), CLIFF conditioning "+ f"{'angular (real per-sequence focal)' if cliff_focal else 'pixel-normalised'}",+ flush=True)first = sets[args.gt[0]]loader = torch.utils.data.DataLoader(first, batch_size=args.batch_size, shuffle=False,@@ -124,8 +163,10 @@ def main():print(hdr)for ck_path in args.ckpt:- model = T.InstantHMRStudent(cfg, pretrained=False).to(device)+ model = T.InstantHMRStudent(cfgs[ck_path], pretrained=False).to(device)ck = torch.load(ck_path, map_location="cpu", weights_only=False)+ # Strict: an unexpected key means the config restored above is wrong+ # and the model being scored is not the model that was trained.model.load_state_dict(ck["model_state_dict"])pred, idx, n_dropped = predict(model, loader, mhr, device, cfg.use_amp)del modeldiff --git a/demo.py b/demo.pyindex 5e98a14..c9f3a8b 100755--- a/demo.py+++ b/demo.py@@ -110,6 +110,14 @@ def parse_args() -> argparse.Namespace:"--no-batch-persons", action="store_true",help="Disable batched multi-person HMR (one ONNX call per person).",)+ p.add_argument(+ "--focal", type=float, default=None,+ help="Camera focal length in PIXELS, when it is known. A graph exported "+ "from a --cliff-focal checkpoint is conditioned on angles, so it "+ "needs one; without it the demo falls back to 1.05x the image "+ "diagonal, which mis-places the person in depth on any camera "+ "whose true focal differs.",+ )p.add_argument("--smoothing-filter", action="store_true",help="Temporally smooth per-person predictions with a moving-average "@@ -211,6 +219,7 @@ def build_pipeline(args: argparse.Namespace, mhr=None) -> PosePipeline:detector_stride=args.detector_stride,batch_persons=not args.no_batch_persons,mhr=mhr,+ focal=args.focal,)diff --git a/docs/accuracy_audit_2026-09-06.md b/docs/accuracy_audit_2026-09-06.mdnew file mode 100644index 0000000..9506bbf--- /dev/null+++ b/docs/accuracy_audit_2026-09-06.md@@ -0,0 +1,97 @@+Audit of the working tree on 6 September 2026++The best opportunity is to improve what the student learns from its supervision before increasing the backbone. There are also confirmed evaluation/export defects that must be fixed before measuring a new method. Three research directions below could support separate papers, but their accuracy gains and novelty remain experimental questions; none is a guaranteed CVPR contribution.++Scope: inspected the current MHR-only trainer, DDP driver, augmentation and conversion code, evaluation, inference/export, available run configurations/results, and relevant primary research. Existing uncommitted changes were included in the audit and preserved. Numerical probes ran on CPU with the local TorchScript rig, local annotations, and the epoch-137 EMA checkpoint b3_s1. CUDA was unavailable to this process, so there was no new GPU timing, distributed reproduction, or training sweep. The small probes are diagnostics, not new benchmark results.++**What the current baseline actually is.**++The active default architecture has 39,961,412 trainable parameters, verified by instantiating it: RepViT-M2.3, a four-layer decoder of width 512, and 71 queries. One query supplies all 204 MHR parameters, 45 surface-shape parameters, and three camera translations; 70 queries supply the auxiliary/deployed 2D output. Self-attention allows those queries to help the global query, so their presence does not prove wasted capacity. The released model's 17M/9-query description and approximately 5 ms timing are not measurements of this current pipeline.++The stored report `benchmark/results/3dpw_test_b3_s1_teacher_adapter.json` records 41.825 mm J14 PA-MPJPE and 69.030 mm root-relative MPJPE on 35,463 test person-frames, with zero dropped predictions. These are existing results, not rerun results. Training used rebalanced losses, so loss rebalance is already part of that baseline. The README's later 41.71 claim is not the value in this report; identify exact checkpoint, adapter and preprocessing hashes before quoting a baseline.++**Confirmed implementation problems, ordered by priority.**++1. **Standalone export silently removes scale bounds.** `tools/pth_to_onnx.py:116` constructs the default configuration, where bounds are off; line 128 loads with `strict=False`, and unexpected keys only print a message. A bounded model's `scale_lo` and `scale_hi` are therefore ignored. Reproducing this exact reload pattern produced no missing keys, two unexpected keys, and a maximum MHR-output difference of 0.288254 on the same input, before any ONNX conversion. This used newly initialized models with identical loaded weights, isolating the configuration defect; it is not a measured deployed checkpoint error. Restore the saved architecture/configuration, reject unexpected model keys, and compare all exported outputs with the original configured model on real crops.++2. **Focal conditioning is not carried through evaluation and deployment.** `benchmark/eval_3dpw_ckpt.py:97` creates a default config; its dataset construction at line 109 does not enable `cliff_focal`. Bounded checkpoints instead fail strict loading because the evaluator has no corresponding buffers. `instanthmr/pipeline.py:98` does not pass focal calibration into `InstantHMR`. Even direct use of `InstantHMR(focal=...)` returns the diagonal-image heuristic in `HMRPrediction.focal_length` at `instanthmr/inference.py:256` and in the batch path. Training validation does pass the new flag. Consequently the documented equality of all evaluation paths only holds for compatible older configurations. Store preprocessing mode independently of whether intrinsics are known, serialize intrinsics/config metadata, and test training-validation/checkpoint/ONNX parity.++3. **The v2 crop-center update omits division by zoom.** `train_distill_mhr_only.py:678` uses `cx -= dx * crop_w / 2` and similarly for y. With zero roll, the image transform is `u' = s(u-center) + center + translation`; its inverse puts the crop center at `center - translation/s`. The conditioning update requires that same `/s`. On a real MPII crop of width 996 pixels, scale 2 and dx 0.20, the code supplies center 1101.4 instead of 1151.2: a 49.8-pixel discrepancy. This is a controlled augmentation probe, not an estimate of mean dataset error. Derive conditioning from the complete inverse affine transform, including rotation and flip, instead of separate manual corrections.++4. **The new camera representation remains approximate for unequal fx/fy.** `train_distill_mhr_only.py:704` uses fy for both axes. A camera with diagonal focal matrix F does not in general satisfy `R F = F R`; rotating pixels and rotating 3D with an unchanged anisotropic camera are different operations. A synthetic fx=1000, fy=500, 30-degree roll example gives 44.88 pixels of disagreement. This does not establish an error of that size in the actual corpus: sampled COCO/AIC/MPII focals had equal axes, and a separate 128-sample Harmony4D probe found fx/fy between 0.99393 and 1.03757. This is a smaller, conditional concern in the available data. Carry full transformed intrinsics/rays or rectify to square pixels. Existing counter-rotation in the reprojection loss avoids claiming that its forward/reverse algebra itself is broken; the issue is the physical consistency and information content of the input representation.++5. **Validation can reward a model that fails on hard frames.** `val3dpw.py:179` removes non-finite predictions before calculating accuracy. Logging a drop count does not prevent checkpoint selection on the easier surviving subset. Mark such a checkpoint invalid for selection, or explicitly define a fixed-population failure metric. `train_distill_jz.py:120` also averages rank means and counts rather than reducing error sums and valid counts. That is slightly inaccurate for uneven shards and potentially worse when failure counts differ. The existing b3_s1 report has zero drops, so this is a vulnerability in selection, not evidence its stored result was inflated this way.++6. **Recovery bookkeeping overstates successful updates.** In both regular and fallback paths, the driver calls the scheduler and EMA after `GradScaler.step` without checking whether gradient overflow skipped the optimizer update (`train_distill_jz.py:715`, `:793`). A finite loss does not imply finite gradients. Likewise, finite non-FK losses are not mathematically bounded: squared parameter error and cross-entropy can grow without bound. Make successful-update counting explicit and inspect gradient finiteness. The scale bounds and fallback remain useful safeguards; they do not by themselves certify recovery. This was established by control-flow inspection, not a GPU overflow reproduction.++**Remaining learning bottlenecks and limits on the evidence.**++- **Incomplete direct parameter supervision.** At the default geometric probabilities, only 20% of samples receive direct root-parameter loss. With `pose_split` enabled, local pose receives it on 60%; without it, only 20%. Flipped examples still have 3D geometric supervision, so saying they have no 3D training signal would be wrong. Correct mirrored local-transform targets and valid rotated root targets can restore direct supervision without another image encoder pass. Validate the rig's mirror mapping instead of assuming its Euler channels have SMPL's permutation/sign convention.+- **Redundant target coordinates.** The actual 889-by-204 rig transform has rank 192. A parameter displacement of norm 10 along a null direction changed skeleton positions by at most 0.000153 mm across 192 sampled annotations. Thus coordinate losses distinguish some targets that are identical for the skeleton. This verifies redundancy, not that those directions contain substantial teacher variance or explain several millimeters of error. Measure that variance and its trunk gradients before treating this as the dominant cause. Skeleton equivalence must also be checked against mesh corrective behavior before replacing exported parameters.+- **The mesh is poorly assessed by the training objective.** `MHRForwardPass.get_joints` explicitly replaces the 45 identity parameters with zeros. Perturbing supplied shape by +2 changed its skeleton by exactly zero in the probe. Shape still receives direct parameter loss, but there is no surface reconstruction loss or surface metric to establish mesh fidelity. PA-MPJPE improvement can coexist with worse body shape or hands. Add sparse surface supervision and a surface evaluation using a valid cross-topology correspondence where needed.+- **Substantial student/label discrepancy remains.** On 32 unaugmented crops from each local source, b3_s1 had body-30 PA error against annotations of 33.57 mm on COCO, 27.21 on AIC, and 33.09 on MPII. These are training-source samples, not verified individual members of the cluster's train partition. They support investigating fit/representation quality, without establishing a generalization score or proving the backbone is the cause. On a separate 192-annotation probe, the skeleton-to-keypoint approximation alone contributed 1.35 mm over 70 points and 3.14 mm over the 30 body points. It is not the whole approximately 30 mm discrepancy, but the overall 70-point average hides its larger body residual.+- **Auxiliary objectives compete for shared features.** The README reports that 2D terms account for roughly 56% of trunk gradient norms in one study and that detaching them gave a small pilot improvement. Those measurements were not independently rerun here. Critically, Gaussian-label entropy divided by total cross-entropy is not the fraction of the task that is learned: `CE=H(target)+KL(target||prediction)`, and H is a constant with zero model gradient. The quoted entropy floor does not prove 95% convergence or justify detachment. Gradient direction, variance, and matched-seed task results are the relevant evidence. Nor does one global output token alone prove a capacity bottleneck.+- **Data quantity is not useful supervision quantity.** Mixture weights depend on dataset counts. Per-keypoint observation confidence is used for 2D; the 3D objective uses fixed body/finger weights rather than sample-specific fit reliability or ambiguity. Many occluded labels are complete optimization fits, which does not mean they are visually identifiable. Do not simply remove all invisible 3D supervision: it also supplies useful pose priors. Measure error by visibility, pose rarity and label provenance, and separate uncertainty in fitted labels from uncertainty in image evidence.+- **The data loader uses stored person crops.** Original frames and optional hand crops exist in the pipeline but are not consumed by this trainer. This limits realistic crop jitter and hand detail; interpolating a 224-pixel body crop cannot restore unseen detail. Stronger augmentation should be tested against access to actual surrounding image content.++**Evaluation issues that matter for a submission.**++The local corpus is documented as containing all 3DPW sequences in `sam3d_distill_mix`; cluster-trained checkpoints are documented as using a different, clean corpus. The loader itself does not enforce this separation. Use a saved source-image/sequence manifest and explicit exclusions for validation and test, including any offline regressor/feature-cache fitting. The skeleton-to-keypoint fitter scans every supplied dataset folder, so its provenance also matters.++The fixed teacher-derived J14 adapter is preferable to fitting a different adapter per student, but it is still learned using paired 3DPW-train ground truth. Disclose that target-dataset supervision. Rotation/translation equivariance does not prove that a linear map cannot absorb systematic pose error. Test the map on held-out sequences and an external dataset or derive it from body-model correspondences. The fitting script's halfway split is not an explicit sequence grouping. Never refit on the reported split.++The harness uses GT-derived boxes, further crop expansion, a 60%-inside-image filter and its own person-frame list. Using the standard SMPL/H36M reference alone does not establish an identical published protocol. Reevaluate comparison models on the same manifest, or implement their standard protocol faithfully. Report GT boxes versus detected boxes and known versus estimated intrinsics separately. Disable recurring test-set monitoring while choosing methods: human design decisions can overfit it even if checkpoint-selection code ignores it.++PA-MPJPE removes global translation, rotation and scale. Root-relative MPJPE removes translation but still penalizes scale and orientation. Neither is a temporal consistency metric; both can detect pose errors that also cause jitter. Report camera-space accuracy, surface error, hand error, temporal acceleration error and bone-length variation when making those claims. Low acceleration alone can result from oversmoothing: compare against GT motion and report lag. The repository's documented 34–49 mm seed spread is for a different 70-keypoint metric, not a measured standard deviation of the current J14+adapter result.++**Three candidate contributions, each intended as an independent research program.**++**1. Distillation over identifiable articulated geometry.**++Hypothesis: a compact student wastes learning capacity on arbitrary choices made by fitting solvers, and receives inconsistent or missing parameter supervision under image transformations. Define an equivalence class of rig parameters that produce the same relevant geometry; supervise that class and physically meaningful local transforms instead of blindly reproducing each solver coordinate.++Start with the verified linear redundancy: for the transform A and parameter prediction p, use a normalized robust loss on `A(p_student-p_target)`, or predict its independent coordinates. Add exact transformation rules for roll and mirroring, periodic/geodesic rotation losses, and confidence that distinguishes image-observable constraints from teacher priors. Keep surface-specific information in a separately supervised residual if skeleton-equivalent parameters are not mesh-equivalent. Recover a valid bounded representative for export; naive projection followed by clipping can break equivalence.++The inexpensive baseline is transformed-coordinate loss with the deployed architecture unchanged. A 192-coordinate head plus fixed reconstruction costs about 39,000 multiply-accumulates per person; it can be fused with adjacent linear operations where there is no intervening nonlinear constraint. Target less than 10% extra training time and approximately unchanged inference; verify both rather than assuming them.++The research claim must be broader than removing 12 dimensions: demonstrate invariance to equivalent relabelings, better gradient conditioning, and improved sample efficiency across more than one rig/annotation source. Compare against raw parameter loss, geometry-only loss, normalized joint-transform loss, a pose-prior baseline and augmentation fixes alone. [MHR](https://arxiv.org/abs/2511.15586), [HybrIK](https://openaccess.thecvf.com/content/CVPR2021/html/Li_HybrIK_A_Hybrid_Analytical-Neural_Inverse_Kinematics_Solution_for_3D_Human_CVPR_2021_paper.html) and [TokenHMR](https://arxiv.org/abs/2404.16752) already cover expressive rigs, geometric inverse kinematics and pose representations; those are not new claims here.++Main risk: the redundant directions may have little actual target variance, so removing them may produce negligible accuracy gains. A cheap first experiment should compare projected and raw parameter losses with identical geometric losses and seeds. If only numerical stability improves, this remains an engineering fix rather than an independent accuracy paper.++**2. Distill the teacher features that resolve 3D ambiguity, under a fixed teacher-compute budget.**++Hypothesis: final fitted labels leave the compact encoder to rediscover difficult cues such as front/back orientation, foreshortening and occluded-limb context. The current loss contains no intermediate teacher-feature transfer. Transfer a small, body-part representation chosen for its influence on 3D pose rather than generic feature similarity or 2D localization.++On a predeclared 5–10% training subset, extract clean-image teacher part descriptors. Estimate which feature directions affect depth/articulation using the teacher decoder's output sensitivities, while separating camera and surface-shape responses. Cache a compressed descriptor and reliability information. Train small student-side projectors on corresponding part queries/features, including degraded views with correctly matched body-part identities. Retain the ordinary supervision on the full corpus. Do not assume spatially warping cached DINO features is equivalent to reencoding a rotated/occluded image.++A possible cache format is 16 descriptors × 64 channels × 2 bytes = 2,048 bytes/image: about 7.6 GB for 3.7M images, or 0.38 GB for 5%, before metadata. This is a proposed compression format, not a measured sufficient representation. Generating teacher features and sensitivities has a real offline GPU cost; report it and enforce a budget. Do not run the teacher every minibatch. Remove projectors at inference, giving exactly zero additional deployed network operations if the student architecture is kept fixed. Target no more than 20% additional total training-plus-preprocessing GPU-hours.++The publishable claim would be that pose-sensitive feature selection transfers more 3D accuracy per teacher GPU-hour than generic feature distillation. Compare equal-budget output-only transfer, ordinary feature matching, random projections, uniform versus selected examples, and simple 2D-loss attenuation/detachment. Require effects beyond a single backbone and on difficult poses in an external dataset. [DUNE](https://arxiv.org/abs/2503.14405) already distills heterogeneous 2D/3D/human features, and [BinParam](https://www.sciencedirect.com/science/article/pii/S0925231226009574) includes feature distillation for efficient parametric reconstruction. Adding feature MSE alone is therefore insufficient novelty.++Main risks: fitting privileged annotations does not guarantee the monocular teacher knows the same answer, and sensitivity selection may retain unstable teacher directions. Teacher accuracy, descriptor compression and reliability calibration must be measured. This is my first choice for improving pose accuracy at fixed deployed architecture, provided the offline budget is acceptable.++**3. A single inexpensive correction that uses 2D evidence only where it constrains 3D.**++Hypothesis: the model predicts both 2D locations and a body model, but the deployed 2D evidence never explicitly corrects the body. A generic reprojection correction can improve pixels while worsening depth. Learn a correction restricted by which pose directions the available observations can actually determine.++Use calibrated 2D uncertainty, residuals between predicted image joints and projected MHR joints, the current pose, and full camera information. During training, the projection/kinematic Jacobian identifies well-observed versus ambiguous directions. A damped small correction should use image residuals in the former and preserve the learned prior in the latter. Distill that operation into a compact module predicting, for example, 16–32 correction coefficients. Runtime uses one encoder pass, one correction module and the necessary rig evaluation; no test-time autograd or iterative diffusion. Calibrate uncertainty separately: SimCC's fixed-width Gaussian training targets do not automatically provide calibrated uncertainty.++The Jacobian and damped-update formulation are training tools here, not an assumption that a full 204-parameter solver is free. Profile the actual correction plus FK. Set a design cap of 0.5M extra parameters and 10% additional median and p95 person-pipeline latency, including geometry decoding. Stop or redesign if the cost exceeds that cap. Numerical stability and ONNX compatibility must be demonstrated.++The claim is safe, calibrated use of available evidence under occlusion and camera error at a tightly bounded compute cost. Compare against an equal-size unconstrained residual MLP, one ungated correction step, reprojection-loss tuning, and an existing refinement method. Evaluate PA-MPJPE and absolute error together; merely improving reprojection is insufficient. [PyMAF](https://openaccess.thecvf.com/content/ICCV2021/papers/Zhang_PyMAF_3D_Human_Pose_and_Shape_Regression_With_Pyramidal_Mesh_ICCV_2021_paper.pdf) already feeds alignment evidence back into regression; [TokenHMR](https://arxiv.org/abs/2404.16752) studies the 2D/3D tradeoff; [Multi-HMR 2](https://arxiv.org/abs/2606.14841) addresses camera-centric recovery. A residual head, uncertainty weighting or camera conditioning alone is not sufficient novelty.++Main risk: monocular depth ambiguity cannot be solved by algebra or confidence alone. The correction must fall back to its prior when evidence is insufficient, and a lower 2D error cannot guarantee a lower true 3D error. Demonstrate failure detection and robustness rather than claiming a universal guarantee.++**How to decide whether any direction deserves a full paper.**++First establish a corrected baseline with config/export parity, stable bounds, correct crop geometry, clean sequence manifests and fixed adapter provenance. Preserve an old-compatible configuration for historical comparisons. Run ordinary fixes as baseline work; do not count their gains as the proposed method's novelty.++The documented new-run safeguards `--cliff-focal`, `--bound-scales` and `--anomaly-safe-fallback` still default to off. Neither preset automatically enables all of them. Explicit run configuration is necessary, and the export/evaluation defects above must be repaired before a bounded, focal-aware run can be judged through all entry points.++Screen each direction independently on matched data, initial weights, sample counts and optimizer-update budgets using validation only. Use paired seeds for early elimination, then at least three complete seeds for a promising direction and more if variance remains high. Bootstrap by sequence/person rather than treating adjacent frames as independent. Compare against the corrected baseline and the simplest non-novel alternative.++As a project decision threshold—not a CVPR rule or a predicted outcome—seek about 10% lower primary 3D error (roughly 4 mm if the corrected baseline remains near 42 mm), replicated on at least one external benchmark, with hand/surface quality preserved and the compute caps met. A smaller aggregate gain can still be meaningful if the paper establishes a substantial, general failure-mode improvement with strong evidence. Fix the threshold on validation before inspecting final test results.++For public comparisons include [SAM 3D Body](https://arxiv.org/abs/2602.15989), [Fast SAM 3D Body](https://arxiv.org/abs/2603.15603), [FastHMR](https://arxiv.org/abs/2510.10868), and relevant strong pose baselines such as [NLF](https://arxiv.org/abs/2407.07532), subject to matched data and evaluation protocols. Fast SAM 3D Body already reports up to 10.9× end-to-end acceleration; a lightweight SAM student by itself is not a sufficient novelty argument. Separate network-only timing, rig decoding and detector-inclusive timing on identical hardware and precision.++Reproduction artifacts from this audit are in `/tmp/instanthmr-audit/`: `probe.py`, `probe_results.json`, `checkpoint_probe.py`, and `checkpoint_results.json`. They use the existing `sam3d_video_312` Python environment and should be run from the repository root. The probes do not modify model weights or training data. The report is the only repository file added by this audit.diff --git a/docs/todo.md b/docs/todo.mdnew file mode 100644index 0000000..80cba39--- /dev/null+++ b/docs/todo.md@@ -0,0 +1,260 @@+# Open work, from the 2026-09-06 accuracy audit++What the external audit found, what was checked against the code, and what is+left. The audit itself is `docs/accuracy_audit_2026-09-06.md`; this file is the+verdict on each item and the queue.++Every claim below was reproduced on real data before being written down. Where+a number appears, the command that produced it is named.++---++## Done (2026-09-06)++### 1. The ONNX exporter dropped the scale bounds — 21 mm, silently++`tools/pth_to_onnx.py` built a default `DistillConfig`, where `bound_scales` is+off, and loaded with `strict=False`. A `--bound-scales` checkpoint's `scale_lo`+/ `scale_hi` were reported as "unexpected keys" and discarded, so the exported+graph had no `tanh` remap while the head still emitted pre-`tanh` values.++**Mechanism.** With `--bound-scales` the last layer no longer emits bone scales.+It emits a raw number that `tanh` maps into the rig's legal size range. Feed+those raw numbers to the forward kinematics directly and the skeleton is+wrong — not catastrophically, because the pre-`tanh` values are small+(`|u|` mean 0.120, max 0.571 over teacher targets), but consistently.++**Measured**, reconstructing the exact pre-`tanh` values a bounded head must+emit to reproduce 64 real COCO teacher targets, then running the rig both ways:++```+MPJPE (export vs correct), raw : 21.0 mm+MPJPE (export vs correct), centred : 19.9 mm+PA-MPJPE(export vs correct) : 14.4 mm+```++On a 41.8 mm PA-MPJPE model that is a third added, with no error raised.++**Fixed by** `T.config_from_checkpoint()` in `train_distill_mhr_only.py`, which+reads `bound_scales` back out of the weights. Unexpected keys are now a hard+exit, and the exporter gates on a PyTorch↔ONNX parity check (`2.7e-05` on a+bounded graph, `3.1e-05` on a legacy one).++### 2. Training and evaluation could use different camera inputs++Three separate holes, failing in opposite ways:++* `benchmark/eval_3dpw_ckpt.py` built a default config, so `cliff_focal` was+ off — **silent**. It also loaded strictly, so a bounded checkpoint raised —+ **loud**, and the only reason no wrong number was ever published.+* `instanthmr/pipeline.py` never passed a focal to `InstantHMR`.+* `HMRPrediction.focal_length` always reported `sqrt(H^2+W^2)` even when a real+ focal was supplied, so anything unprojecting or rendering used a fake camera.++**Fixed by** separating *which conditioning form* (from `run_config.json` for+checkpoints, from ONNX metadata for graphs) from *what the focal is* (the+dataset's own value in training and both evaluators; `--focal`, else+`1.05 x diag`, at deployment). See `instanthmr_distill_train/README.md`+§`--cliff-focal` and `benchmark/README.md`.++**Measured cost of the form mismatch**: 0.13 mm J14+adapter PA-MPJPE on a+170-frame 3DPW validation probe. Small, because Procrustes removes exactly what+this corrupts. The `bound_scales` half is where the 14–21 mm lives.++---++## Queue++Ordered by (cost of being wrong) x (cheapness of the fix). Items 3, 4 and 6 are+defects; 5 and 7 onward are opportunities the audit raised that are not bugs.++### 3. The v2 crop-centre update forgets to divide by the zoom — **in flight**++`train_distill_mhr_only.py:678` writes `cx -= dx * crop_w / 2.0`. The+augmentation warps the crop with `u' = s*R*(u - c) + c + t`; inverting it puts+the visible window's centre at `-t/s`, so the correction needs the `/s`. It+over-corrects when zooming in and under-corrects when zooming out. Live in+every `--preset v2` run (`geom_trans=0.20`, `geom_scale_max=2.0`).++**Measured** over 972 augmented COCO/AIC/MPII samples drawn from the real v2+distribution:++| | px err mean | px p95 | deg mean | deg p95 | deg max |+|---|---|---|---|---|---|+| all | 11.7 | 33.6 | 0.61 | 1.73 | 3.21 |++0.6° of error in the bearing the network is told, on average — 4% of the crop's+own angular half-width, 13% at worst.++**It is a wrong input, not a wrong label.** Verified: feeding the teacher's own+3D joints and `cam_trans` through the reprojection loss's full geometry+(counter-rotate, un-mirror, project in the original frame, apply `aug_M`)+against the augmented 2D targets, over 64 samples with 34 flipped, gives a+residual of **0.000 px**. The augmented geometry chain is exact. And the third+conditioning channel — angular size, `b_scale / scale`, the one that sets depth+and motivated `--cliff-focal` — is already correct. The damage is confined to+lateral placement, which PA-MPJPE cannot see.++**Fix** (one character per line):++```python+cx -= dx * crop_w / (2.0 * scale)+cy -= dy * crop_w / (2.0 * scale)+```++**Do not patch this on the cluster while runs are chaining.**+`52_train_ddp.slurm` resubmits itself on walltime, so an rsync'd trainer changes+the augmentation partway through a 300-epoch run. Land it for the next+generation, and note in `STATUS.md` that generation 5 carried the uncorrected+version.++### 4. Validation drops the frames the model failed on++`val3dpw.py:179` removes non-finite predictions before scoring — necessary,+because one `inf` makes numpy's Procrustes SVD raise and that killed a healthy+20-hour job. But the count is only logged, and the surviving-subset score still+competes for "best checkpoint" at `train_distill_jz.py:895`. A checkpoint that+blows up on the hardest frames can therefore be selected over one that merely+does badly on them.++The distributed half is real but numerically trivial: `all_reduce_mean`+averages rank means rather than pooling, and the 3DPW set is stride-sharded+499/498/498/498 out of 1,993, so the bias is under 0.1% unless failures cluster+on one rank.++**Risk is low right now**: `--bound-scales` is exactly what stops the outputs+going non-finite. **Watch** `⚠️ 3DPW: N non-finite prediction(s) dropped` in+the epoch log — zero every epoch means this never fires; a rising count is a+real instability and should be investigated immediately.++**Fix when convenient**: reduce error *sums* and valid *counts* rather than+rank means, and either mark an epoch with drops ineligible for selection or+score dropped frames at a fixed penalty so the population is constant.++### 5. Score both routes to 2D keypoints on the same footing++The graph emits 2D keypoints two ways, and only one is measured today:++1. `joints_2d` — the SimCC head. This is what `benchmark/eval_coco.py` scores+ (`p.joints_2d[COCO17_FROM_MHR70]`) and what `--detach-2d-head` degrades.+2. `mhr_params` + `cam_trans` -> forward kinematics -> project with the focal.+ Governed by `loss_reproj`, which the `dt` runs leave **unchanged** to within+ seed noise, so the trunk has not lost image-plane localisation — only the+ SimCC readout of it has.++The logged columns cannot settle which is better: `loss_reproj` is an L1 with+fingers down-weighted to 0.2 and `w_reproj = 0.5` folded in, while+`loss_2d_native` is a smooth-L1 at full finger weight times 10. Different+norms, different weights, both on training data.++**Add a `--from-mhr` path to `eval_coco.py`** that projects the MHR keypoints+instead of reading `joints_2d`, and report both on the same 17 COCO body+keypoints. That is the measurement that decides whether the SimCC head still+earns its place — and note the projected route needs `cam_trans` to be right,+which PA-MPJPE cannot validate, so it is not automatically the safer choice.++**If the projected route wins, "remove the 2D head" is still not the change to+make.** The head is 0.025 of ~10.8 GFLOPs — 0.23%, nothing. The cost is in the+**70 decoder queries** that feed it: 15.7% of total FLOPs. Dropping those is a+different architecture that no run has tested, and the standing hypothesis is+that they *help* the global token via self-attention. Sequence: finish the+runs, score both routes, then a separate ablation with the 70 queries removed.+Dropping `loss_2d_simcc` / `loss_2d_native` under `--detach-2d-head` is the one+free part — they already contribute exactly zero trunk gradient there.++### 6. `n_repair` overstates successful updates++`GradScaler.step` silently skips the optimiser when gradients overflow, but+`train_distill_jz.py:715` / `:793` call `scheduler.step()` and+`ema.update_parameters()` regardless and count a repair. Consequences are+cosmetic — re-averaging unchanged weights into the EMA is harmless, and+stepping the scheduler through a skip is deliberate (freezing the LR during a+skip storm is what caused the earlier runaway). Worth making explicit so the+"repaired N" line means what it says.++### 7. Direct parameter supervision reaches 20–60% of samples++At `geom_p=0.8`, `geom_flip_p=0.5`: root rotation (`mhr_params[3:6]`) is+supervised on the 20% with no spatial augmentation; local angles, bone scales+and shape on the 60% that were not flipped. **Not a bug** — the dataset rotates+and mirrors the labels without rotating the parameters, so the masked-out+targets are genuinely wrong, and those samples still get full 3D geometric+supervision.++**The opportunity**: transform the targets properly instead of masking — mirror+the left/right parameter channels for flips, compose the roll into the root+rotation. Needs the rig's mirror mapping **verified, not assumed**; MHR's Euler+channels are not SMPL's permutation/sign convention.++### 8. Twelve redundant target dimensions++`parameter_transform[:, :204]` has rank 192. Moving 10 units along a null+direction changes the skeleton by `< 0.0002 mm`, yet `loss_pose` / `loss_scale`+still penalise the difference — 12 dimensions of solver-arbitrary teacher noise+no image can determine.++**Measure before acting**: how much teacher variance actually lies along those+directions, and how much trunk gradient they carry. The audit is explicit that+redundancy alone does not prove a cost. Do **not** "fix" it by zeroing the+`*_flexible` parameters — the teacher genuinely uses them+(`leg_length_flexible` mean 0.32, max 1.64) and zeroing shortens every leg.++### 9. The mesh is invisible to the geometry objective++`MHRForwardPass.get_joints` zeroes the 45 `shape_params` before the forward+pass; perturbing them by +2 sigma moves the 127-joint skeleton by exactly+`0.00e+00 cm`. They receive direct parameter loss (`w_shape = 0.03`) and+nothing else. So every geometric loss and every reported metric is blind to+body shape.++**Consequence for claims, today**: PA-MPJPE can improve while the mesh gets+worse. Do not say "better mesh" on the strength of a pose number.+**Consequence for work, later**: a surface term and a surface metric, with a+valid cross-topology correspondence.++### 10. `fy` for both axes — checked, not a problem here++The conditioning uses one focal where a camera has two. Measured `fx/fy` over+300 samples per split:++| split | fx/fy |+|---|---|+| coco, aic, mpii | 1.00000 exactly |+| harmony4d | 0.98661 – 1.03656 |+| 3dpw | 0.99625 – 1.00376 |++The `bno` / `dt` mix is `aic/coco/mpii` only — perfectly isotropic — and 3DPW+differs by 0.4%. Revisit only if a new split with anisotropic pixels enters the+mix.++---++## Evaluation hygiene the audit raised++Not code defects, but they gate a submission.++* **Sequence manifests.** The local corpus contains all 3DPW sequences in+ `sam3d_distill_mix`; cluster-trained checkpoints use a different, clean+ corpus, but the loader does not *enforce* the separation. Save a+ source-image / sequence manifest and exclude explicitly — including for any+ offline regressor or adapter fitting.+* **Adapter provenance.** The fixed teacher-derived J14 adapter is fitted on+ 3DPW-train ground truth. That is target-dataset supervision and must be+ disclosed. Test it on held-out sequences; never refit on the reported split.+ The fitting script's halfway split is not an explicit sequence grouping.+* **Protocol parity.** The harness uses GT-derived boxes, its own crop+ expansion, a 60%-inside-image filter and its own person-frame list. Using the+ standard SMPL/H36M reference does not by itself make the protocol identical+ to a published one. Report GT vs detected boxes and known vs estimated+ intrinsics separately.+* **Test-set monitoring.** `--val-3dpw-test` is logged and never used for+ selection, which is right, but human design decisions can still overfit a+ number you watch every epoch.+* **Metrics.** PA-MPJPE removes translation, rotation and scale; root-relative+ MPJPE removes translation. Neither sees `cam_trans` drift, body-size error or+ jitter. Claims about stability need acceleration and bone-length-variance+ numbers, and low acceleration alone can just mean over-smoothing — compare+ against GT motion and report lag.+* **Seed spread.** The documented 34–49 mm spread is for the 70-keypoint+ metric, not for J14+adapter. Measure the spread of the metric you quote+ before calling any gap real.diff --git a/instanthmr/inference.py b/instanthmr/inference.pyindex 7b80113..27b20ed 100644--- a/instanthmr/inference.py+++ b/instanthmr/inference.py@@ -36,6 +36,17 @@ IMAGENET_MEAN = np.array([0.485, 0.456, 0.406], dtype=np.float32)IMAGENET_STD = np.array([0.229, 0.224, 0.225], dtype=np.float32)INPUT_SIZE = 224CROP_EXPAND = 1.2 # square crop around the detector bbox, matching training+# Focal used when the camera is uncalibrated, as a multiple of the image+# diagonal. A focal-aware checkpoint needs a number here whatever happens --+# the conditioning is an ANGLE, so there is no "unknown" to pass. 1.05x diag+# (~50 degrees horizontal FOV on 16:9) is the usual stand-in for a phone or+# webcam; pass the real value through `focal=` whenever it is known.+#+# It applies to focal-aware graphs ONLY. A pixel-conditioned checkpoint was+# trained on a corpus whose annotations set f = sqrt(H^2+W^2) exactly (see+# tools/annotate_dataset.py), so 1.0x diag IS that model's camera and using+# anything else would put a 5% error into its rendered depth.+FOCAL_FALLBACK_DIAG = 1.05def onnx_output_names(onnx_path: str | Path) -> Optional[list[str]]:@@ -70,7 +81,9 @@ class HMRPrediction:joints_3d_cam: (70, 3) joints in camera space (= local + cam_trans).joints_2d: (70, 2) joints projected into full-frame pixel coords.cam_trans: (3,) camera translation [tx, ty, tz], metres.- focal_length: (2,) [fx, fy] full-frame virtual focal = sqrt(H^2+W^2).+ focal_length: (2,) [fx, fy] full-frame focal in pixels -- the camera+ this prediction is expressed in. The real focal when one was+ supplied, else the diagonal stand-in ``_focal_px`` picks.principal_point: (2,) [cx, cy] = full-frame centre.image_shape: (H, W) of the source frame.mhr_params: (204,) MHR pose parameters (34 joints × 6-D rotation).@@ -105,6 +118,14 @@ class InstantHMR:head. Any object exposing ``keypoints(mhr_params, shape_params)``works; see :func:`instanthmr.mhr_renderer.build_mhr`. Ignored for5-output graphs.+ focal: the camera's focal length in pixels, when it is known. Used by+ the focal-aware conditioning and reported back in+ ``HMRPrediction.focal_length``. Left unset, an uncalibrated+ stand-in of ``FOCAL_FALLBACK_DIAG * sqrt(H^2+W^2)`` is used.+ cliff_focal: which conditioning form the checkpoint was trained with.+ Read from the ONNX metadata that ``tools/pth_to_onnx.py`` stamps,+ so it normally needs no setting; pass it explicitly for a graph+ exported before that existed.Example-------@@ -120,6 +141,7 @@ class InstantHMR:providers: Optional[list[str]] = None,mhr: object | None = None,focal: float | None = None,+ cliff_focal: bool | None = None,):import onnxruntime as ort@@ -162,11 +184,37 @@ class InstantHMR:self._out_names = out_namesself.has_joints_3d_head = "joints_3d" in out_names or len(out_names) >= 5self._mhr = mhr- # None -> the image-normalised CLIFF conditioning the model was trained- # with by default. Set it to the camera's focal length in pixels for a- # checkpoint trained with --cliff-focal.++ # Two independent things, and conflating them is what made this wrong:+ #+ # cliff_focal -- WHICH conditioning form the checkpoint was trained+ # with. Angles off the optical axis, or image-normalised pixels.+ # The vector is 3 floats either way, so feeding a model the wrong+ # one raises nothing; it silently mis-places the person in depth.+ # tools/pth_to_onnx.py stamps it into the graph metadata, so a+ # freshly exported model configures itself.+ # focal -- WHAT the camera's focal length is, in pixels. Only used by+ # the angular form. Unknown is not an option there, so an+ # uncalibrated camera falls back to FOCAL_FALLBACK_DIAG * diagonal.+ #+ # Passing `focal=` alone still implies the angular form, which is how+ # this argument behaved before `cliff_focal` existed.+ meta = self.session.get_modelmeta().custom_metadata_map or {}+ if cliff_focal is None:+ cliff_focal = (str(meta.get("cliff_focal", "")).lower() == "true"+ or focal is not None)+ self.cliff_focal = bool(cliff_focal)self.focal = focal+ def _focal_px(self, h: int, w: int, focal: float | None = None) -> float:+ """The camera focal in pixels: this call's, the session's, or a+ stand-in -- in that order."""+ f = focal if focal is not None else self.focal+ if f is not None:+ return float(f)+ diag = math.sqrt(h * h + w * w)+ return (FOCAL_FALLBACK_DIAG * diag) if self.cliff_focal else diag+@propertydef derives_joints_3d(self) -> bool:"""True when the 70 keypoints must come from an MHR forward pass."""@@ -207,6 +255,7 @@ class InstantHMR:image_rgb: np.ndarray,bbox: np.ndarray | list[float],confidence: float = 1.0,+ focal: float | None = None,) -> HMRPrediction:"""Run InstantHMR on a single person.@@ -214,6 +263,9 @@ class InstantHMR:image_rgb: (H, W, 3) uint8 RGB full-frame image.bbox: tight person bbox [x1, y1, x2, y2] in pixel coords.confidence: detection confidence to attach to the output.+ focal: this frame's focal length in pixels, overriding the one+ given to the constructor. Use it when the focal varies per+ image, as it does across calibrated benchmark sequences.Returns:``HMRPrediction`` with joints in full-frame coordinates.@@ -223,7 +275,7 @@ class InstantHMR:bbox_arr = np.asarray(bbox, dtype=np.float32).reshape(4)crop, sq_x1, sq_y1, sq_size, cliff_cond = self._preprocess(- image_rgb, bbox_arr, h, w+ image_rgb, bbox_arr, h, w, focal)outs = self.session.run(@@ -253,8 +305,9 @@ class InstantHMR:joints_3d_cam = joints_3d_local + cam_trans- # Full-frame virtual pinhole: focal = sqrt(H^2 + W^2), principal = centre.- f = math.sqrt(h * h + w * w)+ # Report the focal actually used, so anything that unprojects or+ # renders these joints uses the same camera the model was conditioned on.+ f = self._focal_px(h, w, focal)focal_length = np.array([f, f], dtype=np.float32)principal_point = np.array([w / 2.0, h / 2.0], dtype=np.float32)@@ -277,6 +330,7 @@ class InstantHMR:image_rgb: np.ndarray,detections: list[dict],padded_to: int | None = None,+ focal: float | None = None,) -> list[HMRPrediction]:"""Run InstantHMR on multiple persons in a single ONNX call.@@ -287,6 +341,8 @@ class InstantHMR:(zero-padded if fewer detections). Keeping a constant batchsize prevents CUDA from re-compiling kernels each time theperson count changes.+ focal: this frame's focal length in pixels, overriding the one+ given to the constructor.Returns:One ``HMRPrediction`` per input detection, in the same order.@@ -306,7 +362,7 @@ class InstantHMR:for i, det in enumerate(detections):bbox_arr = np.asarray(det["bbox"], dtype=np.float32).reshape(4)crop, sq_x1, sq_y1, sq_size, cliff = self._preprocess(- image_rgb, bbox_arr, h, w,+ image_rgb, bbox_arr, h, w, focal,)crops[i] = cropcliffs[i] = cliff@@ -327,7 +383,7 @@ class InstantHMR:# including the zero-padded slots — they are discarded below.joints_3d_local_b = self._joints_3d(mhr_params_b, shape_params_b)- f = math.sqrt(h * h + w * w)+ f = self._focal_px(h, w, focal)focal_length = np.array([f, f], dtype=np.float32)principal_point = np.array([w / 2.0, h / 2.0], dtype=np.float32)@@ -392,6 +448,7 @@ class InstantHMR:bbox: np.ndarray,h: int,w: int,+ focal: float | None = None,) -> tuple[np.ndarray, float, float, float, np.ndarray]:"""Square 1.2x crop, ImageNet normalise, and CLIFF conditioning."""x1, y1, x2, y2 = bbox.astype(float)@@ -405,10 +462,11 @@ class InstantHMR:# instanthmr_distill_train/train_distill_mhr_only.py. A model trained# with the focal-aware form and run with the pixel form (or the other# way round) does not error; it silently mis-places the person in depth.- if self.focal is not None:- cliff_cond = np.array([math.atan((cx - w / 2.0) / self.focal),- math.atan((cy - h / 2.0) / self.focal),- max(bw, bh) / self.focal], dtype=np.float32)+ if self.cliff_focal:+ f = self._focal_px(h, w, focal)+ cliff_cond = np.array([math.atan((cx - w / 2.0) / f),+ math.atan((cy - h / 2.0) / f),+ max(bw, bh) / f], dtype=np.float32)else:cx_norm = 2.0 * (cx / w) - 1.0cy_norm = 2.0 * (cy / h) - 1.0diff --git a/instanthmr/pipeline.py b/instanthmr/pipeline.pyindex ff5df10..f9543c1 100644--- a/instanthmr/pipeline.py+++ b/instanthmr/pipeline.py@@ -72,6 +72,13 @@ class PosePipeline:Required for MHR-only graphs, whose 3D keypoints are derivedfrom the predicted MHR parameters instead of a 3D head; ignoredby graphs that carry a ``joints_3d`` output.+ focal: The camera's focal length in pixels, when known. A graph+ exported from a ``--cliff-focal`` checkpoint is conditioned on+ angles rather than pixels, so it needs a focal; without one it+ falls back to a diagonal-derived stand-in, which mis-places the+ person in depth on any camera whose true focal differs.+ cliff_focal: Override the conditioning form; normally read from the+ ONNX metadata. See :class:`instanthmr.inference.InstantHMR`.Example-------@@ -91,11 +98,14 @@ class PosePipeline:detector_stride: int = 1,batch_persons: bool = True,mhr: object | None = None,+ focal: float | None = None,+ cliff_focal: bool | None = None,):if detector_stride < 1:raise ValueError("detector_stride must be >= 1")- self.hmr = InstantHMR(onnx_path, device=device, mhr=mhr)+ self.hmr = InstantHMR(onnx_path, device=device, mhr=mhr,+ focal=focal, cliff_focal=cliff_focal)if self.hmr.derives_joints_3d and mhr is None:raise ValueError(f"{Path(onnx_path).name} has no 'joints_3d' output (MHR-only student): "diff --git a/instanthmr_distill_train/README.md b/instanthmr_distill_train/README.mdindex cffe86e..e24c2a7 100644--- a/instanthmr_distill_train/README.md+++ b/instanthmr_distill_train/README.md@@ -153,10 +153,44 @@ stability and bone-length variance, never on the benchmark.**Three places compute this vector and all three must agree**:`SAM3DStudentDataset.__getitem__`, `val3dpw._preprocess` (which takes the real-`fy` from 3DPW's `cam_intrinsics`), and `instanthmr.inference.InstantHMR`-(pass `focal=` for a checkpoint trained with the flag). Mismatching them raises-nothing; it silently mis-places the person in depth. `run_config.json` records-`cliff_focal`.+`fy` from 3DPW's `cam_intrinsics`), and `instanthmr.inference.InstantHMR`.+Mismatching them raises nothing; it silently mis-places the person in depth.++### Carrying the flag past training (fixed 2026-09-06)++Until 2026-09-06 nothing outside the trainer knew about it: the checkpoint+evaluator and the ONNX exporter both built a default `DistillConfig`, so a+focal-aware model was scored and deployed with the pixel form. Two lookups+close that, and neither needs a flag in the normal case:++| consumer | how it learns the form |+|---|---|+| `train_distill_jz.py` validation | `cfg.cliff_focal` directly |+| `benchmark/eval_3dpw_ckpt.py` | `run_config.json` beside the checkpoint |+| `instanthmr.inference.InstantHMR` | `cliff_focal` in the ONNX metadata, stamped by `tools/pth_to_onnx.py` |++`T.config_from_checkpoint()` in `train_distill_mhr_only.py` is the single+implementation. It also restores `bound_scales` — from the weights, since+`--bound-scales` registers `scale_lo`/`scale_hi` buffers and their presence+*is* the flag. Both scripts print what they inferred and where it came from;+`--cliff-focal` / `--no-cliff-focal` override it for a checkpoint whose+`run_config.json` is missing or predates the flag.++**The value of `f`, once the form is known, is a separate question.** Training+and both 3DPW evaluators use the dataset's own focal — `cam_focal_length[1]`+per annotation, and 3DPW's calibrated `K[1,1]` (1969.23 px on 10 of the 12+validation sequences, 1961.85 on the two landscape ones). Deployment has no+annotation, so `instanthmr.inference` falls back to+`FOCAL_FALLBACK_DIAG * sqrt(H^2+W^2)` with `FOCAL_FALLBACK_DIAG = 1.05`, and+`demo.py --focal <px>` supplies the real one. The fallback applies to+focal-aware graphs **only**: a pixel-conditioned checkpoint was trained on a+corpus where `cam_focal_length = sqrt(H^2+W^2)` exactly, so `1.00 x diag` is+that model's camera and is left untouched.++Measured cost of getting the form wrong: **0.13 mm** J14+adapter PA-MPJPE on a+170-frame 3DPW validation probe (47.46 vs 47.33) — consistent with the ~0.1 mm+above. Like the flag itself, this matters for absolute placement and jitter,+not for the headline number.The default is `False` and is bit-identical to the pre-flag trainer, verifiedover augmented samples tensor by tensor.@@ -257,6 +291,114 @@ Confirmed directly: pushing `scale_spine_length` to 20.3 along a null directionmoves the skeleton by 1.2e-7 m. The bound now keeps that wandering finite;collapsing the redundancy properly would be a separate change.+## `--detach-2d-head` (added 2026-09-06, experimental)++Stops the 2D SimCC head from training the **shared trunk** — the backbone plus+the decoder, i.e. everything that builds the representation. The head keeps its+full loss, keeps its weights trainable, and stays a deployed ONNX output; the+only thing that changes is that its gradient no longer flows back into the+decoder. One line in `InstantHMRStudent.forward`: `feat_2d = feat_2d.detach()`.++### Why++The trunk is being trained mostly for an output the benchmark does not measure.+Back-propagating each loss term separately through the converged `b3_s1`+checkpoint, over real augmented batches, gives the share of the gradient that+reaches backbone + decoder:++| term | share of the trunk's gradient |+|---|---|+| `loss_2d_simcc` | **47.6%** |+| `loss_2d_native` | 8.6% |+| `loss_cam` | 22.3% |+| all seven 3D body-pose terms together | **20.7%** |++The dominant term is also the most exhausted and the noisiest. `loss_2d_simcc`+sits at **2.227 nats against an irreducible floor of 2.112** — that floor is the+entropy of its own Gaussian soft label at `sigma = 2 * bin_w`, which no model can+go below.++> **Correction (2026-09-06).** An earlier version of this section read "only+> 5.2% of the term is reducible, i.e. a task already 95% converged". That does+> not follow. `CE = H(target) + KL(target || prediction)`, and `H` is a+> constant with **zero gradient**, so the ratio `2.112 / 2.227` says nothing+> about how much of the *learnable* part is left: the learnable part is the+> whole of `KL = 0.115` nats, and this number cannot say whether that is close+> to optimal. Use it only as a scale for reading the `simcc` column — subtract+> 2.112 to get the part the model is actually being graded on. The gradient+> measurements below (47.6% share, SNR 0.28, cosine +0.21) are independent of+> this and stand.++Its trunk gradient has the+worst signal-to-noise of any term (`|mean g| / mean |g|` = 0.28, against 0.39 for+the pose group) and only a +0.21 per-batch cosine with the pose gradient. Most of+what it sends into the backbone is batch noise from a task that is already 95%+converged.++The same imbalance is in the compute. At 224, batch 1: backbone 9.040 GFLOPs+(83.8%), the 71-query decoder 1.694 GFLOPs (15.7%), the 2D head 0.025 GFLOPs, and+the **parameter head 0.0003 GFLOPs — 0.003%**. Seventy of the 71 decoder queries+serve the 2D output; all 204 MHR parameters are read from the one remaining+token.++This is a **trade-off, not a free win**: `joints_2d` is a real deployed output+(`instanthmr/inference.py` consumes `outs[3]`), despite this file's module+docstring calling the head training-only. Watch `2d` and `simcc` in the epoch log+— if they regress materially, the flag has cost you the 2D product to buy 3D+accuracy.++### What it does not do++It does not kill the 70 keypoint queries. They still receive gradient through the+decoder's self-attention with the global token, so they stay alive and become+free capacity for the token the parameters are read from — they simply stop being+*forced* to encode 2D image-plane positions.++### Verified++Flag off is **bit-identical** to the pre-flag code: all five forward tensors+match to `0.000e+00` over 32 augmented `--preset v2` samples. Flag on leaves+every forward value unchanged (so the ONNX graph and the deployed output are+untouched) and takes the 2D losses' gradient into the trunk from `1.9778` to+exactly `0.000000`, while the 2D head's own gradient is unchanged at `0.8389`.+Neither mode leaves any parameter without a gradient, so DDP does not need+`find_unused_parameters`.++### Evidence, and its limits++In a 1500-step fine-tune from `b3_s1` on COCO+AIC, scored on held-out 3DPW crops+against the teacher (body-30 PA-MPJPE, mm):++| arm | start | 1500 | delta |+|---|---|---|---|+| control | 42.34 | 42.13 | −0.21 |+| **`--detach-2d-head`** | 42.34 | **41.57** | **−0.77** |+| 2D losses x0.1 | 42.34 | 41.91 | −0.43 |+| control at LR/4 (step-size control) | 42.34 | 42.47 | +0.13 |++The ordering is monotone in how much 2D gradient reaches the trunk, and the LR+arm rules out "it just took smaller steps". But 0.5-0.9 mm on one seed from an+already-converged checkpoint is well inside the 34-49 mm seed spread this repo+sees, so treat it as a direction to test, not a result. The real test is a+from-scratch pair of seeds against a matched control.++### The underlying finding++The teacher's own labels in `data/sam3d_gt_3dpw` are **14.5 mm** J14+adapter+PA-MPJPE from real 3DPW MoCap (sequence-holdout adapter; 12.5 with the shipped+one), and `b3_s1` disagrees with those labels by **28.5-31.1 mm on COCO / AIC /+MPII, which it trained on** (39.8 mm on held-out 3DPW). That is underfitting, not+label noise: there is no variance shrinkage (per-joint student/teacher variance+ratio 0.94-1.06), the per-frame noise floor is only 10.9 mm (teacher 3.9, real+motion 7.3 between adjacent 30 fps frames), and averaging over the mirror and+rotation symmetries makes the error *worse* (46.3 vs 39.9 mm). A frozen-trunk+probe study says it is not the readout either: a plain `Linear` on the global+token scores 41.8 mm against 49.9 for an MLP reading all 71 tokens.++Caveat on the ceiling: those teacher labels were fit with ground-truth access, so+14.5 mm is not a reachable monocular target. Published monocular SOTA (~36-38 mm)+is the practical floor.+## The reported numberOne number everywhere: **J14 PA-MPJPE, adapter-applied, against thediff --git a/instanthmr_distill_train/train_distill_jz.py b/instanthmr_distill_train/train_distill_jz.pyindex 82af302..3d7e19a 100755--- a/instanthmr_distill_train/train_distill_jz.py+++ b/instanthmr_distill_train/train_distill_jz.py@@ -648,6 +648,12 @@ def train(args, cfg, rank, local_rank, world):"bound_scales": cfg.bound_scales,"scale_bound_margin": cfg.scale_bound_margin,"anomaly_safe_fallback": cfg.anomaly_safe_fallback,+ # getattr, not attribute access: the two files are rsynced+ # separately, so a job can start with this driver already updated+ # and train_distill_mhr_only.py still on the old revision. Reading+ # the field directly would raise and, because the self-chain only+ # resubmits on rc == 0, kill the run outright.+ "detach_2d_head": getattr(cfg, "detach_2d_head", False),"started": time.strftime("%Y-%m-%d %H:%M")})ema_rollbacks = 0@@ -959,6 +965,15 @@ def parse_args():action="store_true",help="on an anomalous batch, step on the non-FK terms ""instead of discarding the batch")+ p.add_argument("--detach-2d-head", dest="detach_2d_head", action="store_true",+ help="stop the 2D SimCC head from shaping the shared trunk "+ "(backbone + decoder). It keeps full supervision and "+ "stays a deployed output; only its gradient into the "+ "trunk is cut. On the converged b3_s1 checkpoint the 2D "+ "terms own 56.2%% of the trunk's gradient against 20.7%% "+ "for all seven 3D body-pose terms, while loss_2d_simcc "+ "is 95%% irreducible label entropy. Off by default so "+ "existing runs stay bit-identical.")p.add_argument("--mhr_model_path", default=None)p.add_argument("--kp_regressor_path", default=None)@@ -1074,6 +1089,7 @@ def build_cfg(args):if args.output_dir: cfg.log_dir = args.output_dirif args.bound_scales: cfg.bound_scales = Trueif args.anomaly_safe_fallback: cfg.anomaly_safe_fallback = True+ if args.detach_2d_head: cfg.detach_2d_head = Trueif args.scale_bound_margin is not None:cfg.scale_bound_margin = args.scale_bound_marginif args.mhr_model_path: cfg.mhr_model_path = args.mhr_model_path@@ -1194,6 +1210,9 @@ def main():+ (f" (margin {cfg.scale_bound_margin})" if cfg.bound_scales else "")+ f" | safe_fallback={cfg.anomaly_safe_fallback}"+ f" | rollback@{cfg.anomaly_skip_patience} x{cfg.max_ema_rollbacks}")+ log(f"trunk detach_2d_head={getattr(cfg, 'detach_2d_head', False)}"+ + (" (2D head keeps its loss but no longer trains backbone/decoder)"+ if getattr(cfg, "detach_2d_head", False) else ""))log(f"seed {args.seed} | mix {args.mix} | "f"samples/epoch {args.samples_per_epoch:,}")log("=" * 66)diff --git a/instanthmr_distill_train/train_distill_mhr_only.py b/instanthmr_distill_train/train_distill_mhr_only.pyindex 4516586..fbcf150 100644--- a/instanthmr_distill_train/train_distill_mhr_only.py+++ b/instanthmr_distill_train/train_distill_mhr_only.py@@ -45,6 +45,7 @@ os.environ.setdefault("PYTORCH_CUDA_ALLOC_CONF", "expandable_segments:True")import argparseimport io+import jsonimport mathimport randomimport gc@@ -293,6 +294,28 @@ class DistillConfig:bound_scales: bool = Falsescale_bound_margin: float = 0.5scale_bounds_path: str = str(PROJECT_ROOT / "assets/mhr_size_bounds.npz")+ # Stop the 2D SimCC head from shaping the shared trunk (backbone + decoder).+ # It keeps its full supervision and stays a deployed output -- only the+ # gradient path back into the decoder is cut, so the trunk is trained by the+ # 3D pathway alone.+ #+ # Measured on the converged b3_s1 checkpoint over real augmented batches:+ # of the gradient reaching backbone+decoder, loss_2d_simcc owns 47.6% and+ # loss_2d_native 8.6%, loss_cam 22.3%, and all seven 3D body-pose terms+ # together 20.7%. The dominant term is also the most exhausted and the+ # noisiest: loss_2d_simcc sits at 2.227 nats against an irreducible floor of+ # 2.112 (the entropy of its own Gaussian soft label at sigma = 2 bins), so+ # only 5.2% of it is reducible, and its trunk gradient has the worst+ # signal-to-noise of any term (|mean g| / mean |g| = 0.28 against the pose+ # group's 0.39) at a +0.21 per-batch cosine with it.+ #+ # The 70 SimCC queries keep receiving gradient through the decoder's+ # self-attention with the global token, so they do not go dead -- they stop+ # being *forced* to encode 2D image-plane positions and become free capacity+ # for the token the parameters are read from.+ #+ # Default off: --preset baseline and --losses legacy must stay bit-identical.+ detach_2d_head: bool = Falseuse_amp: bool = Trueema_decay: float = 0.9998early_stop_patience: int = 150@@ -372,6 +395,58 @@ def apply_rebalanced_losses(cfg) -> None:cfg.finger_weight = 0.2 # 40 of 70 keypoints, none of them in J12/J14+def config_from_checkpoint(state, ckpt_path=None, **overrides):+ """Rebuild the DistillConfig a checkpoint was actually trained with.++ Two sources, because the checkpoint dict carries neither.++ * The ARCHITECTURE flags are readable from the weights. ``--bound-scales``+ registers ``scale_lo`` / ``scale_hi`` buffers, so their presence in the+ state dict IS the flag. Building the default config instead drops the+ tanh remap while the head still emits pre-tanh values -- measured on 64+ COCO teacher targets, that is 21.0 mm MPJPE / 14.4 mm PA-MPJPE of silent+ corruption on a model whose benchmark is 41.8 mm.+ * The INPUT-PIPELINE flags are not. ``--cliff-focal`` changes what the+ conditioning vector MEANS, not the graph, so nothing in the weights+ records it; it is read from the ``run_config.json`` that+ train_distill_jz.py writes beside the checkpoint. Feeding a focal-aware+ model the pixel form (or the reverse) raises nothing -- it silently+ mis-places the person in depth.++ Returns ``(cfg, provenance)``; *provenance* maps each restored field to+ where it came from, so a caller can print what it inferred rather than+ leaving the user to trust it.+ """+ cfg = DistillConfig()+ prov = {}++ cfg.bound_scales = "scale_lo" in state+ prov["bound_scales"] = "checkpoint weights"++ run_cfg = {}+ if ckpt_path is not None:+ rc = Path(ckpt_path).resolve().parent / "run_config.json"+ if rc.is_file():+ run_cfg = json.loads(rc.read_text())+ for k in ("cliff_focal", "backbone", "scale_bound_margin"):+ if k in run_cfg:+ setattr(cfg, k, run_cfg[k])+ prov[k] = "run_config.json"++ for k, v in overrides.items():+ if v is not None:+ setattr(cfg, k, v)+ prov[k] = "command line"++ if "cliff_focal" not in prov:+ # Either no run_config.json beside the checkpoint, or one written+ # before --cliff-focal existed. Both mean "assume the old pixel form",+ # which is right for those runs but must be visible, not assumed.+ prov["cliff_focal"] = ("DEFAULT -- run_config.json is missing or "+ "predates the flag; pass --cliff-focal / "+ "--no-cliff-focal if that is wrong")+ return cfg, prov+# ============================================================# Cell 3 — Dataset and Data Augmentation# ============================================================@@ -828,6 +903,7 @@ class InstantHMRStudent(nn.Module):self.kp2d_bins = getattr(cfg, 'kp2d_bins', 96)self.kp2d_range = getattr(cfg, 'kp2d_range', 1.5)+ self.detach_2d_head = bool(getattr(cfg, "detach_2d_head", False))self.head_2d_feat = nn.Sequential(nn.Linear(cfg.d_model, 256),nn.GELU()@@ -916,6 +992,12 @@ class InstantHMRStudent(nn.Module):parts.append(pred_mhr_params[:, prev:])pred_mhr_params = torch.cat(parts, dim=1)+ # Cut the 2D head's gradient into the shared trunk. Forward values are+ # untouched, so the deployed joints_2d output and the ONNX graph are+ # unchanged; only what the backbone and decoder are trained FOR changes.+ if self.detach_2d_head:+ feat_2d = feat_2d.detach()+feat_2d_processed = self.head_2d_feat(feat_2d)logits_2d = self.head_2d_logits(feat_2d_processed)logits_2d = logits_2d.unflatten(-1, (2, self.kp2d_bins))@@ -2303,6 +2385,10 @@ def parse_args():action="store_true",help="On an anomalous batch, step on the non-FK terms ""instead of discarding the batch.")+ p.add_argument("--detach-2d-head", dest="detach_2d_head", action="store_true",+ help="Stop the 2D SimCC head from shaping the backbone and "+ "decoder. It keeps full supervision and stays a deployed "+ "output; only its gradient into the shared trunk is cut.")p.add_argument("--kp3d-warmup-steps", dest="kp3d_warmup_steps", type=int, default=None,help="Optimiser steps over which the FK-path losses ramp from 0 to full weight.")p.add_argument("--w_keypoints3d", type=float, default=None,@@ -2358,6 +2444,7 @@ def main():if args.no_resume: cfg.resume = Falseif args.bound_scales: cfg.bound_scales = Trueif args.anomaly_safe_fallback: cfg.anomaly_safe_fallback = True+ if args.detach_2d_head: cfg.detach_2d_head = Trueif args.scale_bound_margin is not None: cfg.scale_bound_margin = args.scale_bound_marginif args.kp3d_warmup_steps is not None: cfg.kp3d_warmup_steps = args.kp3d_warmup_stepsif args.losses == "rebalanced": apply_rebalanced_losses(cfg)diff --git a/tools/pth_to_onnx.py b/tools/pth_to_onnx.pyindex c4bd018..c2a3a4d 100644--- a/tools/pth_to_onnx.py+++ b/tools/pth_to_onnx.py@@ -98,6 +98,13 @@ def main() -> None:ap.add_argument("--allow-missing", action="store_true",help="Export even if checkpoint weights are missing (NOT recommended).")ap.add_argument("--opset", type=int, default=17)+ ap.add_argument("--cliff-focal", dest="cliff_focal", action="store_true",+ default=None,+ help="Force the focal-aware CLIFF conditioning flag stamped "+ "into the ONNX metadata. Normally read from the "+ "run_config.json beside the checkpoint.")+ ap.add_argument("--no-cliff-focal", dest="cliff_focal", action="store_false",+ help="Force the pixel-normalised CLIFF conditioning flag.")args = ap.parse_args()if not args.ckpt.exists():@@ -113,7 +120,20 @@ def main() -> None:T = importlib.import_module(ARCH_MODULES[arch])print(f"Architecture: {arch} (from {ARCH_MODULES[arch]}.py)")- cfg = T.DistillConfig() # default architecture (matches training)+ # Restore the configuration the checkpoint was TRAINED with, not the+ # defaults. `--bound-scales` puts a tanh remap of the 77 body-size+ # parameters inside forward(); exporting without it leaves the head's raw+ # pre-tanh numbers to be read as bone scales, which is 21.0 mm MPJPE /+ # 14.4 mm PA-MPJPE of silent corruption. See T.config_from_checkpoint.+ if hasattr(T, "config_from_checkpoint"):+ cfg, prov = T.config_from_checkpoint(+ state, args.ckpt, cliff_focal=args.cliff_focal)+ else: # older training modules predate the helper+ cfg, prov = T.DistillConfig(), {}+ print(f" bound_scales : {getattr(cfg, 'bound_scales', False)} "+ f"({prov.get('bound_scales', 'default')})")+ print(f" cliff_focal : {getattr(cfg, 'cliff_focal', False)} "+ f"({prov.get('cliff_focal', 'default')})")# SimCC head geometry lives in the checkpoint — mirror it so the graph and# the bin centres agree with what was actually trained.@@ -129,7 +149,15 @@ def main() -> None:print(f"Loaded {args.ckpt.name} | epoch {ckpt.get('epoch', '?')} "f"| PA-MPJPE {ckpt.get('val_pa_mpjpe', '?')} | source {ckpt.get('source', '?')}")if unexpected:- print(f" unexpected keys: {len(unexpected)} -> {unexpected[:8]}")+ # Fatal, not a note. An unexpected key means the checkpoint carries+ # state this architecture has no slot for, i.e. the config above is+ # wrong -- exactly how `scale_lo`/`scale_hi` used to be dropped.+ sys.exit(+ f"\n[error] {len(unexpected)} key(s) in the checkpoint have no "+ f"home in the model built here:\n {unexpected[:8]}\n"+ f" The exported graph would silently differ from the "+ f"trained one. Fix the config, do not ignore this."+ )if missing:print(f" missing keys : {len(missing)} -> {missing[:8]}")if not args.allow_missing:@@ -170,6 +198,23 @@ def main() -> None:input_names=["image", "cliff_cond"], output_names=output_keys,dynamic_axes=dynamic_axes, opset_version=args.opset,)+ # Stamp which CLIFF conditioning this graph expects. The vector has the+ # same shape either way, so a consumer that guesses wrong gets no error --+ # only a person placed at the wrong depth. instanthmr.inference reads this.+ try:+ import onnx+ m = onnx.load(str(args.output))+ for k, v in (("cliff_focal", str(bool(getattr(cfg, "cliff_focal", False))).lower()),+ ("bound_scales", str(bool(getattr(cfg, "bound_scales", False))).lower()),+ ("arch", arch)):+ e = m.metadata_props.add()+ e.key, e.value = k, v+ onnx.save(m, str(args.output))+ print(f" metadata: cliff_focal={getattr(cfg, 'cliff_focal', False)} "+ f"bound_scales={getattr(cfg, 'bound_scales', False)} arch={arch}")+ except Exception as e: # noqa: BLE001+ print(f" [warning] could not stamp ONNX metadata: {e}")+print(f"\n✅ Wrote {args.output} ({args.output.stat().st_size / 1e6:.1f} MB)")# --- Sanity check: run once through onnxruntime and verify I/O ---@@ -183,6 +228,22 @@ def main() -> None:for o, v in zip(sess.get_outputs(), outs):v = np.asarray(v)print(f" {o.name:14s} {list(v.shape)} std={v.std():.4f}")++ # Parity against the configured PyTorch model on the SAME input. This+ # is the check that catches a config-level export defect: identical+ # weights, different forward. A dropped tanh remap shows up here as a+ # large mhr_params delta while every tensor keeps its right shape.+ with torch.no_grad():+ ref = deploy(dummy_img, dummy_cliff)+ worst = max(float(np.abs(np.asarray(o) - r.numpy()).max())+ for o, r in zip(outs, ref))+ print(f" torch<->onnx max abs diff: {worst:.3e}")+ if worst > 1e-3:+ sys.exit(+ f"\n[error] the ONNX graph disagrees with the PyTorch model it "+ f"was built from by {worst:.3e}.\n Identical weights, "+ f"different forward -- the exported configuration is wrong."+ )# A dead 2D head (wrong arch, weights left at init) predicts every joint# at the crop centre; real predictions spread over normalised [-1, 1].j2d = np.asarray(outs[output_keys.index("joints_2d")])