File size: 22,432 Bytes
f7374e7
 
acfcecc
f7374e7
 
 
 
 
acfcecc
f7374e7
 
 
acfcecc
f7374e7
 
 
 
acfcecc
 
 
f7374e7
 
 
 
acfcecc
 
 
 
 
 
 
f7374e7
 
 
 
 
 
 
 
acfcecc
 
 
f7374e7
 
 
 
 
 
acfcecc
 
 
 
f7374e7
acfcecc
f7374e7
 
 
 
 
 
 
acfcecc
 
 
f7374e7
 
 
 
 
acfcecc
 
 
 
 
 
 
 
f7374e7
acfcecc
 
 
 
 
 
f7374e7
 
 
 
 
 
acfcecc
 
 
f7374e7
acfcecc
 
f7374e7
 
 
 
 
 
acfcecc
 
 
 
 
 
 
 
 
 
f7374e7
acfcecc
 
f7374e7
 
 
 
 
 
acfcecc
 
f7374e7
acfcecc
 
 
 
f7374e7
 
 
 
 
acfcecc
 
 
 
 
f7374e7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
acfcecc
f7374e7
acfcecc
 
 
 
 
 
 
 
 
 
 
f7374e7
acfcecc
f7374e7
 
 
 
 
 
 
 
 
 
acfcecc
f7374e7
 
acfcecc
 
 
f7374e7
 
acfcecc
f7374e7
 
acfcecc
 
 
f7374e7
acfcecc
f7374e7
 
 
 
acfcecc
 
 
f7374e7
 
 
 
 
 
 
acfcecc
 
 
 
 
 
 
f7374e7
 
 
 
 
 
 
 
acfcecc
 
f7374e7
 
 
 
 
 
 
 
 
acfcecc
f7374e7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
acfcecc
f7374e7
 
 
acfcecc
 
 
 
 
 
f7374e7
 
 
 
 
acfcecc
 
f7374e7
 
 
acfcecc
f7374e7
 
 
 
acfcecc
 
f7374e7
 
acfcecc
f7374e7
acfcecc
 
f7374e7
 
 
 
acfcecc
f7374e7
 
 
 
 
acfcecc
 
 
 
 
 
 
 
f7374e7
 
acfcecc
 
 
 
 
 
 
 
f7374e7
acfcecc
 
 
 
 
f7374e7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
acfcecc
f7374e7
 
acfcecc
 
 
 
 
 
f7374e7
acfcecc
 
 
 
 
 
 
 
 
f7374e7
acfcecc
 
f7374e7
 
 
 
 
acfcecc
 
f7374e7
acfcecc
f7374e7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
acfcecc
f7374e7
acfcecc
f7374e7
 
 
acfcecc
 
f7374e7
 
 
 
acfcecc
f7374e7
acfcecc
 
 
 
 
 
 
 
 
f7374e7
 
 
 
 
 
acfcecc
 
 
 
f7374e7
 
acfcecc
f7374e7
acfcecc
f7374e7
 
 
 
 
 
 
 
 
 
acfcecc
 
f7374e7
 
acfcecc
 
 
 
 
 
 
 
 
 
 
 
f7374e7
 
acfcecc
f7374e7
 
 
 
 
 
acfcecc
 
 
 
 
 
 
 
f7374e7
acfcecc
f7374e7
 
acfcecc
f7374e7
acfcecc
f7374e7
 
acfcecc
 
f7374e7
acfcecc
 
f7374e7
acfcecc
f7374e7
acfcecc
 
 
 
 
f7374e7
 
 
acfcecc
 
 
f7374e7
acfcecc
 
f7374e7
acfcecc
 
f7374e7
 
acfcecc
 
 
 
 
 
 
 
 
f7374e7
 
 
 
 
 
 
 
 
acfcecc
f7374e7
 
 
 
acfcecc
 
 
 
 
 
 
 
 
 
f7374e7
acfcecc
 
f7374e7
 
 
 
acfcecc
 
f7374e7
 
 
 
 
 
 
 
acfcecc
f7374e7
 
 
acfcecc
 
f7374e7
acfcecc
f7374e7
 
 
 
 
 
 
 
 
acfcecc
 
 
 
 
 
 
 
f7374e7
acfcecc
f7374e7
 
 
 
acfcecc
f7374e7
 
acfcecc
f7374e7
acfcecc
 
 
 
 
f7374e7
 
 
 
 
 
acfcecc
f7374e7
 
 
 
acfcecc
f7374e7
 
 
acfcecc
f7374e7
 
 
acfcecc
f7374e7
 
acfcecc
f7374e7
 
 
 
acfcecc
 
 
 
 
 
 
 
 
 
 
 
 
f7374e7
 
 
 
 
 
acfcecc
 
 
 
 
 
f7374e7
 
 
 
 
acfcecc
f7374e7
 
 
acfcecc
f7374e7
 
 
acfcecc
 
f7374e7
 
 
 
 
 
acfcecc
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
import os
import re
from typing import Iterable, List, Optional, Tuple

import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F

from muon import MuonWithAuxAdam
from vision import TextEmbeddingsNoAbsPos


# -------------------------
# Generic helpers
# -------------------------
def unwrap_model(model):
    """
    Return the underlying model when wrapped by DDP or similar wrappers.
    """
    return model.module if hasattr(model, "module") else model


def get_latest_checkpoint(ckpt_dir: str) -> Tuple[Optional[str], int]:
    """
    Find the latest checkpoint in a directory.

    Returns:
        (checkpoint_path, step)
        - (None, 0) if no checkpoint is found
    """
    if not os.path.exists(ckpt_dir):
        os.makedirs(ckpt_dir, exist_ok=True)
        return None, 0

    pt_files = [f for f in os.listdir(ckpt_dir) if f.endswith(".pt") and "step" in f]
    if not pt_files:
        return None, 0

    def extract_step(filename: str) -> int:
        match = re.search(r"step(\d+)", filename)
        return int(match.group(1)) if match else 0

    pt_files.sort(key=extract_step, reverse=True)
    latest = pt_files[0]
    return os.path.join(ckpt_dir, latest), extract_step(latest)


def set_seed(seed: int = 42):
    """
    Set random seeds for reproducibility.
    """
    import random

    torch.manual_seed(seed)
    random.seed(seed)
    np.random.seed(seed)
    torch.cuda.manual_seed_all(seed)


def l2norm(x: torch.Tensor, dim: int = -1, eps: float = 1e-12) -> torch.Tensor:
    """
    Apply L2 normalization along a given dimension.
    """
    return x / (x.norm(p=2, dim=dim, keepdim=True) + eps)


def interpolate_1d(x: torch.Tensor, target_dim: int) -> torch.Tensor:
    """
    Resize a 2D tensor along its feature dimension using 1D linear interpolation.

    Args:
        x: Tensor of shape (B, D)
        target_dim: Output feature dimension

    Returns:
        Tensor of shape (B, target_dim)
    """
    return F.interpolate(
        x.unsqueeze(1),
        size=target_dim,
        mode="linear",
        align_corners=False,
    ).squeeze(1)


# -------------------------
# Vision resize & rebuild (SigLIP v1 shell)
# -------------------------
def _size_config(vit_size: str):
    """
    Return model size configuration for SigLIP-style vision/text backbones.
    """
    size_map = {
        "small": {"layers": 12, "hidden": 396, "heads": 6},
        "base": {"layers": 12, "hidden": 792, "heads": 12},
        "large": {"layers": 24, "hidden": 1056, "heads": 16},
    }
    assert vit_size in size_map, f"vit_size must be one of {list(size_map.keys())}"
    return size_map[vit_size]


