Components
Finetune
lazyllm.components.finetune.AlpacaloraFinetune
Bases: LazyLLMFinetuneBase
此类是 LazyLLMFinetuneBase
的子类,基于 alpaca-lora 项目提供的LoRA微调能力,用于对大语言模型进行LoRA微调。
Parameters:
-
base_model
(str
) –用于进行微调的基模型的本地绝对路径。
-
target_path
(str
) –微调后模型保存LoRA权重的本地绝对路径。
-
merge_path
(str
, default:None
) –模型合并LoRA权重后的路径,默认为
None
。如果未指定,则会在target_path
下创建 "lazyllm_lora" 和 "lazyllm_merge" 目录,分别作为target_path
和merge_path
。 -
model_name
(str
, default:'LLM'
) –模型的名称,用于设置日志名的前缀,默认为
LLM
。 -
cp_files
(str
, default:'tokeniz*'
) –指定复制源自基模型路径下的配置文件,会被复制到
merge_path
,默认为tokeniz*
-
launcher
(launcher
, default:remote(ngpus=1)
) –微调的启动器,默认为
launchers.remote(ngpus=1)
。 -
kw
–关键字参数,用于更新默认的训练参数。请注意,除了以下列出的关键字参数外,这里不能传入额外的关键字参数。
此类的关键字参数及其默认值如下:
Other Parameters:
-
data_path
(str
) –数据路径,默认为
None
;一般在此类对象被调用时候,作为唯一位置参数传入。 -
batch_size
(int
) –批处理大小,默认为
64
。 -
micro_batch_size
(int
) –微批处理大小,默认为
4
。 -
num_epochs
(int
) –训练轮数,默认为
2
。 -
learning_rate
(float
) –学习率,默认为
5.e-4
。 -
cutoff_len
(int
) –截断长度,默认为
1030
;输入数据token超过该长度就会被截断。 -
filter_nums
(int
) –过滤器数量,默认为
1024
;仅保留低于该token长度数值的输入。 -
val_set_size
(int
) –验证集大小,默认为
200
。 -
lora_r
(int
) –LoRA 的秩,默认为
8
;该数值决定添加参数的量,数值越小参数量越小。 -
lora_alpha
(int
) –LoRA 的融合因子,默认为
32
;该数值决定LoRA参数对基模型参数的影响度,数值越大影响越大。 -
lora_dropout
(float
) –LoRA 的丢弃率,默认为
0.05
,一般用于防止过拟合。 -
lora_target_modules
(str
) –LoRA 的目标模块,默认为
[wo,wqkv]
,该默认值为 InternLM2 模型的;该配置项不同模型的不一样。 -
modules_to_save
(str
) –用于全量微调的模块,默认为
[tok_embeddings,output]
,该默认值为 InternLM2 模型的;该配置项不同模型的不一样。 -
deepspeed
(str
) –DeepSpeed 配置文件的路径,默认使用 LazyLLM 代码仓库中预制的配置文件:
ds.json
。 -
prompt_template_name
(str
) –提示模板的名称,默认为
alpaca
,即默认使用 LazyLLM 提供的提示模板。 -
train_on_inputs
(bool
) –是否在输入上训练,默认为
True
。 -
show_prompt
(bool
) –是否显示提示,默认为
False
。 -
nccl_port
(int
) –NCCL 端口,默认为
19081
。
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 |
|
lazyllm.components.finetune.CollieFinetune
Bases: LazyLLMFinetuneBase
此类是 LazyLLMFinetuneBase
的子类,基于 Collie 框架提供的LoRA微调能力,用于对大语言模型进行LoRA微调。
Parameters:
-
base_model
(str
) –用于进行微调的基模型。要求是基模型的路径。
-
target_path
(str
) –微调后模型保存LoRA权重的路径。
-
merge_path
(str
, default:None
) –模型合并LoRA权重后的路径,默认为None。如果未指定,则会在
target_path
下创建 "lazyllm_lora" 和 "lazyllm_merge" 目录,分别作为target_path
和merge_path
。 -
model_name
(str
, default:'LLM'
) –模型的名称,用于设置日志名的前缀,默认为 "LLM"。
-
cp_files
(str
, default:'tokeniz*'
) –指定复制源自基模型路径下的配置文件,会被复制到
merge_path
,默认为 "tokeniz*" -
launcher
(launcher
, default:remote(ngpus=1)
) –微调的启动器,默认为
launchers.remote(ngpus=1)
。 -
kw
–关键字参数,用于更新默认的训练参数。请注意,除了以下列出的关键字参数外,这里不能传入额外的关键字参数。
此类的关键字参数及其默认值如下:
Other Parameters:
-
data_path
(str
) –数据路径,默认为
None
;一般在此类对象被调用时候,作为唯一位置参数传入。 -
batch_size
(int
) –批处理大小,默认为
64
。 -
micro_batch_size
(int
) –微批处理大小,默认为
4
。 -
num_epochs
(int
) –训练轮数,默认为
2
。 -
learning_rate
(float
) –学习率,默认为
5.e-4
。 -
dp_size
(int
) –数据并行参数,默认为
8
。 -
pp_size
(int
) –流水线并行参数,默认为
1
。 -
tp_size
(int
) –张量并行参数,默认为
1
。 -
lora_r
(int
) –LoRA 的秩,默认为
8
;该数值决定添加参数的量,数值越小参数量越小。 -
lora_alpha
(int
) –LoRA 的融合因子,默认为
32
;该数值决定LoRA参数对基模型参数的影响度,数值越大影响越大。 -
lora_dropout
(float
) –LoRA 的丢弃率,默认为
0.05
,一般用于防止过拟合。 -
lora_target_modules
(str
) –LoRA 的目标模块,默认为
[wo,wqkv]
,该默认值为 InternLM2 模型的;该配置项不同模型的不一样。 -
modules_to_save
(str
) –用于全量微调的模块,默认为
[tok_embeddings,output]
,该默认值为 InternLM2 模型的;该配置项不同模型的不一样。 -
prompt_template_name
(str
) –提示模板的名称,默认为
alpaca
,即默认使用 LazyLLM 提供的提示模板。
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 120 121 |
|
lazyllm.components.finetune.LlamafactoryFinetune
Bases: LazyLLMFinetuneBase
此类是 LazyLLMFinetuneBase
的子类,基于 LLaMA-Factory 框架提供的训练能力,用于对大语言模型(或视觉语言模型)进行训练。
Parameters:
-
base_model
(str
) –用于进行训练的基模型。要求是基模型的路径。
-
target_path
(str
) –训练后模型保存权重的路径。
-
merge_path
(str
, default:None
) –模型合并LoRA权重后的路径,默认为None。如果未指定,则会在
target_path
下创建 "lazyllm_lora" 和 "lazyllm_merge" 目录,分别作为target_path
和merge_path
。 -
config_path
(str
, default:None
) –LLaMA-Factory的训练配置文件(这里要求格式为yaml),默认为None。如果未指定,则会在当前工作路径下,创建一个名为
.temp
的文件夹,并在其中生成以train_
前缀开头,以.yaml
结尾的配置文件。 -
export_config_path
(str
, default:None
) –LLaMA-Factory的Lora权重合并的配置文件(这里要求格式为yaml),默认为None。如果未指定,则会在当前工作路径下中的
.temp
文件夹内生成以merge_
前缀开头,以.yaml
结尾的配置文件。 -
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
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 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 |
|
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
Deploy
lazyllm.components.deploy.Lightllm
Bases: LazyLLMDeployBase
此类是 LazyLLMDeployBase
的子类,基于 LightLLM 框架提供的推理能力,用于对大语言模型进行推理。
Parameters:
-
trust_remote_code
(bool
, default:True
) –是否允许加载来自远程服务器的模型代码,默认为
True
。 -
launcher
(launcher
, default:remote(ngpus=1)
) –微调的启动器,默认为
launchers.remote(ngpus=1)
。 -
stream
(bool
, default:False
) –是否为流式响应,默认为
False
。 -
kw
–关键字参数,用于更新默认的训练参数。请注意,除了以下列出的关键字参数外,这里不能传入额外的关键字参数。
此类的关键字参数及其默认值如下:
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
。
Examples:
Source code in lazyllm/components/deploy/lightllm.py
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 |
|
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)
。 -
stream
(bool
, default:False
) –是否为流式响应,默认为
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
) –服务的端口号,默认为
auto
。 -
host
(str
) –服务的IP地址,默认为
0.0.0.0
。 -
seed
(int
) –随机数种子,默认为
0
。 -
tokenizer_mode
(str
) –tokenizer的加载模式,默认为
auto
。 -
max-num-seqs
(int
) –推理引擎最大的并行请求数, 默认为
256
。
Examples:
Source code in lazyllm/components/deploy/vllm.py
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 |
|
lazyllm.components.deploy.LMDeploy
Bases: LazyLLMDeployBase
此类是 LazyLLMDeployBase
的子类,基于 LMDeploy 框架提供的推理能力,用于对大语言模型进行推理。
Parameters:
-
launcher
(launcher
, default:remote(ngpus=1)
) –微调的启动器,默认为
launchers.remote(ngpus=1)
。 -
stream
(bool
, default:False
) –是否为流式响应,默认为
False
。 -
kw
–关键字参数,用于更新默认的训练参数。请注意,除了以下列出的关键字参数外,这里不能传入额外的关键字参数。
此类的关键字参数及其默认值如下:
Other Parameters:
-
tp
(int
) –张量并行参数,默认为
1
。 -
server-name
(str
) –服务的IP地址,默认为
0.0.0.0
。 -
server-port
(int
) –服务的端口号,默认为
None
,此情况下LazyLLM会自动生成随机端口号。 -
max-batch-size
(int
) –最大batch数, 默认为
128
。
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('Mini-InternVL-Chat-2B-V1-5').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
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 |
|
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
Launcher
lazyllm.launcher.EmptyLauncher
Bases: LazyLLMLaunchersBase
此类是 LazyLLMLaunchersBase
的子类,作为一个本地的启动器。
Parameters:
-
subprocess
(bool
, default:False
) –是否使用子进程来启动。默认为
False
。 -
sync
(bool
, default:True
) –是否同步执行作业。默认为
True
,否则为异步执行。
Examples:
Source code in lazyllm/launcher.py
1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 |
|
lazyllm.launcher.RemoteLauncher
Bases: LazyLLMLaunchersBase
此类是 LazyLLMLaunchersBase
的一个子类,它充当了一个远程启动器的代理。它根据配置文件中的 lazyllm.config['launcher']
条目动态地创建并返回一个对应的启动器实例(例如:SlurmLauncher
或 ScoLauncher
)。
Parameters:
-
*args
–位置参数,将传递给动态创建的启动器构造函数。
-
sync
(bool
) –是否同步执行作业。默认为
False
。 -
**kwargs
–关键字参数,将传递给动态创建的启动器构造函数。
注意事项
RemoteLauncher
不是一个直接的启动器,而是根据配置动态创建一个启动器。- 配置文件中的
lazyllm.config['launcher']
指定一个存在于lazyllm.launchers
模块中的启动器类名。该配置可通过设置环境变量LAZYLLM_DEFAULT_LAUNCHER
来设置。如:export LAZYLLM_DEFAULT_LAUNCHER=sco
,export LAZYLLM_DEFAULT_LAUNCHER=slurm
。
Examples:
Source code in lazyllm/launcher.py
lazyllm.launcher.SlurmLauncher
Bases: LazyLLMLaunchersBase
此类是 LazyLLMLaunchersBase
的子类,作为slurm启动器。
具体而言,它提供了启动和配置 Slurm 作业的方法,包括指定分区、节点数量、进程数量、GPU 数量以及超时时间等参数。
Parameters:
-
partition
(str
, default:None
) –要使用的 Slurm 分区。默认为
None
,此时将使用lazyllm.config['partition']
中的默认分区。该配置可通过设置环境变量来生效,如export LAZYLLM_SLURM_PART=a100
。 -
nnode
((int
, default:1
) –要使用的节点数量。默认为
1
。 -
nproc
(int
, default:1
) –每个节点要使用的进程数量。默认为
1
。 -
ngpus
–(int): 每个节点要使用的 GPU 数量。默认为
None
, 即不使用 GPU。 -
timeout
(int
, default:None
) –作业的超时时间(以秒为单位)。默认为
None
,此时将不设置超时时间。 -
sync
(bool
, default:True
) –是否同步执行作业。默认为
True
,否则为异步执行。
Examples:
>>> import lazyllm
>>> launcher = lazyllm.launchers.slurm(partition='partition_name', nnode=1, nproc=1, ngpus=1, sync=False)
Source code in lazyllm/launcher.py
1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 |
|
lazyllm.launcher.ScoLauncher
Bases: LazyLLMLaunchersBase
此类是 LazyLLMLaunchersBase
的子类,作为SCO (Sensecore)启动器。
具体而言,它提供了启动和配置 SCO 作业的方法,包括指定分区、工作空间名称、框架类型、节点数量、进程数量、GPU 数量以及是否使用 torchrun 等参数。
Parameters:
-
partition
(str
, default:None
) –要使用的分区。默认为
None
,此时将使用lazyllm.config['partition']
中的默认分区。该配置可通过设置环境变量来生效,如export LAZYLLM_SLURM_PART=a100
。 -
workspace_name
(str
, default:config['sco.workspace']
) –SCO 上的工作空间名称。默认为
lazyllm.config['sco.workspace']
中的配置。该配置可通过设置环境变量来生效,如export LAZYLLM_SCO_WORKSPACE=myspace
。 -
framework
(str
, default:'pt'
) –要使用的框架类型,例如
pt
代表 PyTorch。默认为pt
。 -
nnode
((int
, default:1
) –要使用的节点数量。默认为
1
。 -
nproc
(int
, default:1
) –每个节点要使用的进程数量。默认为
1
。 -
ngpus
–(int): 每个节点要使用的 GPU 数量。默认为
1
, 使用1块 GPU。 -
torchrun
(bool
, default:False
) –是否使用
torchrun
启动作业。默认为False
。 -
sync
(bool
, default:True
) –是否同步执行作业。默认为
True
,否则为异步执行。
Examples:
>>> import lazyllm
>>> launcher = lazyllm.launchers.sco(partition='partition_name', nnode=1, nproc=1, ngpus=1, sync=False)
Source code in lazyllm/launcher.py
1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 |
|
Prompter
lazyllm.components.prompter.LazyLLMPrompterBase
Prompter的基类,自定义的Prompter需要继承此基类,并通过基类提供的 _init_prompt
函数来设置Prompt模板和Instruction的模板,以及截取结果所使用的字符串。可以查看 :prompt 进一步了解Prompt的设计思想和使用方式。
Prompt模板和Instruction模板都用 {}
表示要填充的字段,其中Prompt可包含的字段有 system
, history
, tools
, user
等,而instruction_template可包含的字段为 instruction
和 extro_keys
。
instruction
由应用的开发者传入, instruction
中也可以带有 {}
用于让定义可填充的字段,方便用户填入额外的信息。如果 instruction
字段为字符串,则认为是系统instruction;如果是字典,则它包含的key只能是 user
和 system
两种选择。 user
表示用户输入的instruction,在prompt中放在用户输入前面, system
表示系统instruction,在prompt中凡在system prompt后面。
Examples:
>>> from lazyllm.components.prompter import PrompterBase
>>> class MyPrompter(PrompterBase):
... def __init__(self, instruction = None, extro_keys = None, show = False):
... super(__class__, self).__init__(show)
... instruction_template = f'{instruction}\n{{extro_keys}}\n'.replace('{extro_keys}', PrompterBase._get_extro_key_template(extro_keys))
... self._init_prompt("<system>{system}</system>\n</instruction>{instruction}</instruction>{history}\n{input}\n, ## Response::", instruction_template, '## Response::')
...
>>> p = MyPrompter('ins {instruction}')
>>> p.generate_prompt('hello')
'<system>You are an AI-Agent developed by LazyLLM.</system>\n</instruction>ins hello\n\n</instruction>\n\n, ## Response::'
>>> p.generate_prompt('hello world', return_dict=True)
{'messages': [{'role': 'system', 'content': 'You are an AI-Agent developed by LazyLLM.\nins hello world\n\n'}, {'role': 'user', 'content': ''}]}
Source code in lazyllm/components/prompter/builtinPrompt.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 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 |
|
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]]
, default:None
) –可以使用的工具合集,大模型用作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.AlpacaPrompter
Bases: LazyLLMPrompterBase
Alpaca格式的Prompter,支持工具调用,不支持历史对话。
Parameters:
-
instruction
(Option[str]
, default:None
) –大模型的任务指令,至少带一个可填充的槽位(如
{instruction}
)。或者使用字典指定system
和user
的指令。 -
extro_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}', extro_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]]
, default:None
) –可以使用的工具合集,大模型用作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,支持工具调用和历史对话
Parameters:
-
instruction
(Option[str]
, default:None
) –大模型的任务指令,可以带0到多个待填充的槽位,用
{}
表示。针对用户instruction可以通过字典传递,字段为user
和system
。 -
extro_keys
(Option[List]
, default:None
) –额外的字段,用户的输入会填充这些字段。
-
show
(bool
, default:False
) –标志是否打印生成的Prompt,默认为False
Examples:
>>> from lazyllm import ChatPrompter
>>> p = ChatPrompter('hello world')
>>> p.generate_prompt('this is my input')
'You are an AI-Agent developed by LazyLLM.hello world\n\n\n\n\n\nthis is my input\n\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\n\n'}, {'role': 'user', 'content': 'this is my input'}]}
>>>
>>> p = ChatPrompter('hello world {instruction}', extro_keys=['knowledge'])
>>> p.generate_prompt(dict(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\n\n\n\n\n\n\nthis is my inp\n\n'
>>> p.generate_prompt(dict(instruction='this is my ins', input='this is my inp', knowledge='LazyLLM-Knowledge'), return_dict=True)
{'messages': [{'role': 'system', 'content': 'You are an AI-Agent developed by LazyLLM.\nhello world this is my ins\nHere are some extra messages you can referred to:\n\n### knowledge:\nLazyLLM-Knowledge\n\n\n'}, {'role': 'user', 'content': 'this is my inp'}]}
>>> p.generate_prompt(dict(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\n\n\n\n\ns1e1s2e2\n\nthis is my inp\n\n'
>>>
>>> p = ChatPrompter(dict(system="hello world", user="this is user instruction {input} "))
>>> p.generate_prompt(dict(input="my input", query="this is user query"))
'You are an AI-Agent developed by LazyLLM.hello world\n\n\n\nthis is user instruction my input this is user query\n\n'
>>> p.generate_prompt(dict(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]]
, default:None
) –可以使用的工具合集,大模型用作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
Register
lazyllm.common.Register
Bases: object
LazyLLM提供的Component的注册机制,可以将任意函数注册成LazyLLM的Component。被注册的函数无需显式的import,即可通过注册器提供的分组机制,在任一位置被索引到。
Source code in lazyllm/common/registry.py
ModelManager
lazyllm.components.ModelManager
ModelManager是LazyLLM为开发者提供的自动下载模型的工具类。目前支持从一个本地目录列表查找指定模型,以及从huggingface或者modelscope自动下载模型数据至指定目录。 在使用ModelManager之前,需要设置下列环境变量:
- LAZYLLM_MODEL_SOURCE: 模型下载源,可以设置为
huggingface
或modelscope
。 - LAZYLLM_MODEL_SOURCE_TOKEN:
huggingface
或modelscope
提供的token,用于下载私有模型。 - LAZYLLM_MODEL_PATH: 冒号
:
分隔的本地绝对路径列表用于搜索模型。 - LAZYLLM_MODEL_CACHE_DIR: 下载后的模型在本地的存储目录
Other Parameters:
-
model_source
((str, 可选)
) –模型下载源,目前仅支持
huggingface
或modelscope
。如有必要,ModelManager将从此下载源下载模型数据。如果不提供,默认使用 LAZYLLM_MODEL_SOURCE环境变量中的设置。如未设置LAZYLLM_MODEL_SOURCE,ModelManager将从modelscope
下载模型。 -
token
((str, 可选)
) –huggingface
或modelscope
提供的token。如果token不为空,ModelManager将使用此token下载模型数据。如果不提供,默认使用 LAZYLLM_MODEL_SOURCE_TOKEN环境变量中的设置。如未设置LAZYLLM_MODEL_SOURCE_TOKEN,ModelManager将不会自动下载私有模型。 -
model_path
(str, 可选):冒号
) –)分隔的本地绝对路径列表。在实际下载模型数据之前,ModelManager将在此列表包含的目录中尝试寻找目标模型。如果不提供,默认使用 LAZYLLM_MODEL_PATH环境变量中的设置。如果为空或LAZYLLM_MODEL_PATH未设置,ModelManager将跳过从model_path中寻找模型的步骤。
-
cache_dir
((str, 可选)
) –一个本地目录的绝对路径。下载后的模型将存放在此目录下,如果不提供,默认使用LAZYLLM_MODEL_CACHE_DIR环境变量中的设置。如果 LAZYLLM_MODEL_PATH未设置,默认值为~/.lazyllm/model
ModelManager.download(model) -> str
用于从model_source下载模型。download函数首先在ModelManager类初始化参数model_path列出的目录中搜索目标模型。如果未找到,会在cache_dir下搜索目标模型。如果仍未找到, 则从model_source上下载模型并存放于cache_dir下。
Parameters:
-
model
(str
) –目标模型名称。download函数使用此名称从model_source上下载模型。为了方便开发者使用,LazyLLM为常用模型建立了简略模型名称到下载源实际模型名称的映射, 例如
Llama-3-8B
,GLM3-6B
或Qwen1.5-7B
。具体可参考文件lazyllm/module/utils/downloader/model_mapping.py
。model可以接受简略模型名或下载源中的模型全名。
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
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 |
|
Formatter
lazyllm.components.formatter.LazyLLMFormatterBase
此类是格式化器的基类,格式化器是模型输出结果的格式化器,用户可以自定义格式化器,也可以使用LazyLLM提供的格式化器。 主要方法:_parse_formatter:解析索引内容。_load:解析str对象,其中包含python对象的部分被解析出来,比如list,dict等对象。_parse_py_data_by_formatter:根据自定义的格式化器和索引对python对象进行格式化。format:对传入的内容进行格式化,如果内容是字符串类型,先将字符串转化为python对象,再进行格式化。如果内容是python对象,直接进行格式化。
Examples:
>>> from lazyllm.components.formatter import FormatterBase
>>> class MyFormatter(FormatterBase):
... 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
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
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 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 |
|
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
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 |
|
MultiModal
Text to Image
lazyllm.components.StableDiffusionDeploy
Bases: object
Stable Diffusion 模型部署类。该类用于将SD模型部署到指定服务器上,以便可以通过网络进行调用。
__init__(self, launcher=None)
构造函数,初始化部署类。
Parameters:
-
launcher(lazyllm.launcher)
–用于启动远程服务的启动器实例。
__call__(self, finetuned_model=None, base_model=None)
部署模型,并返回远程服务地址。
Parameters:
-
finetuned_model
(str
) –如果提供,则使用该模型进行部署;如果未提供或路径无效,则使用
base_model
。 -
base_model
(str
) –默认模型,如果
finetuned_model
无效,则使用该模型进行部署。 -
返回值
(str
) –远程服务的URL地址。
Notes
- 推理的输入:字符串。待生成图像的描述。
- 推理的返回值:从生成的文件路径编码的字符串, 编码标志以 "
"开头,后面跟序列化后的字典, 字典中 files
键存放了一个列表,元素是生成的图像文件路径。 - 支持的模型为:stable-diffusion-3-medium
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/stable_diffusion/stable_diffusion3.py
Visual Question Answering
Reference LMDeploy, which supports the Visual Question Answering model.
Text to Sound
lazyllm.components.TTSDeploy
TTSDeploy 是一个用于根据指定的名称创建不同类型文本到语音(TTS)部署实例的工厂类。
__new__(cls, name, **kwarg)
构造函数,根据提供的名称参数动态创建并返回相应的部署实例。
Returns:
-
–
如果 name 参数为 ‘bark’,则返回一个 BarkDeploy 实例。
-
–
如果 name 参数为 ‘ChatTTS’,则返回一个 ChatTTSDeploy 实例。
-
–
如果 name 参数以 ‘musicgen’ 开头,则返回一个 MusicGenDeploy 实例。
-
–
如果 name 参数不匹配以上任何情况,抛出 RuntimeError 异常,说明不支持的模型。
Examples:
>>> from lazyllm import launchers, UrlModule
>>> from lazyllm.components import TTSDeploy
>>> model_name = 'bark'
>>> deployer = TTSDeploy(model_name, launcher=launchers.remote())
>>> url = deployer(base_model=model_name)
>>> 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/text_to_speech/base.py
lazyllm.components.ChatTTSDeploy
Bases: TTSBase
ChatTTS 模型部署类。该类用于将ChatTTS模型部署到指定服务器上,以便可以通过网络进行调用。
__init__(self, launcher=None)
构造函数,初始化部署类。
Parameters:
-
launcher(lazyllm.launcher)
–用于启动远程服务的启动器实例。
__call__(self, finetuned_model=None, base_model=None)
部署模型,并返回远程服务地址。
Parameters:
-
finetuned_model
(str
) –如果提供,则使用该模型进行部署;如果未提供或路径无效,则使用
base_model
。 -
base_model
(str
) –默认模型,如果
finetuned_model
无效,则使用该模型进行部署。 -
返回值
(str
) –远程服务的URL地址。
Notes
- 推理的输入:字符串。待生成音频的对应文字。
- 推理的返回值:从生成的文件路径编码的字符串, 编码标志以 "
"开头,后面跟序列化后的字典, 字典中 files
键存放了一个列表,元素是生成的音频文件路径。 - 支持的模型为:ChatTTS
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/text_to_speech/chattts.py
lazyllm.components.BarkDeploy
Bases: TTSBase
Bark 模型部署类。该类用于将Bark模型部署到指定服务器上,以便可以通过网络进行调用。
__init__(self, launcher=None)
构造函数,初始化部署类。
Parameters:
-
launcher(lazyllm.launcher)
–用于启动远程服务的启动器实例。
__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/text_to_speech/bark.py
lazyllm.components.MusicGenDeploy
Bases: TTSBase
MusicGen 模型部署类。该类用于将MusicGen模型部署到指定服务器上,以便可以通过网络进行调用。
__init__(self, launcher=None)
构造函数,初始化部署类。
Parameters:
-
launcher(lazyllm.launcher)
–用于启动远程服务的启动器实例。
__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/text_to_speech/musicgen.py
Speech to Text
lazyllm.components.SenseVoiceDeploy
Bases: object
SenseVoice 模型部署类。该类用于将SenseVoice模型部署到指定服务器上,以便可以通过网络进行调用。
__init__(self, launcher=None)
构造函数,初始化部署类。
Parameters:
-
launcher(lazyllm.launcher)
–用于启动远程服务的启动器实例。
__call__(self, finetuned_model=None, base_model=None)
部署模型,并返回远程服务地址。
Parameters:
-
finetuned_model
(str
) –如果提供,则使用该模型进行部署;如果未提供或路径无效,则使用
base_model
。 -
base_model
(str
) –默认模型,如果
finetuned_model
无效,则使用该模型进行部署。 -
返回值
(str
) –远程服务的URL地址。
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