main
py 51 lines 1.4 KB
Raw
1 # SPDX-License-Identifier: Apache-2.0
2 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project
3
4
5 import torch
6
7 from vllm.platforms import current_platform
8
9 if current_platform.is_cuda_alike():
10 from vllm import _custom_ops as ops
11 elif current_platform.is_xpu():
12 from vllm._xpu_ops import xpu_ops as ops # type: ignore[no-redef]
13
14
15 class PagedAttention:
16 @staticmethod
17 def split_kv_cache(
18 kv_cache: torch.Tensor,
19 num_kv_heads: int,
20 head_size: int,
21 ) -> tuple[torch.Tensor, torch.Tensor]:
22 x = 16 // kv_cache.element_size()
23 num_blocks = kv_cache.shape[1]
24
25 key_cache = kv_cache[0]
26 key_cache = key_cache.view(num_blocks, num_kv_heads, head_size // x, -1, x)
27 value_cache = kv_cache[1]
28 value_cache = value_cache.view(num_blocks, num_kv_heads, head_size, -1)
29 return key_cache, value_cache
30
31 @staticmethod
32 def write_to_paged_cache(
33 key: torch.Tensor,
34 value: torch.Tensor,
35 key_cache: torch.Tensor,
36 value_cache: torch.Tensor,
37 slot_mapping: torch.Tensor,
38 kv_cache_dtype: str,
39 k_scale: torch.Tensor,
40 v_scale: torch.Tensor,
41 ) -> None:
42 ops.reshape_and_cache(
43 key,
44 value,
45 key_cache,
46 value_cache,
47 slot_mapping.flatten(),
48 kv_cache_dtype,
49 k_scale,
50 v_scale,
51 )