diff --git a/src/python/isaaccapture_egopost/egohand/models/backbones/dinov3.py b/src/python/isaaccapture_egopost/egohand/models/backbones/dinov3.py index 0b390644e5..54b524e555 100644 --- a/src/python/isaaccapture_egopost/egohand/models/backbones/dinov3.py +++ b/src/python/isaaccapture_egopost/egohand/models/backbones/dinov3.py @@ -56,7 +56,23 @@ class DinoV3Backbone(nn.Module): ), } - def __init__(self, name: str = "dinov3_vith16plus", drop_path_rate: float = 0.1): + def __init__( + self, + name: str = "dinov3_vith16plus", + drop_path_rate: float = 0.1, + meta_init: bool = False, + ): + """Build the DINOv3 encoder. + + Args: + name: Architecture key in ``_ARCH_KWARGS``. + drop_path_rate: Stochastic depth rate (training only). + meta_init: Inference loading only. Allocate the encoder on the + ``meta`` device and skip its random initialization; the caller + must materialize it with ``encoder.to_empty(device=...)`` and + then load every encoder tensor from a checkpoint. Training + configs leave this ``False``. + """ super().__init__() if name not in self._ARCH_KWARGS: raise ValueError( @@ -67,8 +83,13 @@ def __init__(self, name: str = "dinov3_vith16plus", drop_path_rate: float = 0.1) vit_kwargs = dict(self._ARCH_KWARGS[name]) vit_kwargs["drop_path_rate"] = drop_path_rate - self.encoder = DinoVisionTransformer(**vit_kwargs) - self.encoder.init_weights() + if meta_init: + # Skip random CPU initialization when checkpoint weights will overwrite every tensor. + with torch.device("meta"): + self.encoder = DinoVisionTransformer(**vit_kwargs) + else: + self.encoder = DinoVisionTransformer(**vit_kwargs) + self.encoder.init_weights() self.name = name self.patch_size = self.encoder.patch_size self.embed_dim = self.embed_dims = self.encoder.embed_dim diff --git a/src/python/isaaccapture_egopost/egohand/models/egohand.py b/src/python/isaaccapture_egopost/egohand/models/egohand.py index 253091c4eb..f61f2c5b3e 100644 --- a/src/python/isaaccapture_egopost/egohand/models/egohand.py +++ b/src/python/isaaccapture_egopost/egohand/models/egohand.py @@ -147,7 +147,7 @@ class EgoHand(nn.Module): full_perspective_modes = ("perspective", "sam3db_perspective") - def __init__(self, cfg: DictConfig, **kwargs): + def __init__(self, cfg: DictConfig, *, build_soma_hand: bool = True, **kwargs): super().__init__() self.cfg = cfg self.freeze_backbone = bool(cfg.get("freeze_backbone", False)) @@ -470,11 +470,14 @@ def __init__(self, cfg: DictConfig, **kwargs): soma_hand_cfg = cfg.get("soma_hand", {}) self.soma_hand_identity = soma_hand_cfg.get("identity_model_type", "mhr") - self.soma_hand = SomaHandWrapper( - data_root=soma_hand_cfg.get("data_root", None), - device="cuda", - identity_model_type=self.soma_hand_identity, - ) + if build_soma_hand: + self.soma_hand = SomaHandWrapper( + data_root=soma_hand_cfg.get("data_root", None), + device="cuda", + identity_model_type=self.soma_hand_identity, + ) + else: + self.soma_hand = nn.Module() # Optional depth modality: per-modality encoder + # ``zero_module``-initialized fusion projection. When @@ -986,6 +989,21 @@ def process_pred_hand_params( def forward_step( self, batch: Dict, train: bool = False, un_rotate: bool = False ) -> Dict: + head = self.forward_step_head(batch, train=train, un_rotate=un_rotate) + with torch.amp.autocast("cuda", enabled=False): + hand_out = self.soma_hand( + hand_type="left", pose2rot=False, **head["soma_inputs"] + ) + return self.forward_step_decode(head, hand_out["joints"], hand_out["vertices"]) + + def forward_step_head( + self, batch: Dict, train: bool = False, un_rotate: bool = False + ) -> Dict: + """Run ``forward_step`` up to (excluding) the left SOMA hand layer. + + Returns the state consumed by ``forward_step_decode`` so callers can + batch SOMA evaluations across multiple head batches. + """ x = batch["img"] batch_size = x.shape[0] device = x.device @@ -1154,20 +1172,55 @@ def forward_step( pred_global_scale, pred_scale_params = self._split_scale_params( pred_hand_params["scale_params"].float() ) - hand_out = self.soma_hand( - poses=poses_25, - identity_coeffs=pred_hand_params["identity_coeffs"].float(), - hand_type="left", - pose2rot=False, - global_scale=pred_global_scale, - scale_params=pred_scale_params, - ) - pred_joints = hand_out["joints"] - pred_vertices = hand_out["vertices"] + soma_inputs = { + "poses": poses_25, + "identity_coeffs": pred_hand_params["identity_coeffs"].float(), + "global_scale": pred_global_scale, + "scale_params": pred_scale_params, + } + return { + "output": output, + "soma_inputs": soma_inputs, + "pred_cam": pred_cam, + "direct_kp2d_output": direct_kp2d_output, + "batch_size": batch_size, + "device": device, + "train": train, + "un_rotate": un_rotate, + "aug_rot": batch.get("aug_rot", None), + "is_full_perspective": is_full_perspective, + "img_wh": img_wh, + "box_center": box_center, + "box_size": box_size, + "focal": focal, + "K_fullimg": K_fullimg, + } + + def forward_step_decode( + self, + head: Dict, + pred_joints: torch.Tensor, + pred_vertices: torch.Tensor | None, + ) -> Dict: + """Finish ``forward_step`` from the left SOMA joints and vertices of ``head``.""" + output = head["output"] + pred_cam = head["pred_cam"] + direct_kp2d_output = head["direct_kp2d_output"] + batch_size = head["batch_size"] + device = head["device"] + train = head["train"] + un_rotate = head["un_rotate"] + is_full_perspective = head["is_full_perspective"] + img_wh = head["img_wh"] + box_center = head["box_center"] + box_size = head["box_size"] + focal = head["focal"] + K_fullimg = head["K_fullimg"] + with torch.amp.autocast("cuda", enabled=False): pred_camera_parameter_f = pred_cam.float() if un_rotate: - aug_rot = batch.get("aug_rot", None) + aug_rot = head["aug_rot"] if aug_rot is not None: aug_rot_f = torch.as_tensor( aug_rot, device=device, dtype=torch.float32 @@ -1184,9 +1237,10 @@ def forward_step( R_undo[:, 1, 1] = cos_t R_undo[:, 2, 2] = 1.0 pred_joints = torch.einsum("bij,bnj->bni", R_undo, pred_joints) - pred_vertices = torch.einsum( - "bij,bnj->bni", R_undo, pred_vertices - ) + if pred_vertices is not None: + pred_vertices = torch.einsum( + "bij,bnj->bni", R_undo, pred_vertices + ) camera_scalar = pred_camera_parameter_f[:, 0:1] cam_tx = pred_camera_parameter_f[:, 1:2] cam_ty = pred_camera_parameter_f[:, 2:3] diff --git a/src/python/isaaccapture_egopost/inference/camera/fisheye_crop_cuda.py b/src/python/isaaccapture_egopost/inference/camera/fisheye_crop_cuda.py new file mode 100644 index 0000000000..5db114d53b --- /dev/null +++ b/src/python/isaaccapture_egopost/inference/camera/fisheye_crop_cuda.py @@ -0,0 +1,1360 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: LicenseRef-OpenMDW-1.1 + +"""Bit-exact GPU/CPU perspective cropping for FISHEYE624, KB4, and PINHOLE cameras. + +Provides batched FP64 inverse distortion (``fisheye_unproject_torch``), batched +virtual-camera geometry computation (``compute_perspective_crop_params_batch``), +a fused Warp kernel (``_fisheye_perspective_crop_u8_kernel``) plus pure-PyTorch +fallback implementing exact OpenCV 5-bit fixed-point bilinear interpolation with +fused BGR-to-RGB conversion and fused right-hand horizontal flip, and a chunked +high-level entry point (``crop_chunk_gpu``). +""" + +from __future__ import annotations + +import logging +import math +from collections.abc import Mapping, Sequence +from typing import Any + +import cv2 +import numpy as np +import torch +from scipy.spatial.transform import Rotation + +from inference.camera.camera_models import ( + CameraModel, + _FISHEYE624_TOLERANCE, + _KB4_MAX_PIXEL_ERROR, + _MAX_INVERSE_ITERATIONS, + _FisheyeCamera, + _PerspectiveCamera, + create_perspective_remap, +) +from inference.preprocessing.crop import IMG_SIZE +from inference.preprocessing.mirroring import mirror_full_image_camera_horizontal + +try: + import warp as wp +except ImportError: # pragma: no cover - warp is optional in CPU-only builds + wp = None + +log = logging.getLogger(__name__) + +_CAMERA_MODEL_PINHOLE = 0 +_CAMERA_MODEL_KB4 = 1 +_CAMERA_MODEL_FISHEYE624 = 2 + +_FAST_CAMERA_MODEL_IDS = { + "PINHOLE": _CAMERA_MODEL_PINHOLE, + "KB4": _CAMERA_MODEL_KB4, + "FISHEYE624": _CAMERA_MODEL_FISHEYE624, +} + +# Tighter internal Newton step thresholds than CPU tolerances so both solvers +# reach machine-precision roots (< 1e-12 agreement with scipy.optimize.newton). +_TANGENTIAL_STEP_EPS = 1e-12 +_RADIAL_STEP_EPS = 1e-13 + +# Cap per-batch tensor memory in the pure-PyTorch fallback. +_TORCH_CROP_SUBBATCH = 64 + + +if wp is not None: + + @wp.kernel(enable_backward=False) + def _fisheye_perspective_crop_u8_kernel( + src_images: wp.array4d(dtype=wp.uint8), + frame_indices: wp.array(dtype=wp.int32), + rotations: wp.array3d(dtype=wp.float64), + focal_lengths: wp.array(dtype=wp.float64), + flip_x: wp.array(dtype=wp.int32), + side: wp.int32, + src_h: wp.int32, + src_w: wp.int32, + camera_model_id: wp.int32, + has_tangential_prism: wp.int32, + intrinsics: wp.vec4d, + radial_012: wp.vec3d, + radial_345: wp.vec3d, + tan_prism_0: wp.vec3d, + tan_prism_1: wp.vec3d, + out_crops: wp.array4d(dtype=wp.uint8), + ): + """Fused perspective ray generation, FP64 fisheye/pinhole projection, + right-hand horizontal flip, OpenCV 5-bit fixed-point bilinear remap, + and BGR-to-RGB channel swap. + """ + job_idx, out_y, out_x = wp.tid() + + zero = wp.float64(0.0) + one = wp.float64(1.0) + two = wp.float64(2.0) + three = wp.float64(3.0) + + gx = out_x + if flip_x[job_idx] != 0: + gx = side - 1 - out_x + + center = wp.float64(side - 1) / two + focal_length = focal_lengths[job_idx] + cx = (wp.float64(gx) - center) / focal_length + cy = (wp.float64(out_y) - center) / focal_length + + rx = ( + cx * rotations[job_idx, 0, 0] + + cy * rotations[job_idx, 0, 1] + + rotations[job_idx, 0, 2] + ) + ry = ( + cx * rotations[job_idx, 1, 0] + + cy * rotations[job_idx, 1, 1] + + rotations[job_idx, 1, 2] + ) + rz = ( + cx * rotations[job_idx, 2, 0] + + cy * rotations[job_idx, 2, 1] + + rotations[job_idx, 2, 2] + ) + + if ( + not wp.isfinite(rx) + or not wp.isfinite(ry) + or not wp.isfinite(rz) + or rz <= zero + ): + out_crops[job_idx, out_y, out_x, 0] = wp.uint8(0) + out_crops[job_idx, out_y, out_x, 1] = wp.uint8(0) + out_crops[job_idx, out_y, out_x, 2] = wp.uint8(0) + return + + fx = intrinsics[0] + fy = intrinsics[1] + k_cx = intrinsics[2] + k_cy = intrinsics[3] + + u = wp.float64(0.0) + v = wp.float64(0.0) + + if camera_model_id == 0: + u = (rx / rz) * fx + k_cx + v = (ry / rz) * fy + k_cy + else: + ray_xy_norm = wp.sqrt(rx * rx + ry * ry) + if not wp.isfinite(ray_xy_norm): + out_crops[job_idx, out_y, out_x, 0] = wp.uint8(0) + out_crops[job_idx, out_y, out_x, 1] = wp.uint8(0) + out_crops[job_idx, out_y, out_x, 2] = wp.uint8(0) + return + + theta = wp.atan2(ray_xy_norm, rz) + theta2 = theta * theta + + poly = radial_345[2] + poly = poly * theta2 + radial_345[1] + poly = poly * theta2 + radial_345[0] + poly = poly * theta2 + radial_012[2] + poly = poly * theta2 + radial_012[1] + poly = poly * theta2 + radial_012[0] + poly = poly * theta2 + one + distorted_r = theta * poly + + xd = zero + yd = zero + if ray_xy_norm > zero: + xd = (rx / ray_xy_norm) * distorted_r + yd = (ry / ray_xy_norm) * distorted_r + + if has_tangential_prism != 0: + p0 = tan_prism_0[0] + p1 = tan_prism_0[1] + s0 = tan_prism_0[2] + s1 = tan_prism_1[0] + s2 = tan_prism_1[1] + s3 = tan_prism_1[2] + x2 = xd * xd + y2 = yd * yd + r2 = x2 + y2 + r4 = r2 * r2 + dx = p0 * (three * x2 + y2) + two * p1 * xd * yd + s0 * r2 + s1 * r4 + dy = p1 * (x2 + three * y2) + two * p0 * xd * yd + s2 * r2 + s3 * r4 + xd = xd + dx + yd = yd + dy + + u = xd * fx + k_cx + v = yd * fy + k_cy + + # Match create_perspective_remap's float32 cast before OpenCV remap. + uf = wp.float32(u) + vf = wp.float32(v) + if ( + not wp.isfinite(uf) + or not wp.isfinite(vf) + or uf < wp.float32(-2.0) + or uf > wp.float32(src_w + 2) + or vf < wp.float32(-2.0) + or vf > wp.float32(src_h + 2) + ): + out_crops[job_idx, out_y, out_x, 0] = wp.uint8(0) + out_crops[job_idx, out_y, out_x, 1] = wp.uint8(0) + out_crops[job_idx, out_y, out_x, 2] = wp.uint8(0) + return + + # OpenCV CV_32FC2 INTER_LINEAR 5-bit fixed-point arithmetic (INTER_BITS=5). + iu = wp.int32(wp.rint(uf * wp.float32(32.0))) + iv = wp.int32(wp.rint(vf * wp.float32(32.0))) + x0 = iu >> 5 + y0 = iv >> 5 + fx_i = iu & 31 + fy_i = iv & 31 + x1 = x0 + 1 + y1 = y0 + 1 + + w00 = (32 - fx_i) * (32 - fy_i) + w01 = fx_i * (32 - fy_i) + w10 = (32 - fx_i) * fy_i + w11 = fx_i * fy_i + + in_x0 = x0 >= 0 and x0 < src_w + in_x1 = x1 >= 0 and x1 < src_w + in_y0 = y0 >= 0 and y0 < src_h + in_y1 = y1 >= 0 and y1 < src_h + + frame_idx = frame_indices[job_idx] + + r00 = wp.int32(0) + g00 = wp.int32(0) + b00 = wp.int32(0) + if in_y0 and in_x0: + b00 = wp.int32(src_images[frame_idx, y0, x0, 0]) + g00 = wp.int32(src_images[frame_idx, y0, x0, 1]) + r00 = wp.int32(src_images[frame_idx, y0, x0, 2]) + + r01 = wp.int32(0) + g01 = wp.int32(0) + b01 = wp.int32(0) + if in_y0 and in_x1: + b01 = wp.int32(src_images[frame_idx, y0, x1, 0]) + g01 = wp.int32(src_images[frame_idx, y0, x1, 1]) + r01 = wp.int32(src_images[frame_idx, y0, x1, 2]) + + r10 = wp.int32(0) + g10 = wp.int32(0) + b10 = wp.int32(0) + if in_y1 and in_x0: + b10 = wp.int32(src_images[frame_idx, y1, x0, 0]) + g10 = wp.int32(src_images[frame_idx, y1, x0, 1]) + r10 = wp.int32(src_images[frame_idx, y1, x0, 2]) + + r11 = wp.int32(0) + g11 = wp.int32(0) + b11 = wp.int32(0) + if in_y1 and in_x1: + b11 = wp.int32(src_images[frame_idx, y1, x1, 0]) + g11 = wp.int32(src_images[frame_idx, y1, x1, 1]) + r11 = wp.int32(src_images[frame_idx, y1, x1, 2]) + + out_r = (r00 * w00 + r01 * w01 + r10 * w10 + r11 * w11 + 512) >> 10 + out_g = (g00 * w00 + g01 * w01 + g10 * w10 + g11 * w11 + 512) >> 10 + out_b = (b00 * w00 + b01 * w01 + b10 * w10 + b11 * w11 + 512) >> 10 + + out_crops[job_idx, out_y, out_x, 0] = wp.uint8(out_r) + out_crops[job_idx, out_y, out_x, 1] = wp.uint8(out_g) + out_crops[job_idx, out_y, out_x, 2] = wp.uint8(out_b) + + # Preserve strict IEEE float64 operation order without fast-math or FMA fusion. + wp.set_module_options({"fast_math": False, "fuse_fp": False}) + + +def _horner_torch(x: torch.Tensor, coeffs: Sequence[float]) -> torch.Tensor: + """Evaluate polynomial sum_i coeffs[i] * x^i via Horner's method.""" + acc = torch.full_like(x, float(coeffs[-1])) + for coeff in reversed(coeffs[:-1]): + acc = acc * x + float(coeff) + return acc + + +def _fisheye624_tangential_prism_offsets_torch( + x: torch.Tensor, + y: torch.Tensor, + p0: float, + p1: float, + s0: float, + s1: float, + s2: float, + s3: float, +) -> tuple[torch.Tensor, torch.Tensor]: + """Compute FISHEYE624 tangential and thin-prism offsets in normalized coordinates.""" + x2 = x * x + y2 = y * y + r2 = x2 + y2 + r4 = r2 * r2 + two_xy = 2.0 * x * y + dx = p0 * (3.0 * x2 + y2) + p1 * two_xy + s0 * r2 + s1 * r4 + dy = p1 * (x2 + 3.0 * y2) + p0 * two_xy + s2 * r2 + s3 * r4 + return dx, dy + + +@torch.no_grad() +def fisheye_unproject_torch( + pixels: torch.Tensor, + camera: _FisheyeCamera, +) -> torch.Tensor: + """Batched FP64 Newton inverse matching ``_FisheyeCamera.unproject``. + + Supports both ``FISHEYE624`` (6 radial, 2 tangential, 4 thin-prism terms) + and ``KB4`` (4 radial terms) on CPU or CUDA tensors, matching + ``_FisheyeCamera.unproject`` to better than ``1e-12``. + + Args: + pixels: Source image coordinates shaped ``(..., 2)`` on CPU or CUDA. + camera: A ``_FisheyeCamera`` (``FISHEYE624`` or ``KB4``). + + Returns: + Unit forward rays shaped ``(..., 3)`` in ``torch.float64`` on + ``pixels.device``, with ``NaN`` for invalid inversions. + """ + if not isinstance(camera, _FisheyeCamera): + raise TypeError( + f"fisheye_unproject_torch requires a FISHEYE624 or KB4 camera, " + f"got {type(camera).__name__} ({getattr(camera, 'model_name', 'unknown')})" + ) + if pixels.ndim == 0 or pixels.shape[-1] != 2: + raise ValueError(f"pixels must have shape (..., 2), got {tuple(pixels.shape)}") + + orig_shape = pixels.shape[:-1] + device = pixels.device + flat_pixels = pixels.to(dtype=torch.float64).reshape(-1, 2) + n_pts = flat_pixels.shape[0] + if n_pts == 0: + return torch.empty((*orig_shape, 3), dtype=torch.float64, device=device) + + fx = float(camera.K[0, 0]) + fy = float(camera.K[1, 1]) + cx = float(camera.K[0, 2]) + cy = float(camera.K[1, 2]) + + valid_pixels = torch.isfinite(flat_pixels).all(dim=1) + principal = torch.tensor([cx, cy], dtype=torch.float64, device=device) + focal = torch.tensor([fx, fy], dtype=torch.float64, device=device) + + distorted_normalized = ( + torch.where(valid_pixels[:, None], flat_pixels, principal) - principal + ) / focal + rx = distorted_normalized[:, 0].clone() + ry = distorted_normalized[:, 1].clone() + is_cpu = device.type == "cpu" + + if np.any(camera.tangential_prism): + p0, p1, s0, s1, s2, s3 = (float(c) for c in camera.tangential_prism) + target_x = distorted_normalized[:, 0] + target_y = distorted_normalized[:, 1] + active = valid_pixels.clone() + zeros = torch.zeros_like(rx) + ones = torch.ones_like(rx) + + for it in range(_MAX_INVERSE_ITERATIONS): + off_x, off_y = _fisheye624_tangential_prism_offsets_torch( + rx, ry, p0, p1, s0, s1, s2, s3 + ) + res_x = target_x - rx - off_x + res_y = target_y - ry - off_y + + r2 = rx * rx + ry * ry + jxx = ( + 1.0 + 6.0 * p0 * rx + 2.0 * p1 * ry + 2.0 * s0 * rx + 4.0 * s1 * r2 * rx + ) + jxy = 2.0 * p0 * ry + 2.0 * p1 * rx + 2.0 * s0 * ry + 4.0 * s1 * r2 * ry + jyx = 2.0 * p1 * rx + 2.0 * p0 * ry + 2.0 * s2 * rx + 4.0 * s3 * r2 * rx + jyy = ( + 1.0 + 6.0 * p1 * ry + 2.0 * p0 * rx + 2.0 * s2 * ry + 4.0 * s3 * r2 * ry + ) + + det = jxx * jyy - jxy * jyx + num_x = jyy * res_x - jxy * res_y + num_y = jxx * res_y - jyx * res_x + + solvable = active & (det != 0.0) & torch.isfinite(det) + safe_det = torch.where(solvable, det, ones) + step_x = torch.where(solvable, num_x / safe_det, zeros) + step_y = torch.where(solvable, num_y / safe_det, zeros) + + rx = rx + step_x + ry = ry + step_y + + active = ( + solvable + & torch.isfinite(step_x) + & torch.isfinite(step_y) + & ( + (step_x.abs() >= _TANGENTIAL_STEP_EPS) + | (step_y.abs() >= _TANGENTIAL_STEP_EPS) + ) + ) + if is_cpu: + if not bool(active.any()): + break + elif it in (5, 11, 23) and not bool(active.any()): + break + + off_x, off_y = _fisheye624_tangential_prism_offsets_torch( + rx, ry, p0, p1, s0, s1, s2, s3 + ) + final_res_x = rx + off_x - target_x + final_res_y = ry + off_y - target_y + max_res = torch.maximum(final_res_x.abs(), final_res_y.abs()) + valid_pixels = ( + valid_pixels & torch.isfinite(max_res) & (max_res < _FISHEYE624_TOLERANCE) + ) + + distorted_radii = torch.hypot(rx, ry) + half_pi = math.pi / 2.0 + radial_poly = [float(c) for c in camera._radial_polynomial] + radial_deriv = [float(c) for c in camera._radial_derivative] + max_distorted_radius = half_pi * float( + np.polynomial.polynomial.polyval(half_pi * half_pi, camera._radial_polynomial) + ) + valid_pixels = ( + valid_pixels + & torch.isfinite(distorted_radii) + & (distorted_radii < max_distorted_radius) + ) + + zeros = torch.zeros_like(distorted_radii) + ones = torch.ones_like(distorted_radii) + target_radii = torch.where(valid_pixels, distorted_radii, zeros) + theta = torch.clamp(target_radii, max=half_pi) + active = valid_pixels.clone() + failed_newton = torch.zeros_like(valid_pixels) + + for it in range(_MAX_INVERSE_ITERATIONS): + theta2 = theta * theta + f_val = theta * _horner_torch(theta2, radial_poly) - target_radii + f_der = _horner_torch(theta2, radial_deriv) + bad = active & ( + (f_der == 0.0) | (~torch.isfinite(f_der)) | (~torch.isfinite(f_val)) + ) + failed_newton = failed_newton | bad + step_active = active & (~bad) + safe_der = torch.where(step_active, f_der, ones) + step = torch.where(step_active, f_val / safe_der, zeros) + theta = theta - step + active = step_active & (step.abs() >= _RADIAL_STEP_EPS) + if is_cpu: + if not bool(active.any()): + break + elif it in (7, 15, 31) and not bool(active.any()): + break + + theta = torch.where(failed_newton, torch.full_like(theta, float("nan")), theta) + radius_residual = theta * _horner_torch(theta * theta, radial_poly) - target_radii + if camera.model_name == "KB4": + radius_tolerance = _KB4_MAX_PIXEL_ERROR / max(fx, fy) + else: + radius_tolerance = _FISHEYE624_TOLERANCE + + valid_pixels = ( + valid_pixels + & torch.isfinite(theta) + & (theta >= 0.0) + & (theta < half_pi) + & torch.isfinite(radius_residual) + & (radius_residual.abs() < radius_tolerance) + ) + + nonzero_r = distorted_radii > 0.0 + safe_r = torch.where(nonzero_r, distorted_radii, ones) + dir_x = torch.where(nonzero_r, rx / safe_r, zeros) + dir_y = torch.where(nonzero_r, ry / safe_r, zeros) + sin_theta = torch.sin(theta) + cos_theta = torch.cos(theta) + rays = torch.stack((dir_x * sin_theta, dir_y * sin_theta, cos_theta), dim=1) + rays = torch.where(valid_pixels[:, None], rays, torch.full_like(rays, float("nan"))) + return rays.reshape(*orig_shape, 3) + + +def _pinhole_unproject_torch( + pixels: torch.Tensor, + camera: CameraModel, +) -> torch.Tensor: + """Closed-form batched FP64 unprojection matching ``_PerspectiveCamera.unproject``.""" + orig_shape = pixels.shape[:-1] + device = pixels.device + flat = pixels.to(dtype=torch.float64).reshape(-1, 2) + if flat.shape[0] == 0: + return torch.empty((*orig_shape, 3), dtype=torch.float64, device=device) + + fx = float(camera.K[0, 0]) + fy = float(camera.K[1, 1]) + cx = float(camera.K[0, 2]) + cy = float(camera.K[1, 2]) + principal = torch.tensor([cx, cy], dtype=torch.float64, device=device) + focal = torch.tensor([fx, fy], dtype=torch.float64, device=device) + + finite = torch.isfinite(flat).all(dim=1) + safe_flat = torch.where(finite[:, None], flat, principal) + xy = (safe_flat - principal) / focal + forward = torch.cat( + (xy, torch.ones((flat.shape[0], 1), dtype=torch.float64, device=device)), + dim=1, + ) + # Match _PerspectiveCamera.unproject scaling to prevent overflow on extreme coords. + max_abs = forward.abs().amax(dim=1, keepdim=True) + forward = forward / max_abs + forward = forward / torch.linalg.norm(forward, dim=1, keepdim=True) + finite = finite & torch.isfinite(forward).all(dim=1) + forward = torch.where( + finite[:, None], forward, torch.full_like(forward, float("nan")) + ) + return forward.reshape(*orig_shape, 3) + + +def _shortest_arc_from_z_torch(center_rays: torch.Tensor) -> torch.Tensor: + """Compute shortest-arc rotations sending ``[0, 0, 1]`` to ``center_rays``. + + Matches ``scipy.spatial.transform.Rotation.align_vectors(ray, [0, 0, 1])`` + for all forward unit rays (``z > 0``) to machine precision. + """ + norms = torch.linalg.norm(center_rays, dim=1, keepdim=True) + safe_norms = torch.where(norms > 0.0, norms, torch.ones_like(norms)) + unit = center_rays / safe_norms + ax = unit[:, 0] + ay = unit[:, 1] + az = unit[:, 2] + + denom = 1.0 + az + safe_denom = torch.where(denom > 1e-12, denom, torch.ones_like(denom)) + inv_1pz = 1.0 / safe_denom + + r00 = 1.0 - ax * ax * inv_1pz + r01 = -ax * ay * inv_1pz + r02 = ax + r10 = r01 + r11 = 1.0 - ay * ay * inv_1pz + r12 = ay + r20 = -ax + r21 = -ay + r22 = az + + row0 = torch.stack((r00, r01, r02), dim=1) + row1 = torch.stack((r10, r11, r12), dim=1) + row2 = torch.stack((r20, r21, r22), dim=1) + rotations = torch.stack((row0, row1, row2), dim=1) + + # Rare antipodal fallback (cannot happen for valid forward rays z > 0). + antipodal = denom <= 1e-12 + if bool(antipodal.any()): + unit_np = unit.detach().cpu().numpy() + anti_idx = torch.nonzero(antipodal, as_tuple=False).squeeze(-1).cpu().tolist() + for idx in anti_idx: + if np.isfinite(unit_np[idx]).all() and np.linalg.norm(unit_np[idx]) > 0.0: + rot_mat = Rotation.align_vectors(unit_np[idx], [0.0, 0.0, 1.0])[ + 0 + ].as_matrix() + rotations[idx] = torch.from_numpy(rot_mat).to( + device=rotations.device, dtype=torch.float64 + ) + return rotations + + +def _build_perimeter_sample_pixels( + bboxes_f64: np.ndarray, + crop_side_pixels: int, + device: torch.device, +) -> torch.Tensor: + """Build exact ``1 + 4 * (4 * side + 1)`` sample pixels per bbox matching perspective_crop.""" + edge_sample_count = 4 * crop_side_pixels + 1 + bboxes_t = torch.from_numpy(np.ascontiguousarray(bboxes_f64)).to( + device=device, dtype=torch.float64 + ) + cx = bboxes_t[:, 0] + cy = bboxes_t[:, 1] + half = bboxes_t[:, 2] / 2.0 + left = cx - half + right = cx + half + top = cy - half + bottom = cy + half + + # Match np.linspace(start, stop, edge_sample_count) bit-for-bit. + steps = torch.arange(edge_sample_count, dtype=torch.float64, device=device) + denom = float(edge_sample_count - 1) + xs = left[:, None] + ((right - left) / denom)[:, None] * steps[None, :] + xs[:, -1] = right + ys = top[:, None] + ((bottom - top) / denom)[:, None] * steps[None, :] + ys[:, -1] = bottom + + center_pt = torch.stack((cx, cy), dim=-1)[:, None, :] + top_edge = torch.stack((xs, top[:, None].expand_as(xs)), dim=-1) + bottom_edge = torch.stack((xs, bottom[:, None].expand_as(xs)), dim=-1) + left_edge = torch.stack((left[:, None].expand_as(ys), ys), dim=-1) + right_edge = torch.stack((right[:, None].expand_as(ys), ys), dim=-1) + + return torch.cat((center_pt, top_edge, bottom_edge, left_edge, right_edge), dim=1) + + +@torch.no_grad() +def compute_perspective_crop_params_batch( + bboxes: np.ndarray, + hands: Sequence[str], + camera: CameraModel, + crop_side_pixels: int, + device: str | torch.device = "cpu", +) -> tuple[ + list[dict[str, Any] | None], + np.ndarray, + np.ndarray, + np.ndarray, + np.ndarray, +]: + """Compute batched virtual-camera parameters for perspective hand crops. + + Generates the exact ``4 * crop_side_pixels + 1`` samples along each bbox + edge plus the bbox center, runs batched unprojection (FP64 PyTorch on + ``device`` for ``FISHEYE624``/``KB4``, closed-form FP64 for ``PINHOLE``, + and CPU fallback for ``RATIONAL_POLYNOMIAL``/other models), computes the + exact shortest-arc ``crop_to_source_rotation``, applies the identical ROI + failure checks as :func:`inference.camera.perspective_crop.perspective_crop`, + and mirrors right-hand virtual cameras via + :func:`mirror_full_image_camera_horizontal`. + + Args: + bboxes: ``(N, 3)`` array of ``[center_x, center_y, side_length]`` boxes. + hands: Sequence of length ``N`` with ``"left"`` or ``"right"``. + camera: Source ``CameraModel``. + crop_side_pixels: Side length of the square crop in pixels. + device: Torch device used for batched FP64 unprojection and geometry. + + Returns: + Five-tuple ``(params_list, valid_indices, rotations, focal_lengths, flip_x)``: + - ``params_list``: Length-``N`` list of parameter dicts (or ``None`` for + failed ROIs). Each valid dict carries ``focal_length``, + ``crop_to_source_rotation``, ``K_virtual``, ``bbox_virtual``, + ``model_bbx_xys``, ``model_K``, ``output_bbx_xys``, ``output_K``, + ``model_img_size``, and ``is_right``. + - ``valid_indices``: ``(M,)`` ``int64`` indices of valid entries. + - ``rotations``: ``(M, 3, 3)`` ``float64`` crop-to-source rotations. + - ``focal_lengths``: ``(M,)`` ``float64`` virtual pinhole focals. + - ``flip_x``: ``(M,)`` ``int32`` horizontal-flip flags (``1`` for right + hand, ``0`` for left hand). + """ + if ( + isinstance(crop_side_pixels, bool) + or not isinstance(crop_side_pixels, int) + or crop_side_pixels <= 0 + ): + raise ValueError("crop_side_pixels must be a positive integer") + bboxes_arr = np.asarray(bboxes, dtype=np.float64) + if bboxes_arr.size == 0: + bboxes_arr = bboxes_arr.reshape(0, 3) + if bboxes_arr.ndim != 2 or bboxes_arr.shape[1] != 3: + raise ValueError(f"bboxes must have shape (N, 3), got {bboxes_arr.shape}") + n_jobs = len(bboxes_arr) + if len(hands) != n_jobs: + raise ValueError(f"len(hands)={len(hands)} does not match len(bboxes)={n_jobs}") + if n_jobs == 0: + return ( + [], + np.empty(0, dtype=np.int64), + np.empty((0, 3, 3), dtype=np.float64), + np.empty(0, dtype=np.float64), + np.empty(0, dtype=np.int32), + ) + + torch_device = torch.device(device) + sample_pixels = _build_perimeter_sample_pixels( + bboxes_arr, crop_side_pixels, torch_device + ) + + if isinstance(camera, _FisheyeCamera): + sample_rays = fisheye_unproject_torch(sample_pixels, camera) + elif ( + isinstance(camera, _PerspectiveCamera) and camera._projection_parameters is None + ) or getattr(camera, "model_name", None) == "PINHOLE": + sample_rays = _pinhole_unproject_torch(sample_pixels, camera) + else: + # CPU fallback for RATIONAL_POLYNOMIAL and any custom CameraModel. + sample_rays_np = camera.unproject(sample_pixels.detach().cpu().numpy()) + sample_rays = torch.from_numpy(np.ascontiguousarray(sample_rays_np)).to( + device=torch_device, dtype=torch.float64 + ) + + center_rays = sample_rays[:, 0, :] + perim_rays = sample_rays[:, 1:, :] + + center_valid = torch.isfinite(center_rays).all(dim=1) + perim_valid = torch.isfinite(perim_rays).all(dim=2) + has_perim = perim_valid.any(dim=1) + + z_axis = torch.tensor([0.0, 0.0, 1.0], dtype=torch.float64, device=torch_device) + safe_center = torch.where(center_valid[:, None], center_rays, z_axis[None, :]) + rotations_t = _shortest_arc_from_z_torch(safe_center) + + safe_perim = torch.where(perim_valid[:, :, None], perim_rays, z_axis[None, None, :]) + virtual_perim = torch.bmm(safe_perim, rotations_t) + + behind_camera = (perim_valid & (virtual_perim[:, :, 2] <= 0.0)).any(dim=1) + positive_z = perim_valid & (virtual_perim[:, :, 2] > 0.0) + safe_z = torch.where( + positive_z, virtual_perim[:, :, 2], torch.ones_like(virtual_perim[:, :, 2]) + ) + normalized_perim = virtual_perim[:, :, :2] / safe_z[:, :, None] + abs_norm = torch.where( + positive_z[:, :, None], + normalized_perim.abs(), + torch.zeros_like(normalized_perim), + ) + max_extent = abs_norm.amax(dim=(1, 2)) + + job_valid = ( + center_valid + & has_perim + & (~behind_camera) + & torch.isfinite(max_extent) + & (max_extent > 0.0) + ) + safe_extent = torch.where(job_valid, max_extent, torch.ones_like(max_extent)) + focal_lengths_t = (crop_side_pixels / 2.0) / safe_extent + job_valid = job_valid & torch.isfinite(focal_lengths_t) & (focal_lengths_t > 0.0) + + valid_np = job_valid.detach().cpu().numpy() + rotations_np = rotations_t.detach().cpu().numpy() + focals_np = focal_lengths_t.detach().cpu().numpy() + + crop_center = (crop_side_pixels - 1) / 2.0 + params_list: list[dict[str, Any] | None] = [None] * n_jobs + valid_indices_list: list[int] = [] + flip_x_list: list[int] = [] + + for idx in range(n_jobs): + if not valid_np[idx]: + continue + focal = float(focals_np[idx]) + rot = np.array(rotations_np[idx], dtype=np.float64, copy=True) + K_virtual = np.array( + [ + [focal, 0.0, crop_center], + [0.0, focal, crop_center], + [0.0, 0.0, 1.0], + ], + dtype=np.float64, + ) + bbox_virtual = np.array( + [crop_center, crop_center, crop_side_pixels], + dtype=np.float64, + ) + is_right = hands[idx] == "right" + if is_right: + model_bbx_xys, model_K = mirror_full_image_camera_horizontal( + bbox_virtual, K_virtual, crop_side_pixels + ) + else: + model_bbx_xys = bbox_virtual + model_K = K_virtual + params_list[idx] = { + "focal_length": focal, + "crop_to_source_rotation": rot, + "K_virtual": K_virtual, + "bbox_virtual": bbox_virtual, + "model_bbx_xys": model_bbx_xys, + "model_K": model_K, + "output_bbx_xys": bbox_virtual, + "output_K": K_virtual, + "model_img_size": np.array( + [crop_side_pixels, crop_side_pixels], dtype=np.float32 + ), + "is_right": is_right, + } + valid_indices_list.append(idx) + flip_x_list.append(1 if is_right else 0) + + valid_indices = np.asarray(valid_indices_list, dtype=np.int64) + if len(valid_indices): + valid_rotations = np.ascontiguousarray( + rotations_np[valid_indices], dtype=np.float64 + ) + valid_focals = np.ascontiguousarray(focals_np[valid_indices], dtype=np.float64) + else: + valid_rotations = np.empty((0, 3, 3), dtype=np.float64) + valid_focals = np.empty(0, dtype=np.float64) + flip_x = np.asarray(flip_x_list, dtype=np.int32) + return params_list, valid_indices, valid_rotations, valid_focals, flip_x + + +def _extract_camera_kernel_args(camera: CameraModel): + """Pack PINHOLE / KB4 / FISHEYE624 calibration into Warp scalar vector args.""" + model_id = _FAST_CAMERA_MODEL_IDS[camera.model_name] + K = camera.K + intrinsics = wp.vec4d( + float(K[0, 0]), float(K[1, 1]), float(K[0, 2]), float(K[1, 2]) + ) + if isinstance(camera, _FisheyeCamera): + radial = np.zeros(6, dtype=np.float64) + radial[: len(camera.radial)] = camera.radial + tan_prism = np.asarray(camera.tangential_prism, dtype=np.float64) + has_tp = 1 if np.any(tan_prism) else 0 + else: + radial = np.zeros(6, dtype=np.float64) + tan_prism = np.zeros(6, dtype=np.float64) + has_tp = 0 + return ( + wp.int32(model_id), + wp.int32(has_tp), + intrinsics, + wp.vec3d(float(radial[0]), float(radial[1]), float(radial[2])), + wp.vec3d(float(radial[3]), float(radial[4]), float(radial[5])), + wp.vec3d(float(tan_prism[0]), float(tan_prism[1]), float(tan_prism[2])), + wp.vec3d(float(tan_prism[3]), float(tan_prism[4]), float(tan_prism[5])), + ) + + +def _launch_warp_perspective_crop( + src_images: torch.Tensor, + frame_indices: torch.Tensor, + rotations: torch.Tensor, + focal_lengths: torch.Tensor, + flip_x: torch.Tensor, + camera: CameraModel, + crop_side_pixels: int, +) -> torch.Tensor: + """Launch ``_fisheye_perspective_crop_u8_kernel`` on CPU or CUDA.""" + if wp is None: + raise RuntimeError("warp is not installed") + wp.init() + + device = src_images.device + m_jobs = int(frame_indices.shape[0]) + src_h = int(src_images.shape[1]) + src_w = int(src_images.shape[2]) + + src_images_c = src_images.contiguous() + frame_indices_c = frame_indices.to(device=device, dtype=torch.int32).contiguous() + rotations_c = rotations.to(device=device, dtype=torch.float64).contiguous() + focal_lengths_c = focal_lengths.to(device=device, dtype=torch.float64).contiguous() + flip_x_c = flip_x.to(device=device, dtype=torch.int32).contiguous() + + out_crops = torch.empty( + (m_jobs, crop_side_pixels, crop_side_pixels, 3), + dtype=torch.uint8, + device=device, + ) + + if device.type == "cuda": + wp_device = wp.device_from_torch(device) + wp_stream = wp.stream_from_torch(torch.cuda.current_stream(device)) + else: + wp_device = "cpu" + wp_stream = None + + cam_args = _extract_camera_kernel_args(camera) + wp.launch( + _fisheye_perspective_crop_u8_kernel, + dim=(m_jobs, crop_side_pixels, crop_side_pixels), + inputs=[ + wp.from_torch(src_images_c, dtype=wp.uint8), + wp.from_torch(frame_indices_c, dtype=wp.int32), + wp.from_torch(rotations_c, dtype=wp.float64), + wp.from_torch(focal_lengths_c, dtype=wp.float64), + wp.from_torch(flip_x_c, dtype=wp.int32), + wp.int32(crop_side_pixels), + wp.int32(src_h), + wp.int32(src_w), + *cam_args, + ], + outputs=[wp.from_torch(out_crops, dtype=wp.uint8)], + device=wp_device, + stream=wp_stream, + record_tape=False, + ) + return out_crops + + +@torch.no_grad() +def _fisheye_perspective_crop_u8_torch( + src_images: torch.Tensor, + frame_indices: torch.Tensor, + rotations: torch.Tensor, + focal_lengths: torch.Tensor, + flip_x: torch.Tensor, + camera: CameraModel, + crop_side_pixels: int, +) -> torch.Tensor: + """Pure-PyTorch fallback matching ``_fisheye_perspective_crop_u8_kernel`` bit-for-bit.""" + device = src_images.device + m_jobs = int(frame_indices.shape[0]) + src_h = int(src_images.shape[1]) + src_w = int(src_images.shape[2]) + + out_crops = torch.empty( + (m_jobs, crop_side_pixels, crop_side_pixels, 3), + dtype=torch.uint8, + device=device, + ) + if m_jobs == 0: + return out_crops + + model_id = _FAST_CAMERA_MODEL_IDS[camera.model_name] + fx = float(camera.K[0, 0]) + fy = float(camera.K[1, 1]) + k_cx = float(camera.K[0, 2]) + k_cy = float(camera.K[1, 2]) + if isinstance(camera, _FisheyeCamera): + radial_poly = [float(c) for c in camera._radial_polynomial] + has_tp = bool(np.any(camera.tangential_prism)) + p0, p1, s0, s1, s2, s3 = (float(c) for c in camera.tangential_prism) + else: + radial_poly = [1.0] + has_tp = False + p0 = p1 = s0 = s1 = s2 = s3 = 0.0 + + coords = torch.arange(crop_side_pixels, dtype=torch.float64, device=device) + flipped_coords = float(crop_side_pixels - 1) - coords + center = (crop_side_pixels - 1) / 2.0 + + frame_indices_l = frame_indices.to(device=device, dtype=torch.int64) + rotations_d = rotations.to(device=device, dtype=torch.float64) + focals_d = focal_lengths.to(device=device, dtype=torch.float64) + flip_bool = flip_x.to(device=device) != 0 + + for start in range(0, m_jobs, _TORCH_CROP_SUBBATCH): + end = min(start + _TORCH_CROP_SUBBATCH, m_jobs) + b = end - start + f_sub = frame_indices_l[start:end] + r_sub = rotations_d[start:end] + foc_sub = focals_d[start:end] + flp_sub = flip_bool[start:end] + + gx = torch.where( + flp_sub[:, None], + flipped_coords[None, :].expand(b, crop_side_pixels), + coords[None, :].expand(b, crop_side_pixels), + ) + cx = (gx[:, None, :] - center) / foc_sub[:, None, None] + cy = (coords[None, :, None] - center) / foc_sub[:, None, None] + + rx = ( + cx * r_sub[:, 0, 0, None, None] + + cy * r_sub[:, 0, 1, None, None] + + r_sub[:, 0, 2, None, None] + ) + ry = ( + cx * r_sub[:, 1, 0, None, None] + + cy * r_sub[:, 1, 1, None, None] + + r_sub[:, 1, 2, None, None] + ) + rz = ( + cx * r_sub[:, 2, 0, None, None] + + cy * r_sub[:, 2, 1, None, None] + + r_sub[:, 2, 2, None, None] + ) + + valid_ray = ( + torch.isfinite(rx) & torch.isfinite(ry) & torch.isfinite(rz) & (rz > 0.0) + ) + + if model_id == _CAMERA_MODEL_PINHOLE: + safe_rz = torch.where(valid_ray, rz, torch.ones_like(rz)) + u = (rx / safe_rz) * fx + k_cx + v = (ry / safe_rz) * fy + k_cy + else: + ray_xy_norm = torch.hypot(rx, ry) + valid_ray = valid_ray & torch.isfinite(ray_xy_norm) + theta = torch.atan2(ray_xy_norm, rz) + distorted_r = theta * _horner_torch(theta * theta, radial_poly) + nonzero = ray_xy_norm > 0.0 + safe_norm = torch.where(nonzero, ray_xy_norm, torch.ones_like(ray_xy_norm)) + xd = torch.where( + nonzero, (rx / safe_norm) * distorted_r, torch.zeros_like(rx) + ) + yd = torch.where( + nonzero, (ry / safe_norm) * distorted_r, torch.zeros_like(ry) + ) + if has_tp: + dx, dy = _fisheye624_tangential_prism_offsets_torch( + xd, yd, p0, p1, s0, s1, s2, s3 + ) + xd = xd + dx + yd = yd + dy + u = xd * fx + k_cx + v = yd * fy + k_cy + + uf = u.to(torch.float32) + vf = v.to(torch.float32) + in_range = ( + valid_ray + & torch.isfinite(uf) + & torch.isfinite(vf) + & (uf >= -2.0) + & (uf <= float(src_w + 2)) + & (vf >= -2.0) + & (vf <= float(src_h + 2)) + ) + sentinel = torch.full_like(uf, -2.0) + uf = torch.where(in_range, uf, sentinel) + vf = torch.where(in_range, vf, sentinel) + + # torch.round uses IEEE round-to-nearest-even, matching cvRound / wp.rint. + iu = torch.round(uf * 32.0).to(torch.int64) + iv = torch.round(vf * 32.0).to(torch.int64) + x0 = iu >> 5 + y0 = iv >> 5 + fx_i = (iu & 31).to(torch.int32) + fy_i = (iv & 31).to(torch.int32) + x1 = x0 + 1 + y1 = y0 + 1 + + in_x0 = (x0 >= 0) & (x0 < src_w) + in_x1 = (x1 >= 0) & (x1 < src_w) + in_y0 = (y0 >= 0) & (y0 < src_h) + in_y1 = (y1 >= 0) & (y1 < src_h) + + x0c = x0.clamp(0, src_w - 1) + x1c = x1.clamp(0, src_w - 1) + y0c = y0.clamp(0, src_h - 1) + y1c = y1.clamp(0, src_h - 1) + + f_idx = f_sub[:, None, None] + zeros_pix = torch.zeros( + (b, crop_side_pixels, crop_side_pixels, 3), + dtype=torch.int32, + device=device, + ) + + p00 = torch.where( + (in_y0 & in_x0)[..., None], + src_images[f_idx, y0c, x0c].to(torch.int32), + zeros_pix, + ) + p01 = torch.where( + (in_y0 & in_x1)[..., None], + src_images[f_idx, y0c, x1c].to(torch.int32), + zeros_pix, + ) + p10 = torch.where( + (in_y1 & in_x0)[..., None], + src_images[f_idx, y1c, x0c].to(torch.int32), + zeros_pix, + ) + p11 = torch.where( + (in_y1 & in_x1)[..., None], + src_images[f_idx, y1c, x1c].to(torch.int32), + zeros_pix, + ) + + w00 = ((32 - fx_i) * (32 - fy_i))[..., None] + w01 = (fx_i * (32 - fy_i))[..., None] + w10 = ((32 - fx_i) * fy_i)[..., None] + w11 = (fx_i * fy_i)[..., None] + + bgr = ((p00 * w00 + p01 * w01 + p10 * w10 + p11 * w11 + 512) >> 10).to( + torch.uint8 + ) + out_crops[start:end] = bgr[..., [2, 1, 0]] + + return out_crops + + +def _crop_fallback_opencv( + images_bgr_chunk: Sequence[np.ndarray] | Mapping[Any, np.ndarray] | None, + images_bgr_gpu: torch.Tensor | None, + raw_frame_indices: list[Any], + valid_indices: np.ndarray, + params_list: list[dict[str, Any] | None], + camera: CameraModel, + crop_side_pixels: int, +) -> list[np.ndarray]: + """CPU OpenCV fallback for non-fast camera models (e.g., RATIONAL_POLYNOMIAL).""" + crops: list[np.ndarray] = [] + for job_i in valid_indices: + params = params_list[int(job_i)] + assert params is not None + f_idx = raw_frame_indices[int(job_i)] + if images_bgr_chunk is not None: + image_bgr = images_bgr_chunk[f_idx] + else: + assert images_bgr_gpu is not None + image_bgr = images_bgr_gpu[int(f_idx)].detach().cpu().numpy() + remap_pixels = create_perspective_remap( + camera, + params["crop_to_source_rotation"], + params["focal_length"], + crop_side_pixels, + ) + crop_bgr = cv2.remap( + image_bgr, + remap_pixels, + None, + interpolation=cv2.INTER_LINEAR, + borderMode=cv2.BORDER_CONSTANT, + borderValue=0, + ) + crop_rgb = cv2.cvtColor(crop_bgr, cv2.COLOR_BGR2RGB) + if params["is_right"]: + crop_rgb = np.ascontiguousarray(crop_rgb[:, ::-1]) + crops.append(crop_rgb) + return crops + + +def _unpack_crop_job( + job: tuple[Any, str, str, np.ndarray] | Mapping[str, Any], +) -> tuple[Any, str, str, np.ndarray]: + """Normalize a crop job tuple or dict to ``(frame_idx, image_id, hand, bbox)``.""" + if isinstance(job, Mapping): + frame_idx = job["frame_idx"] + image_id = job["image_id"] + hand = job.get("hand", job.get("real_hand_side")) + bbox = job.get("bbox", job.get("bbx_xys")) + if hand is None or bbox is None: + raise ValueError("Crop job dict must provide 'hand' and 'bbox'") + return frame_idx, image_id, str(hand), np.asarray(bbox, dtype=np.float64) + if len(job) != 4: + raise ValueError( + "Each crop job must be a 4-tuple (frame_idx, image_id, hand, bbox) or dict" + ) + frame_idx, image_id, hand, bbox = job + return frame_idx, image_id, str(hand), np.asarray(bbox, dtype=np.float64) + + +def crop_chunk_gpu( + images_bgr_chunk: Sequence[np.ndarray] | Mapping[Any, np.ndarray] | None, + crop_jobs_in_chunk: Sequence[tuple[Any, str, str, np.ndarray] | Mapping[str, Any]], + camera: CameraModel, + crop_side_pixels: int = IMG_SIZE, + *, + camera_mode: str = "sam3db_perspective", + device: str | torch.device = "cuda", + images_bgr_gpu: torch.Tensor | None = None, + return_gpu_crops: bool = False, + use_warp: bool | None = None, +) -> tuple[list[dict[str, Any]], list[np.ndarray] | torch.Tensor, int]: + """Produce perspective RGB uint8 hand crops and metadata records for a frame chunk. + + Uploads each unique active frame in the chunk at most once (or reuses + ``images_bgr_gpu`` when already uploaded on ``device``), computes batched + virtual-camera geometry, executes the fused Warp kernel (on CUDA) or + bit-exact pure-PyTorch fallback (on CPU), and returns ``(records, crops_u8, + num_failed)`` with metadata matching ``EgoHandPredictor``'s perspective + crop record schema. + + Args: + images_bgr_chunk: Sequence (or mapping) of ``(H, W, 3)`` uint8 BGR + frames for the chunk. May be ``None`` when ``images_bgr_gpu`` is + supplied and ``camera`` is PINHOLE, KB4, or FISHEYE624. + crop_jobs_in_chunk: Sequence of ``(frame_idx, image_id, hand, bbox)`` + tuples (or dicts with those keys) in model job order. + camera: Source ``CameraModel`` shared across the chunk. + crop_side_pixels: Square output crop side length in pixels. + camera_mode: Checkpoint camera parameterization (accepted for API + parity with ``build_crop_record``). + device: Torch device (``"cuda"`` or ``"cpu"``). + images_bgr_gpu: Optional pre-uploaded ``(T, H, W, 3)`` uint8 BGR tensor + on ``device`` indexed by each job's ``frame_idx``. + return_gpu_crops: If ``True``, return the ``(M, side, side, 3)`` uint8 + RGB tensor on ``device`` directly instead of copying to CPU numpy. + use_warp: Override backend selection. ``None`` uses Warp on CUDA (when + installed) and pure-PyTorch on CPU; ``True`` forces Warp; ``False`` + forces pure-PyTorch. + + Returns: + Tuple ``(records, crops_u8, num_failed)`` where: + - ``records``: Valid crop metadata dicts in job order (matching + ``build_crop_record`` without ``crop_tensor``). + - ``crops_u8``: List of ``(side, side, 3)`` uint8 RGB numpy arrays (or + a ``(M, side, side, 3)`` uint8 torch tensor when ``return_gpu_crops`` + is ``True``). + - ``num_failed``: Count of jobs rejected by perspective-crop validity + checks. + """ + _ = camera_mode # Perspective cropping always mirrors with full-image horizontal flip. + torch_device = torch.device(device) + n_jobs = len(crop_jobs_in_chunk) + if n_jobs == 0: + empty_crops: list[np.ndarray] | torch.Tensor = ( + torch.empty( + (0, crop_side_pixels, crop_side_pixels, 3), + dtype=torch.uint8, + device=torch_device, + ) + if return_gpu_crops + else [] + ) + return [], empty_crops, 0 + + raw_frame_indices: list[Any] = [] + image_ids: list[str] = [] + hands: list[str] = [] + bboxes_list: list[np.ndarray] = [] + for job in crop_jobs_in_chunk: + f_idx, img_id, hand, bbox = _unpack_crop_job(job) + raw_frame_indices.append(f_idx) + image_ids.append(img_id) + hands.append(hand) + bboxes_list.append(bbox) + bboxes_arr = np.stack(bboxes_list, axis=0) + + ( + params_list, + valid_indices, + valid_rotations, + valid_focals, + flip_x_np, + ) = compute_perspective_crop_params_batch( + bboxes_arr, hands, camera, crop_side_pixels, torch_device + ) + + m_valid = len(valid_indices) + num_failed = n_jobs - m_valid + if num_failed > 0: + for idx, params in enumerate(params_list): + if params is None: + log.warning( + "[Skip] %s %s: perspective cropping failed (invalid ROI)", + image_ids[idx], + hands[idx], + ) + + if m_valid == 0: + empty_crops = ( + torch.empty( + (0, crop_side_pixels, crop_side_pixels, 3), + dtype=torch.uint8, + device=torch_device, + ) + if return_gpu_crops + else [] + ) + return [], empty_crops, num_failed + + records: list[dict[str, Any]] = [] + for job_i in valid_indices: + idx = int(job_i) + params = params_list[idx] + assert params is not None + records.append( + { + "image_id": image_ids[idx], + "real_hand_side": hands[idx], + "model_bbx_xys": params["model_bbx_xys"], + "model_K": params["model_K"], + "model_img_size": params["model_img_size"], + "output_bbx_xys": params["output_bbx_xys"], + "output_K": params["output_K"], + "crop_to_source_camera_rotation": params["crop_to_source_rotation"], + } + ) + + if getattr(camera, "model_name", None) not in _FAST_CAMERA_MODEL_IDS: + crops_list = _crop_fallback_opencv( + images_bgr_chunk, + images_bgr_gpu, + raw_frame_indices, + valid_indices, + params_list, + camera, + crop_side_pixels, + ) + if return_gpu_crops: + crops_tensor = torch.from_numpy(np.stack(crops_list, axis=0)).to( + device=torch_device, dtype=torch.uint8 + ) + return records, crops_tensor, num_failed + return records, crops_list, num_failed + + if images_bgr_gpu is not None: + if ( + images_bgr_gpu.ndim != 4 + or images_bgr_gpu.shape[-1] != 3 + or images_bgr_gpu.dtype != torch.uint8 + ): + raise ValueError( + "images_bgr_gpu must be a (T, H, W, 3) uint8 tensor, " + f"got shape={tuple(images_bgr_gpu.shape)} dtype={images_bgr_gpu.dtype}" + ) + num_gpu_frames = int(images_bgr_gpu.shape[0]) + kernel_frame_indices_np = np.asarray( + [int(raw_frame_indices[int(job_i)]) for job_i in valid_indices], + dtype=np.int32, + ) + if kernel_frame_indices_np.size and ( + int(kernel_frame_indices_np.min()) < 0 + or int(kernel_frame_indices_np.max()) >= num_gpu_frames + ): + raise IndexError( + f"frame_idx out of bounds for images_bgr_gpu with {num_gpu_frames} frame(s)" + ) + src_images_t = images_bgr_gpu.to(device=torch_device).contiguous() + else: + if images_bgr_chunk is None: + raise ValueError( + "Either images_bgr_chunk or images_bgr_gpu must be provided" + ) + unique_frame_map: dict[Any, int] = {} + unique_frames: list[np.ndarray] = [] + kernel_frame_indices_np = np.empty(m_valid, dtype=np.int32) + for k, job_i in enumerate(valid_indices): + f_idx = raw_frame_indices[int(job_i)] + u_idx = unique_frame_map.get(f_idx) + if u_idx is None: + u_idx = len(unique_frames) + unique_frame_map[f_idx] = u_idx + unique_frames.append(np.ascontiguousarray(images_bgr_chunk[f_idx])) + kernel_frame_indices_np[k] = u_idx + stacked_np = np.stack(unique_frames, axis=0) + src_images_t = torch.from_numpy(stacked_np) + if torch_device.type == "cuda": + src_images_t = src_images_t.to(device=torch_device, non_blocking=True) + else: + src_images_t = src_images_t.to(device=torch_device) + + frame_indices_t = torch.from_numpy(kernel_frame_indices_np).to(device=torch_device) + rotations_t = torch.from_numpy(valid_rotations).to(device=torch_device) + focals_t = torch.from_numpy(valid_focals).to(device=torch_device) + flip_x_t = torch.from_numpy(flip_x_np).to(device=torch_device) + + should_use_warp = ( + (torch_device.type == "cuda" and wp is not None) + if use_warp is None + else bool(use_warp) + ) + if should_use_warp: + if wp is None: + raise RuntimeError("use_warp=True requested, but warp is not installed") + crops_tensor = _launch_warp_perspective_crop( + src_images_t, + frame_indices_t, + rotations_t, + focals_t, + flip_x_t, + camera, + crop_side_pixels, + ) + else: + crops_tensor = _fisheye_perspective_crop_u8_torch( + src_images_t, + frame_indices_t, + rotations_t, + focals_t, + flip_x_t, + camera, + crop_side_pixels, + ) + + if return_gpu_crops: + return records, crops_tensor, num_failed + + crops_cpu = crops_tensor.detach().cpu().numpy() + crops_list = [crops_cpu[i] for i in range(m_valid)] + return records, crops_list, num_failed + + +def supports_gpu_perspective_crop(camera: Any) -> bool: + """Return True when ``camera`` uses a model accelerated by ``crop_chunk_gpu``.""" + return getattr(camera, "model_name", None) in _FAST_CAMERA_MODEL_IDS + + +__all__ = [ + "compute_perspective_crop_params_batch", + "crop_chunk_gpu", + "fisheye_unproject_torch", + "supports_gpu_perspective_crop", +] diff --git a/src/python/isaaccapture_egopost/inference/cli.py b/src/python/isaaccapture_egopost/inference/cli.py index a772fed6a8..737311be33 100644 --- a/src/python/isaaccapture_egopost/inference/cli.py +++ b/src/python/isaaccapture_egopost/inference/cli.py @@ -13,14 +13,18 @@ ) -def _bundled_default(env_var): - """Path named by ``env_var`` if that file exists, else None (flag stays unset). +def _bundled_default(env_var: str, *, allow_dir: bool = False) -> str | None: + """Path named by ``env_var`` if it exists, else None (flag stays unset). - Lets an image bundle a default checkpoint / detector config: the image sets the - variable, and an explicit flag or a mounted replacement file still wins. + Lets an image bundle a default checkpoint or detector config while still + letting an explicit flag or mounted replacement win. """ path = os.environ.get(env_var) - return path if path and os.path.isfile(path) else None + if not path: + return None + if os.path.isfile(path) or (allow_dir and os.path.isdir(path)): + return path + return None def parse_args(argv=None, *, epilog: str | None = None): @@ -32,12 +36,23 @@ def parse_args(argv=None, *, epilog: str | None = None): p.add_argument("--input", required=True, help="MP4 file or folder of MP4 files") p.add_argument( "--egohand_ckpt", - default=_bundled_default("EGOHAND_DEFAULT_CKPT"), - help="EgoHand checkpoint (.ckpt). Default: the file named by " + default=_bundled_default("EGOHAND_DEFAULT_CKPT", allow_dir=True), + help="EgoHand checkpoint (.ckpt), or an inference-weights folder written by " + "inference/scripts/export_inference_weights.py (model.safetensors + " + "config.json; faster to load, no pickle). Default: the path named by " "$EGOHAND_DEFAULT_CKPT if it exists (bundled in the release image), otherwise downloaded from " "the nvidia/EgoHand-v1 HF repo (see --egohand_ckpt_hf_path) and cached locally -- " "pass an explicit path to use a local checkpoint instead.", ) + p.add_argument( + "--background_model_load", + action=argparse.BooleanOptionalAction, + default=True, + help="Load the EgoHand checkpoint on a worker thread while frames are " + "decoded and 2D boxes detected; the first EgoHand forward waits for it. " + "Results are unchanged. Default: on. Pass --no-background_model_load " + "to load synchronously before detection.", + ) p.add_argument( "--egohand_ckpt_hf_path", default="egohand_s060000.ckpt", @@ -100,6 +115,27 @@ def parse_args(argv=None, *, epilog: str | None = None): "one-off runs, since torch.compile warm-up cost may exceed the " "savings. Off by default, so it has no effect unless passed.", ) + p.add_argument( + "--soma_batch_size", + type=int, + default=0, + help="Run the SOMA hand layer once per this many crops instead of once " + "per --batch_size batch: the left-hand layer per soma_batch_size // " + "batch_size batches, the right-hand mirror per at most this many right " + "hands, each call padded to this size. 0 (default) keeps one call per " + "batch. Only float32 rounding changes (batched-product reduction " + "order). Must be 0 or at least --batch_size; 512 is a good value.", + ) + p.add_argument( + "--mhr_presorted_sparse", + action=argparse.BooleanOptionalAction, + default=True, + help="Build the sparse matrix of the MHR hand model's pose correctives " + "once at load, already coalesced, instead of letting every SOMA call " + "sort it again. The per-call sort can crash with PyTorch builds for " + "CUDA 13.0 on sm_90+ GPUs (NVIDIA/cccl#5297). Results are unchanged. " + "Default: on. Pass --no-mhr_presorted_sparse to keep the per-call sort.", + ) p.add_argument( "--postprocessing_smooth", action=argparse.BooleanOptionalAction, @@ -221,6 +257,8 @@ def parse_args(argv=None, *, epilog: str | None = None): p.error("--frame_batch_size must be positive") if args.max_seconds is not None and not 0 < args.max_seconds < float("inf"): p.error("--max_seconds must be positive and finite") + if args.soma_batch_size < 0 or 0 < args.soma_batch_size < args.batch_size: + p.error("--soma_batch_size must be 0 or at least --batch_size") if not 0 <= args.qc_max_bad_frac <= 1: p.error("--qc_max_bad_frac must be between 0 and 1") if args.postprocessing_qc: diff --git a/src/python/isaaccapture_egopost/inference/hand_detector_2d/rtdetr/PILLOW_LICENSE_NOTICE b/src/python/isaaccapture_egopost/inference/hand_detector_2d/rtdetr/PILLOW_LICENSE_NOTICE new file mode 100644 index 0000000000..9a5a9a6d99 --- /dev/null +++ b/src/python/isaaccapture_egopost/inference/hand_detector_2d/rtdetr/PILLOW_LICENSE_NOTICE @@ -0,0 +1,37 @@ +The fixed-point resize implementation in pillow_exact_cuda.py is derived from +the uint8 resampling semantics in Pillow (12.1.1 / 13.0.0) +src/libImaging/Resample.c. + +The Python Imaging Library (PIL) is + + Copyright © 1997-2011 by Secret Labs AB + Copyright © 1995-2011 by Fredrik Lundh and contributors + +Pillow is the friendly PIL fork. It is + + Copyright © 2010 by Jeffrey A. Clark and contributors + +Like PIL, Pillow is licensed under the open source MIT-CMU License: + +By obtaining, using, and/or copying this software and/or its associated +documentation, you agree that you have read, understood, and will comply +with the following terms and conditions: + +Permission to use, copy, modify and distribute this software and its +documentation for any purpose and without fee is hereby granted, +provided that the above copyright notice appears in all copies, and that +both that copyright notice and this permission notice appear in supporting +documentation, and that the name of Secret Labs AB or the author not be +used in advertising or publicity pertaining to distribution of the software +without specific, written prior permission. + +SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS +SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. +IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR BE LIABLE FOR ANY SPECIAL, +INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE +OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. + +Upstream source: +https://github.com/python-pillow/Pillow/blob/13.0.0/src/libImaging/Resample.c diff --git a/src/python/isaaccapture_egopost/inference/hand_detector_2d/rtdetr/detector.py b/src/python/isaaccapture_egopost/inference/hand_detector_2d/rtdetr/detector.py index 49aeea39cc..2f3f8821ea 100644 --- a/src/python/isaaccapture_egopost/inference/hand_detector_2d/rtdetr/detector.py +++ b/src/python/isaaccapture_egopost/inference/hand_detector_2d/rtdetr/detector.py @@ -30,6 +30,9 @@ import dataclasses import json import logging +import os +import threading +from concurrent.futures import ThreadPoolExecutor from math import log1p from pathlib import Path @@ -49,9 +52,15 @@ ) log = logging.getLogger(__name__) +# Guards lazy creation of per-instance locks on object.__new__ test stubs. +_INIT_LOCK = threading.Lock() DEFAULT_SCORE_THR = 0.5 DEFAULT_BATCH_SIZE = 8 +# Threads for the per-frame CPU preprocessing (cvtColor, PIL resize to 640). Pillow +# and OpenCV release the GIL in these calls, so frames are resized in parallel; the +# same per-frame function runs either way, so the network input is unchanged. +DEFAULT_PREPROCESS_THREADS = 8 # Reject boxes whose side is at most one pixel. MIN_VALID_BOX_SIZE = 1.0 @@ -253,6 +262,10 @@ class RTDetrHandBBoxDetector: providers: Explicit onnxruntime providers, overriding ``device``. smoothing: Optional native-track post-filter. Requires complete clips and frame timestamps in run(). + preprocess_threads: Worker threads that preprocess frames (BGR->RGB, + PIL resize to 640) while ONNX Runtime runs the previous batch. + ``None`` uses ``min(DEFAULT_PREPROCESS_THREADS, os.cpu_count())``; + 1 runs the sequential loop. Network input is identical either way. """ # run() writes to output_paths_per_hand when given one. @@ -272,6 +285,7 @@ def __init__( drop_gap_filled: bool = False, providers: list | None = None, smoothing: BBoxSmoothingConfig | None = None, + preprocess_threads: int | None = None, ): if smoothing is not None and not use_tracker: raise ValueError("BBox smoothing requires use_tracker=True") @@ -286,6 +300,13 @@ def __init__( from .onnx_model import HandDetector self.batch_size = max(1, int(batch_size)) + if preprocess_threads is None: + preprocess_threads = min(DEFAULT_PREPROCESS_THREADS, os.cpu_count() or 1) + self.preprocess_threads = max(1, int(preprocess_threads)) + # ORT batch sizes already run by this session (cuDNN algorithms chosen). + self._ort_batch_sizes_run: set[int] = set() + self._pipeline_lock = threading.Lock() + self._cuda_executor: ThreadPoolExecutor | None = None self.padding = padding self.use_tracker = use_tracker self.enforce_lr_order = enforce_lr_order @@ -352,6 +373,7 @@ def __init__( providers=providers if providers is not None else _providers_for_device(device), + cuda_batch_size=self.batch_size, **detector_kwargs, ) log.info("[RTDetr] onnxruntime providers: %s", self.detector.providers) @@ -381,8 +403,116 @@ def detect_frames(self, images_bgr) -> list: """ return self._detect_per_frame(images_bgr) + def _get_pipeline_lock(self) -> threading.Lock: + """Return the per-instance pipeline lock, creating it lazily if needed.""" + lock = getattr(self, "_pipeline_lock", None) + if lock is None: + with _INIT_LOCK: + lock = getattr(self, "_pipeline_lock", None) + if lock is None: + lock = threading.Lock() + self._pipeline_lock = lock + return lock + + def _get_cuda_executor(self) -> ThreadPoolExecutor: + """Return the persistent single-worker ORT executor (caller holds pipeline lock).""" + executor = getattr(self, "_cuda_executor", None) + if executor is None: + executor = ThreadPoolExecutor( + max_workers=1, thread_name_prefix="rtdetr-onnx" + ) + self._cuda_executor = executor + return executor + + def close(self) -> None: + """Shut down the persistent CUDA inference worker thread, if started.""" + with self._get_pipeline_lock(): + executor = getattr(self, "_cuda_executor", None) + if executor is not None: + self._cuda_executor = None + executor.shutdown(wait=True) + + def __del__(self) -> None: + executor = getattr(self, "_cuda_executor", None) + if executor is not None: + self._cuda_executor = None + try: + executor.shutdown(wait=False) + except Exception: + pass + def _detect_per_frame(self, images_bgr) -> list: - """Run the ONNX detector over every frame, in ``batch_size`` chunks.""" + """Run the ONNX detector over every frame in ``batch_size`` chunks. + + When the underlying ``HandDetector`` enables its CUDA input pipeline, + runs the 2-slot double-buffered GPU preprocessing + ORT I/O Binding + path. Otherwise delegates to ``_detect_per_frame_threaded`` when + ``preprocess_threads > 1`` and the detector exposes + ``detect_preprocessed``, or falls back to ``_detect_per_frame_legacy``. + """ + if not images_bgr: + return [] + + if getattr(self.detector, "cuda_input_enabled", False): + return self._detect_per_frame_cuda(images_bgr) + + if self.preprocess_threads > 1 and hasattr( + self.detector, "detect_preprocessed" + ): + return self._detect_per_frame_threaded(images_bgr) + + return self._detect_per_frame_legacy(images_bgr) + + def _detect_per_frame_cuda(self, images_bgr) -> list: + """Run the 2-slot double-buffered CUDA upload + ORT I/O Binding pipeline.""" + batches = [ + images_bgr[start : start + self.batch_size] + for start in range(0, len(images_bgr), self.batch_size) + ] + if not batches: + return [] + + frame_shapes = {tuple(image.shape) for batch in batches for image in batch} + fixed_slots = len(frame_shapes) == 1 + + def prepare(batch, batch_index): + slot_index = batch_index % 2 if fixed_slots else None + return self.detector.prepare_bgr_batch_async(batch, slot_index=slot_index) + + def infer(prepared): + outputs = self.detector.run_onnx_prepared(prepared) + return self.detector.postprocess(*outputs, prepared.orig_target_sizes_cpu) + + detections = [] + with self._get_pipeline_lock(): + if fixed_slots: + self.detector.initialize_cuda_slots( + self.batch_size, next(iter(frame_shapes)) + ) + executor = self._get_cuda_executor() + prepared = prepare(batches[0], 0) + for batch_index in range(len(batches)): + future = executor.submit(infer, prepared) + next_prepared = None + try: + if batch_index + 1 < len(batches): + next_prepared = prepare( + batches[batch_index + 1], batch_index + 1 + ) + except BaseException: + # Wait for the in-flight ORT job before releasing the + # pipeline lock so no worker touches buffers concurrently. + try: + future.result() + except Exception: + pass + raise + detections.extend(future.result()) + prepared = next_prepared + return detections + + def _detect_per_frame_legacy(self, images_bgr) -> list: + """Preserve the original sequential CPU/Pillow preprocessing loop.""" import cv2 from PIL import Image @@ -398,6 +528,57 @@ def _detect_per_frame(self, images_bgr) -> list: detections.extend(self.detector.detect_batch(pil_chunk)) return detections + def _detect_per_frame_threaded(self, images_bgr) -> list: + """``_detect_per_frame`` with preprocessing in a pool, one chunk ahead.""" + from .onnx_model import HandDetector + + import cv2 + from PIL import Image + + preprocess_fn = getattr(self.detector, "_preprocess", HandDetector._preprocess) + + def frame_input(image): + pil = Image.fromarray( + cv2.cvtColor(np.ascontiguousarray(image), cv2.COLOR_BGR2RGB) + ) + return preprocess_fn(pil), pil.size + + chunks = [ + images_bgr[start : start + self.batch_size] + for start in range(0, len(images_bgr), self.batch_size) + ] + # ORT picks cuDNN algorithms by timing them the first time it sees a + # batch size; that run gets the machine to itself, as in the + # sequential loop. + seen = self._ort_batch_sizes_run + detections = [] + with ThreadPoolExecutor( + max_workers=self.preprocess_threads, thread_name_prefix="rtdetr-pre" + ) as pool: + + def submit(chunk): + return [pool.submit(frame_input, image) for image in chunk] + + pending = submit(chunks[0]) + for index in range(len(chunks)): + prepared = [future.result() for future in pending] + has_next = index + 1 < len(chunks) + first_run = len(prepared) not in seen + if has_next and not first_run: + pending = submit( + chunks[index + 1] + ) # runs while ORT runs this chunk + sizes = np.array([size for _, size in prepared], dtype=np.int64) + detections.extend( + self.detector.detect_preprocessed( + [array for array, _ in prepared], sizes + ) + ) + seen.add(len(prepared)) + if has_next and first_run: + pending = submit(chunks[index + 1]) + return detections + def run( self, image_ids, @@ -568,6 +749,9 @@ class RTDetrConfig: bbox_size_alpha_shrink: Shrink EMA weight at 20 fps, in (0, 1]. bbox_max_size_change: Maximum fractional growth per 20-fps interval. Contraction uses the reciprocal ratio; resets are exempt. + preprocess_threads: Threads for the per-frame CPU preprocessing, run + one batch ahead of ONNX Runtime. None = min(8, CPU count); 1 = the + sequential loop. Does not change the detections. """ weights: str | None = None @@ -582,6 +766,7 @@ class RTDetrConfig: bbox_size_alpha_grow: float = 0.12 bbox_size_alpha_shrink: float = 0.06 bbox_max_size_change: float = 0.01 + preprocess_threads: int | None = None @classmethod def from_spec(cls, spec: str) -> "RTDetrConfig": @@ -643,6 +828,13 @@ def _validate(cls, config: "RTDetrConfig", *, prefix: str): config.smoothing_config() if config.batch_size < 1: raise ValueError(f"{prefix} batch_size={config.batch_size} must be >= 1") + threads = config.preprocess_threads + if threads is not None and ( + isinstance(threads, bool) or not isinstance(threads, int) or threads < 1 + ): + raise ValueError( + f"{prefix} preprocess_threads={threads!r} must be an integer >= 1" + ) @staticmethod def _coerce(key: str, raw: str, annotation): @@ -724,4 +916,5 @@ def build(self, *, device: str, tracking: bool = False): enforce_lr_order=self.lr_order, drop_gap_filled=self.drop_gap_filled, smoothing=self.smoothing_config() if self.bbox_smoothing else None, + preprocess_threads=self.preprocess_threads, ) diff --git a/src/python/isaaccapture_egopost/inference/hand_detector_2d/rtdetr/onnx_model.py b/src/python/isaaccapture_egopost/inference/hand_detector_2d/rtdetr/onnx_model.py index e8f4ec1518..0950c924da 100644 --- a/src/python/isaaccapture_egopost/inference/hand_detector_2d/rtdetr/onnx_model.py +++ b/src/python/isaaccapture_egopost/inference/hand_detector_2d/rtdetr/onnx_model.py @@ -8,11 +8,15 @@ surface is kept: the CLI, the video reader, and the PIL drawing helpers are dropped because EgoHand feeds already-decoded frames and renders overlays itself. -No PyTorch and no RT-DETR source tree are required -- just ``onnxruntime`` + -``numpy`` + ``Pillow``. ``onnxruntime-gpu`` is pinned in requirements.txt, but this module is still -imported lazily (see ``detector.py``) so a checkout without it -- a bare dev env, -or an image built before the pin landed -- can still import the rest of the -package and run with ground-truth or saved boxes. +When both ``CUDAExecutionProvider`` and PyTorch CUDA are available, the CUDA +BGR-frame path uses a Pillow-exact GPU preprocessor and ONNX Runtime I/O +Binding to avoid copying the resized image tensor back through host memory. +PyTorch remains optional (for example in the standalone ``Dockerfile.detector`` +image): if PyTorch or PyTorch CUDA is absent, ``cuda_input_enabled`` stays +``False`` and execution cleanly uses the Pillow/NumPy CPU preprocessing path. +``onnxruntime-gpu`` is pinned in requirements.txt, and this module is still +imported lazily (see ``detector.py``) so a checkout without it can still import +the rest of the package and run with ground-truth or saved boxes. Class ids come from the training config (``num_classes: 3``, index 0 unused): 1 = ``left_hand``, 2 = ``right_hand``, anatomical to the *wearer* rather than @@ -24,13 +28,14 @@ import logging from dataclasses import asdict, dataclass from pathlib import Path +from typing import Any import numpy as np from PIL import Image log = logging.getLogger(__name__) -__all__ = ["Detection", "HandDetector", "LABELS", "refine_box"] +__all__ = ["Detection", "HandDetector", "LABELS", "PreparedBatch", "refine_box"] LABELS = {1: "left_hand", 2: "right_hand"} # Maps the ONNX class id onto the hand-side strings EgoHand uses everywhere else. @@ -118,6 +123,42 @@ def as_dict(self) -> dict: return d +@dataclass +class PreparedBatch: + """Raw CUDA inputs plus the CPU staging storage used to create them. + + CUDA batches retain pinned CPU tensors until their asynchronous H2D + copies complete. ``h2d_ready_event`` establishes the dependency between + the copy and preprocessing streams. + """ + + raw_images: Any + orig_target_sizes: Any + orig_target_sizes_cpu: np.ndarray + h2d_ready_event: Any + host_staging: tuple[Any, ...] + slot: Any = None + + def wait(self) -> None: + """Synchronize only this batch's H2D completion event.""" + self.h2d_ready_event.synchronize() + + +@dataclass +class _CudaInputSlot: + """Reusable page-locked host and CUDA storage for one in-flight batch.""" + + host_images: Any + cuda_images: Any + host_sizes: Any + cuda_sizes: Any + h2d_ready_event: Any + consume_done_event: Any + preprocess_ready_event: Any + has_h2d_event: bool = False + has_consume_event: bool = False + + def refine_box( xyxy, img_w: float, @@ -187,6 +228,10 @@ class HandDetector: square: expand the shorter side so the box is square. min_size: enforce a minimum box side in pixels. clip: keep boxes inside the image. + cuda_batch_size: Configured detector batch D. CUDA execution uses a + static compiled resize graph for full B=D batches (unless + ``EGOHAND_RUNTIME_PROFILE=release``) and the same Pillow-exact + eager implementation for an arbitrary B None: + """Allocate the two fixed host/device buffers used by CUDA input. + + Allocation happens before B0 starts, keeping both pinned-host allocation + and CUDA allocation out of the steady-state A(N+1) submission path. + """ + if not self.cuda_input_enabled: + return + if len(image_shape) != 3: + raise ValueError(f"expected HWC images, got shape {image_shape}") + + import torch + + shape_key = (int(max_batch_size), *map(int, image_shape)) + if ( + self._cuda_preprocessor is None + or max_batch_size != self._cuda_preprocessor.full_batch_size + ): + raise RuntimeError( + "CUDA input slot batch must match the configured exact " + f"preprocessor batch, got slot={max_batch_size} and " + f"preprocessor={getattr(self._cuda_preprocessor, 'full_batch_size', None)}" + ) + if self._cuda_slot_shape == shape_key: + return + if self._cuda_slot_shape is not None: + self.copy_stream.synchronize() + self.inference_stream.synchronize() + + device = torch.device("cuda", self.cuda_device_id) + slots = [] + with torch.cuda.device(self.cuda_device_id): + for _ in range(2): + slots.append( + _CudaInputSlot( + host_images=torch.empty( + shape_key, dtype=torch.uint8, pin_memory=True + ), + cuda_images=torch.empty( + shape_key, dtype=torch.uint8, device=device + ), + host_sizes=torch.empty( + (max_batch_size, 2), dtype=torch.int64, pin_memory=True + ), + cuda_sizes=torch.empty( + (max_batch_size, 2), dtype=torch.int64, device=device + ), + h2d_ready_event=torch.cuda.Event(), + consume_done_event=torch.cuda.Event(), + preprocess_ready_event=torch.cuda.Event(), + ) + ) + self._cuda_slots = slots + self._cuda_slot_shape = shape_key + log.info( + "[RTDetr] allocated 2 CUDA input slots: max_batch=%d image_shape=%s " + "(page-locked host staging + fixed device buffers)", + max_batch_size, + image_shape, + ) + @staticmethod def _preprocess(img: Image.Image) -> np.ndarray: """Resize to 640x640 and scale to [0,1] CHW float32. @@ -258,13 +457,388 @@ def _preprocess(img: Image.Image) -> np.ndarray: ) return arr.transpose(2, 0, 1)[None] # 1,3,H,W - def _run(self, batch: np.ndarray, sizes: np.ndarray) -> list[list[Detection]]: - labels, boxes, scores = self.session.run( - ["labels", "boxes", "scores"], - {"images": batch, "orig_target_sizes": sizes}, + @classmethod + def _preprocess_pil_batch( + cls, images: list[Image.Image] + ) -> tuple[np.ndarray, np.ndarray]: + """Convert RGB PIL images into the two CPU arrays consumed by ONNX.""" + batch = np.concatenate([cls._preprocess(image) for image in images], axis=0) + sizes = np.array( + [[image.size[0], image.size[1]] for image in images], dtype=np.int64 + ) + return batch, sizes + + @classmethod + def _preprocess_bgr_batch_cpu( + cls, images_bgr: list[np.ndarray] + ) -> tuple[np.ndarray, np.ndarray]: + """Build CPU ONNX inputs from decoded OpenCV BGR frames. + + This owns the complete image preprocessing boundary: contiguous BGR, + BGR-to-RGB conversion, PIL wrapping, bilinear resize to 640x640, + float32 scaling to [0, 1], HWC-to-CHW conversion, and batch stacking. + + Returns: + images: C-contiguous float32 array shaped ``(B, 3, 640, 640)``. + orig_target_sizes: int64 array shaped ``(B, 2)`` in ``(width, height)`` order. + """ + import cv2 + + pil_images = [ + Image.fromarray( + cv2.cvtColor(np.ascontiguousarray(image), cv2.COLOR_BGR2RGB) + ) + for image in images_bgr + ] + return cls._preprocess_pil_batch(pil_images) + + def prepare_bgr_batch_async( + self, images_bgr: list[np.ndarray], slot_index: int | None = None + ) -> PreparedBatch: + """Stage decoded BGR frames and submit only H2D copies. + + The raw uint8 NHWC BGR data is copied from pinned staging memory on the + dedicated copy stream. All GPU preprocessing is deliberately deferred + to the inference stream. No device-wide synchronization is performed. + """ + if not images_bgr: + raise ValueError("prepare_bgr_batch_async requires at least one image") + + if not self.cuda_input_enabled or self.copy_stream is None: + raise RuntimeError("asynchronous H2D preparation requires the CUDA path") + + if slot_index is not None: + return self._prepare_bgr_batch_in_slot(images_bgr, slot_index) + + import torch + + device = torch.device("cuda", self.cuda_device_id) + sizes_cpu = np.asarray( + [[image.shape[1], image.shape[0]] for image in images_bgr], + dtype=np.int64, + ) + sizes_host = torch.from_numpy(sizes_cpu).pin_memory() + host_staging = [sizes_host] + + # Video frames normally share a shape. Batching before the upload keeps + # this fast path to one H2D copy; the mixed-resolution path preserves + # the public behavior without padding or changing resize semantics. + shapes = {image.shape for image in images_bgr} + if len(shapes) == 1: + batch_cpu = np.stack( + [np.ascontiguousarray(image) for image in images_bgr], axis=0 + ) + batch_host = torch.from_numpy(batch_cpu).pin_memory() + host_staging.append(batch_host) + with ( + torch.cuda.device(self.cuda_device_id), + torch.cuda.stream(self.copy_stream), + ): + h2d_ready_event = torch.cuda.Event() + raw_images = batch_host.to(device=device, non_blocking=True) + sizes = sizes_host.to(device=device, non_blocking=True) + h2d_ready_event.record(self.copy_stream) + else: + image_hosts = [ + torch.from_numpy(np.ascontiguousarray(image)).pin_memory() + for image in images_bgr + ] + host_staging.extend(image_hosts) + with ( + torch.cuda.device(self.cuda_device_id), + torch.cuda.stream(self.copy_stream), + ): + h2d_ready_event = torch.cuda.Event() + raw_images = tuple( + image_host.to(device=device, non_blocking=True) + for image_host in image_hosts + ) + sizes = sizes_host.to(device=device, non_blocking=True) + h2d_ready_event.record(self.copy_stream) + + return PreparedBatch( + raw_images=raw_images, + orig_target_sizes=sizes, + orig_target_sizes_cpu=sizes_cpu, + h2d_ready_event=h2d_ready_event, + host_staging=tuple(host_staging), + ) + + def _prepare_bgr_batch_in_slot( + self, images_bgr: list[np.ndarray], slot_index: int + ) -> PreparedBatch: + """Fill one persistent pinned slot and enqueue copies into fixed buffers.""" + import torch + + if self._cuda_slots is None or self._cuda_slot_shape is None: + raise RuntimeError("CUDA input slots must be initialized before use") + slot = self._cuda_slots[slot_index] + max_batch_size, height, width, channels = self._cuda_slot_shape + actual_batch_size = len(images_bgr) + if actual_batch_size > max_batch_size: + raise ValueError( + f"batch of {actual_batch_size} exceeds CUDA slot capacity " + f"{max_batch_size}" + ) + expected_shape = (height, width, channels) + if any(tuple(image.shape) != expected_shape for image in images_bgr): + raise ValueError( + f"CUDA input slot expects image shape {expected_shape}; " + "mixed-resolution batches must use the dynamic fallback" + ) + + # Ensure any prior async DMA reading from this slot's pinned host memory + # has finished before the CPU overwrites host_images/host_sizes. + if slot.has_h2d_event: + slot.h2d_ready_event.synchronize() + + host_images = slot.host_images[:actual_batch_size] + host_sizes = slot.host_sizes[:actual_batch_size] + # np.copyto writes decoded pageable frames into storage that was page + # locked once at slot creation. There is no pin/register operation here. + host_images_numpy = host_images.numpy() + host_sizes_numpy = host_sizes.numpy() + for index, image in enumerate(images_bgr): + np.copyto(host_images_numpy[index], image, casting="no") + host_sizes_numpy[index] = (image.shape[1], image.shape[0]) + sizes_cpu = host_sizes_numpy.copy() + cuda_images = slot.cuda_images[:actual_batch_size] + cuda_sizes = slot.cuda_sizes[:actual_batch_size] + with ( + torch.cuda.device(self.cuda_device_id), + torch.cuda.stream(self.copy_stream), + ): + # On reuse, do not overwrite the raw device buffer until the + # inference stream has finished every preprocessing read from it. + if slot.has_consume_event: + self.copy_stream.wait_event(slot.consume_done_event) + cuda_images.copy_(host_images, non_blocking=True) + cuda_sizes.copy_(host_sizes, non_blocking=True) + slot.h2d_ready_event.record(self.copy_stream) + slot.has_h2d_event = True + + return PreparedBatch( + raw_images=cuda_images, + orig_target_sizes=cuda_sizes, + orig_target_sizes_cpu=sizes_cpu, + h2d_ready_event=slot.h2d_ready_event, + host_staging=(host_images, host_sizes), + slot=slot, + ) + + def prepare_cuda_tensor( + self, + raw_bgr, + orig_target_sizes=None, + *, + ready_event=None, + ) -> PreparedBatch: + """Wrap an already-resident CUDA uint8 BGR batch without a second H2D copy. + + Callers that decode or stage frames directly onto the GPU can hand their + contiguous ``(B, H, W, 3)`` ``uint8`` CUDA tensor here and pass the + returned :class:`PreparedBatch` straight to :meth:`run_onnx_prepared`. + """ + if not self.cuda_input_enabled or self.copy_stream is None: + raise RuntimeError("prepare_cuda_tensor requires the CUDA input pipeline") + + import torch + + if not isinstance(raw_bgr, torch.Tensor): + raise TypeError(f"expected a torch.Tensor, got {type(raw_bgr)!r}") + if raw_bgr.ndim != 4 or raw_bgr.shape[-1] != 3: + raise ValueError(f"expected BGR [B,H,W,3], got {tuple(raw_bgr.shape)}") + batch_size = int(raw_bgr.shape[0]) + if batch_size <= 0: + raise ValueError("prepare_cuda_tensor requires a non-empty batch") + if raw_bgr.dtype != torch.uint8 or not raw_bgr.is_cuda: + raise ValueError("expected a CUDA uint8 BGR tensor") + expected_device = torch.device("cuda", self.cuda_device_id) + if raw_bgr.device != expected_device: + raise ValueError( + f"expected CUDA tensor on {expected_device}, got {raw_bgr.device}" + ) + if not raw_bgr.is_contiguous(): + raise ValueError("expected contiguous BGR input") + + height, width = int(raw_bgr.shape[1]), int(raw_bgr.shape[2]) + host_staging: list[Any] = [] + sizes_cuda = None + + if orig_target_sizes is None: + sizes_cpu = np.broadcast_to( + np.array([[width, height]], dtype=np.int64), (batch_size, 2) + ).copy() + elif isinstance(orig_target_sizes, torch.Tensor) and orig_target_sizes.is_cuda: + if orig_target_sizes.dtype != torch.int64 or tuple( + orig_target_sizes.shape + ) != (batch_size, 2): + raise ValueError( + f"expected orig_target_sizes int64 {(batch_size, 2)}, " + f"got {orig_target_sizes.dtype} {tuple(orig_target_sizes.shape)}" + ) + if orig_target_sizes.device != expected_device: + raise ValueError( + f"expected orig_target_sizes on {expected_device}, " + f"got {orig_target_sizes.device}" + ) + if not orig_target_sizes.is_contiguous(): + raise ValueError("expected contiguous orig_target_sizes tensor") + sizes_cuda = orig_target_sizes + sizes_cpu = orig_target_sizes.detach().cpu().numpy() + else: + if isinstance(orig_target_sizes, torch.Tensor): + sizes_cpu = np.ascontiguousarray( + orig_target_sizes.detach().cpu().numpy(), dtype=np.int64 + ) + else: + sizes_cpu = np.ascontiguousarray(orig_target_sizes, dtype=np.int64) + if sizes_cpu.shape != (batch_size, 2): + raise ValueError( + f"expected orig_target_sizes shape {(batch_size, 2)}, " + f"got {sizes_cpu.shape}" + ) + + if ready_event is None: + with torch.cuda.device(self.cuda_device_id): + source_ready_event = torch.cuda.Event() + source_ready_event.record( + torch.cuda.current_stream(self.cuda_device_id) + ) + else: + source_ready_event = ready_event + + if sizes_cuda is None: + sizes_host = torch.from_numpy(sizes_cpu).pin_memory() + host_staging.append(sizes_host) + with ( + torch.cuda.device(self.cuda_device_id), + torch.cuda.stream(self.copy_stream), + ): + h2d_ready_event = torch.cuda.Event() + self.copy_stream.wait_event(source_ready_event) + sizes_cuda = sizes_host.to(device=expected_device, non_blocking=True) + h2d_ready_event.record(self.copy_stream) + else: + h2d_ready_event = source_ready_event + + return PreparedBatch( + raw_images=raw_bgr, + orig_target_sizes=sizes_cuda, + orig_target_sizes_cpu=sizes_cpu, + h2d_ready_event=h2d_ready_event, + host_staging=tuple(host_staging), + slot=None, + ) + + def _preprocess_raw_cuda(self, raw_images): + """Apply Pillow-exact GPU preprocessing on the current CUDA stream.""" + if self._cuda_preprocessor is None: + raise RuntimeError( + "Pillow-exact CUDA preprocessing requires an active " + "CUDAExecutionProvider" + ) + return self._cuda_preprocessor(raw_images) + + def preprocess_prepared_batch(self, prepared: PreparedBatch, stream): + """Run GPU preprocessing after H2D, entirely on ``stream``.""" + import torch + + with torch.cuda.device(self.cuda_device_id), torch.cuda.stream(stream): + stream.wait_event(prepared.h2d_ready_event) + images = self._preprocess_raw_cuda(prepared.raw_images) + if prepared.slot is not None: + ready_event = prepared.slot.preprocess_ready_event + prepared.slot.consume_done_event.record(stream) + prepared.slot.has_consume_event = True + else: + ready_event = torch.cuda.Event() + ready_event.record(stream) + return images, ready_event + + def _preprocess_bgr_batch_cuda(self, images_bgr: list[np.ndarray]): + """Synchronously prepare one batch with the CUDA input pipeline.""" + if not self.cuda_input_enabled: + raise RuntimeError("CUDA preprocessing is not available") + prepared = self.prepare_bgr_batch_async(images_bgr) + images, ready_event = self.preprocess_prepared_batch( + prepared, self.inference_stream + ) + ready_event.synchronize() + return images, prepared.orig_target_sizes + + def preprocess_bgr_batch(self, images_bgr: list[np.ndarray]): + """Create ONNX inputs for the active execution provider. + + CUDA execution preserves Pillow uint8 resize and NumPy float32 scaling + bit for bit. CPU execution (or environments without PyTorch CUDA) uses + the original Pillow path. + """ + if self.cuda_input_enabled: + return self._preprocess_bgr_batch_cuda(images_bgr) + return self._preprocess_bgr_batch_cpu(images_bgr) + + # ---------------------------------------------------------- runtime/postproc + + def _run_onnx_cuda(self, images, orig_target_sizes): + """Run ORT with CUDA tensors bound directly as graph inputs.""" + io_binding = self.session.io_binding() + io_binding.bind_input( + name="images", + device_type="cuda", + device_id=self.cuda_device_id, + element_type=np.float32, + shape=tuple(images.shape), + buffer_ptr=images.data_ptr(), + ) + io_binding.bind_input( + name="orig_target_sizes", + device_type="cuda", + device_id=self.cuda_device_id, + element_type=np.int64, + shape=tuple(orig_target_sizes.shape), + buffer_ptr=orig_target_sizes.data_ptr(), + ) + for output_name in ("labels", "boxes", "scores"): + io_binding.bind_output(output_name, "cpu") + self.session.run_with_iobinding(io_binding) + return tuple(io_binding.copy_outputs_to_cpu()) + + def run_onnx(self, images, orig_target_sizes): + """Run only ONNX Runtime; CUDA tensors use zero-copy I/O Binding.""" + if isinstance(images, np.ndarray): + labels, boxes, scores = self.session.run( + ["labels", "boxes", "scores"], + {"images": images, "orig_target_sizes": orig_target_sizes}, + ) + return labels, boxes, scores + return self._run_onnx_cuda(images, orig_target_sizes) + + def run_onnx_prepared(self, prepared: PreparedBatch): + """Preprocess and run ORT sequentially on the inference stream.""" + if not self.cuda_input_enabled or self.inference_stream is None: + raise RuntimeError("run_onnx_prepared requires the CUDA input pipeline") + images, preprocess_ready_event = self.preprocess_prepared_batch( + prepared, self.inference_stream ) + # ORT keeps its default CUDA stream. Moving the entire EP onto a user + # stream changes B1 numerics, so retain the reference execution path + # and synchronize only the exact resize. + preprocess_ready_event.synchronize() + return self._run_onnx_cuda(images, prepared.orig_target_sizes) + + def postprocess( + self, + labels: np.ndarray, + boxes: np.ndarray, + scores: np.ndarray, + orig_target_sizes: np.ndarray, + ) -> list[list[Detection]]: + """Convert raw CPU ONNX outputs into filtered per-image detections.""" + if not isinstance(orig_target_sizes, np.ndarray): + orig_target_sizes = orig_target_sizes.detach().cpu().numpy() out = [] - for lab, box, sc, (iw, ih) in zip(labels, boxes, scores, sizes): + for lab, box, sc, (iw, ih) in zip(labels, boxes, scores, orig_target_sizes): keep = sc > self.score_thr dets = [ Detection( @@ -294,13 +868,29 @@ def _run(self, batch: np.ndarray, sizes: np.ndarray) -> list[list[Detection]]: out.append(dets) return out + def _run(self, batch: np.ndarray, sizes: np.ndarray) -> list[list[Detection]]: + """Compatibility wrapper composing ONNX execution and postprocessing.""" + labels, boxes, scores = self.run_onnx(batch, sizes) + return self.postprocess(labels, boxes, scores, sizes) + # ------------------------------------------------------------------- api def detect(self, image: str | Path | Image.Image) -> list[Detection]: """Detect hands in one image. Returns detections sorted by score.""" img = Image.open(image) if not isinstance(image, Image.Image) else image - w, h = img.size - return self._run(self._preprocess(img), np.array([[w, h]], dtype=np.int64))[0] + batch, sizes = self._preprocess_pil_batch([img]) + return self._run(batch, sizes)[0] + + def detect_preprocessed( + self, inputs: list[np.ndarray], sizes: np.ndarray + ) -> list[list[Detection]]: + """``detect_batch`` on inputs already made by ``_preprocess``. + + Args: + inputs: One ``(1, 3, 640, 640)`` float32 array per image, in order. + sizes: int64 ``(B, 2)`` original ``(width, height)`` per image. + """ + return self._run(np.concatenate(inputs, axis=0), sizes) def detect_batch(self, images: list) -> list[list[Detection]]: """Detect on several images at once. @@ -309,6 +899,5 @@ def detect_batch(self, images: list) -> list[list[Detection]]: model rescales each result with its own ``orig_target_size``. """ pil = [Image.open(i) if not isinstance(i, Image.Image) else i for i in images] - batch = np.concatenate([self._preprocess(p) for p in pil], axis=0) - sizes = np.array([[p.size[0], p.size[1]] for p in pil], dtype=np.int64) + batch, sizes = self._preprocess_pil_batch(pil) return self._run(batch, sizes) diff --git a/src/python/isaaccapture_egopost/inference/hand_detector_2d/rtdetr/pillow_exact_cuda.py b/src/python/isaaccapture_egopost/inference/hand_detector_2d/rtdetr/pillow_exact_cuda.py new file mode 100644 index 0000000000..e7c17e316b --- /dev/null +++ b/src/python/isaaccapture_egopost/inference/hand_detector_2d/rtdetr/pillow_exact_cuda.py @@ -0,0 +1,417 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: LicenseRef-OpenMDW-1.1 + +"""Pillow-exact RT-DETR image resize implemented with PyTorch tensors. + +The legacy detector preprocesses every uint8 RGB image with Pillow BILINEAR, +keeps a uint8 intermediate after each separable pass, and only then converts +the 640x640 result to float32 in [0, 1]. A floating-point ``interpolate`` call +is close but not bitwise equivalent; thresholding, NMS, and tracking can amplify +that sub-LSB input difference into a different hand box. + +This module reproduces Pillow's uint8 resampling contract with 22-bit +fixed-point coefficients, including Pillow 13.0+'s vertical-before-horizontal +pass-order selection. Full detector batches at the first resolution use one +static ``torch.compile`` graph (disabled under ``EGOHAND_RUNTIME_PROFILE=release``). +Another resolution and every arbitrary tail use the same eager math, so a long +process does not create a family of compiled shape specializations. +Mixed-resolution input is also eager. +""" + +from __future__ import annotations + +import logging +import math +import os +import threading +from dataclasses import dataclass + +import numpy as np +import PIL + +# Fixed-point coefficient/resampling semantics are derived from Pillow +# src/libImaging/Resample.c under the MIT-CMU terms copied beside this file in +# PILLOW_LICENSE_NOTICE. + + +INPUT_SIZE = 640 +PRECISION_BITS = 22 +_MAX_TABLE_CACHE_ENTRIES = 4 + +log = logging.getLogger(__name__) + + +def _is_release_profile() -> bool: + """Return True when ``EGOHAND_RUNTIME_PROFILE`` disables compilation.""" + return os.environ.get("EGOHAND_RUNTIME_PROFILE", "full") == "release" + + +def _pillow_uses_vertical_first(height: int, width: int) -> bool: + """Return True when the installed Pillow runs the vertical pass before horizontal. + + Pillow 13.0.0 selects vertical-first resampling when downsampling vertically + produces a smaller intermediate buffer than horizontal-first resampling. + Because each separable pass rounds to uint8, matching the pass order is + required for bit-exact equivalence. + """ + major = int(PIL.__version__.split(".", 1)[0]) + return ( + major >= 13 + and height > INPUT_SIZE + and width != INPUT_SIZE + and (2 * width < height + INPUT_SIZE) + ) + + +def pillow_bilinear_coefficients( + input_size: int, + output_size: int = INPUT_SIZE, +) -> tuple[np.ndarray, np.ndarray]: + """Return Pillow-compatible bounds and quantized bilinear coefficients. + + For each output coordinate, ``bounds[x]`` stores the first source index and + tap count. ``coefficients[x]`` stores the corresponding 22-bit quantized + int32 weights. This follows Pillow ``precompute_coeffs`` and + ``normalize_coeffs_8bpc``. + """ + input_size = int(input_size) + output_size = int(output_size) + if input_size <= 0 or output_size <= 0: + raise ValueError( + f"resize dimensions must be positive, got {input_size}->{output_size}" + ) + + scale = input_size / output_size + filter_scale = max(scale, 1.0) + support = filter_scale + kernel_size = math.ceil(support) * 2 + 1 + bounds = np.zeros((output_size, 2), dtype=np.int64) + coefficients = np.zeros((output_size, kernel_size), dtype=np.int32) + inverse_filter_scale = 1.0 / filter_scale + + for output_index in range(output_size): + center = (output_index + 0.5) * scale + minimum = max(int(center - support + 0.5), 0) + maximum = min(int(center + support + 0.5), input_size) + count = maximum - minimum + weights = [] + for tap in range(count): + distance = abs((tap + minimum - center + 0.5) * inverse_filter_scale) + weights.append(1.0 - distance if distance < 1.0 else 0.0) + weight_sum = sum(weights) + if weight_sum: + weights = [weight / weight_sum for weight in weights] + + bounds[output_index] = (minimum, count) + for tap, weight in enumerate(weights): + scaled = weight * (1 << PRECISION_BITS) + coefficients[output_index, tap] = int( + -0.5 + scaled if scaled < 0 else 0.5 + scaled + ) + return bounds, coefficients + + +def _fixed_point_pass( + images, + bounds, + coefficients, + *, + horizontal: bool, +): + """Apply one Pillow uint8 pass using int32 accumulation on the same device.""" + import torch + + input_size = images.shape[-1] if horizontal else images.shape[-2] + output_shape = list(images.shape) + output_shape[-1 if horizontal else -2] = INPUT_SIZE + accumulator = torch.full( + output_shape, + 1 << (PRECISION_BITS - 1), + dtype=torch.int32, + device=images.device, + ) + for tap in range(coefficients.shape[1]): + indices = (bounds[:, 0] + tap).clamp(max=input_size - 1) + values = torch.index_select( + images, + -1 if horizontal else -2, + indices, + ).to(torch.int32) + weights = coefficients[:, tap] + if horizontal: + weights = weights.view(1, 1, 1, INPUT_SIZE) + else: + weights = weights.view(1, 1, INPUT_SIZE, 1) + accumulator.add_(values * weights) + return (accumulator >> PRECISION_BITS).clamp_(0, 255).to(torch.uint8) + + +def pillow_exact_preprocess_eager_hv( + raw_bgr, + horizontal_bounds, + horizontal_coefficients, + vertical_bounds, + vertical_coefficients, + normalized_lut, +): + """BGR uint8 ``[B,H,W,3]`` -> Pillow-exact RGB FP32 ``[B,3,640,640]`` (H then V).""" + # Change layout and channel order without converting to float. Pillow's + # uint8 rounding after each separable pass is part of the exact contract. + rgb_uint8 = raw_bgr.permute(0, 3, 1, 2)[:, [2, 1, 0], :, :] + horizontal = _fixed_point_pass( + rgb_uint8, + horizontal_bounds, + horizontal_coefficients, + horizontal=True, + ) + resized_uint8 = _fixed_point_pass( + horizontal, + vertical_bounds, + vertical_coefficients, + horizontal=False, + ) + # Use the NumPy-generated 256-value lookup table so GPU division does not + # introduce a last-bit difference from the legacy CPU path. + return normalized_lut[resized_uint8.long()].contiguous() + + +def pillow_exact_preprocess_eager_vh( + raw_bgr, + horizontal_bounds, + horizontal_coefficients, + vertical_bounds, + vertical_coefficients, + normalized_lut, +): + """BGR uint8 ``[B,H,W,3]`` -> Pillow-exact RGB FP32 ``[B,3,640,640]`` (V then H).""" + rgb_uint8 = raw_bgr.permute(0, 3, 1, 2)[:, [2, 1, 0], :, :] + vertical = _fixed_point_pass( + rgb_uint8, + vertical_bounds, + vertical_coefficients, + horizontal=False, + ) + resized_uint8 = _fixed_point_pass( + vertical, + horizontal_bounds, + horizontal_coefficients, + horizontal=True, + ) + return normalized_lut[resized_uint8.long()].contiguous() + + +def pillow_exact_preprocess_eager( + raw_bgr, + horizontal_bounds, + horizontal_coefficients, + vertical_bounds, + vertical_coefficients, + normalized_lut, +): + """BGR uint8 ``[B,H,W,3]`` -> Pillow-exact RGB FP32 ``[B,3,640,640]``.""" + height, width = int(raw_bgr.shape[-3]), int(raw_bgr.shape[-2]) + if _pillow_uses_vertical_first(height, width): + return pillow_exact_preprocess_eager_vh( + raw_bgr, + horizontal_bounds, + horizontal_coefficients, + vertical_bounds, + vertical_coefficients, + normalized_lut, + ) + return pillow_exact_preprocess_eager_hv( + raw_bgr, + horizontal_bounds, + horizontal_coefficients, + vertical_bounds, + vertical_coefficients, + normalized_lut, + ) + + +@dataclass(frozen=True) +class _ResizeTables: + horizontal_bounds: object + horizontal_coefficients: object + vertical_bounds: object + vertical_coefficients: object + normalized_lut: object + + def arguments(self) -> tuple: + return ( + self.horizontal_bounds, + self.horizontal_coefficients, + self.vertical_bounds, + self.vertical_coefficients, + self.normalized_lut, + ) + + +class PillowExactCudaPreprocessor: + """Route configured full batches to static compile and arbitrary tails eager.""" + + def __init__(self, full_batch_size: int): + full_batch_size = int(full_batch_size) + if full_batch_size <= 0: + raise ValueError(f"full_batch_size must be positive, got {full_batch_size}") + self.full_batch_size = full_batch_size + self._tables: dict[tuple, _ResizeTables] = {} + self._tables_lock = threading.Lock() + self._compiled_resolution: tuple | None = None + self._compiled = None + self._compile_disabled = _is_release_profile() + self._compile_lock = threading.Lock() + + @staticmethod + def _resolution_key(image) -> tuple: + import torch + + height, width = int(image.shape[-3]), int(image.shape[-2]) + device = image.device + if device.index is not None: + device_index = device.index + elif device.type == "cuda": + device_index = torch.cuda.current_device() + else: + device_index = 0 + return device.type, device_index, height, width + + def _compiled_function(self, image): + import torch + + if self._compile_disabled or _is_release_profile(): + return None + key = self._resolution_key(image) + if self._compiled is None: + with self._compile_lock: + if ( + self._compiled is None + and not self._compile_disabled + and not _is_release_profile() + ): + try: + # A user-mapped container UID may be absent from + # /etc/passwd. TorchInductor needs a stable cache name. + os.environ.setdefault("USER", f"uid_{os.getuid()}") + os.environ.setdefault("LOGNAME", os.environ["USER"]) + _, _, height, width = key + target_fn = ( + pillow_exact_preprocess_eager_vh + if _pillow_uses_vertical_first(height, width) + else pillow_exact_preprocess_eager_hv + ) + self._compiled = torch.compile( + target_fn, + fullgraph=True, + dynamic=False, + ) + self._compiled_resolution = key + except Exception as error: + self._compile_disabled = True + log.warning( + "Pillow-exact CUDA compile unavailable; using eager: %s", + error, + ) + if key != self._compiled_resolution: + return None + return self._compiled + + def _disable_compiled_function(self, error: Exception) -> None: + with self._compile_lock: + self._compiled = None + self._compiled_resolution = None + if not self._compile_disabled: + log.warning( + "Pillow-exact compiled CUDA call failed; using eager: %s", + error, + ) + self._compile_disabled = True + + def _get_tables(self, image) -> _ResizeTables: + import torch + + key = self._resolution_key(image) + _, _, height, width = key + device = image.device + cached = self._tables.get(key) + if cached is not None: + return cached + + with self._tables_lock: + cached = self._tables.get(key) + if cached is not None: + return cached + horizontal_bounds, horizontal_coefficients = pillow_bilinear_coefficients( + width + ) + vertical_bounds, vertical_coefficients = pillow_bilinear_coefficients( + height + ) + # Generate normalized values with the same NumPy float32 expression + # used by the legacy path. + normalized_lut = np.arange(256, dtype=np.float32) / 255.0 + cached = _ResizeTables( + horizontal_bounds=torch.from_numpy(horizontal_bounds).to(device), + horizontal_coefficients=torch.from_numpy(horizontal_coefficients).to( + device + ), + vertical_bounds=torch.from_numpy(vertical_bounds).to(device), + vertical_coefficients=torch.from_numpy(vertical_coefficients).to( + device + ), + normalized_lut=torch.from_numpy(normalized_lut).to(device), + ) + if len(self._tables) >= _MAX_TABLE_CACHE_ENTRIES: + self._tables.pop(next(iter(self._tables))) + self._tables[key] = cached + return cached + + @staticmethod + def _validate_batch(raw_bgr) -> None: + import torch + + if not isinstance(raw_bgr, torch.Tensor): + raise TypeError(f"expected a torch.Tensor, got {type(raw_bgr)!r}") + if raw_bgr.ndim != 4 or raw_bgr.shape[-1] != 3: + raise ValueError(f"expected BGR [B,H,W,3], got {tuple(raw_bgr.shape)}") + if raw_bgr.shape[0] <= 0: + raise ValueError("Pillow-exact preprocessing requires a non-empty batch") + if raw_bgr.dtype != torch.uint8 or not raw_bgr.is_cuda: + raise ValueError("expected a CUDA uint8 BGR tensor") + if not raw_bgr.is_contiguous(): + raise ValueError("expected contiguous BGR input") + + def _preprocess_one_batch(self, raw_bgr): + self._validate_batch(raw_bgr) + batch_size = int(raw_bgr.shape[0]) + tables = self._get_tables(raw_bgr) + if batch_size == self.full_batch_size: + operation = self._compiled_function(raw_bgr) + if operation is not None: + try: + return operation(raw_bgr, *tables.arguments()) + except Exception as error: + self._disable_compiled_function(error) + return pillow_exact_preprocess_eager(raw_bgr, *tables.arguments()) + + def __call__(self, raw_images): + """Preprocess a batched tensor or a mixed-resolution tuple exactly.""" + import torch + + if isinstance(raw_images, tuple): + if not raw_images: + raise ValueError("mixed-resolution input tuple must not be empty") + # Mixed-resolution batches cannot share coefficient tensor shapes; + # eager each image and concatenate without creating compile variants. + outputs = [] + for image in raw_images: + batched = image.unsqueeze(0) + self._validate_batch(batched) + outputs.append( + pillow_exact_preprocess_eager( + batched, + *self._get_tables(batched).arguments(), + ) + ) + return torch.cat(outputs, dim=0).contiguous() + return self._preprocess_one_batch(raw_images) diff --git a/src/python/isaaccapture_egopost/inference/hand_detector_2d/scripts/README.md b/src/python/isaaccapture_egopost/inference/hand_detector_2d/scripts/README.md index 867ec4cb12..5f2bf14713 100644 --- a/src/python/isaaccapture_egopost/inference/hand_detector_2d/scripts/README.md +++ b/src/python/isaaccapture_egopost/inference/hand_detector_2d/scripts/README.md @@ -197,6 +197,7 @@ attribute: | `bbox_size_alpha_grow` | `0.12` | Size growth EMA weight at 20 fps, in `(0, 1]`; smaller values smooth more. | | `bbox_size_alpha_shrink` | `0.06` | Size shrink EMA weight at 20 fps, in `(0, 1]`. | | `bbox_max_size_change` | `0.01` | Nonnegative fractional growth limit per 20-fps interval. Shrinkage uses the reciprocal ratio. Zero holds a constant size within each track segment. | +| `preprocess_threads` | `min(8, cpu_count)` | Worker threads preprocessing the next RT-DETR batch while ONNX Runtime runs the current batch. Set `1` for the sequential loop. Network input is byte-identical. | Unknown `rtdetr_config` keys, invalid batch sizes, and invalid smoothing controls are rejected during config validation. The standalone CLI reports these errors diff --git a/src/python/isaaccapture_egopost/inference/media/_pyav_video.py b/src/python/isaaccapture_egopost/inference/media/_pyav_video.py new file mode 100644 index 0000000000..1a67400f1c --- /dev/null +++ b/src/python/isaaccapture_egopost/inference/media/_pyav_video.py @@ -0,0 +1,525 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: LicenseRef-OpenMDW-1.1 + +"""Multi-threaded PyAV chunked video streaming and bounded-RAM random access. + +Provides: +- ``iter_video_chunks_pyav``: sequential multi-threaded PyAV H.264/HEVC/MPEG4 + decoder yielding bounded chunks of ``(frames_bgr, frame_pts, keyframe_pts)`` + from a background prefetch thread (queue depth 2 by default) so video decode + overlaps GPU compute. Falls back to ``video_io.read_video_frames_batched`` + when display rotation metadata is non-zero or ``EGOHAND_RUNTIME_PROFILE`` is + ``"release"``. +- ``SeekablePyAVFrames``: sequence-like random-access frame view backed by an + LRU cache, stateful keyframe PTS seek, and forward decode to exact + ``frame_pts[t]`` for bounded-RAM on-demand verification. +""" + +from __future__ import annotations + +import queue +import threading +from collections import OrderedDict +from collections.abc import Iterator, Sequence +from pathlib import Path +from typing import Any + +import cv2 +import numpy as np + +from . import video_io +from .errors import VideoDecodeError +from .runtime_profile import get_runtime_profile + +try: + import av +except ImportError: # pragma: no cover - optional when PyAV is unavailable + av = None + +_DONE = object() +_ERROR = object() + + +def _get_display_rotation(stream: Any) -> int: + """Return non-zero display rotation angle (degrees mod 360), or 0 if upright.""" + side_data = getattr(stream, "side_data", None) or {} + for key in ("DISPLAYMATRIX", "displaymatrix"): + if key in side_data: + try: + raw_angle = float(side_data[key]) + except (TypeError, ValueError): + continue + mod_angle = raw_angle % 360.0 + if mod_angle > 1e-3 and abs(mod_angle - 360.0) > 1e-3: + return round(mod_angle) % 360 or 1 + + metadata = getattr(stream, "metadata", None) or {} + raw_rotate = metadata.get("rotate") + if raw_rotate is not None: + try: + raw_angle = float(raw_rotate) + except (TypeError, ValueError): + return 0 + mod_angle = raw_angle % 360.0 + if mod_angle > 1e-3 and abs(mod_angle - 360.0) > 1e-3: + return round(mod_angle) % 360 or 1 + return 0 + + +def _put_with_stop( + out_queue: queue.Queue, + item: Any, + stop_event: threading.Event, +) -> bool: + """Enqueue ``item`` while periodically polling ``stop_event`` to prevent deadlock.""" + while not stop_event.is_set(): + try: + out_queue.put(item, timeout=0.05) + return True + except queue.Full: + continue + return False + + +def _iter_fallback_chunks( + video_path: str, + chunk_size: int, + max_frames: int | None, +) -> Iterator[tuple[list[np.ndarray], list[int], list[int]]]: + """Stream chunks through ``video_io.read_video_frames_batched``.""" + for batch in video_io.read_video_frames_batched( + video_path, chunk_size, max_frames=max_frames + ): + frames_bgr = [frame for _, frame in batch] + frame_pts = [int(frame_idx) for frame_idx, _ in batch] + keyframe_pts = [0] * len(frames_bgr) + yield frames_bgr, frame_pts, keyframe_pts + + +def iter_video_chunks_pyav( + video_path: str | Path, + chunk_size: int = 64, + *, + threads: int = 8, + prefetch_chunks: int = 2, + max_frames: int | None = None, +) -> Iterator[tuple[list[np.ndarray], list[int], list[int]]]: + """Stream BGR video frames in bounded chunks using multi-threaded PyAV. + + Decoded chunks are prefetched on a background thread into a bounded queue + (``prefetch_chunks=2`` by default) so CPU decoding overlaps downstream GPU + inference while capping peak host RAM. + + When ``EGOHAND_RUNTIME_PROFILE == "release"``, when PyAV is unavailable, or + when the video stream carries non-zero display rotation metadata, this + function falls back transparently to ``video_io.read_video_frames_batched``. + + Args: + video_path: Path to the input video file. + chunk_size: Maximum number of frames per yielded chunk. + threads: Decoder thread count passed to PyAV/FFmpeg. + prefetch_chunks: Bounded prefetch queue depth (in chunks). + max_frames: Optional hard limit on total decoded frames. + + Yields: + Tuples ``(frames_bgr, frame_pts, keyframe_pts)`` where: + - ``frames_bgr``: List of ``(H, W, 3)`` ``uint8`` BGR numpy arrays. + - ``frame_pts``: List of integer presentation timestamps (or frame + indices on fallback). + - ``keyframe_pts``: List of integer preceding keyframe PTS values for + each frame (for :class:`SeekablePyAVFrames`). + """ + for name, value in ( + ("chunk_size", chunk_size), + ("threads", threads), + ("prefetch_chunks", prefetch_chunks), + ): + if isinstance(value, bool) or not isinstance(value, int) or value <= 0: + raise ValueError(f"{name} must be a positive integer") + if max_frames is not None: + if isinstance(max_frames, bool) or not isinstance(max_frames, int): + raise ValueError("max_frames must be an integer or None") + if max_frames <= 0: + return + + path_str = str(video_path) + + # Release builds must exclusively use the approved restricted FFmpeg backend. + if get_runtime_profile().name == "release" or av is None: + yield from _iter_fallback_chunks(path_str, chunk_size, max_frames) + return + + container = av.open(path_str) + if not container.streams.video: + container.close() + raise VideoDecodeError(f"Input has no video stream: {path_str}") + stream = container.streams.video[0] + + # Rotated videos fall back to video_io so display orientation matches OpenCV/FFmpeg. + if _get_display_rotation(stream) != 0: + container.close() + yield from _iter_fallback_chunks(path_str, chunk_size, max_frames) + return + + stream.thread_type = "AUTO" + stream.thread_count = int(threads) + + chunk_queue: queue.Queue = queue.Queue(maxsize=prefetch_chunks) + stop_event = threading.Event() + + def _producer() -> None: + frames_bgr: list[np.ndarray] = [] + frame_pts_list: list[int] = [] + keyframe_pts_list: list[int] = [] + last_kf_pts: int | None = None + decoded = 0 + try: + for frame in container.decode(stream): + if stop_event.is_set(): + return + if frame.pts is not None: + pts = int(frame.pts) + elif frame.dts is not None: + pts = int(frame.dts) + else: + pts = decoded + if frame.key_frame or last_kf_pts is None: + last_kf_pts = pts + frames_bgr.append(frame.to_ndarray(format="bgr24")) + frame_pts_list.append(pts) + keyframe_pts_list.append(last_kf_pts) + decoded += 1 + + if len(frames_bgr) == chunk_size: + if not _put_with_stop( + chunk_queue, + (frames_bgr, frame_pts_list, keyframe_pts_list), + stop_event, + ): + return + frames_bgr = [] + frame_pts_list = [] + keyframe_pts_list = [] + + if max_frames is not None and decoded >= max_frames: + break + + if frames_bgr and not stop_event.is_set(): + if not _put_with_stop( + chunk_queue, + (frames_bgr, frame_pts_list, keyframe_pts_list), + stop_event, + ): + return + _put_with_stop(chunk_queue, _DONE, stop_event) + except BaseException as exc: # noqa: BLE001 - propagate to consumer + _put_with_stop(chunk_queue, (_ERROR, exc), stop_event) + finally: + container.close() + + worker = threading.Thread( + target=_producer, + name="egohand-pyav-prefetch", + daemon=True, + ) + worker.start() + + try: + while True: + item = chunk_queue.get() + if item is _DONE: + return + if isinstance(item, tuple) and len(item) == 2 and item[0] is _ERROR: + raise item[1] + yield item + finally: + stop_event.set() + while True: + try: + chunk_queue.get_nowait() + except queue.Empty: + break + worker.join() + + +class SeekablePyAVFrames: + """Bounded-RAM random-access BGR frame sequence backed by PyAV PTS seek. + + Implements ``__len__`` and ``__getitem__`` with an LRU cache (default 32 + frames, keeping RAM well below 300 MiB even at 1920x1456), stateful forward + decoding within the same GOP (zero redundant seeks for nearby indices), and + exact keyframe PTS seeking across GOP boundaries. + + Args: + video_path: Path to the input video file. + frame_pts: 1D array/sequence of per-frame PTS values recorded during + sequential decoding. + keyframe_pts: 1D array/sequence of per-frame preceding keyframe PTS + values aligned with ``frame_pts``. + cache_size: Maximum number of decoded BGR frames held in the LRU cache. + threads: Decoder thread count for PyAV seek/decode. + """ + + def __init__( + self, + video_path: str | Path, + frame_pts: np.ndarray | Sequence[int], + keyframe_pts: np.ndarray | Sequence[int], + *, + cache_size: int = 32, + threads: int = 4, + ) -> None: + if ( + isinstance(cache_size, bool) + or not isinstance(cache_size, int) + or cache_size < 0 + ): + raise ValueError("cache_size must be a non-negative integer") + if isinstance(threads, bool) or not isinstance(threads, int) or threads <= 0: + raise ValueError("threads must be a positive integer") + + pts_arr = np.asarray(frame_pts, dtype=np.int64) + kf_arr = np.asarray(keyframe_pts, dtype=np.int64) + if pts_arr.ndim != 1 or kf_arr.ndim != 1 or len(pts_arr) != len(kf_arr): + raise ValueError( + "frame_pts and keyframe_pts must be 1D arrays of equal length, " + f"got shapes {pts_arr.shape} and {kf_arr.shape}" + ) + + self.video_path = str(video_path) + self._frame_pts = pts_arr + self._keyframe_pts = kf_arr + self._cache_size = cache_size + self._threads = threads + + self._lock = threading.RLock() + self._cache: OrderedDict[int, np.ndarray] = OrderedDict() + self._closed = False + self._mode: str | None = None + + # PyAV decoder state (opened lazily on first cache miss). + self._container: Any = None + self._stream: Any = None + self._decode_iter: Iterator[Any] | None = None + self._last_kf_pts: int | None = None + self._last_pts: int | None = None + + # OpenCV fallback state for rotated non-release videos. + self._cv_cap: cv2.VideoCapture | None = None + self._cv_next_idx: int = 0 + + @property + def cache_size(self) -> int: + return self._cache_size + + def __len__(self) -> int: + return len(self._frame_pts) + + def __enter__(self) -> SeekablePyAVFrames: + return self + + def __exit__(self, exc_type, exc_val, exc_tb) -> None: + self.close() + + def __del__(self) -> None: + try: + self.close() + except Exception: # noqa: BLE001 + pass + + def clear_cache(self) -> None: + """Evict all cached frames without closing the underlying decoder.""" + with self._lock: + self._cache.clear() + + def close(self) -> None: + """Release the underlying video container and clear cached frames.""" + with self._lock: + self._closed = True + self._cache.clear() + self._decode_iter = None + self._last_kf_pts = None + self._last_pts = None + if self._container is not None: + try: + self._container.close() + finally: + self._container = None + self._stream = None + if self._cv_cap is not None: + try: + self._cv_cap.release() + finally: + self._cv_cap = None + self._cv_next_idx = 0 + + def _ensure_open(self) -> None: + if self._mode is not None: + return + if get_runtime_profile().name == "release" or av is None: + self._mode = "video_io" + return + + container = av.open(self.video_path) + if not container.streams.video: + container.close() + raise VideoDecodeError(f"Input has no video stream: {self.video_path}") + stream = container.streams.video[0] + if _get_display_rotation(stream) != 0: + container.close() + self._mode = "opencv" + return + + stream.thread_type = "AUTO" + stream.thread_count = int(self._threads) + self._container = container + self._stream = stream + self._mode = "pyav" + + def _scan_pyav_for_pts(self, target_pts: int) -> np.ndarray | None: + assert self._decode_iter is not None + for frame in self._decode_iter: + pts = ( + int(frame.pts) + if frame.pts is not None + else (int(frame.dts) if frame.dts is not None else None) + ) + self._last_pts = pts + if pts == target_pts: + return frame.to_ndarray(format="bgr24") + if pts is not None and pts > target_pts: + return None + # Iterator hit EOF; force seek on next call. + self._decode_iter = None + return None + + def _seek_and_scan_pyav(self, seek_pts: int, target_pts: int) -> np.ndarray | None: + assert self._container is not None and self._stream is not None + self._container.seek( + int(seek_pts), stream=self._stream, backward=True, any_frame=False + ) + self._decode_iter = self._container.decode(self._stream) + self._last_kf_pts = int(seek_pts) + self._last_pts = None + return self._scan_pyav_for_pts(target_pts) + + def _decode_pyav(self, idx: int) -> np.ndarray: + target_pts = int(self._frame_pts[idx]) + kf_pts = int(self._keyframe_pts[idx]) + + # Fast path: continue forward in the current GOP without re-seeking. + if ( + self._decode_iter is not None + and self._last_kf_pts == kf_pts + and self._last_pts is not None + and target_pts > self._last_pts + ): + frame_bgr = self._scan_pyav_for_pts(target_pts) + if frame_bgr is not None: + return frame_bgr + + # Primary path: exact backward seek to the recorded keyframe PTS. + frame_bgr = self._seek_and_scan_pyav(kf_pts, target_pts) + if frame_bgr is not None: + return frame_bgr + + # Defensive retry: if muxer seek table landed past target_pts, seek to + # an earlier keyframe or the start of the stream and scan forward. + earlier_kfs = np.unique(self._keyframe_pts[:idx]) + retry_targets = [int(k) for k in reversed(earlier_kfs) if int(k) < kf_pts] + start_pts = min(0, int(self._frame_pts[0])) + if not retry_targets or retry_targets[-1] > start_pts: + retry_targets.append(start_pts) + for fallback_kf in retry_targets: + frame_bgr = self._seek_and_scan_pyav(fallback_kf, target_pts) + if frame_bgr is not None: + self._last_kf_pts = kf_pts + return frame_bgr + + # Final fallback for timestamp-less streams: count frames from start. + assert self._container is not None and self._stream is not None + self._container.seek(0, stream=self._stream, backward=True, any_frame=False) + self._decode_iter = self._container.decode(self._stream) + self._last_kf_pts = None + self._last_pts = None + for cur_idx, frame in enumerate(self._decode_iter): + if cur_idx == idx: + return frame.to_ndarray(format="bgr24") + raise VideoDecodeError( + f"Could not decode frame {idx} (target_pts={target_pts}) from {self.video_path}" + ) + + def _decode_opencv(self, idx: int) -> np.ndarray: + if self._cv_cap is None or idx < self._cv_next_idx: + if self._cv_cap is not None: + self._cv_cap.release() + self._cv_cap = cv2.VideoCapture(self.video_path) + self._cv_next_idx = 0 + while self._cv_next_idx <= idx: + ok, frame = self._cv_cap.read() + if not ok: + raise VideoDecodeError( + f"Could not decode frame {idx} via OpenCV from {self.video_path}" + ) + cur = self._cv_next_idx + self._cv_next_idx += 1 + if cur == idx: + return frame + raise VideoDecodeError(f"Could not decode frame {idx} from {self.video_path}") + + def _decode_video_io(self, idx: int) -> np.ndarray: + for batch in video_io.read_video_frames_batched( + self.video_path, batch_size=32, max_frames=idx + 1 + ): + for frame_idx, frame in batch: + if frame_idx == idx: + return frame + raise VideoDecodeError( + f"Could not decode frame {idx} via video_io from {self.video_path}" + ) + + def __getitem__(self, index: int | slice) -> np.ndarray | list[np.ndarray]: + if isinstance(index, slice): + return [self[i] for i in range(*index.indices(len(self)))] + if isinstance(index, bool) or not isinstance(index, (int, np.integer)): + raise TypeError( + f"SeekablePyAVFrames indices must be integers or slices, " + f"not {type(index).__name__}" + ) + n_frames = len(self) + idx = int(index) + if idx < 0: + idx += n_frames + if idx < 0 or idx >= n_frames: + raise IndexError( + f"frame index {index} out of range for video of length {n_frames}" + ) + + with self._lock: + if self._closed: + raise RuntimeError("SeekablePyAVFrames has been closed") + cached = self._cache.get(idx) + if cached is not None: + self._cache.move_to_end(idx) + return cached + + self._ensure_open() + if self._mode == "pyav": + frame_bgr = self._decode_pyav(idx) + elif self._mode == "opencv": + frame_bgr = self._decode_opencv(idx) + else: + frame_bgr = self._decode_video_io(idx) + + if self._cache_size > 0: + self._cache[idx] = frame_bgr + self._cache.move_to_end(idx) + while len(self._cache) > self._cache_size: + self._cache.popitem(last=False) + return frame_bgr + + +__all__ = [ + "SeekablePyAVFrames", + "iter_video_chunks_pyav", +] diff --git a/src/python/isaaccapture_egopost/inference/perf/README.md b/src/python/isaaccapture_egopost/inference/perf/README.md index 3ac364a8b4..d0c289623c 100644 --- a/src/python/isaaccapture_egopost/inference/perf/README.md +++ b/src/python/isaaccapture_egopost/inference/perf/README.md @@ -13,21 +13,21 @@ Each stage reports wall-clock elapsed time in milliseconds, measured with `time. | Stage | What is measured | |---|---| -| `MODEL_LOAD` | One-time: `EgoHandPredictor.from_checkpoint(...)` (checkpoint load + model construction + device placement) | +| `MODEL_LOAD` | One-time: `EgoHandPredictor.from_checkpoint(...)` (checkpoint load + model construction + device placement). With default `--background_model_load`, this runs on a worker thread while frames are decoded and detected | | `BBOX_DETECTION` | `pipeline.bbox_detector.run(...)` -- whichever backend is configured (`rtdetr`, or the JSON-read time for `saved_bboxes`). Not recorded when `bbox_detector` is `None` (ground-truth boxes passed directly) | | `INFERENCE` | The whole `predictor.run(...)` call. Roughly the sum of `PREPROCESSING` + `BATCH_ASSEMBLY` + `MODEL_FORWARD` + `POST_FORWARD` + `ADAPTIVE_SMOOTHING` | -| `PREPROCESSING` | Hand-crop preparation: perspective cropping (`--perspective_cropping`) or bbox cropping + resizing, whichever mode the run uses (never both) | -| `BATCH_ASSEMBLY` | Stacking crops and camera data into batch tensors and copying them to the GPU | -| `MODEL_FORWARD` | `model.forward_step(...)` only, bracketed with `torch.cuda.synchronize()` so its GPU time doesn't leak into neighboring stages | +| `PREPROCESSING` | Waiting for hand crops: perspective cropping (`--perspective_cropping`) or bbox cropping + resizing, whichever mode the run uses (never both). Crops of later batches are prepared on worker threads and uploaded while earlier batches run (`inference/pipeline/crop_stream.py`), so only the crop time not hidden behind them is counted | +| `BATCH_ASSEMBLY` | Stacking camera data into batch tensors and copying them to the GPU, and waiting for the crop upload of that batch | +| `MODEL_FORWARD` | `model.forward_step(...)` (or head + grouped SOMA layer when `--soma_batch_size > 0`), bracketed with `torch.cuda.synchronize()` so its GPU time doesn't leak into neighboring stages | | `POST_FORWARD` | Camera math, right-hand mirror, copying outputs back to the CPU, and assembling result dicts | | `ADAPTIVE_SMOOTHING` | `smooth_adaptive_hand_results(...)`. Only recorded when `--postprocessing_smooth` is on (the default) | | `OVERLAY_RENDERING` | `render_clip(...)`: overlay drawing plus video encoding. Not recorded with `--no_save_videos` or `--frame_batch_size` | | `TOTAL_WALL` | The whole per-video block in `process_video(...)`, from bbox detection through overlay rendering | -How the stages nest (siblings run one after another and never overlap): +How the stages nest (within each video, stages are timed sequentially on the main thread; background model load and streamed crop prefetch overlap asynchronously): ```text -MODEL_LOAD (once, before the per-video loop) +MODEL_LOAD (once; overlaps first video's decode/detection by default) TOTAL_WALL (per video) ├── BBOX_DETECTION ├── INFERENCE diff --git a/src/python/isaaccapture_egopost/inference/perf/collector.py b/src/python/isaaccapture_egopost/inference/perf/collector.py index 2653ffe5d4..3087531d02 100644 --- a/src/python/isaaccapture_egopost/inference/perf/collector.py +++ b/src/python/isaaccapture_egopost/inference/perf/collector.py @@ -11,9 +11,9 @@ class PerfStage(Enum): MODEL_LOAD = "model_load" # one-time: checkpoint load + model construction + device placement BBOX_DETECTION = "bbox_detection" # per-frame: pipeline.bbox_detector.run(...), whichever backend is configured INFERENCE = "inference" # per-frame: the whole predictor.run() call -- superset of the five stages below (adaptive_smoothing only when not deferred) - PREPROCESSING = "preprocessing" # per-frame: hand-crop preparation (perspective cropping OR bbox crop+resize, mutually exclusive per run) - BATCH_ASSEMBLY = "batch_assembly" # per-frame: stacking crops/cameras into batch tensors + host-to-device copy, before forward - MODEL_FORWARD = "model_forward" # per-frame: model.forward_step(...) only, CUDA-synchronized for an accurate GPU-inclusive number + PREPROCESSING = "preprocessing" # per-frame: waiting for streamed hand-crop preparation (perspective cropping OR bbox crop+resize) + BATCH_ASSEMBLY = "batch_assembly" # per-frame: stacking camera data + host-to-device copy and waiting for staged crop upload + MODEL_FORWARD = "model_forward" # per-frame: model forward (and grouped SOMA layer when --soma_batch_size > 0), CUDA-synchronized POST_FORWARD = "post_forward" # per-frame: camera math, right-hand mirror, device-to-host copy, result-dict assembly ADAPTIVE_SMOOTHING = "adaptive_smoothing" # per-frame: smooth_adaptive_hand_results(...), only recorded when --postprocessing_smooth is on OVERLAY_RENDERING = "overlay_rendering" # per-frame: render_clip(...) -- per-frame drawing plus video encoding, skipped with --no_save_videos @@ -26,8 +26,8 @@ class PerfStage(Enum): STAGE_DESCRIPTIONS: dict[PerfStage, str] = { PerfStage.MODEL_LOAD: ( "One-time cost: checkpoint load, model construction, and device " - "placement. Recorded once before the per-video loop, so it is " - "amortized across every video in a multi-video run." + "placement. Recorded once per run (overlapping first-video decode " + "and detection when --background_model_load is enabled)." ), PerfStage.BBOX_DETECTION: ( "Per-frame wall time of hand bbox detection, whichever backend is " @@ -35,24 +35,27 @@ class PerfStage(Enum): ), PerfStage.INFERENCE: ( "Per-frame wall time of the whole EgoHand predictor call. A superset " - "of preprocessing, batch_assembly, model_forward, post_forward, and " - "adaptive_smoothing, which run one after another inside it and do " - "not overlap each other. Those five should sum close to this value; " - "the remainder is result regrouping, projecting results back to the " - "source camera, and optional per-frame NPZ writes. Exception: with " - "--frame_batch_size, smoothing runs once per clip after all batches, " - "outside this stage (still inside total_wall)." + "of preprocessing (wait for streamed crops), batch_assembly, " + "model_forward, post_forward, and adaptive_smoothing, which are timed " + "sequentially on the main thread inside it. Those five should sum " + "close to this value; the remainder is result regrouping, projecting " + "results back to the source camera, and optional per-frame NPZ " + "writes. Exception: with --frame_batch_size, smoothing runs once per " + "clip after all batches, outside this stage (still inside total_wall)." ), PerfStage.PREPROCESSING: ( - "Per-frame wall time of hand-crop preparation: either perspective " - "cropping (--perspective_cropping) or bbox cropping + resizing, " - "whichever mode this run uses -- the two are mutually exclusive " - "per run, never both." + "Per-frame wall time the forward loop waits for hand crops: either " + "perspective cropping (--perspective_cropping) or bbox cropping + " + "resizing, whichever mode this run uses -- the two are mutually " + "exclusive per run, never both. Crops of later batches are prepared " + "on worker threads and uploaded while earlier batches run, so only " + "the crop time not hidden behind them is counted." ), PerfStage.BATCH_ASSEMBLY: ( - "Per-frame wall time of stacking prepared crops and camera data into " - "batch tensors and copying them to the GPU, up to and including a " - "torch.cuda.synchronize() that waits for those copies to finish." + "Per-frame wall time of stacking camera data into batch tensors and " + "copying them to the GPU (the crop images are already uploaded), up " + "to and including a torch.cuda.synchronize() that waits for those " + "copies to finish." ), PerfStage.MODEL_FORWARD: ( "Per-frame wall time of the model's forward pass only. Bracketed " diff --git a/src/python/isaaccapture_egopost/inference/pipeline/crop_stream.py b/src/python/isaaccapture_egopost/inference/pipeline/crop_stream.py new file mode 100644 index 0000000000..56c7d3e154 --- /dev/null +++ b/src/python/isaaccapture_egopost/inference/pipeline/crop_stream.py @@ -0,0 +1,314 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: LicenseRef-OpenMDW-1.1 + +"""Stream hand crops in forward batches while earlier batches run on the GPU. + +A worker pool builds crops up to ``prefetch_batches * batch_size`` jobs ahead; +a stager thread drops failed crops, packs each batch into one of two pinned +host slots, and uploads it on a reused copy stream to the matching device slot. +CPU devices and non-uniform batches fall back to ``torch.stack(...).to(device)``. +""" + +from __future__ import annotations + +import queue +import threading +import time +from collections import deque +from concurrent.futures import ThreadPoolExecutor +from typing import Any, Callable, Iterable, Iterator + +import numpy as np +import torch + +_DONE = object() +# Crop dtypes copied through numpy into the pinned slot; others use torch.stack. +_NUMPY_DTYPES = (torch.float32, torch.float64, torch.float16, torch.uint8) + + +class _Slot: + __slots__ = ("consumed", "device", "host", "ready", "uploaded", "used") + + def __init__(self) -> None: + self.host: torch.Tensor | None = None + self.device: torch.Tensor | None = None + self.ready = torch.cuda.Event() + self.consumed = torch.cuda.Event() + self.uploaded = False + self.used = False + + +class StagedCropBatch: + """One forward batch: prepared records (without crops) and their images.""" + + def __init__( + self, + hand_data: list[dict], + images: torch.Tensor, + slot_index: int, + owner: StreamedCropBatches, + on_device: bool, + ) -> None: + self.hand_data = hand_data + self._images: torch.Tensor | None = images + self._slot_index = slot_index + self._owner = owner + self._on_device = on_device + self._released = False + + def images(self, device: str | torch.device) -> torch.Tensor: + """Return the batch images on ``device``, ordered on its current stream.""" + if self._released or self._images is None: + raise RuntimeError("StagedCropBatch has already been released") + if not self._on_device: + return self._images.to(device) + slot = self._owner._slots[self._slot_index] + stream = torch.cuda.current_stream(self._images.device) + stream.wait_event(slot.ready) + # The device slot was allocated on the copy stream; keep the allocator + # from reusing it while this stream may still read it. + slot.device.record_stream(stream) + target = torch.device(device) + if target.type == "cuda" and target.index is None: + target = torch.device("cuda", torch.cuda.current_device()) + return ( + self._images if self._images.device == target else self._images.to(target) + ) + + def release(self) -> None: + """Mark the images consumed; their slot may then be refilled.""" + if self._released: + return + self._released = True + self._images = None + self._owner._release(self._slot_index, self._on_device) + + +class StreamedCropBatches: + """Iterate forward batches of valid crops while later crops are prepared. + + Use as a context manager around the forward loop. Each yielded + ``StagedCropBatch`` must be ``release()``-d after its forward pass, before the + next one is requested; exiting the context stops the threads and waits for + pending copies, also on early exit or error. Errors raised by + ``build_input`` are re-raised in the consuming thread. + + Args: + jobs: Crop jobs in model order. + build_input: ``job -> (image_id, hand, prepared or None)``; ``None`` + drops the job (a failed crop). + batch_size: Valid crops per forward batch (the last one may be short). + device: Forward device. CUDA devices use pinned slots and a copy stream. + workers: Crop threads. + prefetch_batches: Crop jobs in flight, in units of ``batch_size``. + copy_stream: Stream for the uploads. Reuse one per device across clips + so the allocator does not keep a separate block pool per clip. + on_prepared: Called in job order with ``(image_id, hand, prepared)`` for + every valid crop, before it is batched. + """ + + def __init__( + self, + jobs: Iterable[Any], + build_input: Callable[[Any], tuple], + *, + batch_size: int, + device, + workers: int, + prefetch_batches: int = 2, + copy_stream: torch.cuda.Stream | None = None, + on_prepared: Callable[[Any, str, dict], None] | None = None, + ): + for name, value in ( + ("batch_size", batch_size), + ("workers", workers), + ("prefetch_batches", prefetch_batches), + ): + if isinstance(value, bool) or not isinstance(value, int) or value < 1: + raise ValueError(f"{name} must be a positive integer") + self._jobs = list(jobs) + self._build_input = build_input + self._batch_size = batch_size + self._device = torch.device(device) + self._cuda = self._device.type == "cuda" + if self._cuda and self._device.index is None: + self._device = torch.device("cuda", torch.cuda.current_device()) + self._workers = workers + self._window = prefetch_batches * batch_size + self._copy_stream = copy_stream + self._on_prepared = on_prepared + self._slots = [_Slot() for _ in range(2)] if self._cuda else [None, None] + self._free: queue.Queue = queue.Queue() + self._ready: queue.Queue = queue.Queue() + self._stop = threading.Event() + self._pool: ThreadPoolExecutor | None = None + self._thread: threading.Thread | None = None + self._iterated = False + # Main-thread seconds spent waiting for the next batch (crop not hidden). + self.wait_s = 0.0 + self.num_valid = 0 + self.num_failed = 0 + + # ------------------------------------------------------------------ lifecycle + def __enter__(self) -> "StreamedCropBatches": + if self._thread is not None: + raise RuntimeError("StreamedCropBatches can only be entered once") + if self._cuda and self._copy_stream is None: + self._copy_stream = torch.cuda.Stream(device=self._device) + for index in range(2): + self._free.put(index) + self._pool = ThreadPoolExecutor(max_workers=self._workers) + self._thread = threading.Thread( + target=self._stage_loop, name="egohand-crop-stager", daemon=True + ) + self._thread.start() + return self + + def __exit__(self, exc_type, exc_value, traceback) -> None: + self.close() + + def close(self) -> None: + """Stop cropping, then wait for pending uploads and forward reads.""" + self._stop.set() + if self._thread is not None: + self._thread.join() + if self._pool is not None: + self._pool.shutdown(wait=True, cancel_futures=True) + self._pool = None + if self._cuda: + if self._copy_stream is not None: + self._copy_stream.synchronize() + for slot in self._slots: + if slot.used: + slot.consumed.synchronize() + slot.host = slot.device = None + while not self._ready.empty(): + self._ready.get_nowait() + + # ------------------------------------------------------------------ consumer + def __iter__(self) -> Iterator[StagedCropBatch]: + if self._thread is None: + raise RuntimeError("use StreamedCropBatches as a context manager") + if self._iterated: + raise RuntimeError("StreamedCropBatches can only be iterated once") + self._iterated = True + while True: + start = time.perf_counter() + item = self._ready.get() + self.wait_s += time.perf_counter() - start + if item is _DONE: + return + if isinstance(item, BaseException): + raise item + yield item + + def _release(self, slot_index: int, on_device: bool) -> None: + if on_device: + slot = self._slots[slot_index] + slot.consumed.record(torch.cuda.current_stream(self._device)) + slot.used = True + self._free.put(slot_index) + + # ------------------------------------------------------------------ producer + def _stage_loop(self) -> None: + try: + pending: deque = deque() + next_job = 0 + + def top_up() -> None: + nonlocal next_job + while next_job < len(self._jobs) and len(pending) < self._window: + pending.append( + self._pool.submit(self._build_input, self._jobs[next_job]) + ) + next_job += 1 + + top_up() + batch: list[dict] = [] + while pending: + if self._stop.is_set(): + return + image_id, hand, prepared = pending.popleft().result() + top_up() + if prepared is None: + self.num_failed += 1 + continue + self.num_valid += 1 + if self._on_prepared is not None: + self._on_prepared(image_id, hand, prepared) + batch.append(prepared) + if len(batch) == self._batch_size: + if not self._stage(batch): + return + batch = [] + if batch and not self._stage(batch): + return + self._ready.put(_DONE) + except BaseException as exc: # noqa: BLE001 - re-raised by the consumer + self._ready.put(exc) + + def _stage(self, batch: list[dict]) -> bool: + while True: + if self._stop.is_set(): + return False + try: + slot_index = self._free.get(timeout=0.05) + break + except queue.Empty: + continue + images = [prepared.pop("crop_tensor") for prepared in batch] + first = images[0] + uniform = first.dtype in _NUMPY_DTYPES and all( + image.device.type == "cpu" + and image.shape == first.shape + and image.dtype == first.dtype + for image in images + ) + if not (self._cuda and uniform): + # Fallback assembly for CPU or non-uniform crops. + self._ready.put( + StagedCropBatch(batch, torch.stack(images), slot_index, self, False) + ) + return True + slot = self._slots[slot_index] + count = len(images) + if ( + slot.host is None + or slot.host.shape[1:] != first.shape + or slot.host.dtype != first.dtype + ): + if slot.uploaded: + slot.ready.synchronize() + with torch.cuda.device(self._device): + slot.host = torch.empty( + (self._batch_size, *first.shape), + dtype=first.dtype, + pin_memory=True, + ) + with torch.cuda.stream(self._copy_stream): + if slot.used: + self._copy_stream.wait_event(slot.consumed) + slot.device = torch.empty( + (self._batch_size, *first.shape), + dtype=first.dtype, + device=self._device, + ) + elif slot.uploaded: + # The previous upload must have finished reading this pinned buffer. + slot.ready.synchronize() + host = slot.host[:count] + host_array = host.numpy() + for index, image in enumerate(images): + # Single-threaded copy: no OpenMP team in this thread. + np.copyto(host_array[index], image.detach().numpy()) + del images, first + with torch.cuda.device(self._device), torch.cuda.stream(self._copy_stream): + if slot.used: + # The forward that read this device slot must have finished. + self._copy_stream.wait_event(slot.consumed) + device_images = slot.device[:count] + device_images.copy_(host, non_blocking=True) + slot.ready.record(self._copy_stream) + slot.uploaded = True + self._ready.put(StagedCropBatch(batch, device_images, slot_index, self, True)) + return True diff --git a/src/python/isaaccapture_egopost/inference/pipeline/inference_weights.py b/src/python/isaaccapture_egopost/inference/pipeline/inference_weights.py new file mode 100644 index 0000000000..f463346e05 --- /dev/null +++ b/src/python/isaaccapture_egopost/inference/pipeline/inference_weights.py @@ -0,0 +1,311 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: LicenseRef-OpenMDW-1.1 + +"""Inference-only EgoHand weights: export, read, and strict key checks. + +A training ``.ckpt`` (PyTorch Lightning, ``weights_only=False`` pickle) also +carries optimizer state and is several times larger than the model. The +export written by :func:`export_inference_weights` is a folder with + +* ``model.safetensors``: the checkpoint ``state_dict`` tensors, unchanged; +* ``config.json``: the training cfg (``hyper_parameters.cfg``), the top-level + ``egohand_*`` checkpoint fields that + ``EgoHand.validate_camera_depth_checkpoint`` reads, and provenance. + +Loading it needs neither pickle nor ``weights_only=False``. Both formats go +through :func:`read_checkpoint`, so the CLI's ``--egohand_ckpt`` accepts either. +""" + +from __future__ import annotations + +import hashlib +import json +import logging +from dataclasses import dataclass +from pathlib import Path +from typing import Callable + +log = logging.getLogger(__name__) + +WEIGHTS_FILENAME = "model.safetensors" +CONFIG_FILENAME = "config.json" +EXPORT_FORMAT = "egohand-inference-weights/1" + +#: Model keys that a checkpoint is allowed to omit. The SOMA hand layers are +#: rebuilt from the SOMA asset folder at construction and wrapped in +#: ``NonPersistentModuleWrapper`` (``egohand/models/soma_wrapper.py``), whose +#: state-dict hook removes them from every saved checkpoint; ``load_state_dict`` +#: still reports them as missing (``left``/``right`` alias the wrapped layers). +#: Every other model key must be present, including any future learnable +#: parameter added directly under ``soma_hand``. +ALLOWED_MISSING_PREFIXES: tuple[str, ...] = ( + "soma_hand.hand_left.", + "soma_hand.hand_right.", + "soma_hand.left.", + "soma_hand.right.", +) + +#: Checkpoint keys that the model is allowed not to own. None: an unexpected +#: key means the checkpoint and the model configuration disagree. +ALLOWED_UNEXPECTED_PREFIXES: tuple[str, ...] = () + + +@dataclass +class CheckpointSource: + """Configuration read eagerly; tensors read on demand (possibly on another thread).""" + + path: Path + cfg: dict + checkpoint_fields: dict + load_state_dict: Callable[[], dict] + format: str + state_dict_keys: Callable[[], set] + + def validation_view(self) -> dict: + """The subset of a checkpoint dict that model-side validators read.""" + return {"hyper_parameters": {"cfg": self.cfg}, **self.checkpoint_fields} + + +def is_inference_export(path: str | Path) -> bool: + """True for an export folder or its ``model.safetensors`` file.""" + path = Path(path) + if path.is_dir(): + return (path / WEIGHTS_FILENAME).is_file() and ( + path / CONFIG_FILENAME + ).is_file() + return ( + path.is_file() + and path.name == WEIGHTS_FILENAME + and (path.parent / CONFIG_FILENAME).is_file() + ) + + +def _json_value(value, key: str): + """Convert checkpoint metadata to JSON types, rejecting anything else.""" + if isinstance(value, (str, bool, int, float)) or value is None: + return value + if isinstance(value, (list, tuple)): + return [_json_value(item, key) for item in value] + if isinstance(value, dict): + return {str(k): _json_value(v, f"{key}.{k}") for k, v in value.items()} + if hasattr(value, "tolist"): # numpy / torch scalars and small arrays + return _json_value(value.tolist(), key) + raise TypeError(f"checkpoint field {key!r} has non-JSON value {type(value)!r}") + + +def _checkpoint_fields(ckpt: dict) -> dict: + """Top-level ``egohand_*`` fields consumed by checkpoint validation.""" + return { + key: _json_value(value, key) + for key, value in ckpt.items() + if isinstance(key, str) and key.startswith("egohand_") + } + + +def _cfg_container(cfg) -> dict: + from omegaconf import DictConfig, OmegaConf + + if isinstance(cfg, DictConfig): + return OmegaConf.to_container(cfg, resolve=False) + return OmegaConf.to_container(OmegaConf.create(cfg), resolve=False) + + +def _torch_load(path: Path) -> dict: + """Load a training checkpoint; memory-map so optimizer state is never read.""" + import torch + + try: + return torch.load(str(path), map_location="cpu", weights_only=False, mmap=True) + except RuntimeError as exc: + # Legacy (non-zip) serialization cannot be memory-mapped. + log.info("[EgoHand] mmap load unavailable (%s); reading whole checkpoint", exc) + return torch.load(str(path), map_location="cpu", weights_only=False) + + +def read_checkpoint(path: str | Path) -> CheckpointSource: + """Read the cfg now and return a callable that reads the tensors later.""" + path = Path(path) + if is_inference_export(path): + folder = path if path.is_dir() else path.parent + config = json.loads((folder / CONFIG_FILENAME).read_text()) + if config.get("format") != EXPORT_FORMAT: + raise ValueError( + f"{folder / CONFIG_FILENAME}: unsupported format {config.get('format')!r}; " + f"expected {EXPORT_FORMAT!r}" + ) + weights = folder / WEIGHTS_FILENAME + + def load_tensors() -> dict: + from safetensors.torch import load_file + + return load_file(str(weights), device="cpu") + + def tensor_names() -> set: + from safetensors import safe_open + + with safe_open(str(weights), framework="pt", device="cpu") as handle: + return set(handle.keys()) + + return CheckpointSource( + path=folder, + cfg=config["cfg"], + checkpoint_fields=config.get("checkpoint_fields", {}), + load_state_dict=load_tensors, + format=EXPORT_FORMAT, + state_dict_keys=tensor_names, + ) + + if path.is_dir(): + raise FileNotFoundError( + f"{path} is a directory but is missing {WEIGHTS_FILENAME} or {CONFIG_FILENAME}" + ) + + ckpt = _torch_load(path) + state_dict = ckpt["state_dict"] + return CheckpointSource( + path=path, + cfg=_cfg_container(ckpt["hyper_parameters"]["cfg"]), + checkpoint_fields=_checkpoint_fields(ckpt), + load_state_dict=lambda: state_dict, + format="lightning-ckpt", + state_dict_keys=lambda: set(state_dict), + ) + + +def check_state_dict_keys( + missing_keys, unexpected_keys, *, ignore_unexpected: bool = False +) -> None: + """Raise unless every missing/unexpected key is on its allowlist. + + ``ignore_unexpected``: checkpoint keys the model does not own (e.g. extra + training-time tensors) only log a warning. Missing keys always raise: the + model would keep those tensors uninitialized or randomly initialized. + """ + bad_missing = sorted( + key for key in missing_keys if not key.startswith(ALLOWED_MISSING_PREFIXES) + ) + bad_unexpected = sorted( + key + for key in unexpected_keys + if not key.startswith(ALLOWED_UNEXPECTED_PREFIXES) + ) + + def preview(keys): + return ", ".join(keys[:20]) + (" ..." if len(keys) > 20 else "") + + if bad_unexpected and ignore_unexpected and not bad_missing: + log.warning( + "[EgoHand] ignoring %d checkpoint key(s) the model does not own [%s]", + len(bad_unexpected), + preview(bad_unexpected), + ) + return + if bad_missing or bad_unexpected: + raise RuntimeError( + "EgoHand checkpoint does not match the model built from its cfg: " + f"{len(bad_missing)} missing key(s) outside the allowlist " + f"{ALLOWED_MISSING_PREFIXES} [{preview(bad_missing)}]; " + f"{len(bad_unexpected)} unexpected key(s) [{preview(bad_unexpected)}]" + + ( + ". A checkpoint with extra keys only loads with " + "load_egohand_model(..., ignore_unexpected_keys=True)" + if bad_unexpected and not bad_missing + else "" + ) + ) + + +def expected_model_keys(cfg) -> set[str]: + """Checkpoint keys an ``EgoHand(cfg)`` needs, computed on the ``meta`` device.""" + import torch + from omegaconf import OmegaConf + + from egohand.models.egohand import EgoHand + + cfg = OmegaConf.create(OmegaConf.to_container(cfg, resolve=False)) + cfg.backbone_weights = None + backbone = cfg.get("backbone", None) + if backbone is not None and str(backbone.get("_target_", "")).endswith( + "DinoV3Backbone" + ): + cfg.backbone.meta_init = True + with torch.device("meta"): + model = EgoHand(cfg, build_soma_hand=False) + return set(model.state_dict()) + + +def check_checkpoint_keys(source: "CheckpointSource", cfg) -> None: + """Key-set check of ``source`` against ``cfg`` from key names only.""" + expected = expected_model_keys(cfg) + present = source.state_dict_keys() + check_state_dict_keys(expected - present, present - expected) + + +def _sha256(path: Path, chunk_bytes: int = 64 << 20) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + while chunk := handle.read(chunk_bytes): + digest.update(chunk) + return digest.hexdigest() + + +def export_inference_weights( + checkpoint_path: str | Path, + output_dir: str | Path, + *, + source_sha256: bool = True, +) -> dict: + """Write ``model.safetensors`` + ``config.json`` from a training checkpoint. + + Tensors are written exactly as stored (same keys, dtypes and values); + optimizer, scheduler, loop and callback state are dropped. + + Returns: + The ``config.json`` content. + """ + import torch + from safetensors.torch import save_file + + checkpoint_path = Path(checkpoint_path) + output_dir = Path(output_dir) + ckpt = _torch_load(checkpoint_path) + state_dict = ckpt["state_dict"] + tensors = {} + for key, value in state_dict.items(): + if not isinstance(value, torch.Tensor): + raise TypeError(f"state_dict[{key!r}] is {type(value)!r}, not a tensor") + # safetensors rejects shared/strided storage; a private contiguous + # copy keeps the values bit-for-bit. + tensors[key] = value.detach().to("cpu").contiguous().clone() + config = { + "format": EXPORT_FORMAT, + "cfg": _cfg_container(ckpt["hyper_parameters"]["cfg"]), + "checkpoint_fields": _checkpoint_fields(ckpt), + "tensors": { + "count": len(tensors), + "numel": int(sum(t.numel() for t in tensors.values())), + "dtypes": sorted({str(t.dtype) for t in tensors.values()}), + }, + "source": { + "file": checkpoint_path.name, + "bytes": checkpoint_path.stat().st_size, + "sha256": _sha256(checkpoint_path) if source_sha256 else None, + "global_step": _json_value(ckpt.get("global_step"), "global_step"), + }, + } + output_dir.mkdir(parents=True, exist_ok=True) + weights_tmp = output_dir / (WEIGHTS_FILENAME + ".tmp") + try: + save_file(tensors, str(weights_tmp), metadata={"format": EXPORT_FORMAT}) + weights_tmp.replace(output_dir / WEIGHTS_FILENAME) + except BaseException: + weights_tmp.unlink(missing_ok=True) + raise + config_tmp = output_dir / (CONFIG_FILENAME + ".tmp") + try: + config_tmp.write_text(json.dumps(config, indent=2) + "\n") + config_tmp.replace(output_dir / CONFIG_FILENAME) + except BaseException: + config_tmp.unlink(missing_ok=True) + raise + return config diff --git a/src/python/isaaccapture_egopost/inference/pipeline/mhr_presort.py b/src/python/isaaccapture_egopost/inference/pipeline/mhr_presort.py new file mode 100644 index 0000000000..ad6a90b0df --- /dev/null +++ b/src/python/isaaccapture_egopost/inference/pipeline/mhr_presort.py @@ -0,0 +1,292 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: LicenseRef-OpenMDW-1.1 + +"""MHR TorchScript forward with the pose-correctives sparse matrix coalesced once. + +Works around a CCCL 3.0.1 ``cub::DeviceMergeSort`` race (NVIDIA/cccl#5297, +fixed in CCCL 3.0.3) triggered when PyTorch 2.13.0+cu130 coalesces MHR's +``SparseLinear`` COO tensor on every SOMA call on sm_90+ GPUs. Applied only +when TorchScript ``.code`` matches ``_KNOWN_CODE`` and stored indices are +strictly row-major increasing. Inference only (detached sparse weights). +""" + +from __future__ import annotations + +import contextlib +import hashlib +import logging +from typing import Any + +import torch +from torch import nn + +log = logging.getLogger(__name__) + +# sha256[:16] of ``.code`` for methods reimplemented by PresortedMHR +# (py-soma-x 0.3.0 asset MHR/mhr_model_lod1.pt, PyTorch 2.13.0). +_KNOWN_CODE = { + "": "9b6e6a25f5875f04", # MHRDemo.forward + "pose_correctives_model": "3bb8b1f2fb155b90", # MHRPoseCorrectivesModel.forward + "pose_correctives_model.pose_dirs_predictor": "34e7d6ee713f13f2", # Sequential + "pose_correctives_model.pose_dirs_predictor.0": "7975ce70ffd1cd10", # SparseLinear + "pose_correctives_model.pose_dirs_predictor.1": "c406775c105bccef", # ReLU + "pose_correctives_model.pose_dirs_predictor.2": "5ed428953f0a8012", # Linear +} + + +def _code_digest(module: Any) -> str | None: + try: + return hashlib.sha256(module.code.encode()).hexdigest()[:16] + except (AttributeError, RuntimeError): + return None + + +def _get(module: Any, dotted: str) -> Any: + for part in filter(None, dotted.split(".")): + module = getattr(module, part) + return module + + +def check_mhr_torchscript(ts_module: Any) -> str | None: + """Return why ``ts_module`` cannot be rewritten, or None if it can.""" + if not isinstance(ts_module, torch.jit.ScriptModule): + return "not a TorchScript module" + for name, digest in _KNOWN_CODE.items(): + try: + sub = _get(ts_module, name) + except AttributeError: + return f"no submodule {name!r}" + got = _code_digest(sub) + if got != digest: + return f"code of {name or 'forward'!r} is {got}, expected {digest}" + sparse = _get(ts_module, "pose_correctives_model.pose_dirs_predictor.0") + idx, weight = sparse.sparse_indices, sparse.sparse_weight + raw_shape = tuple(int(v) for v in sparse.sparse_shape) + if len(raw_shape) != 2 or raw_shape[0] <= 0 or raw_shape[1] <= 0: + return f"unexpected sparse shape {raw_shape}" + rows, cols = raw_shape + if ( + idx.dim() != 2 + or idx.shape[0] != 2 + or weight.dim() != 1 + or idx.shape[1] != weight.shape[0] + or idx.is_floating_point() + or idx.is_complex() + or idx.dtype == torch.bool + ): + return f"unexpected sparse layout {tuple(idx.shape)} / {tuple(weight.shape)}" + with torch.no_grad(): + idx64 = idx.to(torch.int64) + flat = idx64[0] * cols + idx64[1] + ok = ( + bool((idx64 >= 0).all()) + and bool((idx64[0] < rows).all()) + and bool((idx64[1] < cols).all()) + and bool((flat[1:] > flat[:-1]).all()) + ) + if not ok: + return "sparse indices are not strictly increasing in row-major order" + return None + + +class PresortedMHR(nn.Module): + """``MHRDemo.forward`` with the pose-correctives sparse matrix built once, coalesced. + + Same signature and outputs as the TorchScript module: ``(verts, skel_state)``. + """ + + def __init__(self, ts_module: torch.jit.ScriptModule) -> None: + super().__init__() + self.ts = ts_module + self._cache: tuple[tuple[Any, ...], torch.Tensor] | None = None + + def _apply(self, fn: Any, recurse: bool = True) -> PresortedMHR: + self._cache = None + return super()._apply(fn, recurse=recurse) + + def _sparse_matrix(self) -> torch.Tensor: + layer = _get(self.ts, "pose_correctives_model.pose_dirs_predictor.0") + idx, weight = layer.sparse_indices, layer.sparse_weight + key = ( + idx.device, + idx.dtype, + idx.data_ptr(), + idx._version, + weight.device, + weight.dtype, + weight.data_ptr(), + weight._version, + ) + entry = self._cache + if entry is None or entry[0] != key: + rows, cols = (int(v) for v in layer.sparse_shape) + with torch.no_grad(): + cached = torch.sparse_coo_tensor( + idx.detach(), + weight.detach(), + (rows, cols), + is_coalesced=True, + check_invariants=False, # checked once in check_mhr_torchscript + ) + self._cache = (key, cached) + return cached + return entry[1] + + def forward( + self, + identity_coeffs: torch.Tensor, + model_parameters: torch.Tensor, + face_expr_coeffs: torch.Tensor, + apply_correctives: bool = True, + ) -> tuple[torch.Tensor, torch.Tensor]: + ts = self.ts + if identity_coeffs.dim() != 2: + raise AssertionError( + f"Expected batched (n_rows >= 1) identity coeffs, got {tuple(identity_coeffs.shape)}" + ) + if face_expr_coeffs.dim() != 2: + raise AssertionError( + "Expected batched (n_rows >= 1) face expressions coeffs, " + f"got {tuple(face_expr_coeffs.shape)}" + ) + # TorchScript ignores Python autocast; disable it here so the eager sparse + # matmul matches the TorchScript precision even under an outer autocast. + device_type = identity_coeffs.device.type + autocast_ctx = ( + torch.amp.autocast(device_type, enabled=False) + if device_type in ("cuda", "cpu") + else contextlib.nullcontext() + ) + # Drop intermediates early to limit peak memory (linear_model_unposed stays + # live across skin_points in this Python frame). + with autocast_ctx: + character = ts.character_torch + identity_rest_pose = character.blend_shape(identity_coeffs) + joint_parameters = character.model_parameters_to_joint_parameters( + torch.cat([model_parameters, torch.zeros_like(identity_coeffs)], 1) + ) + skel_state = character.joint_parameters_to_skeleton_state(joint_parameters) + face_expressions = ts.face_expressions_model(face_expr_coeffs) + linear_model_unposed = identity_rest_pose + face_expressions + del identity_rest_pose, face_expressions + if apply_correctives: + correctives = ts.pose_correctives_model + feats = correctives._pose_features_from_joint_params(joint_parameters) + del joint_parameters + rows = feats.shape[0] + predictor = correctives.pose_dirs_predictor + relu, linear = getattr(predictor, "1"), getattr(predictor, "2") + hidden = torch.matmul(self._sparse_matrix(), feats.T).T # SparseLinear + del feats + hidden = relu(hidden) + corrective = linear(hidden).reshape(rows, -1, 3) + del hidden + if torch.is_grad_enabled(): + linear_model_unposed = linear_model_unposed + corrective + else: + linear_model_unposed.add_(corrective) + del corrective + else: + del joint_parameters + verts = character.skin_points(skel_state, linear_model_unposed) + return verts, skel_state + + +def presort_mhr_sparse(model: nn.Module) -> dict[str, Any]: + """Swap every MHR TorchScript model wrapped under ``model`` for ``PresortedMHR``. + + Looks for modules with a ``module`` attribute holding the MHR TorchScript + model (py-soma-x's ``NonPersistentModuleWrapper``). Returns + ``{"patched": [names], "skipped": {name: reason}}``. + """ + patched: list[str] = [] + skipped: dict[str, str] = {} + for name, wrapper in list(model.named_modules()): + inner = getattr(wrapper, "module", None) + if isinstance(inner, PresortedMHR) or not isinstance( + inner, torch.jit.ScriptModule + ): + continue + if getattr(inner, "original_name", None) != "MHRDemo": + continue + reason = check_mhr_torchscript(inner) + if reason is not None: + skipped[name] = reason + log.warning( + "MHR sparse layer left as is (%s): %s", name or "", reason + ) + continue + wrapper.module = PresortedMHR(inner) + wrapper.module._sparse_matrix() # build now, not inside the first SOMA call + patched.append(name) + return {"patched": patched, "skipped": skipped} + + +def _has_unpatched_mhr(model: nn.Module) -> bool: + """True if ``model`` contains any MHR identity or TorchScript model not wrapped by ``PresortedMHR``.""" + wrapped_ids = { + id(module.ts) for module in model.modules() if isinstance(module, PresortedMHR) + } + for module in model.modules(): + if ( + isinstance(module, torch.jit.ScriptModule) + and getattr(module, "original_name", None) == "MHRDemo" + and id(module) not in wrapped_ids + ): + return True + if type(module).__name__ == "MHRHandIdentityModel" and not any( + isinstance(sub, PresortedMHR) for sub in module.modules() + ): + return True + return False + + +def presort_required(device: str | torch.device) -> str | None: + """Return why the per-call merge sort can fault in this process, or None. + + Applies to PyTorch CUDA 13.0 builds (CCCL 3.0.x, NVIDIA/cccl#5297) on + sm_90+ GPUs, where the merge kernels use programmatic dependent launch. + """ + cuda = torch.version.cuda or "" + device = torch.device(device) + if ( + not (cuda == "13.0" or cuda.startswith("13.0.")) + or device.type != "cuda" + or not torch.cuda.is_available() + ): + return None + major, minor = torch.cuda.get_device_capability(device) + if major < 9: + return None + return ( + f"PyTorch {torch.__version__} (CUDA {cuda}, CCCL 3.0.x) on an " + f"sm_{major}{minor} GPU" + ) + + +def apply_mhr_presort(model: nn.Module, device: str | torch.device) -> dict[str, Any]: + """Run ``presort_mhr_sparse(model)`` and fail if an exposed process stays unpatched. + + Raises ``RuntimeError`` when any MHR model remains unpatched and + ``presort_required(device)`` holds; otherwise logs a warning and keeps the + TorchScript forward. + """ + info = presort_mhr_sparse(model) + if not info["skipped"] and not _has_unpatched_mhr(model): + if info["patched"]: + log.info("MHR sparse layer coalesced once at load: %s", info["patched"]) + return info + problem = ( + "MHR sparse layer could not be coalesced at load " + f"(patched {info['patched']}, skipped {info['skipped'] or 'none'})" + ) + exposed = presort_required(device) + if exposed is not None: + raise RuntimeError( + f"{problem}. With {exposed} the per-call merge sort of that layer can " + "fault (NVIDIA/cccl#5297). Update _KNOWN_CODE in " + "inference/pipeline/mhr_presort.py for this py-soma-x / PyTorch, or " + "pass --no-mhr_presorted_sparse with a PyTorch built with CCCL >= 3.0.3." + ) + log.warning("%s; keeping the TorchScript forward.", problem) + return info diff --git a/src/python/isaaccapture_egopost/inference/pipeline/predictor.py b/src/python/isaaccapture_egopost/inference/pipeline/predictor.py index 062bde6d99..3b275e3269 100644 --- a/src/python/isaaccapture_egopost/inference/pipeline/predictor.py +++ b/src/python/isaaccapture_egopost/inference/pipeline/predictor.py @@ -4,10 +4,13 @@ """EgoHand checkpoint loading, forward pass, and SOMA NPZ writing. Owns the full model lifecycle for inference: -- ``load_egohand_model``: loads a checkpoint and returns a CPU-eval model. +- ``load_egohand_model``: loads a checkpoint (.ckpt or inference export) and + returns an eval model with strict key checks. - ``EgoHandPredictor``: owns one loaded model, runs batched crop-and-forward loops, and writes soma.io-compatible prediction files. - ``EgoHandPredictor.from_checkpoint``: convenience factory that combines both steps. +- ``EgoHandPredictor.load_in_background``: the same on a worker thread + (``PendingEgoHandPredictor``), so loading overlaps decoding and detection. ``run()`` returns the per-frame result dict schema consumed by the SOMA NPZ writer. Optional perspective cropping maps each detected hand region to a virtual pinhole @@ -20,18 +23,31 @@ import io import logging import os +import threading import time from concurrent.futures import ThreadPoolExecutor from pathlib import Path +from typing import Any, Callable import numpy as np import torch from omegaconf import OmegaConf from inference.camera.camera_models import CameraModel +from inference.camera.fisheye_crop_cuda import ( + crop_chunk_gpu, + supports_gpu_perspective_crop, +) from inference.camera.perspective_crop import perspective_crop from egohand.utils.cam_utils import compute_transl_full_cam from inference.perf import PerfReporter, PerfStage +from inference.pipeline.crop_stream import StreamedCropBatches +from inference.pipeline.inference_weights import ( + CheckpointSource, + check_checkpoint_keys, + check_state_dict_keys, + read_checkpoint, +) from inference.pipeline.results_io import KEYPOINT_RELIABILITY_FIELDS from inference.preprocessing.crop import ( IMAGENET_MEAN, @@ -45,7 +61,9 @@ mirror_left_prediction_to_right, prepare_right_hand_model_input, ) +from inference.pipeline.soma_batching import SomaBatcher from inference.postprocessing.adaptive_smoothing import ( + _project_batch_to_crop_frame, smooth_adaptive_hand_results, validate_frame_times, ) @@ -55,26 +73,11 @@ _VALID_TARGETS = ("egohand.EgoHand",) -def load_egohand_model(checkpoint_path: str | Path, soma_hand_data_folder: str | Path): - """Load a EgoHand model from a checkpoint. - - Reads the training-time cfg stored in ``ckpt["hyper_parameters"]["cfg"]``, - overrides the two inference-only knobs (skip pretrained backbone load, - redirect SOMAHand asset folder), instantiates the right model class, and - loads weights. Returns the model in CPU eval mode; the caller moves it to - the target device. - - Args: - checkpoint_path: Path to a ``.ckpt`` file produced by this repo's - training entrypoint. - soma_hand_data_folder: SOMAHand asset folder to redirect ``cfg.soma_hand.data_root``. - - Returns: - model: EgoHand instance in eval mode on CPU. - target: The ``_target_`` string from the checkpoint cfg (for logging). - """ - ckpt = torch.load(str(checkpoint_path), map_location="cpu", weights_only=False) - cfg = OmegaConf.create(ckpt["hyper_parameters"]["cfg"]) +def _validated_cfg( + source: CheckpointSource, soma_hand_data_folder: str | Path +) -> tuple[Any, str]: + """Training cfg with the inference-only overrides applied.""" + cfg = OmegaConf.create(source.cfg) target = str(cfg.get("_target_", "")) if not any(target.endswith(t) for t in _VALID_TARGETS): raise ValueError( @@ -83,17 +86,251 @@ def load_egohand_model(checkpoint_path: str | Path, soma_hand_data_folder: str | ) cfg.backbone_weights = None cfg.soma_hand.data_root = str(soma_hand_data_folder) + return cfg, target + + +def load_egohand_model( + checkpoint_path: str | Path | CheckpointSource, + soma_hand_data_folder: str | Path, + device: str | torch.device = "cpu", + *, + ignore_unexpected_keys: bool = False, +) -> tuple[Any, str]: + """Load an EgoHand eval model from a ``.ckpt`` file, export folder, or ``CheckpointSource``. + + Allocates DINOv3 on ``meta`` before loading weights and checks checkpoint + keys strictly outside ``inference_weights.ALLOWED_MISSING_PREFIXES``. + """ + source = ( + checkpoint_path + if isinstance(checkpoint_path, CheckpointSource) + else read_checkpoint(checkpoint_path) + ) + cfg, target = _validated_cfg(source, soma_hand_data_folder) + backbone_cfg = cfg.get("backbone", None) + meta_backbone = backbone_cfg is not None and str( + backbone_cfg.get("_target_", "") + ).endswith("DinoV3Backbone") + if meta_backbone: + cfg.backbone.meta_init = True from egohand.models.egohand import EgoHand model = EgoHand(cfg) + model.validate_camera_depth_checkpoint(source.validation_view()) + if meta_backbone: + model.backbone.encoder.to_empty(device=device) + model = model.to(device) - model.validate_camera_depth_checkpoint(ckpt) - model.load_state_dict(ckpt["state_dict"], strict=False) - log.info("[EgoHand] Loaded checkpoint: %s", checkpoint_path) + state_dict = source.load_state_dict() + if meta_backbone: + # to_empty() leaves memory uninitialized: every encoder tensor must come + # from the checkpoint, independently of the allowlist below. + encoder_keys = { + f"backbone.encoder.{key}" for key in model.backbone.encoder.state_dict() + } + absent = sorted(encoder_keys - state_dict.keys()) + if absent: + raise RuntimeError( + f"Checkpoint lacks {len(absent)} DINOv3 encoder tensor(s): {absent[:10]}" + ) + # Tensors to_empty() materialized that no checkpoint can fill (buffers + # registered with persistent=False) would keep uninitialized memory. + stray = sorted( + name + for name, _ in model.backbone.encoder.named_buffers() + if name not in model.backbone.encoder.state_dict() + ) + if stray: + raise RuntimeError( + f"DINOv3 encoder has non-persistent buffer(s) {stray[:10]} that " + "meta initialization would leave uninitialized" + ) + missing, unexpected = model.load_state_dict(state_dict, strict=False) + check_state_dict_keys(missing, unexpected, ignore_unexpected=ignore_unexpected_keys) + log.info( + "[EgoHand] Loaded %s checkpoint %s: %d tensors; %d allowlisted missing key(s)", + source.format, + source.path, + len(state_dict), + len(missing), + ) return model.eval(), target +#: OpenUSD modules that py-soma-x imports (``soma.io``) during model construction. +_USD_MODULES = ("pxr.Gf", "pxr.Sdf", "pxr.Usd", "pxr.UsdGeom", "pxr.UsdSkel", "pxr.Vt") + + +def preload_usd_libraries() -> None: + """Import OpenUSD on the calling thread before spawning loader threads. + + Prevents a glibc loader-lock / GIL deadlock when a background load imports + ``soma`` while another thread triggers C++ ``thread_local`` registration. + No-op if OpenUSD is not installed. + """ + import importlib + + for name in _USD_MODULES: + try: + importlib.import_module(name) + except ImportError: + return + + +#: Unique source frames cropped per GPU chunk in single-video perspective mode. +_GPU_PERSPECTIVE_CROP_CHUNK_FRAMES = 32 + + +class _GpuStagedCropBatch: + """One forward batch of uint8 RGB perspective crops already on ``device``.""" + + def __init__( + self, + hand_data: list[dict[str, Any]], + crops_u8: torch.Tensor, + mean: torch.Tensor, + std: torch.Tensor, + ) -> None: + self.hand_data = hand_data + self._crops_u8: torch.Tensor | None = crops_u8 + self._mean = mean + self._std = std + + def images(self, device) -> torch.Tensor: + if self._crops_u8 is None: + raise RuntimeError("Batch images already released") + torch_device = torch.device(device) + crops = self._crops_u8 + if crops.device != torch_device: + crops = crops.to(device=torch_device) + crops_f = crops.permute(0, 3, 1, 2).contiguous().to(torch.float32) + mean = ( + self._mean + if self._mean.device == torch_device + else self._mean.to(device=torch_device) + ) + std = ( + self._std + if self._std.device == torch_device + else self._std.to(device=torch_device) + ) + return ((crops_f / 255.0) - mean) / std + + def release(self) -> None: + self._crops_u8 = None + + +class _GpuPerspectiveCropBatches: + """Chunked GPU perspective cropper yielding ``_GpuStagedCropBatch`` slices.""" + + def __init__( + self, + images_bgr, + gpu_crop_jobs: list[tuple[int, str, str, np.ndarray]], + camera: CameraModel, + *, + batch_size: int, + device: str | torch.device, + camera_mode: str, + on_prepared: Callable[[str, str, dict[str, Any]], None] | None = None, + chunk_frames: int = _GPU_PERSPECTIVE_CROP_CHUNK_FRAMES, + ) -> None: + self._images_bgr = images_bgr + self._gpu_crop_jobs = gpu_crop_jobs + self._camera = camera + self._batch_size = int(batch_size) + self._device = torch.device(device) + self._camera_mode = camera_mode + self._on_prepared = on_prepared + self._chunk_frames = max(1, int(chunk_frames)) + self._mean = torch.tensor( + IMAGENET_MEAN, device=self._device, dtype=torch.float32 + ).view(1, 3, 1, 1) + self._std = torch.tensor( + IMAGENET_STD, device=self._device, dtype=torch.float32 + ).view(1, 3, 1, 1) + self.crop_s = 0.0 + + def _iter_job_chunks(self): + chunk: list[tuple[int, str, str, np.ndarray]] = [] + chunk_frames: set[int] = set() + for job in self._gpu_crop_jobs: + frame_idx = job[0] + if ( + frame_idx not in chunk_frames + and len(chunk_frames) >= self._chunk_frames + ): + yield chunk + chunk = [] + chunk_frames = set() + chunk.append(job) + chunk_frames.add(frame_idx) + if chunk: + yield chunk + + def __iter__(self): + pending_records: list[dict[str, Any]] = [] + pending_crops: list[torch.Tensor] = [] + pending_count = 0 + + for chunk_jobs in self._iter_job_chunks(): + t0 = time.perf_counter() + chunk_records, chunk_crops_u8, _ = crop_chunk_gpu( + self._images_bgr, + chunk_jobs, + self._camera, + IMG_SIZE, + camera_mode=self._camera_mode, + device=self._device, + return_gpu_crops=True, + ) + self.crop_s += time.perf_counter() - t0 + if not chunk_records: + continue + if self._on_prepared is not None: + for rec in chunk_records: + self._on_prepared(rec["image_id"], rec["real_hand_side"], rec) + pending_records.extend(chunk_records) + pending_crops.append(chunk_crops_u8) + pending_count += len(chunk_records) + + if pending_count >= self._batch_size: + combined = ( + pending_crops[0] + if len(pending_crops) == 1 + else torch.cat(pending_crops, dim=0) + ) + offset = 0 + while pending_count - offset >= self._batch_size: + end = offset + self._batch_size + batch_records = pending_records[offset:end] + # Clone slice when a chunk yields multiple batches so each + # released batch frees memory cleanly once consumed. + batch_crops = combined[offset:end] + yield _GpuStagedCropBatch( + batch_records, batch_crops, self._mean, self._std + ) + offset = end + if offset < pending_count: + pending_records = pending_records[offset:] + # Clone tiny remainder (< batch_size) so the full chunk can be freed. + pending_crops = [combined[offset:].clone()] + pending_count = len(pending_records) + else: + pending_records = [] + pending_crops = [] + pending_count = 0 + + if pending_records: + combined = ( + pending_crops[0] + if len(pending_crops) == 1 + else torch.cat(pending_crops, dim=0) + ) + yield _GpuStagedCropBatch(pending_records, combined, self._mean, self._std) + + class EgoHandPredictor: """Run bbox-conditioned predictions with an already-loaded EgoHand model. @@ -113,8 +350,22 @@ class EgoHandPredictor: frame timestamps in seconds. ``False`` (default) returns raw output. use_perspective_cropping: Use perspective cropping for each hand bbox with the source camera's ``project`` and ``unproject`` methods. + soma_batch_size: 0 (default) runs the SOMA hand layer once per batch. + Otherwise the left layer runs once per ``soma_batch_size // + batch_size`` batches and the right-hand mirror once per at most + ``soma_batch_size`` right hands, each padded to ``soma_batch_size`` + rows. Changes only float32 rounding (batched-product reduction order). """ + # Crop while earlier batches run (see ``inference/pipeline/crop_stream.py``). + # Same crops, order and batches as building every crop first; False + # restores the build-everything-first path. + stream_crops = True + # Use ``fisheye_crop_cuda.crop_chunk_gpu`` automatically on CUDA when + # ``use_perspective_cropping`` is True and the camera is supported + # (FISHEYE624, KB4, PINHOLE). Set to False to force CPU OpenCV cropping. + gpu_perspective_crop = True + def __init__( self, model, @@ -124,8 +375,17 @@ def __init__( smooth: bool = False, use_perspective_cropping: bool = False, perf_reporter: PerfReporter | None = None, + soma_batch_size: int = 0, ): + if ( + isinstance(soma_batch_size, bool) + or not isinstance(soma_batch_size, int) + or soma_batch_size < 0 + or 0 < soma_batch_size < batch_size + ): + raise ValueError("soma_batch_size must be 0 or at least batch_size") self.batch_size = batch_size + self.soma_batch_size = int(soma_batch_size) self.device = device self.dtype = dtype self.smooth = bool(smooth) @@ -133,6 +393,8 @@ def __init__( self._use_perspective_cropping = use_perspective_cropping self.model = model.eval().to(device) + # What from_checkpoint's apply_mhr_presort patched (None: not applied). + self.mhr_presort = None self._model_wrist_orients = None if self._use_perspective_cropping: @@ -167,6 +429,83 @@ def __init__( paired_names = ["Root"] + left_joint_names + right_joint_names self._pose_mirror = PoseMirror_SOMA(paired_names, root_name="Root") + @property + def camera_mode(self) -> str: + """Camera parameterization of the loaded checkpoint.""" + return getattr(self.model, "camera_mode", "weak_perspective") + + @classmethod + def load_in_background( + cls, + egohand_ckpt_path: str | Path, + soma_hand_data_folder: str | Path, + batch_size: int, + device: str = "cuda", + dtype: torch.dtype = torch.float32, + smooth: bool = False, + dino_compile: bool = False, + **from_checkpoint_kwargs, + ) -> "PendingEgoHandPredictor": + """Start ``from_checkpoint`` on a worker thread and return immediately. + + The checkpoint cfg is read (and its ``_target_`` validated) on the + calling thread so configuration errors still fail fast; building the + model and reading the tensors overlap whatever the caller does next, + typically video decoding and 2D detection. The worker first checks the + checkpoint's key set (``wait_until_validated``). + + Takes the arguments of ``from_checkpoint`` (every keyword not listed + here is passed on unchanged) plus ``dino_compile``. + """ + source = read_checkpoint(egohand_ckpt_path) + cfg, _ = _validated_cfg(source, soma_hand_data_folder) + try: + import warp as wp + + # warp.init() has no lock; initialize on this thread before the + # worker's SOMA construction and the detector/crop kernels race. + wp.init() + except ImportError: + pass + preload_usd_libraries() + + soma_batch_size = from_checkpoint_kwargs.get("soma_batch_size", 0) + if ( + isinstance(soma_batch_size, bool) + or not isinstance(soma_batch_size, int) + or soma_batch_size < 0 + or 0 < soma_batch_size < batch_size + ): + raise ValueError("soma_batch_size must be 0 or at least batch_size") + + def validate(): + check_checkpoint_keys(source, cfg) + + def load(): + predictor = cls.from_checkpoint( + egohand_ckpt_path=source, + soma_hand_data_folder=soma_hand_data_folder, + batch_size=batch_size, + device=device, + dtype=dtype, + smooth=smooth, + **from_checkpoint_kwargs, + ) + if dino_compile: + predictor.enable_dino_compile() + return predictor + + return PendingEgoHandPredictor( + load, + validate=validate, + batch_size=batch_size, + device=device, + dtype=dtype, + smooth=smooth, + camera_mode=str(cfg.get("camera_mode", "weak_perspective")), + soma_batch_size=soma_batch_size, + ) + def enable_dino_compile(self) -> None: """Compile full-batch DINO blocks for inference on this predictor.""" backbone = getattr(self.model, "backbone", None) @@ -180,13 +519,15 @@ def enable_dino_compile(self) -> None: @classmethod def from_checkpoint( cls, - egohand_ckpt_path: str | Path, + egohand_ckpt_path: str | Path | CheckpointSource, soma_hand_data_folder: str | Path, batch_size: int, - device: str = "cuda", + device: str | torch.device = "cuda", dtype: torch.dtype = torch.float32, smooth: bool = False, use_perspective_cropping: bool = False, + soma_batch_size: int = 0, + mhr_presorted_sparse: bool = True, ) -> "EgoHandPredictor": """Load a checkpoint and return a ready-to-use predictor. @@ -195,7 +536,8 @@ def from_checkpoint( you already have a loaded model (e.g. in tests). Args: - egohand_ckpt_path: EgoHand ``.ckpt`` path. + egohand_ckpt_path: EgoHand ``.ckpt`` path, inference-weights + export folder, or a ``CheckpointSource``. soma_hand_data_folder: SOMAHand asset folder. batch_size: Hand crops per forward pass. device: Torch device for inference. @@ -203,20 +545,39 @@ def from_checkpoint( smooth: Enable adaptive parameter smoothing (default off). use_perspective_cropping: Use perspective cropping for each hand bbox before inference (default off). + soma_batch_size: See the class docstring (default 0). + mhr_presorted_sparse: Build the MHR pose-corrective sparse matrix + once, coalesced, instead of on every SOMA call, whose merge + sort can fault with the CCCL bundled in PyTorch builds for + CUDA 13.0 (``inference/pipeline/mhr_presort.py``). Same + results. Default on; ``False`` keeps the TorchScript forward. Returns: Predictor owning the loaded checkpoint and inference configuration. """ - model, target = load_egohand_model(egohand_ckpt_path, soma_hand_data_folder) + model, target = load_egohand_model( + egohand_ckpt_path, soma_hand_data_folder, device=device + ) log.warning("[EgoHand] Model: %s (dtype=%s)", target, dtype) - return cls( + predictor = cls( model=model, batch_size=batch_size, device=device, dtype=dtype, smooth=smooth, use_perspective_cropping=use_perspective_cropping, + soma_batch_size=soma_batch_size, ) + if mhr_presorted_sparse: + from inference.pipeline.mhr_presort import apply_mhr_presort + + predictor.mhr_presort = apply_mhr_presort(predictor.model, device) + if predictor.mhr_presort["patched"]: + log.warning( + "[EgoHand] MHR sparse layer coalesced at load: %d model(s)", + len(predictor.mhr_presort["patched"]), + ) + return predictor @torch.no_grad() def run( @@ -275,7 +636,9 @@ def run( # GIL, so this parallelizes across cores and removes the previously # single-threaded preprocessing latency before the GPU forward pass. crop_jobs = [] - for image_bgr, image_id in zip(images_bgr, image_ids): + gpu_crop_jobs = [] + frame_by_idx: dict[int, np.ndarray] = {} + for frame_idx, (image_bgr, image_id) in enumerate(zip(images_bgr, image_ids)): bboxes_per_hand = bboxes_per_image.get(image_id, {}) for hand in hands: bbox = bboxes_per_hand.get(hand) @@ -286,6 +649,8 @@ def run( # Use the camera intrinsics provided by the dataset for this image. source_camera = intrinsics_per_image[image_id] crop_jobs.append((image_id, hand, image_bgr, bbx_array, source_camera)) + gpu_crop_jobs.append((frame_idx, image_id, hand, bbx_array)) + frame_by_idx[frame_idx] = image_bgr def _build_input(job): """Build one normalized crop and its model/output camera metadata. @@ -384,43 +749,93 @@ def _build_input(job): }, ) + defer_geometry = ( + bool(getattr(self, "smooth", False)) + and not defer_smoothing + and hasattr(self.model, "forward_step_head") + ) perf_reporter = getattr(self, "perf_reporter", None) prepared_inputs_by_image = {} - if crop_jobs: - crop_workers = min(8, (os.cpu_count() or 1)) - preprocessing_start = time.perf_counter() - with ThreadPoolExecutor(max_workers=crop_workers) as pool: - for image_id, hand, prepared_hand_data in pool.map( - _build_input, crop_jobs - ): - if prepared_hand_data is not None: - prepared_inputs_by_image.setdefault(image_id, {})[hand] = ( - prepared_hand_data - ) - if perf_reporter is not None: - preprocessing_ms_per_frame = ( - (time.perf_counter() - preprocessing_start) * 1000 / len(image_ids) - ) - perf_reporter.record_latency( - PerfStage.PREPROCESSING, preprocessing_ms_per_frame - ) - prepared_inputs = [ - prepared_hand_data - for image_id in image_ids - for prepared_hand_data in prepared_inputs_by_image.get( - image_id, {} - ).values() - ] + def _keep_metadata(image_id, hand, prepared_hand_data): + prepared_inputs_by_image.setdefault(image_id, {})[hand] = prepared_hand_data - if prepared_inputs: + use_gpu_pc = ( + self._use_perspective_cropping + and bool(crop_jobs) + and bool(getattr(self, "gpu_perspective_crop", True)) + and torch.device(self.device).type == "cuda" + and len(set(image_ids)) == len(image_ids) + and all(job[4] is crop_jobs[0][4] for job in crop_jobs) + and supports_gpu_perspective_crop(crop_jobs[0][4]) + ) + if use_gpu_pc: + camera_mode = getattr(self.model, "camera_mode", "weak_perspective") log.warning( - "[EgoHand] Running inference on %d hand crop(s)...", - len(prepared_inputs), + "[EgoHand] Running GPU perspective cropping and inference on up to " + "%d hand crop(s)...", + len(crop_jobs), + ) + gpu_batches = _GpuPerspectiveCropBatches( + frame_by_idx, + gpu_crop_jobs, + crop_jobs[0][4], + batch_size=self.batch_size, + device=self.device, + camera_mode=camera_mode, + on_prepared=_keep_metadata, + ) + predictions = self._run_imagebased_predictions( + gpu_batches, + frame_count=len(image_ids), + defer_geometry=defer_geometry, + ) + if perf_reporter is not None and image_ids: + perf_reporter.record_latency( + PerfStage.PREPROCESSING, + gpu_batches.crop_s * 1000 / len(image_ids), + ) + elif ( + crop_jobs + and getattr(self, "stream_crops", False) + and len(set(image_ids)) == len(image_ids) + ): + # Crops of later batches are prepared while earlier batches run. + # Batches are formed from the valid crops in job order, exactly as + # the list path below slices ``prepared_inputs``. + log.warning( + "[EgoHand] Running inference on up to %d hand crop(s), cropped " + "while earlier batches run...", + len(crop_jobs), + ) + with StreamedCropBatches( + crop_jobs, + _build_input, + batch_size=self.batch_size, + device=self.device, + workers=min(8, (os.cpu_count() or 1)), + copy_stream=self._crop_copy_stream(), + on_prepared=_keep_metadata, + ) as crop_batches: + predictions = self._run_imagebased_predictions( + crop_batches, + frame_count=len(image_ids), + defer_geometry=defer_geometry, + ) + if perf_reporter is not None: + # Crop time left on the critical path: waits for the next batch. + perf_reporter.record_latency( + PerfStage.PREPROCESSING, + crop_batches.wait_s * 1000 / len(image_ids), + ) + else: + predictions = self._prepare_all_then_predict( + crop_jobs, + _build_input, + image_ids, + prepared_inputs_by_image, + defer_geometry=defer_geometry, ) - predictions = self._run_imagebased_predictions( - prepared_inputs, frame_count=len(image_ids) - ) results_per_hand = {hand: {} for hand in hands} for result in predictions: @@ -434,9 +849,10 @@ def _build_input(job): # Restore geometry to source-camera axes, retaining output dtypes. for geometry_key in ("pred_vertices", "pred_keypoints_3d"): crop_camera_points = result[geometry_key] - result[geometry_key] = ( - crop_camera_points @ crop_to_source_rotation.T - ).astype(crop_camera_points.dtype, copy=False) + if crop_camera_points is not None: + result[geometry_key] = ( + crop_camera_points @ crop_to_source_rotation.T + ).astype(crop_camera_points.dtype, copy=False) crop_translation = result["transl"] result["transl"] = (crop_to_source_rotation @ crop_translation).astype( crop_translation.dtype, copy=False @@ -469,6 +885,70 @@ def _build_input(job): self.save_results(results_per_hand, output_paths_per_hand) return results_per_hand + def _prepare_all_then_predict( + self, + crop_jobs, + build_input, + image_ids, + prepared_inputs_by_image, + *, + defer_geometry: bool = False, + ): + """Build every crop upfront before running forward batches. + + Used when ``stream_crops`` is off or ``image_ids`` contains duplicates. + """ + perf_reporter = getattr(self, "perf_reporter", None) + if crop_jobs: + crop_workers = min(8, (os.cpu_count() or 1)) + preprocessing_start = time.perf_counter() + with ThreadPoolExecutor(max_workers=crop_workers) as pool: + for image_id, hand, prepared_hand_data in pool.map( + build_input, crop_jobs + ): + if prepared_hand_data is not None: + prepared_inputs_by_image.setdefault(image_id, {})[hand] = ( + prepared_hand_data + ) + if perf_reporter is not None: + preprocessing_ms_per_frame = ( + (time.perf_counter() - preprocessing_start) * 1000 / len(image_ids) + ) + perf_reporter.record_latency( + PerfStage.PREPROCESSING, preprocessing_ms_per_frame + ) + + prepared_inputs = [ + prepared_hand_data + for image_id in image_ids + for prepared_hand_data in prepared_inputs_by_image.get( + image_id, {} + ).values() + ] + + if prepared_inputs: + log.warning( + "[EgoHand] Running inference on %d hand crop(s)...", + len(prepared_inputs), + ) + return self._run_imagebased_predictions( + prepared_inputs, + frame_count=len(image_ids), + defer_geometry=defer_geometry, + ) + + def _crop_copy_stream(self): + """One upload stream per predictor and CUDA device, reused across clips.""" + if torch.device(self.device).type != "cuda": + return None + streams = self.__dict__.setdefault("_crop_copy_streams", {}) + device = torch.device(self.device) + if device.index is None: + device = torch.device("cuda", torch.cuda.current_device()) + if device not in streams: + streams[device] = torch.cuda.Stream(device=device) + return streams[device] + def postprocess_results( self, results_per_hand, @@ -503,7 +983,7 @@ def postprocess_results( frame_times=[frame_times[i] for i in image_ids], soma_hand=self.model.soma_hand, device=self.device, - batch_size=self.batch_size, + batch_size=max(self.batch_size, getattr(self, "soma_batch_size", 0)), intrinsics_per_image=intrinsics_per_image, min_depth=float(getattr(self.model, "kp2d_min_depth", 1e-4)), ) @@ -538,37 +1018,45 @@ def postprocess_results( np.float32 ) - if self._use_perspective_cropping or source_cameras_per_image is not None: - # Project smoothed joints onto the source distorted image, then normalize - # by the detector bbox for overlays and saved predictions. + # When smoothing already projected through intrinsics_per_image and + # there is no separate source_cameras_per_image remap, skip the + # duplicate projection pass. + run_source_projection = source_cameras_per_image is not None or ( + self._use_perspective_cropping and not self.smooth + ) + if run_source_projection: + # Project joints onto the source distorted image (vectorized per + # unique camera), then normalize by the detector bbox. projection_cameras = source_cameras_per_image or intrinsics_per_image min_joint_depth = float(getattr(self.model, "kp2d_min_depth", 1e-4)) for hand, hand_results in results_per_hand.items(): - for image_id, result in hand_results.items(): - source_bbox = np.asarray(bboxes_per_image[image_id][hand]) - source_camera_joints = np.add( - result["pred_keypoints_3d"], result["transl"], dtype=np.float64 - ) - valid_joint_projections = np.isfinite(source_camera_joints).all( - axis=-1 - ) & (source_camera_joints[:, 2] > min_joint_depth) - source_pixels = np.full( - (len(source_camera_joints), 2), np.nan, dtype=np.float64 - ) - source_pixels[valid_joint_projections] = projection_cameras[ - image_id - ].project(source_camera_joints[valid_joint_projections]) - bbox_normalized_joints = ( - source_pixels - source_bbox[:2] - ) / source_bbox[2] - valid_joint_projections &= np.isfinite(bbox_normalized_joints).all( - axis=-1 + if not hand_results: + continue + items = list(hand_results.items()) + kp2d_all, valid_all = _project_batch_to_crop_frame( + np.stack([r["pred_keypoints_3d"] for _, r in items]), + np.stack([r["transl"] for _, r in items]), + [projection_cameras[image_id] for image_id, _ in items], + np.stack( + [ + np.asarray( + bboxes_per_image[image_id][hand], dtype=np.float64 + ) + for image_id, _ in items + ] + ), + min_depth=min_joint_depth, + ) + for idx, (_, result) in enumerate(items): + kp2d_dtype = ( + result["pred_keypoints_2d"].dtype + if result.get("pred_keypoints_2d") is not None + else np.float32 ) - bbox_normalized_joints[~valid_joint_projections] = np.nan - result["pred_keypoints_2d"] = bbox_normalized_joints.astype( - result["pred_keypoints_2d"].dtype, copy=False + result["pred_keypoints_2d"] = kp2d_all[idx].astype( + kp2d_dtype, copy=False ) - result["pred_projection_valid"] = valid_joint_projections + result["pred_projection_valid"] = valid_all[idx] result["K_fullimg"] = None return results_per_hand @@ -643,7 +1131,11 @@ def save_results(self, results_per_hand, output_paths_per_hand): @torch.no_grad() def _run_imagebased_predictions( - self, prepared_inputs: list, frame_count: int | None = None + self, + prepared_inputs: list, + frame_count: int | None = None, + *, + defer_geometry: bool = False, ) -> list: """Run batched inference for EgoHand checkpoints. @@ -656,48 +1148,33 @@ def _run_imagebased_predictions( prepared_inputs: Ordered list of per-crop dicts built by ``run()``'s preprocessing step. Each dict carries ``crop_tensor``, ``model_bbx_xys``, ``model_K``, ``real_hand_side``, etc. + Alternatively a ``StreamedCropBatches`` that yields the same + batches, with the images already uploaded. frame_count: Number of frames these crops were drawn from, for ``PerfStage.MODEL_FORWARD`` normalization. Required when ``self.perf_reporter`` is set. + defer_geometry: When True, defer SOMA mesh decoding to + ``smooth_adaptive_hand_results`` via ``SomaBatcher``. Returns: Flat list of per-crop result dicts ready for ``results_per_hand`` assembly and SOMA NPZ writing. """ + if getattr(self, "soma_batch_size", 0) > 0 or defer_geometry: + return self._run_imagebased_predictions_soma( + prepared_inputs, frame_count, defer_geometry=defer_geometry + ) perf_reporter = getattr(self, "perf_reporter", None) + is_cuda = torch.device(self.device).type == "cuda" predictions = [] # Contiguous, non-overlapping per-batch phases: assembly -> forward -> post-forward. batch_assembly_ms_total = 0.0 forward_ms_total = 0.0 post_forward_ms_total = 0.0 - for start in range(0, len(prepared_inputs), self.batch_size): + for batch_hand_data, staged in self._batch_source(prepared_inputs): batch_assembly_start = time.perf_counter() - end = min(start + self.batch_size, len(prepared_inputs)) - batch_hand_data = prepared_inputs[start:end] - batch = { - "img": torch.stack([d["crop_tensor"] for d in batch_hand_data]).to( - self.device - ), - "bbx_xys": torch.from_numpy( - np.stack([d["model_bbx_xys"] for d in batch_hand_data]) - ) - .float() - .to(self.device), - "K_fullimg": torch.from_numpy( - np.stack([d["model_K"] for d in batch_hand_data]) - ) - .float() - .to(self.device), - "img_size": torch.from_numpy( - np.stack([d["model_img_size"] for d in batch_hand_data]) - ) - .float() - .to(self.device), - # Right-hand crops were flipped into the left-hand canonical frame - # during preprocessing; the model always sees left-hand inputs. - "hand_type": ["left"] * (end - start), - } - if perf_reporter is not None and self.device != "cpu": + batch = self._assemble_batch(batch_hand_data, staged) + if perf_reporter is not None and is_cuda: # Counted in batch assembly: waits for the host-to-device copies. torch.cuda.synchronize(self.device) forward_start = time.perf_counter() @@ -706,68 +1183,15 @@ def _run_imagebased_predictions( "cuda", dtype=self.dtype, enabled=(self.dtype != torch.float32) ): output = self.model.forward_step(batch, train=False) - if perf_reporter is not None and self.device != "cpu": + if perf_reporter is not None and is_cuda: torch.cuda.synchronize(self.device) post_forward_start = time.perf_counter() forward_ms_total += (post_forward_start - forward_start) * 1000 - params = output["pred_hand_params"] - # EgoHand packs global_scale into scale_params[:, 0] and per-finger - # scale into the tail. Split here so the mirror call and D2H loop - # below see consistent shapes. - scale_params_raw = params["scale_params"] - global_scale_batch = scale_params_raw[:, 0] - scale_params_batch = ( - scale_params_raw[:, 1:] if scale_params_raw.shape[1] > 1 else None - ) - - if ( - getattr(self.model, "camera_mode", "weak_perspective") - == "weak_perspective" - ): - output["pred_cam_t"] = compute_transl_full_cam( - output["pred_cam"].float(), - batch["bbx_xys"].float(), - batch["K_fullimg"].float(), - ) - ( - output["pred_keypoints_2d"], - output["pred_projection_valid"], - ) = project_camera_points_to_crop_with_validity( - output["pred_keypoints_3d"].float() - + output["pred_cam_t"].unsqueeze(1), - batch["K_fullimg"].float(), - batch["bbx_xys"].float(), - min_depth=float(getattr(self.model, "kp2d_min_depth", 1e-4)), - ) - - pred_camera_points = output["pred_keypoints_3d"].float() + output[ - "pred_cam_t" - ].float().unsqueeze(1) - fallback_projection_valid = torch.isfinite(pred_camera_points).all( - dim=-1 - ) & ( - pred_camera_points[..., 2] - > float( - getattr( - self.model, - "kp2d_min_depth", - 1e-4, - ) - ) - ) - projection_valid = output.get( - "pred_projection_valid", - fallback_projection_valid, - ) - projection_valid = projection_valid & torch.isfinite( - output["pred_keypoints_2d"] - ).all(dim=-1) - output["pred_projection_valid"] = projection_valid - output["pred_keypoints_2d"] = output["pred_keypoints_2d"].masked_fill( - ~projection_valid.unsqueeze(-1), - float("nan"), + params, global_scale_batch, scale_params_batch = self._split_batch_params( + output ) + self._finalize_projection(output, batch) # Mirror the right-hand sub-batch in one vectorised call. right_indices # is a subset of the mixed-hand batch; right_pos gives O(1) lookup back @@ -779,127 +1203,114 @@ def _run_imagebased_predictions( ] right_batched = None if right_indices: - idx = torch.tensor(right_indices, device=self.device, dtype=torch.long) # Disable any inherited autocast (e.g. from a preceding detector # that uses bfloat16 internally). The MHR identity model uses sparse # CUDA matmul which does not support half precision. with torch.autocast("cuda", enabled=False): + mirror_args = self._right_mirror_inputs( + batch_hand_data, + right_indices, + params, + output, + global_scale_batch, + scale_params_batch, + ) right_batched = mirror_left_prediction_to_right( self.model, - torch.cat( - [ - params["wrist_orient"][idx].float(), - params["hand_pose"][idx].float(), - ], - dim=1, - ), - output["pred_cam_t"][idx].float(), - params["identity_coeffs"][idx].float(), - global_scale_batch[idx].float(), - torch.from_numpy( - np.stack( - [batch_hand_data[i]["output_K"] for i in right_indices] - ) - ) - .float() - .to(self.device), - torch.from_numpy( - np.stack( - [ - batch_hand_data[i]["output_bbx_xys"] - for i in right_indices - ] - ) - ) - .float() - .to(self.device), - scale_params=scale_params_batch[idx].float() - if scale_params_batch is not None - else None, + *mirror_args[:6], + scale_params=mirror_args[6], pose_mirror=self._pose_mirror, ) - # One D2H copy per tensor for the whole batch, then index per sample. - reliability_cpu = { - key: output[key].float().cpu().numpy() - for key in KEYPOINT_RELIABILITY_FIELDS - if output.get(key) is not None - } - verts_cpu = output["pred_vertices"].cpu().numpy() - transl_cpu = output["pred_cam_t"].cpu().numpy() - kp3d_cpu = output["pred_keypoints_3d"].cpu().numpy() - kp2d_cpu = output["pred_keypoints_2d"].cpu().numpy() - kp2d_valid_cpu = ( - output.get( - "pred_projection_valid", - torch.isfinite(output["pred_keypoints_2d"]).all(dim=-1), + predictions.extend( + self._collect_batch_predictions( + batch_hand_data, + output, + params, + global_scale_batch, + scale_params_batch, + right_batched, + right_indices, ) - .cpu() - .numpy() ) - wrist_cpu = params["wrist_orient"].float().cpu().numpy() - fingers_cpu = params["hand_pose"].float().cpu().numpy() - id_cpu = params["identity_coeffs"].float().cpu().numpy() - gs_cpu = global_scale_batch.float().cpu().numpy() - sp_cpu = ( - scale_params_batch.float().cpu().numpy() - if scale_params_batch is not None - else None - ) - rv_cpu = rt_cpu = rk3_cpu = rk2_cpu = rkv_cpu = rp_cpu = None - if right_batched is not None: - rv_cpu = right_batched["pred_vertices"].cpu().numpy() - rt_cpu = right_batched["transl"].cpu().numpy() - rk3_cpu = right_batched["pred_keypoints_3d"].cpu().numpy() - rk2_cpu = right_batched["pred_keypoints_2d"].cpu().numpy() - rkv_cpu = right_batched["pred_projection_valid"].cpu().numpy() - rp_cpu = right_batched["poses"].cpu().numpy() - right_pos: dict[int, int] = {i: r for r, i in enumerate(right_indices)} - - for i, d in enumerate(batch_hand_data): - side = d["real_hand_side"] - if side == "right": - r = right_pos[i] - predictions.append( - { - "pred_vertices": rv_cpu[r], - "transl": rt_cpu[r], - "pred_keypoints_3d": rk3_cpu[r], - "pred_keypoints_2d": rk2_cpu[r], - "pred_projection_valid": rkv_cpu[r], - "poses": rp_cpu[r], - "identity_coeffs": id_cpu[i], - "scale_params": sp_cpu[i] if sp_cpu is not None else None, - "global_scale": float(gs_cpu[i]), - "hand_type": side, - "image_id": d["image_id"], - "K_fullimg": d["output_K"], - } - ) - else: - predictions.append( - { - "pred_vertices": verts_cpu[i], - "transl": transl_cpu[i], - "pred_keypoints_3d": kp3d_cpu[i], - "pred_keypoints_2d": kp2d_cpu[i], - "pred_projection_valid": kp2d_valid_cpu[i], - "poses": np.concatenate( - [wrist_cpu[i], fingers_cpu[i]], axis=0 - ), - "identity_coeffs": id_cpu[i], - "scale_params": sp_cpu[i] if sp_cpu is not None else None, - "global_scale": float(gs_cpu[i]), - "hand_type": side, - "image_id": d["image_id"], - "K_fullimg": d["output_K"], - } - ) - # Both hands retain anatomical joint order; these describe the model crop. - predictions[-1].update( - {key: values[i] for key, values in reliability_cpu.items()} - ) post_forward_ms_total += (time.perf_counter() - post_forward_start) * 1000 + if staged is not None: + # Every read of this batch's images is queued; reuse the slot. + del batch + staged.release() + if perf_reporter is not None and frame_count: + perf_reporter.record_latency( + PerfStage.BATCH_ASSEMBLY, batch_assembly_ms_total / frame_count + ) + perf_reporter.record_latency( + PerfStage.MODEL_FORWARD, forward_ms_total / frame_count + ) + perf_reporter.record_latency( + PerfStage.POST_FORWARD, post_forward_ms_total / frame_count + ) + return predictions + + def _run_imagebased_predictions_soma( + self, + prepared_inputs: list, + frame_count: int | None, + *, + defer_geometry: bool = False, + ) -> list: + """``_run_imagebased_predictions`` with ``soma_batch_size`` / ``defer_geometry``. + + Backbone and heads still run per ``batch_size`` batch. The SOMA hand + layer, the camera solve, the right-hand mirror and the result copies + go through ``SomaBatcher``. Perf stages: model_forward also holds the + SOMA layer and camera solve; post_forward holds the rest. + """ + perf_reporter = getattr(self, "perf_reporter", None) + timed = perf_reporter is not None and torch.device(self.device).type == "cuda" + batcher = SomaBatcher( + self, + getattr(self, "soma_batch_size", 0), + sync_timing=timed, + defer_geometry=defer_geometry, + ) + batch_assembly_ms_total = 0.0 + forward_ms_total = 0.0 + post_forward_ms_total = 0.0 + for batch_hand_data, staged in self._batch_source(prepared_inputs): + batch_assembly_start = time.perf_counter() + batch = self._assemble_batch(batch_hand_data, staged) + if timed: + torch.cuda.synchronize(self.device) + forward_start = time.perf_counter() + batch_assembly_ms_total += (forward_start - batch_assembly_start) * 1000 + with torch.autocast( + "cuda", dtype=self.dtype, enabled=(self.dtype != torch.float32) + ): + head = self.model.forward_step_head(batch, train=False) + if timed: + torch.cuda.synchronize(self.device) + post_forward_start = time.perf_counter() + forward_ms_total += (post_forward_start - forward_start) * 1000 + batch.pop("img") + if staged is not None: + # The head's reads of this batch's images are queued; reuse the slot. + staged.release() + batcher.add(batch, batch_hand_data, head) + post_forward_ms_total += (time.perf_counter() - post_forward_start) * 1000 + finish_start = time.perf_counter() + predictions = batcher.finish() + post_forward_ms_total += (time.perf_counter() - finish_start) * 1000 + # Batcher time spent in the SOMA layer + camera solve belongs to the forward. + forward_ms_total += batcher.left_ms + post_forward_ms_total -= batcher.left_ms + log.warning( + "[EgoHand] SOMA batching %d rows: %d left calls, %d mirror calls, " + "left %.0f ms, mirror+copy %.0f ms", + batcher.group_rows, + batcher.left_calls, + batcher.mirror_calls, + batcher.left_ms, + batcher.right_ms, + ) if perf_reporter is not None and frame_count: perf_reporter.record_latency( PerfStage.BATCH_ASSEMBLY, batch_assembly_ms_total / frame_count @@ -911,3 +1322,398 @@ def _run_imagebased_predictions( PerfStage.POST_FORWARD, post_forward_ms_total / frame_count ) return predictions + + def _batch_source(self, prepared_inputs): + """``(batch_hand_data, staged)`` per forward batch, in input order. + + ``staged`` is the ``StagedCropBatch`` / ``_GpuStagedCropBatch`` when + ``prepared_inputs`` is a streamed or GPU crop batch source, else + ``None`` and the batch is a ``batch_size`` slice of the prepared list. + """ + if isinstance( + prepared_inputs, (StreamedCropBatches, _GpuPerspectiveCropBatches) + ): + # Batches of valid crops, already prepared/uploaded in job order. + return ((staged.hand_data, staged) for staged in prepared_inputs) + return ( + (prepared_inputs[start : start + self.batch_size], None) + for start in range(0, len(prepared_inputs), self.batch_size) + ) + + def _assemble_batch(self, batch_hand_data: list, staged=None) -> dict: + """Stack one batch of prepared crops and cameras onto the device.""" + return { + "img": staged.images(self.device) + if staged is not None + else torch.stack([d["crop_tensor"] for d in batch_hand_data]).to( + self.device + ), + "bbx_xys": torch.from_numpy( + np.stack([d["model_bbx_xys"] for d in batch_hand_data]) + ) + .float() + .to(self.device), + "K_fullimg": torch.from_numpy( + np.stack([d["model_K"] for d in batch_hand_data]) + ) + .float() + .to(self.device), + "img_size": torch.from_numpy( + np.stack([d["model_img_size"] for d in batch_hand_data]) + ) + .float() + .to(self.device), + # Right-hand crops were flipped into the left-hand canonical frame + # during preprocessing; the model always sees left-hand inputs. + "hand_type": ["left"] * len(batch_hand_data), + } + + @staticmethod + def _split_batch_params(output: dict): + params = output["pred_hand_params"] + # EgoHand packs global_scale into scale_params[:, 0] and per-finger + # scale into the tail. Split here so the mirror call and D2H loop + # below see consistent shapes. + scale_params_raw = params["scale_params"] + global_scale_batch = scale_params_raw[:, 0] + scale_params_batch = ( + scale_params_raw[:, 1:] if scale_params_raw.shape[1] > 1 else None + ) + return params, global_scale_batch, scale_params_batch + + def _finalize_projection(self, output: dict, batch: dict) -> None: + """Weak-perspective translation and final 2D projection validity, in place.""" + if getattr(self.model, "camera_mode", "weak_perspective") == "weak_perspective": + output["pred_cam_t"] = compute_transl_full_cam( + output["pred_cam"].float(), + batch["bbx_xys"].float(), + batch["K_fullimg"].float(), + ) + ( + output["pred_keypoints_2d"], + output["pred_projection_valid"], + ) = project_camera_points_to_crop_with_validity( + output["pred_keypoints_3d"].float() + output["pred_cam_t"].unsqueeze(1), + batch["K_fullimg"].float(), + batch["bbx_xys"].float(), + min_depth=float(getattr(self.model, "kp2d_min_depth", 1e-4)), + ) + + pred_camera_points = output["pred_keypoints_3d"].float() + output[ + "pred_cam_t" + ].float().unsqueeze(1) + fallback_projection_valid = torch.isfinite(pred_camera_points).all(dim=-1) & ( + pred_camera_points[..., 2] + > float( + getattr( + self.model, + "kp2d_min_depth", + 1e-4, + ) + ) + ) + projection_valid = output.get( + "pred_projection_valid", + fallback_projection_valid, + ) + projection_valid = projection_valid & torch.isfinite( + output["pred_keypoints_2d"] + ).all(dim=-1) + output["pred_projection_valid"] = projection_valid + output["pred_keypoints_2d"] = output["pred_keypoints_2d"].masked_fill( + ~projection_valid.unsqueeze(-1), + float("nan"), + ) + + def _right_mirror_inputs( + self, + batch_hand_data: list, + right_indices: list, + params: dict, + output: dict, + global_scale_batch: torch.Tensor, + scale_params_batch: torch.Tensor | None, + ) -> tuple: + """Positional ``mirror_left_prediction_to_right`` inputs plus scale_params.""" + idx = torch.tensor(right_indices, device=self.device, dtype=torch.long) + return ( + torch.cat( + [ + params["wrist_orient"][idx].float(), + params["hand_pose"][idx].float(), + ], + dim=1, + ), + output["pred_cam_t"][idx].float(), + params["identity_coeffs"][idx].float(), + global_scale_batch[idx].float(), + torch.from_numpy( + np.stack([batch_hand_data[i]["output_K"] for i in right_indices]) + ) + .float() + .to(self.device), + torch.from_numpy( + np.stack([batch_hand_data[i]["output_bbx_xys"] for i in right_indices]) + ) + .float() + .to(self.device), + scale_params_batch[idx].float() if scale_params_batch is not None else None, + ) + + @staticmethod + def _collect_batch_predictions( + batch_hand_data: list, + output: dict, + params: dict, + global_scale_batch: torch.Tensor, + scale_params_batch: torch.Tensor | None, + right_batched: dict | None, + right_indices: list, + ) -> list: + """Copy one batch's outputs to the host and build its per-crop result dicts.""" + predictions = [] + # One D2H copy per tensor for the whole batch, then index per sample. + reliability_cpu = { + key: output[key].float().cpu().numpy() + for key in KEYPOINT_RELIABILITY_FIELDS + if output.get(key) is not None + } + verts = output["pred_vertices"] + verts_cpu = verts.cpu().numpy() if verts is not None else None + transl_cpu = output["pred_cam_t"].cpu().numpy() + kp3d = output["pred_keypoints_3d"] + kp3d_cpu = kp3d.cpu().numpy() if kp3d is not None else None + kp2d = output["pred_keypoints_2d"] + kp2d_cpu = kp2d.cpu().numpy() if kp2d is not None else None + kp2d_valid = output.get("pred_projection_valid") + if kp2d_valid is None and kp2d is not None: + kp2d_valid = torch.isfinite(kp2d).all(dim=-1) + kp2d_valid_cpu = kp2d_valid.cpu().numpy() if kp2d_valid is not None else None + wrist_cpu = params["wrist_orient"].float().cpu().numpy() + fingers_cpu = params["hand_pose"].float().cpu().numpy() + id_cpu = params["identity_coeffs"].float().cpu().numpy() + gs_cpu = global_scale_batch.float().cpu().numpy() + sp_cpu = ( + scale_params_batch.float().cpu().numpy() + if scale_params_batch is not None + else None + ) + rv_cpu = rt_cpu = rk3_cpu = rk2_cpu = rkv_cpu = rp_cpu = None + if right_batched is not None: + rv = right_batched["pred_vertices"] + rv_cpu = rv.cpu().numpy() if rv is not None else None + rt_cpu = right_batched["transl"].cpu().numpy() + rk3 = right_batched["pred_keypoints_3d"] + rk3_cpu = rk3.cpu().numpy() if rk3 is not None else None + rk2 = right_batched["pred_keypoints_2d"] + rk2_cpu = rk2.cpu().numpy() if rk2 is not None else None + rkv = right_batched["pred_projection_valid"] + rkv_cpu = rkv.cpu().numpy() if rkv is not None else None + rp_cpu = right_batched["poses"].cpu().numpy() + right_pos: dict[int, int] = {i: r for r, i in enumerate(right_indices)} + + for i, d in enumerate(batch_hand_data): + side = d["real_hand_side"] + if side == "right": + r = right_pos[i] + predictions.append( + { + "pred_vertices": rv_cpu[r] if rv_cpu is not None else None, + "transl": rt_cpu[r], + "pred_keypoints_3d": ( + rk3_cpu[r] if rk3_cpu is not None else None + ), + "pred_keypoints_2d": ( + rk2_cpu[r] if rk2_cpu is not None else None + ), + "pred_projection_valid": ( + rkv_cpu[r] if rkv_cpu is not None else None + ), + "poses": rp_cpu[r], + "identity_coeffs": id_cpu[i], + "scale_params": sp_cpu[i] if sp_cpu is not None else None, + "global_scale": float(gs_cpu[i]), + "hand_type": side, + "image_id": d["image_id"], + "K_fullimg": d["output_K"], + } + ) + else: + predictions.append( + { + "pred_vertices": ( + verts_cpu[i] if verts_cpu is not None else None + ), + "transl": transl_cpu[i], + "pred_keypoints_3d": ( + kp3d_cpu[i] if kp3d_cpu is not None else None + ), + "pred_keypoints_2d": ( + kp2d_cpu[i] if kp2d_cpu is not None else None + ), + "pred_projection_valid": ( + kp2d_valid_cpu[i] if kp2d_valid_cpu is not None else None + ), + "poses": np.concatenate([wrist_cpu[i], fingers_cpu[i]], axis=0), + "identity_coeffs": id_cpu[i], + "scale_params": sp_cpu[i] if sp_cpu is not None else None, + "global_scale": float(gs_cpu[i]), + "hand_type": side, + "image_id": d["image_id"], + "K_fullimg": d["output_K"], + } + ) + # Both hands retain anatomical joint order; these describe the model crop. + predictions[-1].update( + {key: values[i] for key, values in reliability_cpu.items()} + ) + return predictions + + +#: Active PendingEgoHandPredictors in this process, guarded by _PENDING_LOADS_LOCK. +_PENDING_LOADS_LOCK = threading.Lock() +_PENDING_LOADS: list["PendingEgoHandPredictor"] = [] + + +def wait_for_background_loads(timeout: float) -> bool: + """Wait up to ``timeout`` seconds for active background model loads to exit. + + Joining active daemon loader threads before interpreter teardown avoids + native-thread aborts when the main thread exits on an error. + """ + deadline = time.monotonic() + max(0.0, timeout) + while True: + with _PENDING_LOADS_LOCK: + snapshot = list(_PENDING_LOADS) + if not snapshot: + return True + for pending in snapshot: + remaining = max(0.0, deadline - time.monotonic()) + pending._thread.join(remaining) + if pending._thread.is_alive(): + return False + + +class PendingEgoHandPredictor: + """An ``EgoHandPredictor`` loading on a worker thread. + + Metadata attributes (``batch_size``, ``device``, ``dtype``, ``smooth``, + ``camera_mode``, ``soma_batch_size``) and ``perf_reporter`` never block; + other attributes wait for the load and re-raise any load error. + """ + + def __init__( + self, + load: Callable[[], EgoHandPredictor], + *, + batch_size: int, + device: str | torch.device, + dtype: torch.dtype | None, + smooth: bool, + camera_mode: str | None, + soma_batch_size: int = 0, + validate: Callable[[], None] | None = None, + ) -> None: + self.batch_size = batch_size + self.device = device + self.dtype = dtype + self.smooth = bool(smooth) + self.camera_mode = camera_mode + self.soma_batch_size = int(soma_batch_size) + self.load_seconds: float | None = None + self.wait_seconds = 0.0 + self._predictor: EgoHandPredictor | None = None + self._error: BaseException | None = None + self._done = threading.Event() + self._validated = threading.Event() + self._validation_error: BaseException | None = None + self.validate_seconds: float | None = None + + def worker() -> None: + start = time.perf_counter() + try: + try: + if validate is not None: + validate() + except BaseException as exc: + self._validation_error = exc + raise + finally: + self.validate_seconds = time.perf_counter() - start + self._validated.set() + predictor = load() + target_device = torch.device(self.device) + if ( + target_device.type == "cuda" + and torch.cuda.is_available() + and torch.cuda.is_initialized() + ): + # Count queued weight copies on the target device as load time. + torch.cuda.current_stream(target_device).synchronize() + self._predictor = predictor + except BaseException as exc: # re-raised on first use + self._error = exc + finally: + self.load_seconds = time.perf_counter() - start + with _PENDING_LOADS_LOCK: + with contextlib.suppress(ValueError): + _PENDING_LOADS.remove(self) + self._done.set() + + self._thread = threading.Thread( + target=worker, name="egohand-model-load", daemon=True + ) + with _PENDING_LOADS_LOCK: + _PENDING_LOADS.append(self) + self._thread.start() + + def wait_until_validated(self) -> float: + """Block until the checkpoint key check is done; re-raise its error. + + Callers do this before decoding so a mismatched checkpoint fails + before any frame is processed or output written. Returns the seconds + spent waiting. + """ + start = time.perf_counter() + self._validated.wait() + waited = time.perf_counter() - start + if self._validation_error is not None: + raise self._validation_error + return waited + + def result(self) -> EgoHandPredictor: + """Block until the predictor is loaded and return it.""" + if not self._done.is_set(): + start = time.perf_counter() + self._done.wait() + self.wait_seconds += time.perf_counter() - start + if self._error is not None: + raise self._error + if "_perf_reporter" in self.__dict__: + self._predictor.perf_reporter = self._perf_reporter + return self._predictor + + def __setattr__(self, name, value): + if name == "perf_reporter": + # The command line sets the per-video perf reporter before the + # model may have finished loading: keep it and hand it to the + # predictor when it is resolved (result()). + self.__dict__["_perf_reporter"] = value + if self.__dict__.get("_predictor") is not None: + self._predictor.perf_reporter = value + return + super().__setattr__(name, value) + + def __getattr__(self, name): + # Only called for attributes not set in __init__. + if name.startswith("__") or name in ( + "_predictor", + "_error", + "_done", + "_thread", + "_validated", + "_validation_error", + "_perf_reporter", + ): + raise AttributeError(name) + return getattr(self.result(), name) diff --git a/src/python/isaaccapture_egopost/inference/pipeline/soma_batching.py b/src/python/isaaccapture_egopost/inference/pipeline/soma_batching.py new file mode 100644 index 0000000000..aa899eecc1 --- /dev/null +++ b/src/python/isaaccapture_egopost/inference/pipeline/soma_batching.py @@ -0,0 +1,361 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: LicenseRef-OpenMDW-1.1 + +"""SOMA hand layer for several EgoHand head batches per call. + +The SOMA layer costs about the same per call for 16 or 512 rows (launch and +host-sync overhead), so ``SomaBatcher`` calls it once per group of head +batches. +""" + +import time + +import torch + +from egohand.utils.cam_utils import compute_transl_full_cam +from inference.preprocessing.mirroring import ( + mirror_left_poses_to_right, + mirror_left_prediction_to_right, +) + +_SOMA_INPUT_KEYS = ("poses", "identity_coeffs", "global_scale", "scale_params") + + +def _pad_rows(tensor: torch.Tensor, rows: int) -> torch.Tensor: + """Pad to ``rows`` rows by repeating the last row. + + Repeat a real row: all-zero identity rows give a degenerate skeleton fit + that takes py-soma-x's slow per-row fallback. + """ + n = tensor.shape[0] + if n <= 0 or n > rows: + raise ValueError(f"cannot pad {n} rows to {rows}") + if n == rows: + return tensor + return torch.cat([tensor, tensor[n - 1 :].expand(rows - n, *tensor.shape[1:])]) + + +class SomaBatcher: + """Left SOMA layer, camera solve, and right-hand mirror over a stream of head batches. + + ``group_rows == 0`` runs one left call and one mirror call per head batch. + ``group_rows > 0`` batches left calls across ``group_rows // batch_size`` + head batches and mirrors up to ``group_rows`` right-hand rows per call, + padded to ``group_rows`` for stable TorchScript shapes; results stay in input order. + """ + + def __init__( + self, + predictor, + group_rows: int = 0, + sync_timing: bool = False, + defer_geometry: bool = False, + ): + self.predictor = predictor + self.model = predictor.model + self.group_rows = int(group_rows) + if self.group_rows and self.group_rows < predictor.batch_size: + raise ValueError("soma_batch_size must be 0 or at least batch_size") + self.left_batches = ( + max(1, self.group_rows // predictor.batch_size) if self.group_rows else 1 + ) + self.sync_timing = sync_timing + self.defer_geometry = bool(defer_geometry) + self.predictions = [] + self.left_calls = 0 + self.mirror_calls = 0 + self.left_ms = 0.0 + self.right_ms = 0.0 + self._left = [] + self._right = [] + self._right_rows = 0 + + def add(self, batch: dict, batch_hand_data: list, head: dict) -> None: + """Queue one head batch (``batch`` without ``img``).""" + self._left.append((batch, batch_hand_data, head)) + if len(self._left) >= self.left_batches: + self._flush_left() + + def finish(self) -> list: + if self._left: + self._flush_left() + if self._right: + self._flush_right() + return self.predictions + + def _gather_left_soma_inputs(self, pending: list) -> dict: + if self.group_rows: + return { + key: None + if pending[0][2]["soma_inputs"][key] is None + else _pad_rows( + torch.cat([head["soma_inputs"][key] for _, _, head in pending]), + self.group_rows, + ) + for key in _SOMA_INPUT_KEYS + } + return pending[0][2]["soma_inputs"] + + def _flush_left(self) -> None: + start = time.perf_counter() + pending, self._left = self._left, [] + decoded = [] + if self.defer_geometry and not getattr( + self.model, "use_kp2d_translation", False + ): + for batch, batch_hand_data, head in pending: + poses = head["soma_inputs"]["poses"] + joints = torch.zeros( + (head["batch_size"], poses.shape[1], 3), + device=poses.device, + dtype=poses.dtype, + ) + output = self.model.forward_step_decode(head, joints, None) + decoded.append((batch, batch_hand_data, output)) + elif self.defer_geometry: + soma_inputs = self._gather_left_soma_inputs(pending) + # Disable TorchScript's thread-local profiling optimizer around MHR + # so the 2nd invocation does not stall ~2.5 s JIT-compiling fused + # graphs for negligible steady-state gain. + with ( + torch.autocast("cuda", enabled=False), + torch.jit.optimized_execution(False), + ): + left_layer = self.model.soma_hand.left + left_layer.prepare_identity( + soma_inputs["identity_coeffs"].float(), + scale_params=soma_inputs["scale_params"], + repose_to_bind_pose=False, + global_scale=soma_inputs["global_scale"], + ) + hand_out = left_layer.pose( + soma_inputs["poses"].float(), + pose2rot=False, + apply_correctives=False, + global_translation=None, + fk_only=True, + ) + self.left_calls += 1 + offset = 0 + for batch, batch_hand_data, head in pending: + joints = hand_out["joints"] + if self.group_rows: + rows = head["batch_size"] + joints = joints[offset : offset + rows] + offset += rows + output = self.model.forward_step_decode(head, joints, None) + decoded.append((batch, batch_hand_data, output)) + else: + soma_inputs = self._gather_left_soma_inputs(pending) + with ( + torch.autocast("cuda", enabled=False), + torch.jit.optimized_execution(False), + ): + hand_out = self.model.soma_hand( + hand_type="left", pose2rot=False, **soma_inputs + ) + self.left_calls += 1 + offset = 0 + for batch, batch_hand_data, head in pending: + joints, vertices = hand_out["joints"], hand_out["vertices"] + if self.group_rows: + rows = head["batch_size"] + # Contiguous dim-0 slices preserve layout without copying. + joints = joints[offset : offset + rows] + vertices = vertices[offset : offset + rows] + offset += rows + output = self.model.forward_step_decode(head, joints, vertices) + decoded.append((batch, batch_hand_data, output)) + if self.sync_timing: + torch.cuda.synchronize(self.predictor.device) + self.left_ms += (time.perf_counter() - start) * 1000 + for batch, batch_hand_data, output in decoded: + self._queue_right(batch, batch_hand_data, output) + + def _queue_right(self, batch: dict, batch_hand_data: list, output: dict) -> None: + params, global_scale, scale_params = self.predictor._split_batch_params(output) + if output["pred_vertices"] is None: + if ( + getattr(self.model, "camera_mode", "weak_perspective") + == "weak_perspective" + ): + with torch.autocast("cuda", enabled=False): + output["pred_cam_t"] = compute_transl_full_cam( + output["pred_cam"].float(), + batch["bbx_xys"].float(), + batch["K_fullimg"].float(), + ) + output["pred_keypoints_3d"] = None + output["pred_keypoints_2d"] = None + output["pred_projection_valid"] = None + else: + self.predictor._finalize_projection(output, batch) + right_indices = [ + i for i, d in enumerate(batch_hand_data) if d["real_hand_side"] == "right" + ] + if not right_indices: + # Collect left-only batches to CPU immediately so GPU outputs are never + # retained across long right-hand-absent spans. + start = time.perf_counter() + preds = self.predictor._collect_batch_predictions( + batch_hand_data, + output, + params, + global_scale, + scale_params, + None, + [], + ) + self.right_ms += (time.perf_counter() - start) * 1000 + if self._right: + self._right.append(("ready", preds)) + else: + self.predictions.extend(preds) + return + record = ( + "pending", + batch_hand_data, + output, + params, + global_scale, + scale_params, + right_indices, + ) + if ( + self.group_rows + and self._right + and self._right_rows + len(right_indices) > self.group_rows + ): + self._flush_right() + self._right.append(record) + self._right_rows += len(right_indices) + if not self.group_rows: + self._flush_right() + + def _flush_right(self) -> None: + start = time.perf_counter() + records, self._right, self._right_rows = self._right, [], 0 + right_out = None + # See the per-batch path in predictor.py: no inherited autocast for SOMA. + with ( + torch.autocast("cuda", enabled=False), + torch.jit.optimized_execution(False), + ): + if self.defer_geometry: + pose_chunks = [] + transl_chunks = [] + for rec in records: + if rec[0] != "pending": + continue + _, _, output, params, _, _, right_indices = rec + idx = torch.tensor( + right_indices, + device=self.predictor.device, + dtype=torch.long, + ) + pose_chunks.append( + torch.cat( + [ + params["wrist_orient"][idx].float(), + params["hand_pose"][idx].float(), + ], + dim=1, + ) + ) + transl_chunks.append(output["pred_cam_t"][idx].float()) + if pose_chunks: + poses_cat = ( + pose_chunks[0] + if len(pose_chunks) == 1 + else torch.cat(pose_chunks) + ) + transl_cat = ( + transl_chunks[0] + if len(transl_chunks) == 1 + else torch.cat(transl_chunks) + ) + right_poses, right_transl = mirror_left_poses_to_right( + self.model.soma_hand.left, + self.model.soma_hand.right, + poses_cat, + transl_cat, + pose_mirror=self.predictor._pose_mirror, + ) + right_out = { + "pred_vertices": None, + "transl": right_transl, + "pred_keypoints_3d": None, + "pred_keypoints_2d": None, + "pred_projection_valid": None, + "poses": right_poses, + } + self.mirror_calls += 1 + else: + inputs = [ + self.predictor._right_mirror_inputs( + rec[1], + rec[6], + rec[3], + rec[2], + rec[4], + rec[5], + ) + if rec[0] == "pending" + else None + for rec in records + ] + present = [args for args in inputs if args is not None] + if present: + if self.group_rows: + mirror_args = [ + None + if present[0][j] is None + else _pad_rows( + torch.cat([args[j] for args in present]), + self.group_rows, + ) + for j in range(len(present[0])) + ] + else: + mirror_args = present[0] + right_out = mirror_left_prediction_to_right( + self.model, + *mirror_args[:6], + scale_params=mirror_args[6], + pose_mirror=self.predictor._pose_mirror, + ) + self.mirror_calls += 1 + offset = 0 + for rec in records: + if rec[0] == "ready": + self.predictions.extend(rec[1]) + continue + ( + _, + batch_hand_data, + output, + params, + global_scale, + scale_params, + right_indices, + ) = rec + right_batched = right_out + if self.group_rows: + rows = len(right_indices) + right_batched = { + key: None if value is None else value[offset : offset + rows] + for key, value in right_out.items() + } + offset += rows + self.predictions.extend( + self.predictor._collect_batch_predictions( + batch_hand_data, + output, + params, + global_scale, + scale_params, + right_batched, + right_indices, + ) + ) + self.right_ms += (time.perf_counter() - start) * 1000 diff --git a/src/python/isaaccapture_egopost/inference/postprocessing/adaptive_smoothing.py b/src/python/isaaccapture_egopost/inference/postprocessing/adaptive_smoothing.py index a66630cbd8..581fc9b9dd 100644 --- a/src/python/isaaccapture_egopost/inference/postprocessing/adaptive_smoothing.py +++ b/src/python/isaaccapture_egopost/inference/postprocessing/adaptive_smoothing.py @@ -340,13 +340,421 @@ def smooth_rotations(values, times, config): def _smooth_shape(values, times, sigma): - values = np.asarray(values) - out = values.astype(np.float64, copy=True) - for i in range(len(times)): - lo, hi, delta = _neighbors(times, i, sigma) - weights = np.exp(-0.5 * (delta / sigma) ** 2) - out[i] = np.tensordot(weights / weights.sum(), values[lo:hi], axes=(0, 0)) - return out + """Vectorized Gaussian smoothing over physical time using padded (T, W) windows.""" + values = np.asarray(values, dtype=np.float64) + times = np.asarray(times, dtype=np.float64) + n = len(times) + if n == 0: + return values.copy() + radius = 3.0 * float(np.max(sigma)) + lo = np.searchsorted(times, times - radius, side="left") + hi = np.searchsorted(times, times + radius, side="right") + counts = hi - lo + orig_shape = values.shape + flat_values = values.reshape(n, -1) + dim = flat_values.shape[1] + out = np.empty_like(flat_values) + max_w = int(counts.max()) + # Bound temporary (chunk, W, D) allocation for very long high-FPS clips. + chunk_size = max(1, min(n, 4_000_000 // max(1, max_w * dim))) + for start in range(0, n, chunk_size): + stop = min(n, start + chunk_size) + c_lo = lo[start:stop] + c_counts = counts[start:stop] + c_max_w = int(c_counts.max()) + offsets = np.arange(c_max_w) + valid = offsets[None, :] < c_counts[:, None] + self_idx = np.arange(start, stop)[:, None] + window_ids = np.where(valid, c_lo[:, None] + offsets[None, :], self_idx) + delta = times[window_ids] - times[start:stop, None] + weights = np.where(valid, np.exp(-0.5 * (delta / sigma) ** 2), 0.0) + weights /= weights.sum(axis=1, keepdims=True) + out[start:stop] = np.einsum("tw,twd->td", weights, flat_values[window_ids]) + return out.reshape(orig_shape) + + +# --------------------------------------------------------------------------- +# Torch FP64 smoothing path (dispatched on CUDA; CPU-testable directly) +# --------------------------------------------------------------------------- + + +def _torch_project_so3(mats): + """Project (..., 3, 3) float64 matrices to SO(3) via Newton-Schulz + SVD fallback.""" + import torch + + if mats.numel() == 0: + return mats.clone() + orig_shape = mats.shape + x = mats.reshape(-1, 3, 3) + eye = torch.eye(3, dtype=x.dtype, device=x.device) + three_eye = 3.0 * eye + y = x + for _ in range(6): + y = 0.5 * torch.bmm(y, three_eye - torch.bmm(y.transpose(-1, -2), y)) + err = (torch.bmm(y.transpose(-1, -2), y) - eye).abs().amax(dim=(-2, -1)) + det = torch.linalg.det(y) + bad = ~torch.isfinite(err) | (err > 1e-12) | ~torch.isfinite(det) | (det < 0.5) + if bad.any(): + u, _, vh = torch.linalg.svd(x[bad]) + r_bad = torch.bmm(u, vh) + neg = torch.linalg.det(r_bad) < 0.0 + if neg.any(): + u = u.clone() + u[neg, :, -1] *= -1.0 + r_bad = torch.bmm(u, vh) + y = y.clone() + y[bad] = r_bad + return y.reshape(orig_shape) + + +def _torch_rotmat_to_rotvec(rotmats): + """Convert SO(3) (..., 3, 3) float64 matrices to rotation vectors via Shepperd's method.""" + import torch + + r00 = rotmats[..., 0, 0] + r01 = rotmats[..., 0, 1] + r02 = rotmats[..., 0, 2] + r10 = rotmats[..., 1, 0] + r11 = rotmats[..., 1, 1] + r12 = rotmats[..., 1, 2] + r20 = rotmats[..., 2, 0] + r21 = rotmats[..., 2, 1] + r22 = rotmats[..., 2, 2] + + d0 = 1.0 + r00 + r11 + r22 + d1 = 1.0 + r00 - r11 - r22 + d2 = 1.0 - r00 + r11 - r22 + d3 = 1.0 - r00 - r11 + r22 + + s0 = torch.sqrt(d0.clamp(min=1e-30)) + s1 = torch.sqrt(d1.clamp(min=1e-30)) + s2 = torch.sqrt(d2.clamp(min=1e-30)) + s3 = torch.sqrt(d3.clamp(min=1e-30)) + + q0 = 0.5 * torch.stack( + (s0, (r21 - r12) / s0, (r02 - r20) / s0, (r10 - r01) / s0), dim=-1 + ) + q1 = 0.5 * torch.stack( + ((r21 - r12) / s1, s1, (r01 + r10) / s1, (r02 + r20) / s1), dim=-1 + ) + q2 = 0.5 * torch.stack( + ((r02 - r20) / s2, (r01 + r10) / s2, s2, (r12 + r21) / s2), dim=-1 + ) + q3 = 0.5 * torch.stack( + ((r10 - r01) / s3, (r02 + r20) / s3, (r12 + r21) / s3, s3), dim=-1 + ) + + c0 = (d0 >= d1) & (d0 >= d2) & (d0 >= d3) + c1 = (~c0) & (d1 >= d2) & (d1 >= d3) + c2 = (~c0) & (~c1) & (d2 >= d3) + q = torch.where( + c0.unsqueeze(-1), + q0, + torch.where( + c1.unsqueeze(-1), + q1, + torch.where(c2.unsqueeze(-1), q2, q3), + ), + ) + q = q / torch.linalg.norm(q, dim=-1, keepdim=True).clamp(min=1e-30) + # Canonicalize w >= 0 so rotation angle lies in [0, pi]. + q = torch.where(q[..., :1] < 0.0, -q, q) + + w = q[..., 0] + v = q[..., 1:] + v_norm = torch.linalg.norm(v, dim=-1) + angle = 2.0 * torch.atan2(v_norm, w) + scale = torch.where( + v_norm > 1e-7, + angle / v_norm.clamp(min=1e-30), + 2.0 * (1.0 + (v_norm * v_norm) / 6.0), + ) + return v * scale.unsqueeze(-1) + + +def _torch_rotvec_to_rotmat(rotvec): + """Convert (..., 3) float64 rotation vectors to SO(3) matrices via quaternion exp.""" + import torch + + theta = torch.linalg.norm(rotvec, dim=-1, keepdim=True) + half = 0.5 * theta + w = torch.cos(half)[..., 0] + sinc_half = torch.where( + theta > 1e-7, + torch.sin(half) / theta.clamp(min=1e-30), + 0.5 - (theta * theta) / 48.0, + ) + v = rotvec * sinc_half + x, y, z = v[..., 0], v[..., 1], v[..., 2] + xx, yy, zz = x * x, y * y, z * z + xy, xz, yz = x * y, x * z, y * z + wx, wy, wz = w * x, w * y, w * z + row0 = torch.stack( + (1.0 - 2.0 * (yy + zz), 2.0 * (xy - wz), 2.0 * (xz + wy)), dim=-1 + ) + row1 = torch.stack( + (2.0 * (xy + wz), 1.0 - 2.0 * (xx + zz), 2.0 * (yz - wx)), dim=-1 + ) + row2 = torch.stack( + (2.0 * (xz - wy), 2.0 * (yz + wx), 1.0 - 2.0 * (xx + yy)), dim=-1 + ) + return torch.stack((row0, row1, row2), dim=-2) + + +def _torch_local_noise(values_t, times_np, floor, radius, rotations, device): + """FP64 Torch equivalent of ``_local_noise`` using CPU searchsorted and exact sort median.""" + import torch + + n_times = len(times_np) + n_res = n_times - 5 + indices_np = np.arange(n_res)[:, None] + np.arange(6) + sample_times = times_np[indices_np] + delta = sample_times[:, :, None] - sample_times[:, None, :] + delta[:, np.arange(6), np.arange(6)] = 1.0 + coefficients_np = 1.0 / np.prod(delta, axis=-1) + coefficients_np /= np.linalg.norm(coefficients_np, axis=-1, keepdims=True) + centers = sample_times.mean(axis=-1) + + # Window indices computed on CPU in NumPy FP64 to avoid GPU FMA boundary drift. + lo = np.searchsorted(centers, times_np - radius, side="left") + hi = np.searchsorted(centers, times_np + radius, side="right") + short = (hi - lo) < 8 + lo_adj = np.maximum(0, np.minimum(n_res - 8, (lo + hi) // 2 - 4)) + lo = np.where(short, lo_adj, lo) + hi = np.where(short, lo + 8, hi) + counts = hi - lo + + indices_t = torch.as_tensor(indices_np, dtype=torch.long, device=device) + coeff_t = torch.as_tensor(coefficients_np, dtype=torch.float64, device=device) + blocks = values_t[indices_t] + if rotations: + relative = values_t[:-5, None].transpose(-1, -2) @ blocks + blocks = _torch_rotmat_to_rotvec(relative) + residual = torch.linalg.norm( + torch.einsum("nk,nkjd->njd", coeff_t, blocks), dim=-1 + ) # (N_res, J) + + joints = values_t.shape[1] + max_w = int(counts.max()) + noise = torch.empty((n_times, joints), dtype=torch.float64, device=device) + chunk_size = max(1, min(n_times, 2_000_000 // max(1, max_w * joints))) + for start in range(0, n_times, chunk_size): + stop = min(n_times, start + chunk_size) + c_lo = lo[start:stop] + c_counts = counts[start:stop] + c_max_w = int(c_counts.max()) + offsets = np.arange(c_max_w) + valid_np = offsets[None, :] < c_counts[:, None] + win_idx_np = np.where(valid_np, c_lo[:, None] + offsets[None, :], 0) + win_idx_t = torch.as_tensor(win_idx_np, dtype=torch.long, device=device) + valid_t = torch.as_tensor(valid_np, dtype=torch.bool, device=device) + win_res = residual[win_idx_t].masked_fill(~valid_t.unsqueeze(-1), float("inf")) + sorted_res, _ = torch.sort(win_res, dim=1) + row_idx = torch.arange(stop - start, device=device) + mid_lo = torch.as_tensor((c_counts - 1) // 2, dtype=torch.long, device=device) + mid_hi = torch.as_tensor(c_counts // 2, dtype=torch.long, device=device) + med = 0.5 * (sorted_res[row_idx, mid_lo] + sorted_res[row_idx, mid_hi]) + noise[start:stop] = torch.clamp(med / 0.888, min=float(floor)) + return noise + + +def _torch_quadratic_fit(values, delta, sigma, noise, robust=False, valid=None): + """Batched FP64 Torch equivalent of ``_quadratic_fit`` via 3x3 ``torch.linalg.solve``.""" + import torch + + if delta.ndim == 1: + delta = delta[:, None] + u = delta / sigma[None, :] + design = torch.stack((torch.ones_like(u), u, u * u), dim=-1) # (W, N, 3) + weights = torch.exp(-0.5 * u * u) + weights = weights.masked_fill(u.abs() > 3.5, 0.0) + if valid is not None: + weights = weights.masked_fill(~valid, 0.0) + + design_t = design.transpose(0, 1) # (N, W, 3) + values_t = values.transpose(0, 1) # (N, W, 3) + reg_mat = torch.diag( + torch.tensor([0.0, 1e-12, 1e-12], dtype=values.dtype, device=values.device) + ) + + def fit(current_weights): + weighted_design = (design * current_weights.unsqueeze(-1)).permute(1, 2, 0) + gram = torch.bmm(weighted_design, design_t) + reg_mat + rhs = torch.bmm(weighted_design, values_t) + return torch.linalg.solve(gram, rhs) + + estimate = fit(weights) + fitted = torch.bmm(design_t, estimate).transpose(0, 1) + residual = torch.linalg.norm(values - fitted, dim=-1) + clamped_res = torch.minimum(residual, 3.0 * noise[None, :]) + score = torch.sqrt( + (weights * clamped_res * clamped_res).sum(dim=0) / weights.sum(dim=0) + ) + if robust: + for iter_idx in range(2): + influence = torch.clamp( + 2.5 * noise[None, :] / residual.clamp(min=1e-12), + max=1.0, + ) + estimate = fit(weights * influence) + if iter_idx == 0: + fitted = torch.bmm(design_t, estimate).transpose(0, 1) + residual = torch.linalg.norm(values - fitted, dim=-1) + return estimate[:, 0], score + + +def _torch_smooth_local_motion( + values_t, times_np, config, noise_floor, device, rotations=False +): + """FP64 Torch equivalent of ``_smooth_local_motion`` with CPU searchsorted windows.""" + import torch + + noise = _torch_local_noise( + values_t, times_np, noise_floor, config.noise_radius_seconds, rotations, device + ) + widths = config.max_sigma_seconds * np.array([1.0, 0.7, 0.45, 0.275]) + out_t = values_t.clone() + centers = np.arange(1, len(times_np) - 1) + max_sigma = np.minimum( + config.max_sigma_seconds, + np.minimum(times_np[centers] - times_np[0], times_np[-1] - times_np[centers]) + / 3.5, + ) + lo = np.searchsorted(times_np, times_np[centers] - 3.5 * max_sigma) + hi = np.searchsorted(times_np, times_np[centers] + 3.5 * max_sigma, side="right") + usable = hi - lo >= 3 + centers, max_sigma, lo, hi = (a[usable] for a in (centers, max_sigma, lo, hi)) + if not len(centers): + return out_t.cpu().numpy() + + joints = values_t.shape[1] + batch_size = max(1, min(1024, 262144 // (int(np.max(hi - lo)) * joints))) + for start in range(0, len(centers), batch_size): + stop = start + batch_size + indices = centers[start:stop] + local_widths = np.minimum(widths[None], max_sigma[start:stop, None]) + counts = hi[start:stop] - lo[start:stop] + offsets = np.arange(int(counts.max())) + valid_np = offsets[None] < counts[:, None] + window_ids_np = lo[start:stop, None] + offsets[None] + window_ids_np = np.where(valid_np, window_ids_np, indices[:, None]) + delta_np = times_np[window_ids_np] - times_np[indices, None] + + indices_t = torch.as_tensor(indices, dtype=torch.long, device=device) + window_ids_t = torch.as_tensor(window_ids_np, dtype=torch.long, device=device) + delta_t = torch.as_tensor(delta_np, dtype=torch.float64, device=device) + valid_t = torch.as_tensor(valid_np, dtype=torch.bool, device=device) + local_widths_t = torch.as_tensor( + local_widths, dtype=torch.float64, device=device + ) + + window = values_t[window_ids_t] + if rotations: + relative = values_t[indices_t, None].transpose(-1, -2) @ window + window = _torch_rotmat_to_rotvec(relative) + + num_offsets = len(offsets) + window = window.permute(1, 0, 2, 3).reshape(num_offsets, -1, 3) + delta_rep = delta_t.T.repeat_interleave(joints, dim=1) + valid_rep = valid_t.T.repeat_interleave(joints, dim=1) + local_noise = noise[indices_t].reshape(-1) + candidate_widths = local_widths_t.repeat_interleave(joints, dim=0) + + num_traj = len(indices) * joints + chosen = torch.zeros((num_traj, 3), dtype=torch.float64, device=device) + pending = torch.arange(num_traj, device=device) + previous_score = None + previous_width = None + for candidate in range(len(widths)): + width = candidate_widths[pending, candidate] + sigma = width.clone() + _, score = _torch_quadratic_fit( + window[:, pending], + delta_rep[:, pending], + sigma, + local_noise[pending], + valid=valid_rep[:, pending], + ) + accepted = (score <= config.fit_tolerance * local_noise[pending]) | ( + width == candidate_widths[pending, -1] + ) + if accepted.any(): + if previous_score is not None: + fraction = torch.clamp( + (config.fit_tolerance * local_noise[pending] - score) + / torch.clamp(previous_score - score, min=1e-12), + 0.0, + 1.0, + ) + sigma = sigma * (previous_width / width) ** fraction + selected = pending[accepted] + estimate, _ = _torch_quadratic_fit( + window[:, selected], + delta_rep[:, selected], + sigma[accepted], + local_noise[selected], + robust=True, + valid=valid_rep[:, selected], + ) + chosen[selected] = estimate + pending = pending[~accepted] + if pending.numel() == 0: + break + previous_score, previous_width = score[~accepted], width[~accepted] + + chosen = chosen.reshape(len(indices), joints, 3) + if rotations: + out_t[indices_t] = values_t[indices_t] @ _torch_rotvec_to_rotmat(chosen) + else: + out_t[indices_t] = chosen + return out_t.cpu().numpy() + + +def _smooth_translation_torch(values, times, config, device): + """FP64 Torch translation smoother; delegates short tracks (< 13) to CPU.""" + import torch + + values = np.asarray(values, dtype=np.float64) + times = np.asarray(times, dtype=np.float64) + if len(values) < 13: + return _short_translation(values, times, config) + values_t = torch.as_tensor(values[:, None], dtype=torch.float64, device=device) + return _torch_smooth_local_motion( + values_t, times, config, config.translation_noise_floor_m, device + )[:, 0] + + +def _smooth_rotations_torch(values, times, config, device): + """FP64 Torch SO(3) rotation smoother; delegates short tracks (< 13) to CPU.""" + import torch + + values = np.asarray(values, dtype=np.float64) + times = np.asarray(times, dtype=np.float64) + if not len(values): + return values.copy() + if len(values) < 13: + return smooth_rotations(values, times, config) + values_t = torch.as_tensor(values, dtype=torch.float64, device=device) + values_t = _torch_project_so3(values_t) + return _torch_smooth_local_motion( + values_t, + times, + config, + config.angular_noise_floor_rad, + device, + rotations=True, + ) + + +def _valid_geometry_parameters(result): + """True when SOMA geometry decode inputs are finite (even if transl is NaN).""" + if result is None: + return False + for key in ("poses", "identity_coeffs", "global_scale"): + if result.get(key) is None or not np.isfinite(result[key]).all(): + return False + scales = result.get("scale_params") + return scales is None or np.isfinite(scales).all() def _valid_parameters(result): @@ -383,16 +791,37 @@ def _segments(hand_results, image_ids, times, config): yield segment -def _filter_parameters(records, segment_times, config): +def _filter_parameters(records, segment_times, config, device=None): """Shared parameter update for full-geometry and parameters-only output.""" - filtered = { - "transl": smooth_translation( - np.stack([r["transl"] for r in records]), segment_times, config - ), - "poses": smooth_rotations( - np.stack([r["poses"] for r in records]), segment_times, config - ), - } + use_cuda = False + if device is not None: + import torch + + use_cuda = torch.device(device).type == "cuda" + if use_cuda: + filtered = { + "transl": _smooth_translation_torch( + np.stack([r["transl"] for r in records]), + segment_times, + config, + device, + ), + "poses": _smooth_rotations_torch( + np.stack([r["poses"] for r in records]), + segment_times, + config, + device, + ), + } + else: + filtered = { + "transl": smooth_translation( + np.stack([r["transl"] for r in records]), segment_times, config + ), + "poses": smooth_rotations( + np.stack([r["poses"] for r in records]), segment_times, config + ), + } for key in ("identity_coeffs", "scale_params", "global_scale"): if records[0].get(key) is not None: filtered[key] = _smooth_shape( @@ -495,6 +924,254 @@ def _project_to_crop_frame( return keypoints_2d, projection_valid +def _project_batch_to_crop_frame( + joints_3d, + transl, + cameras, + bboxes_xys, + *, + min_depth: float = MIN_CAMERA_DEPTH, +): + """Vectorized crop-frame projection for a batch of frames. + + Groups camera objects exposing ``.project`` by ``id(camera)`` so distortion + projection runs once per unique camera, and stacks 3x3 pinhole matrices for + a single batched projection. Matches :func:`_project_to_crop_frame` + element-for-element, including invalid/non-finite handling. + + Args: + joints_3d: Array-like of shape ``(N, J, 3)`` in hand-local meters. + transl: Array-like of shape ``(N, 3)`` camera translation in meters. + cameras: Sequence of length ``N`` of camera objects or ``(3, 3)`` Ks. + bboxes_xys: Array-like of shape ``(N, 3)`` as ``[cx, cy, size]``. + min_depth: Minimum positive Z depth for a valid projection. + + Returns: + ``(keypoints_2d, projection_valid)`` with shapes ``(N, J, 2)`` + (float64, NaN where invalid) and ``(N, J)`` (bool). + """ + joints = np.asarray(joints_3d, dtype=np.float64) + trans = np.asarray(transl, dtype=np.float64) + bboxes = np.asarray(bboxes_xys, dtype=np.float64) + n, num_joints = joints.shape[0], joints.shape[1] + if n == 0: + return ( + np.empty((0, num_joints, 2), dtype=np.float64), + np.empty((0, num_joints), dtype=np.bool_), + ) + + camera_points = joints + trans[:, None, :] + projection_valid = np.isfinite(camera_points).all(axis=-1) & ( + camera_points[:, :, 2] > float(min_depth) + ) + pixels = np.full((n, num_joints, 2), np.nan, dtype=np.float64) + + camera_groups: dict[int, tuple[object, list[int]]] = {} + pinhole_indices: list[int] = [] + for i, cam in enumerate(cameras): + if callable(getattr(cam, "project", None)): + cam_id = id(cam) + if cam_id not in camera_groups: + camera_groups[cam_id] = (cam, [i]) + else: + camera_groups[cam_id][1].append(i) + else: + pinhole_indices.append(i) + + for cam, idx_list in camera_groups.values(): + idx = np.asarray(idx_list, dtype=np.intp) + sub_valid = projection_valid[idx] + if sub_valid.any(): + sub_pts = camera_points[idx] + sub_pixels = np.full((len(idx), num_joints, 2), np.nan, dtype=np.float64) + sub_pixels[sub_valid] = cam.project(sub_pts[sub_valid]) + pixels[idx] = sub_pixels + + if pinhole_indices: + idx = np.asarray(pinhole_indices, dtype=np.intp) + sub_pts = camera_points[idx] + sub_valid = projection_valid[idx] + safe_pts = np.zeros_like(sub_pts) + safe_pts[:, :, 2] = 1.0 + safe_pts[sub_valid] = sub_pts[sub_valid] + K_stack = np.stack( + [np.asarray(cameras[i], dtype=np.float64) for i in pinhole_indices], + axis=0, + ) + normalized = safe_pts / safe_pts[:, :, 2:3] + pixels[idx] = normalized @ K_stack[:, :2, :].swapaxes(-1, -2) + + centers = bboxes[:, None, :2] + sizes = bboxes[:, None, 2:3] + with np.errstate(divide="ignore", invalid="ignore"): + keypoints_2d = (pixels - centers) / sizes + projection_valid &= np.isfinite(keypoints_2d).all(axis=-1) + keypoints_2d[~projection_valid] = np.nan + return keypoints_2d, projection_valid + + +def _infer_hand_geometry_shapes(soma_hand, hand, sample_record, device): + """Determine ``(num_verts, num_joints)`` for NaN-filling deferred invalid records.""" + import torch + + num_verts = None + num_joints = None + if sample_record.get("poses") is not None: + num_joints = int(np.asarray(sample_record["poses"]).shape[0]) + + layer = getattr(soma_hand, hand, None) + if layer is not None: + bind_shape = getattr(layer, "bind_shape", None) + if bind_shape is not None: + num_verts = int(bind_shape.shape[0]) + elif getattr(layer, "hand_vert_ids", None) is not None: + num_verts = len(layer.hand_vert_ids) + if num_joints is None: + bind_pose_world = getattr(layer, "bind_pose_world", None) + if bind_pose_world is not None: + num_joints = int(bind_pose_world.shape[0]) + elif getattr(layer, "joint_parent_ids", None) is not None: + num_joints = len(layer.joint_parent_ids) + + if num_verts is None: + # Fallback for callable stubs that do not expose SOMAHandLayer buffers: + # probe one neutral pose to discover exact output vertex/joint counts. + probe_joints = num_joints if num_joints is not None else 25 + id_dim = ( + int(np.asarray(sample_record["identity_coeffs"]).shape[-1]) + if sample_record.get("identity_coeffs") is not None + else 5 + ) + sp_raw = sample_record.get("scale_params") + sp_tensor = ( + torch.zeros( + (1, int(np.asarray(sp_raw).shape[-1])), + dtype=torch.float32, + device=device, + ) + if sp_raw is not None + else None + ) + with ( + torch.no_grad(), + torch.autocast(device_type=torch.device(device).type, enabled=False), + torch.jit.optimized_execution(False), + ): + probed = soma_hand( + poses=torch.eye(3, dtype=torch.float32, device=device) + .reshape(1, 1, 3, 3) + .expand(1, probe_joints, 3, 3) + .contiguous(), + identity_coeffs=torch.zeros( + (1, id_dim), dtype=torch.float32, device=device + ), + hand_type=hand, + transl=None, + pose2rot=False, + global_scale=torch.ones((1,), dtype=torch.float32, device=device), + scale_params=sp_tensor, + ) + num_verts = int(probed["vertices"].shape[1]) + num_joints = int(probed["joints"].shape[1]) + + if num_joints is None: + num_joints = 25 + return num_verts, num_joints + + +def _decode_soma_batches(records, hand, soma_hand, device, batch_size): + """Run batched ``soma_hand`` decode and populate ``pred_vertices`` / ``pred_keypoints_3d``.""" + import torch + + decoded_shapes = None + for start in range(0, len(records), batch_size): + batch = records[start : start + batch_size] + + def tensor(key, batch=batch): + return torch.as_tensor( + np.stack([r[key] for r in batch]), + dtype=torch.float32, + device=device, + ) + + # Disable TorchScript's thread-local profiling/fusion optimizer around + # SOMA MHR calls: smoothed tracks have variable segment lengths, so + # shape-specialized JIT recompiles stall ~0.4-1.1 s per new length for + # <1 ms steady-state savings. + with ( + torch.no_grad(), + torch.autocast(device_type=torch.device(device).type, enabled=False), + torch.jit.optimized_execution(False), + ): + decoded = soma_hand( + poses=tensor("poses"), + identity_coeffs=tensor("identity_coeffs"), + hand_type=hand, + transl=None, + pose2rot=False, + global_scale=tensor("global_scale"), + scale_params=tensor("scale_params") + if batch[0].get("scale_params") is not None + else None, + ) + vertices = decoded["vertices"].detach().cpu().numpy() + joints = decoded["joints"].detach().cpu().numpy() + decoded_shapes = (int(vertices.shape[1]), int(joints.shape[1])) + for j, result in enumerate(batch): + verts_dtype = ( + result["pred_vertices"].dtype + if result.get("pred_vertices") is not None + else np.float32 + ) + kp3d_dtype = ( + result["pred_keypoints_3d"].dtype + if result.get("pred_keypoints_3d") is not None + else np.float32 + ) + result["pred_vertices"] = vertices[j].astype(verts_dtype) + result["pred_keypoints_3d"] = joints[j].astype(kp3d_dtype) + return decoded_shapes + + +def _project_records_to_crop_frame( + records, + record_image_ids, + hand, + bboxes_per_image, + intrinsics_per_image, + min_depth, +): + """Project a list of decoded records in one vectorized call and update in place.""" + if not records: + return + cameras = [] + bboxes = [] + for image_id, result in zip(record_image_ids, records): + camera = result["K_fullimg"] + if camera is None: + if intrinsics_per_image is None: + raise ValueError("Fisheye smoothing requires intrinsics_per_image") + camera = intrinsics_per_image[image_id] + cameras.append(camera) + bboxes.append(np.asarray(bboxes_per_image[image_id][hand], dtype=np.float64)) + + kp2d_all, valid_all = _project_batch_to_crop_frame( + np.stack([r["pred_keypoints_3d"] for r in records]), + np.stack([r["transl"] for r in records]), + cameras, + np.stack(bboxes), + min_depth=min_depth, + ) + for j, result in enumerate(records): + kp2d_dtype = ( + result["pred_keypoints_2d"].dtype + if result.get("pred_keypoints_2d") is not None + else np.float32 + ) + result["pred_keypoints_2d"] = kp2d_all[j].astype(kp2d_dtype) + result["pred_projection_valid"] = valid_all[j] + + def smooth_adaptive_hand_results( results_per_hand, image_ids, @@ -512,77 +1189,149 @@ def smooth_adaptive_hand_results( ``soma_hand`` is the existing SomaHandWrapper. Calls must be serialized with inference because its hand layers cache mutable identity state. - Missing/non-finite predictions remain untouched and split the filter. + Missing/non-finite predictions remain untouched and split the filter, except + when pre-smooth geometry was deferred (``None``): valid-geometry uncovered + records are decoded via ``soma_hand`` and invalid-geometry records receive + NaN arrays and a ``False`` projection mask so downstream writers never see + ``None``. For perspective-cropped fisheye predictions, ``K_fullimg`` is None; supply their original camera objects in ``intrinsics_per_image``. """ - import torch - if config is None: config = AdaptiveSmoothingConfig() times = validate_frame_times(frame_times, len(image_ids)) if batch_size < 1: raise ValueError("batch_size must be positive") for hand, hand_results in results_per_hand.items(): + covered_ids: set = set() + known_shapes: tuple[int, int] | None = None for indices in _segments(hand_results, image_ids, times, config): - records = [hand_results[image_ids[i]] for i in indices] + seg_image_ids = [image_ids[i] for i in indices] + records = [hand_results[image_id] for image_id in seg_image_ids] + covered_ids.update(seg_image_ids) segment_times = times[indices] - _filter_parameters(records, segment_times, config) + _filter_parameters(records, segment_times, config, device=device) - for start in range(0, len(records), batch_size): - batch = records[start : start + batch_size] + decoded_shapes = _decode_soma_batches( + records, hand, soma_hand, device, batch_size + ) + if decoded_shapes is not None: + known_shapes = decoded_shapes + _project_records_to_crop_frame( + records, + seg_image_ids, + hand, + bboxes_per_image, + intrinsics_per_image, + min_depth, + ) - def tensor(key, batch=batch): - return torch.as_tensor( - np.stack([r[key] for r in batch]), - dtype=torch.float32, - device=device, + # Populate any non-segment (uncovered) records whose pre-smooth geometry + # was deferred (None), so save_hand_results_clip / save_results never + # encounter None arrays. + deferred_valid: list[tuple[str, dict]] = [] + deferred_invalid: list[dict] = [] + for image_id, result in hand_results.items(): + if result is None or image_id in covered_ids: + continue + needs_geometry = any( + result.get(key) is None + for key in ( + "pred_vertices", + "pred_keypoints_3d", + "pred_keypoints_2d", + "pred_projection_valid", + ) + ) + if not needs_geometry: + if known_shapes is None and result.get("pred_vertices") is not None: + known_shapes = ( + int(result["pred_vertices"].shape[0]), + int(result["pred_keypoints_3d"].shape[0]), ) + continue + if _valid_geometry_parameters(result): + deferred_valid.append((image_id, result)) + else: + deferred_invalid.append(result) + + if deferred_valid: + # Group by parameter schema so np.stack inside _decode_soma_batches + # always receives uniform shapes. + by_schema: dict[tuple, list[tuple[str, dict]]] = {} + for image_id, result in deferred_valid: + schema = ( + np.shape(result["poses"]), + np.shape(result["identity_coeffs"]), + None + if result.get("scale_params") is None + else np.shape(result["scale_params"]), + ) + by_schema.setdefault(schema, []).append((image_id, result)) - with ( - torch.no_grad(), - torch.autocast( - device_type=torch.device(device).type, enabled=False - ), - ): - decoded = soma_hand( - poses=tensor("poses"), - identity_coeffs=tensor("identity_coeffs"), - hand_type=hand, - transl=None, - pose2rot=False, - global_scale=tensor("global_scale"), - scale_params=tensor("scale_params") - if batch[0].get("scale_params") is not None - else None, + for group in by_schema.values(): + grp_records = [result for _, result in group] + decoded_shapes = _decode_soma_batches( + grp_records, hand, soma_hand, device, batch_size + ) + if decoded_shapes is not None: + known_shapes = decoded_shapes + proj_ids = [] + proj_records = [] + for image_id, result in group: + transl = result.get("transl") + has_transl = transl is not None and np.isfinite(transl).all() + bbox = (bboxes_per_image.get(image_id) or {}).get(hand) + camera = result.get("K_fullimg") + if camera is None and intrinsics_per_image is not None: + camera = intrinsics_per_image.get(image_id) + if has_transl and bbox is not None and camera is not None: + proj_ids.append(image_id) + proj_records.append(result) + else: + num_joints = int(result["pred_keypoints_3d"].shape[0]) + kp2d_dtype = ( + result["pred_keypoints_2d"].dtype + if result.get("pred_keypoints_2d") is not None + else np.float32 + ) + result["pred_keypoints_2d"] = np.full( + (num_joints, 2), np.nan, dtype=kp2d_dtype + ) + result["pred_projection_valid"] = np.zeros( + (num_joints,), dtype=np.bool_ + ) + if proj_records: + _project_records_to_crop_frame( + proj_records, + proj_ids, + hand, + bboxes_per_image, + intrinsics_per_image, + min_depth, ) - vertices = decoded["vertices"].detach().cpu().numpy() - joints = decoded["joints"].detach().cpu().numpy() - for j, result in enumerate(batch): - result["pred_vertices"] = vertices[j].astype( - result["pred_vertices"].dtype + + if deferred_invalid: + if known_shapes is None: + known_shapes = _infer_hand_geometry_shapes( + soma_hand, hand, deferred_invalid[0], device + ) + num_verts, num_joints = known_shapes + for result in deferred_invalid: + if result.get("pred_vertices") is None: + result["pred_vertices"] = np.full( + (num_verts, 3), np.nan, dtype=np.float32 ) - result["pred_keypoints_3d"] = joints[j].astype( - result["pred_keypoints_3d"].dtype + if result.get("pred_keypoints_3d") is None: + result["pred_keypoints_3d"] = np.full( + (num_joints, 3), np.nan, dtype=np.float32 ) - image_id = image_ids[indices[start + j]] - bbox = bboxes_per_image[image_id][hand] - camera = result["K_fullimg"] - if camera is None: - if intrinsics_per_image is None: - raise ValueError( - "Fisheye smoothing requires intrinsics_per_image" - ) - camera = intrinsics_per_image[image_id] - points, valid = _project_to_crop_frame( - result["pred_keypoints_3d"], - result["transl"], - camera, - bbox, - min_depth=min_depth, + if result.get("pred_keypoints_2d") is None: + result["pred_keypoints_2d"] = np.full( + (num_joints, 2), np.nan, dtype=np.float32 ) - result["pred_keypoints_2d"] = points.astype( - result["pred_keypoints_2d"].dtype + if result.get("pred_projection_valid") is None: + result["pred_projection_valid"] = np.zeros( + (num_joints,), dtype=np.bool_ ) - result["pred_projection_valid"] = valid return results_per_hand diff --git a/src/python/isaaccapture_egopost/inference/preprocessing/crop.py b/src/python/isaaccapture_egopost/inference/preprocessing/crop.py index d7d5ffd714..4ae6effda0 100644 --- a/src/python/isaaccapture_egopost/inference/preprocessing/crop.py +++ b/src/python/isaaccapture_egopost/inference/preprocessing/crop.py @@ -15,6 +15,34 @@ IMG_SIZE = 256 +def crop_uint8(img_bgr, bbx_xys): + """Return the ``IMG_SIZE`` x ``IMG_SIZE`` uint8 RGB crop of ``crop_and_preprocess``. + + Warps the BGR source first and converts only the 256x256 output to RGB. + ``cv2.warpAffine(..., flags=cv2.INTER_LINEAR)`` interpolates each channel + independently with zero border padding, so performing BGR->RGB after the + warp is bit-exact while avoiding a full-frame color conversion copy. + """ + cx, cy, size = float(bbx_xys[0]), float(bbx_xys[1]), float(bbx_xys[2]) + trans = get_transform( + center=np.array([cx, cy]), scale=size, res=(IMG_SIZE, IMG_SIZE), rot=0 + ) + img_crop_bgr = cv2.warpAffine( + img_bgr, trans, (IMG_SIZE, IMG_SIZE), flags=cv2.INTER_LINEAR + ) + return cv2.cvtColor(img_crop_bgr, cv2.COLOR_BGR2RGB) + + +def normalize_crop(img_crop): + """Normalize a uint8 ``HWC`` RGB crop to the model's float32 ``CHW`` input. + + Matches the normalization of ``crop_and_preprocess`` elementwise. + """ + img_f = img_crop.astype(np.float32) / 255.0 + img_f = (img_f - IMAGENET_MEAN) / IMAGENET_STD + return torch.from_numpy(img_f.transpose(2, 0, 1)) + + def crop_and_preprocess(img_bgr, bbx_xys): """Crop a hand bbox and normalize it for EgoHand inference. @@ -25,18 +53,8 @@ def crop_and_preprocess(img_bgr, bbx_xys): Returns: Normalized ``CHW`` tensor and the unnormalized RGB crop. """ - img_rgb = cv2.cvtColor(img_bgr, cv2.COLOR_BGR2RGB) - cx, cy, size = float(bbx_xys[0]), float(bbx_xys[1]), float(bbx_xys[2]) - trans = get_transform( - center=np.array([cx, cy]), scale=size, res=(IMG_SIZE, IMG_SIZE), rot=0 - ) - img_crop = cv2.warpAffine( - img_rgb, trans, (IMG_SIZE, IMG_SIZE), flags=cv2.INTER_LINEAR - ) - img_f = img_crop.astype(np.float32) / 255.0 - img_f = (img_f - IMAGENET_MEAN) / IMAGENET_STD - img_tensor = torch.from_numpy(img_f.transpose(2, 0, 1)) - return img_tensor, img_crop + img_crop = crop_uint8(img_bgr, bbx_xys) + return normalize_crop(img_crop), img_crop def project_camera_points_to_crop_with_validity( diff --git a/src/python/isaaccapture_egopost/inference/preprocessing/mirroring.py b/src/python/isaaccapture_egopost/inference/preprocessing/mirroring.py index 7ec03f732d..4a31115b65 100644 --- a/src/python/isaaccapture_egopost/inference/preprocessing/mirroring.py +++ b/src/python/isaaccapture_egopost/inference/preprocessing/mirroring.py @@ -3,11 +3,15 @@ """Right-hand to canonical-left mirroring of rasters, cameras and predictions.""" +import cv2 import numpy as np import torch +from egohand.utils.crop_transform import get_transform from inference.preprocessing.crop import ( - crop_and_preprocess, + IMAGENET_MEAN, + IMAGENET_STD, + IMG_SIZE, project_camera_points_to_crop_with_validity, ) @@ -90,27 +94,100 @@ def mirror_legacy_crop_camera_horizontal( return mirrored_bbox, mirrored_intrinsics -def prepare_right_hand_model_input( +def _crop_mirrored_full_image_uint8( + img_bgr: np.ndarray, + mirrored_bbx_xys: np.ndarray, +) -> np.ndarray: + """Crop the virtual full-image horizontal mirror without materializing it. + + Slices only the prefix ROI from ``(0, 0)`` to the mirrored affine's + bottom-right support bound (with a 4-pixel bilinear margin) and flips that + source suffix horizontally. Keeping origin ``(0, 0)`` preserves the exact + ``cv2.warpAffine`` transform and bilinear quantization of a full-frame flip. + BGR-to-RGB conversion runs on the 256x256 output crop, which is bit-exact + with converting the full ROI before warping (``max_u8_diff == 0``). + + Args: + img_bgr: Full input image in OpenCV BGR ``uint8`` layout ``(H, W, 3)``. + mirrored_bbx_xys: Mirrored crop ``[center_x, center_y, size]`` in + full-image pixels. + + Returns: + RGB ``uint8`` crop of shape ``(IMG_SIZE, IMG_SIZE, 3)``. + """ + image = np.asarray(img_bgr) + if image.ndim != 3: + raise ValueError(f"img_bgr must have shape (H, W, C), got {image.shape}") + image_height, image_width = int(image.shape[0]), int(image.shape[1]) + cx, cy, size = ( + float(mirrored_bbx_xys[0]), + float(mirrored_bbx_xys[1]), + float(mirrored_bbx_xys[2]), + ) + + # The warp only reads the mirrored bbox plus bilinear support. Four source + # pixels are a conservative margin for OpenCV's interpolation table. + margin = 4 + required_x0 = int(np.floor(cx - size / 2.0)) - margin + required_x1 = int(np.ceil(cx + size / 2.0)) + margin + 1 + required_y0 = int(np.floor(cy - size / 2.0)) - margin + required_y1 = int(np.ceil(cy + size / 2.0)) + margin + 1 + intersects_image = ( + required_x1 > 0 + and required_x0 < image_width + and required_y1 > 0 + and required_y0 < image_height + ) + + # A fully off-image bbox produces the same black crop as warpAffine's + # default BORDER_CONSTANT behavior, without touching an empty ROI. + if not intersects_image: + return np.zeros((IMG_SIZE, IMG_SIZE, 3), dtype=np.uint8) + + # Keep origin (0, 0) so the original transform remains bitwise intact. + # Mirrored prefix [0:x1] is original suffix [W-x1:W] reversed. + x1 = min(image_width, max(1, required_x1)) + y1 = min(image_height, max(1, required_y1)) + original_x0 = image_width - x1 + flipped_roi_bgr = np.ascontiguousarray(image[:y1, original_x0:image_width][:, ::-1]) + + # The ROI begins at full mirrored-image (0, 0), so use the exact same + # forward matrix and interpolation path as the full-frame reference. + crop_from_mirrored = get_transform( + center=np.array([cx, cy]), + scale=size, + res=(IMG_SIZE, IMG_SIZE), + rot=0, + ) + img_crop_bgr = cv2.warpAffine( + flipped_roi_bgr, + crop_from_mirrored, + (IMG_SIZE, IMG_SIZE), + flags=cv2.INTER_LINEAR, + ) + return cv2.cvtColor(img_crop_bgr, cv2.COLOR_BGR2RGB) + + +def prepare_right_hand_model_input_uint8( img_bgr: np.ndarray, bbx_xys: np.ndarray, K_fullimg: np.ndarray, *, calibrated_full_image: bool, -) -> tuple[torch.Tensor, np.ndarray, np.ndarray]: - """Canonicalize a right-hand raster and camera for the left-hand model. +) -> tuple[np.ndarray, np.ndarray, np.ndarray]: + """Canonicalize a right-hand raster (uint8 RGB) and camera for the left-hand model. The calibrated camera contract mirrors the full raster about pixel centers, transforms the complete camera, and only then crops at the - mirrored bbox. Cropping first and flipping the resized crop differs by - one output pixel under the affine sampling convention and would not match - training. Legacy checkpoints intentionally retain their historical - crop-then-flip raster and ``W - x`` metadata contract. + mirrored bbox. Using :func:`_crop_mirrored_full_image_uint8` avoids + materializing the full horizontally flipped frame while remaining bit-exact. + Legacy checkpoints intentionally retain their historical crop-then-flip + raster and ``W - x`` metadata contract. Returns: - ``(normalized_crop, model_bbox, model_K)`` in the canonical-left + ``(rgb_crop_uint8, model_bbox, model_K)`` in the canonical-left model input frame. """ - image = np.asarray(img_bgr) if image.ndim != 3: raise ValueError(f"img_bgr must have shape (H, W, C), got {image.shape}") @@ -121,59 +198,91 @@ def prepare_right_hand_model_input( K_fullimg, image_width, ) - flipped_full_image = np.ascontiguousarray(image[:, ::-1]) - crop_tensor, _ = crop_and_preprocess( - flipped_full_image, - model_bbox, - ) + crop_rgb = _crop_mirrored_full_image_uint8(image, model_bbox) else: model_bbox, model_K = mirror_legacy_crop_camera_horizontal( bbx_xys, K_fullimg, image_width, ) - crop_tensor, _ = crop_and_preprocess(image, bbx_xys) - crop_tensor = crop_tensor.flip(-1) + cx, cy, size = float(bbx_xys[0]), float(bbx_xys[1]), float(bbx_xys[2]) + trans = get_transform( + center=np.array([cx, cy]), + scale=size, + res=(IMG_SIZE, IMG_SIZE), + rot=0, + ) + img_crop_bgr = cv2.warpAffine( + image, + trans, + (IMG_SIZE, IMG_SIZE), + flags=cv2.INTER_LINEAR, + ) + crop_rgb = np.ascontiguousarray( + cv2.cvtColor(img_crop_bgr, cv2.COLOR_BGR2RGB)[:, ::-1] + ) + return crop_rgb, model_bbox, model_K + + +def prepare_right_hand_model_input( + img_bgr: np.ndarray, + bbx_xys: np.ndarray, + K_fullimg: np.ndarray, + *, + calibrated_full_image: bool, +) -> tuple[torch.Tensor, np.ndarray, np.ndarray]: + """Canonicalize a right-hand raster and camera for the left-hand model. + + The calibrated camera contract mirrors the full raster about pixel + centers, transforms the complete camera, and only then crops at the + mirrored bbox. Cropping first and flipping the resized crop differs by + one output pixel under the affine sampling convention and would not match + training. Legacy checkpoints intentionally retain their historical + crop-then-flip raster and ``W - x`` metadata contract. + + Returns: + ``(normalized_crop, model_bbox, model_K)`` in the canonical-left + model input frame. + """ + crop_rgb, model_bbox, model_K = prepare_right_hand_model_input_uint8( + img_bgr, + bbx_xys, + K_fullimg, + calibrated_full_image=calibrated_full_image, + ) + img_f = crop_rgb.astype(np.float32) / 255.0 + img_f = (img_f - IMAGENET_MEAN) / IMAGENET_STD + crop_tensor = torch.from_numpy(img_f.transpose(2, 0, 1)) return crop_tensor, model_bbox, model_K -def mirror_left_prediction_to_right( - model, - poses, - transl, - identity_coeffs, - global_scale, - K_fullimg, - bbx_xys, - scale_params=None, +def mirror_left_poses_to_right( + left_layer, + right_layer, + poses: torch.Tensor, + transl: torch.Tensor, + *, pose_mirror=None, -): - """Convert left-canonicalized right-hand predictions back to right hands (batched). +) -> tuple[torch.Tensor, torch.Tensor]: + """Mirror left-canonicalized SOMA hand rotations and wrist translation to right. - All inputs share a leading batch dim B over the right-hand samples in the - current EgoHand forward pass. + Runs pure rotation-chain forward kinematics via + ``left_layer.batched_skinning._forward_kinematics_impl`` with + ``bind_world_transforms=left_layer.bind_pose_world``, ``bind_batched=False``, + and zero non-root local translations. Because joint rotations and joint-0 + wrist translation are completely independent of bone lengths and identity + shape, this skips ``prepare_identity``, MHR, skeleton transfer, and LBS + while remaining bit-exact with the full FK mirror path. Args: - model: Loaded EgoHand model with left and right SOMAHand layers. - poses: (B, 25, 3, 3) left-canonicalized SOMA hand rotations. - transl: (B, 3) left-canonicalized camera translation in meters. - identity_coeffs: (B, K) SOMAHand identity coefficients. - global_scale: (B,) per-sample uniform scale. - K_fullimg: (B, 3, 3) full-image camera intrinsics. - bbx_xys: (B, 3) per-sample bbox as ``[center_x, center_y, size]``. - scale_params: Optional (B, S) per-sample MHR hand scale parameters. - pose_mirror: Optional pre-constructed ``PoseMirror_SOMA`` matching the - paired ``["Root"] + left_joint_names + right_joint_names`` rig. - The predictor caches this once at init so subsequent batches do - not pay the per-call setup. When ``None``, a fresh instance is - built on each call (correct, but slower). + left_layer: Left ``SOMAHandLayer``. + right_layer: Right ``SOMAHandLayer``. + poses: ``(B, 25, 3, 3)`` left-canonicalized SOMA hand rotations. + transl: ``(B, 3)`` left-canonicalized camera translation in meters. + pose_mirror: Optional cached ``PoseMirror_SOMA`` for the paired rig. Returns: - Dict of right-hand predictions matching EgoHand's saved schema, all with - leading batch dim B: ``pred_vertices`` ``(B, V, 3)``, ``transl`` - ``(B, 3)``, ``pred_keypoints_3d`` ``(B, 25, 3)``, ``pred_keypoints_2d`` - ``(B, 25, 2)`` (bbox-relative, normalized by bbox size), ``poses`` - ``(B, 25, 3, 3)``. + ``(right_poses, right_transl)`` of shapes ``(B, 25, 3, 3)`` and ``(B, 3)``. """ from soma.geometry.rig_utils import ( PoseMirror_SOMA, @@ -182,26 +291,32 @@ def mirror_left_prediction_to_right( remove_joint_orient_local, ) - left_layer = model.soma_hand.left - right_layer = model.soma_hand.right batch_size = poses.shape[0] - - # 1. Forward-kinematics through the left layer in one batched call. - left_layer.prepare_identity( - identity_coeffs, - global_scale=global_scale, - scale_params=scale_params, + skinning = left_layer.batched_skinning + zero_local_t = torch.zeros( + skinning.num_joints, + 3, + dtype=skinning.dtype, + device=skinning.device, ) - left_pose_out = left_layer.pose( - poses=poses, - pose2rot=False, - absolute_pose=False, + left_transforms = skinning._forward_kinematics_impl( + local_rotations=poses.reshape(batch_size, skinning.num_joints, 3, 3), global_translation=transl, - fk_only=True, - ) - left_transforms = left_pose_out.transforms # (B, 25, 4, 4) + align_translation=None, + absolute_pose=False, + hips_translations=None, + local_translations=zero_local_t, + num_joints=skinning.num_joints, + bind_world_transforms=left_layer.bind_pose_world, + bind_batched=False, + default_local_translations=zero_local_t, + global_translation_joint_idx=skinning.global_translation_joint_idx, + levels=skinning._levels, + joint_orient=skinning.joint_orient, + orient_parent_T=skinning._orient_parent_T, + ) # (B, 25, 4, 4) - # 2. Apply the left<->right paired mirror once for the entire sub-batch. + # Apply the left<->right paired mirror once for the entire sub-batch. if pose_mirror is None: left_joint_names = list(left_layer.rig_data["joint_names"]) right_joint_names = list(right_layer.rig_data["joint_names"]) @@ -222,8 +337,8 @@ def mirror_left_prediction_to_right( :, 1 + num_joints : ] # (B, 25, 4, 4) - # 3. Decompose mirrored cam-space transforms back into local rotations - # + wrist translation. + # Decompose mirrored cam-space transforms back into local rotations + wrist + # translation. right_local = joint_world_to_local(right_transforms, right_layer.joint_parent_ids) right_transl = right_transforms[ :, 0, :3, 3 @@ -235,8 +350,56 @@ def mirror_left_prediction_to_right( right_poses = remove_joint_orient_local( right_local[:, :, :3, :3], orient, orient_parent_T ) + return right_poses, right_transl + + +def mirror_left_prediction_to_right( + model, + poses, + transl, + identity_coeffs, + global_scale, + K_fullimg, + bbx_xys, + scale_params=None, + pose_mirror=None, +): + """Convert left-canonicalized right-hand predictions back to right hands (batched). + + All inputs share a leading batch dim B over the right-hand samples in the + current EgoHand forward pass. + + Args: + model: Loaded EgoHand model with left and right SOMAHand layers. + poses: (B, 25, 3, 3) left-canonicalized SOMA hand rotations. + transl: (B, 3) left-canonicalized camera translation in meters. + identity_coeffs: (B, K) SOMAHand identity coefficients. + global_scale: (B,) per-sample uniform scale. + K_fullimg: (B, 3, 3) full-image camera intrinsics. + bbx_xys: (B, 3) per-sample bbox as ``[center_x, center_y, size]``. + scale_params: Optional (B, S) per-sample MHR hand scale parameters. + pose_mirror: Optional pre-constructed ``PoseMirror_SOMA`` matching the + paired ``["Root"] + left_joint_names + right_joint_names`` rig. + The predictor caches this once at init so subsequent batches do + not pay the per-call setup. When ``None``, a fresh instance is + built on each call (correct, but slower). + + Returns: + Dict of right-hand predictions matching EgoHand's saved schema, all with + leading batch dim B: ``pred_vertices`` ``(B, V, 3)``, ``transl`` + ``(B, 3)``, ``pred_keypoints_3d`` ``(B, 25, 3)``, ``pred_keypoints_2d`` + ``(B, 25, 2)`` (bbox-relative, normalized by bbox size), ``poses`` + ``(B, 25, 3, 3)``. + """ + right_poses, right_transl = mirror_left_poses_to_right( + model.soma_hand.left, + model.soma_hand.right, + poses, + transl, + pose_mirror=pose_mirror, + ) - # 4. Run the right SOMAHand forward and project. + # Run the right SOMAHand forward and project. right_out = model.soma_hand( poses=right_poses, identity_coeffs=identity_coeffs, diff --git a/src/python/isaaccapture_egopost/inference/scripts/README.md b/src/python/isaaccapture_egopost/inference/scripts/README.md index 4fa59ee4ac..ed50e9fedd 100644 --- a/src/python/isaaccapture_egopost/inference/scripts/README.md +++ b/src/python/isaaccapture_egopost/inference/scripts/README.md @@ -130,12 +130,15 @@ pointed at different roots. | Flag | Default | Description | | ---- | ------- | ----------- | -| `--egohand_ckpt` | resolved via `nvidia/EgoHand-v1` on HF | EgoHand checkpoint (`.ckpt`); downloads the file named by `--egohand_ckpt_hf_path` from [huggingface.co/nvidia/EgoHand-v1](https://huggingface.co/nvidia/EgoHand-v1) and caches locally if not given | +| `--egohand_ckpt` | resolved via `nvidia/EgoHand-v1` on HF | EgoHand checkpoint (`.ckpt`) or an inference-weights export folder written by `inference/scripts/export_inference_weights.py` (`model.safetensors` + `config.json`); downloads `--egohand_ckpt_hf_path` from [huggingface.co/nvidia/EgoHand-v1](https://huggingface.co/nvidia/EgoHand-v1) and caches locally if not given | +| `--background_model_load` / `--no-background_model_load` | on | Load the EgoHand model on a worker thread while frames are decoded and 2D boxes detected; the first forward waits for it. Pass `--no-background_model_load` to load synchronously before detection | | `--egohand_ckpt_hf_path` | `egohand_s060000.ckpt` | Filename within `nvidia/EgoHand-v1` to fetch for `--egohand_ckpt`'s default. Only consulted when `--egohand_ckpt` is not given -- lets you pick a different HF-hosted checkpoint without a local copy or a code change | | `--batch_size` | `32` | Batch size for EgoHand inference. RT-DETR takes its own batch size via the `rtdetr_config.batch_size` key in the detector YAML | | `--dino_compile` | off | Compile each DINOv3 block (`torch.compile`, inductor, fullgraph) for eval/no-grad calls at the exact `--batch_size`; training, grad-enabled calls, and partial/tail batches keep the unmodified eager path automatically. Opt-in speedup for throughput-sensitive batch inference (e.g. long videos) where most batches are full-size -- skip it for small one-off runs, since `torch.compile` warm-up cost can exceed the savings. Compiled output can differ from eager by up to ~1e-2 on final joints/vertices (bf16/inductor numerics); validate once against an eager baseline before relying on it downstream | +| `--soma_batch_size` | `0` | Run the SOMA hand layer once per this many crops instead of once per `--batch_size` batch (padded to this size). Must be `0` or at least `--batch_size` (e.g. `512`). Changes only float32 batched-product reduction order | | `--device` | `cuda` | Torch device | | `--dtype` | `float32` | `float32`, `float16`, or `bfloat16` | +| `--mhr_presorted_sparse` / `--no-mhr_presorted_sparse` | on | Build the MHR pose-corrective sparse matrix once, coalesced, at model load instead of sorting it on every SOMA call (works around NVIDIA/cccl#5297 in CUDA 13.0 builds on sm_90+ GPUs). Pass `--no-mhr_presorted_sparse` to keep the TorchScript forward | ### Postprocessing diff --git a/src/python/isaaccapture_egopost/inference/scripts/export_inference_weights.py b/src/python/isaaccapture_egopost/inference/scripts/export_inference_weights.py new file mode 100644 index 0000000000..068500739a --- /dev/null +++ b/src/python/isaaccapture_egopost/inference/scripts/export_inference_weights.py @@ -0,0 +1,102 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: LicenseRef-OpenMDW-1.1 + +"""Export an EgoHand training checkpoint to inference weights. + +Writes ``/model.safetensors`` (the checkpoint ``state_dict``, +values unchanged) and ``/config.json`` (training cfg, checkpoint +validation fields, provenance). Pass the folder to +``run_egohand_inference_pipeline.py --egohand_ckpt``. + +With ``--verify``, the export is loaded back and compared tensor-by-tensor +against the checkpoint (bitwise), and a model is built from it with the +strict key check used at inference time. + +Usage: + python inference/scripts/export_inference_weights.py \\ + --checkpoint egohand_s060000.ckpt --output_dir weights/egohand_s060000 --verify +""" + +import argparse +import sys +from pathlib import Path + +PROJECT_ROOT = Path(__file__).resolve().parents[2] +if str(PROJECT_ROOT) not in sys.path: + sys.path.insert(0, str(PROJECT_ROOT)) + +from inference.pipeline.inference_weights import ( # noqa: E402 + export_inference_weights, + read_checkpoint, +) + + +def _verify(checkpoint: Path, output_dir: Path, soma_hand_assets: str | None) -> None: + import torch + + reference = read_checkpoint(checkpoint) + exported = read_checkpoint(output_dir) + ref_tensors = reference.load_state_dict() + out_tensors = exported.load_state_dict() + if ref_tensors.keys() != out_tensors.keys(): + raise SystemExit("export keys differ from the checkpoint state_dict") + + # Byte-level comparison (NaN payloads included); reshape(-1) also handles + # 0-d and non-contiguous tensors. + def as_bytes(tensor: torch.Tensor) -> torch.Tensor: + return tensor.contiguous().reshape(-1).view(torch.uint8) + + for key, value in ref_tensors.items(): + other = out_tensors[key] + if value.dtype != other.dtype or value.shape != other.shape: + raise SystemExit(f"{key}: dtype/shape changed") + if not torch.equal(as_bytes(value), as_bytes(other)): + raise SystemExit(f"{key}: values changed") + if exported.cfg != reference.cfg: + raise SystemExit("exported cfg differs from the checkpoint cfg") + if exported.checkpoint_fields != reference.checkpoint_fields: + raise SystemExit("exported checkpoint_fields differ from the checkpoint") + print(f"[export] verified {len(out_tensors)} tensors bitwise and cfg equality") + if soma_hand_assets is not None: + from inference.pipeline.predictor import load_egohand_model + + load_egohand_model(exported, soma_hand_assets) + print("[export] model built from the export with the strict key check") + + +def main() -> None: + parser = argparse.ArgumentParser( + description=(__doc__ or "Export EgoHand inference weights.").split("\n\n")[0] + ) + parser.add_argument("--checkpoint", required=True, help="Training .ckpt") + parser.add_argument("--output_dir", required=True, help="Destination folder") + parser.add_argument( + "--no_sha256", + action="store_true", + help="Skip hashing the source checkpoint for config.json provenance.", + ) + parser.add_argument( + "--verify", + action="store_true", + help="Reload the export and compare it bitwise with the checkpoint.", + ) + parser.add_argument( + "--soma_hand_assets", + default=None, + help="With --verify, also build the model from the export (strict keys).", + ) + args = parser.parse_args() + config = export_inference_weights( + args.checkpoint, args.output_dir, source_sha256=not args.no_sha256 + ) + print( + f"[export] {config['tensors']['count']} tensors " + f"({config['tensors']['numel']:,} values, {config['tensors']['dtypes']}) " + f"-> {args.output_dir}" + ) + if args.verify: + _verify(Path(args.checkpoint), Path(args.output_dir), args.soma_hand_assets) + + +if __name__ == "__main__": + main() diff --git a/src/python/isaaccapture_egopost/inference/scripts/run_egohand_inference_pipeline.py b/src/python/isaaccapture_egopost/inference/scripts/run_egohand_inference_pipeline.py index a95878a941..2b88c688dc 100644 --- a/src/python/isaaccapture_egopost/inference/scripts/run_egohand_inference_pipeline.py +++ b/src/python/isaaccapture_egopost/inference/scripts/run_egohand_inference_pipeline.py @@ -47,6 +47,7 @@ import json import os import sys +from collections.abc import Callable from pathlib import Path import time from typing import NoReturn @@ -526,8 +527,12 @@ def process_video( ] for h in hands } + # render_clip reads these crops only for the per-hand crop overlays. + # Without them (the default, and always with perspective cropping or + # full-image undistortion) cropping every frame again would be wasted. + render_crop_overlays = save_crop_overlays and source_camera is None crops_per_hand = {} - for h in hands: + for h in hands if render_crop_overlays else (): crops, bbxs_viz, Ks_viz = [], [], [] for frame, fid in zip(valid_frames, valid_fids): bbx = bboxes_per_image.get(fid, {}).get(h) @@ -563,7 +568,7 @@ def process_video( display_size=(W, H) if resize_params is not None and source_camera is None else None, - save_crop_overlays=save_crop_overlays and source_camera is None, + save_crop_overlays=render_crop_overlays, ) if perf_reporter is not None and valid_fids: overlay_ms_per_frame = ( @@ -695,11 +700,8 @@ def main(): f"{args.soma_hand_assets}" ) - print( - f"[infer_video] loading EgoHand model + {backend} detector (config: {args.bbox_detector_config}) ..." - ) - t0 = time.perf_counter() - predictor = EgoHandPredictor.from_checkpoint( + # One set of from_checkpoint arguments for both load paths. + load_kwargs = dict( egohand_ckpt_path=args.egohand_ckpt, soma_hand_data_folder=args.soma_hand_assets, batch_size=args.batch_size, @@ -707,15 +709,43 @@ def main(): dtype=dtype, smooth=args.postprocessing_smooth, use_perspective_cropping=use_perspective_cropping, + soma_batch_size=args.soma_batch_size, + mhr_presorted_sparse=args.mhr_presorted_sparse, ) + if args.background_model_load: + print( + f"[infer_video] loading EgoHand model in the background + {backend} detector " + f"(config: {args.bbox_detector_config}) ..." + ) + # The cfg is read here (fail fast); model construction and tensor + # reads overlap decoding and 2D detection. + predictor = EgoHandPredictor.load_in_background( + **load_kwargs, dino_compile=args.dino_compile + ) + model_load_ms = None # known once the worker finishes + else: + print( + f"[infer_video] loading EgoHand model + {backend} detector (config: {args.bbox_detector_config}) ..." + ) + t0 = time.perf_counter() + predictor = EgoHandPredictor.from_checkpoint(**load_kwargs) + if args.dino_compile: + predictor.enable_dino_compile() + model_load_ms = (time.perf_counter() - t0) * 1000 if args.dino_compile: - predictor.enable_dino_compile() print( "[infer_video] DINO per-block compilation enabled: " f"full batch {args.batch_size}; training, gradients, and partial " "batches use eager" ) - model_load_ms = (time.perf_counter() - t0) * 1000 + if args.background_model_load: + # Checkpoint key set (names only) before any frame is decoded, so a + # mismatched checkpoint fails before outputs are written. + key_check_wait_s = predictor.wait_until_validated() + print( + f"[infer_video] checkpoint keys checked ({predictor.validate_seconds:.2f} s " + f"on the loader thread, waited {key_check_wait_s:.2f} s)" + ) pipeline = EgoHandInferencePipeline( predictor=predictor, bbox_detector=bbox_detector @@ -725,7 +755,7 @@ def main(): save_videos = not args.no_save_videos write_soma_npzs = args.save_npzs - camera_mode = getattr(predictor.model, "camera_mode", "weak_perspective") + camera_mode = predictor.camera_mode print(f"[infer_video] checkpoint camera_mode={camera_mode}") if args.postprocessing_smooth: print( @@ -757,12 +787,14 @@ def main(): else "unknown" ), "batch_size": args.batch_size, + "soma_batch_size": args.soma_batch_size, "dtype": args.dtype, "dino_compile": args.dino_compile, "perspective_cropping": use_perspective_cropping, }, ) - perf_reporter.record_latency(PerfStage.MODEL_LOAD, model_load_ms) + if model_load_ms is not None: + perf_reporter.record_latency(PerfStage.MODEL_LOAD, model_load_ms) pipeline.perf_reporter = perf_reporter predictor.perf_reporter = perf_reporter @@ -876,6 +908,15 @@ def main(): source_camera=source_camera if undistort_maps is not None else None, ) + if model_load_ms is None and predictor.load_seconds is not None: + # Background load: report the worker's own duration once known, + # and how long the main thread actually waited for it. + model_load_ms = predictor.load_seconds * 1000 + perf_reporter.record_latency(PerfStage.MODEL_LOAD, model_load_ms) + print( + f"[infer_video] background model load: {predictor.load_seconds:.2f} s " + f"on the loader thread; main thread waited {predictor.wait_seconds:.2f} s" + ) if not args.perf_output or video_path == videos[-1]: out = perf_reporter.write() print(f"[infer_video] perf results written to {out}") @@ -883,5 +924,50 @@ def main(): print(f"\n[infer_video] all done. results in {output_dir}") +#: How long a failing run waits for a background model load before it exits anyway. +BACKGROUND_LOAD_EXIT_WAIT_S = 300.0 + + +def run_main( + main_fn: Callable[[], None] | None = None, wait_s: float | None = None +) -> None: + """Run ``main()`` and join active background model loads before error teardown.""" + import traceback + + from inference.pipeline.predictor import wait_for_background_loads + + try: + (main_fn or main)() + except BaseException as exc: + timeout = ( + min(5.0, BACKGROUND_LOAD_EXIT_WAIT_S) + if isinstance(exc, KeyboardInterrupt) and wait_s is None + else (BACKGROUND_LOAD_EXIT_WAIT_S if wait_s is None else wait_s) + ) + try: + finished = wait_for_background_loads(timeout) + except KeyboardInterrupt: + finished = False + if finished: + raise + if isinstance(exc, KeyboardInterrupt): + status = 130 + elif isinstance(exc, SystemExit): + code = exc.code + if isinstance(code, str): + print(code, file=sys.stderr) + status = code if isinstance(code, int) else (0 if code is None else 1) + else: + traceback.print_exc() + status = 1 + print( + "[infer_video] the background model load did not finish; exiting without waiting for it", + file=sys.stderr, + ) + sys.stdout.flush() + sys.stderr.flush() + os._exit(status) + + if __name__ == "__main__": - main() + run_main() diff --git a/src/python/isaaccapture_egopost/inference/tests/camera/__init__.py b/src/python/isaaccapture_egopost/inference/tests/camera/__init__.py new file mode 100644 index 0000000000..60bf73b663 --- /dev/null +++ b/src/python/isaaccapture_egopost/inference/tests/camera/__init__.py @@ -0,0 +1,2 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: LicenseRef-OpenMDW-1.1 diff --git a/src/python/isaaccapture_egopost/inference/tests/camera/test_fisheye_crop_cuda.py b/src/python/isaaccapture_egopost/inference/tests/camera/test_fisheye_crop_cuda.py new file mode 100644 index 0000000000..cb8b8847db --- /dev/null +++ b/src/python/isaaccapture_egopost/inference/tests/camera/test_fisheye_crop_cuda.py @@ -0,0 +1,879 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: LicenseRef-OpenMDW-1.1 + +"""CPU unit tests for fisheye_crop_cuda and PyAV chunked/seekable video streaming.""" + +from __future__ import annotations + +import shutil +import subprocess +import threading +from pathlib import Path + +import cv2 +import numpy as np +import pytest +import torch + +from inference.camera.camera_models import ( + create_perspective_remap, + load_camera_calibration, +) +from inference.camera.fisheye_crop_cuda import ( + compute_perspective_crop_params_batch, + crop_chunk_gpu, + fisheye_unproject_torch, + supports_gpu_perspective_crop, +) +from inference.camera.perspective_crop import perspective_crop +from inference.media import _pyav_video as pyav_video +from inference.media._pyav_video import SeekablePyAVFrames, iter_video_chunks_pyav +from inference.preprocessing.mirroring import mirror_full_image_camera_horizontal + +# Real Lightwheel 1920x1456 FISHEYE624 calibration. +_LIGHTWHEEL_FISHEYE624 = { + "model": "FISHEYE624", + "image_width": 1920, + "image_height": 1456, + "camera_matrix": { + "matrix_3x3": [ + [876.255626, 0.0, 955.504124], + [0.0, 876.178673, 734.065202], + [0.0, 0.0, 1.0], + ] + }, + "distortion_coefficients": [ + -0.137012, + 0.403846, + -1.163556, + 1.355783, + -0.715754, + 0.142895, + -0.000799, + 0.000398, + 0.0, + 0.0, + 0.0, + 0.0, + ], +} + +# FISHEYE624 with non-zero thin-prism coefficients s0..s3 as well as p0, p1. +_PRISM_FISHEYE624 = { + "model": "FISHEYE624", + "image_width": 1920, + "image_height": 1456, + "camera_matrix": { + "matrix_3x3": [ + [876.255626, 0.0, 955.504124], + [0.0, 876.178673, 734.065202], + [0.0, 0.0, 1.0], + ] + }, + "distortion_coefficients": [ + -0.137012, + 0.403846, + -1.163556, + 1.355783, + -0.715754, + 0.142895, + -0.000799, + 0.000398, + 0.00042, + -0.00018, + -0.00031, + 0.00015, + ], +} + +_KB4_CAMERA = { + "model": "KB4", + "image_width": 1920, + "image_height": 1456, + "camera_matrix": { + "matrix_3x3": [ + [720.5, 0.0, 960.0], + [0.0, 720.2, 728.0], + [0.0, 0.0, 1.0], + ] + }, + "distortion_coefficients": [-0.041, 0.012, -0.004, 0.0008], +} + +_PINHOLE_1920X1456 = { + "model": "PINHOLE", + "image_width": 1920, + "image_height": 1456, + "camera_matrix": { + "matrix_3x3": [ + [876.255626, 0.0, 955.504124], + [0.0, 876.178673, 734.065202], + [0.0, 0.0, 1.0], + ] + }, + "distortion_coefficients": [], +} + +_RATIONAL_CAMERA = { + "model": "RATIONAL_POLYNOMIAL", + "image_width": 1920, + "image_height": 1456, + "camera_matrix": { + "matrix_3x3": [ + [900.0, 0.0, 960.0], + [0.0, 900.0, 728.0], + [0.0, 0.0, 1.0], + ] + }, + "distortion_coefficients": [ + -0.08, + 0.02, + 0.0002, + -0.0003, + 0.001, + 0.01, + 0.005, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + ], +} + +_LIGHTWHEEL_CLIP = Path("/tmp/lw_nsys_work/clips/lw_08_150f.mp4") + + +def _reference_perspective_crop_uint8( + image_bgr: np.ndarray, + bbox: np.ndarray, + camera, + crop_side_pixels: int, + hand: str, +) -> tuple[np.ndarray, dict]: + """Reference CPU uint8 perspective crop + right-hand flip matching predictor.py.""" + crop_f32, K_virtual, bbox_virtual, crop_to_source_rotation = perspective_crop( + image_bgr, bbox, camera, crop_side_pixels + ) + focal_length = float(K_virtual[0, 0]) + remap_pixels = create_perspective_remap( + camera, crop_to_source_rotation, focal_length, crop_side_pixels + ) + crop_bgr = cv2.remap( + image_bgr, + remap_pixels, + None, + interpolation=cv2.INTER_LINEAR, + borderMode=cv2.BORDER_CONSTANT, + borderValue=0, + ) + crop_rgb_u8 = cv2.cvtColor(crop_bgr, cv2.COLOR_BGR2RGB) + # Sanity check: float32 perspective_crop is exact crop_rgb_u8 / 255.0. + assert np.array_equal(np.round(crop_f32 * 255.0).astype(np.uint8), crop_rgb_u8) + + model_bbx_xys = bbox_virtual + model_K = K_virtual + if hand == "right": + crop_rgb_u8 = np.ascontiguousarray(crop_rgb_u8[:, ::-1]) + model_bbx_xys, model_K = mirror_full_image_camera_horizontal( + model_bbx_xys, model_K, crop_rgb_u8.shape[1] + ) + + record = { + "real_hand_side": hand, + "model_bbx_xys": model_bbx_xys, + "model_K": model_K, + "model_img_size": np.array( + [crop_side_pixels, crop_side_pixels], dtype=np.float32 + ), + "output_bbx_xys": bbox_virtual, + "output_K": K_virtual, + "crop_to_source_camera_rotation": crop_to_source_rotation, + } + return crop_rgb_u8, record + + +# --------------------------------------------------------------------------- +# fisheye_unproject_torch parity tests +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize( + "calib", + [_LIGHTWHEEL_FISHEYE624, _PRISM_FISHEYE624, _KB4_CAMERA], + ids=["lightwheel_fisheye624", "prism_fisheye624", "kb4"], +) +def test_fisheye_unproject_torch_matches_cpu_to_1e_12(calib): + camera = load_camera_calibration(calib) + rng = np.random.default_rng(42) + + xs = np.linspace(-100.0, camera.width + 100.0, 41) + ys = np.linspace(-100.0, camera.height + 100.0, 33) + gx, gy = np.meshgrid(xs, ys) + grid_pixels = np.stack([gx, gy], axis=-1).reshape(-1, 2) + extra_pixels = np.array( + [ + [camera.K[0, 2], camera.K[1, 2]], # exact principal point (r == 0) + [0.0, 0.0], + [camera.width - 1.0, camera.height - 1.0], + [float("nan"), 500.0], + [500.0, float("inf")], + [1.0e5, 1.0e5], # outside lens domain + [-1.0e5, 700.0], + [1.0e100, -1.0e100], # extreme overflow coordinates + ], + dtype=np.float64, + ) + rand_pixels = np.column_stack( + [ + rng.uniform(0.0, camera.width, size=500), + rng.uniform(0.0, camera.height, size=500), + ] + ) + pixels_np = np.concatenate([grid_pixels, extra_pixels, rand_pixels], axis=0) + + ref_rays = camera.unproject(pixels_np) + got_rays = fisheye_unproject_torch(torch.from_numpy(pixels_np), camera).numpy() + + ref_valid = np.isfinite(ref_rays).all(axis=1) + got_valid = np.isfinite(got_rays).all(axis=1) + assert np.array_equal(got_valid, ref_valid) + assert int(ref_valid.sum()) > 1000 + assert int((~ref_valid).sum()) >= 4 + + max_diff = float(np.max(np.abs(got_rays[ref_valid] - ref_rays[ref_valid]))) + assert max_diff < 1e-12, f"max_diff={max_diff}" + + +def test_fisheye_unproject_torch_shapes_and_empty(): + camera = load_camera_calibration(_LIGHTWHEEL_FISHEYE624) + empty = torch.empty((0, 2), dtype=torch.float64) + out_empty = fisheye_unproject_torch(empty, camera) + assert out_empty.shape == (0, 3) + assert out_empty.dtype == torch.float64 + + shaped = torch.tensor( + [[[955.5, 734.0], [400.0, 500.0]], [[1500.0, 900.0], [100.0, 1200.0]]], + dtype=torch.float32, + ) + ref = camera.unproject(shaped.numpy()) + got = fisheye_unproject_torch(shaped, camera).numpy() + assert got.shape == (2, 2, 3) + assert float(np.max(np.abs(got - ref))) < 1e-12 + + +# --------------------------------------------------------------------------- +# crop_chunk_gpu bit-exactness and metadata parity tests +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize("use_warp", [False, True], ids=["pytorch_cpu", "warp_cpu"]) +@pytest.mark.parametrize( + "calib", + [_LIGHTWHEEL_FISHEYE624, _PRISM_FISHEYE624, _KB4_CAMERA, _PINHOLE_1920X1456], + ids=["fisheye624", "prism_fisheye624", "kb4", "pinhole"], +) +def test_crop_chunk_gpu_bit_exact_vs_cpu_reference(calib, use_warp): + camera = load_camera_calibration(calib) + rng = np.random.default_rng(12345) + # Two synthetic 1920x1456 uint8 BGR frames + one unreferenced frame. + frames_bgr = [ + rng.integers(0, 256, size=(1456, 1920, 3), dtype=np.uint8) for _ in range(3) + ] + + crop_jobs = [ + # Frame 0: both left and right hands (tests unique frame upload + fused flip). + (0, "frame0000", "left", np.array([620.5, 810.25, 340.0], dtype=np.float32)), + (0, "frame0000", "right", np.array([1290.75, 780.5, 310.0], dtype=np.float32)), + # Frame 0: top-border-straddling ROI (exercises out-of-bounds black border & edge blend). + ( + 0, + "frame0000_top_edge", + "right", + np.array([960.0, 35.0, 220.0], dtype=np.float32), + ), + # Frame 0: corner border-straddling ROI (valid on FISHEYE624/PINHOLE, outside KB4 domain). + ( + 0, + "frame0000_corner_edge", + "right", + np.array([45.0, 50.0, 220.0], dtype=np.float32), + ), + # Invalid ROI: NaN center. + ( + 0, + "frame0000_nan", + "left", + np.array([float("nan"), 700.0, 300.0], dtype=np.float32), + ), + # Invalid ROI: behind-camera on PINHOLE / out-of-domain on FISHEYE624 & KB4. + ( + 1, + "frame0001_bad", + "right", + np.array([1.0e5, 734.0, 2.0e5], dtype=np.float32), + ), + # Frame 1: near-corner valid ROI (strong fisheye distortion). + (1, "frame0001", "left", np.array([260.0, 1220.0, 280.0], dtype=np.float32)), + (1, "frame0001", "right", np.array([1680.0, 260.0, 290.0], dtype=np.float32)), + ] + + # Compute CPU reference per job so success/failure masks are verified identically. + expected_valid: list[tuple[str, np.ndarray, dict]] = [] + expected_failed = 0 + for f_idx, img_id, hand, bbox in crop_jobs: + try: + crop_ref, rec_ref = _reference_perspective_crop_uint8( + frames_bgr[f_idx], bbox, camera, 256, hand + ) + except (FloatingPointError, ValueError): + expected_failed += 1 + else: + expected_valid.append((img_id, crop_ref, rec_ref)) + + assert expected_failed >= 2 + assert len(expected_valid) >= 5 + + records, crops_u8, num_failed = crop_chunk_gpu( + frames_bgr, + crop_jobs, + camera, + 256, + camera_mode="sam3db_perspective", + device="cpu", + use_warp=use_warp, + ) + + assert num_failed == expected_failed + assert len(records) == len(crops_u8) == len(expected_valid) + + for rec, crop_got, (img_id, crop_ref, rec_ref) in zip( + records, crops_u8, expected_valid + ): + assert crop_got.dtype == np.uint8 + assert crop_got.shape == (256, 256, 3) + max_u8_diff = int( + np.max(np.abs(crop_got.astype(np.int32) - crop_ref.astype(np.int32))) + ) + assert max_u8_diff == 0, ( + f"Non-zero pixel diff {max_u8_diff} for {calib['model']} {img_id} {rec['real_hand_side']}" + ) + + assert rec["image_id"] == img_id + assert rec["real_hand_side"] == rec_ref["real_hand_side"] + for key in ( + "model_bbx_xys", + "model_K", + "model_img_size", + "output_bbx_xys", + "output_K", + "crop_to_source_camera_rotation", + ): + assert rec[key].dtype == rec_ref[key].dtype, ( + key, + rec[key].dtype, + rec_ref[key].dtype, + ) + assert rec[key].shape == rec_ref[key].shape + if rec[key].dtype == np.float32: + np.testing.assert_allclose(rec[key], rec_ref[key], rtol=1e-6, atol=1e-6) + else: + np.testing.assert_allclose( + rec[key], rec_ref[key], rtol=1e-12, atol=1e-12 + ) + + +def test_crop_chunk_gpu_reuses_preuploaded_images_and_returns_tensor(): + camera = load_camera_calibration(_LIGHTWHEEL_FISHEYE624) + rng = np.random.default_rng(7) + frames_np = rng.integers(0, 256, size=(2, 1456, 1920, 3), dtype=np.uint8) + frames_t = torch.from_numpy(frames_np) + jobs = [ + { + "frame_idx": 1, + "image_id": "f1", + "hand": "right", + "bbox": np.array([1100.0, 700.0, 260.0], np.float32), + }, + { + "frame_idx": 0, + "image_id": "f0", + "hand": "left", + "bbox": np.array([700.0, 680.0, 280.0], np.float32), + }, + ] + + records_list, crops_list, failed_list = crop_chunk_gpu( + [frames_np[0], frames_np[1]], + jobs, + camera, + 256, + camera_mode="sam3db_perspective", + device="cpu", + ) + records_gpu, crops_tensor, failed_gpu = crop_chunk_gpu( + None, + jobs, + camera, + 256, + camera_mode="sam3db_perspective", + device="cpu", + images_bgr_gpu=frames_t, + return_gpu_crops=True, + ) + + assert failed_list == failed_gpu == 0 + assert isinstance(crops_tensor, torch.Tensor) + assert crops_tensor.dtype == torch.uint8 + assert crops_tensor.shape == (2, 256, 256, 3) + for i in range(2): + assert np.array_equal(crops_tensor[i].numpy(), crops_list[i]) + assert records_gpu[i]["image_id"] == records_list[i]["image_id"] + + with pytest.raises(IndexError, match="out of bounds"): + crop_chunk_gpu( + None, + [(5, "bad", "left", np.array([700.0, 680.0, 280.0], np.float32))], + camera, + 256, + camera_mode="sam3db_perspective", + device="cpu", + images_bgr_gpu=frames_t, + ) + + +def test_crop_chunk_gpu_all_failed_and_empty_and_rational_fallback(): + pinhole = load_camera_calibration(_PINHOLE_1920X1456) + frame = np.zeros((1456, 1920, 3), dtype=np.uint8) + + records, crops, failed = crop_chunk_gpu( + [frame], [], pinhole, 256, camera_mode="sam3db_perspective", device="cpu" + ) + assert records == [] and crops == [] and failed == 0 + + bad_jobs = [ + (0, "f0", "left", np.array([1.0e5, 734.0, 2.0e5], dtype=np.float32)), + (0, "f0", "right", np.array([float("nan"), 734.0, 200.0], dtype=np.float32)), + ] + records, crops, failed = crop_chunk_gpu( + [frame], bad_jobs, pinhole, 256, camera_mode="sam3db_perspective", device="cpu" + ) + assert records == [] and crops == [] and failed == 2 + + # RATIONAL_POLYNOMIAL exercises CPU unproject + OpenCV fallback cleanly. + rational = load_camera_calibration(_RATIONAL_CAMERA) + rng = np.random.default_rng(99) + tex = rng.integers(0, 256, size=(1456, 1920, 3), dtype=np.uint8) + bbox = np.array([920.0, 710.0, 260.0], dtype=np.float32) + records, crops, failed = crop_chunk_gpu( + [tex], + [(0, "rat0", "right", bbox)], + rational, + 128, + camera_mode="sam3db_perspective", + device="cpu", + ) + assert failed == 0 and len(records) == 1 + ref_crop, _ = _reference_perspective_crop_uint8(tex, bbox, rational, 128, "right") + assert np.array_equal(crops[0], ref_crop) + + +def test_compute_perspective_crop_params_batch_behind_camera_fisheye_and_pinhole(): + pinhole = load_camera_calibration(_PINHOLE_1920X1456) + params, valid_idx, rots, focals, flips = compute_perspective_crop_params_batch( + np.array( + [ + [955.5, 734.0, 300.0], # valid + [1.0e5, 734.0, 2.0e5], # behind virtual pinhole camera (z <= 0) + [float("nan"), 734.0, 300.0], # non-finite center ray + [955.5, 734.0, float("nan")], # empty valid perimeter + [955.504124, 734.065202, 0.0], # degenerate zero extent (focal = inf) + ], + dtype=np.float64, + ), + ["left", "right", "left", "right", "left"], + pinhole, + 256, + "cpu", + ) + assert len(params) == 5 + assert params[0] is not None + assert all(p is None for p in params[1:]) + assert list(valid_idx) == [0] + assert rots.shape == (1, 3, 3) and focals.shape == (1,) and list(flips) == [0] + + # Also test FISHEYE624 failure modes: valid, empty valid perimeter, behind camera, NaN center. + fisheye = load_camera_calibration(_LIGHTWHEEL_FISHEYE624) + fe_params, fe_valid_idx, _, _, _ = compute_perspective_crop_params_batch( + np.array( + [ + [955.5, 734.0, 300.0], # valid + [ + 955.5, + 734.0, + 1.0e6, + ], # valid center, perimeter entirely outside lens domain + [ + 150.0, + 734.0, + 3400.0, + ], # wide ROI whose far perimeter reaches behind virtual camera + [float("nan"), 734.0, 300.0], # non-finite center ray + ], + dtype=np.float64, + ), + ["left", "right", "left", "right"], + fisheye, + 256, + "cpu", + ) + assert fe_params[0] is not None + assert fe_params[1] is None and fe_params[2] is None and fe_params[3] is None + assert list(fe_valid_idx) == [0] + + +# --------------------------------------------------------------------------- +# PyAV chunked streamer and SeekablePyAVFrames tests +# --------------------------------------------------------------------------- + + +def _read_all_opencv(video_path: str | Path) -> list[np.ndarray]: + cap = cv2.VideoCapture(str(video_path)) + frames = [] + try: + while True: + ok, frame = cap.read() + if not ok: + break + frames.append(frame) + finally: + cap.release() + return frames + + +def _make_synthetic_h264_mp4( + path: Path, + *, + width: int = 128, + height: int = 96, + rate: int = 15, + duration: int = 3, + gop: int = 10, + bframes: int = 2, +) -> Path: + subprocess.run( # noqa: S603 + [ + "ffmpeg", + "-v", + "error", + "-y", + "-f", + "lavfi", + "-i", + f"testsrc2=size={width}x{height}:rate={rate}:duration={duration}", + "-c:v", + "libx264", + "-g", + str(gop), + "-bf", + str(bframes), + "-pix_fmt", + "yuv420p", + str(path), + ], + check=True, + ) + return path + + +def test_iter_video_chunks_pyav_and_seekable_match_opencv_bit_exact(tmp_path): + if _LIGHTWHEEL_CLIP.is_file(): + video_path = _LIGHTWHEEL_CLIP + else: + if shutil.which("ffmpeg") is None: + pytest.skip("Neither sample Lightwheel clip nor ffmpeg is available") + video_path = _make_synthetic_h264_mp4(tmp_path / "synthetic_lw.mp4") + + cv_frames = _read_all_opencv(video_path) + assert len(cv_frames) > 0 + + av_frames: list[np.ndarray] = [] + all_pts: list[int] = [] + all_kf_pts: list[int] = [] + chunk_sizes: list[int] = [] + + for frames_chunk, pts_chunk, kf_chunk in iter_video_chunks_pyav( + str(video_path), chunk_size=32, threads=8 + ): + assert len(frames_chunk) == len(pts_chunk) == len(kf_chunk) + assert 0 < len(frames_chunk) <= 32 + chunk_sizes.append(len(frames_chunk)) + av_frames.extend(frames_chunk) + all_pts.extend(pts_chunk) + all_kf_pts.extend(kf_chunk) + + assert len(av_frames) == len(cv_frames) + assert sum(chunk_sizes) == len(cv_frames) + for idx, (got, ref) in enumerate(zip(av_frames, cv_frames)): + assert got.shape == ref.shape and got.dtype == ref.dtype + assert np.array_equal(got, ref), f"Sequential frame {idx} differs from OpenCV" + + # Verify SeekablePyAVFrames random access, negative indexing, slicing & bounded LRU. + n = len(cv_frames) + cache_size = 8 + with SeekablePyAVFrames( + str(video_path), + np.asarray(all_pts, dtype=np.int64), + np.asarray(all_kf_pts, dtype=np.int64), + cache_size=cache_size, + ) as seekable: + assert len(seekable) == n + rng = np.random.default_rng(2026) + # Mix consecutive forward, backward jumps, endpoints, and random indices. + indices = [0, 1, 2, n - 1, n - 2, n // 2, n // 2 + 1, 0, -1] + [ + int(i) for i in rng.integers(0, n, size=20) + ] + for idx in indices: + got = seekable[idx] + ref = cv_frames[idx] + assert np.array_equal(got, ref), f"Seekable frame {idx} differs from OpenCV" + assert len(seekable._cache) <= cache_size + + # Slice indexing. + sliced = seekable[3:6] + assert len(sliced) == 3 + for off, got in enumerate(sliced): + assert np.array_equal(got, cv_frames[3 + off]) + + with pytest.raises(RuntimeError, match="closed"): + _ = seekable[0] + + +@pytest.mark.skipif(shutil.which("ffmpeg") is None, reason="ffmpeg is not installed") +def test_pyav_multi_gop_bframes_and_early_exit(tmp_path): + video_path = _make_synthetic_h264_mp4( + tmp_path / "bframes_multi_gop.mp4", + width=96, + height=64, + rate=10, + duration=4, + gop=10, + bframes=2, + ) + cv_frames = _read_all_opencv(video_path) + assert len(cv_frames) == 40 + + all_pts: list[int] = [] + all_kf: list[int] = [] + av_frames: list[np.ndarray] = [] + for frames, pts, kfs in iter_video_chunks_pyav( + str(video_path), chunk_size=12, threads=4 + ): + av_frames.extend(frames) + all_pts.extend(pts) + all_kf.extend(kfs) + + assert len(set(all_kf)) >= 3 # Multiple GOP keyframes recorded. + assert len(av_frames) == len(cv_frames) + for idx in range(len(cv_frames)): + assert np.array_equal(av_frames[idx], cv_frames[idx]) + + # Every frame in reverse order across GOPs must match OpenCV bit-identically. + with SeekablePyAVFrames(str(video_path), all_pts, all_kf, cache_size=4) as seekable: + for idx in reversed(range(len(cv_frames))): + assert np.array_equal(seekable[idx], cv_frames[idx]) + assert len(seekable._cache) <= 4 + + # Early exit stops prefetch worker thread cleanly without hanging. + before_threads = {t.ident for t in threading.enumerate()} + gen = iter_video_chunks_pyav(str(video_path), chunk_size=4, threads=4) + first_chunk, _, _ = next(gen) + assert len(first_chunk) == 4 + gen.close() + after_names = [ + t.name for t in threading.enumerate() if t.ident not in before_threads + ] + assert "egohand-pyav-prefetch" not in after_names + + +@pytest.mark.skipif(shutil.which("ffmpeg") is None, reason="ffmpeg is not installed") +@pytest.mark.parametrize("rotation", [90, 180, 270]) +def test_pyav_rotated_video_falls_back_and_matches_opencv( + tmp_path, monkeypatch, rotation +): + base = _make_synthetic_h264_mp4( + tmp_path / "base.mp4", width=64, height=32, rate=5, duration=1, gop=5, bframes=0 + ) + rot_path = tmp_path / f"rot_{rotation}.mp4" + subprocess.run( # noqa: S603 + [ + "ffmpeg", + "-v", + "error", + "-y", + "-display_rotation", + str(rotation), + "-i", + str(base), + "-c", + "copy", + str(rot_path), + ], + check=True, + ) + cv_frames = _read_all_opencv(rot_path) + + fallback_called = False + orig_read_batched = pyav_video.video_io.read_video_frames_batched + + def spy_read_batched(*args, **kwargs): + nonlocal fallback_called + fallback_called = True + yield from orig_read_batched(*args, **kwargs) + + monkeypatch.setattr( + pyav_video.video_io, "read_video_frames_batched", spy_read_batched + ) + + av_frames: list[np.ndarray] = [] + all_pts: list[int] = [] + all_kf: list[int] = [] + for frames, pts, kfs in iter_video_chunks_pyav( + str(rot_path), chunk_size=3, threads=2 + ): + av_frames.extend(frames) + all_pts.extend(pts) + all_kf.extend(kfs) + + assert fallback_called is True + assert len(av_frames) == len(cv_frames) + for got, ref in zip(av_frames, cv_frames): + assert np.array_equal(got, ref) + + with SeekablePyAVFrames(str(rot_path), all_pts, all_kf, cache_size=2) as seekable: + for idx in (len(cv_frames) - 1, 0, 2): + assert np.array_equal(seekable[idx], cv_frames[idx]) + assert seekable._mode == "opencv" + + +def test_iter_video_chunks_pyav_release_profile_uses_video_io(monkeypatch): + monkeypatch.setenv("EGOHAND_RUNTIME_PROFILE", "release") + dummy_frame = np.full((16, 16, 3), 7, dtype=np.uint8) + called_with = [] + + def fake_read_batched(path, batch_size, max_frames=None): + called_with.append((path, batch_size, max_frames)) + yield [(0, dummy_frame), (1, dummy_frame)] + + def fail_av_open(*args, **kwargs): + raise AssertionError("PyAV must not be opened in release profile") + + monkeypatch.setattr( + pyav_video.video_io, "read_video_frames_batched", fake_read_batched + ) + if pyav_video.av is not None: + monkeypatch.setattr(pyav_video.av, "open", fail_av_open) + + chunks = list(iter_video_chunks_pyav("fake.mp4", chunk_size=8, threads=4)) + assert called_with == [("fake.mp4", 8, None)] + assert len(chunks) == 1 + frames, pts, kfs = chunks[0] + assert len(frames) == 2 and pts == [0, 1] and kfs == [0, 0] + assert np.array_equal(frames[0], dummy_frame) + + +def test_supports_gpu_perspective_crop_classification(): + assert supports_gpu_perspective_crop( + load_camera_calibration(_LIGHTWHEEL_FISHEYE624) + ) + assert supports_gpu_perspective_crop(load_camera_calibration(_KB4_CAMERA)) + assert supports_gpu_perspective_crop(load_camera_calibration(_PINHOLE_1920X1456)) + assert not supports_gpu_perspective_crop(load_camera_calibration(_RATIONAL_CAMERA)) + assert not supports_gpu_perspective_crop(np.eye(3, dtype=np.float32)) + assert not supports_gpu_perspective_crop(None) + + +def test_gpu_perspective_crop_batches_matches_cpu_predictor_path(): + """Chunked _GpuPerspectiveCropBatches yields bit-exact batches vs CPU path.""" + from inference.pipeline.predictor import _GpuPerspectiveCropBatches + from inference.preprocessing.crop import IMAGENET_MEAN, IMAGENET_STD, IMG_SIZE + + camera = load_camera_calibration(_LIGHTWHEEL_FISHEYE624) + rng = np.random.default_rng(123) + frames = [rng.integers(0, 256, (1456, 1920, 3), dtype=np.uint8) for _ in range(5)] + image_ids = [f"{i:06d}" for i in range(5)] + jobs = [] + for i, img_id in enumerate(image_ids): + jobs.append( + (i, img_id, "left", np.array([750.0 + 10 * i, 700.0, 260.0], np.float32)) + ) + if i == 2: + # Invalid ROI (NaN) must be skipped without shifting valid batch order. + jobs.append( + (i, img_id, "right", np.array([float("nan"), 700.0, 260.0], np.float32)) + ) + else: + jobs.append( + ( + i, + img_id, + "right", + np.array([1150.0 - 8 * i, 720.0, 240.0], np.float32), + ) + ) + + prepared_map: dict[str, dict[str, dict]] = {} + batches = _GpuPerspectiveCropBatches( + dict(enumerate(frames)), + jobs, + camera, + batch_size=3, + device="cpu", + camera_mode="sam3db_perspective", + on_prepared=lambda img_id, hand, rec: prepared_map.setdefault( + img_id, {} + ).__setitem__(hand, rec), + chunk_frames=2, + ) + + got_tensors = [] + got_records = [] + batch_sizes = [] + for staged in batches: + imgs = staged.images("cpu") + batch_sizes.append(len(staged.hand_data)) + for k, rec in enumerate(staged.hand_data): + got_tensors.append(imgs[k].numpy()) + got_records.append(rec) + staged.release() + + # 10 jobs - 1 NaN = 9 valid crops -> 3 batches of 3 across chunk_frames=2. + assert batch_sizes == [3, 3, 3] + assert "right" not in prepared_map["000002"] + + ref_idx = 0 + for f_idx, _img_id, hand, bbox in jobs: + if not np.isfinite(bbox).all(): + continue + crop_rgb, K_v, bbx_v, rot = perspective_crop( + frames[f_idx], bbox, camera, IMG_SIZE + ) + model_bbx, model_K = bbx_v, K_v + if hand == "right": + crop_rgb = np.ascontiguousarray(crop_rgb[:, ::-1]) + model_bbx, model_K = mirror_full_image_camera_horizontal( + model_bbx, model_K, crop_rgb.shape[1] + ) + ref_t = ((crop_rgb - IMAGENET_MEAN) / IMAGENET_STD).transpose(2, 0, 1) + np.testing.assert_allclose(got_tensors[ref_idx], ref_t, atol=1e-6, rtol=0.0) + np.testing.assert_allclose(got_records[ref_idx]["model_K"], model_K, atol=1e-5) + np.testing.assert_allclose( + got_records[ref_idx]["model_bbx_xys"], model_bbx, atol=1e-5 + ) + np.testing.assert_allclose( + got_records[ref_idx]["crop_to_source_camera_rotation"], rot, atol=1e-6 + ) + ref_idx += 1 + assert ref_idx == len(got_records) diff --git a/src/python/isaaccapture_egopost/inference/tests/hand_detector_2d/__init__.py b/src/python/isaaccapture_egopost/inference/tests/hand_detector_2d/__init__.py new file mode 100644 index 0000000000..60bf73b663 --- /dev/null +++ b/src/python/isaaccapture_egopost/inference/tests/hand_detector_2d/__init__.py @@ -0,0 +1,2 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: LicenseRef-OpenMDW-1.1 diff --git a/src/python/isaaccapture_egopost/inference/tests/hand_detector_2d/test_pillow_exact_cuda.py b/src/python/isaaccapture_egopost/inference/tests/hand_detector_2d/test_pillow_exact_cuda.py new file mode 100644 index 0000000000..458e39b38f --- /dev/null +++ b/src/python/isaaccapture_egopost/inference/tests/hand_detector_2d/test_pillow_exact_cuda.py @@ -0,0 +1,623 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: LicenseRef-OpenMDW-1.1 + +"""Unit tests for Pillow-exact RT-DETR CUDA preprocessing, pipeline, and crop_uint8.""" + +from __future__ import annotations + +import builtins +import importlib +import sys +import threading +import time +from dataclasses import dataclass +from pathlib import Path + +import numpy as np +import PIL +import pytest +import torch +from PIL import Image + +from inference.hand_detector_2d.rtdetr import onnx_model as onnx_model_module +from inference.hand_detector_2d.rtdetr.detector import RTDetrHandBBoxDetector +from inference.hand_detector_2d.rtdetr.onnx_model import HandDetector +from inference.hand_detector_2d.rtdetr.pillow_exact_cuda import ( + INPUT_SIZE, + PillowExactCudaPreprocessor, + _pillow_uses_vertical_first, + pillow_bilinear_coefficients, + pillow_exact_preprocess_eager, + pillow_exact_preprocess_eager_hv, + pillow_exact_preprocess_eager_vh, +) + + +def _tables(height: int, width: int, device) -> tuple[torch.Tensor, ...]: + horizontal_bounds, horizontal_coefficients = pillow_bilinear_coefficients(width) + vertical_bounds, vertical_coefficients = pillow_bilinear_coefficients(height) + normalized_lut = np.arange(256, dtype=np.float32) / 255.0 + return tuple( + torch.from_numpy(array).to(device) + for array in ( + horizontal_bounds, + horizontal_coefficients, + vertical_bounds, + vertical_coefficients, + normalized_lut, + ) + ) + + +def _pillow_reference(raw_bgr: np.ndarray) -> np.ndarray: + outputs = [] + for image_bgr in raw_bgr: + image_rgb = np.ascontiguousarray(image_bgr[..., ::-1]) + resized = Image.fromarray(image_rgb).resize( + (INPUT_SIZE, INPUT_SIZE), + Image.Resampling.BILINEAR, + ) + outputs.append(np.asarray(resized, dtype=np.float32).transpose(2, 0, 1) / 255.0) + return np.stack(outputs) + + +# --------------------------------------------------------------------------- +# Pillow-exact CPU eager math & Pillow 13.0.0 V->H pass-order fix +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize( + "height,width", + [ + (1456, 1920), # landscape H->V in PIL 13.0.0 + (1920, 1080), # portrait V->H in PIL 13.0.0 + (641, 639), # near-640 portrait V->H in PIL 13.0.0 + (639, 641), # near-640 landscape H->V in PIL 13.0.0 + (700, 669), # V->H boundary (2*669 = 1338 < 700+640 = 1340) + (700, 670), # H->V boundary (2*670 = 1340 == 700+640) + (640, 640), # identity + (640, 1000), # height == INPUT_SIZE + (1000, 640), # width == INPUT_SIZE + (17, 23), # small upscaling + (240, 320), # upscaling + ], +) +def test_eager_fixed_point_matches_installed_pillow_on_cpu(height, width): + rng = np.random.default_rng(height * 10000 + width) + raw = rng.integers(0, 256, (1, height, width, 3), dtype=np.uint8) + actual = pillow_exact_preprocess_eager( + torch.from_numpy(raw), + *_tables(height, width, "cpu"), + ).numpy() + expected = _pillow_reference(raw) + + assert np.array_equal(actual, expected) + assert float(np.max(np.abs(actual - expected))) == 0.0 + + +def test_pillow_pass_order_predicate_for_pillow_13_and_12(monkeypatch): + monkeypatch.setattr(PIL, "__version__", "13.0.0") + assert _pillow_uses_vertical_first(1456, 1920) is False + assert _pillow_uses_vertical_first(1080, 1920) is False + assert _pillow_uses_vertical_first(639, 641) is False + assert _pillow_uses_vertical_first(700, 670) is False + assert _pillow_uses_vertical_first(640, 640) is False + assert _pillow_uses_vertical_first(1000, 640) is False + assert _pillow_uses_vertical_first(640, 1000) is False + + assert _pillow_uses_vertical_first(1920, 1080) is True + assert _pillow_uses_vertical_first(641, 639) is True + assert _pillow_uses_vertical_first(700, 669) is True + + monkeypatch.setattr(PIL, "__version__", "12.1.1") + assert _pillow_uses_vertical_first(1920, 1080) is False + assert _pillow_uses_vertical_first(641, 639) is False + assert _pillow_uses_vertical_first(700, 669) is False + + +def test_branchless_hv_and_vh_match_pillow_13_respectively(): + major = int(PIL.__version__.split(".", 1)[0]) + if major < 13: + pytest.skip(f"Pillow >= 13 required, got {PIL.__version__}") + + rng = np.random.default_rng(1300) + landscape = rng.integers(0, 256, (1, 1456, 1920, 3), dtype=np.uint8) + hv_out = pillow_exact_preprocess_eager_hv( + torch.from_numpy(landscape), *_tables(1456, 1920, "cpu") + ).numpy() + assert np.array_equal(hv_out, _pillow_reference(landscape)) + + for height, width in ((1920, 1080), (641, 639)): + portrait = rng.integers(0, 256, (1, height, width, 3), dtype=np.uint8) + vh_out = pillow_exact_preprocess_eager_vh( + torch.from_numpy(portrait), *_tables(height, width, "cpu") + ).numpy() + assert np.array_equal(vh_out, _pillow_reference(portrait)) + + +@pytest.mark.parametrize( + "fn,height,width", + [ + (pillow_exact_preprocess_eager_hv, 1456, 1920), + (pillow_exact_preprocess_eager_vh, 1920, 1080), + (pillow_exact_preprocess_eager_vh, 641, 639), + ], +) +def test_branchless_hv_and_vh_trace_with_fullgraph_dynamo_on_cpu(fn, height, width): + major = int(PIL.__version__.split(".", 1)[0]) + if major < 13: + pytest.skip(f"Pillow >= 13 required, got {PIL.__version__}") + + compiled = torch.compile(fn, backend="eager", fullgraph=True, dynamic=False) + rng = np.random.default_rng(height * 100 + width) + raw = rng.integers(0, 256, (1, height, width, 3), dtype=np.uint8) + actual = compiled( + torch.from_numpy(raw), + *_tables(height, width, "cpu"), + ).numpy() + assert np.array_equal(actual, _pillow_reference(raw)) + + +@pytest.mark.parametrize("input_size,output_size", [(0, 640), (10, 0), (-1, 5)]) +def test_coefficient_generation_rejects_nonpositive_dimensions(input_size, output_size): + with pytest.raises(ValueError, match="must be positive"): + pillow_bilinear_coefficients(input_size, output_size) + + +def test_preprocessor_rejects_invalid_configured_batch(): + with pytest.raises(ValueError, match="must be positive"): + PillowExactCudaPreprocessor(0) + + +def test_compiled_function_selects_branchless_hv_or_vh_and_respects_release_profile( + monkeypatch, +): + compiled_targets = [] + + def fake_compile(fn, **kwargs): + compiled_targets.append((fn, kwargs)) + return fn + + monkeypatch.setattr(torch, "compile", fake_compile) + monkeypatch.setattr(PIL, "__version__", "13.0.0") + monkeypatch.setenv("EGOHAND_RUNTIME_PROFILE", "full") + + pre_land = PillowExactCudaPreprocessor(full_batch_size=2) + fn_land = pre_land._compiled_function( + torch.zeros(2, 1456, 1920, 3, dtype=torch.uint8) + ) + assert fn_land is pillow_exact_preprocess_eager_hv + + pre_port = PillowExactCudaPreprocessor(full_batch_size=2) + fn_port = pre_port._compiled_function( + torch.zeros(2, 1920, 1080, 3, dtype=torch.uint8) + ) + assert fn_port is pillow_exact_preprocess_eager_vh + + assert compiled_targets == [ + (pillow_exact_preprocess_eager_hv, {"fullgraph": True, "dynamic": False}), + (pillow_exact_preprocess_eager_vh, {"fullgraph": True, "dynamic": False}), + ] + + # Release profile must never invoke torch.compile. + compiled_targets.clear() + monkeypatch.setenv("EGOHAND_RUNTIME_PROFILE", "release") + pre_release = PillowExactCudaPreprocessor(full_batch_size=2) + assert ( + pre_release._compiled_function(torch.zeros(2, 1456, 1920, 3, dtype=torch.uint8)) + is None + ) + assert compiled_targets == [] + + +# --------------------------------------------------------------------------- +# PyTorch-optional fallback & relative-import contract (Dockerfile.detector) +# --------------------------------------------------------------------------- + + +def test_pytorch_optional_fallback_when_torch_is_absent(monkeypatch, tmp_path): + import onnxruntime as ort + + class FakeSession: + def get_providers(self): + return ["CUDAExecutionProvider", "CPUExecutionProvider"] + + weights = tmp_path / "model.onnx" + weights.write_bytes(b"test") + monkeypatch.setattr(ort, "InferenceSession", lambda _path, providers: FakeSession()) + monkeypatch.setattr(onnx_model_module, "_preload_cuda_libs", lambda: None) + + real_import = builtins.__import__ + + def block_torch(name, *args, **kwargs): + if name == "torch" or name.startswith("torch."): + raise ImportError("simulated Dockerfile.detector without torch") + return real_import(name, *args, **kwargs) + + monkeypatch.setattr(builtins, "__import__", block_torch) + detector = HandDetector( + weights, providers=["CUDAExecutionProvider", "CPUExecutionProvider"] + ) + + assert detector.cuda_io_enabled is True + assert detector.cuda_input_enabled is False + assert detector.copy_stream is None + assert detector.inference_stream is None + assert detector._cuda_preprocessor is None + + # CPU preprocessing fallback still works without torch. + pytest.importorskip("cv2") + frame = np.zeros((32, 48, 3), dtype=np.uint8) + batch, sizes = detector.preprocess_bgr_batch([frame]) + assert batch.shape == (1, 3, INPUT_SIZE, INPUT_SIZE) + assert batch.dtype == np.float32 + assert sizes.tolist() == [[48, 32]] + + +def test_cuda_input_disabled_cleanly_when_torch_cuda_unavailable(monkeypatch, tmp_path): + import onnxruntime as ort + + class FakeSession: + def get_providers(self): + return ["CUDAExecutionProvider", "CPUExecutionProvider"] + + weights = tmp_path / "model.onnx" + weights.write_bytes(b"test") + monkeypatch.setattr(ort, "InferenceSession", lambda _path, providers: FakeSession()) + monkeypatch.setattr(onnx_model_module, "_preload_cuda_libs", lambda: None) + monkeypatch.setattr(torch.cuda, "is_available", lambda: False) + + detector = HandDetector( + weights, providers=["CUDAExecutionProvider", "CPUExecutionProvider"] + ) + + assert detector.cuda_io_enabled is True + assert detector.cuda_input_enabled is False + assert detector.copy_stream is None + assert detector.inference_stream is None + assert detector._cuda_preprocessor is None + + +def test_cpu_ort_session_keeps_legacy_input_path(monkeypatch, tmp_path): + import onnxruntime as ort + + captured = {} + + class FakeSession: + def get_providers(self): + return ["CPUExecutionProvider"] + + def create_session(path, *, providers): + captured.update(path=path, providers=providers) + return FakeSession() + + weights = tmp_path / "model.onnx" + weights.write_bytes(b"test") + monkeypatch.setattr(ort, "InferenceSession", create_session) + detector = HandDetector(weights, providers=["CPUExecutionProvider"]) + + assert captured["providers"] == ["CPUExecutionProvider"] + assert detector.cuda_io_enabled is False + assert detector.cuda_input_enabled is False + assert detector.copy_stream is None + assert detector.inference_stream is None + with pytest.raises(RuntimeError, match="CUDA input pipeline"): + detector.prepare_cuda_tensor(torch.zeros(1, 8, 8, 3, dtype=torch.uint8)) + + +def test_rtdetr_modules_use_relative_imports_for_standalone_script(monkeypatch): + """Standalone run_hand_detector.py imports rtdetr with __package__='rtdetr'.""" + hand_detector_dir = Path(onnx_model_module.__file__).resolve().parent.parent + monkeypatch.syspath_prepend(str(hand_detector_dir)) + for name in list(sys.modules): + if name == "rtdetr" or name.startswith("rtdetr."): + monkeypatch.delitem(sys.modules, name) + + standalone_onnx = importlib.import_module("rtdetr.onnx_model") + standalone_exact = importlib.import_module("rtdetr.pillow_exact_cuda") + standalone_detector = importlib.import_module("rtdetr.detector") + + assert standalone_onnx.__package__ == "rtdetr" + assert standalone_exact.__package__ == "rtdetr" + assert standalone_detector.__package__ == "rtdetr" + + +# --------------------------------------------------------------------------- +# RTDetrHandBBoxDetector 2-slot CUDA pipeline, persistent executor & lazy lock +# --------------------------------------------------------------------------- + + +def test_rtdetr_passes_cuda_batch_size_and_keeps_preprocess_threads(monkeypatch): + captured = {} + + class FakeHandDetector: + def __init__(self, **kwargs): + self.providers = ["CUDAExecutionProvider"] + captured.update(kwargs) + + monkeypatch.setattr(onnx_model_module, "HandDetector", FakeHandDetector) + wrapper = RTDetrHandBBoxDetector( + weights="model.onnx", batch_size=7, preprocess_threads=3 + ) + + assert captured["cuda_batch_size"] == 7 + assert wrapper.preprocess_threads == 3 + + +def _cuda_wrapper(batch_size=2, *, omit_init_attrs=False): + calls = [] + worker_threads = [] + + @dataclass + class Prepared: + values: list[int] + slot_index: int | None + orig_target_sizes_cpu: np.ndarray + + class FakeDetector: + cuda_input_enabled = True + + def initialize_cuda_slots(self, size, image_shape): + calls.append(("initialize", size, image_shape)) + + def prepare_bgr_batch_async(self, batch, slot_index): + values = [int(image[0, 0, 0]) for image in batch] + calls.append(("prepare", tuple(values), slot_index)) + return Prepared( + values, + slot_index, + np.zeros((len(values), 2), dtype=np.int64), + ) + + def run_onnx_prepared(self, prepared): + worker_threads.append(threading.get_ident()) + calls.append(("infer", tuple(prepared.values), prepared.slot_index)) + return prepared.values, None, None + + def postprocess(self, labels, _boxes, _scores, _sizes): + return [[value] for value in labels] + + wrapper = object.__new__(RTDetrHandBBoxDetector) + wrapper.batch_size = batch_size + wrapper.detector = FakeDetector() + if not omit_init_attrs: + wrapper._pipeline_lock = threading.Lock() + wrapper._cuda_executor = None + wrapper._detect_per_frame_legacy = lambda _batch: pytest.fail( + "CUDA execution must not use the CPU input path" + ) + return wrapper, calls, worker_threads + + +def test_cuda_detection_uses_two_slots_and_persistent_executor(): + wrapper, calls, worker_threads = _cuda_wrapper(batch_size=2, omit_init_attrs=True) + try: + images = [np.full((3, 4, 3), value, dtype=np.uint8) for value in range(5)] + + assert wrapper._detect_per_frame(images) == [[0], [1], [2], [3], [4]] + assert [call for call in calls if call[0] == "prepare"] == [ + ("prepare", (0, 1), 0), + ("prepare", (2, 3), 1), + ("prepare", (4,), 0), + ] + # Second clip reuses the same persistent single-worker thread. + assert wrapper._detect_per_frame(images[:2]) == [[0], [1]] + assert len(set(worker_threads)) == 1 + finally: + wrapper.close() + + +def test_cuda_detection_routes_short_and_mixed_batches(): + wrapper, calls, _ = _cuda_wrapper(batch_size=4) + try: + images = [np.full((3, 4, 3), value, dtype=np.uint8) for value in range(3)] + assert wrapper._detect_per_frame(images) == [[0], [1], [2]] + assert ("prepare", (0, 1, 2), 0) in calls + + calls.clear() + mixed = [ + np.zeros((3, 4, 3), dtype=np.uint8), + np.ones((5, 6, 3), dtype=np.uint8), + ] + assert wrapper._detect_per_frame(mixed) == [[0], [1]] + assert not [call for call in calls if call[0] == "initialize"] + assert ("prepare", (0, 1), None) in calls + finally: + wrapper.close() + + +def test_concurrent_resolution_changes_are_serialized_with_lazy_lock(): + wrapper, _calls, _ = _cuda_wrapper(batch_size=2, omit_init_attrs=True) + detector = wrapper.detector + original_initialize = detector.initialize_cuda_slots + original_prepare = detector.prepare_bgr_batch_async + active_shape = {"value": None} + + def initialize(size, image_shape): + active_shape["value"] = image_shape + original_initialize(size, image_shape) + time.sleep(0.01) + + def prepare(batch, slot_index): + if slot_index is not None: + assert all(tuple(image.shape) == active_shape["value"] for image in batch) + time.sleep(0.005) + return original_prepare(batch, slot_index) + + detector.initialize_cuda_slots = initialize + detector.prepare_bgr_batch_async = prepare + barrier = threading.Barrier(2) + errors = [] + + def run(shape): + images = [np.zeros(shape, dtype=np.uint8) for _ in range(4)] + try: + barrier.wait(timeout=2.0) + wrapper._detect_per_frame(images) + except BaseException as error: + errors.append(error) + + try: + threads = [ + threading.Thread(target=run, args=((3, 4, 3),)), + threading.Thread(target=run, args=((5, 6, 3),)), + ] + for thread in threads: + thread.start() + for thread in threads: + thread.join(timeout=3.0) + + assert not any(thread.is_alive() for thread in threads) + assert errors == [] + finally: + wrapper.close() + + +# --------------------------------------------------------------------------- +# crop_uint8 & crop_and_preprocess bit-exactness (BGR warp then BGR2RGB) +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize( + "height,width,bbx", + [ + (1456, 1920, [960.0, 728.0, 420.0]), # interior landscape + (1456, 1920, [15.5, 22.3, 310.5]), # top-left border crossing + (1456, 1920, [1910.2, 1445.8, 512.0]), # bottom-right border crossing + (1920, 1080, [540.25, 960.75, 256.0]), # portrait 1:1 scale + (480, 640, [320.0, 240.0, 128.0]), # upscaling crop + ], +) +def test_crop_uint8_is_bit_exact_with_cvtcolor_before_warp(height, width, bbx): + cv2 = pytest.importorskip("cv2") + from egohand.utils.crop_transform import get_transform + from inference.preprocessing.crop import ( + IMAGENET_MEAN, + IMAGENET_STD, + IMG_SIZE, + crop_and_preprocess, + crop_uint8, + ) + + rng = np.random.default_rng(height * 1000 + width + int(bbx[0])) + img_bgr = rng.integers(0, 256, (height, width, 3), dtype=np.uint8) + + for variant in (img_bgr, img_bgr[:, ::-1]): + cx, cy, size = float(bbx[0]), float(bbx[1]), float(bbx[2]) + trans = get_transform( + center=np.array([cx, cy]), scale=size, res=(IMG_SIZE, IMG_SIZE), rot=0 + ) + legacy_rgb = cv2.warpAffine( + cv2.cvtColor(variant, cv2.COLOR_BGR2RGB), + trans, + (IMG_SIZE, IMG_SIZE), + flags=cv2.INTER_LINEAR, + ) + actual_rgb = crop_uint8(variant, bbx) + assert actual_rgb.dtype == np.uint8 + assert actual_rgb.shape == (IMG_SIZE, IMG_SIZE, 3) + assert np.array_equal(actual_rgb, legacy_rgb) + + tensor, crop_rgb = crop_and_preprocess(variant, bbx) + assert np.array_equal(crop_rgb, legacy_rgb) + legacy_f = ( + legacy_rgb.astype(np.float32) / 255.0 - IMAGENET_MEAN + ) / IMAGENET_STD + assert torch.equal(tensor, torch.from_numpy(legacy_f.transpose(2, 0, 1))) + + +# --------------------------------------------------------------------------- +# CUDA execution tests (run when GPU is available) +# --------------------------------------------------------------------------- + + +@pytest.mark.skipif(not torch.cuda.is_available(), reason="CUDA required") +@pytest.mark.parametrize("height,width", [(1456, 1920), (1920, 1080), (641, 639)]) +def test_compiled_cuda_matches_pillow_13_on_landscape_and_portrait(height, width): + rng = np.random.default_rng(height * 1000 + width) + raw_numpy = rng.integers(0, 256, (2, height, width, 3), dtype=np.uint8) + raw_cuda = torch.from_numpy(raw_numpy).cuda() + preprocessor = PillowExactCudaPreprocessor(full_batch_size=2) + + for batch_size in (2, 1): + actual = preprocessor(raw_cuda[:batch_size].contiguous()) + torch.cuda.synchronize() + expected = torch.from_numpy(_pillow_reference(raw_numpy[:batch_size])).cuda() + assert torch.equal(actual, expected) + + +@pytest.mark.skipif(not torch.cuda.is_available(), reason="CUDA required") +def test_release_profile_runs_eager_cuda_without_compiling(monkeypatch): + monkeypatch.setenv("EGOHAND_RUNTIME_PROFILE", "release") + + def fail_compile(*_args, **_kwargs): + raise AssertionError("release profile must not call torch.compile") + + monkeypatch.setattr(torch, "compile", fail_compile) + rng = np.random.default_rng(99) + raw_numpy = rng.integers(0, 256, (2, 17, 23, 3), dtype=np.uint8) + preprocessor = PillowExactCudaPreprocessor(full_batch_size=2) + + actual = preprocessor(torch.from_numpy(raw_numpy).cuda()) + torch.cuda.synchronize() + expected = torch.from_numpy(_pillow_reference(raw_numpy)).cuda() + assert torch.equal(actual, expected) + + +@pytest.mark.skipif(not torch.cuda.is_available(), reason="CUDA required") +def test_prepare_cuda_tensor_avoids_second_h2d_copy(monkeypatch, tmp_path): + import onnxruntime as ort + + class FakeSession: + def get_providers(self): + return ["CUDAExecutionProvider", "CPUExecutionProvider"] + + weights = tmp_path / "model.onnx" + weights.write_bytes(b"test") + monkeypatch.setattr(ort, "InferenceSession", lambda _path, providers: FakeSession()) + monkeypatch.setattr(onnx_model_module, "_preload_cuda_libs", lambda: None) + + detector = HandDetector( + weights, + providers=[("CUDAExecutionProvider", {"device_id": 0}), "CPUExecutionProvider"], + cuda_batch_size=2, + ) + raw_cuda = torch.zeros(2, 16, 24, 3, dtype=torch.uint8, device="cuda:0") + prepared = detector.prepare_cuda_tensor(raw_cuda) + prepared.wait() + + assert prepared.raw_images.data_ptr() == raw_cuda.data_ptr() + assert prepared.orig_target_sizes_cpu.tolist() == [[24, 16], [24, 16]] + assert prepared.orig_target_sizes.is_cuda + assert prepared.orig_target_sizes.cpu().tolist() == [[24, 16], [24, 16]] + + +def test_cuda_detection_drains_inflight_future_on_prepare_error(): + wrapper, _calls, _ = _cuda_wrapper(batch_size=2) + infer_finished = threading.Event() + original_run = wrapper.detector.run_onnx_prepared + original_prepare = wrapper.detector.prepare_bgr_batch_async + prepare_count = {"n": 0} + + def slow_run(prepared): + time.sleep(0.05) + result = original_run(prepared) + infer_finished.set() + return result + + def failing_second_prepare(batch, slot_index): + prepare_count["n"] += 1 + if prepare_count["n"] == 2: + raise ValueError("simulated prepare failure") + return original_prepare(batch, slot_index) + + wrapper.detector.run_onnx_prepared = slow_run + wrapper.detector.prepare_bgr_batch_async = failing_second_prepare + images = [np.zeros((3, 4, 3), dtype=np.uint8) for _ in range(4)] + + try: + with pytest.raises(ValueError, match="simulated prepare failure"): + wrapper._detect_per_frame(images) + assert infer_finished.is_set() + finally: + wrapper.close() diff --git a/src/python/isaaccapture_egopost/inference/tests/hand_detector_2d/test_rtdetr_preprocess_threads.py b/src/python/isaaccapture_egopost/inference/tests/hand_detector_2d/test_rtdetr_preprocess_threads.py new file mode 100644 index 0000000000..47deb7e50e --- /dev/null +++ b/src/python/isaaccapture_egopost/inference/tests/hand_detector_2d/test_rtdetr_preprocess_threads.py @@ -0,0 +1,124 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: LicenseRef-OpenMDW-1.1 + +"""Threaded RT-DETR preprocessing feeds ORT exactly the batches of the sequential loop.""" + +from __future__ import annotations + +import numpy as np +import pytest + +pytest.importorskip("cv2") + +from inference.hand_detector_2d.rtdetr.detector import ( # noqa: E402 + RTDetrConfig, + RTDetrHandBBoxDetector, +) +from inference.hand_detector_2d.rtdetr.onnx_model import HandDetector # noqa: E402 + + +class _RecordingDetector: + """Stands in for HandDetector: records every ORT batch instead of running it.""" + + def __init__(self): + self.batches = [] + + def _record(self, batch, sizes): + self.batches.append( + (batch.tobytes(), batch.shape, sizes.tobytes(), sizes.dtype) + ) + return [[] for _ in range(len(batch))] + + def detect_batch(self, images): + # HandDetector.detect_batch, minus session.run. + batch = np.concatenate([HandDetector._preprocess(p) for p in images], axis=0) + sizes = np.array([[p.size[0], p.size[1]] for p in images], dtype=np.int64) + return self._record(batch, sizes) + + def detect_preprocessed(self, inputs, sizes): + return self._record(np.concatenate(inputs, axis=0), sizes) + + +def _detector(threads, batch_size=8): + det = object.__new__(RTDetrHandBBoxDetector) + det.batch_size = batch_size + det.preprocess_threads = threads + det._ort_batch_sizes_run = set() + det.detector = _RecordingDetector() + return det + + +def _frames(count, height, width, seed=0): + rng = np.random.default_rng(seed) + return [ + rng.integers(0, 256, (height, width, 3), dtype=np.uint8) for _ in range(count) + ] + + +@pytest.mark.parametrize( + "height,width", [(96, 128), (1080, 1920), (641, 639), (200, 300)] +) +@pytest.mark.parametrize("count", [1, 8, 19]) +def test_threaded_batches_equal_sequential(height, width, count): + frames = _frames(count, height, width, seed=height + width + count) + sequential = _detector(threads=1) + threaded = _detector(threads=4) + out_seq = sequential._detect_per_frame(frames) + out_thr = threaded._detect_per_frame(frames) + assert len(out_seq) == len(out_thr) == count + assert len(threaded.detector.batches) == -(-count // 8) + assert threaded.detector.batches == sequential.detector.batches + + +def test_mixed_sizes_in_one_chunk_keep_order(): + frames = ( + _frames(3, 120, 160, seed=1) + + _frames(2, 90, 200, seed=2) + + _frames(4, 64, 64, seed=3) + ) + sequential, threaded = _detector(threads=1), _detector(threads=3) + sequential._detect_per_frame(frames) + threaded._detect_per_frame(frames) + assert threaded.detector.batches == sequential.detector.batches + + +def test_second_clip_prefetches_from_the_start(): + det = _detector(threads=2) + frames = _frames(17, 64, 96, seed=4) + det._detect_per_frame(frames) + assert det._ort_batch_sizes_run == {8, 1} + det._detect_per_frame(frames) + seq = _detector(threads=1) + seq._detect_per_frame(frames) + seq._detect_per_frame(frames) + assert det.detector.batches == seq.detector.batches # 3 + 3 batches, same bytes + + +def test_wrapper_without_detect_preprocessed_keeps_the_sequential_loop(): + """An ORT wrapper with only detect_batch (e.g. a test double) still works.""" + frames = _frames(19, 64, 96, seed=5) + recording = _RecordingDetector() + + class BatchOnly: + def detect_batch(self, images): + return recording.detect_batch(images) + + det = _detector(threads=4) + det.detector = BatchOnly() + assert len(det._detect_per_frame(frames)) == 19 + seq = _detector(threads=1) + seq._detect_per_frame(frames) + assert recording.batches == seq.detector.batches + + +def test_empty_clip(): + assert _detector(threads=4)._detect_per_frame([]) == [] + + +def test_config_preprocess_threads(): + assert RTDetrConfig().preprocess_threads is None + assert RTDetrConfig.from_dict({"preprocess_threads": 4}).preprocess_threads == 4 + assert RTDetrConfig.from_spec("preprocess_threads=1").preprocess_threads == 1 + for bad in (0, -2, True, 2.5, "4"): + with pytest.raises(ValueError): + RTDetrConfig.from_dict({"preprocess_threads": bad}) diff --git a/src/python/isaaccapture_egopost/inference/tests/pipeline/test_background_load_exit.py b/src/python/isaaccapture_egopost/inference/tests/pipeline/test_background_load_exit.py new file mode 100644 index 0000000000..887d9d9c77 --- /dev/null +++ b/src/python/isaaccapture_egopost/inference/tests/pipeline/test_background_load_exit.py @@ -0,0 +1,102 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: LicenseRef-OpenMDW-1.1 + +"""The command line fails while the model still loads in the background: +the error ends the process normally (traceback, non-zero status), after the +load has finished, instead of aborting in native code at interpreter shutdown +(``run_main`` / ``wait_for_background_loads``).""" + +from __future__ import annotations + +import subprocess +import sys +import time +from pathlib import Path + + +ROOT = ( + Path(__file__).resolve().parents[3] +) # the egopost source root (inference/, egohand/) + +SCRIPT = r""" +import sys, time +from pathlib import Path +sys.path.insert(0, sys.argv[1]) +from inference.pipeline.predictor import PendingEgoHandPredictor +from inference.scripts import run_egohand_inference_pipeline as cli + +flag, mode = sys.argv[2], sys.argv[3] + +def load(): + time.sleep(30 if mode in ("timeout", "sigint_timeout") else 0.3) + Path(flag).write_text("loaded") + return object() + +PendingEgoHandPredictor(load, batch_size=1, device="cpu", dtype=None, smooth=False, camera_mode=None) + +def main(): + if mode == "exit": + raise SystemExit("[infer_video] bad configuration") + if mode == "sigint_timeout": + raise KeyboardInterrupt() + raise RuntimeError("boom while detecting") + +cli.run_main(main, wait_s=0.3 if mode in ("timeout", "sigint_timeout") else None) +""" + + +def _run(tmp_path, mode): + flag = tmp_path / "loaded" + start = time.monotonic() + r = subprocess.run( + [sys.executable, "-c", SCRIPT, str(ROOT), str(flag), mode], + capture_output=True, + text=True, + timeout=120, + check=False, + ) + return r, flag.exists(), time.monotonic() - start + + +def test_error_waits_for_the_load_then_exits_normally(tmp_path): + r, loaded, _ = _run(tmp_path, "raise") + assert r.returncode == 1, r.stderr + assert "Traceback (most recent call last)" in r.stderr + assert "RuntimeError: boom while detecting" in r.stderr + assert "terminate called" not in r.stderr + assert loaded # the load finished before the interpreter shut down + + +def test_exit_message_and_status_are_kept(tmp_path): + r, loaded, _ = _run(tmp_path, "exit") + assert r.returncode == 1, r.stderr + assert "[infer_video] bad configuration" in r.stderr + assert loaded + + +def test_a_load_that_does_not_finish_does_not_hold_the_exit(tmp_path): + r, loaded, elapsed = _run(tmp_path, "timeout") + assert r.returncode == 1, r.stderr + assert ( + "RuntimeError: boom while detecting" in r.stderr + ) # traceback printed before os._exit + assert "the background model load did not finish" in r.stderr + assert not loaded + assert elapsed < 25 + + +def test_keyboard_interrupt_timeout_exits_130(tmp_path): + r, loaded, elapsed = _run(tmp_path, "sigint_timeout") + assert r.returncode == 130, r.stderr + assert not loaded + assert elapsed < 10 + + +def test_success_is_unchanged(): + from inference.pipeline.predictor import wait_for_background_loads + from inference.scripts.run_egohand_inference_pipeline import run_main + + calls = [] + run_main(lambda: calls.append(1)) + assert calls == [1] + assert wait_for_background_loads(0.0) diff --git a/src/python/isaaccapture_egopost/inference/tests/pipeline/test_crop_stream.py b/src/python/isaaccapture_egopost/inference/tests/pipeline/test_crop_stream.py new file mode 100644 index 0000000000..1017953057 --- /dev/null +++ b/src/python/isaaccapture_egopost/inference/tests/pipeline/test_crop_stream.py @@ -0,0 +1,411 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: LicenseRef-OpenMDW-1.1 + +"""Crops streamed to the forward pass in batches of valid crops. + +The streamed path must give the same batches as building every crop first and +slicing the valid ones into ``batch_size`` chunks (failed crops are dropped +before batching), with bounded look-ahead and errors raised to the caller. +""" + +from __future__ import annotations + +import random +import threading +import time + +import numpy as np +import pytest +import torch + +from inference.camera.camera_models import load_camera_calibration +from inference.pipeline import predictor as predictor_module +from inference.pipeline.crop_stream import StreamedCropBatches +from inference.pipeline.predictor import EgoHandPredictor + + +def _jobs(n): + return [(i, f"frame{i // 2:04d}", ("left", "right")[i % 2]) for i in range(n)] + + +def _builder(fail=(), raise_at=None, jitter=0.0, calls=None): + """Crop stub: a (3, 4, 4) non-contiguous float32 view filled with the job index.""" + lock = threading.Lock() + + def build(job): + i, image_id, hand = job + if calls is not None: + with lock: + calls.append(i) + if jitter: + time.sleep(random.random() * jitter) + if raise_at is not None and i == raise_at: + raise RuntimeError(f"crop {i} exploded") + if i in fail: + return image_id, hand, None + hwc = np.full((4, 4, 3), float(i), dtype=np.float32) + return ( + image_id, + hand, + { + "i": i, + "image_id": image_id, + "real_hand_side": hand, + "crop_tensor": torch.from_numpy(hwc.transpose(2, 0, 1)), + }, + ) + + return build + + +@pytest.mark.parametrize("batch_size, workers", [(4, 3), (1, 8), (7, 2)]) +def test_batches_are_valid_crops_in_job_order(batch_size, workers): + fail = {0, 3, 4, 11, 22} + seen = [] + stream = StreamedCropBatches( + _jobs(25), + _builder(fail=fail, jitter=0.002), + batch_size=batch_size, + device="cpu", + workers=workers, + on_prepared=lambda image_id, hand, d: seen.append((image_id, hand, d["i"])), + ) + batches = [] + with stream: + for staged in stream: + ids = [d["i"] for d in staged.hand_data] + assert all("crop_tensor" not in d for d in staged.hand_data) + images = staged.images("cpu") + assert images.shape == (len(ids), 3, 4, 4) + assert images.dtype == torch.float32 + assert [float(x) for x in images[:, 0, 0, 0]] == [float(i) for i in ids] + batches.append(ids) + staged.release() + valid = [i for i in range(25) if i not in fail] + expected = [valid[s : s + batch_size] for s in range(0, len(valid), batch_size)] + assert batches == expected + assert [i for _, _, i in seen] == valid + assert stream.num_valid == len(valid) and stream.num_failed == len(fail) + + +def test_all_crops_failed_gives_no_batch(): + stream = StreamedCropBatches( + _jobs(5), _builder(fail=set(range(5))), batch_size=2, device="cpu", workers=2 + ) + with stream: + assert list(stream) == [] + + +def test_look_ahead_is_bounded(): + calls = [] + batch_size = 4 + stream = StreamedCropBatches( + _jobs(200), + _builder(calls=calls), + batch_size=batch_size, + device="cpu", + workers=4, + prefetch_batches=2, + ) + with stream: + iterator = iter(stream) + first = next(iterator) + time.sleep(0.5) # the forward of the first batch, slots never released + started = len(calls) + first.release() + rest = sum(len(s.hand_data) for s in _drain(iterator)) + # 2 staged slots + 1 filled batch waiting for a slot + 2 batches of jobs in flight + assert 2 * batch_size < started <= 5 * batch_size + assert len(first.hand_data) + rest == 200 + + +def _drain(iterator): + for staged in iterator: + yield staged + staged.release() + + +def test_crop_error_is_raised_in_the_consumer_and_threads_stop(): + stream = StreamedCropBatches( + _jobs(40), _builder(raise_at=9), batch_size=4, device="cpu", workers=3 + ) + with pytest.raises(RuntimeError, match="crop 9 exploded"): + with stream: + for staged in stream: + staged.release() + assert not stream._thread.is_alive() + + +def test_early_exit_stops_threads(): + stream = StreamedCropBatches( + _jobs(400), _builder(), batch_size=4, device="cpu", workers=4 + ) + with stream: + for _ in stream: + break # e.g. the forward raised; the batch is never released + assert not stream._thread.is_alive() + + +@pytest.mark.parametrize("value", [0, -1, True, 2.5]) +def test_invalid_sizes_are_rejected(value): + with pytest.raises(ValueError): + StreamedCropBatches([], _builder(), batch_size=value, device="cpu", workers=1) + + +# --------------------------------------------------------------------------- +# Predictor: streamed path vs build-everything-first path +# --------------------------------------------------------------------------- + + +class _RecordingModel: + """Outputs depend on each crop, so any misalignment changes the results.""" + + camera_mode = "sam3db_perspective" + kp2d_min_depth = 1e-4 + + def __init__(self): + self.batches = [] + + def forward_step(self, batch, train=False): + img = batch["img"] + n = img.shape[0] + signature = img.float().mean(dim=(1, 2, 3)).cpu() + self.batches.append(signature.tolist()) + signature = signature.to(img.device) + identity = torch.eye(3, device=img.device).reshape(1, 1, 3, 3) + scale_params = torch.zeros(n, 27, device=img.device) + scale_params[:, 0] = 1.0 + signature + cam_t = torch.stack( + [signature, -signature, 2.0 + signature.abs()], dim=-1 + ).float() + return { + "pred_vertices": signature.reshape(n, 1, 1).expand(n, 3, 3).contiguous(), + "pred_cam_t": cam_t, + "pred_cam": torch.tensor([1.0, 0.0, 0.0], device=img.device).expand(n, -1), + "pred_keypoints_3d": 0.01 + * signature.reshape(n, 1, 1).expand(n, 25, 3).contiguous(), + "pred_keypoints_2d": torch.zeros(n, 25, 2, device=img.device), + "pred_projection_valid": torch.ones( + n, 25, dtype=torch.bool, device=img.device + ), + "pred_hand_params": { + "wrist_orient": identity.expand(n, 1, 3, 3), + "hand_pose": identity.expand(n, 24, 3, 3), + "identity_coeffs": signature.reshape(n, 1).expand(n, 5).contiguous(), + "scale_params": scale_params, + }, + } + + +def _fake_mirror( + model, + poses, + transl, + identity_coeffs, + global_scale, + K_fullimg, + bbx_xys, + scale_params=None, + pose_mirror=None, +): + n = poses.shape[0] + return { + "pred_vertices": -identity_coeffs[:, :1] + .reshape(n, 1, 1) + .expand(n, 3, 3) + .contiguous(), + "transl": transl, + "pred_keypoints_3d": torch.zeros(n, 25, 3, device=poses.device), + "pred_keypoints_2d": torch.zeros(n, 25, 2, device=poses.device), + "pred_projection_valid": torch.ones( + n, 25, dtype=torch.bool, device=poses.device + ), + "poses": poses, + } + + +def _perspective_predictor(device, batch_size, stream_crops): + predictor = EgoHandPredictor.__new__(EgoHandPredictor) + predictor.batch_size = batch_size + predictor.device = device + predictor.dtype = torch.float32 + predictor.smooth = False + predictor.perf_reporter = None + predictor.model = _RecordingModel() + predictor._pose_mirror = None + predictor._use_perspective_cropping = True + predictor._model_wrist_orients = {"left": np.eye(3), "right": np.eye(3)} + predictor.stream_crops = stream_crops + return predictor + + +# A 1408 x 1408 pinhole camera, and boxes that make perspective_crop +# raise: "ROI perimeter reaches behind the virtual pinhole camera" and +# "Cannot undistort this bounding box" (NaN centre). +_PINHOLE_CAMERA = { + "model": "PINHOLE", + "image_width": 1408, + "image_height": 1408, + "camera_matrix": { + "matrix_3x3": [ + [608.8129272460938, 0.0, 704.0], + [0.0, 608.8129272460938, 704.0], + [0.0, 0.0, 1.0], + ] + }, + "distortion_coefficients": [], +} +_BEHIND_CAMERA_BOX = [1.0e5, 704.0, 2.0e5] +_NAN_BOX = [float("nan"), 704.0, 300.0] + + +def _devices(): + devices = ["cpu"] + if torch.cuda.is_available(): + devices.append("cuda") + return devices + + +@pytest.mark.parametrize("device", _devices()) +@pytest.mark.parametrize("batch_size", [3, 32]) +def test_run_streams_the_same_batches_and_skips_failed_crops( + monkeypatch, device, batch_size +): + monkeypatch.setattr( + predictor_module, "mirror_left_prediction_to_right", _fake_mirror + ) + camera = load_camera_calibration(_PINHOLE_CAMERA) + rng = np.random.default_rng(0) + image_ids = [f"frame{i:04d}" for i in range(9)] + images = [rng.integers(0, 255, (1408, 1408, 3), dtype=np.uint8) for _ in image_ids] + bboxes = { + image_id: { + "left": np.array([500.0 + 7 * i, 650.0, 260.0 + 3 * i], dtype=np.float32), + "right": np.array([900.0 - 5 * i, 700.0, 240.0 + 2 * i], dtype=np.float32), + } + for i, image_id in enumerate(image_ids) + } + bboxes["frame0002"]["right"] = np.array(_BEHIND_CAMERA_BOX, dtype=np.float32) + bboxes["frame0005"]["left"] = np.array(_NAN_BOX, dtype=np.float32) + del bboxes["frame0007"]["left"] # no box: never becomes a crop job + intrinsics = dict.fromkeys(image_ids, camera) + + outputs = {} + for stream_crops in (False, True): + predictor = _perspective_predictor(device, batch_size, stream_crops) + results = predictor.run( + images, + image_ids, + {k: dict(v) for k, v in bboxes.items()}, + ["left", "right"], + intrinsics_per_image=intrinsics, + ) + outputs[stream_crops] = (results, predictor.model.batches) + + (ref, ref_batches), (got, got_batches) = outputs[False], outputs[True] + assert got_batches == ref_batches # same batch boundaries and crop images + assert sum(len(b) for b in got_batches) == 15 # 18 jobs - 1 missing box - 2 failed + assert "frame0002" not in got["right"] and "frame0005" not in got["left"] + assert "frame0007" not in got["left"] + for hand in ("left", "right"): + assert list(got[hand]) == list(ref[hand]) + for image_id, result in ref[hand].items(): + for key, value in result.items(): + other = got[hand][image_id][key] + if isinstance(value, np.ndarray): + assert value.dtype == other.dtype + assert value.tobytes() == other.tobytes(), (hand, image_id, key) + else: + assert value == other or (value is None and other is None) + + +def test_streamed_forward_matches_list_forward_cpu(monkeypatch): + monkeypatch.setattr( + predictor_module, "mirror_left_prediction_to_right", _fake_mirror + ) + build = _builder(fail={2, 5}) + + def prepared(job): + image_id, hand, d = build(job) + if d is not None: + d.update( + model_bbx_xys=np.array([32.0, 32.0, 10.0], np.float32), + model_K=np.eye(3, dtype=np.float32), + model_img_size=np.array([64.0, 64.0], np.float32), + output_bbx_xys=np.array([32.0, 32.0, 10.0], np.float32), + output_K=np.eye(3, dtype=np.float32), + ) + return image_id, hand, d + + jobs = _jobs(13) + as_list = [d for d in (prepared(j)[2] for j in jobs) if d is not None] + a = _perspective_predictor("cpu", 4, True) + ref = a._run_imagebased_predictions(as_list, frame_count=7) + b = _perspective_predictor("cpu", 4, True) + with StreamedCropBatches( + jobs, prepared, batch_size=4, device="cpu", workers=3 + ) as s: + got = b._run_imagebased_predictions(s, frame_count=7) + assert a.model.batches == b.model.batches + assert len(ref) == len(got) == 11 + for r, g in zip(ref, got): + assert r.keys() == g.keys() + for key in r: + if isinstance(r[key], np.ndarray): + assert r[key].tobytes() == g[key].tobytes() + + +# --------------------------------------------------------------------------- +# CUDA: pinned slots, copy stream, slot reuse ordering +# --------------------------------------------------------------------------- + + +@pytest.mark.skipif(not torch.cuda.is_available(), reason="needs CUDA") +def test_cuda_slots_deliver_exact_images_while_the_gpu_is_still_reading(): + rng = np.random.default_rng(1) + crops = { + i: torch.from_numpy( + rng.standard_normal((256, 256, 3), dtype=np.float32).transpose(2, 0, 1) + ) + for i in range(30) + } + expected = { + i: c.clone() for i, c in crops.items() + } # crops are popped by the stream + + def build(job): + i, image_id, hand = job + return image_id, hand, {"i": i, "crop_tensor": crops[i]} + + copies, pointers = [], [] + stream = StreamedCropBatches( + _jobs(30), build, batch_size=4, device="cuda", workers=4 + ) + with stream: + for staged in stream: + ids = [d["i"] for d in staged.hand_data] + images = staged.images("cuda") + pointers.append(images.data_ptr()) + # Keep the GPU busy so the next uploads are queued while this batch + # is still unread; they must wait for this batch's "consumed" event. + torch.cuda._sleep(20_000_000) + copies.append((ids, images.clone())) + staged.release() + torch.cuda.synchronize() + assert [ids for ids, _ in copies] == [ + list(range(s, min(s + 4, 30))) for s in range(0, 30, 4) + ] + for ids, copy in copies: + assert torch.equal(copy.cpu(), torch.stack([expected[i] for i in ids])) + assert len(set(pointers)) == 2 # two device slots, alternating + assert pointers[0] != pointers[1] and pointers[0] == pointers[2] + + +@pytest.mark.skipif(not torch.cuda.is_available(), reason="needs CUDA") +def test_predictor_reuses_one_copy_stream_per_device(): + predictor = EgoHandPredictor.__new__(EgoHandPredictor) + predictor.device = "cuda" + first = predictor._crop_copy_stream() + assert first is predictor._crop_copy_stream() + predictor.device = "cpu" + assert predictor._crop_copy_stream() is None diff --git a/src/python/isaaccapture_egopost/inference/tests/pipeline/test_inference_weights.py b/src/python/isaaccapture_egopost/inference/tests/pipeline/test_inference_weights.py new file mode 100644 index 0000000000..db4533827b --- /dev/null +++ b/src/python/isaaccapture_egopost/inference/tests/pipeline/test_inference_weights.py @@ -0,0 +1,431 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: LicenseRef-OpenMDW-1.1 + +"""Inference-weight export, strict key checks, meta-device DINO and background load.""" + +from __future__ import annotations + +import gc +import json +import sys +import threading +import time +import weakref + +import pytest +import torch + +from inference.pipeline import inference_weights as iw +from inference.pipeline.predictor import EgoHandPredictor, PendingEgoHandPredictor + + +def _fake_checkpoint(path): + cfg = { + "_target_": "egohand.EgoHand", + "backbone": {"_target_": "x.DinoV3Backbone", "name": "dinov3_vith16plus"}, + "camera_mode": "sam3db_perspective", + "soma_hand": {"data_root": None}, + "loss_weights": {"keypoints_2d": 0.01}, + } + generator = torch.Generator().manual_seed(0) + state_dict = { + "backbone.encoder.w": torch.randn(4, 3, generator=generator), + "hand_head.b": torch.randn(5, generator=generator).to(torch.bfloat16), + "hand_head.idx": torch.arange(6, dtype=torch.int64), + } + # A non-contiguous view must still round-trip bit-for-bit. + state_dict["hand_head.t"] = torch.randn(3, 4, generator=generator).t() + torch.save( + { + "hyper_parameters": {"cfg": cfg}, + "state_dict": state_dict, + "optimizer_states": [{"state": {0: torch.ones(1000)}}], + "egohand_camera_depth_mode": "s", + "egohand_camera_log_value_bounds": (-10.0, 10.0), + "global_step": 60000, + }, + path, + ) + return cfg, state_dict + + +def test_export_round_trip_is_bitwise_and_drops_training_state(tmp_path): + ckpt = tmp_path / "model.ckpt" + cfg, state_dict = _fake_checkpoint(ckpt) + out = tmp_path / "export" + + config = iw.export_inference_weights(ckpt, out) + + assert sorted(p.name for p in out.iterdir()) == ["config.json", "model.safetensors"] + assert config["format"] == iw.EXPORT_FORMAT + assert config["source"]["global_step"] == 60000 + assert len(config["source"]["sha256"]) == 64 + assert iw.is_inference_export(out) + assert iw.is_inference_export(out / iw.WEIGHTS_FILENAME) + assert not iw.is_inference_export(ckpt) + + source = iw.read_checkpoint(out) + assert source.cfg == cfg + assert source.checkpoint_fields == { + "egohand_camera_depth_mode": "s", + "egohand_camera_log_value_bounds": [-10.0, 10.0], + } + tensors = source.load_state_dict() + assert tensors.keys() == state_dict.keys() + for key, value in state_dict.items(): + assert tensors[key].dtype == value.dtype + assert torch.equal(tensors[key], value) + view = source.validation_view() + assert view["hyper_parameters"]["cfg"] == cfg + assert view["egohand_camera_depth_mode"] == "s" + # The training checkpoint reads the same cfg/fields through the same API. + reference = iw.read_checkpoint(ckpt) + assert reference.cfg == cfg + assert reference.checkpoint_fields == source.checkpoint_fields + + +def test_export_rejects_unknown_format(tmp_path): + ckpt = tmp_path / "model.ckpt" + _fake_checkpoint(ckpt) + out = tmp_path / "export" + iw.export_inference_weights(ckpt, out, source_sha256=False) + config = json.loads((out / iw.CONFIG_FILENAME).read_text()) + config["format"] = "something-else/9" + (out / iw.CONFIG_FILENAME).write_text(json.dumps(config)) + with pytest.raises(ValueError, match="unsupported format"): + iw.read_checkpoint(out) + + +def test_strict_key_check_allows_only_asset_derived_soma_layers(): + iw.check_state_dict_keys( + ["soma_hand.left.identity_model._mhr_model.module.mesh.faces"], [] + ) + with pytest.raises(RuntimeError, match="1 missing key"): + iw.check_state_dict_keys(["soma_hand.new_learned_scale"], []) + with pytest.raises(RuntimeError, match="1 missing key"): + iw.check_state_dict_keys(["hand_head.decpose.weight"], []) + with pytest.raises(RuntimeError, match=r"1 unexpected key.*ignore_unexpected_keys"): + iw.check_state_dict_keys([], ["kp2d_head.extra"]) + + +def test_ignore_unexpected_keys_still_rejects_missing_keys(caplog): + iw.check_state_dict_keys([], ["ema.hand_head.weight"], ignore_unexpected=True) + assert "ignoring 1 checkpoint key(s)" in caplog.text + with pytest.raises(RuntimeError, match="1 missing key"): + iw.check_state_dict_keys( + ["hand_head.decpose.weight"], ["ema.x"], ignore_unexpected=True + ) + + +def test_dino_meta_init_allocates_no_storage_and_materializes_on_demand(): + pytest.importorskip("dinov3") + from egohand.models.backbones.dinov3 import DinoV3Backbone + + backbone = DinoV3Backbone(meta_init=True) + tensors = list(backbone.encoder.state_dict().values()) + assert tensors and all(t.is_meta for t in tensors) + backbone.encoder.to_empty(device="cpu") + assert not any(t.is_meta for t in backbone.encoder.state_dict().values()) + + +def test_pending_predictor_serves_settings_without_waiting_and_forwards_after_load(): + release = threading.Event() + + class _Loaded: + model = "loaded-model" + + def run(self): + return "ran" + + def load(): + release.wait(5) + return _Loaded() + + pending = PendingEgoHandPredictor( + load, + batch_size=7, + device="cpu", + dtype=torch.float32, + smooth=True, + camera_mode="sam3db_perspective", + ) + # Construction-time settings never block on the load. + assert pending.batch_size == 7 + assert pending.smooth is True + assert pending.camera_mode == "sam3db_perspective" + assert pending.load_seconds is None + release.set() + assert pending.run() == "ran" + assert pending.model == "loaded-model" + assert pending.load_seconds is not None + + +def test_pending_predictor_reraises_load_errors_on_use(): + def load(): + raise RuntimeError("bad checkpoint") + + pending = PendingEgoHandPredictor( + load, + batch_size=1, + device="cpu", + dtype=torch.float32, + smooth=False, + camera_mode="weak_perspective", + ) + with pytest.raises(RuntimeError, match="bad checkpoint"): + pending.run() + + +def test_load_in_background_rejects_unsupported_target_immediately(tmp_path): + ckpt = tmp_path / "model.ckpt" + torch.save( + { + "hyper_parameters": {"cfg": {"_target_": "example.UnsupportedModel"}}, + "state_dict": {}, + }, + ckpt, + ) + with pytest.raises(ValueError, match="not supported"): + EgoHandPredictor.load_in_background(ckpt, tmp_path, batch_size=1, device="cpu") + + +def test_background_model_load_is_default_and_can_be_disabled(monkeypatch): + from inference.cli import parse_args + + argv = ["x.py", "--input", "in.mp4", "--output_dir", "out"] + monkeypatch.setattr(sys, "argv", argv) + assert parse_args().background_model_load is True + monkeypatch.setattr(sys, "argv", argv + ["--no-background_model_load"]) + assert parse_args().background_model_load is False + + +def test_bundled_default_accepts_export_directory(tmp_path, monkeypatch): + from inference.cli import parse_args + + export_dir = tmp_path / "export" + export_dir.mkdir() + monkeypatch.setenv("EGOHAND_DEFAULT_CKPT", str(export_dir)) + monkeypatch.setattr(sys, "argv", ["x.py", "--input", "in.mp4", "--output_dir", "o"]) + assert parse_args().egohand_ckpt == str(export_dir) + + +def test_is_inference_export_checks_file_and_incomplete_dir(tmp_path): + export_dir = tmp_path / "export" + export_dir.mkdir() + (export_dir / iw.CONFIG_FILENAME).write_text("{}") + assert not iw.is_inference_export(export_dir) + assert not iw.is_inference_export(export_dir / "missing.safetensors") + other = export_dir / "other.safetensors" + other.write_bytes(b"x") + assert not iw.is_inference_export(other) + with pytest.raises(FileNotFoundError, match=iw.WEIGHTS_FILENAME): + iw.read_checkpoint(export_dir) + + +def test_wait_for_background_loads_waits_for_multiple_concurrent_loads(): + from inference.pipeline.predictor import wait_for_background_loads + + gate_a = threading.Event() + gate_b = threading.Event() + done: list[str] = [] + + def make_load(name: str, gate: threading.Event): + def _load(): + gate.wait(5.0) + done.append(name) + return object() + + return _load + + PendingEgoHandPredictor( + make_load("a", gate_a), + batch_size=1, + device="cpu", + dtype=torch.float32, + smooth=False, + camera_mode="weak_perspective", + ) + PendingEgoHandPredictor( + make_load("b", gate_b), + batch_size=1, + device="cpu", + dtype=torch.float32, + smooth=False, + camera_mode="weak_perspective", + ) + + def release(): + time.sleep(0.05) + gate_a.set() + time.sleep(0.05) + gate_b.set() + + releaser = threading.Thread(target=release, daemon=True) + releaser.start() + assert wait_for_background_loads(5.0) is True + assert set(done) == {"a", "b"} + + +def test_pending_predictor_reports_key_check_failure_before_loading(): + loaded = threading.Event() + + def validate(): + raise RuntimeError("checkpoint does not match: 3 missing key(s)") + + def load(): # pragma: no cover - must not run + loaded.set() + + pending = PendingEgoHandPredictor( + load, + validate=validate, + batch_size=1, + device="cpu", + dtype=torch.float32, + smooth=False, + camera_mode="weak_perspective", + ) + with pytest.raises(RuntimeError, match="3 missing key"): + pending.wait_until_validated() + assert not loaded.is_set() + + +def test_expected_keys_build_without_soma_layers(): + pytest.importorskip("dinov3") + from omegaconf import OmegaConf + + cfg = OmegaConf.create( + { + "_target_": "egohand.EgoHand", + "backbone": { + "_target_": "egohand.models.backbones.dinov3.DinoV3Backbone", + "name": "dinov3_vith16plus", + "drop_path_rate": 0.1, + }, + "backbone_weights": "/nonexistent/pretrained.pth", + "backbone_input_crop_w": None, + "soma_hand_head": { + "_target_": "egohand.models.heads.soma_hand_head_v2.SOMAHandTransformerDecoderHeadV2", + "num_finger_joints": 24, + "num_identity_coeffs": 5, + "num_scale_params": 27, + "transformer_dim": 1024, + "transformer_depth": 6, + "transformer_heads": 8, + "transformer_dim_head": 64, + "transformer_mlp_dim": 1024, + "transformer_context_dim": 1280, + }, + "soma_hand": {"data_root": None, "identity_model_type": "mhr"}, + "camera_mode": "sam3db_perspective", + "cliff_condition": True, + } + ) + keys = iw.expected_model_keys(cfg) + assert keys and not any(k.startswith("soma_hand.") for k in keys) + assert any(k.startswith("backbone.encoder.") for k in keys) + assert any(k.startswith("hand_head.") for k in keys) + + +def test_export_verify_handles_scalar_and_strided_tensors(tmp_path): + from inference.scripts.export_inference_weights import _verify + + ckpt = tmp_path / "model.ckpt" + torch.save( + { + "hyper_parameters": {"cfg": {"_target_": "egohand.EgoHand"}}, + "state_dict": { + "a.scale": torch.tensor(1.5), # 0-d + "a.t": torch.arange(12.0).reshape(3, 4).t(), # last dim not contiguous + "a.nan": torch.tensor([float("nan"), 1.0]), + }, + }, + ckpt, + ) + iw.export_inference_weights(ckpt, tmp_path / "export", source_sha256=False) + _verify(ckpt, tmp_path / "export", None) + + +def test_load_in_background_imports_usd_before_starting_the_worker( + tmp_path, monkeypatch +): + """OpenUSD dlopen + GIL vs. loader lock: import it while only one thread runs.""" + from inference.pipeline import predictor as predictor_module + + ckpt = tmp_path / "model.ckpt" + _fake_checkpoint(ckpt) + events = [] + real_start = threading.Thread.start + + def start(thread): + if thread.name == "egohand-model-load": + events.append("worker start") + return real_start(thread) + + monkeypatch.setattr(threading.Thread, "start", start) + monkeypatch.setattr( + predictor_module, "preload_usd_libraries", lambda: events.append("usd import") + ) + monkeypatch.setattr( + predictor_module, "check_checkpoint_keys", lambda source, cfg: None + ) + monkeypatch.setattr( + EgoHandPredictor, "from_checkpoint", classmethod(lambda cls, **kw: None) + ) + pending = EgoHandPredictor.load_in_background( + ckpt, tmp_path, batch_size=1, device="cpu" + ) + pending.wait_until_validated() + pending._done.wait() + assert events == ["usd import", "worker start"] + + +def test_load_in_background_passes_on_every_from_checkpoint_argument( + tmp_path, monkeypatch +): + """Arguments added to from_checkpoint later reach it through the background + path too, and a finished load is not kept alive by the module.""" + from inference.pipeline import predictor as predictor_module + + ckpt = tmp_path / "model.ckpt" + _fake_checkpoint(ckpt) + seen = {} + + class Loaded: + pass + + def from_checkpoint(cls, **kwargs): + seen.update(kwargs) + return Loaded() + + monkeypatch.setattr( + predictor_module, "check_checkpoint_keys", lambda source, cfg: None + ) + monkeypatch.setattr( + EgoHandPredictor, "from_checkpoint", classmethod(from_checkpoint) + ) + pending = EgoHandPredictor.load_in_background( + ckpt, + tmp_path, + batch_size=4, + device="cpu", + use_perspective_cropping=True, + some_future_option=7, + ) + loaded = pending.result() + assert seen["batch_size"] == 4 and seen["device"] == "cpu" + assert seen["use_perspective_cropping"] is True + assert seen["some_future_option"] == 7 + pending._thread.join() + assert pending not in predictor_module._PENDING_LOADS + ref = weakref.ref(loaded) + del pending, loaded + gc.collect() + assert ref() is None + + +def test_preload_usd_libraries_imports_what_soma_uses(): + pytest.importorskip("pxr") + from inference.pipeline.predictor import _USD_MODULES, preload_usd_libraries + + preload_usd_libraries() + assert all(name in sys.modules for name in _USD_MODULES) diff --git a/src/python/isaaccapture_egopost/inference/tests/pipeline/test_mhr_presort.py b/src/python/isaaccapture_egopost/inference/tests/pipeline/test_mhr_presort.py new file mode 100644 index 0000000000..0bffc5c1ad --- /dev/null +++ b/src/python/isaaccapture_egopost/inference/tests/pipeline/test_mhr_presort.py @@ -0,0 +1,430 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: LicenseRef-OpenMDW-1.1 + +"""Tests for ``inference.pipeline.mhr_presort`` and its predictor/CLI wiring. + +Real-model tests require ``py-soma-x`` with its MHR asset (skipped otherwise); +the CUDA kernel-count check requires a GPU. +""" + +import logging +import sys + +import pytest +import torch +from torch import nn + +from inference.cli import parse_args +from inference.pipeline import mhr_presort +from inference.pipeline import predictor as predictor_module +from inference.pipeline.mhr_presort import ( + PresortedMHR, + apply_mhr_presort, + check_mhr_torchscript, + presort_mhr_sparse, + presort_required, +) + + +class _Wrapper(nn.Module): + """Same shape as py-soma-x's NonPersistentModuleWrapper.""" + + def __init__(self, module): + super().__init__() + self.module = module + + def forward(self, *args, **kwargs): + return self.module(*args, **kwargs) + + +class MHRDemo(nn.Module): # same original_name as the real model, other code + def forward(self, x: torch.Tensor) -> torch.Tensor: + return x + 1 + + +def test_unknown_code_is_left_alone(): + holder = nn.Module() + holder.mhr = _Wrapper(torch.jit.script(MHRDemo())) + holder.other = _Wrapper(torch.jit.script(nn.ReLU())) + before_mhr, before_other = holder.mhr.module, holder.other.module + info = presort_mhr_sparse(holder) + assert info["patched"] == [] + assert list(info["skipped"]) == ["mhr"] + assert holder.mhr.module is before_mhr + assert holder.other.module is before_other + + +def _load_mhr(device): + soma = pytest.importorskip("soma") + try: + path = soma.get_assets_dir() / "MHR" / "mhr_model_lod1.pt" + except Exception as exc: # noqa: BLE001 + pytest.skip(f"no soma assets: {exc}") + if not path.exists(): + pytest.skip(f"no MHR asset at {path}") + return torch.jit.load(str(path), map_location=device) + + +def _inputs(batch, device, pose_scale): + """MHRHandIdentityModel passes a zero pose (pose_scale=0); a pose makes the + sparse product non-zero, where cuSPARSE itself is not bitwise repeatable.""" + g = torch.Generator().manual_seed(5) + identity = torch.randn(batch, 45, generator=g) * 0.5 + params = torch.zeros(batch, 204) + params[:, 136:] = torch.randn(batch, 68, generator=g) * 0.1 # scales + params[:, 130:136] = torch.randn(batch, 6, generator=g) * 0.1 + params[:, :130] = torch.randn(batch, 130, generator=g) * pose_scale + face = torch.zeros(batch, 72) + return identity.to(device), params.to(device), face.to(device) + + +def _max_diff(a, b): + return float((a - b).abs().max()) + + +def _check_against_torchscript(device): + ts = _load_mhr(device) + assert check_mhr_torchscript(ts) is None + holder = nn.Module() + holder.mhr = _Wrapper(ts) + info = presort_mhr_sparse(holder) + assert info == {"patched": ["mhr"], "skipped": {}} + assert isinstance(holder.mhr.module, PresortedMHR) + assert presort_mhr_sparse(holder)["patched"] == [] # idempotent + pc = ts.pose_correctives_model + sparse_ts = getattr(pc.pose_dirs_predictor, "0") + for pose_scale in (0.0, 0.2): + identity, params, face = _inputs(8, device, pose_scale) + with torch.no_grad(): + jp = ts.character_torch.model_parameters_to_joint_parameters( + torch.cat([params, torch.zeros_like(identity)], 1) + ) + feats = pc._pose_features_from_joint_params(jp) + a, a2 = sparse_ts(feats), sparse_ts(feats) + b = torch.matmul(holder.mhr.module._sparse_matrix(), feats.T).T + verts_ts, skel_ts = ts(identity, params, face) + verts_new, skel_new = holder.mhr(identity, params, face) + verts_ts2, _ = ts(identity, params, face) + assert torch.equal(skel_ts, skel_new) + if pose_scale == 0.0 or device == "cpu": + assert torch.equal(a, b) + else: # cuSPARSE SpMM differs run to run by a few ulp + assert _max_diff(a, b) <= max(_max_diff(a, a2), 1e-6) + # skin_points itself is not bitwise repeatable on CUDA (3e-5 cm run to run) + noise = _max_diff(verts_ts, verts_ts2) + tol = 1e-6 if device == "cpu" else 1e-4 + assert _max_diff(verts_ts, verts_new) <= max(noise, tol) + + # Verify apply_correctives=False matches TorchScript too. + identity, params, face = _inputs(4, device, 0.2) + with torch.no_grad(): + verts_ts, skel_ts = ts(identity, params, face, apply_correctives=False) + verts_new, skel_new = holder.mhr( + identity, params, face, apply_correctives=False + ) + assert torch.equal(skel_ts, skel_new) + tol = 1e-6 if device == "cpu" else 1e-4 + assert _max_diff(verts_ts, verts_new) <= tol + + # Verify outer autocast does not alter eager sparse precision. + if device in ("cpu", "cuda"): + with torch.no_grad(), torch.amp.autocast(device, dtype=torch.bfloat16): + verts_ac, skel_ac = holder.mhr(identity, params, face) + with torch.no_grad(): + verts_ref, skel_ref = ts(identity, params, face) + assert torch.equal(skel_ref, skel_ac) + assert _max_diff(verts_ref, verts_ac) <= tol + return ts, holder + + +def test_same_outputs_cpu(): + _check_against_torchscript("cpu") + + +@pytest.mark.skipif(not torch.cuda.is_available(), reason="needs CUDA") +def test_no_merge_sort_kernels_cuda(): + ts, holder = _check_against_torchscript("cuda") + identity, params, face = _inputs(512, "cuda", 0.0) + + def merge_sort_kernels(fn): + with torch.no_grad(): + fn(identity, params, face) # warm up + torch.cuda.synchronize() + with torch.profiler.profile( + activities=[torch.profiler.ProfilerActivity.CUDA] + ) as prof: + fn(identity, params, face) + torch.cuda.synchronize() + return sum(e.count for e in prof.key_averages() if "DeviceMergeSort" in e.key) + + assert merge_sort_kernels(ts) > 0 # the TorchScript forward sorts every call + assert merge_sort_kernels(holder.mhr) == 0 + + +def test_cache_follows_parameters_cpu(): + ts = _load_mhr("cpu") + holder = nn.Module() + holder.mhr = _Wrapper(ts) + assert presort_mhr_sparse(holder)["patched"] == ["mhr"] + first = holder.mhr.module._sparse_matrix() + assert holder.mhr.module._sparse_matrix() is first # reused while unchanged + holder.double() # _apply drops the old cache immediately; next call rebuilds + assert holder.mhr.module._cache is None + second = holder.mhr.module._sparse_matrix() + assert second is not first and second.dtype == torch.float64 + weight = getattr(ts.pose_correctives_model.pose_dirs_predictor, "0").sparse_weight + assert torch.equal(second.values(), weight.detach()) + + +def test_presorted_mhr_rejects_1d_inputs(): + wrapped = PresortedMHR(torch.jit.script(MHRDemo())) + with pytest.raises(AssertionError, match="identity coeffs"): + wrapped(torch.zeros(45), torch.zeros(1, 204), torch.zeros(1, 72)) + with pytest.raises(AssertionError, match="face expressions coeffs"): + wrapped(torch.zeros(1, 45), torch.zeros(1, 204), torch.zeros(72)) + + +class _FakeSparse(nn.Module): + def __init__(self, idx, weight, shape): + super().__init__() + self.register_buffer("sparse_indices", idx) + self.register_buffer("sparse_weight", weight) + self.sparse_shape = shape + + def forward(self, x: torch.Tensor) -> torch.Tensor: + return x + + +class _FakePoseCorrectives(nn.Module): + def __init__(self, sparse): + super().__init__() + self.pose_dirs_predictor = nn.Sequential(sparse, nn.ReLU(), nn.Linear(2, 2)) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + return x + + +class _FakeMHRTree(nn.Module): + def __init__(self, idx, weight, shape): + super().__init__() + self.pose_correctives_model = _FakePoseCorrectives( + _FakeSparse(idx, weight, shape) + ) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + return x + + +def _script_fake_mhr(idx, weight, shape, monkeypatch): + ts = torch.jit.script(_FakeMHRTree(idx, weight, shape)) + digests = { + name: mhr_presort._code_digest(mhr_presort._get(ts, name)) + for name in mhr_presort._KNOWN_CODE + } + monkeypatch.setattr(mhr_presort, "_KNOWN_CODE", digests) + return ts + + +def test_check_mhr_torchscript_missing_submodule(monkeypatch): + assert check_mhr_torchscript(nn.Linear(2, 2)) == "not a TorchScript module" + bare = torch.jit.script(MHRDemo()) + monkeypatch.setattr( + mhr_presort, + "_KNOWN_CODE", + {"": mhr_presort._code_digest(bare), "missing_sub": "0" * 16}, + ) + assert "no submodule 'missing_sub'" in check_mhr_torchscript(bare) + + +def test_check_mhr_torchscript_invariants(monkeypatch): + valid_idx = torch.tensor([[0, 0, 1], [0, 2, 1]], dtype=torch.int64) + valid_w = torch.tensor([1.0, 2.0, 3.0]) + assert ( + check_mhr_torchscript(_script_fake_mhr(valid_idx, valid_w, [2, 3], monkeypatch)) + is None + ) + + # Bad sparse_shape length or non-positive dims + bad_shape = _script_fake_mhr(valid_idx, valid_w, [2], monkeypatch) + assert "unexpected sparse shape" in check_mhr_torchscript(bad_shape) + + # Mismatched weight length + bad_len = _script_fake_mhr(valid_idx, torch.tensor([1.0, 2.0]), [2, 3], monkeypatch) + assert "unexpected sparse layout" in check_mhr_torchscript(bad_len) + + # Floating-point indices + bad_dtype = _script_fake_mhr(valid_idx.float(), valid_w, [2, 3], monkeypatch) + assert "unexpected sparse layout" in check_mhr_torchscript(bad_dtype) + + # Negative index + neg_idx = torch.tensor([[-1, 0, 1], [0, 2, 1]], dtype=torch.int64) + assert "strictly increasing" in check_mhr_torchscript( + _script_fake_mhr(neg_idx, valid_w, [2, 3], monkeypatch) + ) + + # Out-of-bounds index + oob_idx = torch.tensor([[0, 0, 2], [0, 2, 1]], dtype=torch.int64) + assert "strictly increasing" in check_mhr_torchscript( + _script_fake_mhr(oob_idx, valid_w, [2, 3], monkeypatch) + ) + + # Duplicate / unsorted indices + dup_idx = torch.tensor([[0, 0, 1], [1, 1, 0]], dtype=torch.int64) + assert "strictly increasing" in check_mhr_torchscript( + _script_fake_mhr(dup_idx, valid_w, [2, 3], monkeypatch) + ) + + +def _unknown_mhr_holder(): + holder = nn.Module() + holder.mhr = _Wrapper(torch.jit.script(MHRDemo())) + return holder + + +def test_unpatched_mhr_raises_where_the_sort_can_fault(monkeypatch): + monkeypatch.setattr(mhr_presort, "presort_required", lambda device: "exposed") + with pytest.raises(RuntimeError, match="no-mhr_presorted_sparse"): + apply_mhr_presort(_unknown_mhr_holder(), "cuda") + + +def test_partial_unpatched_mhr_is_detected(monkeypatch): + monkeypatch.setattr(mhr_presort, "presort_required", lambda device: "exposed") + valid_idx = torch.tensor([[0, 1], [0, 1]], dtype=torch.int64) + valid_w = torch.tensor([1.0, 2.0]) + good_ts = _script_fake_mhr(valid_idx, valid_w, [2, 2], monkeypatch) + + holder = nn.Module() + holder.patched = _Wrapper(PresortedMHR(good_ts)) + # A second MHRDemo attached directly without a wrapper must still trigger failure. + holder.unwrapped = torch.jit.script(MHRDemo()) + with pytest.raises(RuntimeError, match="could not be coalesced"): + apply_mhr_presort(holder, "cuda") + + +def test_unpatched_mhr_only_warns_elsewhere(monkeypatch, caplog): + monkeypatch.setattr(mhr_presort, "presort_required", lambda device: None) + holder = _unknown_mhr_holder() + before = holder.mhr.module + with caplog.at_level(logging.WARNING): + info = apply_mhr_presort(holder, "cpu") + assert list(info["skipped"]) == ["mhr"] + assert holder.mhr.module is before + assert "could not be coalesced" in caplog.text + + +def test_model_without_mhr_is_fine(monkeypatch): + monkeypatch.setattr(mhr_presort, "presort_required", lambda device: "exposed") + holder = nn.Module() + holder.other = _Wrapper(torch.jit.script(nn.ReLU())) + assert apply_mhr_presort(holder, "cuda") == {"patched": [], "skipped": {}} + + +@pytest.mark.parametrize( + "cuda,device,avail,capability,exposed", + [ + ("13.0", "cuda", True, (9, 0), True), + ("13.0.1", "cuda:0", True, (12, 0), True), + ("13.0", "cuda", False, (12, 0), False), + ("13.0", "cuda", True, (8, 9), False), + ("12.8", "cuda", True, (12, 0), False), + (None, "cuda", True, (12, 0), False), + ("13.0", "cpu", True, (12, 0), False), + ], +) +def test_presort_required(monkeypatch, cuda, device, avail, capability, exposed): + monkeypatch.setattr(torch.version, "cuda", cuda) + monkeypatch.setattr(torch.cuda, "is_available", lambda: avail) + monkeypatch.setattr(torch.cuda, "get_device_capability", lambda d=None: capability) + assert (presort_required(device) is not None) is exposed + + +@pytest.mark.parametrize("profile", ["full", "release"]) +def test_cli_mhr_presorted_sparse_flag(monkeypatch, profile): + monkeypatch.setenv("EGOHAND_RUNTIME_PROFILE", profile) + base = [ + "run_egohand_inference_pipeline.py", + "--input", + "clip.mp4", + "--output_dir", + "out", + ] + monkeypatch.setattr(sys, "argv", base) + assert parse_args().mhr_presorted_sparse is True + monkeypatch.setattr(sys, "argv", [*base, "--no-mhr_presorted_sparse"]) + assert parse_args().mhr_presorted_sparse is False + + +def test_from_checkpoint_wiring_without_soma_assets(monkeypatch, caplog): + model = nn.Module() + calls: list[tuple[nn.Module, str]] = [] + + def fake_apply(mod, dev): + calls.append((mod, dev)) + return {"patched": ["hand_left", "hand_right"], "skipped": {}} + + monkeypatch.setattr(mhr_presort, "apply_mhr_presort", fake_apply) + monkeypatch.setattr( + predictor_module, + "load_egohand_model", + lambda *args, **kwargs: (model, "egohand.EgoHand"), + ) + + def init(self, model, batch_size, device="cuda", **kwargs): + self.model = model + self.mhr_presort = None + + monkeypatch.setattr(predictor_module.EgoHandPredictor, "__init__", init) + + off = predictor_module.EgoHandPredictor.from_checkpoint( + "x.ckpt", "assets", batch_size=1, device="cpu", mhr_presorted_sparse=False + ) + assert off.mhr_presort is None + assert calls == [] + + with caplog.at_level(logging.WARNING): + on = predictor_module.EgoHandPredictor.from_checkpoint( + "x.ckpt", "assets", batch_size=1, device="cpu" + ) + assert calls == [(model, "cpu")] + assert on.mhr_presort == {"patched": ["hand_left", "hand_right"], "skipped": {}} + assert "MHR sparse layer coalesced at load: 2 model(s)" in caplog.text + + +def test_from_checkpoint_presorts_both_hand_models(monkeypatch, caplog): + model = nn.Module() + model.hand_left = _Wrapper(_load_mhr("cpu")) + model.hand_right = _Wrapper(_load_mhr("cpu")) + monkeypatch.setattr( + predictor_module, + "load_egohand_model", + lambda *args, **kwargs: (model, "egohand.EgoHand"), + ) + + def init(self, model, batch_size, device="cuda", **kwargs): + self.model = model + self.mhr_presort = None + + monkeypatch.setattr(predictor_module.EgoHandPredictor, "__init__", init) + + off = predictor_module.EgoHandPredictor.from_checkpoint( + "x.ckpt", "assets", batch_size=1, device="cpu", mhr_presorted_sparse=False + ) + assert off.mhr_presort is None + assert not isinstance(model.hand_left.module, PresortedMHR) + + caplog.clear() + with caplog.at_level(logging.WARNING): + predictor = predictor_module.EgoHandPredictor.from_checkpoint( + "x.ckpt", "assets", batch_size=1, device="cpu" + ) + # Logged by from_checkpoint, so callers need not read predictor.mhr_presort. + assert "MHR sparse layer coalesced at load: 2 model(s)" in caplog.text + assert predictor.mhr_presort == { + "patched": ["hand_left", "hand_right"], + "skipped": {}, + } + left, right = model.hand_left.module, model.hand_right.module + assert isinstance(left, PresortedMHR) and isinstance(right, PresortedMHR) + # A second call (e.g. a caller that also patches) leaves them as they are. + assert apply_mhr_presort(model, "cpu") == {"patched": [], "skipped": {}} + assert model.hand_left.module is left and model.hand_right.module is right diff --git a/src/python/isaaccapture_egopost/inference/tests/pipeline/test_soma_batching.py b/src/python/isaaccapture_egopost/inference/tests/pipeline/test_soma_batching.py new file mode 100644 index 0000000000..2c599bc3f7 --- /dev/null +++ b/src/python/isaaccapture_egopost/inference/tests/pipeline/test_soma_batching.py @@ -0,0 +1,236 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: LicenseRef-OpenMDW-1.1 + +"""--soma_batch_size bookkeeping: grouped SOMA calls give the per-batch results. + +The fake SOMA layer and mirror are row-wise and exact, so any difference +between grouped and per-batch results is a grouping, padding or ordering bug. +""" + +import numpy as np +import pytest +import torch + +from inference.pipeline.predictor import EgoHandPredictor + +_K = np.array([[100.0, 0.0, 32.0], [0.0, 100.0, 32.0], [0.0, 0.0, 1.0]], np.float32) + + +class _FakeSomaHand: + def __init__(self): + self.calls = [] + + def __call__( + self, poses, identity_coeffs, hand_type, pose2rot, global_scale, scale_params + ): + self.calls.append(poses.shape[0]) + joints = ( + poses[:, :, :, 0] * global_scale[:, None, None] + + identity_coeffs[:, :1, None] + ) + vertices = joints[:, :3] + scale_params[:, :1, None] + return {"joints": joints, "vertices": vertices} + + +class _FakeSplitModel: + camera_mode = "sam3db_perspective" + kp2d_min_depth = 1e-4 + + def __init__(self): + self.soma_hand = _FakeSomaHand() + + def forward_step_head(self, batch, train=False): + value = batch["img"][:, 0, 0, 0] + batch_size = value.shape[0] + poses = ( + torch.eye(3).expand(batch_size, 25, 3, 3) + * (1.0 + value)[:, None, None, None] + ) + scale_params = torch.stack( + [1.0 + 0.1 * value, value, 2.0 * value], dim=1 + ).float() + params = { + "wrist_orient": poses[:, :1].clone(), + "hand_pose": poses[:, 1:].clone(), + "identity_coeffs": torch.stack([value] * 5, dim=1), + "scale_params": scale_params, + } + return { + "batch_size": batch_size, + "soma_inputs": { + "poses": poses.clone(), + "identity_coeffs": params["identity_coeffs"].clone(), + "global_scale": scale_params[:, 0].clone(), + "scale_params": scale_params[:, 1:].clone(), + }, + "params": params, + "cam_t": torch.stack([value, -value, 2.0 + value], dim=1), + } + + def forward_step(self, batch, train=False): + head = self.forward_step_head(batch, train=train) + out = self.soma_hand(hand_type="left", pose2rot=False, **head["soma_inputs"]) + return self.forward_step_decode(head, out["joints"], out["vertices"]) + + def forward_step_decode(self, head, joints, vertices): + batch_size = head["batch_size"] + pred_keypoints_2d = joints[..., :2] * 0.01 + pred_keypoints_2d[:, 0] = float("nan") + valid = torch.ones(batch_size, 25, dtype=torch.bool) + valid[:, 0] = False + return { + "pred_vertices": vertices, + "pred_keypoints_3d": joints, + "pred_cam_t": head["cam_t"], + "pred_keypoints_2d": pred_keypoints_2d, + "pred_projection_valid": valid, + "pred_hand_params": head["params"], + "pred_kp2d_sigma": joints[..., :2] * 0.5, + } + + +def _fake_mirror( + model, + poses, + transl, + identity_coeffs, + global_scale, + K_fullimg, + bbx_xys, + scale_params=None, + pose_mirror=None, +): + _fake_mirror.calls.append(poses.shape[0]) + joints = poses[:, :, :, 1] * global_scale[:, None, None] - transl[:, None] + valid = torch.ones(poses.shape[0], 25, dtype=torch.bool) + valid[:, 1] = False + return { + "pred_vertices": joints[:, :3] + scale_params[:, :1, None], + "transl": transl * 2.0, + "pred_keypoints_3d": joints, + "pred_keypoints_2d": joints[..., :2] / bbx_xys[:, None, 2:] + + K_fullimg[:, None, 0, :2], + "pred_projection_valid": valid, + "poses": poses + identity_coeffs[:, :1, None, None], + } + + +def _inputs(hands): + return [ + { + "image_id": f"frame-{i // 2}", + "real_hand_side": hand, + "crop_tensor": torch.full((3, 8, 8), float(i + 1)), + "model_bbx_xys": np.array([32.0, 32.0, 10.0], np.float32), + "model_K": _K.copy(), + "model_img_size": np.array([64.0, 64.0], np.float32), + "output_bbx_xys": np.array([32.0 + i, 30.0, 10.0 + i], np.float32), + "output_K": _K + i, + } + for i, hand in enumerate(hands) + ] + + +def _predictor(soma_batch_size): + predictor = EgoHandPredictor.__new__(EgoHandPredictor) + predictor.batch_size = 3 + predictor.device = "cpu" + predictor.dtype = torch.float32 + predictor.model = _FakeSplitModel() + predictor._pose_mirror = None + predictor.soma_batch_size = soma_batch_size + return predictor + + +def _run(soma_batch_size, hands, monkeypatch): + _fake_mirror.calls = [] + for module in ("predictor", "soma_batching"): + monkeypatch.setattr( + f"inference.pipeline.{module}.mirror_left_prediction_to_right", + _fake_mirror, + ) + predictor = _predictor(soma_batch_size) + results = predictor._run_imagebased_predictions(_inputs(hands)) + return results, predictor.model.soma_hand.calls, list(_fake_mirror.calls) + + +@pytest.mark.parametrize("soma_batch_size", [3, 6, 7, 9]) +def test_grouped_soma_matches_per_batch(soma_batch_size, monkeypatch): + # Batches of 3; a 2-crop tail batch; a batch with no right hand. + hands = ["left", "right", "right", "left", "left", "left", "right", "left"] + hands += ["right", "right", "left"] + reference, ref_left_calls, ref_mirror_calls = _run(0, hands, monkeypatch) + grouped, left_calls, mirror_calls = _run(soma_batch_size, hands, monkeypatch) + + assert ref_left_calls == [3, 3, 3, 2] + assert ref_mirror_calls == [2, 2, 1] + assert set(left_calls) == {soma_batch_size} + assert len(left_calls) == -(-4 // (soma_batch_size // 3)) + assert set(mirror_calls) == {soma_batch_size} + assert len(grouped) == len(reference) == len(hands) + for got, want in zip(grouped, reference): + assert got.keys() == want.keys() + for key, value in want.items(): + if isinstance(value, np.ndarray): + np.testing.assert_array_equal(got[key], value, err_msg=key) + else: + assert got[key] == value, key + + +def test_soma_batch_size_below_batch_size_is_rejected(): + with pytest.raises(ValueError, match="soma_batch_size"): + EgoHandPredictor( + model=torch.nn.Identity(), batch_size=32, device="cpu", soma_batch_size=16 + ) + with pytest.raises(ValueError, match="soma_batch_size"): + EgoHandPredictor( + model=torch.nn.Identity(), batch_size=1, device="cpu", soma_batch_size=True + ) + + +def test_left_only_clip_does_not_retain_pending_right_batches(monkeypatch): + from inference.pipeline.soma_batching import SomaBatcher + + _fake_mirror.calls = [] + for module in ("predictor", "soma_batching"): + monkeypatch.setattr( + f"inference.pipeline.{module}.mirror_left_prediction_to_right", + _fake_mirror, + ) + predictor = _predictor(soma_batch_size=6) + batcher = SomaBatcher(predictor, group_rows=6) + hands = ["left"] * 18 + for batch_hand_data, staged in predictor._batch_source(_inputs(hands)): + batch = predictor._assemble_batch(batch_hand_data, staged) + head = predictor.model.forward_step_head(batch, train=False) + batch.pop("img") + batcher.add(batch, batch_hand_data, head) + assert batcher._right == [] + results = batcher.finish() + assert len(results) == 18 + assert batcher.mirror_calls == 0 + + +def test_device_cpu_torch_device_with_perf_reporter(monkeypatch): + class _DummyPerf: + def __init__(self): + self.stages = [] + + def record_latency(self, stage, ms): + self.stages.append(stage) + + _fake_mirror.calls = [] + for module in ("predictor", "soma_batching"): + monkeypatch.setattr( + f"inference.pipeline.{module}.mirror_left_prediction_to_right", + _fake_mirror, + ) + for soma_bs in (0, 6): + predictor = _predictor(soma_batch_size=soma_bs) + predictor.device = torch.device("cpu") + predictor.perf_reporter = _DummyPerf() + results = predictor._run_imagebased_predictions( + _inputs(["left", "right", "left", "right"]), frame_count=2 + ) + assert len(results) == 4 + assert len(predictor.perf_reporter.stages) == 3 diff --git a/src/python/isaaccapture_egopost/inference/tests/postprocessing/test_soma_single_pass_and_smooth.py b/src/python/isaaccapture_egopost/inference/tests/postprocessing/test_soma_single_pass_and_smooth.py new file mode 100644 index 0000000000..2e1890d36a --- /dev/null +++ b/src/python/isaaccapture_egopost/inference/tests/postprocessing/test_soma_single_pass_and_smooth.py @@ -0,0 +1,1579 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: LicenseRef-OpenMDW-1.1 + +"""CPU unit tests for Stage 3 single-pass SOMA deferral, FP64 smoothing, +vectorized projection, and GEP de8e8a86 fused right-hand cropping. +""" + +from __future__ import annotations + +from types import SimpleNamespace + +import numpy as np +import pytest +import torch +from scipy.spatial.transform import Rotation + +from egohand.models.egohand import EgoHand +from egohand.utils.cam_utils import compute_transl_full_cam +from inference.camera.camera_models import load_camera_calibration +from inference.pipeline.predictor import EgoHandPredictor +from inference.pipeline.results_io import save_hand_results_clip +from inference.pipeline.soma_batching import SomaBatcher +from inference.postprocessing.adaptive_smoothing import ( + AdaptiveSmoothingConfig, + _decode_soma_batches, + _local_noise, + _neighbors, + _project_batch_to_crop_frame, + _project_to_crop_frame, + _quadratic_fit, + _smooth_rotations_torch, + _smooth_shape, + _smooth_translation_torch, + _torch_local_noise, + _torch_project_so3, + _torch_quadratic_fit, + _torch_rotmat_to_rotvec, + _torch_rotvec_to_rotmat, + smooth_adaptive_hand_results, + smooth_rotations, + smooth_translation, +) +from inference.preprocessing.crop import crop_and_preprocess +from inference.preprocessing.mirroring import ( + _crop_mirrored_full_image_uint8, + mirror_full_image_camera_horizontal, + mirror_left_poses_to_right, + prepare_right_hand_model_input, + prepare_right_hand_model_input_uint8, +) + + +# --------------------------------------------------------------------------- +# 1. Vectorized _smooth_shape +# --------------------------------------------------------------------------- + + +def _reference_smooth_shape(values, times, sigma): + values = np.asarray(values) + out = values.astype(np.float64, copy=True) + for i in range(len(times)): + lo, hi, delta = _neighbors(times, i, sigma) + weights = np.exp(-0.5 * (delta / sigma) ** 2) + out[i] = np.tensordot(weights / weights.sum(), values[lo:hi], axes=(0, 0)) + return out + + +@pytest.mark.parametrize("shape_tail", [(), (5,), (26,)]) +@pytest.mark.parametrize("non_uniform", [False, True]) +def test_vectorized_smooth_shape_matches_reference(shape_tail, non_uniform): + rng = np.random.default_rng(42) + n = 75 + if non_uniform: + dt = rng.uniform(0.01, 0.08, size=n - 1) + times = np.concatenate(([0.0], np.cumsum(dt))) + else: + times = np.arange(n, dtype=np.float64) / 30.0 + values = rng.normal(size=(n, *shape_tail)).astype(np.float32) + + got = _smooth_shape(values, times, sigma=0.2) + want = _reference_smooth_shape(values, times, sigma=0.2) + np.testing.assert_allclose(got, want, rtol=1e-13, atol=1e-14) + + +@pytest.mark.parametrize("n", [0, 1, 2]) +def test_vectorized_smooth_shape_edge_lengths(n): + rng = np.random.default_rng(7) + times = np.arange(n, dtype=np.float64) / 30.0 + values = rng.normal(size=(n, 5)) + got = _smooth_shape(values, times, sigma=0.2) + want = _reference_smooth_shape(values, times, sigma=0.2) + np.testing.assert_allclose(got, want, rtol=1e-13, atol=1e-14) + + +# --------------------------------------------------------------------------- +# 2. Torch FP64 smoothing primitives and full parity vs CPU NumPy/SciPy +# --------------------------------------------------------------------------- + + +def test_torch_project_so3_newton_schulz_and_svd_fallback(): + rng = np.random.default_rng(123) + base_rots = Rotation.random(20, random_state=rng).as_matrix() + + # Near-SO(3) matrices (simulating BF16 quantization noise) -> Newton-Schulz. + noisy = base_rots + rng.normal(scale=0.02, size=base_rots.shape) + + # Degenerate / negative-det / scaled / rank-deficient matrices -> SVD fallback. + reflection = base_rots[0].copy() + reflection[:, 0] *= -1.0 + large_scale = base_rots[1] * 5.0 + small_scale = base_rots[2] * 1e-4 + singular = np.zeros((3, 3), dtype=np.float64) + singular[0, 0] = 1.0 + singular[1, 1] = 1.0 + all_mats = np.concatenate( + [noisy, np.stack([reflection, large_scale, small_scale, singular], axis=0)], + axis=0, + ) + + got = _torch_project_so3(torch.as_tensor(all_mats, dtype=torch.float64)).numpy() + + # Every output must be a proper SO(3) rotation matrix. + eye = np.broadcast_to(np.eye(3), got.shape) + np.testing.assert_allclose(got.swapaxes(-1, -2) @ got, eye, rtol=0, atol=1e-12) + np.testing.assert_allclose(np.linalg.det(got), np.ones(len(got)), atol=1e-12) + assert np.isfinite(got).all() + + # Matches SciPy on all positive-det cases (noisy Newton-Schulz + scaled SVD fallback). + pos_det_indices = list(range(len(noisy))) + [len(noisy) + 1, len(noisy) + 2] + want_pos = Rotation.from_matrix(all_mats[pos_det_indices]).as_matrix() + np.testing.assert_allclose(got[pos_det_indices], want_pos, rtol=0, atol=1e-12) + + +def test_torch_shepperd_rotmat_rotvec_roundtrip_and_scipy_parity(): + rng = np.random.default_rng(99) + # Cover identity, tiny angles, moderate angles, and near-pi / pi along all axes. + axes = rng.normal(size=(60, 3)) + axes /= np.linalg.norm(axes, axis=-1, keepdims=True) + angles = np.concatenate( + [ + np.array([0.0, 1e-12, 1e-9, 1e-7, 1e-6, 1e-4, np.pi - 1e-7, np.pi - 1e-4]), + rng.uniform(0.01, np.pi - 0.01, size=52), + ] + ) + rotvecs = axes * angles[:, None] + # Include exact pi rotations about X, Y, Z to hit all 4 Shepperd branches. + pi_vecs = np.array( + [[np.pi, 0.0, 0.0], [0.0, np.pi, 0.0], [0.0, 0.0, np.pi]], + dtype=np.float64, + ) + rotvecs = np.concatenate([rotvecs, pi_vecs], axis=0) + + mats_scipy = Rotation.from_rotvec(rotvecs).as_matrix() + mats_torch = _torch_rotvec_to_rotmat( + torch.as_tensor(rotvecs, dtype=torch.float64) + ).numpy() + np.testing.assert_allclose(mats_torch, mats_scipy, rtol=0, atol=1e-14) + + rv_torch = _torch_rotmat_to_rotvec( + torch.as_tensor(mats_scipy, dtype=torch.float64) + ).numpy() + rv_scipy = Rotation.from_matrix(mats_scipy).as_rotvec() + + # For angles strictly < pi, rotation vector is unique; for exact pi, +v and -v + # represent the identical rotation matrix. + strict = np.linalg.norm(rotvecs, axis=-1) < np.pi - 1e-9 + np.testing.assert_allclose(rv_torch[strict], rv_scipy[strict], rtol=0, atol=1e-12) + rebuilt = _torch_rotvec_to_rotmat( + torch.as_tensor(rv_torch, dtype=torch.float64) + ).numpy() + np.testing.assert_allclose(rebuilt, mats_scipy, rtol=0, atol=1e-13) + + +@pytest.mark.parametrize("non_uniform", [False, True]) +@pytest.mark.parametrize("n_frames", [8, 13, 45]) +def test_torch_fp64_smoothing_matches_cpu_exact(non_uniform, n_frames): + rng = np.random.default_rng(2026 + n_frames + int(non_uniform)) + if non_uniform: + dt = rng.uniform(0.015, 0.055, size=n_frames - 1) + times = np.concatenate(([0.0], np.cumsum(dt))) + else: + times = np.arange(n_frames, dtype=np.float64) / 30.0 + config = AdaptiveSmoothingConfig() + + # Smooth trajectory + fast burst + outlier + sensor noise. + transl = np.stack( + [ + 0.1 * np.sin(2.5 * times) + 0.004 * rng.normal(size=n_frames), + 0.05 * np.cos(4.0 * times) + 0.004 * rng.normal(size=n_frames), + 0.6 + 0.03 * times + 0.004 * rng.normal(size=n_frames), + ], + axis=-1, + ) + if n_frames >= 20: + transl[n_frames // 2] += np.array([0.08, -0.05, 0.04]) + + joints = 25 + rotvecs = 0.4 * np.sin(3.0 * times)[:, None, None] * rng.normal( + size=(1, joints, 3) + ) + 0.02 * rng.normal(size=(n_frames, joints, 3)) + poses = ( + Rotation.from_rotvec(rotvecs.reshape(-1, 3)) + .as_matrix() + .reshape(n_frames, joints, 3, 3) + ) + # Add tiny BF16-like non-orthogonality. + poses = poses + rng.normal(scale=1e-3, size=poses.shape) + + cpu_t = smooth_translation(transl, times, config) + torch_t = _smooth_translation_torch(transl, times, config, device="cpu") + np.testing.assert_allclose(torch_t, cpu_t, rtol=0, atol=1e-11) + + cpu_r = smooth_rotations(poses, times, config) + torch_r = _smooth_rotations_torch(poses, times, config, device="cpu") + np.testing.assert_allclose(torch_r, cpu_r, rtol=0, atol=1e-10) + + +def test_torch_local_noise_and_quadratic_fit_match_cpu(): + rng = np.random.default_rng(55) + n = 30 + times = np.arange(n, dtype=np.float64) / 30.0 + values = rng.normal(size=(n, 5, 3)) + + cpu_noise = _local_noise(values, times, 0.0015, 0.2, rotations=False) + torch_noise = _torch_local_noise( + torch.as_tensor(values, dtype=torch.float64), + times, + 0.0015, + 0.2, + rotations=False, + device="cpu", + ).numpy() + np.testing.assert_allclose(torch_noise, cpu_noise, rtol=0, atol=1e-14) + + # Test _torch_quadratic_fit with partial valid mask and robust=True. + w, num_traj = 11, 7 + v_win = rng.normal(size=(w, num_traj, 3)) + delta = np.linspace(-0.15, 0.15, w)[:, None] * np.ones((1, num_traj)) + sigma = rng.uniform(0.03, 0.08, size=num_traj) + noise = rng.uniform(0.01, 0.05, size=num_traj) + valid = np.ones((w, num_traj), dtype=bool) + valid[-2:, 0] = False + valid[0, 3] = False + + for robust in (False, True): + c_est, c_score = _quadratic_fit( + v_win, delta, sigma, noise, robust=robust, valid=valid + ) + t_est, t_score = _torch_quadratic_fit( + torch.as_tensor(v_win, dtype=torch.float64), + torch.as_tensor(delta, dtype=torch.float64), + torch.as_tensor(sigma, dtype=torch.float64), + torch.as_tensor(noise, dtype=torch.float64), + robust=robust, + valid=torch.as_tensor(valid, dtype=torch.bool), + ) + np.testing.assert_allclose(t_est.numpy(), c_est, rtol=0, atol=1e-13) + np.testing.assert_allclose(t_score.numpy(), c_score, rtol=0, atol=1e-13) + + +# --------------------------------------------------------------------------- +# 3. Vectorized _project_batch_to_crop_frame +# --------------------------------------------------------------------------- + + +class _SpyCamera: + """Wraps a CameraModel and records every batch size passed to .project().""" + + def __init__(self, inner): + self._inner = inner + self.call_sizes = [] + + def project(self, rays): + self.call_sizes.append(len(np.asarray(rays).reshape(-1, 3))) + return self._inner.project(rays) + + +def test_project_batch_to_crop_frame_matches_scalar_and_groups_by_camera(): + rng = np.random.default_rng(314) + n, j = 16, 25 + joints = rng.normal(scale=0.05, size=(n, j, 3)).astype(np.float32) + transl = np.stack( + [ + rng.uniform(-0.2, 0.2, size=n), + rng.uniform(-0.2, 0.2, size=n), + rng.uniform(0.4, 1.2, size=n), + ], + axis=-1, + ).astype(np.float32) + # Inject edge cases: behind-camera joint, NaN joint, NaN transl, zero-size bbox. + joints[1, 3, 2] = -2.0 + joints[2, 5, :] = np.nan + transl[4, :] = np.nan + bboxes = np.stack( + [ + rng.uniform(200.0, 500.0, size=n), + rng.uniform(200.0, 500.0, size=n), + rng.uniform(100.0, 300.0, size=n), + ], + axis=-1, + ).astype(np.float32) + bboxes[6, 2] = 0.0 + + kb4 = _SpyCamera( + load_camera_calibration( + { + "model": "KB4", + "image_width": 1408, + "image_height": 1408, + "camera_matrix": { + "matrix_3x3": [ + [600.0, 0.0, 704.0], + [0.0, 600.0, 704.0], + [0.0, 0.0, 1.0], + ] + }, + "distortion_coefficients": [-0.02, 0.005, -0.001, 0.0002], + } + ) + ) + pinhole_cam = _SpyCamera( + load_camera_calibration( + { + "model": "PINHOLE", + "image_width": 640, + "image_height": 480, + "camera_matrix": { + "matrix_3x3": [ + [500.0, 0.0, 320.0], + [0.0, 510.0, 240.0], + [0.0, 0.0, 1.0], + ] + }, + "distortion_coefficients": [], + } + ) + ) + # Mix two CameraModel objects (each reused across frames) and pinhole 3x3 Ks. + cameras = [] + for i in range(n): + if i % 3 == 0: + cameras.append(kb4) + elif i % 3 == 1: + cameras.append(pinhole_cam) + else: + cameras.append( + np.array( + [ + [550.0 + i, 2.0, 310.0 + i], + [0.0, 560.0 + i, 250.0], + [0.0, 0.0, 1.0], + ], + dtype=np.float32, + ) + ) + + kp2d_batch, valid_batch = _project_batch_to_crop_frame( + joints, transl, cameras, bboxes + ) + + # Each unique CameraModel must have been called exactly once! + assert len(kb4.call_sizes) == 1 + assert len(pinhole_cam.call_sizes) == 1 + + for i in range(n): + want_kp2d, want_valid = _project_to_crop_frame( + joints[i], transl[i], cameras[i], bboxes[i] + ) + np.testing.assert_array_equal(valid_batch[i], want_valid) + np.testing.assert_allclose( + kp2d_batch[i], want_kp2d, rtol=1e-13, atol=1e-13, equal_nan=True + ) + + # Empty batch returns cleanly shaped arrays. + empty_kp2d, empty_valid = _project_batch_to_crop_frame( + np.empty((0, j, 3)), np.empty((0, 3)), [], np.empty((0, 3)) + ) + assert empty_kp2d.shape == (0, j, 2) + assert empty_valid.shape == (0, j) + + +# --------------------------------------------------------------------------- +# 4. Uncovered NaN-transl & NaN-pose records in smooth_adaptive_hand_results +# --------------------------------------------------------------------------- + + +class _RowwiseStubSomaHand: + def __init__(self, num_verts=11, expose_layers=True): + self.num_verts = num_verts + self.calls = [] + if expose_layers: + layer = SimpleNamespace( + bind_shape=torch.zeros(num_verts, 3), + bind_pose_world=torch.eye(4).expand(25, 4, 4).clone(), + ) + self.left = layer + self.right = layer + + def __call__( + self, + poses, + identity_coeffs, + hand_type, + transl=None, + pose2rot=False, + global_scale=1.0, + scale_params=None, + ): + assert torch.isfinite(poses).all(), "soma_hand must not receive NaN poses" + assert torch.isfinite(identity_coeffs).all() + assert torch.isfinite(global_scale).all() + if scale_params is not None: + assert torch.isfinite(scale_params).all() + bsz = poses.shape[0] + self.calls.append((hand_type, bsz)) + joints = ( + poses[:, :, :, 0] * global_scale[:, None, None] + + identity_coeffs[:, :1, None] + ) + verts = ( + joints[:, : self.num_verts] + if self.num_verts <= 25 + else torch.zeros(bsz, self.num_verts, 3, device=poses.device) + ) + if scale_params is not None: + verts = verts + scale_params[:, :1, None] + return {"vertices": verts, "joints": joints} + + +def _make_record( + *, + transl, + poses=None, + identity_coeffs=None, + global_scale=1.0, + scale_params="default", + K_fullimg=None, + deferred=True, + num_verts=11, +): + if poses is None: + poses = np.broadcast_to(np.eye(3, dtype=np.float32), (25, 3, 3)).copy() + if identity_coeffs is None: + identity_coeffs = np.full((5,), 0.1, dtype=np.float32) + if scale_params == "default": + scale_params = np.full((26,), 0.05, dtype=np.float32) + if K_fullimg is None: + K_fullimg = np.array( + [[500.0, 0.0, 320.0], [0.0, 500.0, 240.0], [0.0, 0.0, 1.0]], + dtype=np.float32, + ) + return { + "pred_vertices": None if deferred else np.zeros((num_verts, 3), np.float32), + "transl": np.asarray(transl, dtype=np.float32), + "pred_keypoints_3d": None if deferred else np.zeros((25, 3), np.float32), + "pred_keypoints_2d": None if deferred else np.zeros((25, 2), np.float32), + "pred_projection_valid": None if deferred else np.ones((25,), np.bool_), + "poses": np.asarray(poses, dtype=np.float32), + "identity_coeffs": np.asarray(identity_coeffs, dtype=np.float32), + "scale_params": None + if scale_params is None + else np.asarray(scale_params, dtype=np.float32), + "global_scale": float(global_scale), + "K_fullimg": K_fullimg, + } + + +def test_smooth_adaptive_handles_uncovered_nan_transl_and_nan_pose_records(tmp_path): + image_ids = [f"f{i:03d}" for i in range(6)] + frame_times = [i / 30.0 for i in range(6)] + bboxes = { + fid: {"left": np.array([320.0, 240.0, 200.0], dtype=np.float32)} + for fid in image_ids + } + + nan_pose = np.full((25, 3, 3), np.nan, dtype=np.float32) + results_per_hand = { + "left": { + # Covered segment frames: + "f000": _make_record(transl=[0.0, 0.0, 0.8], deferred=True), + "f001": _make_record(transl=[0.01, 0.0, 0.8], deferred=True), + "f002": _make_record(transl=[0.02, 0.0, 0.8], deferred=True), + # Uncovered: NaN transl, finite poses/shape -> must decode verts/joints, NaN kp2d. + "f003": _make_record(transl=[np.nan, 0.0, 0.8], deferred=True), + # Uncovered: NaN poses, finite transl -> must NOT call soma_hand, populate NaNs. + "f004": _make_record(transl=[0.0, 0.0, 0.8], poses=nan_pose, deferred=True), + # Uncovered: NaN identity -> also invalid geometry, populate NaNs. + "f005": _make_record( + transl=[0.0, 0.0, 0.8], + identity_coeffs=np.full((5,), np.nan, dtype=np.float32), + deferred=True, + ), + } + } + + soma_hand = _RowwiseStubSomaHand(num_verts=11) + smooth_adaptive_hand_results( + results_per_hand, + image_ids, + bboxes, + frame_times=frame_times, + soma_hand=soma_hand, + device="cpu", + batch_size=16, + ) + + # Segment frames decoded + projected. + for fid in ("f000", "f001", "f002"): + r = results_per_hand["left"][fid] + assert r["pred_vertices"].shape == (11, 3) + assert np.isfinite(r["pred_vertices"]).all() + assert r["pred_keypoints_3d"].shape == (25, 3) + assert r["pred_keypoints_2d"].shape == (25, 2) + assert r["pred_projection_valid"].shape == (25,) + assert r["pred_projection_valid"].all() + + # Uncovered NaN-transl frame: geometry decoded (finite), projection NaN + False. + r_nan_t = results_per_hand["left"]["f003"] + assert r_nan_t["pred_vertices"].shape == (11, 3) + assert np.isfinite(r_nan_t["pred_vertices"]).all() + assert r_nan_t["pred_keypoints_3d"].shape == (25, 3) + assert np.isfinite(r_nan_t["pred_keypoints_3d"]).all() + assert r_nan_t["pred_keypoints_2d"].shape == (25, 2) + assert np.isnan(r_nan_t["pred_keypoints_2d"]).all() + assert r_nan_t["pred_projection_valid"].shape == (25,) + assert not r_nan_t["pred_projection_valid"].any() + + # Uncovered NaN-pose & NaN-identity frames: NaN geometry & False mask, never None. + for fid in ("f004", "f005"): + r_bad = results_per_hand["left"][fid] + assert r_bad["pred_vertices"].shape == (11, 3) + assert r_bad["pred_vertices"].dtype == np.float32 + assert np.isnan(r_bad["pred_vertices"]).all() + assert r_bad["pred_keypoints_3d"].shape == (25, 3) + assert np.isnan(r_bad["pred_keypoints_3d"]).all() + assert r_bad["pred_keypoints_2d"].shape == (25, 2) + assert np.isnan(r_bad["pred_keypoints_2d"]).all() + assert r_bad["pred_projection_valid"].shape == (25,) + assert r_bad["pred_projection_valid"].dtype == np.bool_ + assert not r_bad["pred_projection_valid"].any() + + # Verify save_hand_results_clip succeeds cleanly with zero None values. + clip_records = [] + for fid in image_ids: + rec = dict(results_per_hand["left"][fid]) + rec["hand_poses"] = rec["poses"] + rec["pred_cam_t"] = rec["transl"] + clip_records.append(rec) + out_npz = tmp_path / "left_results.npz" + save_hand_results_clip(out_npz, image_ids, clip_records) + loaded = np.load(out_npz) + assert loaded["vertices"].shape == (6, 11, 3) + assert loaded["joints"].shape == (6, 25, 3) + + +@pytest.mark.parametrize("expose_layers", [True, False]) +def test_smooth_adaptive_all_nan_pose_clip_infers_shapes(expose_layers): + image_ids = ["f000", "f001"] + frame_times = [0.0, 1.0 / 30.0] + bboxes = { + fid: {"right": np.array([320.0, 240.0, 200.0], dtype=np.float32)} + for fid in image_ids + } + nan_pose = np.full((25, 3, 3), np.nan, dtype=np.float32) + results_per_hand = { + "right": { + "f000": _make_record( + transl=[0.0, 0.0, 0.8], + poses=nan_pose, + scale_params=None, + deferred=True, + ), + "f001": _make_record( + transl=[0.0, 0.0, 0.8], + poses=nan_pose, + scale_params=None, + deferred=True, + ), + } + } + soma_hand = _RowwiseStubSomaHand(num_verts=13, expose_layers=expose_layers) + smooth_adaptive_hand_results( + results_per_hand, + image_ids, + bboxes, + frame_times=frame_times, + soma_hand=soma_hand, + device="cpu", + batch_size=8, + ) + for fid in image_ids: + r = results_per_hand["right"][fid] + assert r["pred_vertices"].shape == (13, 3) + assert np.isnan(r["pred_vertices"]).all() + assert r["pred_keypoints_3d"].shape == (25, 3) + assert r["pred_keypoints_2d"].shape == (25, 2) + assert not r["pred_projection_valid"].any() + + +# --------------------------------------------------------------------------- +# 5. GEP de8e8a86 bit-exact right-hand crop vs full-frame flip +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize( + "height, width, bbox", + [ + # Interior right-side box (small prefix ROI — common egocentric right-hand case). + (1080, 1920, [1520.3, 612.7, 295.5]), + # Interior left-side box (large prefix ROI). + (1080, 1920, [210.4, 480.2, 260.0]), + # Odd dimensions, centered. + (481, 643, [321.1, 240.9, 177.25]), + # Partially outside all four borders. + (400, 600, [15.5, 20.25, 180.0]), + (400, 600, [590.2, 390.8, 220.0]), + (400, 600, [595.0, 5.0, 150.0]), + # Completely outside image (all 4 directions). + (400, 600, [-200.0, 200.0, 100.0]), + (400, 600, [900.0, 200.0, 100.0]), + (400, 600, [300.0, -200.0, 100.0]), + (400, 600, [300.0, 700.0, 100.0]), + # Very large scale larger than the full image. + (300, 400, [180.5, 150.25, 900.0]), + # Small zoomed-in box. + (400, 600, [488.6, 211.4, 33.0]), + ], +) +def test_fused_right_hand_crop_bit_exact_with_full_frame_flip(height, width, bbox): + rng = np.random.default_rng(height * 1000 + width) + img_bgr = rng.integers(0, 256, size=(height, width, 3), dtype=np.uint8) + bbx = np.asarray(bbox, dtype=np.float32) + K = np.array( + [[810.0, 11.5, width * 0.48], [0.0, 825.0, height * 0.51], [0.0, 0.0, 1.0]], + dtype=np.float32, + ) + + # Reference: materialize full horizontally flipped image, then crop_and_preprocess. + ref_bbox, ref_K = mirror_full_image_camera_horizontal(bbx, K, width) + ref_tensor, ref_uint8 = crop_and_preprocess( + np.ascontiguousarray(img_bgr[:, ::-1]), + ref_bbox, + ) + + got_uint8, got_bbox, got_K = prepare_right_hand_model_input_uint8( + img_bgr, bbx, K, calibrated_full_image=True + ) + direct_uint8 = _crop_mirrored_full_image_uint8(img_bgr, ref_bbox) + got_tensor, got_bbox_f, got_K_f = prepare_right_hand_model_input( + img_bgr, bbx, K, calibrated_full_image=True + ) + + assert got_uint8.dtype == np.uint8 + assert got_uint8.shape == (256, 256, 3) + assert ( + int(np.max(np.abs(got_uint8.astype(np.int16) - ref_uint8.astype(np.int16)))) + == 0 + ) + np.testing.assert_array_equal(direct_uint8, ref_uint8) + np.testing.assert_array_equal(got_bbox, ref_bbox) + np.testing.assert_array_equal(got_K, ref_K) + np.testing.assert_array_equal(got_bbox_f, ref_bbox) + np.testing.assert_array_equal(got_K_f, ref_K) + torch.testing.assert_close(got_tensor, ref_tensor, rtol=0, atol=0) + + # Also verify legacy calibrated_full_image=False uint8 path is bit-exact. + leg_ref_tensor, leg_ref_uint8 = crop_and_preprocess(img_bgr, bbx) + leg_uint8, _, _ = prepare_right_hand_model_input_uint8( + img_bgr, bbx, K, calibrated_full_image=False + ) + leg_tensor, _, _ = prepare_right_hand_model_input( + img_bgr, bbx, K, calibrated_full_image=False + ) + np.testing.assert_array_equal(leg_uint8, leg_ref_uint8[:, ::-1]) + torch.testing.assert_close(leg_tensor, leg_ref_tensor.flip(-1), rtol=0, atol=0) + + +# --------------------------------------------------------------------------- +# 6. mirror_left_poses_to_right bit-exactness on a real BatchedSkinning rig +# --------------------------------------------------------------------------- + + +def _build_synthetic_soma_hand_pair(): + """Build a paired left/right 25-joint BatchedSkinning rig using py-soma-x.""" + from soma.geometry.batched_skinning import BatchedSkinning + from soma.geometry.rig_utils import PoseMirror_SOMA + + # 1 wrist (0) + 5 fingers x 4-5 joints = 25 joints (chain tree matching hand topology). + parent_ids = [0] + for finger_idx in range(5): + base = len(parent_ids) + parent_ids.append(0) # metacarpal/MCP attached to wrist + for seg in range(1, 4 if finger_idx == 0 else 5): + parent_ids.append(base + seg - 1) + # Trim/pad to exactly 25 joints: 1 + 4 + 5 + 5 + 5 + 5 = 25. + assert len(parent_ids) == 25 + + left_names = ["LeftHand"] + [f"LeftFinger{i:02d}" for i in range(1, 25)] + right_names = ["RightHand"] + [f"RightFinger{i:02d}" for i in range(1, 25)] + + rng = np.random.default_rng(777) + + def make_layer(side, joint_names): + # Distinct non-zero bone offsets and non-trivial joint orientations. + bind_world = torch.eye(4, dtype=torch.float32).repeat(25, 1, 1) + t_pose_world = torch.eye(4, dtype=torch.float32).repeat(25, 1, 1) + rots_bind = Rotation.random(25, random_state=rng).as_matrix().astype(np.float32) + rots_t = Rotation.random(25, random_state=rng).as_matrix().astype(np.float32) + bind_world[:, :3, :3] = torch.from_numpy(rots_bind) + t_pose_world[:, :3, :3] = torch.from_numpy(rots_t) + sign = 1.0 if side == "left" else -1.0 + for j in range(1, 25): + bind_world[j, :3, 3] = torch.tensor( + [sign * 0.02 * j, 0.01 * (j % 5), -0.005 * j], dtype=torch.float32 + ) + t_pose_world[j, :3, 3] = bind_world[j, :3, 3] + + skinning_weights = torch.zeros(10, 25, dtype=torch.float32) + skinning_weights[:, 0] = 1.0 + bind_shape = torch.zeros(10, 3, dtype=torch.float32) + skinning = BatchedSkinning( + joint_parent_ids=parent_ids, + skinning_weights=skinning_weights, + bind_world_transforms=bind_world, + bind_shapes=bind_shape, + joint_orient=t_pose_world, + mode="torch", + global_translation_joint_idx=0, + ) + + class _Layer: + def __init__(self): + self.batched_skinning = skinning + self.bind_pose_world = bind_world + self.t_pose_world = t_pose_world + self.joint_parent_ids = torch.tensor(parent_ids, dtype=torch.long) + self.rig_data = {"joint_names": joint_names} + self.prepare_identity_called = False + self.pose_called = False + + def prepare_identity(self, *args, **kwargs): + self.prepare_identity_called = True + raise AssertionError("prepare_identity must not be called") + + def pose(self, *args, **kwargs): + self.pose_called = True + raise AssertionError("pose must not be called") + + return _Layer() + + left_layer = make_layer("left", left_names) + right_layer = make_layer("right", right_names) + paired_names = ["Root"] + left_names + right_names + pose_mirror = PoseMirror_SOMA(paired_names, root_name="Root") + return left_layer, right_layer, pose_mirror + + +def test_mirror_left_poses_to_right_bit_exact_without_prepare_identity(): + from soma.geometry.rig_utils import ( + joint_world_to_local, + precompute_joint_orient, + remove_joint_orient_local, + ) + + left_layer, right_layer, pose_mirror = _build_synthetic_soma_hand_pair() + rng = np.random.default_rng(888) + bsz = 11 + poses = torch.from_numpy( + Rotation.random(bsz * 25, random_state=rng) + .as_matrix() + .astype(np.float32) + .reshape(bsz, 25, 3, 3) + ) + transl = torch.from_numpy(rng.normal(size=(bsz, 3)).astype(np.float32)) + + # Simulate a previously cached batched rebind on left_layer with a DIFFERENT + # batch size (B=4 != 11) and scaled bone lengths, proving mirror_left_poses_to_right + # is independent of mutable cached state on left_layer.batched_skinning! + scaled_bind = left_layer.bind_pose_world.unsqueeze(0).expand(4, -1, -1, -1).clone() + scaled_bind[..., :3, 3] *= 1.37 + left_layer.batched_skinning.rebind( + scaled_bind, torch.zeros(4, 10, 3, dtype=torch.float32) + ) + + got_poses, got_transl = mirror_left_poses_to_right( + left_layer, right_layer, poses, transl, pose_mirror=pose_mirror + ) + assert not left_layer.prepare_identity_called + assert not left_layer.pose_called + + # Reference: run full forward_kinematics with non-zero bone lengths + PoseMirror_SOMA. + left_layer.batched_skinning.rebind( + left_layer.bind_pose_world, torch.zeros(10, 3, dtype=torch.float32) + ) + left_transforms = left_layer.batched_skinning.forward_kinematics( + local_rotations=poses, + global_translation=transl, + absolute_pose=False, + ) + paired = torch.eye(4, dtype=torch.float32).expand(bsz, 51, 4, 4).clone() + paired[:, 1:26] = left_transforms + right_transforms = pose_mirror(paired)[:, 26:] + right_local = joint_world_to_local(right_transforms, right_layer.joint_parent_ids) + ref_transl = right_transforms[:, 0, :3, 3].clone() + orient, orient_parent_T = precompute_joint_orient( + right_layer.t_pose_world, right_layer.joint_parent_ids + ) + ref_poses = remove_joint_orient_local( + right_local[:, :, :3, :3], orient, orient_parent_T + ) + + torch.testing.assert_close(got_poses, ref_poses, rtol=0, atol=0) + torch.testing.assert_close(got_transl, ref_transl, rtol=0, atol=0) + + +# --------------------------------------------------------------------------- +# 7. defer_geometry=True contract: EgoHand.forward_step_decode, SomaBatcher, Predictor +# --------------------------------------------------------------------------- + + +def test_egohand_forward_step_decode_guards_none_pred_vertices(): + model = EgoHand.__new__(EgoHand) + torch.nn.Module.__init__(model) + model.camera_mode = "sam3db_perspective" + model.camera_depth_mode = "s" + model.camera_log_value_bounds = (-10.0, 10.0) + model.use_kp2d_translation = False + model.kp2d_min_depth = 1e-4 + model.focal_length = 5000.0 + model.image_size = 256 + + bsz = 2 + K = torch.tensor( + [[500.0, 0.0, 320.0], [0.0, 500.0, 240.0], [0.0, 0.0, 1.0]] + ).expand(bsz, 3, 3) + joints = torch.zeros(bsz, 25, 3) + verts = torch.ones(bsz, 7, 3) + + def make_head(): + return { + "output": {}, + "pred_cam": torch.tensor([[1.0, 0.1, -0.2], [0.8, -0.1, 0.3]]), + "direct_kp2d_output": None, + "batch_size": bsz, + "device": torch.device("cpu"), + "train": False, + "un_rotate": True, + "aug_rot": torch.tensor([15.0, -30.0]), + "is_full_perspective": True, + "img_wh": torch.tensor([[640.0, 480.0], [640.0, 480.0]]), + "box_center": torch.tensor([[320.0, 240.0], [300.0, 220.0]]), + "box_size": torch.tensor([200.0, 180.0]), + "focal": torch.tensor([500.0, 500.0]), + "K_fullimg": K.clone(), + } + + out_none = model.forward_step_decode(make_head(), joints.clone(), None) + out_real = model.forward_step_decode(make_head(), joints.clone(), verts.clone()) + + assert out_none["pred_vertices"] is None + assert out_real["pred_vertices"].shape == (bsz, 7, 3) + torch.testing.assert_close( + out_none["pred_cam_t"], out_real["pred_cam_t"], rtol=0, atol=0 + ) + torch.testing.assert_close( + out_none["pred_keypoints_2d"], out_real["pred_keypoints_2d"], rtol=0, atol=0 + ) + + +class _DeferContractModel: + def __init__(self, *, camera_mode="sam3db_perspective", use_kp2d_translation=False): + self.camera_mode = camera_mode + self.use_kp2d_translation = use_kp2d_translation + self.kp2d_min_depth = 1e-4 + self.soma_hand = _TrackingSomaHand() + + def forward_step_head(self, batch, train=False): + value = batch["img"][:, 0, 0, 0] + bsz = value.shape[0] + # Deterministic proper rotations from axis-angle so smoothing is well-posed. + angles = value.cpu().numpy() * 0.05 + mats = np.stack( + [ + np.broadcast_to( + Rotation.from_rotvec([a, -0.5 * a, 0.25 * a]) + .as_matrix() + .astype(np.float32), + (25, 3, 3), + ).copy() + for a in angles + ], + axis=0, + ) + poses = torch.from_numpy(mats).to(value.device) + scale_params = torch.stack( + [1.0 + 0.01 * value, 0.02 * value, -0.01 * value], dim=1 + ).float() + identity = torch.stack([0.05 * value] * 5, dim=1).float() + params = { + "wrist_orient": poses[:, :1].clone(), + "hand_pose": poses[:, 1:].clone(), + "identity_coeffs": identity, + "scale_params": scale_params, + } + pred_cam = torch.stack( + [torch.full_like(value, 1.2), 0.01 * value, -0.01 * value], dim=1 + ).float() + cam_t = torch.stack( + [0.02 * value, -0.01 * value, 0.8 + 0.01 * value], dim=1 + ).float() + return { + "batch_size": bsz, + "soma_inputs": { + "poses": poses.clone(), + "identity_coeffs": identity.clone(), + "global_scale": scale_params[:, 0].clone(), + "scale_params": scale_params[:, 1:].clone(), + }, + "params": params, + "pred_cam": pred_cam, + "cam_t": cam_t, + } + + def forward_step(self, batch, train=False): + head = self.forward_step_head(batch, train=train) + out = self.soma_hand(hand_type="left", pose2rot=False, **head["soma_inputs"]) + return self.forward_step_decode(head, out["joints"], out["vertices"]) + + def forward_step_decode(self, head, joints, vertices): + bsz = head["batch_size"] + cam_t = head["cam_t"] + if self.use_kp2d_translation: + # Depend on FK joints to verify real FK joints were provided! + cam_t = cam_t + joints[:, 0] * 0.1 + kp2d = joints[..., :2] * 0.01 + valid = torch.ones(bsz, 25, dtype=torch.bool) + return { + "pred_vertices": vertices, + "pred_keypoints_3d": joints, + "pred_cam": head["pred_cam"], + "pred_cam_t": cam_t, + "pred_keypoints_2d": kp2d, + "pred_projection_valid": valid, + "pred_hand_params": head["params"], + } + + +class _TrackingSomaLayer: + def __init__(self, side): + self.side = side + self.prepare_calls = [] + self.pose_calls = [] + self.bind_shape = torch.zeros(7, 3) + self.bind_pose_world = torch.eye(4).expand(25, 4, 4).clone() + self._cached_gs = None + + def prepare_identity( + self, + identity_coeffs, + scale_params=None, + repose_to_bind_pose=True, + global_scale=1.0, + ): + self.prepare_calls.append( + { + "rows": identity_coeffs.shape[0], + "repose_to_bind_pose": repose_to_bind_pose, + } + ) + self._cached_id = identity_coeffs + self._cached_gs = global_scale + + def pose( + self, + poses, + pose2rot=True, + apply_correctives=False, + absolute_pose=False, + global_translation=None, + fk_only=False, + ): + self.pose_calls.append( + { + "rows": poses.shape[0], + "apply_correctives": apply_correctives, + "fk_only": fk_only, + } + ) + joints = ( + poses[:, :, :, 0] * self._cached_gs[:, None, None] + + self._cached_id[:, :1, None] + ) + return {"joints": joints} + + +class _TrackingSomaHand: + def __init__(self): + self.left = _TrackingSomaLayer("left") + self.right = _TrackingSomaLayer("right") + self.forward_calls = [] + + def __call__( + self, + poses, + identity_coeffs, + hand_type, + transl=None, + pose2rot=False, + global_scale=1.0, + scale_params=None, + ): + self.forward_calls.append((hand_type, poses.shape[0])) + joints = ( + poses[:, :, :, 0] * global_scale[:, None, None] + + identity_coeffs[:, :1, None] + ) + verts = joints[:, :7] + ( + scale_params[:, :1, None] if scale_params is not None else 0.0 + ) + return {"joints": joints, "vertices": verts} + + +def _make_batch_inputs(hands): + K = np.array( + [[500.0, 0.0, 320.0], [0.0, 500.0, 240.0], [0.0, 0.0, 1.0]], dtype=np.float32 + ) + return [ + { + "image_id": f"f{i // 2:03d}", + "real_hand_side": hand, + "crop_tensor": torch.full((3, 8, 8), float(i + 1)), + "model_bbx_xys": np.array([320.0, 240.0, 150.0], np.float32), + "model_K": K.copy(), + "model_img_size": np.array([640.0, 480.0], np.float32), + "output_bbx_xys": np.array([320.0, 240.0, 150.0], np.float32), + "output_K": K.copy(), + } + for i, hand in enumerate(hands) + ] + + +@pytest.mark.parametrize("group_rows", [0, 6]) +@pytest.mark.parametrize("camera_mode", ["sam3db_perspective", "weak_perspective"]) +def test_soma_batcher_defer_geometry_no_kp2d(monkeypatch, group_rows, camera_mode): + mirror_pose_calls = [] + + def _fake_mirror_poses(left_layer, right_layer, poses, transl, *, pose_mirror=None): + mirror_pose_calls.append(poses.shape[0]) + return poses.clone(), transl * torch.tensor([-1.0, 1.0, 1.0]) + + monkeypatch.setattr( + "inference.pipeline.soma_batching.mirror_left_poses_to_right", + _fake_mirror_poses, + ) + + predictor = EgoHandPredictor.__new__(EgoHandPredictor) + predictor.batch_size = 3 + predictor.device = "cpu" + predictor.dtype = torch.float32 + predictor.model = _DeferContractModel( + camera_mode=camera_mode, use_kp2d_translation=False + ) + predictor._pose_mirror = None + predictor.soma_batch_size = group_rows + + hands = ["left", "right", "left", "left", "left", "right", "right"] + batcher = SomaBatcher(predictor, group_rows=group_rows, defer_geometry=True) + for batch_hand_data, staged in predictor._batch_source(_make_batch_inputs(hands)): + batch = predictor._assemble_batch(batch_hand_data, staged) + head = predictor.model.forward_step_head(batch, train=False) + batch.pop("img") + batcher.add(batch, batch_hand_data, head) + preds = batcher.finish() + + # Zero SOMA forward/FK calls! + assert batcher.left_calls == 0 + assert predictor.model.soma_hand.forward_calls == [] + assert predictor.model.soma_hand.left.prepare_calls == [] + # Right poses mirrored WITHOUT padding to group_rows! + assert sum(mirror_pose_calls) == 3 + if group_rows > 0: + assert mirror_pose_calls == [3] + + assert len(preds) == len(hands) + for p in preds: + assert p["pred_vertices"] is None + assert p["pred_keypoints_3d"] is None + assert p["pred_keypoints_2d"] is None + assert p["pred_projection_valid"] is None + assert p["poses"].shape == (25, 3, 3) + assert p["transl"].shape == (3,) + assert np.isfinite(p["transl"]).all() + + if camera_mode == "weak_perspective": + # Verify pred_cam_t was still converted via compute_transl_full_cam for left hand. + K_t = torch.from_numpy(preds[0]["K_fullimg"]).unsqueeze(0).float() + bbx_t = torch.tensor([[320.0, 240.0, 150.0]], dtype=torch.float32) + pred_cam_0 = torch.tensor([[1.2, 0.01, -0.01]], dtype=torch.float32) + expected_t = compute_transl_full_cam(pred_cam_0, bbx_t, K_t)[0].numpy() + np.testing.assert_allclose(preds[0]["transl"], expected_t, rtol=1e-6, atol=1e-6) + + +def test_soma_batcher_defer_geometry_with_kp2d_uses_fk_only(monkeypatch): + def _fake_mirror_poses(left_layer, right_layer, poses, transl, *, pose_mirror=None): + return poses.clone(), transl * torch.tensor([-1.0, 1.0, 1.0]) + + monkeypatch.setattr( + "inference.pipeline.soma_batching.mirror_left_poses_to_right", + _fake_mirror_poses, + ) + + predictor = EgoHandPredictor.__new__(EgoHandPredictor) + predictor.batch_size = 2 + predictor.device = "cpu" + predictor.dtype = torch.float32 + predictor.model = _DeferContractModel( + camera_mode="sam3db_perspective", use_kp2d_translation=True + ) + predictor._pose_mirror = None + predictor.soma_batch_size = 4 + + hands = ["left", "right", "left", "right"] + batcher = SomaBatcher(predictor, group_rows=4, defer_geometry=True) + for batch_hand_data, staged in predictor._batch_source(_make_batch_inputs(hands)): + batch = predictor._assemble_batch(batch_hand_data, staged) + head = predictor.model.forward_step_head(batch, train=False) + batch.pop("img") + batcher.add(batch, batch_hand_data, head) + preds = batcher.finish() + + # LBS soma_hand() was never called; left_layer ran prepare_identity(repose=False) + # + pose(apply_correctives=False, fk_only=True) exactly once for 4 rows. + assert predictor.model.soma_hand.forward_calls == [] + assert predictor.model.soma_hand.left.prepare_calls == [ + {"rows": 4, "repose_to_bind_pose": False} + ] + assert predictor.model.soma_hand.left.pose_calls == [ + {"rows": 4, "apply_correctives": False, "fk_only": True} + ] + assert batcher.left_calls == 1 + assert len(preds) == 4 + for p in preds: + assert p["pred_vertices"] is None + assert p["pred_keypoints_3d"] is None + assert p["pred_keypoints_2d"] is None + assert p["pred_projection_valid"] is None + + +def test_predictor_run_single_pass_smooth_perspective_skips_duplicate_projection( + monkeypatch, +): + def _fake_mirror_poses(left_layer, right_layer, poses, transl, *, pose_mirror=None): + return poses.clone(), transl * torch.tensor([-1.0, 1.0, 1.0]) + + def _fake_mirror_full( + model, + poses, + transl, + identity_coeffs, + global_scale, + K_fullimg, + bbx_xys, + scale_params=None, + pose_mirror=None, + ): + r_poses, r_transl = _fake_mirror_poses( + model.soma_hand.left, model.soma_hand.right, poses, transl + ) + out = model.soma_hand( + poses=r_poses, + identity_coeffs=identity_coeffs, + hand_type="right", + transl=None, + pose2rot=False, + global_scale=global_scale, + scale_params=scale_params, + ) + return { + "pred_vertices": out["vertices"], + "transl": r_transl, + "pred_keypoints_3d": out["joints"], + "pred_keypoints_2d": torch.zeros(poses.shape[0], 25, 2), + "pred_projection_valid": torch.ones(poses.shape[0], 25, dtype=torch.bool), + "poses": r_poses, + } + + monkeypatch.setattr( + "inference.pipeline.soma_batching.mirror_left_poses_to_right", + _fake_mirror_poses, + ) + monkeypatch.setattr( + "inference.pipeline.soma_batching.mirror_left_prediction_to_right", + _fake_mirror_full, + ) + monkeypatch.setattr( + "inference.pipeline.predictor.mirror_left_prediction_to_right", + _fake_mirror_full, + ) + + inner_camera = load_camera_calibration( + { + "model": "PINHOLE", + "image_width": 640, + "image_height": 480, + "camera_matrix": { + "matrix_3x3": [ + [500.0, 0.0, 320.0], + [0.0, 500.0, 240.0], + [0.0, 0.0, 1.0], + ] + }, + "distortion_coefficients": [], + } + ) + + class _CountingCamera: + def __init__(self, inner): + self._inner = inner + self.K = inner.K + self.width = inner.width + self.height = inner.height + self.model_name = inner.model_name + self.project_calls = 0 + + def project(self, rays): + self.project_calls += 1 + return self._inner.project(rays) + + def unproject(self, pixels): + return self._inner.unproject(pixels) + + rng = np.random.default_rng(11) + n_frames = 6 + image_ids = [f"f{i:03d}" for i in range(n_frames)] + images = [rng.integers(0, 255, (480, 640, 3), dtype=np.uint8) for _ in image_ids] + bboxes = { + fid: { + "left": np.array([220.0 + i, 240.0, 160.0], dtype=np.float32), + "right": np.array([420.0 - i, 240.0, 160.0], dtype=np.float32), + } + for i, fid in enumerate(image_ids) + } + frame_times = {fid: i / 30.0 for i, fid in enumerate(image_ids)} + + cam_single = _CountingCamera(inner_camera) + predictor = EgoHandPredictor.__new__(EgoHandPredictor) + predictor.batch_size = 2 + predictor.soma_batch_size = 8 + predictor.device = "cpu" + predictor.dtype = torch.float32 + predictor.smooth = True + predictor.perf_reporter = None + predictor.model = _DeferContractModel( + camera_mode="sam3db_perspective", use_kp2d_translation=False + ) + predictor._pose_mirror = None + predictor._use_perspective_cropping = True + predictor._model_wrist_orients = {"left": np.eye(3), "right": np.eye(3)} + predictor.stream_crops = False + + got = predictor.run( + images, + image_ids, + {k: dict(v) for k, v in bboxes.items()}, + ["left", "right"], + intrinsics_per_image=dict.fromkeys(image_ids, cam_single), + frame_times=frame_times, + ) + + # Single-pass SOMA: soma_hand ran ONLY in smooth_adaptive_hand_results, with + # batch_size = max(2, 8) = 8 -> 1 call per hand of size 6 (not B=2 -> 3 calls!). + assert predictor.model.soma_hand.forward_calls == [("left", 6), ("right", 6)] + + # Verify duplicate per-frame projection in postprocess_results was SKIPPED: + # each perspective_crop calls camera.project? Let's check postprocess_results alone! + cam_post = _CountingCamera(inner_camera) + predictor.postprocess_results( + {h: {fid: dict(r) for fid, r in d.items()} for h, d in got.items()}, + image_ids, + {k: dict(v) for k, v in bboxes.items()}, + frame_times=frame_times, + intrinsics_per_image=dict.fromkeys(image_ids, cam_post), + ) + # 1 batched camera.project call per hand inside smooth_adaptive_hand_results, + # 0 duplicate calls after smoothing! + assert cam_post.project_calls == 2 + + # Compare against defer_smoothing=True + postprocess_results (two-pass reference). + ref_predictor = EgoHandPredictor.__new__(EgoHandPredictor) + ref_predictor.batch_size = 2 + ref_predictor.soma_batch_size = 8 + ref_predictor.device = "cpu" + ref_predictor.dtype = torch.float32 + ref_predictor.smooth = True + ref_predictor.perf_reporter = None + ref_predictor.model = _DeferContractModel( + camera_mode="sam3db_perspective", use_kp2d_translation=False + ) + ref_predictor._pose_mirror = None + ref_predictor._use_perspective_cropping = True + ref_predictor._model_wrist_orients = {"left": np.eye(3), "right": np.eye(3)} + ref_predictor.stream_crops = False + + ref = ref_predictor.run( + images, + image_ids, + {k: dict(v) for k, v in bboxes.items()}, + ["left", "right"], + intrinsics_per_image=dict.fromkeys(image_ids, inner_camera), + defer_smoothing=True, + ) + ref_predictor.postprocess_results( + ref, + image_ids, + {k: dict(v) for k, v in bboxes.items()}, + frame_times=frame_times, + intrinsics_per_image=dict.fromkeys(image_ids, inner_camera), + ) + + for hand in ("left", "right"): + for fid in image_ids: + for key in ( + "pred_vertices", + "pred_keypoints_3d", + "pred_keypoints_2d", + "pred_projection_valid", + "poses", + "transl", + ): + np.testing.assert_allclose( + got[hand][fid][key], + ref[hand][fid][key], + rtol=0, + atol=1e-6, + equal_nan=True, + ) + + +def test_postprocess_vectorized_source_projection_runs_when_needed(): + inner_camera = load_camera_calibration( + { + "model": "KB4", + "image_width": 640, + "image_height": 480, + "camera_matrix": { + "matrix_3x3": [ + [400.0, 0.0, 320.0], + [0.0, 400.0, 240.0], + [0.0, 0.0, 1.0], + ] + }, + "distortion_coefficients": [-0.02, 0.004, -0.001, 0.0001], + } + ) + K_pinhole = np.array( + [[400.0, 0.0, 320.0], [0.0, 400.0, 240.0], [0.0, 0.0, 1.0]], + dtype=np.float32, + ) + image_ids = [f"f{i:03d}" for i in range(5)] + frame_times = {fid: i / 30.0 for i, fid in enumerate(image_ids)} + bboxes = { + fid: {"left": np.array([320.0, 240.0, 180.0], dtype=np.float32)} + for fid in image_ids + } + + # Case A: smooth=False + _use_perspective_cropping=True -> vectorized projection runs once. + spy_a = _SpyCamera(inner_camera) + predictor_a = EgoHandPredictor.__new__(EgoHandPredictor) + predictor_a.batch_size = 2 + predictor_a.soma_batch_size = 0 + predictor_a.device = "cpu" + predictor_a.smooth = False + predictor_a.perf_reporter = None + predictor_a.model = SimpleNamespace(kp2d_min_depth=1e-4) + predictor_a._use_perspective_cropping = True + + res_a = { + "left": { + fid: _make_record(transl=[0.01 * i, 0.0, 0.7], deferred=False) + for i, fid in enumerate(image_ids) + } + } + predictor_a.postprocess_results( + res_a, + image_ids, + {k: dict(v) for k, v in bboxes.items()}, + intrinsics_per_image=dict.fromkeys(image_ids, spy_a), + ) + assert spy_a.call_sizes == [5 * 25] + for fid in image_ids: + assert res_a["left"][fid]["K_fullimg"] is None + assert res_a["left"][fid]["pred_projection_valid"].all() + + # Case B: smooth=True + source_cameras_per_image != None -> smoothing runs + # through pinhole K, then source camera projection runs once for all 5 frames! + spy_b = _SpyCamera(inner_camera) + predictor_b = EgoHandPredictor.__new__(EgoHandPredictor) + predictor_b.batch_size = 2 + predictor_b.soma_batch_size = 8 + predictor_b.device = "cpu" + predictor_b.smooth = True + predictor_b.perf_reporter = None + predictor_b.model = SimpleNamespace( + kp2d_min_depth=1e-4, soma_hand=_RowwiseStubSomaHand(num_verts=11) + ) + predictor_b._use_perspective_cropping = False + + res_b = { + "left": { + fid: _make_record( + transl=[0.01 * i, 0.0, 0.7], K_fullimg=K_pinhole, deferred=True + ) + for i, fid in enumerate(image_ids) + } + } + predictor_b.postprocess_results( + res_b, + image_ids, + {k: dict(v) for k, v in bboxes.items()}, + frame_times=frame_times, + intrinsics_per_image=dict.fromkeys(image_ids, K_pinhole), + source_cameras_per_image=dict.fromkeys(image_ids, spy_b), + ) + # 5 bbox-conversion calls (17x17=289 rays each) + 1 batched joint projection (5*25=125 rays). + assert spy_b.call_sizes[-1] == 5 * 25 + assert spy_b.call_sizes.count(5 * 25) == 1 + for fid in image_ids: + assert res_b["left"][fid]["K_fullimg"] is None + assert res_b["left"][fid]["pred_projection_valid"].all() + + +def test_predictor_run_smooth_with_soma_batch_size_zero_still_defers_geometry( + monkeypatch, +): + def _fake_mirror_poses(left_layer, right_layer, poses, transl, *, pose_mirror=None): + return poses.clone(), transl * torch.tensor([-1.0, 1.0, 1.0]) + + monkeypatch.setattr( + "inference.pipeline.soma_batching.mirror_left_poses_to_right", + _fake_mirror_poses, + ) + K = np.array( + [[500.0, 0.0, 320.0], [0.0, 500.0, 240.0], [0.0, 0.0, 1.0]], dtype=np.float32 + ) + rng = np.random.default_rng(19) + image_ids = [f"f{i:03d}" for i in range(4)] + images = [rng.integers(0, 255, (480, 640, 3), dtype=np.uint8) for _ in image_ids] + bboxes = { + fid: { + "left": np.array([220.0, 240.0, 160.0], dtype=np.float32), + "right": np.array([420.0, 240.0, 160.0], dtype=np.float32), + } + for fid in image_ids + } + frame_times = {fid: i / 30.0 for i, fid in enumerate(image_ids)} + + predictor = EgoHandPredictor.__new__(EgoHandPredictor) + predictor.batch_size = 2 + predictor.soma_batch_size = 0 + predictor.device = "cpu" + predictor.dtype = torch.float32 + predictor.smooth = True + predictor.perf_reporter = None + predictor.model = _DeferContractModel( + camera_mode="sam3db_perspective", use_kp2d_translation=False + ) + predictor._pose_mirror = None + predictor._use_perspective_cropping = False + predictor._model_wrist_orients = None + predictor.stream_crops = False + + out = predictor.run( + images, + image_ids, + bboxes, + ["left", "right"], + intrinsics_per_image=dict.fromkeys(image_ids, K), + frame_times=frame_times, + ) + # Only smoothing pass called soma_hand (with batch_size=2 -> two 2-row calls per hand). + assert predictor.model.soma_hand.forward_calls == [ + ("left", 2), + ("left", 2), + ("right", 2), + ("right", 2), + ] + for hand in ("left", "right"): + for fid in image_ids: + assert out[hand][fid]["pred_vertices"].shape == (7, 3) + assert out[hand][fid]["pred_keypoints_2d"].shape == (25, 2) + + +def test_soma_decode_and_batcher_disable_torchscript_optimized_execution(): + """SOMA decode & SomaBatcher must disable TorchScript's thread-local + profiling optimizer during MHR calls and restore caller state after.""" + observed = [] + + class _CheckingSomaHand: + def __call__(self, *, poses, identity_coeffs, hand_type, **kwargs): + observed.append( + ("decode", hand_type, torch._C._get_graph_executor_optimize()) + ) + n = poses.shape[0] + return { + "vertices": torch.zeros((n, 7, 3), dtype=torch.float32), + "joints": torch.zeros((n, 25, 3), dtype=torch.float32), + } + + records = [ + { + "poses": np.broadcast_to(np.eye(3, dtype=np.float32), (25, 3, 3)).copy(), + "identity_coeffs": np.zeros(5, dtype=np.float32), + "global_scale": np.array(1.0, dtype=np.float32), + "scale_params": np.zeros(26, dtype=np.float32), + "pred_vertices": None, + "pred_keypoints_3d": None, + } + for _ in range(3) + ] + with torch.jit.optimized_execution(True): + assert torch._C._get_graph_executor_optimize() is True + _decode_soma_batches(records, "left", _CheckingSomaHand(), "cpu", 4) + assert torch._C._get_graph_executor_optimize() is True + + assert observed == [("decode", "left", False)] + + # Verify SomaBatcher._flush_left disables optimized_execution during + # prepare_identity/pose (defer_geometry=True, use_kp2d_translation=True). + batcher_observed = [] + + class _CheckingLeftLayer: + def prepare_identity(self, *args, **kwargs): + batcher_observed.append( + ("prepare_identity", torch._C._get_graph_executor_optimize()) + ) + + def pose(self, poses, *args, **kwargs): + batcher_observed.append(("pose", torch._C._get_graph_executor_optimize())) + return { + "joints": torch.zeros( + (poses.shape[0], poses.shape[1], 3), dtype=torch.float32 + ) + } + + model = _DeferContractModel( + camera_mode="sam3db_perspective", use_kp2d_translation=True + ) + model.soma_hand.left = _CheckingLeftLayer() + predictor = EgoHandPredictor.__new__(EgoHandPredictor) + predictor.batch_size = 2 + predictor.soma_batch_size = 0 + predictor.device = "cpu" + predictor.dtype = torch.float32 + predictor.model = model + predictor._pose_mirror = None + + batcher = SomaBatcher(predictor, group_rows=0, defer_geometry=True) + batch = { + "bbx_xys": torch.tensor([[100.0, 100.0, 80.0]], dtype=torch.float32), + "K_fullimg": torch.eye(3, dtype=torch.float32).unsqueeze(0), + "img_size": torch.tensor([[256.0, 256.0]], dtype=torch.float32), + } + hand_data = [ + { + "image_id": "000000", + "real_hand_side": "left", + "output_K": np.eye(3, dtype=np.float32), + } + ] + head = model.forward_step_head( + {"img": torch.zeros((1, 3, 256, 256), dtype=torch.float32), **batch}, + train=False, + ) + with torch.jit.optimized_execution(True): + batcher.add(batch, hand_data, head) + batcher.finish() + assert torch._C._get_graph_executor_optimize() is True + + assert batcher_observed == [("prepare_identity", False), ("pose", False)] diff --git a/src/python/isaaccapture_egopost/inference/tests/visualization/__init__.py b/src/python/isaaccapture_egopost/inference/tests/visualization/__init__.py new file mode 100644 index 0000000000..60bf73b663 --- /dev/null +++ b/src/python/isaaccapture_egopost/inference/tests/visualization/__init__.py @@ -0,0 +1,2 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: LicenseRef-OpenMDW-1.1 diff --git a/src/python/isaaccapture_egopost/inference/tests/visualization/test_render_clip_threads.py b/src/python/isaaccapture_egopost/inference/tests/visualization/test_render_clip_threads.py new file mode 100644 index 0000000000..8ca7653ae5 --- /dev/null +++ b/src/python/isaaccapture_egopost/inference/tests/visualization/test_render_clip_threads.py @@ -0,0 +1,156 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: LicenseRef-OpenMDW-1.1 + +"""render_clip writes bbox_viz on a worker thread: same bytes, errors surface, no thread left behind. + +CPU only; no checkpoint. ``--no_mesh`` style (skeleton only), as in the documented example. +""" + +import hashlib +import threading +from concurrent.futures import Future + +import cv2 +import numpy as np +import pytest + +import inference.visualization.overlay as overlay + +HANDS = ["left", "right"] + + +def _clip(n=12, w=96, h=72, seed=0): + rng = np.random.default_rng(seed) + frames = [rng.integers(0, 256, (h, w, 3), dtype=np.uint8) for _ in range(n)] + names = [f"{i:06d}" for i in range(n)] + results, boxes = {}, {} + for k, hand in enumerate(HANDS): + results[hand], boxes[hand] = [], [] + for i in range(n): + if (i + k) % 5 == 4: # some frames without this hand + results[hand].append(None) + boxes[hand].append(None) + continue + box = np.array( + [30.0 + 2 * i + 10 * k, 36.0 - i, 40.0 + k], dtype=np.float32 + ) + kp = rng.uniform(-0.45, 0.45, (25, 2)).astype(np.float32) + results[hand].append({"pred_keypoints_2d": kp}) + boxes[hand].append(box) + K = np.array([[80.0, 0, w / 2], [0, 80.0, h / 2], [0, 0, 1]], dtype=np.float32) + faces = {hand: np.zeros((1, 3), dtype=np.int64) for hand in HANDS} + return frames, names, results, boxes, faces, K, w, h + + +def _render(out_dir, save_images=False): + frames, names, results, boxes, faces, K, w, h = _clip() + overlay.render_clip( + out_dir, + frames, + names, + results, + {}, + boxes, + faces, + HANDS, + w, + h, + K, + 30.0, + (1.0, 1.0, 0.9), + save_images, + True, + draw_skeleton=True, + no_mesh=True, + ) + + +def _decoded_md5(path): + cap = cv2.VideoCapture(str(path)) + out = [] + while True: + ok, frame = cap.read() + if not ok: + break + out.append(hashlib.md5(frame.tobytes()).hexdigest()) + cap.release() + return out + + +class _InlineExecutor: + """Runs the submitted job immediately on the calling thread (serial order).""" + + def __init__(self, *args, **kwargs): + pass + + def __enter__(self): + return self + + def __exit__(self, *exc): + return False + + def submit(self, fn, *args, **kwargs): + future = Future() + try: + future.set_result(fn(*args, **kwargs)) + except BaseException as exc: # noqa: BLE001 - mirrors ThreadPoolExecutor + future.set_exception(exc) + return future + + +def test_threaded_outputs_byte_identical_to_serial(tmp_path, monkeypatch): + _render(tmp_path / "threaded", save_images=True) + monkeypatch.setattr(overlay, "ThreadPoolExecutor", _InlineExecutor) + _render(tmp_path / "serial", save_images=True) + for name in ("bbox_viz.mp4", "fullimg_overlay.mp4"): + a = (tmp_path / "threaded" / name).read_bytes() + b = (tmp_path / "serial" / name).read_bytes() + assert a == b, name + assert len(_decoded_md5(tmp_path / "threaded" / name)) == 12 + assert _decoded_md5(tmp_path / "threaded" / name) == _decoded_md5( + tmp_path / "serial" / name + ) + for sub in ("bbox_viz", "fullimg_overlay"): + a = sorted(p.name for p in (tmp_path / "threaded" / sub).iterdir()) + b = sorted(p.name for p in (tmp_path / "serial" / sub).iterdir()) + assert a == b and len(a) == 12 + for name in a: + assert (tmp_path / "threaded" / sub / name).read_bytes() == ( + tmp_path / "serial" / sub / name + ).read_bytes() + + +def test_bbox_writer_error_is_raised(tmp_path, monkeypatch): + def boom(*args, **kwargs): + raise RuntimeError("bbox drawing failed") + + monkeypatch.setattr(overlay, "draw_bbox_on_image", boom) + with pytest.raises(RuntimeError, match="bbox drawing failed"): + _render(tmp_path / "out") + + +def test_fullimg_error_joins_bbox_worker(tmp_path, monkeypatch): + started = threading.Event() + real_draw = overlay.draw_bbox_on_image + + def slow_draw(*args, **kwargs): + started.set() + return real_draw(*args, **kwargs) + + def boom(*args, **kwargs): + started.wait(5) + raise ValueError("skeleton drawing failed") + + monkeypatch.setattr(overlay, "draw_bbox_on_image", slow_draw) + monkeypatch.setattr(overlay, "draw_hand_skeleton", boom) + before = {t.name for t in threading.enumerate()} + with pytest.raises(ValueError, match="skeleton drawing failed"): + _render(tmp_path / "out") + left = [ + t.name + for t in threading.enumerate() + if t.name.startswith("bbox-viz") and t.name not in before + ] + assert left == [] + # The worker finished its file before render_clip returned. + assert len(_decoded_md5(tmp_path / "out" / "bbox_viz.mp4")) == 12 diff --git a/src/python/isaaccapture_egopost/inference/visualization/overlay.py b/src/python/isaaccapture_egopost/inference/visualization/overlay.py index 6c8dc7d085..623d519854 100644 --- a/src/python/isaaccapture_egopost/inference/visualization/overlay.py +++ b/src/python/isaaccapture_egopost/inference/visualization/overlay.py @@ -7,6 +7,7 @@ render the bbox/crop/fullimg overlay videos after EgoHand hand inference. """ +from concurrent.futures import ThreadPoolExecutor from pathlib import Path import cv2 @@ -258,141 +259,166 @@ def _to_display(img): return cv2.resize(img, (out_W, out_H), interpolation=cv2.INTER_AREA) # --- Bbox visualization (both hands on same image) --- - colors = {"left": (0, 255, 0), "right": (255, 0, 0)} # green / blue (BGR) - bbox_viz_dir = out_dir / "bbox_viz" - bbox_writer = None - if save_images: - bbox_viz_dir.mkdir(parents=True, exist_ok=True) - if save_videos and len(frames) > 1: - bbox_writer = _open_video_writer(out_dir / "bbox_viz.mp4", out_W, out_H, fps) - for fi, frame in enumerate(frames): - vis = frame.copy() - for h in hands: - if bbx_per_hand[h][fi] is not None: - draw_bbox_on_image(vis, bbx_per_hand[h][fi], color=colors[h], label=h) - vis = _to_display(vis) + # It reads only ``frames`` and the boxes and writes only its own files, so it + # runs on a worker thread while this thread draws and encodes the crop and + # full-image overlays (renderers stay on this thread). Each file is still + # written frame by frame, in order, by one thread, so its bytes are unchanged. + def _write_bbox_viz(): + colors = {"left": (0, 255, 0), "right": (255, 0, 0)} # green / blue (BGR) + bbox_viz_dir = out_dir / "bbox_viz" + bbox_writer = None if save_images: - cv2.imwrite(str(bbox_viz_dir / f"{frame_names[fi]}_bbox.jpg"), vis) - if bbox_writer is not None: - bbox_writer.write(vis) - if bbox_writer is not None: - bbox_writer.release() - msg_parts = [] - if save_images: - msg_parts.append(f"{bbox_viz_dir}/") - if bbox_writer is not None: - msg_parts.append(f"{out_dir / 'bbox_viz.mp4'}") - print(f"[render_clip] Bbox viz: {' + '.join(msg_parts)}") - - # --- Crop overlays (per hand, separate videos) --- - save_crop_images = save_images and save_crop_overlays - save_crop_videos = save_videos and save_crop_overlays - if not save_crop_overlays: - print( - "[render_clip] Crop overlays: skipped (pass --save_crop_overlays to enable)" - ) - for h in hands if save_crop_overlays else (): - results = results_per_hand[h] - crops, bbxs_viz, Ks_viz = crops_per_hand[h] - crop_out_dir = out_dir / f"crop_overlay_{h}" - if save_crop_images: - crop_out_dir.mkdir(parents=True, exist_ok=True) - crop_writer = None - if save_crop_videos and len(results) > 1: - crop_writer = _open_video_writer( - out_dir / f"crop_overlay_{h}.mp4", - IMG_SIZE, - IMG_SIZE, - fps, + bbox_viz_dir.mkdir(parents=True, exist_ok=True) + if save_videos and len(frames) > 1: + bbox_writer = _open_video_writer( + out_dir / "bbox_viz.mp4", out_W, out_H, fps ) - renderer = Renderer(focal_length=1.0, faces=faces_by_hand[h]) - for fi, (result, img_crop, bbx, K) in enumerate( - zip(results, crops, bbxs_viz, Ks_viz) - ): - if result is None or img_crop is None: - continue - if not (save_crop_images or crop_writer is not None): - continue - overlay = render_crop_overlay( - result, - img_crop, - bbx, - K, - faces_by_hand[h], - "egohand", - mesh_color=mesh_color, - renderer=renderer, + try: + for fi, frame in enumerate(frames): + vis = frame.copy() + for h in hands: + if bbx_per_hand[h][fi] is not None: + draw_bbox_on_image( + vis, bbx_per_hand[h][fi], color=colors[h], label=h + ) + vis = _to_display(vis) + if save_images: + cv2.imwrite(str(bbox_viz_dir / f"{frame_names[fi]}_bbox.jpg"), vis) + if bbox_writer is not None: + bbox_writer.write(vis) + finally: + if bbox_writer is not None: + bbox_writer.release() + msg_parts = [] + if save_images: + msg_parts.append(f"{bbox_viz_dir}/") + if bbox_writer is not None: + msg_parts.append(f"{out_dir / 'bbox_viz.mp4'}") + return f"[render_clip] Bbox viz: {' + '.join(msg_parts)}" + + def _write_crop_and_fullimg_overlays(): + # --- Crop overlays (per hand, separate videos) --- + save_crop_images = save_images and save_crop_overlays + save_crop_videos = save_videos and save_crop_overlays + if not save_crop_overlays: + print( + "[render_clip] Crop overlays: skipped (pass --save_crop_overlays to enable)" ) - overlay_bgr = cv2.cvtColor(overlay, cv2.COLOR_RGB2BGR) + for h in hands if save_crop_overlays else (): + results = results_per_hand[h] + crops, bbxs_viz, Ks_viz = crops_per_hand[h] + crop_out_dir = out_dir / f"crop_overlay_{h}" if save_crop_images: - cv2.imwrite( - str(crop_out_dir / f"{frame_names[fi]}_crop.jpg"), overlay_bgr + crop_out_dir.mkdir(parents=True, exist_ok=True) + crop_writer = None + if save_crop_videos and len(results) > 1: + crop_writer = _open_video_writer( + out_dir / f"crop_overlay_{h}.mp4", + IMG_SIZE, + IMG_SIZE, + fps, ) + renderer = Renderer(focal_length=1.0, faces=faces_by_hand[h]) + try: + for fi, (result, img_crop, bbx, K) in enumerate( + zip(results, crops, bbxs_viz, Ks_viz) + ): + if result is None or img_crop is None: + continue + if not (save_crop_images or crop_writer is not None): + continue + overlay = render_crop_overlay( + result, + img_crop, + bbx, + K, + faces_by_hand[h], + "egohand", + mesh_color=mesh_color, + renderer=renderer, + ) + overlay_bgr = cv2.cvtColor(overlay, cv2.COLOR_RGB2BGR) + if save_crop_images: + cv2.imwrite( + str(crop_out_dir / f"{frame_names[fi]}_crop.jpg"), + overlay_bgr, + ) + if crop_writer is not None: + crop_writer.write(overlay_bgr) + finally: + if crop_writer is not None: + crop_writer.release() + renderer.close() + msg_parts = [] + if save_crop_images: + msg_parts.append(f"{crop_out_dir}/") if crop_writer is not None: - crop_writer.write(overlay_bgr) - if crop_writer is not None: - crop_writer.release() - renderer.close() - msg_parts = [] - if save_crop_images: - msg_parts.append(f"{crop_out_dir}/") - if crop_writer is not None: - msg_parts.append(f"{out_dir / f'crop_overlay_{h}.mp4'}") - print(f"[render_clip] Crop overlays ({h}): {' + '.join(msg_parts)}") - - # --- Full-image overlays (both hands chained onto same frame) --- - full_renderers = ( - {} - if no_mesh - else {h: Renderer(focal_length=1.0, faces=faces_by_hand[h]) for h in hands} - ) - full_out_dir = out_dir / "fullimg_overlay" - full_writer = None - if save_images: - full_out_dir.mkdir(parents=True, exist_ok=True) - if save_videos and len(frames) > 1: - full_writer = _open_video_writer( - out_dir / "fullimg_overlay.mp4", out_W, out_H, fps + msg_parts.append(f"{out_dir / f'crop_overlay_{h}.mp4'}") + print(f"[render_clip] Crop overlays ({h}): {' + '.join(msg_parts)}") + + # --- Full-image overlays (both hands chained onto same frame) --- + full_renderers = ( + {} + if no_mesh + else {h: Renderer(focal_length=1.0, faces=faces_by_hand[h]) for h in hands} ) - skel_colors = {"left": (0, 255, 0), "right": (0, 0, 255)} - for fi, frame in enumerate(frames): - full_img_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) - for h in hands: - result = results_per_hand[h][fi] - if result is None: - continue - if not no_mesh: - full_img_rgb = draw_hand_mesh( - result, - full_img_rgb, - K_fullimg, - None, - faces_by_hand[h], - "egohand", - mesh_color=mesh_color, - renderer=full_renderers[h], - ) - if draw_skeleton: - draw_hand_skeleton( - full_img_rgb, - result["pred_keypoints_2d"], - skel_colors[h], - bbx_per_hand[h][fi], - ) - overlay_bgr = _to_display(cv2.cvtColor(full_img_rgb, cv2.COLOR_RGB2BGR)) + full_out_dir = out_dir / "fullimg_overlay" + full_writer = None if save_images: - cv2.imwrite( - str(full_out_dir / f"{frame_names[fi]}_fullimg.jpg"), overlay_bgr + full_out_dir.mkdir(parents=True, exist_ok=True) + if save_videos and len(frames) > 1: + full_writer = _open_video_writer( + out_dir / "fullimg_overlay.mp4", out_W, out_H, fps ) + skel_colors = {"left": (0, 255, 0), "right": (0, 0, 255)} + try: + for fi, frame in enumerate(frames): + full_img_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) + for h in hands: + result = results_per_hand[h][fi] + if result is None: + continue + if not no_mesh: + full_img_rgb = draw_hand_mesh( + result, + full_img_rgb, + K_fullimg, + None, + faces_by_hand[h], + "egohand", + mesh_color=mesh_color, + renderer=full_renderers[h], + ) + if draw_skeleton: + draw_hand_skeleton( + full_img_rgb, + result["pred_keypoints_2d"], + skel_colors[h], + bbx_per_hand[h][fi], + ) + overlay_bgr = _to_display(cv2.cvtColor(full_img_rgb, cv2.COLOR_RGB2BGR)) + if save_images: + cv2.imwrite( + str(full_out_dir / f"{frame_names[fi]}_fullimg.jpg"), + overlay_bgr, + ) + if full_writer is not None: + full_writer.write(overlay_bgr) + finally: + if full_writer is not None: + full_writer.release() + for r in full_renderers.values(): + r.close() + msg_parts = [] + if save_images: + msg_parts.append(f"{full_out_dir}/") if full_writer is not None: - full_writer.write(overlay_bgr) - if full_writer is not None: - full_writer.release() - for r in full_renderers.values(): - r.close() - msg_parts = [] - if save_images: - msg_parts.append(f"{full_out_dir}/") - if full_writer is not None: - msg_parts.append(f"{out_dir / 'fullimg_overlay.mp4'}") - print(f"[render_clip] Full-image overlays: {' + '.join(msg_parts)}") + msg_parts.append(f"{out_dir / 'fullimg_overlay.mp4'}") + return f"[render_clip] Full-image overlays: {' + '.join(msg_parts)}" + + # Leaving the pool joins the worker, also when this thread's overlays fail. + with ThreadPoolExecutor(max_workers=1, thread_name_prefix="bbox-viz") as pool: + bbox_viz_job = pool.submit(_write_bbox_viz) + fullimg_message = _write_crop_and_fullimg_overlays() + print(bbox_viz_job.result()) # re-raises a failure of the bbox writer + print(fullimg_message)