Skip to content

fix: CodeGen attention on transformers >= 5.24 - #2052

Open
XiaoyuanWang111 wants to merge 2 commits into
TransformerLensOrg:devfrom
XiaoyuanWang111:fix/codegen-transformers-5-24-v2
Open

XiaoyuanWang111 wants to merge 2 commits into
TransformerLensOrg:devfrom
XiaoyuanWang111:fix/codegen-transformers-5-24-v2

Conversation

@XiaoyuanWang111

Copy link
Copy Markdown

Description

transformers 5.24.0 (released 2026-11-21) moved CodeGen's rotary embedding from the attention module to the model: CodeGenModel.rotary_emb computes (sin, cos) once and passes it to each layer as position_embeddings, and CodeGenAttention lost embed_positions and scale_attn (it now has scaling = head_dim ** -0.5). CodeGenAttentionBridge._reconstruct_attention reads both removed attributes, so every forward of a bridged CodeGen model raises:

AttributeError: 'CodeGenAttention' object has no attribute 'embed_positions'

pyproject.toml asks for transformers>=5.9.0 with no upper bound, so a fresh install gets 5.24.1, which behaves the same. CI runs the lock's 5.13.0, which is why it does not show there; the CodeGen cases of tests/integration/model_bridge/test_parallel_residual_identities.py fail on dev under 5.24.0 and 5.24.1.

The change takes (sin, cos) from position_embeddings when the layer passes them and slices embed_positions by position_ids otherwise, and takes the scale from scale_attn when the module has it and from 1 / scaling otherwise. Nothing changes on transformers < 5.24.

To reproduce on dev with transformers 5.24.1 (downloads a tiny test checkpoint):

import torch
from transformers import AutoModelForCausalLM

from transformer_lens.model_bridge import TransformerBridge

name = "hf-internal-testing/tiny-random-CodeGenForCausalLM"
bridge = TransformerBridge.boot_transformers(name, device="cpu")
hf = AutoModelForCausalLM.from_pretrained(name).eval()
tokens = torch.tensor([[11, 22, 33, 44, 55, 66]])
with torch.no_grad():
    print((bridge(tokens) - hf(tokens).logits).abs().max().item())

On dev with 5.24.1 the bridge forward raises the AttributeError above. With this change it prints 1.6e-07 (1.5e-07 on dev with 5.23.0).

Tests: the existing CodeGen tests cover it once they run on 5.24 (test_codegen_attention_bridge.py, test_codegen_adapter.py, test_parallel_residual_identities.py): on dev with 5.24.1, 6 failed and 126 passed (the six CodeGen cases of the parallel-residual identities); with this change all 132 pass under 5.24.1 and under 5.13.0. With #2047 merged, cached generation works too: on 5.24.1, generate(..., use_past_kv_cache=True) returns the same tokens as without the cache.

Type of change

  • Bug fix (non-breaking change which fixes an issue)

Checklist:

  • I have commented my code, particularly in hard-to-understand areas
  • I have made corresponding changes to the documentation
  • My changes generate no new warnings
  • I have added tests that prove my fix is effective or that my feature works
  • New and existing unit tests pass locally with my changes
  • I have not rewritten tests relating to key interfaces which would affect backward compatibility

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.

@jlarson4 jlarson4 left a comment

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.

Thanks for putting this together @XiaoyuanWang111! Just a couple comments, one on testing and the other on a unique edge case. Let me know if you have any questions.

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.

cos: Optional[torch.Tensor] = None
if position_embeddings is not None:
sin, cos = position_embeddings
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.

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.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants