import types import torch import torch.nn as nn import torch.nn.functional as F from transformers.models.siglip.modeling_siglip import SiglipAttention def _rotate_half(x: torch.Tensor) -> torch.Tensor: """ Rotate the last dimension by half. For a tensor shaped (..., 2*d), split it into two halves and rotate: [x1, x2] -> [-x2, x1] """ x1, x2 = x[..., : x.shape[-1] // 2], x[..., x.shape[-1] // 2 :] return torch.cat([-x2, x1], dim=-1) def _build_1d_rope_cache( seq_len: int, head_dim: int, device: torch.device, rope_base: float = 10000.0, ) -> tuple[torch.Tensor, torch.Tensor]: """ Build dynamic 1D RoPE cosine and sine caches. Returns: cos: (1, 1, L, Hd) sin: (1, 1, L, Hd) """ pos = torch.arange(seq_len, device=device, dtype=torch.float32) # (L,) inv_freq = 1.0 / ( rope_base ** (torch.arange(0, head_dim, 2, device=device).float() / head_dim) ) freqs = torch.outer(pos, inv_freq) # (L, Hd/2) cos = freqs.cos().repeat_interleave(2, dim=-1)[None, None, :, :] # (1,1,L,Hd) sin = freqs.sin().repeat_interleave(2, dim=-1)[None, None, :, :] # (1,1,L,Hd) return cos, sin def _apply_rope(q: torch.Tensor, k: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor): """ Apply RoPE to query and key. Args: q, k: (B, H, L, Hd) cos, sin: broadcastable to (B, H, L, Hd) """ q = q * cos + _rotate_half(q) * sin k = k * cos + _rotate_half(k) * sin return q, k def _apply_rope_to_qk( q: torch.Tensor, k: torch.Tensor, packed_freqs: torch.Tensor, head_dim: int, ) -> tuple[torch.Tensor, torch.Tensor]: """ Apply RoPE using pre-packed frequency tensors. Args: q, k: (B, H, L, Hd) packed_freqs: - (L, 2*Hd), or - (1, 1, L, 2*Hd), or compatible 4D tensor """ if packed_freqs.dim() == 2: packed = packed_freqs.unsqueeze(0).unsqueeze(0) # (1,1,L,2*Hd) elif packed_freqs.dim() == 4: packed = packed_freqs else: raise ValueError(f"Unexpected freqs shape: {packed_freqs.shape}") cos = packed[..., :head_dim] sin = packed[..., head_dim:] return _apply_rope(q, k, cos, sin) def _project_qkv(self, hidden_states: torch.Tensor): """ Extract q, k, v from either: - fused qkv projection, or - separate q_proj / k_proj / v_proj """ bsz, seq_len, embed_dim = hidden_states.shape if hasattr(self, "qkv"): qkv = self.qkv(hidden_states) if qkv.shape[-1] == 3 * embed_dim: q, k, v = qkv.split(embed_dim, dim=-1) else: q, k, v = torch.chunk(qkv, 3, dim=-1) else: q = self.q_proj(hidden_states) k = self.k_proj(hidden_states) v = self.v_proj(hidden_states) return q, k, v def _infer_heads(self, q: torch.Tensor) -> tuple[int, int]: """ Infer number of heads and head dimension from attention module attributes. """ num_heads = getattr(self, "num_heads", None) head_dim = getattr(self, "head_dim", None) if num_heads is None or head_dim is None: embed_dim = q.shape[-1] if hasattr(self, "num_heads"): num_heads = self.num_heads head_dim = embed_dim // num_heads elif hasattr(self, "head_dim"): head_dim = self.head_dim num_heads = embed_dim // head_dim else: raise AttributeError("Cannot infer num_heads/head_dim from SiglipAttention.") return num_heads, head_dim def _reshape_to_bhld(x: torch.Tensor, bsz: int, seq_len: int, num_heads: int, head_dim: int): """ Reshape (B, L, C) -> (B, H, L, Hd) """ return x.view(bsz, seq_len, num_heads, head_dim).transpose(1, 2).contiguous() def _merge_heads(x: torch.Tensor, bsz: int, seq_len: int, num_heads: int, head_dim: int): """ Reshape (B, H, L, Hd) -> (B, L, C) """ return x.transpose(1, 2).contiguous().view(bsz, seq_len, num_heads * head_dim) def _output_projection(self, attn_output: torch.Tensor): """ Apply the output projection if available. """ if hasattr(self, "proj"): return self.proj(attn_output) if hasattr(self, "out_proj"): return self.out_proj(attn_output) if hasattr(self, "o_proj"): return self.o_proj(attn_output) return attn_output def enable_text_rope_in_attention(rope_base: float = 10000.0): """ Monkey-patch SiglipAttention.forward to dynamically apply 1D RoPE inside attention for the text branch. This version computes RoPE on the fly from sequence length. """ if hasattr(SiglipAttention, "_orig_forward_text"): print("[Text RoPE] already patched") return SiglipAttention._orig_forward_text = SiglipAttention.forward def patched_forward(self, hidden_states, *args, **kwargs): bsz, seq_len, embed_dim = hidden_states.shape q, k, v = _project_qkv(self, hidden_states) num_heads, head_dim = _infer_heads(self, q) q = _reshape_to_bhld(q, bsz, seq_len, num_heads, head_dim) k = _reshape_to_bhld(k, bsz, seq_len, num_heads, head_dim) v = _reshape_to_bhld(v, bsz, seq_len, num_heads, head_dim) cos, sin = _build_1d_rope_cache( seq_len=seq_len, head_dim=head_dim, device=q.device, rope_base=rope_base, ) q, k = _apply_rope(q, k, cos, sin) attn_scores = torch.matmul(q, k.transpose(-2, -1)) / (head_dim ** 0.5) attn_mask = kwargs.get("attention_mask", None) if attn_mask is not None: attn_scores = attn_scores + attn_mask attn_probs = F.softmax(attn_scores, dim=-1, dtype=torch.float32).to(q.dtype) attn_output = torch.matmul(attn_probs, v) attn_output = _merge_heads(attn_output, bsz, seq_len, num_heads, head_dim) out = _output_projection(self, attn_output) return out, None SiglipAttention.forward = patched_forward print(f"[Text RoPE] Enabled dynamic RoPE in SiglipAttention (base={rope_base})") def monkey_patch_siglip_rope(): """ Monkey-patch SiglipAttention to support: 1. set_freqs(freqs): attach external RoPE frequencies 2. forward(...): apply RoPE to q/k if rope_freqs is available Expected rope_freqs format: - (L, 2*Hd), or - (1, 1, L, 2*Hd) """ def set_freqs(self, freqs: torch.Tensor): self.rope_freqs = freqs SiglipAttention.set_freqs = set_freqs if not hasattr(SiglipAttention, "_orig_forward"): SiglipAttention._orig_forward = SiglipAttention.forward def patched_forward(self, hidden_states, *args, **kwargs): bsz, seq_len, embed_dim = hidden_states.shape q, k, v = _project_qkv(self, hidden_states) num_heads, head_dim = _infer_heads(self, q) q = _reshape_to_bhld(q, bsz, seq_len, num_heads, head_dim) k = _reshape_to_bhld(k, bsz, seq_len, num_heads, head_dim) v = _reshape_to_bhld(v, bsz, seq_len, num_heads, head_dim) freqs = getattr(self, "rope_freqs", None) if freqs is not None: freqs = freqs.to(q.device) if freqs.dim() == 2: if freqs.shape[0] < seq_len: raise ValueError( f"rope_freqs length {freqs.shape[0]} < sequence length {seq_len}" ) if freqs.shape[0] > seq_len: freqs = freqs[:seq_len] elif freqs.dim() == 4: if freqs.shape[-2] < seq_len: raise ValueError( f"rope_freqs length {freqs.shape[-2]} < sequence length {seq_len}" ) if freqs.shape[-2] > seq_len: freqs = freqs[..., :seq_len, :] q, k = _apply_rope_to_qk(q, k, freqs, head_dim) attn_scores = torch.matmul(q, k.transpose(-2, -1)) / (head_dim ** 0.5) attn_mask = kwargs.get("attention_mask", None) if attn_mask is not None: attn_scores = attn_scores + attn_mask attn_probs = F.softmax(attn_scores, dim=-1, dtype=torch.float32).to(q.dtype) attn_output = torch.matmul(attn_probs, v) attn_output = _merge_heads(attn_output, bsz, seq_len, num_heads, head_dim) if hasattr(self, "proj") or hasattr(self, "out_proj") or hasattr(self, "o_proj"): return _output_projection(self, attn_output) return SiglipAttention._orig_forward(self, hidden_states, *args, **kwargs) SiglipAttention.forward = patched_forward print("[RoPE] SiglipAttention monkey-patched with set_freqs() and RoPE-enabled forward().") def _resize_abs_pos_embedding( text_embeddings: nn.Module, text_config, max_seq_len: int, zero_init: bool = False, ): """ Resize SigLIP text_model.embeddings.position_embedding. """ if not hasattr(text_embeddings, "position_embedding"): # Fallback for implementations without an explicit position embedding table if hasattr(text_config, "max_position_embeddings"): text_config.max_position_embeddings = max_seq_len print( f"[Text Pos] No position_embedding found. " f"Only updated config.max_position_embeddings={max_seq_len}." ) return old_pe: nn.Embedding = text_embeddings.position_embedding old_len, hidden_dim = old_pe.weight.shape new_pe = nn.Embedding(max_seq_len, hidden_dim) with torch.no_grad(): if zero_init: new_pe.weight.zero_() else: copy_n = min(old_len, max_seq_len) new_pe.weight[:copy_n].copy_(old_pe.weight[:copy_n]) if max_seq_len > copy_n: std = float(old_pe.weight.std().item() if old_len > 0 else 0.02) nn.init.normal_(new_pe.weight[copy_n:], mean=0.0, std=std) text_embeddings.position_embedding = new_pe if hasattr(text_config, "max_position_embeddings"): text_config.max_position_embeddings = max_seq_len print( f"[Text Pos] Resized ABS pos embedding from {old_len} -> {max_seq_len} " f"{'(zeroed)' if zero_init else ''}." ) def _patch_text_embeddings_remove_abs(text_embeddings: nn.Module): """ Monkey-patch SigLIP text embeddings so that: - no sequence length check is performed - no absolute position embedding is added - only token embeddings (or inputs_embeds) are returned """ def forward_no_pos(self, input_ids=None, position_ids=None, inputs_embeds=None, **kwargs): if inputs_embeds is None: inputs_embeds = self.token_embedding(input_ids) return inputs_embeds text_embeddings.forward = types.MethodType(forward_no_pos, text_embeddings) # Remove the original position embedding parameter to avoid load_state_dict conflicts if hasattr(text_embeddings, "position_embedding"): delattr(text_embeddings, "position_embedding") print("[Text Pos] Patched: removed ABS position addition and length check.") def configure_text_pos_mode( model, mode: str, rope_base: float = None, max_seq_len: int = 16, ): """ Configure the positional encoding mode of the SigLIP text branch. Args: model: SigLIP model instance mode: - 'abs' : keep the default absolute position embedding - 'rope' : disable absolute position embedding in embeddings and apply RoPE inside attention rope_base: kept for API compatibility max_seq_len: reserved argument for compatibility / future use """ text_model = getattr(model, "text_model", None) if text_model is None: raise ValueError("model.text_model not found (is this a SigLIP model?)") text_embeddings = getattr(text_model, "embeddings", None) text_config = getattr(text_model, "config", None) if text_embeddings is None or text_config is None: raise ValueError("SigLIP text_model is missing embeddings/config") if mode == "abs": print( "[Text Pos] ABS mode: keep SigLIP default " f"(position_embedding active). " f"max_len stays {getattr(text_config, 'max_position_embeddings', 'unknown')}." ) return if mode == "rope": _patch_text_embeddings_remove_abs(text_embeddings) if hasattr(text_config, "max_position_embeddings"): text_config.max_position_embeddings = int(1e9) print( "[Text Pos] ROPE mode: disabled ABS position embedding in embeddings; " "set max_position_embeddings=1e9. " "RoPE should be applied inside attention." ) return raise ValueError(f"Unknown text pos mode: {mode}") # Example usage: # # model = AutoModel.from_pretrained(...) # # Option 1: dynamic 1D text RoPE # enable_text_rope_in_attention(rope_base=10000.0) # # Option 2: external RoPE frequencies # monkey_patch_siglip_rope() # ... then call your prepare_vision_rope(...) / set_shared_axial_freqs(...) / set_freqs(...) # # Configure text position mode: # configure_text_pos_mode(model, mode="rope")