vllm-npu 0.4.2__py3-none-any.whl
Sign up to get free protection for your applications and to get access to all the features.
- vllm/__init__.py +23 -0
- vllm/_custom_ops.py +251 -0
- vllm/attention/__init__.py +13 -0
- vllm/attention/backends/__init__.py +0 -0
- vllm/attention/backends/abstract.py +127 -0
- vllm/attention/backends/flash_attn.py +271 -0
- vllm/attention/backends/flashinfer.py +220 -0
- vllm/attention/backends/rocm_flash_attn.py +374 -0
- vllm/attention/backends/torch_sdpa.py +250 -0
- vllm/attention/backends/xformers.py +393 -0
- vllm/attention/layer.py +56 -0
- vllm/attention/ops/__init__.py +0 -0
- vllm/attention/ops/paged_attn.py +216 -0
- vllm/attention/ops/prefix_prefill.py +792 -0
- vllm/attention/ops/triton_flash_attention.py +810 -0
- vllm/attention/selector.py +91 -0
- vllm/block.py +84 -0
- vllm/config.py +1225 -0
- vllm/core/__init__.py +0 -0
- vllm/core/block/__init__.py +0 -0
- vllm/core/block/block_table.py +295 -0
- vllm/core/block/common.py +199 -0
- vllm/core/block/cpu_gpu_block_allocator.py +228 -0
- vllm/core/block/interfaces.py +205 -0
- vllm/core/block/naive_block.py +318 -0
- vllm/core/block/prefix_caching_block.py +606 -0
- vllm/core/block_manager_v1.py +625 -0
- vllm/core/block_manager_v2.py +258 -0
- vllm/core/evictor_v1.py +105 -0
- vllm/core/evictor_v2.py +127 -0
- vllm/core/interfaces.py +113 -0
- vllm/core/policy.py +45 -0
- vllm/core/scheduler.py +1163 -0
- vllm/distributed/__init__.py +3 -0
- vllm/distributed/communication_op.py +237 -0
- vllm/distributed/device_communicators/__init__.py +0 -0
- vllm/distributed/device_communicators/custom_all_reduce.py +274 -0
- vllm/distributed/device_communicators/pynccl.py +287 -0
- vllm/distributed/device_communicators/pynccl_utils.py +66 -0
- vllm/distributed/parallel_state.py +339 -0
- vllm/distributed/utils.py +136 -0
- vllm/engine/__init__.py +0 -0
- vllm/engine/arg_utils.py +649 -0
- vllm/engine/async_llm_engine.py +737 -0
- vllm/engine/llm_engine.py +784 -0
- vllm/engine/metrics.py +368 -0
- vllm/engine/output_processor/__init__.py +0 -0
- vllm/engine/output_processor/interfaces.py +76 -0
- vllm/engine/output_processor/multi_step.py +142 -0
- vllm/engine/output_processor/single_step.py +284 -0
- vllm/engine/output_processor/stop_checker.py +101 -0
- vllm/engine/output_processor/util.py +19 -0
- vllm/entrypoints/__init__.py +0 -0
- vllm/entrypoints/api_server.py +119 -0
- vllm/entrypoints/llm.py +259 -0
- vllm/entrypoints/openai/__init__.py +0 -0
- vllm/entrypoints/openai/api_server.py +186 -0
- vllm/entrypoints/openai/cli_args.py +115 -0
- vllm/entrypoints/openai/protocol.py +460 -0
- vllm/entrypoints/openai/serving_chat.py +392 -0
- vllm/entrypoints/openai/serving_completion.py +347 -0
- vllm/entrypoints/openai/serving_engine.py +234 -0
- vllm/envs.py +217 -0
- vllm/executor/__init__.py +0 -0
- vllm/executor/cpu_executor.py +152 -0
- vllm/executor/distributed_gpu_executor.py +115 -0
- vllm/executor/executor_base.py +115 -0
- vllm/executor/gpu_executor.py +150 -0
- vllm/executor/multiproc_worker_utils.py +263 -0
- vllm/executor/neuron_executor.py +91 -0
- vllm/executor/ray_gpu_executor.py +327 -0
- vllm/executor/ray_utils.py +119 -0
- vllm/logger.py +153 -0
- vllm/logging/__init__.py +5 -0
- vllm/logging/formatter.py +15 -0
- vllm/lora/__init__.py +0 -0
- vllm/lora/fully_sharded_layers.py +262 -0
- vllm/lora/layers.py +1181 -0
- vllm/lora/lora.py +167 -0
- vllm/lora/models.py +645 -0
- vllm/lora/punica.py +213 -0
- vllm/lora/request.py +32 -0
- vllm/lora/utils.py +98 -0
- vllm/lora/worker_manager.py +251 -0
- vllm/model_executor/__init__.py +7 -0
- vllm/model_executor/guided_decoding/__init__.py +25 -0
- vllm/model_executor/guided_decoding/lm_format_enforcer_decoding.py +70 -0
- vllm/model_executor/guided_decoding/outlines_decoding.py +130 -0
- vllm/model_executor/guided_decoding/outlines_logits_processors.py +184 -0
- vllm/model_executor/layers/__init__.py +0 -0
- vllm/model_executor/layers/activation.py +173 -0
- vllm/model_executor/layers/fused_moe/__init__.py +7 -0
- vllm/model_executor/layers/fused_moe/configs/E=16,N=1344,device_name=NVIDIA_A100-SXM4-40GB.json +146 -0
- vllm/model_executor/layers/fused_moe/configs/E=16,N=1344,device_name=NVIDIA_A100-SXM4-80GB.json +146 -0
- vllm/model_executor/layers/fused_moe/configs/E=16,N=1344,device_name=NVIDIA_H100_80GB_HBM3.json +146 -0
- vllm/model_executor/layers/fused_moe/configs/E=16,N=2688,device_name=NVIDIA_A100-SXM4-80GB.json +146 -0
- vllm/model_executor/layers/fused_moe/configs/E=16,N=2688,device_name=NVIDIA_H100_80GB_HBM3.json +146 -0
- vllm/model_executor/layers/fused_moe/configs/E=8,N=1792,device_name=NVIDIA_A100-SXM4-40GB.json +146 -0
- vllm/model_executor/layers/fused_moe/configs/E=8,N=1792,device_name=NVIDIA_A100-SXM4-80GB.json +146 -0
- vllm/model_executor/layers/fused_moe/configs/E=8,N=1792,device_name=NVIDIA_H100_80GB_HBM3.json +146 -0
- vllm/model_executor/layers/fused_moe/configs/E=8,N=2048,device_name=NVIDIA_A100-SXM4-80GB.json +146 -0
- vllm/model_executor/layers/fused_moe/configs/E=8,N=2048,device_name=NVIDIA_H100_80GB_HBM3.json +146 -0
- vllm/model_executor/layers/fused_moe/configs/E=8,N=3584,device_name=NVIDIA_A100-SXM4-40GB.json +146 -0
- vllm/model_executor/layers/fused_moe/configs/E=8,N=3584,device_name=NVIDIA_A100-SXM4-80GB.json +146 -0
- vllm/model_executor/layers/fused_moe/configs/E=8,N=3584,device_name=NVIDIA_H100_80GB_HBM3,dtype=float8.json +140 -0
- vllm/model_executor/layers/fused_moe/configs/E=8,N=3584,device_name=NVIDIA_H100_80GB_HBM3.json +146 -0
- vllm/model_executor/layers/fused_moe/configs/E=8,N=4096,device_name=NVIDIA_A100-SXM4-80GB.json +146 -0
- vllm/model_executor/layers/fused_moe/configs/E=8,N=4096,device_name=NVIDIA_H100_80GB_HBM3.json +146 -0
- vllm/model_executor/layers/fused_moe/configs/E=8,N=7168,device_name=NVIDIA_A100-SXM4-80GB.json +146 -0
- vllm/model_executor/layers/fused_moe/configs/E=8,N=7168,device_name=NVIDIA_H100_80GB_HBM3,dtype=float8.json +146 -0
- vllm/model_executor/layers/fused_moe/configs/E=8,N=7168,device_name=NVIDIA_H100_80GB_HBM3.json +146 -0
- vllm/model_executor/layers/fused_moe/fused_moe.py +479 -0
- vllm/model_executor/layers/layernorm.py +71 -0
- vllm/model_executor/layers/linear.py +709 -0
- vllm/model_executor/layers/logits_processor.py +115 -0
- vllm/model_executor/layers/ops/__init__.py +0 -0
- vllm/model_executor/layers/ops/rand.py +157 -0
- vllm/model_executor/layers/ops/sample.py +406 -0
- vllm/model_executor/layers/quantization/__init__.py +35 -0
- vllm/model_executor/layers/quantization/aqlm.py +376 -0
- vllm/model_executor/layers/quantization/awq.py +175 -0
- vllm/model_executor/layers/quantization/base_config.py +97 -0
- vllm/model_executor/layers/quantization/fp8.py +265 -0
- vllm/model_executor/layers/quantization/gptq.py +224 -0
- vllm/model_executor/layers/quantization/gptq_marlin.py +438 -0
- vllm/model_executor/layers/quantization/marlin.py +227 -0
- vllm/model_executor/layers/quantization/schema.py +84 -0
- vllm/model_executor/layers/quantization/squeezellm.py +137 -0
- vllm/model_executor/layers/rejection_sampler.py +405 -0
- vllm/model_executor/layers/rotary_embedding.py +525 -0
- vllm/model_executor/layers/sampler.py +1051 -0
- vllm/model_executor/layers/vocab_parallel_embedding.py +155 -0
- vllm/model_executor/model_loader/__init__.py +30 -0
- vllm/model_executor/model_loader/loader.py +362 -0
- vllm/model_executor/model_loader/neuron.py +136 -0
- vllm/model_executor/model_loader/tensorizer.py +368 -0
- vllm/model_executor/model_loader/utils.py +41 -0
- vllm/model_executor/model_loader/weight_utils.py +372 -0
- vllm/model_executor/models/__init__.py +119 -0
- vllm/model_executor/models/baichuan.py +410 -0
- vllm/model_executor/models/bloom.py +327 -0
- vllm/model_executor/models/chatglm.py +386 -0
- vllm/model_executor/models/commandr.py +373 -0
- vllm/model_executor/models/dbrx.py +413 -0
- vllm/model_executor/models/decilm.py +122 -0
- vllm/model_executor/models/deepseek.py +438 -0
- vllm/model_executor/models/falcon.py +444 -0
- vllm/model_executor/models/gemma.py +393 -0
- vllm/model_executor/models/gpt2.py +266 -0
- vllm/model_executor/models/gpt_bigcode.py +274 -0
- vllm/model_executor/models/gpt_j.py +281 -0
- vllm/model_executor/models/gpt_neox.py +295 -0
- vllm/model_executor/models/internlm2.py +323 -0
- vllm/model_executor/models/jais.py +333 -0
- vllm/model_executor/models/llama.py +442 -0
- vllm/model_executor/models/llava.py +239 -0
- vllm/model_executor/models/minicpm.py +531 -0
- vllm/model_executor/models/mixtral.py +583 -0
- vllm/model_executor/models/mixtral_quant.py +404 -0
- vllm/model_executor/models/mpt.py +295 -0
- vllm/model_executor/models/olmo.py +356 -0
- vllm/model_executor/models/opt.py +349 -0
- vllm/model_executor/models/orion.py +319 -0
- vllm/model_executor/models/phi.py +300 -0
- vllm/model_executor/models/qwen.py +284 -0
- vllm/model_executor/models/qwen2.py +367 -0
- vllm/model_executor/models/qwen2_moe.py +447 -0
- vllm/model_executor/models/stablelm.py +301 -0
- vllm/model_executor/models/starcoder2.py +302 -0
- vllm/model_executor/models/xverse.py +366 -0
- vllm/model_executor/sampling_metadata.py +588 -0
- vllm/model_executor/utils.py +35 -0
- vllm/outputs.py +150 -0
- vllm/py.typed +2 -0
- vllm/sampling_params.py +340 -0
- vllm/sequence.py +766 -0
- vllm/spec_decode/__init__.py +0 -0
- vllm/spec_decode/batch_expansion.py +397 -0
- vllm/spec_decode/interfaces.py +73 -0
- vllm/spec_decode/metrics.py +191 -0
- vllm/spec_decode/multi_step_worker.py +203 -0
- vllm/spec_decode/ngram_worker.py +176 -0
- vllm/spec_decode/spec_decode_worker.py +472 -0
- vllm/spec_decode/top1_proposer.py +200 -0
- vllm/spec_decode/util.py +228 -0
- vllm/test_utils.py +41 -0
- vllm/transformers_utils/__init__.py +0 -0
- vllm/transformers_utils/config.py +58 -0
- vllm/transformers_utils/configs/__init__.py +16 -0
- vllm/transformers_utils/configs/chatglm.py +68 -0
- vllm/transformers_utils/configs/dbrx.py +278 -0
- vllm/transformers_utils/configs/falcon.py +87 -0
- vllm/transformers_utils/configs/jais.py +236 -0
- vllm/transformers_utils/configs/mpt.py +178 -0
- vllm/transformers_utils/detokenizer.py +313 -0
- vllm/transformers_utils/tokenizer.py +149 -0
- vllm/transformers_utils/tokenizer_group/__init__.py +33 -0
- vllm/transformers_utils/tokenizer_group/base_tokenizer_group.py +55 -0
- vllm/transformers_utils/tokenizer_group/ray_tokenizer_group.py +169 -0
- vllm/transformers_utils/tokenizer_group/tokenizer_group.py +78 -0
- vllm/transformers_utils/tokenizers/__init__.py +5 -0
- vllm/transformers_utils/tokenizers/baichuan.py +255 -0
- vllm/usage/__init__.py +0 -0
- vllm/usage/usage_lib.py +209 -0
- vllm/utils.py +677 -0
- vllm/worker/__init__.py +0 -0
- vllm/worker/cache_engine.py +105 -0
- vllm/worker/cpu_model_runner.py +346 -0
- vllm/worker/cpu_worker.py +321 -0
- vllm/worker/model_runner.py +1168 -0
- vllm/worker/neuron_model_runner.py +196 -0
- vllm/worker/neuron_worker.py +98 -0
- vllm/worker/worker.py +345 -0
- vllm/worker/worker_base.py +146 -0
- vllm_npu-0.4.2.dist-info/LICENSE +201 -0
- vllm_npu-0.4.2.dist-info/METADATA +173 -0
- vllm_npu-0.4.2.dist-info/RECORD +219 -0
- vllm_npu-0.4.2.dist-info/WHEEL +5 -0
- vllm_npu-0.4.2.dist-info/top_level.txt +1 -0
@@ -0,0 +1,347 @@
|
|
1
|
+
import time
|
2
|
+
from typing import (AsyncGenerator, AsyncIterator, Callable, Dict, List,
|
3
|
+
Optional, Tuple)
|
4
|
+
|
5
|
+
from fastapi import Request
|
6
|
+
|
7
|
+
from vllm.engine.async_llm_engine import AsyncLLMEngine
|
8
|
+
from vllm.entrypoints.openai.protocol import (CompletionRequest,
|
9
|
+
CompletionResponse,
|
10
|
+
CompletionResponseChoice,
|
11
|
+
CompletionResponseStreamChoice,
|
12
|
+
CompletionStreamResponse,
|
13
|
+
LogProbs, UsageInfo)
|
14
|
+
from vllm.entrypoints.openai.serving_engine import (LoRAModulePath,
|
15
|
+
OpenAIServing)
|
16
|
+
from vllm.logger import init_logger
|
17
|
+
from vllm.model_executor.guided_decoding import (
|
18
|
+
get_guided_decoding_logits_processor)
|
19
|
+
from vllm.outputs import RequestOutput
|
20
|
+
from vllm.utils import merge_async_iterators, random_uuid
|
21
|
+
|
22
|
+
logger = init_logger(__name__)
|
23
|
+
|
24
|
+
TypeTokenIDs = List[int]
|
25
|
+
TypeTopLogProbs = List[Optional[Dict[int, float]]]
|
26
|
+
TypeCreateLogProbsFn = Callable[
|
27
|
+
[TypeTokenIDs, TypeTopLogProbs, Optional[int], int], LogProbs]
|
28
|
+
|
29
|
+
|
30
|
+
def parse_prompt_format(prompt) -> Tuple[bool, list]:
|
31
|
+
# get the prompt, openai supports the following
|
32
|
+
# "a string, array of strings, array of tokens, or array of token arrays."
|
33
|
+
prompt_is_tokens = False
|
34
|
+
prompts = [prompt] # case 1: a string
|
35
|
+
if isinstance(prompt, list):
|
36
|
+
if len(prompt) == 0:
|
37
|
+
raise ValueError("please provide at least one prompt")
|
38
|
+
elif isinstance(prompt[0], str):
|
39
|
+
prompt_is_tokens = False
|
40
|
+
prompts = prompt # case 2: array of strings
|
41
|
+
elif isinstance(prompt[0], int):
|
42
|
+
prompt_is_tokens = True
|
43
|
+
prompts = [prompt] # case 3: array of tokens
|
44
|
+
elif isinstance(prompt[0], list) and isinstance(prompt[0][0], int):
|
45
|
+
prompt_is_tokens = True
|
46
|
+
prompts = prompt # case 4: array of token arrays
|
47
|
+
else:
|
48
|
+
raise ValueError("prompt must be a string, array of strings, "
|
49
|
+
"array of tokens, or array of token arrays")
|
50
|
+
return prompt_is_tokens, prompts
|
51
|
+
|
52
|
+
|
53
|
+
class OpenAIServingCompletion(OpenAIServing):
|
54
|
+
|
55
|
+
def __init__(self,
|
56
|
+
engine: AsyncLLMEngine,
|
57
|
+
served_model_names: List[str],
|
58
|
+
lora_modules: Optional[List[LoRAModulePath]] = None):
|
59
|
+
super().__init__(engine=engine,
|
60
|
+
served_model_names=served_model_names,
|
61
|
+
lora_modules=lora_modules)
|
62
|
+
|
63
|
+
async def create_completion(self, request: CompletionRequest,
|
64
|
+
raw_request: Request):
|
65
|
+
"""Completion API similar to OpenAI's API.
|
66
|
+
|
67
|
+
See https://platform.openai.com/docs/api-reference/completions/create
|
68
|
+
for the API specification. This API mimics the OpenAI Completion API.
|
69
|
+
|
70
|
+
NOTE: Currently we do not support the following feature:
|
71
|
+
- suffix (the language models we currently support do not support
|
72
|
+
suffix)
|
73
|
+
"""
|
74
|
+
error_check_ret = await self._check_model(request)
|
75
|
+
if error_check_ret is not None:
|
76
|
+
return error_check_ret
|
77
|
+
|
78
|
+
# Return error for unsupported features.
|
79
|
+
if request.suffix is not None:
|
80
|
+
return self.create_error_response(
|
81
|
+
"suffix is not currently supported")
|
82
|
+
|
83
|
+
model_name = self.served_model_names[0]
|
84
|
+
request_id = f"cmpl-{random_uuid()}"
|
85
|
+
created_time = int(time.time())
|
86
|
+
|
87
|
+
# Schedule the request and get the result generator.
|
88
|
+
generators: List[AsyncIterator[RequestOutput]] = []
|
89
|
+
try:
|
90
|
+
sampling_params = request.to_sampling_params()
|
91
|
+
lora_request = self._maybe_get_lora(request)
|
92
|
+
decoding_config = await self.engine.get_decoding_config()
|
93
|
+
guided_decoding_backend = request.guided_decoding_backend \
|
94
|
+
or decoding_config.guided_decoding_backend
|
95
|
+
guided_decode_logit_processor = (
|
96
|
+
await get_guided_decoding_logits_processor(
|
97
|
+
guided_decoding_backend, request, await
|
98
|
+
self.engine.get_tokenizer()))
|
99
|
+
if guided_decode_logit_processor is not None:
|
100
|
+
if sampling_params.logits_processors is None:
|
101
|
+
sampling_params.logits_processors = []
|
102
|
+
sampling_params.logits_processors.append(
|
103
|
+
guided_decode_logit_processor)
|
104
|
+
prompt_is_tokens, prompts = parse_prompt_format(request.prompt)
|
105
|
+
|
106
|
+
for i, prompt in enumerate(prompts):
|
107
|
+
if prompt_is_tokens:
|
108
|
+
prompt_formats = self._validate_prompt_and_tokenize(
|
109
|
+
request,
|
110
|
+
prompt_ids=prompt,
|
111
|
+
truncate_prompt_tokens=sampling_params.
|
112
|
+
truncate_prompt_tokens)
|
113
|
+
else:
|
114
|
+
prompt_formats = self._validate_prompt_and_tokenize(
|
115
|
+
request,
|
116
|
+
prompt=prompt,
|
117
|
+
truncate_prompt_tokens=sampling_params.
|
118
|
+
truncate_prompt_tokens)
|
119
|
+
prompt_ids, prompt_text = prompt_formats
|
120
|
+
|
121
|
+
generators.append(
|
122
|
+
self.engine.generate(prompt_text,
|
123
|
+
sampling_params,
|
124
|
+
f"{request_id}-{i}",
|
125
|
+
prompt_token_ids=prompt_ids,
|
126
|
+
lora_request=lora_request))
|
127
|
+
except ValueError as e:
|
128
|
+
# TODO: Use a vllm-specific Validation Error
|
129
|
+
return self.create_error_response(str(e))
|
130
|
+
|
131
|
+
result_generator: AsyncIterator[Tuple[
|
132
|
+
int, RequestOutput]] = merge_async_iterators(*generators)
|
133
|
+
|
134
|
+
# Similar to the OpenAI API, when n != best_of, we do not stream the
|
135
|
+
# results. In addition, we do not stream the results when use
|
136
|
+
# beam search.
|
137
|
+
stream = (request.stream
|
138
|
+
and (request.best_of is None or request.n == request.best_of)
|
139
|
+
and not request.use_beam_search)
|
140
|
+
|
141
|
+
# Streaming response
|
142
|
+
if stream:
|
143
|
+
return self.completion_stream_generator(request,
|
144
|
+
raw_request,
|
145
|
+
result_generator,
|
146
|
+
request_id,
|
147
|
+
created_time,
|
148
|
+
model_name,
|
149
|
+
num_prompts=len(prompts))
|
150
|
+
|
151
|
+
# Non-streaming response
|
152
|
+
final_res_batch: List[Optional[RequestOutput]] = [None] * len(prompts)
|
153
|
+
try:
|
154
|
+
async for i, res in result_generator:
|
155
|
+
if await raw_request.is_disconnected():
|
156
|
+
# Abort the request if the client disconnects.
|
157
|
+
await self.engine.abort(f"{request_id}-{i}")
|
158
|
+
return self.create_error_response("Client disconnected")
|
159
|
+
final_res_batch[i] = res
|
160
|
+
response = self.request_output_to_completion_response(
|
161
|
+
final_res_batch, request, request_id, created_time, model_name)
|
162
|
+
except ValueError as e:
|
163
|
+
# TODO: Use a vllm-specific Validation Error
|
164
|
+
return self.create_error_response(str(e))
|
165
|
+
|
166
|
+
# When user requests streaming but we don't stream, we still need to
|
167
|
+
# return a streaming response with a single event.
|
168
|
+
if request.stream:
|
169
|
+
response_json = response.model_dump_json()
|
170
|
+
|
171
|
+
async def fake_stream_generator() -> AsyncGenerator[str, None]:
|
172
|
+
yield f"data: {response_json}\n\n"
|
173
|
+
yield "data: [DONE]\n\n"
|
174
|
+
|
175
|
+
return fake_stream_generator()
|
176
|
+
|
177
|
+
return response
|
178
|
+
|
179
|
+
async def completion_stream_generator(
|
180
|
+
self,
|
181
|
+
request: CompletionRequest,
|
182
|
+
raw_request: Request,
|
183
|
+
result_generator: AsyncIterator[Tuple[int, RequestOutput]],
|
184
|
+
request_id: str,
|
185
|
+
created_time: int,
|
186
|
+
model_name: str,
|
187
|
+
num_prompts: int,
|
188
|
+
) -> AsyncGenerator[str, None]:
|
189
|
+
assert request.n is not None
|
190
|
+
previous_texts = [""] * request.n * num_prompts
|
191
|
+
previous_num_tokens = [0] * request.n * num_prompts
|
192
|
+
has_echoed = [False] * request.n * num_prompts
|
193
|
+
|
194
|
+
try:
|
195
|
+
async for prompt_idx, res in result_generator:
|
196
|
+
|
197
|
+
# Abort the request if the client disconnects.
|
198
|
+
if await raw_request.is_disconnected():
|
199
|
+
await self.engine.abort(f"{request_id}-{prompt_idx}")
|
200
|
+
raise StopAsyncIteration()
|
201
|
+
|
202
|
+
for output in res.outputs:
|
203
|
+
i = output.index + prompt_idx * request.n
|
204
|
+
# TODO(simon): optimize the performance by avoiding full
|
205
|
+
# text O(n^2) sending.
|
206
|
+
|
207
|
+
assert request.max_tokens is not None
|
208
|
+
if request.echo and request.max_tokens == 0:
|
209
|
+
# only return the prompt
|
210
|
+
delta_text = res.prompt
|
211
|
+
delta_token_ids = res.prompt_token_ids
|
212
|
+
top_logprobs = res.prompt_logprobs
|
213
|
+
has_echoed[i] = True
|
214
|
+
elif (request.echo and request.max_tokens > 0
|
215
|
+
and not has_echoed[i]):
|
216
|
+
# echo the prompt and first token
|
217
|
+
delta_text = res.prompt + output.text
|
218
|
+
delta_token_ids = (res.prompt_token_ids +
|
219
|
+
output.token_ids)
|
220
|
+
top_logprobs = res.prompt_logprobs + (output.logprobs
|
221
|
+
or [])
|
222
|
+
has_echoed[i] = True
|
223
|
+
else:
|
224
|
+
# return just the delta
|
225
|
+
delta_text = output.text[len(previous_texts[i]):]
|
226
|
+
delta_token_ids = output.token_ids[
|
227
|
+
previous_num_tokens[i]:]
|
228
|
+
top_logprobs = output.logprobs[previous_num_tokens[
|
229
|
+
i]:] if output.logprobs else None
|
230
|
+
|
231
|
+
if request.logprobs is not None:
|
232
|
+
logprobs = self._create_logprobs(
|
233
|
+
token_ids=delta_token_ids,
|
234
|
+
top_logprobs=top_logprobs,
|
235
|
+
num_output_top_logprobs=request.logprobs,
|
236
|
+
initial_text_offset=len(previous_texts[i]),
|
237
|
+
)
|
238
|
+
else:
|
239
|
+
logprobs = None
|
240
|
+
|
241
|
+
previous_texts[i] = output.text
|
242
|
+
previous_num_tokens[i] = len(output.token_ids)
|
243
|
+
finish_reason = output.finish_reason
|
244
|
+
stop_reason = output.stop_reason
|
245
|
+
if output.finish_reason is not None: # return final usage
|
246
|
+
prompt_tokens = len(res.prompt_token_ids)
|
247
|
+
completion_tokens = len(output.token_ids)
|
248
|
+
final_usage = UsageInfo(
|
249
|
+
prompt_tokens=prompt_tokens,
|
250
|
+
completion_tokens=completion_tokens,
|
251
|
+
total_tokens=prompt_tokens + completion_tokens,
|
252
|
+
)
|
253
|
+
else:
|
254
|
+
final_usage = None
|
255
|
+
response_json = CompletionStreamResponse(
|
256
|
+
id=request_id,
|
257
|
+
created=created_time,
|
258
|
+
model=model_name,
|
259
|
+
choices=[
|
260
|
+
CompletionResponseStreamChoice(
|
261
|
+
index=i,
|
262
|
+
text=delta_text,
|
263
|
+
logprobs=logprobs,
|
264
|
+
finish_reason=finish_reason,
|
265
|
+
stop_reason=stop_reason,
|
266
|
+
)
|
267
|
+
],
|
268
|
+
usage=final_usage,
|
269
|
+
).model_dump_json(exclude_unset=True)
|
270
|
+
yield f"data: {response_json}\n\n"
|
271
|
+
except ValueError as e:
|
272
|
+
# TODO: Use a vllm-specific Validation Error
|
273
|
+
data = self.create_streaming_error_response(str(e))
|
274
|
+
yield f"data: {data}\n\n"
|
275
|
+
yield "data: [DONE]\n\n"
|
276
|
+
|
277
|
+
def request_output_to_completion_response(
|
278
|
+
self,
|
279
|
+
final_res_batch: List[RequestOutput],
|
280
|
+
request: CompletionRequest,
|
281
|
+
request_id: str,
|
282
|
+
created_time: int,
|
283
|
+
model_name: str,
|
284
|
+
) -> CompletionResponse:
|
285
|
+
choices: List[CompletionResponseChoice] = []
|
286
|
+
num_prompt_tokens = 0
|
287
|
+
num_generated_tokens = 0
|
288
|
+
for final_res in final_res_batch:
|
289
|
+
assert final_res is not None
|
290
|
+
prompt_token_ids = final_res.prompt_token_ids
|
291
|
+
prompt_logprobs = final_res.prompt_logprobs
|
292
|
+
prompt_text = final_res.prompt
|
293
|
+
|
294
|
+
for output in final_res.outputs:
|
295
|
+
assert request.max_tokens is not None
|
296
|
+
if request.echo and request.max_tokens == 0:
|
297
|
+
token_ids = prompt_token_ids
|
298
|
+
top_logprobs = prompt_logprobs
|
299
|
+
output_text = prompt_text
|
300
|
+
elif request.echo and request.max_tokens > 0:
|
301
|
+
token_ids = prompt_token_ids + output.token_ids
|
302
|
+
top_logprobs = (prompt_logprobs + output.logprobs
|
303
|
+
if request.logprobs else None)
|
304
|
+
output_text = prompt_text + output.text
|
305
|
+
else:
|
306
|
+
token_ids = output.token_ids
|
307
|
+
top_logprobs = output.logprobs
|
308
|
+
output_text = output.text
|
309
|
+
|
310
|
+
if request.logprobs is not None:
|
311
|
+
assert top_logprobs is not None, (
|
312
|
+
"top_logprobs must be provided when logprobs "
|
313
|
+
"is requested")
|
314
|
+
logprobs = self._create_logprobs(
|
315
|
+
token_ids=token_ids,
|
316
|
+
top_logprobs=top_logprobs,
|
317
|
+
num_output_top_logprobs=request.logprobs,
|
318
|
+
)
|
319
|
+
else:
|
320
|
+
logprobs = None
|
321
|
+
|
322
|
+
choice_data = CompletionResponseChoice(
|
323
|
+
index=len(choices),
|
324
|
+
text=output_text,
|
325
|
+
logprobs=logprobs,
|
326
|
+
finish_reason=output.finish_reason,
|
327
|
+
stop_reason=output.stop_reason,
|
328
|
+
)
|
329
|
+
choices.append(choice_data)
|
330
|
+
|
331
|
+
num_prompt_tokens += len(prompt_token_ids)
|
332
|
+
num_generated_tokens += sum(
|
333
|
+
len(output.token_ids) for output in final_res.outputs)
|
334
|
+
|
335
|
+
usage = UsageInfo(
|
336
|
+
prompt_tokens=num_prompt_tokens,
|
337
|
+
completion_tokens=num_generated_tokens,
|
338
|
+
total_tokens=num_prompt_tokens + num_generated_tokens,
|
339
|
+
)
|
340
|
+
|
341
|
+
return CompletionResponse(
|
342
|
+
id=request_id,
|
343
|
+
created=created_time,
|
344
|
+
model=model_name,
|
345
|
+
choices=choices,
|
346
|
+
usage=usage,
|
347
|
+
)
|
@@ -0,0 +1,234 @@
|
|
1
|
+
import asyncio
|
2
|
+
import json
|
3
|
+
from dataclasses import dataclass
|
4
|
+
from http import HTTPStatus
|
5
|
+
from typing import Any, Awaitable, Dict, List, Optional, Tuple, Union
|
6
|
+
|
7
|
+
from pydantic import Field
|
8
|
+
from transformers import PreTrainedTokenizer, PreTrainedTokenizerFast
|
9
|
+
from typing_extensions import Annotated
|
10
|
+
|
11
|
+
from vllm.engine.async_llm_engine import AsyncLLMEngine
|
12
|
+
from vllm.entrypoints.openai.protocol import (ChatCompletionRequest,
|
13
|
+
CompletionRequest, ErrorResponse,
|
14
|
+
LogProbs, ModelCard, ModelList,
|
15
|
+
ModelPermission)
|
16
|
+
from vllm.logger import init_logger
|
17
|
+
from vllm.lora.request import LoRARequest
|
18
|
+
from vllm.sequence import Logprob
|
19
|
+
from vllm.transformers_utils.tokenizer import get_tokenizer
|
20
|
+
|
21
|
+
logger = init_logger(__name__)
|
22
|
+
|
23
|
+
|
24
|
+
@dataclass
|
25
|
+
class LoRAModulePath:
|
26
|
+
name: str
|
27
|
+
local_path: str
|
28
|
+
|
29
|
+
|
30
|
+
class OpenAIServing:
|
31
|
+
|
32
|
+
def __init__(self,
|
33
|
+
engine: AsyncLLMEngine,
|
34
|
+
served_model_names: List[str],
|
35
|
+
lora_modules: Optional[List[LoRAModulePath]],
|
36
|
+
await_post_init: Optional[Awaitable[Any]] = None):
|
37
|
+
self.engine = engine
|
38
|
+
self.served_model_names = served_model_names
|
39
|
+
if lora_modules is None:
|
40
|
+
self.lora_requests = []
|
41
|
+
else:
|
42
|
+
self.lora_requests = [
|
43
|
+
LoRARequest(
|
44
|
+
lora_name=lora.name,
|
45
|
+
lora_int_id=i,
|
46
|
+
lora_local_path=lora.local_path,
|
47
|
+
) for i, lora in enumerate(lora_modules, start=1)
|
48
|
+
]
|
49
|
+
|
50
|
+
self.max_model_len = 0
|
51
|
+
# Lazy initialized
|
52
|
+
self.tokenizer: Union[PreTrainedTokenizer, PreTrainedTokenizerFast]
|
53
|
+
|
54
|
+
try:
|
55
|
+
event_loop = asyncio.get_running_loop()
|
56
|
+
except RuntimeError:
|
57
|
+
event_loop = None
|
58
|
+
|
59
|
+
if event_loop is not None and event_loop.is_running():
|
60
|
+
# If the current is instanced by Ray Serve,
|
61
|
+
# there is already a running event loop
|
62
|
+
event_loop.create_task(self._post_init(await_post_init))
|
63
|
+
else:
|
64
|
+
# When using single vLLM without engine_use_ray
|
65
|
+
asyncio.run(self._post_init(await_post_init))
|
66
|
+
|
67
|
+
async def _post_init(self, await_post_init):
|
68
|
+
engine_model_config = await self.engine.get_model_config()
|
69
|
+
self.max_model_len = engine_model_config.max_model_len
|
70
|
+
|
71
|
+
# A separate tokenizer to map token IDs to strings.
|
72
|
+
self.tokenizer = get_tokenizer(
|
73
|
+
engine_model_config.tokenizer,
|
74
|
+
tokenizer_mode=engine_model_config.tokenizer_mode,
|
75
|
+
tokenizer_revision=engine_model_config.tokenizer_revision,
|
76
|
+
trust_remote_code=engine_model_config.trust_remote_code,
|
77
|
+
truncation_side="left")
|
78
|
+
|
79
|
+
if await_post_init is not None:
|
80
|
+
await await_post_init
|
81
|
+
|
82
|
+
async def show_available_models(self) -> ModelList:
|
83
|
+
"""Show available models. Right now we only have one model."""
|
84
|
+
model_cards = [
|
85
|
+
ModelCard(id=served_model_name,
|
86
|
+
root=self.served_model_names[0],
|
87
|
+
permission=[ModelPermission()])
|
88
|
+
for served_model_name in self.served_model_names
|
89
|
+
]
|
90
|
+
lora_cards = [
|
91
|
+
ModelCard(id=lora.lora_name,
|
92
|
+
root=self.served_model_names[0],
|
93
|
+
permission=[ModelPermission()])
|
94
|
+
for lora in self.lora_requests
|
95
|
+
]
|
96
|
+
model_cards.extend(lora_cards)
|
97
|
+
return ModelList(data=model_cards)
|
98
|
+
|
99
|
+
def _create_logprobs(
|
100
|
+
self,
|
101
|
+
token_ids: List[int],
|
102
|
+
top_logprobs: List[Optional[Dict[int, Logprob]]],
|
103
|
+
num_output_top_logprobs: Optional[int] = None,
|
104
|
+
initial_text_offset: int = 0,
|
105
|
+
) -> LogProbs:
|
106
|
+
"""Create OpenAI-style logprobs."""
|
107
|
+
logprobs = LogProbs()
|
108
|
+
last_token_len = 0
|
109
|
+
if num_output_top_logprobs:
|
110
|
+
logprobs.top_logprobs = []
|
111
|
+
|
112
|
+
for i, token_id in enumerate(token_ids):
|
113
|
+
step_top_logprobs = top_logprobs[i]
|
114
|
+
if step_top_logprobs is None:
|
115
|
+
token = self.tokenizer.decode(token_id)
|
116
|
+
logprobs.tokens.append(token)
|
117
|
+
logprobs.token_logprobs.append(None)
|
118
|
+
assert logprobs.top_logprobs is not None
|
119
|
+
logprobs.top_logprobs.append(None)
|
120
|
+
else:
|
121
|
+
token_logprob = step_top_logprobs[token_id].logprob
|
122
|
+
token = step_top_logprobs[token_id].decoded_token
|
123
|
+
logprobs.tokens.append(token)
|
124
|
+
logprobs.token_logprobs.append(token_logprob)
|
125
|
+
|
126
|
+
if num_output_top_logprobs:
|
127
|
+
assert logprobs.top_logprobs is not None
|
128
|
+
logprobs.top_logprobs.append({
|
129
|
+
# Convert float("-inf") to the
|
130
|
+
# JSON-serializable float that OpenAI uses
|
131
|
+
p.decoded_token: max(p.logprob, -9999.0)
|
132
|
+
for i, p in step_top_logprobs.items()
|
133
|
+
} if step_top_logprobs else None)
|
134
|
+
|
135
|
+
if len(logprobs.text_offset) == 0:
|
136
|
+
logprobs.text_offset.append(initial_text_offset)
|
137
|
+
else:
|
138
|
+
logprobs.text_offset.append(logprobs.text_offset[-1] +
|
139
|
+
last_token_len)
|
140
|
+
last_token_len = len(token)
|
141
|
+
return logprobs
|
142
|
+
|
143
|
+
def create_error_response(
|
144
|
+
self,
|
145
|
+
message: str,
|
146
|
+
err_type: str = "BadRequestError",
|
147
|
+
status_code: HTTPStatus = HTTPStatus.BAD_REQUEST) -> ErrorResponse:
|
148
|
+
return ErrorResponse(message=message,
|
149
|
+
type=err_type,
|
150
|
+
code=status_code.value)
|
151
|
+
|
152
|
+
def create_streaming_error_response(
|
153
|
+
self,
|
154
|
+
message: str,
|
155
|
+
err_type: str = "BadRequestError",
|
156
|
+
status_code: HTTPStatus = HTTPStatus.BAD_REQUEST) -> str:
|
157
|
+
json_str = json.dumps({
|
158
|
+
"error":
|
159
|
+
self.create_error_response(message=message,
|
160
|
+
err_type=err_type,
|
161
|
+
status_code=status_code).model_dump()
|
162
|
+
})
|
163
|
+
return json_str
|
164
|
+
|
165
|
+
async def _check_model(
|
166
|
+
self, request: Union[CompletionRequest, ChatCompletionRequest]
|
167
|
+
) -> Optional[ErrorResponse]:
|
168
|
+
if request.model in self.served_model_names:
|
169
|
+
return None
|
170
|
+
if request.model in [lora.lora_name for lora in self.lora_requests]:
|
171
|
+
return None
|
172
|
+
return self.create_error_response(
|
173
|
+
message=f"The model `{request.model}` does not exist.",
|
174
|
+
err_type="NotFoundError",
|
175
|
+
status_code=HTTPStatus.NOT_FOUND)
|
176
|
+
|
177
|
+
def _maybe_get_lora(
|
178
|
+
self, request: Union[CompletionRequest, ChatCompletionRequest]
|
179
|
+
) -> Optional[LoRARequest]:
|
180
|
+
if request.model in self.served_model_names:
|
181
|
+
return None
|
182
|
+
for lora in self.lora_requests:
|
183
|
+
if request.model == lora.lora_name:
|
184
|
+
return lora
|
185
|
+
# if _check_model has been called earlier, this will be unreachable
|
186
|
+
raise ValueError(f"The model `{request.model}` does not exist.")
|
187
|
+
|
188
|
+
def _validate_prompt_and_tokenize(
|
189
|
+
self,
|
190
|
+
request: Union[ChatCompletionRequest, CompletionRequest],
|
191
|
+
prompt: Optional[str] = None,
|
192
|
+
prompt_ids: Optional[List[int]] = None,
|
193
|
+
truncate_prompt_tokens: Optional[Annotated[int, Field(ge=1)]] = None
|
194
|
+
) -> Tuple[List[int], str]:
|
195
|
+
if not (prompt or prompt_ids):
|
196
|
+
raise ValueError("Either prompt or prompt_ids should be provided.")
|
197
|
+
if (prompt and prompt_ids):
|
198
|
+
raise ValueError(
|
199
|
+
"Only one of prompt or prompt_ids should be provided.")
|
200
|
+
|
201
|
+
if prompt_ids is None:
|
202
|
+
tokenizer_kwargs = {} if truncate_prompt_tokens is None else {
|
203
|
+
"truncation": True,
|
204
|
+
"max_length": truncate_prompt_tokens,
|
205
|
+
}
|
206
|
+
input_ids = self.tokenizer(prompt, **tokenizer_kwargs).input_ids
|
207
|
+
elif truncate_prompt_tokens is not None:
|
208
|
+
input_ids = prompt_ids[-truncate_prompt_tokens:]
|
209
|
+
else:
|
210
|
+
input_ids = prompt_ids
|
211
|
+
|
212
|
+
input_text = prompt if prompt is not None else self.tokenizer.decode(
|
213
|
+
prompt_ids)
|
214
|
+
token_num = len(input_ids)
|
215
|
+
|
216
|
+
if request.max_tokens is None:
|
217
|
+
if token_num >= self.max_model_len:
|
218
|
+
raise ValueError(
|
219
|
+
f"This model's maximum context length is "
|
220
|
+
f"{self.max_model_len} tokens. However, you requested "
|
221
|
+
f"{token_num} tokens in the messages, "
|
222
|
+
f"Please reduce the length of the messages.", )
|
223
|
+
request.max_tokens = self.max_model_len - token_num
|
224
|
+
|
225
|
+
if token_num + request.max_tokens > self.max_model_len:
|
226
|
+
raise ValueError(
|
227
|
+
f"This model's maximum context length is "
|
228
|
+
f"{self.max_model_len} tokens. However, you requested "
|
229
|
+
f"{request.max_tokens + token_num} tokens "
|
230
|
+
f"({token_num} in the messages, "
|
231
|
+
f"{request.max_tokens} in the completion). "
|
232
|
+
f"Please reduce the length of the messages or completion.", )
|
233
|
+
else:
|
234
|
+
return input_ids, input_text
|