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

4
import dataclasses
5
import os
zhuwenwen's avatar
zhuwenwen committed
6
import numa
7
import time
8
from abc import abstractmethod
9
from typing import Any, Dict, List, Optional, Set, Tuple, Type, Union
10

11
import cloudpickle
12
import torch
13
import torch.nn as nn
14

15
16
from vllm.config import (ObservabilityConfig, VllmConfig,
                         set_current_vllm_config)
17
from vllm.distributed import broadcast_tensor_dict, get_pp_group, get_tp_group
18
from vllm.logger import init_logger
19
from vllm.lora.request import LoRARequest
20
21
from vllm.model_executor.layers.sampler import SamplerOutput
from vllm.sequence import ExecuteModelRequest, IntermediateTensors
22
from vllm.utils import (enable_trace_function_call_for_thread,
23
                        resolve_obj_by_qualname, run_method,
24
25
                        update_environment_variables,
                        warn_for_unimplemented_methods)
zhuwenwen's avatar
zhuwenwen committed
26
from vllm.worker.cache_engine import CacheEngine
27
28
29
from vllm.worker.model_runner_base import (BroadcastableModelInput,
                                           ModelRunnerBase,
                                           ModelRunnerInputBase)
30
31

logger = init_logger(__name__)
32
33


zhuwenwen's avatar
zhuwenwen committed
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# 设置当前进程绑定到 NUMA 节点
def bind_to_numa(local_rank):
    env_str = f"VLLM_RANK{local_rank}_NUMA"
    node_count = numa.get_max_node() + 1
    numa_node = int(os.getenv(env_str, -1))

    # 未配置环境变量或配置错误则不做绑定,TODO:根据topo自动绑定方案
    if numa_node < 0:
        logger.warning("%s is unset or set incorrectly, vllm will not bind to numa! %s = %d", env_str, env_str, numa_node)
        return

    if numa_node > numa.get_max_node():
        raise ValueError(f"NUMA node {numa_node} is not available.")

    numa.bind([numa_node])   
    
    
51
52
@warn_for_unimplemented_methods
class WorkerBase:
53
    """Worker interface that allows vLLM to cleanly separate implementations for
54
55
    different hardware. Also abstracts control plane communication, e.g., to
    communicate request metadata to other workers.
56
57
    """

58
    model_input: Optional[ModelRunnerInputBase] = None
59
    tree_decoding = (os.environ.get('VLLM_TREE_DECODING') == '1')
60

61
62
63
64
65
66
67
68
69
70
71
72
73
74
    def __init__(
        self,
        vllm_config: VllmConfig,
    ) -> None:
        self.vllm_config = vllm_config
        self.model_config = vllm_config.model_config
        self.cache_config = vllm_config.cache_config
        self.lora_config = vllm_config.lora_config
        self.load_config = vllm_config.load_config
        self.parallel_config = vllm_config.parallel_config
        self.scheduler_config = vllm_config.scheduler_config
        self.device_config = vllm_config.device_config
        self.speculative_config = vllm_config.speculative_config
        self.observability_config = vllm_config.observability_config
75
        self.kv_transfer_config = vllm_config.kv_transfer_config
76
        self.compilation_config = vllm_config.compilation_config
77
78
        from vllm.platforms import current_platform
        self.current_platform = current_platform
79

80
81
82
83
84
85
86
87
88
89
90
91
    def init_device(self) -> None:
        """Initialize device state, such as loading the model or other on-device
        memory allocations.
        """
        raise NotImplementedError

    def initialize_cache(self, num_gpu_blocks: int,
                         num_cpu_blocks: int) -> None:
        """Initialize the KV cache with the given size in blocks.
        """
        raise NotImplementedError

92
93
94
95
96
97
98
99
100
101
102
103
104
    def get_model(self) -> nn.Module:
        raise NotImplementedError

    def load_model(self) -> None:
        """Load model onto target device."""
        raise NotImplementedError

    def execute_model(
        self,
        execute_model_req: Optional[ExecuteModelRequest] = None
    ) -> Optional[List[SamplerOutput]]:
        raise NotImplementedError

