Update models/rope_generic.py
Browse files- models/rope_generic.py +286 -190
models/rope_generic.py
CHANGED
|
@@ -1,264 +1,328 @@
|
|
| 1 |
-
# --- monkey_patch_siglip_rope.py(可直接粘贴到 train_new.py 顶部或引入) ---
|
| 2 |
import types
|
| 3 |
import torch
|
| 4 |
import torch.nn as nn
|
| 5 |
import torch.nn.functional as F
|
| 6 |
from transformers.models.siglip.modeling_siglip import SiglipAttention
|
| 7 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 8 |
def enable_text_rope_in_attention(rope_base: float = 10000.0):
|
| 9 |
"""
|
| 10 |
-
|
|
|
|
|
|
|
|
|
|
| 11 |
"""
|
| 12 |
if hasattr(SiglipAttention, "_orig_forward_text"):
|
| 13 |
print("[Text RoPE] already patched")
|
| 14 |
return
|
| 15 |
-
SiglipAttention._orig_forward_text = SiglipAttention.forward
|
| 16 |
|
| 17 |
-
|
| 18 |
-
x1, x2 = x[..., : x.shape[-1] // 2], x[..., x.shape[-1] // 2 :]
|
| 19 |
-
return torch.cat([-x2, x1], dim=-1)
|
| 20 |
|
| 21 |
def patched_forward(self, hidden_states, *args, **kwargs):
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
q, k, v = map(shape, (q, k, v))
|
| 40 |
-
|
| 41 |
-
# --- 动态计算 RoPE ---
|
| 42 |
-
device = q.device
|
| 43 |
-
pos = torch.arange(L, device=device, dtype=torch.float32) # (L,)
|
| 44 |
-
inv_freq = 1.0 / (rope_base ** (torch.arange(0, head_dim, 2, device=device).float() / head_dim))
|
| 45 |
-
freqs = torch.outer(pos, inv_freq) # (L, head_dim/2)
|
| 46 |
-
cos = freqs.cos().repeat_interleave(2, dim=-1)[None, None, :, :] # (1,1,L,head_dim)
|
| 47 |
-
sin = freqs.sin().repeat_interleave(2, dim=-1)[None, None, :, :] # (1,1,L,head_dim)
|
| 48 |
-
|
| 49 |
-
q = q * cos + rotate_half(q) * sin
|
| 50 |
-
k = k * cos + rotate_half(k) * sin
|
| 51 |
-
|
| 52 |
-
# --- 注意力 ---
|
| 53 |
attn_scores = torch.matmul(q, k.transpose(-2, -1)) / (head_dim ** 0.5)
|
|
|
|
| 54 |
attn_mask = kwargs.get("attention_mask", None)
|
| 55 |
if attn_mask is not None:
|
| 56 |
attn_scores = attn_scores + attn_mask
|
|
|
|
| 57 |
attn_probs = F.softmax(attn_scores, dim=-1, dtype=torch.float32).to(q.dtype)
|
| 58 |
attn_output = torch.matmul(attn_probs, v)
|
| 59 |
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
if hasattr(self, "proj"):
|
| 63 |
-
out = self.proj(attn_output)
|
| 64 |
-
elif hasattr(self, "out_proj"):
|
| 65 |
-
out = self.out_proj(attn_output)
|
| 66 |
-
else:
|
| 67 |
-
out = attn_output
|
| 68 |
|
| 69 |
-
return out, None
|
| 70 |
|
| 71 |
SiglipAttention.forward = patched_forward
|
| 72 |
print(f"[Text RoPE] Enabled dynamic RoPE in SiglipAttention (base={rope_base})")
|
| 73 |
|
| 74 |
|
| 75 |
def monkey_patch_siglip_rope():
|
|
|
|
|
|
|
|
|
|
|
|
|
| 76 |
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
return torch.cat([-x2, x1], dim=-1)
|
| 82 |
|
| 83 |
-
def
|
| 84 |
-
"""
|
| 85 |
-
q, k: (B, H, L, Hd)
|
| 86 |
-
packed_freqs: (L, 2*Hd) 或 (1,1,L,2*Hd) 皆可
|
| 87 |
-
"""
|
| 88 |
-
if packed_freqs.dim() == 2:
|
| 89 |
-
# (L, 2*Hd) -> (1,1,L,2*Hd)
|
| 90 |
-
packed = packed_freqs.unsqueeze(0).unsqueeze(0)
|
| 91 |
-
elif packed_freqs.dim() == 4:
|
| 92 |
-
packed = packed_freqs
|
| 93 |
-
else:
|
| 94 |
-
raise ValueError(f"Unexpected freqs shape: {packed_freqs.shape}")
|
| 95 |
-
|
| 96 |
-
# cos/sin 拆分并广播到 (B,H,L,Hd)
|
| 97 |
-
cos = packed[..., :head_dim] # (1,1,L,Hd)
|
| 98 |
-
sin = packed[..., head_dim:] # (1,1,L,Hd)
|
| 99 |
-
|
| 100 |
-
# 旋转
|
| 101 |
-
q = q * cos + rotate_half(q) * sin
|
| 102 |
-
k = k * cos + rotate_half(k) * sin
|
| 103 |
-
return q, k
|
| 104 |
-
|
| 105 |
-
# ---- 给类加 set_freqs(供 set_shared_axial_freqs 调用)----
|
| 106 |
-
def set_freqs(self, freqs):
|
| 107 |
-
"""
|
| 108 |
-
freqs: 期望 (L, 2*head_dim) 或已带 batch/head 维的 (1,1,L,2*head_dim)
|
| 109 |
-
注意:L 要与当前注意力输入的序列长度一致(视觉 patch 数),
|
| 110 |
-
你在 prepare_vision_rope 里已经按 (Dx*Dy*Dz) 生成好了。
|
| 111 |
-
"""
|
| 112 |
self.rope_freqs = freqs
|
| 113 |
|
| 114 |
-
# 绑定到类(所有实例共享)
|
| 115 |
SiglipAttention.set_freqs = set_freqs
|
| 116 |
|
| 117 |
-
# ---- 包装 forward:在 q/k 上应用 RoPE ----
|
| 118 |
if not hasattr(SiglipAttention, "_orig_forward"):
|
| 119 |
-
SiglipAttention._orig_forward = SiglipAttention.forward
|
| 120 |
|
| 121 |
def patched_forward(self, hidden_states, *args, **kwargs):
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
if hasattr(self, "qkv"):
|
| 132 |
-
qkv = self.qkv(hidden_states) # (B, L, 3*D)
|
| 133 |
-
q, k, v = qkv.split(C, dim=-1) if qkv.shape[-1] == 3 * C else torch.chunk(qkv, 3, dim=-1)
|
| 134 |
-
else:
|
| 135 |
-
q = self.q_proj(hidden_states)
|
| 136 |
-
k = self.k_proj(hidden_states)
|
| 137 |
-
v = self.v_proj(hidden_states)
|
| 138 |
-
|
| 139 |
-
# Head 维度信息
|
| 140 |
-
H = getattr(self, "num_heads", None)
|
| 141 |
-
Hd = getattr(self, "head_dim", None)
|
| 142 |
-
if H is None or Hd is None:
|
| 143 |
-
# 部分实现用 embed_dim / num_heads 推出
|
| 144 |
-
embed_dim = q.shape[-1]
|
| 145 |
-
if hasattr(self, "num_heads"):
|
| 146 |
-
H = self.num_heads
|
| 147 |
-
Hd = embed_dim // H
|
| 148 |
-
elif hasattr(self, "head_dim"):
|
| 149 |
-
Hd = self.head_dim
|
| 150 |
-
H = embed_dim // Hd
|
| 151 |
-
else:
|
| 152 |
-
raise AttributeError("Cannot infer num_heads/head_dim from SiglipAttention.")
|
| 153 |
-
|
| 154 |
-
# ---- 2. 变形到 (B, H, L, Hd) ----
|
| 155 |
-
def reshape_to_bhlh(x):
|
| 156 |
-
return x.view(B, L, H, Hd).transpose(1, 2).contiguous() # (B,H,L,Hd)
|
| 157 |
-
|
| 158 |
-
q = reshape_to_bhlh(q)
|
| 159 |
-
k = reshape_to_bhlh(k)
|
| 160 |
-
v = reshape_to_bhlh(v)
|
| 161 |
-
|
| 162 |
-
# ---- 3. 应用 RoPE(若已设置 freqs)----
|
| 163 |
freqs = getattr(self, "rope_freqs", None)
|
| 164 |
if freqs is not None:
|
| 165 |
-
# 允许 freqs 在 GPU/CPU 上不一致,自动搬运
|
| 166 |
freqs = freqs.to(q.device)
|
| 167 |
-
|
| 168 |
if freqs.dim() == 2:
|
| 169 |
-
if freqs.shape[0] <
|
| 170 |
-
raise ValueError(
|
| 171 |
-
|
| 172 |
-
|
|
|
|
|
|
|
| 173 |
elif freqs.dim() == 4:
|
| 174 |
-
if freqs.shape[-2] <
|
| 175 |
-
raise ValueError(
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
|
| 180 |
|
| 181 |
-
|
| 182 |
-
|
|
|
|
| 183 |
|
| 184 |
-
# 可选的 attention_mask(适配 kwargs)
|
| 185 |
attn_mask = kwargs.get("attention_mask", None)
|
| 186 |
if attn_mask is not None:
|
| 187 |
-
# 期望 (B,1,1,L) 或 (B,1,L,L);最简单以加法方式处理
|
| 188 |
attn_scores = attn_scores + attn_mask
|
| 189 |
|
| 190 |
attn_probs = F.softmax(attn_scores, dim=-1, dtype=torch.float32).to(q.dtype)
|
| 191 |
-
attn_output = torch.matmul(attn_probs, v)
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
if hasattr(self, "proj"):
|
| 198 |
-
out = self.proj(attn_output)
|
| 199 |
-
elif hasattr(self, "out_proj"):
|
| 200 |
-
out = self.out_proj(attn_output)
|
| 201 |
-
elif hasattr(self, "o_proj"):
|
| 202 |
-
out = self.o_proj(attn_output)
|
| 203 |
-
else:
|
| 204 |
-
# 如果原 forward 还做了别的(dropout/residual),退回原 forward
|
| 205 |
-
# 用原 forward 计算,但把我们算好的结果替代其中的中间变量并返回
|
| 206 |
-
return SiglipAttention._orig_forward(self, hidden_states, *args, **kwargs)
|
| 207 |
|
| 208 |
-
return
|
| 209 |
|
| 210 |
-
# 绑定 patched forward
|
| 211 |
SiglipAttention.forward = patched_forward
|
| 212 |
print("[RoPE] SiglipAttention monkey-patched with set_freqs() and RoPE-enabled forward().")
|
| 213 |
|
| 214 |
-
# --- 使用方式 ---
|
| 215 |
-
# 在构建好模型后调用一次(确保 import 了 transformers):
|
| 216 |
-
# model = AutoModel.from_pretrained(...); # 先有类定义
|
| 217 |
-
# monkey_patch_siglip_rope()
|
| 218 |
-
# 之后再跑你的 prepare_vision_rope(...)-> set_shared_axial_freqs(...)-> set_freqs() 流程
|
| 219 |
-
|
| 220 |
|
| 221 |
-
def _resize_abs_pos_embedding(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 222 |
"""
|
| 223 |
-
|
| 224 |
"""
|
| 225 |
if not hasattr(text_embeddings, "position_embedding"):
|
| 226 |
-
#
|
| 227 |
if hasattr(text_config, "max_position_embeddings"):
|
| 228 |
text_config.max_position_embeddings = max_seq_len
|
| 229 |
-
print(
|
|
|
|
|
|
|
|
|
|
| 230 |
return
|
| 231 |
|
| 232 |
old_pe: nn.Embedding = text_embeddings.position_embedding
|
| 233 |
-
old_len,
|
|
|
|
|
|
|
| 234 |
|
| 235 |
-
new_pe = nn.Embedding(max_seq_len, hidden)
|
| 236 |
with torch.no_grad():
|
| 237 |
if zero_init:
|
| 238 |
new_pe.weight.zero_()
|
| 239 |
else:
|
| 240 |
copy_n = min(old_len, max_seq_len)
|
| 241 |
new_pe.weight[:copy_n].copy_(old_pe.weight[:copy_n])
|
|
|
|
| 242 |
if max_seq_len > copy_n:
|
| 243 |
std = float(old_pe.weight.std().item() if old_len > 0 else 0.02)
|
| 244 |
nn.init.normal_(new_pe.weight[copy_n:], mean=0.0, std=std)
|
| 245 |
|
| 246 |
text_embeddings.position_embedding = new_pe
|
| 247 |
|
| 248 |
-
# 同步修改 config(forward 会检查这个)
|
| 249 |
if hasattr(text_config, "max_position_embeddings"):
|
| 250 |
text_config.max_position_embeddings = max_seq_len
|
| 251 |
|
| 252 |
-
print(
|
| 253 |
-
|
|
|
|
|
|
|
|
|
|
| 254 |
|
| 255 |
def _patch_text_embeddings_remove_abs(text_embeddings: nn.Module):
|
| 256 |
"""
|
| 257 |
-
Monkey
|
| 258 |
-
-
|
| 259 |
-
-
|
| 260 |
-
-
|
| 261 |
"""
|
|
|
|
| 262 |
def forward_no_pos(self, input_ids=None, position_ids=None, inputs_embeds=None, **kwargs):
|
| 263 |
if inputs_embeds is None:
|
| 264 |
inputs_embeds = self.token_embedding(input_ids)
|
|
@@ -266,18 +330,30 @@ def _patch_text_embeddings_remove_abs(text_embeddings: nn.Module):
|
|
| 266 |
|
| 267 |
text_embeddings.forward = types.MethodType(forward_no_pos, text_embeddings)
|
| 268 |
|
| 269 |
-
#
|
| 270 |
if hasattr(text_embeddings, "position_embedding"):
|
| 271 |
delattr(text_embeddings, "position_embedding")
|
| 272 |
|
| 273 |
-
print("[Text Pos] Patched: removed ABS position addition
|
| 274 |
|
| 275 |
|
| 276 |
-
def configure_text_pos_mode(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 277 |
"""
|
| 278 |
-
|
| 279 |
-
|
| 280 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 281 |
"""
|
| 282 |
text_model = getattr(model, "text_model", None)
|
| 283 |
if text_model is None:
|
|
@@ -285,24 +361,44 @@ def configure_text_pos_mode(model, mode: str, rope_base: float = None, max_seq_l
|
|
| 285 |
|
| 286 |
text_embeddings = getattr(text_model, "embeddings", None)
|
| 287 |
text_config = getattr(text_model, "config", None)
|
|
|
|
| 288 |
if text_embeddings is None or text_config is None:
|
| 289 |
-
raise ValueError("SigLIP text_model missing embeddings/config")
|
| 290 |
|
| 291 |
if mode == "abs":
|
| 292 |
-
print(
|
| 293 |
-
|
|
|
|
|
|
|
|
|
|
| 294 |
return
|
| 295 |
|
| 296 |
if mode == "rope":
|
| 297 |
-
# 1) 去掉 position embedding 的相加 & 长度检查
|
| 298 |
_patch_text_embeddings_remove_abs(text_embeddings)
|
| 299 |
|
| 300 |
-
# 2) 避免长度检查出错:直接给个超大值
|
| 301 |
if hasattr(text_config, "max_position_embeddings"):
|
| 302 |
text_config.max_position_embeddings = int(1e9)
|
| 303 |
|
| 304 |
-
print(
|
| 305 |
-
|
|
|
|
|
|
|
|
|
|
| 306 |
return
|
| 307 |
|
| 308 |
raise ValueError(f"Unknown text pos mode: {mode}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import types
|
| 2 |
import torch
|
| 3 |
import torch.nn as nn
|
| 4 |
import torch.nn.functional as F
|
| 5 |
from transformers.models.siglip.modeling_siglip import SiglipAttention
|
| 6 |
|
| 7 |
+
|
| 8 |
+
def _rotate_half(x: torch.Tensor) -> torch.Tensor:
|
| 9 |
+
"""
|
| 10 |
+
Rotate the last dimension by half.
|
| 11 |
+
For a tensor shaped (..., 2*d), split it into two halves and rotate:
|
| 12 |
+
[x1, x2] -> [-x2, x1]
|
| 13 |
+
"""
|
| 14 |
+
x1, x2 = x[..., : x.shape[-1] // 2], x[..., x.shape[-1] // 2 :]
|
| 15 |
+
return torch.cat([-x2, x1], dim=-1)
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def _build_1d_rope_cache(
|
| 19 |
+
seq_len: int,
|
| 20 |
+
head_dim: int,
|
| 21 |
+
device: torch.device,
|
| 22 |
+
rope_base: float = 10000.0,
|
| 23 |
+
) -> tuple[torch.Tensor, torch.Tensor]:
|
| 24 |
+
"""
|
| 25 |
+
Build dynamic 1D RoPE cosine and sine caches.
|
| 26 |
+
|
| 27 |
+
Returns:
|
| 28 |
+
cos: (1, 1, L, Hd)
|
| 29 |
+
sin: (1, 1, L, Hd)
|
| 30 |
+
"""
|
| 31 |
+
pos = torch.arange(seq_len, device=device, dtype=torch.float32) # (L,)
|
| 32 |
+
inv_freq = 1.0 / (
|
| 33 |
+
rope_base ** (torch.arange(0, head_dim, 2, device=device).float() / head_dim)
|
| 34 |
+
)
|
| 35 |
+
freqs = torch.outer(pos, inv_freq) # (L, Hd/2)
|
| 36 |
+
|
| 37 |
+
cos = freqs.cos().repeat_interleave(2, dim=-1)[None, None, :, :] # (1,1,L,Hd)
|
| 38 |
+
sin = freqs.sin().repeat_interleave(2, dim=-1)[None, None, :, :] # (1,1,L,Hd)
|
| 39 |
+
return cos, sin
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def _apply_rope(q: torch.Tensor, k: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor):
|
| 43 |
+
"""
|
| 44 |
+
Apply RoPE to query and key.
|
| 45 |
+
|
| 46 |
+
Args:
|
| 47 |
+
q, k: (B, H, L, Hd)
|
| 48 |
+
cos, sin: broadcastable to (B, H, L, Hd)
|
| 49 |
+
"""
|
| 50 |
+
q = q * cos + _rotate_half(q) * sin
|
| 51 |
+
k = k * cos + _rotate_half(k) * sin
|
| 52 |
+
return q, k
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def _apply_rope_to_qk(
|
| 56 |
+
q: torch.Tensor,
|
| 57 |
+
k: torch.Tensor,
|
| 58 |
+
packed_freqs: torch.Tensor,
|
| 59 |
+
head_dim: int,
|
| 60 |
+
) -> tuple[torch.Tensor, torch.Tensor]:
|
| 61 |
+
"""
|
| 62 |
+
Apply RoPE using pre-packed frequency tensors.
|
| 63 |
+
|
| 64 |
+
Args:
|
| 65 |
+
q, k: (B, H, L, Hd)
|
| 66 |
+
packed_freqs:
|
| 67 |
+
- (L, 2*Hd), or
|
| 68 |
+
- (1, 1, L, 2*Hd), or compatible 4D tensor
|
| 69 |
+
"""
|
| 70 |
+
if packed_freqs.dim() == 2:
|
| 71 |
+
packed = packed_freqs.unsqueeze(0).unsqueeze(0) # (1,1,L,2*Hd)
|
| 72 |
+
elif packed_freqs.dim() == 4:
|
| 73 |
+
packed = packed_freqs
|
| 74 |
+
else:
|
| 75 |
+
raise ValueError(f"Unexpected freqs shape: {packed_freqs.shape}")
|
| 76 |
+
|
| 77 |
+
cos = packed[..., :head_dim]
|
| 78 |
+
sin = packed[..., head_dim:]
|
| 79 |
+
return _apply_rope(q, k, cos, sin)
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
def _project_qkv(self, hidden_states: torch.Tensor):
|
| 83 |
+
"""
|
| 84 |
+
Extract q, k, v from either:
|
| 85 |
+
- fused qkv projection, or
|
| 86 |
+
- separate q_proj / k_proj / v_proj
|
| 87 |
+
"""
|
| 88 |
+
bsz, seq_len, embed_dim = hidden_states.shape
|
| 89 |
+
|
| 90 |
+
if hasattr(self, "qkv"):
|
| 91 |
+
qkv = self.qkv(hidden_states)
|
| 92 |
+
if qkv.shape[-1] == 3 * embed_dim:
|
| 93 |
+
q, k, v = qkv.split(embed_dim, dim=-1)
|
| 94 |
+
else:
|
| 95 |
+
q, k, v = torch.chunk(qkv, 3, dim=-1)
|
| 96 |
+
else:
|
| 97 |
+
q = self.q_proj(hidden_states)
|
| 98 |
+
k = self.k_proj(hidden_states)
|
| 99 |
+
v = self.v_proj(hidden_states)
|
| 100 |
+
|
| 101 |
+
return q, k, v
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
def _infer_heads(self, q: torch.Tensor) -> tuple[int, int]:
|
| 105 |
+
"""
|
| 106 |
+
Infer number of heads and head dimension from attention module attributes.
|
| 107 |
+
"""
|
| 108 |
+
num_heads = getattr(self, "num_heads", None)
|
| 109 |
+
head_dim = getattr(self, "head_dim", None)
|
| 110 |
+
|
| 111 |
+
if num_heads is None or head_dim is None:
|
| 112 |
+
embed_dim = q.shape[-1]
|
| 113 |
+
|
| 114 |
+
if hasattr(self, "num_heads"):
|
| 115 |
+
num_heads = self.num_heads
|
| 116 |
+
head_dim = embed_dim // num_heads
|
| 117 |
+
elif hasattr(self, "head_dim"):
|
| 118 |
+
head_dim = self.head_dim
|
| 119 |
+
num_heads = embed_dim // head_dim
|
| 120 |
+
else:
|
| 121 |
+
raise AttributeError("Cannot infer num_heads/head_dim from SiglipAttention.")
|
| 122 |
+
|
| 123 |
+
return num_heads, head_dim
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
def _reshape_to_bhld(x: torch.Tensor, bsz: int, seq_len: int, num_heads: int, head_dim: int):
|
| 127 |
+
"""
|
| 128 |
+
Reshape (B, L, C) -> (B, H, L, Hd)
|
| 129 |
+
"""
|
| 130 |
+
return x.view(bsz, seq_len, num_heads, head_dim).transpose(1, 2).contiguous()
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
def _merge_heads(x: torch.Tensor, bsz: int, seq_len: int, num_heads: int, head_dim: int):
|
| 134 |
+
"""
|
| 135 |
+
Reshape (B, H, L, Hd) -> (B, L, C)
|
| 136 |
+
"""
|
| 137 |
+
return x.transpose(1, 2).contiguous().view(bsz, seq_len, num_heads * head_dim)
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
def _output_projection(self, attn_output: torch.Tensor):
|
| 141 |
+
"""
|
| 142 |
+
Apply the output projection if available.
|
| 143 |
+
"""
|
| 144 |
+
if hasattr(self, "proj"):
|
| 145 |
+
return self.proj(attn_output)
|
| 146 |
+
if hasattr(self, "out_proj"):
|
| 147 |
+
return self.out_proj(attn_output)
|
| 148 |
+
if hasattr(self, "o_proj"):
|
| 149 |
+
return self.o_proj(attn_output)
|
| 150 |
+
return attn_output
|
| 151 |
+
|
| 152 |
+
|
| 153 |
def enable_text_rope_in_attention(rope_base: float = 10000.0):
|
| 154 |
"""
|
| 155 |
+
Monkey-patch SiglipAttention.forward to dynamically apply 1D RoPE
|
| 156 |
+
inside attention for the text branch.
|
| 157 |
+
|
| 158 |
+
This version computes RoPE on the fly from sequence length.
|
| 159 |
"""
|
| 160 |
if hasattr(SiglipAttention, "_orig_forward_text"):
|
| 161 |
print("[Text RoPE] already patched")
|
| 162 |
return
|
|
|
|
| 163 |
|
| 164 |
+
SiglipAttention._orig_forward_text = SiglipAttention.forward
|
|
|
|
|
|
|
| 165 |
|
| 166 |
def patched_forward(self, hidden_states, *args, **kwargs):
|
| 167 |
+
bsz, seq_len, embed_dim = hidden_states.shape
|
| 168 |
+
|
| 169 |
+
q, k, v = _project_qkv(self, hidden_states)
|
| 170 |
+
num_heads, head_dim = _infer_heads(self, q)
|
| 171 |
+
|
| 172 |
+
q = _reshape_to_bhld(q, bsz, seq_len, num_heads, head_dim)
|
| 173 |
+
k = _reshape_to_bhld(k, bsz, seq_len, num_heads, head_dim)
|
| 174 |
+
v = _reshape_to_bhld(v, bsz, seq_len, num_heads, head_dim)
|
| 175 |
+
|
| 176 |
+
cos, sin = _build_1d_rope_cache(
|
| 177 |
+
seq_len=seq_len,
|
| 178 |
+
head_dim=head_dim,
|
| 179 |
+
device=q.device,
|
| 180 |
+
rope_base=rope_base,
|
| 181 |
+
)
|
| 182 |
+
q, k = _apply_rope(q, k, cos, sin)
|
| 183 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 184 |
attn_scores = torch.matmul(q, k.transpose(-2, -1)) / (head_dim ** 0.5)
|
| 185 |
+
|
| 186 |
attn_mask = kwargs.get("attention_mask", None)
|
| 187 |
if attn_mask is not None:
|
| 188 |
attn_scores = attn_scores + attn_mask
|
| 189 |
+
|
| 190 |
attn_probs = F.softmax(attn_scores, dim=-1, dtype=torch.float32).to(q.dtype)
|
| 191 |
attn_output = torch.matmul(attn_probs, v)
|
| 192 |
|
| 193 |
+
attn_output = _merge_heads(attn_output, bsz, seq_len, num_heads, head_dim)
|
| 194 |
+
out = _output_projection(self, attn_output)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 195 |
|
| 196 |
+
return out, None
|
| 197 |
|
| 198 |
SiglipAttention.forward = patched_forward
|
| 199 |
print(f"[Text RoPE] Enabled dynamic RoPE in SiglipAttention (base={rope_base})")
|
| 200 |
|
| 201 |
|
| 202 |
def monkey_patch_siglip_rope():
|
| 203 |
+
"""
|
| 204 |
+
Monkey-patch SiglipAttention to support:
|
| 205 |
+
1. set_freqs(freqs): attach external RoPE frequencies
|
| 206 |
+
2. forward(...): apply RoPE to q/k if rope_freqs is available
|
| 207 |
|
| 208 |
+
Expected rope_freqs format:
|
| 209 |
+
- (L, 2*Hd), or
|
| 210 |
+
- (1, 1, L, 2*Hd)
|
| 211 |
+
"""
|
|
|
|
| 212 |
|
| 213 |
+
def set_freqs(self, freqs: torch.Tensor):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 214 |
self.rope_freqs = freqs
|
| 215 |
|
|
|
|
| 216 |
SiglipAttention.set_freqs = set_freqs
|
| 217 |
|
|
|
|
| 218 |
if not hasattr(SiglipAttention, "_orig_forward"):
|
| 219 |
+
SiglipAttention._orig_forward = SiglipAttention.forward
|
| 220 |
|
| 221 |
def patched_forward(self, hidden_states, *args, **kwargs):
|
| 222 |
+
bsz, seq_len, embed_dim = hidden_states.shape
|
| 223 |
+
|
| 224 |
+
q, k, v = _project_qkv(self, hidden_states)
|
| 225 |
+
num_heads, head_dim = _infer_heads(self, q)
|
| 226 |
+
|
| 227 |
+
q = _reshape_to_bhld(q, bsz, seq_len, num_heads, head_dim)
|
| 228 |
+
k = _reshape_to_bhld(k, bsz, seq_len, num_heads, head_dim)
|
| 229 |
+
v = _reshape_to_bhld(v, bsz, seq_len, num_heads, head_dim)
|
| 230 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 231 |
freqs = getattr(self, "rope_freqs", None)
|
| 232 |
if freqs is not None:
|
|
|
|
| 233 |
freqs = freqs.to(q.device)
|
| 234 |
+
|
| 235 |
if freqs.dim() == 2:
|
| 236 |
+
if freqs.shape[0] < seq_len:
|
| 237 |
+
raise ValueError(
|
| 238 |
+
f"rope_freqs length {freqs.shape[0]} < sequence length {seq_len}"
|
| 239 |
+
)
|
| 240 |
+
if freqs.shape[0] > seq_len:
|
| 241 |
+
freqs = freqs[:seq_len]
|
| 242 |
elif freqs.dim() == 4:
|
| 243 |
+
if freqs.shape[-2] < seq_len:
|
| 244 |
+
raise ValueError(
|
| 245 |
+
f"rope_freqs length {freqs.shape[-2]} < sequence length {seq_len}"
|
| 246 |
+
)
|
| 247 |
+
if freqs.shape[-2] > seq_len:
|
| 248 |
+
freqs = freqs[..., :seq_len, :]
|
| 249 |
|
| 250 |
+
q, k = _apply_rope_to_qk(q, k, freqs, head_dim)
|
| 251 |
+
|
| 252 |
+
attn_scores = torch.matmul(q, k.transpose(-2, -1)) / (head_dim ** 0.5)
|
| 253 |
|
|
|
|
| 254 |
attn_mask = kwargs.get("attention_mask", None)
|
| 255 |
if attn_mask is not None:
|
|
|
|
| 256 |
attn_scores = attn_scores + attn_mask
|
| 257 |
|
| 258 |
attn_probs = F.softmax(attn_scores, dim=-1, dtype=torch.float32).to(q.dtype)
|
| 259 |
+
attn_output = torch.matmul(attn_probs, v)
|
| 260 |
+
|
| 261 |
+
attn_output = _merge_heads(attn_output, bsz, seq_len, num_heads, head_dim)
|
| 262 |
+
|
| 263 |
+
if hasattr(self, "proj") or hasattr(self, "out_proj") or hasattr(self, "o_proj"):
|
| 264 |
+
return _output_projection(self, attn_output)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 265 |
|
| 266 |
+
return SiglipAttention._orig_forward(self, hidden_states, *args, **kwargs)
|
| 267 |
|
|
|
|
| 268 |
SiglipAttention.forward = patched_forward
|
| 269 |
print("[RoPE] SiglipAttention monkey-patched with set_freqs() and RoPE-enabled forward().")
|
| 270 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 271 |
|
| 272 |
+
def _resize_abs_pos_embedding(
|
| 273 |
+
text_embeddings: nn.Module,
|
| 274 |
+
text_config,
|
| 275 |
+
max_seq_len: int,
|
| 276 |
+
zero_init: bool = False,
|
| 277 |
+
):
|
| 278 |
"""
|
| 279 |
+
Resize SigLIP text_model.embeddings.position_embedding.
|
| 280 |
"""
|
| 281 |
if not hasattr(text_embeddings, "position_embedding"):
|
| 282 |
+
# Fallback for implementations without an explicit position embedding table
|
| 283 |
if hasattr(text_config, "max_position_embeddings"):
|
| 284 |
text_config.max_position_embeddings = max_seq_len
|
| 285 |
+
print(
|
| 286 |
+
f"[Text Pos] No position_embedding found. "
|
| 287 |
+
f"Only updated config.max_position_embeddings={max_seq_len}."
|
| 288 |
+
)
|
| 289 |
return
|
| 290 |
|
| 291 |
old_pe: nn.Embedding = text_embeddings.position_embedding
|
| 292 |
+
old_len, hidden_dim = old_pe.weight.shape
|
| 293 |
+
|
| 294 |
+
new_pe = nn.Embedding(max_seq_len, hidden_dim)
|
| 295 |
|
|
|
|
| 296 |
with torch.no_grad():
|
| 297 |
if zero_init:
|
| 298 |
new_pe.weight.zero_()
|
| 299 |
else:
|
| 300 |
copy_n = min(old_len, max_seq_len)
|
| 301 |
new_pe.weight[:copy_n].copy_(old_pe.weight[:copy_n])
|
| 302 |
+
|
| 303 |
if max_seq_len > copy_n:
|
| 304 |
std = float(old_pe.weight.std().item() if old_len > 0 else 0.02)
|
| 305 |
nn.init.normal_(new_pe.weight[copy_n:], mean=0.0, std=std)
|
| 306 |
|
| 307 |
text_embeddings.position_embedding = new_pe
|
| 308 |
|
|
|
|
| 309 |
if hasattr(text_config, "max_position_embeddings"):
|
| 310 |
text_config.max_position_embeddings = max_seq_len
|
| 311 |
|
| 312 |
+
print(
|
| 313 |
+
f"[Text Pos] Resized ABS pos embedding from {old_len} -> {max_seq_len} "
|
| 314 |
+
f"{'(zeroed)' if zero_init else ''}."
|
| 315 |
+
)
|
| 316 |
+
|
| 317 |
|
| 318 |
def _patch_text_embeddings_remove_abs(text_embeddings: nn.Module):
|
| 319 |
"""
|
| 320 |
+
Monkey-patch SigLIP text embeddings so that:
|
| 321 |
+
- no sequence length check is performed
|
| 322 |
+
- no absolute position embedding is added
|
| 323 |
+
- only token embeddings (or inputs_embeds) are returned
|
| 324 |
"""
|
| 325 |
+
|
| 326 |
def forward_no_pos(self, input_ids=None, position_ids=None, inputs_embeds=None, **kwargs):
|
| 327 |
if inputs_embeds is None:
|
| 328 |
inputs_embeds = self.token_embedding(input_ids)
|
|
|
|
| 330 |
|
| 331 |
text_embeddings.forward = types.MethodType(forward_no_pos, text_embeddings)
|
| 332 |
|
| 333 |
+
# Remove the original position embedding parameter to avoid load_state_dict conflicts
|
| 334 |
if hasattr(text_embeddings, "position_embedding"):
|
| 335 |
delattr(text_embeddings, "position_embedding")
|
| 336 |
|
| 337 |
+
print("[Text Pos] Patched: removed ABS position addition and length check.")
|
| 338 |
|
| 339 |
|
| 340 |
+
def configure_text_pos_mode(
|
| 341 |
+
model,
|
| 342 |
+
mode: str,
|
| 343 |
+
rope_base: float = None,
|
| 344 |
+
max_seq_len: int = 16,
|
| 345 |
+
):
|
| 346 |
"""
|
| 347 |
+
Configure the positional encoding mode of the SigLIP text branch.
|
| 348 |
+
|
| 349 |
+
Args:
|
| 350 |
+
model: SigLIP model instance
|
| 351 |
+
mode:
|
| 352 |
+
- 'abs' : keep the default absolute position embedding
|
| 353 |
+
- 'rope' : disable absolute position embedding in embeddings and
|
| 354 |
+
apply RoPE inside attention
|
| 355 |
+
rope_base: kept for API compatibility
|
| 356 |
+
max_seq_len: reserved argument for compatibility / future use
|
| 357 |
"""
|
| 358 |
text_model = getattr(model, "text_model", None)
|
| 359 |
if text_model is None:
|
|
|
|
| 361 |
|
| 362 |
text_embeddings = getattr(text_model, "embeddings", None)
|
| 363 |
text_config = getattr(text_model, "config", None)
|
| 364 |
+
|
| 365 |
if text_embeddings is None or text_config is None:
|
| 366 |
+
raise ValueError("SigLIP text_model is missing embeddings/config")
|
| 367 |
|
| 368 |
if mode == "abs":
|
| 369 |
+
print(
|
| 370 |
+
"[Text Pos] ABS mode: keep SigLIP default "
|
| 371 |
+
f"(position_embedding active). "
|
| 372 |
+
f"max_len stays {getattr(text_config, 'max_position_embeddings', 'unknown')}."
|
| 373 |
+
)
|
| 374 |
return
|
| 375 |
|
| 376 |
if mode == "rope":
|
|
|
|
| 377 |
_patch_text_embeddings_remove_abs(text_embeddings)
|
| 378 |
|
|
|
|
| 379 |
if hasattr(text_config, "max_position_embeddings"):
|
| 380 |
text_config.max_position_embeddings = int(1e9)
|
| 381 |
|
| 382 |
+
print(
|
| 383 |
+
"[Text Pos] ROPE mode: disabled ABS position embedding in embeddings; "
|
| 384 |
+
"set max_position_embeddings=1e9. "
|
| 385 |
+
"RoPE should be applied inside attention."
|
| 386 |
+
)
|
| 387 |
return
|
| 388 |
|
| 389 |
raise ValueError(f"Unknown text pos mode: {mode}")
|
| 390 |
+
|
| 391 |
+
|
| 392 |
+
# Example usage:
|
| 393 |
+
#
|
| 394 |
+
# model = AutoModel.from_pretrained(...)
|
| 395 |
+
#
|
| 396 |
+
# Option 1: dynamic 1D text RoPE
|
| 397 |
+
# enable_text_rope_in_attention(rope_base=10000.0)
|
| 398 |
+
#
|
| 399 |
+
# Option 2: external RoPE frequencies
|
| 400 |
+
# monkey_patch_siglip_rope()
|
| 401 |
+
# ... then call your prepare_vision_rope(...) / set_shared_axial_freqs(...) / set_freqs(...)
|
| 402 |
+
#
|
| 403 |
+
# Configure text position mode:
|
| 404 |
+
# configure_text_pos_mode(model, mode="rope")
|