Add Transformers 5.x Compatibility #262
Open
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Summary
This PR adds support for
transformers>=5.0.0while maintaining full backward compatibility with transformers 4.x. The fix addresses a breaking change in how HuggingFace transformer models return outputs whenadd_pooling_layer=False.Problem
With
transformers==5.0.0, COMET fails with the following error when scoring translations:This occurs in
comet/encoders/xlmr.py:95andcomet/encoders/bert.py:171where the code expects 3 values from the model output tuple.Root Cause
In transformers 5.0, when models are created with
add_pooling_layer=False, the output tuple format changed:(last_hidden_states, pooler_output_or_None, hidden_states_tuple)(last_hidden_states, hidden_states_tuple)The pooler output is now omitted entirely rather than being included as
None.Solution
Updated the encoder
forward()methods to dynamically handle both output formats by checking the tuple length:Changes
comet/encoders/xlmr.py: UpdatedXLMREncoder.forward()to handle both 2-value and 3-value output tuplescomet/encoders/bert.py: UpdatedBERTEncoder.forward()with the same fixpyproject.toml: Relaxed version constraints:transformers = "^4.17"→transformers = ">=4.17"huggingface-hub = ">=0.19.3,<1.0"→huggingface-hub = ">=0.19.3"Testing
Tested with
Unbabel/wmt22-comet-damodel on sample translation pairs:Scores are identical, confirming backward compatibility and correctness.
The Transformers 5 release broke some of my scripts using Comet to benchmark translation scores due to the return value being different now, so worked on this PR (with Claude Code and Opus 4.5) to fix it.
I ran the translation scores on Spanish and checked everything still matched before and after. I've read and looked over the change and it looks ok to me, fairly minimal change that doesn't seem very disruptive to the code base.