def resize_vit_and_rebuild_vision_v1(
    model,
    *,
    vit_size: str,
    patch_size,
    use_sdpa: bool = True,
    mlp_ratio: float = 4.0,
    image_size: int = 256,
    in_channels: int = 1,
):
    """
    Update vision_config values and rebuild vision_model (SigLIP v1 shell only).
    The text branch is left untouched.
    """
    cfg = _size_config(vit_size)

    vconf = model.config.vision_config
    tconf = model.config.text_config

    vconf.num_hidden_layers = int(cfg["layers"])
    vconf.hidden_size = int(cfg["hidden"])
    vconf.num_attention_heads = int(cfg["heads"])
    vconf.intermediate_size = int(vconf.hidden_size * mlp_ratio)
    vconf.image_size = image_size
    vconf.patch_size = patch_size
    vconf.num_channels = in_channels
    setattr(vconf, "_attn_implementation", "sdpa" if use_sdpa else "eager")

    head_dim = vconf.hidden_size // vconf.num_attention_heads
    assert head_dim % 2 == 0, f"head_dim must be even for RoPE, got {head_dim}"

    # Keep the text-side projection dimension unchanged
    if hasattr(tconf, "projection_size"):
        tconf.projection_size = getattr(tconf, "projection_size")
    if hasattr(tconf, "projection_dim"):
        tconf.projection_dim = getattr(tconf, "projection_dim")

    VisionCls = type(model.vision_model)
    model.vision_model = VisionCls(vconf)

    return {
        "layers": vconf.num_hidden_layers,
        "hidden": vconf.hidden_size,
        "heads": vconf.num_attention_heads,
        "head_dim": head_dim,
        "mlp": vconf.intermediate_size,
        "attn_impl": getattr(vconf, "_attn_implementation", "eager"),
        "image_size": vconf.image_size,
        "patch_size": vconf.patch_size,
        "in_channels": vconf.num_channels,
    }


# -------------------------
# 3D embeddings
# -------------------------
def inject_3d_embeddings(
    model,
    *,
    in_channels: int,
    embed_dim: int,
    patch_size,
    pos_embed_type: str,
):
    """
    Replace vision embeddings with the custom 3D embedding implementation.
    """
    from vision import SiglipVisionEmbeddings3D

    real = unwrap_model(model)
    real.vision_model.embeddings = SiglipVisionEmbeddings3D(
        in_channels=in_channels,
        embed_dim=embed_dim,
        patch_size=patch_size,
        pos_embed_type=pos_embed_type,
    )


# -------------------------
# Projection alignment (vision -> text)
# -------------------------
def _get_text_proj_dim(model) -> int:
    """
    Infer the text projection output dimension from the model or config.
    """
    if hasattr(model, "text_projection") and isinstance(model.text_projection, torch.nn.Parameter):
        return int(model.text_projection.shape[1])

    d = getattr(model.config, "projection_dim", None)
    if d is None and hasattr(model, "config") and hasattr(model.config, "text_config"):
        d = (
            getattr(model.config.text_config, "projection_size", None)
            or getattr(model.config.text_config, "projection_dim", None)
        )

    return int(d) if d is not None else 768


def _set_all_visual_proj_aliases(model, param: torch.nn.Parameter):
    """
    Register the same visual projection parameter under multiple common alias names.
    """
    setattr(model, "visual_projection", param)
    setattr(model, "vision_projection", param)
    setattr(model, "image_projection", param)


