EnyaWoooo commited on
Commit
fd3d8f8
·
verified ·
1 Parent(s): f7374e7

Update models/rope_generic.py

Browse files
Files changed (1) hide show
  1. 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
- 给 SiglipAttention 打补丁,在 forward 里对文本 q/k 应用 RoPE。
 
 
 
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
- def rotate_half(x):
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
- # 调用原始 forward 拿到 q, k, v
23
- B, L, C = hidden_states.shape
24
- # --- 取 qkv ---
25
- if hasattr(self, "qkv"): # 有些实现用 qkv projection
26
- qkv = self.qkv(hidden_states)
27
- q, k, v = qkv.split(C, dim=-1)
28
- else: # HuggingFace SiglipAttention 是分开的
29
- q = self.q_proj(hidden_states)
30
- k = self.k_proj(hidden_states)
31
- v = self.v_proj(hidden_states)
32
-
33
- num_heads = self.num_heads
34
- head_dim = q.shape[-1] // num_heads
35
-
36
- def shape(x): # (B, L, num_heads, head_dim)
37
- return x.view(B, L, num_heads, head_dim).transpose(1, 2).contiguous()
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
- # --- 合并 heads ---
61
- attn_output = attn_output.transpose(1, 2).contiguous().view(B, L, num_heads * head_dim)
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
- def rotate_half(x):
79
- # (..., 2*d) -> split into two d parts
80
- x1, x2 = x[..., : x.shape[-1] // 2], x[..., x.shape[-1] // 2 :]
81
- return torch.cat([-x2, x1], dim=-1)
82
 
83
- def apply_rope_to_qk(q, k, packed_freqs, head_dim):
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 # 保存原 forward
120
 
121
  def patched_forward(self, hidden_states, *args, **kwargs):
122
- """
123
- 兼容两种形态:
124
- A) self.qkv 存在:一次性线性 -> 切成 q,k,v
125
- B) self.q_proj/k_proj/v_proj 分开
126
- 输出继续走原有投影/残差等(尽量保持行为一致)
127
- """
128
- # ---- 1. 取到 q,k,v ----
129
- B, L, C = hidden_states.shape
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
- # 长度对齐(若外面传进来的更长,按 L 截断;若更短,报错)
168
  if freqs.dim() == 2:
169
- if freqs.shape[0] < L:
170
- raise ValueError(f"rope_freqs length {freqs.shape[0]} < sequence length {L}")
171
- if freqs.shape[0] > L:
172
- freqs = freqs[:L]
 
 
173
  elif freqs.dim() == 4:
174
- if freqs.shape[-2] < L:
175
- raise ValueError(f"rope_freqs length {freqs.shape[-2]} < sequence length {L}")
176
- if freqs.shape[-2] > L:
177
- freqs = freqs[..., :L, :]
178
- q, k = apply_rope_to_qk(q, k, freqs, Hd)
179
- #k, q = apply_rope_to_qk(q, k, freqs, Hd)
180
 
181
- # ---- 4. 点积注意力 ----
182
- attn_scores = torch.matmul(q, k.transpose(-2, -1)) / (Hd ** 0.5) # (B,H,L,L)
 
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) # (B,H,L,Hd)
192
-
193
- # ---- 5. 合并头 & 输出投影 ----
194
- attn_output = attn_output.transpose(1, 2).contiguous().view(B, L, H * Hd) # (B,L,C)
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 out
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(text_embeddings: nn.Module, text_config, max_seq_len: int, zero_init: bool = False):
 
 
 
 
 
222
  """
223
- 适配 SigLIP 的 text_model.embeddings.position_embedding
224
  """
225
  if not hasattr(text_embeddings, "position_embedding"):
226
- # fallback: 有些实现可能没有显式位置表
227
  if hasattr(text_config, "max_position_embeddings"):
228
  text_config.max_position_embeddings = max_seq_len
229
- print(f"[Text Pos] No position_embedding found. Only updated config.max_position_embeddings={max_seq_len}.")
 
 
 
230
  return
231
 
232
  old_pe: nn.Embedding = text_embeddings.position_embedding
233
- old_len, hidden = old_pe.weight.shape
 
 
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(f"[Text Pos] Resized ABS pos embedding from {old_len} -> {max_seq_len} "
253
- f"{'(zeroed)' if zero_init else ''}.")
 
 
 
254
 
255
  def _patch_text_embeddings_remove_abs(text_embeddings: nn.Module):
256
  """
257
- Monkey patch SigLIP 的文本 embeddings:
258
- - 不再做长度检查
259
- - 不再加 position_embedding
260
- - 只返回 token_embedding(input_ids) 或 inputs_embeds
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
- # 删除原本的 position_embedding 参数,避免 load_state_dict 冲突
270
  if hasattr(text_embeddings, "position_embedding"):
271
  delattr(text_embeddings, "position_embedding")
272
 
273
- print("[Text Pos] Patched: removed ABS position addition & length check.")
274
 
275
 
276
- def configure_text_pos_mode(model, mode: str, rope_base: float = None, max_seq_len: int = 16):
 
 
 
 
 
277
  """
278
- 配置 SigLIP 文本分支的位置编码方式(接口保持不变)。
279
- - mode='abs' : 保持默认(不改动)
280
- - mode='rope': 去掉 ABS 位置相加(patch embeddings.forward),RoPE 在 attention 里自行应用
 
 
 
 
 
 
 
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(f"[Text Pos] ABS mode: keep SigLIP default (position_embedding active). "
293
- f"max_len stays {getattr(text_config, 'max_position_embeddings', 'unknown')}.")
 
 
 
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(f"[Text Pos] ROPE mode: disabled ABS pos in embeddings; "
305
- f"set max_position_embeddings=1e9. Apply RoPE inside attention.")
 
 
 
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")