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