"vscode:/vscode.git/clone" did not exist on "677424c7acd9fb7477294017c99f798588002d4f"
utils.py 9.22 KB
Newer Older
1
# SPDX-License-Identifier: Apache-2.0
2
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
3
import math
4
from collections import defaultdict
5
from dataclasses import dataclass, field
6

7
8
import torch

9
from vllm.config import CacheConfig, VllmConfig
10
from vllm.logger import init_logger
11
from vllm.model_executor.layers.attention import Attention
12
from vllm.model_executor.models.interfaces import MultiModalEmbeddings
13
from vllm.model_executor.models.utils import extract_layer_index
14
from vllm.platforms import current_platform
15
from vllm.utils.mem_utils import MemorySnapshot, format_gib
16
from vllm.v1.attention.backend import AttentionBackend, AttentionMetadataBuilder
17
from vllm.v1.kv_cache_interface import KVCacheGroupSpec, KVCacheSpec
18

19
20
logger = init_logger(__name__)

21

22
23
24
25
@dataclass
class AttentionGroup:
    backend: type[AttentionBackend]
    layer_names: list[str]
26
    kv_cache_spec: KVCacheSpec
27
    kv_cache_group_id: int
28
    # When ubatching is enabled we will have a metadata builder for each ubatch
29
    # so that if they use internal persistent buffers for cudagraphs, and they
30
31
32
33
    # won't have to worry about conflicting with the other ubatches.
    metadata_builders: list[AttentionMetadataBuilder] = field(
        default_factory=lambda: []
    )
34

35
36
37
38
39
    def create_metadata_builders(
        self,
        vllm_config,
        device,
        kernel_block_size: int | None,
40
        num_metadata_builders: int = 1,
41
42
43
44
45
46
47
48
49
50
51
52
53
    ):
        kv_cache_spec_builder = (
            self.kv_cache_spec.copy_with_new_block_size(kernel_block_size)
            if kernel_block_size is not None
            else self.kv_cache_spec
        )
        self.metadata_builders = [
            self.backend.get_builder_cls()(
                kv_cache_spec_builder,
                self.layer_names,
                vllm_config,
                device,
            )
54
55
56
            for _ in range(num_metadata_builders)
        ]

57
    def get_metadata_builder(self, ubatch_id: int = 0) -> AttentionMetadataBuilder:
58
59
60
        assert len(self.metadata_builders) > ubatch_id
        return self.metadata_builders[ubatch_id]

61

62
def sanity_check_mm_encoder_outputs(
63
    mm_embeddings: MultiModalEmbeddings,
64
65
66
67
    expected_num_items: int,
) -> None:
    """
    Perform sanity checks for the result of
68
    [`vllm.model_executor.models.SupportsMultiModal.embed_multimodal`][].
69
70
71
72
73
    """
    assert isinstance(mm_embeddings, (list, tuple, torch.Tensor)), (
        "Expected multimodal embeddings to be a list/tuple of 2D tensors, "
        f"or a single 3D tensor, but got {type(mm_embeddings)} "
        "instead. This is most likely due to incorrect implementation "
74
        "of the model's `embed_multimodal` method."
75
    )
76
77
78
79
80

    assert len(mm_embeddings) == expected_num_items, (
        "Expected number of multimodal embeddings to match number of "
        f"input items: {expected_num_items}, but got {len(mm_embeddings)=} "
        "instead. This is most likely due to incorrect implementation "
81
        "of the model's `embed_multimodal` method."
82
    )
83
84
85
86
87

    assert all(e.ndim == 2 for e in mm_embeddings), (
        "Expected multimodal embeddings to be a sequence of 2D tensors, "
        f"but got tensors with shapes {[e.shape for e in mm_embeddings]} "
        "instead. This is most likely due to incorrect implementation "
88
        "of the model's `embed_multimodal` method."
89
    )
90
91


92
def request_memory(init_snapshot: MemorySnapshot, cache_config: CacheConfig) -> int:
93
94
95
96
    """
    Calculate the amount of memory required by vLLM, then validate
    that the current amount of free memory is sufficient for that.
    """
97
98
99
    requested_memory = math.ceil(
        init_snapshot.total_memory * cache_config.gpu_memory_utilization
    )
100
101
102
103

    if init_snapshot.free_memory < requested_memory:
        raise ValueError(
            f"Free memory on device {init_snapshot.device_} "
104
105
            f"({format_gib(init_snapshot.free_memory)}/"
            f"{format_gib(init_snapshot.total_memory)} GiB) on startup "
106
107
            f"is less than desired GPU memory utilization "
            f"({cache_config.gpu_memory_utilization}, "
108
            f"{format_gib(requested_memory)} GiB). Decrease GPU memory "
109
110
111
112
113
114
            f"utilization or reduce GPU memory used by other processes."
        )

    return requested_memory


