paged_attn.py 8.19 KB
Newer Older
1
# SPDX-License-Identifier: Apache-2.0
2
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
3

4
from dataclasses import dataclass
5
from typing import List, Optional, Tuple
6
7
8

import torch

9
from vllm import _custom_ops as ops
10
11
12
13
from vllm.triton_utils import HAS_TRITON

if HAS_TRITON:
    from vllm.attention.ops.prefix_prefill import context_attention_fwd
14
15
16
17
18
19
20
21

# Should be the same as PARTITION_SIZE in `paged_attention_v2_launcher`.
_PARTITION_SIZE = 512


@dataclass
class PagedAttentionMetadata:
    """Metadata for PagedAttention."""
22
23
24
    # (batch_size,). The length of sequences (entire tokens seen so far) per
    # sequence.
    seq_lens_tensor: Optional[torch.Tensor]
25
26
    # Maximum sequence length in the batch. 0 if it is prefill-only batch.
    max_decode_seq_len: int
27
28
29
30
31
32
33
34
35
36
37
38
39
    # (batch_size, max_blocks_per_seq).
    # Block addresses per sequence. (Seq id -> list of physical block)
    # E.g., [0, 1, 2] means tokens are stored in 0th, 1st, and 2nd blocks
    # in the kv cache. Each block can contain up to block_size tokens.
    # 2nd dimensions are padded up to max_blocks_per_seq if it is cuda-graph
    # captured.
    block_tables: Optional[torch.Tensor]


class PagedAttention:

    @staticmethod
    def get_supported_head_sizes() -> List[int]:
40
        return [32, 64, 80, 96, 112, 120, 128, 192, 256]
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74

    @staticmethod
    def get_kv_cache_shape(
        num_blocks: int,
        block_size: int,
        num_kv_heads: int,
        head_size: int,
    ) -> Tuple[int, ...]:
        return (2, num_blocks, block_size * num_kv_heads * head_size)

    @staticmethod
    def split_kv_cache(
        kv_cache: torch.Tensor,
        num_kv_heads: int,
        head_size: int,
    ) -> Tuple[torch.Tensor, torch.Tensor]:
        x = 16 // kv_cache.element_size()
        num_blocks = kv_cache.shape[1]

        key_cache = kv_cache[0]
        key_cache = key_cache.view(num_blocks, num_kv_heads, head_size // x,
                                   -1, x)
        value_cache = kv_cache[1]
        value_cache = value_cache.view(num_blocks, num_kv_heads, head_size, -1)
        return key_cache, value_cache

    @staticmethod
    def write_to_paged_cache(
        key: torch.Tensor,
        value: torch.Tensor,
        key_cache: torch.Tensor,
        value_cache: torch.Tensor,
        slot_mapping: torch.Tensor,
        kv_cache_dtype: str,
75
76
        k_scale: torch.Tensor,
        v_scale: torch.Tensor,
77
    ) -> None:
78
        ops.reshape_and_cache(
79
80
81
82
83
84
            key,
            value,
            key_cache,
            value_cache,
            slot_mapping.flatten(),
            kv_cache_dtype,
85
86
            k_scale,
            v_scale,
87
88
89
90
91
92
93
94
        )

    @staticmethod
    def forward_decode(
        query: torch.Tensor,
        key_cache: torch.Tensor,
        value_cache: torch.Tensor,
        block_tables: torch.Tensor,
95
96
        seq_lens: torch.Tensor,
        max_seq_len: int,
97
98
99
100
        kv_cache_dtype: str,
        num_kv_heads: int,
        scale: float,
        alibi_slopes: Optional[torch.Tensor],
101
102
        k_scale: torch.Tensor,
        v_scale: torch.Tensor,
103
104
105
106
107
        tp_rank: int = 0,
        blocksparse_local_blocks: int = 0,
        blocksparse_vert_stride: int = 0,
        blocksparse_block_size: int = 64,
        blocksparse_head_sliding_step: int = 0,
108
    ) -> torch.Tensor:
109
110
111
112
113
114
115
        if blocksparse_vert_stride is not None and blocksparse_vert_stride > 1:
            # use blocksparse paged attention
            block_size = value_cache.size(-1)
            assert (blocksparse_block_size > 0 and
                    blocksparse_block_size % block_size == 0), \
                (f"{blocksparse_block_size=} needs to be a multiple of"
                 f"{block_size=} used in block_tables.")
116

117
        output = torch.empty_like(query)
118
119
        block_size = value_cache.shape[3]
        num_seqs, num_heads, head_size = query.shape
