main
py 80 lines 2.57 KB
Raw
1 # SPDX-License-Identifier: Apache-2.0
2 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project
3 from abc import ABC, abstractmethod
4 from collections.abc import AsyncGenerator, Sequence
5 from typing import Generic, TypeVar
6
7 from vllm.config import VllmConfig
8 from vllm.inputs import PromptType
9 from vllm.outputs import PoolingRequestOutput
10 from vllm.pooling_params import PoolingParams
11 from vllm.renderers import BaseRenderer
12 from vllm.sampling_params import SamplingParams
13
14 IOProcessorInput = TypeVar("IOProcessorInput")
15 IOProcessorOutput = TypeVar("IOProcessorOutput")
16
17
18 class IOProcessor(ABC, Generic[IOProcessorInput, IOProcessorOutput]):
19 """Abstract interface for pre/post-processing of engine I/O."""
20
21 def __init__(self, vllm_config: VllmConfig, renderer: BaseRenderer):
22 super().__init__()
23
24 self.vllm_config = vllm_config
25
26 def parse_data(self, data: object) -> IOProcessorInput:
27 raise NotImplementedError
28
29 def merge_sampling_params(
30 self,
31 params: SamplingParams | None = None,
32 ) -> SamplingParams:
33 return params or SamplingParams()
34
35 def merge_pooling_params(
36 self,
37 params: PoolingParams | None = None,
38 ) -> PoolingParams:
39 return params or PoolingParams(task="plugin")
40
41 @abstractmethod
42 def pre_process(
43 self,
44 prompt: IOProcessorInput,
45 request_id: str | None = None,
46 **kwargs,
47 ) -> PromptType | Sequence[PromptType]:
48 raise NotImplementedError
49
50 async def pre_process_async(
51 self,
52 prompt: IOProcessorInput,
53 request_id: str | None = None,
54 **kwargs,
55 ) -> PromptType | Sequence[PromptType]:
56 return self.pre_process(prompt, request_id, **kwargs)
57
58 @abstractmethod
59 def post_process(
60 self,
61 model_output: Sequence[PoolingRequestOutput],
62 request_id: str | None = None,
63 **kwargs,
64 ) -> IOProcessorOutput:
65 raise NotImplementedError
66
67 async def post_process_async(
68 self,
69 model_output: AsyncGenerator[tuple[int, PoolingRequestOutput]],
70 request_id: str | None = None,
71 **kwargs,
72 ) -> IOProcessorOutput:
73 # We cannot guarantee outputs are returned in the same order they were
74 # fed to vLLM.
75 # Let's sort them by id before post_processing
76 sorted_output = sorted(
77 [(i, item) async for i, item in model_output], key=lambda output: output[0]
78 )
79 collected_output = [output[1] for output in sorted_output]
80 return self.post_process(collected_output, request_id=request_id, **kwargs)