当前位置:   article > 正文

【llm 使用vLLM部署本地大模型】_export vllm_use_modelscope=true

export vllm_use_modelscope=true

Quickstart

Contents

Quickstart

This guide shows how to use vLLM to:

  • run offline batched inference on a dataset;
  • build an API server for a large language model;
  • start an OpenAI-compatible API server.

Be sure to complete theinstallation instructionsbefore continuing with this guide.

Offline Batched Inference

We first show an example of using vLLM for offline batched inference on a dataset. In other words, we use vLLM to generate texts for a list of input prompts.

Import LLM and SamplingParams from vLLM. The LLM class is the main class for running offline inference with vLLM engine. The SamplingParams class specifies the parameters for the sampling process.

from vllm import LLM,SamplingParams

Define the list of input prompts and the sampling parameters for generation. The sampling temperature is set to 0.8 and the nucleus sampling probability is set to 0.95. For more information about the sampling parameters, refer to theclass definition.

  1. prompts=[
  2. "Hello, my name is",
  3. "The president of the United States is",
  4. "The capital of France is",
  5. "The future of AI is",
  6. ]
  7. sampling_params=SamplingParams(temperature=0.8,top_p=0.95)

Initialize vLLM’s engine for offline inference with theLLMclass and theOPT-125M model. The list of supported models can be found at supported models.

llm=LLM(model="facebook/opt-125m")

Or use model from www.modelscope.cn 从国内站点下载

  1. # 设置环境变量 os.environ['VLLM_USE_MODELSCOPE']=True
  2. export VLLM_USE_MODELSCOPE=True
  3. llm=LLM(model="qwen/Qwen-7B-Chat",revision="v1.1.8",trust_remote_code=True)

Callllm.generateto generate the outputs. It adds the input prompts to vLLM engine’s waiting queue and executes the vLLM engine to generate the outputs with high throughput. The outputs are returned as a list ofRequestOutputobjects, which include all the output tokens.

outputs=llm.generate(prompts, sampling_params)

-> Print the outputs.

  1. for output in outputs:
  2. prompt=output.prompt
  3. generated_text=output.outputs[0].text
  4. print(f"Prompt: {prompt!r}, Generated text: {generated_text!r}")

The code example can also be found inexamples/offline_inference.py.

API Server

vLLM can be deployed as an LLM service. We provide an exampleFastAPIserver. Checkvllm/entrypoints/api_server.pyfor the server implementation. The server usesAsyncLLMEngineclass to support asynchronous processing of incoming requests.

第一步开启服务 Start the server:

$ python-mvllm.entrypoints.api_server

Or use model from www.modelscope.cn国内的开源社区下载

$ VLLM_USE_MODELSCOPE=True python-mvllm.entrypoints.api_server\
$ --model="qwen/Qwen-7B-Chat"\
$ --revision="v1.1.8"\
$ --trust-remote-code

By default, this command starts the server athttp://localhost:8000with the OPT-125M model.

第二步通过API使用 Query the model in shell:

$ curl http://localhost:8000/generate \
$ -d'{
$ "prompt": "San Francisco is a",
$ "use_beam_search": true,
$ "n": 4,
$ "temperature": 0
$ }'

python版本

  1. """Example Python client for vllm.entrypoints.api_server"""
  2. import argparse
  3. import json
  4. from typing import Iterable, List
  5. import requests
  6. def clear_line(n: int = 1) -> None:
  7. LINE_UP = '\033[1A'
  8. LINE_CLEAR = '\x1b[2K'
  9. for _ in range(n):
  10. print(LINE_UP, end=LINE_CLEAR, flush=True)
  11. def post_http_request(prompt: str,
  12. api_url: str,
  13. n: int = 1,
  14. temperature=0.0,
  15. max_tokens=8192,
  16. stream: bool = False) -> requests.Response:
  17. headers = {"User-Agent": "Test Client"}
  18. pload = {
  19. "prompt": prompt,
  20. "n": n,
  21. "use_beam_search": True,
  22. "temperature": temperature,
  23. "max_tokens": max_tokens,
  24. "stream": stream,
  25. }
  26. response = requests.post(api_url, headers=headers, json=pload, stream=True)
  27. return response
  28. def get_streaming_response(response: requests.Response) -> Iterable[List[str]]:
  29. for chunk in response.iter_lines(chunk_size=8192,
  30. decode_unicode=False,
  31. delimiter=b"\0"):
  32. if chunk:
  33. data = json.loads(chunk.decode("utf-8"))
  34. output = data["text"]
  35. yield output
  36. def get_response(response: requests.Response) -> List[str]:
  37. data = json.loads(response.content)
  38. output = data["text"]
  39. return output
  40. if __name__ == "__main__":
  41. parser = argparse.ArgumentParser()
  42. parser.add_argument("--host", type=str, default="localhost")
  43. parser.add_argument("--port", type=int, default=8000)
  44. parser.add_argument("--n", type=int, default=4)
  45. parser.add_argument("--prompt", type=str, default="San Francisco is a")
  46. parser.add_argument("--stream", action="store_true")
  47. args = parser.parse_args()
  48. prompt = args.prompt
  49. api_url = f"http://{args.host}:{args.port}/generate"
  50. n = args.n
  51. stream = args.stream
  52. print(f"Prompt: {prompt!r}\n", flush=True)
  53. response = post_http_request(prompt, api_url, n, stream)
  54. if stream:
  55. num_printed_lines = 0
  56. for h in get_streaming_response(response):
  57. clear_line(num_printed_lines)
  58. num_printed_lines = 0
  59. for i, line in enumerate(h):
  60. num_printed_lines += 1
  61. print(f"Beam candidate {i}: {line!r}", flush=True)
  62. else:
  63. output = get_response(response)
  64. for i, line in enumerate(output):
  65. print(f"Beam candidate {i}: {line!r}", flush=True)

