Skip to content

Cache.get_recurrent_states_to_keep returns None after default activate_past_recording() and raises ValueError on empty DynamicCache #51336

Not planned

Description

@avnps

System Info

  • transformers version: 5.25.0.dev0 (main @ d7c980c)
  • Platform: Windows 11 / Linux (CPU)
  • Python version: 3.12 / 3.14
  • PyTorch version: 2.15.0+cpu

Who can help?

@Cyrilvallez

Reproduction

Following #51180 ([cache][generate] Allow rollback on recurrent states caches!), Cache.get_recurrent_states_to_keep is annotated as returning int (def get_recurrent_states_to_keep(self, layer_idx: int | None = None) -> int:), and callers across modeling_*.py and generation/utils.py pass its return value directly into min(...) / max(...):

  • In 23+ hybrid/recurrent modeling files (modeling_mamba.py, modeling_mamba2.py, modeling_falcon_h1.py, modeling_bamba.py, modeling_qwen3_5.py, modeling_qwen3_next.py, modeling_jamba.py, modeling_zamba2.py, etc.):
    num_intermediate_recurrent_states = (
        cache.get_recurrent_states_to_keep(self.layer_idx) if cache is not None else 0
    )
    num_intermediate_recurrent_states = min(num_intermediate_recurrent_states, seq_len)
  • In DeferredStopCheck.__init__ (src/transformers/generation/utils.py:430):
    self.cache.activate_past_recording(
        recurrent_states_to_keep=max(1, self.cache.get_recurrent_states_to_keep())
    )

However, there are two bugs in LinearAttentionCacheLayerMixin.activate_past_recording and Cache.get_recurrent_states_to_keep (src/transformers/cache_utils.py):

  1. activate_past_recording() with default recurrent_states_to_keep=None stores None on the layer:
    LinearAttentionCacheLayerMixin.activate_past_recording(self, recurrent_states_to_keep: int | None = None) sets self.recurrent_states_to_keep = None. Because the attribute exists on the layer with value None, getattr(self.layers[layer_idx], "recurrent_states_to_keep", 0) returns None instead of 0:
    • cache.get_recurrent_states_to_keep(layer_idx) returns None, causing min(num_intermediate_recurrent_states, seq_len) in model forward() to crash with TypeError: '<' not supported between instances of 'int' and 'NoneType'.
    • cache.get_recurrent_states_to_keep() (layer_idx=None) crashes inside max(...) with TypeError: '>' not supported between instances of 'NoneType' and 'int' (or 'NoneType' and 'NoneType').
  2. Calling get_recurrent_states_to_keep() on an unpopulated DynamicCache() raises ValueError:
    When a fresh DynamicCache() (where self.layers is lazily populated on the first forward, so len(self.layers) == 0) is queried via cache.get_recurrent_states_to_keep(), max(...) receives an empty generator without default=0 and raises ValueError: max() iterable argument is empty (and cache.get_recurrent_states_to_keep(0) raises IndexError: list index out of range).

Minimal reproduction script:

from transformers.cache_utils import (
    Cache,
    DynamicCache,
    DynamicLayer,
    LinearAttentionAndFullAttentionLayer,
    LinearAttentionLayer,
)

# 1. Default activate_past_recording() on a cache with linear/hybrid attention layers
cache = Cache(layers=[DynamicLayer(), LinearAttentionLayer(), LinearAttentionAndFullAttentionLayer()])
cache.activate_past_recording()

print("layer 1 recurrent_states_to_keep:", cache.get_recurrent_states_to_keep(1))
# Actual: None (Expected: 0)
# Crashes model forward at `min(num_intermediate_recurrent_states, seq_len)`:
# TypeError: '<' not supported between instances of 'int' and 'NoneType'

try:
    cache.get_recurrent_states_to_keep()
except TypeError as e:
    print("cache.get_recurrent_states_to_keep() raised TypeError:", e)
    # Actual: TypeError: '>' not supported between instances of 'NoneType' and 'int'

# 2. Fresh DynamicCache() before layers are lazily populated
empty_cache = DynamicCache()
try:
    empty_cache.get_recurrent_states_to_keep()
except ValueError as e:
    print("empty_cache.get_recurrent_states_to_keep() raised ValueError:", e)
    # Actual: ValueError: max() iterable argument is empty

Output on main:

layer 1 recurrent_states_to_keep: None
cache.get_recurrent_states_to_keep() raised TypeError: '>' not supported between instances of 'NoneType' and 'int'
empty_cache.get_recurrent_states_to_keep() raised ValueError: max() iterable argument is empty

Expected behavior

Cache.get_recurrent_states_to_keep(layer_idx) and Cache.get_recurrent_states_to_keep() should always return an int (defaulting to 0 when recurrent_states_to_keep was not specified in activate_past_recording(), or when self.layers is empty / layer_idx >= len(self.layers)).

I have prepared and tested a fix + unit test (test_get_recurrent_states_to_keep in tests/utils/test_cache_utils.py) on my remote fork branch here:

Could you please let me know if this looks good and assign this issue to me so I can open a PR?

Activity

  1. avnps commented on Dec 4, 2026

    @avnps
    Author

    Closing this issue since PR #51440 was closed as not reachable in real generation flows. Thanks @Cyrilvallez for the review!

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions