Skip to content

Fuse transposition into first indexing for kv cache read #1456

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 2 commits into
base: main
Choose a base branch
from
Open
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: 12 additions & 8 deletions sharktank/sharktank/layers/paged_attention.py
Original file line number Diff line number Diff line change
Expand Up @@ -283,18 +283,22 @@ def read(

# Gather both partitions and split post gather. This is more
# computationally efficient without gather fusion:
subblock_table = page_table.flatten(start_dim=0, end_dim=1)
page_stride = self.pipeline_to_block_count[pipeline]

page_table = page_table.flatten(start_dim=0, end_dim=1)
transformer_block_index = torch.full(
(bs, block_seq_len), transformer_block_index, device=self.device
)
subblock_ids = page_ids * page_stride + transformer_block_index
selected = ops.index_select(subblock_table, 0, subblock_ids.flatten(0, 1))
subblock_ids = page_ids * self.transformer_block_count + transformer_block_index
selected = ops.index_select(page_table, 0, subblock_ids.flatten(0, 1))

selected = selected.transpose(0, 1)
key = selected[0]
value = selected[1]

key = key.unflatten(0, blocked_shape[:2])
value = value.unflatten(0, blocked_shape[:2])

selected = selected.unflatten(0, blocked_shape[:2])
key = selected[:, :, 0, :].flatten(1, 2)
value = selected[:, :, 1, :].flatten(1, 2)
key = key.flatten(1, 2)
value = value.flatten(1, 2)

return key, value

Expand Down
Loading