def align_siglip_projection_to_text(model, target_dim: int = None):
    """
    Align the visual projection matrix to the text-side projection dimension.

    Behavior:
    - Reuse an existing visual projection if its shape already matches
    - Otherwise create a new (hidden_vis, target_dim) parameter
    - Copy as many existing columns as possible from the old visual projection
    - Do not modify the text projection itself
    """
    real = unwrap_model(model)

    if target_dim is None:
        target_dim = _get_text_proj_dim(real)

    vconf = getattr(real.config, "vision_config", None)
    if vconf is None:
        return

    vis_in = int(vconf.hidden_size)

    device = next(real.parameters()).device
    dtype = next(real.parameters()).dtype

    for name in ("visual_projection", "vision_projection", "image_projection"):
        w = getattr(real, name, None)
        if isinstance(w, torch.nn.Parameter) and w.ndim == 2 and w.shape == (vis_in, target_dim):
            _set_all_visual_proj_aliases(real, w)

            if hasattr(real.config, "projection_dim"):
                real.config.projection_dim = target_dim
            if hasattr(real.config, "vision_config"):
                real.config.vision_config.projection_dim = target_dim
            if hasattr(real.config, "text_config"):
                if hasattr(real.config.text_config, "projection_size"):
                    real.config.text_config.projection_size = target_dim
                if hasattr(real.config.text_config, "projection_dim"):
                    real.config.text_config.projection_dim = target_dim
            return

    new_w = torch.empty(vis_in, target_dim, dtype=dtype, device=device)
    init_factor = getattr(real.config, "initializer_factor", 1.0)
    nn.init.normal_(new_w, std=0.02 * init_factor)

    for name in ("visual_projection", "vision_projection", "image_projection"):
        w = getattr(real, name, None)
        if isinstance(w, torch.nn.Parameter) and w.ndim == 2 and w.shape[0] == vis_in:
            with torch.no_grad():
                c = min(w.shape[1], target_dim)
                new_w[:, :c] = w.data.to(dtype=dtype, device=device)[:, :c]
                if c < target_dim:
                    nn.init.normal_(new_w[:, c:], std=0.02 * init_factor)
            break

    new_param = nn.Parameter(new_w, requires_grad=True)
    _set_all_visual_proj_aliases(real, new_param)

    if hasattr(real.config, "projection_dim"):
        real.config.projection_dim = target_dim
    if hasattr(real.config, "vision_config"):
        real.config.vision_config.projection_dim = target_dim
    if hasattr(real.config, "text_config"):
        if hasattr(real.config.text_config, "projection_size"):
            real.config.text_config.projection_size = target_dim
        if hasattr(real.config.text_config, "projection_dim"):
            real.config.text_config.projection_dim = target_dim


# -------------------------
# Text RoPE initialization (once)
# -------------------------
def init_text_rope_once(model, base: float = 10000.0, max_len: Optional[int] = None) -> bool:
    """
    Initialize text-side RoPE once.

    Steps:
    1. Replace text embeddings with a version without absolute position embedding
    2. Patch the text encoder self-attention with a generic RoPE wrapper
    3. Build shared 1D RoPE frequencies and assign them to all encoder layers
    """
    real = unwrap_model(model)

    txt = getattr(real, "text_model", None)
    if txt is None:
        raise ValueError("model.text_model was not found.")

    if not isinstance(txt.embeddings, TextEmbeddingsNoAbsPos):
        txt.embeddings = TextEmbeddingsNoAbsPos(txt.embeddings)

    from models.rope_generic import build_rope_packed as text_build_packed
    from models.rope_generic import patch_encoder_with_rope as patch_text_with_rope
    from models.rope_generic import set_shared_axial_freqs as text_set_shared_freqs

    enc = txt.encoder

    need_patch = False
    for lyr in enc.layers:
        if not hasattr(lyr.self_attn, "set_freqs"):
            need_patch = True
            break

    if need_patch:
        patch_text_with_rope(enc)

    if max_len is None:
        max_len = getattr(real.config.text_config, "max_position_embeddings", 16)

    head_dim = getattr(real.config.text_config, "hidden_size", 768) // getattr(
        real.config.text_config, "num_attention_heads", 12
    )
    assert head_dim % 2 == 0, f"text head_dim must be even for RoPE, got {head_dim}"

    freqs = text_build_packed(
        L=max_len,
        D=head_dim,
        base=base,
        device=next(real.parameters()).device,
        dtype=next(real.parameters()).dtype,
    )
    text_set_shared_freqs(enc, freqs)
    return True


