Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions src/python/isaaccapture_egopost/inference/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
292 changes: 292 additions & 0 deletions src/python/isaaccapture_egopost/inference/pipeline/mhr_presort.py
Original file line number Diff line number Diff line change
@@ -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 "<root>", 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
20 changes: 19 additions & 1 deletion src/python/isaaccapture_egopost/inference/pipeline/predictor.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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.

Expand All @@ -203,20 +206,35 @@ 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,
dtype=dtype,
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(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down
Loading