Browse Source

chatgpt服务使用vllm方式预测

master
majiahui@haimaqingfan.com 1 year ago
parent
commit
6348a1b647
  1. 2
      articles_directory_predict.py
  2. 6
      gunicorn_config.py
  3. 45
      mistral_api.py
  4. 10
      mistral_model_predict_vllm.py
  5. 1
      run_api.sh
  6. 1
      run_api_gunicorn.sh
  7. 1
      run_model.sh
  8. 25
      测试并发性能.py
  9. 119
      测试并发请求.py

2
articles_directory_predict.py

@ -63,7 +63,7 @@ def articles_directory():
nums = request.json["nums"]
nums = int(nums)
url = "http://{}:18001/predict".format(str(get_host_ip()))
url = "http://{}:12000/predict".format(str(get_host_ip()))
input_data = []
for i in range(nums):

6
gunicorn_config.py

@ -1,7 +1,7 @@
# 并行工作线程数
workers = 8
# 监听内网端口5000【按需要更改】
bind = '0.0.0.0:12000'
bind = '0.0.0.0:12003'
loglevel = 'debug'
@ -11,8 +11,8 @@ daemon = True
# 设置超时时间120s,默认为30s。按自己的需求进行设置
timeout = 120
# 设置访问日志和错误信息日志路径
accesslog = './logs/acess.log'
errorlog = './logs/error.log'
accesslog = './logs/acess1.log'
errorlog = './logs/error1.log'
# access_log_format = '%(h) - %(t)s - %(u)s - %(s)s %(H)s'
# errorlog = '-' # 记录到标准输出

45
mistral_api.py

@ -0,0 +1,45 @@
import os
os.environ["CUDA_VISIBLE_DEVICES"] = "0"
from flask import Flask, jsonify
from flask import request
from transformers import pipeline
import redis
import uuid
import json
from threading import Thread
from vllm import LLM, SamplingParams
import time
import threading
import time
import concurrent.futures
import requests
import socket
app = Flask(__name__)
app.config["JSON_AS_ASCII"] = False
pool = redis.ConnectionPool(host='localhost', port=63179, max_connections=50,db=4, password="zhicheng123*")
redis_ = redis.Redis(connection_pool=pool, decode_responses=True)
db_key_query = 'query'
db_key_query_articles_directory = 'query_articles_directory'
db_key_result = 'result'
@app.route("/predict", methods=["POST"])
def handle_query():
text = request.json["texts"] # 获取用户query中的文本 例如"I love you"
id_ = str(uuid.uuid1()) # 为query生成唯一标识
d = {'id': id_, 'text': text} # 绑定文本和query id
redis_.rpush(db_key_query, json.dumps(d)) # 加入redis
time.sleep(1)
while True:
result = redis_.get(id_) # 获取该query的模型结果
if result is not None:
redis_.delete(id_)
result_text = {'code': "200", 'data': json.loads(result)}
break
time.sleep(1)
return jsonify(result_text) # 返回结果
if __name__ == "__main__":
app.run(debug=False, host='0.0.0.0', port=12001)

10
mistral_model_predict_vllm.py

@ -1,5 +1,5 @@
import os
os.environ["CUDA_VISIBLE_DEVICES"] = "3"
os.environ["CUDA_VISIBLE_DEVICES"] = "2"
from transformers import pipeline
import redis
import uuid
@ -14,7 +14,7 @@ import requests
import socket
pool = redis.ConnectionPool(host='localhost', port=63179, max_connections=50,db=11, password="zhicheng123*")
pool = redis.ConnectionPool(host='localhost', port=63179, max_connections=50,db=5, password="zhicheng123*")
redis_ = redis.Redis(connection_pool=pool, decode_responses=True)
db_key_query = 'query'
@ -22,10 +22,12 @@ db_key_query_articles_directory = 'query_articles_directory'
db_key_result = 'result'
batch_size = 512
sampling_params = SamplingParams(temperature=0.95, top_p=0.7,presence_penalty=0.9,stop="</s>", max_tokens=4096)
models_path = "/home/majiahui/project/models-llm/openbuddy-llama-7b-finetune"
# sampling_params = SamplingParams(temperature=0.95, top_p=0.7,presence_penalty=0.9,stop="</s>", max_tokens=4096)
sampling_params = SamplingParams(temperature=0.95, top_p=0.7,stop="</s>", max_tokens=4096)
models_path = "/home/majiahui/project/models-llm/openbuddy-mistral-7b-v13.1-finetune-90000"
llm = LLM(model=models_path, tokenizer_mode="slow")
def classify(batch_size): # 调用模型,设置最大batch_size
while True:
texts = []

