attn_utils.py 10.5 KB
Newer Older
Woosuk Kwon's avatar
Woosuk Kwon committed
1
2
3
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from collections.abc import Sequence
4
from dataclasses import dataclass
5
from typing import Any, cast
Woosuk Kwon's avatar
Woosuk Kwon committed
6

7
import numpy as np
Woosuk Kwon's avatar
Woosuk Kwon committed
8
9
10
11
import torch

from vllm.config import VllmConfig, get_layers_from_vllm_config
from vllm.model_executor.layers.attention_layer_base import AttentionLayerBase
12
13
14
15
16
from vllm.v1.attention.backend import (
    AttentionBackend,
    AttentionCGSupport,
    CommonAttentionMetadata,
)
Woosuk Kwon's avatar
Woosuk Kwon committed
17
from vllm.v1.kv_cache_interface import (
18
    AttentionSpec,
Woosuk Kwon's avatar
Woosuk Kwon committed
19
20
    KVCacheConfig,
    KVCacheSpec,
21
    UniformTypeKVCacheSpecs,
Woosuk Kwon's avatar
Woosuk Kwon committed
22
)
23
from vllm.v1.worker.utils import AttentionGroup, bind_kv_cache
Woosuk Kwon's avatar
Woosuk Kwon committed
24
25


26
27
28
29
30
31
@dataclass(frozen=True)
class AttentionCGSupportInfo:
    min_cg_support: AttentionCGSupport = AttentionCGSupport.ALWAYS
    min_cg_attn_backend: str | None = None


Woosuk Kwon's avatar
Woosuk Kwon committed
32
33
def get_kv_cache_spec(vllm_config: VllmConfig) -> dict[str, KVCacheSpec]:
    kv_cache_spec: dict[str, KVCacheSpec] = {}
34
35
    layer_type = cast(type[Any], AttentionLayerBase)
    attn_layers = get_layers_from_vllm_config(vllm_config, layer_type)
Woosuk Kwon's avatar
Woosuk Kwon committed
36
37
38
39
40
41
42
43
    for layer_name, attn_module in attn_layers.items():
        # Skip modules that don't need KV cache (eg encoder-only attention)
        if spec := attn_module.get_kv_cache_spec(vllm_config):
            kv_cache_spec[layer_name] = spec
    return kv_cache_spec


def init_attn_backend(
44
45
46
47
    kv_cache_config: KVCacheConfig,
    vllm_config: VllmConfig,
    device: torch.device,
    active_layer_names: set[str] | None = None,
48
49
50
51
52
) -> tuple[
    dict[str, type[AttentionBackend]],
    list[list[AttentionGroup]],
    AttentionCGSupportInfo,
]:
53
    attn_backends: dict[str, type[AttentionBackend]] = {}
54
55
    attn_groups: list[list[AttentionGroup]] = []
    attn_backend_workspace: torch.Tensor | None = None
56
57
58
    # Find minimum cudagraph support across all attention backends
    min_cg_support = AttentionCGSupport.ALWAYS
    min_cg_attn_backend = None
59
60
61
    for kv_cache_group_id, kv_cache_group_spec in enumerate(
        kv_cache_config.kv_cache_groups
    ):
Woosuk Kwon's avatar
Woosuk Kwon committed
62
        layer_names = kv_cache_group_spec.layer_names
63
64
        if active_layer_names is not None:
            layer_names = list(active_layer_names.intersection(layer_names))
Woosuk Kwon's avatar
Woosuk Kwon committed
65

66
67
        layer_type = cast(type[Any], AttentionLayerBase)
        attn_layers = get_layers_from_vllm_config(vllm_config, layer_type, layer_names)
68
69
70
71

        group_map: dict[tuple[tuple[str, str], KVCacheSpec], AttentionGroup] = {}
        group_order: list[tuple[tuple[str, str], KVCacheSpec]] = []

Woosuk Kwon's avatar
Woosuk Kwon committed
72
        for layer_name in layer_names:
73
            attn_backend = attn_layers[layer_name].get_attn_backend()
Woosuk Kwon's avatar
Woosuk Kwon committed
74
75
            attn_backends[layer_name] = attn_backend

76
77
78
79
80
81
82
83
84
85
86
87
88
            layer_kv_cache_spec: KVCacheSpec = kv_cache_group_spec.kv_cache_spec
            if isinstance(layer_kv_cache_spec, UniformTypeKVCacheSpecs):
                layer_kv_cache_spec = layer_kv_cache_spec.kv_cache_specs[layer_name]

            key = (attn_backend.full_cls_name(), layer_kv_cache_spec)
            if key not in group_map:
                group_map[key] = AttentionGroup(
                    attn_backend,
                    [layer_name],
                    layer_kv_cache_spec,
                    kv_cache_group_id,
                )
                group_order.append(key)
