Skip to content
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

Unbreak torch export with static cache #33287

Closed
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 9 additions & 2 deletions src/transformers/cache_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -1090,8 +1090,15 @@ def update(
A tuple containing the updated key and value states.
"""
cache_position = cache_kwargs.get("cache_position")
self.key_cache[layer_idx] = self.key_cache[layer_idx].to(device=key_states.device)
self.value_cache[layer_idx] = self.value_cache[layer_idx].to(device=value_states.device)
if key_states.device != self.key_cache[layer_idx].device:
# Note: The static cache is also used by `torch.export`. Attempting to call `.to()` on it
# will raise an error: "cannot mutate tensors with frozen storage" when using `torch.export`.
# Since `torch.export` currently works on "cpu", the workaround is to ensure that any device
# change is scoped within this conditional check to avoid tracing the device change code.
guangy10 marked this conversation as resolved.
Show resolved Hide resolved
# See: https://github.com/pytorch/pytorch/issues/131679
self.key_cache[layer_idx] = self.key_cache[layer_idx].to(device=key_states.device)
if value_states.device != self.value_cache[layer_idx].device:
self.value_cache[layer_idx] = self.value_cache[layer_idx].to(device=value_states.device)
k_out = self.key_cache[layer_idx]
v_out = self.value_cache[layer_idx]

Expand Down