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

XLA optimized Implementation of StaticCache with Tensor Indexing API #31129

Closed
wants to merge 14 commits into from
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
20 changes: 17 additions & 3 deletions src/transformers/cache_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -858,8 +858,12 @@ def update(
k_out = self.key_cache[layer_idx]
v_out = self.value_cache[layer_idx]

k_out[:, :, cache_position] = key_states
v_out[:, :, cache_position] = value_states
# `index_copy_(dim, index, source)` functions similarly to `tensor[index] = source`,
# but it is used for better generality and flexibility.
# For more information, refer to: https://pytorch.org/cppdocs/notes/tensor_indexing.html

k_out.index_copy_(2, cache_position, key_states)
v_out.index_copy_(2, cache_position, value_states)

return k_out, v_out

Expand All @@ -868,7 +872,17 @@ def get_seq_length(self, layer_idx: Optional[int] = 0) -> int:
# Occupied cache == any slot in the 3rd dim (sequence length) holds a non-zero value. To save on compute, let's
# limit the check to the first batch member and head dimension.
# TODO: deprecate this function in favor of `cache_position`
return (self.key_cache[layer_idx][0, 0].any(dim=-1)).sum()
key_cache = self.key_cache[layer_idx]
device = key_cache.device

# index_select(dim, index) performs the same operation as item = tensor[..., index, ...]
# but it is used for better generality and flexibility.
# For more information, refer to: https://pytorch.org/cppdocs/notes/tensor_indexing.html

item = key_cache.index_select(0, torch.tensor(0, device=device))
head = item.index_select(1, torch.tensor(0, device=device))

return head.any(dim=-1).sum()
Comment on lines +875 to +885
Copy link
Collaborator

Choose a reason for hiding this comment

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

TBH this will be deprecated anyways!


def get_max_length(self) -> Optional[int]:
"""Returns the maximum sequence length of the cached states."""
Expand Down
Loading