105
106
107
108
109
110
    def start_worker_execution_loop(self) -> None:
        """Execute model loop in parallel worker.

        You can stop the loop by executing a driver worker with an empty output.
        See `stop_remote_worker_execution_loop` for more details.
        """
111
112
113
114
115
        with self.current_platform.inference_mode():
            while True:
                output = self.execute_model(execute_model_req=None)
                if output is None:
                    return None
116

117
118
119
    def determine_num_available_blocks(self) -> Tuple[int, int]:
        """Determine the number of available blocks for the GPU KV cache and
        swappable CPU KV cache.
120

121
122
123
124
125
126
127
128
        The implementation may run profiling or other heuristics to determine
        the size of caches.

        Returns a Tuple[num_gpu_blocks, num_cpu_blocks], where num_gpu_blocks
        are blocks that are "active" on the device and can be appended to.
        num_cpu_blocks refers to "swapped" blocks in CPU memory and cannot be
        appended to.
        """
129
130
        raise NotImplementedError

131
    def get_cache_block_size_bytes(self) -> int:
132
133
134
135
136
137
138
139
140
141
142
        """Return the size of a single cache block, in bytes. Used in
        speculative decoding.
        """
        raise NotImplementedError

    def add_lora(self, lora_request: LoRARequest) -> bool:
        raise NotImplementedError

    def remove_lora(self, lora_id: int) -> bool:
        raise NotImplementedError

143
144
145
    def pin_lora(self, lora_id: int) -> bool:
        raise NotImplementedError

146
    def list_loras(self) -> Set[int]:
147
        raise NotImplementedError
148
    
zhuwenwen's avatar
zhuwenwen committed
149
150
151
152
    # @property
    # @abstractmethod
    # def cache_engines(self) -> Optional[List[CacheEngine]]:
    #     raise NotImplementedError
153

154
155
156
157
158
    @property
    def vocab_size(self) -> int:
        """Get vocabulary size from model configuration."""
        return self.model_config.get_vocab_size()

159

160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
class DelegateWorkerBase(WorkerBase):
    """
    A class that delegates all methods to another WorkerBase instance. This is
    useful for creating a WorkerBase that wraps another WorkerBase instance,
    e.g. speculative decoding.
    """
    worker: WorkerBase

    def __init__(
        self,
        *args,
        **kwargs,
    ) -> None:
        vllm_config: VllmConfig = kwargs.get("vllm_config")
        cls = resolve_obj_by_qualname(vllm_config.parallel_config.worker_cls)
        self.worker = cls(*args, **kwargs)

    def init_device(self) -> None:
        self.worker.init_device()

    def determine_num_available_blocks(self) -> Tuple[int, int]:
        return self.worker.determine_num_available_blocks()

    def initialize_cache(self, num_gpu_blocks: int,
                         num_cpu_blocks: int) -> None:
        self.worker.initialize_cache(num_gpu_blocks, num_cpu_blocks)

187
188
189
190
    def load_model(self) -> None:
        """Load model onto target device."""
        self.worker.load_model()

191
192
193
    def get_model(self) -> nn.Module:
        return self.worker.get_model()

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
    def execute_model(
        self,
        execute_model_req: Optional[ExecuteModelRequest] = None
    ) -> Optional[List[SamplerOutput]]:
        return self.worker.execute_model(execute_model_req)

    def get_cache_block_size_bytes(self) -> int:
        return self.worker.get_cache_block_size_bytes()

    def add_lora(self, lora_request: LoRARequest) -> bool:
        return self.worker.add_lora(lora_request)

    def remove_lora(self, lora_id: int) -> bool:
        return self.worker.remove_lora(lora_id)

    def pin_lora(self, lora_id: int) -> bool:
        return self.worker.pin_lora(lora_id)

    def list_loras(self) -> Set[int]:
        return self.worker.list_loras()

    def __getattr__(self, attr):
        return getattr(self.worker, attr)


