Spaces:
Running on Zero
Running on Zero
Download anything4d/model/modules/sparse/attention/modules.py from hugging-apps/4danything: direct link, hf CLI and curl.
- Browser
- Download file 6.15 kB
-
https://huggingface.co/spaces/hugging-apps/4danything/resolve/main/anything4d/model/modules/sparse/attention/modules.py
- Command line
-
hf download hf://spaces/hugging-apps/4danything/anything4d/model/modules/sparse/attention/modules.py
-
curl -L -o modules.py https://huggingface.co/spaces/hugging-apps/4danything/resolve/main/anything4d/model/modules/sparse/attention/modules.py
6.15 kB
| """Video-extended sparse self-attention. | |
| Subclasses SAM-3D's `SparseMultiHeadAttention` (constructed with use_rope=False, | |
| so it owns no internal rope) and adds: | |
| - per-call spatial/temporal RoPE kwargs on the sparse `forward` path | |
| (within-frame attention over a SparseTensor); | |
| - a `dense_self_attention` helper that reuses to_qkv / to_out / qk_rms_norm on | |
| a regular (B, L, C) tensor with an optional pad mask — used by the cross-frame | |
| folded path. Mirrors `modules/sparse/attention/modules.py`. | |
| """ | |
| from typing import * | |
| import torch | |
| import torch.nn.functional as F | |
| from sam3d_objects.model.backbone.tdfy_dit.modules.sparse import SparseTensor | |
| from sam3d_objects.model.backbone.tdfy_dit.modules.sparse.attention.full_attn import ( | |
| sparse_scaled_dot_product_attention, | |
| ) | |
| from sam3d_objects.model.backbone.tdfy_dit.modules.sparse.attention.serialized_attn import ( | |
| sparse_serialized_scaled_dot_product_self_attention, | |
| ) | |
| from sam3d_objects.model.backbone.tdfy_dit.modules.sparse.attention.windowed_attn import ( | |
| sparse_windowed_scaled_dot_product_self_attention, | |
| ) | |
| from sam3d_objects.model.backbone.tdfy_dit.modules.sparse.attention.modules import ( | |
| SparseMultiHeadAttention as _UpstreamSparseMHA, | |
| ) | |
| class VideoSparseMultiHeadAttention(_UpstreamSparseMHA): | |
| def _apply_rope_sparse(self, qkv: SparseTensor, rope_module, indices) -> SparseTensor: | |
| q, k, v = qkv.feats.unbind(dim=1) | |
| q, k = rope_module(q, k, indices) | |
| return qkv.replace(torch.stack([q, k, v], dim=1)) | |
| def _apply_temporal_phases_sparse(self, qkv: SparseTensor, rope_module, phases) -> SparseTensor: | |
| q, k, v = qkv.feats.unbind(dim=1) | |
| q, k = rope_module.apply_phases(q, k, phases) | |
| return qkv.replace(torch.stack([q, k, v], dim=1)) | |
| def forward( | |
| self, | |
| x: Union[SparseTensor, torch.Tensor], | |
| context: Optional[Union[SparseTensor, torch.Tensor]] = None, | |
| spatial_rope=None, | |
| spatial_indices: Optional[torch.Tensor] = None, | |
| temporal_rope=None, | |
| temporal_indices: Optional[torch.Tensor] = None, | |
| temporal_phases: Optional[torch.Tensor] = None, | |
| ) -> Union[SparseTensor, torch.Tensor]: | |
| if self._type == "self": | |
| qkv = self._linear(self.to_qkv, x) | |
| qkv = self._fused_pre(qkv, num_fused=3) | |
| if spatial_rope is not None: | |
| coords = spatial_indices if spatial_indices is not None else x.coords[:, 1:] | |
| qkv = self._apply_rope_sparse(qkv, spatial_rope, coords) | |
| if temporal_rope is not None: | |
| if temporal_phases is not None: | |
| qkv = self._apply_temporal_phases_sparse(qkv, temporal_rope, temporal_phases) | |
| else: | |
| assert temporal_indices is not None, ( | |
| "temporal_rope requires temporal_indices or temporal_phases" | |
| ) | |
| qkv = self._apply_rope_sparse(qkv, temporal_rope, temporal_indices) | |
| if self.qk_rms_norm: | |
| q, k, v = qkv.unbind(dim=1) | |
| q = self.q_rms_norm(q) | |
| k = self.k_rms_norm(k) | |
| qkv = qkv.replace(torch.stack([q.feats, k.feats, v.feats], dim=1)) | |
| if self.attn_mode == "full": | |
| h = sparse_scaled_dot_product_attention(qkv) | |
| elif self.attn_mode == "serialized": | |
| h = sparse_serialized_scaled_dot_product_self_attention( | |
| qkv, self.window_size, serialize_mode=self.serialize_mode, | |
| shift_sequence=self.shift_sequence, shift_window=self.shift_window, | |
| ) | |
| elif self.attn_mode == "windowed": | |
| h = sparse_windowed_scaled_dot_product_self_attention( | |
| qkv, self.window_size, shift_window=self.shift_window, | |
| ) | |
| else: | |
| q = self._linear(self.to_q, x) | |
| q = self._reshape_chs(q, (self.num_heads, -1)) | |
| kv = self._linear(self.to_kv, context) | |
| kv = self._fused_pre(kv, num_fused=2) | |
| if self.qk_rms_norm: | |
| q = self.q_rms_norm(q) | |
| k, v = kv.unbind(dim=1) | |
| k = self.k_rms_norm(k) | |
| kv = kv.replace(torch.stack([k.feats, v.feats], dim=1)) | |
| h = sparse_scaled_dot_product_attention(q, kv) | |
| h = self._reshape_chs(h, (-1,)) | |
| h = self._linear(self.to_out, h) | |
| return h | |
| def dense_self_attention( | |
| self, | |
| feats: torch.Tensor, | |
| spatial_rope=None, | |
| spatial_indices: Optional[torch.Tensor] = None, | |
| temporal_rope=None, | |
| temporal_indices: Optional[torch.Tensor] = None, | |
| temporal_phases: Optional[torch.Tensor] = None, | |
| attn_mask: Optional[torch.Tensor] = None, | |
| ) -> torch.Tensor: | |
| """Self-attention over a dense (B, L, C) tensor, reusing this module's | |
| to_qkv / to_out / qk_rms_norm. attn_mask: (B, L) bool, True = valid.""" | |
| assert self._type == "self", "dense_self_attention only valid for self-attn module" | |
| B, L, C = feats.shape | |
| qkv = self.to_qkv(feats).reshape(B, L, 3, self.num_heads, -1) | |
| if spatial_rope is not None or temporal_rope is not None: | |
| q, k, v = qkv.unbind(dim=2) | |
| if spatial_rope is not None: | |
| q, k = spatial_rope(q, k, spatial_indices) | |
| if temporal_rope is not None: | |
| if temporal_phases is not None: | |
| q, k = temporal_rope.apply_phases(q, k, temporal_phases) | |
| else: | |
| q, k = temporal_rope(q, k, temporal_indices) | |
| qkv = torch.stack([q, k, v], dim=2) | |
| q, k, v = qkv.unbind(dim=2) | |
| if self.qk_rms_norm: | |
| q = self.q_rms_norm(q) | |
| k = self.k_rms_norm(k) | |
| q = q.permute(0, 2, 1, 3) | |
| k = k.permute(0, 2, 1, 3) | |
| v = v.permute(0, 2, 1, 3) | |
| sdpa_mask = None if attn_mask is None else attn_mask[:, None, None, :] | |
| h = F.scaled_dot_product_attention(q, k, v, attn_mask=sdpa_mask) | |
| h = h.permute(0, 2, 1, 3).reshape(B, L, -1) | |
| return self.to_out(h) | |