yuccaaa commited on
Commit
d0167cc
·
verified ·
1 Parent(s): 20addd1

Upload ms-swift/examples/deploy/client/mllm/swift_client.py with huggingface_hub

Browse files
ms-swift/examples/deploy/client/mllm/swift_client.py ADDED
@@ -0,0 +1,127 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Alibaba, Inc. and its affiliates.
2
+ import os
3
+ from typing import List, Literal
4
+
5
+ os.environ['CUDA_VISIBLE_DEVICES'] = '0'
6
+
7
+
8
+ def infer_batch(engine: 'InferEngine', infer_requests: List['InferRequest']):
9
+ request_config = RequestConfig(max_tokens=512, temperature=0)
10
+ metric = InferStats()
11
+ resp_list = engine.infer(infer_requests, request_config, metrics=[metric])
12
+ query0 = infer_requests[0].messages[0]['content']
13
+ print(f'query0: {query0}')
14
+ print(f'response0: {resp_list[0].choices[0].message.content}')
15
+ print(f'metric: {metric.compute()}')
16
+
17
+
18
+ def infer_stream(engine: 'InferEngine', infer_request: 'InferRequest'):
19
+ request_config = RequestConfig(max_tokens=512, temperature=0, stream=True)
20
+ metric = InferStats()
21
+ gen_list = engine.infer([infer_request], request_config, metrics=[metric])
22
+ query = infer_request.messages[0]['content']
23
+ print(f'query: {query}\nresponse: ', end='')
24
+ for resp in gen_list[0]:
25
+ if resp is None:
26
+ continue
27
+ print(resp.choices[0].delta.content, end='', flush=True)
28
+ print()
29
+ print(f'metric: {metric.compute()}')
30
+
31
+
32
+ def get_message(mm_type: Literal['text', 'image', 'video', 'audio']):
33
+ if mm_type == 'text':
34
+ message = {'role': 'user', 'content': 'who are you?'}
35
+ elif mm_type == 'image':
36
+ message = {
37
+ 'role':
38
+ 'user',
39
+ 'content': [
40
+ {
41
+ 'type': 'image',
42
+ # url or local_path or PIL.Image or base64
43
+ 'image': 'http://modelscope-open.oss-cn-hangzhou.aliyuncs.com/images/animal.png'
44
+ },
45
+ {
46
+ 'type': 'text',
47
+ 'text': 'How many sheep are there in the picture?'
48
+ }
49
+ ]
50
+ }
51
+
52
+ elif mm_type == 'video':
53
+ # # use base64
54
+ # import base64
55
+ # with open('baby.mp4', 'rb') as f:
56
+ # vid_base64 = base64.b64encode(f.read()).decode('utf-8')
57
+ # video = f'data:video/mp4;base64,{vid_base64}'
58
+
59
+ # use url
60
+ video = 'https://modelscope-open.oss-cn-hangzhou.aliyuncs.com/images/baby.mp4'
61
+ message = {
62
+ 'role': 'user',
63
+ 'content': [{
64
+ 'type': 'video',
65
+ 'video': video
66
+ }, {
67
+ 'type': 'text',
68
+ 'text': 'Describe this video.'
69
+ }]
70
+ }
71
+ elif mm_type == 'audio':
72
+ message = {
73
+ 'role':
74
+ 'user',
75
+ 'content': [{
76
+ 'type': 'audio',
77
+ 'audio': 'http://modelscope-open.oss-cn-hangzhou.aliyuncs.com/images/weather.wav'
78
+ }, {
79
+ 'type': 'text',
80
+ 'text': 'What does this audio say?'
81
+ }]
82
+ }
83
+ return message
84
+
85
+
86
+ def get_data(mm_type: Literal['text', 'image', 'video', 'audio']):
87
+ data = {}
88
+ if mm_type == 'text':
89
+ messages = [{'role': 'user', 'content': 'who are you?'}]
90
+ elif mm_type == 'image':
91
+ # The number of <image> tags must be the same as len(images).
92
+ messages = [{'role': 'user', 'content': '<image>How many sheep are there in the picture?'}]
93
+ # Support URL/Path/base64/PIL.Image
94
+ data['images'] = ['http://modelscope-open.oss-cn-hangzhou.aliyuncs.com/images/animal.png']
95
+ elif mm_type == 'video':
96
+ messages = [{'role': 'user', 'content': '<video>Describe this video.'}]
97
+ data['videos'] = ['https://modelscope-open.oss-cn-hangzhou.aliyuncs.com/images/baby.mp4']
98
+ elif mm_type == 'audio':
99
+ messages = [{'role': 'user', 'content': '<audio>What does this audio say?'}]
100
+ data['audios'] = ['http://modelscope-open.oss-cn-hangzhou.aliyuncs.com/images/weather.wav']
101
+ data['messages'] = messages
102
+ return data
103
+
104
+
105
+ def run_client(host: str = '127.0.0.1', port: int = 8000):
106
+ engine = InferClient(host=host, port=port)
107
+ print(f'models: {engine.models}')
108
+ # Here, `load_dataset` is used for convenience; `infer_batch` does not require creating a dataset.
109
+ dataset = load_dataset(['AI-ModelScope/LaTeX_OCR:small#1000'], seed=42)[0]
110
+ print(f'dataset: {dataset}')
111
+ infer_requests = [InferRequest(**data) for data in dataset]
112
+ infer_batch(engine, infer_requests)
113
+
114
+ infer_stream(engine, InferRequest(messages=[get_message(mm_type='video')]))
115
+ # This writing is equivalent to the above writing.
116
+ infer_stream(engine, InferRequest(**get_data(mm_type='video')))
117
+
118
+
119
+ if __name__ == '__main__':
120
+ from swift.llm import (InferEngine, InferRequest, InferClient, RequestConfig, load_dataset, run_deploy,
121
+ DeployArguments)
122
+ from swift.plugin import InferStats
123
+ # NOTE: In a real deployment scenario, please comment out the context of run_deploy.
124
+ with run_deploy(
125
+ DeployArguments(model='Qwen/Qwen2.5-VL-3B-Instruct', verbose=False, log_interval=-1,
126
+ infer_backend='vllm')) as port:
127
+ run_client(port=port)