115
def add_kv_sharing_layers_to_kv_cache_groups(
116
117
    shared_kv_cache_layers: dict[str, str],
    kv_cache_groups: list[KVCacheGroupSpec],
118
    runner_only_attn_layers: set[str] | None = None,
119
120
121
122
123
124
125
126
127
128
129
130
131
132
) -> None:
    """
    Sets up KV cache sharing by reusing the allocated KV caches in `kv_caches`
    for layers that do not allocate its own KV cache, based on the mapping in
    `shared_kv_cache_layers`. Adds these layers to the corresponding KV cache
    group, which is needed to ensure that attention metadata is assigned later.

    Args:
        shared_kv_cache_layers: Layer pairings for cross-layer KV sharing.
            If an Attention layer `layer_name` is in the keys of this dict, it
            means this layer will perform attention using the keys and values
            from the KV cache of `shared_kv_cache_layers[layer_name]`.
        kv_cache_groups: The KV cache groups of the model.
    """
133
134
135
136
    layer_to_kv_cache_group: dict[str, KVCacheGroupSpec] = {}
    for kv_cache_group in kv_cache_groups:
        for layer_name in kv_cache_group.layer_names:
            layer_to_kv_cache_group[layer_name] = kv_cache_group
137
138

    for layer_name, target_layer_name in shared_kv_cache_layers.items():
139
140
        tgt_kv_cache_group = layer_to_kv_cache_group[target_layer_name]
        tgt_kv_cache_group.layer_names.append(layer_name)
141

142
143
144
        if runner_only_attn_layers is not None:
            runner_only_attn_layers.add(layer_name)

145
146
147

def bind_kv_cache(
    kv_caches: dict[str, torch.Tensor],
148
    forward_context: dict[str, Attention],
149
    runner_kv_caches: list[torch.Tensor],
150
    num_attn_module: int = 1,
151
152
153
154
155
156
157
158
159
160
161
162
163
164
) -> None:
    """
    Bind the allocated KV cache to both ModelRunner and forward context so
    that the KV cache can be used in the forward pass.

    This function:
      1) Fills the ModelRunner's kv cache list (`runner_kv_caches`) with
         kv_caches.
      2) Associates each attention layer in the `forward_context` with its
         corresponding KV cache in kv_caches.

    Args:
        kv_caches: The allocated kv_caches with layer names as keys.
        forward_context: The global forward context containing all Attention
165
            layers with layer names as keys.
166
167
168
169
170
171
172
173
        runner_kv_caches: The kv_cache declared by ModelRunner.
    """
    # Bind kv_caches to ModelRunner
    assert len(runner_kv_caches) == 0

    # Convert kv_caches dict to a list of tensors in the order of layer_index.
    index2name = defaultdict(list)
    for layer_name in kv_caches:
174
        index2name[extract_layer_index(layer_name, num_attn_module)].append(layer_name)
175
176
177
178
179
180
181

    for layer_index in sorted(index2name.keys()):
        layer_names = index2name[layer_index]
        if len(layer_names) > 1:
            # One typical case is encoder-decoder model, e.g., bart.
            # The cross attention and self attention in the same decoder layer
            # has different layer_name but the same layer_index.
182
183
184
185

            # TODO - analyze where runner_kv_caches is used and the right
            # way to ensure it properly reflects multiple attention layers
            # in the same decoder block.
186
187
188
189
190
191
            if (
                current_platform.is_cuda_alike()
                or current_platform.is_xpu()
                or current_platform.is_cpu()
            ):
                # We know that the GPU / CPU runner is not impacted by this
192
193
194
195
196
                # case. Some test code depends on runner_kv_caches, but
                # not in a way that's impacted by ignoring this.
                pass
            else:
                raise NotImplementedError
197
198
        for layer_name in layer_names:
            runner_kv_caches.append(kv_caches[layer_name])
199
200
201
202
203

    # Bind kv_caches to forward context
    for layer_name, kv_cache in kv_caches.items():
        # NOTE: Use list because of v0 PP virtual engine.
        forward_context[layer_name].kv_cache = [kv_cache]
204
205


206
207
208
def is_residual_scattered_for_sp(
    vllm_config: VllmConfig, num_input_tokens: int
) -> bool:
209
210
211
    """Check if the residual tensor is scattered for sequence parallelism.

    The residual tensor is scattered across tensor parallel ranks when sequence
212
213
    parallelism and tensor parallelism is enabled.

214
    This follows the same logic as SequenceParallelismPass.is_applicable_for_range():
215
216
217
    - In full-graph compilation mode (no splitting ops or using inductor graph
      partition), SP is always applied
    - Otherwise, SP is only applied for specific shapes in compile_sizes
218
    """
219
    if not vllm_config.compilation_config.pass_config.enable_sp:
220
221
222
223
224
225
226
227
228
229
230
        return False

    tp = vllm_config.parallel_config.tensor_parallel_size

    if tp == 1:
        return False

    # When sequence parallelism is enabled, we always pad num_input_tokens
    # to be a multiple of tensor_parallel_size (tp) earlier.
    assert num_input_tokens % tp == 0

231
232
233
234
235
    if (
        not vllm_config.compilation_config.splitting_ops
        or vllm_config.compilation_config.use_inductor_graph_partition
    ):
        return True
236
237
238
239
    compile_sizes = vllm_config.compilation_config.compile_sizes
    if compile_sizes is None:
        return False
    return num_input_tokens in compile_sizes