29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324 | class Vllm(LLM):
r"""Vllm LLM.
该类在本地运行一个vLLM模型。
示例:
`pip install llama-index-llms-vllm`
```python
from llama_index.llms.vllm import Vllm
# 用于格式化为mistral指令的特定函数
def messages_to_prompt(messages):
prompt = "\n".join([str(x) for x in messages])
return f"<s>[INST] {prompt} [/INST] </s>\n"
def completion_to_prompt(completion):
return f"<s>[INST] {completion} [/INST] </s>\n"
llm = Vllm(
model="mistralai/Mistral-7B-Instruct-v0.1",
tensor_parallel_size=4,
max_new_tokens=256,
vllm_kwargs={"swap_space": 1, "gpu_memory_utilization": 0.5},
messages_to_prompt=messages_to_prompt,
completion_to_prompt=completion_to_prompt,
)
llm.complete(
"What is a black hole?"
)
```"""
model: Optional[str] = Field(description="The HuggingFace Model to use.")
temperature: float = Field(description="The temperature to use for sampling.")
tensor_parallel_size: Optional[int] = Field(
default=1,
description="The number of GPUs to use for distributed execution with tensor parallelism.",
)
trust_remote_code: Optional[bool] = Field(
default=True,
description="Trust remote code (e.g., from HuggingFace) when downloading the model and tokenizer.",
)
n: int = Field(
default=1,
description="Number of output sequences to return for the given prompt.",
)
best_of: Optional[int] = Field(
default=None,
description="Number of output sequences that are generated from the prompt.",
)
presence_penalty: float = Field(
default=0.0,
description="Float that penalizes new tokens based on whether they appear in the generated text so far.",
)
frequency_penalty: float = Field(
default=0.0,
description="Float that penalizes new tokens based on their frequency in the generated text so far.",
)
top_p: float = Field(
default=1.0,
description="Float that controls the cumulative probability of the top tokens to consider.",
)
top_k: int = Field(
default=-1,
description="Integer that controls the number of top tokens to consider.",
)
use_beam_search: bool = Field(
default=False, description="Whether to use beam search instead of sampling."
)
stop: Optional[List[str]] = Field(
default=None,
description="List of strings that stop the generation when they are generated.",
)
ignore_eos: bool = Field(
default=False,
description="Whether to ignore the EOS token and continue generating tokens after the EOS token is generated.",
)
max_new_tokens: int = Field(
default=512,
description="Maximum number of tokens to generate per output sequence.",
)
logprobs: Optional[int] = Field(
default=None,
description="Number of log probabilities to return per output token.",
)
dtype: str = Field(
default="auto",
description="The data type for the model weights and activations.",
)
download_dir: Optional[str] = Field(
default=None,
description="Directory to download and load the weights. (Default to the default cache dir of huggingface)",
)
vllm_kwargs: Dict[str, Any] = Field(
default_factory=dict,
description="Holds any model parameters valid for `vllm.LLM` call not explicitly specified.",
)
api_url: str = Field(description="The api url for vllm server")
_client: Any = PrivateAttr()
def __init__(
self,
model: str = "facebook/opt-125m",
temperature: float = 1.0,
tensor_parallel_size: int = 1,
trust_remote_code: bool = True,
n: int = 1,
best_of: Optional[int] = None,
presence_penalty: float = 0.0,
frequency_penalty: float = 0.0,
top_p: float = 1.0,
top_k: int = -1,
use_beam_search: bool = False,
stop: Optional[List[str]] = None,
ignore_eos: bool = False,
max_new_tokens: int = 512,
logprobs: Optional[int] = None,
dtype: str = "auto",
download_dir: Optional[str] = None,
vllm_kwargs: Dict[str, Any] = {},
api_url: Optional[str] = "",
callback_manager: Optional[CallbackManager] = None,
system_prompt: Optional[str] = None,
messages_to_prompt: Optional[Callable[[Sequence[ChatMessage]], str]] = None,
completion_to_prompt: Optional[Callable[[str], str]] = None,
pydantic_program_mode: PydanticProgramMode = PydanticProgramMode.DEFAULT,
output_parser: Optional[BaseOutputParser] = None,
) -> None:
if not api_url:
try:
from vllm import LLM as VLLModel
except ImportError:
raise ImportError(
"Could not import vllm python package. "
"Please install it with `pip install vllm`."
)
self._client = VLLModel(
model=model,
tensor_parallel_size=tensor_parallel_size,
trust_remote_code=trust_remote_code,
dtype=dtype,
download_dir=download_dir,
**vllm_kwargs
)
else:
self._client = None
callback_manager = callback_manager or CallbackManager([])
super().__init__(
model=model,
temperature=temperature,
n=n,
best_of=best_of,
presence_penalty=presence_penalty,
frequency_penalty=frequency_penalty,
top_p=top_p,
top_k=top_k,
use_beam_search=use_beam_search,
stop=stop,
ignore_eos=ignore_eos,
max_new_tokens=max_new_tokens,
logprobs=logprobs,
dtype=dtype,
download_dir=download_dir,
vllm_kwargs=vllm_kwargs,
api_url=api_url,
callback_manager=callback_manager,
system_prompt=system_prompt,
messages_to_prompt=messages_to_prompt,
completion_to_prompt=completion_to_prompt,
pydantic_program_mode=pydantic_program_mode,
output_parser=output_parser,
)
@classmethod
def class_name(cls) -> str:
return "Vllm"
@property
def metadata(self) -> LLMMetadata:
return LLMMetadata(model_name=self.model)
@property
def _model_kwargs(self) -> Dict[str, Any]:
base_kwargs = {
"temperature": self.temperature,
"max_tokens": self.max_new_tokens,
"n": self.n,
"frequency_penalty": self.frequency_penalty,
"presence_penalty": self.presence_penalty,
"use_beam_search": self.use_beam_search,
"best_of": self.best_of,
"ignore_eos": self.ignore_eos,
"stop": self.stop,
"logprobs": self.logprobs,
"top_k": self.top_k,
"top_p": self.top_p,
}
return {**base_kwargs}
def __del__(self) -> None:
import torch
if torch.cuda.is_available():
from vllm.model_executor.parallel_utils.parallel_state import (
destroy_model_parallel,
)
destroy_model_parallel()
del self._client
torch.cuda.synchronize()
def _get_all_kwargs(self, **kwargs: Any) -> Dict[str, Any]:
return {
**self._model_kwargs,
**kwargs,
}
@llm_chat_callback()
def chat(self, messages: Sequence[ChatMessage], **kwargs: Any) -> ChatResponse:
kwargs = kwargs if kwargs else {}
prompt = self.messages_to_prompt(messages)
completion_response = self.complete(prompt, **kwargs)
return completion_response_to_chat_response(completion_response)
@llm_completion_callback()
def complete(
self, prompt: str, formatted: bool = False, **kwargs: Any
) -> CompletionResponse:
kwargs = kwargs if kwargs else {}
params = {**self._model_kwargs, **kwargs}
from vllm import SamplingParams
# build sampling parameters
sampling_params = SamplingParams(**params)
outputs = self._client.generate([prompt], sampling_params)
return CompletionResponse(text=outputs[0].outputs[0].text)
@llm_chat_callback()
def stream_chat(
self, messages: Sequence[ChatMessage], **kwargs: Any
) -> ChatResponseGen:
raise (ValueError("Not Implemented"))
@llm_completion_callback()
def stream_complete(
self, prompt: str, formatted: bool = False, **kwargs: Any
) -> CompletionResponseGen:
raise (ValueError("Not Implemented"))
@llm_chat_callback()
async def achat(
self, messages: Sequence[ChatMessage], **kwargs: Any
) -> ChatResponse:
kwargs = kwargs if kwargs else {}
return self.chat(messages, **kwargs)
@llm_completion_callback()
async def acomplete(
self, prompt: str, formatted: bool = False, **kwargs: Any
) -> CompletionResponse:
kwargs = kwargs if kwargs else {}
return self.complete(prompt, **kwargs)
@llm_chat_callback()
async def astream_chat(
self, messages: Sequence[ChatMessage], **kwargs: Any
) -> ChatResponseAsyncGen:
raise (ValueError("Not Implemented"))
@llm_completion_callback()
async def astream_complete(
self, prompt: str, formatted: bool = False, **kwargs: Any
) -> CompletionResponseAsyncGen:
raise (ValueError("Not Implemented"))
|