yuccaaa commited on
Commit
b7f5bc5
·
verified ·
1 Parent(s): 86283fd

Upload ms-swift/docs/source/Instruction/预训练与微调.md with huggingface_hub

Browse files
ms-swift/docs/source/Instruction/预训练与微调.md ADDED
@@ -0,0 +1,317 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 预训练与微调
2
+
3
+ 训练能力:
4
+
5
+ | 方法 | 全参数 | LoRA | QLoRA | Deepspeed | 多机 | 多模态 |
6
+ | ------ | ------ | ---- | ----- | ------ | ------ | ------ |
7
+ | 预训练 | [✅](https://github.com/modelscope/ms-swift/blob/main/examples/train/pretrain/train.sh) | ✅ | ✅ | ✅ | ✅ | ✅ |
8
+ | 指令监督微调 | [✅](https://github.com/modelscope/ms-swift/blob/main/examples/train/full/train.sh) | [✅](https://github.com/modelscope/ms-swift/blob/main/examples/train/lora_sft.sh) | [✅](https://github.com/modelscope/ms-swift/tree/main/examples/train/qlora) | [✅](https://github.com/modelscope/ms-swift/tree/main/examples/train/multi-gpu/deepspeed) | [✅](https://github.com/modelscope/ms-swift/tree/main/examples/train/multi-node) | [✅](https://github.com/modelscope/ms-swift/tree/main/examples/train/multimodal) |
9
+ | DPO训练 | ✅ | [✅](https://github.com/modelscope/ms-swift/blob/main/examples/train/rlhf/dpo.sh) | ✅ | [✅](https://github.com/modelscope/ms-swift/blob/main/examples/train/rlhf/dpo.sh) | ✅ | [✅](https://github.com/modelscope/ms-swift/blob/main/examples/train/multimodal/rlhf/dpo.sh) |
10
+ | GRPO训练 | [✅](https://github.com/modelscope/ms-swift/blob/main/examples/train/grpo/grpo_zero2.sh) | ✅ | ✅ | ✅ | [✅](https://github.com/modelscope/ms-swift/blob/main/examples/train/grpo/multi_node) | ✅ |
11
+ | 奖励模型训练 | ✅ | [✅](https://github.com/modelscope/ms-swift/blob/main/examples/train/rlhf/rm.sh) | ✅ | [✅](https://github.com/modelscope/ms-swift/blob/main/examples/train/rlhf/rm.sh) | ✅ | ✅ |
12
+ | PPO训练 | ✅ | [✅](https://github.com/modelscope/ms-swift/blob/main/examples/train/rlhf/ppo.sh) | ✅ | [✅](https://github.com/modelscope/ms-swift/blob/main/examples/train/rlhf/ppo.sh) | ✅ | ❌ |
13
+ | KTO训练 | ✅ | [✅](https://github.com/modelscope/ms-swift/blob/main/examples/train/rlhf/kto.sh) | ✅ | [✅](https://github.com/modelscope/ms-swift/blob/main/examples/train/rlhf/kto.sh) | ✅ | [✅](https://github.com/modelscope/ms-swift/blob/main/examples/train/multimodal/rlhf/kto.sh) |
14
+ | CPO训练 | ✅ | [✅](https://github.com/modelscope/ms-swift/blob/main/examples/train/rlhf/cpo.sh) | ✅ | [✅](https://github.com/modelscope/ms-swift/blob/main/examples/train/rlhf/cpo.sh) | ✅ | ✅ |
15
+ | SimPO训练 | ✅ | [✅](https://github.com/modelscope/ms-swift/blob/main/examples/train/rlhf/simpo.sh) | ✅ | [✅](https://github.com/modelscope/ms-swift/blob/main/examples/train/rlhf/simpo.sh) | ✅ | ✅ |
16
+ | ORPO训练 | ✅ | [✅](https://github.com/modelscope/ms-swift/blob/main/examples/train/rlhf/orpo.sh) | ✅ | [✅](https://github.com/modelscope/ms-swift/blob/main/examples/train/rlhf/orpo.sh) | ✅ | ✅ |
17
+ | 分类模型训练 | ✅ | [✅](https://github.com/modelscope/ms-swift/blob/main/examples/train/seq_cls/qwen2_5/sft.sh) | ✅ | ✅ | ✅ | [✅](https://github.com/modelscope/ms-swift/blob/main/examples/train/seq_cls/qwen2_vl/sft.sh) |
18
+ | Embedding模型训练 | ✅ | [✅](https://github.com/modelscope/ms-swift/blob/main/examples/train/embedding/train_gte.sh) | ✅ | ✅ | ✅ | [✅](https://github.com/modelscope/ms-swift/blob/main/examples/train/embedding/train_gme.sh) |
19
+
20
+
21
+ ## 环境准备
22
+ 推荐的第三方库版本参考[SWIFT安装文档](../GetStarted/SWIFT安装.md)
23
+ ```bash
24
+ pip install ms-swift -U
25
+
26
+ # 若使用deepspeed zero2/zero3
27
+ pip install deepspeed -U
28
+ ```
29
+
30
+ ## 预训练
31
+ 预训练使用`swift pt`命令,这将自动使用生成式而非对话式的template,即将`use_chat_template`设置为False(其他所有的命令,例如`swift sft/rlhf/infer`,都默认将`use_chat_template`设置为True)。此外,`swift pt`与`swift sft`相比,具有不同的数据集格式,可以参考[自定义数据集文档](../Customization/自定义数据集.md)。
32
+
33
+ 使用CLI进行预训练的脚本可以参考[这里](https://github.com/modelscope/swift/blob/main/examples/train/pretrain/train.sh)。更多训练技术的介绍可以参考微调章节。
34
+
35
+ 小贴士:
36
+ - `swift pt`与`swift sft --use_chat_template false`等价。
37
+ - `swift pt`通常会使用大数据集,建议与`--streaming`流式数据集结合使用。
38
+
39
+ ## 微调
40
+
41
+ ms-swift使用了分层式的设计思想,用户可以使用命令行界面、Web-UI界面和直接使用Python的方式进行微调。
42
+
43
+ ### 使用CLI
44
+
45
+ 我们提供了10分钟在单卡3090上对Qwen2.5-7B-Instruct进行自我认知微调的最佳实践,具体参考[这里](../GetStarted/快速开始.md),这可以帮助您快速了解SWIFT。
46
+
47
+ 此外,我们给出了一系列脚本帮助您了解SWIFT的训练能力:
48
+
49
+ - 轻量化训练:SWIFT支持的轻量微调示例可以参考[这里](https://github.com/modelscope/swift/blob/main/examples/train/tuners)。(注意:这些方式预训练也可以使用,但预训练通常使用全参数训练)。
50
+ - 分布式训练:SWIFT支持的分布式训练技术包括:DDP、device_map、DeepSpeed ZeRO2/ZeRO3、FSDP。
51
+ - device_map: 简易模型并行。如果存在多GPU,device_map会自动开启。���会将模型按层均匀的划分到可见的GPU中,显著降低显存消耗,但是训练速度通常会降低,因为是串行的。
52
+ - DDP+device_map:将按组对模型进行device_map划分,参考[这里](https://github.com/modelscope/ms-swift/blob/main/examples/train/multi-gpu/ddp_device_map/train.sh)。
53
+ - DeepSpeed ZeRO2/ZeRO3: 节约显存资源,但训练速度下降。ZeRO2将对优化器状态、模型梯度进行分片。ZeRO3在ZeRO2基础上,对模型参数进行分片,更加节约显存,但训练速度更慢。参考[这里](https://github.com/modelscope/ms-swift/tree/main/examples/train/multi-gpu/deepspeed)。
54
+ - FSDP+QLoRA: 双卡3090运行70B模型的训练,参考[这里](https://github.com/modelscope/ms-swift/tree/main/examples/train/multi-gpu/fsdp_qlora/train.sh)。
55
+ - 多机多卡训练: 我们书写了使用swift、torchrun、dlc、deepspeed、accelerate启动多节点运行的shell脚本示例。除了dlc和deepspeed,其他启动脚本都需要在所有节点中启动才可运行。具体参考[这里](https://github.com/modelscope/swift/blob/main/examples/train/multi-node)。
56
+ - 量化训练:支持使用GPTQ、AWQ、AQLM、BNB、HQQ、EETQ量化技术的QLoRA训练。微调7B模型只需要9GB显存资源。具体参考[这里](https://github.com/modelscope/ms-swift/tree/main/examples/train/qlora)。
57
+ - 多模态训练:SWIFT支持多模态模型的预训练、微调和RLHF。支持Caption、VQA、OCR、[Grounding](https://github.com/modelscope/ms-swift/blob/main/examples/notebook/qwen2_5-vl-grounding/zh.ipynb)任务。支持图像、视频和音频三种模态。具体参考[这里](https://github.com/modelscope/ms-swift/tree/main/examples/train/multimodal)。多模态自定义数据集格式参考[自定义数据集文档](../Customization/自定义数据集.md)。
58
+ - 对ViT/Aligner使用全参数训练,LLM使用LoRA训练,并采用不同学习率的例子参考[这里](https://github.com/modelscope/ms-swift/tree/main/examples/train/multimodal/lora_llm_full_vit)。
59
+ - 多模态模型packing,增加训练速度,例子参考[这里](https://github.com/modelscope/ms-swift/tree/main/examples/train/packing)。
60
+ - RLHF训练:参考[这里](https://github.com/modelscope/ms-swift/tree/main/examples/train/rlhf)。多模态模型参考[这里](https://github.com/modelscope/ms-swift/tree/main/examples/train/multimodal/rlhf)。GRPO训练参考[这里](https://github.com/modelscope/ms-swift/blob/main/examples/train/grpo/grpo_zero2.sh)。强化微调查看[这里](https://github.com/modelscope/ms-swift/tree/main/examples/train/rft)。
61
+ - Megatron训练:支持使用Megatron的并行技术来加速大模型的训练,包括数据并行、张量并行、流水线并行、序列并行,上下文并行。参考[Megatron-SWIFT训练文档](./Megatron-SWIFT训练.md)。
62
+ - 序列分类模型训练:参考[这里](https://github.com/modelscope/ms-swift/tree/main/examples/train/seq_cls)。
63
+ - Embedding模型训练:参考[这里](https://github.com/modelscope/ms-swift/tree/main/examples/train/embedding)
64
+ - Agent训练:参考[这里](https://github.com/modelscope/swift/blob/main/examples/train/agent)。
65
+ - Any-to-Any模型训练:参考[这里](https://github.com/modelscope/swift/blob/main/examples/train/all_to_all)。
66
+ - 其他能力:
67
+ - 数据流式读取: 在数据量较大时减少内存使用。参考[这里](https://github.com/modelscope/swift/blob/main/examples/train/streaming/train.sh)。
68
+ - packing: 将多个序列拼成一个,让每个训练样本尽可能接近max_length,提高显卡利用率,参考[这里](https://github.com/modelscope/swift/blob/main/examples/train/packing/train.sh)。
69
+ - 长文本训练: 参考[这里](https://github.com/modelscope/swift/blob/main/examples/train/long_text)。
70
+ - lazy tokenize: 在训练期间对数据进行tokenize而不是在训练前tokenize(多模态模型可以避免在训练前读入所有多模态资源),这可以避免预处理等待并节约内存。参考[这里](https://github.com/modelscope/swift/blob/main/examples/train/lazy_tokenize/train.sh)。
71
+
72
+ 小帖士:
73
+
74
+ - 在使用`swift sft`通过LoRA技术微调base模型为chat模型时,有时需要手动设置模板。通过添加`--template default`参数来避免base模型因未见过对话模板中的特殊字符而无法正常停止的情况。具体参考[这里](https://github.com/modelscope/ms-swift/tree/main/examples/train/base_to_chat)。
75
+ - 如果需要在**断网**环境下进行训练,请设置`--model <model_dir>`和`--check_model false`。如果对应的模型需要`git clone`github的仓库,例如`deepseek-ai/Janus-Pro-7B`,请设置手动下载仓库,并设置`--local_repo_path <repo_dir>`。具体参数含义请参考[命令行参数文档](命令行参数.md)。
76
+ - 无法对QLoRA训练的模型进行Merge LoRA,因此不建议使用QLoRA进行微调,无法在推理和部署时使用vLLM/LMDeploy进行推理加速。建议使用LoRA/全参数进行微调,合并为完整权重后再使用GPTQ/AWQ/BNB进行[量���](https://github.com/modelscope/ms-swift/tree/main/examples/export/quantize)。
77
+ - 如果使用NPU进行训练,只需要将shell中的`CUDA_VISIBLE_DEVICES`修改为`ASCEND_RT_VISIBLE_DEVICES`。
78
+ - SWIFT默认在训练时设置`--gradient_checkpointing true`来节约显存,这会略微降低训练速度。
79
+ - 若使用DDP进行训练,出现报错:`RuntimeError: Expected to mark a variable ready only once.`,请额外设置参数`--gradient_checkpointing_kwargs '{"use_reentrant": false}'`或者使用DeepSpeed进行训练。
80
+ - 如果要使用deepspeed,你需要安装deepspeed:`pip install deepspeed -U`。使用deepspeed可以节约显存,但会略微降低训练速度。
81
+ - 如果您的机器是A100等高性能显卡,且模型支持flash-attn,推荐你安装[flash-attn](https://github.com/Dao-AILab/flash-attention/releases),并设置`--attn_impl flash_attn`,这将会加快训练和推理的速度并略微降低显存占用。
82
+
83
+ **如何debug:**
84
+
85
+ 你可以使用以下方式进行debug,这与使用命令行微调是等价的,但此方式不支持分布式。微调命令行运行入口可以查看[这里](https://github.com/modelscope/ms-swift/blob/main/swift/cli/sft.py)。
86
+
87
+ ```python
88
+ from swift.llm import sft_main, TrainArguments
89
+ result = sft_main(TrainArguments(
90
+ model='Qwen/Qwen2.5-7B-Instruct',
91
+ train_type='lora',
92
+ dataset=['AI-ModelScope/alpaca-gpt4-data-zh#500',
93
+ 'AI-ModelScope/alpaca-gpt4-data-en#500',
94
+ 'swift/self-cognition#500'],
95
+ torch_dtype='bfloat16',
96
+ # ...
97
+ ))
98
+ ```
99
+
100
+
101
+ ### 使用Web-UI
102
+ 如果你要使用界面的方式进行训练,可以查看[Web-UI文档](../GetStarted/Web-UI.md)。
103
+
104
+ ### 使用python
105
+
106
+ - Qwen2.5自我认知微调notebook查看[这里](https://github.com/modelscope/ms-swift/blob/main/examples/notebook/qwen2_5-self-cognition/self-cognition-sft.ipynb)。
107
+ - Qwen2VL进行OCR任务notebook查看[这里](https://github.com/modelscope/ms-swift/blob/main/examples/notebook/qwen2vl-ocr/ocr-sft.ipynb)。
108
+
109
+
110
+ ## Merge LoRA
111
+
112
+ - 查看[这里](https://github.com/modelscope/ms-swift/blob/main/examples/export/merge_lora.sh)。
113
+
114
+ ## 推理(微调后模型)
115
+
116
+ 使用CLI对LoRA训练的checkpoint进行推理:
117
+ ```shell
118
+ CUDA_VISIBLE_DEVICES=0 \
119
+ swift infer \
120
+ --adapters output/vx-xxx/checkpoint-xxx \
121
+ --infer_backend pt \
122
+ --stream true \
123
+ --temperature 0 \
124
+ --max_new_tokens 2048
125
+ ```
126
+ - adapters文件夹中包含了训练的参数文件`args.json`,因此不需要额外指定`--model`,`--system`,swift会自动读取这些参数。如果要关闭此行为,可以设置`--load_args false`。
127
+ - 如果使用全参数训练,请使用`--model`替代`--adapters`指定训练的checkpoint目录。更多参考[推理和部署文档](./推理和部署.md#推理)。
128
+ - 你可以使用`swift app`替代`swift infer`进行界面推理。
129
+ - 你可以选择对LoRA进行merge(额外指定`--merge_lora true`),然后指定`--infer_backend vllm/lmdeploy`进行推理加速。
130
+
131
+ 对数据集中的验证集进行批量推理:
132
+ ```shell
133
+ CUDA_VISIBLE_DEVICES=0 \
134
+ swift infer \
135
+ --adapters output/vx-xxx/checkpoint-xxx \
136
+ --infer_backend pt \
137
+ --temperature 0 \
138
+ --max_new_tokens 2048 \
139
+ --load_data_args true \
140
+ --max_batch_size 1
141
+ ```
142
+
143
+ - 你可以设置`--max_batch_size 8`,从而使用`--infer_backend pt`进行批量处理。若使用`infer_backend vllm/lmdeploy`则无需指定,会进行自动batch。
144
+ - `--load_data_args true`会额外读取训练存储参数文件`args.json`中的数据参数。
145
+
146
+ 若想对额外的测试集进行推理,而不使用训练时的验证集,使用`--val_dataset <dataset_path>`进行推理:
147
+ ```shell
148
+ CUDA_VISIBLE_DEVICES=0 \
149
+ swift infer \
150
+ --adapters output/vx-xxx/checkpoint-xxx \
151
+ --infer_backend pt \
152
+ --temperature 0 \
153
+ --max_new_tokens 2048 \
154
+ --val_dataset <dataset-path> \
155
+ --max_batch_size 1
156
+ ```
157
+
158
+
159
+ 使用Python对训练后LoRA推理的例子如下:
160
+
161
+ ```python
162
+ import os
163
+ os.environ['CUDA_VISIBLE_DEVICES'] = '0'
164
+
165
+ from swift.llm import (
166
+ PtEngine, RequestConfig, safe_snapshot_download, get_model_tokenizer, get_template, InferRequest
167
+ )
168
+ from swift.tuners import Swift
169
+ # 请调整下面几行
170
+ model = 'Qwen/Qwen2.5-7B-Instruct'
171
+ lora_checkpoint = safe_snapshot_download('swift/test_lora') # 修改成checkpoint_dir
172
+ template_type = None # None: 使用对应模型默认的template_type
173
+ default_system = "You are a helpful assistant." # None: 使用对应模型默认的default_system
174
+
175
+ # 加载模型和对话模板
176
+ model, tokenizer = get_model_tokenizer(model)
177
+ model = Swift.from_pretrained(model, lora_checkpoint)
178
+ template_type = template_type or model.model_meta.template
179
+ template = get_template(template_type, tokenizer, default_system=default_system)
180
+ engine = PtEngine.from_model_template(model, template, max_batch_size=2)
181
+ request_config = RequestConfig(max_tokens=512, temperature=0)
182
+
183
+ # 这里使用了2个infer_request来展示batch推理
184
+ infer_requests = [
185
+ InferRequest(messages=[{'role': 'user', 'content': 'who are you?'}]),
186
+ InferRequest(messages=[{'role': 'user', 'content': '浙江的省会在哪?'},
187
+ {'role': 'assistant', 'content': '浙江的省会在哪?'},
188
+ {'role': 'user', 'content': '这里有什么好吃的'},]),
189
+ ]
190
+ resp_list = engine.infer(infer_requests, request_config)
191
+ query0 = infer_requests[0].messages[0]['content']
192
+ print(f'response0: {resp_list[0].choices[0].message.content}')
193
+ print(f'response1: {resp_list[1].choices[0].message.content}')
194
+ ```
195
+
196
+ 多模态模型的LoRA推理示例如下:
197
+ ```python
198
+ import os
199
+ os.environ['CUDA_VISIBLE_DEVICES'] = '0'
200
+
201
+ from swift.llm import (
202
+ PtEngine, RequestConfig, safe_snapshot_download, get_model_tokenizer, get_template, InferRequest
203
+ )
204
+ from swift.tuners import Swift
205
+ # 请调整下面几行
206
+ model = 'Qwen/Qwen2.5-VL-7B-Instruct'
207
+ lora_checkpoint = safe_snapshot_download('swift/test_grounding') # 修改成checkpoint_dir
208
+ template_type = None # None: 使用对应模型默认的template_type
209
+ default_system = None # None: 使用对应模型默认的default_system
210
+
211
+ # 加载模型和对话模板
212
+ model, tokenizer = get_model_tokenizer(model)
213
+ model = Swift.from_pretrained(model, lora_checkpoint)
214
+ template_type = template_type or model.model_meta.template
215
+ template = get_template(template_type, tokenizer, default_system=default_system)
216
+ engine = PtEngine.from_model_template(model, template, max_batch_size=2)
217
+ request_config = RequestConfig(max_tokens=512, temperature=0)
218
+
219
+ # 这里使用了2个infer_request来展示batch推理
220
+ infer_requests = [
221
+ InferRequest(messages=[{'role': 'user', 'content': 'who are you?'}]),
222
+ InferRequest(messages=[{'role': 'user', 'content': '<image>Task: Object Detection'}],
223
+ images=['http://modelscope-open.oss-cn-hangzhou.aliyuncs.com/images/animal.png']),
224
+ ]
225
+ resp_list = engine.infer(infer_requests, request_config)
226
+ query0 = infer_requests[0].messages[0]['content']
227
+ print(f'response0: {resp_list[0].choices[0].message.content}')
228
+ print(f'response1: {resp_list[1].choices[0].message.content}')
229
+ ```
230
+
231
+ 如果使用ms-swift训练的模型,可以通过以下方式获取训练的配置:
232
+ ```python
233
+ from swift.llm import safe_snapshot_download, BaseArguments
234
+
235
+ lora_adapters = safe_snapshot_download('swift/test_lora')
236
+ args = BaseArguments.from_pretrained(lora_adapters)
237
+ print(f'args.model: {args.model}')
238
+ print(f'args.model_type: {args.model_type}')
239
+ print(f'args.template_type: {args.template}')
240
+ print(f'args.default_system: {args.system}')
241
+ ```
242
+
243
+ - 对全参数训练的checkpoint进行推理,将`model`设置为checkpoint_dir,并将lora_checkpoint设置为None即可。更多参考[推理和部署文档](./推理和部署.md#推理)。
244
+ - 使用流式推理以及`VllmEngine`、`LmdeployEngine`进行推理加速,可以参考[大模型](https://github.com/modelscope/ms-swift/blob/main/examples/infer/demo.py)和[多模态大模型](https://github.com/modelscope/ms-swift/blob/main/examples/infer/demo_mllm.py)推理示例。
245
+ - 微调后的模型使用huggingface transformers/peft生态推理,可以参考[这里](https://github.com/modelscope/ms-swift/blob/main/examples/infer/demo_hf.py)。
246
+ - 若训练了多个LoRA,要进行多LoRA切换,可以参考[推理](https://github.com/modelscope/ms-swift/blob/main/examples/infer/demo_lora.py)、[部署](https://github.com/modelscope/ms-swift/tree/main/examples/deploy/lora)样例。
247
+ - 对多模态模型进行Grounding任务的画框,可以参考[这里](https://github.com/modelscope/ms-swift/blob/main/examples/infer/demo_grounding.py)。
248
+ - 对LoRA微调后的Bert进行推理,可以参考[这里](https://github.com/modelscope/ms-swift/blob/main/examples/infer/demo_bert.py)。
249
+
250
+
251
+ ## 部署(微调后模型)
252
+
253
+ 使用以下命令启动部署服务端。如果权重使用全参数训练,请使用`--model`替代`--adapters`指定训练的checkpoint目录。你可以参考[推理和部署文档](./推理和部署.md#部署)介绍的客户端调用方式:curl、openai库和swift客户端进行调用。
254
+
255
+ ```shell
256
+ CUDA_VISIBLE_DEVICES=0 \
257
+ swift deploy \
258
+ --adapters output/vx-xxx/checkpoint-xxx \
259
+ --infer_backend pt \
260
+ --temperature 0 \
261
+ --max_new_tokens 2048 \
262
+ --served_model_name '<model-name>'
263
+ ```
264
+
265
+ 这里将给出使用vLLM对多LoRA进行部署并调用的完整例子。
266
+
267
+ ### 服务端
268
+ 首先你需要安装vLLM:`pip install vllm -U`,并在部署时使用`--infer_backend vllm`,这通常可以显著加速推理速度。
269
+
270
+ 我们预先训练了2个基模型为`Qwen/Qwen2.5-7B-Instruct`的不同自我认知LoRA增量权重(可以直接跑通),我们可以在[args.json](https://modelscope.cn/models/swift/test_lora/file/view/master)中找到相关信息。你需要在部署时修改`--adapters`指定训练好的LoRA权重本地路径即可。
271
+ ```bash
272
+ CUDA_VISIBLE_DEVICES=0 \
273
+ swift deploy \
274
+ --adapters lora1=swift/test_lora lora2=swift/test_lora2 \
275
+ --infer_backend vllm \
276
+ --temperature 0 \
277
+ --max_new_tokens 2048
278
+ ```
279
+
280
+ ### 客户端
281
+
282
+ 这里只介绍使用openai库进行调用。使用curl、swift客户端调用的例子可以参考[推理和部署文档](./推理和部署.md#部署)。
283
+
284
+ ```python
285
+ from openai import OpenAI
286
+
287
+ client = OpenAI(
288
+ api_key='EMPTY',
289
+ base_url=f'http://127.0.0.1:8000/v1',
290
+ )
291
+ models = [model.id for model in client.models.list().data]
292
+ print(f'models: {models}')
293
+
294
+ query = 'who are you?'
295
+ messages = [{'role': 'user', 'content': query}]
296
+
297
+ resp = client.chat.completions.create(model=models[1], messages=messages, max_tokens=512, temperature=0)
298
+ query = messages[0]['content']
299
+ response = resp.choices[0].message.content
300
+ print(f'query: {query}')
301
+ print(f'response: {response}')
302
+
303
+ gen = client.chat.completions.create(model=models[2], messages=messages, stream=True, temperature=0)
304
+ print(f'query: {query}\nresponse: ', end='')
305
+ for chunk in gen:
306
+ if chunk is None:
307
+ continue
308
+ print(chunk.choices[0].delta.content, end='', flush=True)
309
+ print()
310
+ """
311
+ models: ['Qwen2.5-7B-Instruct', 'lora1', 'lora2']
312
+ query: who are you?
313
+ response: I am an artificial intelligence model named swift-robot, developed by swift. I can answer your questions, provide information, and engage in conversation. If you have any inquiries or need assistance, feel free to ask me at any time.
314
+ query: who are you?
315
+ response: I am an artificial intelligence model named Xiao Huang, developed by ModelScope. I can answer your questions, provide information, and engage in conversation. If you have any inquiries or need assistance, feel free to ask me at any time.
316
+ """
317
+ ```