"""Video-extended sparse transformer cross block. Subclasses SAM-3D's `ModulatedSparseTransformerCrossBlock`, swapping `self_attn` for `VideoSparseMultiHeadAttention` (identical parameter keys -> warm-starts 1:1) and routing the self-attention between within-frame (sparse) and cross-frame (fold to dense, masked SDPA) per (block_idx, n_alt, num_frames). Cross-attention (image conditioning), MLP, norms, adaLN are inherited unchanged. Mirrors `modules/sparse/transformer/modulated.py`. No modality mask here — unlike the MoT geometry model, the SLat stream is single-modality. """ from typing import * import torch import torch.nn as nn from einops import rearrange from sam3d_objects.model.backbone.tdfy_dit.modules.sparse import SparseTensor from sam3d_objects.model.backbone.tdfy_dit.modules.sparse.transformer.modulated import ( ModulatedSparseTransformerCrossBlock, ) from anything4d.model.modules.sparse.attention.modules import VideoSparseMultiHeadAttention from anything4d.model.modules.sparse.transformer._fold import ( pad_per_layout, build_pad_mask, unpad_to_layout, ) class VideoModulatedSparseTransformerCrossBlock(ModulatedSparseTransformerCrossBlock): def __init__( self, channels: int, ctx_channels: int, num_heads: int, mlp_ratio: float = 4.0, attn_mode: Literal["full", "serialized", "windowed"] = "full", window_size: Optional[int] = None, shift_sequence: Optional[int] = None, shift_window: Optional[Tuple[int, int, int]] = None, serialize_mode=None, use_checkpoint: bool = False, use_rope: bool = False, qk_rms_norm: bool = False, qk_rms_norm_cross: bool = False, qkv_bias: bool = True, share_mod: bool = False, block_idx: int = 0, n_alt: int = 0, start_rope: int = 0, use_spatial_rope: bool = True, use_temporal_rope: bool = True, ): super().__init__( channels, ctx_channels, num_heads, mlp_ratio=mlp_ratio, attn_mode=attn_mode, window_size=window_size, shift_sequence=shift_sequence, shift_window=shift_window, serialize_mode=serialize_mode, use_checkpoint=use_checkpoint, use_rope=use_rope, qk_rms_norm=qk_rms_norm, qk_rms_norm_cross=qk_rms_norm_cross, qkv_bias=qkv_bias, share_mod=share_mod, ) self.block_idx = block_idx self.n_alt = n_alt self.start_rope = start_rope self.use_spatial_rope = use_spatial_rope self.use_temporal_rope = use_temporal_rope self.self_attn = VideoSparseMultiHeadAttention( channels, num_heads=num_heads, type="self", attn_mode=attn_mode, window_size=window_size, shift_sequence=shift_sequence, shift_window=shift_window, serialize_mode=serialize_mode, qkv_bias=qkv_bias, use_rope=False, qk_rms_norm=qk_rms_norm, ) def _layer_kind(self, num_frames: int) -> Tuple[str, bool, bool]: """Returns (kind, use_spatial_rope, use_temporal_rope).""" n = self.block_idx is_alt = (n >= self.n_alt) and (num_frames > 1) is_cross = is_alt and (n % 2 == 1) sp_on = self.use_spatial_rope and (n >= self.start_rope) tp_on = self.use_temporal_rope and is_cross if is_cross: return "cross", sp_on, tp_on return "within", sp_on, False def _self_attention( self, h: SparseTensor, num_frames: int, spatial_rope: Optional[nn.Module], temporal_rope: Optional[nn.Module], temporal_phases: Optional[torch.Tensor] = None, ) -> SparseTensor: kind, use_sp, use_tp = self._layer_kind(num_frames) if kind == "within": return self.self_attn( h, spatial_rope=spatial_rope if use_sp else None, spatial_indices=None, ) F_ = num_frames layout = h.layout bf = len(layout) assert bf % F_ == 0, f"layout length {bf} not divisible by num_frames {F_}" b = bf // F_ n_max = max(sl.stop - sl.start for sl in layout) feats = h.feats feats_pad, lengths = pad_per_layout(feats, layout, n_max) feats_fold = rearrange(feats_pad, "(b f) n c -> b (f n) c", f=F_) mask = build_pad_mask(lengths, F_, n_max, b) sp_idx = t_idx = t_phases = None device = feats.device if use_sp: sp_idx = torch.ones(b, F_ * n_max, 3, device=device, dtype=torch.long) if use_tp: if temporal_phases is not None: t_phases = temporal_phases.repeat_interleave(n_max, dim=1) else: t1d = torch.arange(F_, device=device).repeat_interleave(n_max) t_idx = t1d.unsqueeze(0).expand(b, -1).unsqueeze(-1) h_fold = self.self_attn.dense_self_attention( feats_fold, spatial_rope=spatial_rope if use_sp else None, spatial_indices=sp_idx, temporal_rope=temporal_rope if use_tp else None, temporal_indices=t_idx, temporal_phases=t_phases, attn_mask=mask, ) h_unpad = unpad_to_layout(h_fold, layout, F_, n_max) return h.replace(h_unpad) def _forward( self, x: SparseTensor, mod: torch.Tensor, context: torch.Tensor, num_frames: int = 1, spatial_rope: Optional[nn.Module] = None, temporal_rope: Optional[nn.Module] = None, temporal_phases: Optional[torch.Tensor] = None, ) -> SparseTensor: if self.share_mod: shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp = mod.chunk(6, dim=1) else: shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp = ( self.adaLN_modulation(mod).chunk(6, dim=1) ) x = self._ckpt( self._sa_block, x, scale_msa, shift_msa, gate_msa, num_frames, spatial_rope, temporal_rope, temporal_phases, ) x = self._ckpt(self._ca_block, x, context) x = self._ckpt(self._mlp_block, x, scale_mlp, shift_mlp, gate_mlp) return x def _sa_block( self, x: SparseTensor, scale_msa: torch.Tensor, shift_msa: torch.Tensor, gate_msa: torch.Tensor, num_frames: int, spatial_rope: Optional[nn.Module], temporal_rope: Optional[nn.Module], temporal_phases: Optional[torch.Tensor], ) -> SparseTensor: h = x.replace(self.norm1(x.feats)) h = h * (1 + scale_msa) + shift_msa h = self._self_attention(h, num_frames, spatial_rope, temporal_rope, temporal_phases) h = h * gate_msa return x + h def _ca_block(self, x: SparseTensor, context: torch.Tensor) -> SparseTensor: h = x.replace(self.norm2(x.feats)) h = self.cross_attn(h, context) return x + h def _mlp_block( self, x: SparseTensor, scale_mlp: torch.Tensor, shift_mlp: torch.Tensor, gate_mlp: torch.Tensor, ) -> SparseTensor: h = x.replace(self.norm3(x.feats)) h = h * (1 + scale_mlp) + shift_mlp h = self.mlp(h) h = h * gate_mlp return x + h def _ckpt(self, fn, *args): if self.use_checkpoint and getattr(self, "checkpoint_fine", False): return torch.utils.checkpoint.checkpoint(fn, *args, use_reentrant=False) return fn(*args) def forward( self, x: SparseTensor, mod: torch.Tensor, context: torch.Tensor, num_frames: int = 1, spatial_rope: Optional[nn.Module] = None, temporal_rope: Optional[nn.Module] = None, temporal_phases: Optional[torch.Tensor] = None, ) -> SparseTensor: if self.use_checkpoint and not getattr(self, "checkpoint_fine", False): return torch.utils.checkpoint.checkpoint( self._forward, x, mod, context, num_frames, spatial_rope, temporal_rope, temporal_phases, use_reentrant=False, ) return self._forward(x, mod, context, num_frames, spatial_rope, temporal_rope, temporal_phases)