File size: 26,773 Bytes
b506011
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# This code is referenced from https://github.com/dhansmair/flamingo-mini

import torch
from einops import rearrange, repeat
from einops_exts import rearrange_many
from torch import einsum, nn
import torch.nn.functional as F

from policy_models.module.transformers.utils import feed_forward_layer

class Attention(nn.Module):
    def __init__(
            self,
            dim: int,
            num_heads: int = 8,
            use_cross_attn=False,
            y_dim=512,
            qkv_bias: bool = False,
            qk_norm: bool = False,
            attn_drop: float = 0.,
            proj_drop: float = 0.,
            norm_layer: nn.Module = nn.LayerNorm,
            attn_mask = None,
    ) -> None:
        super().__init__()
        assert dim % num_heads == 0, 'dim should be divisible by num_heads'
        self.num_heads = num_heads
        self.head_dim = dim // num_heads
        self.scale = self.head_dim ** -0.5
        self.fused_attn = True

        self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
        self.q_norm = norm_layer(self.head_dim) if qk_norm else nn.Identity()
        self.k_norm = norm_layer(self.head_dim) if qk_norm else nn.Identity()
        self.attn_drop = nn.Dropout(attn_drop)
        self.proj = nn.Linear(dim, dim)
        self.proj_drop = nn.Dropout(proj_drop)
        self.attn_mask = attn_mask
        self.use_cross_attn=use_cross_attn
        if self.use_cross_attn:
            #print('use_cross_attn')
            self.y_kv = nn.Linear(y_dim, dim * 2, bias=qkv_bias)
            self.y_k_norm = norm_layer(self.head_dim) if qk_norm else nn.Identity()
            self.gate = nn.Parameter(torch.zeros([self.num_heads]))

    def forward(self, x: torch.Tensor, y=None, attn_mask=None) -> torch.Tensor:
        B, N, C = x.shape
        qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, self.head_dim).permute(2, 0, 3, 1, 4)
        q, k, v = qkv.unbind(0)
        q, k = self.q_norm(q), self.k_norm(k)

        # TODO: whether to use attn_mask
        if self.fused_attn:
            runtime_mask = None
            if attn_mask is not None:
                runtime_mask = attn_mask.to(x.device)
            elif self.attn_mask is not None:
                runtime_mask = self.attn_mask.to(x.device)[:q.shape[2],:k.shape[2]]
            x = F.scaled_dot_product_attention(
                q, k, v,
                dropout_p=self.attn_drop.p if self.training else 0.,
                attn_mask=runtime_mask
            )
        else:
            q = q * self.scale
            attn = q @ k.transpose(-2, -1)
            attn = attn.softmax(dim=-1)
            attn = self.attn_drop(attn)
            x = attn @ v

        if self.use_cross_attn:
            #print('y_shape:',y.shape)
            N_y = y.shape[1]
            y_kv = self.y_kv(y).reshape(B, N_y, 2, self.num_heads, self.head_dim).permute(2, 0, 3, 1, 4)
            y_k, y_v = y_kv.unbind(0)
            y_k = self.y_k_norm(y_k)
            y_out = F.scaled_dot_product_attention(
                q, y_k, y_v,
                dropout_p=self.attn_drop.p if self.training else 0.,
            )
            #print('y_out_shape:', y_out.shape)
            y_out = y_out*self.gate.tanh().view(1, -1, 1, 1)
            x = x + y_out

        x = x.transpose(1, 2).reshape(B, N, C)
        x = self.proj(x)
        x = self.proj_drop(x)
        return x

