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

4
5
6
import asyncio
import base64
import time
7
from collections.abc import AsyncGenerator
8
from typing import Final, Literal, Optional, Union, cast
9

10
import jinja2
11
import numpy as np
12
import torch
13
14
15
from fastapi import Request
from typing_extensions import assert_never

16
from vllm.config import VllmConfig
17
18
19
from vllm.engine.protocol import EngineClient
from vllm.entrypoints.chat_utils import ChatTemplateContentFormatOption
from vllm.entrypoints.logger import RequestLogger
20

21
# yapf: disable
22
23
24
25
26
27
28
29
30
31
32
33
from vllm.entrypoints.openai.protocol import (
    ErrorResponse,
    IOProcessorRequest,
    IOProcessorResponse,
    PoolingChatRequest,
    PoolingCompletionRequest,
    PoolingRequest,
    PoolingResponse,
    PoolingResponseData,
    UsageInfo,
)

34
# yapf: enable
35
from vllm.entrypoints.openai.serving_engine import OpenAIServing
36
from vllm.entrypoints.openai.serving_models import OpenAIServingModels
37
from vllm.entrypoints.renderer import RenderConfig
38
from vllm.entrypoints.utils import _validate_truncation_size
39
40
from vllm.logger import init_logger
from vllm.outputs import PoolingOutput, PoolingRequestOutput
41
from vllm.plugins.io_processors import get_io_processor
42
43
44
45
46
47
48
49
from vllm.utils import merge_async_iterators

logger = init_logger(__name__)


def _get_data(
    output: PoolingOutput,
    encoding_format: Literal["float", "base64"],
50
) -> Union[list[float], str]:
51
52
53
54
55
    if encoding_format == "float":
        return output.data.tolist()
    elif encoding_format == "base64":
        # Force to use float32 for base64 encoding
        # to match the OpenAI python client behavior
56
57
        pt_float32 = output.data.to(dtype=torch.float32)
        pooling_bytes = np.array(pt_float32, dtype="float32").tobytes()
58
59
60
61
62
63
64
65
66
        return base64.b64encode(pooling_bytes).decode("utf-8")

    assert_never(encoding_format)


class OpenAIServingPooling(OpenAIServing):
    def __init__(
        self,
        engine_client: EngineClient,
67
        vllm_config: VllmConfig,
68
        models: OpenAIServingModels,
69
70
71
72
        *,
        request_logger: Optional[RequestLogger],
        chat_template: Optional[str],
        chat_template_content_format: ChatTemplateContentFormatOption,
73
        trust_request_chat_template: bool = False,
74
        log_error_stack: bool = False,
75
    ) -> None:
76
77
78
79
80
81
82
        super().__init__(
            engine_client=engine_client,
            model_config=vllm_config.model_config,
            models=models,
            request_logger=request_logger,
            log_error_stack=log_error_stack,
        )
83
84
85

        self.chat_template = chat_template
        self.chat_template_content_format: Final = chat_template_content_format
86
        self.trust_request_chat_template = trust_request_chat_template
87
88
        io_processor_plugin = self.model_config.io_processor_plugin
        self.io_processor = get_io_processor(vllm_config, io_processor_plugin)
89
90
91
92
93

    async def create_pooling(
        self,
        request: PoolingRequest,
        raw_request: Optional[Request] = None,
94
    ) -> Union[PoolingResponse, IOProcessorResponse, ErrorResponse]:
95
96
97
98
99
100
101
102
        """
        See https://platform.openai.com/docs/api-reference/embeddings/create
        for the API specification. This API mimics the OpenAI Embedding API.
        """
        error_check_ret = await self._check_model(request)
        if error_check_ret is not None:
            return error_check_ret

103
        model_name = self.models.model_name()
104

105
106
107
        request_id = f"pool-{self._base_request_id(raw_request)}"
        created_time = int(time.time())

108
        is_io_processor_request = isinstance(request, IOProcessorRequest)
109
        try:
110
            lora_request = self._maybe_get_adapters(request)
111

112
113
114
            if self.model_config.skip_tokenizer_init:
                tokenizer = None
            else:
115
                tokenizer = await self.engine_client.get_tokenizer()
116
            renderer = self._get_renderer(tokenizer)
117

118
119
            if getattr(request, "dimensions", None) is not None:
                return self.create_error_response(
120
121
                    "dimensions is currently not supported"
                )
122

123
            truncate_prompt_tokens = getattr(request, "truncate_prompt_tokens", None)
124
            truncate_prompt_tokens = _validate_truncation_size(
125
126
                self.max_model_len, truncate_prompt_tokens
            )
127
128
129
130
131
132
133

            if is_io_processor_request:
                if self.io_processor is None:
                    raise ValueError(
                        "No IOProcessor plugin installed. Please refer "
                        "to the documentation and to the "
                        "'prithvi_geospatial_mae_io_processor' "
134
135
                        "offline inference example for more details."
                    )
136
137
138
139

                validated_prompt = self.io_processor.parse_request(request)

                engine_prompts = await self.io_processor.pre_process_async(
140
141
                    prompt=validated_prompt, request_id=request_id
                )