219
class LoRANotSupportedWorkerBase(WorkerBase):
220
221
222
223
224
225
226
227
228
229
    """Partial implementation of WorkerBase that raises exceptions when LoRA
    methods are invoked.
    """

    def add_lora(self, lora_request: LoRARequest) -> bool:
        raise ValueError(f"{type(self)} does not support LoRA")

    def remove_lora(self, lora_id: int) -> bool:
        raise ValueError(f"{type(self)} does not support LoRA")

230
    def pin_lora(self, lora_id: int) -> bool:
231
        raise ValueError(f"{type(self)} does not support LoRA")
232

233
    def list_loras(self) -> Set[int]:
234
        raise ValueError(f"{type(self)} does not support LoRA")
235
236
237
238

    @property
    def cache_engines(self) -> Optional[List[CacheEngine]]:
        return None
239
240


241
242
243
244
245
246
247
248
249
250
@dataclasses.dataclass(frozen=True)
class WorkerInput:
    """Local inputs to each worker. May contain device-specific data. These
    fields should be broadcastable to other workers.
    """

    num_seq_groups: Optional[int] = None
    blocks_to_swap_in: Optional[torch.Tensor] = None
    blocks_to_swap_out: Optional[torch.Tensor] = None
    blocks_to_copy: Optional[torch.Tensor] = None
251
    virtual_engine: int = 0
252
    num_steps: int = 1
253

254
255
256
    # Optional slot mapping of kvcache that pending to be moved generated from draft model.
    kvcache_slot_to_be_moved: Optional[torch.Tensor] = None

257
258
259
260
261
262
263
264
265
266
267
268
269
270
    @classmethod
    def from_broadcasted_tensor_dict(
        cls: Type["WorkerInput"],
        tensor_dict: Dict[str, Any],
    ) -> "WorkerInput":
        """
        Pop fields from the given tensor_dict and populate a new instance of
        WorkerInput.
        """
        return cls(
            num_seq_groups=tensor_dict.pop("num_seq_groups"),
            blocks_to_swap_in=tensor_dict.pop("blocks_to_swap_in"),
            blocks_to_swap_out=tensor_dict.pop("blocks_to_swap_out"),
            blocks_to_copy=tensor_dict.pop("blocks_to_copy"),
271
            virtual_engine=tensor_dict["virtual_engine"],
272
            num_steps=tensor_dict.pop("num_steps"),
273
            kvcache_slot_to_be_moved=tensor_dict.pop("kvcache_slot_to_be_moved"),
274
275
276
277
278
279
280
281
282
283
284
285
        )

    def as_broadcastable_tensor_dict(
            self) -> Dict[str, Union[int, torch.Tensor]]:
        """
        Extract broadcastable fields.
        """
        tensor_dict = {
            "num_seq_groups": self.num_seq_groups,
            "blocks_to_swap_in": self.blocks_to_swap_in,
            "blocks_to_swap_out": self.blocks_to_swap_out,
            "blocks_to_copy": self.blocks_to_copy,
286
            "virtual_engine": self.virtual_engine,
287
            "num_steps": self.num_steps,
288
            "kvcache_slot_to_be_moved": self.kvcache_slot_to_be_moved
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
        }

        return tensor_dict


class LocalOrDistributedWorkerBase(WorkerBase):
    """
    Partial implementation of WorkerBase that has a default `execute_model`
    definition to perform metadata transfer between workers when in distributed
    mode. Subclasses of this interface should use model runners that inherit
    from ModelRunnerBase, and should only need to implement worker-local logic.
    If custom control plane logic is needed to transfer metadata, or if the
    model runner cannot inherit from ModelRunnerBase, use WorkerBase instead.
    """
    is_driver_worker: bool
    model_runner: ModelRunnerBase
305
    observability_config: Optional[ObservabilityConfig] = None
306
307
308
309
310
311
312
313
314
315
316
317
318
319

    @property
    @abstractmethod
    def do_metadata_broadcast(self) -> bool:
        """
        Used by the default `execute_model` to check whether broadcast is
        needed to transfer request inputs from the driver worker to other
        workers in the TP group. If WorkerBase subclass only supports
        single-worker execution, then this method should return False.
        """
        raise NotImplementedError

    @property
    @abstractmethod
320
    def kv_cache(self) -> Optional[List[List[torch.Tensor]]]:
