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

4
import time
5
from collections.abc import Callable, Mapping
6
from copy import copy
7
from typing import Any
8

9
import torch.nn as nn
10
from typing_extensions import TypeVar
11

12
import vllm.envs as envs
13
from vllm.config import ParallelConfig, VllmConfig
14
from vllm.distributed import stateless_destroy_torch_distributed_process_group
15
from vllm.distributed.parallel_state import get_dp_group
16
from vllm.engine.arg_utils import EngineArgs
17
from vllm.inputs import EngineInput, PromptType
18
19
from vllm.logger import init_logger
from vllm.lora.request import LoRARequest
20
from vllm.multimodal import MULTIMODAL_REGISTRY, MultiModalRegistry
21
from vllm.outputs import PoolingRequestOutput, RequestOutput
22
from vllm.plugins.io_processors import get_io_processor
23
from vllm.pooling_params import PoolingParams
24
from vllm.renderers import renderer_from_config
25
from vllm.renderers.inputs.preprocess import extract_prompt_components
26
from vllm.sampling_params import SamplingParams
27
from vllm.tasks import SupportedTask
28
from vllm.tokenizers import TokenizerLike
29
from vllm.tracing import init_tracer
30
from vllm.usage.usage_lib import UsageContext
31
from vllm.v1.engine import EngineCoreRequest, PauseMode
32
from vllm.v1.engine.core_client import EngineCoreClient
33
from vllm.v1.engine.input_processor import InputProcessor
34
from vllm.v1.engine.output_processor import OutputProcessor
35
from vllm.v1.engine.parallel_sampling import ParentRequest
36
from vllm.v1.executor import Executor
37
from vllm.v1.metrics.loggers import StatLoggerFactory, StatLoggerManager
38
39
from vllm.v1.metrics.reader import Metric, get_metrics_snapshot
from vllm.v1.metrics.stats import IterationStats
40
from vllm.v1.utils import record_function_or_nullcontext
41
from vllm.v1.worker.worker_base import WorkerBase
42
43
44

logger = init_logger(__name__)

45
_R = TypeVar("_R", default=Any)
46

47
48

class LLMEngine:
49
    """Legacy LLMEngine for backwards compatibility."""
50
51
52

    def __init__(
        self,
53
        vllm_config: VllmConfig,
54
        executor_class: type[Executor],
55
        log_stats: bool,
56
        aggregate_engine_logging: bool = False,
57
        usage_context: UsageContext = UsageContext.ENGINE_CONTEXT,
58
        stat_loggers: list[StatLoggerFactory] | None = None,
59
        mm_registry: MultiModalRegistry = MULTIMODAL_REGISTRY,
60
        use_cached_outputs: bool = False,
61
        multiprocess_mode: bool = False,
62
    ) -> None:
63
        self.vllm_config = vllm_config
64
        self.model_config = vllm_config.model_config
65
66
67
68
69
        self.observability_config = vllm_config.observability_config

        tracing_endpoint = self.observability_config.otlp_traces_endpoint
        if tracing_endpoint is not None:
            init_tracer("vllm.llm_engine", tracing_endpoint)
70

71
72
        self.log_stats = log_stats

73
        parallel_config = vllm_config.parallel_config
74
75
        executor_backend = parallel_config.distributed_executor_backend

76
77
78
79
        self.external_launcher_dp = (
            parallel_config.data_parallel_size > 1
            and executor_backend == "external_launcher"
        )
80
        # important: init dp group before init the engine_core
81
        # In the decoupled engine case this is handled in EngineCoreProc.
82
83
84
85
86
        if (
            not multiprocess_mode
            and parallel_config.data_parallel_size > 1
            and not self.external_launcher_dp
        ):
87
88
89
            self.dp_group = parallel_config.stateless_init_dp_group()
        else:
            self.dp_group = None
90
91
        self.should_execute_dummy_batch = False

92
        self.renderer = renderer = renderer_from_config(self.vllm_config)
93
94
        self.io_processor = get_io_processor(
            self.vllm_config,
95
            self.renderer,
96
            self.model_config.io_processor_plugin,
97
        )
98

99
        # Convert EngineInput --> EngineCoreRequest.
100
101
102
        self.input_processor = InputProcessor(self.vllm_config, renderer)

        # Converts EngineCoreOutputs --> RequestOutput.
