File size: 50,482 Bytes
9c890d3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
# (c) Meta Platforms, Inc. and affiliates. Confidential and proprietary.

"""UCPE with validated, locally centered cameras and optional metric extent conditioning."""

from __future__ import annotations

import copy
import logging
import math
from collections.abc import Sequence
from dataclasses import dataclass
from typing import Any, ClassVar, cast

import torch
import torch.utils.checkpoint as cp
from torch import nn

from nets.ucpe_cd50.encoder import load_encoder_weights
from nets.ucpe_cd50_stable.backbone import (
    VisionTransformer,
    trunc_normal_,
    vit_giant_patch14_224,
)
from nets.ucpe_cd50_stable.geometry import (
    camera_diameter,
    center_camera_translations,
    center_world_to_ray_transforms,
    sanitize_camera_inputs,
)
from nets.ucpe_cd50_stable.ucpe import prepare_world_up
from nets.ucpe_cd50_stable.ucpe_transition import (
    RelativeRayAttention,
    build_lat_up_encoding,
    build_relative_ray_transforms,
)

logger: logging.Logger = logging.getLogger(__name__)
DEFAULT_CHECKPOINT_PATH = ""
TUBELET_SIZE = 2
NUM_FRAMES = 48
IMG_SIZE = 224
VIDEOMAE_FEATURE_LAYERS = (10, 20, 30, 40)
DENSETRACK_CLASSIFIER_NUM_CLASSES = 710
DENSETRACK_ENCODER_SECTION = "d4rtencoder"
ATTENTION_GLOBAL = "global"
ATTENTION_ALTERNATING_FRAME_GLOBAL = "alternating_frame_global"
ATTENTION_PATTERNS = (ATTENTION_GLOBAL, ATTENTION_ALTERNATING_FRAME_GLOBAL)
CAMERA_ENCODING_PLUECKER = "pluecker"
CAMERA_ENCODING_NONE = "none"
CAMERA_ENCODING_UCPE_RELATIVE = "ucpe_relative"
CAMERA_ENCODINGS = (
    CAMERA_ENCODING_PLUECKER,
    CAMERA_ENCODING_NONE,
    CAMERA_ENCODING_UCPE_RELATIVE,
)
EXTENT_SCALE_INJECTIONS = ("aspect", "ucpe_bias")


def _validate_extent_policy(
    diameter: float | None,
    scale_token: bool,
    aspect_token: bool,
    gate: float | None = None,
    injection: str = "aspect",
) -> None:
    if injection not in EXTENT_SCALE_INJECTIONS:
        raise ValueError(f"unknown extent scale injection {injection!r}")
    if injection == "ucpe_bias" and not scale_token:
        raise ValueError("UCPE scale bias requires the extent scale projection")
    for name, value in (
        ("max_camera_diameter_m", diameter),
        ("camera_condition_max_diameter_m", gate),
    ):
        if value is not None and (not math.isfinite(value) or value <= 0):
            raise ValueError(f"{name} must be positive and finite")
    if scale_token and (diameter is None or not aspect_token):
        raise ValueError(
            "extent scale token requires a diameter cap and an aspect token"
        )


def apply_densetrack_classifier_head_rng_compatibility(
    enabled: bool, *, embed_dim: int
) -> None:
    """Advance CPU RNG as DenseTrack's discarded VideoMAE classifier head did."""
    if not enabled:
        return
    compatibility_head = nn.Linear(
        embed_dim, DENSETRACK_CLASSIFIER_NUM_CLASSES, device="cpu"
    )
    trunc_normal_(compatibility_head.weight, std=0.02)
    if compatibility_head.bias is not None:
        nn.init.constant_(compatibility_head.bias, 0)


def _gate_pluecker_ray_tokens(
    ray_tokens: torch.Tensor, pluecker_ray_mask: torch.Tensor | None
) -> torch.Tensor:
    """Zero the ray contribution for masked samples.

    The mask multiplies the *embedded tokens*, not the input rays, so a masked sample gets
    exactly the image-only embedding rather than the embedding of a zero ray map -- which
    would differ by the convolution's bias.
    """
    if pluecker_ray_mask is None:
        return ray_tokens
    batch_size = ray_tokens.shape[0]
    if pluecker_ray_mask.shape != (batch_size,):
        raise ValueError(
            f"pluecker_ray_mask must have shape ({batch_size},), got {tuple(pluecker_ray_mask.shape)}"
        )
    scale = pluecker_ray_mask.to(device=ray_tokens.device, dtype=ray_tokens.dtype)
    return ray_tokens * scale.reshape(batch_size, 1, 1)