321
        """
322
323
324
325
326
        Gets the list of kv caches to pass to the worker's model runner. Each
        element in the list is a kv cache corresponding to a particular virtual
        engine (PP stream). Used by the default `execute_model`. If the worker's
        model runner does not follow the ModelRunnerBase interface, then inherit
        from WorkerBase instead.
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
        """
        raise NotImplementedError

    @abstractmethod
    def prepare_worker_input(
            self, execute_model_req: ExecuteModelRequest) -> WorkerInput:
        """
        Prepare the inputs to WorkerBase.execute_worker from an execution
        request. This method may move data to the worker's local device. It is
        not allowed to communicate with other workers or devices.
        """
        raise NotImplementedError

    @abstractmethod
    def execute_worker(self, worker_input: WorkerInput) -> None:
        """
        Process an execution request.
        """
        raise NotImplementedError

347
    def _get_worker_input_from_broadcast(
348
349
350
        self
    ) -> Optional[Tuple[BroadcastableModelInput, WorkerInput, Dict[
            str, torch.Tensor]]]:
351
352
353
354
355
356
357
358
359
360
361
362
        """ Get the worker input from the broadcasted tensor dict. """
        assert self.do_metadata_broadcast
        assert not self.is_driver_worker
        broadcast_data = broadcast_tensor_dict(src=0)
        if not broadcast_data:
            return None

        worker_input = WorkerInput.from_broadcasted_tensor_dict(broadcast_data)
        model_input = (
            self.model_runner.make_model_input_from_broadcasted_tensor_dict(
                broadcast_data))

363
364
365
        kwargs = extract_previous_hidden_states(broadcast_data)

        return model_input, worker_input, kwargs
366
367
368

    def _get_driver_input_and_broadcast(
        self, execute_model_req: ExecuteModelRequest
369
    ) -> Tuple[BroadcastableModelInput, WorkerInput, Dict[str, torch.Tensor]]:
370
371
372
373
374
        """ Get the driver input and broadcast it to other workers.  """
        assert self.is_driver_worker

        worker_input: WorkerInput = self.prepare_worker_input(
            execute_model_req=execute_model_req)
375

376
377
378
379
380
381
        model_input: ModelRunnerInputBase = (
            self.model_runner.prepare_model_input(
                execute_model_req.seq_group_metadata_list,
                execute_model_req.virtual_engine,
                execute_model_req.finished_requests_ids))

382
383
384
385
386
387
388
389
390
391
392
        if self.tree_decoding and execute_model_req.tree_position_ids is not None and \
            execute_model_req.tree_attn_masks is not None:
            if hasattr(model_input, "input_positions") and \
                hasattr(model_input, "attn_metadata") and \
                    hasattr(model_input.attn_metadata, "tree_attention_masks_tensor"):
                attn_metadata = model_input.attn_metadata
                attn_metadata.tree_attention_masks_tensor = execute_model_req.tree_attn_masks.contiguous()
                model_input = dataclasses.replace(model_input,
                                    input_positions=execute_model_req.tree_position_ids.contiguous(),
                                    attn_metadata=attn_metadata)

393
394
        kwargs = extract_previous_hidden_states(execute_model_req)

395
396
397
        if self.do_metadata_broadcast:
            broadcast_data = worker_input.as_broadcastable_tensor_dict()
            broadcast_data.update(model_input.as_broadcastable_tensor_dict())
398
            broadcast_data.update(kwargs)
399
400
            broadcast_tensor_dict(broadcast_data, src=0)

401
        if execute_model_req.async_callback:
402
403
            model_input = dataclasses.replace(  # type: ignore
                model_input,
404
                async_callback=execute_model_req.async_callback)
405

406
        return model_input, worker_input, kwargs
407
408

    def prepare_input(
409
410
        self,
        execute_model_req: Optional[ExecuteModelRequest] = None
411
412
    ) -> Optional[Tuple[BroadcastableModelInput, WorkerInput, Dict[
            str, torch.Tensor]]]:
413
414
415
        """
        Prepare the inputs to ModelRunner and workers.
        """
