"git@developer.sourcefind.cn:zhaoyu6/sglang.git" did not exist on "ca13f3b8c58e419c04e706bb5a6711073f466aa0"
cuda.py 11 KB
Newer Older
1
import torch
2
from text_generation_server.layers.attention.kv_cache import KVCache
3
from text_generation_server.utils.import_utils import SYSTEM
4
from text_generation_server.models.globals import (
5
    ATTENTION,
6
7
    BLOCK_SIZE,
)
8
from text_generation_server.layers.attention import Seqlen
9
from typing import Optional
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29

major, minor = torch.cuda.get_device_capability()
is_sm75 = major == 7 and minor == 5
_PARTITION_SIZE = 512

try:
    from vllm._C import cache_ops
except Exception as e:
    raise ImportError(
        f"Could not import vllm paged attention. Make sure your installation is correct. Complete error: {e}"
    )


def reshape_and_cache(
    key: torch.Tensor,
    value: torch.Tensor,
    key_cache: torch.Tensor,
    value_cache: torch.Tensor,
    slots: torch.Tensor,
):
30
    if ATTENTION in {"flashdecoding", "flashinfer"}:
31
32
33
34
35
36
37
        shape = key_cache.shape
        key_cache.view(-1, shape[-2], shape[-1])[slots] = key
        value_cache.view(-1, shape[-2], shape[-1])[slots] = value
    else:
        cache_ops.reshape_and_cache(
            key, value, key_cache, value_cache, slots, "auto", 1.0
        )
38
39
40
41


def paged_attention(
    query: torch.Tensor,
42
    kv_cache: KVCache,
43
44
45
    kv_head_mapping: torch.Tensor,
    softmax_scale: float,
    block_tables: torch.Tensor,
46
    seqlen: Seqlen,
47
    max_s: int,
48
    softcap: Optional[float] = None,
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
):
    # Adapted from: https://github.com/vllm-project/vllm/blob/f8a1e39fae05ca610be8d5a78be9d40f5274e5fc/vllm/model_executor/layers/attention.py
    # Copyright 2023 The vLLM team. All rights
    # reserved.
    #
    # Licensed under the Apache License, Version 2.0 (the "License");
    # you may not use this file except in compliance with the License.
    # You may obtain a copy of the License at
    #
    #     http://www.apache.org/licenses/LICENSE-2.0
    #
    # Unless required by applicable law or agreed to in writing, software
    # distributed under the License is distributed on an "AS IS" BASIS,
    # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    # See the License for the specific language governing permissions and
    # limitations under the License.
    #

    # value_cache => [num_blocks, num_heads, head_size, block_size]
68
69
    # block_size = value_cache.shape[3]
    block_size = BLOCK_SIZE
70
71
72
73
74
75
76
77
    num_seqs, num_heads, head_size = query.shape
    max_num_partitions = (max_s + _PARTITION_SIZE - 1) // _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.
78
    if ATTENTION == "flashinfer":
Nicolas Patry's avatar
Nicolas Patry committed
79
        from text_generation_server.layers.attention.flashinfer import decode_state
80
81
82

        return decode_state.get().forward(
            query.contiguous(),
83
            paged_kv_cache=(kv_cache.key, kv_cache.value),
84
85
86
            logits_soft_cap=softcap,
            sm_scale=softmax_scale,
        )
87
    elif ATTENTION == "flashdecoding":
88
89
90
        max_q = 1
        max_k = max_s
        import flash_attn_2_cuda
91

92
93
94
95
96
        # TODO fixme when flash contains the fix.
        # Number of splits is not correctly handled
        # by the current path
        # https://github.com/Dao-AILab/flash-attention/blob/320fb59487658f033f56711efd3d61b7c7a6f8f3/csrc/flash_attn/flash_api.cpp#L577
        # This fails becuase we're using causal, therefore window_right is set to 0 and the split logic is never applied.
97
98
        if softcap is None:
            softcap = 0.0
99
        out = flash_attn_2_cuda.varlen_fwd(
100
            query,
101
102
            kv_cache.key,
            kv_cache.value,
103
104
105
            None,
            seqlen.cu_seqlen_q,
            seqlen.cu_seqlen_k,
106
            None,  # pad_k
107
            None,
108
109
            block_tables,
            None,
110
111
112
113
114
115
116
117
            max_q,
            max_k,
            0.0,  # dropout
            softmax_scale,
            False,  # zero_tensors
            True,  # causal
            -1,  # Window_left
            -1,  # Window right
118
            softcap,
119
120
            False,  # return softmax
            None,  # generator
121
        )
122
        return out[0]
123
    else:
124
125
        if softcap is not None:
            raise RuntimeError("Paged attention doesn't support softcapping")
126
        input_lengths = seqlen.input_lengths + seqlen.cache_lengths
127
        from vllm._C import ops
128

129
130
        out = torch.empty_like(query)

131
132
        use_v1 = max_s <= 8192 and (
            max_num_partitions == 1 or num_seqs * num_heads > 512
133
        )
134
135
136
137
        if use_v1:
            ops.paged_attention_v1(
                out,
                query,
138
139
                kv_cache.key,
                kv_cache.value,
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
                kv_head_mapping,
                softmax_scale,
                block_tables,
                input_lengths,
                block_size,
                max_s,
                None,
                "auto",
                1.0,
            )
        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=out.dtype,
                device=out.device,
            )
            exp_sums = torch.empty(
                size=(num_seqs, num_heads, max_num_partitions),
                dtype=torch.float32,
                device=out.device,
            )
            max_logits = torch.empty_like(exp_sums)

            ops.paged_attention_v2(
                out,
                exp_sums,
                max_logits,
                tmp_output,
                query,
171
172
                kv_cache.key,
                kv_cache.value,
173
174
175
176
177
178
179
180
181
182
183
                kv_head_mapping,
                softmax_scale,
                block_tables,
                input_lengths,
                block_size,
                max_s,
                None,
                "auto",
                1.0,
            )
    return out