@dataclass
class VideoMAEEncoderConfig:
    """`type: "videomae_transition_ucpe_v00.VideoMAEEncoderConfig"` in `encoders_v02`.

    Resolution is scoped to the family package of the field's declared type, so a config
    reaching this class did so through `mv_trainer_v03`. Which encoder *member* a recipe
    names is config; which *interface* it gets is code.
    """

    ucpe_transition_supported: ClassVar[bool] = True
    ucpe_tubelet_size: ClassVar[int] = TUBELET_SIZE
    ucpe_camera_frame_offsets: ClassVar[tuple[int, ...]] = tuple(range(TUBELET_SIZE))
    checkpoint_path: str = DEFAULT_CHECKPOINT_PATH
    load_pretrained: bool = True
    freeze_encoder: bool = True
    all_frames: int = NUM_FRAMES
    img_size: int = IMG_SIZE
    drop_path_rate: float = 0.0
    camera_encoding: str = CAMERA_ENCODING_PLUECKER
    ucpe_attention_compression: int = 8
    ucpe_attention_interval: int = 1
    ucpe_absolute_lat_up: bool = False
    use_aspect_ratio_token: bool = False
    use_flash_attn: bool = True
    use_checkpoint: bool = False
    checkpoint_every: int = 1
    attention_pattern: str = ATTENTION_GLOBAL
    mv_interleave: bool = False
    same_time_view_attention_interval: int = 2
    mv_use_view_embed: bool = True
    max_view_num: int = 3
    max_camera_diameter_m: float | None = None
    camera_condition_max_diameter_m: float | None = None
    use_extent_scale_token: bool = False
    selective_ucpe_rows: bool = False
    densetrack_classifier_head_rng_compat: bool = False
    extent_scale_injection: str = "aspect"

    def build(self) -> VideoMAEEncoder:
        _validate_extent_policy(
            self.max_camera_diameter_m,
            self.use_extent_scale_token,
            self.use_aspect_ratio_token,
            self.camera_condition_max_diameter_m,
            self.extent_scale_injection,
        )
        if self.camera_condition_max_diameter_m is not None and (
            not math.isfinite(self.camera_condition_max_diameter_m)
            or self.camera_condition_max_diameter_m <= 0
        ):
            raise ValueError("camera condition diameter must be positive and finite")
        if self.camera_encoding not in CAMERA_ENCODINGS:
            raise ValueError(
                f"unknown camera_encoding {self.camera_encoding!r}; expected one of {CAMERA_ENCODINGS}"
            )
        model = vit_giant_patch14_224(
            img_size=self.img_size,
            all_frames=self.all_frames,
            tubelet_size=TUBELET_SIZE,
            drop_path_rate=self.drop_path_rate,
            use_flash_attn=self.use_flash_attn,
            no_pluecker_rays=self.camera_encoding != CAMERA_ENCODING_PLUECKER,
        )
        apply_densetrack_classifier_head_rng_compatibility(
            self.densetrack_classifier_head_rng_compat, embed_dim=model.embed_dim
        )
        if self.load_pretrained:
            load_encoder_weights(model, self.checkpoint_path)
        else:
            logger.info("skipping pretrained encoder weights (random init)")
        return VideoMAEEncoder(
            model,
            freeze_encoder=self.freeze_encoder,
            camera_encoding=self.camera_encoding,
            ucpe_attention_compression=self.ucpe_attention_compression,
            ucpe_attention_interval=self.ucpe_attention_interval,
            ucpe_absolute_lat_up=self.ucpe_absolute_lat_up,
            use_aspect_ratio_token=self.use_aspect_ratio_token,
            use_checkpoint=self.use_checkpoint,
            checkpoint_every=self.checkpoint_every,
            attention_pattern=self.attention_pattern,
            all_frames=self.all_frames,
            mv_interleave=self.mv_interleave,
            same_time_view_attention_interval=self.same_time_view_attention_interval,
            mv_use_view_embed=self.mv_use_view_embed,
            max_view_num=self.max_view_num,
            max_camera_diameter_m=self.max_camera_diameter_m,
            camera_condition_max_diameter_m=self.camera_condition_max_diameter_m,
            use_extent_scale_token=self.use_extent_scale_token,
            extent_scale_injection=self.extent_scale_injection,
            selective_ucpe_rows=self.selective_ucpe_rows,
        )


def _collect_multilayer_feature(
    features: list[torch.Tensor],
    block_number: int,
    tokens: torch.Tensor,
    aspect_tokens: torch.Tensor | None = None,
) -> None:
    if block_number not in VIDEOMAE_FEATURE_LAYERS:
        return
    if tokens.ndim == 5:
        tokens = tokens.flatten(2, 3)
    if aspect_tokens is not None:
        tokens = torch.cat((tokens, aspect_tokens), dim=-2)
    features.append(tokens)


def _fuse_multilayer_features(
    model: nn.Module, features: Sequence[torch.Tensor], projection: nn.Linear
) -> torch.Tensor:
    if len(features) != len(VIDEOMAE_FEATURE_LAYERS):
        raise ValueError("multilayer features require outputs from blocks 10/20/30/40")
    model_any: Any = model
    norm = model_any.fc_norm if model_any.fc_norm is not None else model_any.norm
    return projection(torch.cat([norm(feature) for feature in features], dim=-1))


def _gate_ucpe_residual(
    residual: torch.Tensor, camera_condition_mask: torch.Tensor | None
) -> torch.Tensor:
    """Drop a sample's camera conditioning without dropping the sample.

    Mirrors `_gate_pluecker_ray_tokens`: the RGB path keeps its full gradient, so a masked
    sample still trains everything except the camera residual. That is what lets one
    checkpoint serve both camera-on and camera-off evaluation.
    """
    if camera_condition_mask is None:
        return residual
    batch_size = residual.shape[0]
    if camera_condition_mask.shape != (batch_size,):
        raise ValueError(
            f"camera_condition_mask must have shape {(batch_size,)}, got {tuple(camera_condition_mask.shape)}"
        )
    return residual * camera_condition_mask.to(
        device=residual.device, dtype=residual.dtype
    ).reshape(batch_size, 1, 1)


