Fix Gemma4 use_cache=False producing bad logits#45253
Open
Charly21r wants to merge 1 commit intohuggingface:mainfrom
Open
Fix Gemma4 use_cache=False producing bad logits#45253Charly21r wants to merge 1 commit intohuggingface:mainfrom
use_cache=False producing bad logits#45253Charly21r wants to merge 1 commit intohuggingface:mainfrom
Conversation
Contributor
|
[For maintainers] Suggested jobs to run (before merge) run-slow: gemma4 |
use_cache=False producing bad logits
Contributor
|
View the CircleCI Test Summary for this PR: https://huggingface.co/spaces/transformers-community/circle-ci-viz?pr=45253&sha=bc35f6 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.
What does this PR do?
Fixes a bug where
use_cache=Falseproduces garbage logits in Gemma 4 models due to broken KV sharing between layers.Fixes #45242
Root cause of the issue
Gemma 4 introduces two architectural features not present in Gemma 3:
KV sharing (
num_kv_shared_layers): The last N decoder layers ("receiver" layers) don't compute their own keys/values, instead they reuse K/V states from earlier "donor" layers.K=V attention (
attention_k_eq_v): On global attention layers, keys and values share the same projection weights, sov_projis set toNone.Both mechanisms were implemented by piggybacking on
past_key_values(the KV cache object):past_key_values.shared_layers[layer_idx]past_key_values.shared_layers[donor_layer_idx]Both code paths are guarded by
if past_key_values is not None.When
use_cache=True, aDynamicCacheis created,past_key_valuesis notNone, and everything works correctly.When
use_cache=False,past_key_valuesremainsNone, so:past_key_values is not Noneguard failselsebranch and try to compute their own K/Vattention_k_eq_v=Truehavev_proj = None, so the fallbackvalue_states = self.v_proj(hidden_states) if self.v_proj is not None else key_statesuses keys as valuesThe current fix
The fix creates a
DynamicCacheeven whenuse_cache=False, but after causal mask creation to avoid affecting mask computation (which also depends onpast_key_values). The cache is then available internally for KV sharing between layers. The return value is set toNonewhenuse_cache=Falseto preserve the expected API behavior.Alternative approach considered
A more memory-efficient approach would decouple KV sharing from
past_key_valuesentirely by introducinga lightweight
shared_kvdict passed throughkwargs. This would avoid allocating a fullDynamicCachewhen
use_cache=False, preserving the memory savings that users expect during training. However, thischanges the gradient flow: KV-shared receiver layers would no longer exercise their own
k_proj/k_norm/v_proj/v_normparams (since they correctly skip computing their own K/V), causingtest_training_gradient_checkpointingto fail. Those params are architecturally unused on receiver layers,so the missing gradients are semantically correct, but it requires updating the test expectations.
The current fix (always creating a
DynamicCacheafter mask creation) was chosen for simplicity andbecause it passes all existing tests without modification. Happy to switch to the
shared_kvapproachif reviewers prefer it.
Code Agent Policy
Before submitting
Who can review?
Anyone in the community is free to review the PR once the tests have passed. Feel free to tag
members/contributors who may be interested in your PR.
@ArthurZucker @Cyrilvallez @zucchini-nlp