1
run_api.sh

@ -1 +0,0 @@
gunicorn flask_predict:app -c gunicorn_config.py

1
run_api_gunicorn.sh

@ -0,0 +1 @@
gunicorn mistral_api:app -c gunicorn_config.py

1
run_model.sh

@ -0,0 +1 @@
nohup python mistral_model_predict_vllm.py > myout.file 2>&1 &

25
测试并发性能.py

@ -0,0 +1,25 @@
import os
os.environ["CUDA_VISIBLE_DEVICES"] = "0"
from flask import Flask, jsonify
from flask import request
import redis
import uuid
import json
import time
app = Flask(__name__)
app.config["JSON_AS_ASCII"] = False
pool = redis.ConnectionPool(host='localhost', port=63179, max_connections=50,db=5, password="zhicheng123*")
redis_ = redis.Redis(connection_pool=pool, decode_responses=True)
db_key_query = 'query'
db_key_query_articles_directory = 'query_articles_directory'
db_key_result = 'result'
for i in range(100):
text = "User: 背景:我是一名博士生,我想写一篇论文。\n角色:我需要你作为拥有google学术论文数据库和百度学术论文数据库的资深数据。\n要求:根据论文题目“中学教育国际化之路”和目录“一、 引言\n1.1 研究背景\n1.2 研究目的\n1.3 研究意义\n二、 国际化教育的概念与特点\n2.1 国际化教育的定义\n2.2 国际化教育的目标\n2.3 国际化教育的特点\n三、 中学教育国际化的现状分析\n3.1 国内中学教育国际化的发展历程\n3.2 国内中学教育国际化的现状\n3.3 存在的问题与挑战\n四、 中学教育国际化的路径探索\n4.1 课程设置与教学方法改革\n4.2 师资队伍建设与培训\n4.3 学校合作与交流机制建设\n五、 中学教育国际化的效果评估\n5.1 学生国际视野与跨文化交际能力的提升\n5.2 学校与教育机构的国际合作与交流的拓展\n5.3 教育资源的优化配置与整合\n六、 结论\n6.1 研究总结\n6.2 研究展望”,为小标题“4.2 师资队伍建设与培训”填充1200字左右的中文内容,内容第一行返回“4.2 师资队伍建设与培训”且不包含目录中其他标题,要求生成内容符合学术论文写法,可以出现三级标题,绝不能出现“首先”,“其次”等字样的词\n\nAssistant:" # 获取用户query中的文本 例如"I love you"
id_ = str(uuid.uuid1()) # 为query生成唯一标识
d = {'id': id_, 'text': text} # 绑定文本和query id
redis_.rpush(db_key_query, json.dumps(d)) # 加入redis

119
测试并发请求.py