103
        self.output_processor = OutputProcessor(
104
            renderer.tokenizer,
105
106
            log_stats=self.log_stats,
            stream_interval=self.vllm_config.scheduler_config.stream_interval,
107
            tracing_enabled=tracing_endpoint is not None,
108
        )
109
110
111
112
113

        # EngineCore (gets EngineCoreRequests and gives EngineCoreOutputs)
        self.engine_core = EngineCoreClient.make_client(
            multiprocess_mode=multiprocess_mode,
            asyncio_mode=False,
114
115
            vllm_config=vllm_config,
            executor_class=executor_class,
116
            log_stats=self.log_stats,
117
        )
118

119
        self.logger_manager: StatLoggerManager | None = None
120
121
122
123
124
        if self.log_stats:
            self.logger_manager = StatLoggerManager(
                vllm_config=vllm_config,
                custom_stat_loggers=stat_loggers,
                enable_default_loggers=log_stats,
125
                aggregate_engine_logging=aggregate_engine_logging,
126
127
128
            )
            self.logger_manager.log_engine_initialized()

129
130
131
132
        if not multiprocess_mode:
            # for v0 compatibility
            self.model_executor = self.engine_core.engine_core.model_executor  # type: ignore

133
134
135
136
137
        if self.external_launcher_dp:
            # If we use DP in external launcher mode, we reuse the
            # existing DP group used for data communication.
            self.dp_group = get_dp_group().cpu_group

138
139
140
        # Don't keep the dummy data in memory
        self.reset_mm_cache()

141
142
143
144
145
    @classmethod
    def from_vllm_config(
        cls,
        vllm_config: VllmConfig,
        usage_context: UsageContext = UsageContext.ENGINE_CONTEXT,
146
        stat_loggers: list[StatLoggerFactory] | None = None,
147
148
        disable_log_stats: bool = False,
    ) -> "LLMEngine":
149
150
151
152
153
154
155
156
        return cls(
            vllm_config=vllm_config,
            executor_class=Executor.get_class(vllm_config),
            log_stats=(not disable_log_stats),
            usage_context=usage_context,
            stat_loggers=stat_loggers,
            multiprocess_mode=envs.VLLM_ENABLE_V1_MULTIPROCESSING,
        )
157

158
159
160
161
162
    @classmethod
    def from_engine_args(
        cls,
        engine_args: EngineArgs,
        usage_context: UsageContext = UsageContext.ENGINE_CONTEXT,
163
        stat_loggers: list[StatLoggerFactory] | None = None,
164
        enable_multiprocessing: bool = False,
165
166
    ) -> "LLMEngine":
        """Creates an LLM engine from the engine arguments."""
167

168
        # Create the engine configs.
169
        vllm_config = engine_args.create_engine_config(usage_context)
170
        executor_class = Executor.get_class(vllm_config)
171

172
        if envs.VLLM_ENABLE_V1_MULTIPROCESSING:
173
174
175
176
            logger.debug("Enabling multiprocessing for LLMEngine.")
            enable_multiprocessing = True

        # Create the LLMEngine.
177
178
179
180
181
182
183
184
        return cls(
            vllm_config=vllm_config,
            executor_class=executor_class,
            log_stats=not engine_args.disable_log_stats,
            usage_context=usage_context,
            stat_loggers=stat_loggers,
            multiprocess_mode=enable_multiprocessing,
        )
185
186

    def get_num_unfinished_requests(self) -> int:
187
        return self.output_processor.get_num_unfinished_requests()
188
189

    def has_unfinished_requests(self) -> bool:
190
        has_unfinished = self.output_processor.has_unfinished_requests()
191
        if self.dp_group is None:
192
            return has_unfinished or self.engine_core.dp_engines_running()
193
194
195
196
        return self.has_unfinished_requests_dp(has_unfinished)

    def has_unfinished_requests_dp(self, has_unfinished: bool) -> bool:
        aggregated_has_unfinished = ParallelConfig.has_unfinished_dp(
197
198
            self.dp_group, has_unfinished
        )
199
200
201
        if not has_unfinished and aggregated_has_unfinished:
            self.should_execute_dummy_batch = True
        return aggregated_has_unfinished
202

203
    def get_supported_tasks(self) -> tuple[SupportedTask, ...]:
204
205
206
207
208
        if not hasattr(self, "_supported_tasks"):
            # Cache the result
            self._supported_tasks = self.engine_core.get_supported_tasks()

        return self._supported_tasks
209

