gpu_executor.py 6.69 KB
Newer Older
1
from typing import Any, Dict, List, Optional, Set, Tuple, Union
2
3
4

from vllm.executor.executor_base import ExecutorAsyncBase, ExecutorBase
from vllm.logger import init_logger
5
from vllm.lora.request import LoRARequest
6
from vllm.model_executor.layers.sampler import SamplerOutput
7
from vllm.prompt_adapter.request import PromptAdapterRequest
8
from vllm.sequence import ExecuteModelRequest, PoolerOutput
9
from vllm.utils import (get_distributed_init_method, get_ip, get_open_port,
10
                        make_async)
11
from vllm.worker.worker_base import WorkerWrapperBase
12

zhouxiang's avatar
zhouxiang committed
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
import numa,os
# 设置当前进程绑定到 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])    


31
32
33
logger = init_logger(__name__)


34
35
def create_worker(**kwargs):
    vllm_config = kwargs.get("vllm_config")
zhouxiang's avatar
zhouxiang committed
36
37
38
39
40
41
42
43
    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()))
zhuwenwen's avatar
zhuwenwen committed
44
    
45
    wrapper = WorkerWrapperBase(vllm_config=vllm_config)
46
47
48
49
    wrapper.init_worker(**kwargs)
    return wrapper.worker


50
51
class GPUExecutor(ExecutorBase):

52
53
    uses_ray: bool = False

54
    def _init_executor(self) -> None:
55
56
        """Initialize the worker and load the model.
        """
57
58
59
60
61
62
        assert self.parallel_config.world_size == 1, (
            "GPUExecutor only supports single GPU.")

        self.driver_worker = self._create_worker()
        self.driver_worker.init_device()
        self.driver_worker.load_model()
63

64
65
66
67
68
69
70
71
72
73
    def _get_worker_kwargs(
            self,
            local_rank: int = 0,
            rank: int = 0,
            distributed_init_method: Optional[str] = None) -> Dict[str, Any]:
        """Return worker init args for a given rank."""
        if distributed_init_method is None:
            distributed_init_method = get_distributed_init_method(
                get_ip(), get_open_port())
        return dict(
74
            vllm_config=self.vllm_config,
75
76
            local_rank=local_rank,
            rank=rank,
77
            distributed_init_method=distributed_init_method,
78
79
            is_driver_worker=(not self.parallel_config)
            or (rank % self.parallel_config.tensor_parallel_size == 0),
80
81
82
83
84
85
        )

    def _create_worker(self,
                       local_rank: int = 0,
                       rank: int = 0,
                       distributed_init_method: Optional[str] = None):
86
        return create_worker(**self._get_worker_kwargs(
87
88
89
            local_rank=local_rank,
            rank=rank,
            distributed_init_method=distributed_init_method))
90

91
    def determine_num_available_blocks(self) -> Tuple[int, int]:
92
93
        """Determine the number of available KV blocks by invoking the
        underlying worker.
94
        """
95
        return self.driver_worker.determine_num_available_blocks()
96

97
98
99
100
101
102
    def initialize_cache(self, num_gpu_blocks: int, num_cpu_blocks) -> None:
        """Initialize the KV cache by invoking the underlying worker.
        """
        # NOTE: This is logged in the executor because there can be >1 worker
        # with other executors. We could log in the engine level, but work
        # remains to abstract away the device for non-GPU configurations.
103
104
        logger.info("# GPU blocks: %d, # CPU blocks: %d", num_gpu_blocks,
                    num_cpu_blocks)
105
106
107
108
        max_concurrency = (num_gpu_blocks * self.cache_config.block_size /
                           self.model_config.max_model_len)
        logger.info("Maximum concurrency for %s tokens per request: %.2fx",
                    self.model_config.max_model_len, max_concurrency)
109

110
        self.driver_worker.initialize_cache(num_gpu_blocks, num_cpu_blocks)
111

112
    def execute_model(
113
        self, execute_model_req: ExecuteModelRequest
114
    ) -> Optional[List[Union[SamplerOutput, PoolerOutput]]]:
115
        output = self.driver_worker.execute_model(execute_model_req)
116
117
118
119
120
121
122
123
124
125
        return output

    def add_lora(self, lora_request: LoRARequest) -> bool:
        assert lora_request.lora_int_id > 0, "lora_id must be greater than 0."
        return self.driver_worker.add_lora(lora_request)

    def remove_lora(self, lora_id: int) -> bool:
        assert lora_id > 0, "lora_id must be greater than 0."
        return self.driver_worker.remove_lora(lora_id)

126
127
128
129
    def pin_lora(self, lora_id: int) -> bool:
        assert lora_id > 0, "lora_id must be greater than 0."
        return self.driver_worker.pin_lora(lora_id)

130
    def list_loras(self) -> Set[int]:
131
132
        return self.driver_worker.list_loras()

133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
    def add_prompt_adapter(
            self, prompt_adapter_request: PromptAdapterRequest) -> bool:
        assert prompt_adapter_request.prompt_adapter_id > 0, \
            "prompt_adapter_id must be greater than 0."
        return self.driver_worker.add_prompt_adapter(prompt_adapter_request)

    def remove_prompt_adapter(self, prompt_adapter_id: int) -> bool:
        assert prompt_adapter_id > 0, \
            "prompt_adapter_id must be greater than 0."
        return self.driver_worker.remove_prompt_adapter(prompt_adapter_id)

    def pin_prompt_adapter(self, prompt_adapter_id: int) -> bool:
        assert prompt_adapter_id > 0, \
                "prompt_adapter_id must be greater than 0."
        return self.driver_worker.pin_prompt_adapter(prompt_adapter_id)

    def list_prompt_adapters(self) -> Set[int]:
        return self.driver_worker.list_prompt_adapters()

152
153
154
155
156
    def check_health(self) -> None:
        # GPUExecutor will always be healthy as long as
        # it's running.
        return

157
158
159
160
161
162
    def start_profile(self) -> None:
        self.driver_worker.start_profile()

    def stop_profile(self) -> None:
        self.driver_worker.stop_profile()

163
164
165
166
167

class GPUExecutorAsync(GPUExecutor, ExecutorAsyncBase):

    async def execute_model_async(
        self,
168
        execute_model_req: ExecuteModelRequest,
169
    ) -> List[Union[SamplerOutput, PoolerOutput]]:
170
        output = await make_async(self.driver_worker.execute_model
171
                                  )(execute_model_req=execute_model_req)
172
        return output