def configure_text_pos_mode(
    model,
    *,
    mode: str,
    rope_base: float = 10000.0,
    max_seq_len: int = 16,
) -> dict:
    """
    Configure text-side positional encoding.

    Modes:
    - 'abs'  : keep the default absolute position embedding
    - 'rope' : remove absolute position embedding and initialize RoPE
    """
    real = unwrap_model(model)

    mode = str(mode).lower()
    if mode not in ("abs", "rope"):
        raise ValueError(f"text_pos_mode must be 'abs' or 'rope', got {mode}")

    if mode == "abs":
        return {"mode": "abs"}

    init_text_rope_once(real, base=rope_base, max_len=max_seq_len)
    return {"mode": "rope", "base": float(rope_base), "max_len": int(max_seq_len)}


# -------------------------
# Resize: rebuild text encoder
# -------------------------
def _size_config_text(text_size: str):
    """
    Return text model size configuration.
    Currently reuses the same size presets as the vision branch.
    """
    return _size_config(text_size)


def resize_text_and_rebuild_v1(
    model,
    *,
    text_size: str,
    use_sdpa: bool = True,
    mlp_ratio: float = 4.0,
    vocab_size: int = None,
    max_position_embeddings: int = 16,
):
    """
    Update text_config values and rebuild text_model (SigLIP v1 shell only).
    The vision branch is left untouched.
    """
    real = unwrap_model(model)
    cfg = _size_config_text(text_size)

    tconf = real.config.text_config
    tconf.num_hidden_layers = int(cfg["layers"])
    tconf.hidden_size = int(cfg["hidden"])
    tconf.num_attention_heads = int(cfg["heads"])
    tconf.intermediate_size = int(tconf.hidden_size * mlp_ratio)
    tconf.max_position_embeddings = int(max_position_embeddings)
    setattr(tconf, "_attn_implementation", "sdpa" if use_sdpa else "eager")

    if hasattr(tconf, "projection_size"):
        tconf.projection_size = tconf.hidden_size
    if hasattr(tconf, "projection_dim"):
        tconf.projection_dim = tconf.hidden_size

    if vocab_size is not None:
        tconf.vocab_size = int(vocab_size)

    TextCls = type(real.text_model)
    real.text_model = TextCls(tconf)

    head_dim = tconf.hidden_size // tconf.num_attention_heads
    assert head_dim % 2 == 0, f"[Text] head_dim must be even for RoPE, got {head_dim}"

    return {
        "layers": tconf.num_hidden_layers,
        "hidden": tconf.hidden_size,
        "heads": tconf.num_attention_heads,
        "head_dim": head_dim,
        "mlp": tconf.intermediate_size,
        "attn_impl": getattr(tconf, "_attn_implementation", "eager"),
        "vocab_size": getattr(tconf, "vocab_size", None),
        "max_pos": tconf.max_position_embeddings,
    }


# -------------------------
# Sanity check: no stray 768
# -------------------------
def assert_no_dim_768_left(model, expected_hidden: int):
    """
    Check whether there are still modules using 768 where expected_hidden should be used
    instead, such as Linear layers or LayerNorm dimensions.
    """
    real = unwrap_model(model)
    offenders = []

    def _check_module(prefix: str, module: nn.Module):
        nonlocal offenders

        if isinstance(module, nn.Linear):
            if module.in_features == 768 and module.in_features != expected_hidden:
                offenders.append(f"{prefix}.in={module.in_features} (Linear)")
            if module.out_features == 768 and module.out_features != expected_hidden:
                offenders.append(f"{prefix}.out={module.out_features} (Linear)")

        elif isinstance(module, nn.LayerNorm):
            if tuple(module.normalized_shape) == (768,) and 768 != expected_hidden:
                offenders.append(f"{prefix}.norm=768 (LayerNorm)")

    for name, mod in real.named_modules():
        _check_module(name, mod)

    if offenders:
        msg = (
            "Found 768-shaped leftovers in modules that should use hidden_size "
            f"{expected_hidden}:\n  - " + "\n  - ".join(offenders)
        )
        raise AssertionError(msg)