210
    def abort_request(self, request_ids: list[str], internal: bool = False) -> None:
211
212
        """Remove request_ids from EngineCore and Detokenizer."""

213
        request_ids = self.output_processor.abort_requests(request_ids, internal)
214
215
        self.engine_core.abort_requests(request_ids)

216
217
218
    def add_request(
        self,
        request_id: str,
219
        prompt: EngineCoreRequest | PromptType | EngineInput,
220
221
222
223
224
        params: SamplingParams | PoolingParams,
        arrival_time: float | None = None,
        lora_request: LoRARequest | None = None,
        tokenization_kwargs: dict[str, Any] | None = None,
        trace_headers: Mapping[str, str] | None = None,
225
        priority: int = 0,
226
        prompt_text: str | None = None,
227
    ) -> str:
228
229
        # Validate the request_id type.
        if not isinstance(request_id, str):
230
            raise TypeError(f"request_id must be a string, got {type(request_id)}")
231

232
        # Process raw inputs into the request.
233
        if isinstance(prompt, EngineCoreRequest):
234
235
236
237
238
239
            logger.warning_once(
                "Passing EngineCoreRequest to LLMEngine.generate() and .add_requests() "
                "is deprecated and will be removed in v0.18. You should instead pass "
                "the outputs of Renderer.render_cmpl() or Renderer.render_chat()."
            )

240
            request = prompt
241
242
            if request_id != request.request_id:
                logger.warning_once(
243
                    "LLMEngine.add_request() was passed a request_id parameter that "
244
245
246
                    "does not match the EngineCoreRequest.request_id attribute. The "
                    "latter will be used, and the former will be ignored."
                )
247
        else:
248
            request = self.input_processor.process_inputs(
249
250
251
                request_id,
                prompt,
                params,
252
                supported_tasks=self.get_supported_tasks(),
253
254
255
256
257
                arrival_time=arrival_time,
                lora_request=lora_request,
                tokenization_kwargs=tokenization_kwargs,
                trace_headers=trace_headers,
                priority=priority,
258
            )
259
            prompt_text, _, _ = extract_prompt_components(self.model_config, prompt)
260

261
262
        self.input_processor.assign_request_id(request)

263
264
        req_id = request.request_id

265
266
267
        # Use cloned params that may have been updated in process_inputs()
        params = request.params

268
        n = params.n if isinstance(params, SamplingParams) else 1
269

270
271
        if n == 1:
            # Make a new RequestState and queue.
272
            self.output_processor.add_request(request, prompt_text, None, 0)
273
            # Add the request to EngineCore.
274
            self.engine_core.add_request(request)
275
            return req_id
276
277

        # Fan out child requests (for n>1).
278
        parent_req = ParentRequest(request)
279
        for idx in range(n):
280
            request_id, child_params = parent_req.get_child_info(idx)
281
282
            child_request = request if idx == n - 1 else copy(request)
            child_request.request_id = request_id
283
            child_request.sampling_params = child_params
284
285

            # Make a new RequestState and queue.
286
287
288
            self.output_processor.add_request(
                child_request, prompt_text, parent_req, idx
            )
289
290
            # Add the request to EngineCore.
            self.engine_core.add_request(child_request)
291

292
293
        return req_id

294
    def step(self) -> list[RequestOutput | PoolingRequestOutput]:
295
296
297
298
299
        if self.should_execute_dummy_batch:
            self.should_execute_dummy_batch = False
            self.engine_core.execute_dummy_batch()
            return []

300
        # 1) Get EngineCoreOutput from the EngineCore.
301
        with record_function_or_nullcontext("llm_engine step: get_output"):
302
            outputs = self.engine_core.get_output()
303

304
        # 2) Process EngineCoreOutputs.
305
        with record_function_or_nullcontext("llm_engine step: process_outputs"):
306
307
308
309
310
311
312
            iteration_stats = IterationStats() if self.log_stats else None
            processed_outputs = self.output_processor.process_outputs(
                outputs.outputs,
                engine_core_timestamp=outputs.timestamp,
                iteration_stats=iteration_stats,
            )
            self.output_processor.update_scheduler_stats(outputs.scheduler_stats)
313

314
        # 3) Abort any reqs that finished due to stop strings.
315
        with record_function_or_nullcontext("llm_engine step: abort_requests"):
316
            self.engine_core.abort_requests(processed_outputs.reqs_to_abort)
317

318
        # 4) Record stats