416
417
418
419
420
421
422
423
424
425
        if self.is_driver_worker:
            if execute_model_req is None:
                if self.do_metadata_broadcast:
                    # This signals that there's no more requests to process for
                    # now. All workers are running infinite loop with
                    # broadcast_tensor_dict, and it stops the loop when the
                    # driver broadcasts an empty input. Send an empty input to
                    # notify all other workers to stop their execution loop.
                    broadcast_tensor_dict({}, src=0)
                return None
426
            return self._get_driver_input_and_broadcast(execute_model_req)
427
        else:
428
429
            return self._get_worker_input_from_broadcast()

430
431
432
    def get_model(self) -> nn.Module:
        return self.model_runner.get_model()

433
434
    def execute_model(
        self,
435
        execute_model_req: Optional[ExecuteModelRequest] = None,
436
437
438
439
440
441
442
443
    ) -> Optional[List[SamplerOutput]]:
        """Executes at least one model step on the given sequences, unless no
        sequences are provided."""
        start_time = time.perf_counter()

        inputs = self.prepare_input(execute_model_req)
        if inputs is None:
            return None
444

445
        model_input, worker_input, kwargs = inputs
446
        num_steps = worker_input.num_steps
447

448
449
        self.model_input = model_input

450
451
452
453
454
455
        self.execute_worker(worker_input)

        # If there is no input, we don't need to execute the model.
        if worker_input.num_seq_groups == 0:
            return []

456
        intermediate_tensors = None
457
        orig_model_execute_time = 0.0
458
459
        if not get_pp_group().is_first_rank:
            intermediate_tensors = IntermediateTensors(
460
461
                get_pp_group().recv_tensor_dict(
                    all_gather_group=get_tp_group()))
462
463
464
465
            if (self.observability_config is not None
                    and self.observability_config.collect_model_execute_time):
                orig_model_execute_time = intermediate_tensors.tensors.get(
                    "model_execute_time", torch.tensor(0)).item()
466
467

        output = self.model_runner.execute_model(
468
469
470
471
472
473
474
475
            model_input=model_input,
            kv_caches=self.kv_cache[worker_input.virtual_engine]
            if self.kv_cache is not None else None,
            intermediate_tensors=intermediate_tensors,
            num_steps=num_steps,
            **kwargs,
        )

476
        model_execute_time = time.perf_counter() - start_time
477
        if not get_pp_group().is_last_rank:
478
            # output is IntermediateTensors
479
            assert isinstance(output, IntermediateTensors)
480
481
482
483
            if (self.observability_config is not None
                    and self.observability_config.collect_model_execute_time):
                output.tensors["model_execute_time"] = torch.tensor(
                    model_execute_time + orig_model_execute_time)
484
485
            get_pp_group().send_tensor_dict(output.tensors,
                                            all_gather_group=get_tp_group())
486
            return [None]
487
488
489
490
491
492
        if (self.observability_config is not None
                and self.observability_config.collect_model_execute_time
                and output is not None):
            for o in output:
                o.model_execute_time = (orig_model_execute_time +
                                        model_execute_time)
493

494
        # output is List[SamplerOutput]
495
        return output
496

497
    def _execute_model_spmd(
498
499
500
        self,
        execute_model_req: ExecuteModelRequest,
        intermediate_tensors: Optional[IntermediateTensors] = None
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
    ) -> Optional[List[SamplerOutput]]:
        """
        Execute model in Single Program Multiple Data (SPMD) fashion.
        All workers take the same request, prepare the input and
        execute the model.
        """
        assert execute_model_req is not None, (
            "_execute_model_spmd() requires each worker to take in an "
            "ExecuteModelRequest")
        worker_input: WorkerInput = self.prepare_worker_input(
            execute_model_req=execute_model_req)
        model_input: ModelRunnerInputBase = (
            self.model_runner.prepare_model_input(
                execute_model_req.seq_group_metadata_list))

        self.execute_worker(worker_input)

        # If there is no input, we don't need to execute the model.
        if worker_input.num_seq_groups == 0:
            return []

522
523
        kwargs = extract_previous_hidden_states(execute_model_req)