142
143

            elif isinstance(request, PoolingChatRequest):
144
145
146
                error_check_ret = self._validate_chat_template(
                    request_chat_template=request.chat_template,
                    chat_template_kwargs=request.chat_template_kwargs,
147
                    trust_request_chat_template=self.trust_request_chat_template,
148
149
150
                )
                if error_check_ret is not None:
                    return error_check_ret
151
152
                (
                    _,
153
                    _,
154
155
156
157
158
159
                    engine_prompts,
                ) = await self._preprocess_chat(
                    request,
                    tokenizer,
                    request.messages,
                    chat_template=request.chat_template or self.chat_template,
160
                    chat_template_content_format=self.chat_template_content_format,
161
162
163
164
165
166
                    # In pooling requests, we are not generating tokens,
                    # so there is no need to append extra tokens to the input
                    add_generation_prompt=False,
                    continue_final_message=False,
                    add_special_tokens=request.add_special_tokens,
                )
167
            elif isinstance(request, PoolingCompletionRequest):
168
169
                engine_prompts = await renderer.render_prompt(
                    prompt_or_prompts=request.input,
170
                    config=self._build_render_config(request),
171
                )
172
            else:
173
                raise ValueError(f"Unsupported request of type {type(request)}")
174
        except (ValueError, TypeError, jinja2.TemplateError) as e:
175
176
            logger.exception("Error in preprocessing prompt inputs")
            return self.create_error_response(str(e))
177
178

        # Schedule the request and get the result generator.
179
        generators: list[AsyncGenerator[PoolingRequestOutput, None]] = []
180
181
182
        try:
            pooling_params = request.to_pooling_params()

183
184
185
186
187
            try:
                pooling_params.verify("encode", self.model_config)
            except ValueError as e:
                return self.create_error_response(str(e))

188
189
190
            for i, engine_prompt in enumerate(engine_prompts):
                request_id_item = f"{request_id}-{i}"

191
192
193
194
195
196
                self._log_inputs(
                    request_id_item,
                    engine_prompt,
                    params=pooling_params,
                    lora_request=lora_request,
                )
197

198
199
200
201
202
                trace_headers = (
                    None
                    if raw_request is None
                    else await self._get_trace_headers(raw_request.headers)
                )
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219

                generator = self.engine_client.encode(
                    engine_prompt,
                    pooling_params,
                    request_id_item,
                    lora_request=lora_request,
                    trace_headers=trace_headers,
                    priority=request.priority,
                )

                generators.append(generator)
        except ValueError as e:
            # TODO: Use a vllm-specific Validation Error
            return self.create_error_response(str(e))

        result_generator = merge_async_iterators(*generators)

220
221
222
223
224
225
226
227
        if is_io_processor_request:
            assert self.io_processor is not None
            output = await self.io_processor.post_process_async(
                model_output=result_generator,
                request_id=request_id,
            )
            return self.io_processor.output_to_response(output)

228
        assert isinstance(request, (PoolingCompletionRequest, PoolingChatRequest))
229
230
231
        num_prompts = len(engine_prompts)

        # Non-streaming response
232
        final_res_batch: list[Optional[PoolingRequestOutput]]
233
234
235
236
237
238
239
        final_res_batch = [None] * num_prompts
        try:
            async for i, res in result_generator:
                final_res_batch[i] = res

            assert all(final_res is not None for final_res in final_res_batch)

240
            final_res_batch_checked = cast(list[PoolingRequestOutput], final_res_batch)
241
242
243
244
245
246

            response = self.request_output_to_pooling_response(
                final_res_batch_checked,
                request_id,
                created_time,
                model_name,
247
                request.encoding_format,
248
249
250
251
252
253
254
255
256
257
258
            )
        except asyncio.CancelledError:
            return self.create_error_response("Client disconnected")
        except ValueError as e:
            # TODO: Use a vllm-specific Validation Error
            return self.create_error_response(str(e))

        return response

    def request_output_to_pooling_response(
        self,
259
        final_res_batch: list[PoolingRequestOutput],
260
261
262
263
264
        request_id: str,
        created_time: int,
        model_name: str,
        encoding_format: Literal["float", "base64"],
    ) -> PoolingResponse:
265
        items: list[PoolingResponseData] = []
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
        num_prompt_tokens = 0

        for idx, final_res in enumerate(final_res_batch):
            item = PoolingResponseData(
                index=idx,
                data=_get_data(final_res.outputs, encoding_format),
            )
            prompt_token_ids = final_res.prompt_token_ids

            items.append(item)
            num_prompt_tokens += len(prompt_token_ids)

        usage = UsageInfo(
            prompt_tokens=num_prompt_tokens,
            total_tokens=num_prompt_tokens,
        )

        return PoolingResponse(
            id=request_id,
            created=created_time,
            model=model_name,
            data=items,
            usage=usage,
        )
290

291
    def _build_render_config(self, request: PoolingCompletionRequest) -> RenderConfig:
292
293
294
        return RenderConfig(
            max_length=self.max_model_len,
            truncate_prompt_tokens=request.truncate_prompt_tokens,
295
296
            add_special_tokens=request.add_special_tokens,
        )