File size: 26,435 Bytes
3bad2ed
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""HuggingFace modeling code for the Mistral two-encoder contrastive model.

Self-contained (only depends on ``torch`` and ``transformers``) so it can be shipped
alongside the weights and loaded via ``trust_remote_code=True``.

The forward passes match the training implementation:

- RoPE uses the ``view_as_complex`` (interleaved adjacent-pair) convention.
- RMSNorm normalizes in fp32, casts back, then scales by ``weight``.
- SwiGLU FFN: ``down(silu(gate(x)) * up(x))``.
- Text tower: causal attention, final RMSNorm, EOS-token pooling, linear projection.
- Vision tower: bidirectional 2D-RoPE ViT, ``pre_mm_projector_norm``, 2x2 patch merge,
  ``contrastive_pre_norm``, ``amax`` over merged tokens, linear projection.
- Video path: the same per-frame ViT and patch merge, followed by post-ViT joint 3D
  attention with rotate-half RoPE, then ``amax`` across the entire clip.

Text, image and video embeddings are L2-normalized in float32, even when the encoder
weights use bfloat16.
"""

from collections import OrderedDict
from dataclasses import dataclass
from typing import ClassVar

import torch
import torch.nn.functional as F
from torch import nn
from transformers.modeling_utils import PreTrainedModel
from transformers.utils.generic import ModelOutput

from .configuration_mistral_contrastive import MistralContrastiveConfig

try:
    # Best packed kernel where available: the one used in training, and fp32-capable.
    # If xformers is not installed, fall back to flash-attn / dense below.
    from xformers.ops import memory_efficient_attention as _xops_mea
    from xformers.ops.fmha.attn_bias import BlockDiagonalMask as _BlockDiagonalMask
except ImportError:  # pragma: no cover - xformers is an optional accelerator
    _xops_mea = None
    _BlockDiagonalMask = None

try:
    # Optional accelerator; fp16/bf16 only.
    from flash_attn import flash_attn_varlen_func as _flash_attn_varlen_func
except ImportError:  # pragma: no cover - flash-attn is an optional accelerator
    _flash_attn_varlen_func = None


def _packed_attention(q: torch.Tensor, k: torch.Tensor, v: torch.Tensor, seqlens: list[int]) -> torch.Tensor:
    """Block-diagonal attention over concatenated variable-length images.

    q/k/v are (1, total_tokens, n_heads, head_dim); each image attends only to its
    own patches. Tries, in order: xformers ``BlockDiagonalMask`` (matches training,
    fp32-capable) -> flash-attn varlen (fp16/bf16) -> dense
    SDPA block-diagonal mask (always correct, fp32/CPU-safe, O(total^2)).
    """
    if _xops_mea is not None and _BlockDiagonalMask is not None:
        try:
            attn_bias = _BlockDiagonalMask.from_seqlens(seqlens)
            return _xops_mea(q, k, v, attn_bias=attn_bias)  # (1, total, n_heads, head_dim)
        except (NotImplementedError, RuntimeError):
            pass  # no kernel for this config (CPU / fp32 on some GPUs / head_dim<32)

    if _flash_attn_varlen_func is not None and q.dtype in (torch.float16, torch.bfloat16):
        seqlens_t = torch.tensor(seqlens, dtype=torch.int32, device=q.device)
        cu_seqlens = F.pad(seqlens_t.cumsum(0, dtype=torch.int32), (1, 0))
        max_seqlen = int(seqlens_t.max())
        out = _flash_attn_varlen_func(
            q[0], k[0], v[0], cu_seqlens, cu_seqlens, max_seqlen, max_seqlen, dropout_p=0.0, causal=False
        )
        return out.unsqueeze(0)  # (1, total, n_heads, head_dim)

    seg = torch.repeat_interleave(
        torch.arange(len(seqlens), device=q.device),
        torch.tensor(seqlens, device=q.device),
    )
    block_mask = (seg[:, None] == seg[None, :])[None, None]  # (1, 1, total, total)
    qh, kh, vh = (t.transpose(1, 2) for t in (q, k, v))  # (1, n_heads, total, head_dim)
    out = F.scaled_dot_product_attention(qh, kh, vh, attn_mask=block_mask)
    return out.transpose(1, 2)  # (1, total, n_heads, head_dim)


def precompute_freqs_cis_1d(dim: int, end: int, theta: float, device: torch.device) -> torch.Tensor:
    """1D RoPE frequencies, shape (end, dim // 2), complex64."""
    freqs = 1.0 / (theta ** (torch.arange(0, dim, 2, device=device, dtype=torch.float32) / dim))
    t = torch.arange(end, device=device, dtype=torch.float32)
    freqs = torch.outer(t, freqs)
    return torch.polar(torch.ones_like(freqs), freqs)


def precompute_freqs_cis_2d(dim: int, height: int, width: int, theta: float, device: torch.device) -> torch.Tensor:
    """2D RoPE frequencies flattened to (height * width, dim // 2), complex64.

    The first ``dim // 4`` frequencies index the height axis, the next ``dim // 4``
    index the width axis. Tokens are ordered row-major (height outer, width inner),
    matching the patch-conv ``flatten(2)`` order.
    """
    freqs = 1.0 / (theta ** (torch.arange(0, dim, 2, device=device, dtype=torch.float32) / dim))
    h = torch.arange(height, device=device, dtype=torch.float32)
    w = torch.arange(width, device=device, dtype=torch.float32)
    freqs_h = torch.outer(h, freqs[::2])
    freqs_w = torch.outer(w, freqs[1::2])
    freqs_2d = torch.cat(
        [
            freqs_h[:, None, :].repeat(1, width, 1),
            freqs_w[None, :, :].repeat(height, 1, 1),
        ],
        dim=-1,
    )
    freqs_cis = torch.polar(torch.ones_like(freqs_2d), freqs_2d)
    return freqs_cis.reshape(height * width, dim // 2)


def apply_rotary_emb(x: torch.Tensor, freqs_cis: torch.Tensor) -> torch.Tensor:
    """Apply RoPE to a (batch, seq, n_heads, head_dim) tensor. ``freqs_cis`` is (seq, head_dim // 2)."""
    x_ = torch.view_as_complex(x.float().reshape(*x.shape[:-1], x.shape[-1] // 2, 2))
    freqs_cis = freqs_cis.view(1, x.shape[1], 1, x.shape[-1] // 2)
    x_out = torch.view_as_real(x_ * freqs_cis).flatten(3)
    return x_out.type_as(x)


def precompute_temporal_rope3d(
    n_frames: int,
    grid_h: int,
    grid_w: int,
    head_dim: int,
    theta: float,
    device: torch.device,
) -> tuple[torch.Tensor, torch.Tensor]:
    """Match the post-merge, rotate-half 3D RoPE used by TemporalTokenEncoder."""
    half = head_dim // 2
    n_h = half // 3
    n_w = half // 3
    n_t = half - n_h - n_w
    n_patches = grid_h * grid_w
    patch_index = torch.arange(n_patches, device=device)
    t_pos = torch.arange(n_frames, device=device).repeat_interleave(n_patches)
    h_pos = (patch_index // grid_w).repeat(n_frames)
    w_pos = (patch_index % grid_w).repeat(n_frames)

    def angles(positions: torch.Tensor, n_freqs: int) -> torch.Tensor:
        freqs = theta ** (-torch.arange(n_freqs, device=device, dtype=torch.float32) / max(n_freqs, 1))
        return positions.float()[:, None] * freqs

    phases = torch.cat([angles(t_pos, n_t), angles(h_pos, n_h), angles(w_pos, n_w)], dim=-1)
    return phases.cos()[None, None], phases.sin()[None, None]


def apply_temporal_rope(x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor) -> torch.Tensor:
    """The temporal encoder rotates the first and second halves of each head."""
    half = x.shape[-1] // 2
    first, second = x[..., :half], x[..., half:]
    cos, sin = cos.to(x.dtype), sin.to(x.dtype)
    return torch.cat([first * cos - second * sin, first * sin + second * cos], dim=-1)


class RMSNorm(nn.Module):
    def __init__(self, dim: int, eps: float) -> None:
        super().__init__()
        self.eps = eps
        self.weight = nn.Parameter(torch.ones(dim))

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        # Same fp32 math as the reference implementation; F.rms_norm runs it as one fused kernel, which makes
        # eager (uncompiled) video encoding ~1.4x faster on GPU.
        if hasattr(F, "rms_norm"):  # torch >= 2.4
            output = F.rms_norm(x.float(), (x.shape[-1],), eps=self.eps).type_as(x)
        else:
            x_float = x.float()
            output = (x_float * torch.rsqrt(x_float.pow(2).mean(-1, keepdim=True) + self.eps)).type_as(x)
        return output * self.weight


class SwiGLUMLP(nn.Module):
    def __init__(self, dim: int, hidden_dim: int) -> None:
        super().__init__()
        self.gate_proj = nn.Linear(dim, hidden_dim, bias=False)  # w1
        self.up_proj = nn.Linear(dim, hidden_dim, bias=False)  # w3
        self.down_proj = nn.Linear(hidden_dim, dim, bias=False)  # w2

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        return self.down_proj(F.silu(self.gate_proj(x)) * self.up_proj(x))


class Attention(nn.Module):
    def __init__(self, dim: int, n_heads: int, head_dim: int) -> None:
        super().__init__()
        self.n_heads = n_heads
        self.head_dim = head_dim
        self.q_proj = nn.Linear(dim, n_heads * head_dim, bias=False)
        self.k_proj = nn.Linear(dim, n_heads * head_dim, bias=False)
        self.v_proj = nn.Linear(dim, n_heads * head_dim, bias=False)
        self.o_proj = nn.Linear(n_heads * head_dim, dim, bias=False)

    def forward(
        self,
        x: torch.Tensor,
        freqs_cis: torch.Tensor,
        is_causal: bool,
        attn_mask: torch.Tensor | None = None,
        seqlens: list[int] | None = None,
    ) -> torch.Tensor:
        bsz, seqlen, _ = x.shape
        q = self.q_proj(x).view(bsz, seqlen, self.n_heads, self.head_dim)
        k = self.k_proj(x).view(bsz, seqlen, self.n_heads, self.head_dim)
        v = self.v_proj(x).view(bsz, seqlen, self.n_heads, self.head_dim)

        q = apply_rotary_emb(q, freqs_cis)
        k = apply_rotary_emb(k, freqs_cis)

        if seqlens is not None:
            # Packed variable-length images (bsz == 1): block-diagonal attention.
            assert bsz == 1, "packed mode expects bsz==1"
            out = _packed_attention(q, k, v, seqlens)  # (1, total, n_heads, head_dim)
            out = out.reshape(bsz, seqlen, self.n_heads * self.head_dim)
            return self.o_proj(out)

        q = q.transpose(1, 2)
        k = k.transpose(1, 2)
        v = v.transpose(1, 2)

        # sdpa does not allow both is_causal and an explicit mask; an explicit mask
        # (used when padding is present) already encodes causality.
        out = F.scaled_dot_product_attention(q, k, v, attn_mask=attn_mask, is_causal=is_causal and attn_mask is None)
        out = out.transpose(1, 2).reshape(bsz, seqlen, self.n_heads * self.head_dim)
        return self.o_proj(out)


class TransformerBlock(nn.Module):
    def __init__(self, dim: int, n_heads: int, head_dim: int, hidden_dim: int, eps: float) -> None:
        super().__init__()
        self.input_layernorm = RMSNorm(dim, eps)
        self.self_attn = Attention(dim, n_heads, head_dim)
        self.post_attention_layernorm = RMSNorm(dim, eps)
        self.mlp = SwiGLUMLP(dim, hidden_dim)

    def forward(
        self,
        x: torch.Tensor,
        freqs_cis: torch.Tensor,
        is_causal: bool,
        attn_mask: torch.Tensor | None = None,
        seqlens: list[int] | None = None,
    ) -> torch.Tensor:
        x = x + self.self_attn(self.input_layernorm(x), freqs_cis, is_causal, attn_mask, seqlens)
        x = x + self.mlp(self.post_attention_layernorm(x))
        return x


class TemporalAttentionBlock(nn.Module):
    def __init__(self, dim: int, n_heads: int, mlp_ratio: float) -> None:
        super().__init__()
        self.n_heads = n_heads
        self.head_dim = dim // n_heads
        mlp_dim = int(dim * mlp_ratio)
        self.norm1 = nn.LayerNorm(dim)
        self.q_proj = nn.Linear(dim, dim)
        self.k_proj = nn.Linear(dim, dim)
        self.v_proj = nn.Linear(dim, dim)
        self.out_proj = nn.Linear(dim, dim)
        self.norm2 = nn.LayerNorm(dim)
        self.mlp = nn.Sequential(
            OrderedDict(
                [
                    ("c_fc", nn.Linear(dim, mlp_dim)),
                    ("gelu", nn.GELU()),
                    ("c_proj", nn.Linear(mlp_dim, dim)),
                ]
            )
        )

    def forward(self, x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor) -> torch.Tensor:
        bsz, seqlen, dim = x.shape
        h = self.norm1(x)

        def heads(proj: nn.Linear) -> torch.Tensor:
            return proj(h).view(bsz, seqlen, self.n_heads, self.head_dim).transpose(1, 2)

        q = apply_temporal_rope(heads(self.q_proj), cos, sin)
        k = apply_temporal_rope(heads(self.k_proj), cos, sin)
        v = heads(self.v_proj)
        attn = F.scaled_dot_product_attention(q, k, v)
        x = x + self.out_proj(attn.transpose(1, 2).reshape(bsz, seqlen, dim))
        return x + self.mlp(self.norm2(x))


class TemporalTokenEncoder(nn.Module):
    def __init__(self, config: MistralContrastiveConfig) -> None:
        super().__init__()
        assert config.vision_dim % config.temporal_num_attention_heads == 0, (
            "Vision dimension must be divisible by temporal attention heads"
        )
        self.head_dim = config.vision_dim // config.temporal_num_attention_heads
        assert self.head_dim % 2 == 0, f"Expected even temporal head dim, got {self.head_dim}"
        self.rope_theta = config.temporal_rope_theta
        self.blocks = nn.ModuleList(
            TemporalAttentionBlock(
                config.vision_dim,
                config.temporal_num_attention_heads,
                config.temporal_mlp_ratio,
            )
            for _ in range(config.temporal_num_hidden_layers)
        )
        self.norm = nn.LayerNorm(config.vision_dim)

    def forward(self, x: torch.Tensor, grid_h: int, grid_w: int) -> torch.Tensor:
        n_frames, n_patches, dim = x.shape
        assert n_frames > 0, "A video must contain at least one frame"
        assert grid_h * grid_w == n_patches, f"Post-merge grid {grid_h}x{grid_w} does not match {n_patches} tokens"
        cos, sin = precompute_temporal_rope3d(n_frames, grid_h, grid_w, self.head_dim, self.rope_theta, x.device)
        sequence = x.reshape(1, n_frames * n_patches, dim)
        for block in self.blocks:
            sequence = block(sequence, cos, sin)
        return self.norm(sequence).reshape(n_frames * n_patches, dim)


class MistralContrastiveTextModel(nn.Module):
    def __init__(self, config: MistralContrastiveConfig) -> None:
        super().__init__()
        self.config = config
        assert config.eos_token_id is not None, "eos_token_id is required for EOS pooling"
        self.eos_token_id: int = config.eos_token_id
        self.head_dim: int = config.text_head_dim
        self.rope_theta: float = config.text_rope_theta

        self.embed_tokens = nn.Embedding(config.text_vocab_size, config.text_dim)
        self.layers = nn.ModuleList(
            TransformerBlock(
                config.text_dim,
                config.text_num_attention_heads,
                config.text_head_dim,
                config.text_intermediate_size,
                config.text_norm_eps,
            )
            for _ in range(config.text_num_hidden_layers)
        )
        self.norm = RMSNorm(config.text_dim, config.text_norm_eps)
        self.text_projection = nn.Linear(config.text_dim, config.projection_dim, bias=False)

    def forward(
        self,
        input_ids: torch.Tensor,
        attention_mask: torch.Tensor | None = None,
        *,
        normalize: bool = True,
    ) -> torch.Tensor:
        bsz, seqlen = input_ids.shape
        x = self.embed_tokens(input_ids)
        freqs_cis = precompute_freqs_cis_1d(self.head_dim, seqlen, self.rope_theta, x.device)

        attn_mask: torch.Tensor | None = None
        if attention_mask is not None:
            causal = torch.tril(torch.ones(seqlen, seqlen, dtype=torch.bool, device=x.device))
            key_pad = attention_mask.to(torch.bool)[:, None, None, :]
            attn_mask = causal[None, None, :, :] & key_pad

        for layer in self.layers:
            x = layer(x, freqs_cis, is_causal=True, attn_mask=attn_mask)

        x = self.norm(x)

        # EOS pooling: take the hidden state at the first eos token of each row.
        matches = input_ids == self.eos_token_id
        # Checked on device (no host sync), so the check does not break torch.compile graphs.
        torch._assert_async(
            matches.any(dim=-1).all(), f"every row must contain eos_token_id={self.eos_token_id} for EOS pooling"
        )
        eos_idx = matches.int().argmax(dim=-1)
        pooled = x[torch.arange(bsz, device=x.device), eos_idx]

        embeds = self.text_projection(pooled)
        if not normalize:
            return embeds
        return F.normalize(embeds.float(), p=2, dim=-1)


class PatchMerger(nn.Module):
    def __init__(self, dim: int, spatial_merge_size: int) -> None:
        super().__init__()
        self.spatial_merge_size = spatial_merge_size
        self.merging_layer = nn.Linear(dim * spatial_merge_size**2, dim, bias=False)

    def forward(self, x: torch.Tensor, grid_h: int, grid_w: int) -> torch.Tensor:
        """x: (batch, grid_h * grid_w, dim) -> (batch, merged_tokens, dim)."""
        bsz, _, dim = x.shape
        s = self.spatial_merge_size
        img = x.view(bsz, grid_h, grid_w, dim).permute(0, 3, 1, 2)  # (B, dim, H, W)
        # F.unfold channel order is (dim, kh, kw) flattened as dim*kh*kw, which matches
        # the patch-merge ordering used in training.
        unfolded = F.unfold(img, kernel_size=s, stride=s)  # (B, dim * s * s, L)
        unfolded = unfolded.transpose(1, 2)  # (B, L, dim * s * s)
        return self.merging_layer(unfolded)


class MistralContrastiveVisionModel(nn.Module):
    def __init__(self, config: MistralContrastiveConfig) -> None:
        super().__init__()
        self.config = config
        self.patch_size: int = config.patch_size
        self.head_dim: int = config.vision_head_dim
        self.rope_theta: float = config.vision_rope_theta
        self.spatial_merge_size: int = config.spatial_merge_size

        self.patch_conv = nn.Conv2d(
            config.num_channels,
            config.vision_dim,
            kernel_size=config.patch_size,
            stride=config.patch_size,
            bias=False,
        )
        self.ln_pre: nn.Module = RMSNorm(config.vision_dim, config.vision_norm_eps) if config.ln_pre else nn.Identity()
        self.layers = nn.ModuleList(
            TransformerBlock(
                config.vision_dim,
                config.vision_num_attention_heads,
                config.vision_head_dim,
                config.vision_intermediate_size,
                config.vision_norm_eps,
            )
            for _ in range(config.vision_num_hidden_layers)
        )
        self.pre_mm_projector_norm = RMSNorm(config.vision_dim, config.vision_norm_eps)
        self.patch_merger = PatchMerger(config.vision_dim, config.spatial_merge_size)
        self.contrastive_pre_norm = RMSNorm(config.vision_dim, config.vision_norm_eps)
        self.visual_projection = nn.Linear(config.vision_dim, config.projection_dim, bias=False)

    def encode_patches(self, pixel_values: torch.Tensor) -> tuple[torch.Tensor, int, int]:
        x = self.patch_conv(pixel_values)  # (B, dim, gh, gw)
        grid_h, grid_w = x.shape[-2], x.shape[-1]
        x = x.flatten(2).transpose(1, 2)  # (B, gh * gw, dim)
        x = self.ln_pre(x)

        freqs_cis = precompute_freqs_cis_2d(self.head_dim, grid_h, grid_w, self.rope_theta, x.device)
        for layer in self.layers:
            x = layer(x, freqs_cis, is_causal=False)

        x = self.pre_mm_projector_norm(x)
        x = self.patch_merger(x, grid_h, grid_w)
        return x, grid_h // self.spatial_merge_size, grid_w // self.spatial_merge_size

    def forward(self, pixel_values: torch.Tensor) -> torch.Tensor:
        x, _, _ = self.encode_patches(pixel_values)
        x = self.contrastive_pre_norm(x)
        x = x.amax(dim=1)  # amax pooling over the merged tokens

        embeds = self.visual_projection(x)
        return F.normalize(embeds.float(), p=2, dim=-1)

    def forward_packed(self, images: list[torch.Tensor]) -> torch.Tensor:
        """Encode variable-resolution images without padding (e.g. keep_ratio).

        Each image attends only to its own patches (block-diagonal attention, as in the
        packed-sequence vision encoder used in training). Images with the same patch grid are therefore batched
        together and run through the dense path, which is the same computation without a variable-length
        attention kernel, so the whole encoder compiles without graph breaks. Embeddings are returned in
        input order. Every image's height/width must be a multiple of ``patch_size * spatial_merge_size``.
        """
        assert len(images) > 0, "forward_packed requires at least one image"
        images = [img.unsqueeze(0) if img.dim() == 3 else img for img in images]  # each (1, 3, H, W)
        groups: dict[tuple[int, int], list[int]] = {}
        for i, img in enumerate(images):
            groups.setdefault((img.shape[-2], img.shape[-1]), []).append(i)

        embeds: list[torch.Tensor | None] = [None] * len(images)
        for idx in groups.values():
            x, _, _ = self.encode_patches(torch.cat([images[i] for i in idx], dim=0))  # (n, merged, dim)
            x = self.contrastive_pre_norm(x).amax(dim=1)
            for i, e in zip(idx, self.visual_projection(x).unbind(0), strict=True):
                embeds[i] = e
        return F.normalize(torch.stack(embeds).float(), p=2, dim=-1)


@dataclass
class MistralContrastiveOutput(ModelOutput):
    logits_per_image: torch.Tensor | None = None
    logits_per_text: torch.Tensor | None = None
    image_embeds: torch.Tensor | None = None
    logits_per_video: torch.Tensor | None = None
    video_embeds: torch.Tensor | None = None
    text_embeds: torch.Tensor | None = None


class MistralContrastiveModel(PreTrainedModel):
    config_class = MistralContrastiveConfig
    base_model_prefix = "mistral_contrastive"
    main_input_name = "pixel_values"
    _no_split_modules: ClassVar[list[str]] = ["TransformerBlock"]
    supports_gradient_checkpointing = False

    def __init__(self, config: MistralContrastiveConfig) -> None:
        super().__init__(config)
        self.text_model = MistralContrastiveTextModel(config)
        self.vision_model = MistralContrastiveVisionModel(config)
        self.temporal_encoder = TemporalTokenEncoder(config) if config.temporal_num_hidden_layers > 0 else None
        self.logit_scale = nn.Parameter(torch.tensor([config.logit_scale_init], dtype=torch.float32))
        self.post_init()

    def _init_weights(self, module: nn.Module) -> None:
        if isinstance(module, (nn.Linear, nn.Conv2d)):
            module.weight.data.normal_(mean=0.0, std=0.02)
            bias = getattr(module, "bias", None)
            if bias is not None:
                bias.data.zero_()
        elif isinstance(module, nn.Embedding):
            module.weight.data.normal_(mean=0.0, std=0.02)
        elif isinstance(module, RMSNorm):
            module.weight.data.fill_(1.0)

    def get_text_features(
        self,
        input_ids: torch.Tensor,
        attention_mask: torch.Tensor | None = None,
        *,
        normalize: bool = True,
    ) -> torch.Tensor:
        # Class prototypes in the native zero-shot evaluator average raw prompt
        # projections before their final L2 normalization.
        return self.text_model(input_ids, attention_mask, normalize=normalize)

    def get_image_features(self, pixel_values: torch.Tensor | list[torch.Tensor]) -> torch.Tensor:
        # A list of (3, H, W) tensors -> packed variable-resolution path (keep_ratio).
        # A single (B, 3, H, W) tensor -> dense path (squash / center_crop).
        if isinstance(pixel_values, (list, tuple)):
            return self.vision_model.forward_packed(list(pixel_values))
        return self.vision_model(pixel_values)

    def get_video_features(self, videos: torch.Tensor | list[torch.Tensor]) -> torch.Tensor:
        """Encode (B,T,C,H,W) or a list of (T,C,H,W) clips, one embedding per clip."""
        assert self.temporal_encoder is not None, (
            "This checkpoint has no temporal encoder; video features are unavailable"
        )
        clips = list(videos) if isinstance(videos, (list, tuple)) else list(videos.unbind(0))
        assert len(clips) > 0, "get_video_features requires at least one video"
        embeddings = []
        for frames in clips:
            assert frames.ndim == 4 and frames.shape[0] > 0, (
                f"Each video must have shape (T,C,H,W) with T>0, got {tuple(frames.shape)}"
            )
            x, grid_h, grid_w = self.vision_model.encode_patches(frames)
            x = self.temporal_encoder(x, grid_h, grid_w)
            x = self.vision_model.contrastive_pre_norm(x)
            pooled = x.amax(dim=0)
            embeddings.append(self.vision_model.visual_projection(pooled))
        return F.normalize(torch.stack(embeddings).float(), p=2, dim=-1)

    def forward(
        self,
        input_ids: torch.Tensor | None = None,
        pixel_values: torch.Tensor | list[torch.Tensor] | None = None,
        attention_mask: torch.Tensor | None = None,
        video_pixel_values: torch.Tensor | list[torch.Tensor] | None = None,
    ) -> MistralContrastiveOutput:
        assert input_ids is not None, "MistralContrastiveModel.forward requires input_ids"
        assert (pixel_values is None) != (video_pixel_values is None), (
            "Pass exactly one of pixel_values or video_pixel_values"
        )
        text_embeds = self.get_text_features(input_ids, attention_mask)
        if video_pixel_values is not None:
            video_embeds = self.get_video_features(video_pixel_values)
            logits_per_text = self.logit_scale.float().exp() * (text_embeds.float() @ video_embeds.float().t())
            return MistralContrastiveOutput(
                logits_per_text=logits_per_text,
                logits_per_video=logits_per_text.t(),
                video_embeds=video_embeds,
                text_embeds=text_embeds,
            )

        assert pixel_values is not None
        image_embeds = self.get_image_features(pixel_values)
        logits_per_text = self.logit_scale.float().exp() * (text_embeds.float() @ image_embeds.float().t())
        return MistralContrastiveOutput(
            logits_per_image=logits_per_text.t(),
            logits_per_text=logits_per_text,
            image_embeds=image_embeds,
            text_embeds=text_embeds,
        )


MistralContrastiveConfig.register_for_auto_class()
MistralContrastiveModel.register_for_auto_class("AutoModel")

__all__ = ["MistralContrastiveModel", "MistralContrastiveOutput"]