524
        return self.model_runner.execute_model(
525
526
527
528
529
530
            model_input=model_input,
            kv_caches=self.kv_cache[worker_input.virtual_engine]
            if self.kv_cache is not None else None,
            intermediate_tensors=intermediate_tensors,
            **kwargs,
        )
531

532

533
534
class WorkerWrapperBase:
    """
535
536
    This class represents one process in an executor/engine. It is responsible
    for lazily initializing the worker and handling the worker's lifecycle.
537
538
539
540
541
    We first instantiate the WorkerWrapper, which remembers the worker module
    and class name. Then, when we call `update_environment_variables`, and the
    real initialization happens in `init_worker`.
    """

542
543
    def __init__(
        self,
544
        vllm_config: VllmConfig,
545
        rpc_rank: int = 0,
546
    ) -> None:
547
548
549
550
551
552
553
554
555
556
557
        """
        Initialize the worker wrapper with the given vllm_config and rpc_rank.
        Note: rpc_rank is the rank of the worker in the executor. In most cases,
        it is also the rank of the worker in the distributed group. However,
        when multiple executors work together, they can be different.
        e.g. in the case of SPMD-style offline inference with TP=2,
        users can launch 2 engines/executors, each with only 1 worker.
        All workers have rpc_rank=0, but they have different ranks in the TP
        group.
        """
        self.rpc_rank = rpc_rank
558
        self.worker: Optional[WorkerBase] = None
559
        self.vllm_config: Optional[VllmConfig] = None
560
561
562
563
        # do not store this `vllm_config`, `init_worker` will set the final
        # one. TODO: investigate if we can remove this field in
        # `WorkerWrapperBase`, `init_cached_hf_modules` should be
        # unnecessary now.
564
565
566
567
568
569
570
571
572
573
        if vllm_config.model_config is not None:
            # it can be None in tests
            trust_remote_code = vllm_config.model_config.trust_remote_code
            if trust_remote_code:
                # note: lazy import to avoid importing torch before initializing
                from vllm.utils import init_cached_hf_modules
                init_cached_hf_modules()

    def adjust_rank(self, rank_mapping: Dict[int, int]) -> None:
        """
574
        Adjust the rpc_rank based on the given mapping.
575
        It is only used during the initialization of the executor,
576
        to adjust the rpc_rank of workers after we create all workers.
577
        """
578
579
        if self.rpc_rank in rank_mapping:
            self.rpc_rank = rank_mapping[self.rpc_rank]
580

581
582
    def update_environment_variables(self, envs_list: List[Dict[str,
                                                                str]]) -> None:
583
        envs = envs_list[self.rpc_rank]
584
585
586
587
588
589
590
        key = 'CUDA_VISIBLE_DEVICES'
        if key in envs and key in os.environ:
            # overwriting CUDA_VISIBLE_DEVICES is desired behavior
            # suppress the warning in `update_environment_variables`
            del os.environ[key]
        update_environment_variables(envs)

591
    def init_worker(self, all_kwargs: List[Dict[str, Any]]) -> None:
592
        """
593
        Here we inject some common logic before initializing the worker.
594
595
        Arguments are passed to the worker class constructor.
        """
596
        kwargs = all_kwargs[self.rpc_rank]
597
598
599
        self.vllm_config = kwargs.get("vllm_config", None)
        assert self.vllm_config is not None, (
            "vllm_config is required to initialize the worker")
600
        enable_trace_function_call_for_thread(self.vllm_config)
601

602
603
604
        from vllm.plugins import load_general_plugins
        load_general_plugins()

605
606
607
608
        if isinstance(self.vllm_config.parallel_config.worker_cls, str):
            worker_class = resolve_obj_by_qualname(
                self.vllm_config.parallel_config.worker_cls)
        else:
609
610
611
612
613
614
            logger.warning(
                "passing worker_cls as a class object is strongly deprecated,"
                " as the serialization of class objects can be tricky and"
                " error-prone. To be safe, please keep the class in a separate"
                " module and pass the qualified name of the class as a string."
            )
