Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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 (
Expand Down Expand Up @@ -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)
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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.
Expand All @@ -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

Expand All @@ -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
Expand Down Expand Up @@ -301,8 +325,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

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

On 5.24, existing tests only confirm the forward runs. The tests pass with or without this swap. Could you add a unit test that puts the stand-in in test_codegen_attention_bridge.py into the new layout and checks it against the old one?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added in 102a752. test_position_embeddings_match_embed_positions runs the stand-in in the old layout (embed_positions and scale_attn, called with position_ids), then moves it to the 5.24 layout (no table, scaling = head_dim ** -0.5, called with position_embeddings taken from the same table) and requires the output and the pattern to be identical. It covers rotary_dim 8 (partial) and 16 (the whole head). Swapping sin and cos, or using scaling without inverting it, makes it fail.

elif position_ids is not None:

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

On 5.24, a call that only has position_ids lands here and raises on embed_positions. get_random_inputs will hit that issue, so the component benchmark will fail every CodeGen attention block. Can you please have it supply position_embeddings when the module has no table of its own?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 102a752. When the wrapped module has no embed_positions, get_random_inputs now also returns position_embeddings, built from position_ids with the same sinusoidal table that CodeGenRotaryEmbedding uses (the new _create_sinusoidal_positions returns exactly what HF's create_sinusoidal_positions does). I ran benchmark_all_components on a tiny random CodeGen. With transformers 5.24.1, both attention blocks failed before (2 of 13 components, the embed_positions error) and all 13 pass now; 5.23.0 passes before and after. test_random_inputs_supply_position_embeddings covers it. test_codegen_attention_bridge.py, test_codegen_adapter.py and test_parallel_residual_identities.py give 135 passed on 5.24.1 and on 5.13.0, merged onto current dev.

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:
Expand All @@ -313,6 +347,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.
Expand All @@ -329,7 +364,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)

Expand Down
Loading