class UCPEAttentionBranch(RelativeRayAttention):
    """A UCPE residual running in parallel with one pretrained attention layer.

    Cloned from the block it accompanies -- its own `norm1`, `drop_path` and `gamma_1` --
    so it is a complete pre-norm residual block rather than a bare attention op, and its
    parameters are independent of the RGB path it runs beside. `out_proj` stays zero, which
    is inherited from `RelativeRayAttention` and is the only zero-init here.
    """

    def __init__(
        self,
        source_block: nn.Module,
        *,
        compression: int,
        use_absolute_orientation: bool,
    ) -> None:
        source: Any = source_block
        dim = int(source.norm1.normalized_shape[0])
        super().__init__(
            dim=dim,
            num_heads=int(source.attn.num_heads),
            compression=compression,
            use_absolute_orientation=use_absolute_orientation,
        )
        self.norm = copy.deepcopy(source.norm1)
        self.drop_path = copy.deepcopy(source.drop_path)
        self.layer_scale = (
            None
            if source.gamma_1 is None
            else nn.Parameter(source.gamma_1.detach().clone())
        )

    def forward(
        self,
        tokens: torch.Tensor,
        ray_transforms: torch.Tensor,
        *,
        spatial_height: int,
        spatial_width: int,
        lat_up_encoding: torch.Tensor | None = None,
        lat_up_valid: torch.Tensor | None = None,
        camera_condition_mask: torch.Tensor | None = None,
        active_rows: torch.Tensor | None = None,
        scale_bias: torch.Tensor | None = None,
    ) -> torch.Tensor:
        if scale_bias is not None and scale_bias.shape != (
            tokens.shape[0],
            tokens.shape[-1],
        ):
            raise ValueError("scale bias must have shape (B, C)")
        if self.training and getattr(self.drop_path, "drop_prob", 0.0) > 0:
            active_rows = None
        if active_rows is not None:
            if active_rows.numel() == 0:
                zero = tokens.new_zeros(())
                for parameter in self.parameters():
                    if parameter.requires_grad:
                        zero = zero + parameter.reshape(-1)[0] * 0
                if scale_bias is not None:
                    zero = zero + scale_bias.sum() * 0
                return tokens * 0 + zero.to(tokens.dtype)
            delta = self._residual(
                tokens.index_select(0, active_rows),
                ray_transforms.index_select(0, active_rows),
                spatial_height,
                spatial_width,
                None
                if lat_up_encoding is None
                else lat_up_encoding.index_select(0, active_rows),
                None
                if lat_up_valid is None
                else lat_up_valid.index_select(0, active_rows),
                None if scale_bias is None else scale_bias.index_select(0, active_rows),
            )
            return torch.zeros_like(tokens).index_copy(0, active_rows, delta)
        return _gate_ucpe_residual(
            self._residual(
                tokens,
                ray_transforms,
                spatial_height,
                spatial_width,
                lat_up_encoding,
                lat_up_valid,
                scale_bias,
            ),
            camera_condition_mask,
        )

    def _residual(
        self,
        tokens: torch.Tensor,
        ray_transforms: torch.Tensor,
        spatial_height: int,
        spatial_width: int,
        lat_up_encoding: torch.Tensor | None,
        lat_up_valid: torch.Tensor | None,
        scale_bias: torch.Tensor | None = None,
    ) -> torch.Tensor:
        normalized = self.norm(tokens)
        if scale_bias is not None:
            with torch.autocast(tokens.device.type, enabled=False):
                normalized = normalized.float() + scale_bias.float()[:, None, :]
        delta = super().forward(
            normalized,
            ray_transforms,
            spatial_height=spatial_height,
            spatial_width=spatial_width,
            lat_up_encoding=lat_up_encoding,
            lat_up_valid=lat_up_valid,
        )
        if self.layer_scale is not None:
            delta = self.layer_scale.to(dtype=delta.dtype) * delta
        delta = self.drop_path(delta)
        return delta


def _run_block_with_ucpe(
    tokens: torch.Tensor,
    block: nn.Module,
    branch: UCPEAttentionBranch,
    ray_transforms: torch.Tensor,
    lat_up_encoding: torch.Tensor | None,
    spatial_height: int,
    spatial_width: int,
    camera_condition_mask: torch.Tensor | None,
    lat_up_valid: torch.Tensor | None,
    active_rows: torch.Tensor | None,
    scale_bias: torch.Tensor | None = None,
) -> torch.Tensor:
    """One VideoMAE block with the UCPE residual added *in parallel* with its attention.

    The block's forward is re-implemented rather than called, because the UCPE delta has to
    join the residual stream alongside the attention output and before the MLP -- a wrapper
    around `block(...)` could only add it afterwards, which is a different architecture.

    Tokens past `ray_transforms`'s length are extras with no pixel location -- today only the
    aspect-ratio token. They get a zero UCPE residual rather than being dropped, so the
    block still sees them in attention.
    """
    block_any: Any = block
    patch_token_count = ray_transforms.shape[1]
    ucpe_residual = branch(
        tokens[:, :patch_token_count],
        ray_transforms,
        spatial_height=spatial_height,
        spatial_width=spatial_width,
        lat_up_encoding=lat_up_encoding,
        lat_up_valid=lat_up_valid,
        camera_condition_mask=camera_condition_mask,
        active_rows=active_rows,
        scale_bias=scale_bias,
    )
    if tokens.shape[1] > patch_token_count:
        ucpe_residual = torch.cat(
            (ucpe_residual, torch.zeros_like(tokens[:, patch_token_count:])), dim=1
        )
    attention_residual = block_any.attn(block_any.norm1(tokens))
    if block_any.gamma_1 is None:
        tokens = tokens + block_any.drop_path(attention_residual) + ucpe_residual
        return tokens + block_any.drop_path(block_any.mlp(block_any.norm2(tokens)))
    tokens = (
        tokens
        + block_any.drop_path(block_any.gamma_1 * attention_residual)
        + ucpe_residual
    )
    return tokens + block_any.drop_path(
        block_any.gamma_2 * block_any.mlp(block_any.norm2(tokens))
    )


class SameTimeViewAttentionBranch(nn.Module):
    """Cross-view attention at one timestep, as a gated residual on the per-view stream.

    Cloned from the block it sits after, so it starts as a second copy of attention that
    block already learned -- a better starting point than random, and the reason the clone
    is a `deepcopy` rather than a fresh module.

    **The gate starts at zero**, so at initialization the branch contributes exactly
    nothing and the encoder computes what the single-view encoder computes. That is what
    makes this warm-startable from a single-view checkpoint: the multi-view model begins
    as the model it was initialized from, and learns to use the views rather than having
    to first recover from randomly scrambled ones. Same reasoning as the fusion neck's
    `residual_scale_init`.
    """

    def __init__(self, source_block: nn.Module) -> None:
        super().__init__()
        source: Any = source_block
        self.norm = copy.deepcopy(source.norm1)
        self.attn = copy.deepcopy(source.attn)
        self.drop_path = copy.deepcopy(source.drop_path)
        self.gate = nn.Parameter(torch.zeros_like(source.norm1.weight))
        self.initialize_from_block(source_block)

    def initialize_from_block(self, source_block: nn.Module) -> None:
        source: Any = source_block
        self.norm.load_state_dict(source.norm1.state_dict(), strict=True)
        self.attn.load_state_dict(source.attn.state_dict(), strict=True)
        nn.init.zeros_(self.gate)

    def forward(self, tokens: torch.Tensor) -> torch.Tensor:
        delta = self.drop_path(self.attn(self.norm(tokens)))
        return self.gate.to(dtype=delta.dtype) * delta


