yuccaaa commited on
Commit
b9e3d35
·
verified ·
1 Parent(s): 5c699da

Upload ms-swift/docs/source/Instruction/推理和部署.md with huggingface_hub

Browse files
ms-swift/docs/source/Instruction/推理和部署.md ADDED
@@ -0,0 +1,353 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 推理和部署
2
+
3
+ 以下为swift支持的推理引擎以及接入部分的相应能力,三种推理加速引擎为SWIFT的推理、部署、评测模块提供推理加速:
4
+
5
+ | 推理加速引擎 | OpenAI API | 多模态 | 量化模型 | 多LoRA | QLoRA | Batch推理 | 并行技术 |
6
+ | ------------ | -------------- | ---------- | ------ | -------- | ------ | ----- | ----- |
7
+ | pytorch | [✅](https://github.com/modelscope/ms-swift/blob/main/examples/deploy/client/llm/chat/openai_client.py) | [✅](https://github.com/modelscope/ms-swift/blob/main/examples/app/mllm.sh) | ✅ | [✅](https://github.com/modelscope/ms-swift/blob/main/examples/infer/demo_lora.py) | ✅ | [✅](https://github.com/modelscope/ms-swift/blob/main/examples/infer/pt/batch_ddp.sh) |DDP/device_map |
8
+ | [vllm](https://github.com/vllm-project/vllm) | ✅ | [✅](https://github.com/modelscope/ms-swift/blob/main/examples/infer/vllm/mllm_tp.sh) | ✅ | [✅](https://github.com/modelscope/ms-swift/blob/main/examples/deploy/lora/server.sh) | ❌ | ✅ | TP/PP/DP |
9
+ | [lmdeploy](https://github.com/InternLM/lmdeploy) | ✅ | [✅](https://github.com/modelscope/ms-swift/blob/main/examples/infer/lmdeploy/mllm_tp.sh) | ✅ | ❌ | ❌ | ✅ | TP/DP |
10
+
11
+
12
+ ## 推理
13
+ ms-swift使用了分层式的设计思想,用户可以使用命令行界面、Web-UI界面和直接使用Python的方式进行推理。
14
+
15
+ 如果要查看LoRA微调后模型的推理,可以参考[预训练与微调文档](./预训练与微调.md#推理微调后模型)。
16
+
17
+ ### 使用CLI
18
+
19
+ **全参数模型:**
20
+ ```shell
21
+ CUDA_VISIBLE_DEVICES=0 swift infer \
22
+ --model Qwen/Qwen2.5-7B-Instruct \
23
+ --stream true \
24
+ --infer_backend pt \
25
+ --max_new_tokens 2048
26
+ ```
27
+
28
+ **LoRA模型:**
29
+ ```shell
30
+ CUDA_VISIBLE_DEVICES=0 swift infer \
31
+ --model Qwen/Qwen2.5-7B-Instruct \
32
+ --adapters swift/test_lora \
33
+ --stream true \
34
+ --infer_backend pt \
35
+ --temperature 0 \
36
+ --max_new_tokens 2048
37
+ ```
38
+
39
+
40
+ **命令行推理指令**
41
+
42
+ 以上为交互式命令行界面推理,脚本运行后仅需在terminal中输入query即可。你也可以输入以下特殊指令:
43
+ - `multi-line`: 切换到多行模式,在输入中支持换行输入,以`#`代表输入结束。
44
+ - `single-line`: 切换到单行模式,以换行代表输入结束。
45
+ - `reset-system`: 重置system并清空历史记录。
46
+ - `clear`: 清除历史记录。
47
+ - `quit` or `exit`: 退出对话。
48
+
49
+ **多模态模型**
50
+
51
+ ```shell
52
+ CUDA_VISIBLE_DEVICES=0 \
53
+ MAX_PIXELS=1003520 \
54
+ VIDEO_MAX_PIXELS=50176 \
55
+ FPS_MAX_FRAMES=12 \
56
+ swift infer \
57
+ --model Qwen/Qwen2.5-VL-3B-Instruct \
58
+ --stream true \
59
+ --infer_backend pt \
60
+ --max_new_tokens 2048
61
+ ```
62
+
63
+ 如果要进行多模态模型的推理,可以在query中添加`<image>/<video>/<audio>`等标签(代表图像表征在`inputs_embeds`中的位置),例如输入`<image><image>这两张图有啥区别`,`<video>描述这段视频`。然后根据提示输入相应的图像/视频/音频即可。
64
+
65
+ 以下为一个推理的示例:
66
+ ```
67
+ <<< <image><image>这两张图有什么区别
68
+ Input an image path or URL <<< http://modelscope-open.oss-cn-hangzhou.aliyuncs.com/images/cat.png
69
+ Input an image path or URL <<< http://modelscope-open.oss-cn-hangzhou.aliyuncs.com/images/animal.png
70
+ 这两张图片的区别在于它们所展示的动物和场景。
71
+
72
+ 1. **第一张图片**:
73
+ - 展示了一只小猫。
74
+ - 小猫有大大的眼睛,表情显得有些困惑或好奇。
75
+ - 背景是模糊的,可能是室内环境。
76
+
77
+ 2. **第二张图片**:
78
+ - 展示了一群羊。
79
+ - 羊们站在草地上,背景是绿色的山丘和蓝天白云。
80
+ - 羊的表情看起来很平静,似乎在享受大自然的环境。
81
+
82
+ 总结来说,第一张图片是一只小猫,而第二张图片是一群羊。
83
+ --------------------------------------------------
84
+ <<< clear
85
+ <<< <video>描述这段视频
86
+ Input a video path or URL <<< https://modelscope-open.oss-cn-hangzhou.aliyuncs.com/images/baby.mp4
87
+ The video shows a baby wearing sunglasses sitting on a bed and reading a book. The baby is holding the book with both hands and appears to be focused on the pages. The baby's feet are visible in the frame, and they are moving slightly as they read. The background of the video shows a room with a bed and some furniture.
88
+ ```
89
+
90
+
91
+ **数据集推理:**
92
+ ```shell
93
+ CUDA_VISIBLE_DEVICES=0 swift infer \
94
+ --model Qwen/Qwen2.5-7B-Instruct \
95
+ --stream true \
96
+ --infer_backend pt \
97
+ --val_dataset AI-ModelScope/alpaca-gpt4-data-zh \
98
+ --max_new_tokens 2048
99
+ ```
100
+
101
+ 以上提供了全参数和LoRA流式推理的例子,以下介绍更多SWIFT中的推理技术:
102
+ - 界面推理:你可以将`swift infer`改成`swift app`。
103
+ - batch推理:`infer_backend=pt`可以指定`--max_batch_size`对大模型和多模态大模型进行batch推理,具体参考[这里](https://github.com/modelscope/ms-swift/blob/main/examples/infer/pt/batch_ddp.sh)。在进行batch推理时,你不能设置`--stream true`。
104
+ - DDP/device_map推理:`infer_backend=pt`支持使用DDP/device_map技术进行并行推理,具体参考[这里](https://github.com/modelscope/ms-swift/blob/main/examples/infer/pt/mllm_device_map.sh)。
105
+ - 推理加速:swift支持使用vllm/lmdeploy对推理、部署和评测模块进行推理加速,只需要额外指定`--infer_backend vllm/lmdeploy`即可。可以参考[这里](https://github.com/modelscope/ms-swift/blob/main/examples/infer/vllm/ddp.sh)。
106
+ - 多模态模型:我们提供了[pt](https://github.com/modelscope/ms-swift/blob/main/examples/infer/pt/mllm_device_map.sh)/[vllm](https://github.com/modelscope/ms-swift/blob/main/examples/infer/vllm/mllm_tp.sh)/[lmdeploy](https://github.com/modelscope/ms-swift/blob/main/examples/infer/lmdeploy/mllm_tp.sh)对多模态模型进行多GPU推理的shell脚本。
107
+ - 量化模型:直接选择GPTQ、AWQ、BNB量化的模型,例如:`--model Qwen/Qwen2.5-7B-Instruct-GPTQ-Int4`即可。
108
+ - 更多模型类型:我们提供了[bert](https://github.com/modelscope/ms-swift/blob/main/examples/infer/pt/bert.sh)、[reward_model](https://github.com/modelscope/ms-swift/blob/main/examples/infer/pt/reward_model.sh)、[prm](https://github.com/modelscope/ms-swift/blob/main/examples/infer/pt/prm.sh)的推理脚本。
109
+
110
+
111
+ **小帖士:**
112
+ - SWIFT会将推理结果保存起来,你可以通过`--result_path`指定保存路径。
113
+ - 如果要输出logprobs,只需要在推理时,指定`--logprobs true`即可。SWIFT会保存。注意,设置`--stream true`将不会存储。
114
+ - infer_backend为pt支持所有swift已支持模型的推理,而infer_backend为vllm/lmdeploy只支持部分模型,具体请参考[vllm](https://docs.vllm.ai/en/latest/models/supported_models.html)、[lmdeploy](https://lmdeploy.readthedocs.io/en/latest/supported_models/supported_models.html)文档。
115
+ - 使用`--infer_backend vllm`出现OOM,可以通过降低`--max_model_len`,`--max_num_seqs`,选择合适的`--gpu_memory_utilization`,设置`--enforce_eager true`。或者使用tensor并行`--tensor_parallel_size`来解决。
116
+ - 使用`--infer_backend vllm`推理多模态模型,需要传入多张图片。可以设置`--limit_mm_per_prompt`解决,例如:`--limit_mm_per_prompt '{"image": 10, "video": 5}'`。
117
+ - 推理qwen2-vl/qwen2.5-vl出现OOM,可以通过设置`MAX_PIXELS`、`VIDEO_MAX_PIXELS`、`FPS_MAX_FRAMES`解决,可以参考[这里](https://github.com/modelscope/ms-swift/blob/main/examples/app/mllm.sh)。
118
+ - swift内置对话模板与使用transformers运行的对话模板对齐,测试参考[这里](https://github.com/modelscope/ms-swift/blob/main/tests/test_align/test_template/test_vision.py)。如果出现未对齐情况,欢迎提issue/PR修正。
119
+
120
+
121
+ ### 使用Web-UI
122
+ 如果你要使用界面的方式进行推理,可以查看[Web-UI文档](../GetStarted/Web-UI.md)。
123
+
124
+ ### 使用Python
125
+
126
+ 文本模型:
127
+ ```python
128
+ import os
129
+ os.environ['CUDA_VISIBLE_DEVICES'] = '0'
130
+
131
+ from swift.llm import PtEngine, RequestConfig, InferRequest
132
+ model = 'Qwen/Qwen2.5-0.5B-Instruct'
133
+
134
+ # 加载推理引擎
135
+ engine = PtEngine(model, max_batch_size=2)
136
+ request_config = RequestConfig(max_tokens=512, temperature=0)
137
+
138
+ # 这里使用了2个infer_request来展示batch推理
139
+ infer_requests = [
140
+ InferRequest(messages=[{'role': 'user', 'content': 'who are you?'}]),
141
+ InferRequest(messages=[{'role': 'user', 'content': '浙江的省会在哪?'},
142
+ {'role': 'assistant', 'content': '浙江省的省会是杭州。'},
143
+ {'role': 'user', 'content': '这里有什么好玩的地方'},]),
144
+ ]
145
+ resp_list = engine.infer(infer_requests, request_config)
146
+ query0 = infer_requests[0].messages[0]['content']
147
+ print(f'response0: {resp_list[0].choices[0].message.content}')
148
+ print(f'response1: {resp_list[1].choices[0].message.content}')
149
+ ```
150
+
151
+ 多模态模型:
152
+ ```python
153
+ import os
154
+ os.environ['CUDA_VISIBLE_DEVICES'] = '0'
155
+ os.environ['MAX_PIXELS'] = '1003520'
156
+ os.environ['VIDEO_MAX_PIXELS'] = '50176'
157
+ os.environ['FPS_MAX_FRAMES'] = '12'
158
+
159
+ from swift.llm import PtEngine, RequestConfig, InferRequest
160
+ model = 'Qwen/Qwen2.5-VL-3B-Instruct'
161
+
162
+ # 加载推理引擎
163
+ engine = PtEngine(model, max_batch_size=2)
164
+ request_config = RequestConfig(max_tokens=512, temperature=0)
165
+
166
+ # 这里使用了3个infer_request来展示batch推理
167
+ infer_requests = [
168
+ InferRequest(messages=[{'role': 'user', 'content': 'who are you?'}]),
169
+ InferRequest(messages=[{'role': 'user', 'content': '<image><image>两张图的区别是什么?'}],
170
+ images=['http://modelscope-open.oss-cn-hangzhou.aliyuncs.com/images/cat.png',
171
+ 'http://modelscope-open.oss-cn-hangzhou.aliyuncs.com/images/animal.png']),
172
+ InferRequest(messages=[{'role': 'user', 'content': '<video>describe the video'}],
173
+ videos=['https://modelscope-open.oss-cn-hangzhou.aliyuncs.com/images/baby.mp4']),
174
+ ]
175
+ resp_list = engine.infer(infer_requests, request_config)
176
+ query0 = infer_requests[0].messages[0]['content']
177
+ print(f'response0: {resp_list[0].choices[0].message.content}')
178
+ print(f'response1: {resp_list[1].choices[0].message.content}')
179
+ print(f'response2: {resp_list[2].choices[0].message.content}')
180
+ ```
181
+
182
+ 我们也提供了更多使用python推理的demo:
183
+ - 使用流式推理以及`VllmEngine`、`LmdeployEngine`进行推理加速,可以参考[这里](https://github.com/modelscope/ms-swift/blob/main/examples/infer/demo.py)。
184
+ - 多模态推理:除了上述多模态输入格式外,swift兼容OpenAI的多模态输入格式,参考[这里](https://github.com/modelscope/ms-swift/blob/main/examples/infer/demo_mllm.py)。
185
+ - grounding任务:对多模态模型进行Grounding任务画框,可以参考[这里](https://github.com/modelscope/ms-swift/blob/main/examples/infer/demo_grounding.py)。
186
+ - 多LoRA推理:参考[这里](https://github.com/modelscope/ms-swift/blob/main/examples/infer/demo_lora.py)。
187
+ - agent推理:参考[这里](https://github.com/modelscope/ms-swift/blob/main/examples/infer/demo_agent.py)。
188
+ - 异步接口:使用`engine.infer_async`进行python方式推理,参考[这里](https://github.com/modelscope/ms-swift/blob/main/examples/infer/demo.py)。
189
+
190
+
191
+ ## 部署
192
+
193
+ 如果要查看LoRA微调后模型的部署,可以参考[预训练与微调文档](./预训练与微调.md#部署微调后模型)。
194
+
195
+ 这里主要介绍对多模态模型的部署和调用,文本大模型我们给出简单的部署和调用的简单案例:
196
+
197
+ 服务端部署:
198
+ ```shell
199
+ CUDA_VISIBLE_DEVICES=0 swift deploy \
200
+ --model Qwen/Qwen2.5-7B-Instruct \
201
+ --infer_backend vllm \
202
+ --max_new_tokens 2048 \
203
+ --served_model_name Qwen2.5-7B-Instruct
204
+ ```
205
+
206
+ 客户端调用测试:
207
+ ```shell
208
+ curl http://localhost:8000/v1/chat/completions \
209
+ -H "Content-Type: application/json" \
210
+ -d '{
211
+ "model": "Qwen2.5-7B-Instruct",
212
+ "messages": [{"role": "user", "content": "晚上睡不着觉怎么办?"}],
213
+ "max_tokens": 256,
214
+ "temperature": 0
215
+ }'
216
+ ```
217
+
218
+
219
+ ### 服务端
220
+
221
+ ```shell
222
+ # test env: pip install transformers==4.49.* vllm==0.7.3
223
+ CUDA_VISIBLE_DEVICES=0 \
224
+ MAX_PIXELS=1003520 \
225
+ VIDEO_MAX_PIXELS=50176 \
226
+ FPS_MAX_FRAMES=12 \
227
+ swift deploy \
228
+ --model Qwen/Qwen2.5-VL-3B-Instruct \
229
+ --infer_backend vllm \
230
+ --gpu_memory_utilization 0.9 \
231
+ --max_model_len 8192 \
232
+ --max_new_tokens 2048 \
233
+ --limit_mm_per_prompt '{"image": 5, "video": 2}' \
234
+ --served_model_name Qwen2.5-VL-3B-Instruct
235
+ ```
236
+
237
+
238
+ ### 客户端
239
+
240
+ 这里介绍3种调用客户端的方式,分别是curl、openai库和swift客户端。
241
+
242
+
243
+ 方案一: curl
244
+ ```shell
245
+ curl http://localhost:8000/v1/chat/completions \
246
+ -H "Content-Type: application/json" \
247
+ -d '{
248
+ "model": "Qwen2.5-VL-3B-Instruct",
249
+ "messages": [{"role": "user", "content": [
250
+ {"type": "image", "image": "http://modelscope-open.oss-cn-hangzhou.aliyuncs.com/images/cat.png"},
251
+ {"type": "image", "image": "http://modelscope-open.oss-cn-hangzhou.aliyuncs.com/images/animal.png"},
252
+ {"type": "text", "text": "两张图的区别是什么?"}
253
+ ]}],
254
+ "max_tokens": 256,
255
+ "temperature": 0
256
+ }'
257
+ ```
258
+
259
+ 方案2: openai库
260
+ ```python
261
+ from openai import OpenAI
262
+
263
+ client = OpenAI(
264
+ api_key='EMPTY',
265
+ base_url=f'http://127.0.0.1:8000/v1',
266
+ )
267
+ model = client.models.list().data[0].id
268
+ print(f'model: {model}')
269
+
270
+ messages = [{'role': 'user', 'content': [
271
+ {'type': 'video', 'video': 'https://modelscope-open.oss-cn-hangzhou.aliyuncs.com/images/baby.mp4'},
272
+ {'type': 'text', 'text': 'describe the video'}
273
+ ]}]
274
+
275
+ resp = client.chat.completions.create(model=model, messages=messages, max_tokens=512, temperature=0)
276
+ query = messages[0]['content']
277
+ response = resp.choices[0].message.content
278
+ print(f'query: {query}')
279
+ print(f'response: {response}')
280
+
281
+ # base64
282
+ import base64
283
+ import requests
284
+ resp = requests.get('https://modelscope-open.oss-cn-hangzhou.aliyuncs.com/images/baby.mp4')
285
+ base64_encoded = base64.b64encode(resp.content).decode('utf-8')
286
+ messages = [{'role': 'user', 'content': [
287
+ {'type': 'video', 'video': f'data:video/mp4;base64,{base64_encoded}'},
288
+ {'type': 'text', 'text': 'describe the video'}
289
+ ]}]
290
+
291
+ gen = client.chat.completions.create(model=model, messages=messages, stream=True, temperature=0)
292
+ print(f'query: {query}\nresponse: ', end='')
293
+ for chunk in gen:
294
+ if chunk is None:
295
+ continue
296
+ print(chunk.choices[0].delta.content, end='', flush=True)
297
+ print()
298
+ ```
299
+
300
+ 方案三:swift客户端
301
+
302
+ ```python
303
+ from swift.llm import InferRequest, InferClient, RequestConfig
304
+ from swift.plugin import InferStats
305
+
306
+
307
+ engine = InferClient(host='127.0.0.1', port=8000)
308
+ print(f'models: {engine.models}')
309
+ metric = InferStats()
310
+ request_config = RequestConfig(max_tokens=512, temperature=0)
311
+
312
+ # 这里使用了3个infer_request来展示batch推理
313
+ # 支持传入本地路径、base64和url
314
+ infer_requests = [
315
+ InferRequest(messages=[{'role': 'user', 'content': 'who are you?'}]),
316
+ InferRequest(messages=[{'role': 'user', 'content': '<image><image>两张图的区别是什么?'}],
317
+ images=['http://modelscope-open.oss-cn-hangzhou.aliyuncs.com/images/cat.png',
318
+ 'http://modelscope-open.oss-cn-hangzhou.aliyuncs.com/images/animal.png']),
319
+ InferRequest(messages=[{'role': 'user', 'content': '<video>describe the video'}],
320
+ videos=['https://modelscope-open.oss-cn-hangzhou.aliyuncs.com/images/baby.mp4']),
321
+ ]
322
+
323
+ resp_list = engine.infer(infer_requests, request_config, metrics=[metric])
324
+ print(f'response0: {resp_list[0].choices[0].message.content}')
325
+ print(f'response1: {resp_list[1].choices[0].message.content}')
326
+ print(f'response2: {resp_list[2].choices[0].message.content}')
327
+ print(metric.compute())
328
+ metric.reset()
329
+
330
+ # base64
331
+ import base64
332
+ import requests
333
+ resp = requests.get('https://modelscope-open.oss-cn-hangzhou.aliyuncs.com/images/baby.mp4')
334
+ base64_encoded = base64.b64encode(resp.content).decode('utf-8')
335
+ messages = [{'role': 'user', 'content': [
336
+ {'type': 'video', 'video': f'data:video/mp4;base64,{base64_encoded}'},
337
+ {'type': 'text', 'text': 'describe the video'}
338
+ ]}]
339
+ infer_request = InferRequest(messages=messages)
340
+ request_config = RequestConfig(max_tokens=512, temperature=0, stream=True)
341
+ gen_list = engine.infer([infer_request], request_config, metrics=[metric])
342
+ print(f'response0: ', end='')
343
+ for chunk in gen_list[0]:
344
+ if chunk is None:
345
+ continue
346
+ print(chunk.choices[0].delta.content, end='', flush=True)
347
+ print()
348
+ print(metric.compute())
349
+ ```
350
+ 我们也提供了更多部署的demo:
351
+ - 多LoRA部署与调用: 参考[这里](https://github.com/modelscope/ms-swift/tree/main/examples/deploy/lora)。
352
+ - Base模型的部署与调用: 参考[这里](https://github.com/modelscope/ms-swift/tree/main/examples/deploy/client/llm/base)。
353
+ - 更多模型类型: 我们提供了[bert](https://github.com/modelscope/ms-swift/tree/main/examples/deploy/bert)、[reward_model](https://github.com/modelscope/ms-swift/tree/main/examples/deploy/reward_model)的部署脚本。