Skip to content

Fix bugs in DynamicCache#37880

Merged
Cyrilvallez merged 8 commits into
huggingface:mainfrom
tugsbayasgalan:dynamic_cache_v2
Jun 24, 2025
Merged

Fix bugs in DynamicCache#37880
Cyrilvallez merged 8 commits into
huggingface:mainfrom
tugsbayasgalan:dynamic_cache_v2

Conversation

@tugsbayasgalan

@tugsbayasgalan tugsbayasgalan commented Apr 30, 2025

Copy link
Copy Markdown
Contributor

What does this PR do?

When we flatten DynamicCache for export, we never end up flattening the inner tensors of DynamicCache because when we start, there are 0 tensors initialized. As a result, we didn't correctly test the ep.module()(*args, **kwargs) behaviour when we do export when cache is populated.

Fixes # (issue)

Before submitting

  • This PR fixes a typo or improves the docs (you can dismiss the other checks if that's the case).
  • Did you read the contributor guideline,
    Pull Request section?
  • Was this discussed/approved via a Github issue or the forum? Please add a link
    to it if that's the case.
  • Did you make sure to update the documentation with your changes? Here are the
    documentation guidelines, and
    here are tips on formatting docstrings.
  • Did you write any new necessary tests?

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.

@github-actions github-actions Bot marked this pull request as draft April 30, 2025 04:14
@github-actions

Copy link
Copy Markdown
Contributor

Hi 👋, thank you for opening this pull request! The pull request is converted to draft by default. The CI will be paused while the PR is in draft mode. When it is ready for review, please click the Ready for review button (at the bottom of the PR page). This will assign reviewers and trigger CI.

@Rocketknight1

Copy link
Copy Markdown
Member

cc @gante

@tugsbayasgalan tugsbayasgalan marked this pull request as ready for review April 30, 2025 15:06

@gante gante left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Thank you for the PR 🤗 In general, LGTM (I'm not super keen in increasing the complexity in DynamicCache, but I understand the importance of the fix)

Missing: update docstring with the new optional arg

Comment thread src/transformers/cache_utils.py Outdated
"""

def __init__(self, _distributed_cache_data: Optional[Iterable] = None) -> None:
def __init__(self, _distributed_cache_data: Optional[Iterable] = None, num_layers: Optional[int] = None) -> None:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Let's accept config instead of num_layers (=config.num_layers). It's more consistent with the other caches, which also take config in __init__.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Sure!

@ArthurZucker ArthurZucker 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! Not sure we need a new argument here!

Comment thread src/transformers/cache_utils.py Outdated
Comment on lines +369 to +370
self.key_cache = [torch.tensor([]) for _ in range(num_layers)]
self.value_cache = [torch.tensor([]) for _ in range(num_layers)]

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.

why don't we always init like this?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

We need to know how many layers we want to do this for.

@gante gante May 2, 2025

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

DynamicCache has lazy tensor init, and export needs eager tensor init :D

It's similar to the issue we have with TP (should be lazy) vs torch.compile (should be eager) in the hybrid caches

@gante gante left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

One more detail and it's good for me 👍

Comment thread src/transformers/cache_utils.py Outdated

def __init__(self, _distributed_cache_data: Optional[Iterable] = None) -> None:
def __init__(
self, _distributed_cache_data: Optional[Iterable] = None, config: Optional[PretrainedConfig] = None

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

missing: docs for config in the docstring above, explaining when it should be used (torch.export)

(sorry, I missed this detail in the previous review :D)

@tugsbayasgalan

Copy link
Copy Markdown
Contributor Author

@ArthurZucker @gante,

I originally hoped to make DynamicCache torch.export compatible with dynamic shapes. But this seems quite difficult and seems outside of scope for export since the caching code is not really the model's forward pass. To make it work,

  1. We need to pass extra config parameter so that we prefill key_cache and value_cache with dummy shapes
  2. We need torch.cond to switch between the initila value and the populated value.

Both of the above will make transformers code quite ugly. And in export, we are working on exporting submodules with different input specs, so i don't feel it is that important to make DynamicShapes fully seamless with export at the cost of code complexity. Our current suggestion would be to get two graphs:

  1. You should export without cache first to populate the cache entries
  2. You should export after populating the cache with dynamic shapes.

This PR still fixes the bug where we weren't able to run the exported artifact when dynamic shapes are used.

cc: @xadupre @zhxchen17

@Cyrilvallez Cyrilvallez left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Hey! I think we can probably make the test a bit cleaner, then let's go! 🤗🚀

Comment on lines 627 to +630

def test_dynamic_cache_exportability_dynamic_cache(self):
model = AutoModelForCausalLM.from_pretrained("hf-internal-testing/tiny-random-MistralForCausalLM")

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Is it an extension of test_dynamic_cache_exportability, or a new test that should be independent? If an extension, let's simply add the new parts to the existing test, otherwise let's have a better name for this new test! 🤗

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Done!

@Cyrilvallez Cyrilvallez left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Hey @tugsbayasgalan! The new test you added does not pass (see the CI report below the PR), so it would need to be fixed before merging!

Comment thread tests/utils/test_cache_utils.py Outdated
Comment on lines +718 to +719
@slow
@require_read_token

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

It should not need these decorators, does it?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

nah it was just copy pasta. Deleted

@Cyrilvallez

Copy link
Copy Markdown
Member

We just need to fix the small conflict based on our new ruff rules, then it's good to go!

@gante gante left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

LGTM

"value_cache": getattr(cache, "value_cache"),
}
return torch.utils._pytree.tree_flatten(dictionary)[0]
return torch.fx._pytree._dict_flatten_spec(dictionary, spec)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

(If this requires torch>2.1, we throw an informative exception when the minimum torch version is not installed)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Should be fine as we require torch>=2.1 anyway!

for v1, v2 in zip(res.past_key_values.value_cache, res_eager.past_key_values.value_cache):
self.assertTrue(torch.allclose(v1, v2))

def test_dynamic_cache_exportability_multiple_run(self):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

If possible, adding a few comments in the test will help us (HF team) better understand the test's purpose. Then we can be more autonomous fixing future issues :)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

DOne

@HuggingFaceDocBuilderDev

Copy link
Copy Markdown

The docs for this PR live here. All of your documentation changes will be reflected on that endpoint. The docs are available until 30 days after the last update.

@Cyrilvallez Cyrilvallez left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Perfect, thanks for adding the last comment! Merging!

@Cyrilvallez Cyrilvallez merged commit 67d36dc into huggingface:main Jun 24, 2025
18 checks passed
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.

6 participants