See examples/api_client.py for a more detailed client example.

OpenAI-Compatible Server

vLLM can be deployed as a server that mimics the OpenAI API protocol. This allows vLLM to be used as a drop-in replacement for applications using OpenAI API. By default, it starts the server athttp://localhost:8000. You can specify the address with--hostand--portarguments. The server currently hosts one model at a time (OPT-125M in the above command) and implementslist models,create chat completion, andcreate completionendpoints. We are actively adding support for more endpoints.

第一步Start the server:

$ python-m vllm.entrypoints.openai.api_server \
$ --modelfacebook/opt-125m

Or use model from www.modelscope.cn

$ VLLM_USE_MODELSCOPE=True python-m vllm.entrypoints.openai.api_server \
$ --model="qwen/Qwen-7B-Chat"--revision="v1.1.8"--trust-remote-code

By default, the server uses a predefined chat template stored in the tokenizer. You can override this template by using the--chat-templateargument:

$ python-m vllm.entrypoints.openai.api_server\
$ --modelfacebook/opt-125m\
$ --chat-template./examples/template_chatml.jinja

This server can be queried in the same format as OpenAI API. For example, list the models:

$ curl http://localhost:8000/v1/models

第二步调用接口

Using OpenAI Completions API with vLLM

Query the model with input prompts:

$ curl http://localhost:8000/v1/completions\
$ -H"Content-Type: application/json"\
$ -d'{
$ "model": "facebook/opt-125m",
$ "prompt": "San Francisco is a",
$ "max_tokens": 7,
$ "temperature": 0
$ }'

Since this server is compatible with OpenAI API, you can use it as a drop-in replacement for any applications using OpenAI API. For example, another way to query the server is via theopenaipython package:

Modify OpenAI's API key and API base to use vLLM's API server.

  1. from openai import OpenAI
  2. # 方法1通过设置环境变量
  3. # import os
  4. # os.environ['OPENAI_API_KEY']="ANY THING"
  5. # os.environ['OPENAI_API_BASE']="http://localhost:8000/v1"
  6. # 方法2Modify OpenAI's API key and API base to use vLLM's API server.
  7. openai_api_key = "ANY THING"
  8. openai_api_base = "http://localhost:8000/v1"
  9. client = OpenAI(
  10. api_key=openai_api_key,
  11. base_url=openai_api_base,
  12. )
  13. completion = client.completions.create(model="facebook/opt-125m",
  14. prompt="San Francisco is a")
  15. print("Completion result:", completion)

For a more detailed client example, refer toexamples/openai_completion_client.py.

Using OpenAI Chat API with vLLM

The vLLM server is designed to support the OpenAI Chat API, allowing you to engage in dynamic conversations with the model. The chat interface is a more interactive way to communicate with the model, allowing back-and-forth exchanges that can be stored in the chat history. This is useful for tasks that require context or more detailed explanations.

Querying the model using OpenAI Chat API:

You can use thecreate chat completionendpoint to communicate with the model in a chat-like interface:

$ curl http://localhost:8000/v1/chat/completions\
$ -H"Content-Type: application/json"\
$ -d'{
$ "model": "facebook/opt-125m",
$ "messages": [
$ {"role": "system", "content": "You are a helpful assistant."},
$ {"role": "user", "content": "Who won the world series in 2020?"}
$ ]
$ }'

Python Client Example,using the openai python package, you can also communicate with the model in a chat-like manner:

  1. from openai import OpenAI
  2. # 方法1通过设置环境变量
  3. # import os
  4. # os.environ['OPENAI_API_KEY']="ANY THING"
  5. # os.environ['OPENAI_API_BASE']="http://localhost:8000/v1"
  6. # 方法2Modify OpenAI's API key and API base to use vLLM's API server.
  7. openai_api_key = "ANY THING"
  8. openai_api_base = "http://localhost:8000/v1"
  9. client = OpenAI(
  10. api_key=openai_api_key,
  11. base_url=openai_api_base,
  12. )
  13. chat_response = client.chat.completions.create(
  14. model="facebook/opt-125m",
  15. messages=[
  16. {"role": "system", "content": "You are a helpful assistant."},
  17. {"role": "user", "content": "Tell me a joke."},
  18. ]
  19. )
  20. print("Chat response:", chat_response)

For more in-depth examples and advanced features of the chat API, you can refer to the official OpenAI documentation.

参考链接Quickstart — vLLM

声明:本文内容由网友自发贡献,转载请注明出处:【wpsshop】
推荐阅读
相关标签
  

闽ICP备14008679号