"tests/vscode:/vscode.git/clone" did not exist on "1986de137502d0d767cb4c1d3cad23dedbd22397"
cpu_model_runner.py 15.2 KB
Newer Older
1
from dataclasses import dataclass
2
from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Type, Union
3
4

import torch
5
from torch import nn
6
7

from vllm.attention import AttentionMetadata, get_attn_backend
8
from vllm.config import (CacheConfig, DeviceConfig, LoadConfig, LoRAConfig,
9
10
                         ModelConfig, ParallelConfig, PromptAdapterConfig,
                         SchedulerConfig)
11
12
from vllm.logger import init_logger
from vllm.model_executor import SamplingMetadata
13
from vllm.model_executor.layers.sampler import SamplerOutput
14
from vllm.model_executor.model_loader import get_model
15
from vllm.multimodal import (MULTIMODAL_REGISTRY, BatchedTensorInputs,
16
                             MultiModalInputs)
17
from vllm.sequence import IntermediateTensors, SequenceGroupMetadata
18
from vllm.utils import STR_NOT_IMPL_ENC_DEC_ERR_STRS, make_tensor_with_pad
19
20
21
22
23
24
25
26
27
from vllm.worker.model_runner_base import (
    ModelRunnerBase, ModelRunnerInputBase,
    _add_attn_metadata_broadcastable_dict,
    _add_sampling_metadata_broadcastable_dict,
    _init_attn_metadata_from_tensor_dict,
    _init_sampling_metadata_from_tensor_dict)

if TYPE_CHECKING:
    from vllm.attention.backends.abstract import AttentionBackend
28
29
30
31
32
33

logger = init_logger(__name__)

_PAD_SLOT_ID = -1


34
35
36
37
38
39
40
41
42
@dataclass(frozen=True)
class CPUModelInput(ModelRunnerInputBase):
    """
    Used by the CPUModelRunner.
    """
    input_tokens: Optional[torch.Tensor] = None
    input_positions: Optional[torch.Tensor] = None
    attn_metadata: Optional["AttentionMetadata"] = None
    sampling_metadata: Optional["SamplingMetadata"] = None
43
    multi_modal_kwargs: Optional[BatchedTensorInputs] = None
44
    virtual_engine: Optional[int] = None
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

    def as_broadcastable_tensor_dict(
            self) -> Dict[str, Union[int, torch.Tensor]]:
        tensor_dict = {
            "input_tokens": self.input_tokens,
            "input_positions": self.input_positions,
            "multi_modal_kwargs": self.multi_modal_kwargs,
        }
        _add_attn_metadata_broadcastable_dict(tensor_dict, self.attn_metadata)
        _add_sampling_metadata_broadcastable_dict(tensor_dict,
                                                  self.sampling_metadata)
        return tensor_dict

    @classmethod
    def from_broadcasted_tensor_dict(
            cls: Type["CPUModelInput"],
            tensor_dict: Dict[str, Any],
            attn_backend: Optional["AttentionBackend"] = None
    ) -> "CPUModelInput":
        tensor_dict = _init_sampling_metadata_from_tensor_dict(tensor_dict)
        if attn_backend is not None:
            tensor_dict = _init_attn_metadata_from_tensor_dict(
                attn_backend, tensor_dict)
        return cls(**tensor_dict)


class CPUModelRunner(ModelRunnerBase[CPUModelInput]):
72
73
74
75
76
77
78

    def __init__(
        self,
        model_config: ModelConfig,
        parallel_config: ParallelConfig,
        scheduler_config: SchedulerConfig,
        device_config: DeviceConfig,
79
        cache_config: CacheConfig,
80
        load_config: LoadConfig,
81
82
        lora_config: Optional[LoRAConfig],
        kv_cache_dtype: Optional[str] = "auto",
83
        prompt_adapter_config: Optional[PromptAdapterConfig] = None,
84
85
86
87
88
89
90
        is_driver_worker: bool = False,
        *args,
        **kwargs,
    ):
        self.model_config = model_config
        self.parallel_config = parallel_config
        self.scheduler_config = scheduler_config