# -------------------------
# Metrics (first batch only)
# -------------------------
@torch.no_grad()
def compute_metrics(
    model,
    dataloader,
    tokenizer,
    device,
    max_txt_len: int = 16,
    log_to_wandb: bool = True,
    wandb_prefix: str = "eval",
    make_heatmap: bool = True,
    step=None,
):
    """
    Evaluate only the first batch from the dataloader using 1:1 image-text pairs.

    Behavior:
    - Uses SigLIP-style logits_per_image / logits_per_text directly
    - Computes i->t and t->i retrieval metrics:
        - Recall@K
        - MeanRank
        - Top1Acc
    - Optionally draws a row-wise softmax percentage heatmap for image->text

    Returns:
        A dictionary of evaluation metrics.
    """
    model.eval()

    try:
        batch = next(iter(dataloader))
    except StopIteration:
        return {"error": "empty dataloader"}

    images = batch["pixel_values"].to(device, non_blocking=True)
    texts = batch["text"]

    tokenized = tokenizer(
        texts,
        padding="max_length",
        truncation=True,
        max_length=max_txt_len,
        return_tensors="pt",
    )
    tokenized = {k: v.to(device, non_blocking=True) for k, v in tokenized.items()}

    outputs = model(
        input_ids=tokenized["input_ids"],
        pixel_values=images,
        return_dict=True,
    )

    sims_i2t = outputs.logits_per_image
    sims_t2i = outputs.logits_per_text

    batch_size = sims_i2t.size(0)
    idx = torch.arange(batch_size, device=sims_i2t.device)

    def recall_at_k(sim: torch.Tensor, k: int):
        k = min(k, sim.size(1))
        ranks = torch.argsort(sim, dim=1, descending=True)
        topk = ranks[:, :k]
        hits = (topk == idx.unsqueeze(1)).any(dim=1).float().mean().item()
        pos = (ranks == idx.unsqueeze(1)).nonzero(as_tuple=False)[:, 1]
        mean_rank = pos.float().mean().item() + 1.0
        return hits, mean_rank

    r1_i2t, mr_i2t = recall_at_k(sims_i2t, 1)
    r5_i2t, _ = recall_at_k(sims_i2t, 5)
    r10_i2t, _ = recall_at_k(sims_i2t, 10)

    r1_t2i, mr_t2i = recall_at_k(sims_t2i, 1)
    r5_t2i, _ = recall_at_k(sims_t2i, 5)
    r10_t2i, _ = recall_at_k(sims_t2i, 10)

    top1_i2t = float((sims_i2t.argmax(dim=1).cpu().numpy() == np.arange(batch_size)).mean())
    top1_t2i = float((sims_t2i.argmax(dim=1).cpu().numpy() == np.arange(batch_size)).mean())

    out = {
        "pairs_in_batch": int(batch_size),
        "i2t/R@1": r1_i2t,
        "i2t/R@5": r5_i2t,
        "i2t/R@10": r10_i2t,
        "i2t/MeanRank": mr_i2t,
        "t2i/R@1": r1_t2i,
        "t2i/R@5": r5_t2i,
        "t2i/R@10": r10_t2i,
        "t2i/MeanRank": mr_t2i,
        "i2t/Top1Acc": top1_i2t,
        "t2i/Top1Acc": top1_t2i,
    }

    if make_heatmap:
        try:
            import matplotlib.pyplot as plt

            with torch.no_grad():
                mat = sims_i2t.detach().float().cpu().numpy()
                mat = mat - mat.max(axis=1, keepdims=True)
                prob = np.exp(mat)
                prob /= prob.sum(axis=1, keepdims=True) + 1e-12

            fig, ax = plt.subplots(
                figsize=(min(12, batch_size * 0.3 + 2), min(12, batch_size * 0.3 + 2))
            )
            im = ax.imshow(prob, aspect="auto")

            ax.set_title(f"Image→Text softmax % (B={batch_size})")
            ax.set_xlabel("Text index")
            ax.set_ylabel("Image index")
            ax.set_xticks(range(batch_size))
            ax.set_yticks(range(batch_size))

            for i in range(batch_size):
                for j in range(batch_size):
                    p = int(round(prob[i, j] * 100))
                    txt = f"{p}%" if p >= 1 else "0%"
                    ax.text(j, i, txt, ha="center", va="center", fontsize=8)

            for i in range(batch_size):
                rect = plt.Rectangle((i - 0.5, i - 0.5), 1, 1, fill=False, linewidth=1.5)
                ax.add_patch(rect)

            fig.colorbar(im, ax=ax, fraction=0.046, pad=0.04)
            fig.tight_layout()

            if log_to_wandb:
                try:
                    import wandb

                    if wandb.run is not None:
                        wandb.log({f"{wandb_prefix}/batch_heatmap": wandb.Image(fig)}, step=step)
                except Exception as e:
                    print(f"[WARN] wandb heatmap logging failed: {e}")

            plt.close(fig)

        except Exception as e:
            print(f"[WARN] heatmap plotting failed: {e}")

    return out


