forked from pytorch/ao
-
Notifications
You must be signed in to change notification settings - Fork 0
Paged attention #1
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
liangan1
wants to merge
22
commits into
main
Choose a base branch
from
liangan1/paged_attention
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 11 commits
Commits
Show all changes
22 commits
Select commit
Hold shift + click to select a range
de3ac6b
Add pagedattention kernel for CPU
liangan1 2b843e6
Add ut
liangan1 63a826a
Add UT
liangan1 ab17859
Refine code
liangan1 784f503
Add PagedAttention KV Cache manager
liangan1 57c4faa
Enable flash decodeing for paged attention.
liangan1 d744dff
Update kv cache manager
liangan1 3ee352f
clang-format and recover test/kernel/test_fused_kernels.py
liangan1 101c4db
Merge branch 'main' into liangan1/paged_attention
liangan1 302dd70
Update test_paged_attention.py
liangan1 52d5924
Update test_paged_attention.py
liangan1 0511027
Update test/kernel/test_paged_attention.py
liangan1 51ad5cb
Refine code
liangan1 b48b5ff
Update according to the review suggestions.
liangan1 fcabfce
Update test_ops.py
liangan1 11d4f47
Update test_paged_attention.py
liangan1 ad7caaa
Remove redundant test
liangan1 1daba57
update
liangan1 93c5a7d
update format
liangan1 8f75d4b
Merge branch 'main' into liangan1/paged_attention
liangan1 2e4c048
Enable subclassing for paged attention design
liangan1 5133692
Merge branch 'main' into liangan1/paged_attention
liangan1 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,206 @@ | ||
| import torch | ||
| import unittest | ||
| import random | ||
| from typing import List, Optional, Tuple | ||
| from itertools import product | ||
| import torchao | ||
| from torchao.kv_cache import PagedAttentionCache, PagedTensor | ||
|
|
||
| class NiaveCache: | ||
| def __init__(self): | ||
| self.past_key = None | ||
| self.past_value = None | ||
|
|
||
| def expand_cache(self, beam_size): | ||
| self.past_key = self.past_key.repeat_interleave(beam_size, dim=0) | ||
| self.past_value = self.past_value.repeat_interleave(beam_size, dim=0) | ||
|
|
||
| def update(self, key, value, layer_idx=0): | ||
| if self.past_key is None: | ||
| self.past_key = key | ||
| self.past_value = value | ||
| else: | ||
| self.past_key = torch.cat((self.past_key, key), dim=2) | ||
| self.past_value = torch.cat((self.past_value, value), dim=2) | ||
| return self.past_key, self.past_value | ||
|
|
||
| def reorder_cache(self, beam_idx): | ||
| self.past_key = self.past_key.index_select(0, beam_idx) | ||
| self.past_value = self.past_value.index_select(0, beam_idx) | ||
|
|
||
|
|
||
| class MHAModule(torch.nn.Module): | ||
| def __init__(self, head_dim, num_heads, num_kv_heads): | ||
| super(MHAModule, self).__init__() | ||
| self.head_dim = head_dim | ||
| self.num_heads = num_heads | ||
| self.num_kv_heads = num_kv_heads | ||
| self.scale = head_dim**-0.5 | ||
| self.q = torch.nn.Linear( | ||
| self.num_heads * self.head_dim, self.num_heads * self.head_dim | ||
| ) | ||
| self.k = torch.nn.Linear( | ||
| self.num_heads * self.head_dim, self.num_kv_heads * self.head_dim | ||
| ) | ||
| self.v = torch.nn.Linear( | ||
| self.num_heads * self.head_dim, self.num_kv_heads * self.head_dim | ||
| ) | ||
|
|
||
| def forward(self, inputs, kv_cache): | ||
| query = self.q(inputs) | ||
| key = self.k(inputs) | ||
| value = self.v(inputs) | ||
| batch_size = inputs.size(0) | ||
| query = query.view(batch_size, -1, self.num_heads, self.head_dim).transpose( | ||
| 1, 2 | ||
| ) | ||
| key = key.view(batch_size, -1, self.num_kv_heads, self.head_dim).transpose(1, 2) | ||
| value = value.view(batch_size, -1, self.num_kv_heads, self.head_dim).transpose( | ||
| 1, 2 | ||
| ) | ||
| updated_key, updated_value = kv_cache.update(key, value, 0) | ||
| if isinstance(updated_key, torch.Tensor): | ||
| updated_key = updated_key.repeat_interleave( | ||
| self.num_heads // self.num_kv_heads, dim=1 | ||
| ) | ||
| updated_value = updated_value.repeat_interleave( | ||
| self.num_heads // self.num_kv_heads, dim=1 | ||
| ) | ||
| output = torch.nn.functional.scaled_dot_product_attention( | ||
| query, updated_key, updated_value, scale=self.scale | ||
| ) | ||
| return output | ||
|
|
||
|
|
||
| class PagedAttentionCachePagedTensorTest(unittest.TestCase): | ||
| def _test_paged_attention_cache( | ||
| self, | ||
| num_blocks, | ||
| block_size, | ||
| num_query_heads, | ||
| num_key_value_heads, | ||
| head_dim, | ||
| device, | ||
| dtype, | ||
| batch_size, | ||
| beam_size, | ||
| ): | ||
| num_layers = 1 | ||
| prompt_len = 32 | ||
| mha_model = MHAModule(head_dim, num_query_heads, num_key_value_heads).to( | ||
| device=device, dtype=dtype | ||
| ) | ||
| naive_cache = NiaveCache() | ||
| pagedcache = PagedAttentionCache( | ||
| num_blocks, | ||
| block_size, | ||
| num_key_value_heads, | ||
| head_dim, | ||
| num_layers, | ||
| device, | ||
| dtype, | ||
| ) | ||
| # enable prompt sharing for the first token, fork | ||
| pagedcache.set_batch2seq_for_prompt_sharing(batch_size, beam_size) | ||
| pagedcache.allocate(batch_size, prompt_len) | ||
| prompt_inputs = torch.randn( | ||
| batch_size, | ||
| prompt_len, | ||
| num_query_heads * head_dim, | ||
| device=device, | ||
| dtype=dtype, | ||
| ) | ||
| paged_output = mha_model(prompt_inputs, pagedcache) | ||
| naive_output = mha_model(prompt_inputs, naive_cache) | ||
| torch.allclose(paged_output, naive_output) | ||
|
|
||
| beam_idx = torch.arange( | ||
| 0, batch_size * beam_size, beam_size, device=device, dtype=torch.int64 | ||
| ).repeat_interleave(beam_size) | ||
| naive_cache.expand_cache(beam_size) | ||
| naive_cache.reorder_cache(beam_idx) | ||
| pagedcache.reorder_cache(beam_idx) | ||
|
|
||
| # Next token | ||
| pagedcache.allocate(batch_size * beam_size, 1) | ||
| next_inputs = torch.randn( | ||
| batch_size * beam_size, | ||
| 1, | ||
| num_query_heads * head_dim, | ||
| device=device, | ||
| dtype=dtype, | ||
| ) | ||
|
|
||
| paged_output = mha_model(next_inputs, pagedcache) | ||
| naive_output = mha_model(next_inputs, naive_cache) | ||
| torch.allclose(paged_output, naive_output, atol=1e-3, rtol=1e-3) | ||
|
|
||
| for i in range(batch_size): | ||
| beam_idx[i * beam_size : (i + 1) * beam_size] = torch.randint( | ||
| i * beam_size, | ||
| (i + 1) * beam_size, | ||
| (1, beam_size), | ||
| device=device, | ||
| dtype=torch.int64, | ||
| ) | ||
| naive_cache.reorder_cache(beam_idx) | ||
| pagedcache.reorder_cache(beam_idx) | ||
|
|
||
| # Next token | ||
| pagedcache.allocate(batch_size * beam_size, 1) | ||
| prompt_inputs = torch.randn( | ||
| batch_size * beam_size, | ||
| 1, | ||
| num_query_heads * head_dim, | ||
| device=device, | ||
| dtype=dtype, | ||
| ) | ||
| paged_output = mha_model(prompt_inputs, pagedcache) | ||
| naive_output = mha_model(prompt_inputs, naive_cache) | ||
| torch.allclose(paged_output, naive_output, atol=1e-3, rtol=1e-3) | ||
|
|
||
| def test_paged_attention_kv_cache(self): | ||
| # num_blocks, block_size, num_query_heads, num_key_value_heads, head_dim, device, dtype, batch_size, beam_size | ||
| num_blocks = 128 | ||
| block_sizes = [16, 32] | ||
| num_query_heads = [40] | ||
| num_key_value_heads = [40, 10, 1] | ||
| head_dim = [64, 128] | ||
| device = ['cpu'] | ||
| dtypes = [torch.float, torch.float16, torch.bfloat16] | ||
| batch_size = [1, 8] | ||
| beam_size = [1, 4] | ||
| for ( | ||
| block_size, | ||
| num_query_head, | ||
| num_key_value_head, | ||
| head_dim, | ||
| device, | ||
| dtype, | ||
| batch_size, | ||
| beam_size, | ||
| ) in product( | ||
| block_sizes, | ||
| num_query_heads, | ||
| num_key_value_heads, | ||
| head_dim, | ||
| device, | ||
| dtypes, | ||
| batch_size, | ||
| beam_size, | ||
| ): | ||
| self._test_paged_attention_cache( | ||
| num_blocks, | ||
| block_size, | ||
| num_query_head, | ||
| num_key_value_head, | ||
| head_dim, | ||
| device, | ||
| dtype, | ||
| batch_size, | ||
| beam_size, | ||
| ) | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| test = unittest.main() | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.