组件
Finetune
lazyllm.components.finetune.AlpacaloraFinetune
Bases: LazyLLMFinetuneBase
此类是 LazyLLMFinetuneBase 的子类,基于 alpaca-lora 项目提供的 LoRA 微调能力,用于对大语言模型进行 LoRA 微调。
Parameters:
-
base_model(str) –用于微调的基模型本地路径。
-
target_path(str) –微调后 LoRA 权重保存路径。
-
merge_path(Optional[str], default:None) –合并 LoRA 权重后的模型保存路径,默认
None。 若未提供,则在target_path下创建 "lazyllm_lora" 与 "lazyllm_merge" 目录。 -
model_name(Optional[str], default:'LLM') –模型名称,用于日志前缀,默认
LLM。 -
cp_files(Optional[str], default:'tokeniz*') –从基模型路径复制配置文件到
merge_path,默认tokeniz*。 -
launcher(launcher, default:remote(ngpus=1)) –微调启动器,默认
launchers.remote(ngpus=1)。 -
kw(dict, default:{}) –用于更新默认训练参数的关键字参数,允许更新如下参数:
Other Parameters:
-
data_path(Optional[str]) –数据路径,默认
None。 -
batch_size(Optional[int]) –批大小,默认 64。
-
micro_batch_size(Optional[int]) –微批大小,默认 4。
-
num_epochs(Optional[int]) –训练轮数,默认 2。
-
learning_rate(Optional[float]) –学习率,默认 5.e-4。
-
cutoff_len(Optional[int]) –截断长度,默认 1030。
-
filter_nums(Optional[int]) –过滤器数量,默认 1024。
-
val_set_size(Optional[int]) –验证集大小,默认 200。
-
lora_r(Optional[int]) –LoRA 秩,默认 8。
-
lora_alpha(Optional[int]) –LoRA 融合因子,默认 32。
-
lora_dropout(Optional[float]) –LoRA 丢弃率,默认 0.05。
-
lora_target_modules(Optional[str]) –LoRA 目标模块,默认
[wo,wqkv]。 -
modules_to_save(Optional[str]) –全量微调模块,默认
[tok_embeddings,output]。 -
deepspeed(Optional[str]) –DeepSpeed 配置路径,默认使用仓库预制 ds.json。
-
prompt_template_name(Optional[str]) –提示模板名称,默认
alpaca。 -
train_on_inputs(Optional[bool]) –是否在输入上训练,默认
True。 -
show_prompt(Optional[bool]) –是否显示提示,默认
False。 -
nccl_port(Optional[int]) –NCCL 端口,默认随机在 19000-20500。
Examples:
>>> from lazyllm import finetune
>>> trainer = finetune.alpacalora('path/to/base/model', 'path/to/target')
Source code in lazyllm/components/finetune/alpacalora.py
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 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 | |
cmd(trainset, valset=None)
生成用于执行Alpaca-LoRA微调和模型合并的shell命令序列。
Parameters:
-
trainset(str) –训练数据集路径,支持相对data_path配置的路径或绝对路径
-
valset(str, default:None) –验证数据集路径,未指定时将从训练集中自动划分
Returns:
- str or list: 当不需要合并模型时返回单个命令字符串,需要合并时返回包含微调命令、合并命令和文件拷贝命令的列表
Examples:
>>> from lazyllm import finetune
>>> trainer = finetune.alpacalora('path/to/base/model', 'path/to/target')
>>> cmd = trainer.cmd("my_dataset.json")
Source code in lazyllm/components/finetune/alpacalora.py
lazyllm.components.finetune.CollieFinetune
Bases: LazyLLMFinetuneBase
此类是 LazyLLMFinetuneBase 的子类,基于 Collie 框架提供的 LoRA 微调能力,用于对大语言模型进行 LoRA 微调。
Parameters:
-
base_model(str) –用于微调的基模型路径。
-
target_path(str) –微调后 LoRA 权重保存路径。
-
merge_path(Optional[str], default:None) –合并 LoRA 权重后的模型路径,默认
None。 若未提供,则在target_path下创建 "lazyllm_lora" 与 "lazyllm_merge" 目录。 -
model_name(Optional[str], default:'LLM') –模型名称,用于日志前缀,默认 "LLM"。
-
cp_files(Optional[str], default:'tokeniz*') –指定从基模型路径复制到
merge_path的配置文件,默认 "tokeniz*"。 -
launcher(launcher, default:remote(ngpus=1)) –微调启动器,默认
launchers.remote(ngpus=1)。 -
kw(dict, default:{}) –用于更新默认训练参数的关键字参数。仅允许更新如下参数:
Other Parameters:
-
data_path(Optional[str]) –数据路径,默认
None。 -
batch_size(Optional[int]) –批大小,默认 64。
-
micro_batch_size(Optional[int]) –微批大小,默认 4。
-
num_epochs(Optional[int]) –训练轮数,默认 3。
-
learning_rate(Optional[float]) –学习率,默认 5.e-4。
-
dp_size(Optional[int]) –数据并行参数,默认 8。
-
pp_size(Optional[int]) –流水线并行参数,默认 1。
-
tp_size(Optional[int]) –张量并行参数,默认 1。
-
lora_r(Optional[int]) –LoRA 秩,默认 8。
-
lora_alpha(Optional[int]) –LoRA 融合因子,默认 16。
-
lora_dropout(Optional[float]) –LoRA 丢弃率,默认 0.05。
-
lora_target_modules(Optional[str]) –LoRA 目标模块,默认
[wo,wqkv]。 -
modules_to_save(Optional[str]) –全量微调模块,默认
[tok_embeddings,output]。 -
prompt_template_name(Optional[str]) –提示模板名称,默认 "alpaca"。
Examples:
>>> from lazyllm import finetune
>>> trainer = finetune.collie('path/to/base/model', 'path/to/target')
Source code in lazyllm/components/finetune/collie.py
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 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 | |
lazyllm.components.finetune.LlamafactoryFinetune
Bases: LazyLLMFinetuneBase
此类是 LazyLLMFinetuneBase 的子类,基于 LLaMA-Factory 框架提供的训练能力,用于对大语言模型(或视觉语言模型)进行训练。
Parameters:
-
base_model–用于进行训练的基模型路径。支持本地路径,若路径不存在则尝试从配置的模型路径中查找。
-
target_path–训练完成后,模型权重保存的目标路径。
-
merge_path(str, default:None) –模型合并LoRA权重后的保存路径,默认为None。 如果未指定,将在
target_path下自动创建两个目录: - "lazyllm_lora"(用于存放LoRA训练权重) - "lazyllm_merge"(用于存放合并后的模型权重) -
config_path(str, default:None) –训练配置的 YAML 文件路径,默认None。 如果未指定,则使用默认配置文件
llama_factory/sft.yaml。 配置文件支持覆盖默认训练参数。 -
export_config_path(str, default:None) –LoRA权重合并导出配置的 YAML 文件路径,默认None。 如果未指定,则使用默认配置文件
llama_factory/lora_export.yaml。 -
lora_r(int, default:None) –LoRA的秩(rank),若提供则覆盖配置中的
lora_rank。 -
modules_to_save(str, default:None) –额外需要保存的模型模块名称列表,格式类似于Python列表字符串,如 "[module1,module2]"。
-
lora_target_modules(str, default:None) –目标LoRA微调的模块名称列表,格式同上。
-
launcher(launcher, default:remote(ngpus=1, sync=True)) –微调任务的启动器,默认为单卡同步远程启动器
launchers.remote(ngpus=1, sync=True)。 -
**kw–关键字参数,用于动态覆盖默认训练配置中的参数。
此类的关键字参数及其默认值如下:
Other Parameters:
-
stage(Literal['pt', 'sft', 'rm', 'ppo', 'dpo', 'kto']) –默认值是:
sft。将在训练中执行的阶段。 -
do_train(bool) –默认值是:
True。是否运行训练。 -
finetuning_type(Literal['lora', 'freeze', 'full']) –默认值是:
lora。要使用的微调方法。 -
lora_target(str) –默认值是:
all。要应用LoRA的目标模块的名称。使用逗号分隔多个模块。使用all指定所有线性模块。 -
template(Optional[str]) –默认值是:
None。用于构建训练和推理提示的模板。 -
cutoff_len(int) –默认值是:
1024。数据集中token化后输入的截止长度。 -
max_samples(Optional[int]) –默认值是:
1000。出于调试目的,截断每个数据集的示例数量。 -
overwrite_cache(bool) –默认值是:
True。覆盖缓存的训练和评估集。 -
preprocessing_num_workers(Optional[int]) –默认值是:
16。用于预处理的进程数。 -
dataset_dir(str) –默认值是:
lazyllm_temp_dir。包含数据集的文件夹的路径。如果没有明确指定,LazyLLM将在当前工作目录的.temp文件夹中生成一个dataset_info.json文件,供LLaMA-Factory使用。 -
logging_steps(float) –默认值是:
10。每X个更新步骤记录一次日志。应该是整数或范围在[0,1)的浮点数。如果小于1,将被解释为总训练步骤的比例。 -
save_steps(float) –默认值是:
500。每X个更新步骤保存一次检查点。应该是整数或范围在[0,1)的浮点数。如果小于1,将被解释为总训练步骤的比例。 -
plot_loss(bool) –默认值是:
True。是否保存训练损失曲线。 -
overwrite_output_dir(bool) –默认值是:
True。覆盖输出目录的内容。 -
per_device_train_batch_size(int) –默认值是:
1。每个GPU/TPU/MPS/NPU核心/CPU的训练批次的大小。 -
gradient_accumulation_steps(int) –默认值是:
8。在执行反向传播及参数更新前,要累积的更新步骤数。 -
learning_rate(float) –默认值是:
1e-04。AdamW的初始学习率。 -
num_train_epochs(float) –默认值是:
3.0。要执行的总训练周期数。 -
lr_scheduler_type(Union[SchedulerType, str]) –默认值是:
cosine。要使用的调度器类型。 -
warmup_ratio(float) –默认值是:
0.1。在总步骤的warmup_ratio分之一阶段内进行线性预热。 -
fp16(bool) –默认值是:
True。是否使用fp16(混合)精度,而不是32位。 -
ddp_timeout(Optional[int]) –默认值是:
180000000。覆盖分布式训练的默认超时时间(值应以秒为单位给出)。 -
report_to(Union[NoneType, str, List[str]]) –默认值是:
tensorboard。要将结果和日志报告到的集成列表。 -
val_size(float) –默认值是:
0.1。验证集的大小,应该是整数或范围在[0,1)的浮点数。 -
per_device_eval_batch_size(int) –默认值是:
1。每个GPU/TPU/MPS/NPU核心/CPU的验证集批次大小。 -
eval_strategy(Union[IntervalStrategy, str]) –默认值是:
steps。要使用的验证评估策略。 -
eval_steps(Optional[float]) –默认值是:
500。每X个步骤运行一次验证评估。应该是整数或范围在[0,1)的浮点数。如果小于1,将被解释为总训练步骤的比例。
Examples:
>>> from lazyllm import finetune
>>> trainer = finetune.llamafactory('internlm2-chat-7b', 'path/to/target')
<lazyllm.llm.finetune type=LlamafactoryFinetune>
Source code in lazyllm/components/finetune/llamafactory.py
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 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 | |
cmd(trainset, valset=None)
生成LLaMA-Factory微调命令序列,包括训练和模型合并命令。
Parameters:
-
trainset(str) –训练数据集路径(支持相对lazyllm.config['data_path']的路径)
-
valset(str, default:None) –验证数据集路径(当前实现中未直接使用)
Returns:
- str: 完整的shell命令字符串,包含:
- 训练命令(自动配置参数)
- 日志重定向(保存到目标路径)
- 可选的模型合并命令(当配置LoRA时)
注意事项
- 自动生成带时间戳的训练日志文件
- 临时文件会在使用后自动清理
- 支持多种数据格式(alpaca/sharegpt等)
- 多模态数据(图像/视频/音频)会自动检测处理
Source code in lazyllm/components/finetune/llamafactory.py
lazyllm.components.deploy.LazyLLMDeployBase
Bases: ComponentBase
此类是 ComponentBase 的一个子类,提供了LazyLLM部署的基础功能。它支持多种媒体类型的编码转换,并提供了结果提取和流式处理的配置选项。
Parameters:
-
launcher(LauncherBase, default:remote()) –用于部署的启动器实例,默认为远程启动器(
launchers.remote())。
注意事项
- 继承此类时需要实现具体的部署逻辑
- 可以通过重写extract_result方法来自定义结果提取逻辑
Examples:
>>> import lazyllm
>>> from lazyllm.components.deploy.base import LazyLLMDeployBase
>>> class MyDeployer(LazyLLMDeployBase):
... def __call__(self, inputs):
... return processed_result
def extract_result(output, inputs):
... return output.json()['result']
>>> deployer = MyDeployer()
>>> result = deployer.extract_result(raw_output, input_data)
Source code in lazyllm/components/deploy/base.py
extract_result(output, inputs)
staticmethod
从模型输出中提取最终结果,默认实现直接返回原始输出,子类可重写此方法实现自定义结果提取逻辑。
Parameters:
-
output–模型原始输出
-
inputs–原始输入数据,可用于结果后处理
Returns:
- 处理后的最终结果
lazyllm.components.deploy.LazyLLMDeployBase.extract_result(output, inputs)
staticmethod
从模型输出中提取最终结果,默认实现直接返回原始输出,子类可重写此方法实现自定义结果提取逻辑。
Parameters:
-
output–模型原始输出
-
inputs–原始输入数据,可用于结果后处理
Returns:
- 处理后的最终结果
lazyllm.components.finetune.FlagembeddingFinetune
Bases: LazyLLMFinetuneBase
该类是 LazyLLMFinetuneBase 的子类,基于 FlagEmbedding 框架提供的训练能力,用于训练嵌入和重排模型。
Parameters:
-
base_model(str) –用于训练的基础模型。必须是基础模型的路径。
-
target_path(str) –训练后模型权重保存的路径。
-
launcher(launcher, default:remote(ngpus=1, sync=True)) –微调的启动器,默认为
launchers.remote(ngpus=1, sync=True)。 -
kw–用于更新默认训练参数的关键字参数。
该类嵌入模型的关键字参数及其默认值如下:
Other Parameters:
-
train_group_size(int) –默认为:
8。训练组的大小。用于控制每个训练集中的负样本数量。 -
query_max_len(int) –默认为:
512。经过分词后,段落的最大总输入序列长度。超过此长度的序列将被截断,较短的序列将被填充。 -
passage_max_len(int) –默认为:
512。经过分词后,段落的最大总输入序列长度。超过此长度的序列将被截断,较短的序列将被填充。 -
pad_to_multiple_of(int) –默认为:
8。如果设置,将序列填充为提供值的倍数。 -
query_instruction_for_retrieval(str) –默认为:
Represent this sentence for searching relevant passages:。查询query的指令。 -
query_instruction_format(str) –默认为:
{}{}。查询指令格式。 -
learning_rate(float) –默认为:
1e-5。学习率。 -
num_train_epochs(int) –默认为:
1。要执行的总训练周期数。 -
per_device_train_batch_size(int) –默认为:
2。训练批量大小。 -
gradient_accumulation_steps(int) –默认为:
1。在执行反向/更新传递之前要累积的更新步骤数。 -
dataloader_drop_last(bool) –默认为:
True。如果数据集大小不能被批量大小整除,则丢弃最后一个不完整的批量,即 DataLoader 只返回完整的批量。 -
warmup_ratio(float) –默认为:
0.1。线性调度器的预热比率。 -
weight_decay(float) –默认为:
0.01。AdamW 中的权重衰减。 -
deepspeed(str) –默认为:
``。DeepSpeed 配置文件的路径,默认使用 LazyLLM 代码仓库中的预置文件:ds_stage0.json``。 -
logging_steps(int) –默认为:
1。更新日志的频率。 -
save_steps(int) –默认为:
1000。保存频率。 -
temperature(float) –默认为:
0.02。用于相似度评分的温度。 -
sentence_pooling_method(str) –默认为:
cls。池化方法。可用选项:'cls', 'mean', 'last_token'。 -
normalize_embeddings(bool) –默认为:
True。是否归一化嵌入。 -
kd_loss_type(str) –默认为:
kl_div。知识蒸馏的损失类型。可用选项:'kl_div', 'm3_kd_loss'。 -
overwrite_output_dir(bool) –默认为:
True。用于允许程序覆盖现有的输出目录。 -
fp16(bool) –默认为:
True。是否使用 fp16(混合)精度而不是 32 位。 -
gradient_checkpointing(bool) –默认为:
True。是否启用梯度检查点。 -
negatives_cross_device(bool) –默认为:
True。是否在设备间共享负样本。
该类重排模型的关键字参数及其默认值如下:
Other Parameters:
-
train_group_size(int) –默认为:
8。训练组的大小。用于控制每个训练集中的负样本数量。 -
query_max_len(int) –默认为:
256。经过分词后,段落的最大总输入序列长度。超过此长度的序列将被截断,较短的序列将被填充。 -
passage_max_len(int) –默认为:
256。经过分词后,段落的最大总输入序列长度。超过此长度的序列将被截断,较短的序列将被填充。 -
pad_to_multiple_of(int) –默认为:
8。如果设置,将序列填充为提供值的倍数。 -
learning_rate(float) –默认为:
6e-5。学习率。 -
num_train_epochs(int) –默认为:
1。要执行的总训练周期数。 -
per_device_train_batch_size(int) –默认为:
2。训练批量大小。 -
gradient_accumulation_steps(int) –默认为:
1。在执行反向/更新传递之前要累积的更新步骤数。 -
dataloader_drop_last(bool) –默认为:
True。如果数据集大小不能被批量大小整除,则丢弃最后一个不完整的批量,即 DataLoader 只返回完整的批量。 -
warmup_ratio(float) –默认为:
0.1。线性调度器的预热比率。 -
weight_decay(float) –默认为:
0.01。AdamW 中的权重衰减。 -
deepspeed(str) –默认为:
``。DeepSpeed 配置文件的路径,默认使用 LazyLLM 代码仓库中的预置文件:ds_stage0.json``。 -
logging_steps(int) –默认为:
1。更新日志的频率。 -
save_steps(int) –默认为:
1000。保存频率。 -
overwrite_output_dir(bool) –默认为:
True。用于允许程序覆盖现有的输出目录。 -
fp16(bool) –默认为:
True。是否使用 fp16(混合)精度而不是 32 位。 -
gradient_checkpointing(bool) –默认为:
True。是否启用梯度检查点。
Examples:
>>> from lazyllm import finetune
>>> finetune.FlagembeddingFinetune('bge-m3', 'path/to/target')
<lazyllm.llm.finetune type=FlagembeddingFinetune>
Source code in lazyllm/components/finetune/flagembedding.py
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 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 | |
lazyllm.components.auto.AutoFinetune
Bases: LazyLLMFinetuneBase
此类是 LazyLLMFinetuneBase 的子类,可根据输入的参数自动选择合适的微调框架和参数,以对大语言模型进行微调。
具体而言,基于输入的:base_model 的模型参数、ctx_len、batch_size、lora_r、launcher 中GPU的类型以及卡数,该类可以自动选择出合适的微调框架(如: AlpacaloraFinetune 或 CollieFinetune)及所需的参数。
Parameters:
-
base_model(str) –用于进行微调的基模型。要求是基模型的路径。
-
source(config[model_source]) –指定模型的下载源。可通过设置环境变量
LAZYLLM_MODEL_SOURCE来配置,目前仅支持huggingface或modelscope。若不设置,lazyllm不会启动自动模型下载。 -
target_path(str) –微调后模型保存LoRA权重的路径。
-
merge_path(str) –模型合并LoRA权重后的路径,默认为
None。如果未指定,则会在target_path下创建 "lazyllm_lora" 和 "lazyllm_merge" 目录,分别作为target_path和merge_path。 -
ctx_len(int) –输入微调模型的token最大长度,默认为
1024。 -
batch_size(int) –批处理大小,默认为
32。 -
lora_r(int) –LoRA 的秩,默认为
8;该数值决定添加参数的量,数值越小参数量越小。 -
launcher(launcher, default:remote()) –微调的启动器,默认为
launchers.remote(ngpus=1)。 -
kw–关键字参数,用于更新默认的训练参数。注意这里能够指定的关键字参数取决于 LazyLLM 推测出的框架,因此建议谨慎设置。
Examples:
>>> from lazyllm import finetune
>>> finetune.auto("internlm2-chat-7b", 'path/to/target')
<lazyllm.llm.finetune type=AlpacaloraFinetune>
Source code in lazyllm/components/auto/autofinetune.py
lazyllm.components.finetune.base.DummyFinetune
Bases: LazyLLMFinetuneBase
DummyFinetune 是 LazyLLMFinetuneBase 的子类,用于占位实现微调逻辑。 此类主要用于演示或测试目的,因为它不执行任何实际的微调操作。
Parameters:
-
base_model–字符串,指定基础模型的名称,默认为 'base'。
-
target_path–字符串,指定微调输出的目标路径,默认为 'target'。
-
launcher–启动器实例,用于执行命令。默认为 [launchers.remote()][lazyllm.launchers.remote]。
-
**kw–其他关键字参数,这些参数会被保存以供后续使用。
Returns:
-
–
一个字符串,表示一个占位命令。该字符串包括初始化时传递的参数。
Examples:
>>> from lazyllm.components import DummyFinetune
>>> from lazyllm import launchers
>>> # 创建一个 DummyFinetune 实例
>>> finetuner = DummyFinetune(base_model='example-base', target_path='example-target', launcher=launchers.local(), custom_arg='custom_value')
>>> # 调用 cmd 方法生成占位命令
>>> command = finetuner.cmd('--example-arg', key='value')
>>> print(command)
... echo 'dummy finetune!, and init-args is {'custom_arg': 'custom_value'}'
Source code in lazyllm/components/finetune/base.py
cmd(*args, **kw)
cmd 方法生成一个用于微调的占位命令字符串。此方法主要用于测试或演示目的。
Parameters:
-
*args–要包含在命令中的位置参数(在本实现中未使用)。
-
**kw–要包含在命令中的关键字参数(在本实现中未使用)。
Returns:
-
str–一个字符串,表示一个占位命令。该字符串包括初始化时传递的关键字参数 (
**kw),存储在self.kw中。
Example
如果类初始化时使用 custom_arg='value',调用 cmd 方法将返回:
"echo 'dummy finetune!, and init-args is {'custom_arg': 'value'}'"
Examples:
>>> from lazyllm.components import DummyFinetune
>>> from lazyllm import launchers
>>> # 创建一个 DummyFinetune 实例,并传递初始化参数
>>> finetuner = DummyFinetune(base_model='example-base', target_path='example-target', launcher=launchers.local(), custom_arg='value')
>>> # 调用 cmd 方法生成占位命令
>>> command = finetuner.cmd()
>>> # 打印生成的占位命令
>>> print(command)
... echo 'dummy finetune!, and init-args is {'custom_arg': 'value'}'
Source code in lazyllm/components/finetune/base.py
lazyllm.components.finetune.LazyLLMFinetuneBase
Bases: ComponentBase
LazyLLM微调基础组件类,继承自ComponentBase。
提供大语言模型微调的基础功能,支持远程启动器配置和模型路径管理。
Parameters:
-
base_model(str) –基础模型路径或标识
-
target_path(str) –微调后模型输出路径
-
launcher(Launcher, default:remote()) –任务启动器,默认为远程启动器
Source code in lazyllm/components/finetune/base.py
Deploy
lazyllm.components.deploy.Lightllm
Bases: LazyLLMDeployBase
此类是 LazyLLMDeployBase 的子类,基于 LightLLM 框架提供的推理能力,用于对大语言模型进行推理。
Parameters:
-
trust_remote_code(bool, default:True) –是否信任远程代码,默认为True
-
launcher(Launcher, default:remote(ngpus=1)) –任务启动器,默认为单GPU远程启动器
-
log_path(str, default:None) –日志文件路径,默认为None
-
**kw–其他LightLLM服务器配置参数
此类的关键字参数及其默认值如下:
Other Parameters:
-
tp(int) –张量并行参数,默认为
1。 -
max_total_token_num(int) –最大总token数,默认为
64000。 -
eos_id(int) –结束符ID,默认为
2。 -
port(int) –服务的端口号,默认为
None。此情况下LazyLLM会自动生成随机端口号。 -
host(str) –服务的IP地址,默认为
0.0.0.0。 -
nccl_port(int) –NCCL 端口,默认为
None。此情况下LazyLLM会自动生成随机端口号。 -
tokenizer_mode(str) –tokenizer的加载模式,默认为
auto。 -
running_max_req_size(int) –推理引擎最大的并行请求数, 默认为
256。 -
data_type(str) –模型权重的数据类型,默认为
float16。 -
max_req_total_len(int) –请求的最大总长度,默认为
64000。 -
max_req_input_len(int) –输入的最大长度,默认为
4096。 -
long_truncation_mode(str) –长文本的截断模式,默认为
head。
Examples:
Source code in lazyllm/components/deploy/lightllm.py
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 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 | |
cmd(finetuned_model=None, base_model=None)
该方法用于生成启动LightLLM服务的命令。
Parameters:
-
finetuned_model(str, default:None) –微调后的模型路径。
-
base_model(str, default:None) –基础模型路径,当finetuned_model无效时使用。
Returns:
- LazyLLMCMD: 一个包含启动命令的LazyLLMCMD对象。
Source code in lazyllm/components/deploy/lightllm.py
geturl(job=None)
获取LightLLM服务的URL地址。
Parameters:
-
job(optional, default:None) –任务对象,默认为None,此时使用self.job。
Returns:
- str: 服务的URL地址,格式为"http://{ip}:{port}/generate"。
Source code in lazyllm/components/deploy/lightllm.py
extract_result(x, inputs)
staticmethod
从服务响应中提取生成的文本结果。
Parameters:
-
x(str) –服务返回的响应文本。
-
inputs(str) –输入文本。
Returns:
- str: 提取出的生成文本。
异常
Exception: 当解析JSON响应失败时抛出异常。
Source code in lazyllm/components/deploy/lightllm.py
lazyllm.components.deploy.Vllm
Bases: LazyLLMDeployBase
此类是 LazyLLMDeployBase 的子类,基于 VLLM 框架提供的推理能力,用于大语言模型的部署与推理。
Parameters:
-
trust_remote_code(bool, default:True) –是否允许加载来自远程服务器的模型代码,默认为
True。 -
launcher(launcher, default:remote(ngpus=1)) –模型启动器,默认为
launchers.remote(ngpus=1)。 -
log_path(str, default:None) –日志保存路径,若为
None则不保存日志。 -
openai_api(bool, default:None) –是否使用 OpenAI API 接口启动 VLLM 服务,默认为
False。 -
kw–关键字参数,用于更新默认的部署参数。除支持的关键字参数外,不允许传入额外参数。
此类支持的关键字参数及其默认值如下:
Other Parameters:
-
tensor-parallel-size(int) –张量并行大小,默认为
1。 -
dtype(str) –模型权重和激活值的数据类型,默认为
auto。可选:half、float16、bfloat16、float、float32。 -
kv-cache-dtype(str) –KV 缓存的数据类型,默认为
auto。可选:fp8、fp8_e5m2、fp8_e4m3。 -
device(str) –VLLM 支持的硬件类型,默认为
auto。可选:cuda、neuron、cpu。 -
block-size(int) –token 块大小,默认为
16。 -
port(int | str) –服务端口号,默认为
auto,即随机分配。 -
host(str) –服务绑定的 IP 地址,默认为
0.0.0.0。 -
seed(int) –随机数种子,默认为
0。 -
tokenizer_mode(str) –Tokenizer 加载模式,默认为
auto。 -
max-num-seqs(int) –推理引擎支持的最大并行请求数,默认为
256。 -
pipeline-parallel-size(int) –流水线并行大小,默认为
1。 -
max-num-batched-tokens(int) –最大批处理 token 数,默认为
64000。
Examples:
Source code in lazyllm/components/deploy/vllm.py
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 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 | |
cmd(finetuned_model=None, base_model=None, master_ip=None)
构造用于启动 vLLM 推理服务的命令。
该方法会自动检测模型路径是否有效,并根据当前配置参数动态生成可执行命令,支持多节点部署时自动加入 ray 启动命令。
Parameters:
-
finetuned_model(str, default:None) –微调后的模型路径。
-
base_model(str, default:None) –备用基础模型路径(当 finetuned_model 无效时启用)。
-
master_ip(str, default:None) –分布式部署中的主节点 IP,仅在多节点时启用。
Returns:
- LazyLLMCMD: 可执行命令对象,包含启动指令、结果回调函数及健康检查方法。
Source code in lazyllm/components/deploy/vllm.py
geturl(job=None)
获取 vLLM 服务的推理地址。
根据运行模式(Display 模式或实际部署)返回相应的 URL,用于访问模型的生成接口。
Parameters:
-
job(Job, default:None) –部署任务对象。默认取当前模块绑定的 job。
Returns:
- str: 推理服务的 HTTP 地址。
Source code in lazyllm/components/deploy/vllm.py
extract_result(x, inputs)
staticmethod
从 VLLM 接口返回的 JSON 字符串中提取推理结果。
Parameters:
-
x(str) –VLLM 服务返回的原始 JSON 字符串。
-
inputs(Any) –输入参数(此处未使用,保留接口一致性)。
Returns:
- str: 模型生成的文本结果。
Source code in lazyllm/components/deploy/vllm.py
lazyllm.components.deploy.LMDeploy
Bases: LazyLLMDeployBase
LMDeploy 类,继承自 LazyLLMDeployBase,基于 LMDeploy 框架,
用于启动并管理大语言模型的推理服务。
Parameters:
-
launcher(Optional[launcher], default:remote(ngpus=1)) –服务启动器,默认使用
launchers.remote(ngpus=1)。 -
trust_remote_code(bool, default:True) –是否信任远程代码,默认为
True。 -
log_path(Optional[str], default:None) –日志输出路径,默认为
None。 -
**kw–关键字参数,用于更新默认的部署配置。除下列参数外,不允许传入额外参数。
Other Parameters:
-
tp(int) –张量并行参数,默认为
1。 -
server-name(str) –服务监听的 IP 地址,默认为
0.0.0.0。 -
server-port(Optional[int]) –服务端口号,默认为
None,此时会自动随机分配 30000–40000 区间的端口。 -
max-batch-size(int) –最大批处理大小,默认为
128。 -
chat-template(Optional[str]) –对话模板文件路径。若模型不是视觉语言模型且未指定模板,将使用默认模板。
-
eager-mode(bool) –是否启用 eager 模式,受环境变量
LMDEPLOY_EAGER_MODE控制,默认为False。
Examples:
>>> # Basic use:
>>> from lazyllm import deploy
>>> infer = deploy.LMDeploy()
>>>
>>> # MultiModal:
>>> import lazyllm
>>> from lazyllm import deploy, globals
>>> from lazyllm.components.formatter import encode_query_with_filepaths
>>> chat = lazyllm.TrainableModule('InternVL3_5-1B').deploy_method(deploy.LMDeploy)
>>> chat.update_server()
>>> inputs = encode_query_with_filepaths('What is it?', ['path/to/image'])
>>> res = chat(inputs)
Source code in lazyllm/components/deploy/lmdeploy.py
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 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 | |
cmd(finetuned_model=None, base_model=None)
该方法用于生成启动LMDeploy服务的命令。
Parameters:
-
finetuned_model(str, default:None) –微调后的模型路径。
-
base_model(str, default:None) –基础模型路径,当finetuned_model无效时使用。
Returns:
- LazyLLMCMD: 一个包含启动命令的LazyLLMCMD对象。
Source code in lazyllm/components/deploy/lmdeploy.py
geturl(job=None)
获取LMDeploy服务的URL地址。
Parameters:
-
job(optional, default:None) –任务对象,默认为None,此时使用self.job。
Returns:
- str: 服务的URL地址,格式为"http://{ip}:{port}/v1/chat/interactive"。
Source code in lazyllm/components/deploy/lmdeploy.py
extract_result(x, inputs)
staticmethod
解析模型推理结果,从返回的 JSON 字符串中提取文本输出。
Parameters:
-
x(str) –模型返回的 JSON 格式字符串。
-
inputs(dict) –原始输入数据(此参数未被直接使用,保留作接口兼容)。
Returns:
- str: 从响应中解析得到的文本结果。
Source code in lazyllm/components/deploy/lmdeploy.py
lazyllm.components.deploy.base.DummyDeploy
Bases: LazyLLMDeployBase, Pipeline
DummyDeploy(launcher=launchers.remote(sync=False), , stream=False, *kw)
一个用于测试的模拟部署类,继承自 LazyLLMDeployBase 和 flows.Pipeline,实现了一个简单的流水线风格部署服务,
支持流式输出(可选)。
该类主要用于内部测试和示例用途。它接收符合 message_format 格式的输入,根据是否启用 stream 参数,返回
字符串或逐步输出的模拟响应。
Args:
launcher: 部署器实例,默认值为 launchers.remote(sync=False)。
stream (bool): 是否以流式方式输出结果。
kw: 其他传递给父类的关键字参数。
Call Arguments
keys_name_handle (dict): 输入字段名的映射。
message_format (dict): 默认请求模板,包括输入内容与生成参数。
Source code in lazyllm/components/deploy/base.py
lazyllm.components.auto.AutoDeploy
Bases: LazyLLMDeployBase
此类是 LazyLLMDeployBase 的子类,可根据输入的参数自动选择合适的推理框架和参数,以对大语言模型进行推理。
具体而言,基于输入的:base_model 的模型参数、max_token_num、launcher 中GPU的类型以及卡数,该类可以自动选择出合适的推理框架(如: Lightllm 或 Vllm)及所需的参数。
Parameters:
-
base_model(str) –用于进行微调的基模型,要求是基模型的路径或模型名。用于提供基模型信息。
-
source(config[model_source]) –指定模型的下载源。可通过设置环境变量
LAZYLLM_MODEL_SOURCE来配置,目前仅支持huggingface或modelscope。若不设置,lazyllm不会启动自动模型下载。 -
trust_remote_code(bool) –是否允许加载来自远程服务器的模型代码,默认为
True。 -
launcher(launcher, default:remote()) –微调的启动器,默认为
launchers.remote(ngpus=1)。 -
stream(bool) –是否为流式响应,默认为
False。 -
type(str) –类型参数,默认为
None,及llm类型,另外还支持embed类型。 -
max_token_num(int) –输入微调模型的token最大长度,默认为
1024。 -
launcher(launcher, default:remote()) –微调的启动器,默认为
launchers.remote(ngpus=1)。 -
kw–关键字参数,用于更新默认的训练参数。注意这里能够指定的关键字参数取决于 LazyLLM 推测出的框架,因此建议谨慎设置。
Examples:
>>> from lazyllm import deploy
>>> deploy.auto('internlm2-chat-7b')
<lazyllm.llm.deploy type=Lightllm>
Source code in lazyllm/components/auto/autodeploy.py
get_deployer(base_model, source=None, trust_remote_code=True, launcher=None, type=None, log_path=None, **kw)
classmethod
根据模型类型获取对应的部署器类。
自动检测模型类型并返回最适合的部署器类、启动器和配置参数。
Parameters:
-
base_model(str) –基础模型名称或路径。
-
source(Optional[str], default:None) –模型来源。
-
trust_remote_code(bool, default:True) –是否信任远程代码。
-
launcher(Optional[LazyLLMLaunchersBase], default:None) –启动器实例。
-
type(Optional[str], default:None) –模型类型。
-
log_path(Optional[str], default:None) –日志文件路径。
-
**kw–其他配置参数。
Source code in lazyllm/components/auto/autodeploy.py
lazyllm.components.deploy.embed.AbstractEmbedding
Bases: ABC
抽象嵌入基类,为所有嵌入模型提供统一的接口和基础功能。此类定义了嵌入模型的标准接口,包括模型加载、调用和序列化等功能。
Parameters:
-
base_embed(str) –嵌入模型的基础路径或标识符,用于指定要加载的嵌入模型。
-
source(str, default:None) –模型来源,默认为
None。如果未指定,将使用 LazyLLM 配置中的默认模型来源。 -
init(bool, default:False) –是否在初始化时立即加载模型,默认为
False。如果为True,将在对象创建时立即调用load_embed()方法。
Source code in lazyllm/components/deploy/embed.py
lazyllm.components.deploy.EmbeddingDeploy
Bases: LazyLLMDeployBase
此类是 LazyLLMDeployBase 的子类,用于部署文本嵌入(Embedding)服务。支持稠密向量(dense)和稀疏向量(sparse)两种嵌入方式,可使用 HuggingFace 模型或 FlagEmbedding 模型。
Parameters:
-
launcher(Optional[launcher], default:None) –启动器实例,默认为
None。 -
model_type(Optional[str], default:'embed') –模型类型,默认为
'embed'。 -
log_path(Optional[str], default:None) –日志文件路径,默认为
None。 -
embed_type(Optional[str], default:'dense') –嵌入类型,可选
'dense'或'sparse',默认为'dense'。 -
trust_remote_code(bool, default:True) –是否信任远程代码,默认为
True。 -
port(Optional[int], default:None) –服务端口号,默认为
None,此情况下 LazyLLM 会自动生成随机端口号。
Call Arguments
finetuned_model (Optional[str]): 微调后的模型路径或名称。
base_model (Optional[str]): 基础模型路径或名称,当 finetuned_model 无效时会使用此模型。
Examples:
>>> from lazyllm import deploy
>>> embed_service = deploy.EmbeddingDeploy(embed_type='dense')
>>> embed_service('path/to/model')
Source code in lazyllm/components/deploy/embed.py
lazyllm.components.deploy.embed.RerankDeploy
Bases: EmbeddingDeploy
此类是 EmbeddingDeploy 的子类,用于部署重排序(Rerank)服务。支持使用HuggingFace模型进行文本重排序。
Parameters:
-
launcher(launcher, default:None) –启动器,默认为
None。 -
model_type(str, default:'embed') –模型类型,默认为
'embed'。 -
log_path(str, default:None) –日志文件路径,默认为
None。 -
trust_remote_code(bool, default:True) –是否信任远程代码,默认为
True。 -
port(int, default:None) –服务端口号,默认为
None,此情况下LazyLLM会自动生成随机端口号。
Call Arguments
finetuned_model: 微调后的模型路径或模型名称。
base_model: 基础模型路径或模型名称,当finetuned_model无效时会使用此模型。
Examples:
>>> from lazyllm import deploy
>>> rerank_service = deploy.embed.RerankDeploy()
>>> rerank_service('path/to/model')
>>> input_data = {
... "query": "What is machine learning?",
... "documents": [
... "Machine learning is a branch of AI.",
... "Machine learning uses data to improve.",
... "Deep learning is a subset of machine learning."
... ],
... "top_n": 2
... }
>>> result = rerank_service(input_data)
Source code in lazyllm/components/deploy/embed.py
lazyllm.components.deploy.embed.LazyHuggingFaceRerank
Bases: object
基于 HuggingFace CrossEncoder 的重排序(Rerank)封装类。
用于根据查询与候选文档的相关性分数,对文档进行排序。
支持在初始化时下载并加载指定的重排序模型,并可选择延迟加载以提升启动性能。
Parameters:
-
base_rerank(str) –重排序模型名称或本地路径。支持 HuggingFace Hub 模型标识符或本地路径。
-
source(Optional[str], default:None) –模型来源,支持
huggingface和modelscope,默认为全局配置项model_source。 -
init(bool, default:False) –是否在实例化时立即加载模型。若为
False,将在首次调用时延迟加载。
Source code in lazyllm/components/deploy/embed.py
load_reranker()
加载重排序模型。
该方法会基于 self.base_rerank 初始化一个 sentence_transformers.CrossEncoder 实例,
并赋值给类属性 self.reranker,用于后续的重排序任务。
rebuild(base_rerank, init)
classmethod
重建 LazyHuggingFaceRerank 实例的类方法。
主要用于序列化(pickle/cloudpickle)时的反序列化过程,根据提供的参数重新实例化对象。
Parameters:
-
base_rerank(str) –模型名称或路径。
-
init(bool) –是否在重建时立即加载模型。
Returns:
- LazyHuggingFaceRerank: 重新构建的类实例。
Source code in lazyllm/components/deploy/embed.py
lazyllm.components.deploy.embed.HuggingFaceEmbedding
HuggingFace嵌入模型管理类,用于管理和注册不同的嵌入模型实现。
属性: _model_id_mapping (dict): 模型ID到具体实现类的映射字典。
Parameters:
-
base_embed(str) –基础嵌入模型的路径或名称。
-
source(Optional[str], default:None) –模型来源,默认为None。
Source code in lazyllm/components/deploy/embed.py
get_emb_cls(model_name)
classmethod
获取模型对应的嵌入实现类。
Parameters:
-
model_name(str) –模型名称或路径。
Returns:
- type: 返回对应的嵌入模型实现类,如果未找到则返回默认实现LazyHuggingFaceDefaultEmbedding。
Source code in lazyllm/components/deploy/embed.py
register(model_ids)
classmethod
注册模型ID到特定实现类的装饰器。
Parameters:
-
model_ids(List[str]) –要注册的模型ID列表。
Returns:
- Callable: 返回装饰器函数。
Source code in lazyllm/components/deploy/embed.py
lazyllm.components.deploy.embed.LazyFlagEmbedding
Bases: object
支持懒加载的 FlagEmbedding 嵌入模块封装。
该类包装了 FlagEmbedding 的加载和调用逻辑,提供对稀疏和稠密嵌入的支持,并通过 lazyllm.once_flag() 机制实现懒加载。适用于嵌入模型的本地/远程下载、初始化与编码流程的封装,便于与 LazyLLM 系统集成。
Parameters:
-
base_embed(str) –嵌入模型名称或路径。
-
sparse(bool, default:False) –是否使用稀疏嵌入模式,默认为 False。
-
source(str, default:None) –模型下载源,若未提供则使用 lazyllm 全局配置。
-
init(bool, default:False) –是否在初始化时立即加载模型,默认为 False。
Source code in lazyllm/components/deploy/embed.py
load_embed()
加载嵌入模型并初始化到设备上。
该方法根据系统是否支持 CUDA 自动选择运行设备(GPU 或 CPU),并从本地或远程加载预训练的 FlagEmbedding 模型。
Source code in lazyllm/components/deploy/embed.py
rebuild(base_embed, sparse, init)
classmethod
重建 LazyFlagEmbedding 实例的方法。
该类方法用于在序列化或跨进程传递时,重新构造带有初始化配置的 LazyFlagEmbedding 实例。
Parameters:
-
base_embed(str) –嵌入模型的路径或模型名称。
-
sparse(bool) –是否启用稀疏嵌入。
-
init(bool) –是否在构造时立即加载模型。
Returns:
- LazyFlagEmbedding: 一个新的 LazyFlagEmbedding 实例。
Source code in lazyllm/components/deploy/embed.py
lazyllm.components.deploy.Mindie
Bases: LazyLLMDeployBase
此类是 LazyLLMDeployBase 的一个子类, 用于部署和管理MindIE大模型推理服务。它封装了MindIE服务的配置生成、进程启动和API交互的全流程。
Parameters:
-
trust_remote_code(bool, default:True) –是否信任远程代码(如HuggingFace模型)。默认为
True。 -
launcher–任务启动器实例,默认为
launchers.remote()。 -
log_path(str, default:None) –日志保存路径,若为
None则不保存日志。 -
**kw–其他配置参数
Other Parameters:
-
npuDeviceIds–NPU设备ID列表(如
[[0,1]]表示使用2张卡) -
worldSize–模型并行数量
-
port–服务端口(设为
'auto'时自动分配30000-40000的随机端口) -
maxSeqLen–最大序列长度
-
maxInputTokenLen–单次输入最大token数
-
maxPrefillTokens–预填充token上限
-
config–自定义配置文件
Notes
:
必须预先设置环境变量 LAZYLLM_MINDIE_HOME 指向MindIE安装目录, 若未指定 finetuned_model 或路径无效,会自动回退到 base_model
Examples:
>>> import lazyllm
>>> from lazyllm.components.deploy import Mindie
>>> deployer = Mindie(
... port=30000,
... launcher=lazyllm.launchers.remote(),
... max_seq_len=32000,
... log_path="/path/to/logs"
... )
>>> cmd = deployer.cmd(
... finetuned_model="/path/to/finetuned_model",
... base_model="/path/to/base_model")
>>> print("Service URL:", cmd.geturl())
Source code in lazyllm/components/deploy/mindie.py
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 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 | |
cmd(finetuned_model=None, base_model=None, master_ip=None)
生成启动MindIE服务的命令。
Parameters:
-
finetuned_model(str, default:None) –微调模型路径
-
base_model(str, default:None) –基础模型路径(当微调模型无效时作为后备)
-
master_ip(str, default:None) –主节点IP地址(当前未使用)
Returns:
- LazyLLMCMD: 启动服务的命令对象
注意事项
- 自动处理模型路径验证
- 启动服务前更新配置
- 支持配置随机端口分配
Source code in lazyllm/components/deploy/mindie.py
extract_result(x, inputs)
staticmethod
从API响应中提取生成的文本。
Parameters:
-
x–原始API响应
-
inputs–原始输入(未使用)
Returns:
- str: 生成的文本
注意事项
- 解析JSON响应
- 返回响应中的第一个文本条目
Source code in lazyllm/components/deploy/mindie.py
geturl(job=None)
获取部署后的服务URL。
Parameters:
-
job–任务对象(可选,默认为self.job)
Returns:
- str: generate接口的URL
注意事项
- 根据显示模式返回不同格式
- 包含配置中的端口号
Source code in lazyllm/components/deploy/mindie.py
load_config(config_path)
加载并解析MindIE配置文件。
Parameters:
-
config_path(str) –JSON配置文件的路径
Returns:
- dict: 解析后的配置字典
注意事项
- 处理默认和自定义配置文件
- 使用JSON格式配置
- 修改前会创建原始配置的备份
Source code in lazyllm/components/deploy/mindie.py
save_config()
保存当前配置到文件。
注意事项
- 自动创建现有配置的备份
- 写入到标准MindIE配置位置
- 使用带缩进的JSON格式
- 部署时自动调用
Source code in lazyllm/components/deploy/mindie.py
update_config()
使用当前设置更新配置字典。
注意事项
- 处理多个配置部分:
- 模型部署参数
- 服务器设置
- 调度参数
Source code in lazyllm/components/deploy/mindie.py
lazyllm.components.deploy.OCRDeploy
Bases: LazyLLMDeployBase
OCRDeploy 是 LazyLLMDeployBase 的子类,用于部署 OCR(光学字符识别)模型。 此类支持额外的配置,例如日志记录、远程代码信任以及端口自定义。
属性:
keys_name_handle: 一个字典,用于将输入键映射到相应的处理键。例如:
- "inputs": 处理一般输入。
- "ocr_files": 同样映射到 "inputs"。
message_format: 一个字典,指定模型期望的消息格式。例如:
- {"inputs": "/path/to/pdf"} 表示模型需要一个 PDF 文件路径作为输入。
default_headers: 一个字典,指定 API 请求的默认头部。默认为:
- {"Content-Type": "application/json"}
Parameters:
-
launcher–启动器实例,用于部署模型。默认为
None。 -
log_path–字符串,指定日志保存的路径。默认为
None。 -
trust_remote_code–布尔值,指示是否信任远程代码执行。默认为
True。 -
port–整数,指定部署服务器的端口号。默认为
None。
Returns:
-
–
OCRDeploy实例,可通过调用方式启动服务
Examples:
>>> from lazyllm.components import OCRDeploy
>>> from lazyllm import launchers
>>> # 创建一个 OCRDeploy 实例
>>> deployer = OCRDeploy(launcher=launchers.local(), log_path='./logs', port=8080)
>>> # 使用微调的 OCR 模型部署服务器
>>> server = deployer(finetuned_model='ocr-model')
>>> # 打印部署服务器信息
>>> print(server)
... <RelayServer instance ready to handle OCR requests>
Source code in lazyllm/components/deploy/ocr/pp_ocr.py
lazyllm.components.deploy.Infinity
Bases: LazyLLMDeployBase
此类是 LazyLLMDeployBase 的子类,基于 Infinity 框架提供的高性能文本嵌入、重排序和CLIP等能力。
Parameters:
-
launcher(launcher, default:remote(ngpus=1)) –Infinity 的启动器,默认为
launchers.remote(ngpus=1)。 -
kw–关键字参数,用于更新默认的训练参数。请注意,除了以下列出的关键字参数外,这里不能传入额外的关键字参数。
此类的关键字参数及其默认值如下:
Other Parameters:
-
launcher(Launcher) –启动器配置,默认为remote(ngpus=1)。
-
model_type(str) –模型类型,默认为'embed'。
-
log_path(str) –日志文件路径,默认为None。
-
**kw–额外的配置参数,包括host、port、batch-size等。
Examples:
>>> import lazyllm
>>> from lazyllm import deploy
>>> deploy.Infinity()
<lazyllm.llm.deploy type=Infinity>
Source code in lazyllm/components/deploy/infinity.py
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 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 | |
extract_result(x, inputs)
staticmethod
从Infinity API响应中提取结果数据。 解析Infinity服务的JSON响应,根据返回的对象类型提取嵌入向量或重排序结果。
Parameters:
-
x(str) –API返回的JSON字符串响应。
-
inputs(Dict) –原始输入数据,用于确定返回结果的格式。
Source code in lazyllm/components/deploy/infinity.py
geturl(job=None)
获取Infinity服务的URL地址。根据部署模式和作业状态,返回对应的API访问URL地址。
Parameters:
-
job(Optional[Any], default:None) –作业对象,如果为None则使用当前实例的job属性。
Source code in lazyllm/components/deploy/infinity.py
lazyllm.components.deploy.relay.base.RelayServer
Bases: LazyLLMDeployBase
Source code in lazyllm/components/deploy/relay/base.py
lazyllm.components.deploy.OCRDeploy
Bases: LazyLLMDeployBase
OCRDeploy 是 LazyLLMDeployBase 的子类,用于部署 OCR(光学字符识别)模型。 此类支持额外的配置,例如日志记录、远程代码信任以及端口自定义。
属性:
keys_name_handle: 一个字典,用于将输入键映射到相应的处理键。例如:
- "inputs": 处理一般输入。
- "ocr_files": 同样映射到 "inputs"。
message_format: 一个字典,指定模型期望的消息格式。例如:
- {"inputs": "/path/to/pdf"} 表示模型需要一个 PDF 文件路径作为输入。
default_headers: 一个字典,指定 API 请求的默认头部。默认为:
- {"Content-Type": "application/json"}
Parameters:
-
launcher–启动器实例,用于部署模型。默认为
None。 -
log_path–字符串,指定日志保存的路径。默认为
None。 -
trust_remote_code–布尔值,指示是否信任远程代码执行。默认为
True。 -
port–整数,指定部署服务器的端口号。默认为
None。
Returns:
-
–
OCRDeploy实例,可通过调用方式启动服务
Examples:
>>> from lazyllm.components import OCRDeploy
>>> from lazyllm import launchers
>>> # 创建一个 OCRDeploy 实例
>>> deployer = OCRDeploy(launcher=launchers.local(), log_path='./logs', port=8080)
>>> # 使用微调的 OCR 模型部署服务器
>>> server = deployer(finetuned_model='ocr-model')
>>> # 打印部署服务器信息
>>> print(server)
... <RelayServer instance ready to handle OCR requests>
Source code in lazyllm/components/deploy/ocr/pp_ocr.py
lazyllm.components.deploy.text_to_speech.utils.TTSBase
Bases: LazyLLMDeployBase
TTS(文本转语音)服务的基类。
提供文本转语音服务的部署基础框架,支持模型加载和RelayServer部署。
Parameters:
-
launcher(LazyLLMLaunchersBase, default:None) –任务启动器
-
log_path(str, default:None) –日志文件路径
-
port(int, default:None) –服务端口号
Source code in lazyllm/components/deploy/text_to_speech/utils.py
lazyllm.components.deploy.relay.base.FastapiApp
Bases: object
Source code in lazyllm/components/deploy/relay/base.py
Prompter
lazyllm.components.prompter.LazyLLMPrompterBase
LazyLLM提示词基类,用于管理和生成模型提示词。
Parameters:
-
show(bool, default:False) –是否显示生成的提示词,默认为False。
-
tools(Optional[List], default:None) –可用工具列表,默认为None。
-
history(Optional[List], default:None) –对话历史记录,默认为None。
Attributes:
-
ISA(str) –指令分隔符起始标记 "<!lazyllm-spliter!>"。
-
ISE(str) –指令分隔符结束标记 "</!lazyllm-spliter!>"。
Configuration Items
-
system: 系统角色设定
-
sos/eos: 会话开始/结束标记
-
soh/eoh: 人类输入开始/结束标记
-
soa/eoa: AI回复开始/结束标记
-
soe/eoe: 工具执行结果开始/结束标记
-
tool_start_token/tool_end_token: 工具调用开始/结束标记
-
tool_args_token: 工具参数标记
Source code in lazyllm/components/prompter/builtinPrompt.py
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 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 | |
generate_prompt(input=None, history=None, tools=None, label=None, *, show=False, return_dict=False)
根据用户输入,生成对应的Prompt.
Parameters:
-
input(Option[str | Dict], default:None) –Prompter的输入,如果是dict,会填充到instruction的槽位中;如果是str,则会作为输入。
-
history(Option[List[List | Dict]], default:None) –历史对话,可以为
[[u, s], [u, s]]或 openai的history格式,默认为None。 -
tools (Option[List[Dict]]–可以使用的工具合集,大模型用作FunctionCall时使用,默认为None
-
label(Option[str], default:None) –标签,训练或微调时使用,默认为None
-
show(bool, default:False) –标志是否打印生成的Prompt,默认为False
-
return_dict(bool, default:False) –标志是否返回dict,一般情况下使用
OnlineChatModule时会设置为True。如果返回dict,则仅填充instruction。默认为False
Source code in lazyllm/components/prompter/builtinPrompt.py
get_response(output, input=None)
用作对Prompt的截断,只保留有价值的输出
Parameters:
-
output(str) –大模型的输出
-
input(Option[[str], default:None) –大模型的输入,若指定此参数,会将输出中包含输入的部分全部截断,默认为None
Source code in lazyllm/components/prompter/builtinPrompt.py
pre_hook(func=None)
设置预处理钩子函数,供外部在生成提示词前对输入数据进行自定义处理。
Parameters:
-
func(Optional[Callable], default:None) –一个可调用对象,作为预处理钩子函数,接收并处理输入数据。
Returns:
- LazyLLMPrompterBase: 返回自身实例,方便链式调用。
Source code in lazyllm/components/prompter/builtinPrompt.py
lazyllm.components.prompter.EmptyPrompter
Bases: LazyLLMPrompterBase
继承自 LazyLLMPrompterBase 的空提示生成器,用于直接返回原始输入。
该类不会对输入进行任何处理,适用于无需格式化的调试、测试或占位场景。
Examples:
>>> from lazyllm.components.prompter import EmptyPrompter
>>> prompter = EmptyPrompter()
>>> prompter.generate_prompt("Hello LazyLLM")
'Hello LazyLLM'
>>> prompter.generate_prompt({"query": "Tell me a joke"})
{'query': 'Tell me a joke'}
>>> # Even with additional parameters, the input is returned unchanged
>>> prompter.generate_prompt("No-op", history=[["Hi", "Hello"]], tools=[{"name": "search"}], label="debug")
'No-op'
Source code in lazyllm/components/prompter/builtinPrompt.py
generate_prompt(input, history=None, tools=None, label=None, show=False, return_dict=False)
直接返回输入的Prompt实现,继承自 LazyLLMPrompterBase。
该方法不会对输入做任何格式化操作,适用于调试、测试或占位场景。
Parameters:
-
input(Any) –任意输入,作为Prompt返回。
-
history(Option[List[List | Dict]], default:None) –历史对话,可忽略,默认None。
-
tools(Option[List[Dict]], default:None) –工具参数,可忽略,默认None。
-
label(Option[str], default:None) –标签,可忽略,默认None。
-
show(bool, default:False) –是否打印返回内容,默认为False。
Source code in lazyllm/components/prompter/builtinPrompt.py
lazyllm.components.Prompter
Bases: object
用于生成模型输入的Prompt类,支持模板、历史对话拼接与响应抽取。
该类支持从字典、模板名称或文件中加载prompt配置,支持历史对话结构拼接(用于Chat类任务), 可灵活处理有/无history结构的prompt输入,适配非字典类型输入。
Parameters:
-
prompt(Optional[str], default:None) –模板Prompt字符串,支持格式化字段。
-
response_split(Optional[str], default:None) –对模型响应进行切分的分隔符,仅用于抽取模型回答。
-
chat_prompt(Optional[str], default:None) –多轮对话使用的Prompt模板,必须包含history字段。
-
history_symbol(str, default:'llm_chat_history') –表示历史对话字段的名称,默认为'llm_chat_history'。
-
eoa(Optional[str], default:None) –对话中 assistant/user 分隔符。
-
eoh(Optional[str], default:None) –多轮history中 user-assistant 分隔符。
-
show(bool, default:False) –是否打印最终生成的Prompt,默认False。
Examples:
>>> p = Prompter(prompt="Answer the following: {question}")
>>> p.generate_prompt("What is AI?")
'Answer the following: What is AI?'
>>> p.generate_prompt({"question": "Define machine learning"})
'Answer the following: Define machine learning'
>>> p = Prompter(
... prompt="Instruction: {instruction}",
... chat_prompt="Instruction: {instruction}\nHistory:\n{llm_chat_history}",
... history_symbol="llm_chat_history",
... eoa="</s>",
... eoh="|"
... )
>>> p.generate_prompt(
... input={"instruction": "Translate this."},
... history=[["hello", "你好"], ["how are you", "你好吗"]]
... )
'Instruction: Translate this.\nHistory:\nhello|你好</s>how are you|你好吗'
>>> prompt_conf = {
... "prompt": "Task: {task}",
... "response_split": "---"
... }
>>> p = Prompter.from_dict(prompt_conf)
>>> p.generate_prompt("Summarize this article.")
'Task: Summarize this article.'
>>> full_output = "Task: Summarize this article.---This is the summary."
>>> p.get_response(full_output)
'This is the summary.'
Source code in lazyllm/components/prompter/prompter.py
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 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 | |
from_dict(prompt, *, show=False)
classmethod
通过字典配置初始化一个 Prompter 实例。
Parameters:
-
prompt(Dict) –包含 prompt 相关字段的配置字典,需包含
prompt键,其他为可选。 -
show(bool, default:False) –是否显示生成的 prompt,默认为 False。
Returns:
- Prompter: 返回一个初始化的 Prompter 实例。
Source code in lazyllm/components/prompter/prompter.py
from_template(template_name, *, show=False)
classmethod
根据模板名称加载 prompt 配置并初始化 Prompter 实例。
Parameters:
-
template_name(str) –模板名称,必须在
templates中存在。 -
show(bool, default:False) –是否显示生成的 prompt,默认为 False。
Returns:
- Prompter: 返回一个初始化的 Prompter 实例。
Source code in lazyllm/components/prompter/prompter.py
from_file(fname, *, show=False)
classmethod
从 JSON 文件中读取配置并初始化 Prompter 实例。
Parameters:
-
fname(str) –JSON 配置文件路径。
-
show(bool, default:False) –是否显示生成的 prompt,默认为 False。
Returns:
-
Prompter–返回一个初始化的 Prompter 实例。
Source code in lazyllm/components/prompter/prompter.py
empty()
classmethod
generate_prompt(input, history=None, tools=None, label=None, show=False)
根据输入和可选的历史记录生成最终 Prompt。
Parameters:
-
input(Union[str, Dict]) –用户输入。可以是字符串或包含多字段的字典。
-
history(Optional[List[List[str]]], default:None) –多轮对话历史,例如 [['u1', 'a1'], ['u2', 'a2']]。
-
tools(Optional[Any], default:None) –目前未支持工具调用,此字段必须为 None。
-
label(Optional[str], default:None) –附加在 prompt 末尾的标签,通常用于训练。
-
show(bool, default:False) –是否显示生成的 prompt,默认 False。
Returns:
-
str–格式化后的 prompt 字符串。
Source code in lazyllm/components/prompter/prompter.py
get_response(response, input=None)
从 LLM 返回结果中提取模型的回答内容。
Parameters:
-
response(str) –模型完整响应文本。
-
input(Optional[str], default:None) –如果模型输出以输入开头,将会自动去除输入部分。
Returns:
-
str–提取后的模型响应内容。
Source code in lazyllm/components/prompter/prompter.py
lazyllm.components.AlpacaPrompter
Bases: LazyLLMPrompterBase
Alpaca格式的Prompter,支持工具调用,不支持历史对话。
Parameters:
-
instruction(Option[str], default:None) –大模型的任务指令,至少带一个可填充的槽位(如
{instruction})。或者使用字典指定system和user的指令。 -
extra_keys(Option[List], default:None) –额外的字段,用户的输入会填充这些字段。
-
show(bool, default:False) –标志是否打印生成的Prompt,默认为False
-
tools(Option[list], default:None) –大模型可以使用的工具集合,默认为None
Examples:
>>> from lazyllm import AlpacaPrompter
>>> p = AlpacaPrompter('hello world {instruction}')
>>> p.generate_prompt('this is my input')
'You are an AI-Agent developed by LazyLLM.\nBelow is an instruction that describes a task, paired with extra messages such as input that provides further context if possible. Write a response that appropriately completes the request.\n\n ### Instruction:\nhello world this is my input\n\n\n### Response:\n'
>>> p.generate_prompt('this is my input', return_dict=True)
{'messages': [{'role': 'system', 'content': 'You are an AI-Agent developed by LazyLLM.\nBelow is an instruction that describes a task, paired with extra messages such as input that provides further context if possible. Write a response that appropriately completes the request.\n\n ### Instruction:\nhello world this is my input\n\n'}, {'role': 'user', 'content': ''}]}
>>>
>>> p = AlpacaPrompter('hello world {instruction}, {input}', extra_keys=['knowledge'])
>>> p.generate_prompt(dict(instruction='hello world', input='my input', knowledge='lazyllm'))
'You are an AI-Agent developed by LazyLLM.\nBelow is an instruction that describes a task, paired with extra messages such as input that provides further context if possible. Write a response that appropriately completes the request.\n\n ### Instruction:\nhello world hello world, my input\n\nHere are some extra messages you can referred to:\n\n### knowledge:\nlazyllm\n\n\n### Response:\n'
>>> p.generate_prompt(dict(instruction='hello world', input='my input', knowledge='lazyllm'), return_dict=True)
{'messages': [{'role': 'system', 'content': 'You are an AI-Agent developed by LazyLLM.\nBelow is an instruction that describes a task, paired with extra messages such as input that provides further context if possible. Write a response that appropriately completes the request.\n\n ### Instruction:\nhello world hello world, my input\n\nHere are some extra messages you can referred to:\n\n### knowledge:\nlazyllm\n\n'}, {'role': 'user', 'content': ''}]}
>>>
>>> p = AlpacaPrompter(dict(system="hello world", user="this is user instruction {input}"))
>>> p.generate_prompt(dict(input="my input"))
'You are an AI-Agent developed by LazyLLM.\nBelow is an instruction that describes a task, paired with extra messages such as input that provides further context if possible. Write a response that appropriately completes the request.\n\n ### Instruction:\nhello word\n\n\n\nthis is user instruction my input### Response:\n'
>>> p.generate_prompt(dict(input="my input"), return_dict=True)
{'messages': [{'role': 'system', 'content': 'You are an AI-Agent developed by LazyLLM.\nBelow is an instruction that describes a task, paired with extra messages such as input that provides further context if possible. Write a response that appropriately completes the request.\n\n ### Instruction:\nhello world'}, {'role': 'user', 'content': 'this is user instruction my input'}]}
Source code in lazyllm/components/prompter/alpacaPrompter.py
generate_prompt(input=None, history=None, tools=None, label=None, *, show=False, return_dict=False)
根据用户输入,生成对应的Prompt.
Parameters:
-
input(Option[str | Dict], default:None) –Prompter的输入,如果是dict,会填充到instruction的槽位中;如果是str,则会作为输入。
-
history(Option[List[List | Dict]], default:None) –历史对话,可以为
[[u, s], [u, s]]或 openai的history格式,默认为None。 -
tools (Option[List[Dict]]–可以使用的工具合集,大模型用作FunctionCall时使用,默认为None
-
label(Option[str], default:None) –标签,训练或微调时使用,默认为None
-
show(bool, default:False) –标志是否打印生成的Prompt,默认为False
-
return_dict(bool, default:False) –标志是否返回dict,一般情况下使用
OnlineChatModule时会设置为True。如果返回dict,则仅填充instruction。默认为False
Source code in lazyllm/components/prompter/builtinPrompt.py
get_response(output, input=None)
用作对Prompt的截断,只保留有价值的输出
Parameters:
-
output(str) –大模型的输出
-
input(Option[[str], default:None) –大模型的输入,若指定此参数,会将输出中包含输入的部分全部截断,默认为None
Source code in lazyllm/components/prompter/builtinPrompt.py
lazyllm.components.ChatPrompter
Bases: LazyLLMPrompterBase
用于多轮对话的大模型Prompt构造器,继承自 LazyLLMPrompterBase。
支持工具调用、历史对话与自定义指令模版。支持传入 system/user 拆分的指令结构,自动合并为统一模板。支持额外字段注入和打印提示信息。
Parameters:
-
instruction(Option[str | Dict[str, str]], default:None) –Prompt模板指令,可为字符串或包含
system和user的字典。若为字典,将自动拼接并注入特殊标记分隔符。 -
extra_keys(Option[List[str]], default:None) –额外的字段列表,用户输入中的内容会被插入对应槽位,用于丰富上下文。
-
show(bool, default:False) –是否打印生成的Prompt,默认False。
-
tools(Option[List], default:None) –可选的工具列表,用于FunctionCall任务,默认None。
-
history(Option[List[List[str]]], default:None) –可选的历史对话,用于对话记忆,格式为[[user, assistant], ...],默认None。
Examples:
- Simple instruction string
>>> p = ChatPrompter('hello world')
>>> p.generate_prompt('this is my input')
'You are an AI-Agent developed by LazyLLM.hello world\nthis is my input\n'
>>> p.generate_prompt('this is my input', return_dict=True)
{'messages': [{'role': 'system', 'content': 'You are an AI-Agent developed by LazyLLM.\nhello world'}, {'role': 'user', 'content': 'this is my input'}]}
- Using extra_keys
>>> p = ChatPrompter('hello world {instruction}', extra_keys=['knowledge'])
>>> p.generate_prompt({
... 'instruction': 'this is my ins',
... 'input': 'this is my inp',
... 'knowledge': 'LazyLLM-Knowledge'
... })
'You are an AI-Agent developed by LazyLLM.hello world this is my ins\nHere are some extra messages you can referred to:\n\n### knowledge:\nLazyLLM-Knowledge\nthis is my inp\n'
- With conversation history
>>> p.generate_prompt({
... 'instruction': 'this is my ins',
... 'input': 'this is my inp',
... 'knowledge': 'LazyLLM-Knowledge'
... }, history=[['s1', 'e1'], ['s2', 'e2']])
'You are an AI-Agent developed by LazyLLM.hello world this is my ins\nHere are some extra messages you can referred to:\n\n### knowledge:\nLazyLLM-Knowledge\ns1|e1\ns2|e2\nthis is my inp\n'
- Using dict format for system/user instructions
>>> p = ChatPrompter(dict(system="hello world", user="this is user instruction {input}"))
>>> p.generate_prompt({'input': "my input", 'query': "this is user query"})
'You are an AI-Agent developed by LazyLLM.hello world\nthis is user instruction my input this is user query\n'
>>> p.generate_prompt({'input': "my input", 'query': "this is user query"}, return_dict=True)
{'messages': [{'role': 'system', 'content': 'You are an AI-Agent developed by LazyLLM.\nhello world'}, {'role': 'user', 'content': 'this is user instruction my input this is user query'}]}
Source code in lazyllm/components/prompter/chatPrompter.py
generate_prompt(input=None, history=None, tools=None, label=None, *, show=False, return_dict=False)
根据用户输入,生成对应的Prompt.
Parameters:
-
input(Option[str | Dict], default:None) –Prompter的输入,如果是dict,会填充到instruction的槽位中;如果是str,则会作为输入。
-
history(Option[List[List | Dict]], default:None) –历史对话,可以为
[[u, s], [u, s]]或 openai的history格式,默认为None。 -
tools (Option[List[Dict]]–可以使用的工具合集,大模型用作FunctionCall时使用,默认为None
-
label(Option[str], default:None) –标签,训练或微调时使用,默认为None
-
show(bool, default:False) –标志是否打印生成的Prompt,默认为False
-
return_dict(bool, default:False) –标志是否返回dict,一般情况下使用
OnlineChatModule时会设置为True。如果返回dict,则仅填充instruction。默认为False
Source code in lazyllm/components/prompter/builtinPrompt.py
get_response(output, input=None)
用作对Prompt的截断,只保留有价值的输出
Parameters:
-
output(str) –大模型的输出
-
input(Option[[str], default:None) –大模型的输入,若指定此参数,会将输出中包含输入的部分全部截断,默认为None
Source code in lazyllm/components/prompter/builtinPrompt.py
MultiModal
Text to Image
lazyllm.components.StableDiffusionDeploy
Bases: LazyLLMDeployBase
Stable Diffusion 模型部署类。该类用于将SD模型部署到指定服务器上,以便可以通过网络进行调用。
Parameters:
-
launcher(Optional[LazyLLMLaunchersBase], default:None) –启动器实例。默认为
None -
log_path(Optional[str], default:None) –日志文件路径。默认为
None -
trust_remote_code(bool, default:True) –是否信任远程代码。默认为
True -
port(Optional[int], default:None) –服务端口号。默认为
None
Examples:
>>> from lazyllm import launchers, UrlModule
>>> from lazyllm.components import StableDiffusionDeploy
>>> deployer = StableDiffusionDeploy(launchers.remote())
>>> url = deployer(base_model='stable-diffusion-3-medium')
>>> model = UrlModule(url=url)
>>> res = model('a tiny cat.')
>>> print(res)
... <lazyllm-query>{"query": "", "files": ["path/to/sd3/image_xxx.png"]}
Source code in lazyllm/components/deploy/stable_diffusion/stable_diffusion3.py
Visual Question Answering
Reference LMDeploy, which supports the Visual Question Answering model.
Text to Sound
lazyllm.components.TTSDeploy
Source code in lazyllm/components/deploy/text_to_speech/__init__.py
lazyllm.components.ChatTTSDeploy
Bases: TTSBase
ChatTTS 模型部署类。
Other Parameters:
-
keys_name_handle(dict) –键名映射字典,用于处理内部和外部API接口之间的参数名称转换。 默认为
{'inputs': 'inputs'}。 -
message_format(dict) –请求负载结构,包含三个主要部分:
-
inputs(str): 要合成为语音的原始文本内容。 -
refinetext(dict): 文本细化和风格化参数,控制语音表达:-
prompt(str): 语音风格控制标签,例如:"[oral_2][laugh_0][break_6]" -
top_P(float): 核采样参数,用于解码策略(默认值:0.7) -
top_K(int): Top-K 采样参数(默认值:20) -
temperature(float): 采样温度,控制随机性(默认值:0.7) -
repetition_penalty(float): 重复惩罚,避免冗余生成(默认值:1.0) -
max_new_token(int): 最大生成token数(默认值:384) -
min_new_token(int): 最小生成token数(默认值:0) -
show_tqdm(bool): 是否在生成过程中显示进度条(默认值:True) -
ensure_non_empty(bool): 确保生成非空结果(默认值:True)
-
-
infercode(dict): 推理和编码参数,影响音频质量:-
prompt(str): 语速控制标签,例如:"[speed_5]" -
spk_emb(可选): 说话人嵌入向量,用于指定音色特征(默认值:None) -
temperature(float): 音频生成的采样温度(默认值:0.3) -
repetition_penalty(float): 重复惩罚系数(默认值:1.05) -
max_new_token(int): 音频生成的最大token数(默认值:2048)
-
-
Examples:
>>> from lazyllm import launchers, UrlModule
>>> from lazyllm.components import ChatTTSDeploy
>>> deployer = ChatTTSDeploy(launchers.remote())
>>> url = deployer(base_model='ChatTTS')
>>> model = UrlModule(url=url)
>>> res = model('Hello World!')
>>> print(res)
... <lazyllm-query>{"query": "", "files": ["path/to/chattts/sound_xxx.wav"]}
Source code in lazyllm/components/deploy/text_to_speech/chattts.py
lazyllm.components.BarkDeploy
Bases: TTSBase
Bark 模型部署类。该类用于将Bark模型部署到指定服务器上,以便可以通过网络进行调用。
__init__(self, launcher=None)
构造函数,初始化部署类。
Parameters:
-
launcher(launcher, default:None) –用于启动远程服务的启动器实例。
__call__(self, finetuned_model=None, base_model=None)
部署模型,并返回远程服务地址。
Parameters:
-
finetuned_model(str) –如果提供,则使用该模型进行部署;如果未提供或路径无效,则使用
base_model。 -
base_model(str) –默认模型,如果
finetuned_model无效,则使用该模型进行部署。 -
返回值(str) –远程服务的URL地址。
Notes
- 推理的输入:字符串。待生成音频的对应文字。
- 推理的返回值:从生成的文件路径编码的字符串, 编码标志以 "
"开头,后面跟序列化后的字典, 字典中 files键存放了一个列表,元素是生成的音频文件路径。 - 支持的模型为:bark
Examples:
>>> from lazyllm import launchers, UrlModule
>>> from lazyllm.components import BarkDeploy
>>> deployer = BarkDeploy(launchers.remote())
>>> url = deployer(base_model='bark')
>>> model = UrlModule(url=url)
>>> res = model('Hello World!')
>>> print(res)
... <lazyllm-query>{"query": "", "files": ["path/to/bark/sound_xxx.wav"]}
Source code in lazyllm/components/deploy/text_to_speech/bark.py
lazyllm.components.MusicGenDeploy
Bases: TTSBase
MusicGen 模型部署类。该类用于将MusicGen模型部署到指定服务器上,以便可以通过网络进行调用。
__init__(self, launcher=None)
构造函数,初始化部署类。
Parameters:
-
launcher(launcher, default:None) –用于启动远程服务的启动器实例。
__call__(self, finetuned_model=None, base_model=None)
部署模型,并返回远程服务地址。
Parameters:
-
finetuned_model(str) –如果提供,则使用该模型进行部署;如果未提供或路径无效,则使用
base_model。 -
base_model(str) –默认模型,如果
finetuned_model无效,则使用该模型进行部署。 -
返回值(str) –远程服务的URL地址。
Notes
- 推理的输入:字符串。待生成音频的对应文字。
- 推理的返回值:从生成的文件路径编码的字符串, 编码标志以 "
"开头,后面跟序列化后的字典, 字典中 files键存放了一个列表,元素是生成的音频文件路径。 - 支持的模型为:musicgen-small
Examples:
>>> from lazyllm import launchers, UrlModule
>>> from lazyllm.components import MusicGenDeploy
>>> deployer = MusicGenDeploy(launchers.remote())
>>> url = deployer(base_model='musicgen-small')
>>> model = UrlModule(url=url)
>>> model('Symphony with flute as the main melody')
... <lazyllm-query>{"query": "", "files": ["path/to/musicgen/sound_xxx.wav"]}
Source code in lazyllm/components/deploy/text_to_speech/musicgen.py
Speech to Text
lazyllm.components.SenseVoiceDeploy
Bases: LazyLLMDeployBase
SenseVoice 模型部署类。该类用于将SenseVoice模型部署到指定服务器上,以便可以通过网络进行调用。
__init__(self, launcher=None)
构造函数,初始化部署类。
Parameters:
-
launcher(Optional[LazyLLMLaunchersBase], default:None) –Launcher instance, defaults to None.
-
log_path(Optional[str], default:None) –Log file path, defaults to None.
-
trust_remote_code(bool, default:True) –Whether to trust remote code, defaults to True.
-
port(Optional[int], default:None) –Service port number, defaults to None.
Notes
- 推理的输入:字符串。音频路径或者链接。
- 推理的返回值:字符串。识别出的内容。
- 支持的模型为:SenseVoiceSmall
Examples:
>>> import os
>>> import lazyllm
>>> from lazyllm import launchers, UrlModule
>>> from lazyllm.components import SenseVoiceDeploy
>>> deployer = SenseVoiceDeploy(launchers.remote())
>>> url = deployer(base_model='SenseVoiceSmall')
>>> model = UrlModule(url=url)
>>> model('path/to/audio') # support format: .mp3, .wav
... xxxxxxxxxxxxxxxx
Source code in lazyllm/components/deploy/speech_to_text/sense_voice.py
lazyllm.components.deploy.speech_to_text.sense_voice.SenseVoice
Bases: object
SenseVoice 类,封装了基于 FunASR 的语音转文本模型加载与调用逻辑。
支持懒加载、自动模型下载,输入可为字符串路径、URL 或包含音频的字典。
Parameters:
-
base_path(str) –模型路径或标识符,将通过 ModelManager 下载到本地。
-
source(Optional[str], default:None) –模型来源,若未指定则使用
lazyllm.config['model_source']。 -
init(bool, default:False) –是否在初始化时立即加载模型,默认为
False。
Attributes:
-
base_path(str) –下载或解析后的模型路径。
-
model(Optional[AutoModel]) –FunASR 语音识别模型实例,初始化后可用。
-
init_flag–用于懒加载的标志,确保模型只加载一次。
Source code in lazyllm/components/deploy/speech_to_text/sense_voice.py
load_stt()
初始化并加载 FunASR 语音转文本模型,如果存在 torch_npu 则支持华为 NPU 加速。
使用 fsmn-vad 进行语音活动检测(VAD),支持长语音段。
单段语音最大持续时间为 30 秒。
默认推理设备为 cuda:0(GPU)。
加载的模型将保存在 self.model 中,用于后续音频转写。
注意:
- 如果当前环境中存在 torch_npu,函数会导入以支持昇腾 NPU 加速。
Source code in lazyllm/components/deploy/speech_to_text/sense_voice.py
rebuild(base_path, init)
classmethod
类方法,用于在反序列化过程中重新构建 SenseVoice 实例(例如使用 cloudpickle)。
Parameters:
-
base_path(str) –语音识别模型路径。
-
init(bool) –实例化时是否立即初始化并加载模型。
Returns:
- SenseVoice: 返回一个新的
SenseVoice实例,用于支持序列化/多进程兼容。
Source code in lazyllm/components/deploy/speech_to_text/sense_voice.py
ModelManager
lazyllm.components.ModelManager
ModelManager 是 LazyLLM 提供的模型管理与下载工具类,支持本地搜索和 Huggingface/Modelscope 下载。
Parameters:
-
model_source(Optional[str]) –模型下载源,仅支持
huggingface或modelscope。 未提供时使用 LAZYLLM_MODEL_SOURCE,若未设置则默认modelscope。 -
token(Optional[str], default:config['model_source_token']) –下载私有模型的访问令牌。未提供时使用 LAZYLLM_MODEL_SOURCE_TOKEN。
-
model_path(Optional[str], default:config['model_path']) –冒号分隔的本地绝对路径列表,用于下载前搜索模型。未提供时使用 LAZYLLM_MODEL_PATH。
-
cache_dir(Optional[str], default:config['model_cache_dir']) –本地缓存目录,用于存放下载的模型。未提供时使用 LAZYLLM_MODEL_CACHE_DIR,默认
~/.lazyllm/model。
Static Methods
get_model_type(model: str) -> str
返回指定模型类型,如 llm、chat,未识别返回 llm。
get_model_prompt_keys(model: str) -> dict
返回模型的 prompt key 映射字典。
validate_model_path(model_path: str) -> bool
检查目录下是否存在有效模型文件(扩展名: .pt, .bin, .safetensors)。
Instance Methods
download(model: Optional[str] = '', call_back: Optional[Callable] = None) -> str | bool 下载指定模型。流程: 1. 在 model_path 列出的本地目录搜索; 2. 未找到则在 cache_dir 下搜索; 3. 仍未找到则从 model_source 下载并存放 cache_dir。
Args:
model (Optional[str]): 目标模型名称,可使用简略名称或下载源完整名称。
call_back (Optional[Callable]): 下载进度回调函数,可选。
Examples:
>>> from lazyllm.components import ModelManager
>>> downloader = ModelManager(model_source='modelscope')
>>> downloader.download('chatglm3-6b')
Source code in lazyllm/components/utils/downloader/model_downloader.py
121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 | |
get_model_type(model)
cached
staticmethod
根据模型名称获取模型类型(如 LLM、VLM 等)。
Parameters:
-
model(str) –模型名称或路径,必须为非空字符串。
Returns:
- str: 模型类型,如果无法匹配则返回
llm。
Source code in lazyllm/components/utils/downloader/model_downloader.py
get_model_prompt_keys(model)
cached
staticmethod
获取指定模型的 prompt key 映射字典,用于推理时构建输入。
Parameters:
-
model(str) –模型名称或路径。
Returns:
- dict: 模型对应的 prompt key 映射,如果不存在则返回空字典
Source code in lazyllm/components/utils/downloader/model_downloader.py
validate_model_path(model_path)
staticmethod
检查指定路径下是否存在有效的模型文件(.pt, .bin, .safetensors)。
Parameters:
-
model_path(str) –模型目录路径。
Returns:
- bool: 如果目录中存在模型文件返回 True,否则返回 False
Source code in lazyllm/components/utils/downloader/model_downloader.py
download(model='', call_back=None)
下载指定名称的模型,如果本地已有则直接返回本地路径;
支持 Huggingface 和 Modelscope 平台的自动下载,并会在缓存目录创建符号链接以便统一管理。
Parameters:
-
model(str, default:'') –模型名称或路径,默认为空字符串,表示不下载。
-
call_back(Optional[Callable], default:None) –下载进度回调函数,接受当前下载状态等参数。
Returns:
- str | bool: 模型在本地的完整路径,如果下载失败返回 False
Source code in lazyllm/components/utils/downloader/model_downloader.py
Formatter
lazyllm.components.formatter.LazyLLMFormatterBase
此类是格式化器的基类,格式化器是模型输出结果的格式化器,用户可以自定义格式化器,也可以使用LazyLLM提供的格式化器。
Examples:
>>> from lazyllm.components.formatter import LazyLLMFormatterBase
>>> class MyFormatter(LazyLLMFormatterBase):
... def __init__(self, formatter: str = None):
... self._formatter = formatter
... if self._formatter:
... self._parse_formatter()
... else:
... self._slices = None
... def _parse_formatter(self):
... slice_str = self._formatter.strip()[1:-1]
... slices = []
... parts = slice_str.split(":")
... start = int(parts[0]) if parts[0] else None
... end = int(parts[1]) if len(parts) > 1 and parts[1] else None
... step = int(parts[2]) if len(parts) > 2 and parts[2] else None
... slices.append(slice(start, end, step))
... self._slices = slices
... def _load(self, data):
... return [int(x) for x in data.strip('[]').split(',')]
... def _parse_py_data_by_formatter(self, data):
... if self._slices is not None:
... result = []
... for s in self._slices:
... if isinstance(s, slice):
... result.extend(data[s])
... else:
... result.append(data[int(s)])
... return result
... else:
... return data
...
>>> fmt = MyFormatter("[1:3]")
>>> res = fmt.format("[1,2,3,4,5]")
>>> print(res)
[2, 3]
Source code in lazyllm/components/formatter/formatterbase.py
format(msg)
格式化输入消息。
Parameters:
-
msg–输入消息,可以是字符串或其他格式
Returns:
- 格式化后的数据,具体类型由子类实现决定
Source code in lazyllm/components/formatter/formatterbase.py
lazyllm.components.formatter.formatterbase.JsonLikeFormatter
Bases: LazyLLMFormatterBase
该类用于以类 JSON 的格式提取嵌套结构(如 dict、list、tuple)中的子字段内容。
其功能通过格式化字符串 formatter 来控制,格式类似于数组/字典的索引切片表达式。例如:
[0]表示取第 0 个元素[0][{key}]表示取第 0 个元素并获取其中 key 字段[0,1][{a,b}]表示同时提取第 0 和第 1 个对象的 a 和 b 字段[::2]表示步长为 2 的切片*[0][{x}]表示以包装格式返回处理后的数据(用于进一步结构化)
Parameters:
-
formatter(str, default:None) –控制提取规则的格式字符串。若为 None,则返回原始数据。
Examples:
>>> from lazyllm.components.formatter.formatterbase import JsonLikeFormatter
>>> formatter = JsonLikeFormatter("[{a,b}]")
Source code in lazyllm/components/formatter/formatterbase.py
124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 | |
lazyllm.components.formatter.formatterbase.PythonFormatter
lazyllm.components.formatter.FileFormatter
Bases: LazyLLMFormatterBase
用于处理带文档上下文的查询字符串格式转换的格式化器。
支持三种模式:
- "decode":将结构化查询字符串解码为包含 query 和 files 的字典。
- "encode":将包含 query 和 files 的字典编码为结构化查询字符串。
- "merge":将多个结构化查询字符串合并为一个整体查询。
Parameters:
-
formatter(str, default:'decode') –指定操作模式,可为 "decode"、"encode" 或 "merge"(默认为 "decode")。
Examples:
Source code in lazyllm/components/formatter/formatterbase.py
lazyllm.components.formatter.YamlFormatter
Bases: JsonLikeFormatter
用于从 YAML 格式的字符串中提取结构化信息的格式化器。
继承自 JsonLikeFormatter,通过内部方法将字符串解析为 Python 对象后使用类 JSON 的方式提取字段。
适合用于处理包含嵌套结构的 YAML 文本,并结合格式化表达式获取目标数据。
Examples:
>>> from lazyllm.components.formatter import YamlFormatter
>>> formatter = YamlFormatter("{name,age}")
>>> msg = """
... name: Alice
... age: 30
... city: London
... """
>>> formatter(msg)
{'name': 'Alice', 'age': 30}
Source code in lazyllm/components/formatter/yamlformatter.py
lazyllm.components.formatter.encode_query_with_filepaths(query=None, files=None)
将查询文本和文件路径编码为带有文档上下文的结构化字符串格式。
当指定文件路径时,该函数会将查询内容与文件路径打包成 JSON 格式,并在前缀 __lazyllm_docs__ 的基础上编码返回。否则仅返回原始查询文本。
Parameters:
-
query(str, default:None) –用户查询字符串,默认为空字符串。
-
files(str or List[str], default:None) –与查询相关的文档路径,可为单个字符串或字符串列表。
Returns:
- str: 编码后的结构化查询字符串,或原始查询。
Raises:
-
AssertionError–如果
files不是字符串或字符串列表,或列表中元素类型错误。
Examples:
>>> # Encode a query along with associated documentation files
>>> encode_query_with_filepaths("Generate questions based on the document", files=["a.md"])
'<lazyllm-query>{"query": "Generate questions based on the document", "files": ["a.md"]}'
Source code in lazyllm/components/formatter/formatterbase.py
lazyllm.components.formatter.decode_query_with_filepaths(query_files)
将结构化查询字符串解析为包含原始查询和文件路径的字典格式。
当输入字符串以特殊前缀 __lazyllm_docs__ 开头时,函数会尝试从中提取 JSON 格式的查询信息;否则将原样返回字符串内容。
Parameters:
-
query_files(str) –编码后的查询字符串,可能包含文档路径和查询内容。
Returns:
- Union[dict, str]: 若为结构化格式则返回包含 'query' 和 'files' 的字典,否则返回原始查询字符串。
Raises:
-
AssertionError–如果输入参数不是字符串类型。
-
ValueError–如果字符串为结构化格式但解析 JSON 失败。
Examples:
>>> # Decode a structured query with files
>>> decode_query_with_filepaths('<lazyllm-query>{"query": "Summarize the content", "files": ["doc.md"]}')
{'query': 'Summarize the content', 'files': ['doc.md']}
>>> # Decode a plain string without files
>>> decode_query_with_filepaths("This is just a simple question")
'This is just a simple question'
Source code in lazyllm/components/formatter/formatterbase.py
lazyllm.components.formatter.lazyllm_merge_query(*args)
将多个查询字符串(可能包含文档路径)合并为一个统一的结构化查询字符串。
每个输入参数可以是普通查询字符串或由 encode_query_with_filepaths 编码后的结构化字符串。函数会自动解码、拼接查询文本,并合并所有涉及的文档路径,最终重新编码为统一的查询格式。
Parameters:
-
*args(str, default:()) –多个查询字符串。每个字符串可以是普通文本或已编码的带文件路径的结构化查询。
Returns:
- str: 合并后的结构化查询字符串,包含统一的查询内容与文件路径。
Examples:
>>> # Merge two structured queries with English content and associated files
>>> q1 = encode_query_with_filepaths("Please summarize document one", files=["doc1.md"])
>>> q2 = encode_query_with_filepaths("Add details from document two", files=["doc2.md"])
>>> lazyllm_merge_query(q1, q2)
'<lazyllm-query>{"query": "Please summarize document oneAdd details from document two", "files": ["doc1.md", "doc2.md"]}'
>>> # Merge plain English text queries without documents
>>> lazyllm_merge_query("What is AI?", "Explain deep learning.")
'What is AI?Explain deep learning.'
Source code in lazyllm/components/formatter/formatterbase.py
lazyllm.components.JsonFormatter
Bases: JsonLikeFormatter
此类是JSON格式化器,即用户希望模型输出的内容格式为JSON,还可以通过索引方式对输出内容中的某个字段进行选择。
Examples:
>>> import lazyllm
>>> from lazyllm.components import JsonFormatter
>>> toc_prompt='''
... You are now an intelligent assistant. Your task is to understand the user's input and convert the outline into a list of nested dictionaries. Each dictionary contains a `title` and a `describe`, where the `title` should clearly indicate the level using Markdown format, and the `describe` is a description and writing guide for that section.
...
... Please generate the corresponding list of nested dictionaries based on the following user input:
...
... Example output:
... [
... {
... "title": "# Level 1 Title",
... "describe": "Please provide a detailed description of the content under this title, offering background information and core viewpoints."
... },
... {
... "title": "## Level 2 Title",
... "describe": "Please provide a detailed description of the content under this title, giving specific details and examples to support the viewpoints of the Level 1 title."
... },
... {
... "title": "### Level 3 Title",
... "describe": "Please provide a detailed description of the content under this title, deeply analyzing and providing more details and data support."
... }
... ]
... User input is as follows:
... '''
>>> query = "Please help me write an article about the application of artificial intelligence in the medical field."
>>> m = lazyllm.TrainableModule("internlm2-chat-20b").prompt(toc_prompt).start()
>>> ret = m(query, max_new_tokens=2048)
>>> print(f"ret: {ret!r}") # the model output without specifying a formatter
'Based on your user input, here is the corresponding list of nested dictionaries:
[
{
"title": "# Application of Artificial Intelligence in the Medical Field",
"describe": "Please provide a detailed description of the application of artificial intelligence in the medical field, including its benefits, challenges, and future prospects."
},
{
"title": "## AI in Medical Diagnosis",
"describe": "Please provide a detailed description of how artificial intelligence is used in medical diagnosis, including specific examples of AI-based diagnostic tools and their impact on patient outcomes."
},
{
"title": "### AI in Medical Imaging",
"describe": "Please provide a detailed description of how artificial intelligence is used in medical imaging, including the advantages of AI-based image analysis and its applications in various medical specialties."
},
{
"title": "### AI in Drug Discovery and Development",
"describe": "Please provide a detailed description of how artificial intelligence is used in drug discovery and development, including the role of AI in identifying potential drug candidates and streamlining the drug development process."
},
{
"title": "## AI in Medical Research",
"describe": "Please provide a detailed description of how artificial intelligence is used in medical research, including its applications in genomics, epidemiology, and clinical trials."
},
{
"title": "### AI in Genomics and Precision Medicine",
"describe": "Please provide a detailed description of how artificial intelligence is used in genomics and precision medicine, including the role of AI in analyzing large-scale genomic data and tailoring treatments to individual patients."
},
{
"title": "### AI in Epidemiology and Public Health",
"describe": "Please provide a detailed description of how artificial intelligence is used in epidemiology and public health, including its applications in disease surveillance, outbreak prediction, and resource allocation."
},
{
"title": "### AI in Clinical Trials",
"describe": "Please provide a detailed description of how artificial intelligence is used in clinical trials, including its role in patient recruitment, trial design, and data analysis."
},
{
"title": "## AI in Medical Practice",
"describe": "Please provide a detailed description of how artificial intelligence is used in medical practice, including its applications in patient monitoring, personalized medicine, and telemedicine."
},
{
"title": "### AI in Patient Monitoring",
"describe": "Please provide a detailed description of how artificial intelligence is used in patient monitoring, including its role in real-time monitoring of vital signs and early detection of health issues."
},
{
"title": "### AI in Personalized Medicine",
"describe": "Please provide a detailed description of how artificial intelligence is used in personalized medicine, including its role in analyzing patient data to tailor treatments and predict outcomes."
},
{
"title": "### AI in Telemedicine",
"describe": "Please provide a detailed description of how artificial intelligence is used in telemedicine, including its applications in remote consultations, virtual diagnoses, and digital health records."
},
{
"title": "## AI in Medical Ethics and Policy",
"describe": "Please provide a detailed description of the ethical and policy considerations surrounding the use of artificial intelligence in the medical field, including issues related to data privacy, bias, and accountability."
}
]'
>>> m = lazyllm.TrainableModule("internlm2-chat-20b").formatter(JsonFormatter("[:][title]")).prompt(toc_prompt).start()
>>> ret = m(query, max_new_tokens=2048)
>>> print(f"ret: {ret}") # the model output of the specified formaater
['# Application of Artificial Intelligence in the Medical Field', '## AI in Medical Diagnosis', '### AI in Medical Imaging', '### AI in Drug Discovery and Development', '## AI in Medical Research', '### AI in Genomics and Precision Medicine', '### AI in Epidemiology and Public Health', '### AI in Clinical Trials', '## AI in Medical Practice', '### AI in Patient Monitoring', '### AI in Personalized Medicine', '### AI in Telemedicine', '## AI in Medical Ethics and Policy']
Source code in lazyllm/components/formatter/jsonformatter.py
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 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 | |
lazyllm.components.EmptyFormatter
Bases: LazyLLMFormatterBase
此类是空的格式化器,即用户希望对模型的输出不做格式化,用户可以对模型指定该格式化器,也可以不指定(模型默认的格式化器就是空格式化器)
Examples:
>>> import lazyllm
>>> from lazyllm.components import EmptyFormatter
>>> toc_prompt='''
... You are now an intelligent assistant. Your task is to understand the user's input and convert the outline into a list of nested dictionaries. Each dictionary contains a `title` and a `describe`, where the `title` should clearly indicate the level using Markdown format, and the `describe` is a description and writing guide for that section.
...
... Please generate the corresponding list of nested dictionaries based on the following user input:
...
... Example output:
... [
... {
... "title": "# Level 1 Title",
... "describe": "Please provide a detailed description of the content under this title, offering background information and core viewpoints."
... },
... {
... "title": "## Level 2 Title",
... "describe": "Please provide a detailed description of the content under this title, giving specific details and examples to support the viewpoints of the Level 1 title."
... },
... {
... "title": "### Level 3 Title",
... "describe": "Please provide a detailed description of the content under this title, deeply analyzing and providing more details and data support."
... }
... ]
... User input is as follows:
... '''
>>> query = "Please help me write an article about the application of artificial intelligence in the medical field."
>>> m = lazyllm.TrainableModule("internlm2-chat-20b").prompt(toc_prompt).start() # the model output without specifying a formatter
>>> ret = m(query, max_new_tokens=2048)
>>> print(f"ret: {ret!r}")
'Based on your user input, here is the corresponding list of nested dictionaries:
[
{
"title": "# Application of Artificial Intelligence in the Medical Field",
"describe": "Please provide a detailed description of the application of artificial intelligence in the medical field, including its benefits, challenges, and future prospects."
},
{
"title": "## AI in Medical Diagnosis",
"describe": "Please provide a detailed description of how artificial intelligence is used in medical diagnosis, including specific examples of AI-based diagnostic tools and their impact on patient outcomes."
},
{
"title": "### AI in Medical Imaging",
"describe": "Please provide a detailed description of how artificial intelligence is used in medical imaging, including the advantages of AI-based image analysis and its applications in various medical specialties."
},
{
"title": "### AI in Drug Discovery and Development",
"describe": "Please provide a detailed description of how artificial intelligence is used in drug discovery and development, including the role of AI in identifying potential drug candidates and streamlining the drug development process."
},
{
"title": "## AI in Medical Research",
"describe": "Please provide a detailed description of how artificial intelligence is used in medical research, including its applications in genomics, epidemiology, and clinical trials."
},
{
"title": "### AI in Genomics and Precision Medicine",
"describe": "Please provide a detailed description of how artificial intelligence is used in genomics and precision medicine, including the role of AI in analyzing large-scale genomic data and tailoring treatments to individual patients."
},
{
"title": "### AI in Epidemiology and Public Health",
"describe": "Please provide a detailed description of how artificial intelligence is used in epidemiology and public health, including its applications in disease surveillance, outbreak prediction, and resource allocation."
},
{
"title": "### AI in Clinical Trials",
"describe": "Please provide a detailed description of how artificial intelligence is used in clinical trials, including its role in patient recruitment, trial design, and data analysis."
},
{
"title": "## AI in Medical Practice",
"describe": "Please provide a detailed description of how artificial intelligence is used in medical practice, including its applications in patient monitoring, personalized medicine, and telemedicine."
},
{
"title": "### AI in Patient Monitoring",
"describe": "Please provide a detailed description of how artificial intelligence is used in patient monitoring, including its role in real-time monitoring of vital signs and early detection of health issues."
},
{
"title": "### AI in Personalized Medicine",
"describe": "Please provide a detailed description of how artificial intelligence is used in personalized medicine, including its role in analyzing patient data to tailor treatments and predict outcomes."
},
{
"title": "### AI in Telemedicine",
"describe": "Please provide a detailed description of how artificial intelligence is used in telemedicine, including its applications in remote consultations, virtual diagnoses, and digital health records."
},
{
"title": "## AI in Medical Ethics and Policy",
"describe": "Please provide a detailed description of the ethical and policy considerations surrounding the use of artificial intelligence in the medical field, including issues related to data privacy, bias, and accountability."
}
]'
>>> m = lazyllm.TrainableModule("internlm2-chat-20b").formatter(EmptyFormatter()).prompt(toc_prompt).start() # the model output of the specified formatter
>>> ret = m(query, max_new_tokens=2048)
>>> print(f"ret: {ret!r}")
'Based on your user input, here is the corresponding list of nested dictionaries:
[
{
"title": "# Application of Artificial Intelligence in the Medical Field",
"describe": "Please provide a detailed description of the application of artificial intelligence in the medical field, including its benefits, challenges, and future prospects."
},
{
"title": "## AI in Medical Diagnosis",
"describe": "Please provide a detailed description of how artificial intelligence is used in medical diagnosis, including specific examples of AI-based diagnostic tools and their impact on patient outcomes."
},
{
"title": "### AI in Medical Imaging",
"describe": "Please provide a detailed description of how artificial intelligence is used in medical imaging, including the advantages of AI-based image analysis and its applications in various medical specialties."
},
{
"title": "### AI in Drug Discovery and Development",
"describe": "Please provide a detailed description of how artificial intelligence is used in drug discovery and development, including the role of AI in identifying potential drug candidates and streamlining the drug development process."
},
{
"title": "## AI in Medical Research",
"describe": "Please provide a detailed description of how artificial intelligence is used in medical research, including its applications in genomics, epidemiology, and clinical trials."
},
{
"title": "### AI in Genomics and Precision Medicine",
"describe": "Please provide a detailed description of how artificial intelligence is used in genomics and precision medicine, including the role of AI in analyzing large-scale genomic data and tailoring treatments to individual patients."
},
{
"title": "### AI in Epidemiology and Public Health",
"describe": "Please provide a detailed description of how artificial intelligence is used in epidemiology and public health, including its applications in disease surveillance, outbreak prediction, and resource allocation."
},
{
"title": "### AI in Clinical Trials",
"describe": "Please provide a detailed description of how artificial intelligence is used in clinical trials, including its role in patient recruitment, trial design, and data analysis."
},
{
"title": "## AI in Medical Practice",
"describe": "Please provide a detailed description of how artificial intelligence is used in medical practice, including its applications in patient monitoring, personalized medicine, and telemedicine."
},
{
"title": "### AI in Patient Monitoring",
"describe": "Please provide a detailed description of how artificial intelligence is used in patient monitoring, including its role in real-time monitoring of vital signs and early detection of health issues."
},
{
"title": "### AI in Personalized Medicine",
"describe": "Please provide a detailed description of how artificial intelligence is used in personalized medicine, including its role in analyzing patient data to tailor treatments and predict outcomes."
},
{
"title": "### AI in Telemedicine",
"describe": "Please provide a detailed description of how artificial intelligence is used in telemedicine, including its applications in remote consultations, virtual diagnoses, and digital health records."
},
{
"title": "## AI in Medical Ethics and Policy",
"describe": "Please provide a detailed description of the ethical and policy considerations surrounding the use of artificial intelligence in the medical field, including issues related to data privacy, bias, and accountability."
}
]'
Source code in lazyllm/components/formatter/formatterbase.py
226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 | |
lazyllm.components.FunctionCallFormatter
Bases: LazyLLMFormatterBase
函数调用格式化器,用于处理包含函数调用信息的消息字典。
该格式化器专门用于处理函数调用场景下的模型输出,只提取字典中的 'role'、'content' 和 'tool_calls' 字段,过滤掉其他不需要的字段。
主要用于 FunctionCall 等工具调用相关的功能模块。
注意
- 输入必须是字典类型,否则会抛出断言错误
- 只保留字典中存在的 'role'、'content'、'tool_calls' 字段
Examples:
>>> from lazyllm.components.formatter.formatterbase import FunctionCallFormatter
>>> formatter = FunctionCallFormatter()
>>>
>>> # 处理包含函数调用的消息
>>> msg = {
... 'role': 'assistant',
... 'content': 'I will call a function to get the weather.',
... 'tool_calls': [
... {
... 'id': 'call_123',
... 'type': 'function',
... 'function': {
... 'name': 'get_weather',
... 'arguments': '{"location": "Beijing"}'
... }
... }
... ],
... 'other_field': 'will be filtered'
... }
>>> result = formatter.format(msg)
>>> print(result)
{'role': 'assistant', 'content': 'I will call a function to get the weather.', 'tool_calls': [{'id': 'call_123', 'type': 'function', 'function': {'name': 'get_weather', 'arguments': '{"location": "Beijing"}'}}]}
>>>
>>> # 处理只包含部分字段的消息
>>> msg2 = {
... 'role': 'assistant',
... 'content': 'Hello, how can I help you?'
... }
>>> result2 = formatter.format(msg2)
>>> print(result2)
{'role': 'assistant', 'content': 'Hello, how can I help you?'}
Source code in lazyllm/components/formatter/formatterbase.py
lazyllm.components.formatter.formatterbase.PipelineFormatter
Bases: LazyLLMFormatterBase
流水线格式化器,用于将数据处理流水线封装为格式化器。
该类将Pipeline实例包装为格式化器,支持通过管道操作符组合多个格式化器。
Parameters:
-
formatter(Pipeline) –要封装的流水线实例
Source code in lazyllm/components/formatter/formatterbase.py
ComponentBase
lazyllm.components.core.ComponentBase
Bases: object
组件基类,提供统一的接口与基础实现,便于创建不同类型的组件。
组件通过指定的 Launcher 来执行任务,支持自定义任务执行逻辑。
Parameters:
-
launcher(LazyLLMLaunchersBase or type, default:empty()) –组件使用的启动器实例或启动器类,默认为空启动器(empty)。
Examples:
>>> from lazyllm.components.core import ComponentBase
>>> class MyComponent(ComponentBase):
... def apply(self, x):
... return x * 2
>>> comp = MyComponent()
>>> comp.name = "ExampleComponent"
>>> print(comp.name)
ExampleComponent
>>> result = comp(10)
>>> print(result)
20
>>> print(comp.apply(5))
10
Source code in lazyllm/components/core.py
apply()
cmd(*args, **kw)
生成组件的执行命令,需由子类实现。
返回的命令可以是字符串、元组或列表,表示具体执行任务的指令。
注意:
调用组件时,如果未重写 apply 方法,将通过此命令生成任务并由启动器执行。
lazyllm.components.deploy.ray.Distributed
Bases: LazyLLMDeployBase
分布式部署类,继承自LazyLLMDeployBase。
提供基于Ray框架的分布式模型部署功能,支持多节点集群部署。
Parameters:
-
launcher–启动器配置,默认为远程启动器(ngpus=1)
-
port(int, default:None) –服务端口号,默认为随机端口(30000-40000)
Attributes:
-
finetuned_model–微调后的模型路径
-
base_model–基础模型路径
-
master_ip–主节点IP地址
Methods:
-
cmd–生成部署命令
-
geturl–获取部署服务的URL地址
Source code in lazyllm/components/deploy/ray.py
cmd(finetuned_model=None, base_model=None, master_ip=None)
生成Ray分布式部署命令。
根据是否为主节点生成相应的Ray启动命令,支持头节点和工作节点两种模式。
Parameters:
-
finetuned_model–微调后的模型路径
-
base_model–基础模型路径
-
master_ip–主节点IP地址,如果为空则作为头节点启动
Returns:
-
LazyLLMCMD–包含部署命令的对象