# -------------------------
# Optimizer (Muon + Adam)
# -------------------------
def _split_params_by_dim(
    params: Iterable[torch.nn.Parameter],
) -> Tuple[List[torch.nn.Parameter], List[torch.nn.Parameter]]:
    """
    Split parameters into:
    - weights: ndim >= 2, typically sent to Muon
    - bias/norm: ndim < 2, typically sent to Adam
    """
    weights, bias_norm = [], []

    for p in params:
        if not p.requires_grad:
            continue
        (weights if p.ndim >= 2 else bias_norm).append(p)

    return weights, bias_norm


def build_optimizer_with_muon(model, lr: float, weight_decay: float):
    """
    Build a hybrid optimizer:
    - Muon for matrix/tensor weights
    - Adam-style auxiliary optimizer for bias, norm, projection, and temperature terms
    """
    real = unwrap_model(model)

    img_w, img_b = _split_params_by_dim(real.vision_model.parameters())
    txt_w, txt_b = _split_params_by_dim(real.text_model.parameters())

    extra = []

    if hasattr(real, "projection"):
        for p in real.projection.parameters():
            if p.requires_grad:
                extra.append(p)

    if hasattr(real, "visual_projection") and isinstance(real.visual_projection, torch.nn.Parameter):
        if real.visual_projection.requires_grad:
            extra.append(real.visual_projection)

    if hasattr(real, "text_projection") and isinstance(real.text_projection, torch.nn.Parameter):
        if real.text_projection.requires_grad:
            extra.append(real.text_projection)

    if hasattr(real, "logit_scale") and getattr(real.logit_scale, "requires_grad", False):
        extra.append(real.logit_scale)

    if hasattr(real, "logit_bias") and getattr(real.logit_bias, "requires_grad", False):
        extra.append(real.logit_bias)

    param_groups = [
        dict(
            params=[*img_w, *txt_w],
            use_muon=True,
            lr=lr,
            weight_decay=weight_decay,
        ),
        dict(
            params=[*img_b, *txt_b, *extra],
            use_muon=False,
            lr=lr,
            betas=(0.9, 0.95),
            weight_decay=weight_decay,
        ),
    ]
    return MuonWithAuxAdam(param_groups)


def swap_text_to_no_abs_pos(model) -> bool:
    """
    Replace text_model.embeddings with the no-absolute-position version.

    Behavior:
    - Automatically unwraps DDP-style wrappers
    - Returns False if the replacement has already been applied
    - Returns True if the replacement is performed
    """
    real = unwrap_model(model)

    txt = getattr(real, "text_model", None)
    if txt is None:
        raise ValueError("swap_text_to_no_abs_pos: model.text_model was not found.")

    emb = getattr(txt, "embeddings", None)
    if emb is None:
        raise ValueError("swap_text_to_no_abs_pos: text_model.embeddings was not found.")

    if TextEmbeddingsNoAbsPos is None:
        raise ImportError(
            "swap_text_to_no_abs_pos requires vision.TextEmbeddingsNoAbsPos. "
            "Please make sure it is defined in vision.py and importable."
        )

    if isinstance(emb, TextEmbeddingsNoAbsPos):
        return False

    txt.embeddings = TextEmbeddingsNoAbsPos(emb)
    return True