forked from SkyworkAI/Skywork-R1V
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.py
81 lines (66 loc) · 2.59 KB
/
app.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
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
from flask import Flask, request, jsonify
import torch
from transformers import AutoModel, AutoTokenizer
from utils import load_image, split_model
app = Flask(__name__)
# 全局变量存储模型和tokenizer
model = None
tokenizer = None
def load_model(model_path):
global model, tokenizer
if model is None:
device_map = split_model(model_path)
model = AutoModel.from_pretrained(
model_path,
torch_dtype=torch.bfloat16,
load_in_8bit=False,
low_cpu_mem_usage=True,
use_flash_attn=True,
trust_remote_code=True,
device_map=device_map
).eval()
tokenizer = AutoTokenizer.from_pretrained(model_path, trust_remote_code=True, use_fast=False)
@app.route('/initialize', methods=['POST'])
def initialize():
try:
model_path = request.json.get('model_path')
if not model_path:
return jsonify({'error': '需要提供model_path参数'}), 400
load_model(model_path)
return jsonify({'message': '模型加载成功'}), 200
except Exception as e:
return jsonify({'error': str(e)}), 500
@app.route('/inference', methods=['POST'])
def inference():
try:
if model is None or tokenizer is None:
return jsonify({'error': '模型未初始化,请先调用initialize接口'}), 400
data = request.json
image_paths = data.get('image_paths', [])
question = data.get('question')
if not image_paths or not question:
return jsonify({'error': '需要提供image_paths和question参数'}), 400
# 处理图片
pixel_values = [load_image(img_path, max_num=12).to(torch.bfloat16).cuda()
for img_path in image_paths]
if len(pixel_values) > 1:
num_patches_list = [img.size(0) for img in pixel_values]
pixel_values = torch.cat(pixel_values, dim=0)
else:
pixel_values = pixel_values[0]
num_patches_list = None
prompt = "<image>\n" * len(image_paths) + question
generation_config = dict(
max_new_tokens=64000,
do_sample=True,
temperature=0.6,
top_p=0.95,
repetition_penalty=1.05
)
response = model.chat(tokenizer, pixel_values, prompt,
generation_config, num_patches_list=num_patches_list)
return jsonify({'response': response}), 200
except Exception as e:
return jsonify({'error': str(e)}), 500
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000)