KBlueLeaf commited on
Commit
742c169
Β·
verified Β·
1 Parent(s): 6dee607

TT-VidT TT3D encoder (structured resample), transformers remote code

Browse files
Files changed (13) hide show
  1. README.md +77 -0
  2. config.json +171 -0
  3. dinov3_vit.py +395 -0
  4. env.py +3 -0
  5. layers.py +341 -0
  6. model.safetensors +3 -0
  7. modeling_ttvidt.py +62 -0
  8. mup.py +18 -0
  9. patch.py +67 -0
  10. pos_embed.py +358 -0
  11. tt.py +167 -0
  12. tt3d.py +505 -0
  13. utils.py +28 -0
README.md ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: apache-2.0
3
+ library_name: transformers
4
+ pipeline_tag: video-classification
5
+ tags:
6
+ - video
7
+ - self-supervised
8
+ - motion
9
+ ---
10
+
11
+ # TT-VidT (TT3D, structured resample)
12
+
13
+ Video encoder from *TT-VidT: Decoupling the Temporal Axis for Efficient
14
+ Motion-Centric Video Pretraining*. A DINOv3 ViT-B/16 appearance path is paired with
15
+ a compact Temporal Transfer (TT3D) pathway that produces per-frame motion tokens.
16
+ TT3D down/up-samples the spatial tokens with a fixed structured weight plus a
17
+ trainable channel mix: 195.5M parameters instead of 407.8M for the full-linear
18
+ resample of the paper checkpoint.
19
+
20
+ Code, training recipes and evaluation: see the TT-VidT repository.
21
+
22
+ ## Usage
23
+
24
+ With `transformers` only:
25
+
26
+ ```python
27
+ import torch
28
+ from transformers import AutoModel
29
+
30
+ model = AutoModel.from_pretrained("<this repo>", trust_remote_code=True).cuda().eval()
31
+ video = torch.rand(1, 8, 3, 256, 256, device="cuda") * 2 - 1 # [B, T, C, H, W], pixels in [-1, 1]
32
+ with torch.no_grad(), torch.autocast("cuda", dtype=torch.float16):
33
+ motion = model(video).motion_output # [B, T, 1, 768]
34
+ ```
35
+
36
+ With the TT-VidT repository:
37
+
38
+ ```python
39
+ from ttvidt.hub import load_model
40
+
41
+ model = load_model("<this repo>", device="cuda")
42
+ motion = model.encoder(video).motion_output
43
+ ```
44
+
45
+ Input: 8 frames at 256x256, normalised with mean = std = 0.5 (frames were sampled at
46
+ 6 fps during training).
47
+
48
+ ## Files
49
+
50
+ | File | Content |
51
+ |---|---|
52
+ | `config.json` | architecture + `TTVidTrainer` arguments, and the `transformers` fields |
53
+ | `model.safetensors` | fp32 encoder (195.5M parameters, incl. the 85.1M DINOv3 spatial path); no decoder |
54
+ | `*.py` | encoder code for `trust_remote_code` (needs `torch` and `transformers` only) |
55
+
56
+ Loading needs no access to the DINOv3 base weights.
57
+
58
+ ## Training
59
+
60
+ Initialised from the paper's TT3D + Diff Compression encoder (full-linear resample)
61
+ with the resample replaced, then trained for 30k steps to match that encoder's motion
62
+ and conditioning embeddings (relative MSE) on the pretraining data
63
+ (OpenVid-1M 384 px + Moments-in-Time v2), batch 16, AdamW 5e-4 with muP
64
+ scaling, 200 warmup steps, cosine decay.
65
+
66
+ ## Results
67
+
68
+ Frozen attentive probe, mean top-1 over 3 seeds (TT-VidT evaluation protocol, 8 frames):
69
+
70
+ | Encoder | HMDB51 | ARID | IARD | Jester | SSv2 |
71
+ |---|---:|---:|---:|---:|---:|
72
+ | paper TT3D (full-linear resample, 407.8M) | 24.8 | 35.4 | 86.6 | 72.9 | 25.9 |
73
+ | this checkpoint (structured resample, 195.5M) | 25.2 | 36.1 | 86.0 | 72.9 | 25.4 |
74
+
75
+ ## License
76
+
77
+ Apache-2.0. The spatial path is initialised from DINOv3, which has its own license.
config.json ADDED
@@ -0,0 +1,171 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "format": "ttvidt-release-v1",
3
+ "model": {
4
+ "base_model_name": null,
5
+ "motion_encoder_config": {
6
+ "temporal_patch_size": 1,
7
+ "temporal_patch_overlap": 0,
8
+ "motion_layers_period": 1,
9
+ "num_motion_tokens": 8,
10
+ "motion_ffn_type": "gelu",
11
+ "tt_mode": "3d",
12
+ "tt_downsample": 4
13
+ },
14
+ "motion_decoder_config": {
15
+ "image_dim": 4,
16
+ "patch_size": 2,
17
+ "decoder_style": "dit",
18
+ "num_layers": 12,
19
+ "hidden_size": 768,
20
+ "intermediate_size": 3072,
21
+ "num_heads": 12,
22
+ "decode_mode": "diffusion",
23
+ "qk_norm": true,
24
+ "attn_bias": false,
25
+ "use_final_norm": true,
26
+ "encoder_hidden_size": 768,
27
+ "temporal_patch_size": 1
28
+ },
29
+ "encoder_ae_mode": "video",
30
+ "decoder_ae_mode": "image",
31
+ "latent_mean": [
32
+ -0.69,
33
+ -0.48,
34
+ -0.6,
35
+ 0.28
36
+ ],
37
+ "latent_std": [
38
+ 12.38,
39
+ 11.22,
40
+ 7.93,
41
+ 21.22
42
+ ],
43
+ "patch_size": null,
44
+ "image_dim": null,
45
+ "token_counts": [
46
+ 1
47
+ ],
48
+ "gradient_checkpointing": false,
49
+ "train_mode": "regression",
50
+ "mae_mask_ratio": 0.75,
51
+ "ar_shift_range": null,
52
+ "ar_shift_sampling": "gamma",
53
+ "source_frame_count": 8,
54
+ "use_ref": false,
55
+ "unfreeze_backbone": true,
56
+ "decoder_mask_ratio": 0.0,
57
+ "mask_patch_size": 4,
58
+ "diffusion_timestep_sampling": "uniform",
59
+ "backbone_arch": "ttvidt",
60
+ "backbone_config": {
61
+ "transformers_version": "5.14.1",
62
+ "architectures": [
63
+ "DINOv3ViTModel"
64
+ ],
65
+ "output_hidden_states": false,
66
+ "return_dict": true,
67
+ "dtype": "float32",
68
+ "chunk_size_feed_forward": 0,
69
+ "is_encoder_decoder": false,
70
+ "id2label": {
71
+ "0": "LABEL_0",
72
+ "1": "LABEL_1"
73
+ },
74
+ "label2id": {
75
+ "LABEL_0": 0,
76
+ "LABEL_1": 1
77
+ },
78
+ "problem_type": null,
79
+ "patch_size": 16,
80
+ "hidden_size": 768,
81
+ "intermediate_size": 3072,
82
+ "num_hidden_layers": 12,
83
+ "num_attention_heads": 12,
84
+ "hidden_act": "gelu",
85
+ "attention_dropout": 0.0,
86
+ "initializer_range": 0.02,
87
+ "layer_norm_eps": 1e-05,
88
+ "rope_theta": 100.0,
89
+ "image_size": 224,
90
+ "num_channels": 3,
91
+ "query_bias": true,
92
+ "key_bias": false,
93
+ "value_bias": true,
94
+ "proj_bias": true,
95
+ "mlp_bias": true,
96
+ "layerscale_value": 1.0,
97
+ "drop_path_rate": 0.0,
98
+ "use_gated_mlp": false,
99
+ "num_register_tokens": 4,
100
+ "pos_embed_shift": null,
101
+ "pos_embed_jitter": null,
102
+ "pos_embed_rescale": 2.0,
103
+ "apply_layernorm": true,
104
+ "reshape_hidden_states": true,
105
+ "stage_names": [
106
+ "stem",
107
+ "stage1",
108
+ "stage2",
109
+ "stage3",
110
+ "stage4",
111
+ "stage5",
112
+ "stage6",
113
+ "stage7",
114
+ "stage8",
115
+ "stage9",
116
+ "stage10",
117
+ "stage11",
118
+ "stage12"
119
+ ],
120
+ "_name_or_path": "facebook/dinov3-vitb16-pretrain-lvd1689m",
121
+ "model_type": "dinov3_vit",
122
+ "temporal_patch_size": 1,
123
+ "temporal_patch_overlap": 0,
124
+ "motion_layers_period": 1,
125
+ "num_motion_tokens": 8,
126
+ "motion_ffn_type": "gelu",
127
+ "tt_mode": "3d",
128
+ "tt_downsample": 4,
129
+ "output_attentions": false,
130
+ "out_features": [
131
+ "stage12"
132
+ ],
133
+ "out_indices": [
134
+ 12
135
+ ]
136
+ },
137
+ "decoder_lr_multiplier": 1.0,
138
+ "fused_adam": false,
139
+ "ema_foreach": false,
140
+ "nan_guard_interval": 1,
141
+ "name": "ttvidt-tt3d-diffcomp",
142
+ "log_interval": 2500,
143
+ "learning_rate": 0.0005,
144
+ "base_dim": 256,
145
+ "decoder_base_dim": null,
146
+ "weight_decay": 0.01,
147
+ "betas": [
148
+ 0.9,
149
+ 0.98
150
+ ],
151
+ "scheduler_config": {
152
+ "lr": {
153
+ "mode": "cosine",
154
+ "end": 436705,
155
+ "min_value": 0.01,
156
+ "warmup": 10000
157
+ }
158
+ }
159
+ },
160
+ "encoder_only": true,
161
+ "name": "ttvidt-tt3d-structured",
162
+ "source": "distilled from ttvidt-tt3d-diffcomp",
163
+ "model_type": "ttvidt",
164
+ "architectures": [
165
+ "TTVidTModel"
166
+ ],
167
+ "auto_map": {
168
+ "AutoConfig": "modeling_ttvidt.TTVidTConfig",
169
+ "AutoModel": "modeling_ttvidt.TTVidTModel"
170
+ }
171
+ }
dinov3_vit.py ADDED
@@ -0,0 +1,395 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from dataclasses import dataclass
2
+ from typing import Optional, Unpack
3
+
4
+ import torch
5
+ import torch.nn as nn
6
+ from transformers import DINOv3ViTModel, DINOv3ViTConfig
7
+ from transformers.utils import TransformersKwargs
8
+ from transformers.modeling_outputs import ModelOutput
9
+ from transformers.models.dinov3_vit.modeling_dinov3_vit import DINOv3ViTEmbeddings
10
+ from .mup import mup_init, mup_init_output
11
+
12
+ from .layers import AttentivePooling, RMSNorm
13
+ from .patch import TemporalPatch
14
+ from .tt import TemporalTransfer
15
+ from .tt3d import TemporalTransfer3D
16
+
17
+
18
+ @dataclass
19
+ class VideoModelOutputWithMotionTokens(ModelOutput):
20
+ last_hidden_state: Optional[torch.FloatTensor] = None
21
+ frames_output: Optional[torch.FloatTensor] = None
22
+ pooler_output: Optional[torch.FloatTensor] = None
23
+ motion_output: Optional[torch.FloatTensor] = None
24
+ cls_output: Optional[torch.FloatTensor] = None
25
+ hidden_states: Optional[tuple[torch.FloatTensor, ...]] = None
26
+ attentions: Optional[tuple[torch.FloatTensor, ...]] = None
27
+
28
+
29
+ class DINOv3VidTConfig(DINOv3ViTConfig):
30
+ model_type = "dinov3_vit"
31
+
32
+ def __init__(
33
+ self,
34
+ patch_size: int = 16,
35
+ temporal_patch_size: int = 1,
36
+ temporal_patch_overlap: int = 0,
37
+ hidden_size: int = 384,
38
+ intermediate_size: int = 1536,
39
+ num_hidden_layers: int = 12,
40
+ motion_layers_period: int = 0,
41
+ num_attention_heads: int = 6,
42
+ hidden_act: str = "gelu",
43
+ attention_dropout: float = 0.0,
44
+ initializer_range: float = 0.02,
45
+ layer_norm_eps: float = 1e-5,
46
+ rope_theta: float = 100.0,
47
+ image_size: int = 224,
48
+ num_channels: int = 3,
49
+ query_bias: bool = True,
50
+ key_bias: bool = False,
51
+ value_bias: bool = True,
52
+ proj_bias: bool = True,
53
+ mlp_bias: bool = True,
54
+ layerscale_value: float = 1.0,
55
+ drop_path_rate: float = 0.0,
56
+ use_gated_mlp: bool = False,
57
+ num_register_tokens: int = 0,
58
+ num_motion_tokens: int = 0,
59
+ motion_ffn_type: str = "swiglu", # "swiglu" or "gelu" for TemporalTransfer
60
+ tt_mode: str = "1d", # "1d" (motion-only) or "3d" (motion + downsampled spatial)
61
+ tt_downsample: int = 4, # spatial downsample factor for tt_mode="3d"
62
+ # train augs
63
+ pos_embed_shift: Optional[float] = None,
64
+ pos_embed_jitter: Optional[float] = None,
65
+ pos_embed_rescale: Optional[float] = 2.0,
66
+ **kwargs,
67
+ ):
68
+ super().__init__(**kwargs)
69
+
70
+ self.image_size = image_size
71
+ self.patch_size = patch_size
72
+ self.temporal_patch_size = temporal_patch_size
73
+ self.temporal_patch_overlap = temporal_patch_overlap
74
+ self.num_channels = num_channels
75
+ self.hidden_size = hidden_size
76
+ self.intermediate_size = intermediate_size
77
+ self.num_hidden_layers = num_hidden_layers
78
+ self.motion_layers_period = motion_layers_period
79
+ self.num_attention_heads = num_attention_heads
80
+ self.hidden_act = hidden_act
81
+ self.attention_dropout = attention_dropout
82
+ self.initializer_range = initializer_range
83
+ self.layer_norm_eps = layer_norm_eps
84
+ self.layerscale_value = layerscale_value
85
+ self.drop_path_rate = drop_path_rate
86
+ self.use_gated_mlp = use_gated_mlp
87
+ self.rope_theta = rope_theta
88
+ self.query_bias = query_bias
89
+ self.key_bias = key_bias
90
+ self.value_bias = value_bias
91
+ self.proj_bias = proj_bias
92
+ self.mlp_bias = mlp_bias
93
+ self.num_register_tokens = num_register_tokens
94
+ self.num_motion_tokens = num_motion_tokens
95
+ self.motion_ffn_type = motion_ffn_type
96
+ self.tt_mode = tt_mode
97
+ self.tt_downsample = tt_downsample
98
+
99
+ # train augs
100
+ self.pos_embed_shift = pos_embed_shift
101
+ self.pos_embed_jitter = pos_embed_jitter
102
+ self.pos_embed_rescale = pos_embed_rescale
103
+
104
+
105
+ class DINOv3VidTModel(DINOv3ViTModel):
106
+ config: DINOv3VidTConfig
107
+
108
+ def __init__(self, config: DINOv3VidTConfig):
109
+ super().__init__(config)
110
+ self.num_motion_tokens = config.num_motion_tokens
111
+ if self.num_motion_tokens > 0:
112
+ self.motion_tokens = nn.Parameter(
113
+ torch.randn(config.num_motion_tokens, config.hidden_size)
114
+ / (config.hidden_size * config.num_motion_tokens) ** 0.5
115
+ )
116
+ else:
117
+ self.motion_tokens = None
118
+ if config.temporal_patch_size > 1:
119
+ self.temporal_embeddings = TemporalPatch(
120
+ config.hidden_size,
121
+ config.hidden_size,
122
+ config.temporal_patch_size,
123
+ config.temporal_patch_overlap,
124
+ )
125
+ else:
126
+ self.temporal_embeddings = nn.Identity()
127
+ # Attentive pooling on motion tokens -> CLS-like conditioning token
128
+ if self.num_motion_tokens > 0:
129
+ self.motion_pooler = AttentivePooling(
130
+ config.hidden_size, num_heads=config.num_attention_heads
131
+ )
132
+ # Pool all TT tokens β†’ 1 motion token for decoder output
133
+ self.motion_output_pooler = AttentivePooling(
134
+ config.hidden_size, num_heads=config.num_attention_heads
135
+ )
136
+ # Normalize cls_output (AttentivePooling has no output norm; without this
137
+ # cls_output can reach absmax~50 and destabilize AdaRMSNorm conditioning)
138
+ self.cls_norm = RMSNorm(config.hidden_size)
139
+ else:
140
+ self.motion_pooler = None
141
+ self.motion_output_pooler = None
142
+ self.cls_norm = None
143
+
144
+ self.motion_layers = nn.ModuleList([])
145
+ self.tt_mode = config.tt_mode
146
+
147
+ layer_added = 0
148
+ for idx, layer in enumerate(self.model.layer):
149
+ if (
150
+ config.motion_layers_period > 0
151
+ and idx % config.motion_layers_period == 0
152
+ ):
153
+ layer_added += 1
154
+ if config.tt_mode == "3d":
155
+ self.motion_layers.append(
156
+ TemporalTransfer3D(
157
+ config.hidden_size,
158
+ config.intermediate_size,
159
+ config.num_attention_heads,
160
+ downsample_factor=config.tt_downsample,
161
+ ffn_type=config.motion_ffn_type,
162
+ )
163
+ )
164
+ else:
165
+ self.motion_layers.append(
166
+ TemporalTransfer(
167
+ config.hidden_size,
168
+ config.intermediate_size,
169
+ config.num_attention_heads,
170
+ ffn_type=config.motion_ffn_type,
171
+ )
172
+ )
173
+ else:
174
+ self.motion_layers.append(nn.Identity())
175
+
176
+ mup_init(self.motion_layers.parameters())
177
+ # Restore special inits clobbered by mup_init
178
+ for layer in self.motion_layers:
179
+ if isinstance(layer, nn.Identity):
180
+ continue
181
+ # Residual output projections: near-zero init
182
+ if hasattr(layer, 'attn') and hasattr(layer.attn, 'out_proj'):
183
+ mup_init_output(layer.attn.out_proj.weight)
184
+ if hasattr(layer, 'out_proj'): # TT3D has out_proj on the module
185
+ mup_init_output(layer.out_proj.weight)
186
+ if hasattr(layer.mlp, 'fc2'):
187
+ mup_init_output(layer.mlp.fc2.weight)
188
+ elif hasattr(layer.mlp, 'down'):
189
+ mup_init_output(layer.mlp.down.weight)
190
+ # TT3D-specific: zero-init spatial_out_proj, identity resample channel mix, qk_scale
191
+ if hasattr(layer, 'spatial_out_proj'):
192
+ nn.init.zeros_(layer.spatial_out_proj.weight)
193
+ layer.spatial_down.reset_parameters()
194
+ layer.spatial_up.reset_parameters()
195
+ for module in layer.modules():
196
+ if hasattr(module, 'qk_scale'):
197
+ module.qk_scale.data.fill_(10.0)
198
+ print(f"Motion layers added: {layer_added} / {config.num_hidden_layers} (mode={config.tt_mode})")
199
+
200
+ @torch.no_grad()
201
+ def _init_weights(self, module) -> None:
202
+ super()._init_weights(module)
203
+ # transformers' from_pretrained builds on the meta device and leaves
204
+ # non-persistent buffers empty: recompute those of the TT modules
205
+ if hasattr(module, "reset_buffers"):
206
+ module.reset_buffers()
207
+
208
+ def freeze_pretrained(self, requires_grad: bool = False):
209
+ """Freeze or unfreeze the pretrained backbone components.
210
+
211
+ Pretrained components: embeddings, rope_embeddings, transformer layers, norm.
212
+ Leaves trainable-from-scratch parts (motion_tokens, motion_layers,
213
+ temporal_embeddings) untouched.
214
+ """
215
+ self.embeddings.requires_grad_(requires_grad)
216
+ self.rope_embeddings.requires_grad_(requires_grad)
217
+ self.model.layer.requires_grad_(requires_grad)
218
+ self.norm.requires_grad_(requires_grad)
219
+
220
+ def setup_patch(self, num_channels, patch_size):
221
+ self.config.num_channels = num_channels
222
+ self.config.patch_size = patch_size
223
+ self.embeddings = DINOv3ViTEmbeddings(self.config)
224
+ mup_init(self.embeddings.parameters())
225
+
226
+ @classmethod
227
+ def from_dino_v3(
228
+ cls,
229
+ dino_v3: DINOv3ViTModel,
230
+ temporal_patch_size: int = 0,
231
+ temporal_patch_overlap: int = 0,
232
+ motion_layers_period: int = 0,
233
+ num_motion_tokens: int = 0,
234
+ motion_ffn_type: str = "swiglu",
235
+ tt_mode: str = "1d",
236
+ tt_downsample: int = 4,
237
+ ):
238
+ dino_v3_config = dino_v3.config
239
+ ttvidt_config = DINOv3VidTConfig(
240
+ **dino_v3_config.to_dict(),
241
+ temporal_patch_size=temporal_patch_size,
242
+ temporal_patch_overlap=temporal_patch_overlap,
243
+ motion_layers_period=motion_layers_period,
244
+ num_motion_tokens=num_motion_tokens,
245
+ motion_ffn_type=motion_ffn_type,
246
+ tt_mode=tt_mode,
247
+ tt_downsample=tt_downsample,
248
+ )
249
+ new_model = cls(ttvidt_config)
250
+ new_model.load_state_dict(dino_v3.state_dict(), strict=False)
251
+ return new_model
252
+
253
+ def forward(
254
+ self,
255
+ pixel_values: torch.Tensor,
256
+ bool_masked_pos: Optional[torch.Tensor] = None,
257
+ head_mask: Optional[torch.Tensor] = None,
258
+ spatial_mask: Optional[torch.Tensor] = None,
259
+ **kwargs: Unpack[TransformersKwargs],
260
+ ) -> VideoModelOutputWithMotionTokens:
261
+ r"""
262
+ pixel_values: [B, T, C, H, W]
263
+ spatial_mask: optional bool tensor [L], True = visible/keep (for MAE tube masking)
264
+ """
265
+ b, t = pixel_values.shape[:2]
266
+
267
+ _, _, _, H_in, W_in = pixel_values.shape
268
+ ps = self.config.patch_size
269
+ spatial_h = H_in // ps
270
+ spatial_w = W_in // ps
271
+
272
+ pixel_values = pixel_values.to(
273
+ self.embeddings.patch_embeddings.weight.dtype
274
+ ).flatten(0, 1)
275
+ hidden_states = self.embeddings(pixel_values, bool_masked_pos=bool_masked_pos)
276
+ position_embeddings = self.rope_embeddings(pixel_values)
277
+ pixel_length = position_embeddings[0].size(0)
278
+
279
+ hidden_states = self.temporal_embeddings(hidden_states.unflatten(0, (b, -1)))
280
+
281
+ # MAE tube masking: keep only visible spatial tokens
282
+ if spatial_mask is not None:
283
+ # hidden_states may have prefix tokens (CLS + registers) before spatial tokens
284
+ # spatial_mask: bool [L] where L = num spatial patches
285
+ n_prefix = hidden_states.shape[2] - spatial_mask.shape[0]
286
+ if n_prefix > 0:
287
+ prefix = hidden_states[:, :, :n_prefix]
288
+ spatial = hidden_states[:, :, n_prefix:]
289
+ hidden_states = torch.cat([prefix, spatial[:, :, spatial_mask]], dim=2)
290
+ else:
291
+ hidden_states = hidden_states[:, :, spatial_mask]
292
+ # Subsample RoPE position embeddings: (cos[L, head_dim], sin[L, head_dim])
293
+ cos, sin = position_embeddings
294
+ position_embeddings = (cos[spatial_mask], sin[spatial_mask])
295
+ pixel_length = spatial_mask.sum().item()
296
+ b, ot, seq_len, dim = hidden_states.shape
297
+ if self.motion_tokens is not None:
298
+ hidden_states = torch.concat(
299
+ [self.motion_tokens[None, None].repeat(b, ot, 1, 1), hidden_states],
300
+ dim=2,
301
+ )
302
+
303
+ hidden_states = hidden_states.flatten(0, 1)
304
+ for i, (layer_module, motion_module) in enumerate(
305
+ zip(self.model.layer, self.motion_layers)
306
+ ):
307
+ layer_head_mask = head_mask[i] if head_mask is not None else None
308
+ hidden_states = layer_module(
309
+ hidden_states,
310
+ attention_mask=layer_head_mask,
311
+ position_embeddings=position_embeddings,
312
+ )
313
+ if not isinstance(motion_module, nn.Identity):
314
+ hidden_states = hidden_states.unflatten(0, (b, ot))
315
+ motion_tokens = hidden_states[:, :, : self.num_motion_tokens]
316
+ vit_state = hidden_states[:, :, self.num_motion_tokens :]
317
+
318
+ if isinstance(motion_module, TemporalTransfer3D):
319
+ # TT3D: pass spatial tokens (last pixel_length of vit_state)
320
+ # vit_state layout: [CLS, REG_0..REG_3, S_0..S_L]
321
+ spatial_tokens = vit_state[:, :, -pixel_length:]
322
+
323
+ if spatial_mask is not None:
324
+ # MAE mode: pad visible tokens back to full spatial grid
325
+ # for pixel unshuffle/shuffle in TT3D, then extract visible
326
+ L_full = spatial_h * spatial_w
327
+ full_spatial = spatial_tokens.new_zeros(
328
+ b, ot, L_full, dim
329
+ )
330
+ full_spatial[:, :, spatial_mask] = spatial_tokens
331
+ motion_tokens, full_spatial_out = motion_module(
332
+ motion_tokens, full_spatial, spatial_h, spatial_w
333
+ )
334
+ spatial_out = full_spatial_out[:, :, spatial_mask]
335
+ else:
336
+ motion_tokens, spatial_out = motion_module(
337
+ motion_tokens, spatial_tokens, spatial_h, spatial_w
338
+ )
339
+
340
+ # Write spatial back (only last pixel_length of vit_state)
341
+ vit_state = torch.cat(
342
+ [vit_state[:, :, :-pixel_length], spatial_out], dim=2
343
+ )
344
+ else:
345
+ # TT1D: motion tokens only
346
+ motion_tokens = motion_module(motion_tokens)
347
+
348
+ hidden_states = torch.concat([motion_tokens, vit_state], dim=2)
349
+ hidden_states = hidden_states.flatten(0, 1)
350
+
351
+ sequence_output = self.norm(hidden_states).unflatten(0, (b, ot))
352
+ frames_output = sequence_output[:, :, -pixel_length:, :]
353
+ pooled_output = sequence_output[:, :, self.num_motion_tokens, :]
354
+ if self.motion_tokens is None:
355
+ motion_output = None
356
+ cls_output = None
357
+ else:
358
+ all_tt_tokens = sequence_output[
359
+ :, :, : self.num_motion_tokens, :
360
+ ] # [B, T, num_motion_tokens, dim]
361
+ cls_output = self.cls_norm(self.motion_pooler(all_tt_tokens)) # [B, T, dim]
362
+ # Pool all TT tokens β†’ 1 motion token for decoder
363
+ motion_output = self.motion_output_pooler(all_tt_tokens).unsqueeze(2) # [B, T, 1, dim]
364
+
365
+ return VideoModelOutputWithMotionTokens(
366
+ last_hidden_state=sequence_output,
367
+ frames_output=frames_output,
368
+ pooler_output=pooled_output,
369
+ motion_output=motion_output,
370
+ cls_output=cls_output,
371
+ )
372
+
373
+
374
+ if __name__ == "__main__":
375
+ dino = DINOv3ViTModel.from_pretrained(
376
+ "facebook/dinov3-vitb16-pretrain-lvd1689m"
377
+ ).cuda()
378
+ dino_vidt = DINOv3VidTModel.from_dino_v3(
379
+ dino,
380
+ temporal_patch_size=4,
381
+ temporal_patch_overlap=1,
382
+ motion_layers_period=1,
383
+ num_motion_tokens=16,
384
+ ).cuda()
385
+
386
+ print(dino)
387
+ print(dino_vidt)
388
+
389
+ test_x = torch.randn(1, 61, 3, 256, 256).cuda()
390
+ with torch.autocast("cuda"):
391
+ result = dino_vidt(test_x)
392
+
393
+ print(result.frames_output.shape)
394
+ print(result.pooler_output.shape)
395
+ print(result.motion_output.shape)
env.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ import os
2
+ TORCH_COMPILE = os.environ.get("TORCH_COMPILE", "1") == "1"
3
+ COMPILE_KWARG = {"mode": "default", "dynamic": False}
layers.py ADDED
@@ -0,0 +1,341 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ import torch.nn.functional as F
4
+
5
+ from .utils import compile_wrapper
6
+
7
+
8
+ class RMSNorm(nn.RMSNorm):
9
+ @compile_wrapper
10
+ def forward(self, x):
11
+ return F.rms_norm(
12
+ x.to(self.weight), self.normalized_shape, self.weight, self.eps
13
+ )
14
+
15
+
16
+ class SwiGLU(nn.Module):
17
+ def __init__(self, hidden_size, intermediate_size):
18
+ super(SwiGLU, self).__init__()
19
+ self.hidden_size = hidden_size
20
+ self.intermediate_size = intermediate_size
21
+ self.up = nn.Linear(hidden_size, intermediate_size * 2)
22
+ self.down = nn.Linear(intermediate_size, hidden_size)
23
+
24
+ @compile_wrapper
25
+ def forward(self, x):
26
+ x, gate = self.up(x).chunk(2, dim=-1)
27
+ x = F.silu(x) * gate
28
+ x = self.down(x)
29
+ return x
30
+
31
+
32
+ class GELUMLP(nn.Module):
33
+ def __init__(self, hidden_size, intermediate_size):
34
+ super().__init__()
35
+ self.fc1 = nn.Linear(hidden_size, intermediate_size)
36
+ self.act = nn.GELU()
37
+ self.fc2 = nn.Linear(intermediate_size, hidden_size)
38
+
39
+ @compile_wrapper
40
+ def forward(self, x):
41
+ return self.fc2(self.act(self.fc1(x)))
42
+
43
+
44
+ def _qk_norm(q, k, scale, eps=1e-6):
45
+ """Cosine-similarity attention with learnable temperature (DisMo-style).
46
+
47
+ Logits = scale * cos(q, k).
48
+ Computes in float32 for numerical stability, uses rsqrt(sum_sq + eps).
49
+ Scale is clamped to min=eps to prevent NaN from sqrt of negative values.
50
+ """
51
+ dtype = q.dtype
52
+ q, k, scale = q.float(), k.float(), scale.float()
53
+ sum_sq_q = torch.sum(q ** 2, dim=-1, keepdim=True)
54
+ sum_sq_k = torch.sum(k ** 2, dim=-1, keepdim=True)
55
+ sqrt_scale = torch.sqrt(scale.clamp(min=eps))
56
+ scale_q = sqrt_scale * torch.rsqrt(sum_sq_q + eps)
57
+ scale_k = sqrt_scale * torch.rsqrt(sum_sq_k + eps)
58
+ return (q * scale_q).to(dtype), (k * scale_k).to(dtype)
59
+
60
+
61
+ class Attention(nn.Module):
62
+ def __init__(self, hidden_size, num_heads, qk_norm=False, bias=True):
63
+ super(Attention, self).__init__()
64
+ self.hidden_size = hidden_size
65
+ self.num_heads = num_heads
66
+ self.head_dim = hidden_size // num_heads
67
+ self.qk_norm = qk_norm
68
+ self.q_proj = nn.Linear(hidden_size, hidden_size, bias=bias)
69
+ self.k_proj = nn.Linear(hidden_size, hidden_size, bias=bias)
70
+ self.v_proj = nn.Linear(hidden_size, hidden_size, bias=bias)
71
+ self.out_proj = nn.Linear(hidden_size, hidden_size, bias=bias)
72
+ if qk_norm:
73
+ self.qk_scale = nn.Parameter(torch.full([num_heads, 1, 1], 10.0))
74
+
75
+ @compile_wrapper
76
+ def forward(self, x, rope=None, positions=None):
77
+ """
78
+ Args:
79
+ x: [B, T, SL, D] or [B, SL, D]
80
+ rope: optional RoPE3D module (from tt3d.py)
81
+ positions: optional [SL, 3] positions for 3D RoPE
82
+ """
83
+ # [B, T, SL, D]
84
+ *b, seq_len, dim = x.shape
85
+ x = x.flatten(1, 2)
86
+ q = self.q_proj(x)
87
+ k = self.k_proj(x)
88
+ v = self.v_proj(x)
89
+ q = q.view(-1, seq_len, self.num_heads, self.head_dim).transpose(1, 2)
90
+ k = k.view(-1, seq_len, self.num_heads, self.head_dim).transpose(1, 2)
91
+ v = v.view(-1, seq_len, self.num_heads, self.head_dim).transpose(1, 2)
92
+
93
+ # Optional 3D RoPE
94
+ if rope is not None and positions is not None:
95
+ q, k = rope(q, k, positions)
96
+
97
+ if self.qk_norm:
98
+ q, k = _qk_norm(q, k, self.qk_scale)
99
+ attn = F.scaled_dot_product_attention(q, k, v, scale=1.0)
100
+ else:
101
+ attn = F.scaled_dot_product_attention(q, k, v)
102
+
103
+ x = self.out_proj(attn.transpose(1, 2).flatten(2, 3))
104
+ return x.reshape(*b, seq_len, dim)
105
+
106
+
107
+ class TransformerBlock(nn.Module):
108
+ """Standard pre-norm transformer block: RMSNorm + Attention + FFN (SwiGLU or GELU)."""
109
+
110
+ def __init__(self, hidden_size: int, intermediate_size: int, num_heads: int,
111
+ ffn_type: str = "swiglu", qk_norm: bool = False):
112
+ super().__init__()
113
+ self.norm1 = RMSNorm(hidden_size)
114
+ self.attn = Attention(hidden_size, num_heads, qk_norm=qk_norm)
115
+ self.norm2 = RMSNorm(hidden_size)
116
+ if ffn_type == "gelu":
117
+ self.mlp = GELUMLP(hidden_size, intermediate_size)
118
+ else:
119
+ self.mlp = SwiGLU(hidden_size, intermediate_size)
120
+
121
+ def forward(self, x: torch.Tensor, rope=None, positions=None) -> torch.Tensor:
122
+ x = x + self.attn(self.norm1(x), rope=rope, positions=positions)
123
+ x = x + self.mlp(self.norm2(x))
124
+ return x
125
+
126
+
127
+ class AdaRMSNorm(nn.Module):
128
+ """Adaptive RMSNorm: scale-only modulation from conditioning signal (DisMo-style)."""
129
+
130
+ def __init__(self, hidden_size: int, cond_size: int):
131
+ super().__init__()
132
+ self.norm = nn.RMSNorm(hidden_size)
133
+ self.linear = nn.Linear(cond_size, hidden_size, bias=False)
134
+ nn.init.zeros_(self.linear.weight)
135
+
136
+ @compile_wrapper
137
+ def forward(self, x: torch.Tensor, c: torch.Tensor) -> torch.Tensor:
138
+ """
139
+ Args:
140
+ x: [..., D] input tensor
141
+ c: [..., C] conditioning tensor (broadcastable to x batch dims)
142
+ Returns:
143
+ [..., D] modulated tensor
144
+ """
145
+ return (self.linear(F.silu(c)) + 1) * self.norm(x.to(self.norm.weight))
146
+
147
+
148
+ class CrossAttention(nn.Module):
149
+ """Cross-attention: Q from main stream, K/V from context."""
150
+
151
+ def __init__(self, hidden_size: int, num_heads: int, context_size: int | None = None, qk_norm: bool = False, bias: bool = True):
152
+ super().__init__()
153
+ self.hidden_size = hidden_size
154
+ self.num_heads = num_heads
155
+ self.head_dim = hidden_size // num_heads
156
+ self.qk_norm = qk_norm
157
+ context_size = context_size or hidden_size
158
+ self.q_proj = nn.Linear(hidden_size, hidden_size, bias=bias)
159
+ self.k_proj = nn.Linear(context_size, hidden_size, bias=bias)
160
+ self.v_proj = nn.Linear(context_size, hidden_size, bias=bias)
161
+ self.out_proj = nn.Linear(hidden_size, hidden_size, bias=bias)
162
+ if qk_norm:
163
+ self.qk_scale = nn.Parameter(torch.full([num_heads, 1, 1], 10.0))
164
+
165
+ @compile_wrapper
166
+ def forward(self, x: torch.Tensor, context: torch.Tensor) -> torch.Tensor:
167
+ """
168
+ Args:
169
+ x: [B, T, S, D] main stream (query)
170
+ context: [B, T, Sc, Dc] context (key/value)
171
+ Returns:
172
+ [B, T, S, D]
173
+ """
174
+ bt = x.shape[0] * x.shape[1]
175
+ seq_q = x.shape[2]
176
+ seq_kv = context.shape[2]
177
+
178
+ x_flat = x.reshape(bt, seq_q, self.hidden_size)
179
+ ctx_flat = context.reshape(bt, seq_kv, -1)
180
+
181
+ q = self.q_proj(x_flat).view(bt, seq_q, self.num_heads, self.head_dim).transpose(1, 2)
182
+ k = self.k_proj(ctx_flat).view(bt, seq_kv, self.num_heads, self.head_dim).transpose(1, 2)
183
+ v = self.v_proj(ctx_flat).view(bt, seq_kv, self.num_heads, self.head_dim).transpose(1, 2)
184
+
185
+ if self.qk_norm:
186
+ q, k = _qk_norm(q, k, self.qk_scale)
187
+ attn = F.scaled_dot_product_attention(q, k, v, scale=1.0)
188
+ else:
189
+ attn = F.scaled_dot_product_attention(q, k, v)
190
+ out = self.out_proj(attn.transpose(1, 2).flatten(2, 3))
191
+ return out.view(x.shape)
192
+
193
+
194
+ class AttentivePooling(nn.Module):
195
+ """Learnable query token attends to M tokens to produce a CLS-like token."""
196
+
197
+ def __init__(self, hidden_size: int, num_heads: int = 1):
198
+ super().__init__()
199
+ self.hidden_size = hidden_size
200
+ self.num_heads = num_heads
201
+ self.head_dim = hidden_size // num_heads
202
+ self.query = nn.Parameter(torch.randn(1, 1, 1, hidden_size) * 0.02)
203
+ self.k_proj = nn.Linear(hidden_size, hidden_size)
204
+ self.v_proj = nn.Linear(hidden_size, hidden_size)
205
+ self.out_proj = nn.Linear(hidden_size, hidden_size)
206
+
207
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
208
+ """
209
+ Args:
210
+ x: [B, T, M, D] motion tokens
211
+ Returns:
212
+ [B, T, D] pooled CLS-like token
213
+ """
214
+ B, T, M, D = x.shape
215
+ bt = B * T
216
+
217
+ q = self.query.expand(B, T, -1, -1).reshape(bt, 1, self.num_heads, self.head_dim).transpose(1, 2)
218
+ x_flat = x.reshape(bt, M, D)
219
+ k = self.k_proj(x_flat).view(bt, M, self.num_heads, self.head_dim).transpose(1, 2)
220
+ v = self.v_proj(x_flat).view(bt, M, self.num_heads, self.head_dim).transpose(1, 2)
221
+
222
+ attn = F.scaled_dot_product_attention(q, k, v) # [bt, H, 1, head_dim]
223
+ out = self.out_proj(attn.transpose(1, 2).flatten(2, 3)) # [bt, 1, D]
224
+ return out.squeeze(2).view(B, T, D)
225
+
226
+
227
+ class DiTTransformerBlock(nn.Module):
228
+ """DiT-style transformer block with AdaRMSNorm conditioning and optional cross-attention."""
229
+
230
+ def __init__(
231
+ self,
232
+ hidden_size: int,
233
+ intermediate_size: int,
234
+ num_heads: int,
235
+ cond_size: int,
236
+ use_cross_attn: bool = False,
237
+ context_size: int | None = None,
238
+ use_rope: bool = False,
239
+ qk_norm: bool = False,
240
+ bias: bool = True,
241
+ ):
242
+ super().__init__()
243
+ from .pos_embed import RoPE2DAttention
244
+
245
+ # Self-attention sub-layer (with optional 2D RoPE)
246
+ self.ada_norm1 = AdaRMSNorm(hidden_size, cond_size)
247
+ self.use_rope = use_rope
248
+ if use_rope:
249
+ self.attn = RoPE2DAttention(hidden_size, num_heads, qk_norm=qk_norm, bias=bias)
250
+ else:
251
+ self.attn = Attention(hidden_size, num_heads, qk_norm=qk_norm, bias=bias)
252
+
253
+ # Optional cross-attention sub-layer
254
+ self.use_cross_attn = use_cross_attn
255
+ if use_cross_attn:
256
+ self.ada_norm_cross = AdaRMSNorm(hidden_size, cond_size)
257
+ self.cross_attn = CrossAttention(hidden_size, num_heads, context_size, qk_norm=qk_norm, bias=bias)
258
+
259
+ # FFN sub-layer
260
+ self.ada_norm2 = AdaRMSNorm(hidden_size, cond_size)
261
+ self.mlp = SwiGLU(hidden_size, intermediate_size)
262
+
263
+ def forward(
264
+ self,
265
+ x: torch.Tensor,
266
+ c: torch.Tensor,
267
+ context: torch.Tensor | None = None,
268
+ h: int | None = None,
269
+ w: int | None = None,
270
+ ) -> torch.Tensor:
271
+ """
272
+ Args:
273
+ x: [B, T, S, D] main stream
274
+ c: [B, T, 1, Dc] conditioning (broadcast over S)
275
+ context: [B, T, Sc, Dc_ctx] optional cross-attn context
276
+ h, w: spatial dims (required when use_rope=True)
277
+ Returns:
278
+ [B, T, S, D]
279
+ """
280
+ if self.use_rope:
281
+ x = x + self.attn(self.ada_norm1(x, c), h, w)
282
+ else:
283
+ x = x + self.attn(self.ada_norm1(x, c))
284
+ if self.use_cross_attn and context is not None:
285
+ x = x + self.cross_attn(self.ada_norm_cross(x, c), context)
286
+ x = x + self.mlp(self.ada_norm2(x, c))
287
+ return x
288
+
289
+
290
+ class LatentPatchEmbed(nn.Module):
291
+ """
292
+ Patch embedding for latent-space video input.
293
+
294
+ Expects input of shape [B, T, C_in, H, W] where the spatial dimensions are
295
+ already at patch resolution (e.g. from a VAE encoder). If the input channel
296
+ dimension differs from hidden_size, a linear projection is applied per-patch.
297
+
298
+ When spatial_patch_size > 1 the spatial grid is further down-sampled via a
299
+ Conv2d with kernel_size = stride = spatial_patch_size.
300
+ """
301
+
302
+ def __init__(
303
+ self,
304
+ in_channels: int,
305
+ hidden_size: int,
306
+ spatial_patch_size: int = 1,
307
+ ):
308
+ super().__init__()
309
+ self.in_channels = in_channels
310
+ self.hidden_size = hidden_size
311
+ self.spatial_patch_size = spatial_patch_size
312
+
313
+ if spatial_patch_size > 1:
314
+ self.proj = nn.Conv2d(
315
+ in_channels,
316
+ hidden_size,
317
+ kernel_size=spatial_patch_size,
318
+ stride=spatial_patch_size,
319
+ )
320
+ else:
321
+ self.proj = nn.Linear(in_channels, hidden_size)
322
+
323
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
324
+ """
325
+ Args:
326
+ x: [B, T, C, H, W]
327
+ Returns:
328
+ [B, T, H'*W', D] where H' = H // spatial_patch_size, etc.
329
+ """
330
+ b, t, c, h, w = x.shape
331
+ if self.spatial_patch_size > 1:
332
+ x = x.reshape(b * t, c, h, w)
333
+ x = self.proj(x) # [B*T, D, H', W']
334
+ _, d, hp, wp = x.shape
335
+ x = x.flatten(2).transpose(1, 2) # [B*T, H'*W', D]
336
+ x = x.reshape(b, t, hp * wp, d)
337
+ else:
338
+ # x: [B, T, C, H, W] -> [B, T, H*W, C] -> Linear -> [B, T, H*W, D]
339
+ x = x.permute(0, 1, 3, 4, 2).reshape(b, t, h * w, c)
340
+ x = self.proj(x)
341
+ return x
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:03f7f365511775818645e02e4b4d56758a981d2c5c9122c4758fcb22fccbfce5
3
+ size 781976200
modeling_ttvidt.py ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Hugging Face ``transformers`` wrapper around the TT-VidT encoder.
2
+
3
+ ``scripts/tools/export_hf.py`` copies this file (as ``modeling_ttvidt.py``) and the
4
+ encoder sources next to an exported model, so the same directory / Hub repo loads with
5
+
6
+ from transformers import AutoModel
7
+ model = AutoModel.from_pretrained("<repo>", trust_remote_code=True)
8
+ motion = model(video).motion_output # video: [B, T, 3, 256, 256] in [-1, 1]
9
+
10
+ and with ``ttvidt.hub.load_model("<repo>")``: ``config.json`` holds the release format
11
+ (``format``, ``model`` = TTVidTrainer arguments) plus the ``transformers`` fields, and
12
+ ``model.safetensors`` uses the TTVidTrainer key names (``encoder.*``).
13
+ """
14
+
15
+ from transformers import PretrainedConfig, PreTrainedModel
16
+
17
+ from .dinov3_vit import DINOv3VidTConfig, DINOv3VidTModel
18
+
19
+
20
+ class TTVidTConfig(PretrainedConfig):
21
+ """``model``: the TTVidTrainer keyword arguments of the release (``backbone_config``
22
+ holds the full DINOv3VidTConfig, so no DINOv3 download is needed)."""
23
+
24
+ model_type = "ttvidt"
25
+
26
+ def __init__(self, format: str | None = None, model: dict | None = None,
27
+ encoder_only: bool = False, **kwargs):
28
+ self.format = format
29
+ self.model = model or {}
30
+ self.encoder_only = encoder_only
31
+ super().__init__(**kwargs)
32
+
33
+ def encoder_config(self) -> DINOv3VidTConfig:
34
+ if self.model.get("backbone_arch", "ttvidt") != "ttvidt":
35
+ raise ValueError(f"only TT-VidT encoders are supported, got {self.model.get('backbone_arch')!r}")
36
+ cfg = dict(self.model["backbone_config"])
37
+ for k, v in (self.model.get("motion_encoder_config") or {}).items():
38
+ cfg.setdefault(k, v) # same merge as TTVidTrainer
39
+ return DINOv3VidTConfig(**cfg)
40
+
41
+
42
+ class TTVidTModel(PreTrainedModel):
43
+ """The TT-VidT video encoder (``DINOv3VidTModel``); ``forward`` returns its output
44
+ (``motion_output``: [B, T, K, D] motion tokens per frame)."""
45
+
46
+ config_class = TTVidTConfig
47
+ base_model_prefix = "ttvidt"
48
+ main_input_name = "pixel_values"
49
+ # the decoder and the frame-VAE latent statistics of full releases are not used
50
+ _keys_to_ignore_on_load_unexpected = [r"^decoder\.", r"^latent_(mean|std)$"]
51
+
52
+ def __init__(self, config: TTVidTConfig):
53
+ super().__init__(config)
54
+ self.encoder = DINOv3VidTModel(config.encoder_config())
55
+ self.post_init()
56
+
57
+ def _init_weights(self, module):
58
+ pass # DINOv3VidTModel initialises itself; pretrained weights come from the file
59
+
60
+ def forward(self, pixel_values, **kwargs):
61
+ """pixel_values: [B, T, 3, H, W] in [-1, 1]."""
62
+ return self.encoder(pixel_values, **kwargs)
mup.py ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """muP initialisation (same as ``optimfactory.mup_init`` / ``mup_init_output``)."""
2
+
3
+ import math
4
+
5
+ import torch
6
+
7
+
8
+ def mup_init(params, is_output: bool = False) -> None:
9
+ for param in params:
10
+ if param.ndim == 1:
11
+ continue
12
+ fan_in = math.prod(param.shape[1:])
13
+ std = (1 / fan_in) ** (1 if is_output else 0.5)
14
+ torch.nn.init.normal_(param, mean=0.0, std=std)
15
+
16
+
17
+ def mup_init_output(param: torch.Tensor) -> None:
18
+ mup_init([param], is_output=True)
patch.py ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ import torch.nn.functional as F
4
+
5
+ from .utils import compile_wrapper
6
+
7
+
8
+ class TemporalPatch(nn.Module):
9
+ def __init__(
10
+ self,
11
+ input_channels,
12
+ output_channels,
13
+ patch_size=2,
14
+ overlap=1,
15
+ init_gamma=1.1,
16
+ ):
17
+ super(TemporalPatch, self).__init__()
18
+ self.patch_size = patch_size
19
+ self.overlap = overlap
20
+ self.input_channels = input_channels
21
+ self.output_channels = output_channels
22
+ if input_channels != output_channels:
23
+ self.fproj = nn.Conv1d(input_channels, output_channels, 1, 1, 0)
24
+ else:
25
+ self.fproj = nn.Identity()
26
+ self.tproj = nn.Conv1d(
27
+ output_channels, output_channels, patch_size + overlap, stride=patch_size
28
+ )
29
+ self.init_gamma = init_gamma
30
+ self.init_weight()
31
+
32
+ def init_weight(self):
33
+ if isinstance(self.fproj, nn.Conv1d):
34
+ nn.init.constant_(self.fproj.bias, 0)
35
+ nn.init.normal_(self.fproj.weight, std=1 / self.input_channels**0.5)
36
+
37
+ nn.init.constant_(self.tproj.bias, 0)
38
+ tproj_patch = self.tproj.weight.size(-1)
39
+ I = torch.eye(self.tproj.weight.size(0)).to(self.tproj.weight)[..., None]
40
+ weight = I.repeat(1, 1, tproj_patch) * self.init_gamma
41
+ scale = [self.init_gamma**i for i in range(tproj_patch)]
42
+ scale = torch.tensor(scale).to(self.tproj.weight) / sum(scale)
43
+ self.tproj.weight.data.copy_(weight * scale[None, None, :])
44
+
45
+ @compile_wrapper
46
+ def forward(self, x):
47
+ """
48
+ x: [B, T, L, C]
49
+ """
50
+ b, t, l, c = x.shape
51
+ x = x.permute(0, 2, 3, 1).contiguous().view(b * l, c, t)
52
+
53
+ x = self.fproj(x)
54
+ first_frame = x[..., 0:1]
55
+ x = self.tproj(x)
56
+ x = torch.concat([first_frame, x], dim=-1)
57
+
58
+ _, oc, ot = x.shape
59
+ x = x.view(b, l, oc, ot).permute(0, 3, 1, 2).contiguous()
60
+ return x
61
+
62
+
63
+ if __name__ == "__main__":
64
+ x = torch.randn(2, 1 + 15 * 8, 3, 224, 224)
65
+ m = TemporalPatch(3, 4, 8, 1)
66
+ y = m(x) # [B, 1 + (T-1)//p, 4, H, W]
67
+ print(y.shape)
pos_embed.py ADDED
@@ -0,0 +1,358 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Positional embedding modules for TT-VidT.
3
+
4
+ Includes:
5
+ - Sinusoidal 1D/2D position embeddings
6
+ - Adaptive RoPE (Rotary Position Embedding) with aspect-ratio-aware positions
7
+ - Temporal distance embeddings
8
+ """
9
+
10
+ import math
11
+ import torch
12
+ import torch.nn as nn
13
+ import torch.nn.functional as F
14
+
15
+ from .utils import compile_wrapper
16
+
17
+ # ============================================================================
18
+ # Sinusoidal Position Embeddings
19
+ # ============================================================================
20
+
21
+
22
+ def get_1d_sincos_pos_embed(
23
+ embed_dim: int, pos: torch.Tensor, max_period: int = 10000
24
+ ) -> torch.Tensor:
25
+ """
26
+ Generate 1D sinusoidal positional embeddings.
27
+
28
+ Args:
29
+ embed_dim: Embedding dimension
30
+ pos: Position tensor [N]
31
+ max_period: Maximum period for frequency bands
32
+
33
+ Returns:
34
+ Sinusoidal embeddings [N, embed_dim]
35
+ """
36
+ half_dim = embed_dim // 2
37
+ freqs = torch.exp(
38
+ -math.log(max_period)
39
+ * torch.arange(half_dim, dtype=torch.float32, device=pos.device)
40
+ / half_dim
41
+ )
42
+ args = pos.unsqueeze(-1) * freqs # [N, D/2]
43
+ return torch.cat([torch.sin(args), torch.cos(args)], dim=-1) # [N, D]
44
+
45
+
46
+ def get_2d_sincos_pos_embed(
47
+ embed_dim: int, h: int, w: int, max_period: int = 10000
48
+ ) -> torch.Tensor:
49
+ """
50
+ Generate 2D sinusoidal positional embeddings.
51
+
52
+ Args:
53
+ embed_dim: Embedding dimension
54
+ h, w: Grid height and width
55
+ max_period: Maximum period for frequency bands
56
+
57
+ Returns:
58
+ Sinusoidal embeddings [H*W, embed_dim]
59
+ """
60
+ grid_h = torch.arange(h, dtype=torch.float32)
61
+ grid_w = torch.arange(w, dtype=torch.float32)
62
+ grid = torch.stack(
63
+ torch.meshgrid(grid_h, grid_w, indexing="ij"), dim=-1
64
+ ) # [H, W, 2]
65
+ grid = grid.reshape(-1, 2) # [H*W, 2]
66
+
67
+ # Split embedding dim for h and w
68
+ half_dim = embed_dim // 2
69
+ emb_h = get_1d_sincos_pos_embed(half_dim, grid[:, 0], max_period)
70
+ emb_w = get_1d_sincos_pos_embed(half_dim, grid[:, 1], max_period)
71
+ return torch.cat([emb_h, emb_w], dim=-1) # [H*W, D]
72
+
73
+
74
+ def get_adaptive_2d_pos(
75
+ h: int, w: int, device: torch.device
76
+ ) -> tuple[torch.Tensor, torch.Tensor]:
77
+ """
78
+ Generate adaptive 2D positions with aspect-ratio-aware normalization.
79
+
80
+ Position mapping is normalized such that:
81
+ - max(H) * max(W) = 1 (positions are in normalized range)
82
+ - max(H) / max(W) = h / w (preserves aspect ratio)
83
+
84
+ This means: max_H = sqrt(h/w), max_W = sqrt(w/h)
85
+
86
+ Args:
87
+ h, w: Grid dimensions
88
+ device: Torch device
89
+
90
+ Returns:
91
+ (grid_h, grid_w): Flattened position grids, each [H*W]
92
+ """
93
+ aspect = h / w
94
+ max_H = math.sqrt(aspect)
95
+ max_W = math.sqrt(1.0 / aspect)
96
+
97
+ pos_h = torch.linspace(0, max_H, h, device=device, dtype=torch.float32)
98
+ pos_w = torch.linspace(0, max_W, w, device=device, dtype=torch.float32)
99
+
100
+ grid_h, grid_w = torch.meshgrid(pos_h, pos_w, indexing="ij")
101
+ return grid_h.reshape(-1), grid_w.reshape(-1)
102
+
103
+
104
+ # ============================================================================
105
+ # Temporal Distance Embedding
106
+ # ============================================================================
107
+
108
+
109
+ class TemporalDistanceEmbedding(nn.Module):
110
+ """
111
+ Temporal distance embedding as a concatenated token using sincos encoding.
112
+
113
+ Instead of adding temporal pos encoding, we create a dedicated token
114
+ that encodes the distance from source frame to target motion frame.
115
+ This token is concatenated: [frame_emb, motion_emb, time_info]
116
+
117
+ Uses sinusoidal positional encoding (like standard transformer timestep)
118
+ which generalizes to arbitrary frame distances without a fixed max.
119
+ """
120
+
121
+ def __init__(self, hidden_size: int, max_period: int = 10000):
122
+ super().__init__()
123
+ self.hidden_size = hidden_size
124
+ self.max_period = max_period
125
+
126
+ # Precompute frequency bands for sincos encoding
127
+ half_dim = hidden_size // 2
128
+ freqs = torch.exp(
129
+ -math.log(max_period)
130
+ * torch.arange(half_dim, dtype=torch.float32)
131
+ / half_dim
132
+ )
133
+ self.register_buffer("freqs", freqs)
134
+
135
+ def forward(
136
+ self,
137
+ batch_size: int,
138
+ num_frames: int,
139
+ device: torch.device,
140
+ start_distance: int = 1,
141
+ ) -> torch.Tensor:
142
+ """
143
+ Generate temporal distance tokens using sincos encoding.
144
+
145
+ Args:
146
+ batch_size: batch size
147
+ num_frames: number of motion frames (T)
148
+ device: torch device
149
+ start_distance: distance of first motion frame from reference
150
+
151
+ Returns:
152
+ [B, T, 1, D] temporal distance tokens
153
+ """
154
+ distances = torch.arange(
155
+ start_distance,
156
+ start_distance + num_frames,
157
+ device=device,
158
+ dtype=torch.float32,
159
+ )
160
+
161
+ # Sincos encoding: [T, D/2] -> [T, D]
162
+ args = distances.unsqueeze(-1) * self.freqs.to(device) # [T, D/2]
163
+ time_tokens = torch.cat([torch.sin(args), torch.cos(args)], dim=-1) # [T, D]
164
+
165
+ # Expand: [1, T, 1, D] -> [B, T, 1, D]
166
+ return time_tokens.unsqueeze(0).unsqueeze(2).expand(batch_size, -1, -1, -1)
167
+
168
+
169
+ # ============================================================================
170
+ # Additive RoPE
171
+ # ============================================================================
172
+
173
+
174
+ class AdditiveRoPE2D(nn.Module):
175
+ """
176
+ Additive 2D Rotary Position Embedding with adaptive aspect-ratio-aware positions.
177
+
178
+ x = x + rope(learnable_token, pos)
179
+
180
+ Position mapping is normalized such that:
181
+ - max(H) * max(W) = 1 (positions are in [0, 1] range)
182
+ - max(H) / max(W) = vid_h / vid_w (preserves aspect ratio)
183
+
184
+ This removes the need for max_h/max_w parameters and generalizes to any resolution.
185
+ """
186
+
187
+ def __init__(self, hidden_size: int, max_period: int = 10000):
188
+ super().__init__()
189
+ self.hidden_size = hidden_size
190
+ self.max_period = max_period
191
+
192
+ # Learnable token that gets modulated by position
193
+ self.learnable_token = nn.Parameter(torch.randn(1, 1, hidden_size) * 0.02)
194
+
195
+ # Precompute frequency bands for sincos encoding (half for h, half for w)
196
+ quarter_dim = hidden_size // 4
197
+ freqs = torch.exp(
198
+ -math.log(max_period)
199
+ * torch.arange(quarter_dim, dtype=torch.float32)
200
+ / quarter_dim
201
+ )
202
+ self.register_buffer("freqs", freqs)
203
+
204
+ def _get_adaptive_pos_embed(
205
+ self, h: int, w: int, device: torch.device
206
+ ) -> torch.Tensor:
207
+ """Generate position embeddings with adaptive aspect-ratio-aware mapping."""
208
+ grid_h, grid_w = get_adaptive_2d_pos(h, w, device)
209
+
210
+ # Sincos encoding for h and w positions
211
+ args_h = grid_h.unsqueeze(-1) * self.freqs.to(device) # [L, D/4]
212
+ emb_h = torch.cat([torch.sin(args_h), torch.cos(args_h)], dim=-1) # [L, D/2]
213
+
214
+ args_w = grid_w.unsqueeze(-1) * self.freqs.to(device) # [L, D/4]
215
+ emb_w = torch.cat([torch.sin(args_w), torch.cos(args_w)], dim=-1) # [L, D/2]
216
+
217
+ return torch.cat([emb_h, emb_w], dim=-1) # [L, D]
218
+
219
+ def forward(self, x: torch.Tensor, h: int, w: int) -> torch.Tensor:
220
+ """
221
+ Args:
222
+ x: [B, T, L, D] or [B, L, D] input tensor
223
+ h, w: spatial dimensions
224
+
225
+ Returns:
226
+ x with additive RoPE applied
227
+ """
228
+ pos = self._get_adaptive_pos_embed(h, w, x.device).unsqueeze(0) # [1, L, D]
229
+ rope_emb = self.learnable_token * pos # [1, L, D]
230
+
231
+ if x.ndim == 4:
232
+ rope_emb = rope_emb.unsqueeze(1) # [1, 1, L, D]
233
+
234
+ return x + rope_emb
235
+
236
+
237
+ # ============================================================================
238
+ # Rotary RoPE Attention
239
+ # ============================================================================
240
+
241
+
242
+ class RoPE2DAttention(nn.Module):
243
+ """
244
+ Attention with 2D Rotary Position Embedding applied to Q and K.
245
+
246
+ Uses standard RoPE formulation extended to 2D with adaptive aspect-ratio-aware positions.
247
+ Position mapping is normalized such that max(H) * max(W) = 1 and preserves aspect ratio.
248
+ """
249
+
250
+ def __init__(self, hidden_size: int, num_heads: int, max_period: int = 10000, qk_norm: bool = False, bias: bool = True):
251
+ super().__init__()
252
+ self.hidden_size = hidden_size
253
+ self.num_heads = num_heads
254
+ self.head_dim = hidden_size // num_heads
255
+ self.max_period = max_period
256
+ self.qk_norm = qk_norm
257
+ if qk_norm:
258
+ self.qk_scale = nn.Parameter(torch.full([num_heads, 1, 1], 10.0))
259
+
260
+ self.q_proj = nn.Linear(hidden_size, hidden_size, bias=bias)
261
+ self.k_proj = nn.Linear(hidden_size, hidden_size, bias=bias)
262
+ self.v_proj = nn.Linear(hidden_size, hidden_size, bias=bias)
263
+ self.out_proj = nn.Linear(hidden_size, hidden_size, bias=bias)
264
+
265
+ # Precompute frequency bands (quarter for h, quarter for w)
266
+ quarter_head_dim = self.head_dim // 4
267
+ freqs = 1.0 / (
268
+ max_period
269
+ ** (
270
+ torch.arange(0, quarter_head_dim, dtype=torch.float32)
271
+ / quarter_head_dim
272
+ )
273
+ )
274
+ self.register_buffer("freqs", freqs)
275
+
276
+ def _compute_adaptive_rope_freqs(self, h: int, w: int, device: torch.device):
277
+ """Compute RoPE frequencies for 2D grid with adaptive aspect-ratio mapping."""
278
+ grid_h, grid_w = get_adaptive_2d_pos(h, w, device)
279
+
280
+ freqs_h = torch.outer(grid_h, self.freqs.to(device)) # [L, head_dim/4]
281
+ freqs_w = torch.outer(grid_w, self.freqs.to(device)) # [L, head_dim/4]
282
+ freqs = torch.cat([freqs_h, freqs_w], dim=-1) # [L, head_dim/2]
283
+
284
+ return torch.cos(freqs), torch.sin(freqs)
285
+
286
+ def _apply_rope(
287
+ self, x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor
288
+ ) -> torch.Tensor:
289
+ """Apply rotary position embedding."""
290
+ # x: [B, num_heads, L, head_dim]
291
+ # cos, sin: [L, head_dim/2]
292
+ x_half = x.shape[-1] // 2
293
+ x1, x2 = x[..., :x_half], x[..., x_half:]
294
+
295
+ cos = cos.unsqueeze(0).unsqueeze(0) # [1, 1, L, head_dim/2]
296
+ sin = sin.unsqueeze(0).unsqueeze(0)
297
+
298
+ return torch.cat([x1 * cos - x2 * sin, x1 * sin + x2 * cos], dim=-1)
299
+
300
+ @compile_wrapper
301
+ def forward(self, x: torch.Tensor, h: int, w: int) -> torch.Tensor:
302
+ """
303
+ Args:
304
+ x: [B, T, S, D] input (T=temporal, S=sequence length)
305
+ S may be h*w (spatial only) or h*w + extra tokens (motion, timestep, etc.)
306
+ h, w: spatial dimensions (h*w <= S)
307
+ """
308
+ B, T, S, D = x.shape
309
+ L = h * w # spatial token count
310
+ total = T * S
311
+
312
+ x_flat = x.flatten(1, 2) # [B, T*S, D]
313
+
314
+ q = self.q_proj(x_flat)
315
+ k = self.k_proj(x_flat)
316
+ v = self.v_proj(x_flat)
317
+
318
+ q = q.view(B, total, self.num_heads, self.head_dim).transpose(1, 2)
319
+ k = k.view(B, total, self.num_heads, self.head_dim).transpose(1, 2)
320
+ v = v.view(B, total, self.num_heads, self.head_dim).transpose(1, 2)
321
+
322
+ # Get adaptive RoPE frequencies for spatial positions
323
+ cos_spatial, sin_spatial = self._compute_adaptive_rope_freqs(h, w, x.device)
324
+ # cos_spatial, sin_spatial: [L, head_dim/2]
325
+
326
+ # Build per-token RoPE: spatial tokens get position encoding,
327
+ # extra tokens (motion, timestep) get zero rotation (cos=1, sin=0)
328
+ half = cos_spatial.shape[-1]
329
+ if S > L:
330
+ extra = S - L
331
+ ones = torch.ones(extra, half, device=x.device, dtype=cos_spatial.dtype)
332
+ zeros = torch.zeros(extra, half, device=x.device, dtype=cos_spatial.dtype)
333
+ cos_frame = torch.cat([cos_spatial, ones], dim=0) # [S, half]
334
+ sin_frame = torch.cat([sin_spatial, zeros], dim=0) # [S, half]
335
+ else:
336
+ cos_frame = cos_spatial
337
+ sin_frame = sin_spatial
338
+
339
+ # Tile for all temporal frames
340
+ cos = cos_frame.unsqueeze(0).expand(T, -1, -1).reshape(total, -1)
341
+ sin = sin_frame.unsqueeze(0).expand(T, -1, -1).reshape(total, -1)
342
+
343
+ # Apply RoPE to Q and K
344
+ q = self._apply_rope(q, cos, sin)
345
+ k = self._apply_rope(k, cos, sin)
346
+
347
+ # QK-norm (after RoPE)
348
+ if self.qk_norm:
349
+ from .layers import _qk_norm
350
+ q, k = _qk_norm(q, k, self.qk_scale)
351
+ attn = F.scaled_dot_product_attention(q, k, v, scale=1.0)
352
+ else:
353
+ attn = F.scaled_dot_product_attention(q, k, v)
354
+
355
+ out = attn.transpose(1, 2).flatten(2, 3) # [B, T*S, D]
356
+ out = self.out_proj(out)
357
+
358
+ return out.view(B, T, S, D)
tt.py ADDED
@@ -0,0 +1,167 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ TemporalTransfer (TT1D): Block-causal temporal attention on motion tokens with 1D temporal RoPE.
3
+
4
+ Each frame's M motion tokens attend to current and past frames' motion tokens.
5
+ 1D RoPE encodes temporal position (frame index) so tokens know their temporal order.
6
+ """
7
+
8
+ import math
9
+
10
+ import torch
11
+ import torch.nn as nn
12
+ import torch.nn.functional as F
13
+ from .utils import compile_wrapper
14
+ from .layers import SwiGLU, GELUMLP, RMSNorm
15
+
16
+
17
+ # =============================================================================
18
+ # Block-causal mask (cached)
19
+ # =============================================================================
20
+
21
+ _mask_cache: dict[tuple, torch.Tensor] = {}
22
+
23
+
24
+ def get_block_causal_mask(t, m, device):
25
+ """Bool mask [T*M, T*M] where frame i attends to frames 0..i."""
26
+ key = (t, m, str(device))
27
+ if key not in _mask_cache:
28
+ causal = torch.tril(torch.ones(t, t, device=device, dtype=torch.bool))
29
+ block = causal[:, :, None, None].expand(-1, -1, m, m)
30
+ mask = block.permute(0, 2, 1, 3).reshape(t * m, t * m)
31
+ _mask_cache[key] = mask
32
+ return _mask_cache[key]
33
+
34
+
35
+ # =============================================================================
36
+ # 1D Temporal RoPE
37
+ # =============================================================================
38
+
39
+ class TemporalRoPE1D(nn.Module):
40
+ """1D Rotary Position Embedding for temporal dimension.
41
+
42
+ Applies RoPE to half the head_dim (temporal), leaves the other half unchanged.
43
+ """
44
+
45
+ def __init__(self, head_dim: int, max_period: float = 10000.0):
46
+ super().__init__()
47
+ self.head_dim = head_dim
48
+ # Use half for temporal RoPE, half unchanged
49
+ self.rope_dim = head_dim // 2
50
+ self.unused_dim = head_dim - self.rope_dim
51
+ self.max_period = max_period
52
+ self.register_buffer("freqs", self._freqs(), persistent=False)
53
+
54
+ def _freqs(self) -> torch.Tensor:
55
+ half = self.rope_dim // 2
56
+ return torch.exp(
57
+ -math.log(self.max_period) * torch.arange(half, dtype=torch.float32) / half
58
+ )
59
+
60
+ def reset_buffers(self) -> None:
61
+ """Recompute the non-persistent buffers (e.g. after transformers' meta-device loading)."""
62
+ self.freqs.copy_(self._freqs())
63
+
64
+ def forward(self, q: torch.Tensor, k: torch.Tensor, t: int, m: int):
65
+ """
66
+ Apply 1D temporal RoPE to q and k.
67
+
68
+ Args:
69
+ q, k: [B, H, T*M, head_dim]
70
+ t: number of frames
71
+ m: tokens per frame
72
+ """
73
+ # Build temporal positions: each token in frame i gets position i
74
+ # [0,0,...,0, 1,1,...,1, 2,2,...,2, ...] repeated m times per frame
75
+ positions = torch.arange(t, device=q.device).repeat_interleave(m) # [T*M]
76
+
77
+ angles = positions.unsqueeze(-1).float() * self.freqs.to(q.device) # [T*M, half]
78
+ cos = torch.cos(angles).to(q.dtype)
79
+ sin = torch.sin(angles).to(q.dtype)
80
+
81
+ def apply(x):
82
+ x_rope = x[..., :self.rope_dim]
83
+ x_pass = x[..., self.rope_dim:]
84
+ half = self.rope_dim // 2
85
+ x1, x2 = x_rope[..., :half], x_rope[..., half:]
86
+ x_rope = torch.cat([x1 * cos - x2 * sin, x2 * cos + x1 * sin], dim=-1)
87
+ return torch.cat([x_rope, x_pass], dim=-1)
88
+
89
+ return apply(q), apply(k)
90
+
91
+
92
+ # =============================================================================
93
+ # Block-causal temporal attention with 1D RoPE
94
+ # =============================================================================
95
+
96
+ class BlockCausalTemporalAttention(nn.Module):
97
+ def __init__(self, hidden_size, num_heads, qk_norm=False):
98
+ super().__init__()
99
+ self.hidden_size = hidden_size
100
+ self.num_heads = num_heads
101
+ self.head_dim = hidden_size // num_heads
102
+ self.qk_norm = qk_norm
103
+ self.q_proj = nn.Linear(hidden_size, hidden_size)
104
+ self.k_proj = nn.Linear(hidden_size, hidden_size)
105
+ self.v_proj = nn.Linear(hidden_size, hidden_size)
106
+ self.out_proj = nn.Linear(hidden_size, hidden_size)
107
+ if qk_norm:
108
+ self.qk_scale = nn.Parameter(torch.full([num_heads, 1, 1], 10.0))
109
+
110
+ # 1D temporal RoPE
111
+ self.rope = TemporalRoPE1D(self.head_dim)
112
+
113
+ @compile_wrapper
114
+ def forward(self, x):
115
+ from .layers import _qk_norm
116
+ b, t, m, _ = x.shape
117
+ x = x.flatten(1, 2)
118
+ q = self.q_proj(x)
119
+ k = self.k_proj(x)
120
+ v = self.v_proj(x)
121
+ q = q.view(b, -1, self.num_heads, self.head_dim).transpose(1, 2)
122
+ k = k.view(b, -1, self.num_heads, self.head_dim).transpose(1, 2)
123
+ v = v.view(b, -1, self.num_heads, self.head_dim).transpose(1, 2)
124
+
125
+ # Apply 1D temporal RoPE
126
+ q, k = self.rope(q, k, t, m)
127
+
128
+ mask = get_block_causal_mask(t, m, q.device)
129
+ if self.qk_norm:
130
+ q, k = _qk_norm(q, k, self.qk_scale)
131
+ attn = F.scaled_dot_product_attention(q, k, v, attn_mask=mask, scale=1.0)
132
+ else:
133
+ attn = F.scaled_dot_product_attention(q, k, v, attn_mask=mask)
134
+
135
+ x = self.out_proj(attn.transpose(1, 2).flatten(2, 3))
136
+ return x.unflatten(1, (t, m))
137
+
138
+
139
+ # =============================================================================
140
+ # TemporalTransfer (TT1D)
141
+ # =============================================================================
142
+
143
+ class TemporalTransfer(nn.Module):
144
+ def __init__(self, hidden_size, intermediate_size, num_heads, ffn_type="swiglu", qk_norm=False):
145
+ super().__init__()
146
+ self.norm1 = RMSNorm(hidden_size)
147
+ self.attn = BlockCausalTemporalAttention(hidden_size, num_heads, qk_norm=qk_norm)
148
+ self.norm2 = RMSNorm(hidden_size)
149
+ if ffn_type == "gelu":
150
+ self.mlp = GELUMLP(hidden_size, intermediate_size)
151
+ else:
152
+ self.mlp = SwiGLU(hidden_size, intermediate_size)
153
+
154
+ @compile_wrapper
155
+ def forward(self, x):
156
+ x = x + self.attn(self.norm1(x))
157
+ x = x + self.mlp(self.norm2(x))
158
+ return x
159
+
160
+
161
+ if __name__ == "__main__":
162
+ tt_layer = TemporalTransfer(768, 3072, 12)
163
+ x = torch.randn(2, 8, 8, 768)
164
+ y = tt_layer(x)
165
+ print(f"TT1D: {x.shape} -> {y.shape}")
166
+ assert y.shape == x.shape
167
+ print("TT1D smoke test passed!")
tt3d.py ADDED
@@ -0,0 +1,505 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ TemporalTransfer3D: Temporal attention with downsampled spatial context and 3D RoPE.
3
+
4
+ Each frame contributes M motion tokens + S downsampled spatial tokens.
5
+ Block-causal attention across time with 3D RoPE (x, y, t).
6
+ Both motion and spatial tokens receive attention residual.
7
+ Spatial tokens are downsampled via pixel unshuffle + a linear map,
8
+ and upsampled back via a linear map + pixel shuffle for residual add-back.
9
+
10
+ 3D RoPE head_dim split: [x, y, t, unused] with 1/4 each.
11
+ Motion tokens use position (0, 0, t) β€” no spatial, only temporal.
12
+ Spatial tokens use position (x, y, t) β€” full 3D.
13
+ """
14
+
15
+ import math
16
+
17
+ import torch
18
+ import torch.nn as nn
19
+ import torch.nn.functional as F
20
+
21
+ from .utils import compile_wrapper
22
+ from .layers import SwiGLU, GELUMLP, RMSNorm
23
+
24
+
25
+ # =============================================================================
26
+ # Block-causal mask (cached)
27
+ # =============================================================================
28
+
29
+ _mask_cache: dict[tuple, torch.Tensor] = {}
30
+
31
+
32
+ def get_block_causal_mask(t: int, tokens_per_frame: int, device: torch.device) -> torch.Tensor:
33
+ """Bool mask [T*N, T*N] where frame i attends to frames 0..i."""
34
+ key = (t, tokens_per_frame, str(device))
35
+ if key not in _mask_cache:
36
+ causal = torch.tril(torch.ones(t, t, device=device, dtype=torch.bool))
37
+ n = tokens_per_frame
38
+ block = causal[:, :, None, None].expand(-1, -1, n, n)
39
+ mask = block.permute(0, 2, 1, 3).reshape(t * n, t * n)
40
+ _mask_cache[key] = mask
41
+ return _mask_cache[key]
42
+
43
+
44
+ # =============================================================================
45
+ # 3D RoPE
46
+ # =============================================================================
47
+
48
+ def _compute_freqs(dim: int, max_period: float = 10000.0) -> torch.Tensor:
49
+ """Frequency bands for RoPE. Returns [dim//2]."""
50
+ half = dim // 2
51
+ freqs = torch.exp(
52
+ -math.log(max_period) * torch.arange(half, dtype=torch.float32) / half
53
+ )
54
+ return freqs
55
+
56
+
57
+ def _apply_rope_1d(x: torch.Tensor, freqs: torch.Tensor, positions: torch.Tensor) -> torch.Tensor:
58
+ """
59
+ Apply RoPE to a slice of x along the last dim.
60
+
61
+ Args:
62
+ x: [..., dim] β€” the slice of q or k to rotate
63
+ freqs: [dim//2] β€” precomputed frequency bands
64
+ positions: [...] β€” positions for each token
65
+
66
+ Returns:
67
+ [..., dim] rotated tensor
68
+ """
69
+ half = x.shape[-1] // 2
70
+ angles = positions.unsqueeze(-1).float() * freqs.to(x.device)
71
+ cos = torch.cos(angles).to(x.dtype)
72
+ sin = torch.sin(angles).to(x.dtype)
73
+ x1, x2 = x[..., :half], x[..., half:]
74
+ return torch.cat([x1 * cos - x2 * sin, x2 * cos + x1 * sin], dim=-1)
75
+
76
+
77
+ class RoPE3D(nn.Module):
78
+ """
79
+ 3D Rotary Position Embedding for (x, y, t) positions.
80
+
81
+ Head dim split into 4 equal parts: [x_rope, y_rope, t_rope, unused].
82
+ The unused portion passes through unchanged (identity).
83
+ """
84
+
85
+ def __init__(self, head_dim: int, max_period: float = 10000.0):
86
+ super().__init__()
87
+ self.head_dim = head_dim
88
+ self.dim_x = head_dim // 4
89
+ self.dim_y = head_dim // 4
90
+ self.dim_t = head_dim // 4
91
+ self.dim_unused = head_dim - self.dim_x - self.dim_y - self.dim_t
92
+ self.max_period = max_period
93
+
94
+ self.register_buffer("freqs_x", _compute_freqs(self.dim_x, max_period), persistent=False)
95
+ self.register_buffer("freqs_y", _compute_freqs(self.dim_y, max_period), persistent=False)
96
+ self.register_buffer("freqs_t", _compute_freqs(self.dim_t, max_period), persistent=False)
97
+
98
+ def reset_buffers(self) -> None:
99
+ """Recompute the non-persistent buffers (e.g. after transformers' meta-device loading)."""
100
+ self.freqs_x.copy_(_compute_freqs(self.dim_x, self.max_period))
101
+ self.freqs_y.copy_(_compute_freqs(self.dim_y, self.max_period))
102
+ self.freqs_t.copy_(_compute_freqs(self.dim_t, self.max_period))
103
+
104
+ def forward(self, q: torch.Tensor, k: torch.Tensor, positions: torch.Tensor):
105
+ """
106
+ Args:
107
+ q, k: [B, H, S, head_dim]
108
+ positions: [S, 3] β€” (x, y, t) per token
109
+ Returns:
110
+ q_rot, k_rot: same shape
111
+ """
112
+ pos_x = positions[:, 0]
113
+ pos_y = positions[:, 1]
114
+ pos_t = positions[:, 2]
115
+
116
+ def apply(tensor):
117
+ t_x = tensor[..., :self.dim_x]
118
+ t_y = tensor[..., self.dim_x:self.dim_x + self.dim_y]
119
+ t_t = tensor[..., self.dim_x + self.dim_y:self.dim_x + self.dim_y + self.dim_t]
120
+ t_u = tensor[..., self.dim_x + self.dim_y + self.dim_t:]
121
+
122
+ t_x = _apply_rope_1d(t_x, self.freqs_x, pos_x)
123
+ t_y = _apply_rope_1d(t_y, self.freqs_y, pos_y)
124
+ t_t = _apply_rope_1d(t_t, self.freqs_t, pos_t)
125
+
126
+ return torch.cat([t_x, t_y, t_t, t_u], dim=-1)
127
+
128
+ return apply(q), apply(k)
129
+
130
+
131
+ # =============================================================================
132
+ # Pixel unshuffle/shuffle spatial resampling
133
+ # =============================================================================
134
+
135
+ def _hadamard(n: int) -> torch.Tensor:
136
+ h = torch.ones(1, 1, dtype=torch.float64)
137
+ while h.shape[0] < n:
138
+ h = torch.cat([torch.cat([h, h], 1), torch.cat([h, -h], 1)], 0)
139
+ if h.shape[0] != n:
140
+ raise ValueError(f"Walsh-Hadamard needs a power-of-two size, got {n}")
141
+ return h
142
+
143
+
144
+ def _dct(n: int) -> torch.Tensor:
145
+ """Orthonormal DCT-II ``[frequency, index]``."""
146
+ k = torch.arange(n, dtype=torch.float64)[:, None]
147
+ c = torch.arange(n, dtype=torch.float64)[None]
148
+ m = torch.cos(math.pi * (c + 0.5) * k / n) * math.sqrt(2 / n)
149
+ m[0] /= math.sqrt(2)
150
+ return m
151
+
152
+
153
+ def _chirp_signs(n: int, i: int) -> torch.Tensor:
154
+ """A deterministic +-1 pattern per frequency ``i`` (quadratic chirp, never 0)."""
155
+ c = torch.arange(n, dtype=torch.float64)
156
+ s = torch.sign(torch.cos(math.pi * (c * c * (2 * i + 1) + 3 * i * c) / n + 0.25 * i))
157
+ s[s == 0] = 1.0
158
+ return s
159
+
160
+
161
+ def structured_weight(dim: int, factor: int) -> torch.Tensor:
162
+ """The fixed structured down weight ``[D, D*f^2]`` (column index ``c*f^2 + p``,
163
+ the pixel-unshuffle channel order).
164
+
165
+ Over the f^2 positions of a patch, take orthonormal Walsh-Hadamard frequencies
166
+ ``z_i = sum_p h_i[p] x[:, p]``; then ``y = (1/f) sum_i Q_i z_i`` with
167
+ ``Q_i = C^T diag(chi_i) C`` (C the orthonormal DCT-II over channels, chi_i
168
+ deterministic chirp signs): one orthogonal D x D map per position frequency.
169
+ Depends only on ``D`` and ``f``: nothing is stored.
170
+ """
171
+ f2 = factor * factor
172
+ h = _hadamard(f2) / factor # [i, p], orthonormal rows
173
+ c = _dct(dim)
174
+ q = torch.stack([c.T @ (_chirp_signs(dim, i)[:, None] * c) for i in range(f2)])
175
+ w = torch.einsum("ioc,ip->ocp", q, h) / factor # [o, c, p]
176
+ return w.reshape(dim, dim * f2).float()
177
+
178
+
179
+ def _to_unshuffled(x: torch.Tensor, h: int, w: int, f: int) -> torch.Tensor:
180
+ """[B, T, H*W, D] -> [B, T, H'W', D*f*f] (index c*f*f + p)."""
181
+ B, T = x.shape[:2]
182
+ x = x.unflatten(2, (h, w)).permute(0, 1, 4, 2, 3).flatten(0, 1) # [BT, D, H, W]
183
+ x = F.pixel_unshuffle(x, f) # [BT, D*f*f, H', W']
184
+ return x.flatten(2).transpose(1, 2).unflatten(0, (B, T)) # [B, T, H'W', D*f*f]
185
+
186
+
187
+ def _from_unshuffled(x: torch.Tensor, h: int, w: int, f: int) -> torch.Tensor:
188
+ """[B, T, H'W', D*f*f] -> [B, T, H*W, D] (inverse of ``_to_unshuffled``)."""
189
+ B, T = x.shape[:2]
190
+ x = x.transpose(-1, -2).unflatten(-1, (h // f, w // f)).flatten(0, 1) # [BT, D*f*f, H', W']
191
+ x = F.pixel_shuffle(x, f) # [BT, D, H, W]
192
+ return x.unflatten(0, (B, T)).flatten(3, 4).transpose(-1, -2) # [B, T, H*W, D]
193
+
194
+
195
+ class SpatialDownsample(nn.Module):
196
+ """
197
+ [B, T, H*W, D] -> [B, T, (H/f)*(W/f), D]: pixel unshuffle, the fixed dense
198
+ ``structured_weight`` (no parameters, rebuilt from D and f, not saved), then a
199
+ trainable D x D channel mix ``I + mix`` (``mix`` zero at init). Params: DΒ².
200
+ """
201
+
202
+ def __init__(self, hidden_size: int, factor: int):
203
+ super().__init__()
204
+ self.hidden_size = hidden_size
205
+ self.factor = factor
206
+ self.register_buffer("fixed", self._fixed(), persistent=False)
207
+ self.mix = nn.Parameter(torch.zeros(hidden_size, hidden_size))
208
+
209
+ def _fixed(self) -> torch.Tensor:
210
+ return structured_weight(self.hidden_size, self.factor)
211
+
212
+ def reset_parameters(self) -> None:
213
+ """Channel mix back to the identity (after a generic init such as mup_init)."""
214
+ nn.init.zeros_(self.mix)
215
+
216
+ def reset_buffers(self) -> None:
217
+ """Recompute the fixed weight (e.g. after transformers' meta-device loading)."""
218
+ self.fixed.copy_(self._fixed())
219
+
220
+ def forward(self, x: torch.Tensor, h: int, w: int) -> torch.Tensor:
221
+ """
222
+ Args:
223
+ x: [B, T, H*W, D]
224
+ h, w: spatial grid dims
225
+ Returns:
226
+ [B, T, (H//f)*(W//f), D]
227
+ """
228
+ y = F.linear(_to_unshuffled(x, h, w, self.factor), self.fixed) # [B, T, H'W', D]
229
+ return y + F.linear(y, self.mix)
230
+
231
+
232
+ class SpatialUpsample(nn.Module):
233
+ """
234
+ [B, T, (H/f)*(W/f), D] -> [B, T, H*W, D], the counterpart of SpatialDownsample:
235
+ channel mix ``I + mix``, then ``f`` times the transpose of the fixed down weight
236
+ (writes go back in the basis that was read), pixel shuffle. Params: DΒ².
237
+ """
238
+
239
+ def __init__(self, hidden_size: int, factor: int):
240
+ super().__init__()
241
+ self.hidden_size = hidden_size
242
+ self.factor = factor
243
+ self.register_buffer("fixed", self._fixed(), persistent=False)
244
+ self.mix = nn.Parameter(torch.zeros(hidden_size, hidden_size))
245
+
246
+ def _fixed(self) -> torch.Tensor:
247
+ return self.factor * structured_weight(self.hidden_size, self.factor).T.contiguous()
248
+
249
+ def reset_parameters(self) -> None:
250
+ """Channel mix back to the identity (after a generic init such as mup_init)."""
251
+ nn.init.zeros_(self.mix)
252
+
253
+ def reset_buffers(self) -> None:
254
+ """Recompute the fixed weight (e.g. after transformers' meta-device loading)."""
255
+ self.fixed.copy_(self._fixed())
256
+
257
+ def forward(self, x: torch.Tensor, h: int, w: int) -> torch.Tensor:
258
+ """
259
+ Args:
260
+ x: [B, T, H'Β·W', D] where H' = h // f, W' = w // f
261
+ h, w: ORIGINAL spatial grid dims (output size)
262
+ Returns:
263
+ [B, T, H*W, D]
264
+ """
265
+ x = x + F.linear(x, self.mix)
266
+ return _from_unshuffled(F.linear(x, self.fixed), h, w, self.factor)
267
+
268
+
269
+ # =============================================================================
270
+ # TemporalTransfer3D
271
+ # =============================================================================
272
+
273
+ class TemporalTransfer3D(nn.Module):
274
+ """
275
+ Temporal attention with downsampled spatial context and 3D RoPE.
276
+
277
+ Both motion and spatial tokens participate in block-causal attention.
278
+ Spatial tokens are downsampled (pixel unshuffle + linear), attend temporally,
279
+ then upsampled (linear + pixel shuffle) for residual add-back to the spatial stream.
280
+
281
+ Args:
282
+ hidden_size: model dimension
283
+ intermediate_size: FFN hidden dim
284
+ num_heads: attention heads
285
+ downsample_factor: spatial downsample factor (e.g. 4 β†’ 16x16 β†’ 4x4)
286
+ ffn_type: "swiglu" or "gelu"
287
+ qk_norm: use cosine-similarity attention
288
+ """
289
+
290
+ def __init__(
291
+ self,
292
+ hidden_size: int,
293
+ intermediate_size: int,
294
+ num_heads: int,
295
+ downsample_factor: int = 4,
296
+ ffn_type: str = "swiglu",
297
+ qk_norm: bool = False,
298
+ ):
299
+ super().__init__()
300
+ self.hidden_size = hidden_size
301
+ self.num_heads = num_heads
302
+ self.head_dim = hidden_size // num_heads
303
+ self.downsample_factor = downsample_factor
304
+ self.qk_norm = qk_norm
305
+
306
+ # Spatial resampling: fixed structured weight + D x D channel mix
307
+ self.spatial_down = SpatialDownsample(hidden_size, downsample_factor)
308
+ self.spatial_up = SpatialUpsample(hidden_size, downsample_factor)
309
+ # Zero-init output projection for spatial add-back (identity at init)
310
+ self.spatial_out_proj = nn.Linear(hidden_size, hidden_size, bias=False)
311
+ nn.init.zeros_(self.spatial_out_proj.weight)
312
+
313
+ # Pre-norm
314
+ self.norm1 = RMSNorm(hidden_size)
315
+ self.norm2 = RMSNorm(hidden_size)
316
+
317
+ # Attention projections
318
+ self.q_proj = nn.Linear(hidden_size, hidden_size)
319
+ self.k_proj = nn.Linear(hidden_size, hidden_size)
320
+ self.v_proj = nn.Linear(hidden_size, hidden_size)
321
+ self.out_proj = nn.Linear(hidden_size, hidden_size)
322
+
323
+ if qk_norm:
324
+ self.qk_scale = nn.Parameter(torch.full([num_heads, 1, 1], 10.0))
325
+
326
+ # 3D RoPE
327
+ self.rope = RoPE3D(self.head_dim)
328
+
329
+ # FFN
330
+ if ffn_type == "gelu":
331
+ self.mlp = GELUMLP(hidden_size, intermediate_size)
332
+ else:
333
+ self.mlp = SwiGLU(hidden_size, intermediate_size)
334
+
335
+ # Position cache
336
+ self._pos_cache: dict[tuple, torch.Tensor] = {}
337
+
338
+ def _build_positions(
339
+ self, M: int, ds_h: int, ds_w: int, T: int, device: torch.device
340
+ ) -> torch.Tensor:
341
+ """
342
+ Build 3D positions for all tokens across all frames.
343
+
344
+ Per-frame layout: [MT_0..MT_{M-1}, DS_(0,0)..DS_(ds_w-1,ds_h-1)]
345
+ Motion: (0, 0, t) Spatial: (x, y, t)
346
+
347
+ Returns: [T * (M + ds_h*ds_w), 3]
348
+ """
349
+ key = (M, ds_h, ds_w, T, str(device))
350
+ if key in self._pos_cache:
351
+ return self._pos_cache[key]
352
+
353
+ tokens_per_frame = M + ds_h * ds_w
354
+ positions = torch.zeros(T, tokens_per_frame, 3, device=device)
355
+
356
+ for t in range(T):
357
+ # Motion tokens: (0, 0, t)
358
+ positions[t, :M, 2] = t
359
+ # Spatial tokens: (x, y, t)
360
+ idx = M
361
+ for row in range(ds_h):
362
+ for col in range(ds_w):
363
+ positions[t, idx, 0] = col
364
+ positions[t, idx, 1] = row
365
+ positions[t, idx, 2] = t
366
+ idx += 1
367
+
368
+ positions = positions.reshape(T * tokens_per_frame, 3)
369
+ self._pos_cache[key] = positions
370
+ return positions
371
+
372
+ @compile_wrapper
373
+ def _attention(self, x: torch.Tensor, positions: torch.Tensor, mask: torch.Tensor) -> torch.Tensor:
374
+ """
375
+ Block-causal attention with 3D RoPE.
376
+
377
+ Args:
378
+ x: [B, S, D] β€” normed, flattened (T * tokens_per_frame)
379
+ positions: [S, 3] β€” (x, y, t) per token
380
+ mask: [S, S] β€” block-causal bool mask
381
+ """
382
+ from .layers import _qk_norm
383
+
384
+ B, S, D = x.shape
385
+ q = self.q_proj(x).view(B, S, self.num_heads, self.head_dim).transpose(1, 2)
386
+ k = self.k_proj(x).view(B, S, self.num_heads, self.head_dim).transpose(1, 2)
387
+ v = self.v_proj(x).view(B, S, self.num_heads, self.head_dim).transpose(1, 2)
388
+
389
+ # 3D RoPE
390
+ q, k = self.rope(q, k, positions)
391
+
392
+ # QK-norm (cosine-sim attention)
393
+ if self.qk_norm:
394
+ q, k = _qk_norm(q, k, self.qk_scale)
395
+ attn = F.scaled_dot_product_attention(q, k, v, attn_mask=mask, scale=1.0)
396
+ else:
397
+ attn = F.scaled_dot_product_attention(q, k, v, attn_mask=mask)
398
+
399
+ return self.out_proj(attn.transpose(1, 2).reshape(B, S, D))
400
+
401
+ def forward(
402
+ self,
403
+ motion_tokens: torch.Tensor,
404
+ spatial_tokens: torch.Tensor,
405
+ spatial_h: int,
406
+ spatial_w: int,
407
+ ) -> tuple[torch.Tensor, torch.Tensor]:
408
+ """
409
+ Args:
410
+ motion_tokens: [B, T, M, D] β€” motion tokens from DINOv3 stream
411
+ spatial_tokens: [B, T, H*W, D] β€” spatial tokens from DINOv3 stream
412
+ spatial_h, spatial_w: spatial grid dimensions (e.g. 16, 16)
413
+
414
+ Returns:
415
+ motion_tokens: [B, T, M, D] β€” enriched motion tokens
416
+ spatial_tokens: [B, T, H*W, D] β€” spatial tokens with temporal residual
417
+ """
418
+ B, T, M, D = motion_tokens.shape
419
+ f = self.downsample_factor
420
+ ds_h, ds_w = spatial_h // f, spatial_w // f
421
+ tokens_per_frame = M + ds_h * ds_w
422
+
423
+ # 1. Downsample spatial: pixel unshuffle + linear
424
+ ds_spatial = self.spatial_down(spatial_tokens, spatial_h, spatial_w)
425
+ # ds_spatial: [B, T, ds_h*ds_w, D]
426
+
427
+ # 2. Concat motion + downsampled spatial per frame
428
+ x = torch.cat([motion_tokens, ds_spatial], dim=2) # [B, T, M+S_down, D]
429
+
430
+ # 3. Pre-norm + flatten temporal dim
431
+ x_normed = self.norm1(x).flatten(1, 2) # [B, T*(M+S_down), D]
432
+
433
+ # 4. Positions and mask
434
+ positions = self._build_positions(M, ds_h, ds_w, T, x.device)
435
+ mask = get_block_causal_mask(T, tokens_per_frame, x.device)
436
+
437
+ # 5. Block-causal attention with 3D RoPE
438
+ attn_out = self._attention(x_normed, positions, mask)
439
+ attn_out = attn_out.unflatten(1, (T, tokens_per_frame))
440
+
441
+ # 6. Attention residual on ALL tokens (motion + spatial)
442
+ x = x + attn_out
443
+
444
+ # 7. FFN on ALL tokens (motion + spatial)
445
+ x = x + self.mlp(self.norm2(x))
446
+
447
+ # 8. Split back into motion and spatial
448
+ motion_tokens = x[:, :, :M]
449
+ spatial_part = x[:, :, M:]
450
+
451
+ # 9. Spatial add-back: zero-init proj β†’ upsample β†’ residual
452
+ # spatial_out_proj is zero-init, so initially this is a no-op
453
+ spatial_residual = self.spatial_up(
454
+ self.spatial_out_proj(spatial_part), spatial_h, spatial_w
455
+ )
456
+ spatial_tokens = spatial_tokens + spatial_residual
457
+
458
+ return motion_tokens, spatial_tokens
459
+
460
+
461
+ # =============================================================================
462
+ # Smoke test
463
+ # =============================================================================
464
+
465
+ if __name__ == "__main__":
466
+ B, T, M, D = 2, 8, 8, 768
467
+ H, W = 16, 16
468
+
469
+ layer = TemporalTransfer3D(
470
+ hidden_size=D,
471
+ intermediate_size=D * 4,
472
+ num_heads=12,
473
+ downsample_factor=4,
474
+ )
475
+
476
+ motion = torch.randn(B, T, M, D)
477
+ spatial = torch.randn(B, T, H * W, D)
478
+
479
+ motion_out, spatial_out = layer(motion, spatial, H, W)
480
+ print(f"Input: motion={motion.shape}, spatial={spatial.shape}")
481
+ print(f"Output: motion={motion_out.shape}, spatial={spatial_out.shape}")
482
+ assert motion_out.shape == (B, T, M, D)
483
+ assert spatial_out.shape == (B, T, H * W, D)
484
+
485
+ # Verify spatial add-back is zero-init (residual starts as no-op)
486
+ diff = (spatial_out - spatial).abs().max().item()
487
+ print(f"Spatial diff at init (should be ~0 from zero-init out proj): {diff:.6f}")
488
+
489
+ # Check gradient flows through spatial
490
+ motion.requires_grad_(True)
491
+ spatial.requires_grad_(True)
492
+ m_out, s_out = layer(motion, spatial, H, W)
493
+ loss = m_out.sum() + s_out.sum()
494
+ loss.backward()
495
+ print(f"Gradient on spatial: {spatial.grad is not None}, norm={spatial.grad.norm():.4f}")
496
+ print(f"Gradient on motion: {motion.grad is not None}, norm={motion.grad.norm():.4f}")
497
+
498
+ # Different downsample factors
499
+ for ds in [1, 2, 4, 8]:
500
+ l = TemporalTransfer3D(D, D * 4, 12, downsample_factor=ds)
501
+ m_o, s_o = l(motion.detach(), spatial.detach(), H, W)
502
+ ds_tokens = (H // ds) * (W // ds)
503
+ print(f" ds={ds}: {ds_tokens} spatial tokens/frame, total={M + ds_tokens}/frame")
504
+
505
+ print("\nSmoke test passed!")
utils.py ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import importlib
2
+ import torch
3
+ from . import env
4
+ from .env import TORCH_COMPILE as _ # noqa: F401 (bundles env.py)
5
+
6
+
7
+ def import_class(cls_string):
8
+ if not isinstance(cls_string, str):
9
+ return cls_string
10
+ module, cls = cls_string.rsplit(".", 1)
11
+ module = importlib.import_module(module)
12
+ return getattr(module, cls)
13
+
14
+
15
+ def compile_wrapper(func):
16
+ """Decorator: compile the function once with torch.compile when TORCH_COMPILE=True."""
17
+ _compiled = None
18
+
19
+ def wrapper(*args, **kwargs):
20
+ nonlocal _compiled
21
+ if env.TORCH_COMPILE:
22
+ if _compiled is None:
23
+ _compiled = torch.compile(func, **env.COMPILE_KWARG)
24
+ return _compiled(*args, **kwargs)
25
+ else:
26
+ return func(*args, **kwargs)
27
+
28
+ return wrapper