Skip to content

Fix bugs in DynamicCache #37880

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 8 commits into
base: main
Choose a base branch
from

Conversation

tugsbayasgalan
Copy link
Contributor

@tugsbayasgalan tugsbayasgalan commented Apr 30, 2025

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
Copy link
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
Member

cc @gante

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

@gante gante left a comment

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

@@ -359,11 +359,15 @@ class DynamicCache(Cache):
```
"""

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
Member

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
Contributor Author

Choose a reason for hiding this comment

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

Sure!

Copy link
Collaborator

@ArthurZucker ArthurZucker left a comment

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 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
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
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.

Copy link
Member

@gante gante May 2, 2025

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

Copy link
Member

@gante gante left a comment

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 👍

@@ -359,11 +359,17 @@ class DynamicCache(Cache):
```
"""

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
Member

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
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

Copy link
Member

@Cyrilvallez Cyrilvallez left a comment

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
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
Contributor Author

Choose a reason for hiding this comment

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

Done!

Copy link
Member

@Cyrilvallez Cyrilvallez left a comment

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 on lines 718 to 719
@slow
@require_read_token
Copy link
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
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
Member

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

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.

5 participants