91
92
        # Currently, CPU worker doesn't support chunked prefill.
        assert self.scheduler_config.chunked_prefill_enabled is False
93
94
        self.device_config = device_config
        self.cache_config = cache_config
95
        self.lora_config = lora_config
96
        self.prompt_adapter_config = prompt_adapter_config
97
        self.load_config = load_config
98
99
100
101
102
        self.is_driver_worker = is_driver_worker

        self.device = self.device_config.device

        self.kv_cache_dtype = kv_cache_dtype
103
104
        self.sliding_window = model_config.get_sliding_window()
        self.block_size = cache_config.block_size
105
106
107
108
109
110
111
112
113
        self.attn_backend = get_attn_backend(
            self.model_config.get_num_attention_heads(self.parallel_config),
            self.model_config.get_head_size(),
            self.model_config.get_num_kv_heads(self.parallel_config),
            self.model_config.get_sliding_window(),
            self.model_config.dtype,
            self.kv_cache_dtype,
            self.block_size,
        )
114

115
        # Multi-modal data support
116
117
        self.mm_registry = MULTIMODAL_REGISTRY
        self.multi_modal_input_mapper = self.mm_registry \
118
            .create_input_mapper(self.model_config)
119
        self.mm_registry.init_mm_limits_per_prompt(self.model_config)
120

121
122
123
        # Lazy initialization.
        self.model: nn.Module  # Set after init_Model

124
125
126
127
        if self.model_config.is_encoder_decoder_model:
            raise NotImplementedError(
                STR_NOT_IMPL_ENC_DEC_ERR_STRS['STR_NOT_IMPL_ENC_DEC_CPU'])

128
    def load_model(self) -> None:
129
130
131
132
133
134
135
        self.model = get_model(model_config=self.model_config,
                               load_config=self.load_config,
                               device_config=self.device_config,
                               lora_config=self.lora_config,
                               parallel_config=self.parallel_config,
                               scheduler_config=self.scheduler_config,
                               cache_config=self.cache_config)
136
137
138
139

    def _prepare_prompt(
        self,
        seq_group_metadata_list: List[SequenceGroupMetadata],
140
    ) -> Tuple[torch.Tensor, torch.Tensor, AttentionMetadata, List[int],
141
               BatchedTensorInputs]:
142
143
144
145
        assert len(seq_group_metadata_list) > 0
        input_tokens: List[int] = []
        input_positions: List[int] = []
        slot_mapping: List[int] = []
146
        seq_lens: List[int] = []
147
        multi_modal_inputs_list: List[MultiModalInputs] = []
148
149
150
151
152
153
154
155
156
157

        for seq_group_metadata in seq_group_metadata_list:
            assert seq_group_metadata.is_prompt
            seq_ids = list(seq_group_metadata.seq_data.keys())
            assert len(seq_ids) == 1
            seq_id = seq_ids[0]

            seq_data = seq_group_metadata.seq_data[seq_id]
            prompt_tokens = seq_data.get_token_ids()
            computed_len = seq_data.get_num_computed_tokens()
158
            seq_len = len(prompt_tokens)
159

160
            seq_lens.append(seq_len)  # Prompt token num
161
162
163
164
165
            input_tokens.extend(prompt_tokens)  # Token ids

            # Token position ids
            # NOTE(woosuk): Here we assume that the first token in the prompt
            # is always the first token in the sequence.
166
            input_positions.extend(list(range(computed_len, seq_len)))
167

168
            mm_data = seq_group_metadata.multi_modal_data
169
            if mm_data:
170
                mm_kwargs = self.multi_modal_input_mapper(mm_data)
171
                multi_modal_inputs_list.append(mm_kwargs)
172

173
174
175
            # Compute the slot mapping.
            block_table = seq_group_metadata.block_tables[seq_id]
            # Mask the [0, start_idx) tokens of the prompt with _PAD_SLOT_ID,
176
            # where start_idx is max(0, seq_len - sliding_window).
