Peft库使用技巧(一):合并基座模型与Lora模型【使用Peft库微调基座模型(比如LLaMA-7B)后会得到Lora参数模块,将基座模型与Lora参数合并后才能得到完整的微调后的大模型】

本文介绍了如何使用Peft库对LLaMA-7B等基座模型进行微调,得到Lora参数,并详细阐述了如何将两者合并形成完整的大模型。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

使用Peft库微调基座模型(比如LLaMA-7B)后会得到Lora参数模块,将基座模型与Lora参数合并后才能得到完整的微调后的大模型

#    Copyright 2023 Rohan Taori, Ishaan Gulrajani, Tianyi Zhang, Yann Dubois, Xuechen Li
#
#    Licensed under the Apache License, Version 2.0 (the "License");
#    you may not use this file except in compliance with the License.
#    You may obtain a copy of the License at
#
#        http://www.apache.org/licenses/LICENSE-2.0
#
#    Unless required by applicable law or agreed to in writing, software
#    distributed under the License is distributed on an "AS IS" BASIS,
#    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#    See the License for the specific language governing permissions and
#    limitations under the
### Llama-7B 使用 LoRA 进行微调的方法 低秩适应(Low-Rank Adaptation, LoRA)是种高效的参数高效迁移学习方法,它通过仅更新模型权重矩阵中的低秩分解部分来减少训练所需的计算资源时间。这种方法特别适合大规模预训练模型微调工作。 对于 Llama-7B 模型而言,在实际操作中可以采用如下方式完成基于 LoRA微调: #### 安装依赖 为了支持 LoRA 微调功能,通常需要安装 `transformers` `peft` 。以下是安装命令: ```bash pip install transformers peft accelerate bitsandbytes ``` 这些工具提供了对 Hugging Face Transformers API 的扩展能力以及硬件优化的支持[^1]。 #### 数据准备 准备好用于微调的数据集,并将其转换成适配 Transformer 输入格式的形式。这步可能涉及分词器初始化、文本编码等处理过程[^2]。 #### 配置环境变量 如果计划利用混合精度训练技术进步提高效率,则需设置相应的 CUDA 环境配置项。例如启用 FP16 或 BF16 计算模式以降低显存消耗并加快收敛速度。 #### 编写脚本实现具体逻辑 下面是个简单的 Python 脚本模板展示如何加载基础模型并通过 PEFT 工具箱定义 LoRA 参数化策略来进行后续训练流程的设计: ```python from transformers import AutoTokenizer, AutoModelForCausalLM, BitsAndBytesConfig import torch from peft import get_peft_config, PeftModel, TaskType, LoraConfig, prepare_model_for_int8_training model_name_or_path = "meta-llama/Llama-7b" tokenizer_name_or_path = "meta-llama/Llama-7b" bnb_config = BitsAndBytesConfig( load_in_4bit=True, bnb_4bit_quant_type="nf4", bnb_4bit_compute_dtype=torch.bfloat16 ) tokenizer = AutoTokenizer.from_pretrained(tokenizer_name_or_path) model = AutoModelForCausalLM.from_pretrained(model_name_or_path, quantization_config=bnb_config, device_map={"":0}) peft_config = LoraConfig(task_type=TaskType.CAUSAL_LM, inference_mode=False, r=8, lora_alpha=32, lora_dropout=0.1) # Prepare the model for int8 training. model = prepare_model_for_int8_training(model) # Add LoRA adapters to the model. model = PeftModel.from_pretrained(model, "./path_to_lora_weights", config=peft_config) def print_trainable_parameters(model): """ Prints the number of trainable parameters in the model. """ trainable_params = 0 all_param = 0 for _, param in model.named_parameters(): num_params = param.numel() if num_params == 0 and hasattr(param, "ds_numel"): num_params = param.ds_numel all_param += num_params if param.requires_grad: trainable_params += num_params print(f"trainable params: {trainable_params} || all params: {all_param} || trainable%: {100 * trainable_params / all_param}") print_trainable_parameters(model) output_dir = "./results" training_arguments = TrainingArguments(output_dir=output_dir, ... ) trainer = Trainer( model=model, args=training_arguments, train_dataset=train_dataset, eval_dataset=val_dataset, tokenizer=tokenizer, data_collator=data_collator, ) model.config.use_cache = False # silence the warnings. Please re-enable for inference! trainer.train() model.save_pretrained("./lora-finetuned-model") ``` 上述代码片段展示了完整的端到端解决方案,涵盖了从加载原始大语言模型实例直到保存最终经过调整后的版本整个链条上各个重要环节的操作细节说明^。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值