@ -0,0 +1,119 @@
# -*- coding: utf-8 -*-
import concurrent.futures
import time
from threading import Thread
import requests
import json
def request_api_chatgpt(prompt):
url = "http://192.168.31.149:12003/predict"
data = {
"texts": prompt
}
response = requests.post(
url,
json=data,
timeout=100000
)
if response.status_code == 200:
return response.json()
else:
# logger.error(
# "【{}】 Failed to get a proper response from remote "
# "server. Status Code: {}. Response: {}"
# "".format(url, response.status_code, response.text)
# )
print("{}】 Failed to get a proper response from remote "
"server. Status Code: {}. Response: {}"
"".format(url, response.status_code, response.text))
return {}
def uuid_search(uuid):
url = "http://192.168.31.149:12003/search"
data = {
"id": uuid
}
response = requests.post(
url,
json=data,
timeout=100000
)
if response.status_code == 200:
return response.json()
else:
# logger.error(
# "【{}】 Failed to get a proper response from remote "
# "server. Status Code: {}. Response: {}"
# "".format(url, response.status_code, response.text)
# )
print("{}】 Failed to get a proper response from remote "
"server. Status Code: {}. Response: {}"
"".format(url, response.status_code, response.text))
return {}
input_values_1 = ["User: 背景:我是一名博士生,我想写一篇论文。\n角色:我需要你作为拥有google学术论文数据库和百度学术论文数据库的资深数据。\n要求:根据论文题目“中学教育国际化之路”和目录“一、 引言\n1.1 研究背景\n1.2 研究目的\n1.3 研究意义\n二、 国际化教育的概念与特点\n2.1 国际化教育的定义\n2.2 国际化教育的目标\n2.3 国际化教育的特点\n三、 中学教育国际化的现状分析\n3.1 国内中学教育国际化的发展历程\n3.2 国内中学教育国际化的现状\n3.3 存在的问题与挑战\n四、 中学教育国际化的路径探索\n4.1 课程设置与教学方法改革\n4.2 师资队伍建设与培训\n4.3 学校合作与交流机制建设\n五、 中学教育国际化的效果评估\n5.1 学生国际视野与跨文化交际能力的提升\n5.2 学校与教育机构的国际合作与交流的拓展\n5.3 教育资源的优化配置与整合\n六、 结论\n6.1 研究总结\n6.2 研究展望”,为小标题“4.2 师资队伍建设与培训”填充1200字左右的中文内容,内容第一行返回“4.2 师资队伍建设与培训”且不包含目录中其他标题,要求生成内容符合学术论文写法,可以出现三级标题,绝不能出现“首先”,“其次”等字样的词\n\nAssistant:"] * 50
input_values_2 = ["User: 任务:生成论文小标题内容\n任务:问:论文题目是《空调后板压筋成形的回弹翘曲研究》,目录是“一、引言\n1.1 研究背景\n1.2 研究意义\n1.3 回弹翘曲的定义与影响因素\n\n二、相关理论与方法\n2.1 空调后板压筋成形技术\n2.2 回弹翘曲的测量方法\n2.3 影响回弹翘曲的因素分析\n\n三、实验设计与参数设置\n3.1 实验样品制备\n3.2 实验装置与测量仪器\n3.3 实验参数设置\n\n四、回弹翘曲的数值模拟\n4.1 模型建立\n4.2 材料参数与边界条件\n4.3 数值模拟结果分析\n\n五、实验结果与分析\n5.1 回弹翘曲的测量结果\n5.2 影响因素的实验分析\n5.3 实验结果与数值模拟结果的对比\n\n六、结论与展望\n6.1 结论\n6.2 研究的不足与改进方向”,请把其中的小标题“6.2 研究的不足与改进方向”的内容补充完整,补充内容字数在600字左右\n答:\n\nAssistant:"] * 50
input_values = input_values_1 + input_values_2
# "User: 任务:生成论文小标题内容\n任务:问:论文题目是《空调后板压筋成形的回弹翘曲研究》,目录是“一、引言\n1.1 研究背景\n1.2 研究意义\n1.3 回弹翘曲的定义与影响因素\n\n二、相关理论与方法\n2.1 空调后板压筋成形技术\n2.2 回弹翘曲的测量方法\n2.3 影响回弹翘曲的因素分析\n\n三、实验设计与参数设置\n3.1 实验样品制备\n3.2 实验装置与测量仪器\n3.3 实验参数设置\n\n四、回弹翘曲的数值模拟\n4.1 模型建立\n4.2 材料参数与边界条件\n4.3 数值模拟结果分析\n\n五、实验结果与分析\n5.1 回弹翘曲的测量结果\n5.2 影响因素的实验分析\n5.3 实验结果与数值模拟结果的对比\n\n六、结论与展望\n6.1 结论\n6.2 研究的不足与改进方向”,请把其中的小标题“6.2 研究的不足与改进方向”的内容补充完整,补充内容字数在600字左右\n答:\n\nAssistant:"
t1 = time.time()
with concurrent.futures.ThreadPoolExecutor() as executor:
# 使用map方法并发地调用worker_function
results = list(executor.map(request_api_chatgpt, input_values))
t2 = time.time()
print(t2 - t1)
# 打印结果
# print("Results:", results[0])
for i in results:
print(i)
def classify(results):
results_list = [""] * len(results)
while True:
tiaochu_bool = True
for i in results_list:
if i == "":
tiaochu_bool = False
break
if tiaochu_bool == True:
break
for i in range(len(results)):
uuid = results[i]["texts"]["id"]
'''
{
"code": 200,
"probabilities": null,
"text": " 4.2 师资队伍建设与培训\n\n师资队伍是中学教育国际化的重要支撑,他们的专业素养和跨文化交际能力对于学生的发展和学校的发展至关重要。因此,建设和培训高素质的师资队伍是实现中学教育国际化的重要途径。本节将从师资队伍的培训与发展、师资队伍的选拔与激励以及师资队伍的跨文化交际能力培养等方面进行探讨。\n\n首先,师资队伍的培训与发展是实现中学教育国际化的基础。培训与发展的目标是提高教师的专业素养和跨文化交际能力,使他们能够更好地适应国际化教育的需求。培训与发展的内容可以包括教育理论、教学方法、教材选择与开发、教育评价等方面的知识和技能。此外,还可以通过参与国际教育项目、交流研究等方式拓宽教师的国际视野和跨文化交际能力。\n\n其次,师资队伍的选拔与激励是提高教师专业素养和跨文化交际能力的重要手段。选拔优秀的教师是建设高素质师资队伍的基础,他们具有良好的教育背景、专业知识和教学经验。激励教师是提高他们工作积极性和专业素养的重要手段,可以通过薪酬激励、职称评定、学术荣誉等方式进行。激励教师不仅可以提高他们的工作动力和专业素养,还可以激发他们的创新潜能,推动中学教育国际化的进程。\n\n最后,师资队伍的跨文化交际能力培养是实现中学教育国际化的重要保障。跨文化交际能力是指教师在跨文化环境中有效地传递和接收信息的能力。培养教师的跨文化交际能力可以通过提供跨文化交际培训、组织国际交流项目、开展跨文化教育研究等方式进行。培养教师的跨文化交际能力可以提高他们的国际视野和跨文化交际能力,使他们能够更好地适应国际化教育的需求。\n\n综上所述,师资队伍建设与培训是实现中学教育国际化的重要途径。通过培训与发展、选拔与激励以及跨文化交际能力培养等方式,可以提高教师的专业素养和跨文化交际能力,为中学教育国际化的发展提供有力支撑。然而,师资队伍建设与培训仍面临一些挑战,如教师培训资源不足、教师培训方式不灵活等。因此,需要进一步完善师资队伍建设与培训的机制和政策,提高教师培训的质量和效果。只有通过不断改进和创新,才能实现中学教育国际化的目标。\n"
}
{
"code": "203",
"probabilities": null,
"text": ""
}
'''
result = uuid_search(uuid)
if result["code"] == 200:
results_list[i] = result["text"]
time.sleep(3)
return results_list
with concurrent.futures.ThreadPoolExecutor() as executor:
# 使用map方法并发地调用worker_function
results = list(executor.map(classify, [results]))
for i in results[0]:
print(i)
Loading…
Cancel
Save