120
        max_num_partitions = ((max_seq_len + _PARTITION_SIZE - 1) //
121
122
123
124
125
126
127
128
                              _PARTITION_SIZE)
        # NOTE(woosuk): We use a simple heuristic to decide whether to use
        # PagedAttention V1 or V2. If the number of partitions is 1, we use
        # V1 to avoid the overhead of reduction. Also, if the number of
        # sequences or heads is large, we use V1 since there is enough work
        # to parallelize.
        # TODO(woosuk): Tune this heuristic.
        # For context len > 8192, use V2 kernel to avoid shared memory shortage.
129
        use_v1 = (max_seq_len <= 8192
130
                  and (max_num_partitions == 1 or num_seqs * num_heads > 512))
131

132
133
134
135
136
137
138
139
140
141
        if use_v1:
            # Run PagedAttention V1.
            ops.paged_attention_v1(
                output,
                query,
                key_cache,
                value_cache,
                num_kv_heads,
                scale,
                block_tables,
142
                seq_lens,
143
                block_size,
144
                max_seq_len,
145
146
                alibi_slopes,
                kv_cache_dtype,
147
148
                k_scale,
                v_scale,
149
150
151
152
153
                tp_rank,
                blocksparse_local_blocks,
                blocksparse_vert_stride,
                blocksparse_block_size,
                blocksparse_head_sliding_step,
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
            )
        else:
            # Run PagedAttention V2.
            assert _PARTITION_SIZE % block_size == 0
            tmp_output = torch.empty(
                size=(num_seqs, num_heads, max_num_partitions, head_size),
                dtype=output.dtype,
                device=output.device,
            )
            exp_sums = torch.empty(
                size=(num_seqs, num_heads, max_num_partitions),
                dtype=torch.float32,
                device=output.device,
            )
            max_logits = torch.empty_like(exp_sums)
            ops.paged_attention_v2(
                output,
                exp_sums,
                max_logits,
                tmp_output,
                query,
                key_cache,
                value_cache,
                num_kv_heads,
                scale,
                block_tables,
180
                seq_lens,
181
                block_size,
182
                max_seq_len,
183
184
                alibi_slopes,
                kv_cache_dtype,
185
186
                k_scale,
                v_scale,
187
188
189
190
191
                tp_rank,
                blocksparse_local_blocks,
                blocksparse_vert_stride,
                blocksparse_block_size,
                blocksparse_head_sliding_step,
192
193
194
195
196
197
198
199
            )
        return output

    @staticmethod
    def forward_prefix(
        query: torch.Tensor,
        key: torch.Tensor,
        value: torch.Tensor,
200
        kv_cache_dtype: str,
201
202
203
        key_cache: torch.Tensor,
        value_cache: torch.Tensor,
        block_tables: torch.Tensor,
204
        query_start_loc: torch.Tensor,
205
206
        seq_lens_tensor: torch.Tensor,
        max_query_len: int,
207
        alibi_slopes: Optional[torch.Tensor],
208
        sliding_window: Optional[int],
209
210
        k_scale: torch.Tensor,
        v_scale: torch.Tensor,
211
212
    ) -> torch.Tensor:
        output = torch.empty_like(query)
213
        max_seq_len = None
214
215
216
217
218
        context_attention_fwd(
            query,
            key,
            value,
            output,
219
            kv_cache_dtype,
220
221
222
            key_cache,
            value_cache,
            block_tables,
223
            # query_start_loc is (batch_size + 1,)
224
            query_start_loc,
225
            seq_lens_tensor,
226
            max_seq_len,
227
            max_query_len,
228
229
            k_scale,
            v_scale,
230
            alibi_slopes,
231
            sliding_window,
232
233
234
235
236
237
238
        )
        return output

    @staticmethod
    def swap_blocks(
        src_kv_cache: torch.Tensor,
        dst_kv_cache: torch.Tensor,
239
        src_to_dst: torch.Tensor,
240
241
242
    ) -> None:
        src_key_cache = src_kv_cache[0]
        dst_key_cache = dst_kv_cache[0]
243
        ops.swap_blocks(src_key_cache, dst_key_cache, src_to_dst)
244
245
246

        src_value_cache = src_kv_cache[1]
        dst_value_cache = dst_kv_cache[1]
247
        ops.swap_blocks(src_value_cache, dst_value_cache, src_to_dst)
248
249
250
251

    @staticmethod
    def copy_blocks(
        kv_caches: List[torch.Tensor],
252
        src_to_dists: torch.Tensor,
253
254
255
    ) -> None:
        key_caches = [kv_cache[0] for kv_cache in kv_caches]
        value_caches = [kv_cache[1] for kv_cache in kv_caches]
256
        ops.copy_blocks(key_caches, value_caches, src_to_dists)