184
185
186


try:
187
188
189
190
    is_ampere_or_newer = major >= 8 and minor >= 0
    if not is_ampere_or_newer:
        raise ImportError("FlashAttention only supports Ampere GPUs or newer.")

191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
    import flash_attn_2_cuda

    V2 = True
except ImportError:
    try:
        import flash_attn_cuda

        V2 = False
    except ImportError as e:
        if major >= 8:
            architecture_suffix = f"-{SYSTEM}"
            raise ImportError(
                "Flash Attention V2 is not installed.\n"
                "Use the official Docker image (ghcr.io/huggingface/text-generation-inference:latest) "
                f"or install flash attention v2 with `cd server && make install install-flash-attention-v2{architecture_suffix}`"
            )
        elif is_sm75:
            raise ImportError(
                "Flash Attention is not installed.\n"
                "Use the official Docker image (ghcr.io/huggingface/text-generation-inference:latest) "
                "or install flash attention with `cd server && make install install-flash-attention`"
            ) from e
        else:
            raise ImportError(
                f"GPU with CUDA capability {major} {minor} is not supported"
            ) from e


219
220
221
if ATTENTION == "flashdecoding" and not V2:
    raise ValueError("Flash decoding requires Flash Attention V2")

222
SUPPORTS_WINDOWING = V2
223

224
225
226
227
228
229
230
231
232
233
234
235
236
237
238

def attention(
    *,
    query: torch.Tensor,
    key: torch.Tensor,
    value: torch.Tensor,
    kv_cache: KVCache,
    seqlen: Seqlen,
    block_tables: torch.Tensor,
    softmax_scale: float,
    window_size_left: int = -1,
    causal: bool = True,
    softcap: Optional[float] = None,
):
    if ATTENTION == "flashinfer":
Nicolas Patry's avatar
Nicolas Patry committed
239
240
241
        from text_generation_server.layers.attention.flashinfer import (
            prefill_with_paged_kv_state,
        )
242

243
244
245
        if softcap is None:
            softcap = 0.0

Nicolas Patry's avatar
Nicolas Patry committed
246
        return prefill_with_paged_kv_state.get().forward(
247
            query.contiguous(),
248
            causal=causal,
249
            paged_kv_cache=(kv_cache.key, kv_cache.value),
250
251
            logits_soft_cap=softcap,
            sm_scale=softmax_scale,
252
            window_left=window_size_left,
253
254
        )

255
256
257
258
259
260
    # If we are using flashdecoding or paged, we always use flash-attn for
    # the prefill. We have to branch on whether we use flash-attn v1 or v2.
    elif V2:
        out = torch.empty_like(query)
        if window_size_left <= 0 and window_size_left != -1:
            raise ValueError("`window_size_left` must be > 0 or -1")
261

262
263
        if softcap is None:
            softcap = 0.0
264

265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
        return flash_attn_2_cuda.varlen_fwd(
            query,
            # flashdecoding: pass the KV caches, paged: pass the KV.
            kv_cache.key if ATTENTION == "flashdecoding" else key,
            kv_cache.value if ATTENTION == "flashdecoding" else value,
            out,
            seqlen.cu_seqlen_q,
            seqlen.cu_seqlen_k,
            None,
            None,
            block_tables if ATTENTION == "flashdecoding" else None,
            None,
            seqlen.max_q,
            seqlen.max_k,
            0.0,
280
            softmax_scale,
281
282
283
284
285
286
287
288
            False,
            causal,
            window_size_left,
            0,
            softcap,
            False,
            None,
        )[0]
289
290

    else:
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
        if window_size_left != -1:
            raise NotImplementedError(
                "window_size_left is only available with flash attn v2"
            )
        if softcap is not None:
            raise NotImplementedError("softcap is not available in flash attn v1")

        # Flash attention v1 requires q, k and v to have the same number of heads
        if key.shape[1] != query.shape[1]:
            # MQA expand
            if key.shape[1] == 1:
                key = key.expand(-1, query.shape[1], -1)
            # Grouped attention reshape
            else:
                original_shape = key.shape
                key = (
                    key.unsqueeze(2)
                    .expand(-1, -1, query.shape[1] // key.shape[1], -1)
                    .reshape(original_shape[0], -1, original_shape[2])
310
                )
311
312
313
314
315
316
317
318
319
320
321
        if value.shape[1] != query.shape[1]:
            # MQA expand
            if value.shape[1] == 1:
                value = value.expand(-1, query.shape[1], -1)
            # Grouped attention reshape
            else:
                original_shape = value.shape
                value = (
                    value.unsqueeze(2)
                    .expand(-1, -1, query.shape[1] // value.shape[1], -1)
                    .reshape(original_shape[0], -1, original_shape[2])
322
323
                )

324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
        out = torch.empty_like(query)
        flash_attn_cuda.fwd(
            query,
            key,
            value,
            out,
            seqlen.cu_seqlen_q,
            seqlen.cu_seqlen_q,
            seqlen.max_q,
            seqlen.max_k,
            0.0,
            softmax_scale,
            False,
            causal,
            False,
            0,
            None,
        )
        return out
343

344
345
346
347
348
349
350

__all__ = [
    "SUPPORTS_WINDOWING",
    "attention",
    "paged_attention",
    "reshape_and_cache",
]