177
178
179
180
181
            # For example, if the prompt len is 10, sliding window is 8, and
            # block size is 4, the first two tokens are masked and the slot
            # mapping will be [-1, -1, 2, 3, 4, 5, 6, 7, 0, 1].
            start_idx = 0
            if self.sliding_window is not None:
182
                start_idx = max(0, seq_len - self.sliding_window)
183

184
            for i in range(computed_len, seq_len):
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
                if i < start_idx:
                    slot_mapping.append(_PAD_SLOT_ID)
                    continue

                block_number = block_table[i //
                                           self.block_size]  # type: ignore
                block_offset = i % self.block_size  # type: ignore
                slot = block_number * self.block_size + block_offset
                slot_mapping.append(slot)

        num_prompt_tokens = len(input_tokens)

        input_tokens = torch.tensor(input_tokens,
                                    dtype=torch.long,
                                    device=self.device)  # type: ignore
        input_positions = torch.tensor(input_positions,
                                       dtype=torch.long,
                                       device=self.device)  # type: ignore
        slot_mapping = torch.tensor(slot_mapping,
                                    dtype=torch.long,
                                    device=self.device)  # type: ignore

        attn_metadata = self.attn_backend.make_metadata(
            is_prompt=True,
209
            seq_lens=seq_lens,
210
211
            seq_lens_tensor=torch.tensor([]),
            max_decode_seq_len=0,
212
            num_prefills=len(seq_lens),
213
214
215
216
217
            num_prefill_tokens=num_prompt_tokens,
            num_decode_tokens=0,
            block_tables=torch.tensor([]),
            slot_mapping=slot_mapping,
        )
218

219
        multi_modal_kwargs = MultiModalInputs.batch(multi_modal_inputs_list)
220

221
        return (input_tokens, input_positions, attn_metadata, seq_lens,
222
                multi_modal_kwargs)
223
224
225
226
227
228
229
230
231

    def _prepare_decode(
        self,
        seq_group_metadata_list: List[SequenceGroupMetadata],
    ) -> Tuple[torch.Tensor, torch.Tensor, AttentionMetadata]:
        assert len(seq_group_metadata_list) > 0
        input_tokens: List[int] = []
        input_positions: List[int] = []
        slot_mapping: List[int] = []
232
        seq_lens: List[int] = []
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
        block_tables: List[List[int]] = []

        for seq_group_metadata in seq_group_metadata_list:
            assert not seq_group_metadata.is_prompt
            assert seq_group_metadata.token_chunk_size == 1

            seq_ids = list(seq_group_metadata.seq_data.keys())

            for seq_id in seq_ids:
                seq_data = seq_group_metadata.seq_data[seq_id]
                generation_token = seq_data.get_last_token_id()
                input_tokens.append(generation_token)

                seq_len = seq_data.get_len()
                position = seq_len - 1
                input_positions.append(position)

250
                seq_len = seq_len if self.sliding_window is None else min(
251
                    seq_len, self.sliding_window)
252
                seq_lens.append(seq_len)
