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

4
from concurrent.futures import Future
5
from typing import Callable, Optional, Union
6

7
8
9
import torch
import torch.distributed as dist

10
from vllm.config import VllmConfig
11
12
13
14
15
from vllm.executor.executor_base import ExecutorBase
from vllm.executor.uniproc_executor import (  # noqa
    ExecutorWithExternalLauncher as ExecutorWithExternalLauncherV0)
from vllm.executor.uniproc_executor import (  # noqa
    UniProcExecutor as UniProcExecutorV0)
16
from vllm.v1.kv_cache_interface import KVCacheConfig, KVCacheSpec
17
from vllm.v1.outputs import DraftTokenIds, ModelRunnerOutput
18

19
20
FailureCallback = Callable[[], None]

21

22
23
24
25
class Executor(ExecutorBase):
    """
    Abstract class for v1 executors, mainly define some methods for v1.
    For methods shared by v0 and v1, define them in ExecutorBase"""
26

27
    @staticmethod
28
29
    def get_class(vllm_config: VllmConfig) -> type["Executor"]:
        executor_class: type[Executor]
30
        parallel_config = vllm_config.parallel_config
31
        distributed_executor_backend = (
32
            parallel_config.distributed_executor_backend)
33
34
35
36
37
38
39
40
        # distributed_executor_backend must be set in VllmConfig.__post_init__
        if isinstance(distributed_executor_backend, type):
            if not issubclass(distributed_executor_backend, ExecutorBase):
                raise TypeError(
                    "distributed_executor_backend must be a subclass of "
                    f"ExecutorBase. Got {distributed_executor_backend}.")
            executor_class = distributed_executor_backend
        elif distributed_executor_backend == "ray":
41
42
            from vllm.v1.executor.ray_distributed_executor import (  # noqa
                RayDistributedExecutor)
43
            executor_class = RayDistributedExecutor
44
45
46
        elif distributed_executor_backend == "mp":
            from vllm.v1.executor.multiproc_executor import MultiprocExecutor
            executor_class = MultiprocExecutor
47
48
49
50
51
52
        elif distributed_executor_backend == "uni":
            executor_class = UniProcExecutor
        elif distributed_executor_backend == "external_launcher":
            # TODO: make v1 scheduling deterministic
            # to support external launcher
            executor_class = ExecutorWithExternalLauncher
53
        else:
54
55
            raise ValueError("Unknown distributed executor backend: "
                             f"{distributed_executor_backend}")
56
57
        return executor_class

58
    def initialize_from_config(self,
59
                               kv_cache_configs: list[KVCacheConfig]) -> None:
60
61
62
63
        """
        Initialize the KV caches and begin the model execution loop of the
        underlying workers.
        """
64
65
        self.collective_rpc("initialize_from_config",
                            args=(kv_cache_configs, ))
66
        self.collective_rpc("compile_or_warm_up_model")
67

68
69
70
71
72
73
74
    def register_failure_callback(self, callback: FailureCallback):
        """
        Register a function to be called if the executor enters a permanent
        failed state.
        """
        pass

75
    def determine_available_memory(self) -> list[int]:  # in bytes
76
        output = self.collective_rpc("determine_available_memory")
77
        return output
78

79
    def get_kv_cache_specs(self) -> list[dict[str, KVCacheSpec]]:
80
        output = self.collective_rpc("get_kv_cache_spec")
81
        return output
82
83
84
85

    def execute_model(
        self,
        scheduler_output,
86
    ) -> Union[ModelRunnerOutput, Future[ModelRunnerOutput]]:
87
88
89
        output = self.collective_rpc("execute_model",
                                     args=(scheduler_output, ))
        return output[0]
90

91
92
93
94
    def take_draft_token_ids(self) -> Optional[DraftTokenIds]:
        output = self.collective_rpc("take_draft_token_ids")
        return output[0]

95
96
97
98
    @property
    def max_concurrent_batches(self) -> int:
        return 1

99
    def profile(self, is_start: bool = True):
100
101
102
103
104
105
106
107
        self.collective_rpc("profile", args=(is_start, ))


class UniProcExecutor(UniProcExecutorV0, Executor):
    pass


class ExecutorWithExternalLauncher(ExecutorWithExternalLauncherV0, Executor):
108

109
    def determine_available_memory(self) -> list[int]:  # in bytes
110
111
112
113
114
115
116
        # same as determine_num_available_blocks in v0,
        # we need to get the min across all ranks.
        memory = super().determine_available_memory()
        from vllm.distributed.parallel_state import get_world_group
        cpu_group = get_world_group().cpu_group
        memory_tensor = torch.tensor([memory], device="cpu", dtype=torch.int64)
        dist.all_reduce(memory_tensor, group=cpu_group, op=dist.ReduceOp.MIN)
117
        return [memory_tensor.item()]