Woosuk Kwon's avatar
Woosuk Kwon committed
89
            else:
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
                group_map[key].layer_names.append(layer_name)

        groups = [group_map[key] for key in group_order]
        for group in groups:
            group.create_metadata_builders(
                vllm_config=vllm_config,
                device=device,
                kernel_block_size=None,
                num_metadata_builders=1,
            )
            builder = group.get_metadata_builder(0)
            if attn_backend_workspace is None:
                if hasattr(builder, "_get_workspace_buffer"):
                    attn_backend_workspace = builder._get_workspace_buffer()
            else:
                if hasattr(builder, "set_workspace_buffer"):
                    builder.set_workspace_buffer(attn_backend_workspace)
107
108
109
110
111
112
113
114
            # Check cudagraph support for the attention backend
            cg_support = builder.get_cudagraph_support(
                vllm_config,
                cast(AttentionSpec, kv_cache_group_spec.kv_cache_spec),
            )
            if cg_support.value < min_cg_support.value:
                min_cg_support = cg_support
                min_cg_attn_backend = attn_backend.__name__
115
        attn_groups.append(groups)
116
117
118
119
120
121
122
123
124

    return (
        attn_backends,
        attn_groups,
        AttentionCGSupportInfo(
            min_cg_support=min_cg_support,
            min_cg_attn_backend=min_cg_attn_backend,
        ),
    )
Woosuk Kwon's avatar
Woosuk Kwon committed
125
126


127
def _allocate_kv_cache(kv_cache_config: KVCacheConfig, device: torch.device):
Woosuk Kwon's avatar
Woosuk Kwon committed
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
    kv_cache_raw_tensors: dict[str, torch.Tensor] = {}
    for kv_cache_tensor in kv_cache_config.kv_cache_tensors:
        tensor = torch.zeros(kv_cache_tensor.size, dtype=torch.int8, device=device)
        for layer_name in kv_cache_tensor.shared_by:
            kv_cache_raw_tensors[layer_name] = tensor

    layer_names = set()
    for group in kv_cache_config.kv_cache_groups:
        for layer_name in group.layer_names:
            layer_names.add(layer_name)
    assert layer_names == set(kv_cache_raw_tensors.keys()), (
        "Some layers are not correctly initialized"
    )
    return kv_cache_raw_tensors


def _reshape_kv_cache(
    kv_cache_config: KVCacheConfig,
    kv_cache_raw_tensors: dict[str, torch.Tensor],
147
    attn_backends: dict[str, type[AttentionBackend]],
148
    cache_dtype: str,
Woosuk Kwon's avatar
Woosuk Kwon committed
149
150
151
152
) -> dict[str, torch.Tensor]:
    kv_caches: dict[str, torch.Tensor] = {}
    for kv_cache_group_spec in kv_cache_config.kv_cache_groups:
        for layer_name in kv_cache_group_spec.layer_names:
Woosuk Kwon's avatar
Woosuk Kwon committed
153
154
155
156
157
            kv_cache_spec = kv_cache_group_spec.kv_cache_spec
            if isinstance(kv_cache_spec, UniformTypeKVCacheSpecs):
                kv_cache_spec = kv_cache_spec.kv_cache_specs[layer_name]
            assert isinstance(kv_cache_spec, AttentionSpec)

Woosuk Kwon's avatar
Woosuk Kwon committed
158
159
160
161
162
163
164
165
166
167
            raw_tensor = kv_cache_raw_tensors[layer_name]
            assert raw_tensor.numel() % kv_cache_spec.page_size_bytes == 0
            num_blocks = raw_tensor.numel() // kv_cache_spec.page_size_bytes

            attn_backend = attn_backends[layer_name]
            kv_cache_shape = attn_backend.get_kv_cache_shape(
                num_blocks,
                kv_cache_spec.block_size,
                kv_cache_spec.num_kv_heads,
                kv_cache_spec.head_size,
168
                cache_dtype,
Woosuk Kwon's avatar
Woosuk Kwon committed
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
            )

            # FIXME(woosuk): Add kv_cache_stride_order to all attention backends.
            try:
                kv_cache_stride_order = attn_backend.get_kv_cache_stride_order()
                assert len(kv_cache_stride_order) == len(kv_cache_shape)
            except (AttributeError, NotImplementedError):
                kv_cache_stride_order = tuple(range(len(kv_cache_shape)))

            kv_cache_shape = tuple(kv_cache_shape[i] for i in kv_cache_stride_order)
            inv_order = [
                kv_cache_stride_order.index(i)
                for i in range(len(kv_cache_stride_order))
            ]

            dtype = kv_cache_spec.dtype
            raw_tensor = raw_tensor.view(dtype)
            raw_tensor = raw_tensor.view(kv_cache_shape)
            kv_caches[layer_name] = raw_tensor.permute(*inv_order)
    return kv_caches


