From d77cfafb2df0668944763c65ff21e753b7c67fd7 Mon Sep 17 00:00:00 2001 From: Hui Kang Date: Sat, 21 Nov 2026 20:08:46 -0800 Subject: [PATCH 1/3] fix(egopost): coalesce the MHR pose-corrective sparse matrix once at model load The MHR identity model of py-soma-x (MHR/mhr_model_lod1.pt, TorchScript) builds an uncoalesced COO tensor for its pose-correctives SparseLinear (3000 x 750, 53,136 non-zeros) on every forward, so every torch.matmul first coalesces it: thrust::sort_by_key = cub::DeviceMergeSort (1 block sort + 5 partition + 5 merge kernels, launched with programmatic dependent launch). The CCCL 3.0.1 merge kernel built into PyTorch 2.13.0+cu130 reads the partition table before cudaGridDependencySynchronize() (NVIDIA/cccl#5297, fixed in CCCL 3.0.3). With other kernels running in the same CUDA context it sometimes reads stale offsets and faults: "merge_sort: failed to synchronize: cudaErrorIllegalAddress", Xid 13 / Xid 31. With 2-3 EgoHand processes per GPU this happened about once per 230 clips on sm_120. inference/pipeline/mhr_presort.py: - PresortedMHR runs the TorchScript forward from Python (with autocast disabled to match TorchScript precision), calling the TorchScript submodules for every step except the sparse product, which uses a COO tensor built once with is_coalesced=True. The stored indices are already row-major without duplicates (checked once at load), so it is the same tensor the sort produced, followed by the same COO -> CSR + cuSPARSE product, without the sort kernels. - presort_mhr_sparse swaps it in for every MHR model under a module (the two SOMA hand layers), only if the TorchScript code of the rewritten methods matches the known code (sha256 for py-soma-x 0.3.0 with PyTorch 2.13.0) and the index check passes. - apply_mhr_presort: if any MHR model remains unpatched (e.g. after a py-soma-x or PyTorch update), it raises when the process is exposed to the race (presort_required: PyTorch built with CUDA 13.0 on an sm_90+ GPU) and only warns otherwise. EgoHandPredictor.from_checkpoint applies it (mhr_presorted_sparse=True) and logs what it patched, so the inference CLI, EgoHandInferencePipeline users and other callers of from_checkpoint are covered. --no-mhr_presorted_sparse keeps the TorchScript forward. Not covered: code that builds EgoHandPredictor(model=...) itself (it can call apply_mhr_presort(predictor.model, device)) and the keypoint-to-SOMA fitting tool, which loads MHR on its own. Same results: the network outputs are bitwise unchanged; the SOMA outputs differ only as much as two runs of the TorchScript forward differ from each other (cuSPARSE and skinning are not bitwise repeatable on CUDA). Cost: one TorchScript call becomes six calls of its submodules (about 0.4% slower end to end), and the unposed mesh stays referenced during skinning: GPU memory peak +108 MiB for one MHR call at 512 rows, +126 MiB whole-GPU peak with one EgoHand process. Tests: inference/tests/pipeline/test_mhr_presort.py. Signed-off-by: Hui Kang Co-Authored-By: Claude Code --- .../isaaccapture_egopost/inference/cli.py | 10 + .../inference/pipeline/mhr_presort.py | 292 ++++++++++++ .../inference/pipeline/predictor.py | 20 +- .../inference/scripts/README.md | 1 + .../scripts/run_egohand_inference_pipeline.py | 1 + .../tests/pipeline/test_mhr_presort.py | 430 ++++++++++++++++++ 6 files changed, 753 insertions(+), 1 deletion(-) create mode 100644 src/python/isaaccapture_egopost/inference/pipeline/mhr_presort.py create mode 100644 src/python/isaaccapture_egopost/inference/tests/pipeline/test_mhr_presort.py diff --git a/src/python/isaaccapture_egopost/inference/cli.py b/src/python/isaaccapture_egopost/inference/cli.py index a772fed6a8..4f0b343356 100644 --- a/src/python/isaaccapture_egopost/inference/cli.py +++ b/src/python/isaaccapture_egopost/inference/cli.py @@ -100,6 +100,16 @@ 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( + "--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, 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..a9f16e636f 100644 --- a/src/python/isaaccapture_egopost/inference/pipeline/predictor.py +++ b/src/python/isaaccapture_egopost/inference/pipeline/predictor.py @@ -133,6 +133,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: @@ -187,6 +189,7 @@ def from_checkpoint( dtype: torch.dtype = torch.float32, smooth: bool = False, use_perspective_cropping: bool = False, + mhr_presorted_sparse: bool = True, ) -> "EgoHandPredictor": """Load a checkpoint and return a ready-to-use predictor. @@ -203,13 +206,18 @@ def from_checkpoint( smooth: Enable adaptive parameter smoothing (default off). use_perspective_cropping: Use perspective cropping for each hand bbox before inference (default off). + 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) log.warning("[EgoHand] Model: %s (dtype=%s)", target, dtype) - return cls( + predictor = cls( model=model, batch_size=batch_size, device=device, @@ -217,6 +225,16 @@ def from_checkpoint( smooth=smooth, use_perspective_cropping=use_perspective_cropping, ) + 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( diff --git a/src/python/isaaccapture_egopost/inference/scripts/README.md b/src/python/isaaccapture_egopost/inference/scripts/README.md index 4fa59ee4ac..b3506f9973 100644 --- a/src/python/isaaccapture_egopost/inference/scripts/README.md +++ b/src/python/isaaccapture_egopost/inference/scripts/README.md @@ -136,6 +136,7 @@ pointed at different roots. | `--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 | | `--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/run_egohand_inference_pipeline.py b/src/python/isaaccapture_egopost/inference/scripts/run_egohand_inference_pipeline.py index a95878a941..6c1282cf14 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 @@ -707,6 +707,7 @@ def main(): dtype=dtype, smooth=args.postprocessing_smooth, use_perspective_cropping=use_perspective_cropping, + mhr_presorted_sparse=args.mhr_presorted_sparse, ) if args.dino_compile: predictor.enable_dino_compile() 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 From 5adbe5d6973319d3c6c27760c3c24a7f048c0f11 Mon Sep 17 00:00:00 2001 From: Hui Kang Date: Wed, 2 Dec 2026 06:44:34 -0800 Subject: [PATCH 2/3] perf(egopost): GPU RT-DETR/fisheye crop, single-pass SOMA 512, and streaming speed-ups Single-video inference speed-ups for EgoHand v1 stacked directly on PR #1691: - Streamed hand crops, background model loading, threaded bbox_viz.mp4 rendering, and safetensors inference weight export with strict key check and meta-device DINOv3 loading. - RT-DETR Pillow-exact CUDA preprocessing (with Pillow 13 V->H pass-order parity and PyTorch-optional fallback) + ONNX Runtime CUDA I/O Binding, plus BGR-first crop_uint8 and prefix-ROI right-hand mirroring without full-frame flip. - Bit-exact GPU perspective cropping for FISHEYE624, KB4, and PINHOLE cameras (FP64 Newton unprojection + fused Warp 5-bit bilinear remap with right-hand horizontal flip) and bounded-memory chunked PyAV video streaming with PTS-indexed SeekablePyAVFrames. - Single-pass SOMA batching (--soma_batch_size 512) with deferred pre-smooth geometry when adaptive smoothing is enabled, static-FK right-hand pose mirroring (mirror_left_poses_to_right), GPU FP64 Newton-Schulz adaptive smoothing, vectorized 2D keypoint reprojection, and TorchScript profiling optimizer disabled around SOMA MHR calls. Signed-off-by: Hui Kang Co-Authored-By: Claude Code --- .../egohand/models/backbones/dinov3.py | 27 +- .../egohand/models/egohand.py | 94 +- .../inference/camera/fisheye_crop_cuda.py | 1360 ++++++++++++++ .../isaaccapture_egopost/inference/cli.py | 42 +- .../rtdetr/PILLOW_LICENSE_NOTICE | 37 + .../hand_detector_2d/rtdetr/detector.py | 195 +- .../hand_detector_2d/rtdetr/onnx_model.py | 621 ++++++- .../rtdetr/pillow_exact_cuda.py | 417 +++++ .../hand_detector_2d/scripts/README.md | 1 + .../inference/media/_pyav_video.py | 525 ++++++ .../inference/perf/README.md | 12 +- .../inference/perf/collector.py | 41 +- .../inference/pipeline/crop_stream.py | 314 ++++ .../inference/pipeline/inference_weights.py | 311 ++++ .../inference/pipeline/predictor.py | 1358 +++++++++++--- .../inference/pipeline/soma_batching.py | 361 ++++ .../postprocessing/adaptive_smoothing.py | 887 ++++++++- .../inference/preprocessing/crop.py | 42 +- .../inference/preprocessing/mirroring.py | 297 +++- .../inference/scripts/README.md | 4 +- .../scripts/export_inference_weights.py | 102 ++ .../scripts/run_egohand_inference_pipeline.py | 109 +- .../inference/tests/camera/__init__.py | 2 + .../tests/camera/test_fisheye_crop_cuda.py | 879 +++++++++ .../tests/hand_detector_2d/__init__.py | 2 + .../test_pillow_exact_cuda.py | 623 +++++++ .../test_rtdetr_preprocess_threads.py | 124 ++ .../pipeline/test_background_load_exit.py | 102 ++ .../tests/pipeline/test_crop_stream.py | 411 +++++ .../tests/pipeline/test_inference_weights.py | 431 +++++ .../tests/pipeline/test_soma_batching.py | 236 +++ .../test_soma_single_pass_and_smooth.py | 1579 +++++++++++++++++ .../inference/tests/visualization/__init__.py | 2 + .../visualization/test_render_clip_threads.py | 156 ++ .../inference/visualization/overlay.py | 282 +-- 35 files changed, 11340 insertions(+), 646 deletions(-) create mode 100644 src/python/isaaccapture_egopost/inference/camera/fisheye_crop_cuda.py create mode 100644 src/python/isaaccapture_egopost/inference/hand_detector_2d/rtdetr/PILLOW_LICENSE_NOTICE create mode 100644 src/python/isaaccapture_egopost/inference/hand_detector_2d/rtdetr/pillow_exact_cuda.py create mode 100644 src/python/isaaccapture_egopost/inference/media/_pyav_video.py create mode 100644 src/python/isaaccapture_egopost/inference/pipeline/crop_stream.py create mode 100644 src/python/isaaccapture_egopost/inference/pipeline/inference_weights.py create mode 100644 src/python/isaaccapture_egopost/inference/pipeline/soma_batching.py create mode 100644 src/python/isaaccapture_egopost/inference/scripts/export_inference_weights.py create mode 100644 src/python/isaaccapture_egopost/inference/tests/camera/__init__.py create mode 100644 src/python/isaaccapture_egopost/inference/tests/camera/test_fisheye_crop_cuda.py create mode 100644 src/python/isaaccapture_egopost/inference/tests/hand_detector_2d/__init__.py create mode 100644 src/python/isaaccapture_egopost/inference/tests/hand_detector_2d/test_pillow_exact_cuda.py create mode 100644 src/python/isaaccapture_egopost/inference/tests/hand_detector_2d/test_rtdetr_preprocess_threads.py create mode 100644 src/python/isaaccapture_egopost/inference/tests/pipeline/test_background_load_exit.py create mode 100644 src/python/isaaccapture_egopost/inference/tests/pipeline/test_crop_stream.py create mode 100644 src/python/isaaccapture_egopost/inference/tests/pipeline/test_inference_weights.py create mode 100644 src/python/isaaccapture_egopost/inference/tests/pipeline/test_soma_batching.py create mode 100644 src/python/isaaccapture_egopost/inference/tests/postprocessing/test_soma_single_pass_and_smooth.py create mode 100644 src/python/isaaccapture_egopost/inference/tests/visualization/__init__.py create mode 100644 src/python/isaaccapture_egopost/inference/tests/visualization/test_render_clip_threads.py 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 4f0b343356..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,17 @@ 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, @@ -231,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/predictor.py b/src/python/isaaccapture_egopost/inference/pipeline/predictor.py index a9f16e636f..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(ckpt) - model.load_state_dict(ckpt["state_dict"], strict=False) - log.info("[EgoHand] Loaded checkpoint: %s", checkpoint_path) + model.validate_camera_depth_checkpoint(source.validation_view()) + if meta_backbone: + model.backbone.encoder.to_empty(device=device) + model = model.to(device) + + 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) @@ -169,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) @@ -182,13 +519,14 @@ 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. @@ -198,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. @@ -206,6 +545,7 @@ 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 @@ -215,7 +555,9 @@ def from_checkpoint( 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) predictor = cls( model=model, @@ -224,6 +566,7 @@ def from_checkpoint( 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 @@ -293,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) @@ -304,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. @@ -402,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) - ) + + def _keep_metadata(image_id, hand, prepared_hand_data): + prepared_inputs_by_image.setdefault(image_id, {})[hand] = prepared_hand_data + + 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 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, preprocessing_ms_per_frame + PerfStage.PREPROCESSING, + gpu_batches.crop_s * 1000 / len(image_ids), ) - - 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: + 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 %d hand crop(s)...", - len(prepared_inputs), + "[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: @@ -452,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 @@ -487,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, @@ -521,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)), ) @@ -556,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 @@ -661,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. @@ -674,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() @@ -724,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 @@ -797,127 +1203,41 @@ 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 @@ -929,3 +1249,471 @@ def _run_imagebased_predictions( 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 + ) + 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 _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 b3506f9973..ed50e9fedd 100644 --- a/src/python/isaaccapture_egopost/inference/scripts/README.md +++ b/src/python/isaaccapture_egopost/inference/scripts/README.md @@ -130,10 +130,12 @@ 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 | 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 6c1282cf14..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,16 +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 @@ -726,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( @@ -758,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 @@ -877,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}") @@ -884,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_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) From 0fbc343ba787f414dc02463abdbc2ed57a26b5f1 Mon Sep 17 00:00:00 2001 From: Hui Kang Date: Wed, 2 Dec 2026 06:44:34 -0800 Subject: [PATCH 3/3] feat(egopost): model-resident three-stage queue driver with GPU crop streaming Add run_egohand_three_stage.py and inference/pipeline/three_stage.py stacked on PR #1691 and PR #1692: - Model-resident queue driver supporting thr, serial, and proc modes with --claim_dir multi-worker coordination and graceful signal/error cleanup. - Deterministic --backbone_compile (block | whole), --backbone_bf16_weights, and --warp_mempool options (no FP8 quantization). - Automatic 3-regime Stage 1 streaming (shared H2D non-tracker, RAM-cached short clips <= 4 GiB, and 2-pass 8-thread PyAV bounded-RAM streaming with GPU FISHEYE624 perspective cropping), dedicated Stage 1 CUDA stream, CUDA IOBinding detector warm-up, and single-pass SOMA deferral in Stage 3. Signed-off-by: Hui Kang Co-Authored-By: Claude Code --- .../egohand/models/backbones/dinov3.py | 98 +- .../inference/camera/perspective_crop.py | 17 +- .../isaaccapture_egopost/inference/cli.py | 6 +- .../inference/pipeline/predictor.py | 55 +- .../inference/pipeline/three_stage.py | 2866 +++++++++++++++++ .../scripts/run_egohand_three_stage.py | 672 ++++ .../tests/pipeline/test_backbone_options.py | 518 +++ .../tests/pipeline/test_three_stage.py | 1132 +++++++ .../tests/pipeline/test_three_stage_driver.py | 115 + 9 files changed, 5449 insertions(+), 30 deletions(-) create mode 100644 src/python/isaaccapture_egopost/inference/pipeline/three_stage.py create mode 100644 src/python/isaaccapture_egopost/inference/scripts/run_egohand_three_stage.py create mode 100644 src/python/isaaccapture_egopost/inference/tests/pipeline/test_backbone_options.py create mode 100644 src/python/isaaccapture_egopost/inference/tests/pipeline/test_three_stage.py create mode 100644 src/python/isaaccapture_egopost/inference/tests/pipeline/test_three_stage_driver.py diff --git a/src/python/isaaccapture_egopost/egohand/models/backbones/dinov3.py b/src/python/isaaccapture_egopost/egohand/models/backbones/dinov3.py index 54b524e555..0911de0478 100644 --- a/src/python/isaaccapture_egopost/egohand/models/backbones/dinov3.py +++ b/src/python/isaaccapture_egopost/egohand/models/backbones/dinov3.py @@ -98,21 +98,57 @@ def __init__( # ModuleList, state_dict, and training paths remain unchanged. They are # created lazily by an eligible inference call. self._compiled_blocks = None + # Inference-only options (all off by default; see the methods below). + self._compile_scope = "block" + self._compile_options = None + self._compile_backend = "inductor" + self._compiled_whole = None - def enable_full_batch_compile(self, full_batch_size: int) -> None: - """Compile DINO blocks only for eval/no-grad batches of this exact size.""" + def enable_full_batch_compile( + self, + full_batch_size: int, + scope: str = "block", + options: dict | None = None, + backend: str = "inductor", + ) -> None: + """Compile the backbone only for eval/no-grad batches of this exact size. + + Args: + full_batch_size: Batch size taking the compiled path; tail batches stay eager. + scope: ``"block"`` compiles each transformer block separately; ``"whole"`` + compiles one graph from patch embedding through final norm. + options: Inductor options passed to ``torch.compile`` instead of + ``mode="default"``; ``None`` uses ``mode="default"``. + backend: ``torch.compile`` backend (tests use ``"eager"``). + """ if isinstance(full_batch_size, bool) or not isinstance(full_batch_size, int): raise TypeError("full_batch_size must be an integer") if full_batch_size <= 0: raise ValueError("full_batch_size must be positive") - if ( - self._compiled_blocks is not None - and self._compiled_full_batch_size != full_batch_size + if scope not in ("block", "whole"): + raise ValueError(f"scope must be 'block' or 'whole', got {scope!r}") + built = self._compiled_blocks is not None or self._compiled_whole is not None + if built and ( + self._compiled_full_batch_size != full_batch_size + or self._compile_scope != scope + or self._compile_options != options + or self._compile_backend != backend ): raise RuntimeError( - "cannot change full_batch_size after compiled wrappers are created" + "cannot change the compile settings after compiled wrappers are created" ) self._compiled_full_batch_size = full_batch_size + self._compile_scope = scope + self._compile_options = dict(options) if options is not None else None + self._compile_backend = backend + + def _compile_kwargs(self) -> dict: + kwargs = dict(backend=self._compile_backend, fullgraph=True, dynamic=False) + if self._compile_options is not None: + kwargs["options"] = dict(self._compile_options) + elif self._compile_backend == "inductor": + kwargs["mode"] = "default" + return kwargs def _ensure_inference_compiled_blocks(self): if self._compiled_blocks is None: @@ -121,19 +157,33 @@ def _ensure_inference_compiled_blocks(self): f"for B={self._compiled_full_batch_size}" ) self._compiled_blocks = [ - torch.compile( - block, - backend="inductor", - fullgraph=True, - dynamic=False, - mode="default", - ) + torch.compile(block, **self._compile_kwargs()) for block in self.encoder.blocks ] return self._compiled_blocks + def _ensure_inference_compiled_whole(self): + if self._compiled_whole is None: + Log.info( + "[DinoV3Backbone] Building eval-only static compiled backbone " + f"(one graph) for B={self._compiled_full_batch_size}" + ) + self._compiled_whole = torch.compile( + self._eager_spatial_features, **self._compile_kwargs() + ) + return self._compiled_whole + + def _eager_spatial_features(self, x: torch.Tensor) -> torch.Tensor: + """``_spatial_features`` over the plain blocks (compiled as one graph).""" + return self._spatial_features(x, self.encoder.blocks) + def _forward_compiled_spatial_features(self, x: torch.Tensor) -> torch.Tensor: - """Run the exact get_intermediate_layers(n=1) contract via compiled blocks.""" + """Run the exact get_intermediate_layers(n=1) contract via compiled code.""" + if self._compile_scope == "whole": + return self._ensure_inference_compiled_whole()(x) + return self._spatial_features(x, self._ensure_inference_compiled_blocks()) + + def _spatial_features(self, x: torch.Tensor, blocks) -> torch.Tensor: encoder = self.encoder tokens, (height, width) = encoder.prepare_tokens_with_masks(x) rope = ( @@ -141,7 +191,7 @@ def _forward_compiled_spatial_features(self, x: torch.Tensor) -> torch.Tensor: if encoder.rope_embed is not None else None ) - for block in self._ensure_inference_compiled_blocks(): + for block in blocks: tokens = block(tokens, rope) special_count = encoder.n_storage_tokens + 1 @@ -177,6 +227,24 @@ def forward(self, x: torch.Tensor) -> torch.Tensor: norm=True, )[-1] + # ------------------------------------------------------------------ + # Inference-only weight preparation (never used by training configs). + + def cast_matmul_weights_bf16(self) -> int: + """Cast encoder ``nn.Linear`` / ``nn.Conv2d`` weights and biases to bf16 once. + + Inference only: matches bf16 autocast while avoiding per-call casts and + halving weight memory; norms, layerscale, tokens, and RoPE remain fp32. + """ + count = 0 + for module in self.encoder.modules(): + if isinstance(module, (nn.Linear, nn.Conv2d)): + module.weight.data = module.weight.data.to(torch.bfloat16) + if module.bias is not None: + module.bias.data = module.bias.data.to(torch.bfloat16) + count += 1 + return count + def load_pretrained(self, ckpt_path: str) -> None: """Load a checkpoint with a `backbone.encoder.*` state_dict prefix into self.encoder. diff --git a/src/python/isaaccapture_egopost/inference/camera/perspective_crop.py b/src/python/isaaccapture_egopost/inference/camera/perspective_crop.py index 11eac11536..76abd6140a 100644 --- a/src/python/isaaccapture_egopost/inference/camera/perspective_crop.py +++ b/src/python/isaaccapture_egopost/inference/camera/perspective_crop.py @@ -15,6 +15,20 @@ def perspective_crop( bbox: np.ndarray, camera: CameraModel, crop_side_pixels: int, +) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]: + """``perspective_crop_uint8`` with the crop as float32 RGB divided by 255.""" + crop_rgb, K_virtual, bbox_virtual, crop_to_source_rotation = perspective_crop_uint8( + image_bgr, bbox, camera, crop_side_pixels + ) + crop_rgb = crop_rgb.astype(np.float32) / 255.0 + return crop_rgb, K_virtual, bbox_virtual, crop_to_source_rotation + + +def perspective_crop_uint8( + image_bgr: np.ndarray, + bbox: np.ndarray, + camera: CameraModel, + crop_side_pixels: int, ) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]: """Create a square perspective crop of a detected hand region. @@ -32,7 +46,7 @@ def perspective_crop( pixels. The caller sets it from the resolution its model consumes. Returns: - Tuple of the square RGB crop (float32, pixel values divided by 255), + Tuple of the square RGB crop (uint8; ``perspective_crop`` divides it by 255), virtual pinhole intrinsics, full-crop bbox ``[center_x, center_y, side_length]`` in crop pixels, and the rotation from crop-camera to source-camera coordinates, in that order. @@ -106,7 +120,6 @@ def perspective_crop( borderValue=0, ) crop_rgb = cv2.cvtColor(crop_bgr, cv2.COLOR_BGR2RGB) - crop_rgb = crop_rgb.astype(np.float32) / 255.0 K_virtual = np.array( [ [focal_length, 0, crop_center], diff --git a/src/python/isaaccapture_egopost/inference/cli.py b/src/python/isaaccapture_egopost/inference/cli.py index 737311be33..a177cc95b0 100644 --- a/src/python/isaaccapture_egopost/inference/cli.py +++ b/src/python/isaaccapture_egopost/inference/cli.py @@ -113,7 +113,11 @@ def parse_args(argv=None, *, epilog: str | None = None): "the eager path. Use for throughput-sensitive batch inference where " "most batches are full-size (e.g. long videos); skip it for small " "one-off runs, since torch.compile warm-up cost may exceed the " - "savings. Off by default, so it has no effect unless passed.", + "savings. Off by default, so it has no effect unless passed. Compiles " + 'with mode="default": Inductor picks some reduction block sizes by ' + "timing, so processes cold-compiling at the same time on one GPU can " + "give slightly different outputs (run_egohand_three_stage.py " + "--backbone_compile compiles deterministically).", ) p.add_argument( "--soma_batch_size", diff --git a/src/python/isaaccapture_egopost/inference/pipeline/predictor.py b/src/python/isaaccapture_egopost/inference/pipeline/predictor.py index 3b275e3269..2ffa747fb8 100644 --- a/src/python/isaaccapture_egopost/inference/pipeline/predictor.py +++ b/src/python/isaaccapture_egopost/inference/pipeline/predictor.py @@ -516,6 +516,25 @@ def enable_dino_compile(self) -> None: ) enable_compile(self.batch_size) + def enable_backbone_compile( + self, scope: str = "block", options: dict | None = None + ) -> None: + """Compile the DINO backbone for full batches: per block or as one graph. + + ``scope="block"`` with ``options=None`` is ``enable_dino_compile``. + ``options`` are Inductor options used instead of ``mode="default"``. + """ + if scope == "block" and options is None: + self.enable_dino_compile() + return + backbone = getattr(self.model, "backbone", None) + enable_compile = getattr(backbone, "enable_full_batch_compile", None) + if enable_compile is None: + raise RuntimeError( + "DINO compilation requires a DINOv3 backbone with compile support" + ) + enable_compile(self.batch_size, scope=scope, options=options) + @classmethod def from_checkpoint( cls, @@ -837,6 +856,30 @@ def _keep_metadata(image_id, hand, prepared_hand_data): defer_geometry=defer_geometry, ) + results_per_hand = self._results_per_hand( + predictions, hands, prepared_inputs_by_image + ) + + if not defer_smoothing: + self.postprocess_results( + results_per_hand, + image_ids, + bboxes_per_image, + frame_times=frame_times, + intrinsics_per_image=intrinsics_per_image, + source_cameras_per_image=source_cameras_per_image, + ) + if output_paths_per_hand is not None: + self.save_results(results_per_hand, output_paths_per_hand) + return results_per_hand + + def _results_per_hand(self, predictions, hands, prepared_inputs_by_image): + """``{hand: {image_id: result}}`` from the flat predictions, in their order. + + With perspective cropping, geometry, translation and wrist rotation go + back from the crop camera to source-camera axes + (``prepared_inputs_by_image[image_id][hand]`` holds the rotation). + """ results_per_hand = {hand: {} for hand in hands} for result in predictions: image_id = result["image_id"] @@ -871,18 +914,6 @@ def _keep_metadata(image_id, hand, prepared_hand_data): # A pinhole K cannot project source pixels with lens distortion. result["K_fullimg"] = None results_per_hand[hand][image_id] = result - - if not defer_smoothing: - self.postprocess_results( - results_per_hand, - image_ids, - bboxes_per_image, - frame_times=frame_times, - intrinsics_per_image=intrinsics_per_image, - source_cameras_per_image=source_cameras_per_image, - ) - if output_paths_per_hand is not None: - self.save_results(results_per_hand, output_paths_per_hand) return results_per_hand def _prepare_all_then_predict( diff --git a/src/python/isaaccapture_egopost/inference/pipeline/three_stage.py b/src/python/isaaccapture_egopost/inference/pipeline/three_stage.py new file mode 100644 index 0000000000..063dd1e362 --- /dev/null +++ b/src/python/isaaccapture_egopost/inference/pipeline/three_stage.py @@ -0,0 +1,2866 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: LicenseRef-OpenMDW-1.1 + +"""Model-resident EgoHand inference over a queue of videos, in three stages. + +The per-video work of ``run_egohand_inference_pipeline.py`` split so that the +stages work on different videos at once: + +1. prepare: whole-clip decode, detection + tracking, bbox JSONs, uint8 crops + (failed crops dropped where ``predictor.run`` drops them); +2. head: batches of valid crops in job order, normalized as + ``crop_and_preprocess`` does, ``forward_step_head`` under autocast; +3. soma: ``SomaBatcher`` (SOMA decode, mirror), then per clip the source-camera + rotation, adaptive smoothing and the results npz. Every SOMA call stays in + this stage, in single-video order. + +``ThreadedThreeStage`` runs stages 1-2 on threads (stage 2 on its own CUDA +stream) and stage 3 on the caller's thread; ``run_process_pipeline`` runs them +as three processes; ``run_serial`` runs them back to back. A Python error +fails only its video; a CUDA error aborts the run. +""" + +from __future__ import annotations + +import contextlib +import dataclasses +import io +import json +import logging +import os +import pickle +import queue +import signal +import threading +import time +import traceback +from concurrent.futures import ThreadPoolExecutor +from pathlib import Path +from typing import Any, Callable, Iterable, Iterator + +import numpy as np +import torch + +log = logging.getLogger(__name__) + +FPS_FALLBACK = 30.0 # inference.video_io.FPS_FALLBACK +_END = "__end_of_queue__" +# Default host RAM cap for Regime B frame caching (4 GiB). Clips above this +# threshold (or with unknown frame count) stream in 2 passes via PyAV (Regime C). +RAM_CACHE_BUDGET_BYTES = 4 * 1024**3 +STREAM_CHUNK_SIZE = 64 +PYAV_DECODE_THREADS = 8 + + +# --------------------------------------------------------------------------- data + + +@dataclasses.dataclass +class ClipRequest: + """One queue item. ``frames`` / ``camera`` / ``fps`` replace decoding (tests).""" + + index: int + name: str + video: str + intrinsics: str | None + out_root: str + frames: list | None = None + camera: Any = None + fps: float | None = None + + +@dataclasses.dataclass +class StageConfig: + """Per-run settings shared by the three stages.""" + + hands: list + use_perspective_cropping: bool + camera_mode: str + batch_size: int + smooth: bool + crop_workers: int = 8 + norm_workers: int = 4 + rectify_pixel_aspect_ratio: bool = True + perf_metadata: dict | None = None + + +@dataclasses.dataclass +class PreparedClip: + """Stage 1 output: everything later stages need, without the frames.""" + + request: ClipRequest + stem: str = "" + out_dir: Path | None = None + fps: float = FPS_FALLBACK + width: int = 0 + height: int = 0 + image_ids: list = dataclasses.field(default_factory=list) + frame_times: dict | None = None + bboxes_per_image: dict = dataclasses.field(default_factory=dict) + intrinsics_per_image: dict = dataclasses.field(default_factory=dict) + records: list = dataclasses.field(default_factory=list) + crops: Any = None # uint8 [N, 256, 256, 3] (list of arrays or one array) + crops_path: str | None = None # proc mode: .npy in shared memory + num_jobs: int = 0 + num_failed_crops: int = 0 + frame_regime: str | None = None + times: dict = dataclasses.field(default_factory=dict) + error: str | None = None + error_class: str | None = None + error_stage: str | None = None + error_traceback: str | None = None + began: bool = False + + def fail(self, stage: str, exc: BaseException) -> None: + if self.error is None: + self.error = f"{type(exc).__name__}: {exc}"[:2000] + self.error_class = type(exc).__name__ + self.error_stage = stage + self.error_traceback = traceback.format_exc()[-4000:] + + def without_pixels(self) -> "PreparedClip": + """Shallow copy for queues between processes: no crops, no camera objects. + + Camera models may hold Warp arrays (distorted cameras), so the receiving + process rebuilds ``intrinsics_per_image`` with ``resolve_clip_camera``. + """ + return dataclasses.replace(self, crops=None, intrinsics_per_image={}) + + def light(self) -> "PreparedClip": + """Shallow copy with only identity, times and error (end-of-clip messages).""" + return dataclasses.replace( + self, + crops=None, + records=[], + image_ids=[], + frame_times=None, + bboxes_per_image={}, + intrinsics_per_image={}, + ) + + +@dataclasses.dataclass +class HeadBatch: + """Stage 2 output for one forward batch.""" + + start: int # index of the batch's first record in ``PreparedClip.records`` + hand_data: list + batch: dict # _assemble_batch output without "img" + head: dict # forward_step_head output + event: Any = None # CUDA event recorded after the head on stage 2's stream + + +class UnsupportedOption(ValueError): + """A pipeline option the three-stage driver does not implement.""" + + +def is_fatal_cuda_error(exc: BaseException) -> bool: + """True for errors that leave the CUDA context unusable (not OOM).""" + if isinstance(exc, torch.cuda.OutOfMemoryError): + return False + accelerator_error = getattr(torch, "AcceleratorError", None) + if accelerator_error is not None and isinstance(exc, accelerator_error): + return True + text = f"{type(exc).__name__}: {exc}" + return any( + marker in text + for marker in ( + "CUDA error", + "cudaError", + "illegal memory access", + "CUBLAS_STATUS_EXECUTION_FAILED", + "CUDNN_STATUS_EXECUTION_FAILED", + "device-side assert", + "unspecified launch failure", + ) + ) + + +# --------------------------------------------------------------------------- stage 1 + + +def decode_all_frames(video_path: str) -> list: + """Every frame of the video, decoded by the active video backend + (``inference.video_io``, as ``run_egohand_inference_pipeline.py`` without + ``--frame_batch_size``).""" + from inference.video_io import read_video_frames_batched + + return [ + frame + for batch in read_video_frames_batched(str(video_path), 10**9) + for _, frame in batch + ] + + +def video_meta(video_path: str) -> dict: + """``inference.video_io.get_video_meta``.""" + from inference.video_io import get_video_meta + + return get_video_meta(str(video_path)) + + +def check_video_decodable(video_path, meta: dict) -> None: + """``run_egohand_inference_pipeline.check_video_decodable`` (raises instead of exiting). + + The first frame is read through the active video backend, which also + rejects an unsupported codec (``UnsupportedVideoCodecError``). + """ + from inference.video_io import read_video_frames_batched + + decodable = meta["width"] > 0 and meta["height"] > 0 + if decodable: + frames = read_video_frames_batched(str(video_path), 1, 1) + try: + decodable = next(frames, None) is not None + finally: + frames.close() + if not decodable: + raise RuntimeError( + f"Cannot read video {video_path}: no decodable video stream " + "(empty, truncated, or unsupported file)" + ) + + +def resolve_clip_camera(clip: "PreparedClip", use_perspective_cropping: bool): + """The camera stage 1 resolved for ``clip`` (same JSON, same ``resolve_K`` call).""" + from inference.camera.intrinsics import resolve_K + + request = clip.request + if request.camera is not None: + return request.camera + calibration = None + if request.intrinsics: + with open(request.intrinsics) as fh: + calibration = json.load(fh) + camera, _ = resolve_K( + clip.width, + clip.height, + calibration, + perspective_cropping=use_perspective_cropping, + calibration_source=( + f"calibration {request.intrinsics}" if request.intrinsics else None + ), + ) + return camera + + +def build_crop_record(job, *, use_perspective_cropping: bool, camera_mode: str): + """``predictor.run``'s ``_build_input`` with the crop kept as uint8 RGB. + + Returns ``(image_id, hand, record or None)``; the record holds ``crop_u8`` + (HWC, right hands already mirrored) instead of ``crop_tensor``. + ``normalize_crop(record["crop_u8"])`` has the values of ``crop_tensor``. + ``None`` is a failed perspective crop, skipped with the same warning. + """ + from inference.camera.perspective_crop import perspective_crop_uint8 + from inference.preprocessing.crop import IMG_SIZE, crop_uint8 + from inference.preprocessing.mirroring import ( + mirror_full_image_camera_horizontal, + prepare_right_hand_model_input_uint8, + ) + + image_id, hand, image_bgr, bbx_array, source_camera = job + if use_perspective_cropping: + try: + crop_u8, K_virtual, bbox_virtual, crop_to_source_rotation = ( + perspective_crop_uint8(image_bgr, bbx_array, source_camera, IMG_SIZE) + ) + except (FloatingPointError, ValueError) as exc: + log.warning( + "[Skip] %s %s: perspective cropping failed: %s", image_id, hand, exc + ) + return image_id, hand, None + model_bbx_xys = bbox_virtual + model_K = K_virtual + if hand == "right": + crop_u8 = np.ascontiguousarray(crop_u8[:, ::-1]) + model_bbx_xys, model_K = mirror_full_image_camera_horizontal( + model_bbx_xys, model_K, crop_u8.shape[1] + ) + return ( + image_id, + hand, + { + "image_id": image_id, + "real_hand_side": hand, + "crop_u8": crop_u8, + "model_bbx_xys": model_bbx_xys, + "model_K": model_K, + "model_img_size": np.array( + [crop_u8.shape[1], crop_u8.shape[0]], dtype=np.float32 + ), + "output_bbx_xys": bbox_virtual, + "output_K": K_virtual, + "crop_to_source_camera_rotation": crop_to_source_rotation, + }, + ) + K_fullimg = np.asarray(source_camera, dtype=np.float32) + image_width = image_bgr.shape[1] + image_height = image_bgr.shape[0] + model_bbx_xys = bbx_array.copy() + model_K = K_fullimg.copy() + if hand == "right": + crop_u8, model_bbx_xys, model_K = prepare_right_hand_model_input_uint8( + image_bgr, + model_bbx_xys, + model_K, + calibrated_full_image=camera_mode == "sam3db_perspective", + ) + else: + crop_u8 = crop_uint8(image_bgr, bbx_array) + return ( + image_id, + hand, + { + "image_id": image_id, + "real_hand_side": hand, + "crop_u8": crop_u8, + "model_bbx_xys": model_bbx_xys, + "model_K": model_K, + "model_img_size": np.array([image_width, image_height], dtype=np.float32), + "output_bbx_xys": bbx_array, + "output_K": K_fullimg, + }, + ) + + +def _write_bbox_jsons( + bbox_per_hand: dict[str, dict[str, np.ndarray]], + hands: list[str], + bbox_paths: dict[str, Path], +) -> None: + """Write per-hand bbox JSON files matching ``RTDetrHandBBoxDetector.run``.""" + for hand in hands: + bbox_dict = bbox_per_hand.get(hand, {}) + output_path = Path(bbox_paths[hand]) + output_path.parent.mkdir(parents=True, exist_ok=True) + payload = {k: [float(v) for v in b] for k, b in bbox_dict.items()} + with open(output_path, "w") as fh: + json.dump(payload, fh, indent=2) + log.info("[Saved] %s (%d image(s))", output_path, len(bbox_dict)) + + +def _bboxes_per_image_from_hand_dict( + image_ids: list[str], + bbox_per_hand: dict[str, dict[str, np.ndarray]], + hands: list[str], +) -> dict[str, dict[str, np.ndarray]]: + """Invert ``{hand: {image_id: bbox}}`` into ``{image_id: {hand: bbox}}``.""" + bboxes_per_image: dict[str, dict[str, np.ndarray]] = { + image_id: {} for image_id in image_ids + } + for hand in hands: + for image_id, bbox in bbox_per_hand.get(hand, {}).items(): + bboxes_per_image[image_id][hand] = np.asarray(bbox, dtype=np.float32) + return bboxes_per_image + + +def _detect_chunk_cuda_shared(detector, chunk_gpu: torch.Tensor, upload_event) -> list: + """Run RT-DETR directly on an already-uploaded ``(T, H, W, 3)`` CUDA batch.""" + inner = detector.detector + det_batch = max(1, int(getattr(detector, "batch_size", 8))) + detections: list = [] + lock_fn = getattr(detector, "_get_pipeline_lock", None) + lock_ctx = lock_fn() if callable(lock_fn) else contextlib.nullcontext() + with lock_ctx: + inf_stream = getattr(inner, "inference_stream", None) + if inf_stream is not None and chunk_gpu.is_cuda: + chunk_gpu.record_stream(inf_stream) + n_frames = int(chunk_gpu.shape[0]) + for start in range(0, n_frames, det_batch): + sub_gpu = chunk_gpu[start : start + det_batch] + prepared = inner.prepare_cuda_tensor(sub_gpu, ready_event=upload_event) + outputs = inner.run_onnx_prepared(prepared) + detections.extend( + inner.postprocess(*outputs, prepared.orig_target_sizes_cpu) + ) + return detections + + +def _track_clip_detections( + detector, + image_ids: list[str], + all_dets: list, + hands: list[str], + width: int, + height: int, + frame_times: dict[str, float] | None, + images_bgr, +) -> dict[str, dict[str, np.ndarray]]: + """Run whole-clip tracking (stock RT-DETR or track_cleanup) on raw detections.""" + from inference.hand_detector_2d.rtdetr.bbox_smoothing import validate_frame_times + + if hasattr(detector, "track_boxes"): + if frame_times is None or any(i not in frame_times for i in image_ids): + raise ValueError("track_cleanup requires frame_times for every image ID") + times = validate_frame_times( + [frame_times[i] for i in image_ids], len(image_ids) + ) + bbox_per_hand, info = detector.track_boxes( + image_ids, + all_dets, + hands, + (width, height), + frame_times=times, + images_bgr=images_bgr, + ) + if hasattr(detector, "log_tracking"): + detector.log_tracking(info, hands) + if hasattr(detector, "log_cleanup"): + detector.log_cleanup(info) + return bbox_per_hand + + from inference.hand_detector_2d.rtdetr.detector import boxes_from_tracks + + times = None + if getattr(detector, "smoothing", None) is not None: + if frame_times is None or any(i not in frame_times for i in image_ids): + raise ValueError("BBox smoothing requires frame_times for every image ID") + times = validate_frame_times( + [frame_times[i] for i in image_ids], len(image_ids) + ) + bbox_per_hand, info = boxes_from_tracks( + image_ids, + all_dets, + hands, + image_width=width, + enforce_lr_order=getattr(detector, "enforce_lr_order", True), + drop_gap_filled=getattr(detector, "drop_gap_filled", False), + smoothing=getattr(detector, "smoothing", None), + frame_times=times, + ) + if hasattr(detector, "log_tracking"): + detector.log_tracking(info, hands) + return bbox_per_hand + + +def _crop_frames_gpu_chunked( + frames, + gpu_crop_jobs: list[tuple[int, str, str, np.ndarray]], + camera, + *, + camera_mode: str, + device: torch.device, + stream, + chunk_frames: int, +) -> tuple[list[dict[str, Any]], list[np.ndarray], int]: + """Run ``fisheye_crop_cuda.crop_chunk_gpu`` over in-memory frames in bounded chunks.""" + from inference.camera.fisheye_crop_cuda import crop_chunk_gpu + from inference.preprocessing.crop import IMG_SIZE + + if not gpu_crop_jobs: + return [], [], 0 + + stream_ctx = ( + torch.cuda.stream(stream) if stream is not None else contextlib.nullcontext() + ) + records: list[dict[str, Any]] = [] + crops: list[np.ndarray] = [] + total_failed = 0 + chunk_limit = max(1, int(chunk_frames)) + chunk: list[tuple[int, str, str, np.ndarray]] = [] + seen_frames: set[int] = set() + + def _flush(active_chunk: list[tuple[int, str, str, np.ndarray]]) -> None: + nonlocal total_failed + with stream_ctx: + chunk_recs, chunk_crops, n_failed = crop_chunk_gpu( + frames, + active_chunk, + camera, + IMG_SIZE, + camera_mode=camera_mode, + device=device, + return_gpu_crops=False, + ) + records.extend(chunk_recs) + crops.extend(chunk_crops) + total_failed += n_failed + + for job in gpu_crop_jobs: + f_idx = job[0] + if f_idx not in seen_frames and len(seen_frames) >= chunk_limit: + _flush(chunk) + chunk = [] + seen_frames = set() + chunk.append(job) + seen_frames.add(f_idx) + if chunk: + _flush(chunk) + return records, crops, total_failed + + +class PrepareStage: + """Stage 1: decode, detect, crop one clip (CPU + the detector's GPU work). + + Automatically chooses among three frame-handling regimes for video files: + - Regime A (non-tracker RT-DETR): 1-pass PyAV chunked streaming with shared + H2D upload on CUDA when perspective cropping is accelerated on GPU. + - Regime B (tracker / full-clip detector, decoded clip <= 4 GiB): 1-pass + PyAV chunked streaming overlapped with detection, RAM-cached frames for + tracking and cropping (spilling cleanly to Regime C if actual decoded + bytes exceed ``ram_cache_budget_bytes``). + - Regime C (tracker / full-clip detector, clip > 4 GiB or unknown length): + 2-pass PyAV chunked streaming with bounded RAM and ``SeekablePyAVFrames`` + on-demand random access for MediaPipe verification. + """ + + ram_cache_budget_bytes = RAM_CACHE_BUDGET_BYTES + stream_chunk_size = STREAM_CHUNK_SIZE + pyav_threads = PYAV_DECODE_THREADS + gpu_perspective_crop = True + + def __init__( + self, + bbox_detector, + config: StageConfig, + *, + device: str | torch.device | None = None, + own_stream: bool = False, + ): + if getattr(bbox_detector, "reports_in_source_frame", False): + raise UnsupportedOption( + "detectors that report boxes in the source frame (saved_bboxes)" + ) + self.bbox_detector = bbox_detector + self.config = config + if device is not None: + resolved_device = torch.device(device) + else: + inner = getattr(bbox_detector, "detector", None) + if getattr(inner, "cuda_input_enabled", False): + resolved_device = torch.device( + "cuda", int(getattr(inner, "cuda_device_id", 0)) + ) + else: + resolved_device = torch.device("cpu") + self.cuda = resolved_device.type == "cuda" and torch.cuda.is_available() + if self.cuda and resolved_device.index is None: + resolved_device = torch.device("cuda", torch.cuda.current_device()) + self.device = resolved_device + # One dedicated stream for the whole run so Stage 1 GPU crop and shared + # H2D overlap smoothly with Stage 2 DINOv3 and Stage 3 SOMA. + self.stream = ( + torch.cuda.Stream(device=self.device) + if (self.cuda and own_stream) + else None + ) + + def _stream_ctx(self): + return ( + torch.cuda.stream(self.stream) + if self.stream is not None + else contextlib.nullcontext() + ) + + def _use_gpu_perspective_crop(self, camera) -> bool: + if not self.config.use_perspective_cropping or not self.gpu_perspective_crop: + return False + if not self.cuda: + return False + from inference.camera.fisheye_crop_cuda import supports_gpu_perspective_crop + + return supports_gpu_perspective_crop(camera) + + def _inner_cuda_ready(self) -> bool: + if not self.cuda: + return False + inner = getattr(self.bbox_detector, "detector", None) + if inner is None or not getattr(inner, "cuda_input_enabled", False): + return False + if not ( + hasattr(inner, "prepare_cuda_tensor") + and hasattr(inner, "run_onnx_prepared") + and hasattr(inner, "postprocess") + ): + return False + dev_idx = self.device.index if self.device.index is not None else 0 + return int(getattr(inner, "cuda_device_id", -1)) == dev_idx + + def _crop_records_cpu( + self, + crop_jobs: list, + *, + pool: ThreadPoolExecutor | None = None, + ) -> tuple[list[dict[str, Any]], list[np.ndarray], int]: + if not crop_jobs: + return [], [], 0 + pc = self.config.use_perspective_cropping + camera_mode = self.config.camera_mode + + def build(job): + return build_crop_record( + job, + use_perspective_cropping=pc, + camera_mode=camera_mode, + ) + + records: list[dict[str, Any]] = [] + crops: list[np.ndarray] = [] + failed = 0 + if pool is not None: + for _, _, record in pool.map(build, crop_jobs): + if record is None: + failed += 1 + continue + crops.append(record.pop("crop_u8")) + records.append(record) + else: + with ThreadPoolExecutor(max_workers=self.config.crop_workers) as local_pool: + for _, _, record in local_pool.map(build, crop_jobs): + if record is None: + failed += 1 + continue + crops.append(record.pop("crop_u8")) + records.append(record) + return records, crops, failed + + def run( + self, request: ClipRequest, crops_out: Callable | None = None + ) -> PreparedClip: + """Prepare one clip; errors are recorded on the returned clip. + + ``crops_out(clip, crops_list)`` may store the crops elsewhere (proc mode + shared memory) and set ``clip.crops_path``; by default the list of + uint8 crops is kept on the clip. + """ + clip = PreparedClip(request=request) + clip.times["s1_start"] = time.time() + try: + self._run(clip, crops_out) + except Exception as exc: # noqa: BLE001 - per-video isolation + clip.fail("prepare", exc) + clip.crops = None + if is_fatal_cuda_error(exc): + raise + clip.times["s1_end"] = time.time() + return clip + + def _run(self, clip: PreparedClip, crops_out) -> None: + from inference.camera.intrinsics import resolve_K + from inference.camera.square_pixel import compute_square_pixel_resize_params + from inference.postprocessing.adaptive_smoothing import validate_frame_times + + config = self.config + request = clip.request + detector = self.bbox_detector + pc = config.use_perspective_cropping + out_root = Path(request.out_root) + out_root.mkdir(parents=True, exist_ok=True) + if not os.access(out_root, os.W_OK | os.X_OK): + raise PermissionError(f"output root {out_root} is not writable") + video_path = Path(request.video) + clip.stem = video_path.stem + num_frames_est = 0 + if request.frames is None: + calibration = None + if request.intrinsics: + with open(request.intrinsics) as fh: + calibration = json.load(fh) + meta = video_meta(str(video_path)) + check_video_decodable(video_path, meta) + K_original, _ = resolve_K( + meta["width"], + meta["height"], + calibration, + perspective_cropping=pc, + calibration_source=( + f"calibration {request.intrinsics}" if request.intrinsics else None + ), + ) + clip.width, clip.height = meta["width"], meta["height"] + fps = meta["fps"] or FPS_FALLBACK + num_frames_est = int(meta.get("num_frames") or 0) + else: + K_original = request.camera + fps = request.fps or FPS_FALLBACK + clip.height, clip.width = request.frames[0].shape[:2] + if not np.isfinite(fps) or fps <= 0: + fps = FPS_FALLBACK + clip.fps = fps + if not pc and not isinstance(K_original, np.ndarray): + raise UnsupportedOption("full-image undistortion (non-pinhole camera)") + if not pc and config.rectify_pixel_aspect_ratio: + params = compute_square_pixel_resize_params( + K_original, clip.width, clip.height + ) + if not params.is_identity: + raise UnsupportedOption("pixel-aspect rectification") + K_model = K_original + if hasattr(detector, "prepare_clip"): + detector.prepare_clip(video_path=video_path, K=K_original) + + out_dir = out_root / clip.stem + clip.out_dir = out_dir + (out_dir / "quality_control.json").unlink(missing_ok=True) + if detector.writes_bbox_json: + for hand in config.hands: + (out_dir / f"{clip.stem}_{hand}_bbox.json").unlink(missing_ok=True) + out_dir.mkdir(parents=True, exist_ok=True) + bbox_paths = { + hand: out_dir / f"{out_dir.name}_{hand}_bbox.json" for hand in config.hands + } + + # Explicit pre-decoded frames (tests and library callers): preserve the + # direct detector.run + CPU ThreadPoolExecutor path cleanly. + if request.frames is not None: + clip.frame_regime = "frames" + self._run_in_memory( + clip, + request.frames, + K_model, + bbox_paths, + crops_out, + use_gpu_crop=False, + validate_frame_times=validate_frame_times, + ) + return + + can_gpu_pc = self._use_gpu_perspective_crop(K_model) + is_rtdetr_like = hasattr(detector, "detect_frames") and hasattr( + detector, "use_tracker" + ) + use_tracker = bool(getattr(detector, "use_tracker", False)) + smooth_bboxes = bool(getattr(detector, "requires_full_clip", False)) + needs_whole_clip = use_tracker or smooth_bboxes + + if not is_rtdetr_like: + # Generic / custom detector that exposes only run(): decode all + # frames via video_io and crop on GPU when supported. + clip.frame_regime = "B" + frames = decode_all_frames(str(video_path)) + self._run_in_memory( + clip, + frames, + K_model, + bbox_paths, + crops_out, + use_gpu_crop=can_gpu_pc, + validate_frame_times=validate_frame_times, + ) + return + + if not needs_whole_clip: + # Regime A: non-tracker RT-DETR -> 1-pass PyAV chunked streaming + # with shared H2D upload when both RT-DETR CUDA and GPU crop apply. + self._run_regime_a( + clip, + video_path, + K_model, + bbox_paths, + crops_out, + can_gpu_pc=can_gpu_pc, + validate_frame_times=validate_frame_times, + ) + return + + estimated_bytes = ( + num_frames_est * clip.height * clip.width * 3 + if num_frames_est > 0 and clip.height > 0 and clip.width > 0 + else None + ) + cache_in_ram = ( + estimated_bytes is not None + and estimated_bytes <= self.ram_cache_budget_bytes + ) + self._run_regime_b_or_c( + clip, + video_path, + K_model, + bbox_paths, + crops_out, + cache_in_ram=cache_in_ram, + can_gpu_pc=can_gpu_pc, + smooth_bboxes=smooth_bboxes, + validate_frame_times=validate_frame_times, + ) + + def _run_in_memory( + self, + clip: PreparedClip, + frames: list, + K_model, + bbox_paths: dict[str, Path], + crops_out, + *, + use_gpu_crop: bool, + validate_frame_times, + ) -> None: + config = self.config + detector = self.bbox_detector + video_path = Path(clip.request.video) + clip.times["decode_end"] = time.time() + if not frames: + raise RuntimeError(f"[infer_video] {video_path}: no frames decoded.") + image_ids = [f"{idx:06d}" for idx in range(len(frames))] + clip.image_ids = image_ids + smooth_bboxes = getattr(detector, "requires_full_clip", False) + frame_times = None + if config.smooth or smooth_bboxes: + frame_times = {f"{idx:06d}": idx / clip.fps for idx in range(len(frames))} + clip.frame_times = frame_times + + bboxes_per_image = detector.run( + image_ids=image_ids, + images_bgr=frames, + hands=config.hands, + output_paths_per_hand=bbox_paths, + **({"frame_times": frame_times} if smooth_bboxes else {}), + ) + clip.bboxes_per_image = bboxes_per_image + clip.times["detect_end"] = time.time() + + if config.smooth: + if frame_times is None: + raise ValueError("Adaptive smoothing requires frame_times in seconds") + validate_frame_times([frame_times[i] for i in image_ids], len(image_ids)) + clip.intrinsics_per_image = dict.fromkeys(image_ids, K_model) + if use_gpu_crop: + gpu_crop_jobs = [] + for frame_idx, image_id in enumerate(image_ids): + bboxes_per_hand = bboxes_per_image.get(image_id, {}) + for hand in config.hands: + bbox = bboxes_per_hand.get(hand) + if bbox is None: + log.info("[Skip] %s %s: no reliable hand bbox", image_id, hand) + continue + gpu_crop_jobs.append( + (frame_idx, image_id, hand, np.asarray(bbox, dtype=np.float32)) + ) + clip.num_jobs = len(gpu_crop_jobs) + records, crops, failed = _crop_frames_gpu_chunked( + frames, + gpu_crop_jobs, + K_model, + camera_mode=config.camera_mode, + device=self.device, + stream=self.stream, + chunk_frames=self.stream_chunk_size, + ) + clip.num_failed_crops += failed + del gpu_crop_jobs, frames + else: + crop_jobs = [] + for image_bgr, image_id in zip(frames, image_ids): + bboxes_per_hand = bboxes_per_image.get(image_id, {}) + for hand in config.hands: + bbox = bboxes_per_hand.get(hand) + if bbox is None: + log.info("[Skip] %s %s: no reliable hand bbox", image_id, hand) + continue + crop_jobs.append( + ( + image_id, + hand, + image_bgr, + np.asarray(bbox, dtype=np.float32), + K_model, + ) + ) + clip.num_jobs = len(crop_jobs) + records, crops, failed = self._crop_records_cpu(crop_jobs) + clip.num_failed_crops += failed + del crop_jobs, frames + + clip.records = records + if crops_out is not None: + crops_out(clip, crops) + else: + clip.crops = crops + clip.times["crop_end"] = time.time() + + def _run_regime_a( + self, + clip: PreparedClip, + video_path: Path, + K_model, + bbox_paths: dict[str, Path], + crops_out, + *, + can_gpu_pc: bool, + validate_frame_times, + ) -> None: + """Regime A: 1-pass PyAV streaming (with shared H2D on CUDA when eligible).""" + from inference.camera.fisheye_crop_cuda import crop_chunk_gpu + from inference.hand_detector_2d.rtdetr.detector import boxes_from_detections + from inference.media._pyav_video import iter_video_chunks_pyav + from inference.preprocessing.crop import IMG_SIZE + + config = self.config + detector = self.bbox_detector + shared_h2d = can_gpu_pc and self._inner_cuda_ready() + clip.frame_regime = "A" + + all_bbox_per_hand: dict[str, dict[str, np.ndarray]] = { + hand: {} for hand in config.hands + } + bboxes_per_image: dict[str, dict[str, np.ndarray]] = {} + records: list[dict[str, Any]] = [] + crops: list[np.ndarray] = [] + total_frames = 0 + total_jobs = 0 + decode_s = 0.0 + detect_s = 0.0 + crop_s = 0.0 + t_loop_start = time.time() + + stream_ctx = self._stream_ctx() + chunk_iter = iter_video_chunks_pyav( + str(video_path), + chunk_size=self.stream_chunk_size, + threads=self.pyav_threads, + ) + with contextlib.ExitStack() as stack: + cpu_pool = ( + None + if can_gpu_pc + else stack.enter_context( + ThreadPoolExecutor(max_workers=config.crop_workers) + ) + ) + while True: + t_dec = time.perf_counter() + try: + chunk_frames, _, _ = next(chunk_iter) + except StopIteration: + break + decode_s += time.perf_counter() - t_dec + if not chunk_frames: + continue + + if total_frames == 0: + clip.height, clip.width = chunk_frames[0].shape[:2] + + chunk_image_ids = [ + f"{total_frames + local_i:06d}" + for local_i in range(len(chunk_frames)) + ] + total_frames += len(chunk_frames) + + use_chunk_shared = ( + shared_h2d and len({f.shape for f in chunk_frames}) == 1 + ) + chunk_gpu = None + t_det = time.perf_counter() + if use_chunk_shared: + stacked_np = np.stack( + [np.ascontiguousarray(f) for f in chunk_frames], axis=0 + ) + host_t = torch.from_numpy(stacked_np).pin_memory() + with stream_ctx: + chunk_gpu = host_t.to(device=self.device, non_blocking=True) + upload_event = torch.cuda.Event() + upload_event.record(torch.cuda.current_stream(self.device)) + chunk_dets = _detect_chunk_cuda_shared( + detector, chunk_gpu, upload_event + ) + del host_t, stacked_np + else: + chunk_dets = detector.detect_frames(chunk_frames) + + chunk_bbox_per_hand = boxes_from_detections( + chunk_image_ids, chunk_dets, config.hands + ) + for img_id in chunk_image_ids: + bboxes_per_image[img_id] = {} + for hand in config.hands: + for img_id, bbox in chunk_bbox_per_hand[hand].items(): + arr = np.asarray(bbox, dtype=np.float32) + all_bbox_per_hand[hand][img_id] = arr + bboxes_per_image[img_id][hand] = arr + detect_s += time.perf_counter() - t_det + + t_crop = time.perf_counter() + if can_gpu_pc: + chunk_gpu_jobs = [] + for local_i, img_id in enumerate(chunk_image_ids): + frame_boxes = bboxes_per_image[img_id] + for hand in config.hands: + bbox = frame_boxes.get(hand) + if bbox is None: + log.info( + "[Skip] %s %s: no reliable hand bbox", img_id, hand + ) + continue + chunk_gpu_jobs.append((local_i, img_id, hand, bbox)) + total_jobs += len(chunk_gpu_jobs) + if chunk_gpu_jobs: + with stream_ctx: + chunk_recs, chunk_crops, n_failed = crop_chunk_gpu( + None if chunk_gpu is not None else chunk_frames, + chunk_gpu_jobs, + K_model, + IMG_SIZE, + camera_mode=config.camera_mode, + device=self.device, + images_bgr_gpu=chunk_gpu, + return_gpu_crops=False, + ) + records.extend(chunk_recs) + crops.extend(chunk_crops) + clip.num_failed_crops += n_failed + else: + chunk_cpu_jobs = [] + for local_i, img_id in enumerate(chunk_image_ids): + frame_boxes = bboxes_per_image[img_id] + for hand in config.hands: + bbox = frame_boxes.get(hand) + if bbox is None: + log.info( + "[Skip] %s %s: no reliable hand bbox", img_id, hand + ) + continue + chunk_cpu_jobs.append( + (img_id, hand, chunk_frames[local_i], bbox, K_model) + ) + total_jobs += len(chunk_cpu_jobs) + if chunk_cpu_jobs: + chunk_recs, chunk_crops, n_failed = self._crop_records_cpu( + chunk_cpu_jobs, pool=cpu_pool + ) + records.extend(chunk_recs) + crops.extend(chunk_crops) + clip.num_failed_crops += n_failed + crop_s += time.perf_counter() - t_crop + del chunk_gpu, chunk_frames + + if total_frames == 0: + raise RuntimeError(f"[infer_video] {video_path}: no frames decoded.") + + image_ids = [f"{idx:06d}" for idx in range(total_frames)] + clip.image_ids = image_ids + frame_times = ( + {f"{idx:06d}": idx / clip.fps for idx in range(total_frames)} + if config.smooth + else None + ) + if config.smooth: + assert frame_times is not None + validate_frame_times([frame_times[i] for i in image_ids], len(image_ids)) + clip.frame_times = frame_times + + if detector.writes_bbox_json: + _write_bbox_jsons(all_bbox_per_hand, config.hands, bbox_paths) + for hand in config.hands: + num_without = total_frames - len(all_bbox_per_hand[hand]) + if num_without: + log.info( + "[Skip] %d image(s) had no reliable %s hand bbox", num_without, hand + ) + + clip.bboxes_per_image = bboxes_per_image + clip.intrinsics_per_image = dict.fromkeys(image_ids, K_model) + clip.num_jobs = total_jobs + clip.records = records + if crops_out is not None: + crops_out(clip, crops) + else: + clip.crops = crops + clip.times["decode_end"] = t_loop_start + decode_s + clip.times["detect_end"] = clip.times["decode_end"] + detect_s + clip.times["crop_end"] = clip.times["detect_end"] + crop_s + + def _run_regime_b_or_c( + self, + clip: PreparedClip, + video_path: Path, + K_model, + bbox_paths: dict[str, Path], + crops_out, + *, + cache_in_ram: bool, + can_gpu_pc: bool, + smooth_bboxes: bool, + validate_frame_times, + ) -> None: + """Regime B (RAM-cached <= 4 GiB) or Regime C (2-pass PyAV streaming).""" + from inference.camera.fisheye_crop_cuda import crop_chunk_gpu + from inference.media._pyav_video import ( + SeekablePyAVFrames, + iter_video_chunks_pyav, + ) + from inference.preprocessing.crop import IMG_SIZE + + config = self.config + detector = self.bbox_detector + + ram_frames: list[np.ndarray] | None = [] if cache_in_ram else None + ram_bytes = 0 + all_dets: list = [] + all_pts: list[int] = [] + all_kf_pts: list[int] = [] + total_frames = 0 + decode_s = 0.0 + detect_s = 0.0 + t_pass1_start = time.time() + + chunk_iter = iter_video_chunks_pyav( + str(video_path), + chunk_size=self.stream_chunk_size, + threads=self.pyav_threads, + ) + while True: + t_dec = time.perf_counter() + try: + chunk_frames, chunk_pts, chunk_kf = next(chunk_iter) + except StopIteration: + break + decode_s += time.perf_counter() - t_dec + if not chunk_frames: + continue + + if total_frames == 0: + clip.height, clip.width = chunk_frames[0].shape[:2] + + t_det = time.perf_counter() + all_dets.extend(detector.detect_frames(chunk_frames)) + detect_s += time.perf_counter() - t_det + + all_pts.extend(chunk_pts) + all_kf_pts.extend(chunk_kf) + total_frames += len(chunk_frames) + + if ram_frames is not None: + ram_bytes += sum(f.nbytes for f in chunk_frames) + if ram_bytes <= self.ram_cache_budget_bytes: + ram_frames.extend(chunk_frames) + else: + log.info( + "[PrepareStage] %s exceeded RAM cache budget (%d > %d B); " + "switching to Regime C 2-pass streaming", + clip.stem, + ram_bytes, + self.ram_cache_budget_bytes, + ) + ram_frames = None + del chunk_frames + + if total_frames == 0: + raise RuntimeError(f"[infer_video] {video_path}: no frames decoded.") + + image_ids = [f"{idx:06d}" for idx in range(total_frames)] + clip.image_ids = image_ids + frame_times = ( + {f"{idx:06d}": idx / clip.fps for idx in range(total_frames)} + if (config.smooth or smooth_bboxes) + else None + ) + clip.frame_times = frame_times + if config.smooth: + if frame_times is None: + raise ValueError("Adaptive smoothing requires frame_times in seconds") + validate_frame_times([frame_times[i] for i in image_ids], len(image_ids)) + + t_track = time.perf_counter() + if ram_frames is not None: + bbox_per_hand = _track_clip_detections( + detector, + image_ids, + all_dets, + config.hands, + clip.width, + clip.height, + frame_times, + ram_frames, + ) + else: + needs_mp_frames = ( + hasattr(detector, "track_boxes") + and getattr(detector, "verifier", None) is not None + ) + if needs_mp_frames: + with SeekablePyAVFrames( + str(video_path), all_pts, all_kf_pts + ) as seekable_frames: + bbox_per_hand = _track_clip_detections( + detector, + image_ids, + all_dets, + config.hands, + clip.width, + clip.height, + frame_times, + seekable_frames, + ) + else: + bbox_per_hand = _track_clip_detections( + detector, + image_ids, + all_dets, + config.hands, + clip.width, + clip.height, + frame_times, + None, + ) + detect_s += time.perf_counter() - t_track + del all_dets + + if detector.writes_bbox_json: + _write_bbox_jsons(bbox_per_hand, config.hands, bbox_paths) + bboxes_per_image = _bboxes_per_image_from_hand_dict( + image_ids, bbox_per_hand, config.hands + ) + clip.bboxes_per_image = bboxes_per_image + clip.intrinsics_per_image = dict.fromkeys(image_ids, K_model) + clip.times["decode_end"] = t_pass1_start + decode_s + clip.times["detect_end"] = clip.times["decode_end"] + detect_s + + t_crop_start = time.perf_counter() + records: list[dict[str, Any]] = [] + crops: list[np.ndarray] = [] + + if ram_frames is not None: + clip.frame_regime = "B" + if can_gpu_pc: + gpu_crop_jobs = [] + for frame_idx, image_id in enumerate(image_ids): + bboxes_per_hand = bboxes_per_image.get(image_id, {}) + for hand in config.hands: + bbox = bboxes_per_hand.get(hand) + if bbox is None: + log.info( + "[Skip] %s %s: no reliable hand bbox", image_id, hand + ) + continue + gpu_crop_jobs.append((frame_idx, image_id, hand, bbox)) + clip.num_jobs = len(gpu_crop_jobs) + records, crops, failed = _crop_frames_gpu_chunked( + ram_frames, + gpu_crop_jobs, + K_model, + camera_mode=config.camera_mode, + device=self.device, + stream=self.stream, + chunk_frames=self.stream_chunk_size, + ) + clip.num_failed_crops += failed + else: + cpu_crop_jobs = [] + for image_bgr, image_id in zip(ram_frames, image_ids): + bboxes_per_hand = bboxes_per_image.get(image_id, {}) + for hand in config.hands: + bbox = bboxes_per_hand.get(hand) + if bbox is None: + log.info( + "[Skip] %s %s: no reliable hand bbox", image_id, hand + ) + continue + cpu_crop_jobs.append((image_id, hand, image_bgr, bbox, K_model)) + clip.num_jobs = len(cpu_crop_jobs) + records, crops, failed = self._crop_records_cpu(cpu_crop_jobs) + clip.num_failed_crops += failed + del ram_frames + else: + clip.frame_regime = "C" + total_jobs = 0 + for image_id in image_ids: + bboxes_per_hand = bboxes_per_image.get(image_id, {}) + for hand in config.hands: + if bboxes_per_hand.get(hand) is None: + log.info("[Skip] %s %s: no reliable hand bbox", image_id, hand) + else: + total_jobs += 1 + clip.num_jobs = total_jobs + + if total_jobs > 0: + stream_ctx = self._stream_ctx() + frame_offset = 0 + with contextlib.ExitStack() as stack: + cpu_pool = ( + None + if can_gpu_pc + else stack.enter_context( + ThreadPoolExecutor(max_workers=config.crop_workers) + ) + ) + for chunk_frames, _, _ in iter_video_chunks_pyav( + str(video_path), + chunk_size=self.stream_chunk_size, + threads=self.pyav_threads, + ): + chunk_len = len(chunk_frames) + if can_gpu_pc: + chunk_gpu_jobs = [] + for local_i in range(chunk_len): + global_i = frame_offset + local_i + if global_i >= total_frames: + break + img_id = image_ids[global_i] + frame_boxes = bboxes_per_image.get(img_id, {}) + for hand in config.hands: + bbox = frame_boxes.get(hand) + if bbox is not None: + chunk_gpu_jobs.append( + (local_i, img_id, hand, bbox) + ) + if chunk_gpu_jobs: + with stream_ctx: + chunk_recs, chunk_crops, n_failed = crop_chunk_gpu( + chunk_frames, + chunk_gpu_jobs, + K_model, + IMG_SIZE, + camera_mode=config.camera_mode, + device=self.device, + return_gpu_crops=False, + ) + records.extend(chunk_recs) + crops.extend(chunk_crops) + clip.num_failed_crops += n_failed + else: + chunk_cpu_jobs = [] + for local_i in range(chunk_len): + global_i = frame_offset + local_i + if global_i >= total_frames: + break + img_id = image_ids[global_i] + frame_boxes = bboxes_per_image.get(img_id, {}) + for hand in config.hands: + bbox = frame_boxes.get(hand) + if bbox is not None: + chunk_cpu_jobs.append( + ( + img_id, + hand, + chunk_frames[local_i], + bbox, + K_model, + ) + ) + if chunk_cpu_jobs: + chunk_recs, chunk_crops, n_failed = ( + self._crop_records_cpu( + chunk_cpu_jobs, pool=cpu_pool + ) + ) + records.extend(chunk_recs) + crops.extend(chunk_crops) + clip.num_failed_crops += n_failed + frame_offset += chunk_len + del chunk_frames + if frame_offset != total_frames: + raise RuntimeError( + f"[PrepareStage] {video_path}: Pass 2 decoded {frame_offset} " + f"frame(s), expected {total_frames}" + ) + + clip.records = records + if crops_out is not None: + crops_out(clip, crops) + else: + clip.crops = crops + clip.times["crop_end"] = clip.times["detect_end"] + ( + time.perf_counter() - t_crop_start + ) + + +# --------------------------------------------------------------------------- stage 2 + + +class HeadStage: + """Stage 2: batch assembly, upload and ``forward_step_head``.""" + + def __init__(self, predictor, config: StageConfig, *, own_stream: bool = False): + self.predictor = predictor + self.config = config + self.device = torch.device(predictor.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()) + # One stream for the whole run (a new stream per clip makes the caching + # allocator keep a separate block pool per stream). + self.stream = ( + torch.cuda.Stream(device=self.device) + if (self.cuda and own_stream) + else None + ) + + @torch.no_grad() + def run( + self, clip: PreparedClip, emit: Callable[[HeadBatch], None], crops=None + ) -> int: + """Run every forward batch of ``clip``; ``emit`` each one. Returns the count.""" + from inference.pipeline.crop_stream import StreamedCropBatches + from inference.preprocessing.crop import normalize_crop + + predictor = self.predictor + crops = clip.crops if crops is None else crops + records = clip.records + if len(records) != (0 if crops is None else len(crops)): + raise RuntimeError( + f"{clip.stem}: {len(records)} crop records but " + f"{0 if crops is None else len(crops)} crops" + ) + dtype = predictor.dtype + + def build(index): + record = dict(records[index]) + record["crop_tensor"] = normalize_crop(np.asarray(crops[index])) + return record["image_id"], record["real_hand_side"], record + + stream_ctx = ( + torch.cuda.stream(self.stream) + if self.stream is not None + else contextlib.nullcontext() + ) + count = 0 + start = 0 + with stream_ctx: + with StreamedCropBatches( + range(len(records)), + build, + batch_size=predictor.batch_size, + device=predictor.device, + workers=self.config.norm_workers, + copy_stream=predictor._crop_copy_stream(), + ) as crop_batches: + for staged in crop_batches: + batch_hand_data = staged.hand_data + batch = predictor._assemble_batch(batch_hand_data, staged) + with torch.autocast( + self.device.type, dtype=dtype, enabled=(dtype != torch.float32) + ): + head = predictor.model.forward_step_head(batch, train=False) + batch.pop("img") + # The head's reads of the images are queued; reuse the slot. + staged.release() + event = None + if self.cuda: + event = torch.cuda.Event() + event.record(torch.cuda.current_stream(self.device)) + emit(HeadBatch(start, batch_hand_data, batch, head, event)) + start += len(batch_hand_data) + count += 1 + if start != len(records): + raise RuntimeError( + f"{clip.stem}: forward batches covered {start} of {len(records)} crops" + ) + return count + + +# --------------------------------------------------------------------------- stage 3 + + +def _record_stream(obj, stream) -> None: + if isinstance(obj, torch.Tensor): + if obj.is_cuda: + obj.record_stream(stream) + elif isinstance(obj, dict): + for value in obj.values(): + _record_stream(value, stream) + elif isinstance(obj, (list, tuple)): + for value in obj: + _record_stream(value, stream) + + +def save_clip_outputs(clip: PreparedClip, results_per_hand: dict, hands: list) -> dict: + """Write clip-level ``{hand}_results.npz`` outputs (matching ``process_video`` with ``--no_save_videos``).""" + from inference.pipeline.results_io import save_hand_results_clip + + out_dir = clip.out_dir + total_frames = len(clip.image_ids) + inference_results: dict[str, dict] = {"left": {}, "right": {}} + for hand in hands: + inference_results[hand].update(results_per_hand[hand]) + for hand in hands: + n_inferred = len(inference_results[hand]) + print( + f"[infer_video] {clip.stem} {hand}: {n_inferred}/{total_frames} frames " + f"inferred ({total_frames - n_inferred} skipped — no prediction)" + ) + if not any(inference_results[hand] for hand in hands): + raise RuntimeError( + f"[infer_video] {clip.request.video}: 0/{total_frames} frames inferred across " + "the requested hands. Check bbox inputs, frame IDs, and detector confidence." + ) + for hand, results in inference_results.items(): + remapped = [ + {**r, "hand_poses": r["poses"], "pred_cam_t": r["transl"]} + for r in results.values() + ] + save_hand_results_clip( + out_dir / f"{hand}_results.npz", list(results.keys()), remapped + ) + return {hand: len(inference_results[hand]) for hand in hands} + + +#: What the perf.json latencies of a three-stage clip measure (written into its +#: metadata): the stages overlap other videos, so these are per-frame wall times +#: of this clip's stage spans, including waits, not the single-video meanings of +#: ``inference.perf.STAGE_DESCRIPTIONS``. +THREE_STAGE_PERF_MEANING = { + "bbox_detection": "stage 1: detection + tracking of the decoded clip", + "preprocessing": "stage 1: uint8 crops of every hand", + "model_forward": "stage 2 wall time for the clip: waiting for crop slots, " + "normalization, upload, forward_step_head", + "post_forward": "stage 3 from its first head batch of the clip to the last, " + "including waits for stage 2 (SOMA decode, mirror)", + "adaptive_smoothing": "stage 3: results assembly and smoothing", + "total_wall": "stage 1 start to stage 3 end of the clip (overlaps other clips)", +} + + +class SomaStage: + """Stage 3: SOMA decode, mirror, results, smoothing, export.""" + + def __init__( + self, + predictor, + config: StageConfig, + *, + writer: Callable | None = None, + model_load_ms: float | None = None, + ): + self.predictor = predictor + self.config = config + self.device = torch.device(predictor.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.writer = writer if writer is not None else save_clip_outputs + self.model_load_ms = model_load_ms + self._batcher = None + self._clip = None + self.results = None # results_per_hand of the last finished clip (tests) + + def begin(self, clip: PreparedClip) -> None: + from inference.pipeline.soma_batching import SomaBatcher + + self._clip = clip + self._batcher = SomaBatcher( + self.predictor, + getattr(self.predictor, "soma_batch_size", 0), + defer_geometry=bool(self.config.smooth), + ) + clip.times.setdefault("s3_start", time.time()) + + def discard(self) -> None: + self._batcher = None + self._clip = None + + @torch.no_grad() + def add(self, head_batch: HeadBatch) -> None: + if head_batch.event is not None: + stream = torch.cuda.current_stream(self.device) + stream.wait_event(head_batch.event) + # Stage 2's tensors were allocated on its stream; keep the + # allocator from reusing them while this stream may read them. + _record_stream((head_batch.batch, head_batch.head), stream) + self._batcher.add(head_batch.batch, head_batch.hand_data, head_batch.head) + + @torch.no_grad() + def finish(self, clip: PreparedClip) -> dict: + predictor = self.predictor + hands = self.config.hands + clip.times["s3_batches_end"] = time.time() + predictions = self._batcher.finish() + self._batcher = None + prepared_inputs_by_image: dict = {} + for record in clip.records: + prepared_inputs_by_image.setdefault(record["image_id"], {})[ + record["real_hand_side"] + ] = record + results_per_hand = predictor._results_per_hand( + predictions, hands, prepared_inputs_by_image + ) + t_smooth = time.time() + predictor.postprocess_results( + results_per_hand, + clip.image_ids, + clip.bboxes_per_image, + frame_times=clip.frame_times, + intrinsics_per_image=clip.intrinsics_per_image, + source_cameras_per_image=None, + ) + clip.times["s3_smooth_end"] = time.time() + clip.times["smooth_s"] = clip.times["s3_smooth_end"] - t_smooth + self.results = results_per_hand + counts = self.writer(clip, results_per_hand, hands) + clip.times["s3_end"] = time.time() + self._write_perf(clip) + self._clip = None + return counts + + def _write_perf(self, clip: PreparedClip) -> None: + if clip.out_dir is None or not clip.image_ids: + return + from inference.perf import LocalPerfWriter, PerfStage + + n = len(clip.image_ids) + t = clip.times + writer = LocalPerfWriter( + output_path=clip.out_dir / "perf.json", + metadata={ + **(self.config.perf_metadata or {}), + "three_stage": True, + "three_stage_latencies": dict(THREE_STAGE_PERF_MEANING), + }, + ) + writer.record_frames(n) + if self.model_load_ms is not None: + writer.record_latency(PerfStage.MODEL_LOAD, self.model_load_ms) + + def per_frame(a, b): + return (t[b] - t[a]) * 1000.0 / n if a in t and b in t else None + + for stage, value in ( + (PerfStage.BBOX_DETECTION, per_frame("decode_end", "detect_end")), + (PerfStage.PREPROCESSING, per_frame("detect_end", "crop_end")), + (PerfStage.MODEL_FORWARD, per_frame("s2_start", "s2_end")), + (PerfStage.POST_FORWARD, per_frame("s3_start", "s3_batches_end")), + ( + PerfStage.ADAPTIVE_SMOOTHING, + per_frame("s3_batches_end", "s3_smooth_end"), + ), + (PerfStage.TOTAL_WALL, per_frame("s1_start", "s3_end")), + ): + if value is not None: + writer.record_latency(stage, value) + writer.write() + + +# --------------------------------------------------------------------------- records + + +def clip_record(clip: PreparedClip, status: str | None = None) -> dict: + """Per-video summary record (driver JSON).""" + request = clip.request + t = dict(clip.times) + start = t.get("s1_start") + end = t.get("s3_end") or t.get("failed_at") or time.time() + record = { + "i": request.index, + "name": request.name, + "video": request.video, + "out_root": request.out_root, + "status": status or ("ok" if clip.error is None else "error"), + "frames": len(clip.image_ids), + "crop_jobs": clip.num_jobs, + "crops": len(clip.records), + "failed_crops": clip.num_failed_crops, + "t_start_epoch": start, + "t_end_epoch": end, + "wall_s": (end - start) if start else None, + "times": t, + } + if clip.frame_regime is not None: + record["frame_regime"] = clip.frame_regime + if clip.error is not None: + record.update( + error=clip.error, + error_class=clip.error_class, + error_stage=clip.error_stage, + traceback=clip.error_traceback, + ) + return record + + +# --------------------------------------------------------------------------- thr mode + + +class _Stopped(Exception): + pass + + +class ThreadedThreeStage: + """thr mode: stage 1 and 2 on worker threads, stage 3 on the calling thread. + + Args: + prepare_ahead: 1 (default): stage 1 starts decoding the next clip + only after stage 2 has taken the previous one (at most one prepared + clip waits). 2: one more clip may be prepared while one waits. + soma_videos: Clips stage 2 may have handed to stage 3 and stage 3 has + not finished (bounds the GPU memory held by queued head batches). + warp_mempool: Enable Warp's memory pool on the device while running. + py-soma-x disables it; then every Warp temporary is freed with + ``cudaFree``, which waits for the whole device (also for stage 2). + Only the allocation method changes. + """ + + def __init__( + self, + prepare: PrepareStage, + head: HeadStage, + soma: SomaStage, + *, + prepare_ahead: int = 1, + soma_videos: int = 2, + warp_mempool: bool = False, + poll_s: float = 0.1, + ): + if prepare_ahead < 1 or soma_videos < 1: + raise ValueError("prepare_ahead and soma_videos must be >= 1") + self.prepare = prepare + self.head = head + self.soma = soma + self.prepare_ahead = prepare_ahead + self.soma_videos = soma_videos + self.warp_mempool = warp_mempool + self.poll_s = poll_s + self._stop = threading.Event() + self.fatal: BaseException | None = None + self.fatal_traceback: str | None = None + self.in_flight: dict[int, PreparedClip] = {} + self._lock = threading.Lock() + + # queue helpers that give up when the run stops + def _put(self, q: queue.Queue, item) -> None: + while True: + if self._stop.is_set(): + raise _Stopped() + try: + q.put(item, timeout=self.poll_s) + return + except queue.Full: + continue + + def _get(self, q: queue.Queue): + while True: + if self._stop.is_set(): + raise _Stopped() + try: + return q.get(timeout=self.poll_s) + except queue.Empty: + continue + + def _wait(self, waitable) -> None: + while not waitable(self.poll_s): + if self._stop.is_set(): + raise _Stopped() + + def _set_fatal(self, exc: BaseException) -> None: + with self._lock: + if self.fatal is None: + self.fatal = exc + self.fatal_traceback = traceback.format_exc()[-4000:] + self._stop.set() + + def _prepare_loop(self, requests: Iterable[ClipRequest], q12: queue.Queue) -> None: + try: + for request in requests: + if self._stop.is_set(): + return + try: + clip = self.prepare.run(request) + except ( + BaseException + ) as exc: # fatal (CUDA): report this clip as aborted + lost = PreparedClip(request=request) + lost.fail("prepare", exc) + with self._lock: + self.in_flight[request.index] = lost + raise + with self._lock: + self.in_flight[request.index] = clip + taken = threading.Event() + self._put(q12, (clip, taken)) + if self.prepare_ahead <= 1: + self._wait(taken.wait) + self._put(q12, _END) + except _Stopped: + return + except BaseException as exc: # noqa: BLE001 + self._set_fatal(exc) + + def _head_loop( + self, q12: queue.Queue, q23: queue.Queue, slots: threading.Semaphore + ) -> None: + try: + while True: + item = self._get(q12) + if item == _END: + self._put(q23, ("end_of_queue", None, None)) + return + clip, taken = item + taken.set() + if clip.error is not None: + self._put(q23, ("fail", clip, None)) + continue + self._wait(lambda timeout: slots.acquire(timeout=timeout)) + clip.began = True + clip.times["s2_start"] = time.time() + self._put(q23, ("begin", clip, None)) + try: + self.head.run( + clip, lambda hb, clip=clip: self._put(q23, ("batch", clip, hb)) + ) + except _Stopped: + raise + except Exception as exc: # noqa: BLE001 + clip.fail("head", exc) + clip.times["failed_at"] = time.time() + self._put(q23, ("fail", clip, None)) + if is_fatal_cuda_error(exc): + self._set_fatal(exc) + return + if isinstance(exc, torch.cuda.OutOfMemoryError): + torch.cuda.empty_cache() + continue + finally: + clip.crops = None # the uint8 crops are no longer needed + clip.times["s2_end"] = time.time() + self._put(q23, ("end", clip, None)) + except _Stopped: + return + except BaseException as exc: # noqa: BLE001 + self._set_fatal(exc) + + def run( + self, requests: Iterable[ClipRequest], on_record: Callable[[dict], None] + ) -> None: + """Process ``requests``; ``on_record`` gets one record per finished clip.""" + q12: queue.Queue = queue.Queue(maxsize=1) + q23: queue.Queue = queue.Queue() + slots = threading.Semaphore(self.soma_videos) + wp_restore = None + if self.warp_mempool and self.soma.cuda: + wp_restore = _enable_warp_mempool(self.soma.device) + threads = [ + threading.Thread( + target=self._prepare_loop, + args=(requests, q12), + name="egopost-t3-prepare", + daemon=True, + ), + threading.Thread( + target=self._head_loop, + args=(q12, q23, slots), + name="egopost-t3-head", + daemon=True, + ), + ] + for thread in threads: + thread.start() + current = None + try: + while True: + kind, clip, payload = self._get(q23) + if kind == "end_of_queue": + break + if kind == "begin": + current = clip + try: + self.soma.begin(clip) + except Exception as exc: # noqa: BLE001 + clip.fail("soma", exc) + elif kind == "batch": + if clip.error is None: + try: + self.soma.add(payload) + except Exception as exc: # noqa: BLE001 + clip.fail("soma", exc) + clip.times["failed_at"] = time.time() + self.soma.discard() + if is_fatal_cuda_error(exc): + raise + if isinstance(exc, torch.cuda.OutOfMemoryError): + torch.cuda.empty_cache() + del payload + elif kind in ("end", "fail"): + if kind == "end" and clip.error is None: + try: + self.soma.finish(clip) + except Exception as exc: # noqa: BLE001 + clip.fail("soma", exc) + clip.times["failed_at"] = time.time() + self.soma.discard() + if is_fatal_cuda_error(exc): + raise + if isinstance(exc, torch.cuda.OutOfMemoryError): + torch.cuda.empty_cache() + else: + clip.times.setdefault("failed_at", time.time()) + self.soma.discard() + if clip.began: + slots.release() + current = None + with self._lock: + self.in_flight.pop(clip.request.index, None) + clip.crops = None + on_record(clip_record(clip)) + except _Stopped: + pass + except BaseException as exc: # noqa: BLE001 + if current is not None: + current.fail("soma", exc) + self._set_fatal(exc) + finally: + for thread in threads: + thread.join(timeout=None if self.fatal is None else 60) + if wp_restore is not None: + wp_restore() + if self.fatal is not None: + for clip in list(self.in_flight.values()): + if clip.error is None: + clip.error = f"aborted: {type(self.fatal).__name__}: {self.fatal}"[ + :2000 + ] + clip.error_class = "Aborted" + clip.error_stage = "run" + clip.times.setdefault("failed_at", time.time()) + on_record(clip_record(clip, status="aborted")) + self.in_flight.clear() + + +def _enable_warp_mempool(device: torch.device): + try: + import warp as wp + except ImportError: + return None + wp_device = wp.device_from_torch(device) + was = wp.is_mempool_enabled(wp_device) + wp.set_mempool_enabled(wp_device, True) + + def restore(): + wp.set_mempool_enabled(wp_device, was) + + return restore + + +def run_serial( + prepare: PrepareStage, + head: HeadStage, + soma: SomaStage, + requests: Iterable[ClipRequest], + on_record: Callable[[dict], None], + *, + warp_mempool: bool = False, +) -> None: + """The three stages one after the other per clip, in the calling thread.""" + wp_restore = ( + _enable_warp_mempool(soma.device) if warp_mempool and soma.cuda else None + ) + try: + for request in requests: + try: + clip = prepare.run(request) + except Exception as exc: # noqa: BLE001 + clip = PreparedClip( + request=request, + stem=Path(request.video).stem, + out_dir=Path(request.out_root) / Path(request.video).stem, + ) + clip.fail("prepare", exc) + clip.times["failed_at"] = time.time() + if is_fatal_cuda_error(exc): + on_record(clip_record(clip, status="aborted")) + raise + if clip.error is None: + clip.began = True + clip.times["s2_start"] = time.time() + try: + soma.begin(clip) + head.run(clip, soma.add) + clip.times["s2_end"] = time.time() + soma.finish(clip) + except Exception as exc: # noqa: BLE001 + clip.fail("head/soma", exc) + clip.times["failed_at"] = time.time() + soma.discard() + if is_fatal_cuda_error(exc): + on_record(clip_record(clip, status="aborted")) + raise + if isinstance(exc, torch.cuda.OutOfMemoryError): + torch.cuda.empty_cache() + clip.crops = None + on_record(clip_record(clip)) + finally: + if wp_restore is not None: + wp_restore() + + +# --------------------------------------------------------------------------- proc mode + + +def tensors_to(obj, device, non_blocking: bool = False): + """Copy every tensor in a nested dict / list / tuple to ``device``.""" + if isinstance(obj, torch.Tensor): + return obj.to(device, non_blocking=non_blocking) + if isinstance(obj, dict): + return { + key: tensors_to(value, device, non_blocking) for key, value in obj.items() + } + if isinstance(obj, list): + return [tensors_to(value, device, non_blocking) for value in obj] + if isinstance(obj, tuple): + return tuple(tensors_to(value, device, non_blocking) for value in obj) + return obj + + +def pack_head_batch(head_batch: HeadBatch) -> bytes: + """Host bytes of one head batch for another process (dtype and strides kept).""" + payload = { + "start": head_batch.start, + "rows": len(head_batch.hand_data), + "batch": tensors_to(head_batch.batch, "cpu"), + "head": tensors_to(head_batch.head, "cpu"), + } + buffer = io.BytesIO() + torch.save(payload, buffer) + return buffer.getvalue() + + +def unpack_head_batch(data: bytes, records: list, device) -> HeadBatch: + """Inverse of ``pack_head_batch``; ``hand_data`` is the records' slice.""" + payload = torch.load(io.BytesIO(data), map_location="cpu", weights_only=False) + start, rows = payload["start"], payload["rows"] + return HeadBatch( + start=start, + hand_data=records[start : start + rows], + batch=tensors_to(payload["batch"], device), + head=tensors_to(payload["head"], device), + event=None, + ) + + +def claim_requests( + requests: list[ClipRequest], claim_dir: str | None +) -> Iterator[ClipRequest]: + """Yield the requests this worker claims (all of them without ``claim_dir``). + + Several workers sharing ``claim_dir`` take the queue in order, each item + once: a claim is an exclusively created file ``.claim``. + """ + for request in requests: + if claim_dir: + path = os.path.join(claim_dir, f"{request.index:05d}.claim") + try: + fd = os.open(path, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o644) + except FileExistsError: + continue + with os.fdopen(fd, "w") as fh: + fh.write(f"{os.getpid()} {time.time():.6f}\n") + yield request + + +def build_detector(detector_cfg: dict, device: str, batch_size: int): + """The detector of ``detector_cfg`` by backend name, as + ``run_egohand_inference_pipeline._build_detector_from_config`` builds it. + + For the proc-mode stage-1 process and library callers; the driver builds + through the CLI function in thr / serial mode, which also turns config + errors into its one-line invalid-input exit. + """ + import importlib + + backend = detector_cfg["detector_backend"] + module = importlib.import_module(f"inference.hand_detector_2d.configs.{backend}") + return module.build( + detector_cfg, device, batch_size, detector_cfg.get("tracking", False) + ) + + +def warm_detector(bbox_detector) -> list: + """Run ORT once per batch size 1..B on zeros (``--warm_detector``), so its + cuDNN algorithm search by timing happens before the first video.""" + warm = [] + inner = getattr(bbox_detector, "detector", None) + if inner is None: + return warm + max_batch = int(getattr(bbox_detector, "batch_size", 8)) + if getattr(inner, "cuda_input_enabled", False) and hasattr(inner, "_run_onnx_cuda"): + cuda_device = torch.device("cuda", int(getattr(inner, "cuda_device_id", 0))) + for b in range(1, max_batch + 1): + t = time.perf_counter() + images = torch.zeros( + (b, 3, 640, 640), dtype=torch.float32, device=cuda_device + ) + sizes = torch.full((b, 2), 640, dtype=torch.int64, device=cuda_device) + inner._run_onnx_cuda(images, sizes) + warm.append({"batch": b, "s": time.perf_counter() - t}) + return warm + if not hasattr(inner, "_run"): + return warm + for b in range(1, max_batch + 1): + t = time.perf_counter() + inner._run( + np.zeros((b, 3, 640, 640), np.float32), np.full((b, 2), 640, np.int64) + ) + warm.append({"batch": b, "s": time.perf_counter() - t}) + return warm + + +_DTYPES = { + "float32": torch.float32, + "float16": torch.float16, + "bfloat16": torch.bfloat16, +} + + +def load_predictor(settings: dict): + """``EgoHandPredictor.from_checkpoint`` (+ backbone options) from driver settings. + + ``settings["mhr_presorted_sparse"]`` (default True) is passed on: + ``from_checkpoint`` coalesces the MHR sparse matrix once + (``mhr_presort.py``); ``predictor.mhr_presort`` records what it patched. + The backbone options (``configure_backbone``) are applied here, so the load + time includes them; their setup facts are on ``predictor.backbone_setup``. + """ + from inference.pipeline.predictor import EgoHandPredictor + + t = time.perf_counter() + predictor = EgoHandPredictor.from_checkpoint( + egohand_ckpt_path=settings["egohand_ckpt"], + soma_hand_data_folder=settings["soma_hand_assets"], + batch_size=settings["batch_size"], + device=settings["device"], + dtype=_DTYPES[settings["dtype"]], + smooth=settings["smooth"], + use_perspective_cropping=settings["use_perspective_cropping"], + soma_batch_size=settings["soma_batch_size"], + mhr_presorted_sparse=settings.get("mhr_presorted_sparse", True), + ) + predictor.backbone_setup = configure_backbone(predictor, settings) + return predictor, (time.perf_counter() - t) * 1000.0 + + +# --------------------------------------------------------------------------- backbone options + +BACKBONE_COMPILE_SCOPES = ("off", "block", "whole") +# Fix Inductor reduction configs so concurrent cold compiles pick identical +# block sizes and reduction orders. Passed via torch.compile(options=...) +# because PyTorch Dynamo resets the process-global deterministic flag after +# each traced frame (convert_frame -> use_deterministic_algorithms). +DETERMINISTIC_INDUCTOR_OPTIONS = {"dynamic_scale_rblock": False, "deterministic": True} + + +def backbone_compile_scope(settings: dict) -> str: + """``backbone_compile`` if set, else ``"block"`` for the legacy ``dino_compile``.""" + scope = settings.get("backbone_compile") + if scope in (None, ""): + scope = "block" if settings.get("dino_compile") else "off" + if scope not in BACKBONE_COMPILE_SCOPES: + raise ValueError(f"backbone_compile must be one of {BACKBONE_COMPILE_SCOPES}") + return scope + + +def backbone_options_active(settings: dict) -> bool: + return backbone_compile_scope(settings) != "off" or bool( + settings.get("backbone_bf16_weights") + ) + + +def without_backbone_options(settings: dict) -> dict: + """Settings for a process that never runs the backbone (proc mode P3).""" + return { + **settings, + "dino_compile": False, + "backbone_compile": "off", + "backbone_bf16_weights": False, + } + + +def configure_backbone(predictor, settings: dict) -> dict: + """Apply the backbone options of ``settings`` to a loaded predictor. + + Order: weights first (``backbone_bf16_weights`` stores the Linear / Conv2d + weights in bf16), then the compile settings (lazy: the compile itself + happens on the first full batch, see ``warm_backbone``). + All options off: nothing is touched. + """ + scope = backbone_compile_scope(settings) + bf16 = bool(settings.get("backbone_bf16_weights")) + info: dict = {"compile": scope, "bf16_weights": bf16} + if scope == "off" and not bf16: + return info + if bf16 and getattr(predictor, "dtype", None) != torch.bfloat16: + # The weights only give the same values when the backbone runs under + # bf16 autocast; float32 (no autocast) fails on the dtype mismatch and + # float16 autocast would round the bf16 weights again. + raise ValueError( + "backbone_bf16_weights needs the bfloat16 inference dtype, got " + f"{getattr(predictor, 'dtype', None)}" + ) + backbone = getattr(predictor.model, "backbone", None) + t = time.perf_counter() + if bf16: + cast = getattr(backbone, "cast_matmul_weights_bf16", None) + if cast is None: + raise RuntimeError( + "backbone_bf16_weights requires a backbone with cast_matmul_weights_bf16()" + ) + info["bf16_modules"] = cast() + if torch.cuda.is_available(): + torch.cuda.empty_cache() + info["weights_s"] = time.perf_counter() - t + if scope != "off": + predictor.enable_backbone_compile( + scope, options=dict(DETERMINISTIC_INDUCTOR_OPTIONS) + ) + info["compile_options"] = dict(DETERMINISTIC_INDUCTOR_OPTIONS) + info["full_batch_size"] = predictor.batch_size + return info + + +def dynamo_counters() -> dict: + """Graphs torch.compile has built so far in this process, recompiles, and + the Inductor / AOTAutograd cache hits and misses (cache_*).""" + try: + from torch._dynamo.utils import counters + except Exception: # noqa: BLE001 + return {} + out = { + "unique_graphs": int(counters["stats"].get("unique_graphs", 0)), + "recompiles": int(sum(counters["recompiles"].values())) + if "recompiles" in counters + else 0, + } + for group in ("inductor", "aot_autograd"): + if group in counters: + for key, value in counters[group].items(): + if "cache" in key: + out[f"cache_{key}"] = int(value) + return out + + +@torch.no_grad() +def warm_backbone(predictor, calls: int = 3) -> dict | None: + """Compile the backbone before the queue starts (once per process). + + Runs ``calls`` full batches of random crops through the backbone the way + stage 2 calls it (``forward_step_head``: same batch size, the same + ``_backbone_crop_w`` view of a float32 ``[B, 3, 256, 256]`` batch, no_grad, + the same autocast), so the first real batch finds the compiled code and + every timing after "ready" excludes compilation. The crops come from a + private generator (the global RNG is untouched); outputs are discarded. + Returns the first-call time (compile + Inductor's first-call tuning) and the + later call times, or ``None`` when the backbone is not compiled. + """ + from inference.preprocessing.crop import IMG_SIZE + + if calls < 1: + raise ValueError(f"warm_backbone requires calls >= 1, got {calls}") + model = getattr(predictor, "model", None) + backbone = getattr(model, "backbone", None) + batch = getattr(backbone, "_compiled_full_batch_size", None) + if backbone is None or batch is None: + return None + device = torch.device(predictor.device) + if device.type == "cuda" and device.index is None: + device = torch.device("cuda", torch.cuda.current_device()) + generator = torch.Generator(device=device) + generator.manual_seed(0) + img = torch.randn( + (batch, 3, IMG_SIZE, IMG_SIZE), + generator=generator, + device=device, + dtype=torch.float32, + ) + crop = getattr(model, "_backbone_crop_w", None) + x = img[:, :, :, crop[0] : crop[1]] if crop is not None else img + dtype = predictor.dtype + before = dynamo_counters() + times = [] + for _ in range(calls): + t = time.perf_counter() + with torch.autocast(device.type, dtype=dtype, enabled=(dtype != torch.float32)): + out = backbone(x) + if device.type == "cuda": + torch.cuda.synchronize(device) + times.append(time.perf_counter() - t) + del out + after = dynamo_counters() + try: + import torch._inductor.config as inductor_config + + rblock = bool(inductor_config.dynamic_scale_rblock) + except Exception: # noqa: BLE001 + rblock = None + return { + "batch": batch, + "input_shape": list(x.shape), + "first_call_s": times[0], + "later_calls_ms": [t * 1000.0 for t in times[1:]], + "warmup_total_s": sum(times), + "dynamo_before": before, + "dynamo_after": after, + "inductor_cache_dir": os.environ.get("TORCHINDUCTOR_CACHE_DIR"), + "triton_cache_dir": os.environ.get("TRITON_CACHE_DIR"), + "env_dynamic_scale_rblock": os.environ.get( + "TORCHINDUCTOR_DYNAMIC_SCALE_RBLOCK" + ), + "global_config_dynamic_scale_rblock": rblock, + "env_deterministic": os.environ.get("TORCHINDUCTOR_DETERMINISTIC"), + } + + +def trim_for_stage(predictor, stage: str) -> None: + """Drop the modules a proc-mode stage never calls and return their GPU memory. + + head: the SOMA hand layers (only ``forward_step`` / decode use them). + soma: the DINOv3 backbone and the hand head (only ``forward_step_head``). + """ + import gc + + model = predictor.model + if stage == "head": + model.soma_hand = None + elif stage == "soma": + model.backbone = None + model.hand_head = None + gc.collect() + if torch.cuda.is_available(): + torch.cuda.empty_cache() + + +def stage_config_from_settings(settings: dict, camera_mode: str) -> StageConfig: + return StageConfig( + hands=list(settings["hands"]), + use_perspective_cropping=settings["use_perspective_cropping"], + camera_mode=camera_mode, + batch_size=settings["batch_size"], + smooth=settings["smooth"], + crop_workers=settings.get("crop_workers", 8), + norm_workers=settings.get("norm_workers", 4), + rectify_pixel_aspect_ratio=settings.get("rectify_pixel_aspect_ratio", True), + perf_metadata=settings.get("perf_metadata"), + ) + + +def _factory(settings: dict, kind: str): + """Optional ``"module:function"`` replacing ``build_detector`` / ``load_predictor`` + in the proc-mode processes (``settings["factories"][kind]``; tests use fakes).""" + import importlib + + spec = (settings.get("factories") or {}).get(kind) + if not spec: + return None + module, function = spec.split(":") + return getattr(importlib.import_module(module), function) + + +def _cuda_mem(device: str | torch.device | None = None) -> dict: + if not torch.cuda.is_available(): + return {} + dev = torch.device(device) if device is not None else None + if dev is not None and dev.type != "cuda": + return {} + return { + "allocated_mib": torch.cuda.memory_allocated(dev) / 2**20, + "reserved_mib": torch.cuda.memory_reserved(dev) / 2**20, + "max_reserved_mib": torch.cuda.max_memory_reserved(dev) / 2**20, + } + + +def _mp_get(q, stop, poll_s=0.2): + while True: + if stop.is_set(): + raise _Stopped() + try: + return pickle.loads(q.get(timeout=poll_s)) + except queue.Empty: + continue + + +def _mp_put(q, item, stop, poll_s=0.2): + # Pickled here, not in the queue's feeder thread, so a pickling error + # raises in the sender instead of silently dropping the message. + data = pickle.dumps(item, protocol=pickle.HIGHEST_PROTOCOL) + while True: + if stop.is_set(): + raise _Stopped() + try: + q.put(data, timeout=poll_s) + return + except queue.Full: + continue + + +def _mp_acquire(sem, stop, poll_s=0.2): + while not sem.acquire(timeout=poll_s): + if stop.is_set(): + raise _Stopped() + + +def _proc_setup(settings: dict) -> None: + import sys + + for path in settings.get("sys_path", []): + if path not in sys.path: + sys.path.insert(0, path) + if settings.get("switch_interval"): + sys.setswitchinterval(float(settings["switch_interval"])) + + +def _p1_main(settings, requests, camera_mode, q12, taken, ctrl, stop): + """proc mode, process P1: decode + detect + crop; crops to shared memory.""" + _proc_setup(settings) + bbox_detector = None + try: + try: + import warp as wp + + wp.init() + except ImportError: + pass + t = time.perf_counter() + make = _factory(settings, "detector") + bbox_detector = ( + make(settings) + if make is not None + else build_detector( + settings["detector_cfg"], settings["device"], settings["batch_size"] + ) + ) + warm = ( + warm_detector(bbox_detector) if settings.get("warm_detector", True) else [] + ) + config = stage_config_from_settings(settings, camera_mode) + prepare = PrepareStage( + bbox_detector, + config, + device=settings.get("device"), + own_stream=True, + ) + if settings.get("warp_mempool") and prepare.cuda: + _enable_warp_mempool(prepare.device) + ctrl.put( + ("ready", "prepare", os.getpid(), (time.perf_counter() - t) * 1000.0, warm) + ) + shm_dir = settings["shm_dir"] + + def to_shm(clip, crops): + path = os.path.join(shm_dir, f"{clip.request.index:05d}_{clip.stem}.u8.npy") + if crops: + array = None + try: + array = np.lib.format.open_memmap( + path, + mode="w+", + dtype=np.uint8, + shape=(len(crops), *crops[0].shape), + ) + for index, crop in enumerate(crops): + array[index] = crop + array.flush() + del array + array = None + clip.crops_path = path + except BaseException: + del array + with contextlib.suppress(OSError): + os.unlink(path) + raise + crops.clear() + + claimed = 0 + for request in claim_requests(requests, settings.get("claim_dir")): + claimed += 1 + clip = prepare.run(request, crops_out=to_shm) + _mp_put(q12, clip.without_pixels(), stop) + if settings.get("prepare_ahead", 1) <= 1: + _mp_acquire(taken, stop) + _mp_put(q12, (_END, claimed), stop) + ctrl.put(("done", "prepare", claimed)) + except _Stopped: + q12.cancel_join_thread() + except BaseException as exc: # noqa: BLE001 + q12.cancel_join_thread() + ctrl.put( + ( + "fatal", + "prepare", + f"{type(exc).__name__}: {exc}", + traceback.format_exc()[-4000:], + ) + ) + raise + finally: + if bbox_detector is not None and hasattr(bbox_detector, "close"): + with contextlib.suppress(Exception): + bbox_detector.close() + + +def _p2_main(settings, q12, q23, taken, slots, ctrl, stop): + """proc mode, process P2: DINOv3 + heads; head batches to P3 through host memory.""" + _proc_setup(settings) + try: + make = _factory(settings, "predictor") + predictor, load_ms = (make or load_predictor)(settings) + if settings.get("trim_models", True): + trim_for_stage(predictor, "head") + camera_mode = getattr(predictor.model, "camera_mode", "weak_perspective") + config = stage_config_from_settings(settings, camera_mode) + head = HeadStage(predictor, config) + backbone = { + "setup": getattr(predictor, "backbone_setup", None), + "warmup": warm_backbone(predictor) + if settings.get("backbone_warmup", True) + else None, + } + ctrl.put( + ( + "ready", + "head", + os.getpid(), + load_ms, + camera_mode, + _cuda_mem(head.device), + backbone, + ) + ) + while True: + item = _mp_get(q12, stop) + if isinstance(item, tuple) and item and item[0] == _END: + _mp_put(q23, ("end_of_queue", item[1], None), stop) + break + clip = item + if settings.get("prepare_ahead", 1) <= 1: + taken.release() + if clip.error is not None: + _mp_put(q23, ("fail", clip, None), stop) + continue + _mp_acquire(slots, stop) + clip.began = True + clip.times["s2_start"] = time.time() + _mp_put(q23, ("begin", clip, None), stop) + crops = None + try: + if clip.crops_path: + crops = np.load(clip.crops_path, mmap_mode="r") + head.run( + clip, + lambda hb, index=clip.request.index: _mp_put( + q23, ("batch", index, pack_head_batch(hb)), stop + ), + crops=crops if crops is not None else [], + ) + except _Stopped: + raise + except Exception as exc: # noqa: BLE001 + clip.fail("head", exc) + clip.times["failed_at"] = time.time() + _mp_put(q23, ("fail", clip.light(), None), stop) + if is_fatal_cuda_error(exc): + raise + if isinstance(exc, torch.cuda.OutOfMemoryError): + torch.cuda.empty_cache() + continue + finally: + del crops + if clip.crops_path: + with contextlib.suppress(OSError): + os.unlink(clip.crops_path) + clip.times["s2_end"] = time.time() + _mp_put(q23, ("end", clip.light(), None), stop) + ctrl.put(("done", "head", _cuda_mem(head.device), dynamo_counters())) + except _Stopped: + q23.cancel_join_thread() + except BaseException as exc: # noqa: BLE001 + q23.cancel_join_thread() + ctrl.put( + ( + "fatal", + "head", + f"{type(exc).__name__}: {exc}", + traceback.format_exc()[-4000:], + ) + ) + raise + + +def _p3_main(settings, q23, slots, ctrl, stop): + """proc mode, process P3: SOMA decode, mirror, smoothing and export, on the main thread.""" + _proc_setup(settings) + try: + make = _factory(settings, "predictor") + # P3 drops the backbone: do not prepare or compile it here. + predictor, load_ms = (make or load_predictor)( + without_backbone_options(settings) + ) + if settings.get("trim_models", True): + trim_for_stage(predictor, "soma") + camera_mode = getattr(predictor.model, "camera_mode", "weak_perspective") + config = stage_config_from_settings(settings, camera_mode) + soma = SomaStage(predictor, config, model_load_ms=load_ms) + if settings.get("warp_mempool") and soma.cuda: + _enable_warp_mempool(soma.device) + ctrl.put( + ( + "ready", + "soma", + os.getpid(), + load_ms, + camera_mode, + _cuda_mem(soma.device), + {"mhr_presort": getattr(predictor, "mhr_presort", None)}, + ) + ) + clips: dict[int, PreparedClip] = {} + while True: + kind, clip, payload = _mp_get(q23, stop) + if kind == "end_of_queue": + ctrl.put(("done", "soma", clip, _cuda_mem(soma.device))) + break + if kind == "begin": + clips[clip.request.index] = clip + try: + if not clip.intrinsics_per_image: + camera = resolve_clip_camera( + clip, config.use_perspective_cropping + ) + clip.intrinsics_per_image = dict.fromkeys( + clip.image_ids, camera + ) + soma.begin(clip) + except Exception as exc: # noqa: BLE001 + clip.fail("soma", exc) + continue + if kind == "batch": + current = clips.get(clip) + if current is not None and current.error is None: + try: + soma.add( + unpack_head_batch(payload, current.records, soma.device) + ) + except Exception as exc: # noqa: BLE001 + current.fail("soma", exc) + current.times["failed_at"] = time.time() + soma.discard() + if is_fatal_cuda_error(exc): + raise + if isinstance(exc, torch.cuda.OutOfMemoryError): + torch.cuda.empty_cache() + continue + # end / fail: the message carries P2's copy of the clip (times, error) + began = clips.pop(clip.request.index, None) + if began is not None: + began.times.update(clip.times) + if clip.error is not None and began.error is None: + began.error, began.error_class = clip.error, clip.error_class + began.error_stage, began.error_traceback = ( + clip.error_stage, + clip.error_traceback, + ) + clip = began + if kind == "end" and clip.error is None: + try: + soma.finish(clip) + except Exception as exc: # noqa: BLE001 + clip.fail("soma", exc) + clip.times["failed_at"] = time.time() + soma.discard() + if is_fatal_cuda_error(exc): + raise + if isinstance(exc, torch.cuda.OutOfMemoryError): + torch.cuda.empty_cache() + else: + clip.times.setdefault("failed_at", time.time()) + soma.discard() + if clip.began: + slots.release() + record = clip_record(clip) + record["cuda_p3"] = _cuda_mem(soma.device) + ctrl.put(("record", record)) + except _Stopped: + pass + except BaseException as exc: # noqa: BLE001 + ctrl.put( + ( + "fatal", + "soma", + f"{type(exc).__name__}: {exc}", + traceback.format_exc()[-4000:], + ) + ) + raise + + +def run_process_pipeline( + settings: dict, + requests: list[ClipRequest], + on_record: Callable[[dict], None], + on_event: Callable[[tuple], None] | None = None, + *, + ready_timeout_s: float = 900.0, +) -> dict: + """proc mode: run the three stages as three processes (P1 prepare, P2 head, + P3 SOMA); returns process info.""" + import multiprocessing as mp + import shutil + + soma_videos = int(settings.get("soma_videos", 2)) + if soma_videos < 1: + raise ValueError(f"soma_videos must be >= 1, got {soma_videos}") + ctx = mp.get_context("spawn") + shm_dir = settings["shm_dir"] + os.makedirs(shm_dir, exist_ok=True) + q12 = ctx.Queue(maxsize=1) + q23 = ctx.Queue() + ctrl = ctx.Queue() + taken = ctx.Semaphore(0) + slots = ctx.Semaphore(soma_videos) + stop = ctx.Event() + procs = { + "soma": ctx.Process( + target=_p3_main, args=(settings, q23, slots, ctrl, stop), name="t3-p3" + ), + "head": ctx.Process( + target=_p2_main, + args=(settings, q12, q23, taken, slots, ctrl, stop), + name="t3-p2", + ), + } + info: dict = {"ready": {}, "done": {}, "fatal": None, "exitcodes": {}} + recorded: set = set() + claimed_total = None + + def handle(message) -> None: + nonlocal claimed_total + kind = message[0] + if on_event is not None: + on_event(message) + if kind == "record": + recorded.add(message[1]["i"]) + on_record(message[1]) + elif kind == "ready": + stage = message[1] + entry: dict[str, Any] = { + "pid": message[2], + "load_ms": message[3], + "epoch": time.time(), + } + if len(message) > 5: + entry["camera_mode"] = message[4] + entry["cuda"] = message[5] + else: + entry["warmup"] = message[4] + if len(message) > 6 and message[6] is not None: + if stage == "head": + entry["backbone"] = message[6] + elif isinstance(message[6], dict): + entry.update(message[6]) + info["ready"][stage] = entry + elif kind == "done": + info["done"][message[1]] = { + "epoch": time.time(), + "detail": list(message[2:]), + } + if message[1] == "prepare": + claimed_total = message[2] + elif kind == "fatal": + info["fatal"] = { + "stage": message[1], + "error": message[2], + "traceback": message[3], + } + + def poll(timeout: float) -> bool: + try: + handle(ctrl.get(timeout=timeout)) + return True + except queue.Empty: + return False + + def drain_ctrl() -> None: + while poll(0.05): + pass + + def dead() -> list: + return [n for n, p in procs.items() if p.exitcode not in (None, 0)] + + prev_sigterm = None + in_main_thread = threading.current_thread() is threading.main_thread() + if in_main_thread: + prev_sigterm = signal.getsignal(signal.SIGTERM) + + def _on_sigterm(_signum, _frame): + raise SystemExit(143) + + signal.signal(signal.SIGTERM, _on_sigterm) + + for proc in procs.values(): + proc.start() + t0 = time.time() + try: + while not {"head", "soma"} <= set(info["ready"]): + poll(0.5) + if dead() or info["fatal"] or time.time() - t0 > ready_timeout_s: + drain_ctrl() + raise RuntimeError( + f"proc mode start failed: dead={dead()} fatal={info['fatal']}" + ) + for stage_name in ("head", "soma"): + if procs[stage_name].exitcode == 0 and stage_name not in info["ready"]: + drain_ctrl() + if stage_name not in info["ready"]: + raise RuntimeError( + f"proc mode start failed: {stage_name} exited 0 without ready" + ) + camera_mode = info["ready"]["head"]["camera_mode"] + procs["prepare"] = ctx.Process( + target=_p1_main, + args=(settings, requests, camera_mode, q12, taken, ctrl, stop), + name="t3-p1", + ) + procs["prepare"].start() + while True: + poll(0.5) + if info["fatal"] or dead(): + drain_ctrl() + raise RuntimeError( + f"proc mode stage failed: dead={dead()} fatal={info['fatal']}" + ) + if "soma" in info["done"]: + break + if procs["soma"].exitcode is not None: + drain_ctrl() + if "soma" in info["done"]: + break + raise RuntimeError( + f"proc mode stage failed: soma exited {procs['soma'].exitcode} without done" + ) + except BaseException as exc: # noqa: BLE001 + info["abort"] = f"{type(exc).__name__}: {exc}" + stop.set() + finally: + deadline = time.time() + 60 + for proc in procs.values(): + proc.join(timeout=max(0.0, deadline - time.time())) + drain_ctrl() + for name, proc in procs.items(): + if proc.is_alive(): + proc.terminate() + proc.join(timeout=10) + if proc.is_alive(): + proc.kill() + proc.join(timeout=5) + info["exitcodes"][name] = proc.exitcode + shutil.rmtree(shm_dir, ignore_errors=True) + if in_main_thread and prev_sigterm is not None: + signal.signal(signal.SIGTERM, prev_sigterm) + info["claimed"] = claimed_total + info["recorded"] = sorted(recorded) + if "abort" in info: + # Clips this worker claimed (all, without a claim dir) and did not + # finish are lost with the failed process. + claim_dir = settings.get("claim_dir") + p1_pid = info["ready"].get("prepare", {}).get("pid") + for request in requests: + if request.index in recorded: + continue + if claim_dir: + if p1_pid is None: + continue + claim = os.path.join(claim_dir, f"{request.index:05d}.claim") + try: + with open(claim) as fh: + owner = int(fh.read().split()[0]) + except (OSError, ValueError, IndexError): + continue + if owner != p1_pid: + continue + on_record( + { + "i": request.index, + "name": request.name, + "video": request.video, + "out_root": request.out_root, + "status": "aborted", + "error": info["abort"], + "t_start_epoch": None, + "t_end_epoch": time.time(), + } + ) + return info diff --git a/src/python/isaaccapture_egopost/inference/scripts/run_egohand_three_stage.py b/src/python/isaaccapture_egopost/inference/scripts/run_egohand_three_stage.py new file mode 100644 index 0000000000..4773f5e350 --- /dev/null +++ b/src/python/isaaccapture_egopost/inference/scripts/run_egohand_three_stage.py @@ -0,0 +1,672 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: LicenseRef-OpenMDW-1.1 + +"""Model-resident three-stage EgoHand driver over a queue of videos. + +Usage: + python inference/scripts/run_egohand_three_stage.py --queue queue.json \\ + [--mode thr|proc|serial] [--summary summary.json] [--claim_dir DIR] \\ + [--backbone_compile off|block|whole] [--backbone_bf16_weights] \\ + -- + +``queue.json`` has ``{"items": [{"name", "video", "intrinsics", "out_root"}, ...]}``. +Exit codes: 0 all ok, 3 queue completed with per-item failures, 1 fatal CUDA/runtime +abort, 2 invalid input. See ``inference/pipeline/three_stage.py`` for stage details. +""" + +# ruff: noqa: E402 +import argparse +import hashlib +import importlib.util +import json +import os +import sys +import tempfile +import time +import traceback +import uuid +from pathlib import Path + +T_START = time.time() +T0 = time.perf_counter() + +_HERE = Path(__file__).resolve() +PROJECT_ROOT = _HERE.parents[2] +if str(PROJECT_ROOT) not in sys.path: + sys.path.insert(0, str(PROJECT_ROOT)) + +# Same module-level setup as `python run_egohand_inference_pipeline.py` +# (torch.load patch, sys.path); also runs in the spawned proc-mode children, +# which import this file as their main module. +_CLI_PATH = _HERE.parent / "run_egohand_inference_pipeline.py" +_spec = importlib.util.spec_from_file_location("egopost_cli", _CLI_PATH) +cli = importlib.util.module_from_spec(_spec) +sys.modules.setdefault("egopost_cli", cli) +_spec.loader.exec_module(cli) + +import torch + +from inference.media.runtime_profile import get_runtime_profile +from inference.pipeline import three_stage as ts + +#: Exit status when the queue ran to the end but some items failed. +EXIT_SOME_ITEMS_FAILED = 3 + + +def parse_driver_args(argv): + ap = argparse.ArgumentParser( + description=(__doc__ or "Model-resident three-stage EgoHand driver.").split( + "\n\n" + )[0] + ) + ap.add_argument( + "--queue", required=True, help="Queue JSON file listing video items." + ) + ap.add_argument("--summary", default=None, help="Output summary JSON path.") + ap.add_argument( + "--mode", + choices=("thr", "proc", "serial"), + default="thr", + help="Execution mode: thr (threads), proc (3 spawned processes), or serial.", + ) + ap.add_argument( + "--claim_dir", + default=None, + help="Shared directory for multi-worker exclusive item claiming.", + ) + ap.add_argument( + "--soma_videos", + type=int, + default=2, + help="Max in-flight videos between stage 2 and stage 3 (>= 1).", + ) + ap.add_argument( + "--prepare_ahead", + type=int, + default=1, + help="Videos stage 1 may prepare ahead of stage 2 (>= 1).", + ) + ap.add_argument( + "--crop_workers", + type=int, + default=8, + help="Worker threads for stage 1 hand cropping (>= 1).", + ) + ap.add_argument( + "--norm_workers", + type=int, + default=4, + help="Worker threads for stage 2 crop normalization (>= 1).", + ) + ap.add_argument( + "--warp_mempool", + action="store_true", + help="Enable Warp CUDA memory pool during the run.", + ) + ap.add_argument( + "--switch_interval", + type=float, + default=None, + help="Optional sys.setswitchinterval() in seconds (> 0).", + ) + ap.add_argument( + "--warm_detector", + action=argparse.BooleanOptionalAction, + default=True, + help="Warm up RT-DETR ONNX batch sizes at startup.", + ) + ap.add_argument( + "--trim_models", + action=argparse.BooleanOptionalAction, + default=True, + help="Drop unused submodules in proc-mode workers.", + ) + ap.add_argument( + "--shm_root", + default="/dev/shm", + help="Directory root for proc-mode crop transfer files.", + ) + ap.add_argument( + "--backbone_compile", + choices=ts.BACKBONE_COMPILE_SCOPES, + default=None, + help="Compile DINOv3 backbone with deterministic Inductor options (off|block|whole).", + ) + ap.add_argument( + "--backbone_bf16_weights", + action="store_true", + help="Cast DINOv3 Linear/Conv2d weights to bf16 once at load (requires --dtype bfloat16).", + ) + ap.add_argument( + "--backbone_warmup", + action=argparse.BooleanOptionalAction, + default=True, + help="Warm up compiled backbone before starting the queue.", + ) + ap.add_argument( + "--inductor_cache_root", + default=None, + help="Root directory for versioned TORCHINDUCTOR_CACHE_DIR.", + ) + if "--" not in argv: + # Parse first so -h/--help exits 0 with usage text before rejecting missing --. + ap.parse_args(argv) + ap.error("missing -- before the pipeline arguments") + cut = argv.index("--") + opt = ap.parse_args(argv[:cut]) + for name in ("soma_videos", "prepare_ahead", "crop_workers", "norm_workers"): + if getattr(opt, name) < 1: + ap.error(f"--{name} must be >= 1, got {getattr(opt, name)}") + if opt.switch_interval is not None and not (opt.switch_interval > 0): + ap.error(f"--switch_interval must be > 0, got {opt.switch_interval}") + return opt, argv[cut + 1 :] + + +def check_supported(args) -> None: + """Reject the pipeline options the three-stage driver does not implement.""" + unsupported = [] + if not args.no_save_videos: + unsupported.append("overlay videos (pass --no_save_videos)") + if args.save_images: + unsupported.append("--save_images") + if args.save_npzs: + unsupported.append("--save_npzs") + if args.per_frame_results: + unsupported.append("--per_frame_results") + if args.postprocessing_qc: + unsupported.append("--postprocessing_qc") + if args.frame_batch_size is not None: + unsupported.append("--frame_batch_size") + if args.max_seconds is not None: + unsupported.append("--max_seconds") + if args.perf_output: + unsupported.append("--perf_output") + if not args.device.startswith("cuda"): + unsupported.append(f"--device {args.device}") + if unsupported: + cli.reject_input( + "run_egohand_three_stage.py does not support: " + ", ".join(unsupported) + ) + + +def default_summary_path(requests, claim_dir) -> str: + """Next to the first item's out_root; per process when workers share a queue + (``--claim_dir``), so they do not overwrite each other's summary.""" + name = ( + f"three_stage_summary_{os.getpid()}.json" + if claim_dir + else "three_stage_summary.json" + ) + return os.path.join( + os.path.dirname(requests[0].out_root) if requests else ".", name + ) + + +def exit_status(run_status: str, records: list) -> int: + """0: every item ok; 3: the queue ran to the end, some items failed; + 1: the run was aborted (CUDA error).""" + if run_status != "done": + return cli.EXIT_RUNTIME_ERROR + if any(record["status"] != "ok" for record in records): + return EXIT_SOME_ITEMS_FAILED + return 0 + + +def resolve_backbone_compile(opt, args) -> str: + """--backbone_compile, or block for the pipeline's --dino_compile.""" + if args.dino_compile and opt.backbone_compile not in (None, "block"): + cli.reject_input( + f"--dino_compile (= --backbone_compile block) conflicts with " + f"--backbone_compile {opt.backbone_compile}" + ) + if opt.backbone_compile is not None: + return opt.backbone_compile + return "block" if args.dino_compile else "off" + + +def check_bf16_weights_dtype(opt, args) -> None: + """--backbone_bf16_weights gives the same values only under bf16 autocast.""" + if opt.backbone_bf16_weights and args.dtype != "bfloat16": + cli.reject_input( + "--backbone_bf16_weights needs --dtype bfloat16 (got --dtype " + f"{args.dtype}): the weights only keep their values when the " + "backbone runs under bf16 autocast" + ) + + +def check_backbone_compile_supported(scope: str) -> None: + """Reject a compiled backbone where the runtime profile has no torch.compile + (the release profile; ``--dino_compile`` is rejected there the same way).""" + profile = get_runtime_profile() + if scope != "off" and not profile.compilation: + cli.reject_input( + f"--backbone_compile {scope} is unsupported in the {profile.name} " + "runtime profile" + ) + + +def code_version() -> dict: + """Hash of the running egohand/ + inference/ sources and the compiler stack.""" + digest = hashlib.sha256() + files = 0 + for top in ("egohand", "inference"): + root = PROJECT_ROOT / top + for path in sorted(root.rglob("*.py")): + rel = path.relative_to(PROJECT_ROOT).as_posix() + digest.update(rel.encode() + b"\0") + digest.update(path.read_bytes() + b"\0") + files += 1 + versions = {"torch": torch.__version__} + try: + import triton + + versions["triton"] = triton.__version__ + except ImportError: + versions["triton"] = None + digest.update(json.dumps(versions, sort_keys=True).encode()) + return {"hash": digest.hexdigest(), "files": files, **versions} + + +# Environment variable -> (value, torch._inductor.config attribute, attribute +# value) for a compiled backbone; why: three_stage.DETERMINISTIC_INDUCTOR_OPTIONS. +COMPILE_ENV = { + "TORCHINDUCTOR_DYNAMIC_SCALE_RBLOCK": ("0", "dynamic_scale_rblock", False), + "TORCHINDUCTOR_DETERMINISTIC": ("1", "deterministic", True), +} + + +def setup_compile_env(opt, scope: str) -> dict: + """Process environment for a compiled backbone (inherited by proc-mode children). + + COMPILE_ENV (also applied to an already imported Inductor config) and a + TORCHINDUCTOR_CACHE_DIR per code version. Dynamo resets the global + ``deterministic`` after each traced frame; the backbone compiles get it from + their options (three_stage.DETERMINISTIC_INDUCTOR_OPTIONS). + """ + config = sys.modules.get("torch._inductor.config") + config_was_imported = config is not None + previous = {} + for var, (value, attr, attr_value) in COMPILE_ENV.items(): + previous[var] = os.environ.get(var) + os.environ[var] = value + if config is not None: + setattr(config, attr, attr_value) + version = code_version() + root = ( + opt.inductor_cache_root + or os.environ.get("TORCHINDUCTOR_CACHE_DIR") + or os.path.join( + tempfile.gettempdir(), + "torchinductor_" + (os.environ.get("USER") or "user"), + ) + ) + cache_dir = os.path.join(root, f"egopost_{version['hash'][:16]}") + os.makedirs(cache_dir, exist_ok=True) + stamp = os.path.join(cache_dir, "egopost_code_version.json") + if not os.path.exists(stamp): + tmp = f"{stamp}.{os.getpid()}.{uuid.uuid4().hex[:8]}.tmp" + with open(tmp, "w") as fh: + json.dump({**version, "created_epoch": time.time()}, fh, indent=1) + os.replace(tmp, stamp) + os.environ["TORCHINDUCTOR_CACHE_DIR"] = cache_dir + info = { + "scope": scope, + "code_version": version, + "inductor_cache_root": root, + "inductor_cache_dir": cache_dir, + "triton_cache_dir": os.environ.get("TRITON_CACHE_DIR") + or os.path.join(cache_dir, "triton"), + } + for var, (value, _, _) in COMPILE_ENV.items(): + info[var] = value + info[f"{var}_before"] = previous[var] + info["inductor_config_imported_before"] = config_was_imported + return info + + +def proc_mem() -> dict: + out = {} + try: + with open("/proc/self/status") as fh: + for line in fh: + if line.startswith(("VmRSS:", "VmHWM:")): + key, value = line.split(":", 1) + out[key.lower() + "_kb"] = int(value.split()[0]) + except OSError: + pass + return out + + +def cuda_mem(device: str | torch.device | None = None) -> dict: + if not torch.cuda.is_available(): + return {} + dev = torch.device(device) if device is not None else None + if dev is not None and dev.type != "cuda": + return {} + return { + "allocated_mib": torch.cuda.memory_allocated(dev) / 2**20, + "reserved_mib": torch.cuda.memory_reserved(dev) / 2**20, + "max_allocated_mib": torch.cuda.max_memory_allocated(dev) / 2**20, + "max_reserved_mib": torch.cuda.max_memory_reserved(dev) / 2**20, + } + + +def main(): + opt, pipeline_cli = parse_driver_args(sys.argv[1:]) + sys.argv = [str(_CLI_PATH)] + pipeline_cli + args = cli.parse_args() + check_supported(args) + compile_scope = resolve_backbone_compile(opt, args) + check_backbone_compile_supported(compile_scope) + check_bf16_weights_dtype(opt, args) + backbone_env = ( + setup_compile_env(opt, compile_scope) if compile_scope != "off" else None + ) + if backbone_env: + print( + f"[three_stage] backbone compile {compile_scope}: " + + " ".join(f"{var}={backbone_env[var]}" for var in COMPILE_ENV) + + f" TORCHINDUCTOR_CACHE_DIR={backbone_env['inductor_cache_dir']}", + flush=True, + ) + cli.check_gpu_visible(args.device) + if opt.switch_interval: + sys.setswitchinterval(opt.switch_interval) + hands = ["left", "right"] if args.hand == "both" else [args.hand] + if not args.bbox_detector_config: + cli.reject_input("--bbox_detector_config is required.") + try: + detector_cfg = cli._load_detector_config(args.bbox_detector_config) + except cli.DetectorConfigError as exc: + cli.reject_input(str(exc)) + if args.egohand_ckpt is None: + args.egohand_ckpt = cli.hf_download(args.egohand_ckpt_hf_path) + if args.soma_hand_assets is None: + from soma import get_assets_dir + + args.soma_hand_assets = str(get_assets_dir()) + + try: + with open(opt.queue) as fh: + queue_data = json.load(fh) + queue_items = queue_data["items"] + if not isinstance(queue_items, list): + raise TypeError("'items' must be a list") + requests = [ + ts.ClipRequest( + index=i, + name=item["name"], + video=item["video"], + intrinsics=item.get("intrinsics"), + out_root=item["out_root"], + ) + for i, item in enumerate(queue_items) + ] + except (OSError, json.JSONDecodeError, KeyError, TypeError) as exc: + cli.reject_input(f"Invalid --queue file {opt.queue!r}: {exc}") + summary_path = opt.summary or default_summary_path(requests, opt.claim_dir) + cli.prepare_output_dir(Path(summary_path).parent) + if opt.claim_dir: + os.makedirs(opt.claim_dir, exist_ok=True) + for root in sorted({r.out_root for r in requests}): + cli.prepare_output_dir(Path(root)) + + settings = { + "egohand_ckpt": args.egohand_ckpt, + "soma_hand_assets": args.soma_hand_assets, + "batch_size": args.batch_size, + "device": args.device, + "dtype": args.dtype, + "smooth": args.postprocessing_smooth, + "use_perspective_cropping": args.perspective_cropping, + "soma_batch_size": args.soma_batch_size, + "mhr_presorted_sparse": args.mhr_presorted_sparse, + "dino_compile": args.dino_compile, + "backbone_compile": compile_scope, + "backbone_bf16_weights": opt.backbone_bf16_weights, + "backbone_warmup": opt.backbone_warmup, + "detector_cfg": detector_cfg, + "hands": hands, + "crop_workers": opt.crop_workers, + "norm_workers": opt.norm_workers, + "prepare_ahead": opt.prepare_ahead, + "soma_videos": opt.soma_videos, + "warp_mempool": opt.warp_mempool, + "trim_models": opt.trim_models, + "warm_detector": opt.warm_detector, + "switch_interval": opt.switch_interval, + "rectify_pixel_aspect_ratio": args.rectify_pixel_aspect_ratio, + "claim_dir": opt.claim_dir, + "shm_dir": os.path.join( + opt.shm_root, + f"egopost_three_stage_{os.getpid()}_{int(T_START)}_{uuid.uuid4().hex[:8]}", + ), + "sys_path": [str(PROJECT_ROOT)], + "perf_metadata": { + "checkpoint": Path(args.egohand_ckpt).stem, + "batch_size": args.batch_size, + "soma_batch_size": args.soma_batch_size, + "dtype": args.dtype, + "dino_compile": args.dino_compile, + "backbone_compile": compile_scope, + "backbone_bf16_weights": opt.backbone_bf16_weights, + "perspective_cropping": args.perspective_cropping, + "three_stage_mode": opt.mode, + }, + } + records = [] + summary = { + "driver": "run_egohand_three_stage.py", + "mode": opt.mode, + "options": vars(opt), + "pipeline_cli": pipeline_cli, + "settings": {k: v for k, v in settings.items() if k != "detector_cfg"}, + "detector_cfg": detector_cfg, + "driver_start_epoch": T_START, + "pid": os.getpid(), + "backbone": {"env": backbone_env}, + "records": records, + } + + def flush(): + tmp = summary_path + ".tmp" + with open(tmp, "w") as fh: + json.dump(summary, fh, indent=1, default=str) + os.replace(tmp, summary_path) + + def on_record(record): + record = dict(record) + record["t_start_s"] = ( + (record["t_start_epoch"] - T_START) if record.get("t_start_epoch") else None + ) + record["t_end_s"] = ( + (record["t_end_epoch"] - T_START) if record.get("t_end_epoch") else None + ) + if opt.mode != "proc": + record["cuda"] = cuda_mem(args.device) + record["proc"] = proc_mem() + records.append(record) + print( + f"[three_stage] {record['i']} {record['name']} {record['status']} " + f"wall={record.get('wall_s') or 0:.2f}s frames={record.get('frames')} " + f"crops={record.get('crops')}" + + (f" error={record.get('error')}" if record["status"] != "ok" else ""), + flush=True, + ) + flush() + + if opt.mode == "proc": + # The detector is built in the stage-1 process; check the backend + # name here so a typo is still an invalid-input exit. + backend = detector_cfg["detector_backend"] + try: + spec = ( + importlib.util.find_spec( + f"inference.hand_detector_2d.configs.{backend}" + ) + if isinstance(backend, str) and backend.isidentifier() + else None + ) + except (ModuleNotFoundError, ValueError): + spec = None + if spec is None: + cli.reject_input( + f"Unknown detector_backend {backend!r} in the detector config; see " + "inference/hand_detector_2d/configs/ for the available backends" + ) + summary["ready_at_s"] = None + print( + "[three_stage] proc mode: starting P3 (SOMA) and P2 (head), then P1 (prepare)", + flush=True, + ) + + def on_event(message): + if message[0] == "ready": + warm = ( + (message[6] or {}).get("warmup") + if message[1] == "head" and len(message) > 6 + else None + ) + print( + f"[three_stage] ready: {message[1]} pid={message[2]} load {message[3] / 1000:.2f}s" + + ( + f" backbone warm-up first call {warm['first_call_s']:.2f}s" + if warm + else "" + ), + flush=True, + ) + + info = ts.run_process_pipeline(settings, requests, on_record, on_event) + summary["processes"] = info + summary["mhr_presort"] = ( + info.get("ready", {}).get("soma", {}).get("mhr_presort") + ) + head_ready = info.get("ready", {}).get("head", {}).get("backbone") or {} + summary["backbone"].update(head_ready) + head_done = info.get("done", {}).get("head", {}).get("detail") or [] + if len(head_done) > 1: + summary["backbone"]["dynamo_end"] = head_done[1] + ready = [ + v.get("epoch") for v in info.get("ready", {}).values() if v.get("epoch") + ] + if ready: + summary["ready_epoch"] = max(ready) + summary["ready_at_s"] = max(ready) - T_START + summary["status"] = "aborted" if "abort" in info else "done" + else: + try: + import warp as wp + + wp.init() # once, on this thread, before any stage thread uses Warp + except ImportError: + pass + t = time.perf_counter() + try: + bbox_detector, _ = cli._build_detector_from_config( + detector_cfg, args.device, args.batch_size + ) + except cli.DetectorConfigError as exc: + cli.reject_input(str(exc)) + if getattr(bbox_detector, "reports_in_source_frame", False): + cli.reject_input( + "run_egohand_three_stage.py does not support: detectors that report boxes in the source frame" + ) + predictor, load_ms = ts.load_predictor(settings) + camera_mode = getattr(predictor.model, "camera_mode", "weak_perspective") + config = ts.stage_config_from_settings(settings, camera_mode) + try: + prepare = ts.PrepareStage( + bbox_detector, + config, + device=args.device, + own_stream=(opt.mode == "thr"), + ) + except ts.UnsupportedOption as exc: + cli.reject_input(f"run_egohand_three_stage.py does not support: {exc}") + head = ts.HeadStage(predictor, config, own_stream=(opt.mode == "thr")) + soma = ts.SomaStage(predictor, config, model_load_ms=load_ms) + try: + warm = ts.warm_detector(bbox_detector) if opt.warm_detector else [] + backbone_warm = ts.warm_backbone(predictor) if opt.backbone_warmup else None + summary["backbone"].update( + setup=getattr(predictor, "backbone_setup", None), warmup=backbone_warm + ) + summary.update( + mhr_presort=predictor.mhr_presort, + model_load_ms=load_ms, + load_total_s=time.perf_counter() - t, + camera_mode=camera_mode, + detector_warmup=warm, + ready_epoch=time.time(), + ready_at_s=time.perf_counter() - T0, + cuda_ready=cuda_mem(args.device), + ) + print( + f"[three_stage] mode={opt.mode} ready at {summary['ready_at_s']:.2f}s " + f"(model load {load_ms / 1000:.2f}s, detector warm-up " + f"{sum(w['s'] for w in warm):.2f}s" + + ( + f", backbone {compile_scope} warm-up first call " + f"{backbone_warm['first_call_s']:.2f}s then " + f"{', '.join(f'{v:.1f}' for v in backbone_warm['later_calls_ms'])} ms" + if backbone_warm + else "" + ) + + ")", + flush=True, + ) + flush() + claimed = ts.claim_requests(requests, opt.claim_dir) + if opt.mode == "serial": + try: + ts.run_serial( + prepare, + head, + soma, + claimed, + on_record, + warp_mempool=opt.warp_mempool, + ) + summary["status"] = "done" + except Exception as exc: # noqa: BLE001 + summary["status"] = "aborted" + summary["fatal"] = f"{type(exc).__name__}: {exc}" + summary["fatal_traceback"] = traceback.format_exc()[-4000:] + else: + runner = ts.ThreadedThreeStage( + prepare, + head, + soma, + prepare_ahead=opt.prepare_ahead, + soma_videos=opt.soma_videos, + warp_mempool=opt.warp_mempool, + ) + runner.run(claimed, on_record) + summary["status"] = "done" if runner.fatal is None else "aborted" + if runner.fatal is not None: + summary["fatal"] = f"{type(runner.fatal).__name__}: {runner.fatal}" + summary["fatal_traceback"] = runner.fatal_traceback + finally: + if hasattr(bbox_detector, "close"): + bbox_detector.close() + summary["cuda_end"] = cuda_mem(args.device) + summary["proc_end"] = proc_mem() + if compile_scope != "off": + summary["backbone"]["dynamo_end"] = ts.dynamo_counters() + summary["done_epoch"] = time.time() + summary["t_done_s"] = time.perf_counter() - T0 + flush() + ok = sum(r["status"] == "ok" for r in records) + print( + f"[three_stage] {summary['status']}: {ok}/{len(records)} ok, " + f"{summary['t_done_s']:.1f}s since driver start; summary {summary_path}", + flush=True, + ) + status = exit_status(summary["status"], records) + if status: + sys.exit(status) + + +if __name__ == "__main__": + main() diff --git a/src/python/isaaccapture_egopost/inference/tests/pipeline/test_backbone_options.py b/src/python/isaaccapture_egopost/inference/tests/pipeline/test_backbone_options.py new file mode 100644 index 0000000000..c9fe0f3149 --- /dev/null +++ b/src/python/isaaccapture_egopost/inference/tests/pipeline/test_backbone_options.py @@ -0,0 +1,518 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: LicenseRef-OpenMDW-1.1 + +"""Backbone options of the three-stage driver (--backbone_compile / _bf16_weights, +warm-up, per-code-version Inductor cache, deterministic Inductor). A +two-block DINOv3 with random weights; compiled paths use the ``eager`` +torch.compile backend (graph capture and dispatch), except one CUDA test that +checks the settings in the kernels Inductor generates.""" + +from __future__ import annotations + +import argparse +import os +import sys +from types import SimpleNamespace + +import pytest +import torch + +pytest.importorskip("dinov3") + +from egohand.models.backbones.dinov3 import DinoV3Backbone # noqa: E402 +from inference.pipeline import three_stage as ts # noqa: E402 +from inference.pipeline.predictor import EgoHandPredictor # noqa: E402 + +_TINY = dict( + img_size=32, + patch_size=16, + in_chans=3, + pos_embed_rope_base=100, + pos_embed_rope_normalize_coords="separate", + pos_embed_rope_rescale_coords=2, + pos_embed_rope_dtype="fp32", + embed_dim=64, + depth=2, + num_heads=4, + ffn_ratio=2.0, + qkv_bias=True, + layerscale_init=1.0e-05, + norm_layer="layernormbf16", + ffn_layer="swiglu", + ffn_bias=True, + proj_bias=True, + n_storage_tokens=4, + mask_k_bias=True, +) + + +def _build_tiny(monkeypatch, **arch): + monkeypatch.setitem(DinoV3Backbone._ARCH_KWARGS, "tiny", {**_TINY, **arch}) + torch.manual_seed(0) + backbone = DinoV3Backbone(name="tiny", drop_path_rate=0.0).eval() + # Non-trivial layerscale so every block changes the tokens visibly. + with torch.no_grad(): + for module in backbone.encoder.modules(): + if hasattr(module, "gamma"): + module.gamma.fill_(0.5) + return backbone + + +@pytest.fixture +def tiny(monkeypatch): + return _build_tiny(monkeypatch) + + +def _x(batch, h=32, w=48, seed=1): + g = torch.Generator().manual_seed(seed) + return torch.randn(batch, 3, h, w, generator=g) + + +def _fresh_dynamo(): + torch._dynamo.reset() + + +# ----------------------------------------------------------------- compile scopes + + +@pytest.mark.parametrize("scope", ["block", "whole"]) +def test_compiled_full_batch_equals_eager_and_tail_stays_eager(tiny, scope): + _fresh_dynamo() + x = _x(4) + with torch.no_grad(): + ref_full = tiny(x) + ref_tail = tiny(x[:3]) + tiny.enable_full_batch_compile(4, scope=scope, backend="eager") + with torch.no_grad(): + got_full = tiny(x) + got_tail = tiny(x[:3]) + assert torch.equal(got_full, ref_full) + assert torch.equal(got_tail, ref_tail) + if scope == "whole": + assert tiny._compiled_whole is not None and tiny._compiled_blocks is None + else: + assert tiny._compiled_blocks is not None and tiny._compiled_whole is None + # Grad-enabled calls never take the compiled path. + assert torch.equal(tiny(x).detach(), ref_full) + + +def test_compile_kwargs_options_replace_mode(tiny, monkeypatch): + calls = [] + + def fake_compile(fn, **kwargs): + calls.append(kwargs) + return fn + + monkeypatch.setattr(torch, "compile", fake_compile) + tiny.enable_full_batch_compile(2) + with torch.no_grad(): + tiny(_x(2)) + assert calls and all( + c == dict(backend="inductor", fullgraph=True, dynamic=False, mode="default") + for c in calls + ) + assert len(calls) == len(tiny.encoder.blocks) + + calls.clear() + tiny._compiled_blocks = None + tiny.enable_full_batch_compile( + 2, scope="whole", options={"dynamic_scale_rblock": False} + ) + with torch.no_grad(): + tiny(_x(2)) + assert calls == [ + dict( + backend="inductor", + fullgraph=True, + dynamic=False, + options={"dynamic_scale_rblock": False}, + ) + ] + + +def test_compile_settings_are_fixed_once_built(tiny): + _fresh_dynamo() + tiny.enable_full_batch_compile(2, scope="whole", backend="eager") + with torch.no_grad(): + tiny(_x(2)) + tiny.enable_full_batch_compile(2, scope="whole", backend="eager") # same: ok + with pytest.raises(RuntimeError, match="cannot change"): + tiny.enable_full_batch_compile(2, scope="block", backend="eager") + with pytest.raises(ValueError, match="scope"): + DinoV3Backbone.enable_full_batch_compile(tiny, 2, scope="graph") + + +# ----------------------------------------------------------------- bf16 weights + + +def test_bf16_weights_give_the_autocast_result_bitwise(tiny): + x = _x(3) + with torch.no_grad(), torch.autocast("cpu", dtype=torch.bfloat16): + ref = tiny(x) + converted = tiny.cast_matmul_weights_bf16() + with torch.no_grad(), torch.autocast("cpu", dtype=torch.bfloat16): + got = tiny(x) + assert torch.equal(got, ref) + assert ref.dtype == got.dtype + # 2 blocks x (qkv, proj, w1, w2, w3) + the patch embedding conv. + assert converted == 11 + enc = tiny.encoder + assert enc.blocks[0].attn.qkv.weight.dtype == torch.bfloat16 + assert enc.blocks[0].attn.qkv.bias.dtype == torch.bfloat16 + assert enc.patch_embed.proj.weight.dtype == torch.bfloat16 + assert enc.blocks[0].norm1.weight.dtype == torch.float32 + assert enc.norm.weight.dtype == torch.float32 + assert enc.rope_embed.periods.dtype == torch.float32 + + +# ----------------------------------------------------------------- settings / configure + + +def test_compile_scope_from_settings(): + assert ts.backbone_compile_scope({}) == "off" + assert ts.backbone_compile_scope({"dino_compile": True}) == "block" + assert ts.backbone_compile_scope({"backbone_compile": "whole"}) == "whole" + assert ( + ts.backbone_compile_scope({"dino_compile": True, "backbone_compile": "off"}) + == "off" + ) + with pytest.raises(ValueError): + ts.backbone_compile_scope({"backbone_compile": "graph"}) + stripped = ts.without_backbone_options( + { + "dino_compile": True, + "backbone_compile": "whole", + "backbone_bf16_weights": True, + "batch_size": 32, + } + ) + assert not ts.backbone_options_active(stripped) + assert stripped["batch_size"] == 32 + + +class _RecordingBackbone: + def __init__(self): + self.calls = [] + + def enable_full_batch_compile(self, batch, **kwargs): + self.calls.append(("compile", batch, kwargs)) + + def cast_matmul_weights_bf16(self): + self.calls.append(("bf16",)) + return 11 + + +def _fake_predictor(backbone, batch_size=32, dtype=torch.bfloat16): + predictor = object.__new__(EgoHandPredictor) + predictor.model = SimpleNamespace(backbone=backbone) + predictor.batch_size = batch_size + predictor.dtype = dtype + return predictor + + +def test_configure_backbone_all_off_touches_nothing(): + backbone = _RecordingBackbone() + info = ts.configure_backbone(_fake_predictor(backbone), {}) + assert backbone.calls == [] + assert info == {"compile": "off", "bf16_weights": False} + + +_DET = {"dynamic_scale_rblock": False, "deterministic": True} + + +@pytest.mark.parametrize( + "settings, calls", + [ + ( + {"dino_compile": True}, + [("compile", 32, {"scope": "block", "options": _DET})], + ), + ( + {"backbone_compile": "whole", "backbone_bf16_weights": True}, + [ + ("bf16",), + ("compile", 32, {"scope": "whole", "options": _DET}), + ], + ), + ({"backbone_bf16_weights": True}, [("bf16",)]), + ], +) +def test_configure_backbone_order(settings, calls): + backbone = _RecordingBackbone() + info = ts.configure_backbone(_fake_predictor(backbone), settings) + assert backbone.calls == calls + assert info["compile"] == ts.backbone_compile_scope(settings) + if info["compile"] != "off": + assert info["compile_options"] == _DET + + +@pytest.mark.parametrize("dtype", [torch.float32, torch.float16]) +def test_bf16_weights_need_the_bfloat16_dtype(dtype): + backbone = _RecordingBackbone() + with pytest.raises(ValueError, match="bfloat16"): + ts.configure_backbone( + _fake_predictor(backbone, dtype=dtype), {"backbone_bf16_weights": True} + ) + assert backbone.calls == [] + + +def test_driver_rejects_bf16_weights_without_bfloat16(monkeypatch, capsys, driver): + opt, _ = driver.parse_driver_args( + ["--queue", "q.json", "--backbone_bf16_weights", "--"] + ) + for dtype in ("float32", "float16"): + args = _cli_args(monkeypatch, driver, "--dtype", dtype) + with pytest.raises(SystemExit) as exc: + driver.check_bf16_weights_dtype(opt, args) + assert exc.value.code == driver.cli.EXIT_INVALID_INPUT + assert "--dtype bfloat16" in capsys.readouterr().err + driver.check_bf16_weights_dtype( + opt, _cli_args(monkeypatch, driver, "--dtype", "bfloat16") + ) + + +# ----------------------------------------------------------------- warm-up + + +def test_warm_backbone_skips_uncompiled_backbones(tiny): + predictor = SimpleNamespace( + model=SimpleNamespace(backbone=tiny, _backbone_crop_w=(32, -32)), + device="cpu", + dtype=torch.float32, + ) + assert ts.warm_backbone(predictor) is None + assert ts.warm_backbone(SimpleNamespace(model=SimpleNamespace())) is None + + +def test_warm_backbone_compiles_once_for_the_head_call(tiny): + _fresh_dynamo() + tiny.enable_full_batch_compile(2, scope="whole", backend="eager") + predictor = SimpleNamespace( + model=SimpleNamespace(backbone=tiny, _backbone_crop_w=(32, -32)), + device="cpu", + dtype=torch.float32, + ) + rng_before = torch.random.get_rng_state() + warm = ts.warm_backbone(predictor) + assert torch.equal(torch.random.get_rng_state(), rng_before) + assert warm["batch"] == 2 + assert warm["input_shape"] == [2, 3, 256, 192] + assert len(warm["later_calls_ms"]) == 2 + graphs = warm["dynamo_after"]["unique_graphs"] + assert graphs >= 1 + # A head-like call: a fresh [B, 3, 256, 256] batch cropped the same way. + img = torch.randn(2, 3, 256, 256) + with torch.no_grad(): + tiny(img[:, :, :, 32:-32]) + assert ts.dynamo_counters()["unique_graphs"] == graphs + + +# ----------------------------------------------------------------- driver + + +@pytest.fixture +def driver(monkeypatch): + pytest.importorskip("cv2") + monkeypatch.setattr(sys, "argv", ["run_egohand_three_stage.py"]) + from inference.scripts import run_egohand_three_stage as drv + + return drv + + +def _cli_args(monkeypatch, drv, *extra): + monkeypatch.setattr( + sys, + "argv", + [ + "run_egohand_inference_pipeline.py", + "--input", + "in.mp4", + "--egohand_ckpt", + "m.ckpt", + "--output_dir", + "out", + *extra, + ], + ) + return drv.cli.parse_args() + + +def test_driver_flags_and_dino_compile_alias(monkeypatch, driver): + opt, rest = driver.parse_driver_args(["--queue", "q.json", "--", "--dino_compile"]) + assert opt.backbone_compile is None + assert opt.backbone_bf16_weights is False + assert opt.backbone_warmup is True + args = _cli_args(monkeypatch, driver, *rest) + assert driver.resolve_backbone_compile(opt, args) == "block" + + opt, rest = driver.parse_driver_args( + [ + "--queue", + "q.json", + "--backbone_compile", + "whole", + "--backbone_bf16_weights", + "--no-backbone_warmup", + "--", + ] + ) + args = _cli_args(monkeypatch, driver, *rest) + assert driver.resolve_backbone_compile(opt, args) == "whole" + assert (opt.backbone_bf16_weights, opt.backbone_warmup) == (True, False) + args = _cli_args(monkeypatch, driver, "--dino_compile") + with pytest.raises(SystemExit): + driver.resolve_backbone_compile(opt, args) + + opt, rest = driver.parse_driver_args(["--queue", "q.json", "--"]) + args = _cli_args(monkeypatch, driver, *rest) + assert driver.resolve_backbone_compile(opt, args) == "off" + + +def test_release_profile_rejects_a_compiled_backbone(monkeypatch, driver): + monkeypatch.setenv("EGOHAND_RUNTIME_PROFILE", "release") + driver.check_backbone_compile_supported("off") + for scope in ("block", "whole"): + with pytest.raises(SystemExit): + driver.check_backbone_compile_supported(scope) + monkeypatch.setenv("EGOHAND_RUNTIME_PROFILE", "full") + driver.check_backbone_compile_supported("whole") + + +def test_code_version_follows_the_sources(monkeypatch, tmp_path, driver): + (tmp_path / "egohand").mkdir() + (tmp_path / "inference" / "sub").mkdir(parents=True) + (tmp_path / "egohand" / "a.py").write_text("A = 1\n") + (tmp_path / "inference" / "sub" / "b.py").write_text("B = 2\n") + (tmp_path / "inference" / "notes.txt").write_text("not code\n") + monkeypatch.setattr(driver, "PROJECT_ROOT", tmp_path) + first = driver.code_version() + assert first["files"] == 2 and first["torch"] == torch.__version__ + assert driver.code_version()["hash"] == first["hash"] + (tmp_path / "inference" / "notes.txt").write_text("changed, still not code\n") + assert driver.code_version()["hash"] == first["hash"] + (tmp_path / "egohand" / "a.py").write_text("A = 3\n") + assert driver.code_version()["hash"] != first["hash"] + + +def test_setup_compile_env(monkeypatch, tmp_path, driver): + for key in (*driver.COMPILE_ENV, "TORCHINDUCTOR_CACHE_DIR"): + monkeypatch.setenv(key, "placeholder") # records the original for teardown + monkeypatch.delenv(key) + import torch._inductor.config as config + + # config.patch restores the attributes; monkeypatch.setattr would delattr + # them on undo (not in the module __dict__), hiding them from Inductor. + attrs = {attr: getattr(config, attr) for _, attr, _ in driver.COMPILE_ENV.values()} + opt = argparse.Namespace(inductor_cache_root=str(tmp_path / "ind")) + with config.patch(attrs): + env = driver.setup_compile_env(opt, "whole") + applied = {attr: getattr(config, attr) for attr in attrs} + assert os.environ["TORCHINDUCTOR_DYNAMIC_SCALE_RBLOCK"] == "0" + assert os.environ["TORCHINDUCTOR_DETERMINISTIC"] == "1" + assert env["TORCHINDUCTOR_DETERMINISTIC"] == "1" + assert env["TORCHINDUCTOR_DETERMINISTIC_before"] is None + assert env["inductor_config_imported_before"] is True + cache_dir = os.environ["TORCHINDUCTOR_CACHE_DIR"] + assert cache_dir == env["inductor_cache_dir"] + assert os.path.dirname(cache_dir) == str(tmp_path / "ind") + assert os.path.basename(cache_dir) == "egopost_" + env["code_version"]["hash"][:16] + assert os.path.exists(os.path.join(cache_dir, "egopost_code_version.json")) + # Applied to the already imported config too. + assert applied == {"dynamic_scale_rblock": False, "deterministic": True} + assert {attr: getattr(config, attr) for attr in attrs} == attrs + + +def test_compile_env_maps_to_inductor_config(driver): + """Each COMPILE_ENV variable sets its config attribute in a fresh process, + and the compile options are Inductor config keys of this torch.""" + import subprocess + + import torch._inductor.config as config + + known = config.get_config_copy() + assert set(ts.DETERMINISTIC_INDUCTOR_OPTIONS) <= set(known) + for var, (value, attr, attr_value) in driver.COMPILE_ENV.items(): + assert ts.DETERMINISTIC_INDUCTOR_OPTIONS[attr] == attr_value + out = subprocess.run( + [ + sys.executable, + "-c", + f"import torch._inductor.config as c; print(c.{attr})", + ], + env={**os.environ, var: value}, + capture_output=True, + text=True, + check=True, + ) + assert out.stdout.strip() == str(attr_value) + + +def test_deterministic_mode_takes_one_reduction_config(): + """With deterministic on, Inductor keeps one config per reduction kernel, + so nothing is left to pick by timing on the first call.""" + triton = pytest.importorskip("triton") + from torch._inductor.runtime.triton_heuristics import ( + filter_reduction_configs_for_determinism, + ) + + configs = [ + triton.Config({"XBLOCK": 16, "R0_BLOCK": 32}, num_warps=4), + triton.Config({"XBLOCK": 64, "R0_BLOCK": 64}, num_warps=16), + triton.Config({"XBLOCK": 8, "R0_BLOCK": 128}, num_warps=8), + ] + assert len(filter_reduction_configs_for_determinism({}, list(configs))) == 3 + picked = filter_reduction_configs_for_determinism( + {"deterministic": True}, list(configs) + ) + again = filter_reduction_configs_for_determinism( + {"deterministic": True}, configs[::-1] + ) + assert len(picked) == 1 + assert (picked[0].kwargs, picked[0].num_warps) == ( + again[0].kwargs, + again[0].num_warps, + ) + + +def _row_sums(y): + """An unrelated function with a reduction kernel (compiled first).""" + return (y * y).sum(dim=-1) + + +@pytest.mark.skipif(not torch.cuda.is_available(), reason="needs CUDA") +@pytest.mark.parametrize("scope", ["whole", "block"]) +def test_compiled_backbone_kernels_are_deterministic(monkeypatch, scope): + """The compile options reach every generated backbone kernel when the + process-wide flag is False, which is what torch 2.13 Dynamo leaves after any + earlier compile in the process (convert_frame restores it to + are_deterministic_algorithms_enabled()). Another function is compiled + first, without the options; its kernels show the test can see a + non-deterministic kernel. Block scope: the blocks share one graph.""" + from torch._inductor.utils import run_and_get_code + + _fresh_dynamo() + backbone = _build_tiny(monkeypatch).cuda() + backbone.enable_full_batch_compile( + 2, scope=scope, options=dict(ts.DETERMINISTIC_INDUCTOR_OPTIONS) + ) + x = _x(2).cuda() + y = torch.randn(64, 256, device="cuda") + with ( + torch.no_grad(), + torch._inductor.config.patch(deterministic=False, force_disable_caches=True), + ): + _, other = run_and_get_code(torch.compile(_row_sums), y) + before = ts.dynamo_counters()["unique_graphs"] + with torch.autocast("cuda", dtype=torch.bfloat16): + _, code = run_and_get_code(backbone, x) + graphs = ts.dynamo_counters()["unique_graphs"] - before + other, code = "\n".join(other), "\n".join(code) + assert "'deterministic': False" in other + assert graphs == 1 + assert ( + "triton_heuristics.reduction" in code + or "triton_heuristics.persistent_reduction" in code + ) + assert "'deterministic': True" in code + assert "'deterministic': False" not in code + assert "'dynamic_scale_rblock': False" in code diff --git a/src/python/isaaccapture_egopost/inference/tests/pipeline/test_three_stage.py b/src/python/isaaccapture_egopost/inference/tests/pipeline/test_three_stage.py new file mode 100644 index 0000000000..0a1d4274ee --- /dev/null +++ b/src/python/isaaccapture_egopost/inference/tests/pipeline/test_three_stage.py @@ -0,0 +1,1132 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: LicenseRef-OpenMDW-1.1 + +"""Three-stage pipeline hand-off: same crops, batches, order and results as +``EgoHandPredictor.run``; failed crops dropped as before; one video's failure +does not touch the others. Fake model and detector; CPU except the CUDA +stream hand-off test.""" + +import os +import threading + +import numpy as np +import pytest +import torch + +pytest.importorskip("cv2") + +from inference.camera.intrinsics import resolve_K # noqa: E402 +from inference.camera.perspective_crop import perspective_crop # noqa: E402 +from inference.pipeline import three_stage as ts # noqa: E402 +from inference.pipeline.predictor import EgoHandPredictor # noqa: E402 +from inference.preprocessing.crop import ( # noqa: E402 + IMAGENET_MEAN, + IMAGENET_STD, + IMG_SIZE, + crop_and_preprocess, + normalize_crop, +) +from inference.preprocessing.mirroring import ( # noqa: E402 + mirror_full_image_camera_horizontal, + prepare_right_hand_model_input, +) +from inference.tests.pipeline.test_soma_batching import ( # noqa: E402 + _fake_mirror, + _FakeSplitModel, +) + +H, W = 72, 96 +_K = np.array([[80.0, 0.0, W / 2], [0.0, 80.0, H / 2], [0.0, 0.0, 1.0]], np.float32) +_PINHOLE_JSON = { + "model": "PINHOLE", + "image_width": W, + "image_height": H, + "camera_matrix": {"matrix_3x3": _K.tolist()}, + "distortion_coefficients": [], +} + + +def _camera(): + camera, _ = resolve_K(W, H, _PINHOLE_JSON, perspective_cropping=True) + return camera + + +# ----------------------------------------------------------------- video input + + +def test_stage_one_decodes_through_the_video_backend(monkeypatch): + """Stage 1 reads videos through inference.video_io (the backend of the + runtime profile), like run_egohand_inference_pipeline.py.""" + import inference.video_io as video_io + + frames = [np.full((H, W, 3), i, np.uint8) for i in range(5)] + calls = [] + + def fake_read(path, batch_size, max_frames=None): + calls.append((path, batch_size, max_frames)) + stop = len(frames) if max_frames is None else min(max_frames, len(frames)) + for start in range(0, stop, batch_size): + yield [(i, frames[i]) for i in range(start, min(start + batch_size, stop))] + + monkeypatch.setattr(video_io, "read_video_frames_batched", fake_read) + monkeypatch.setattr( + video_io, + "get_video_meta", + lambda path: {"fps": 0.0, "width": W, "height": H, "num_frames": 5}, + ) + decoded = ts.decode_all_frames("clip.mp4") + assert [int(f[0, 0, 0]) for f in decoded] == list(range(5)) + assert ts.video_meta("clip.mp4")["num_frames"] == 5 + ts.check_video_decodable("clip.mp4", {"width": W, "height": H}) + assert calls[-1] == ("clip.mp4", 1, 1) + frames.clear() + with pytest.raises(RuntimeError, match="no decodable video stream"): + ts.check_video_decodable("clip.mp4", {"width": W, "height": H}) + + +# ----------------------------------------------------------------- fakes + + +class _RecordingModel(_FakeSplitModel): + """Records every batch the head sees; the fake outputs depend on many pixels.""" + + def __init__(self): + super().__init__() + self.images = [] + self.inputs = [] + self.fail_head = None # callable(batch) -> bool + + def forward_step_head(self, batch, train=False): + img = batch["img"] + if self.fail_head is not None and self.fail_head(batch): + raise ValueError("injected head failure") + if "bbx_xys" in batch: + self.images.append(img.clone()) + self.inputs.append( + {k: batch[k].clone() for k in ("bbx_xys", "K_fullimg", "img_size")} + ) + probe = img.reshape(img.shape[0], -1)[:, ::101].sum(dim=1) * 1e-4 + fake = probe[:, None, None, None].contiguous() + return super().forward_step_head({"img": fake}, train) + + +def _predictor(perspective, soma_batch_size=0, batch_size=3): + predictor = EgoHandPredictor.__new__(EgoHandPredictor) + predictor.batch_size = batch_size + predictor.soma_batch_size = soma_batch_size + predictor.device = "cpu" + predictor.dtype = torch.float32 + predictor.smooth = False + predictor.perf_reporter = None + predictor.model = _RecordingModel() + predictor._pose_mirror = None + predictor._use_perspective_cropping = perspective + predictor._model_wrist_orients = ( + {"left": np.eye(3), "right": np.eye(3)} if perspective else None + ) + return predictor + + +def _frames(clip, count): + rng = np.random.default_rng(1000 + clip) + return [rng.integers(0, 256, (H, W, 3), dtype=np.uint8) for _ in range(count)] + + +def _boxes(clip, frame_index, frame, hands, perspective): + """Deterministic boxes; some frames miss a hand; some perspective crops fail.""" + boxes = {} + shift = float(frame[0, 0, 0] % 7) + if "left" in hands and frame_index % 4 != 3: + boxes["left"] = np.array([30.0 + shift, 35.0, 24.0 + clip], np.float32) + if "right" in hands and frame_index % 3 != 1: + if perspective and frame_index % 5 == 2: + # Perimeter rays reach behind the virtual camera: perspective_crop fails. + boxes["right"] = np.array([0.9 * W, 0.5 * H, 1.0e6], np.float32) + else: + boxes["right"] = np.array([60.0, 30.0 + shift, 20.0 + 2 * clip], np.float32) + return boxes + + +class _FakeDetector: + writes_bbox_json = False + requires_full_clip = False + + def __init__(self, clip_of, hands, perspective, fail_names=()): + self.clip_of = clip_of # id(first frame) -> (clip number, name) + self.hands = hands + self.perspective = perspective + self.fail_names = set(fail_names) + self.calls = [] + + def run(self, image_ids, images_bgr, hands, output_paths_per_hand=None, **_): + clip, name = self.clip_of[id(images_bgr[0])] + self.calls.append(name) + if name in self.fail_names: + raise RuntimeError("injected detector failure") + return { + image_id: _boxes(clip, i, frame, hands, self.perspective) + for i, (image_id, frame) in enumerate(zip(image_ids, images_bgr)) + } + + +def _setup(tmp_path, perspective, clips, *, soma_batch_size=0, fail_names=()): + hands = ["left", "right"] + camera = _camera() if perspective else _K + requests, frames_of, clip_of = [], {}, {} + for index, (clip, count, name) in enumerate(clips): + frames = _frames(clip, count) + frames_of[name] = (clip, frames) + clip_of[id(frames[0])] = (clip, name) + requests.append( + ts.ClipRequest( + index=index, + name=name, + video=f"/nonexistent/{name}.mp4", + intrinsics=None, + out_root=str(tmp_path / "out"), + frames=frames, + camera=camera, + fps=30.0, + ) + ) + predictor = _predictor(perspective, soma_batch_size) + config = ts.StageConfig( + hands=hands, + use_perspective_cropping=perspective, + camera_mode=predictor.model.camera_mode, + batch_size=predictor.batch_size, + smooth=False, + crop_workers=3, + norm_workers=2, + ) + detector = _FakeDetector(clip_of, hands, perspective, fail_names) + results = {} + + def writer(clip, results_per_hand, hands_): + results[clip.request.name] = results_per_hand + return {h: len(results_per_hand[h]) for h in hands_} + + prepare = ts.PrepareStage(detector, config) + head = ts.HeadStage(predictor, config) + soma = ts.SomaStage(predictor, config, writer=writer) + return requests, frames_of, camera, predictor, prepare, head, soma, results + + +def _reference(frames_of, camera, perspective, soma_batch_size=0): + """``EgoHandPredictor.run`` (the single-video path) per clip.""" + out = {} + for name, (clip, frames) in frames_of.items(): + predictor = _predictor(perspective, soma_batch_size) + ids = [f"{i:06d}" for i in range(len(frames))] + boxes = { + image_id: _boxes(clip, i, frame, ["left", "right"], perspective) + for i, (image_id, frame) in enumerate(zip(ids, frames)) + } + results = predictor.run( + images_bgr=frames, + image_ids=ids, + bboxes_per_image=boxes, + hands=["left", "right"], + intrinsics_per_image=dict.fromkeys(ids, camera), + ) + out[name] = (results, predictor.model.images, predictor.model.inputs) + return out + + +def _assert_results_equal(got, want): + assert list(got) == list(want) + for hand in want: + assert list(got[hand]) == list(want[hand]), hand + for image_id, result in want[hand].items(): + other = got[hand][image_id] + assert list(other) == list(result), (hand, image_id) + for key, value in result.items(): + if isinstance(value, np.ndarray): + assert other[key].dtype == value.dtype, key + np.testing.assert_array_equal(other[key], value, err_msg=key) + else: + assert other[key] == value or ( + other[key] is None and value is None + ), key + + +@pytest.fixture(autouse=True) +def _fake_mirror_patch(monkeypatch): + _fake_mirror.calls = [] + for module in ("predictor", "soma_batching"): + monkeypatch.setattr( + f"inference.pipeline.{module}.mirror_left_prediction_to_right", _fake_mirror + ) + + +# ----------------------------------------------------------------- crops + + +@pytest.mark.parametrize("hand", ["left", "right"]) +@pytest.mark.parametrize("camera_mode", ["sam3db_perspective", "weak_perspective"]) +def test_uint8_pinhole_crop_normalizes_to_original_input(hand, camera_mode): + frame = _frames(3, 1)[0] + bbox = np.array([41.3, 30.7, 27.9], np.float32) + _, _, record = ts.build_crop_record( + ("000000", hand, frame, bbox, _K), + use_perspective_cropping=False, + camera_mode=camera_mode, + ) + if hand == "left": + want, want_bbox, want_K = crop_and_preprocess(frame, bbox)[0], bbox, _K + else: + want, want_bbox, want_K = prepare_right_hand_model_input( + frame, + bbox.copy(), + _K.copy(), + calibrated_full_image=camera_mode == "sam3db_perspective", + ) + got = normalize_crop(record["crop_u8"]) + assert record["crop_u8"].dtype == np.uint8 + assert got.dtype == want.dtype and got.shape == want.shape + assert torch.equal(got, want) + np.testing.assert_array_equal(record["model_bbx_xys"], want_bbox) + np.testing.assert_array_equal(record["model_K"], want_K) + + +@pytest.mark.parametrize("hand", ["left", "right"]) +def test_uint8_perspective_crop_normalizes_to_original_input(hand): + frame = _frames(4, 1)[0] + camera = _camera() + bbox = np.array([30.5, 40.25, 22.0], np.float32) + _, _, record = ts.build_crop_record( + ("000000", hand, frame, bbox, camera), + use_perspective_cropping=True, + camera_mode="sam3db_perspective", + ) + # predictor.run's perspective branch, verbatim. + crop_rgb, K_virtual, bbox_virtual, rotation = perspective_crop( + frame, bbox, camera, IMG_SIZE + ) + model_bbx_xys, model_K = bbox_virtual, K_virtual + if hand == "right": + crop_rgb = np.ascontiguousarray(crop_rgb[:, ::-1]) + model_bbx_xys, model_K = mirror_full_image_camera_horizontal( + model_bbx_xys, model_K, crop_rgb.shape[1] + ) + normalized = (crop_rgb - IMAGENET_MEAN) / IMAGENET_STD + want = torch.from_numpy(normalized.transpose(2, 0, 1)) + assert torch.equal(normalize_crop(record["crop_u8"]), want) + np.testing.assert_array_equal(record["model_bbx_xys"], model_bbx_xys) + np.testing.assert_array_equal(record["model_K"], model_K) + np.testing.assert_array_equal(record["crop_to_source_camera_rotation"], rotation) + + +def test_failed_perspective_crop_is_dropped_with_none(): + frame = _frames(5, 1)[0] + bbox = np.array([0.9 * W, 0.5 * H, 1.0e6], np.float32) + with pytest.raises(ValueError): + perspective_crop(frame, bbox, _camera(), IMG_SIZE) + assert ts.build_crop_record( + ("000002", "right", frame, bbox, _camera()), + use_perspective_cropping=True, + camera_mode="sam3db_perspective", + ) == ("000002", "right", None) + + +# ----------------------------------------------------------------- end to end + +_CLIPS = [(0, 7, "clip_a"), (1, 1, "clip_b"), (2, 11, "clip_c"), (3, 4, "clip_d")] + + +@pytest.mark.parametrize("perspective", [False, True]) +@pytest.mark.parametrize("soma_batch_size", [0, 6]) +@pytest.mark.parametrize("mode", ["serial", "threaded"]) +def test_three_stage_equals_predictor_run(tmp_path, perspective, soma_batch_size, mode): + requests, frames_of, camera, predictor, prepare, head, soma, results = _setup( + tmp_path, perspective, _CLIPS, soma_batch_size=soma_batch_size + ) + records = [] + if mode == "serial": + ts.run_serial(prepare, head, soma, requests, records.append) + else: + runner = ts.ThreadedThreeStage(prepare, head, soma, soma_videos=2) + runner.run(iter(requests), records.append) + assert runner.fatal is None + reference = _reference(frames_of, camera, perspective, soma_batch_size) + + assert [r["name"] for r in records] == [name for _, _, name in _CLIPS] + assert all(r["status"] == "ok" for r in records), records + # Same forward batches, in the same order, with the same bytes. + want_images = [img for name in results for img in reference[name][1]] + want_inputs = [x for name in results for x in reference[name][2]] + got_images = predictor.model.images + assert [i.shape[0] for i in got_images] == [i.shape[0] for i in want_images] + assert any( + i.shape[0] < predictor.batch_size for i in got_images + ) # partial last batches + for got, want in zip(got_images, want_images): + assert torch.equal(got, want) + for got, want in zip(predictor.model.inputs, want_inputs): + for key in want: + assert torch.equal(got[key], want[key]), key + for name in results: + _assert_results_equal(results[name], reference[name][0]) + if perspective: + failed = sum(r["failed_crops"] for r in records) + assert failed > 0 + for record in records: + assert record["crops"] + record["failed_crops"] == record["crop_jobs"] + # perf.json per clip + for _, _, name in _CLIPS: + assert os.path.exists(tmp_path / "out" / name / "perf.json") + + +def test_failures_stay_with_their_video(tmp_path, monkeypatch): + clips = [ + (0, 7, "ok_1"), + (1, 5, "bad_detect"), + (2, 8, "bad_head"), + (3, 6, "bad_soma"), + (4, 9, "ok_2"), + ] + requests, frames_of, camera, _, prepare, head, soma, results = _setup( + tmp_path, False, clips, fail_names=("bad_detect",) + ) + real_head_run = head.run + + head_failures = {"n": 0} + + def head_run(clip, emit, crops=None): + if clip.request.name != "bad_head": + return real_head_run(clip, emit, crops) + + def emit_then_fail(batch): + emit(batch) # stage 3 already has one batch of this clip + head_failures["n"] += 1 + raise RuntimeError("injected head failure after one batch") + + return real_head_run(clip, emit_then_fail, crops) + + real_finish = soma.finish + + def finish(clip): + if clip.request.name == "bad_soma": + raise ValueError("injected smoothing failure") + return real_finish(clip) + + monkeypatch.setattr(head, "run", head_run) + monkeypatch.setattr(soma, "finish", finish) + records = [] + runner = ts.ThreadedThreeStage(prepare, head, soma) + runner.run(iter(requests), records.append) + assert runner.fatal is None + assert head_failures["n"] == 1 + status = {r["name"]: (r["status"], r.get("error_stage")) for r in records} + assert status == { + "ok_1": ("ok", None), + "bad_detect": ("error", "prepare"), + "bad_head": ("error", "head"), + "bad_soma": ("error", "soma"), + "ok_2": ("ok", None), + } + reference = _reference( + {k: v for k, v in frames_of.items() if k.startswith("ok_")}, camera, False + ) + assert sorted(results) == ["ok_1", "ok_2"] + for name in results: + _assert_results_equal(results[name], reference[name][0]) + + +def test_cuda_error_stops_the_run_and_reports_in_flight(tmp_path, monkeypatch): + clips = [(0, 7, "first"), (1, 5, "broken"), (2, 8, "never")] + requests, _, _, _, prepare, head, soma, results = _setup(tmp_path, False, clips) + real_head_run = head.run + + def head_run(clip, emit, crops=None): + if clip.request.name == "broken": + raise RuntimeError("CUDA error: an illegal memory access was encountered") + return real_head_run(clip, emit, crops) + + monkeypatch.setattr(head, "run", head_run) + records = [] + runner = ts.ThreadedThreeStage(prepare, head, soma, poll_s=0.01) + done = threading.Event() + + def target(): + runner.run(iter(requests), records.append) + done.set() + + thread = threading.Thread(target=target, daemon=True) + thread.start() + assert done.wait(60), "run did not stop after a fatal error" + assert runner.fatal is not None + by_name = {r["name"]: r["status"] for r in records} + # The CUDA context is gone: whatever was still in flight is aborted, not + # finished (stage 3 may or may not have finished "first" before the stop). + assert by_name["first"] in ("ok", "aborted") + assert (by_name["first"] == "ok") == ("first" in results) + assert by_name["broken"] in ("error", "aborted") + assert by_name.get("never", "aborted") == "aborted" + assert "never" not in results + assert len(records) == len({r["name"] for r in records}) + + +class _HeadValues: + """``forward_step_head`` returning values computed from the images; on CUDA + it first spins the current stream (stage 2's), so the outputs are written + late.""" + + camera_mode = "sam3db_perspective" + + def __init__(self, spin_cycles=0): + self.spin_cycles = spin_cycles + + def forward_step_head(self, batch, train=False): + img = batch["img"] + if self.spin_cycles: + torch.cuda._sleep(self.spin_cycles) + value = img.reshape(img.shape[0], -1)[:, ::101].sum(dim=1) + return {"value": value, "scaled": value * 2.0} + + +class _ReadOnCallerStream: + """Stands in for SOMA: reads the head outputs on the caller's stream, + optionally after spinning that stream (so stage 2 is ahead of it).""" + + def __init__(self, delay_cycles=0): + self.delay_cycles = delay_cycles + self.values = [] + + def add(self, batch, hand_data, head): + if self.delay_cycles: + torch.cuda._sleep(self.delay_cycles) + self.values.append(head["value"].clone()) + + +@pytest.mark.skipif(not torch.cuda.is_available(), reason="needs CUDA") +@pytest.mark.parametrize("reader_behind", [False, True], ids=["event", "record_stream"]) +def test_cuda_handoff_from_stage_two_stream_to_stage_three(tmp_path, reader_behind): + """thr mode: stage 2 runs on its own stream; stage 3 (another thread, its + default stream) must wait for each batch's event before reading, and the + allocator must not hand stage 2 the memory of a batch stage 3 has not read + yet (record_stream). Without the wait, ``event`` reads values before the + spinning head wrote them; without record_stream, ``record_stream`` reads + blocks stage 2 already reused.""" + import queue as queue_module + + clips = [(0, 30, "cuda_a"), (1, 20, "cuda_b")] + requests, _, _, predictor, prepare, head_cpu, _, _ = _setup(tmp_path, False, clips) + config = head_cpu.config + prepared = [prepare.run(request) for request in requests] + assert all(clip.error is None for clip in prepared) + + predictor.model = _HeadValues() + want = [] + for clip in prepared: + ts.HeadStage(predictor, config).run( + clip, lambda b: want.append(b.head["value"].clone()) + ) + + predictor.device = "cuda" + # GPU clock cycles: roughly 5 ms per head batch, 40 ms per delayed read. + predictor.model = _HeadValues(spin_cycles=10_000_000) + head = ts.HeadStage(predictor, config, own_stream=True) + soma = ts.SomaStage(predictor, config) + reader = _ReadOnCallerStream(delay_cycles=80_000_000 if reader_behind else 0) + soma._batcher = reader + handoff: queue_module.Queue = queue_module.Queue() + + def stage_two(): + try: + for clip in prepared: + head.run(clip, handoff.put) + finally: + handoff.put(None) + + worker = threading.Thread(target=stage_two, daemon=True) + worker.start() + while (head_batch := handoff.get(timeout=120)) is not None: + soma.add(head_batch) + del head_batch # stage 3 drops its references right away + worker.join() + torch.cuda.synchronize() + assert len(reader.values) == len(want) > 10 + for got, expected in zip(reader.values, want): + torch.testing.assert_close(got.cpu(), expected, rtol=1e-4, atol=1e-3) + + +def test_claims_split_one_queue(tmp_path): + requests = [ + ts.ClipRequest(index=i, name=f"v{i}", video="", intrinsics=None, out_root="") + for i in range(9) + ] + claim_dir = str(tmp_path / "claims") + os.makedirs(claim_dir) + a = ts.claim_requests(requests, claim_dir) + b = ts.claim_requests(requests, claim_dir) + got_a, got_b = [], [] + for step in range(9): + target, source = (got_a, a) if step % 3 else (got_b, b) + item = next(source, None) + if item is not None: + target.append(item.index) + got_a += [r.index for r in a] + got_b += [r.index for r in b] + assert sorted(got_a + got_b) == list(range(9)) + assert not set(got_a) & set(got_b) + assert got_a == sorted(got_a) and got_b == sorted(got_b) + assert [r.index for r in ts.claim_requests(requests, None)] == list(range(9)) + + +def test_head_batch_round_trip_keeps_values_dtypes_strides(): + base = torch.arange(24, dtype=torch.float32).reshape(4, 6) + head = { + "output": { + "a": base.t(), # non-contiguous + "b": base.to(torch.bfloat16), + "flag": False, + "nested": [base[:, :2], (base[1:, 3],)], + }, + "batch_size": 4, + "device": torch.device("cpu"), + } + batch = {"bbx_xys": base[:, :3].contiguous(), "hand_type": ["left"] * 4} + records = [{"image_id": f"{i:06d}"} for i in range(10)] + packed = ts.pack_head_batch(ts.HeadBatch(4, records[4:8], batch, head)) + got = ts.unpack_head_batch(packed, records, "cpu") + assert got.start == 4 and got.hand_data == records[4:8] + assert got.batch["hand_type"] == ["left"] * 4 + for key in ("a", "b"): + assert got.head["output"][key].dtype == head["output"][key].dtype + assert got.head["output"][key].stride() == head["output"][key].stride() + assert torch.equal(got.head["output"][key], head["output"][key]) + assert torch.equal(got.head["output"]["nested"][1][0], base[1:, 3]) + assert got.head["output"]["flag"] is False and got.head["device"] == torch.device( + "cpu" + ) + + +# ----------------------------------------------------------------- proc mode (spawned processes) + +_PROC_CLIPS = [(0, 7, "p_a"), (1, 1, "p_b"), (2, 5, "p_c")] + + +def _patch_mirror_in_process(): + import inference.pipeline.predictor as predictor_module + import inference.pipeline.soma_batching as soma_batching_module + + _fake_mirror.calls = [] + predictor_module.mirror_left_prediction_to_right = _fake_mirror + soma_batching_module.mirror_left_prediction_to_right = _fake_mirror + + +class _ContentDetector(_FakeDetector): + """``_FakeDetector`` that finds the clip by the first frame's bytes (frames are + copies in another process).""" + + def run(self, image_ids, images_bgr, hands, output_paths_per_hand=None, **_): + clip, _name = self.clip_of[images_bgr[0].tobytes()] + return { + image_id: _boxes(clip, i, frame, hands, self.perspective) + for i, (image_id, frame) in enumerate(zip(image_ids, images_bgr)) + } + + +def proc_fake_detector(settings): + """proc-mode factory (P1): the fake detector.""" + _patch_mirror_in_process() + clip_of = { + _frames(clip, count)[0].tobytes(): (clip, name) + for clip, count, name in settings["test_clips"] + } + return _ContentDetector( + clip_of, settings["hands"], settings["use_perspective_cropping"] + ) + + +def proc_fake_predictor(settings): + """proc-mode factory (P2, P3): the fake predictor.""" + _patch_mirror_in_process() + pred = _predictor(settings["use_perspective_cropping"], settings["soma_batch_size"]) + pred.mhr_presort = {"patched": ["hand_left", "hand_right"], "skipped": {}} + return pred, 0.0 + + +def proc_failing_predictor(settings): + """proc-mode factory that fails during startup.""" + raise RuntimeError("injected startup failure") + + +@pytest.mark.parametrize("perspective", [False, True]) +def test_process_pipeline_equals_predictor_run(tmp_path, perspective): + requests, frames_of, camera, *_ = _setup(tmp_path, perspective, _PROC_CLIPS) + module = "inference.tests.pipeline.test_three_stage" + settings = { + "hands": ["left", "right"], + "use_perspective_cropping": perspective, + "batch_size": 3, + "smooth": False, + "soma_batch_size": 0, + "device": "cpu", + "crop_workers": 2, + "norm_workers": 2, + "prepare_ahead": 1, + "soma_videos": 2, + "trim_models": True, + "warm_detector": False, + "shm_dir": str(tmp_path / "shm"), + "detector_cfg": None, + "factories": { + "detector": f"{module}:proc_fake_detector", + "predictor": f"{module}:proc_fake_predictor", + }, + "test_clips": _PROC_CLIPS, + } + records = [] + info = ts.run_process_pipeline( + settings, requests, records.append, ready_timeout_s=600 + ) + assert "abort" not in info, info + assert info["exitcodes"] == {"soma": 0, "head": 0, "prepare": 0} + assert info["ready"]["soma"]["mhr_presort"] == { + "patched": ["hand_left", "hand_right"], + "skipped": {}, + } + assert [r["name"] for r in records] == [name for _, _, name in _PROC_CLIPS] + assert all(r["status"] == "ok" for r in records), records + assert not os.path.exists(tmp_path / "shm") # crops removed + reference = _reference(frames_of, camera, perspective) + for name, (results, _, _) in reference.items(): + ref_clip = ts.PreparedClip( + request=next(r for r in requests if r.name == name), + out_dir=tmp_path / "ref" / name, + image_ids=[f"{i:06d}" for i in range(len(frames_of[name][1]))], + ) + ref_clip.out_dir.mkdir(parents=True) + ts.save_clip_outputs(ref_clip, results, ["left", "right"]) + for hand in ("left", "right"): + got = np.load(tmp_path / "out" / name / f"{hand}_results.npz") + want = np.load(ref_clip.out_dir / f"{hand}_results.npz") + assert sorted(got.files) == sorted(want.files) + for key in want.files: + assert got[key].dtype == want[key].dtype, (name, hand, key) + np.testing.assert_array_equal( + got[key], want[key], err_msg=f"{name} {hand} {key}" + ) + + +def test_proc_startup_abort_with_claim_dir_does_not_abort_other_workers(tmp_path): + requests, *_ = _setup(tmp_path, False, [(0, 4, "other_worker_clip")]) + claim_dir = tmp_path / "claims" + claim_dir.mkdir() + # Claim owned by a different worker PID. + (claim_dir / "00000.claim").write_text("999999 other_worker_clip\n") + module = "inference.tests.pipeline.test_three_stage" + settings = { + "hands": ["left", "right"], + "use_perspective_cropping": False, + "batch_size": 3, + "smooth": False, + "soma_batch_size": 0, + "device": "cpu", + "crop_workers": 2, + "norm_workers": 2, + "prepare_ahead": 1, + "soma_videos": 2, + "trim_models": True, + "warm_detector": False, + "claim_dir": str(claim_dir), + "shm_dir": str(tmp_path / "shm_abort"), + "detector_cfg": None, + "factories": { + "detector": f"{module}:proc_fake_detector", + "predictor": f"{module}:proc_failing_predictor", + }, + "test_clips": [(0, 4, "other_worker_clip")], + } + records = [] + info = ts.run_process_pipeline( + settings, requests, records.append, ready_timeout_s=60 + ) + assert "abort" in info + assert records == [] + assert not os.path.exists(tmp_path / "shm_abort") + + +def test_run_serial_fatal_cuda_error_records_aborted(tmp_path, monkeypatch): + requests, _, _, _, prepare, head, soma, _ = _setup(tmp_path, False, [(0, 4, "c0")]) + + def boom_prepare(_request): + raise RuntimeError("CUDA error: an illegal memory access was encountered") + + monkeypatch.setattr(prepare, "run", boom_prepare) + records = [] + with pytest.raises(RuntimeError, match="illegal memory access"): + ts.run_serial(prepare, head, soma, iter(requests), records.append) + assert len(records) == 1 + assert records[0]["status"] == "aborted" + assert records[0]["error_stage"] == "prepare" + + +# ------------------------------------------------------- Track A/B/C wiring tests + + +def test_soma_stage_begin_passes_defer_geometry_from_smooth(tmp_path): + """SomaStage.begin forwards defer_geometry=bool(config.smooth) to SomaBatcher.""" + for smooth in (False, True): + predictor = _predictor(perspective=False, soma_batch_size=0, batch_size=3) + config = ts.StageConfig( + hands=["left", "right"], + use_perspective_cropping=False, + camera_mode="sam3db_perspective", + batch_size=3, + smooth=smooth, + ) + soma = ts.SomaStage(predictor, config) + clip = ts.PreparedClip( + request=ts.ClipRequest(0, "c", str(tmp_path / "c.mp4"), None, str(tmp_path)) + ) + soma.begin(clip) + assert soma._batcher is not None + assert soma._batcher.defer_geometry is smooth + soma.discard() + + +def test_warm_detector_cuda_iobinding_and_cpu_paths(monkeypatch): + """warm_detector warms _run_onnx_cuda on cuda_device_id when cuda_input_enabled.""" + cuda_calls = [] + + class _FakeCudaInner: + cuda_input_enabled = True + cuda_device_id = 2 + + def _run_onnx_cuda(self, images, sizes): + cuda_calls.append((tuple(images.shape), tuple(sizes.shape), images.device)) + + def _run(self, images, sizes): + raise AssertionError("CPU _run must not be called when cuda_input_enabled") + + class _FakeDetectorWrap: + batch_size = 3 + detector = _FakeCudaInner() + + # Stub torch.zeros / torch.full to return CPU tensors tagged with the requested device. + class _TaggedTensor: + def __init__(self, shape, device): + self.shape = shape + self.device = device + + monkeypatch.setattr( + ts.torch, + "zeros", + lambda shape, dtype=None, device=None: _TaggedTensor(shape, device), + ) + monkeypatch.setattr( + ts.torch, + "full", + lambda shape, fill, dtype=None, device=None: _TaggedTensor(shape, device), + ) + + warm = ts.warm_detector(_FakeDetectorWrap()) + assert [w["batch"] for w in warm] == [1, 2, 3] + assert cuda_calls == [ + ((1, 3, 640, 640), (1, 2), torch.device("cuda", 2)), + ((2, 3, 640, 640), (2, 2), torch.device("cuda", 2)), + ((3, 3, 640, 640), (3, 2), torch.device("cuda", 2)), + ] + + cpu_calls = [] + + class _FakeCpuInner: + cuda_input_enabled = False + + def _run(self, images, sizes): + cpu_calls.append((images.shape, sizes.shape)) + + class _FakeCpuWrap: + batch_size = 2 + detector = _FakeCpuInner() + + warm_cpu = ts.warm_detector(_FakeCpuWrap()) + assert [w["batch"] for w in warm_cpu] == [1, 2] + assert cpu_calls == [ + ((1, 3, 640, 640), (1, 2)), + ((2, 3, 640, 640), (2, 2)), + ] + + +def test_detect_chunk_cuda_shared_slices_without_second_h2d(): + """_detect_chunk_cuda_shared passes sub-batches directly to prepare_cuda_tensor.""" + seen_batches = [] + + class _FakeInner: + inference_stream = None + + def prepare_cuda_tensor( + self, raw_bgr, orig_target_sizes=None, *, ready_event=None + ): + seen_batches.append((tuple(raw_bgr.shape), ready_event)) + sizes_cpu = np.full( + (raw_bgr.shape[0], 2), [raw_bgr.shape[2], raw_bgr.shape[1]], np.int64 + ) + return type( + "_Prepared", + (), + {"raw_images": raw_bgr, "orig_target_sizes_cpu": sizes_cpu}, + )() + + def run_onnx_prepared(self, prepared): + return (prepared.raw_images.shape[0],) + + def postprocess(self, count, sizes_cpu): + return [[("det", i, int(sizes_cpu[i, 0]))] for i in range(count)] + + class _FakeDet: + batch_size = 4 + detector = _FakeInner() + + chunk_gpu = torch.zeros((10, 32, 48, 3), dtype=torch.uint8) + sentinel_event = object() + dets = ts._detect_chunk_cuda_shared(_FakeDet(), chunk_gpu, sentinel_event) + assert len(dets) == 10 + assert seen_batches == [ + ((4, 32, 48, 3), sentinel_event), + ((4, 32, 48, 3), sentinel_event), + ((2, 32, 48, 3), sentinel_event), + ] + + +def _write_test_video(path, count=9, height=72, width=96, fps=10.0): + import cv2 + + rng = np.random.default_rng(2026) + writer = cv2.VideoWriter( + str(path), cv2.VideoWriter_fourcc(*"mp4v"), fps, (width, height) + ) + assert writer.isOpened() + for i in range(count): + frame = rng.integers(0, 256, (height, width, 3), dtype=np.uint8) + frame[0, 0] = (i * 17) % 256 + writer.write(frame) + writer.release() + + +def _make_rtdetr_detection( + label_id: int, cx: float, cy: float, size: float, score: float = 0.9 +): + from inference.hand_detector_2d.rtdetr.onnx_model import Detection + + half = size / 2.0 + label = "left_hand" if label_id == 0 else "right_hand" + return Detection( + label, label_id, score, (cx - half, cy - half, cx + half, cy + half) + ) + + +class _FakeStreamRTDetr: + """Minimal RT-DETR-like detector supporting detect_frames + optional tracking/cleanup.""" + + writes_bbox_json = True + batch_size = 4 + enforce_lr_order = True + drop_gap_filled = False + smoothing = None + + def __init__(self, *, use_tracker: bool, with_cleanup_mediapipe: bool = False): + self.use_tracker = use_tracker + self.requires_full_clip = with_cleanup_mediapipe + self.verifier = object() if with_cleanup_mediapipe else None + self.track_images_types: list[type] = [] + self.verified_pixels: list[tuple[int, int]] = [] + self._frame_counter = 0 + + def detect_frames(self, images_bgr): + out = [] + for frame in images_bgr: + idx = self._frame_counter + self._frame_counter += 1 + shift = float(int(frame[0, 0, 0]) % 5) + dets = [_make_rtdetr_detection(0, 32.0 + shift, 36.0, 22.0, 0.92)] + if idx % 3 != 1: + dets.append(_make_rtdetr_detection(1, 64.0, 34.0 + shift, 20.0, 0.88)) + out.append(dets) + return out + + def track_boxes( + self, image_ids, detections, hands, image_size, *, frame_times, images_bgr=None + ): + assert len(detections) == len(image_ids) + assert len(frame_times) == len(image_ids) + self.track_images_types.append(type(images_bgr)) + if self.verifier is not None: + assert images_bgr is not None + # Exercise random-access indexing (as MediaPipe LazyVerifier does). + for idx in (len(image_ids) - 1, 0, len(image_ids) // 2): + self.verified_pixels.append((idx, int(images_bgr[idx][0, 0, 0]))) + from inference.hand_detector_2d.rtdetr.detector import boxes_from_tracks + + return boxes_from_tracks( + image_ids, + detections, + hands, + image_width=image_size[0], + enforce_lr_order=self.enforce_lr_order, + drop_gap_filled=self.drop_gap_filled, + smoothing=None, + frame_times=None, + ) + + @staticmethod + def log_tracking(info, hands): + _ = (info, hands) + + +@pytest.mark.parametrize("use_gpu_crop_path", [False, True]) +def test_prepare_stage_regime_a_streaming_parity( + tmp_path, monkeypatch, use_gpu_crop_path +): + """Regime A (non-tracker RT-DETR) matches CPU reference on both CPU and GPU crop paths.""" + import json + + video_path = tmp_path / "clip_a.mp4" + _write_test_video(video_path, count=8) + intr_path = tmp_path / "intr.json" + intr_path.write_text(json.dumps(_PINHOLE_JSON)) + + config = ts.StageConfig( + hands=["left", "right"], + use_perspective_cropping=True, + camera_mode="sam3db_perspective", + batch_size=3, + smooth=False, + crop_workers=2, + ) + det = _FakeStreamRTDetr(use_tracker=False) + prepare = ts.PrepareStage(det, config, device="cpu") + prepare.stream_chunk_size = 3 + prepare.pyav_threads = 2 + if use_gpu_crop_path: + monkeypatch.setattr(prepare, "_use_gpu_perspective_crop", lambda _cam: True) + + req = ts.ClipRequest( + 0, "clip_a", str(video_path), str(intr_path), str(tmp_path / "out_a") + ) + clip = prepare.run(req) + assert clip.error is None, clip.error_traceback + assert clip.frame_regime == "A" + assert len(clip.image_ids) == 8 + assert len(clip.records) == len(clip.crops) > 0 + assert (clip.out_dir / "clip_a_left_bbox.json").is_file() + assert (clip.out_dir / "clip_a_right_bbox.json").is_file() + + # Compare crops bit-for-bit against direct CPU perspective_crop_uint8 on decoded frames. + frames = ts.decode_all_frames(str(video_path)) + camera = _camera() + rec_iter = iter(zip(clip.records, clip.crops)) + for i, img_id in enumerate(clip.image_ids): + for hand in config.hands: + bbox = clip.bboxes_per_image[img_id].get(hand) + if bbox is None: + continue + rec, got_crop = next(rec_iter) + _, _, ref = ts.build_crop_record( + (img_id, hand, frames[i], bbox, camera), + use_perspective_cropping=True, + camera_mode=config.camera_mode, + ) + assert rec["image_id"] == ref["image_id"] + assert rec["real_hand_side"] == ref["real_hand_side"] + np.testing.assert_array_equal(got_crop, ref["crop_u8"]) + + +@pytest.mark.parametrize("use_gpu_crop_path", [False, True]) +def test_prepare_stage_regime_b_vs_c_and_seekable_mediapipe( + tmp_path, monkeypatch, use_gpu_crop_path +): + """Regime B (RAM-cached) and Regime C (2-pass PyAV + SeekablePyAVFrames) produce identical outputs.""" + import json + + from inference.media._pyav_video import SeekablePyAVFrames + + video_path = tmp_path / "clip_bc.mp4" + _write_test_video(video_path, count=9) + intr_path = tmp_path / "intr.json" + intr_path.write_text(json.dumps(_PINHOLE_JSON)) + + config = ts.StageConfig( + hands=["left", "right"], + use_perspective_cropping=True, + camera_mode="sam3db_perspective", + batch_size=3, + smooth=False, + crop_workers=2, + ) + + # Regime B: ample RAM budget. + det_b = _FakeStreamRTDetr(use_tracker=True, with_cleanup_mediapipe=True) + prep_b = ts.PrepareStage(det_b, config, device="cpu") + prep_b.ram_cache_budget_bytes = 64 * 1024**2 + prep_b.stream_chunk_size = 3 + prep_b.pyav_threads = 2 + if use_gpu_crop_path: + monkeypatch.setattr(prep_b, "_use_gpu_perspective_crop", lambda _cam: True) + clip_b = prep_b.run( + ts.ClipRequest( + 0, "clip_bc", str(video_path), str(intr_path), str(tmp_path / "out_b") + ) + ) + assert clip_b.error is None, clip_b.error_traceback + assert clip_b.frame_regime == "B" + assert det_b.track_images_types == [list] + + # Regime C: tiny RAM budget forces 2-pass streaming + SeekablePyAVFrames for MediaPipe. + det_c = _FakeStreamRTDetr(use_tracker=True, with_cleanup_mediapipe=True) + prep_c = ts.PrepareStage(det_c, config, device="cpu") + prep_c.ram_cache_budget_bytes = 1 + prep_c.stream_chunk_size = 3 + prep_c.pyav_threads = 2 + if use_gpu_crop_path: + monkeypatch.setattr(prep_c, "_use_gpu_perspective_crop", lambda _cam: True) + clip_c = prep_c.run( + ts.ClipRequest( + 0, "clip_bc", str(video_path), str(intr_path), str(tmp_path / "out_c") + ) + ) + assert clip_c.error is None, clip_c.error_traceback + assert clip_c.frame_regime == "C" + assert det_c.track_images_types == [SeekablePyAVFrames] + assert det_c.verified_pixels == det_b.verified_pixels + + # Regime B->C mid-stream spill when metadata underestimates num_frames. + orig_meta = ts.video_meta + monkeypatch.setattr( + ts, + "video_meta", + lambda path: {**orig_meta(path), "num_frames": 1}, + ) + det_spill = _FakeStreamRTDetr(use_tracker=True, with_cleanup_mediapipe=True) + prep_spill = ts.PrepareStage(det_spill, config, device="cpu") + # Budget fits 1 frame (72*96*3 = 20736 B) so it enters Regime B, then spills on chunk 1 (3 frames). + prep_spill.ram_cache_budget_bytes = 30_000 + prep_spill.stream_chunk_size = 3 + prep_spill.pyav_threads = 2 + if use_gpu_crop_path: + monkeypatch.setattr(prep_spill, "_use_gpu_perspective_crop", lambda _cam: True) + clip_spill = prep_spill.run( + ts.ClipRequest( + 0, "clip_bc", str(video_path), str(intr_path), str(tmp_path / "out_s") + ) + ) + assert clip_spill.error is None, clip_spill.error_traceback + assert clip_spill.frame_regime == "C" + assert det_spill.track_images_types == [SeekablePyAVFrames] + + # All three regimes produce bit-identical crops and metadata. + for other in (clip_c, clip_spill): + assert other.image_ids == clip_b.image_ids + assert len(other.crops) == len(clip_b.crops) + for c_got, c_ref in zip(other.crops, clip_b.crops): + np.testing.assert_array_equal(c_got, c_ref) + for r_got, r_ref in zip(other.records, clip_b.records): + assert r_got["image_id"] == r_ref["image_id"] + assert r_got["real_hand_side"] == r_ref["real_hand_side"] + np.testing.assert_allclose(r_got["model_K"], r_ref["model_K"], atol=1e-6) + np.testing.assert_allclose( + r_got["model_bbx_xys"], r_ref["model_bbx_xys"], atol=1e-6 + ) diff --git a/src/python/isaaccapture_egopost/inference/tests/pipeline/test_three_stage_driver.py b/src/python/isaaccapture_egopost/inference/tests/pipeline/test_three_stage_driver.py new file mode 100644 index 0000000000..3037e22c1e --- /dev/null +++ b/src/python/isaaccapture_egopost/inference/tests/pipeline/test_three_stage_driver.py @@ -0,0 +1,115 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: LicenseRef-OpenMDW-1.1 + +"""Command line of run_egohand_three_stage.py: rejected options, exit status, +summary file names.""" + +from __future__ import annotations + +import os +import sys + +import pytest + +pytest.importorskip("cv2") + + +@pytest.fixture(scope="module") +def driver(): + from inference.scripts import run_egohand_three_stage as drv + + return drv + + +def _cli_args(monkeypatch, drv, *extra): + monkeypatch.setattr( + sys, + "argv", + [ + "run_egohand_inference_pipeline.py", + "--input", + "in.mp4", + "--egohand_ckpt", + "m.ckpt", + "--output_dir", + "out", + "--no_save_videos", + *extra, + ], + ) + return drv.cli.parse_args() + + +def test_supported_arguments_pass(monkeypatch, driver): + driver.check_supported(_cli_args(monkeypatch, driver)) + # --dino_compile is --backbone_compile block (compiled and warmed up + # before the queue starts). + driver.check_supported(_cli_args(monkeypatch, driver, "--dino_compile")) + + +@pytest.mark.parametrize( + "extra", + [ + ["--save_npzs"], + ["--frame_batch_size", "64"], + ["--save_images"], + ["--per_frame_results"], + ["--postprocessing_qc", "--intrinsics_json", "cam.json"], + ["--max_seconds", "10"], + ["--perf_output", "p.json"], + ["--device", "cpu"], + ], +) +def test_unsupported_arguments_are_invalid_input(monkeypatch, capsys, driver, extra): + args = _cli_args(monkeypatch, driver, *extra) + with pytest.raises(SystemExit) as exc: + driver.check_supported(args) + assert exc.value.code == driver.cli.EXIT_INVALID_INPUT + assert extra[0] in capsys.readouterr().err + + +def test_driver_help_works_without_double_dash(capsys, driver): + with pytest.raises(SystemExit) as exc: + driver.parse_driver_args(["--help"]) + assert exc.value.code == 0 + assert "--queue" in capsys.readouterr().out + + +@pytest.mark.parametrize( + "bad_flag", + [ + ["--soma_videos", "0"], + ["--prepare_ahead", "0"], + ["--crop_workers", "0"], + ["--norm_workers", "0"], + ["--switch_interval", "0"], + ], +) +def test_driver_rejects_nonpositive_numeric_flags(driver, bad_flag): + with pytest.raises(SystemExit) as exc: + driver.parse_driver_args(["--queue", "q.json", *bad_flag, "--", "--input", "x"]) + assert exc.value.code == 2 + + +def test_exit_status(driver): + ok, failed = {"status": "ok"}, {"status": "error"} + assert driver.exit_status("done", []) == 0 + assert driver.exit_status("done", [ok, ok]) == 0 + assert driver.exit_status("done", [ok, failed]) == driver.EXIT_SOME_ITEMS_FAILED + assert driver.exit_status("aborted", [ok]) == driver.cli.EXIT_RUNTIME_ERROR + + +def test_workers_sharing_a_queue_write_separate_summaries(driver): + from inference.pipeline import three_stage as ts + + requests = [ + ts.ClipRequest( + index=0, name="a", video="a.mp4", intrinsics=None, out_root="/r/out" + ) + ] + assert driver.default_summary_path(requests, None) == os.path.join( + "/r", "three_stage_summary.json" + ) + assert driver.default_summary_path(requests, "/r/claims") == os.path.join( + "/r", f"three_stage_summary_{os.getpid()}.json" + )