class PerceiverAttentionLayer(nn.Module):
    """Perceiver Attention Layer"""

    def __init__(self, dim: int, dim_head: int = 64, heads: int = 8):
        super().__init__()
        self.scale = dim_head**-0.5
        self.heads = heads
        self.dim_head = dim_head
        inner_dim = dim_head * heads

        # trainable components of PerceiverAttentionLayer
        self.norm_media = nn.LayerNorm(dim)
        self.norm_latents = nn.LayerNorm(dim)

        self.to_q = nn.Linear(dim, inner_dim, bias=False)
        self.to_k = nn.Linear(dim, inner_dim, bias=False)
        self.to_v = nn.Linear(dim, inner_dim, bias=False)
        self.to_out = nn.Linear(inner_dim, dim, bias=False)

    def forward(self, features, latents):
        """Latent vectors are cross-attending to the visual features x

        Args:
            features: Batch of visual features with shape (batch_size, n_features, dim)
            latents: Latent learnt vectors which are used to compute queries with shape (batch_size, n_latents, dim)

        Returns:
            Attention score with shape (batch_size, n_latents, dim)
        """
        assert features.ndim == 3
        assert latents.ndim == 3
        assert features.shape[0] == latents.shape[0]
        assert features.shape[2] == latents.shape[2]

        n_heads = self.heads
        n_batch, n_features, dim = features.shape
        n_queries = latents.shape[1]

        # Layer normalization
        x = self.norm_media(features)
        latents = self.norm_latents(latents)

        # Compute the queries from the latents, for all attention heads simultaneously
        q = self.to_q(latents)
        q = rearrange(q, 'b q (h d) -> b h q d', h=n_heads)
        assert q.shape == torch.Size([n_batch, n_heads, n_queries, self.dim_head])

        # Keys and values for all attention heads
        kv_input = torch.cat((x, latents), dim=-2)
        n_features_latents = n_features + n_queries
        k = self.to_k(kv_input)
        v = self.to_v(kv_input)

        k, v = rearrange_many((k, v), 'b f (h d) -> b h f d', h=n_heads)
        assert v.shape == torch.Size([n_batch, n_heads, n_features_latents, self.dim_head])

        q = q * self.scale

        # Attention scores
        sim = einsum('b h q d, b h f d -> b h q f', q, k)
        sim = sim - sim.amax(dim=-1, keepdim=True).detach()
        alphas = sim.softmax(dim=-1)

        out = einsum('b h q f, b h f v -> b h q v', alphas, v)
        out = rearrange(out, 'b h q v -> b q (h v)')

        return self.to_out(out)

class TempAttentionLayer(nn.Module):
    """Perceiver Attention Layer"""

    def __init__(self, dim: int, dim_head: int = 64, heads: int = 8):
        super().__init__()
        self.scale = dim_head**-0.5
        self.heads = heads
        self.dim_head = dim_head
        inner_dim = dim_head * heads

        # trainable components of PerceiverAttentionLayer
        self.norm_media = nn.LayerNorm(dim)

        self.to_q = nn.Linear(dim, inner_dim, bias=False)
        self.to_k = nn.Linear(dim, inner_dim, bias=False)
        self.to_v = nn.Linear(dim, inner_dim, bias=False)
        self.to_out = nn.Linear(inner_dim, dim, bias=False)

    def forward(self, features):
        """Latent vectors are cross-attending to the visual features x

        Args:
            features: Batch of visual features with shape (batch_size, n_features, dim)
            latents: Latent learnt vectors which are used to compute queries with shape (batch_size, n_latents, dim)

        Returns:
            Attention score with shape (batch_size, n_latents, dim)
        """
        assert features.ndim == 3

        n_heads = self.heads
        n_batch, n_features, dim = features.shape
        n_queries = features.shape[1]

        # Layer normalization
        x = self.norm_media(features)

        # Compute the queries from the latents, for all attention heads simultaneously
        q = self.to_q(x)
        q = rearrange(q, 'b q (h d) -> b h q d', h=n_heads)
        assert q.shape == torch.Size([n_batch, n_heads, n_queries, self.dim_head])

        # Keys and values for all attention heads
        n_features_latents = n_features
        k = self.to_k(x)
        v = self.to_v(x)

        k, v = rearrange_many((k, v), 'b f (h d) -> b h f d', h=n_heads)
        assert v.shape == torch.Size([n_batch, n_heads, n_features_latents, self.dim_head])

        q = q * self.scale

        # Attention scores
        sim = einsum('b h q d, b h f d -> b h q f', q, k)
        sim = sim - sim.amax(dim=-1, keepdim=True).detach()
        alphas = sim.softmax(dim=-1)

        out = einsum('b h q f, b h f v -> b h q v', alphas, v)
        out = rearrange(out, 'b h q v -> b q (h v)')

        return self.to_out(out)