253
254
255
256
257
258
259
260
261
262
263
264
265

                block_table = seq_group_metadata.block_tables[seq_id]
                block_number = block_table[position // self.block_size]
                block_offset = position % self.block_size
                slot = block_number * self.block_size + block_offset
                slot_mapping.append(slot)

                if self.sliding_window is not None:
                    sliding_window_blocks = (self.sliding_window //
                                             self.block_size)
                    block_table = block_table[-sliding_window_blocks:]
                block_tables.append(block_table)

266
        max_decode_seq_len = max(seq_lens)
267
268
269
270
271
272
273
274
275
276

        input_tokens = torch.tensor(input_tokens,
                                    dtype=torch.long,
                                    device=self.device)
        input_positions = torch.tensor(input_positions,
                                       dtype=torch.long,
                                       device=self.device)
        slot_mapping = torch.tensor(slot_mapping,
                                    dtype=torch.long,
                                    device=self.device)
277
278
279
        seq_lens_tensor = torch.tensor(seq_lens,
                                       dtype=torch.int,
                                       device=self.device)
280
281
282
283
284
285
286
287
288
289
290

        block_tables = make_tensor_with_pad(
            block_tables,
            pad=0,
            dtype=torch.int,
            device=self.device,
        )

        attn_metadata = self.attn_backend.make_metadata(
            is_prompt=False,
            slot_mapping=slot_mapping,
291
292
            seq_lens=seq_lens,
            seq_lens_tensor=seq_lens_tensor,
293
            max_decode_seq_len=max_decode_seq_len,
294
295
296
297
298
299
300
301
302
303
304
            num_prefill_tokens=0,
            num_decode_tokens=len(input_tokens),
            num_prefills=0,
            block_tables=block_tables,
        )
        return (
            input_tokens,
            input_positions,
            attn_metadata,
        )

305
306
307
308
309
310
311
312
313
314
    def make_model_input_from_broadcasted_tensor_dict(
        self,
        tensor_dict: Dict[str, Any],
    ) -> CPUModelInput:
        return CPUModelInput.from_broadcasted_tensor_dict(
            tensor_dict,
            attn_backend=self.attn_backend,
        )

    def prepare_model_input(
Mor Zusman's avatar
Mor Zusman committed
315
316
317
318
            self,
            seq_group_metadata_list: List[SequenceGroupMetadata],
            virtual_engine: int = 0,
            finished_requests_ids: Optional[List[str]] = None
319
    ) -> CPUModelInput:
320
        multi_modal_kwargs = None
321
322
323
324
325
326
327
328
        # NOTE: We assume that all sequences in the group are all prompts or
        # all decodes.
        is_prompt = seq_group_metadata_list[0].is_prompt
        # Prepare input tensors.
        if is_prompt:
            (input_tokens, input_positions, attn_metadata, seq_lens,
             multi_modal_kwargs
             ) = self._prepare_prompt(seq_group_metadata_list)
329
        else:
330
331
332
333
334
335
336
337
338
339
340
            (input_tokens, input_positions,
             attn_metadata) = self._prepare_decode(seq_group_metadata_list)
            seq_lens = []
        sampling_metadata = SamplingMetadata.prepare(
            seq_group_metadata_list,
            seq_lens,
            # query_lens is not needed if chunked prefill is not
            # supported. Since CPU worker doesn't support chunked prefill
            # just use seq_lens instead.
            seq_lens,
            self.device,
341
342
            pin_memory=False,
            generators=self.get_generators(finished_requests_ids))
343
344
345
346
347
        return CPUModelInput(
            input_tokens=input_tokens,
            input_positions=input_positions,
            attn_metadata=attn_metadata,
            sampling_metadata=sampling_metadata,
348
            multi_modal_kwargs=multi_modal_kwargs,
349
        )
350

351
    @torch.no_grad()
352
353
    def execute_model(
        self,
354
        model_input: CPUModelInput,
355
        kv_caches: List[torch.Tensor],
356
        intermediate_tensors: Optional[IntermediateTensors] = None,
357
358
359
360
361
362
        num_steps: int = 1,
    ) -> Optional[List[SamplerOutput]]:
        if num_steps > 1:
            raise ValueError(
                "CPU worker does not support multi-step execution.")

363
364
        model_executable = self.model
        execute_model_kwargs = {
365
366
367
368
369
370
371
372
373
374
            "input_ids":
            model_input.input_tokens,
            "positions":
            model_input.input_positions,
            "kv_caches":
            kv_caches,
            "attn_metadata":
            model_input.attn_metadata,
            **MultiModalInputs.as_kwargs(model_input.multi_modal_kwargs or {},
                                         device=self.device),
375
376
377
378
379
        }

        hidden_states = model_executable(**execute_model_kwargs)

        # Compute the logits.
380
381
        logits = self.model.compute_logits(hidden_states,
                                           model_input.sampling_metadata)
382
383

        # Only perform sampling in the driver worker.
384
        if not self.is_driver_worker:
385
            return []
386
387
388
389

        # Sample the next token.
        output = self.model.sample(
            logits=logits,
390
            sampling_metadata=model_input.sampling_metadata,
391
        )
392
        return [output]