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
125 changes: 107 additions & 18 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 All @@ -77,21 +98,57 @@ def __init__(self, name: str = "dinov3_vith16plus", drop_path_rate: float = 0.1)
# 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,
scope: str = "block",
options: dict | None = None,
backend: str = "inductor",
) -> None:
"""Compile the backbone only for eval/no-grad batches of this exact size.

def enable_full_batch_compile(self, full_batch_size: int) -> None:
"""Compile DINO blocks 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:
Expand All @@ -100,27 +157,41 @@ 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 = (
encoder.rope_embed(H=height, W=width)
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
Expand Down Expand Up @@ -156,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.

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