def init_kv_cache(
    runner_kv_caches: list[torch.Tensor],
    forward_context: dict[str, Any],
    kv_cache_config: KVCacheConfig,
195
    attn_backends: dict[str, type[AttentionBackend]],
Woosuk Kwon's avatar
Woosuk Kwon committed
196
    device: torch.device,
197
    cache_dtype: str,
198
) -> dict[str, torch.Tensor]:
Woosuk Kwon's avatar
Woosuk Kwon committed
199
    kv_cache_raw_tensors = _allocate_kv_cache(kv_cache_config, device)
200
201
202
    kv_caches = _reshape_kv_cache(
        kv_cache_config, kv_cache_raw_tensors, attn_backends, cache_dtype
    )
Woosuk Kwon's avatar
Woosuk Kwon committed
203
    bind_kv_cache(kv_caches, forward_context, runner_kv_caches)
204
    return kv_caches
Woosuk Kwon's avatar
Woosuk Kwon committed
205
206


207
def build_slot_mappings_by_layer(
208
    slot_mappings: torch.Tensor, kv_cache_config: KVCacheConfig
209
210
) -> dict[str, torch.Tensor]:
    slot_mappings_by_layer: dict[str, torch.Tensor] = {}
211
212
    kv_cache_groups = kv_cache_config.kv_cache_groups
    for slot_mapping, kv_cache_group in zip(slot_mappings, kv_cache_groups):
213
214
215
216
217
        for layer_name in kv_cache_group.layer_names:
            slot_mappings_by_layer[layer_name] = slot_mapping
    return slot_mappings_by_layer


Woosuk Kwon's avatar
Woosuk Kwon committed
218
def build_attn_metadata(
219
    attn_groups: list[list[AttentionGroup]],
Woosuk Kwon's avatar
Woosuk Kwon committed
220
221
    num_reqs: int,
    num_tokens: int,
222
223
    query_start_loc_gpu: torch.Tensor,
    query_start_loc_cpu: torch.Tensor,
224
    max_query_len: int,
225
    seq_lens: torch.Tensor,
226
    max_seq_len: int,
Woosuk Kwon's avatar
Woosuk Kwon committed
227
228
229
    block_tables: Sequence[torch.Tensor],
    slot_mappings: torch.Tensor,
    kv_cache_config: KVCacheConfig,
230
    seq_lens_cpu_upper_bound: torch.Tensor | None = None,
231
    dcp_local_seq_lens: torch.Tensor | None = None,
232
    encoder_seq_lens: dict[int, tuple[torch.Tensor, np.ndarray]] | None = None,
Woosuk Kwon's avatar
Woosuk Kwon committed
233
) -> dict[str, Any]:
234
    seq_lens = seq_lens[:num_reqs]
235
236
    if dcp_local_seq_lens is not None:
        dcp_local_seq_lens = dcp_local_seq_lens[:num_reqs]
237
238
    if seq_lens_cpu_upper_bound is not None:
        seq_lens_cpu_upper_bound = seq_lens_cpu_upper_bound[:num_reqs]
239

Woosuk Kwon's avatar
Woosuk Kwon committed
240
    attn_metadata: dict[str, Any] = {}
241
242
    num_kv_cache_groups = len(kv_cache_config.kv_cache_groups)
    for i in range(num_kv_cache_groups):
Woosuk Kwon's avatar
Woosuk Kwon committed
243
244
245
246
247
248
        block_table = block_tables[i]
        slot_mapping = slot_mappings[i]

        common_attn_metadata = CommonAttentionMetadata(
            query_start_loc=query_start_loc_gpu,
            query_start_loc_cpu=query_start_loc_cpu,
249
            seq_lens=seq_lens,
250
            seq_lens_cpu_upper_bound=seq_lens_cpu_upper_bound,
Woosuk Kwon's avatar
Woosuk Kwon committed
251
252
253
254
255
256
257
            max_seq_len=max_seq_len,
            num_reqs=num_reqs,
            num_actual_tokens=num_tokens,
            max_query_len=max_query_len,
            block_table_tensor=block_table,
            slot_mapping=slot_mapping,
            causal=True,
258
            dcp_local_seq_lens=dcp_local_seq_lens,
Woosuk Kwon's avatar
Woosuk Kwon committed
259
        )
260
261
262
263
        if encoder_seq_lens and i in encoder_seq_lens:
            encoder_seq_lens_gpu, encoder_seq_lens_cpu = encoder_seq_lens[i]
            common_attn_metadata.encoder_seq_lens = encoder_seq_lens_gpu
            common_attn_metadata.encoder_seq_lens_cpu = encoder_seq_lens_cpu
Woosuk Kwon's avatar
Woosuk Kwon committed
264

265
266
267
268
269
270
271
        for attn_group in attn_groups[i]:
            attn_metadata_builder = attn_group.get_metadata_builder(0)
            metadata = attn_metadata_builder.build(
                common_prefix_len=0, common_attn_metadata=common_attn_metadata
            )
            for layer_name in attn_group.layer_names:
                attn_metadata[layer_name] = metadata
Woosuk Kwon's avatar
Woosuk Kwon committed
272
    return attn_metadata