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