319
        with record_function_or_nullcontext("llm_engine step: record_stats"):
320
321
322
323
324
            if (
                self.logger_manager is not None
                and outputs.scheduler_stats is not None
                and len(outputs.outputs) > 0
            ):
325
326
327
                self.logger_manager.record(
                    scheduler_stats=outputs.scheduler_stats,
                    iteration_stats=iteration_stats,
328
                    mm_cache_stats=self.renderer.stat_mm_cache(),
329
330
                )
                self.do_log_stats_with_interval()
331

332
        return processed_outputs.request_outputs
333

334
335
    def start_profile(self, profile_prefix: str | None = None):
        self.engine_core.profile(True, profile_prefix)
336

337
    def stop_profile(self):
338
        self.engine_core.profile(False)
339

340
    def reset_mm_cache(self):
341
        self.renderer.clear_mm_cache()
342
343
        self.engine_core.reset_mm_cache()

344
345
346
347
348
349
    def reset_prefix_cache(
        self, reset_running_requests: bool = False, reset_connector: bool = False
    ) -> bool:
        return self.engine_core.reset_prefix_cache(
            reset_running_requests, reset_connector
        )
350

351
352
353
354
355
356
357
358
    def reset_encoder_cache(self) -> None:
        """Reset the encoder cache to invalidate all cached encoder outputs.

        This should be called when model weights are updated to ensure
        stale vision embeddings computed with old weights are not reused.
        """
        self.engine_core.reset_encoder_cache()

359
360
    def sleep(self, level: int = 1, mode: PauseMode = "abort"):
        self.engine_core.sleep(level, mode)
361

362
363
364
        if self.logger_manager is not None:
            self.logger_manager.record_sleep_state(1, level)

365
    def wake_up(self, tags: list[str] | None = None):
366
        self.engine_core.wake_up(tags)
367

368
369
370
        if self.logger_manager is not None:
            self.logger_manager.record_sleep_state(0, 0)

371
372
373
    def is_sleeping(self) -> bool:
        return self.engine_core.is_sleeping()

374
375
376
377
    def get_metrics(self) -> list[Metric]:
        assert self.log_stats, "Stat logging disabled"
        return get_metrics_snapshot()

378
    @property
379
    def tokenizer(self) -> TokenizerLike | None:
380
        return self.renderer.tokenizer
381

382
    def get_tokenizer(self) -> TokenizerLike:
383
        return self.renderer.get_tokenizer()
384

385
386
387
388
389
390
391
392
393
394
395
396
397
398
    def do_log_stats(self) -> None:
        """Log stats if logging is enabled."""
        if self.logger_manager:
            self.logger_manager.log()

    def do_log_stats_with_interval(self) -> None:
        """Log stats when the time interval has passed."""
        now = time.time()
        if not hasattr(self, "_last_log_time"):
            self._last_log_time = now
        if now - self._last_log_time >= envs.VLLM_LOG_STATS_INTERVAL:
            self.do_log_stats()
            self._last_log_time = now

399
400
401
402
403
404
405
406
    def add_lora(self, lora_request: LoRARequest) -> bool:
        """Load a new LoRA adapter into the engine for future requests."""
        return self.engine_core.add_lora(lora_request)

    def remove_lora(self, lora_id: int) -> bool:
        """Remove an already loaded LoRA adapter."""
        return self.engine_core.remove_lora(lora_id)

407
    def list_loras(self) -> set[int]:
408
409
410
411
412
413
        """List all registered adapters."""
        return self.engine_core.list_loras()

    def pin_lora(self, lora_id: int) -> bool:
        """Prevent an adapter from being evicted."""
        return self.engine_core.pin_lora(lora_id)
414

415
416
    def collective_rpc(
        self,
417
418
        method: str | Callable[[WorkerBase], _R],
        timeout: float | None = None,
419
        args: tuple = (),
420
        kwargs: dict[str, Any] | None = None,
421
    ) -> list[_R]:
422
423
        return self.engine_core.collective_rpc(method, timeout, args, kwargs)

424
    def apply_model(self, func: Callable[[nn.Module], _R]) -> list[_R]:
425
        return self.collective_rpc("apply_model", args=(func,))
426

427
    def __del__(self):
428
429
        dp_group = getattr(self, "dp_group", None)
        if dp_group is not None and not self.external_launcher_dp:
430
            stateless_destroy_torch_distributed_process_group(dp_group)