class Video_Former_3D(nn.Module):
    """Perceiver Resampler with multi-head attention layer"""

    def __init__(
            self,
            dim: int,
            depth: int,
            condition_dim: int = 1280,
            dim_head: int = 64,
            heads: int = 8,
            num_latents: int = 64,
            num_frame: int = 14,
            num_time_embeds: int = 4,
            ff_mult: int = 4,
            activation: str = 'gelu',
            trainable: bool = True,
            use_temporal: bool = False,
    ):
        super().__init__()

        self.dim = dim
        self.num_queries = num_latents
        self.num_frame = num_frame
        self.condition_dim = condition_dim
        self.use_temporal = use_temporal
        self.input_mask_mode = 'zero' # 'none' | 'zero' | 'gaussian' | 'learnable'

        self.goal_emb = nn.Sequential(
            nn.Linear(condition_dim, dim * 2),
            nn.GELU(),
            nn.Linear(dim * 2, dim)
        )
        # self.goal_emb = nn.Sequential(
        #     nn.Linear(condition_dim, dim),
        #     nn.LayerNorm(dim),
        # )
        frame_seq_len = num_latents // num_frame
        self.latents = nn.Parameter(torch.randn(self.num_frame, frame_seq_len, dim))  # type: ignore[reportPrivateUsage]
        self.time_pos_emb = nn.Parameter(torch.randn(num_time_embeds, 1, dim))  # type: ignore[reportPrivateUsage]
        attn_mask = torch.ones((num_frame, num_frame))
        #attn_mask = torch.tril(attn_mask).bool()

        self.layers = nn.ModuleList([])

        if self.use_temporal:
            for _ in range(depth):
                self.layers.append(
                    nn.ModuleList(
                        [
                            PerceiverAttentionLayer(dim=dim, dim_head=dim_head, heads=heads),
                            #TempAttentionLayer(dim=dim, dim_head=dim_head, heads=heads),
                            Attention(dim, num_heads=heads, qkv_bias=True, use_cross_attn=False,
                                      y_dim=512, attn_mask=attn_mask),
                            feed_forward_layer(dim=dim, mult=ff_mult, activation=activation),
                        ]
                    )
                )
        else:
            for _ in range(depth):
                self.layers.append(
                    nn.ModuleList(
                        [
                            PerceiverAttentionLayer(dim=dim, dim_head=dim_head, heads=heads),
                            feed_forward_layer(dim=dim, mult=ff_mult, activation=activation),
                        ]
                    )
                )

        # Layer normalization takes as input the query vector length
        self.norm = nn.LayerNorm(dim)

        self._update_trainable_state(trainable)

        # learnable frame token (used when input_mask_mode == 'learnable')
        if self.input_mask_mode == 'learnable':
            # shape: (1, 1, n_features, dim) after goal_emb
            self.learnable_mask_token = nn.Parameter(torch.zeros(1, 1, 1, dim))

    def _update_trainable_state(self, trainable: bool = True):
        for param in self.parameters():
            param.requires_grad = trainable

    def forward(self, x_f: torch.Tensor, mask: torch.BoolTensor = None, extra : torch.Tensor = None, frame_mask_prob: float = 0.0, language: torch.Tensor = None):
        """Run perceiver resampler on the input visual embeddings

        Args:
            x_f: Input visual embeddings of shape (batch_size, n_frames, n_features, d_visual)
            mask: Mask for the input visual embeddings of shape (batch_size, n_frames)
            extra: Extra tensor for concatenation
            frame_mask_prob: Probability of masking each frame during training (0.0 = no masking)
            language: Language embeddings of shape (batch_size, 1, lang_dim)

        Returns:
            Resampler features of shape (batch_size, num_queries, d_visual)
        """
        assert x_f.ndim == 4

        batch_size, max_length, _, dim = x_f.shape

        # Generate per-batch frame mask (True=keep, False=mask) with non-uniform probability centered at index 6
        frame_mask = None
        if frame_mask_prob > 0.0 and self.training:
            # per-frame mask probabilities p_i: highest at center_idx=6, decays with distance
            center_idx = 6 if max_length == 14 else (max_length // 2)
            frame_indices = torch.arange(max_length, device=x_f.device).float()
            distances = (frame_indices - float(center_idx)).abs()
            sigma = 2.0
            # Gaussian decay: p_i = frame_mask_prob * exp(-0.5 * (d/sigma)^2)
            per_frame_p = frame_mask_prob * torch.exp(-0.5 * (distances / sigma) ** 2)
            # broadcast to batch and sample Bernoulli per (b, t)
            rand_vals = torch.rand(batch_size, max_length, device=x_f.device)
            # True=keep, False=mask
            frame_mask = rand_vals > per_frame_p.unsqueeze(0)
            # ensure at least one frame kept per sample
            needs_fix = frame_mask.sum(dim=1) == 0
            if needs_fix.any():
                idx = torch.nonzero(needs_fix, as_tuple=False).squeeze(-1)
                rand_cols = torch.randint(0, max_length, (idx.numel(),), device=x_f.device)
                frame_mask[idx, rand_cols] = True

        # Mask the position embeddings for the padded frames
        time_pos_emb = (
            self.time_pos_emb[:max_length].unsqueeze(0).expand(batch_size, -1, -1, -1)
        )  # [batch_size, max_length, 1, dim]
        if mask is not None:
            time_pos_emb = time_pos_emb * mask.unsqueeze(-1).unsqueeze(-1)

        # Apply the position embeddings
        x_f = self.goal_emb(x_f)
        # Frame-level input masking before adding positional encoding
        if frame_mask is not None:
            bsz = batch_size
            T = max_length
            n_features = x_f.shape[2]
            d = x_f.shape[3]
            mask_expand = frame_mask.unsqueeze(-1).unsqueeze(-1).expand(bsz, T, n_features, d)
            if self.input_mask_mode == 'zero':
                x_f = torch.where(mask_expand, x_f, torch.zeros_like(x_f))
            elif self.input_mask_mode == 'gaussian':
                noise = torch.randn_like(x_f)
                x_f = torch.where(mask_expand, x_f, noise)
            elif self.input_mask_mode == 'learnable':
                token = self.learnable_mask_token
                token = token.expand(bsz, T, n_features, d)
                x_f = torch.where(mask_expand, x_f, token)
            # 'none' -> do nothing
        if extra is not None:
            extra = repeat(extra, 'b q d -> b T q d', T=max_length)
            x_f = torch.cat([x_f, extra],dim = 2)
        x_f = x_f + time_pos_emb

        # Flatten the frames
        x_f = rearrange(x_f, 'b T n d -> (b T) n d')

        # Copy the latents for every element in the batch
        x = repeat(self.latents, 'T q d -> b T q d', b=batch_size)
        x = rearrange(x, 'b T q d -> (b T) q d')

        # Apply attention and feed forward layer
        if self.use_temporal:
            for attn, Temp_attn, ffw in self.layers:
                x = x + attn(x_f, x)
                x = rearrange(x, '(b T) q d -> (b q) T d', b = batch_size)
                # build per-batch temporal attention mask if frame_mask is provided
                runtime_temporal_mask = None
                if frame_mask is not None:
                    # frame_mask: (b, T) True=keep, False=mask
                    keep = frame_mask  # (b, T)
                    # expand along batch for each latent query: current batch for attention is (b * q)
                    q_per_frame = x.shape[0] // batch_size
                    # construct (b, 1, 1, T) -> (b*q, 1, 1, T)
                    mask_bt = keep.unsqueeze(1).unsqueeze(2)  # (b,1,1,T)
                    runtime_temporal_mask = mask_bt.repeat_interleave(q_per_frame, dim=0)  # (b*q,1,1,T)
                    # convert to additive mask with 0 for keep and -inf for masked
                    runtime_temporal_mask = runtime_temporal_mask.to(x.dtype)
                    runtime_temporal_mask = torch.where(
                        runtime_temporal_mask > 0,
                        torch.zeros_like(runtime_temporal_mask),
                        torch.full_like(runtime_temporal_mask, -1e9)
                    )
                x = x + Temp_attn(x, attn_mask=runtime_temporal_mask)
                x = rearrange(x, '(b q) T d -> (b T) q d', b = batch_size)
                x = x + ffw(x)
        else:
            for attn, ffw in self.layers:
                x = x + attn(x_f, x)
                x = x + ffw(x)

        #x = rearrange(x, 'l q d -> b T q d', b=batch_size)
        x = x.reshape(batch_size, -1 ,x.shape[1],x.shape[2])
        x = rearrange(x, 'b T q d -> b (T q) d')
        assert x.shape == torch.Size([batch_size, self.num_queries, self.dim])
        norm = self.norm(x)

        return norm

class Video_Former_2D(nn.Module):
    """Perceiver Resampler with multi-head attention layer"""

    def __init__(
            self,
            dim: int,
            depth: int,
            condition_dim: int = 1280,
            dim_head: int = 64,
            heads: int = 8,
            num_latents: int = 64,
            num_frame: int = 16,
            num_time_embeds: int = 4,
            ff_mult: int = 4,
            activation: str = 'gelu',
            trainable: bool = True,
    ):
        super().__init__()

        self.dim = dim
        self.num_queries = num_latents
        self.num_frame = num_frame
        self.condition_dim = condition_dim

        self.goal_emb = nn.Sequential(
            nn.Linear(condition_dim, dim * 2),
            nn.GELU(),
            nn.Linear(dim * 2, dim)
        )
        seq_len = num_latents // num_frame
        self.latents = nn.Parameter(torch.randn(num_frame, seq_len, dim))  # type: ignore[reportPrivateUsage]
        self.time_pos_emb = nn.Parameter(torch.randn(num_time_embeds, 1, dim))  # type: ignore[reportPrivateUsage]

        self.layers = nn.ModuleList([])
        for _ in range(depth):
            self.layers.append(
                nn.ModuleList(
                    [
                        PerceiverAttentionLayer(dim=dim, dim_head=dim_head, heads=heads),
                        feed_forward_layer(dim=dim, mult=ff_mult, activation=activation),
                    ]
                )
            )

        # Layer normalization takes as input the query vector length
        self.norm = nn.LayerNorm(dim)

        self._update_trainable_state(trainable)

    def _update_trainable_state(self, trainable: bool = True):
        for param in self.parameters():
            param.requires_grad = trainable

    def forward(self, x_f: torch.Tensor, mask: torch.BoolTensor = None):
        """Run perceiver resampler on the input visual embeddings

        Args:
            x_f: Input visual embeddings of shape (batch_size, n_frames, n_features, d_visual)
            mask: Mask for the input visual embeddings of shape (batch_size, n_frames)

        Returns:
            Resampler features of shape (batch_size, num_queries, d_visual)
        """
        assert x_f.ndim == 4

        batch_size, max_length, _, dim = x_f.shape

        assert dim == self.condition_dim

        # Mask the position embeddings for the padded frames
        time_pos_emb = (
            self.time_pos_emb[:max_length].unsqueeze(0).expand(batch_size, -1, -1, -1)
        )  # [batch_size, max_length, 1, dim]
        if mask is not None:
            time_pos_emb = time_pos_emb * mask.unsqueeze(-1).unsqueeze(-1)

        # Apply the position embeddings
        x_f = self.goal_emb(x_f)
        x_f = x_f + time_pos_emb

        # Flatten the frames
        x_f = rearrange(x_f, 'b T n d -> (b T) n d')

        # Copy the latents for every element in the batch
        x = repeat(self.latents, 'T q d -> b T q d', b=batch_size)
        x = rearrange(x, 'b T q d -> (b T) q d')

        # Apply attention and feed forward layer
        for attn, ffw in self.layers:
            x = x + attn(x_f, x)
            x = x + ffw(x)

        #x = rearrange(x, 'l q d -> b T q d', b=batch_size)
        x = x.reshape(batch_size, -1 ,x.shape[1],x.shape[2])
        x = rearrange(x, 'b T q d -> b (T q) d')
        assert x.shape == torch.Size([batch_size, self.num_queries, self.dim])
        norm = self.norm(x)

        return norm



class Video_Former_3D_vggt(nn.Module):
    """Perceiver Resampler with multi-head attention layer"""

    def __init__(
            self,
            dim: int,
            depth: int,
            condition_dim: int = 1280,
            dim_head: int = 64,
            heads: int = 8,
            num_latents: int = 64,
            num_frame: int = 14,
            num_time_embeds: int = 4,
            ff_mult: int = 4,
            activation: str = 'gelu',
            trainable: bool = True,
            use_temporal: bool = False,
    ):
        super().__init__()

        self.dim = dim
        self.num_queries = num_latents
        self.num_frame = num_frame
        self.condition_dim = condition_dim
        self.use_temporal = use_temporal
        self.input_mask_mode = 'zero' # 'none' | 'zero' | 'gaussian' | 'learnable'

        self.goal_emb = nn.Sequential(
            nn.Linear(condition_dim, dim * 2),
            nn.GELU(),
            nn.Linear(dim * 2, dim)
        )
        frame_seq_len = num_latents // num_frame
        self.latents = nn.Parameter(torch.randn(self.num_frame, frame_seq_len, dim))  # type: ignore[reportPrivateUsage]
        self.time_pos_emb = nn.Parameter(torch.randn(num_time_embeds, 1, dim))  # type: ignore[reportPrivateUsage]
        attn_mask = torch.ones((num_frame, num_frame))
        attn_mask2 = torch.ones((256, 256))
        #attn_mask = torch.tril(attn_mask).bool()

        self.layers = nn.ModuleList([])

        self.vggt_emb = nn.Sequential(
            nn.Linear(dim, 2048),
            nn.GELU(),
            nn.Linear(2048, 2048)
        )


        self.spatial_attn = Attention(dim, num_heads=heads, qkv_bias=True, use_cross_attn=False,
                                y_dim=512, attn_mask=attn_mask2)
        self.temporal_attn = Attention(dim, num_heads=heads, qkv_bias=True, use_cross_attn=False,
                                y_dim=512, attn_mask=attn_mask)
        self.feature_ffw = feed_forward_layer(dim=dim, mult=ff_mult, activation=activation)

        if self.use_temporal:
            for _ in range(depth):
                self.layers.append(
                    nn.ModuleList(
                        [
                            PerceiverAttentionLayer(dim=dim, dim_head=dim_head, heads=heads),
                            Attention(dim, num_heads=heads, qkv_bias=True, use_cross_attn=False,
                                      y_dim=512, attn_mask=attn_mask),
                            feed_forward_layer(dim=dim, mult=ff_mult, activation=activation),
                        ]
                    )
                )
        else:
            for _ in range(depth):
                self.layers.append(
                    nn.ModuleList(
                        [
                            PerceiverAttentionLayer(dim=dim, dim_head=dim_head, heads=heads),
                            feed_forward_layer(dim=dim, mult=ff_mult, activation=activation),
                        ]
                    )
                )

        # Layer normalization takes as input the query vector length
        self.norm = nn.LayerNorm(dim)
        self.norm_g = nn.LayerNorm(dim)

        self._update_trainable_state(trainable)

        # learnable frame token (used when input_mask_mode == 'learnable')
        if self.input_mask_mode == 'learnable':
            # shape: (1, 1, n_features, dim) after goal_emb
            self.learnable_mask_token = nn.Parameter(torch.zeros(1, 1, 1, dim))

    def _update_trainable_state(self, trainable: bool = True):
        for param in self.parameters():
            param.requires_grad = trainable

    def forward(self, x_f: torch.Tensor, mask: torch.BoolTensor = None, extra : torch.Tensor = None, frame_mask_prob: float = 0.0, language: torch.Tensor = None):
        """Run perceiver resampler on the input visual embeddings
        Args:
            x_f: Input visual embeddings of shape (batch_size, n_frames, n_features, d_visual)
            mask: Mask for the input visual embeddings of shape (batch_size, n_frames)
            extra: Extra tensor for concatenation
        Returns:
            Resampler features of shape (batch_size, num_queries, d_visual)
        """
        assert x_f.ndim == 4

        batch_size, max_length, _, dim = x_f.shape

        # Mask the position embeddings for the padded frames
        time_pos_emb = (
            self.time_pos_emb[:max_length].unsqueeze(0).expand(batch_size, -1, -1, -1)
        )  # [batch_size, max_length, 1, dim]
        if mask is not None:
            time_pos_emb = time_pos_emb * mask.unsqueeze(-1).unsqueeze(-1)

        # Apply the position embeddings
        x_f = self.goal_emb(x_f)
        
        if extra is not None:
            extra = repeat(extra, 'b q d -> b T q d', T=max_length)
            x_f = torch.cat([x_f, extra],dim = 2)
        x_f = x_f + time_pos_emb

        # Flatten the frames
        x_f = rearrange(x_f, 'b T n d -> (b T) n d')

        # Copy the latents for every element in the batch
        x = repeat(self.latents, 'T q d -> b T q d', b=batch_size)
        x = rearrange(x, 'b T q d -> (b T) q d')

        x_g = x_f + self.spatial_attn(x_f)
        x_g = rearrange(x_g, '(b T) q d -> (b q) T d', b = batch_size)
        x_g = x_g + self.temporal_attn(x_g)
        x_g = rearrange(x_g, '(b q) T d -> (b T) q d', b = batch_size)
        x_g = x_g + self.feature_ffw(x_g)

        # x_f = torch.cat([x_f, x_g], dim = 1)
        x_f = x_g

        # Apply attention and feed forward layer
        for attn, Temp_attn, ffw in self.layers:
            x = x + attn(x_f, x)
            x = rearrange(x, '(b T) q d -> (b q) T d', b = batch_size)
            x = x + Temp_attn(x)
            x = rearrange(x, '(b q) T d -> (b T) q d', b = batch_size)
            x = x + ffw(x)

        #x = rearrange(x, 'l q d -> b T q d', b=batch_size)
        x = x.reshape(batch_size, -1 ,x.shape[1],x.shape[2])
        x = rearrange(x, 'b T q d -> b (T q) d')
        assert x.shape == torch.Size([batch_size, self.num_queries, self.dim])
        norm = self.norm(x)
        x_g = rearrange(x_g, '(b T) q d -> b T q d', b = batch_size)

        return norm, self.vggt_emb(self.norm_g(x_g))