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
27 changes: 24 additions & 3 deletions src/python/isaaccapture_egopost/egohand/models/backbones/dinov3.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand All @@ -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
Expand Down
94 changes: 74 additions & 20 deletions src/python/isaaccapture_egopost/egohand/models/egohand.py
Original file line number Diff line number Diff line change
Expand Up @@ -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))
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand All @@ -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]
Expand Down
Loading