@dataclass(frozen=True)
class _UCPEInputs:
    """Everything the UCPE branches need, bundled so it threads as one argument.

    Internal to this module: a dataclass rather than five parallel parameters because they
    are always passed together and are meaningless apart.
    """

    rays: torch.Tensor
    lat_up: torch.Tensor | None
    spatial_height: int
    spatial_width: int
    condition_mask: torch.Tensor | None
    lat_up_valid: torch.Tensor | None
    per_view_rows: torch.Tensor | None
    cross_view_rows: torch.Tensor | None
    scale_bias: torch.Tensor | None = None


class VideoMAEEncoder(nn.Module):
    """VideoMAE tokens for a decoder to cross-attend to.

    `forward(video, pluecker_rays, pluecker_ray_mask)` returns `(B, L, C)`, or `(B, V, L, C)`
    when `mv_interleave` is on and the video arrives with a view axis.
    """

    requires_fp32_camera_inputs = True

    def __init__(
        self,
        model: VisionTransformer,
        freeze_encoder: bool = True,
        camera_encoding: str = CAMERA_ENCODING_PLUECKER,
        ucpe_attention_compression: int = 8,
        ucpe_attention_interval: int = 1,
        ucpe_absolute_lat_up: bool = False,
        use_aspect_ratio_token: bool = False,
        use_checkpoint: bool = False,
        checkpoint_every: int = 1,
        attention_pattern: str = ATTENTION_GLOBAL,
        all_frames: int = NUM_FRAMES,
        mv_interleave: bool = False,
        same_time_view_attention_interval: int = 2,
        mv_use_view_embed: bool = True,
        max_view_num: int = 3,
        max_camera_diameter_m: float | None = None,
        camera_condition_max_diameter_m: float | None = None,
        use_extent_scale_token: bool = False,
        selective_ucpe_rows: bool = False,
        extent_scale_injection: str = "aspect",
    ) -> None:
        super().__init__()
        _validate_extent_policy(
            max_camera_diameter_m,
            use_extent_scale_token,
            use_aspect_ratio_token,
            camera_condition_max_diameter_m,
            extent_scale_injection,
        )
        if (
            extent_scale_injection == "ucpe_bias"
            and camera_encoding != CAMERA_ENCODING_UCPE_RELATIVE
        ):
            raise ValueError("UCPE scale bias requires relative UCPE camera encoding")
        self.max_camera_diameter_m = max_camera_diameter_m
        self.camera_condition_max_diameter_m = camera_condition_max_diameter_m
        self.freeze_encoder = freeze_encoder
        self.selective_ucpe_rows = selective_ucpe_rows
        self.extent_scale_injection = extent_scale_injection
        if len(model.blocks) != VIDEOMAE_FEATURE_LAYERS[-1]:
            raise ValueError("multilayer features require 40-block VideoMAE")
        if attention_pattern not in ATTENTION_PATTERNS:
            raise ValueError(
                f"unknown attention_pattern {attention_pattern!r}; expected one of {ATTENTION_PATTERNS}"
            )
        if camera_encoding not in CAMERA_ENCODINGS:
            raise ValueError(
                f"unknown camera_encoding {camera_encoding!r}; expected one of {CAMERA_ENCODINGS}"
            )
        if camera_encoding == CAMERA_ENCODING_UCPE_RELATIVE:
            if attention_pattern != ATTENTION_GLOBAL:
                raise ValueError(
                    "camera_encoding='ucpe_relative' requires attention_pattern='global'"
                )
        elif ucpe_absolute_lat_up:
            raise ValueError(
                "ucpe_absolute_lat_up requires camera_encoding='ucpe_relative'"
            )
        self.model = model
        self.num_frames = all_frames
        self.use_checkpoint = use_checkpoint
        self.checkpoint_every = checkpoint_every
        self.camera_encoding = camera_encoding
        self.no_pluecker_rays = camera_encoding != CAMERA_ENCODING_PLUECKER
        self.ucpe_absolute_lat_up = ucpe_absolute_lat_up
        self.attention_pattern = attention_pattern
        self.embed_dim = model.embed_dim
        self.num_patches = model.patch_embed.num_patches
        self.tubelet_size = model.patch_embed.tubelet_size
        self.patch_size = model.patch_embed.patch_size[0]
        self.use_aspect_ratio_token = use_aspect_ratio_token
        self.aspect_ratio_proj: nn.Module | None = None
        if use_aspect_ratio_token:
            embed_dim = self.embed_dim
            self.aspect_ratio_proj = nn.Sequential(
                nn.Linear(1, embed_dim), nn.GELU(), nn.Linear(embed_dim, embed_dim)
            )
        self.extent_scale_proj: nn.Linear | None = None
        if use_extent_scale_token:
            self.extent_scale_proj = nn.Linear(1, self.embed_dim, bias=False)
            nn.init.zeros_(self.extent_scale_proj.weight)
        self.mv_interleave = mv_interleave
        self.same_time_view_attention_interval = 0
        self.mv_view_embed: nn.Parameter | None = None
        self.videomae_mv_view_branches: nn.ModuleList = nn.ModuleList()
        if mv_interleave:
            self._configure_multiview_interleave(
                interval=same_time_view_attention_interval,
                use_view_embed=mv_use_view_embed,
                max_view_num=max_view_num,
            )
        self.ucpe_attention_interval = 0
        self.ucpe_attention_branches: nn.ModuleList = nn.ModuleList()
        self.ucpe_cross_view_attention_branches: nn.ModuleList = nn.ModuleList()
        if camera_encoding == CAMERA_ENCODING_UCPE_RELATIVE:
            self._configure_ucpe_attention(
                interval=ucpe_attention_interval, compression=ucpe_attention_compression
            )
        if freeze_encoder:
            for parameter in self.model.parameters():
                parameter.requires_grad = False
            self.model.eval()
        projection_width = self.embed_dim
        self.multilayer_projection = nn.Linear(
            len(VIDEOMAE_FEATURE_LAYERS) * projection_width,
            projection_width,
            bias=False,
        )
        with torch.no_grad():
            self.multilayer_projection.weight.zero_()
            identity = torch.eye(
                self.embed_dim,
                device=self.multilayer_projection.weight.device,
                dtype=self.multilayer_projection.weight.dtype,
            )
            self.multilayer_projection.weight[:, -self.embed_dim :].copy_(identity)

    def _configure_ucpe_attention(self, interval: int, compression: int) -> None:
        if interval <= 0:
            raise ValueError(
                f"ucpe_attention_interval must be positive, got {interval}"
            )
        depth = len(self.model.blocks)
        if depth % interval != 0:
            raise ValueError(
                f"block depth {depth} is not divisible by ucpe_attention_interval={interval}"
            )
        self.ucpe_attention_interval = interval
        self.ucpe_attention_branches = nn.ModuleList(
            UCPEAttentionBranch(
                self.model.blocks[index],
                compression=compression,
                use_absolute_orientation=self.ucpe_absolute_lat_up,
            )
            for index in range(interval - 1, depth, interval)
        )
        if self.mv_interleave:
            cross_interval = self.same_time_view_attention_interval
            self.ucpe_cross_view_attention_branches = nn.ModuleList(
                UCPEAttentionBranch(
                    self.model.blocks[index],
                    compression=compression,
                    use_absolute_orientation=self.ucpe_absolute_lat_up,
                )
                for index in range(cross_interval - 1, depth, cross_interval)
            )

    def train(self, mode: bool = True) -> VideoMAEEncoder:
        super().train(mode)
        if self.freeze_encoder:
            self.model.eval()
        return self

    def _build_ucpe_geometry(
        self,
        T_world_cam: torch.Tensor,
        T_pix_cam: torch.Tensor,
        height: int,
        width: int,
        world_up: torch.Tensor | None,
    ) -> tuple[torch.Tensor, torch.Tensor | None]:
        """Build per-view geometry with one camera-frame axis inside each tubelet."""
        if T_world_cam.ndim != 5 or T_world_cam.shape[-2:] != (4, 4):
            raise ValueError(
                f"expected T_world_cam (B, V, T, 4, 4), got {tuple(T_world_cam.shape)}"
            )
        if T_pix_cam.ndim != 5:
            raise ValueError(
                f"expected T_pix_cam (B, V, T, k, k), got {tuple(T_pix_cam.shape)}"
            )
        if T_pix_cam.shape[:3] != T_world_cam.shape[:3]:
            raise ValueError(
                f"T_world_cam and T_pix_cam must agree on (B, V, T); got {tuple(T_world_cam.shape[:3])} and {tuple(T_pix_cam.shape[:3])}"
            )
        (batch, views) = T_world_cam.shape[:2]
        flat_world = T_world_cam.reshape(batch * views, *T_world_cam.shape[2:])
        flat_pix = T_pix_cam.reshape(batch * views, *T_pix_cam.shape[2:])
        geometry = {
            "image_height": height,
            "image_width": width,
            "patch_size": self.patch_size,
            "tubelet_size": self.tubelet_size,
        }
        rays = build_relative_ray_transforms(flat_world, flat_pix, **geometry)
        tokens = rays.shape[1]
        tokens_per_slot = height // self.patch_size * (width // self.patch_size)
        rays = rays.reshape(
            batch,
            views,
            tokens // tokens_per_slot,
            tokens_per_slot,
            self.tubelet_size,
            4,
            4,
        )
        lat_up = None
        if self.ucpe_absolute_lat_up:
            assert world_up is not None
            lat_up = build_lat_up_encoding(
                flat_world,
                flat_pix,
                world_up=world_up.repeat_interleave(views, dim=0),
                **geometry,
            ).reshape(
                batch,
                views,
                tokens // tokens_per_slot,
                tokens_per_slot,
                self.tubelet_size,
                3,
            )
        return (rays, lat_up)

    def _project_aspect_tokens(
        self,
        aspect_ratio: torch.Tensor | None,
        batch: int,
        views: int,
        dtype: torch.dtype,
        device: torch.device,
    ) -> torch.Tensor | None:
        if self.aspect_ratio_proj is None:
            return None
        if aspect_ratio is None:
            raise ValueError(
                "aspect_ratio is required when use_aspect_ratio_token=True"
            )
        aspect_ratio = aspect_ratio.to(device=device, dtype=dtype)
        if aspect_ratio.ndim == 2:
            aspect_ratio = aspect_ratio.unsqueeze(-1)
        if aspect_ratio.shape != (batch, views, 1):
            raise ValueError(
                f"expected aspect_ratio {(batch, views, 1)}, got {tuple(aspect_ratio.shape)}"
            )
        projected = self.aspect_ratio_proj(aspect_ratio.reshape(batch * views, 1))
        return projected.reshape(batch, views, 1, self.embed_dim)

    def _configure_multiview_interleave(
        self, interval: int, use_view_embed: bool, max_view_num: int
    ) -> None:
        if interval <= 0:
            raise ValueError(
                f"same_time_view_attention_interval must be positive, got {interval}"
            )
        if max_view_num <= 0:
            raise ValueError(f"max_view_num must be positive, got {max_view_num}")
        depth = len(self.model.blocks)
        if depth % interval != 0:
            raise ValueError(
                f"block depth {depth} is not divisible by same_time_view_attention_interval={interval}"
            )
        self.same_time_view_attention_interval = interval
        self.videomae_mv_view_branches = nn.ModuleList(
            SameTimeViewAttentionBranch(self.model.blocks[index])
            for index in range(interval - 1, depth, interval)
        )
        if use_view_embed:
            self.mv_view_embed = nn.Parameter(torch.zeros(max_view_num, self.embed_dim))

    def _embed(
        self,
        video: torch.Tensor,
        pluecker_rays: torch.Tensor | None,
        pluecker_ray_mask: torch.Tensor | None,
    ) -> torch.Tensor:
        """Patch-embed RGB and rays, add positions."""
        batch_size = video.size(0)
        x = self.model.patch_embed(video)
        ray_embed = self.model.patch_embed_pluecker_rays
        if (
            not self.no_pluecker_rays
            and pluecker_rays is not None
            and (ray_embed is not None)
        ):
            ray_tokens = ray_embed(pluecker_rays)
            x = x + _gate_pluecker_ray_tokens(ray_tokens, pluecker_ray_mask)
        if self.model.pos_embed is not None:
            positions = cast(torch.Tensor, self.model.pos_embed)[:, : x.shape[1]]
            x = (
                x
                + positions.expand(batch_size, -1, -1).type_as(x).to(x.device).detach()
            )
        return self.model.pos_drop(x)

    def _run_block(self, block_index: int, x: torch.Tensor) -> torch.Tensor:
        block = cast(nn.Module, self.model.blocks[block_index])
        if (
            self.use_checkpoint
            and self.training
            and (self.checkpoint_every > 0)
            and (block_index % self.checkpoint_every == 0)
        ):
            return cp.checkpoint(block, x, use_reentrant=False)
        return block(x)

    def get_encoder_tokens(
        self,
        video: torch.Tensor,
        pluecker_rays: torch.Tensor | None = None,
        pluecker_ray_mask: torch.Tensor | None = None,
    ) -> torch.Tensor:
        """Single-view tokens."""
        x = self._embed(video, pluecker_rays, pluecker_ray_mask)
        (_, _, frames, height, width) = video.shape
        (patch_height, patch_width) = self.model.patch_embed.patch_size
        temporal_tokens = frames // self.model.patch_embed.tubelet_size
        spatial_tokens = height // patch_height * (width // patch_width)
        expected = temporal_tokens * spatial_tokens
        if x.shape[1] != expected:
            raise ValueError(
                f"expected {expected} tokens from {temporal_tokens} temporal bins x {spatial_tokens} spatial tokens, got {x.shape[1]}"
            )
        intermediate_features: list[torch.Tensor] = []
        frame_local = self.attention_pattern == ATTENTION_ALTERNATING_FRAME_GLOBAL
        for index in range(len(self.model.blocks)):
            if frame_local and index % 2 == 0:
                x = self._run_frame_local(index, x, temporal_tokens, spatial_tokens)
            else:
                x = self._run_block(index, x)
            _collect_multilayer_feature(intermediate_features, index + 1, x)
        return _fuse_multilayer_features(
            self.model, intermediate_features, self.multilayer_projection
        )

    def _run_frame_local(
        self,
        block_index: int,
        x: torch.Tensor,
        temporal_tokens: int,
        spatial_tokens: int,
    ) -> torch.Tensor:
        """Run one block with attention confined within each temporal tubelet.

        Folding the temporal axis into the batch is what restricts attention: the block is
        unchanged and keeps its pretrained weights, only the grouping of tokens it sees
        differs.
        """
        (batch_size, tokens, channels) = x.shape
        if tokens != temporal_tokens * spatial_tokens:
            raise ValueError(
                f"frame-local attention expected {temporal_tokens * spatial_tokens} tokens, got {tokens}"
            )
        folded = x.reshape(batch_size * temporal_tokens, spatial_tokens, channels)
        folded = self._run_block(block_index, folded)
        return folded.reshape(batch_size, tokens, channels)

    def _run_frame_local_multiview_block(
        self, block_index: int, x: torch.Tensor
    ) -> torch.Tensor:
        """One block, attention confined to one view's one frame."""
        (b, v, t, p, c) = x.shape
        folded = self._run_block(block_index, x.reshape(b * v * t, p, c))
        return folded.reshape(b, v, t, p, c)

    def _run_global_per_view_block(
        self,
        block_index: int,
        x: torch.Tensor,
        aspect_tokens: torch.Tensor | None,
        ucpe: _UCPEInputs | None,
    ) -> tuple[torch.Tensor, torch.Tensor | None]:
        """One block, attention over a whole view's clip but never across views.

        The aspect token rides along here and only here: it participates in per-view global
        attention, and is carried untouched through frame-local and cross-view attention,
        which are both organised by a spatial grid it has no place in.
        """
        (b, v, t, p, c) = x.shape
        folded = x.reshape(b * v, t * p, c)
        if aspect_tokens is not None:
            folded = torch.cat((folded, aspect_tokens.reshape(b * v, 1, c)), dim=1)
        use_ucpe = (
            ucpe is not None
            and self.ucpe_attention_interval > 0
            and ((block_index + 1) % self.ucpe_attention_interval == 0)
        )
        if use_ucpe:
            assert ucpe is not None
            branch_index = (block_index + 1) // self.ucpe_attention_interval - 1
            branch = cast(
                UCPEAttentionBranch, self.ucpe_attention_branches[branch_index]
            )
            rays = ucpe.rays.reshape(b * v, t * p, self.tubelet_size, 4, 4)
            rays = center_world_to_ray_transforms(rays)
            lat_up = (
                None
                if ucpe.lat_up is None
                else ucpe.lat_up.reshape(b * v, t * p, self.tubelet_size, 3)
            )
            mask = (
                None
                if ucpe.condition_mask is None
                else ucpe.condition_mask.repeat_interleave(v)
            )
            lat_up_valid = (
                None
                if ucpe.lat_up_valid is None
                else ucpe.lat_up_valid.repeat_interleave(v)
            )

            def run(tokens: torch.Tensor) -> torch.Tensor:
                return _run_block_with_ucpe(
                    tokens,
                    self.model.blocks[block_index],
                    branch,
                    rays,
                    lat_up,
                    ucpe.spatial_height,
                    ucpe.spatial_width,
                    mask,
                    lat_up_valid,
                    ucpe.per_view_rows,
                    None
                    if ucpe.scale_bias is None
                    else ucpe.scale_bias.repeat_interleave(v, dim=0),
                )

            if self._recompute(block_index):
                folded = cp.checkpoint(run, folded, use_reentrant=False)
            else:
                folded = run(folded)
        else:
            folded = self._run_block(block_index, folded)
        if aspect_tokens is None:
            return (folded.reshape(b, v, t, p, c), None)
        return (
            folded[:, :-1].reshape(b, v, t, p, c),
            folded[:, -1:].reshape(b, v, 1, c),
        )

    def _recompute(self, index: int) -> bool:
        return (
            self.use_checkpoint
            and self.training
            and (self.checkpoint_every > 0)
            and (index % self.checkpoint_every == 0)
        )

    def _run_same_time_view_branch(
        self, branch_index: int, x: torch.Tensor, ucpe: _UCPEInputs | None
    ) -> torch.Tensor:
        """Add the gated cross-view delta for one timestep's tokens.

        Views are packed into the token axis so one attention call sees every view at that
        timestep. The result is *added*, not substituted -- the per-view stream survives,
        which is what lets the gate start closed.

        Under UCPE a second delta from `ucpe_cross_view_attention_branches` is summed into
        the same residual, so the cross-view step is camera-conditioned too.
        """
        (b, v, t, p, c) = x.shape
        packed = x.permute(0, 2, 1, 3, 4).reshape(b * t, v * p, c)
        branch = self.videomae_mv_view_branches[branch_index]
        if self._recompute(branch_index):
            delta = cp.checkpoint(branch, packed, use_reentrant=False)
        else:
            delta = branch(packed)
        if ucpe is not None and len(self.ucpe_cross_view_attention_branches) > 0:
            ucpe_branch = cast(
                UCPEAttentionBranch,
                self.ucpe_cross_view_attention_branches[branch_index],
            )
            rays = ucpe.rays.permute(0, 2, 1, 3, 4, 5, 6).reshape(
                b * t, v * p, self.tubelet_size, 4, 4
            )
            rays = center_world_to_ray_transforms(rays)
            lat_up = (
                None
                if ucpe.lat_up is None
                else ucpe.lat_up.permute(0, 2, 1, 3, 4, 5).reshape(
                    b * t, v * p, self.tubelet_size, 3
                )
            )
            mask = (
                None
                if ucpe.condition_mask is None
                else ucpe.condition_mask.repeat_interleave(t)
            )
            lat_up_valid = (
                None
                if ucpe.lat_up_valid is None
                else ucpe.lat_up_valid.repeat_interleave(t)
            )

            def run_ucpe(tokens: torch.Tensor) -> torch.Tensor:
                return ucpe_branch(
                    tokens,
                    rays,
                    spatial_height=ucpe.spatial_height,
                    spatial_width=ucpe.spatial_width,
                    lat_up_encoding=lat_up,
                    lat_up_valid=lat_up_valid,
                    camera_condition_mask=mask,
                    active_rows=ucpe.cross_view_rows,
                    scale_bias=None
                    if ucpe.scale_bias is None
                    else ucpe.scale_bias.repeat_interleave(t, dim=0),
                )

            if self._recompute(branch_index):
                delta = delta + cp.checkpoint(run_ucpe, packed, use_reentrant=False)
            else:
                delta = delta + run_ucpe(packed)
        delta = delta.reshape(b, t, v, p, c).permute(0, 2, 1, 3, 4)
        return x + delta

    def get_multiview_encoder_tokens(
        self,
        video: torch.Tensor,
        pluecker_rays: torch.Tensor | None = None,
        pluecker_ray_mask: torch.Tensor | None = None,
        T_world_cam: torch.Tensor | None = None,
        T_pix_cam: torch.Tensor | None = None,
        aspect_ratio: torch.Tensor | None = None,
        camera_condition_mask: torch.Tensor | None = None,
        world_up: torch.Tensor | None = None,
        world_up_valid: torch.Tensor | None = None,
    ) -> torch.Tensor:
        """Interleaved multi-view tokens, cross-view attention at full depth.

        Every block runs per-view, exactly as it would single-view; a gated cross-view
        branch is added after every `same_time_view_attention_interval` blocks. Unlike
        `encoders_v00/videomae_v00`, no block is replaced and no prefix of the network is
        excluded, so views can inform each other from the first block rather than only the
        last few. Under `camera_encoding='ucpe_relative'` both the per-view and the
        cross-view step additionally see relative camera pose.
        """
        if not self.mv_interleave:
            raise ValueError("mv_interleave is not enabled on this encoder")
        if video.ndim != 6:
            raise ValueError(
                f"expected (B, V, C, T, H, W), got shape {tuple(video.shape)}"
            )
        (batch_size, num_views, _, _, height, width) = video.shape
        view_embed = self.mv_view_embed
        if view_embed is not None and num_views > view_embed.shape[0]:
            raise ValueError(
                f"num_views={num_views} exceeds max_view_num={view_embed.shape[0]}"
            )
        log_scale = None
        if self.camera_encoding == CAMERA_ENCODING_UCPE_RELATIVE:
            if T_world_cam is None or T_pix_cam is None:
                raise ValueError("UCPE requires camera poses and intrinsics")
            (T_world_cam, T_pix_cam, aspect_ratio) = sanitize_camera_inputs(
                T_world_cam, T_pix_cam, aspect_ratio, camera_condition_mask
            )
            T_world_cam = center_camera_translations(T_world_cam)
            if self.camera_condition_max_diameter_m is not None:
                diameter = camera_diameter(T_world_cam)
                keep = torch.isfinite(diameter) & (
                    diameter <= self.camera_condition_max_diameter_m
                )
                camera_condition_mask = (
                    keep
                    if camera_condition_mask is None
                    else camera_condition_mask & keep
                )
                (T_world_cam, T_pix_cam, aspect_ratio) = sanitize_camera_inputs(
                    T_world_cam, T_pix_cam, aspect_ratio, camera_condition_mask
                )
            if self.max_camera_diameter_m is not None:
                diameter = camera_diameter(T_world_cam)
                if not bool(torch.isfinite(diameter).all()):
                    raise ValueError("camera diameter must be finite")
                scale = (diameter / self.max_camera_diameter_m).clamp_min(1)
                T_world_cam = T_world_cam.clone()
                T_world_cam[..., :3, 3] /= scale[:, None, None, None]
                log_scale = scale.log()
                if camera_condition_mask is not None:
                    log_scale = log_scale * camera_condition_mask.to(log_scale)
        per_view = [
            self._embed(
                video[:, view_index],
                None if pluecker_rays is None else pluecker_rays[:, view_index],
                pluecker_ray_mask,
            )
            for view_index in range(num_views)
        ]
        x = torch.stack(per_view, dim=1)
        (_, _, tokens, channels) = x.shape
        patches_wide = width // self.patch_size
        patches_high = height // self.patch_size
        tokens_per_slot = patches_high * patches_wide
        if tokens % tokens_per_slot != 0:
            raise ValueError(
                f"token count {tokens} is not divisible by {tokens_per_slot} tokens per temporal slot"
            )
        temporal_slots = tokens // tokens_per_slot
        x = x.reshape(batch_size, num_views, temporal_slots, tokens_per_slot, channels)
        aspect_tokens = self._project_aspect_tokens(
            aspect_ratio, batch_size, num_views, x.dtype, x.device
        )
        scale_bias = None
        if self.extent_scale_proj is not None:
            assert log_scale is not None and aspect_tokens is not None
            with torch.autocast(x.device.type, enabled=False):
                scale_embedding = torch.nn.functional.linear(
                    log_scale[:, None].float(), self.extent_scale_proj.weight.float()
                )
            if self.extent_scale_injection == "aspect":
                aspect_tokens = aspect_tokens + scale_embedding[:, None, None].to(
                    x.dtype
                )
            else:
                scale_bias = scale_embedding
                aspect_tokens = aspect_tokens + scale_embedding.sum().to(x.dtype) * 0
        if view_embed is not None:
            slots = view_embed[:num_views].to(device=x.device, dtype=x.dtype)
            x = x + slots.reshape(1, num_views, 1, 1, channels)
            if aspect_tokens is not None:
                aspect_tokens = aspect_tokens + slots.reshape(1, num_views, 1, channels)
        ucpe = None
        if self.camera_encoding == CAMERA_ENCODING_UCPE_RELATIVE and (
            self.training
            or camera_condition_mask is None
            or bool(camera_condition_mask.any())
        ):
            if T_world_cam is None or T_pix_cam is None:
                raise ValueError(
                    "camera_encoding='ucpe_relative' requires T_world_cam and T_pix_cam"
                )
            lat_up_valid = None
            if self.ucpe_absolute_lat_up:
                (world_up, lat_up_valid) = prepare_world_up(
                    world_up, world_up_valid, batch_size=batch_size, device=video.device
                )
            (rays, lat_up) = self._build_ucpe_geometry(
                T_world_cam, T_pix_cam, height, width, world_up
            )
            per_view_rows = cross_view_rows = None
            if self.selective_ucpe_rows and camera_condition_mask is not None:
                active = camera_condition_mask.nonzero(as_tuple=True)[0]
                if active.numel() < batch_size:
                    per_view_rows = (
                        active[:, None] * num_views
                        + torch.arange(num_views, device=active.device)
                    ).flatten()
                    cross_view_rows = (
                        active[:, None] * temporal_slots
                        + torch.arange(temporal_slots, device=active.device)
                    ).flatten()
            ucpe = _UCPEInputs(
                rays=rays,
                lat_up=lat_up,
                spatial_height=patches_high,
                spatial_width=patches_wide,
                condition_mask=camera_condition_mask,
                lat_up_valid=lat_up_valid,
                per_view_rows=per_view_rows,
                cross_view_rows=cross_view_rows,
                scale_bias=scale_bias,
            )
        intermediate_features: list[torch.Tensor] = []
        frame_local = self.attention_pattern == ATTENTION_ALTERNATING_FRAME_GLOBAL
        interval = self.same_time_view_attention_interval
        for block_index in range(len(self.model.blocks)):
            if frame_local and block_index % 2 == 0:
                x = self._run_frame_local_multiview_block(block_index, x)
            else:
                (x, aspect_tokens) = self._run_global_per_view_block(
                    block_index, x, aspect_tokens, ucpe
                )
            if (block_index + 1) % interval == 0:
                x = self._run_same_time_view_branch(block_index // interval, x, ucpe)
            _collect_multilayer_feature(
                intermediate_features, block_index + 1, x, aspect_tokens
            )
        x = _fuse_multilayer_features(
            self.model, intermediate_features, self.multilayer_projection
        )
        return x

    def forward(
        self,
        video: torch.Tensor,
        pluecker_rays: torch.Tensor | None = None,
        pluecker_ray_mask: torch.Tensor | None = None,
        T_world_cam: torch.Tensor | None = None,
        T_pix_cam: torch.Tensor | None = None,
        aspect_ratio: torch.Tensor | None = None,
        camera_condition_mask: torch.Tensor | None = None,
        world_up: torch.Tensor | None = None,
        world_up_valid: torch.Tensor | None = None,
    ) -> torch.Tensor:
        if video.ndim == 6:
            return self.get_multiview_encoder_tokens(
                video,
                pluecker_rays,
                pluecker_ray_mask,
                T_world_cam,
                T_pix_cam,
                aspect_ratio,
                camera_condition_mask,
                world_up,
                world_up_valid,
            )
        if self.mv_interleave:
            tokens = self.get_multiview_encoder_tokens(
                video.unsqueeze(1),
                None if pluecker_rays is None else pluecker_rays.unsqueeze(1),
                pluecker_ray_mask,
                None if T_world_cam is None else T_world_cam.unsqueeze(1),
                None if T_pix_cam is None else T_pix_cam.unsqueeze(1),
                None if aspect_ratio is None else aspect_ratio.unsqueeze(1),
                camera_condition_mask,
                world_up,
                world_up_valid,
            )
            return tokens.squeeze(1)
        if self.camera_encoding == CAMERA_ENCODING_UCPE_RELATIVE:
            raise ValueError(
                "camera_encoding='ucpe_relative' requires mv_interleave=True; the UCPE branches are built alongside the interleaved blocks"
            )
        return self.get_encoder_tokens(video, pluecker_rays, pluecker_ray_mask)

    @staticmethod
    def get_normalization() -> tuple[tuple[float, float, float], ...]:
        """ImageNet statistics, which is what the pretrained backbone expects.

        Worth keeping reachable: a port that fed the encoder unnormalized images and still
        matched a synthetic-input harness at 1e-6 is the cautionary tale behind the
        equivalence gates' "real batches only" rule.
        """
        return ((0.485, 0.456, 0.406), (0.229, 0.224, 0.225))