-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmodel.py
More file actions
3007 lines (2438 loc) · 112 KB
/
Copy pathmodel.py
File metadata and controls
3007 lines (2438 loc) · 112 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
V-JEPA-Q: Quaternion-Enhanced Video Joint-Embedding Predictive Architecture
with Continuous Spectral Autoencoders and Topological World Modeling.
Lie Algebra Trick (exp/log): Converts quaternion multiplications into vector
additions in the tangent space (so(3)), enabling efficient message passing
on the torus graph via Baker-Campbell-Hausdorff approximation.
Architecture:
- Quaternion algebra with exp/log maps for SO(3)/SU(2) group
- Complex spectral kernels in Fourier domain (GOE/GUE transition)
- 2D Torus brain: 4 angular x 2 radial = 8 nodes, fully periodic
- V-JEPA asymmetric masking with cosine-similarity prediction
- Phase diagram tracking: Berry phase, delta, kappa, T_eff, GOE/GUE
- GQA attention with Rotary Position Embeddings
- Topological MoE with load-balancing auxiliary loss
"""
import argparse
import json
import logging
import math
import os
import signal
import sys
import time
import unittest
from collections import deque
from dataclasses import dataclass, fields as dc_fields
from pathlib import Path
from typing import Any, Dict, List, Optional, Tuple, Union
import numpy as np
import torch
import torch.nn as nn
import safetensors.torch
import torch.nn.functional as F
from torch.utils.checkpoint import checkpoint as grad_ckpt
from src.quaternion_ops import QuaternionOps, QuaternionLinear
# ============================================================================
# CONFIGURATION
# ============================================================================
@dataclass
class VJEPAQConfig:
"""Central configuration for V-JEPA-Q model and training.
All hyperparameters defined here. No hardcoded values or magic numbers
exist outside this class. Computed fields in __post_init__.
"""
NUM_FRAMES: int = 16
PATCH_SIZE: Tuple[int, int] = (16, 16)
IMAGE_SIZE: Tuple[int, int] = (224, 224)
IN_CHANNELS: int = 3
D_MODEL: int = 384
N_HEADS: int = 6
N_KV_HEADS: int = 0
N_ENCODER_LAYERS: int = 12
N_PREDICTOR_LAYERS: int = 12
DROPOUT: float = 0.1
SPECTRAL_LATENT_RATIO: float = 0.5
SPECTRAL_KERNEL_INIT_SCALE: float = 0.02
NUM_SPECTRAL_LAYERS: int = 2
AE_RECON_WEIGHT: float = 0.01
TEMPORAL_FFT_BINS: int = 32
TORUS_RADIAL_BINS: int = 2
TORUS_ANGULAR_BINS: int = 4
TORUS_GRID_SIZE: int = 8
TORUS_SOFT_ASSIGN_TEMPERATURE: float = 0.3
TORUS_LIE_APPROX: bool = True
MOE_ENABLED: bool = True
N_EXPERTS: int = 4
MOE_TOP_K: int = 2
MOE_AUX_LOSS_WEIGHT: float = 0.01
ENCODER_MASK_RATIO: float = 0.9
PREDICTOR_MASK_RATIO: float = 0.75
MASK_PATCH_SIZE: Tuple[int, int] = (4, 4)
PREDICT_FRAMES: int = 4
CONTEXT_FRAMES: int = 12
BATCH_SIZE: int = 16
GRAD_ACCUM_STEPS: int = 1
LEARNING_RATE: float = 1e-4
WEIGHT_DECAY: float = 0.05
WARMUP_RATIO: float = 0.05
GRADIENT_CLIP_NORM: float = 1.0
GRADIENT_CHECKPOINTING: bool = False
USE_AMP: bool = False
NUM_WORKERS: int = 4
SAVE_EVERY_STEPS: int = 200
TORCH_COMPILE: bool = False
DECODER_CHANNELS: int = 64
DECODER_N_LAYERS: int = 3
DECODER_LR: float = 1e-4
DECODER_WEIGHT_DECAY: float = 0.05
DECODER_TEMPORAL_LOSS_WEIGHT: float = 1.0
DECODER_GRADIENT_LOSS_WEIGHT: float = 0.1
DECODER_LOAD_PATH: str = ''
TRACK_PHASE: bool = True
GRASS_TRACK_EVERY: int = 200
GRASS_MAX_RANK: int = 16
GRASS_ELBOW_RATIO: float = 0.05
DELTA_CRYSTAL_THRESHOLD: float = 0.1
KAPPA_CRYSTAL_THRESHOLD: float = 1.5
TEMP_CRYSTAL_THRESHOLD: float = 1e-9
GOE_GUE_TARGET: str = 'gue'
IMAGINARY_RATIO_TARGET: float = 0.3
DATA_MODE: str = 'synthetic'
SYNTHETIC_NUM_OBJECTS: int = 3
SYNTHETIC_CANVAS_SIZE: int = 64
SYNTHETIC_NUM_SAMPLES: int = 10000
UCF101_ROOT: str = './data/ucf101'
UCF101_ANNOTATION_DIR: str = ''
UCF101_FRAMES_PER_CLIP: int = 16
UCF101_OUTPUT_SIZE: Tuple[int, int] = (64, 64)
UCF101_RESIZE: bool = True
UCF101_DOWNLOAD_ANNOTATIONS: bool = True
UCF101_SPLIT_INDEX: int = 1
DEVICE: str = ''
RANDOM_SEED: int = 42
CHECKPOINT_DIR: str = 'checkpoints_vjepa_q'
LOG_DIR: str = 'logs_vjepa_q'
def __post_init__(self) -> None:
if not self.DEVICE:
self.DEVICE = 'cuda' if torch.cuda.is_available() else 'cpu'
assert self.D_MODEL % 4 == 0, "D_MODEL must be divisible by 4"
assert self.D_MODEL % self.N_HEADS == 0, "D_MODEL must be divisible by N_HEADS"
assert 0.0 < self.ENCODER_MASK_RATIO < 1.0
assert 0.0 < self.PREDICTOR_MASK_RATIO < 1.0
assert self.NUM_FRAMES > 1
assert self.BATCH_SIZE > 0
assert self.GRADIENT_CLIP_NORM > 0.0
assert self.TORUS_SOFT_ASSIGN_TEMPERATURE > 0.0
assert self.DATA_MODE in ('synthetic', 'video_dir', 'ucf101')
assert self.GOE_GUE_TARGET in ('goe', 'gue')
assert self.CONTEXT_FRAMES + self.PREDICT_FRAMES <= self.NUM_FRAMES, (
f"NUM_FRAMES ({self.NUM_FRAMES}) must be >= CONTEXT_FRAMES + PREDICT_FRAMES "
f"({self.CONTEXT_FRAMES + self.PREDICT_FRAMES})"
)
self.D_QUAT: int = self.D_MODEL // 4
if self.N_KV_HEADS <= 0:
kv = max(1, self.N_HEADS // 4)
while self.N_HEADS % kv != 0:
kv -= 1
self.N_KV_HEADS = kv
elif self.N_KV_HEADS == -1:
self.N_KV_HEADS = self.N_HEADS
self.GQA_GROUPS: int = self.N_HEADS // self.N_KV_HEADS
self.D_HEAD: int = self.D_MODEL // self.N_HEADS
self.PATCH_H: int = self.IMAGE_SIZE[0] // self.PATCH_SIZE[0]
self.PATCH_W: int = self.IMAGE_SIZE[1] // self.PATCH_SIZE[1]
assert self.PATCH_H > 0 and self.PATCH_W > 0
self.NUM_PATCHES_PER_FRAME: int = self.PATCH_H * self.PATCH_W
self.NUM_PATCHES: int = self.NUM_FRAMES * self.NUM_PATCHES_PER_FRAME
self.PATCH_DIM: int = self.IN_CHANNELS * self.PATCH_SIZE[0] * self.PATCH_SIZE[1]
self.SPECTRAL_LATENT_DIM: int = max(16, int(self.D_MODEL * self.SPECTRAL_LATENT_RATIO))
self.N_TORUS_NODES: int = self.TORUS_RADIAL_BINS * self.TORUS_ANGULAR_BINS
self.TORUS_GRID_SIZE = self.N_TORUS_NODES
def to_dict(self) -> Dict[str, Any]:
valid_keys = {f.name for f in dc_fields(VJEPAQConfig)}
return {k: v for k, v in self.__dict__.items() if k in valid_keys and not k.startswith('_')}
def to_json(self) -> str:
d = self.to_dict()
for key in ('IMAGE_SIZE', 'PATCH_SIZE', 'MASK_PATCH_SIZE', 'UCF101_OUTPUT_SIZE'):
if key in d:
d[key] = list(d[key])
return json.dumps(d, indent=2, default=str)
@classmethod
def from_json(cls, path_or_str: str) -> 'VJEPAQConfig':
p = Path(path_or_str)
if len(path_or_str) < 256 and p.exists():
with open(p) as f:
d = json.load(f)
else:
d = json.loads(path_or_str)
for key in ('IMAGE_SIZE', 'PATCH_SIZE', 'MASK_PATCH_SIZE', 'UCF101_OUTPUT_SIZE'):
if key in d:
d[key] = tuple(d[key])
valid_keys = {f.name for f in dc_fields(cls)}
d = {k: v for k, v in d.items() if k in valid_keys}
return cls(**d)
@staticmethod
def auto_batch_size(config: 'VJEPAQConfig', min_batch: int = 1, max_batch: int = 512) -> int:
dev = config.DEVICE
if 'cuda' not in dev:
return min_batch
lo, hi = min_batch, max_batch
best = min_batch
while lo <= hi:
mid = (lo + hi) // 2
cfg = VJEPAQConfig(**{**config.to_dict(), 'BATCH_SIZE': mid, 'DEVICE': dev})
try:
model = VJEPAQ(cfg).to(dev)
video = torch.randn(mid, cfg.NUM_FRAMES, 3, *cfg.IMAGE_SIZE, device=dev)
with torch.amp.autocast(dev.split(':')[0], enabled=cfg.USE_AMP):
_ = model(video)
del model, video
torch.cuda.empty_cache()
best = mid
lo = mid + 1
except (RuntimeError, torch.cuda.OutOfMemoryError):
hi = mid - 1
torch.cuda.empty_cache()
return best
# ============================================================================
# UTILITY
# ============================================================================
def _setup_logger(name: str, level: str = 'INFO') -> logging.Logger:
logger = logging.getLogger(name)
logger.setLevel(getattr(logging, level.upper(), logging.INFO))
if not logger.handlers:
handler = logging.StreamHandler(sys.stdout)
handler.setFormatter(logging.Formatter(
'%(asctime)s %(name)s %(levelname)s %(message)s'))
logger.addHandler(handler)
return logger
def _set_seed(seed: int, device: str) -> None:
torch.manual_seed(seed)
np.random.seed(seed)
if 'cuda' in device and torch.cuda.is_available():
torch.cuda.manual_seed_all(seed)
def _count_parameters(module: nn.Module) -> int:
return sum(p.numel() for p in module.parameters() if p.requires_grad)
# ============================================================================
# SPECTRAL LAYERS
# ============================================================================
class ComplexSpectralLayer(nn.Module):
"""Spectral convolution with tuneable real/imaginary kernel ratio.
Operates in 2D Fourier domain: P(k) = W(k) * X(k) with channel mixing
via einsum. Real part: conservative dynamics. Imaginary part: dissipative.
Tracks GOE -> GUE transition via imaginary_ratio.
"""
def __init__(
self,
channels: int,
grid_h: int,
grid_w: int,
imaginary_ratio: float = 0.3,
init_scale: float = 0.02,
):
super().__init__()
self.channels = channels
self.grid_h = grid_h
self.grid_w = grid_w
self.imaginary_ratio = imaginary_ratio
freq_h = grid_h
freq_w = grid_w // 2 + 1
self.kernel_real = nn.Parameter(
torch.randn(channels, channels, freq_h, freq_w) * init_scale)
self.kernel_imag = nn.Parameter(
torch.randn(channels, channels, freq_h, freq_w) * init_scale * imaginary_ratio)
self._imag_ratio_history = deque(maxlen=100)
def set_imaginary_ratio(self, ratio: float) -> None:
old = self.imaginary_ratio
self.imaginary_ratio = ratio
if old > 1e-8:
with torch.no_grad():
self.kernel_imag.data *= ratio / max(old, 1e-8)
def get_effective_imaginary_ratio(self) -> float:
real_norm = self.kernel_real.data.norm().item()
imag_norm = self.kernel_imag.data.norm().item()
if real_norm < 1e-8:
return self.imaginary_ratio
ratio = imag_norm / real_norm
self._imag_ratio_history.append(ratio)
return ratio
def get_spectral_operator(self) -> torch.Tensor:
kr = self.kernel_real[:, :, 0, 0]
ki = self.kernel_imag[:, :, 0, 0]
kr_sym = (kr + kr.T) / 2
ki_asym = (ki - ki.T) / 2
return torch.complex(kr_sym, ki_asym * self.get_effective_imaginary_ratio())
def forward(self, x: torch.Tensor) -> torch.Tensor:
x_fft = torch.fft.rfft2(x, s=(self.grid_h, self.grid_w))
B, C, freq_h, freq_w = x_fft.shape
kr = self.kernel_real
ki = self.kernel_imag
if kr.shape[2:] != (freq_h, freq_w):
kr = F.interpolate(
kr.mean(dim=0).unsqueeze(0).unsqueeze(0),
size=(freq_h, freq_w), mode='bilinear', align_corners=False,
).squeeze(0).unsqueeze(0)
ki = F.interpolate(
ki.mean(dim=0).unsqueeze(0).unsqueeze(0),
size=(freq_h, freq_w), mode='bilinear', align_corners=False,
).squeeze(0).unsqueeze(0)
K = torch.complex(kr, ki)
out_fft = torch.einsum('cihw,bihw->bchw', K, x_fft)
return torch.fft.irfft2(out_fft, s=(self.grid_h, self.grid_w))
class QuaternionSpectralLayer(nn.Module):
"""Full quaternion spectral convolution in Fourier domain.
Each quaternion component (w, x, y, z) gets a complex kernel.
Combined via Hamilton product in frequency space using Gauss's trick
(3 real MUL instead of 4 for complex multiply).
"""
def __init__(
self,
in_q: int,
out_q: int,
grid_h: int,
grid_w: int,
init_scale: float = 0.02,
):
super().__init__()
self.in_q = in_q
self.out_q = out_q
self.grid_h = grid_h
self.grid_w = grid_w
freq_h = grid_h
freq_w = grid_w // 2 + 1
for c in ('w', 'x', 'y', 'z'):
self.register_parameter(
f'kr_{c}',
nn.Parameter(torch.randn(in_q, out_q, freq_h, freq_w) * init_scale),
)
self.register_parameter(
f'ki_{c}',
nn.Parameter(torch.randn(in_q, out_q, freq_h, freq_w) * init_scale),
)
def _kernel(self, c: str) -> torch.Tensor:
return torch.complex(getattr(self, f'kr_{c}'), getattr(self, f'ki_{c}'))
@staticmethod
def _gauss_contract(W: torch.Tensor, X: torch.Tensor) -> torch.Tensor:
Wr, Wi = W.real, W.imag
Xr, Xi = X.real, X.imag
m1 = torch.einsum("iohw,bihw->bohw", Wr, Xr)
m2 = torch.einsum("iohw,bihw->bohw", Wi, Xi)
m3 = torch.einsum("iohw,bihw->bohw", Wr + Wi, Xr + Xi)
return torch.complex(m1 - m2, m3 - m1 - m2)
def forward(self, x: torch.Tensor) -> torch.Tensor:
q = self.in_q
xw, xx, xy, xz = x[:, :q], x[:, q:2 * q], x[:, 2 * q:3 * q], x[:, 3 * q:]
Xw = torch.fft.rfft2(xw, s=(self.grid_h, self.grid_w))
Xx = torch.fft.rfft2(xx, s=(self.grid_h, self.grid_w))
Xy = torch.fft.rfft2(xy, s=(self.grid_h, self.grid_w))
Xz = torch.fft.rfft2(xz, s=(self.grid_h, self.grid_w))
Ww, Wx, Wy, Wz = self._kernel('w'), self._kernel('x'), self._kernel('y'), self._kernel('z')
C = {}
for wc, W in (('w', Ww), ('x', Wx), ('y', Wy), ('z', Wz)):
for xc, X in (('w', Xw), ('x', Xx), ('y', Xy), ('z', Xz)):
C[(wc, xc)] = self._gauss_contract(W, X)
Pw = C[('w', 'w')] - C[('x', 'x')] - C[('y', 'y')] - C[('z', 'z')]
Px = C[('w', 'x')] + C[('x', 'w')] + C[('y', 'z')] - C[('z', 'y')]
Py = C[('w', 'y')] - C[('x', 'z')] + C[('y', 'w')] + C[('z', 'x')]
Pz = C[('w', 'z')] + C[('x', 'y')] - C[('y', 'x')] + C[('z', 'w')]
ow = torch.fft.irfft2(Pw, s=(self.grid_h, self.grid_w))
ox = torch.fft.irfft2(Px, s=(self.grid_h, self.grid_w))
oy = torch.fft.irfft2(Py, s=(self.grid_h, self.grid_w))
oz = torch.fft.irfft2(Pz, s=(self.grid_h, self.grid_w))
return torch.cat([ow, ox, oy, oz], dim=1)
# ============================================================================
# SPECTRAL AUTOENCODER
# ============================================================================
class SpatiotemporalSpectralAE(nn.Module):
"""Two-level spectral autoencoder: temporal FFT + spatial quaternion spectral."""
def __init__(self, config: VJEPAQConfig):
super().__init__()
self.config = config
d = config.D_MODEL
d_lat = config.SPECTRAL_LATENT_DIM
d_q = config.D_QUAT
self.temporal_fft_bins = config.TEMPORAL_FFT_BINS
self.temporal_kr = nn.Parameter(torch.randn(d, config.TEMPORAL_FFT_BINS) * 0.02)
self.temporal_ki = nn.Parameter(torch.randn(d, config.TEMPORAL_FFT_BINS) * 0.02)
self.temporal_enc = QuaternionLinear(d, d_lat)
self.temporal_dec = QuaternionLinear(d_lat, d)
r, a = config.TORUS_RADIAL_BINS, config.TORUS_ANGULAR_BINS
self.spatial_spectral = nn.ModuleList([
QuaternionSpectralLayer(d_q, d_q, r, a, config.SPECTRAL_KERNEL_INIT_SCALE)
for _ in range(config.NUM_SPECTRAL_LAYERS)
])
self.act = nn.GELU()
def _temporal_filter(self, x: torch.Tensor, kr: torch.Tensor, ki: torch.Tensor) -> torch.Tensor:
X = torch.fft.rfft(x.transpose(1, 2), dim=-1)
K = torch.complex(kr, ki)
filtered = X * K.unsqueeze(0)
return torch.fft.irfft(filtered, n=x.shape[1], dim=-1).transpose(1, 2)
def encode_temporal(self, x: torch.Tensor) -> torch.Tensor:
x_filt = self.act(self._temporal_filter(x, self.temporal_kr, self.temporal_ki))
return self.temporal_enc(x_filt)
def decode_temporal(self, z: torch.Tensor) -> torch.Tensor:
x = self.temporal_dec(z)
return self._temporal_filter(x, self.temporal_kr.conj(), self.temporal_ki.conj())
def forward(self, x: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
z = self.encode_temporal(x)
recon = self.decode_temporal(z)
recon_loss = F.mse_loss(recon, x.detach())
return z, recon_loss
# ============================================================================
# VIDEO PATCH EMBEDDING
# ============================================================================
class VideoPatchEmbedding(nn.Module):
"""Convert video to quaternion-encoded patch embeddings with motion cues.
Extracts spatial patches and temporal derivative, then projects to
D_MODEL-dimensional quaternion space with position encodings.
"""
def __init__(self, config: VJEPAQConfig):
super().__init__()
self.config = config
patch_dim = config.PATCH_DIM
motion_dim = config.IN_CHANNELS
self.patch_to_quat = nn.Linear(patch_dim + motion_dim, config.D_MODEL * 4)
self.quat_proj = QuaternionLinear(config.D_MODEL * 4, config.D_MODEL)
self.temporal_pos_embed = nn.Parameter(
torch.randn(1, config.NUM_FRAMES, config.D_MODEL) * 0.02)
self.spatial_pos_embed = nn.Parameter(
torch.randn(1, config.NUM_PATCHES_PER_FRAME, config.D_MODEL) * 0.02)
self.norm = nn.LayerNorm(config.D_MODEL)
@staticmethod
def _compute_temporal_derivative(video: torch.Tensor) -> torch.Tensor:
if video.shape[1] < 2:
return torch.zeros_like(video[:, :1])
return video[:, 1:] - video[:, :-1]
def forward(self, video: torch.Tensor) -> torch.Tensor:
B, T, C, H, W = video.shape
cfg = self.config
patches = video.reshape(
B, T, C,
H // cfg.PATCH_SIZE[0], cfg.PATCH_SIZE[0],
W // cfg.PATCH_SIZE[1], cfg.PATCH_SIZE[1],
)
patches = patches.permute(0, 1, 3, 5, 2, 4, 6).contiguous()
patches = patches.reshape(B, T * cfg.NUM_PATCHES_PER_FRAME, -1)
temp_deriv = self._compute_temporal_derivative(video)
if T <= 1:
motion_features = torch.zeros(
B, T * cfg.NUM_PATCHES_PER_FRAME, cfg.IN_CHANNELS,
device=video.device, dtype=video.dtype)
else:
temp_deriv = F.interpolate(
temp_deriv.reshape(B * (T - 1), C, H, W),
size=(cfg.PATCH_H, cfg.PATCH_W),
mode='area',
).reshape(B, T - 1, cfg.NUM_PATCHES_PER_FRAME, cfg.IN_CHANNELS)
temp_deriv = F.pad(temp_deriv, (0, 0, 0, 0, 0, 1), value=0.0)
motion_features = temp_deriv.reshape(
B, T * cfg.NUM_PATCHES_PER_FRAME, cfg.IN_CHANNELS)
combined = torch.cat([patches, motion_features], dim=-1)
quat_features = self.quat_proj(self.patch_to_quat(combined))
temporal_pe = self.temporal_pos_embed[:, :T, :].repeat_interleave(
cfg.NUM_PATCHES_PER_FRAME, dim=1)
spatial_pe = self.spatial_pos_embed.unsqueeze(1).expand(B, T, -1, -1).reshape(
B, T * cfg.NUM_PATCHES_PER_FRAME, cfg.D_MODEL)
embeddings = self.norm(quat_features + temporal_pe + spatial_pe)
return embeddings
# ============================================================================
# MASKING
# ============================================================================
class VJEPAMasker:
"""Generate asymmetric encoder/predictor masks for V-JEPA training."""
def __init__(self, config: VJEPAQConfig):
self.config = config
self.logger = _setup_logger("VJEPAMasker")
@staticmethod
def _generate_block_mask(
h: int,
w: int,
mask_ratio: float,
block_size: Tuple[int, int],
device: torch.device,
) -> torch.Tensor:
bh, bw = block_size
grid_h = math.ceil(h / bh)
grid_w = math.ceil(w / bw)
mask_blocks = torch.rand(grid_h, grid_w, device=device) > mask_ratio
mask = mask_blocks.repeat_interleave(bh, dim=0).repeat_interleave(bw, dim=1)
return mask[:h, :w]
def generate_masks(self, batch_size: int, device: torch.device) -> Dict[str, torch.Tensor]:
cfg = self.config
T = cfg.NUM_FRAMES
N = cfg.NUM_PATCHES_PER_FRAME
total = T * N
bh, bw = cfg.MASK_PATCH_SIZE
grid_h = math.ceil(cfg.PATCH_H / bh)
grid_w = math.ceil(cfg.PATCH_W / bw)
mask_blocks = torch.rand(batch_size, T, grid_h, grid_w, device=device) > cfg.ENCODER_MASK_RATIO
encoder_full = mask_blocks.repeat_interleave(bh, dim=2).repeat_interleave(bw, dim=3)
encoder_mask = encoder_full[:, :, :cfg.PATCH_H, :cfg.PATCH_W].reshape(batch_size, total).to(torch.bool)
predictor_mask = torch.zeros(batch_size, total, dtype=torch.bool, device=device)
masked_positions = ~encoder_mask
for b in range(batch_size):
masked_idx = masked_positions[b].nonzero(as_tuple=True)[0]
num_to_predict = int(masked_idx.shape[0] * cfg.PREDICTOR_MASK_RATIO)
if num_to_predict > 0:
perm = torch.randperm(masked_idx.shape[0], device=device)[:num_to_predict]
predictor_mask[b, masked_idx[perm]] = True
return {
'encoder_mask': encoder_mask,
'predictor_mask': predictor_mask,
'visible_mask': encoder_mask,
'masked_not_predicted': encoder_mask.logical_not().logical_and(
predictor_mask.logical_not()),
}
# ============================================================================
# POSITIONAL ENCODING AND NORMALISATION
# ============================================================================
class RotaryEmbedding(nn.Module):
"""Rotary Position Embeddings (RoPE) for spatiotemporal attention."""
def __init__(self, d_head: int, max_seq_len: int = 4096, base: int = 10000):
super().__init__()
inv_freq = 1.0 / (base ** (torch.arange(0, d_head, 2, dtype=torch.float) / d_head))
self.register_buffer('inv_freq', inv_freq)
self._build_cache(max_seq_len)
def _build_cache(self, seq_len: int) -> None:
t = torch.arange(seq_len, device=self.inv_freq.device, dtype=torch.float)
freqs = torch.outer(t, self.inv_freq)
emb = torch.cat([freqs, freqs], dim=-1)
self.register_buffer('cos_cache', emb.cos(), persistent=False)
self.register_buffer('sin_cache', emb.sin(), persistent=False)
def _rotate_half(self, x: torch.Tensor) -> torch.Tensor:
x1, x2 = x[..., :x.shape[-1] // 2], x[..., x.shape[-1] // 2:]
return torch.cat([-x2, x1], dim=-1)
def forward(self, q: torch.Tensor, k: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
sq, sk = q.shape[2], k.shape[2]
cos_q = self.cos_cache[:sq].unsqueeze(0).unsqueeze(0)
sin_q = self.sin_cache[:sq].unsqueeze(0).unsqueeze(0)
cos_k = self.cos_cache[:sk].unsqueeze(0).unsqueeze(0)
sin_k = self.sin_cache[:sk].unsqueeze(0).unsqueeze(0)
return (
q * cos_q + self._rotate_half(q) * sin_q,
k * cos_k + self._rotate_half(k) * sin_k,
)
class RMSNorm(nn.Module):
"""Root Mean Square Layer Normalisation."""
def __init__(self, d_model: int, eps: float = 1e-6):
super().__init__()
self.eps = eps
self.weight = nn.Parameter(torch.ones(d_model))
def forward(self, x: torch.Tensor) -> torch.Tensor:
rms = x.pow(2).mean(-1, keepdim=True).add(self.eps).sqrt()
return x / rms * self.weight
# ============================================================================
# SPATIOTEMPORAL ATTENTION
# ============================================================================
class SpatiotemporalAttention(nn.Module):
"""Grouped-Query Attention with RoPE for spatiotemporal sequences."""
def __init__(self, d_model: int, n_heads: int, config: VJEPAQConfig):
super().__init__()
self.d_model = d_model
self.n_heads = n_heads
self.n_kv = config.N_KV_HEADS
self.n_groups = config.GQA_GROUPS
self.d_head = d_model // n_heads
self.q_proj = nn.Linear(d_model, n_heads * self.d_head, bias=False)
self.k_proj = nn.Linear(d_model, self.n_kv * self.d_head, bias=False)
self.v_proj = nn.Linear(d_model, self.n_kv * self.d_head, bias=False)
self.o_proj = nn.Linear(d_model, d_model, bias=False)
self.rope = RotaryEmbedding(self.d_head, max_seq_len=config.NUM_PATCHES * 2)
self.dropout_p = config.DROPOUT if config.DROPOUT > 0 else 0.0
def forward(
self,
x: torch.Tensor,
mask: Optional[torch.Tensor] = None,
is_causal: bool = False,
) -> torch.Tensor:
B, S, D = x.shape
Q = self.q_proj(x).view(B, S, self.n_heads, self.d_head).transpose(1, 2)
K = self.k_proj(x).view(B, S, self.n_kv, self.d_head).transpose(1, 2)
V = self.v_proj(x).view(B, S, self.n_kv, self.d_head).transpose(1, 2)
Q, K = self.rope(Q, K)
if self.n_groups > 1:
K = K.repeat_interleave(self.n_groups, dim=1)
V = V.repeat_interleave(self.n_groups, dim=1)
scale = self.d_head ** -0.5
if mask is not None:
attn_mask = mask.unsqueeze(1).unsqueeze(2) & mask.unsqueeze(1).unsqueeze(3)
attn_mask = attn_mask.expand(B, self.n_heads, S, S)
else:
attn_mask = None
out = F.scaled_dot_product_attention(
Q, K, V,
attn_mask=attn_mask,
dropout_p=self.dropout_p if self.training else 0.0,
is_causal=is_causal and attn_mask is None,
scale=scale,
)
out = out.transpose(1, 2).contiguous().view(B, S, D)
return self.o_proj(out)
# ============================================================================
# QUATERNION TORUS BRAIN (FFN REPLACEMENT)
# ============================================================================
class QuaternionTorusBrain(nn.Module):
"""FFN replacement with quaternion-topological processing on a 2D torus.
Pipeline:
1. Token compression (no temporal FFT per token)
2. Project to torus coordinates (phi1, phi2)
3. Soft-assignment to 8 torus nodes (4 angular x 2 radial)
4. Lightweight channel mixer on torus grid
5. Message passing with Lie algebra (exp/log) quaternion product
6. Attention-weighted readout
The Lie algebra trick (TORUS_LIE_APPROX) replaces the Hamilton product
in message passing with log-space addition: exp(log(q1) + log(q2)).
This converts O(n^2) quaternion multiplications to O(n) element-wise adds.
"""
def __init__(self, d_model: int, config: VJEPAQConfig):
super().__init__()
self.d_model = d_model
self.d_q = d_model // 4
self.n_radial = config.TORUS_RADIAL_BINS
self.n_angular = config.TORUS_ANGULAR_BINS
self.n_nodes = config.N_TORUS_NODES
self.config = config
self.assign_temp = config.TORUS_SOFT_ASSIGN_TEMPERATURE
self.lie_approx = config.TORUS_LIE_APPROX
d_lat = config.SPECTRAL_LATENT_DIM
self.token_proj = nn.Sequential(
nn.Linear(d_model, d_lat),
nn.GELU(),
nn.Linear(d_lat, d_model),
) if d_lat != d_model else nn.Identity()
self.spatial_mixer = nn.Sequential(
nn.Linear(4 * self.d_q, 4 * self.d_q),
nn.GELU(),
nn.Linear(4 * self.d_q, 4 * self.d_q),
)
self.torus_proj = nn.Sequential(
QuaternionLinear(d_model, d_model),
nn.GELU(),
nn.Linear(d_model, 4),
)
self.node_embed = nn.Parameter(torch.randn(self.n_nodes, d_model) * 0.02)
self.edge_quat = nn.Parameter(torch.randn(4, 4) * 0.1)
self.node_net = QuaternionLinear(d_model, d_model)
self.readout = nn.Sequential(
nn.Linear(d_model, d_model * 2),
nn.GELU(),
nn.Linear(d_model * 2, d_model),
)
self.spectral_ae = SpatiotemporalSpectralAE(config)
self._build_torus_graph()
def _build_torus_graph(self) -> None:
"""Build fully periodic 2D torus adjacency."""
edges_i, edges_j, edge_type = [], [], []
R, A = self.n_radial, self.n_angular
for r in range(R):
for a in range(A):
n = r * A + a
edges_i.append(n)
edges_j.append(r * A + (a - 1) % A)
edge_type.append(0)
edges_i.append(n)
edges_j.append(r * A + (a + 1) % A)
edge_type.append(1)
edges_i.append(n)
edges_j.append(((r - 1) % R) * A + a)
edge_type.append(2)
edges_i.append(n)
edges_j.append(((r + 1) % R) * A + a)
edge_type.append(3)
self.register_buffer('edges_i', torch.tensor(edges_i, dtype=torch.long))
self.register_buffer('edges_j', torch.tensor(edges_j, dtype=torch.long))
self.register_buffer('edge_type', torch.tensor(edge_type, dtype=torch.long))
def _torus_soft_assign(self, phi1: torch.Tensor, phi2: torch.Tensor) -> torch.Tensor:
BS = phi1.shape[0]
device = phi1.device
ang_pos = torch.linspace(-math.pi, math.pi, self.n_angular + 1, device=device)[:-1]
rad_pos = torch.linspace(-math.pi, math.pi, self.n_radial + 1, device=device)[:-1]
d_ang = torch.sin((phi1.unsqueeze(1) - ang_pos.unsqueeze(0)) / 2).pow(2)
d_rad = torch.sin((phi2.unsqueeze(1) - rad_pos.unsqueeze(0)) / 2).pow(2)
d_torus = d_rad.unsqueeze(2) + d_ang.unsqueeze(1)
d_flat = d_torus.view(BS, -1)
return torch.softmax(-d_flat / self.assign_temp, dim=-1)
def _message_passing(self, node_feat: torch.Tensor) -> torch.Tensor:
"""Message passing with Lie algebra quaternion product.
When self.lie_approx is True, uses exp(log(q) + log(p)) instead of
Hamilton product q * p. This converts quaternion multiplication to
vector addition in so(3) tangent space via BCH approximation.
"""
BS = node_feat.shape[0]
n_edges = self.edges_i.shape[0]
d_q = self.d_q
eq = QuaternionOps.normalize(self.edge_quat)
src_feat = node_feat[:, self.edges_j, :]
edge_q = eq[self.edge_type].unsqueeze(0).unsqueeze(2).expand(BS, -1, d_q, -1)
src_q = src_feat.view(BS, n_edges, d_q, 4)
if self.lie_approx:
log_edge = QuaternionOps.log(edge_q)
log_src = QuaternionOps.log(src_q)
msg_rot = QuaternionOps.exp(log_edge + log_src)
else:
msg_rot = QuaternionOps.hamilton_product(edge_q, src_q)
msg_rot = msg_rot.view(BS, n_edges, self.d_model)
agg = torch.zeros_like(node_feat, dtype=msg_rot.dtype)
dst_idx = self.edges_i.view(1, n_edges, 1).expand(BS, -1, self.d_model)
agg.scatter_add_(1, dst_idx, msg_rot)
return self.node_net(node_feat + agg)
def forward(self, x: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
B, S, D = x.shape
x_flat = x.reshape(B * S, D)
z = self.token_proj(x_flat)
recon_loss = x_flat.new_zeros(())
coords = self.torus_proj(z)
phi1 = math.pi * torch.tanh(coords[:, 0])
phi2 = math.pi * torch.tanh(coords[:, 1])
attn_w = self._torus_soft_assign(phi1, phi2)
nodes = (
attn_w.unsqueeze(-1) * self.node_embed.unsqueeze(0)
+ attn_w.unsqueeze(-1) * z.unsqueeze(1)
)
grid = nodes.view(B * S, self.n_radial, self.n_angular, D)
grid = grid.permute(0, 3, 1, 2)
d_q = self.d_q
grid_q = grid.view(B * S, 4, d_q, self.n_radial, self.n_angular)
grid_q = grid_q.permute(0, 1, 2, 3, 4).reshape(B * S, 4 * d_q, self.n_radial, self.n_angular)
B_grid, C_grid, H_grid, W_grid = grid_q.shape
grid_q = grid_q.permute(0, 2, 3, 1).reshape(-1, C_grid)
grid_q = self.spatial_mixer(grid_q)
grid_q = grid_q.reshape(B_grid, H_grid, W_grid, C_grid).permute(0, 3, 1, 2)
grid_back = grid_q.view(B * S, 4, d_q, self.n_radial, self.n_angular)
grid_back = grid_back.permute(0, 3, 4, 1, 2).reshape(B * S, self.n_nodes, D)
nodes_mp = self._message_passing(grid_back)
out_flat = (attn_w.unsqueeze(-1) * nodes_mp).sum(dim=1)
out_flat = self.readout(out_flat)
return out_flat.reshape(B, S, D), recon_loss
# ============================================================================
# MIXTURE OF EXPERTS
# ============================================================================
class TopoMoE(nn.Module):
"""Mixture of Experts with shared Topological Torus Brain."""
def __init__(self, d_model: int, config: VJEPAQConfig):
super().__init__()
self.moe_enabled = config.MOE_ENABLED
self.n_experts = config.N_EXPERTS
self.top_k = config.MOE_TOP_K
self.aux_weight = config.MOE_AUX_LOSS_WEIGHT
self.shared_expert = QuaternionTorusBrain(d_model, config)
if self.moe_enabled:
self.experts = nn.ModuleList([
nn.Sequential(
nn.Linear(d_model, d_model * 4 // 3),
nn.GELU(),
nn.Linear(d_model * 4 // 3, d_model),
) for _ in range(self.n_experts)
])
self.router = nn.Linear(d_model, self.n_experts, bias=False)
nn.init.normal_(self.router.weight, std=0.02)
def _route(self, x: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
N, D = x.shape
router_logits = self.router(x)
router_probs = F.softmax(router_logits, dim=-1)
top_k_probs, top_k_idx = torch.topk(router_probs, self.top_k, dim=-1)
top_k_probs = top_k_probs / top_k_probs.sum(dim=-1, keepdim=True).clamp(min=1e-9)
flat_idx = top_k_idx.reshape(-1)
flat_weights = top_k_probs.reshape(-1)
token_indices = torch.arange(N, device=x.device).unsqueeze(1).expand(-1, self.top_k).reshape(-1)
expert_out = torch.zeros_like(x)
for e in range(self.n_experts):
expert_mask = (flat_idx == e)
src_token_idx = token_indices[expert_mask]
w = flat_weights[expert_mask].unsqueeze(-1).to(x.dtype)
out_e = self.experts[e](x[src_token_idx])
contrib = w * out_e
expert_out.scatter_add_(0, src_token_idx.unsqueeze(1).expand_as(contrib), contrib)
token_frac = router_probs.mean(dim=0)
one_hot = F.one_hot(top_k_idx, self.n_experts).float()
dispatch_frac = one_hot.mean(dim=(0, 1))
aux_loss = self.n_experts * (token_frac * dispatch_frac).sum()
return expert_out, aux_loss
def forward(self, x: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
B, S, D = x.shape
shared_out, recon_loss = self.shared_expert(x)
if not self.moe_enabled:
return shared_out, recon_loss
x_flat = x.reshape(B * S, D)
expert_out, aux_loss = self._route(x_flat)
expert_out = expert_out.reshape(B, S, D)
output = shared_out + expert_out
total_aux = recon_loss + self.aux_weight * aux_loss
return output, total_aux
# ============================================================================
# TRANSFORMER BLOCK
# ============================================================================
class VJEPAQBlock(nn.Module):
"""Transformer block with SpatiotemporalAttention + TopoMoE FFN."""
def __init__(self, d_model: int, n_heads: int, config: VJEPAQConfig):
super().__init__()
self.norm1 = RMSNorm(d_model)
self.norm2 = RMSNorm(d_model)
self.attn = SpatiotemporalAttention(d_model, n_heads, config)
self.topo_brain = TopoMoE(d_model, config)
self.dropout = nn.Dropout(config.DROPOUT)
self.use_ckpt = config.GRADIENT_CHECKPOINTING
def _forward_impl(
self,
x: torch.Tensor,
mask: Optional[torch.Tensor] = None,
) -> Tuple[torch.Tensor, torch.Tensor]:
attn_out = self.attn(self.norm1(x), mask=mask)
x = x + self.dropout(attn_out)
brain_out, aux_loss = self.topo_brain(self.norm2(x))
x = x + self.dropout(brain_out)
return x, aux_loss
def forward(