Python
v1.1: network + kinematic fit graphs (--fit 1|2), tuned pose filters, keypoint-tracked boxes, uint8 crops and CUDA graphs.
mohamdev5d7920145e9b
diff --git a/README.md b/README.mdindex a50ab48..89e05da 100644--- a/README.md+++ b/README.md@@ -9,6 +9,10 @@ InstantHMR recovers the 3D body of every person in an image: pose, body shape, 7and 3D, and a full body mesh in the [Momentum Human Rig](https://github.com/facebookresearch/MHR)(MHR). It runs in about 5 ms per person on a phone NPU and in about 1 ms on a desktop GPU.+**New in v1.1:** a kinematic fit inside the model graph refines each pose against the network's own+2D keypoints (`--fit`, on by default), and two pose filters for video (`--pose-filter`). See+[Kinematic fit](#kinematic-fit).+<p align="center"><img src="assets/demo_desktop.gif" height="300" alt="InstantHMR on a desktop GPU, shown in the Rerun viewer"><img src="assets/demo_phone.gif" height="300" alt="InstantHMR on a Samsung Galaxy S23">@@ -34,6 +38,27 @@ up to a 6,890-vertex mesh).(Harmony4D and part of COCO). The weights download automatically from[Hugging Face](https://huggingface.co/momolesang/InstantHMR) on first use.+### Kinematic fit++Every model also comes with a kinematic fit in the same graph. The network predicts the MHR pose+and, separately, the person's 2D keypoints; the 2D keypoints are about twice as accurate as the+projection of the 3D pose. The fit moves the pose (one Levenberg-Marquardt step through the MHR+skeleton, each keypoint weighted by its confidence) so that the projected body lands on those 2D+keypoints. It has no learned parameters and runs inside the graph in fp16, on the GPU or the phone+NPU. `--fit 1` runs it on one crop of each person (0.9 of the box); `--fit 2` (default) adds a+zoomed-in crop (0.7 of the box) in the same batch and fuses the 2D of both.++| Model | EMDB-1 (mm) | 3DPW (mm) | RTX 4070, TensorRT (ms) | Galaxy S23 NPU (ms) |+|---|---|---|---|---|+| `nano`, `--fit 0 / 1 / 2` | 61.7 / 57.2 / 55.9 | 46.6 / 44.5 / 44.1 | 0.70 / 0.85 / 1.10 | 4.60 / 5.49 / 8.73 |+| `tiny`, `--fit 0 / 1 / 2` | 58.0 / 53.8 / 52.6 | 44.0 / 42.4 / 42.0 | 0.73 / 0.87 / 1.13 | 4.84 / 5.84 / 9.20 |+| `small`, `--fit 0 / 1 / 2` | 53.3 / 49.2 / 48.1 | 41.7 / 40.3 / 40.0 | 0.84 / 1.00 / 1.30 | 5.38 / 6.37 / 10.36 |+| `medium`, `--fit 0 / 1 / 2` | 48.8 / 45.2 / 44.4 | 40.0 / 39.4 / 39.3 | 0.98 / 1.12 / 1.53 | 5.49 / 6.40 / 10.22 |+| `medium-commercial`, `--fit 0 / 1 / 2` | 72.2 / 68.8 / 68.3 | 50.7 / 47.7 / 47.5 | 0.98 / 1.12 / 1.53 | 5.49 / 6.40 / 10.22 |++The fit graphs take one person per call, and their crop scales assume the person box of the+benchmarks; the demo enlarges RF-DETR's tighter boxes to match (by 1/0.866, measured on 3DPW).+## InstallPython 3.10 to 3.12, and on Linux or Windows an NVIDIA driver 525 or newer.@@ -54,31 +79,35 @@ it.```bashpython demo.py --image photo.jpg-python demo.py --video clip.mp4 --smooth-python demo.py --camera 0+python demo.py --video clip.mp4 --pose-filter one-euro+python demo.py --camera 0 --model small --fit 1```The [Rerun](https://rerun.io) viewer opens with the frame and its 2D skeletons, the 3D scene, andthe latency of each stage. People are found by the [RF-DETR](https://github.com/roboflow/rf-detr)-detector, then InstantHMR runs on all of them in one batch.+detector, then InstantHMR runs on each of them.| Option | ||---|---|| `--model` | `nano`, `tiny`, `small`, `medium` (default), `medium-commercial`, or a path to an `.onnx` file |+| `--fit` | kinematic fit on `2` crops per person (default), `1` crop, or `0` for the network alone || `--device` | `cuda` (default), `tensorrt`, `cpu` or `coreml` |-| `--smooth` | temporal smoothing for videos and cameras (1 Euro filter, no visible lag) |+| `--pose-filter` | videos and cameras: `one-euro` or `alpha-beta` filters each person's pose before the mesh is built; both were tuned on 3DPW and EgoHumans, lower the error slightly and the jitter by a third, and lag less than half a frame |+| `--smooth` | videos and cameras: smooths the keypoints and mesh instead; steadier still, but it lags on fast motion || `--focal` | the camera's focal length in pixels, if you know it; it places people at the right depth || `--detector` | RF-DETR size: `nano`, `small`, `medium` (default), `base`, `large` || `--max-persons` | most people per frame (default 4) |+| `--detector-stride` | run the detector every N frames; in between, each person's box follows their 2D keypoints || `--no-mesh` | skeleton only || `--save-rrd` | also save the recording, to replay with `rerun file.rrd` |-The latencies in the table above are the model alone on the GPU, as measured in the paper. The-demo's timings are what a frame costs end to end in Python: on an RTX 4070 with TensorRT, the-InstantHMR stage takes about 5 ms per person, of which 1.8 ms cut and normalise the crop on the CPU,-1.3 ms run the network and 1.5 ms build the keypoints and the full 18,439-vertex mesh. The-detector is the slow stage (about 27 ms for RF-DETR medium); for a faster live demo, use-`--detector nano` or `--detector-stride 2`.+The latencies in the tables above are the model alone, as measured in the paper. The demo's timings+are what a frame costs end to end in Python. On an RTX 4070 with TensorRT, the InstantHMR stage takes+2.8 ms per person with `--fit 1` (0.25 ms to cut the crop on the CPU, 1.3 ms for the graph, 1.2 ms+for the keypoints and the full 18,439-vertex mesh) and 3.3 ms with `--fit 2`; with CUDA, 4.7 and+5.7 ms. The fit graphs are faster end to end than the network alone (3.3 ms with TensorRT), because+they take the crop as 8-bit pixels and run in fp16. The detector is the slow stage (about 27 ms for+RF-DETR medium); for a faster live demo, use `--detector nano` or `--detector-stride 3`.## Use it from Python@@ -86,7 +115,7 @@ detector is the slow stage (about 27 ms for RF-DETR medium); for a faster live dimport cv2from instanthmr import PosePipeline-pipeline = PosePipeline("medium", device="cuda")+pipeline = PosePipeline("medium", fit=2, device="cuda") # pose_filter="one-euro" for videoimage = cv2.cvtColor(cv2.imread("photo.jpg"), cv2.COLOR_BGR2RGB)for person in pipeline(image).persons:person.joints_2d # (70, 2) keypoints, pixels@@ -97,7 +126,7 @@ for person in pipeline(image).persons:```With your own person boxes, use `InstantHMR` directly:-`InstantHMR(resolve_model("medium")).predict(image, boxes)`. The 70 keypoints are listed in+`InstantHMR(resolve_model("medium", fit=2)).predict(image, boxes)`. The 70 keypoints are listed in`instanthmr.JOINT_NAMES`.## TensorRT@@ -110,11 +139,11 @@ pip install tensorrt-cu12==10.15.*python demo.py --camera 0 --device tensorrt```-The first run builds an engine for your GPU, about two minutes, and caches it in-`models/trt_cache/`; later runs start in under a second. The engine covers batches of up to-`--max-persons` people. On an RTX 4070, the `medium` network takes 1.2 ms per person with-TensorRT against 3.5 ms with CUDA; the MHR body (keypoints and mesh) runs on CUDA in 1.2 ms-either way.+The first run builds an engine for your GPU and caches it in `models/trt_cache/`: about two+minutes for a network graph (it covers batches of up to `--max-persons` people), and four to ten+minutes for a fit graph (one person per call, one engine per graph). Later runs start in under a+second. With CUDA, the fit graphs are replayed as a single CUDA graph, so they need no extra+installation to be fast.## Training and evaluation@@ -130,7 +159,7 @@ The code is under the [Apache-2.0](LICENSE) licence, except[`training/mhr_cont.py`](training/mhr_cont.py) and [`training/assets/`](training/assets/), whichare derived from SAM 3D Body and are under the [SAM License](LICENSE-SAM).-The weights, all five models and the shared `mhr-body.onnx`, are under the+The weights, all five models (with and without the fit) and the shared `mhr-body.onnx`, are under the[SAM License](LICENSE-SAM): they are trained on the SAM 3D Body annotations, which Meta releasesunder that licence, and they contain tables from the SAM 3D Body checkpoint. The SAM Licenseallows commercial use, under the conditions it lists (trade controls, no military use, amongdiff --git a/demo.py b/demo.pyindex 0b94ae4..1046745 100755--- a/demo.py+++ b/demo.py@@ -2,8 +2,8 @@"""InstantHMR demo: people in an image, a video or a live camera, shown in the Rerun viewer.python demo.py --image photo.jpg- python demo.py --video clip.mp4 --smooth- python demo.py --camera 0 --model small --device tensorrt+ python demo.py --video clip.mp4 --pose-filter one-euro+ python demo.py --camera 0 --model small --fit 1 --device tensorrt"""from __future__ import annotations@@ -14,7 +14,7 @@ import timeimport cv2import numpy as np-from instanthmr import DEFAULT_MODEL, MODELS, PosePipeline+from instanthmr import DEFAULT_FIT, DEFAULT_MODEL, MODELS, PosePipelinefrom instanthmr.smoothing import TemporalSmootherfrom instanthmr.visualizer import RerunVisualizer@@ -27,6 +27,9 @@ def parse_args() -> argparse.Namespace:src.add_argument("--camera", type=int, metavar="INDEX", help="live camera, e.g. 0")p.add_argument("--model", default=DEFAULT_MODEL,help=f"{', '.join(MODELS)}, or a path to an .onnx file (default: {DEFAULT_MODEL})")+ p.add_argument("--fit", type=int, default=DEFAULT_FIT, choices=(0, 1, 2),+ help="kinematic fit on 1 or 2 crops per person, 0 for the network alone (default: "+ f"{DEFAULT_FIT}; ignored for an .onnx path)")p.add_argument("--device", default="cuda", choices=("cuda", "tensorrt", "cpu", "coreml"))p.add_argument("--max-persons", type=int, default=4)p.add_argument("--detector", default="medium", choices=("nano", "small", "medium", "base", "large"),@@ -35,7 +38,10 @@ def parse_args() -> argparse.Namespace:p.add_argument("--detector-stride", type=int, default=1, metavar="N",help="run the detector every N frames and reuse its boxes in between")p.add_argument("--focal", type=float, help="camera focal length in pixels, if known")- p.add_argument("--smooth", action="store_true", help="temporal smoothing (1 Euro filter)")+ p.add_argument("--pose-filter", choices=("one-euro", "alpha-beta"),+ help="video: filter each person's pose across frames (more accurate and steadier)")+ p.add_argument("--smooth", action="store_true",+ help="video: smooth the keypoints and mesh instead (steadiest, but lags on fast motion)")p.add_argument("--no-mesh", action="store_true", help="show the skeleton only")p.add_argument("--mesh-alpha", type=float, default=0.35, help="mesh opacity (default: 0.35)")p.add_argument("--save-rrd", metavar="PATH", help="also save the Rerun recording")@@ -70,10 +76,11 @@ def frames(args):def main() -> None:args = parse_args()- print(f"loading InstantHMR ({args.model}) on {args.device} and RF-DETR {args.detector}...")- pipeline = PosePipeline(args.model, device=args.device, detector=args.detector,+ fit = f", kinematic fit on {args.fit} crop{'s' if args.fit > 1 else ''}" if args.fit else ""+ print(f"loading InstantHMR ({args.model}{fit}) on {args.device} and RF-DETR {args.detector}...")+ pipeline = PosePipeline(args.model, fit=args.fit, device=args.device, detector=args.detector,det_confidence=args.det_confidence, max_persons=args.max_persons,- detector_stride=args.detector_stride, focal=args.focal)+ detector_stride=args.detector_stride, focal=args.focal, pose_filter=args.pose_filter)print(f"InstantHMR runs on {pipeline.hmr.provider}")viewer = RerunVisualizer(None if args.no_mesh else pipeline.hmr.faces, args.mesh_alpha,spawn=not args.no_viewer, save_path=args.save_rrd)@@ -82,7 +89,7 @@ def main() -> None:history = []try:for i, t, rgb in frames(args):- result = pipeline(rgb)+ result = pipeline(rgb, t)persons = smoother(result.persons, t) if smoother else result.personstimings = {"detector": result.detector_ms, "InstantHMR": result.hmr_ms}viewer.log(i, rgb, persons, timings)diff --git a/instanthmr/__init__.py b/instanthmr/__init__.pyindex 4cb11df..7824ca1 100644--- a/instanthmr/__init__.py+++ b/instanthmr/__init__.py@@ -1,9 +1,9 @@"""InstantHMR: real-time 3D human mesh recovery from a single image."""from .inference import HMRPrediction, InstantHMR-from .models import DEFAULT_MODEL, MODELS, resolve_model+from .models import DEFAULT_FIT, DEFAULT_MODEL, MODELS, resolve_modelfrom .pipeline import FrameResult, PosePipelinefrom .skeleton import JOINT_NAMES, SKELETON_EDGES-__all__ = ["InstantHMR", "HMRPrediction", "PosePipeline", "FrameResult", "MODELS", "DEFAULT_MODEL",+__all__ = ["InstantHMR", "HMRPrediction", "PosePipeline", "FrameResult", "MODELS", "DEFAULT_MODEL", "DEFAULT_FIT","resolve_model", "JOINT_NAMES", "SKELETON_EDGES"]-__version__ = "1.0.0"+__version__ = "1.1.0"diff --git a/instanthmr/inference.py b/instanthmr/inference.pyindex 673096f..415b6a1 100644--- a/instanthmr/inference.py+++ b/instanthmr/inference.py@@ -16,6 +16,9 @@ CROP_EXPAND = 1.2# Focal used when the camera is not calibrated, as a multiple of the image diagonal# (about 50 degrees of horizontal field of view on a 16:9 frame).FOCAL_FALLBACK_DIAG = 1.05+# The kinematic-fit graphs' crop scales (0.9 and 0.7 of the box) were chosen on ground-truth person boxes; RF-DETR's+# boxes are tighter (median long side 0.866 of the ground-truth box), so they are enlarged by this factor first.+DETECTOR_TO_GT_BOX = 1 / 0.866DEVICES = ("cuda", "tensorrt", "cpu", "coreml")@@ -73,16 +76,18 @@ def providers_for(device: str, max_batch: int = 1, image_size: int = 288,class InstantHMR:- """An exported InstantHMR network and the MHR body graph that turns its output into 3D.-- `device` runs the network ("cuda", "tensorrt", "cpu" or "coreml"); the body graph runs on- CUDA when the network does, else on the CPU. `focal` is the camera focal length in pixels- when it is known; otherwise 1.05 x the image diagonal is assumed. `max_batch` is the most- people predicted in one call (TensorRT builds its engine for batches up to it).+ """An exported InstantHMR graph and the MHR body graph that turns its output into 3D.++ The graph is either a network (`instanthmr-<size>.onnx`) or a network + kinematic fit+ (`instanthmr-<size>-fit<1|2>.onnx`, read from its metadata), which refines the pose on 1 or 2 crops per+ person. `device` runs it ("cuda", "tensorrt", "cpu" or "coreml"); the body graph runs on CUDA when the+ graph does, else on the CPU. `focal` is the camera focal length in pixels when it is known; otherwise+ 1.05 x the image diagonal is assumed. `max_batch` is the most people predicted in one call. `pose_filter`+ (smoothing.PoseFilter) filters each person's pose across frames before the mesh is built."""def __init__(self, model_path: str | Path, body_path: str | Path | None = None, device: str = "cuda",- focal: float | None = None, max_batch: int = 4):+ focal: float | None = None, max_batch: int = 4, pose_filter=None):import onnxruntime as ortfrom .models import resolve_body@@ -96,19 +101,25 @@ class InstantHMR:options.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_ALLoptions.log_severity_level = 3- size = 288- if device == "tensorrt": # the engine profile needs the crop size before the session exists- probe = ort.InferenceSession(str(model_path), providers=["CPUExecutionProvider"])- size = int(probe.get_modelmeta().custom_metadata_map.get("image_size", size))- del probe- self.network = ort.InferenceSession(str(model_path), sess_options=options,- providers=providers_for(device, max_batch, size))- self.provider = self.network.get_providers()[0]- meta = self.network.get_modelmeta().custom_metadata_map- self.input_size = int(meta.get("image_size", size))+ probe = ort.InferenceSession(str(model_path), providers=["CPUExecutionProvider"])+ meta = probe.get_modelmeta().custom_metadata_map+ self.input_size = int(meta.get("image_size", 288))self.cliff_focal = meta.get("cliff_focal", "true") == "true"+ self.n_crops = int(meta.get("crops", 0)) # 0: a network graph; 1 or 2: network + kinematic fit+ self.scales = tuple(float(v) for v in meta["crop_scales"].split(",")) if self.n_crops else (1.0,)+ del probe+ if self.n_crops:+ providers = _fit_providers(device, Path(model_path).stem)+ else:+ providers = providers_for(device, max_batch, self.input_size)+ self.network = ort.InferenceSession(str(model_path), sess_options=options, providers=providers)+ self.provider = self.network.get_providers()[0]self.focal = focalself.max_batch = max_batch+ self.pose_filter = pose_filter+ self._binding = None+ if self.n_crops and self.provider == "CUDAExecutionProvider":+ self._bind_cuda_graph(ort)body_path = Path(body_path) if body_path else resolve_body(Path(model_path))self.body = ort.InferenceSession(str(body_path), sess_options=options,@@ -123,61 +134,118 @@ class InstantHMR:return (FOCAL_FALLBACK_DIAG if self.cliff_focal else 1.0) * math.hypot(h, w)def predict(self, image_rgb: np.ndarray, bboxes: Sequence, confidences: Sequence[float] | None = None,- focal: float | None = None) -> list[HMRPrediction]:- """All people of one frame in a single call. `bboxes` are tight person boxes, x1 y1 x2 y2."""+ focal: float | None = None, timestamp: float | None = None) -> list[HMRPrediction]:+ """All people of one frame. `bboxes` are tight person boxes (as a detector gives them), x1 y1 x2 y2;+ `timestamp` (seconds) is only read by the pose filter."""if len(bboxes) == 0:return []h, w = image_rgb.shape[:2]f = self.focal_px(h, w, focal)- crops, cliffs, squares = zip(*(self._preprocess(image_rgb, np.asarray(b, np.float32), f) for b in bboxes))- crops, cliffs = np.stack(crops), np.stack(cliffs)- chunks = [self._run(crops[i:i + self.max_batch], cliffs[i:i + self.max_batch])- for i in range(0, len(crops), self.max_batch)]- outs = {k: np.concatenate([c[k] for c in chunks]) for k in chunks[0]}- confidences = confidences if confidences is not None else [1.0] * len(bboxes)-- results = []- for i, (x0, y0, side) in enumerate(squares):- j2d = (outs["joints_2d"][i] + 1.0) * 0.5 * side + np.array([x0, y0], np.float32)- results.append(HMRPrediction(- bbox=np.asarray(bboxes[i], np.float32), confidence=float(confidences[i]),- joints_2d=j2d.astype(np.float32), joints_3d_local=outs["joints_3d"][i],- cam_trans=outs["cam_trans"][i], mhr_params=outs["mhr_params"][i],- shape_params=outs["shape_params"][i], focal_length=f, image_shape=(h, w),- vertices_local=outs["vertices"][i]))- return results-- def _run(self, crops: np.ndarray, cliffs: np.ndarray) -> dict[str, np.ndarray]:+ boxes = [np.asarray(b, np.float32) for b in bboxes]+ outs = self._estimate_fit(image_rgb, boxes, f) if self.n_crops else self._estimate(image_rgb, boxes, f)+ if self.pose_filter is not None:+ outs["mhr_params"] = self.pose_filter(boxes, outs["mhr_params"], timestamp)+ joints_3d, vertices = self.body.run(["joints_3d", "vertices"], {"mhr_params": outs["mhr_params"],+ "shape_params": outs["shape_params"]})+ confidences = confidences if confidences is not None else [1.0] * len(boxes)+ return [HMRPrediction(bbox=boxes[i], confidence=float(confidences[i]), joints_2d=outs["joints_2d"][i],+ joints_3d_local=joints_3d[i], cam_trans=outs["cam_trans"][i],+ mhr_params=outs["mhr_params"][i], shape_params=outs["shape_params"][i],+ focal_length=f, image_shape=(h, w), vertices_local=vertices[i])+ for i in range(len(boxes))]++ def _estimate(self, image_rgb, boxes, f) -> dict[str, np.ndarray]:+ """The network graph: one crop per person, batches of up to `max_batch`; 2D in pixels."""names = ["mhr_params", "shape_params", "cam_trans", "joints_2d"]- outs = dict(zip(names, self.network.run(names, {"image": crops, "cliff_cond": cliffs})))- outs.update(zip(["joints_3d", "vertices"], self.body.run(- ["joints_3d", "vertices"], {"mhr_params": outs["mhr_params"], "shape_params": outs["shape_params"]})))+ crops, cliffs, squares = zip(*(self._crop(image_rgb, b, 1.0, f) for b in boxes))+ crops = np.stack([_normalise(c) for c in crops])+ cliffs = np.stack(cliffs)+ chunks = [self.network.run(names, {"image": crops[i:i + self.max_batch], "cliff_cond": cliffs[i:i + self.max_batch]})+ for i in range(0, len(crops), self.max_batch)]+ outs = {k: np.concatenate([c[j] for c in chunks]) for j, k in enumerate(names)}+ sq = np.asarray(squares, np.float32) # (P, 4) x1, y1, w, h+ outs["joints_2d"] = (outs["joints_2d"] + 1.0) * 0.5 * sq[:, None, 2:] + sq[:, None, :2]return outs+ def _estimate_fit(self, image_rgb, boxes, f) -> dict[str, np.ndarray]:+ """The network + fit graph: one call per person on its 1 or 2 crops; 2D in pixels."""+ h, w = image_rgb.shape[:2]+ cam = np.array([[f, w / 2.0, h / 2.0]], np.float32)+ per_person = []+ for b in boxes:+ c, half = (b[:2] + b[2:]) / 2, (b[2:] - b[:2]) * DETECTOR_TO_GT_BOX / 2+ gt_box = np.concatenate([c - half, c + half])+ crops, cliffs, squares = zip(*(self._crop(image_rgb, gt_box, s, f) for s in self.scales))+ per_person.append(self._run_fit({"image": np.stack(crops), "cliff_cond": np.stack(cliffs),+ "crop_box": np.asarray(squares, np.float32), "cam": cam}))+ return {k: np.concatenate([o[k] for o in per_person]) for k in per_person[0]}++ def _run_fit(self, feeds: dict) -> dict[str, np.ndarray]:+ names = ["mhr_params", "shape_params", "cam_trans", "joints_2d"]+ if self._binding is None:+ return dict(zip(names, self.network.run(names, feeds)))+ for k, v in feeds.items():+ self._inputs[k].update_inplace(np.ascontiguousarray(v))+ self.network.run_with_iobinding(self._binding)+ return dict(zip(names, (o.numpy() for o in self._binding.get_outputs())))++ def _bind_cuda_graph(self, ort) -> None:+ """ORT CUDA: fixed device buffers for every input and output, so the first run is captured as one CUDA+ graph and every later run replays it."""+ n, s = self.n_crops, self.input_size+ shapes = {"image": ((n, s, s, 3), np.uint8), "cliff_cond": ((n, 3), np.float32),+ "crop_box": ((n, 4), np.float32), "cam": ((1, 3), np.float32)}+ self._inputs = {k: ort.OrtValue.ortvalue_from_numpy(np.zeros(*v), "cuda", 0) for k, v in shapes.items()}+ self._binding = self.network.io_binding()+ for k, v in self._inputs.items():+ self._binding.bind_ortvalue_input(k, v)+ for k in ("mhr_params", "shape_params", "cam_trans", "joints_2d"):+ self._binding.bind_output(k, "cuda", 0)+def warmup(self, max_batch: int = 1) -> None:- for n in sorted({1, max_batch}):- self.network.run(None, {"image": np.zeros((n, 3, self.input_size, self.input_size), np.float32),- "cliff_cond": np.zeros((n, 3), np.float32)})- self.body.run(None, {"mhr_params": np.zeros((n, 204), np.float32),- "shape_params": np.zeros((n, 45), np.float32)})-- def _preprocess(self, image_rgb: np.ndarray, bbox: np.ndarray, focal: float):- """The square 1.2x crop the model was trained on, and its CLIFF conditioning vector."""+ image, pose_filter, self.pose_filter = np.zeros((480, 640, 3), np.uint8), self.pose_filter, None+ try:+ for n in sorted({1, max_batch}):+ self.predict(image, [[200, 100, 400, 450]] * n)+ finally:+ self.pose_filter = pose_filter++ def _crop(self, image_rgb: np.ndarray, bbox: np.ndarray, scale: float, focal: float):+ """The square 1.2x crop of the box scaled by `scale` about its centre, as uint8, cut and resized by one+ affine warp (the same sampling as cropping then resizing); its CLIFF vector and pixel square."""h, w = image_rgb.shape[:2]x1, y1, x2, y2 = bbox.astype(np.float64)- cx, cy, size = (x1 + x2) / 2, (y1 + y2) / 2, max(x2 - x1, y2 - y1)+ cx, cy, size = (x1 + x2) / 2, (y1 + y2) / 2, max(x2 - x1, y2 - y1) * scaleif self.cliff_focal:cliff = [math.atan((cx - w / 2) / focal), math.atan((cy - h / 2) / focal), size / focal]else:cliff = [2 * cx / w - 1, 2 * cy / h - 1, size / max(w, h)]-side = size * CROP_EXPAND- sx, sy = cx - side / 2, cy - side / 2- ix1, iy1 = math.floor(sx), math.floor(sy)- ix2, iy2 = math.ceil(sx + side), math.ceil(sy + side)- patch = image_rgb[max(0, iy1):min(h, iy2), max(0, ix1):min(w, ix2)]- patch = cv2.copyMakeBorder(patch, max(0, -iy1), max(0, iy2 - h), max(0, -ix1), max(0, ix2 - w),- cv2.BORDER_CONSTANT, value=(0, 0, 0))- crop = cv2.resize(patch, (self.input_size, self.input_size), interpolation=cv2.INTER_LINEAR)- crop = ((crop.astype(np.float32) / 255.0 - IMAGENET_MEAN) / IMAGENET_STD).transpose(2, 0, 1)- return np.ascontiguousarray(crop), np.asarray(cliff, np.float32), (float(sx), float(sy), float(side))+ ix1, iy1 = math.floor(cx - side / 2), math.floor(cy - side / 2)+ ix2, iy2 = math.ceil(cx - side / 2 + side), math.ceil(cy - side / 2 + side)+ s = self.input_size+ sx, sy = (ix2 - ix1) / s, (iy2 - iy1) / s+ m = np.array([[sx, 0, ix1 + 0.5 * sx - 0.5], [0, sy, iy1 + 0.5 * sy - 0.5]], np.float64)+ crop = cv2.warpAffine(image_rgb, m, (s, s), flags=cv2.INTER_LINEAR | cv2.WARP_INVERSE_MAP,+ borderMode=cv2.BORDER_CONSTANT, borderValue=(0, 0, 0))+ return crop, np.asarray(cliff, np.float32), (float(ix1), float(iy1), float(ix2 - ix1), float(iy2 - iy1))+++def _normalise(crop: np.ndarray) -> np.ndarray:+ """uint8 HWC -> ImageNet-normalised float32 CHW, the network graphs' input."""+ return np.ascontiguousarray(((crop.astype(np.float32) / 255.0 - IMAGENET_MEAN) / IMAGENET_STD).transpose(2, 0, 1))+++def _fit_providers(device: str, name: str, cache_dir: str | Path = "models/trt_cache") -> list:+ """Providers for a fit graph (fixed shapes): TensorRT in fp16 with a cached engine, or ORT CUDA with CUDA graphs."""+ if device == "tensorrt":+ providers = providers_for(device) # checks the installation+ cache = Path(cache_dir) / name+ cache.mkdir(parents=True, exist_ok=True)+ return [("TensorrtExecutionProvider", {"trt_fp16_enable": True, "trt_engine_cache_enable": True,+ "trt_engine_cache_path": str(cache), "trt_timing_cache_enable": True,+ "trt_timing_cache_path": str(cache)}), *providers[1:]]+ if device == "cuda":+ providers_for(device)+ return [("CUDAExecutionProvider", {"enable_cuda_graph": "1"}), "CPUExecutionProvider"]+ return providers_for(device)diff --git a/instanthmr/models.py b/instanthmr/models.pyindex 95bccb3..c5c7635 100644--- a/instanthmr/models.py+++ b/instanthmr/models.py@@ -13,6 +13,7 @@ MODELS = {"medium-commercial": "instanthmr-medium-commercial.onnx",}DEFAULT_MODEL = "medium"+DEFAULT_FIT = 2BODY = "mhr-body.onnx"@@ -22,8 +23,9 @@ def _download(filename: str) -> Path:return Path(hf_hub_download(REPO_ID, filename))-def resolve_model(model: str | Path) -> Path:- """A local `.onnx` path, or a model name downloaded once into the Hugging Face cache."""+def resolve_model(model: str | Path, fit: int = 0) -> Path:+ """A local `.onnx` path, or a model name downloaded once into the Hugging Face cache. `fit` (1 or 2) picks+ that model's graph with the kinematic fit on 1 or 2 crops per person; 0 the network alone."""path = Path(model)if path.suffix == ".onnx":if not path.exists():@@ -31,7 +33,10 @@ def resolve_model(model: str | Path) -> Path:return pathif str(model) not in MODELS:raise ValueError(f"unknown model {model!r}: choose one of {', '.join(MODELS)} or pass an .onnx path")- return _download(MODELS[str(model)])+ if fit not in (0, 1, 2):+ raise ValueError(f"fit must be 0, 1 or 2, got {fit}")+ name = MODELS[str(model)]+ return _download(name.replace(".onnx", f"-fit{fit}.onnx") if fit else name)def resolve_body(model_path: Path) -> Path:diff --git a/instanthmr/pipeline.py b/instanthmr/pipeline.pyindex f2775a0..08c2ed3 100644--- a/instanthmr/pipeline.py+++ b/instanthmr/pipeline.py@@ -8,8 +8,11 @@ from pathlib import Pathimport numpy as npfrom .detector import PersonDetector-from .inference import HMRPrediction, InstantHMR-from .models import DEFAULT_MODEL, resolve_model+from .inference import DETECTOR_TO_GT_BOX, HMRPrediction, InstantHMR+from .models import DEFAULT_FIT, DEFAULT_MODEL, resolve_model+from .smoothing import PoseFilter++BODY_KEYPOINTS = list(range(21)) + [41, 62] + list(range(63, 70))@dataclass@@ -19,17 +22,30 @@ class FrameResult:hmr_ms: float+def keypoint_box(joints_2d: np.ndarray, w: int, h: int, pad: float = 0.15) -> np.ndarray:+ """A detector-like box from a person's 2D keypoints: their extent padded by `pad` of its size per side (the+ ground-truth box convention: on 3DPW the box's long side is 1.30x the keypoints' extent), shrunk to a+ detector's tighter framing, clipped to the frame."""+ k = joints_2d[BODY_KEYPOINTS]+ c, half = (k.min(0) + k.max(0)) / 2, (k.max(0) - k.min(0)) * (0.5 + pad) / DETECTOR_TO_GT_BOX+ return np.array([max(0.0, c[0] - half[0]), max(0.0, c[1] - half[1]),+ min(float(w), c[0] + half[0]), min(float(h), c[1] + half[1])], np.float32)++class PosePipeline:- """RF-DETR, then InstantHMR on every detected person in one batched call.+ """RF-DETR, then InstantHMR on every detected person.- `model` is a released model name (nano, tiny, small, medium, medium-commercial) or an .onnx- path. `detector_stride` > 1 runs the detector every N frames and reuses its boxes in between.+ `model` is a released model name (nano, tiny, small, medium, medium-commercial) or an .onnx path; `fit` picks+ the network + kinematic-fit graph on 1 or 2 crops per person (0: the network alone). `detector_stride` > 1+ runs the detector every N frames; in between, each person's box follows its 2D keypoints of the previous+ frame. `pose_filter` ("one-euro" or "alpha-beta") filters each person's pose across frames."""- def __init__(self, model: str | Path = DEFAULT_MODEL, device: str = "cuda", detector: str = "medium",- det_confidence: float = 0.5, max_persons: int = 4, detector_stride: int = 1,- focal: float | None = None):- self.hmr = InstantHMR(resolve_model(model), device=device, focal=focal, max_batch=max_persons)+ def __init__(self, model: str | Path = DEFAULT_MODEL, fit: int = DEFAULT_FIT, device: str = "cuda",+ detector: str = "medium", det_confidence: float = 0.5, max_persons: int = 4,+ detector_stride: int = 1, focal: float | None = None, pose_filter: str | None = None):+ self.hmr = InstantHMR(resolve_model(model, fit), device=device, focal=focal, max_batch=max_persons,+ pose_filter=PoseFilter(pose_filter) if pose_filter else None)self.detector = PersonDetector(detector, det_confidence, max_persons)self.detector_stride = max(1, detector_stride)self._frame = 0@@ -38,12 +54,14 @@ class PosePipeline:self.detector(np.zeros((288, 288, 3), np.uint8))self.hmr.warmup(max_persons)- def __call__(self, image_rgb: np.ndarray) -> FrameResult:+ def __call__(self, image_rgb: np.ndarray, timestamp: float | None = None) -> FrameResult:t0 = time.perf_counter()if self._frame % self.detector_stride == 0:self._boxes, self._scores = self.detector(image_rgb)t1 = time.perf_counter()- persons = self.hmr.predict(image_rgb, self._boxes, self._scores)+ persons = self.hmr.predict(image_rgb, self._boxes, self._scores, timestamp=timestamp)t2 = time.perf_counter()+ h, w = image_rgb.shape[:2]+ self._boxes = np.array([keypoint_box(p.joints_2d, w, h) for p in persons], np.float32).reshape(-1, 4)self._frame += 1return FrameResult(persons, (t1 - t0) * 1000, (t2 - t1) * 1000)diff --git a/instanthmr/smoothing.py b/instanthmr/smoothing.pyindex 581f913..0c0d8fe 100644--- a/instanthmr/smoothing.py+++ b/instanthmr/smoothing.py@@ -1,9 +1,13 @@-"""Temporal smoothing of per-person predictions with the 1 Euro filter.+"""Temporal filters for video, all causal (they work on a live camera). People are matched across frames by box+overlap.-InstantHMR estimates every frame on its own, so a video shows per-frame jitter. The 1 Euro filter-(Casiez, Roussel and Vogel, CHI 2012) smooths each coordinate with a cutoff that rises with its-own speed: still joints are smoothed hard and fast ones barely, so it adds no visible lag. It is-causal, so it works on a live camera. People are matched across frames by box overlap.+`PoseFilter` filters the MHR pose (root rotation and body angles) before the mesh is built, so the mesh, the 3D+keypoints and the pose stay consistent. Its two settings were tuned on 3DPW validation and 56 EgoHumans takes and+checked on EMDB-1 and 3DPW: both lower PA-MPJPE by 0.1-0.3 mm and the jitter by about 27 % (`alpha-beta`) or 35 %+(`one-euro`), with under half a frame of lag.++`TemporalSmoother` smooths the outputs themselves (keypoints, mesh, translation) with the 1 Euro filter (Casiez,+Roussel and Vogel, CHI 2012): smoother still, at the cost of some accuracy and visible lag on fast motion."""from __future__ import annotations@@ -21,16 +25,23 @@ FIELDS = {"vertices_local": (1.0, 4.0),"cam_trans": (0.6, 2.0),}+POSE = slice(3, 68) # MHR parameters: root rotation (3:6) and the body angles (6:68), in radians+++def _wrap(a: np.ndarray) -> np.ndarray:+ return (a + np.pi) % (2 * np.pi) - np.pi+++def _alpha(cutoff, dt):+ return 1.0 / (1.0 + 1.0 / (2 * np.pi * np.maximum(cutoff, 1e-6) * dt))class _OneEuro:- def __init__(self, mincutoff: float, beta: float, dcutoff: float = 1.0):- self.mincutoff, self.beta, self.dcutoff = mincutoff, beta, dcutoff- self.x = self.dx = self.t = None+ """1 Euro filter; `angles` wraps each residual to (-pi, pi], so an angle crossing +/-pi is not a 2 pi jump."""- @staticmethod- def _alpha(cutoff, dt):- return 1.0 / (1.0 + 1.0 / (2 * np.pi * np.maximum(cutoff, 1e-6) * dt))+ def __init__(self, mincutoff: float, beta: float, dcutoff: float = 1.0, angles: bool = False):+ self.mincutoff, self.beta, self.dcutoff, self.angles = mincutoff, beta, dcutoff, angles+ self.x = self.dx = self.t = Nonedef __call__(self, x: np.ndarray, t: float) -> np.ndarray:if self.x is None:@@ -38,13 +49,39 @@ class _OneEuro:return xdt = t - self.t if t > self.t else 1 / 30self.t = t- a_d = self._alpha(self.dcutoff, dt)- self.dx = a_d * (x - self.x) / dt + (1 - a_d) * self.dx- a = self._alpha(self.mincutoff + self.beta * np.abs(self.dx), dt)- self.x = a * x + (1 - a) * self.x+ r = x - self.x+ if self.angles:+ r = _wrap(r)+ a_d = _alpha(self.dcutoff, dt)+ self.dx = a_d * r / dt + (1 - a_d) * self.dx+ self.x = self.x + _alpha(self.mincutoff + self.beta * np.abs(self.dx), dt) * rreturn self.x.astype(np.float32)+class _AlphaBeta:+ """Constant-velocity filter on angles, one step per frame: predict x + v, correct by `a` and `b` times the+ wrapped residual."""++ def __init__(self, a: float, b: float):+ self.a, self.b = a, b+ self.x = self.v = None++ def __call__(self, x: np.ndarray, t: float) -> np.ndarray:+ if self.x is None:+ self.x, self.v = x.astype(np.float64), np.zeros(x.shape)+ return x+ pred = self.x + self.v+ r = _wrap(x - pred)+ self.x, self.v = pred + self.a * r, self.v + self.b * r+ return self.x.astype(np.float32)+++POSE_FILTERS = {+ "one-euro": lambda: _OneEuro(mincutoff=12.0, beta=0.5, dcutoff=1.0, angles=True),+ "alpha-beta": lambda: _AlphaBeta(a=0.8, b=0.005),+}++def _iou(a: np.ndarray, b: np.ndarray) -> float:iw = max(0.0, min(a[2], b[2]) - max(a[0], b[0]))ih = max(0.0, min(a[3], b[3]) - max(a[1], b[1]))@@ -53,49 +90,80 @@ def _iou(a: np.ndarray, b: np.ndarray) -> float:return float(inter / union) if union > 0 else 0.0+class _Tracks:+ """Matches boxes to the previous frame's by overlap; a track survives `max_age` frames without a match."""++ def __init__(self, iou_threshold: float = 0.3, max_age: int = 5):+ self.iou_threshold, self.max_age = iou_threshold, max_age+ self.tracks: dict[int, dict] = {}+ self._next_id = 0++ def assign(self, boxes: Sequence[np.ndarray]) -> list[dict]:+ """The state dict of each box's track (new tracks start empty)."""+ pairs = sorted(((_iou(b, tr["box"]), i, t) for i, b in enumerate(boxes)+ for t, tr in self.tracks.items()), reverse=True)+ ids, used = [-1] * len(boxes), set()+ for score, i, t in pairs:+ if score >= self.iou_threshold and ids[i] == -1 and t not in used:+ ids[i] = t+ used.add(t)+ for i, b in enumerate(boxes):+ if ids[i] == -1:+ ids[i] = self._next_id+ self.tracks[ids[i]] = {"filters": {}}+ self._next_id += 1+ self.tracks[ids[i]].update(box=np.asarray(b), age=0)+ for t in set(self.tracks) - set(ids):+ self.tracks[t]["age"] += 1+ if self.tracks[t]["age"] > self.max_age:+ del self.tracks[t]+ return [self.tracks[t] for t in ids]+++class PoseFilter:+ """`pose_filter(boxes, mhr_params, timestamp)` returns the parameters with the pose filtered per person.++ `kind` is "one-euro" or "alpha-beta". `timestamp` is in seconds; without one, frames are taken 1/30 s apart.+ """++ def __init__(self, kind: str = "one-euro"):+ if kind not in POSE_FILTERS:+ raise ValueError(f"unknown pose filter {kind!r}: choose one of {', '.join(POSE_FILTERS)}")+ self.kind = kind+ self._tracks = _Tracks()+ self._clock = 0.0++ def __call__(self, boxes: Sequence[np.ndarray], mhr_params: np.ndarray, timestamp: float | None = None) -> np.ndarray:+ if timestamp is None:+ self._clock += 1 / 30+ timestamp = self._clock+ out = np.array(mhr_params, np.float32, copy=True)+ for i, track in enumerate(self._tracks.assign(boxes)):+ f = track["filters"].setdefault("pose", POSE_FILTERS[self.kind]())+ out[i, POSE] = f(out[i, POSE], timestamp)+ return out++class TemporalSmoother:"""`smoother(persons, timestamp)` returns the same people with smoothed fields.`beta_scale` trades jitter for lag: raise it if fast motion lags, lower it if a still person- shakes. A track survives `max_age` frames without a match before its filter is reset.+ shakes."""def __init__(self, beta_scale: float = 1.0, iou_threshold: float = 0.3, max_age: int = 5):- self.beta_scale, self.iou_threshold, self.max_age = beta_scale, iou_threshold, max_age- self._tracks: dict[int, dict] = {}- self._next_id = 0+ self.beta_scale = beta_scale+ self._tracks = _Tracks(iou_threshold, max_age)def __call__(self, persons: Sequence[HMRPrediction], timestamp: float) -> list[HMRPrediction]:- ids = self._assign(persons)out = []- for track_id, person in zip(ids, persons):- filters = self._tracks[track_id]["filters"]+ for track, person in zip(self._tracks.assign([p.bbox for p in persons]), persons):fields = {}for name, (mincutoff, beta) in FIELDS.items():value = getattr(person, name)if value is None:continue- f = filters.setdefault(name, _OneEuro(mincutoff, beta * self.beta_scale))+ f = track["filters"].setdefault(name, _OneEuro(mincutoff, beta * self.beta_scale))fields[name] = f(value, timestamp)out.append(replace(person, **fields))return out-- def _assign(self, persons: Sequence[HMRPrediction]) -> list[int]:- pairs = sorted(((_iou(p.bbox, tr["box"]), i, t) for i, p in enumerate(persons)- for t, tr in self._tracks.items()), reverse=True)- ids, used = [-1] * len(persons), set()- for score, i, t in pairs:- if score >= self.iou_threshold and ids[i] == -1 and t not in used:- ids[i] = t- used.add(t)- for i, p in enumerate(persons):- if ids[i] == -1:- ids[i] = self._next_id- self._tracks[ids[i]] = {"filters": {}}- self._next_id += 1- self._tracks[ids[i]].update(box=p.bbox, age=0)- for t in set(self._tracks) - set(ids):- self._tracks[t]["age"] += 1- if self._tracks[t]["age"] > self.max_age:- del self._tracks[t]- return idsdiff --git a/tools/export_onnx.py b/tools/export_onnx.pyindex 0e169c9..b379501 100644--- a/tools/export_onnx.py+++ b/tools/export_onnx.py@@ -6,12 +6,18 @@ network (--ckpt): image (B, 3, S, S) ImageNet-normalised RGB crop, cliff_cond (joints_2d (B, 70, 2) in [-1, 1] over the cropbody (--body): mhr_params, shape_params -> joints_3d (B, 70, 3), vertices (B, 18439, 3),metres, body-centred (add cam_trans for camera space)+fit (--ckpt --fit 1|2): one person, the network on 1 crop (0.9 of the box) or 2 crops (0.9 and 0.7, batched),+ then the MHR kinematic fit (training/kinematic_fit.py), in fp16:+ image (N, S, S, 3) uint8 RGB crops, cliff_cond (N, 3), crop_box (N, 4) each crop's pixel square+ (x1, y1, w, h) in the frame, cam (1, 3) = (focal, cx, cy) in pixels+ -> mhr_params (1, 204), shape_params (1, 45), cam_trans (1, 3), joints_2d (1, 70, 2) in pixelsThe network graph stores its crop size and conditioning form in the model metadata, the bodygraph its mesh faces, so instanthmr.InstantHMR configures itself from the files.python tools/export_onnx.py --ckpt runs/medium/best_student_model_v3.pth --output models/instanthmr-medium.onnxpython tools/export_onnx.py --body --output models/mhr-body.onnx+ python tools/export_onnx.py --ckpt runs/medium/best_student_model_v3.pth --fit 2 --output models/instanthmr-medium-fit2.onnx"""import argparseimport base64@@ -27,6 +33,7 @@ REPO = Path(__file__).resolve().parent.parentsys.path.insert(0, str(REPO / "training"))import train as T # noqa: E402+from kinematic_fit import FitHead, MHRKinematics # noqa: E402from mhr_body import MHRBody # noqa: E402NETWORK_OUTPUTS = ["mhr_params", "shape_params", "cam_trans", "joints_2d"]@@ -79,12 +86,113 @@ def export(module, inputs: dict, outputs: list, path: Path, metadata: dict) -> Nsys.exit("[error] the ONNX graph disagrees with the PyTorch model")+class FitNetwork(torch.nn.Module):+ """Network + kinematic fit for one person, in ``dtype``; uint8 crops in, float32 out."""++ def __init__(self, net, kin, n_crops, dtype):+ super().__init__()+ self.net, self.dtype = net, dtype+ self.head = FitHead(kin, net.kp2d_bin_centers, n_crops)+ self.register_buffer("mean", torch.tensor([0.485, 0.456, 0.406]).view(1, 3, 1, 1) * 255.0)+ self.register_buffer("istd", 1.0 / (torch.tensor([0.229, 0.224, 0.225]).view(1, 3, 1, 1) * 255.0))++ def forward(self, image, cliff_cond, crop_box, cam):+ x = (image.float().permute(0, 3, 1, 2) - self.mean) * self.istd # cast first: TensorRT has no uint8 tensors+ out = self.net(x.to(self.dtype), cliff_cond.to(self.dtype))+ mp, t, fused, _, _ = self.head(out["mhr_params"], out["cam_trans"], out["joints_2d_logits"],+ crop_box.to(self.dtype), cam.to(self.dtype))+ joints_2d = crop_box[:1, None, :2] + 0.5 * crop_box[:1, None, 2:] + fused.float() * crop_box[:1, None, 2:3]+ return mp.float(), out["shape_params"][:1].float(), t.float(), joints_2d+++def atan2_poly(y, x):+ """atan2 from basic operations (max error ~1e-5 rad): onnxruntime's CUDA provider has no Atan kernel, so the+ native operator would send the rotation decoding to the CPU and prevent CUDA-graph capture."""+ ax, ay = x.abs(), y.abs()+ a = torch.minimum(ax, ay) / torch.maximum(ax, ay).clamp_min(1e-12)+ s = a * a+ r = a * (0.9998660 + s * (-0.3302995 + s * (0.1801410 + s * (-0.0851330 + s * 0.0208351))))+ r = torch.where(ay > ax, 1.5707963267948966 - r, r)+ r = torch.where(x < 0, 3.141592653589793 - r, r)+ return torch.where(y < 0, -r, r)+++def _attention_in_fp32(module: torch.nn.Module) -> None:+ """Run every attention block in float32 inside an fp16 graph. Exported attention computes the query-key scores+ as a plain matrix product, and in fp16 they overflow (65504) on some models and images: medium-commercial+ reaches 81 x 31 per dimension over 64 dimensions, which turns the softmax into NaN on onnxruntime's CUDA+ provider. PyTorch's fused kernel never stores those scores in fp16, so the PyTorch model does not show it."""+ for m in module.modules():+ if isinstance(m, torch.nn.MultiheadAttention):+ m.float()++ def forward(query, key, value, *args, _forward=m.forward, **kwargs):+ kwargs = {k: v.float() if torch.is_tensor(v) and v.is_floating_point() else v for k, v in kwargs.items()}+ out, weights = _forward(query.float(), key.float(), value.float(), *args, **kwargs)+ return out.to(query.dtype), weights+ m.forward = forward+++def export_fit(net, cfg, n_crops: int, path: Path, mhr_model: Path, fp32: bool) -> None:+ if not torch.cuda.is_available() and not fp32:+ sys.exit("[error] an fp16 export needs a CUDA GPU to trace the network; pass --fp32 on a CPU-only machine")+ dev = torch.device("cuda" if torch.cuda.is_available() else "cpu")+ dtype = torch.float32 if fp32 else torch.float16+ kin = MHRKinematics.from_rig(mhr_model, REPO / "training" / "assets" / "mhr_j127_to_kp70.npy")+ graph = FitNetwork(net, kin, n_crops, dtype).eval().to(dev, dtype)+ graph.mean.data, graph.istd.data = graph.mean.float(), graph.istd.float()+ if not fp32:+ _attention_in_fp32(graph)+ size = int(cfg.image_size)+ scales = (0.9, 0.7)[:n_crops]+ side = torch.tensor([600.0 * 1.2 * s for s in scales]) # a person ~600 px tall in a 1280 x 720 frame+ box = torch.stack([640 - side / 2, 360 - side / 2, side, side], 1)+ inputs = {"image": torch.randint(0, 255, (n_crops, size, size, 3), dtype=torch.uint8),+ "cliff_cond": torch.tensor([[0.0, 0.0, 0.5]]).repeat(n_crops, 1), "crop_box": box,+ "cam": torch.tensor([[1100.0, 640.0, 360.0]])}+ path.parent.mkdir(parents=True, exist_ok=True)+ torch.atan2, atan2 = atan2_poly, torch.atan2 # traced into the graph instead of Atan+ try: # no torch.no_grad(): it selects a fused attention kernel ONNX lacks+ torch.onnx.export(graph, tuple(v.to(dev) for v in inputs.values()), str(path), input_names=list(inputs),+ output_names=NETWORK_OUTPUTS, opset_version=17, dynamo=False)+ finally:+ torch.atan2 = atan2+ model = onnx.load(str(path))+ try: # optional: folds the constants the fp16 trace leaves behind+ from onnxsim import simplify+ model, ok = simplify(model)+ assert ok, "onnxsim could not validate the simplified graph"+ except ImportError:+ pass+ for key, value in {"image_size": str(size), "cliff_focal": str(bool(cfg.cliff_focal)).lower(),+ "crops": str(n_crops), "crop_scales": ",".join(map(str, scales)),+ "precision": "fp32" if fp32 else "fp16",+ "fit": "1 Levenberg-Marquardt step, 10 Newton-Schulz steps, prior 30 / 0.01"}.items():+ entry = model.metadata_props.add()+ entry.key, entry.value = key, value+ onnx.save(model, str(path))++ session = ort.InferenceSession(str(path), providers=["CPUExecutionProvider"])+ got = dict(zip(NETWORK_OUTPUTS, session.run(None, {k: v.numpy() for k, v in inputs.items()})))+ ref = FitNetwork(net, kin, n_crops, torch.float32).float().eval().cpu()+ with torch.no_grad():+ want = dict(zip(NETWORK_OUTPUTS, (o.numpy() for o in ref(*inputs.values()))))+ if not all(np.isfinite(v).all() for v in got.values()):+ sys.exit("[error] the ONNX graph returns non-finite values")+ print(f"wrote {path} ({path.stat().st_size / 1e6:.1f} MB, {'fp32' if fp32 else 'fp16'}); onnxruntime vs PyTorch "+ f"fp32: pose {np.abs(got['mhr_params'][:, 3:68] - want['mhr_params'][:, 3:68]).max():.1e} rad, "+ f"joints_2d {np.abs(got['joints_2d'] - want['joints_2d']).max():.2f} px")++def main() -> None:ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)what = ap.add_mutually_exclusive_group(required=True)what.add_argument("--ckpt", type=Path, help="checkpoint written by training/train.py or train_ddp.py")what.add_argument("--body", action="store_true", help="export the MHR body graph instead")ap.add_argument("--output", type=Path, required=True)+ ap.add_argument("--fit", type=int, choices=(1, 2), help="with --ckpt: export the network + kinematic fit graph, "+ "on 1 crop or 2 crops per person")+ ap.add_argument("--fp32", action="store_true", help="with --fit: float32 instead of float16")ap.add_argument("--mhr-model", type=Path, default=REPO / "training" / "checkpoints" / "mhr_model.pt",help="MHR TorchScript rig the body is read from")args = ap.parse_args()@@ -98,6 +206,9 @@ def main() -> None:returnnet, cfg = load_network(args.ckpt)+ if args.fit:+ export_fit(net, cfg, args.fit, args.output, args.mhr_model, args.fp32)+ returnsize = int(cfg.image_size)inputs = {"image": torch.randn(2, 3, size, size), "cliff_cond": torch.randn(2, 3) * 0.3}export(Network(net).eval(), inputs, NETWORK_OUTPUTS, args.output,diff --git a/training/README.md b/training/README.mdindex 9e739f5..de49de2 100644--- a/training/README.md+++ b/training/README.md@@ -136,3 +136,13 @@ python demo.py --image photo.jpg --model models/my-model.onnxThe first graph is the network; the second turns its MHR parameters into the 70 3D keypoints andthe mesh, and the demo looks for it next to the model. The exporter reads the training settingsfrom the `run_config.json` beside the checkpoint, so keep the two together.++To export the network with the kinematic fit (on 1 or 2 crops per person), add `--fit`:++```bash+python tools/export_onnx.py --ckpt runs/medium/best_student_model_v3.pth --fit 2 --output models/my-model-fit2.onnx+python demo.py --video clip.mp4 --model models/my-model-fit2.onnx+```++This graph is fp16 by default, which needs a CUDA GPU to trace (`--fp32` otherwise). It reads the+MHR rig from `training/checkpoints/mhr_model.pt`, like `--body`.diff --git a/training/kinematic_fit.py b/training/kinematic_fit.pynew file mode 100644index 0000000..67c6caa--- /dev/null+++ b/training/kinematic_fit.py@@ -0,0 +1,260 @@+"""MHR kinematic fit as a static, export-ready PyTorch module (ONNX -> TensorRT / ORT CUDA / ORT QNN, fp16).++Used by ``tools/export_onnx.py --fit``: the network's MHR pose is refined so that its 30 body keypoints, projected+into the frame, land on the network's own 2D (SimCC) keypoints, weighted by their spread.++The pose (root rotation + 62 body angles, MHR parameters 3:68) and the camera translation are moved so that the+30 projected body keypoints land on given 2D targets, weighted by their spread, with a quadratic prior pulling+towards the network's prediction. Levenberg-Marquardt, a fixed number of iterations, no data-dependent control+flow:++* forward kinematics as in the MHR rig (prefix-multiplication levels, quaternions), from constants read once out+ of ``checkpoints/mhr_model.pt``;+* an exact Jacobian: parameters 3:68 drive only joint rotations, so the derivative of a joint position along a+ rotation axis w of an ancestor j is w x (p - p_j); keypoints are a fixed linear map of joint positions;+* the 68x68 normal equations solved by Newton-Schulz iterations (matrix products only: no solve / inverse+ operator exists in ONNX, and phone NPUs are slow on long chains of tiny operations).+"""++from __future__ import annotations++import math+from pathlib import Path++import numpy as np+import torch+from torch import nn++BODY_KP = list(range(21)) + [41, 62] + list(range(63, 70))+POSE = slice(3, 68)+N_POSE = 65+LN2 = math.log(2.0)+++def _qmul(a, b):+ x1, y1, z1, w1 = a.unbind(-1)+ x2, y2, z2, w2 = b.unbind(-1)+ return torch.stack((w1 * x2 + x1 * w2 + y1 * z2 - z1 * y2, w1 * y2 - x1 * z2 + y1 * w2 + z1 * x2,+ w1 * z2 + x1 * y2 - y1 * x2 + z1 * w2, w1 * w2 - x1 * x2 - y1 * y2 - z1 * z2), -1)+++def _cross(a, b):+ ax, ay, az = a.unbind(-1)+ bx, by, bz = b.unbind(-1)+ return torch.stack((ay * bz - az * by, az * bx - ax * bz, ax * by - ay * bx), -1)+++def _rotate(q, v):+ u, w = q[..., :3], q[..., 3:]+ uv = _cross(u, v)+ return v + 2 * (uv * w + _cross(u, uv))+++def _normalize(q):+ return q / torch.sqrt((q * q).sum(-1, keepdim=True)).clamp_min(1e-6)+++def _half_angle_quats(e):+ """Euler XYZ (roll, pitch, yaw) -> the three elementary quaternions qx, qy, qz (x, y, z, w)."""+ h = e * 0.5+ c, s = torch.cos(h), torch.sin(h)+ z = c[..., 0] * 0+ qx = torch.stack((s[..., 0], z, z, c[..., 0]), -1)+ qy = torch.stack((z, s[..., 1], z, c[..., 1]), -1)+ qz = torch.stack((z, z, s[..., 2], c[..., 2]), -1)+ return qx, qy, qz+++def rig_constants(mhr_path: str | Path, kp_regressor_path: str | Path) -> dict:+ """Read the TorchScript rig once: what forward kinematics and the keypoint readout need."""+ rig = torch.jit.load(str(mhr_path), map_location="cpu").eval()+ ct = rig.character_torch+ sk = ct.skeleton+ parents = sk.joint_parents.numpy().astype(np.int64)+ chains = []+ for j in range(len(parents)):+ c = [j]+ while parents[c[-1]] >= 0:+ c.append(int(parents[c[-1]]))+ chains.append(c[::-1])+ partners, actives, level = [], [], 0+ while True: # pymomentum's prefix-multiplication levels+ partner, active = np.arange(len(parents)), np.zeros(len(parents), bool)+ for c in chains:+ i = len(c) - 1+ if (i >> level) & 1:+ partner[c[i]] = c[((i >> level) << level) - 1]+ active[c[i]] = True+ if not active.any():+ break+ partners.append(partner); actives.append(active); level += 1+ desc = np.zeros((len(parents), len(parents)), np.float32) # desc[j, k] = 1 if k is a strict descendant of j+ for k, c in enumerate(chains):+ for j in c[:-1]:+ desc[j, k] = 1.0+ return dict(parameter_transform=ct.parameter_transform.parameter_transform[:, :204].numpy(),+ joint_offsets=sk.joint_translation_offsets.numpy(), joint_prerotations=sk.joint_prerotations.numpy(),+ fk_partner=np.stack(partners), fk_active=np.stack(actives), joint_parents=parents, descendants=desc,+ kp_regressor=np.load(kp_regressor_path).astype(np.float32))+++class MHRKinematics(nn.Module):+ """Forward kinematics of the MHR skeleton (raw units: cm, Y-up) and the 30 body keypoints (vision frame)."""++ def __init__(self, constants: dict):+ super().__init__()+ P = torch.as_tensor(constants["parameter_transform"], dtype=torch.float32) # (889, 204)+ n_j = P.shape[0] // 7+ rot = P.reshape(n_j, 7, 204)[:, 3:6, POSE] # (127, 3, 65)+ self.register_buffer("P", P)+ self.register_buffer("P_rot", rot.reshape(n_j * 3, N_POSE))+ self.register_buffer("offsets", torch.as_tensor(constants["joint_offsets"], dtype=torch.float32))+ self.register_buffer("prerot", torch.as_tensor(constants["joint_prerotations"], dtype=torch.float32))+ self.register_buffer("partner", torch.as_tensor(constants["fk_partner"], dtype=torch.long))+ self.register_buffer("active", torch.as_tensor(constants["fk_active"], dtype=torch.bool))+ A = torch.as_tensor(constants["kp_regressor"], dtype=torch.float32)[BODY_KP] # (30, 127)+ D = torch.as_tensor(constants["descendants"], dtype=torch.float32) # (127, 127)+ self.register_buffer("A", A)+ self.register_buffer("AD", (A[:, None, :] * D[None]).reshape(-1, n_j)) # (30*127, 127)+ self.register_buffer("AD_sum", (A[:, None, :] * D[None]).sum(-1)) # (30, 127)+ self.register_buffer("vision", torch.tensor([0.01, -0.01, -0.01]))+ self.register_buffer("axes", torch.eye(3)) # e_x, e_y, e_z+ self.register_buffer("conj", torch.tensor([-1.0, -1.0, -1.0, 1.0]))+ self.n_j = n_j++ @classmethod+ def from_rig(cls, mhr_path: str | Path, kp_regressor_path: str | Path) -> "MHRKinematics":+ return cls(rig_constants(mhr_path, kp_regressor_path))++ def forward(self, mp):+ """(B, 204) -> joint positions (B, 127, 3) raw, global quaternions (B, 127, 4), local Euler quats."""+ jp = (mp @ self.P.T).unflatten(-1, (self.n_j, 7))+ qx, qy, qz = _half_angle_quats(jp[..., 3:6])+ q = _qmul(self.prerot, _qmul(qz, _qmul(qy, qx)))+ t, s = jp[..., :3] + self.offsets, torch.exp(LN2 * jp[..., 6:])+ for lvl in range(self.partner.shape[0]): # global = parent_global o local, by levels+ idx = self.partner[lvl]+ tp, qp, sp = t.index_select(-2, idx), _normalize(q.index_select(-2, idx)), s.index_select(-2, idx)+ tn, qn, sn = tp + sp * _rotate(qp, t), _qmul(qp, _normalize(q)), sp * s+ a = self.active[lvl][:, None]+ t, q, s = torch.where(a, tn, t), torch.where(a, qn, q), torch.where(a, sn, s)+ return t, _normalize(q), qx, qy++ def keypoints(self, t):+ """(B, 127, 3) raw joint positions -> (B, 30, 3) body keypoints, vision frame (metres, Y-down)."""+ return (self.A @ t) * self.vision++ def keypoint_jacobian(self, t, q, qx, qy):+ """d(30 body keypoints, vision frame) / d(MHR params 3:68): (B, 30, 3, 65)."""+ B = t.shape[0]+ ex, ey, ez = (self.axes[i].expand_as(t) for i in range(3))+ cx, cy = qx * self.conj, qy * self.conj # conjugates+ wx = _rotate(q, ex) # world axes of the three Euler rotations+ wy = _rotate(q, _rotate(cx, ey))+ wz = _rotate(q, _rotate(cx, _rotate(cy, ez)))+ w = torch.stack((wx, wy, wz), 2) # (B, 127, 3 axes, 3)+ S = (self.AD @ t).reshape(B, -1, self.n_j, 3) # (B, 30, 127, 3): sum_k A D p_k+ lever = S - self.AD_sum[None, :, :, None] * t[:, None] # (B, 30, 127, 3)+ M = _cross(w[:, None], lever[:, :, :, None]) # (B, 30, 127, 3 axes, 3 coords)+ M = M.permute(0, 1, 4, 2, 3).reshape(B, -1, self.n_j * 3) # (B, 30*3, 127*3)+ J = (M @ self.P_rot).reshape(B, -1, 3, N_POSE) # (B, 30, 3, 65)+ return J * self.vision[None, None, :, None]+++def newton_schulz_solve(H, g, iters: int, eye):+ """x = H^-1 g for SPD H (B, n, n), by Jacobi scaling and Newton-Schulz on the inverse."""+ d = torch.rsqrt((H * eye).sum(-1).clamp_min(1e-12)) # (B, n): 1 / sqrt(diag H)+ Hs = H * d[:, :, None] * d[:, None, :]+ X = eye / Hs.abs().sum(-1).amax(-1)[:, None, None] # ||I - X0 Hs|| < 1+ for _ in range(iters):+ X = X @ (2 * eye - Hs @ X)+ return d * (X @ (d * g)[..., None])[..., 0]+++class KinematicFit(nn.Module):+ """Levenberg-Marquardt on (MHR params 3:68, camera translation), fixed iterations, export-ready."""++ def __init__(self, kin: MHRKinematics, lam_pose: float = 30.0, lam_t: float = 1e-2, iters: int = 1,+ ns_iters: int = 10, damping: float = 1e-3):+ super().__init__()+ self.kin = kin+ self.register_buffer("prior", torch.cat([torch.full((N_POSE,), lam_pose), torch.full((3,), lam_t)]))+ self.register_buffer("eye", torch.eye(N_POSE + 3)[None])+ self.register_buffer("zero", torch.zeros(1))+ self.iters, self.ns_iters, self.damping = iters, ns_iters, damping++ def forward(self, mp, t, target, sigma, cam):+ """mp (B, 204), t (B, 3), target / sigma (B, 30, 2), cam (B, 3) = (focal, cx, cy), all in one unit.++ Residuals and Jacobian are scaled by 1/16 and the prior by 1/256 (the same problem): with a 1 % of the crop+ sigma floor the weighted Jacobian reaches ~100 per entry, and J^T J would overflow fp16 (65504) unscaled."""+ inv_sigma = (1.0 / 16.0) / sigma+ x0 = torch.cat([mp[:, POSE], t], 1)+ x, mu = x0, x0[:, :1] * 0 + self.damping+ prior, eye = self.prior * (1.0 / 256.0), self.eye+ for i in range(self.iters):+ m = torch.cat([mp[:, :3], x[:, :N_POSE], mp[:, 68:]], 1)+ pos, q, qx, qy = self.kin(m)+ X = self.kin.keypoints(pos) + x[:, None, N_POSE:]+ z = X[..., 2:].clamp_min(1e-3)+ f = cam[:, None, :1]+ uv = f * X[..., :2] / z + cam[:, None, 1:]+ r = ((uv - target) * inv_sigma).flatten(1)+ Jk = self.kin.keypoint_jacobian(pos, q, qx, qy) # (B, 30, 3, 65)+ zero = z * 0 # d(u, v) / d(X, Y, Z)+ du = torch.stack((f / z, zero, -f * X[..., :1] / z ** 2), -1)[..., 0, :]+ dv = torch.stack((zero, f / z, -f * X[..., 1:2] / z ** 2), -1)[..., 0, :]+ Jp = torch.stack((du, dv), 2) # (B, 30, 2, 3)+ Jx = (torch.cat([Jp @ Jk, Jp], -1) * inv_sigma[..., None]).flatten(1, 2) # (B, 60, 68)+ JtJ = Jx.transpose(1, 2) @ Jx+ H = JtJ + eye * (prior + mu * (JtJ * eye).sum(-1))[:, None, :]+ g = (Jx.transpose(1, 2) @ r[..., None])[..., 0] + prior * (x - x0)+ step = newton_schulz_solve(H, g, self.ns_iters, eye)+ x = x - torch.where(step == step, step, self.zero) # a NaN step is dropped+ return torch.cat([mp[:, :3], x[:, :N_POSE], mp[:, 68:]], 1), x[:, N_POSE:]+++class FitHead(nn.Module):+ """One person's network outputs on ``n_crops`` crops -> fused 2D keypoints -> KinematicFit.++ Crop 0 is the main crop (its MHR parameters and camera translation start the fit). With two crops, crop 1 is+ the zoomed-in one: each body keypoint's 2D is the inverse-variance mean of the two SimCC estimates, keypoints+ outside crop 1 using crop 0 alone. ``crop_box`` (n_crops, 4) is each crop's pixel square (x1, y1, w, h) in the+ full image, i.e. what the 288 px input was resized from; ``cam`` (1, 3) is (focal, cx, cy).+ """++ def __init__(self, kin: MHRKinematics, bin_centers: torch.Tensor, n_crops: int, sigma_floor: float = 0.01,+ **fit_kwargs):+ super().__init__()+ self.fit = KinematicFit(kin, **fit_kwargs)+ self.register_buffer("centers", bin_centers.detach().float().clone())+ self.register_buffer("body", torch.as_tensor(BODY_KP))+ self.n_crops, self.sigma_floor = n_crops, sigma_floor++ def forward(self, mhr_params, cam_trans, logits, crop_box, cam):+ """Returns the fitted (1, 204) parameters and (1, 3) translation, the fused (1, 70, 2) 2D in units of crop 0+ (origin at its centre), and crop 0's centre (1, 2) and side (1, 1) in pixels: ``pixels = c0 + 2D * s0``.++ Every 2D quantity is expressed in crop-0 units so that it stays near 1 whatever the frame resolution: in+ pixels, a broad SimCC on a 2000 px close-up crop gives sigma^2 ~ 1e5, beyond fp16 (65504), and absolute+ coordinates near 4000 px keep only 2 px of fp16 precision."""+ prob = torch.softmax(logits, -1) # (N, 70, 2, bins)+ mu = (prob * self.centers).sum(-1) # crop units, [-1, 1] = the crop+ sd = torch.sqrt((prob * (self.centers - mu[..., None]) ** 2).sum(-1).clamp_min(1e-6))+ s0 = crop_box[:1, 2:3]+ c0 = crop_box[:1, :2] + 0.5 * crop_box[:1, 2:]+ rel = (crop_box[:, None, 2:] / s0) # (N, 1, 2) crop size / crop 0's+ off = (crop_box[:, None, :2] + 0.5 * crop_box[:, None, 2:] - c0) / s0 # (N, 1, 2) crop centre, crop-0 units+ xy = off + mu * 0.5 * rel # (N, 70, 2)+ sig = torch.clamp(sd, min=2 * self.sigma_floor) * 0.5 * rel # floor: sigma_floor of the crop side+ if self.n_crops == 2:+ inside = (mu[1].abs() <= 1).all(-1, keepdim=True).to(xy.dtype) # keypoint within the zoomed crop+ r2 = (sig[0] / sig[1]) ** 2 * inside # w1 / w0+ fused = xy[0] + (r2 / (1 + r2)) * (xy[1] - xy[0]) # inverse-variance mean+ sigma = sig[0] * torch.rsqrt(1 + r2)+ else:+ fused, sigma = xy[0], sig[0]+ cam_n = torch.cat([cam[:, :1] / s0, (cam[:, 1:] - c0) / s0], 1)+ mp, t = self.fit(mhr_params[:1], cam_trans[:1], fused[None].index_select(1, self.body),+ sigma[None].index_select(1, self.body), cam_n)+ return mp, t, fused[None], c0, s0