From 7280f749037e6a381fae617e25cc147bdba606c3 Mon Sep 17 00:00:00 2001 From: Xiaoyuan Wang <174581044+XiaoyuanWang111@users.noreply.github.com> Date: Sun, 22 Nov 2026 15:20:44 +0000 Subject: [PATCH 1/2] fix: CodeGen attention on transformers >= 5.24 transformers 5.24 moved CodeGen's rotary embedding to CodeGenModel.rotary_emb, which passes (sin, cos) as position_embeddings, and replaced the attention's embed_positions and scale_attn with scaling = head_dim ** -0.5. The bridge read the removed attributes and raised. Use position_embeddings and scaling when present, and the old attributes otherwise. --- .../codegen_attention.py | 20 ++++++++++++++++--- 1 file changed, 17 insertions(+), 3 deletions(-) diff --git a/transformer_lens/model_bridge/generalized_components/codegen_attention.py b/transformer_lens/model_bridge/generalized_components/codegen_attention.py index e21bc46b0c..9681725fa9 100644 --- a/transformer_lens/model_bridge/generalized_components/codegen_attention.py +++ b/transformer_lens/model_bridge/generalized_components/codegen_attention.py @@ -10,7 +10,7 @@ - rotary_dim: if None, RoPE is applied to the full head dimension. """ -from typing import Any, Callable, Dict, Optional, cast +from typing import Any, Callable, Dict, Optional, Tuple, cast import torch @@ -301,8 +301,18 @@ def _reconstruct_attention( q, k, v, batch_size, seq_len, head_dim = self._reshape_qkv_to_heads(q, k, v, num_heads) # ---- RoPE ---- + # transformers >= 5.24 computes (sin, cos) once in CodeGenModel.rotary_emb and + # passes them as position_embeddings; earlier versions keep the sinusoidal + # table on the attention module as embed_positions. + position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = kwargs.get( + "position_embeddings", None + ) position_ids: Optional[torch.Tensor] = kwargs.get("position_ids", None) - if position_ids is not None: + sin: Optional[torch.Tensor] = None + cos: Optional[torch.Tensor] = None + if position_embeddings is not None: + sin, cos = position_embeddings + elif position_ids is not None: embed_positions = cast(torch.Tensor, self.original_component.embed_positions) # type: ignore[union-attr] # Move buffer to the right device if needed (mirrors HF forward) if embed_positions.device != position_ids.device: @@ -313,6 +323,7 @@ def _reconstruct_attention( half = sincos.shape[-1] // 2 sin, cos = sincos[:, :, :half], sincos[:, :, half:] + if sin is not None and cos is not None: rotary_dim: Optional[int] = getattr(self.original_component, "rotary_dim", None) if rotary_dim is not None: # Only rotate the first rotary_dim dimensions; pass the rest through. @@ -329,7 +340,10 @@ def _reconstruct_attention( kv_seq_len = k.shape[-2] # ---- Scaled dot-product (fp32, matching HF CodeGen._attn) ---- - scale = cast(torch.Tensor, self.original_component.scale_attn) # type: ignore[union-attr] + # transformers >= 5.24 stores the reciprocal, head_dim ** -0.5, as `scaling`. + scale = getattr(self.original_component, "scale_attn", None) + if scale is None: + scale = 1.0 / cast(float, self.original_component.scaling) q_f32 = q.to(torch.float32) k_f32 = k.to(torch.float32) From 102a752c13b254ab62e94a7ccd2189a58d1ceca8 Mon Sep 17 00:00:00 2001 From: Xiaoyuan Wang <174581044+XiaoyuanWang111@users.noreply.github.com> Date: Wed, 25 Nov 2026 16:32:52 +0000 Subject: [PATCH 2/2] fix: supply CodeGen position_embeddings in get_random_inputs on 5.24 On transformers >= 5.24 CodeGenAttention has no embed_positions, so the component benchmark's position_ids-only call failed on every CodeGen attention block. get_random_inputs now builds (sin, cos) from position_ids when the wrapped module has no table of its own. Add unit tests that move the stand-in to the 5.24 layout (position_embeddings, scaling) and check output and pattern against the earlier layout (embed_positions, scale_attn), and that check the position_embeddings get_random_inputs builds. --- .../test_codegen_attention_bridge.py | 61 +++++++++++++++++++ .../codegen_attention.py | 36 +++++++++-- 2 files changed, 91 insertions(+), 6 deletions(-) diff --git a/tests/unit/model_bridge/generalized_components/test_codegen_attention_bridge.py b/tests/unit/model_bridge/generalized_components/test_codegen_attention_bridge.py index 026bd14f58..c8a3d2641e 100644 --- a/tests/unit/model_bridge/generalized_components/test_codegen_attention_bridge.py +++ b/tests/unit/model_bridge/generalized_components/test_codegen_attention_bridge.py @@ -8,10 +8,13 @@ - RoPE is applied to Q and K (partial rotary_dim path and full-dim path) - Causal masking is applied correctly - KV cache is passed through to _update_kv_cache +- The transformers >= 5.24 layout (position_embeddings, scaling) gives the + same output as the earlier layout (embed_positions, scale_attn) """ from unittest.mock import MagicMock +import pytest import torch from transformer_lens.model_bridge.generalized_components.codegen_attention import ( @@ -518,3 +521,61 @@ def test_future_positions_have_zero_attention_weight(self): assert torch.all( attn_weights[:, :, i, j].abs() < 1e-5 ), f"attn_weights[:, :, {i}, {j}] should be ~0 (future position)" + + +# --------------------------------------------------------------------------- +# transformers >= 5.24 layout +# --------------------------------------------------------------------------- + + +def _to_transformers_5_24_layout(original, head_dim: int) -> None: + """Rearrange the stand-in in place as transformers >= 5.24 lays out CodeGenAttention. + + The sinusoidal table moves to ``CodeGenModel.rotary_emb``, which passes + ``position_embeddings`` (sin, cos) to the attention, and ``scale_attn`` + (``head_dim ** 0.5``) becomes ``scaling`` (``head_dim ** -0.5``). + """ + del original.embed_positions + del original.scale_attn + original.scaling = float(head_dim) ** -0.5 + + +class TestCodeGenAttentionBridgeTransformers524Layout: + """The 5.24 layout must reproduce the earlier layout's attention exactly.""" + + @pytest.mark.parametrize("rotary_dim", [8, 16]) + def test_position_embeddings_match_embed_positions(self, rotary_dim): + """Output and pattern with position_embeddings equal those with embed_positions.""" + config = _make_config(rotary_dim=rotary_dim) + bridge, original = _make_bridge(config=config) + B, S = 2, 6 + hs = torch.randn(B, S, config.d_model) + pos_ids = torch.arange(3, 3 + S).unsqueeze(0).expand(B, -1) + sincos = original.embed_positions[pos_ids] + position_embeddings = torch.split(sincos, sincos.shape[-1] // 2, dim=-1) + + with torch.no_grad(): + old_out, old_weights = bridge(hs, position_ids=pos_ids) + _to_transformers_5_24_layout(original, config.d_head) + new_out, new_weights = bridge(hs, position_embeddings=position_embeddings) + + torch.testing.assert_close(new_out, old_out, rtol=0.0, atol=0.0) + torch.testing.assert_close(new_weights, old_weights, rtol=0.0, atol=0.0) + + def test_random_inputs_supply_position_embeddings(self): + """Without a table on the module, get_random_inputs builds (sin, cos) from position_ids.""" + config = _make_config() + bridge, original = _make_bridge(config=config) + old_inputs = bridge.get_random_inputs(batch_size=2, seq_len=5) + assert "position_embeddings" not in old_inputs + table = original.embed_positions + + _to_transformers_5_24_layout(original, config.d_head) + inputs = bridge.get_random_inputs(batch_size=2, seq_len=5) + sin, cos = inputs["position_embeddings"] + torch.testing.assert_close( + torch.cat([sin, cos], dim=-1), table[inputs["position_ids"]], rtol=0.0, atol=0.0 + ) + with torch.no_grad(): + attn_out, _ = bridge(**inputs) + assert attn_out.shape == (2, 5, config.d_model) diff --git a/transformer_lens/model_bridge/generalized_components/codegen_attention.py b/transformer_lens/model_bridge/generalized_components/codegen_attention.py index 9681725fa9..afb15b9120 100644 --- a/transformer_lens/model_bridge/generalized_components/codegen_attention.py +++ b/transformer_lens/model_bridge/generalized_components/codegen_attention.py @@ -47,6 +47,17 @@ def _rotate_every_two(x: torch.Tensor) -> torch.Tensor: return x.flatten(-2) +def _create_sinusoidal_positions(num_pos: int, dim: int) -> torch.Tensor: + """Return CodeGen's sinusoidal RoPE table, ``[num_pos, dim]`` (sin half, then cos half). + + Mirrors ``create_sinusoidal_positions`` from + ``transformers.models.codegen.modeling_codegen``. + """ + inv_freq = 1.0 / (10000 ** (torch.arange(0, dim, 2, dtype=torch.int64) / dim)) + sinusoid_inp = torch.arange(num_pos, dtype=torch.int64).float()[:, None] * inv_freq + return torch.cat((torch.sin(sinusoid_inp), torch.cos(sinusoid_inp)), dim=1) + + def _apply_rotary_pos_emb( tensor: torch.Tensor, sin: torch.Tensor, @@ -151,6 +162,9 @@ def get_random_inputs( ``embed_positions``) and a HuggingFace-style 4D causal attention mask. The mask is provided so that both the bridge and the HF component apply identical causal masking during the ``all_components`` benchmark. + From transformers 5.24 the attention module has no ``embed_positions`` + and takes ``position_embeddings`` (sin, cos) instead; when the wrapped + module has no table of its own, they are built here from ``position_ids``. Args: batch_size: Batch size. @@ -159,8 +173,9 @@ def get_random_inputs( dtype: Tensor dtype (defaults to float32). Returns: - Dict with ``hidden_states``, ``position_ids``, and - ``attention_mask`` suitable for both bridge and HF forward calls. + Dict with ``hidden_states``, ``position_ids``, ``attention_mask`` + and, on transformers >= 5.24, ``position_embeddings``, suitable for + both bridge and HF forward calls. """ import torch @@ -180,13 +195,22 @@ def get_random_inputs( ) causal[:, 0] = causal[:, 0].masked_fill(mask_upper, min_val) - return { + position_ids = torch.arange(seq_len, device=device).unsqueeze(0).expand(batch_size, -1) + inputs: Dict[str, Any] = { "hidden_states": torch.randn(batch_size, seq_len, d_model, device=device, dtype=dtype), - "position_ids": torch.arange(seq_len, device=device) - .unsqueeze(0) - .expand(batch_size, -1), + "position_ids": position_ids, "attention_mask": causal, } + # transformers >= 5.24 keeps the table on CodeGenModel.rotary_emb and passes + # (sin, cos) to the attention as position_embeddings. + if self.original_component is not None and not hasattr( + self.original_component, "embed_positions" + ): + rotary_dim = getattr(self.original_component, "rotary_dim", None) + table = _create_sinusoidal_positions(seq_len, rotary_dim or d_model).to(device) + sincos = table[position_ids] + inputs["position_embeddings"] = torch.split(sincos, sincos.shape[-1] // 2, dim=-1) + return inputs # ------------------------------------------------------------------ # Component wiring