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.
Files changed (219) hide show
  1. vllm/__init__.py +23 -0
  2. vllm/_custom_ops.py +251 -0
  3. vllm/attention/__init__.py +13 -0
  4. vllm/attention/backends/__init__.py +0 -0
  5. vllm/attention/backends/abstract.py +127 -0
  6. vllm/attention/backends/flash_attn.py +271 -0
  7. vllm/attention/backends/flashinfer.py +220 -0
  8. vllm/attention/backends/rocm_flash_attn.py +374 -0
  9. vllm/attention/backends/torch_sdpa.py +250 -0
  10. vllm/attention/backends/xformers.py +393 -0
  11. vllm/attention/layer.py +56 -0
  12. vllm/attention/ops/__init__.py +0 -0
  13. vllm/attention/ops/paged_attn.py +216 -0
  14. vllm/attention/ops/prefix_prefill.py +792 -0
  15. vllm/attention/ops/triton_flash_attention.py +810 -0
  16. vllm/attention/selector.py +91 -0
  17. vllm/block.py +84 -0
  18. vllm/config.py +1225 -0
  19. vllm/core/__init__.py +0 -0
  20. vllm/core/block/__init__.py +0 -0
  21. vllm/core/block/block_table.py +295 -0
  22. vllm/core/block/common.py +199 -0
  23. vllm/core/block/cpu_gpu_block_allocator.py +228 -0
  24. vllm/core/block/interfaces.py +205 -0
  25. vllm/core/block/naive_block.py +318 -0
  26. vllm/core/block/prefix_caching_block.py +606 -0
  27. vllm/core/block_manager_v1.py +625 -0
  28. vllm/core/block_manager_v2.py +258 -0
  29. vllm/core/evictor_v1.py +105 -0
  30. vllm/core/evictor_v2.py +127 -0
  31. vllm/core/interfaces.py +113 -0
  32. vllm/core/policy.py +45 -0
  33. vllm/core/scheduler.py +1163 -0
  34. vllm/distributed/__init__.py +3 -0
  35. vllm/distributed/communication_op.py +237 -0
  36. vllm/distributed/device_communicators/__init__.py +0 -0
  37. vllm/distributed/device_communicators/custom_all_reduce.py +274 -0
  38. vllm/distributed/device_communicators/pynccl.py +287 -0
  39. vllm/distributed/device_communicators/pynccl_utils.py +66 -0
  40. vllm/distributed/parallel_state.py +339 -0
  41. vllm/distributed/utils.py +136 -0
  42. vllm/engine/__init__.py +0 -0
  43. vllm/engine/arg_utils.py +649 -0
  44. vllm/engine/async_llm_engine.py +737 -0
  45. vllm/engine/llm_engine.py +784 -0
  46. vllm/engine/metrics.py +368 -0
  47. vllm/engine/output_processor/__init__.py +0 -0
  48. vllm/engine/output_processor/interfaces.py +76 -0
  49. vllm/engine/output_processor/multi_step.py +142 -0
  50. vllm/engine/output_processor/single_step.py +284 -0
  51. vllm/engine/output_processor/stop_checker.py +101 -0
  52. vllm/engine/output_processor/util.py +19 -0
  53. vllm/entrypoints/__init__.py +0 -0
  54. vllm/entrypoints/api_server.py +119 -0
  55. vllm/entrypoints/llm.py +259 -0
  56. vllm/entrypoints/openai/__init__.py +0 -0
  57. vllm/entrypoints/openai/api_server.py +186 -0
  58. vllm/entrypoints/openai/cli_args.py +115 -0
  59. vllm/entrypoints/openai/protocol.py +460 -0
  60. vllm/entrypoints/openai/serving_chat.py +392 -0
  61. vllm/entrypoints/openai/serving_completion.py +347 -0
  62. vllm/entrypoints/openai/serving_engine.py +234 -0
  63. vllm/envs.py +217 -0
  64. vllm/executor/__init__.py +0 -0
  65. vllm/executor/cpu_executor.py +152 -0
  66. vllm/executor/distributed_gpu_executor.py +115 -0
  67. vllm/executor/executor_base.py +115 -0
  68. vllm/executor/gpu_executor.py +150 -0
  69. vllm/executor/multiproc_worker_utils.py +263 -0
  70. vllm/executor/neuron_executor.py +91 -0
  71. vllm/executor/ray_gpu_executor.py +327 -0
  72. vllm/executor/ray_utils.py +119 -0
  73. vllm/logger.py +153 -0
  74. vllm/logging/__init__.py +5 -0
  75. vllm/logging/formatter.py +15 -0
  76. vllm/lora/__init__.py +0 -0
  77. vllm/lora/fully_sharded_layers.py +262 -0
  78. vllm/lora/layers.py +1181 -0
  79. vllm/lora/lora.py +167 -0
  80. vllm/lora/models.py +645 -0
  81. vllm/lora/punica.py +213 -0
  82. vllm/lora/request.py +32 -0
  83. vllm/lora/utils.py +98 -0
  84. vllm/lora/worker_manager.py +251 -0
  85. vllm/model_executor/__init__.py +7 -0
  86. vllm/model_executor/guided_decoding/__init__.py +25 -0
  87. vllm/model_executor/guided_decoding/lm_format_enforcer_decoding.py +70 -0
  88. vllm/model_executor/guided_decoding/outlines_decoding.py +130 -0
  89. vllm/model_executor/guided_decoding/outlines_logits_processors.py +184 -0
  90. vllm/model_executor/layers/__init__.py +0 -0
  91. vllm/model_executor/layers/activation.py +173 -0
  92. vllm/model_executor/layers/fused_moe/__init__.py +7 -0
  93. vllm/model_executor/layers/fused_moe/configs/E=16,N=1344,device_name=NVIDIA_A100-SXM4-40GB.json +146 -0
  94. vllm/model_executor/layers/fused_moe/configs/E=16,N=1344,device_name=NVIDIA_A100-SXM4-80GB.json +146 -0
  95. vllm/model_executor/layers/fused_moe/configs/E=16,N=1344,device_name=NVIDIA_H100_80GB_HBM3.json +146 -0
  96. vllm/model_executor/layers/fused_moe/configs/E=16,N=2688,device_name=NVIDIA_A100-SXM4-80GB.json +146 -0
  97. vllm/model_executor/layers/fused_moe/configs/E=16,N=2688,device_name=NVIDIA_H100_80GB_HBM3.json +146 -0
  98. vllm/model_executor/layers/fused_moe/configs/E=8,N=1792,device_name=NVIDIA_A100-SXM4-40GB.json +146 -0
  99. vllm/model_executor/layers/fused_moe/configs/E=8,N=1792,device_name=NVIDIA_A100-SXM4-80GB.json +146 -0
  100. vllm/model_executor/layers/fused_moe/configs/E=8,N=1792,device_name=NVIDIA_H100_80GB_HBM3.json +146 -0
  101. vllm/model_executor/layers/fused_moe/configs/E=8,N=2048,device_name=NVIDIA_A100-SXM4-80GB.json +146 -0
  102. vllm/model_executor/layers/fused_moe/configs/E=8,N=2048,device_name=NVIDIA_H100_80GB_HBM3.json +146 -0
  103. vllm/model_executor/layers/fused_moe/configs/E=8,N=3584,device_name=NVIDIA_A100-SXM4-40GB.json +146 -0
  104. vllm/model_executor/layers/fused_moe/configs/E=8,N=3584,device_name=NVIDIA_A100-SXM4-80GB.json +146 -0
  105. vllm/model_executor/layers/fused_moe/configs/E=8,N=3584,device_name=NVIDIA_H100_80GB_HBM3,dtype=float8.json +140 -0
  106. vllm/model_executor/layers/fused_moe/configs/E=8,N=3584,device_name=NVIDIA_H100_80GB_HBM3.json +146 -0
  107. vllm/model_executor/layers/fused_moe/configs/E=8,N=4096,device_name=NVIDIA_A100-SXM4-80GB.json +146 -0
  108. vllm/model_executor/layers/fused_moe/configs/E=8,N=4096,device_name=NVIDIA_H100_80GB_HBM3.json +146 -0
  109. vllm/model_executor/layers/fused_moe/configs/E=8,N=7168,device_name=NVIDIA_A100-SXM4-80GB.json +146 -0
  110. vllm/model_executor/layers/fused_moe/configs/E=8,N=7168,device_name=NVIDIA_H100_80GB_HBM3,dtype=float8.json +146 -0
  111. vllm/model_executor/layers/fused_moe/configs/E=8,N=7168,device_name=NVIDIA_H100_80GB_HBM3.json +146 -0
  112. vllm/model_executor/layers/fused_moe/fused_moe.py +479 -0
  113. vllm/model_executor/layers/layernorm.py +71 -0
  114. vllm/model_executor/layers/linear.py +709 -0
  115. vllm/model_executor/layers/logits_processor.py +115 -0
  116. vllm/model_executor/layers/ops/__init__.py +0 -0
  117. vllm/model_executor/layers/ops/rand.py +157 -0
  118. vllm/model_executor/layers/ops/sample.py +406 -0
  119. vllm/model_executor/layers/quantization/__init__.py +35 -0
  120. vllm/model_executor/layers/quantization/aqlm.py +376 -0
  121. vllm/model_executor/layers/quantization/awq.py +175 -0
  122. vllm/model_executor/layers/quantization/base_config.py +97 -0
  123. vllm/model_executor/layers/quantization/fp8.py +265 -0
  124. vllm/model_executor/layers/quantization/gptq.py +224 -0
  125. vllm/model_executor/layers/quantization/gptq_marlin.py +438 -0
  126. vllm/model_executor/layers/quantization/marlin.py +227 -0
  127. vllm/model_executor/layers/quantization/schema.py +84 -0
  128. vllm/model_executor/layers/quantization/squeezellm.py +137 -0
  129. vllm/model_executor/layers/rejection_sampler.py +405 -0
  130. vllm/model_executor/layers/rotary_embedding.py +525 -0
  131. vllm/model_executor/layers/sampler.py +1051 -0
  132. vllm/model_executor/layers/vocab_parallel_embedding.py +155 -0
  133. vllm/model_executor/model_loader/__init__.py +30 -0
  134. vllm/model_executor/model_loader/loader.py +362 -0
  135. vllm/model_executor/model_loader/neuron.py +136 -0
  136. vllm/model_executor/model_loader/tensorizer.py +368 -0
  137. vllm/model_executor/model_loader/utils.py +41 -0
  138. vllm/model_executor/model_loader/weight_utils.py +372 -0
  139. vllm/model_executor/models/__init__.py +119 -0
  140. vllm/model_executor/models/baichuan.py +410 -0
  141. vllm/model_executor/models/bloom.py +327 -0
  142. vllm/model_executor/models/chatglm.py +386 -0
  143. vllm/model_executor/models/commandr.py +373 -0
  144. vllm/model_executor/models/dbrx.py +413 -0
  145. vllm/model_executor/models/decilm.py +122 -0
  146. vllm/model_executor/models/deepseek.py +438 -0
  147. vllm/model_executor/models/falcon.py +444 -0
  148. vllm/model_executor/models/gemma.py +393 -0
  149. vllm/model_executor/models/gpt2.py +266 -0
  150. vllm/model_executor/models/gpt_bigcode.py +274 -0
  151. vllm/model_executor/models/gpt_j.py +281 -0
  152. vllm/model_executor/models/gpt_neox.py +295 -0
  153. vllm/model_executor/models/internlm2.py +323 -0
  154. vllm/model_executor/models/jais.py +333 -0
  155. vllm/model_executor/models/llama.py +442 -0
  156. vllm/model_executor/models/llava.py +239 -0
  157. vllm/model_executor/models/minicpm.py +531 -0
  158. vllm/model_executor/models/mixtral.py +583 -0
  159. vllm/model_executor/models/mixtral_quant.py +404 -0
  160. vllm/model_executor/models/mpt.py +295 -0
  161. vllm/model_executor/models/olmo.py +356 -0
  162. vllm/model_executor/models/opt.py +349 -0
  163. vllm/model_executor/models/orion.py +319 -0
  164. vllm/model_executor/models/phi.py +300 -0
  165. vllm/model_executor/models/qwen.py +284 -0
  166. vllm/model_executor/models/qwen2.py +367 -0
  167. vllm/model_executor/models/qwen2_moe.py +447 -0
  168. vllm/model_executor/models/stablelm.py +301 -0
  169. vllm/model_executor/models/starcoder2.py +302 -0
  170. vllm/model_executor/models/xverse.py +366 -0
  171. vllm/model_executor/sampling_metadata.py +588 -0
  172. vllm/model_executor/utils.py +35 -0
  173. vllm/outputs.py +150 -0
  174. vllm/py.typed +2 -0
  175. vllm/sampling_params.py +340 -0
  176. vllm/sequence.py +766 -0
  177. vllm/spec_decode/__init__.py +0 -0
  178. vllm/spec_decode/batch_expansion.py +397 -0
  179. vllm/spec_decode/interfaces.py +73 -0
  180. vllm/spec_decode/metrics.py +191 -0
  181. vllm/spec_decode/multi_step_worker.py +203 -0
  182. vllm/spec_decode/ngram_worker.py +176 -0
  183. vllm/spec_decode/spec_decode_worker.py +472 -0
  184. vllm/spec_decode/top1_proposer.py +200 -0
  185. vllm/spec_decode/util.py +228 -0
  186. vllm/test_utils.py +41 -0
  187. vllm/transformers_utils/__init__.py +0 -0
  188. vllm/transformers_utils/config.py +58 -0
  189. vllm/transformers_utils/configs/__init__.py +16 -0
  190. vllm/transformers_utils/configs/chatglm.py +68 -0
  191. vllm/transformers_utils/configs/dbrx.py +278 -0
  192. vllm/transformers_utils/configs/falcon.py +87 -0
  193. vllm/transformers_utils/configs/jais.py +236 -0
  194. vllm/transformers_utils/configs/mpt.py +178 -0
  195. vllm/transformers_utils/detokenizer.py +313 -0
  196. vllm/transformers_utils/tokenizer.py +149 -0
  197. vllm/transformers_utils/tokenizer_group/__init__.py +33 -0
  198. vllm/transformers_utils/tokenizer_group/base_tokenizer_group.py +55 -0
  199. vllm/transformers_utils/tokenizer_group/ray_tokenizer_group.py +169 -0
  200. vllm/transformers_utils/tokenizer_group/tokenizer_group.py +78 -0
  201. vllm/transformers_utils/tokenizers/__init__.py +5 -0
  202. vllm/transformers_utils/tokenizers/baichuan.py +255 -0
  203. vllm/usage/__init__.py +0 -0
  204. vllm/usage/usage_lib.py +209 -0
  205. vllm/utils.py +677 -0
  206. vllm/worker/__init__.py +0 -0
  207. vllm/worker/cache_engine.py +105 -0
  208. vllm/worker/cpu_model_runner.py +346 -0
  209. vllm/worker/cpu_worker.py +321 -0
  210. vllm/worker/model_runner.py +1168 -0
  211. vllm/worker/neuron_model_runner.py +196 -0
  212. vllm/worker/neuron_worker.py +98 -0
  213. vllm/worker/worker.py +345 -0
  214. vllm/worker/worker_base.py +146 -0
  215. vllm_npu-0.4.2.dist-info/LICENSE +201 -0
  216. vllm_npu-0.4.2.dist-info/METADATA +173 -0
  217. vllm_npu-0.4.2.dist-info/RECORD +219 -0
  218. vllm_npu-0.4.2.dist-info/WHEEL +5 -0
  219. 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