Update utils_v2.py
Browse files- utils_v2.py +295 -431
utils_v2.py
CHANGED
|
@@ -1,23 +1,34 @@
|
|
| 1 |
import os
|
| 2 |
import re
|
| 3 |
-
from typing import Iterable,
|
| 4 |
|
| 5 |
import numpy as np
|
| 6 |
import torch
|
| 7 |
import torch.nn as nn
|
| 8 |
import torch.nn.functional as F
|
| 9 |
-
|
| 10 |
from muon import MuonWithAuxAdam
|
| 11 |
from vision import TextEmbeddingsNoAbsPos
|
| 12 |
|
|
|
|
| 13 |
# -------------------------
|
| 14 |
# Generic helpers
|
| 15 |
# -------------------------
|
| 16 |
def unwrap_model(model):
|
|
|
|
|
|
|
|
|
|
| 17 |
return model.module if hasattr(model, "module") else model
|
| 18 |
|
| 19 |
|
| 20 |
def get_latest_checkpoint(ckpt_dir: str) -> Tuple[Optional[str], int]:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 21 |
if not os.path.exists(ckpt_dir):
|
| 22 |
os.makedirs(ckpt_dir, exist_ok=True)
|
| 23 |
return None, 0
|
|
@@ -26,17 +37,21 @@ def get_latest_checkpoint(ckpt_dir: str) -> Tuple[Optional[str], int]:
|
|
| 26 |
if not pt_files:
|
| 27 |
return None, 0
|
| 28 |
|
| 29 |
-
def extract_step(
|
| 30 |
-
|
| 31 |
-
return int(
|
| 32 |
|
| 33 |
pt_files.sort(key=extract_step, reverse=True)
|
| 34 |
latest = pt_files[0]
|
| 35 |
return os.path.join(ckpt_dir, latest), extract_step(latest)
|
| 36 |
|
| 37 |
|
| 38 |
-
def set_seed(seed=42):
|
|
|
|
|
|
|
|
|
|
| 39 |
import random
|
|
|
|
| 40 |
torch.manual_seed(seed)
|
| 41 |
random.seed(seed)
|
| 42 |
np.random.seed(seed)
|
|
@@ -44,56 +59,84 @@ def set_seed(seed=42):
|
|
| 44 |
|
| 45 |
|
| 46 |
def l2norm(x: torch.Tensor, dim: int = -1, eps: float = 1e-12) -> torch.Tensor:
|
|
|
|
|
|
|
|
|
|
| 47 |
return x / (x.norm(p=2, dim=dim, keepdim=True) + eps)
|
| 48 |
|
| 49 |
|
| 50 |
def interpolate_1d(x: torch.Tensor, target_dim: int) -> torch.Tensor:
|
| 51 |
"""
|
| 52 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 53 |
"""
|
| 54 |
-
return F.interpolate(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 55 |
|
| 56 |
|
| 57 |
# -------------------------
|
| 58 |
# Vision resize & rebuild (SigLIP v1 shell)
|
| 59 |
# -------------------------
|
| 60 |
def _size_config(vit_size: str):
|
|
|
|
|
|
|
|
|
|
| 61 |
size_map = {
|
| 62 |
-
"small": {"layers": 12, "hidden": 396,
|
| 63 |
-
"base":
|
| 64 |
"large": {"layers": 24, "hidden": 1056, "heads": 16},
|
| 65 |
}
|
| 66 |
assert vit_size in size_map, f"vit_size must be one of {list(size_map.keys())}"
|
| 67 |
return size_map[vit_size]
|
| 68 |
|
| 69 |
|
| 70 |
-
def resize_vit_and_rebuild_vision_v1(
|
| 71 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 72 |
"""
|
| 73 |
-
|
|
|
|
| 74 |
"""
|
| 75 |
cfg = _size_config(vit_size)
|
| 76 |
|
| 77 |
vconf = model.config.vision_config
|
| 78 |
tconf = model.config.text_config
|
| 79 |
|
| 80 |
-
vconf.num_hidden_layers
|
| 81 |
-
vconf.hidden_size
|
| 82 |
vconf.num_attention_heads = int(cfg["heads"])
|
| 83 |
-
vconf.intermediate_size
|
| 84 |
-
vconf.image_size
|
| 85 |
-
vconf.patch_size
|
| 86 |
-
vconf.num_channels
|
| 87 |
setattr(vconf, "_attn_implementation", "sdpa" if use_sdpa else "eager")
|
| 88 |
|
| 89 |
head_dim = vconf.hidden_size // vconf.num_attention_heads
|
| 90 |
assert head_dim % 2 == 0, f"head_dim must be even for RoPE, got {head_dim}"
|
| 91 |
|
| 92 |
-
#
|
| 93 |
-
if hasattr(tconf, "projection_size"):
|
| 94 |
-
|
|
|
|
|
|
|
| 95 |
|
| 96 |
-
# 重新构建 vision(SigLIP v1)
|
| 97 |
VisionCls = type(model.vision_model)
|
| 98 |
model.vision_model = VisionCls(vconf)
|
| 99 |
|
|
@@ -111,11 +154,21 @@ def resize_vit_and_rebuild_vision_v1(model, *, vit_size: str, patch_size, use_sd
|
|
| 111 |
|
| 112 |
|
| 113 |
# -------------------------
|
| 114 |
-
# 3D
|
| 115 |
# -------------------------
|
| 116 |
-
def inject_3d_embeddings(
|
| 117 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 118 |
from vision import SiglipVisionEmbeddings3D
|
|
|
|
| 119 |
real = unwrap_model(model)
|
| 120 |
real.vision_model.embeddings = SiglipVisionEmbeddings3D(
|
| 121 |
in_channels=in_channels,
|
|
@@ -126,23 +179,29 @@ def inject_3d_embeddings(model, *, in_channels: int, embed_dim: int, patch_size,
|
|
| 126 |
|
| 127 |
|
| 128 |
# -------------------------
|
| 129 |
-
# Projection alignment (vision->text)
|
| 130 |
# -------------------------
|
| 131 |
def _get_text_proj_dim(model) -> int:
|
| 132 |
-
|
|
|
|
|
|
|
| 133 |
if hasattr(model, "text_projection") and isinstance(model.text_projection, torch.nn.Parameter):
|
| 134 |
return int(model.text_projection.shape[1])
|
| 135 |
-
|
| 136 |
d = getattr(model.config, "projection_dim", None)
|
| 137 |
if d is None and hasattr(model, "config") and hasattr(model.config, "text_config"):
|
| 138 |
-
d =
|
| 139 |
-
model.config.text_config, "
|
|
|
|
| 140 |
)
|
|
|
|
| 141 |
return int(d) if d is not None else 768
|
| 142 |
|
| 143 |
|
| 144 |
def _set_all_visual_proj_aliases(model, param: torch.nn.Parameter):
|
| 145 |
-
|
|
|
|
|
|
|
| 146 |
setattr(model, "visual_projection", param)
|
| 147 |
setattr(model, "vision_projection", param)
|
| 148 |
setattr(model, "image_projection", param)
|
|
@@ -150,10 +209,13 @@ def _set_all_visual_proj_aliases(model, param: torch.nn.Parameter):
|
|
| 150 |
|
| 151 |
def align_siglip_projection_to_text(model, target_dim: int = None):
|
| 152 |
"""
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
|
|
|
|
|
|
|
|
|
| 157 |
"""
|
| 158 |
real = unwrap_model(model)
|
| 159 |
|
|
@@ -162,17 +224,18 @@ def align_siglip_projection_to_text(model, target_dim: int = None):
|
|
| 162 |
|
| 163 |
vconf = getattr(real.config, "vision_config", None)
|
| 164 |
if vconf is None:
|
| 165 |
-
return
|
|
|
|
| 166 |
vis_in = int(vconf.hidden_size)
|
| 167 |
|
| 168 |
device = next(real.parameters()).device
|
| 169 |
dtype = next(real.parameters()).dtype
|
| 170 |
|
| 171 |
-
# 已存在且匹配就直接绑定别名并返回
|
| 172 |
for name in ("visual_projection", "vision_projection", "image_projection"):
|
| 173 |
w = getattr(real, name, None)
|
| 174 |
if isinstance(w, torch.nn.Parameter) and w.ndim == 2 and w.shape == (vis_in, target_dim):
|
| 175 |
_set_all_visual_proj_aliases(real, w)
|
|
|
|
| 176 |
if hasattr(real.config, "projection_dim"):
|
| 177 |
real.config.projection_dim = target_dim
|
| 178 |
if hasattr(real.config, "vision_config"):
|
|
@@ -184,7 +247,6 @@ def align_siglip_projection_to_text(model, target_dim: int = None):
|
|
| 184 |
real.config.text_config.projection_dim = target_dim
|
| 185 |
return
|
| 186 |
|
| 187 |
-
# 新建并尽量拷贝
|
| 188 |
new_w = torch.empty(vis_in, target_dim, dtype=dtype, device=device)
|
| 189 |
init_factor = getattr(real.config, "initializer_factor", 1.0)
|
| 190 |
nn.init.normal_(new_w, std=0.02 * init_factor)
|
|
@@ -214,59 +276,73 @@ def align_siglip_projection_to_text(model, target_dim: int = None):
|
|
| 214 |
|
| 215 |
|
| 216 |
# -------------------------
|
| 217 |
-
# Text RoPE
|
| 218 |
# -------------------------
|
| 219 |
def init_text_rope_once(model, base: float = 10000.0, max_len: Optional[int] = None) -> bool:
|
| 220 |
"""
|
| 221 |
-
|
| 222 |
-
|
| 223 |
-
|
|
|
|
|
|
|
|
|
|
| 224 |
"""
|
| 225 |
real = unwrap_model(model)
|
| 226 |
|
| 227 |
-
# 1) swap embeddings
|
| 228 |
-
from vision import TextEmbeddingsNoAbsPos
|
| 229 |
txt = getattr(real, "text_model", None)
|
| 230 |
if txt is None:
|
| 231 |
-
raise ValueError("model.text_model
|
|
|
|
| 232 |
if not isinstance(txt.embeddings, TextEmbeddingsNoAbsPos):
|
| 233 |
txt.embeddings = TextEmbeddingsNoAbsPos(txt.embeddings)
|
| 234 |
|
| 235 |
-
|
| 236 |
from models.rope_generic import patch_encoder_with_rope as patch_text_with_rope
|
| 237 |
from models.rope_generic import set_shared_axial_freqs as text_set_shared_freqs
|
| 238 |
-
from models.rope_generic import build_rope_packed as text_build_packed
|
| 239 |
|
| 240 |
enc = txt.encoder
|
| 241 |
-
|
| 242 |
-
|
| 243 |
for lyr in enc.layers:
|
| 244 |
if not hasattr(lyr.self_attn, "set_freqs"):
|
| 245 |
-
|
| 246 |
break
|
| 247 |
-
|
|
|
|
| 248 |
patch_text_with_rope(enc)
|
| 249 |
|
| 250 |
-
# 3) set shared 1D freqs
|
| 251 |
if max_len is None:
|
| 252 |
-
# 取 config 中可用长度
|
| 253 |
max_len = getattr(real.config.text_config, "max_position_embeddings", 16)
|
|
|
|
| 254 |
head_dim = getattr(real.config.text_config, "hidden_size", 768) // getattr(
|
| 255 |
real.config.text_config, "num_attention_heads", 12
|
| 256 |
)
|
| 257 |
assert head_dim % 2 == 0, f"text head_dim must be even for RoPE, got {head_dim}"
|
| 258 |
|
| 259 |
-
freqs = text_build_packed(
|
| 260 |
-
|
| 261 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 262 |
return True
|
| 263 |
|
| 264 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 265 |
"""
|
| 266 |
-
|
| 267 |
-
|
| 268 |
-
|
| 269 |
-
|
|
|
|
| 270 |
"""
|
| 271 |
real = unwrap_model(model)
|
| 272 |
|
|
@@ -275,40 +351,44 @@ def configure_text_pos_mode(model, *, mode: str, rope_base: float = 10000.0, max
|
|
| 275 |
raise ValueError(f"text_pos_mode must be 'abs' or 'rope', got {mode}")
|
| 276 |
|
| 277 |
if mode == "abs":
|
| 278 |
-
# 重建 Text 后默认就是 abs;如果之前被换成 NoAbs/贴了 RoPE,最安全的方式是“先重建再 abs”
|
| 279 |
-
# 这里不做任何额外动作(重建由上层调用保证)
|
| 280 |
return {"mode": "abs"}
|
| 281 |
|
| 282 |
-
# == rope ==
|
| 283 |
-
# 幂等:多次调用也不会重复 patch/重复下发频率
|
| 284 |
init_text_rope_once(real, base=rope_base, max_len=max_seq_len)
|
| 285 |
return {"mode": "rope", "base": float(rope_base), "max_len": int(max_seq_len)}
|
| 286 |
|
| 287 |
|
| 288 |
# -------------------------
|
| 289 |
-
#
|
| 290 |
# -------------------------
|
| 291 |
def _size_config_text(text_size: str):
|
| 292 |
-
|
| 293 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 294 |
|
| 295 |
-
def resize_text_and_rebuild_v1(
|
| 296 |
-
|
| 297 |
-
|
| 298 |
-
|
| 299 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 300 |
"""
|
| 301 |
-
|
| 302 |
-
|
| 303 |
"""
|
| 304 |
real = unwrap_model(model)
|
| 305 |
cfg = _size_config_text(text_size)
|
| 306 |
|
| 307 |
tconf = real.config.text_config
|
| 308 |
-
tconf.num_hidden_layers
|
| 309 |
-
tconf.hidden_size
|
| 310 |
tconf.num_attention_heads = int(cfg["heads"])
|
| 311 |
-
tconf.intermediate_size
|
| 312 |
tconf.max_position_embeddings = int(max_position_embeddings)
|
| 313 |
setattr(tconf, "_attn_implementation", "sdpa" if use_sdpa else "eager")
|
| 314 |
|
|
@@ -320,7 +400,6 @@ def resize_text_and_rebuild_v1(model, *, text_size: str,
|
|
| 320 |
if vocab_size is not None:
|
| 321 |
tconf.vocab_size = int(vocab_size)
|
| 322 |
|
| 323 |
-
# 重新构建 text(SigLIP v1)
|
| 324 |
TextCls = type(real.text_model)
|
| 325 |
real.text_model = TextCls(tconf)
|
| 326 |
|
|
@@ -338,407 +417,165 @@ def resize_text_and_rebuild_v1(model, *, text_size: str,
|
|
| 338 |
"max_pos": tconf.max_position_embeddings,
|
| 339 |
}
|
| 340 |
|
|
|
|
| 341 |
# -------------------------
|
| 342 |
-
#
|
| 343 |
# -------------------------
|
| 344 |
def assert_no_dim_768_left(model, expected_hidden: int):
|
| 345 |
"""
|
| 346 |
-
|
|
|
|
| 347 |
"""
|
| 348 |
real = unwrap_model(model)
|
| 349 |
offenders = []
|
| 350 |
|
| 351 |
-
def _check_module(prefix,
|
| 352 |
nonlocal offenders
|
| 353 |
-
|
| 354 |
-
|
| 355 |
-
|
| 356 |
-
|
| 357 |
-
|
| 358 |
-
|
| 359 |
-
|
|
|
|
|
|
|
| 360 |
offenders.append(f"{prefix}.norm=768 (LayerNorm)")
|
| 361 |
|
| 362 |
for name, mod in real.named_modules():
|
| 363 |
_check_module(name, mod)
|
| 364 |
|
| 365 |
if offenders:
|
| 366 |
-
msg =
|
| 367 |
-
|
|
|
|
|
|
|
| 368 |
raise AssertionError(msg)
|
| 369 |
|
| 370 |
-
|
| 371 |
# -------------------------
|
| 372 |
-
#
|
| 373 |
# -------------------------
|
| 374 |
-
from contextlib import nullcontext
|
| 375 |
-
|
| 376 |
@torch.no_grad()
|
| 377 |
def compute_metrics(
|
| 378 |
model,
|
| 379 |
-
val_dataloader,
|
| 380 |
-
tokenizer,
|
| 381 |
-
device,
|
| 382 |
-
max_txt_len: int = 16,
|
| 383 |
-
log_to_wandb: bool = True,
|
| 384 |
-
wandb_prefix: str = "eval",
|
| 385 |
-
):
|
| 386 |
-
# Retrieval evaluation (1:1 image<->text) + binary metrics from full similarity matrix:
|
| 387 |
-
# - i2t, t2i: Recall@K, MeanRank
|
| 388 |
-
# - PR curve + AP(PR-AUC), ROC curve + ROC-AUC
|
| 389 |
-
# - Best-F1 (扫描阈值得到), 以及该阈值下的 Precision/Recall/Acc
|
| 390 |
-
# - Top-1 混淆矩阵(i->t 与 t->i),观察对角线
|
| 391 |
-
|
| 392 |
-
try:
|
| 393 |
-
real = unwrap_model(model)
|
| 394 |
-
except NameError:
|
| 395 |
-
real = model
|
| 396 |
-
|
| 397 |
-
real.eval()
|
| 398 |
-
|
| 399 |
-
all_img, all_txt = [], []
|
| 400 |
-
K = 10
|
| 401 |
-
for b, batch in enumerate(val_dataloader):
|
| 402 |
-
if b >= K: break
|
| 403 |
-
images = batch["pixel_values"].to(device)
|
| 404 |
-
texts = batch["text"]
|
| 405 |
-
|
| 406 |
-
# tokenize text
|
| 407 |
-
text_inputs = tokenizer(
|
| 408 |
-
texts, padding="max_length", truncation=True,
|
| 409 |
-
max_length=max_txt_len, return_tensors="pt",
|
| 410 |
-
)
|
| 411 |
-
text_inputs = {k: v.to(device) for k, v in text_inputs.items()}
|
| 412 |
-
|
| 413 |
-
# text embed
|
| 414 |
-
if hasattr(real, "get_text_features"):
|
| 415 |
-
t = real.get_text_features(**text_inputs)
|
| 416 |
-
else:
|
| 417 |
-
to = real.text_model(**text_inputs, return_dict=True)
|
| 418 |
-
if getattr(to, "pooler_output", None) is not None:
|
| 419 |
-
t = to.pooler_output
|
| 420 |
-
else:
|
| 421 |
-
eos_idx = text_inputs["attention_mask"].sum(dim=1) - 1
|
| 422 |
-
t = to.last_hidden_state[torch.arange(eos_idx.size(0), device=eos_idx.device), eos_idx]
|
| 423 |
-
if hasattr(real, "text_projection") and isinstance(getattr(real, "text_projection", None), torch.nn.Parameter):
|
| 424 |
-
t = t @ real.text_projection
|
| 425 |
-
t = F.normalize(t, dim=-1)
|
| 426 |
-
|
| 427 |
-
# image embed
|
| 428 |
-
vo = real.vision_model(pixel_values=images, return_dict=True)
|
| 429 |
-
v = getattr(vo, "pooler_output", vo)
|
| 430 |
-
if hasattr(real, "visual_projection") and isinstance(getattr(real, "visual_projection", None), torch.nn.Parameter):
|
| 431 |
-
v = v @ real.visual_projection
|
| 432 |
-
v = F.normalize(v, dim=-1)
|
| 433 |
-
|
| 434 |
-
all_txt.append(t)
|
| 435 |
-
all_img.append(v)
|
| 436 |
-
|
| 437 |
-
text_mat = torch.cat(all_txt, dim=0) # (N, D)
|
| 438 |
-
image_mat = torch.cat(all_img, dim=0) # (N, D)
|
| 439 |
-
assert text_mat.size(0) == image_mat.size(0), "Val set must be 1:1 image↔text."
|
| 440 |
-
N = text_mat.size(0)
|
| 441 |
-
|
| 442 |
-
# similarity (I x T)
|
| 443 |
-
sims = image_mat @ text_mat.t() # (N, N)
|
| 444 |
-
if hasattr(real, "logit_scale"):
|
| 445 |
-
sims = sims * real.logit_scale.exp()
|
| 446 |
-
if hasattr(real, "logit_bias"):
|
| 447 |
-
sims = sims + real.logit_bias
|
| 448 |
-
|
| 449 |
-
# ---------- Retrieval metrics ----------
|
| 450 |
-
def recall_at_k(sim, k, dim=1):
|
| 451 |
-
ranks = torch.argsort(sim, dim=dim, descending=True)
|
| 452 |
-
idx = torch.arange(sim.size(0), device=sim.device)
|
| 453 |
-
if dim == 1: # i->t
|
| 454 |
-
topk = ranks[:, :k]
|
| 455 |
-
hits = (topk == idx.unsqueeze(1)).any(dim=1).float().mean().item()
|
| 456 |
-
pos = (ranks == idx.unsqueeze(1)).nonzero(as_tuple=False)[:, 1]
|
| 457 |
-
else: # t->i
|
| 458 |
-
topk = ranks[:k, :].t()
|
| 459 |
-
hits = (topk == idx.unsqueeze(1)).any(dim=1).float().mean().item()
|
| 460 |
-
pos = (ranks.t() == idx.unsqueeze(1)).nonzero(as_tuple=False)[:, 1]
|
| 461 |
-
mean_rank = (pos.float().mean().item() + 1.0)
|
| 462 |
-
return hits, mean_rank
|
| 463 |
-
|
| 464 |
-
diag_mean = torch.diag(sims).mean().item()
|
| 465 |
-
r1_i2t, mr_i2t = recall_at_k(sims, 1, dim=1)
|
| 466 |
-
r5_i2t, _ = recall_at_k(sims, 5, dim=1)
|
| 467 |
-
r10_i2t, _ = recall_at_k(sims, 10, dim=1)
|
| 468 |
-
|
| 469 |
-
r1_t2i, mr_t2i = recall_at_k(sims.t(), 1, dim=1)
|
| 470 |
-
r5_t2i, _ = recall_at_k(sims.t(), 5, dim=1)
|
| 471 |
-
r10_t2i, _ = recall_at_k(sims.t(),10, dim=1)
|
| 472 |
-
|
| 473 |
-
# ---------- Binary metrics from scores ----------
|
| 474 |
-
# labels: diag=1, off-diag=0
|
| 475 |
-
y_true = torch.eye(N, device=sims.device, dtype=torch.int8).flatten().cpu().numpy()
|
| 476 |
-
y_score = sims.flatten().detach().cpu().numpy()
|
| 477 |
-
|
| 478 |
-
# 可能非常大(N^2),给个软保护(> 9e6 个样本时跳过曲线绘图以省显存/时间)
|
| 479 |
-
do_curves = (y_true.size <= 9_000_000)
|
| 480 |
-
|
| 481 |
-
pr_auc = roc_auc = None
|
| 482 |
-
best_f1 = best_p = best_r = best_acc = None
|
| 483 |
-
thr_at_best_f1 = None
|
| 484 |
-
pr_curve_fig = roc_curve_fig = None
|
| 485 |
-
|
| 486 |
-
try:
|
| 487 |
-
from sklearn.metrics import (
|
| 488 |
-
precision_recall_curve, average_precision_score,
|
| 489 |
-
roc_curve, roc_auc_score, confusion_matrix
|
| 490 |
-
)
|
| 491 |
-
if do_curves:
|
| 492 |
-
# PR 曲线 & AP (PR-AUC)
|
| 493 |
-
prec, rec, thr = precision_recall_curve(y_true, y_score)
|
| 494 |
-
ap = average_precision_score(y_true, y_score)
|
| 495 |
-
pr_auc = float(ap)
|
| 496 |
-
|
| 497 |
-
# ROC 曲线 & AUC
|
| 498 |
-
fpr, tpr, thr_roc = roc_curve(y_true, y_score)
|
| 499 |
-
auc = roc_auc_score(y_true, y_score)
|
| 500 |
-
roc_auc = float(auc)
|
| 501 |
-
|
| 502 |
-
# 扫描阈值取 F1 最大(用 PR 曲线上的阈值)
|
| 503 |
-
eps = 1e-12
|
| 504 |
-
f1s = 2 * prec * rec / (prec + rec + eps)
|
| 505 |
-
best_idx = int(f1s.argmax())
|
| 506 |
-
best_f1 = float(f1s[best_idx])
|
| 507 |
-
thr_at_best_f1 = float(thr[best_idx-1]) if best_idx > 0 and best_idx-1 < len(thr) else float(y_score.mean())
|
| 508 |
-
|
| 509 |
-
# 用最佳阈值计算 Precision/Recall/Accuracy
|
| 510 |
-
y_pred = (y_score >= thr_at_best_f1).astype(np.int32)
|
| 511 |
-
tp = int((y_pred * y_true).sum())
|
| 512 |
-
fp = int(y_pred.sum() - tp)
|
| 513 |
-
fn = int(y_true.sum() - tp)
|
| 514 |
-
tn = int(y_true.size - tp - fp - fn)
|
| 515 |
-
best_p = float(tp / max(1, tp + fp))
|
| 516 |
-
best_r = float(tp / max(1, tp + fn))
|
| 517 |
-
best_acc = float((tp + tn) / max(1, y_true.size))
|
| 518 |
-
|
| 519 |
-
# 画 PR / ROC 曲线
|
| 520 |
-
if log_to_wandb:
|
| 521 |
-
import matplotlib.pyplot as plt, wandb
|
| 522 |
-
fig1, ax1 = plt.subplots(figsize=(5,4), dpi=140)
|
| 523 |
-
ax1.plot(rec, prec, label=f"AP={ap:.4f}")
|
| 524 |
-
ax1.set_xlabel("Recall"); ax1.set_ylabel("Precision"); ax1.set_title("Precision-Recall")
|
| 525 |
-
ax1.legend(loc="lower left")
|
| 526 |
-
pr_curve_fig = fig1
|
| 527 |
-
|
| 528 |
-
fig2, ax2 = plt.subplots(figsize=(5,4), dpi=140)
|
| 529 |
-
ax2.plot(fpr, tpr, label=f"AUC={auc:.4f}")
|
| 530 |
-
ax2.plot([0,1],[0,1], linestyle="--", linewidth=1)
|
| 531 |
-
ax2.set_xlabel("FPR"); ax2.set_ylabel("TPR"); ax2.set_title("ROC")
|
| 532 |
-
ax2.legend(loc="lower right")
|
| 533 |
-
roc_curve_fig = fig2
|
| 534 |
-
except Exception as e:
|
| 535 |
-
print(f"[WARN] sklearn metrics unavailable or failed: {e}")
|
| 536 |
-
|
| 537 |
-
# ---------- Top-1 Confusion Matrix (i->t and t->i) ----------
|
| 538 |
-
# i->t
|
| 539 |
-
pred_t = sims.argmax(dim=1).cpu().numpy() # 预测的文本索引
|
| 540 |
-
true_t = np.arange(N)
|
| 541 |
-
# t->i
|
| 542 |
-
pred_i = sims.argmax(dim=0).cpu().numpy()
|
| 543 |
-
true_i = np.arange(N)
|
| 544 |
-
|
| 545 |
-
# 构造 NxN 混淆矩阵(可能很大;仅用于可视化)
|
| 546 |
-
def make_conf_mat(pred, true, num_classes):
|
| 547 |
-
# 稀疏 bincount 构造
|
| 548 |
-
idx = pred * num_classes + true
|
| 549 |
-
cm = np.bincount(idx, minlength=num_classes*num_classes).reshape(num_classes, num_classes)
|
| 550 |
-
return cm
|
| 551 |
-
|
| 552 |
-
cm_i2t = make_conf_mat(pred_t, true_t, N)
|
| 553 |
-
cm_t2i = make_conf_mat(pred_i, true_i, N)
|
| 554 |
-
|
| 555 |
-
# ---------- Collect ----------
|
| 556 |
-
out = {
|
| 557 |
-
"pairs": N,
|
| 558 |
-
"mean_sim_diag": diag_mean,
|
| 559 |
-
# retrieval
|
| 560 |
-
"i2t/R@1": r1_i2t, "i2t/R@5": r5_i2t, "i2t/R@10": r10_i2t, "i2t/MeanRank": mr_i2t,
|
| 561 |
-
"t2i/R@1": r1_t2i, "t2i/R@5": r5_t2i, "t2i/R@10": r10_t2i, "t2i/MeanRank": mr_t2i,
|
| 562 |
-
# binary metrics
|
| 563 |
-
"bin/PR_AUC": pr_auc if pr_auc is not None else float("nan"),
|
| 564 |
-
"bin/ROC_AUC": roc_auc if roc_auc is not None else float("nan"),
|
| 565 |
-
"bin/BestF1": best_f1 if best_f1 is not None else float("nan"),
|
| 566 |
-
"bin/BestPrec": best_p if best_p is not None else float("nan"),
|
| 567 |
-
"bin/BestRec": best_r if best_r is not None else float("nan"),
|
| 568 |
-
"bin/BestAcc": best_acc if best_acc is not None else float("nan"),
|
| 569 |
-
"bin/Thr@BestF1": thr_at_best_f1 if thr_at_best_f1 is not None else float("nan"),
|
| 570 |
-
# top-1 acc(与 R@1 等价)
|
| 571 |
-
"i2t/Top1Acc": float((pred_t == true_t).mean()),
|
| 572 |
-
"t2i/Top1Acc": float((pred_i == true_i).mean()),
|
| 573 |
-
}
|
| 574 |
-
|
| 575 |
-
# ---------- W&B logging ----------
|
| 576 |
-
if log_to_wandb:
|
| 577 |
-
try:
|
| 578 |
-
import wandb, matplotlib.pyplot as plt
|
| 579 |
-
# 相似度直方图
|
| 580 |
-
fig, ax = plt.subplots(figsize=(5, 4), dpi=140)
|
| 581 |
-
ax.hist(sims.detach().cpu().flatten().numpy(), bins=50)
|
| 582 |
-
ax.set_title("Similarity distribution (I·T)")
|
| 583 |
-
ax.set_xlabel("sim"); ax.set_ylabel("count")
|
| 584 |
-
if wandb.run is not None:
|
| 585 |
-
wandb.log({f"{wandb_prefix}/sim_hist": wandb.Image(fig)})
|
| 586 |
-
plt.close(fig)
|
| 587 |
-
|
| 588 |
-
# 对角线分布
|
| 589 |
-
fig2, ax2 = plt.subplots(figsize=(5, 4), dpi=140)
|
| 590 |
-
ax2.hist(torch.diag(sims).detach().cpu().numpy(), bins=50)
|
| 591 |
-
ax2.set_title("Diagonal similarity (positive pairs)")
|
| 592 |
-
ax2.set_xlabel("sim"); ax2.set_ylabel("count")
|
| 593 |
-
if wandb.run is not None:
|
| 594 |
-
wandb.log({f"{wandb_prefix}/sim_diag_hist": wandb.Image(fig2)})
|
| 595 |
-
plt.close(fig2)
|
| 596 |
-
|
| 597 |
-
# PR / ROC 曲线
|
| 598 |
-
if pr_curve_fig is not None and wandb.run is not None:
|
| 599 |
-
wandb.log({f"{wandb_prefix}/PR_curve": wandb.Image(pr_curve_fig)})
|
| 600 |
-
plt.close(pr_curve_fig)
|
| 601 |
-
if roc_curve_fig is not None and wandb.run is not None:
|
| 602 |
-
wandb.log({f"{wandb_prefix}/ROC_curve": wandb.Image(roc_curve_fig)})
|
| 603 |
-
plt.close(roc_curve_fig)
|
| 604 |
-
|
| 605 |
-
# Top-1 混淆矩阵(热力图)
|
| 606 |
-
# 注意:N 很大时图会很大,这里只在 N<=256 时画全尺寸;更大时下采样/不画
|
| 607 |
-
if N <= 256:
|
| 608 |
-
import seaborn as sns
|
| 609 |
-
fig3, ax3 = plt.subplots(figsize=(6, 5), dpi=140)
|
| 610 |
-
sns.heatmap(cm_i2t, ax=ax3, cmap="viridis", cbar=False)
|
| 611 |
-
ax3.set_title("Confusion (Image→Text); diagonal=correct")
|
| 612 |
-
ax3.set_xlabel("True text idx"); ax3.set_ylabel("Pred text idx")
|
| 613 |
-
wandb.log({f"{wandb_prefix}/confmat_i2t": wandb.Image(fig3)})
|
| 614 |
-
plt.close(fig3)
|
| 615 |
-
|
| 616 |
-
fig4, ax4 = plt.subplots(figsize=(6, 5), dpi=140)
|
| 617 |
-
sns.heatmap(cm_t2i, ax=ax4, cmap="viridis", cbar=False)
|
| 618 |
-
ax4.set_title("Confusion (Text→Image); diagonal=correct")
|
| 619 |
-
ax4.set_xlabel("True image idx"); ax4.set_ylabel("Pred image idx")
|
| 620 |
-
wandb.log({f"{wandb_prefix}/confmat_t2i": wandb.Image(fig4)})
|
| 621 |
-
plt.close(fig4)
|
| 622 |
-
|
| 623 |
-
# 最后把所有标量一起打点
|
| 624 |
-
if wandb.run is not None:
|
| 625 |
-
wandb.log({f"{wandb_prefix}/{k}": v for k, v in out.items()})
|
| 626 |
-
except Exception as e:
|
| 627 |
-
print(f"[WARN] W&B logging failed: {e}")
|
| 628 |
-
|
| 629 |
-
return out
|
| 630 |
-
"""
|
| 631 |
-
|
| 632 |
-
@torch.no_grad()
|
| 633 |
-
def compute_metrics(
|
| 634 |
-
model,
|
| 635 |
dataloader,
|
| 636 |
tokenizer,
|
| 637 |
device,
|
| 638 |
max_txt_len: int = 16,
|
| 639 |
log_to_wandb: bool = True,
|
| 640 |
wandb_prefix: str = "eval",
|
| 641 |
-
make_heatmap: bool = True,
|
| 642 |
-
step=None
|
| 643 |
):
|
| 644 |
"""
|
| 645 |
-
|
| 646 |
-
|
| 647 |
-
|
| 648 |
-
|
| 649 |
-
|
| 650 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 651 |
"""
|
| 652 |
model.eval()
|
|
|
|
| 653 |
try:
|
| 654 |
batch = next(iter(dataloader))
|
| 655 |
except StopIteration:
|
| 656 |
return {"error": "empty dataloader"}
|
| 657 |
|
| 658 |
images = batch["pixel_values"].to(device, non_blocking=True)
|
| 659 |
-
texts
|
| 660 |
-
|
| 661 |
-
|
| 662 |
-
texts,
|
| 663 |
-
|
|
|
|
|
|
|
|
|
|
| 664 |
)
|
| 665 |
-
|
| 666 |
|
| 667 |
-
# 前向:一次拿全(logits & embeds)
|
| 668 |
outputs = model(
|
| 669 |
-
input_ids=
|
| 670 |
pixel_values=images,
|
| 671 |
-
return_dict=True
|
| 672 |
)
|
| 673 |
|
| 674 |
-
sims_i2t = outputs.logits_per_image
|
| 675 |
-
sims_t2i = outputs.logits_per_text
|
| 676 |
|
| 677 |
-
|
| 678 |
-
idx = torch.arange(
|
| 679 |
|
| 680 |
-
def recall_at_k(sim, k):
|
| 681 |
k = min(k, sim.size(1))
|
| 682 |
-
ranks = torch.argsort(sim, dim=1, descending=True)
|
| 683 |
-
topk
|
| 684 |
-
hits
|
| 685 |
-
pos
|
| 686 |
-
mean_rank =
|
| 687 |
return hits, mean_rank
|
| 688 |
|
| 689 |
-
# i->t
|
| 690 |
r1_i2t, mr_i2t = recall_at_k(sims_i2t, 1)
|
| 691 |
-
r5_i2t,
|
| 692 |
-
r10_i2t, _
|
| 693 |
-
|
| 694 |
r1_t2i, mr_t2i = recall_at_k(sims_t2i, 1)
|
| 695 |
-
r5_t2i,
|
| 696 |
-
r10_t2i, _
|
| 697 |
|
| 698 |
-
|
| 699 |
-
|
| 700 |
-
top1_t2i = float((sims_t2i.argmax(dim=1).cpu().numpy() == np.arange(B)).mean())
|
| 701 |
|
| 702 |
out = {
|
| 703 |
-
"pairs_in_batch": int(
|
| 704 |
-
"i2t/R@1": r1_i2t,
|
| 705 |
-
"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 706 |
"i2t/Top1Acc": top1_i2t,
|
| 707 |
"t2i/Top1Acc": top1_t2i,
|
| 708 |
-
#"mean_sim_diag": float(torch.diag(sims_i2t).mean().item()),
|
| 709 |
-
# 如需后续分析可放回 logits(注意:可能较大)
|
| 710 |
-
#"logits_per_image": sims_i2t.detach().cpu(),
|
| 711 |
-
#"logits_per_text": sims_t2i.detach().cpu(),
|
| 712 |
}
|
| 713 |
|
| 714 |
-
# ===== 可视化:行softmax百分比热力图(Image→Text) =====
|
| 715 |
if make_heatmap:
|
| 716 |
try:
|
| 717 |
import matplotlib.pyplot as plt
|
| 718 |
|
| 719 |
with torch.no_grad():
|
| 720 |
-
mat = sims_i2t.detach().float().cpu().numpy()
|
| 721 |
-
# 行 softmax
|
| 722 |
mat = mat - mat.max(axis=1, keepdims=True)
|
| 723 |
prob = np.exp(mat)
|
| 724 |
prob /= prob.sum(axis=1, keepdims=True) + 1e-12
|
| 725 |
|
| 726 |
-
fig, ax = plt.subplots(
|
| 727 |
-
|
| 728 |
-
|
| 729 |
-
|
| 730 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 731 |
|
| 732 |
-
|
| 733 |
-
|
| 734 |
-
for j in range(B):
|
| 735 |
p = int(round(prob[i, j] * 100))
|
| 736 |
txt = f"{p}%" if p >= 1 else "0%"
|
| 737 |
ax.text(j, i, txt, ha="center", va="center", fontsize=8)
|
| 738 |
|
| 739 |
-
|
| 740 |
-
|
| 741 |
-
rect = plt.Rectangle((i-0.5, i-0.5), 1, 1, fill=False, linewidth=1.5)
|
| 742 |
ax.add_patch(rect)
|
| 743 |
|
| 744 |
fig.colorbar(im, ax=ax, fraction=0.046, pad=0.04)
|
|
@@ -747,11 +584,14 @@ def compute_metrics(
|
|
| 747 |
if log_to_wandb:
|
| 748 |
try:
|
| 749 |
import wandb
|
|
|
|
| 750 |
if wandb.run is not None:
|
| 751 |
wandb.log({f"{wandb_prefix}/batch_heatmap": wandb.Image(fig)}, step=step)
|
| 752 |
except Exception as e:
|
| 753 |
-
print(f"[WARN] wandb
|
|
|
|
| 754 |
plt.close(fig)
|
|
|
|
| 755 |
except Exception as e:
|
| 756 |
print(f"[WARN] heatmap plotting failed: {e}")
|
| 757 |
|
|
@@ -761,77 +601,101 @@ def compute_metrics(
|
|
| 761 |
# -------------------------
|
| 762 |
# Optimizer (Muon + Adam)
|
| 763 |
# -------------------------
|
| 764 |
-
|
| 765 |
-
|
| 766 |
-
|
| 767 |
-
|
| 768 |
-
|
| 769 |
-
|
|
|
|
|
|
|
| 770 |
weights, bias_norm = [], []
|
|
|
|
| 771 |
for p in params:
|
| 772 |
if not p.requires_grad:
|
| 773 |
continue
|
| 774 |
(weights if p.ndim >= 2 else bias_norm).append(p)
|
|
|
|
| 775 |
return weights, bias_norm
|
| 776 |
|
|
|
|
| 777 |
def build_optimizer_with_muon(model, lr: float, weight_decay: float):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 778 |
real = unwrap_model(model)
|
| 779 |
|
| 780 |
-
# vision / text 主干
|
| 781 |
img_w, img_b = _split_params_by_dim(real.vision_model.parameters())
|
| 782 |
txt_w, txt_b = _split_params_by_dim(real.text_model.parameters())
|
| 783 |
|
| 784 |
-
# 额外顶层参数(一起放到 Adam 组里)
|
| 785 |
extra = []
|
|
|
|
| 786 |
if hasattr(real, "projection"):
|
| 787 |
for p in real.projection.parameters():
|
| 788 |
if p.requires_grad:
|
| 789 |
extra.append(p)
|
|
|
|
| 790 |
if hasattr(real, "visual_projection") and isinstance(real.visual_projection, torch.nn.Parameter):
|
| 791 |
if real.visual_projection.requires_grad:
|
| 792 |
extra.append(real.visual_projection)
|
|
|
|
| 793 |
if hasattr(real, "text_projection") and isinstance(real.text_projection, torch.nn.Parameter):
|
| 794 |
if real.text_projection.requires_grad:
|
| 795 |
extra.append(real.text_projection)
|
|
|
|
| 796 |
if hasattr(real, "logit_scale") and getattr(real.logit_scale, "requires_grad", False):
|
| 797 |
extra.append(real.logit_scale)
|
|
|
|
| 798 |
if hasattr(real, "logit_bias") and getattr(real.logit_bias, "requires_grad", False):
|
| 799 |
extra.append(real.logit_bias)
|
| 800 |
|
| 801 |
-
# 两组就够了:隐藏权重走 Muon,偏置/Norm/投影/温度走 Adam
|
| 802 |
param_groups = [
|
| 803 |
-
dict(
|
| 804 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 805 |
]
|
| 806 |
return MuonWithAuxAdam(param_groups)
|
| 807 |
|
| 808 |
|
| 809 |
def swap_text_to_no_abs_pos(model) -> bool:
|
| 810 |
"""
|
| 811 |
-
|
| 812 |
-
|
| 813 |
-
|
| 814 |
-
|
|
|
|
|
|
|
| 815 |
"""
|
| 816 |
real = unwrap_model(model)
|
| 817 |
|
| 818 |
txt = getattr(real, "text_model", None)
|
| 819 |
if txt is None:
|
| 820 |
-
raise ValueError("swap_text_to_no_abs_pos: model.text_model
|
| 821 |
|
| 822 |
emb = getattr(txt, "embeddings", None)
|
| 823 |
if emb is None:
|
| 824 |
-
raise ValueError("swap_text_to_no_abs_pos: text_model.embeddings
|
| 825 |
|
| 826 |
if TextEmbeddingsNoAbsPos is None:
|
| 827 |
raise ImportError(
|
| 828 |
-
"swap_text_to_no_abs_pos
|
| 829 |
-
"
|
| 830 |
)
|
| 831 |
|
| 832 |
if isinstance(emb, TextEmbeddingsNoAbsPos):
|
| 833 |
-
# 已经是无绝对位置的版本了
|
| 834 |
return False
|
| 835 |
|
| 836 |
txt.embeddings = TextEmbeddingsNoAbsPos(emb)
|
| 837 |
-
return True
|
|
|
|
| 1 |
import os
|
| 2 |
import re
|
| 3 |
+
from typing import Iterable, List, Optional, Tuple
|
| 4 |
|
| 5 |
import numpy as np
|
| 6 |
import torch
|
| 7 |
import torch.nn as nn
|
| 8 |
import torch.nn.functional as F
|
| 9 |
+
|
| 10 |
from muon import MuonWithAuxAdam
|
| 11 |
from vision import TextEmbeddingsNoAbsPos
|
| 12 |
|
| 13 |
+
|
| 14 |
# -------------------------
|
| 15 |
# Generic helpers
|
| 16 |
# -------------------------
|
| 17 |
def unwrap_model(model):
|
| 18 |
+
"""
|
| 19 |
+
Return the underlying model when wrapped by DDP or similar wrappers.
|
| 20 |
+
"""
|
| 21 |
return model.module if hasattr(model, "module") else model
|
| 22 |
|
| 23 |
|
| 24 |
def get_latest_checkpoint(ckpt_dir: str) -> Tuple[Optional[str], int]:
|
| 25 |
+
"""
|
| 26 |
+
Find the latest checkpoint in a directory.
|
| 27 |
+
|
| 28 |
+
Returns:
|
| 29 |
+
(checkpoint_path, step)
|
| 30 |
+
- (None, 0) if no checkpoint is found
|
| 31 |
+
"""
|
| 32 |
if not os.path.exists(ckpt_dir):
|
| 33 |
os.makedirs(ckpt_dir, exist_ok=True)
|
| 34 |
return None, 0
|
|
|
|
| 37 |
if not pt_files:
|
| 38 |
return None, 0
|
| 39 |
|
| 40 |
+
def extract_step(filename: str) -> int:
|
| 41 |
+
match = re.search(r"step(\d+)", filename)
|
| 42 |
+
return int(match.group(1)) if match else 0
|
| 43 |
|
| 44 |
pt_files.sort(key=extract_step, reverse=True)
|
| 45 |
latest = pt_files[0]
|
| 46 |
return os.path.join(ckpt_dir, latest), extract_step(latest)
|
| 47 |
|
| 48 |
|
| 49 |
+
def set_seed(seed: int = 42):
|
| 50 |
+
"""
|
| 51 |
+
Set random seeds for reproducibility.
|
| 52 |
+
"""
|
| 53 |
import random
|
| 54 |
+
|
| 55 |
torch.manual_seed(seed)
|
| 56 |
random.seed(seed)
|
| 57 |
np.random.seed(seed)
|
|
|
|
| 59 |
|
| 60 |
|
| 61 |
def l2norm(x: torch.Tensor, dim: int = -1, eps: float = 1e-12) -> torch.Tensor:
|
| 62 |
+
"""
|
| 63 |
+
Apply L2 normalization along a given dimension.
|
| 64 |
+
"""
|
| 65 |
return x / (x.norm(p=2, dim=dim, keepdim=True) + eps)
|
| 66 |
|
| 67 |
|
| 68 |
def interpolate_1d(x: torch.Tensor, target_dim: int) -> torch.Tensor:
|
| 69 |
"""
|
| 70 |
+
Resize a 2D tensor along its feature dimension using 1D linear interpolation.
|
| 71 |
+
|
| 72 |
+
Args:
|
| 73 |
+
x: Tensor of shape (B, D)
|
| 74 |
+
target_dim: Output feature dimension
|
| 75 |
+
|
| 76 |
+
Returns:
|
| 77 |
+
Tensor of shape (B, target_dim)
|
| 78 |
"""
|
| 79 |
+
return F.interpolate(
|
| 80 |
+
x.unsqueeze(1),
|
| 81 |
+
size=target_dim,
|
| 82 |
+
mode="linear",
|
| 83 |
+
align_corners=False,
|
| 84 |
+
).squeeze(1)
|
| 85 |
|
| 86 |
|
| 87 |
# -------------------------
|
| 88 |
# Vision resize & rebuild (SigLIP v1 shell)
|
| 89 |
# -------------------------
|
| 90 |
def _size_config(vit_size: str):
|
| 91 |
+
"""
|
| 92 |
+
Return model size configuration for SigLIP-style vision/text backbones.
|
| 93 |
+
"""
|
| 94 |
size_map = {
|
| 95 |
+
"small": {"layers": 12, "hidden": 396, "heads": 6},
|
| 96 |
+
"base": {"layers": 12, "hidden": 792, "heads": 12},
|
| 97 |
"large": {"layers": 24, "hidden": 1056, "heads": 16},
|
| 98 |
}
|
| 99 |
assert vit_size in size_map, f"vit_size must be one of {list(size_map.keys())}"
|
| 100 |
return size_map[vit_size]
|
| 101 |
|
| 102 |
|
| 103 |
+
def resize_vit_and_rebuild_vision_v1(
|
| 104 |
+
model,
|
| 105 |
+
*,
|
| 106 |
+
vit_size: str,
|
| 107 |
+
patch_size,
|
| 108 |
+
use_sdpa: bool = True,
|
| 109 |
+
mlp_ratio: float = 4.0,
|
| 110 |
+
image_size: int = 256,
|
| 111 |
+
in_channels: int = 1,
|
| 112 |
+
):
|
| 113 |
"""
|
| 114 |
+
Update vision_config values and rebuild vision_model (SigLIP v1 shell only).
|
| 115 |
+
The text branch is left untouched.
|
| 116 |
"""
|
| 117 |
cfg = _size_config(vit_size)
|
| 118 |
|
| 119 |
vconf = model.config.vision_config
|
| 120 |
tconf = model.config.text_config
|
| 121 |
|
| 122 |
+
vconf.num_hidden_layers = int(cfg["layers"])
|
| 123 |
+
vconf.hidden_size = int(cfg["hidden"])
|
| 124 |
vconf.num_attention_heads = int(cfg["heads"])
|
| 125 |
+
vconf.intermediate_size = int(vconf.hidden_size * mlp_ratio)
|
| 126 |
+
vconf.image_size = image_size
|
| 127 |
+
vconf.patch_size = patch_size
|
| 128 |
+
vconf.num_channels = in_channels
|
| 129 |
setattr(vconf, "_attn_implementation", "sdpa" if use_sdpa else "eager")
|
| 130 |
|
| 131 |
head_dim = vconf.hidden_size // vconf.num_attention_heads
|
| 132 |
assert head_dim % 2 == 0, f"head_dim must be even for RoPE, got {head_dim}"
|
| 133 |
|
| 134 |
+
# Keep the text-side projection dimension unchanged
|
| 135 |
+
if hasattr(tconf, "projection_size"):
|
| 136 |
+
tconf.projection_size = getattr(tconf, "projection_size")
|
| 137 |
+
if hasattr(tconf, "projection_dim"):
|
| 138 |
+
tconf.projection_dim = getattr(tconf, "projection_dim")
|
| 139 |
|
|
|
|
| 140 |
VisionCls = type(model.vision_model)
|
| 141 |
model.vision_model = VisionCls(vconf)
|
| 142 |
|
|
|
|
| 154 |
|
| 155 |
|
| 156 |
# -------------------------
|
| 157 |
+
# 3D embeddings
|
| 158 |
# -------------------------
|
| 159 |
+
def inject_3d_embeddings(
|
| 160 |
+
model,
|
| 161 |
+
*,
|
| 162 |
+
in_channels: int,
|
| 163 |
+
embed_dim: int,
|
| 164 |
+
patch_size,
|
| 165 |
+
pos_embed_type: str,
|
| 166 |
+
):
|
| 167 |
+
"""
|
| 168 |
+
Replace vision embeddings with the custom 3D embedding implementation.
|
| 169 |
+
"""
|
| 170 |
from vision import SiglipVisionEmbeddings3D
|
| 171 |
+
|
| 172 |
real = unwrap_model(model)
|
| 173 |
real.vision_model.embeddings = SiglipVisionEmbeddings3D(
|
| 174 |
in_channels=in_channels,
|
|
|
|
| 179 |
|
| 180 |
|
| 181 |
# -------------------------
|
| 182 |
+
# Projection alignment (vision -> text)
|
| 183 |
# -------------------------
|
| 184 |
def _get_text_proj_dim(model) -> int:
|
| 185 |
+
"""
|
| 186 |
+
Infer the text projection output dimension from the model or config.
|
| 187 |
+
"""
|
| 188 |
if hasattr(model, "text_projection") and isinstance(model.text_projection, torch.nn.Parameter):
|
| 189 |
return int(model.text_projection.shape[1])
|
| 190 |
+
|
| 191 |
d = getattr(model.config, "projection_dim", None)
|
| 192 |
if d is None and hasattr(model, "config") and hasattr(model.config, "text_config"):
|
| 193 |
+
d = (
|
| 194 |
+
getattr(model.config.text_config, "projection_size", None)
|
| 195 |
+
or getattr(model.config.text_config, "projection_dim", None)
|
| 196 |
)
|
| 197 |
+
|
| 198 |
return int(d) if d is not None else 768
|
| 199 |
|
| 200 |
|
| 201 |
def _set_all_visual_proj_aliases(model, param: torch.nn.Parameter):
|
| 202 |
+
"""
|
| 203 |
+
Register the same visual projection parameter under multiple common alias names.
|
| 204 |
+
"""
|
| 205 |
setattr(model, "visual_projection", param)
|
| 206 |
setattr(model, "vision_projection", param)
|
| 207 |
setattr(model, "image_projection", param)
|
|
|
|
| 209 |
|
| 210 |
def align_siglip_projection_to_text(model, target_dim: int = None):
|
| 211 |
"""
|
| 212 |
+
Align the visual projection matrix to the text-side projection dimension.
|
| 213 |
+
|
| 214 |
+
Behavior:
|
| 215 |
+
- Reuse an existing visual projection if its shape already matches
|
| 216 |
+
- Otherwise create a new (hidden_vis, target_dim) parameter
|
| 217 |
+
- Copy as many existing columns as possible from the old visual projection
|
| 218 |
+
- Do not modify the text projection itself
|
| 219 |
"""
|
| 220 |
real = unwrap_model(model)
|
| 221 |
|
|
|
|
| 224 |
|
| 225 |
vconf = getattr(real.config, "vision_config", None)
|
| 226 |
if vconf is None:
|
| 227 |
+
return
|
| 228 |
+
|
| 229 |
vis_in = int(vconf.hidden_size)
|
| 230 |
|
| 231 |
device = next(real.parameters()).device
|
| 232 |
dtype = next(real.parameters()).dtype
|
| 233 |
|
|
|
|
| 234 |
for name in ("visual_projection", "vision_projection", "image_projection"):
|
| 235 |
w = getattr(real, name, None)
|
| 236 |
if isinstance(w, torch.nn.Parameter) and w.ndim == 2 and w.shape == (vis_in, target_dim):
|
| 237 |
_set_all_visual_proj_aliases(real, w)
|
| 238 |
+
|
| 239 |
if hasattr(real.config, "projection_dim"):
|
| 240 |
real.config.projection_dim = target_dim
|
| 241 |
if hasattr(real.config, "vision_config"):
|
|
|
|
| 247 |
real.config.text_config.projection_dim = target_dim
|
| 248 |
return
|
| 249 |
|
|
|
|
| 250 |
new_w = torch.empty(vis_in, target_dim, dtype=dtype, device=device)
|
| 251 |
init_factor = getattr(real.config, "initializer_factor", 1.0)
|
| 252 |
nn.init.normal_(new_w, std=0.02 * init_factor)
|
|
|
|
| 276 |
|
| 277 |
|
| 278 |
# -------------------------
|
| 279 |
+
# Text RoPE initialization (once)
|
| 280 |
# -------------------------
|
| 281 |
def init_text_rope_once(model, base: float = 10000.0, max_len: Optional[int] = None) -> bool:
|
| 282 |
"""
|
| 283 |
+
Initialize text-side RoPE once.
|
| 284 |
+
|
| 285 |
+
Steps:
|
| 286 |
+
1. Replace text embeddings with a version without absolute position embedding
|
| 287 |
+
2. Patch the text encoder self-attention with a generic RoPE wrapper
|
| 288 |
+
3. Build shared 1D RoPE frequencies and assign them to all encoder layers
|
| 289 |
"""
|
| 290 |
real = unwrap_model(model)
|
| 291 |
|
|
|
|
|
|
|
| 292 |
txt = getattr(real, "text_model", None)
|
| 293 |
if txt is None:
|
| 294 |
+
raise ValueError("model.text_model was not found.")
|
| 295 |
+
|
| 296 |
if not isinstance(txt.embeddings, TextEmbeddingsNoAbsPos):
|
| 297 |
txt.embeddings = TextEmbeddingsNoAbsPos(txt.embeddings)
|
| 298 |
|
| 299 |
+
from models.rope_generic import build_rope_packed as text_build_packed
|
| 300 |
from models.rope_generic import patch_encoder_with_rope as patch_text_with_rope
|
| 301 |
from models.rope_generic import set_shared_axial_freqs as text_set_shared_freqs
|
|
|
|
| 302 |
|
| 303 |
enc = txt.encoder
|
| 304 |
+
|
| 305 |
+
need_patch = False
|
| 306 |
for lyr in enc.layers:
|
| 307 |
if not hasattr(lyr.self_attn, "set_freqs"):
|
| 308 |
+
need_patch = True
|
| 309 |
break
|
| 310 |
+
|
| 311 |
+
if need_patch:
|
| 312 |
patch_text_with_rope(enc)
|
| 313 |
|
|
|
|
| 314 |
if max_len is None:
|
|
|
|
| 315 |
max_len = getattr(real.config.text_config, "max_position_embeddings", 16)
|
| 316 |
+
|
| 317 |
head_dim = getattr(real.config.text_config, "hidden_size", 768) // getattr(
|
| 318 |
real.config.text_config, "num_attention_heads", 12
|
| 319 |
)
|
| 320 |
assert head_dim % 2 == 0, f"text head_dim must be even for RoPE, got {head_dim}"
|
| 321 |
|
| 322 |
+
freqs = text_build_packed(
|
| 323 |
+
L=max_len,
|
| 324 |
+
D=head_dim,
|
| 325 |
+
base=base,
|
| 326 |
+
device=next(real.parameters()).device,
|
| 327 |
+
dtype=next(real.parameters()).dtype,
|
| 328 |
+
)
|
| 329 |
+
text_set_shared_freqs(enc, freqs)
|
| 330 |
return True
|
| 331 |
|
| 332 |
+
|
| 333 |
+
def configure_text_pos_mode(
|
| 334 |
+
model,
|
| 335 |
+
*,
|
| 336 |
+
mode: str,
|
| 337 |
+
rope_base: float = 10000.0,
|
| 338 |
+
max_seq_len: int = 16,
|
| 339 |
+
) -> dict:
|
| 340 |
"""
|
| 341 |
+
Configure text-side positional encoding.
|
| 342 |
+
|
| 343 |
+
Modes:
|
| 344 |
+
- 'abs' : keep the default absolute position embedding
|
| 345 |
+
- 'rope' : remove absolute position embedding and initialize RoPE
|
| 346 |
"""
|
| 347 |
real = unwrap_model(model)
|
| 348 |
|
|
|
|
| 351 |
raise ValueError(f"text_pos_mode must be 'abs' or 'rope', got {mode}")
|
| 352 |
|
| 353 |
if mode == "abs":
|
|
|
|
|
|
|
| 354 |
return {"mode": "abs"}
|
| 355 |
|
|
|
|
|
|
|
| 356 |
init_text_rope_once(real, base=rope_base, max_len=max_seq_len)
|
| 357 |
return {"mode": "rope", "base": float(rope_base), "max_len": int(max_seq_len)}
|
| 358 |
|
| 359 |
|
| 360 |
# -------------------------
|
| 361 |
+
# Resize: rebuild text encoder
|
| 362 |
# -------------------------
|
| 363 |
def _size_config_text(text_size: str):
|
| 364 |
+
"""
|
| 365 |
+
Return text model size configuration.
|
| 366 |
+
Currently reuses the same size presets as the vision branch.
|
| 367 |
+
"""
|
| 368 |
+
return _size_config(text_size)
|
| 369 |
+
|
| 370 |
|
| 371 |
+
def resize_text_and_rebuild_v1(
|
| 372 |
+
model,
|
| 373 |
+
*,
|
| 374 |
+
text_size: str,
|
| 375 |
+
use_sdpa: bool = True,
|
| 376 |
+
mlp_ratio: float = 4.0,
|
| 377 |
+
vocab_size: int = None,
|
| 378 |
+
max_position_embeddings: int = 16,
|
| 379 |
+
):
|
| 380 |
"""
|
| 381 |
+
Update text_config values and rebuild text_model (SigLIP v1 shell only).
|
| 382 |
+
The vision branch is left untouched.
|
| 383 |
"""
|
| 384 |
real = unwrap_model(model)
|
| 385 |
cfg = _size_config_text(text_size)
|
| 386 |
|
| 387 |
tconf = real.config.text_config
|
| 388 |
+
tconf.num_hidden_layers = int(cfg["layers"])
|
| 389 |
+
tconf.hidden_size = int(cfg["hidden"])
|
| 390 |
tconf.num_attention_heads = int(cfg["heads"])
|
| 391 |
+
tconf.intermediate_size = int(tconf.hidden_size * mlp_ratio)
|
| 392 |
tconf.max_position_embeddings = int(max_position_embeddings)
|
| 393 |
setattr(tconf, "_attn_implementation", "sdpa" if use_sdpa else "eager")
|
| 394 |
|
|
|
|
| 400 |
if vocab_size is not None:
|
| 401 |
tconf.vocab_size = int(vocab_size)
|
| 402 |
|
|
|
|
| 403 |
TextCls = type(real.text_model)
|
| 404 |
real.text_model = TextCls(tconf)
|
| 405 |
|
|
|
|
| 417 |
"max_pos": tconf.max_position_embeddings,
|
| 418 |
}
|
| 419 |
|
| 420 |
+
|
| 421 |
# -------------------------
|
| 422 |
+
# Sanity check: no stray 768
|
| 423 |
# -------------------------
|
| 424 |
def assert_no_dim_768_left(model, expected_hidden: int):
|
| 425 |
"""
|
| 426 |
+
Check whether there are still modules using 768 where expected_hidden should be used
|
| 427 |
+
instead, such as Linear layers or LayerNorm dimensions.
|
| 428 |
"""
|
| 429 |
real = unwrap_model(model)
|
| 430 |
offenders = []
|
| 431 |
|
| 432 |
+
def _check_module(prefix: str, module: nn.Module):
|
| 433 |
nonlocal offenders
|
| 434 |
+
|
| 435 |
+
if isinstance(module, nn.Linear):
|
| 436 |
+
if module.in_features == 768 and module.in_features != expected_hidden:
|
| 437 |
+
offenders.append(f"{prefix}.in={module.in_features} (Linear)")
|
| 438 |
+
if module.out_features == 768 and module.out_features != expected_hidden:
|
| 439 |
+
offenders.append(f"{prefix}.out={module.out_features} (Linear)")
|
| 440 |
+
|
| 441 |
+
elif isinstance(module, nn.LayerNorm):
|
| 442 |
+
if tuple(module.normalized_shape) == (768,) and 768 != expected_hidden:
|
| 443 |
offenders.append(f"{prefix}.norm=768 (LayerNorm)")
|
| 444 |
|
| 445 |
for name, mod in real.named_modules():
|
| 446 |
_check_module(name, mod)
|
| 447 |
|
| 448 |
if offenders:
|
| 449 |
+
msg = (
|
| 450 |
+
"Found 768-shaped leftovers in modules that should use hidden_size "
|
| 451 |
+
f"{expected_hidden}:\n - " + "\n - ".join(offenders)
|
| 452 |
+
)
|
| 453 |
raise AssertionError(msg)
|
| 454 |
|
| 455 |
+
|
| 456 |
# -------------------------
|
| 457 |
+
# Metrics (first batch only)
|
| 458 |
# -------------------------
|
|
|
|
|
|
|
| 459 |
@torch.no_grad()
|
| 460 |
def compute_metrics(
|
| 461 |
model,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 462 |
dataloader,
|
| 463 |
tokenizer,
|
| 464 |
device,
|
| 465 |
max_txt_len: int = 16,
|
| 466 |
log_to_wandb: bool = True,
|
| 467 |
wandb_prefix: str = "eval",
|
| 468 |
+
make_heatmap: bool = True,
|
| 469 |
+
step=None,
|
| 470 |
):
|
| 471 |
"""
|
| 472 |
+
Evaluate only the first batch from the dataloader using 1:1 image-text pairs.
|
| 473 |
+
|
| 474 |
+
Behavior:
|
| 475 |
+
- Uses SigLIP-style logits_per_image / logits_per_text directly
|
| 476 |
+
- Computes i->t and t->i retrieval metrics:
|
| 477 |
+
- Recall@K
|
| 478 |
+
- MeanRank
|
| 479 |
+
- Top1Acc
|
| 480 |
+
- Optionally draws a row-wise softmax percentage heatmap for image->text
|
| 481 |
+
|
| 482 |
+
Returns:
|
| 483 |
+
A dictionary of evaluation metrics.
|
| 484 |
"""
|
| 485 |
model.eval()
|
| 486 |
+
|
| 487 |
try:
|
| 488 |
batch = next(iter(dataloader))
|
| 489 |
except StopIteration:
|
| 490 |
return {"error": "empty dataloader"}
|
| 491 |
|
| 492 |
images = batch["pixel_values"].to(device, non_blocking=True)
|
| 493 |
+
texts = batch["text"]
|
| 494 |
+
|
| 495 |
+
tokenized = tokenizer(
|
| 496 |
+
texts,
|
| 497 |
+
padding="max_length",
|
| 498 |
+
truncation=True,
|
| 499 |
+
max_length=max_txt_len,
|
| 500 |
+
return_tensors="pt",
|
| 501 |
)
|
| 502 |
+
tokenized = {k: v.to(device, non_blocking=True) for k, v in tokenized.items()}
|
| 503 |
|
|
|
|
| 504 |
outputs = model(
|
| 505 |
+
input_ids=tokenized["input_ids"],
|
| 506 |
pixel_values=images,
|
| 507 |
+
return_dict=True,
|
| 508 |
)
|
| 509 |
|
| 510 |
+
sims_i2t = outputs.logits_per_image
|
| 511 |
+
sims_t2i = outputs.logits_per_text
|
| 512 |
|
| 513 |
+
batch_size = sims_i2t.size(0)
|
| 514 |
+
idx = torch.arange(batch_size, device=sims_i2t.device)
|
| 515 |
|
| 516 |
+
def recall_at_k(sim: torch.Tensor, k: int):
|
| 517 |
k = min(k, sim.size(1))
|
| 518 |
+
ranks = torch.argsort(sim, dim=1, descending=True)
|
| 519 |
+
topk = ranks[:, :k]
|
| 520 |
+
hits = (topk == idx.unsqueeze(1)).any(dim=1).float().mean().item()
|
| 521 |
+
pos = (ranks == idx.unsqueeze(1)).nonzero(as_tuple=False)[:, 1]
|
| 522 |
+
mean_rank = pos.float().mean().item() + 1.0
|
| 523 |
return hits, mean_rank
|
| 524 |
|
|
|
|
| 525 |
r1_i2t, mr_i2t = recall_at_k(sims_i2t, 1)
|
| 526 |
+
r5_i2t, _ = recall_at_k(sims_i2t, 5)
|
| 527 |
+
r10_i2t, _ = recall_at_k(sims_i2t, 10)
|
| 528 |
+
|
| 529 |
r1_t2i, mr_t2i = recall_at_k(sims_t2i, 1)
|
| 530 |
+
r5_t2i, _ = recall_at_k(sims_t2i, 5)
|
| 531 |
+
r10_t2i, _ = recall_at_k(sims_t2i, 10)
|
| 532 |
|
| 533 |
+
top1_i2t = float((sims_i2t.argmax(dim=1).cpu().numpy() == np.arange(batch_size)).mean())
|
| 534 |
+
top1_t2i = float((sims_t2i.argmax(dim=1).cpu().numpy() == np.arange(batch_size)).mean())
|
|
|
|
| 535 |
|
| 536 |
out = {
|
| 537 |
+
"pairs_in_batch": int(batch_size),
|
| 538 |
+
"i2t/R@1": r1_i2t,
|
| 539 |
+
"i2t/R@5": r5_i2t,
|
| 540 |
+
"i2t/R@10": r10_i2t,
|
| 541 |
+
"i2t/MeanRank": mr_i2t,
|
| 542 |
+
"t2i/R@1": r1_t2i,
|
| 543 |
+
"t2i/R@5": r5_t2i,
|
| 544 |
+
"t2i/R@10": r10_t2i,
|
| 545 |
+
"t2i/MeanRank": mr_t2i,
|
| 546 |
"i2t/Top1Acc": top1_i2t,
|
| 547 |
"t2i/Top1Acc": top1_t2i,
|
|
|
|
|
|
|
|
|
|
|
|
|
| 548 |
}
|
| 549 |
|
|
|
|
| 550 |
if make_heatmap:
|
| 551 |
try:
|
| 552 |
import matplotlib.pyplot as plt
|
| 553 |
|
| 554 |
with torch.no_grad():
|
| 555 |
+
mat = sims_i2t.detach().float().cpu().numpy()
|
|
|
|
| 556 |
mat = mat - mat.max(axis=1, keepdims=True)
|
| 557 |
prob = np.exp(mat)
|
| 558 |
prob /= prob.sum(axis=1, keepdims=True) + 1e-12
|
| 559 |
|
| 560 |
+
fig, ax = plt.subplots(
|
| 561 |
+
figsize=(min(12, batch_size * 0.3 + 2), min(12, batch_size * 0.3 + 2))
|
| 562 |
+
)
|
| 563 |
+
im = ax.imshow(prob, aspect="auto")
|
| 564 |
+
|
| 565 |
+
ax.set_title(f"Image→Text softmax % (B={batch_size})")
|
| 566 |
+
ax.set_xlabel("Text index")
|
| 567 |
+
ax.set_ylabel("Image index")
|
| 568 |
+
ax.set_xticks(range(batch_size))
|
| 569 |
+
ax.set_yticks(range(batch_size))
|
| 570 |
|
| 571 |
+
for i in range(batch_size):
|
| 572 |
+
for j in range(batch_size):
|
|
|
|
| 573 |
p = int(round(prob[i, j] * 100))
|
| 574 |
txt = f"{p}%" if p >= 1 else "0%"
|
| 575 |
ax.text(j, i, txt, ha="center", va="center", fontsize=8)
|
| 576 |
|
| 577 |
+
for i in range(batch_size):
|
| 578 |
+
rect = plt.Rectangle((i - 0.5, i - 0.5), 1, 1, fill=False, linewidth=1.5)
|
|
|
|
| 579 |
ax.add_patch(rect)
|
| 580 |
|
| 581 |
fig.colorbar(im, ax=ax, fraction=0.046, pad=0.04)
|
|
|
|
| 584 |
if log_to_wandb:
|
| 585 |
try:
|
| 586 |
import wandb
|
| 587 |
+
|
| 588 |
if wandb.run is not None:
|
| 589 |
wandb.log({f"{wandb_prefix}/batch_heatmap": wandb.Image(fig)}, step=step)
|
| 590 |
except Exception as e:
|
| 591 |
+
print(f"[WARN] wandb heatmap logging failed: {e}")
|
| 592 |
+
|
| 593 |
plt.close(fig)
|
| 594 |
+
|
| 595 |
except Exception as e:
|
| 596 |
print(f"[WARN] heatmap plotting failed: {e}")
|
| 597 |
|
|
|
|
| 601 |
# -------------------------
|
| 602 |
# Optimizer (Muon + Adam)
|
| 603 |
# -------------------------
|
| 604 |
+
def _split_params_by_dim(
|
| 605 |
+
params: Iterable[torch.nn.Parameter],
|
| 606 |
+
) -> Tuple[List[torch.nn.Parameter], List[torch.nn.Parameter]]:
|
| 607 |
+
"""
|
| 608 |
+
Split parameters into:
|
| 609 |
+
- weights: ndim >= 2, typically sent to Muon
|
| 610 |
+
- bias/norm: ndim < 2, typically sent to Adam
|
| 611 |
+
"""
|
| 612 |
weights, bias_norm = [], []
|
| 613 |
+
|
| 614 |
for p in params:
|
| 615 |
if not p.requires_grad:
|
| 616 |
continue
|
| 617 |
(weights if p.ndim >= 2 else bias_norm).append(p)
|
| 618 |
+
|
| 619 |
return weights, bias_norm
|
| 620 |
|
| 621 |
+
|
| 622 |
def build_optimizer_with_muon(model, lr: float, weight_decay: float):
|
| 623 |
+
"""
|
| 624 |
+
Build a hybrid optimizer:
|
| 625 |
+
- Muon for matrix/tensor weights
|
| 626 |
+
- Adam-style auxiliary optimizer for bias, norm, projection, and temperature terms
|
| 627 |
+
"""
|
| 628 |
real = unwrap_model(model)
|
| 629 |
|
|
|
|
| 630 |
img_w, img_b = _split_params_by_dim(real.vision_model.parameters())
|
| 631 |
txt_w, txt_b = _split_params_by_dim(real.text_model.parameters())
|
| 632 |
|
|
|
|
| 633 |
extra = []
|
| 634 |
+
|
| 635 |
if hasattr(real, "projection"):
|
| 636 |
for p in real.projection.parameters():
|
| 637 |
if p.requires_grad:
|
| 638 |
extra.append(p)
|
| 639 |
+
|
| 640 |
if hasattr(real, "visual_projection") and isinstance(real.visual_projection, torch.nn.Parameter):
|
| 641 |
if real.visual_projection.requires_grad:
|
| 642 |
extra.append(real.visual_projection)
|
| 643 |
+
|
| 644 |
if hasattr(real, "text_projection") and isinstance(real.text_projection, torch.nn.Parameter):
|
| 645 |
if real.text_projection.requires_grad:
|
| 646 |
extra.append(real.text_projection)
|
| 647 |
+
|
| 648 |
if hasattr(real, "logit_scale") and getattr(real.logit_scale, "requires_grad", False):
|
| 649 |
extra.append(real.logit_scale)
|
| 650 |
+
|
| 651 |
if hasattr(real, "logit_bias") and getattr(real.logit_bias, "requires_grad", False):
|
| 652 |
extra.append(real.logit_bias)
|
| 653 |
|
|
|
|
| 654 |
param_groups = [
|
| 655 |
+
dict(
|
| 656 |
+
params=[*img_w, *txt_w],
|
| 657 |
+
use_muon=True,
|
| 658 |
+
lr=lr,
|
| 659 |
+
weight_decay=weight_decay,
|
| 660 |
+
),
|
| 661 |
+
dict(
|
| 662 |
+
params=[*img_b, *txt_b, *extra],
|
| 663 |
+
use_muon=False,
|
| 664 |
+
lr=lr,
|
| 665 |
+
betas=(0.9, 0.95),
|
| 666 |
+
weight_decay=weight_decay,
|
| 667 |
+
),
|
| 668 |
]
|
| 669 |
return MuonWithAuxAdam(param_groups)
|
| 670 |
|
| 671 |
|
| 672 |
def swap_text_to_no_abs_pos(model) -> bool:
|
| 673 |
"""
|
| 674 |
+
Replace text_model.embeddings with the no-absolute-position version.
|
| 675 |
+
|
| 676 |
+
Behavior:
|
| 677 |
+
- Automatically unwraps DDP-style wrappers
|
| 678 |
+
- Returns False if the replacement has already been applied
|
| 679 |
+
- Returns True if the replacement is performed
|
| 680 |
"""
|
| 681 |
real = unwrap_model(model)
|
| 682 |
|
| 683 |
txt = getattr(real, "text_model", None)
|
| 684 |
if txt is None:
|
| 685 |
+
raise ValueError("swap_text_to_no_abs_pos: model.text_model was not found.")
|
| 686 |
|
| 687 |
emb = getattr(txt, "embeddings", None)
|
| 688 |
if emb is None:
|
| 689 |
+
raise ValueError("swap_text_to_no_abs_pos: text_model.embeddings was not found.")
|
| 690 |
|
| 691 |
if TextEmbeddingsNoAbsPos is None:
|
| 692 |
raise ImportError(
|
| 693 |
+
"swap_text_to_no_abs_pos requires vision.TextEmbeddingsNoAbsPos. "
|
| 694 |
+
"Please make sure it is defined in vision.py and importable."
|
| 695 |
)
|
| 696 |
|
| 697 |
if isinstance(emb, TextEmbeddingsNoAbsPos):
|
|
|
|
| 698 |
return False
|
| 699 |
|
| 700 |
txt.embeddings = TextEmbeddingsNoAbsPos(emb)
|
| 701 |
+
return True
|