615
616
617
618
            assert isinstance(self.vllm_config.parallel_config.worker_cls,
                              bytes)
            worker_class = cloudpickle.loads(
                self.vllm_config.parallel_config.worker_cls)
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
        if self.vllm_config.parallel_config.worker_extension_cls:
            worker_extension_cls = resolve_obj_by_qualname(
                self.vllm_config.parallel_config.worker_extension_cls)
            extended_calls = []
            if worker_extension_cls not in worker_class.__bases__:
                # check any conflicts between worker and worker_extension_cls
                for attr in dir(worker_extension_cls):
                    if attr.startswith("__"):
                        continue
                    assert not hasattr(worker_class, attr), (
                        f"Worker class {worker_class} already has an attribute"
                        f" {attr}, which conflicts with the worker"
                        f" extension class {worker_extension_cls}.")
                    if callable(getattr(worker_extension_cls, attr)):
                        extended_calls.append(attr)
                # dynamically inherit the worker extension class
                worker_class.__bases__ = worker_class.__bases__ + (
                    worker_extension_cls, )
                logger.info(
                    "Injected %s into %s for extended collective_rpc calls %s",
                    worker_extension_cls, worker_class, extended_calls)
640
641
642
643
        with set_current_vllm_config(self.vllm_config):
            # To make vLLM config available during worker initialization
            self.worker = worker_class(**kwargs)
            assert self.worker is not None
zhuwenwen's avatar
zhuwenwen committed
644
645
646
647
648
649
650
651
652
653
            
        VLLM_NUMA_BIND = int(os.getenv("VLLM_NUMA_BIND", 1))
        if VLLM_NUMA_BIND > 0:
            # 绑定当前进程到指定 NUMA 节点
            bind_to_numa(kwargs['local_rank'])

            pid = os.getpid()
            logger.info("########## %d process(rank%s) is running on CPU(s): %s", pid, str(kwargs['local_rank']), str(os.sched_getaffinity(pid)))
            logger.info("########## %d process(rank%s) is running on memnode(s): %s", pid, str(kwargs['local_rank']), str(numa.get_membind()))

654

655
656
    def initialize_from_config(self, kv_cache_configs: List[Any]) -> None:
        kv_cache_config = kv_cache_configs[self.rpc_rank]
657
658
        with set_current_vllm_config(self.vllm_config):
            self.worker.initialize_from_config(kv_cache_config)  # type: ignore
659

660
661
662
663
664
    def init_device(self):
        with set_current_vllm_config(self.vllm_config):
            # To make vLLM config available during device initialization
            self.worker.init_device()  # type: ignore

665
    def execute_method(self, method: Union[str, bytes], *args, **kwargs):
666
        try:
667
668
669
670
671
            # method resolution order:
            # if a method is defined in this class, it will be called directly.
            # otherwise, since we define `__getattr__` and redirect attribute
            # query to `self.worker`, the method will be called on the worker.
            return run_method(self, method, args, kwargs)
672
673
674
675
676
        except Exception as e:
            # if the driver worker also execute methods,
            # exceptions in the rest worker may cause deadlock in rpc like ray
            # see https://github.com/vllm-project/vllm/issues/3455
            # print the error and inform the user to solve the error
677
            msg = (f"Error executing method {method!r}. "
678
679
680
                   "This might cause deadlock in distributed execution.")
            logger.exception(msg)
            raise e
681

682
683
684
    def __getattr__(self, attr):
        return getattr(self.worker, attr)

685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703

def extract_previous_hidden_states(
        data: Union[ExecuteModelRequest, Dict[str, torch.Tensor]]) -> \
            Dict[str, torch.Tensor]:
    """If data contains previous_hidden_states, extract it. This returns a dict
    which can be used directly as additional kwargs in any following 
    execute_model calls. This is used in draft models like EAGLE."""
    output = {}

    # When called from non-driver worker, data is dict but when called from
    # driver worker, data is ExecuteModelRequest.
    if isinstance(data, dict):
        if "previous_hidden_states" in data:
            output["previous_hidden_states"] = data["previous_hidden_states"]
    elif data.previous_hidden_states is not None:
        output["previous_hidden_states"] = data.previous_hidden_states\
            .hidden_states

    return output