LLM、AIGC、RAG 開發交流裙:377891973
文章目錄
- 一、關于 PEFT
- 二、安裝
- 1、使用 PyPI 安裝
- 2、使用源碼安裝
- 三、快速開始
- 1、訓練
- 2、保存模型
- 3、推理
- 4、后續步驟
本文翻譯整理自:https://huggingface.co/docs/peft/index
一、關于 PEFT
🤗PEFT(Parameter-Efficient Fine-Tuning 參數高效微調)是一個庫,用于有效地將大型預訓練模型適應各種目標端應用,而無需微調模型的所有參數,因為它成本過高。
PEFT方法僅微調少量(額外)模型參數——顯著降低計算和存儲成本——同時產生與完全微調模型相當的性能。
這使得在消費硬件上訓練和存儲大型語言模型(LLM)更容易。
PEFT與Transformer、擴散器和加速庫集成,提供了一種更快、更簡單的方法來加載、訓練和使用大型模型進行推理。
二、安裝
PEFT 在 Python3.8+ 上經過測試。
🤗PEFT可從PyPI和GitHub上獲得:
1、使用 PyPI 安裝
要從PyPI安裝🤗PEFT:
pip install peft
2、使用源碼安裝
每天都會添加尚未發布的新功能,這也意味著可能存在一些錯誤。
要試用它們,請從GitHub存儲庫安裝:
pip install git+https://github.com/huggingface/peft
如果您正在努力為庫做出貢獻,或者希望使用源碼并觀看直播 結果當您運行代碼時,可以從本地克隆的版本安裝可編輯的版本 存儲庫:
git clone https://github.com/huggingface/peft
cd peft
pip install -e .
三、快速開始
https://huggingface.co/docs/peft/quicktour
PEFT提供了參數有效的方法 來微調大型預訓練模型。
傳統的范式是為每個下游任務微調模型的所有參數,但是由于當今模型中的參數數量巨大,這變得非常昂貴和不切實際。
相反,訓練更少數量的提示參數 或 使用低秩自適應(LoRA)等重新參數化方法 來減少可訓練參數的數量會更有效。
本快速導覽將向您展示PEFT的主要功能,以及如何在消費設備上通常無法訪問的大型模型上訓練或運行推理。
1、訓練
每個PEFT方法都由一個PeftConfig類定義,該類存儲了構建PeftModel的所有重要參數。
例如,要使用LoRA進行訓練,請加載并創建一個LoraConfig類并指定以下參數:
task_type
:要訓練的任務(在這種情況下sequence-to-sequence語言模型化)inference_mode
無論你是否使用模型進行推理r
:低秩矩陣的維度lora_alpha
:低秩矩陣的縮放因子lora_dropout
:LoRA層的暫退法概率
from peft import LoraConfig, TaskTypepeft_config = LoraConfig(task_type=TaskType.SEQ_2_SEQ_LM, inference_mode=False, r=8, lora_alpha=32, lora_dropout=0.1)
請參閱LoraConfig參考,了解有關您可以調整的其他參數的更多詳細信息,例如要定位的模塊或偏置類型。
設置LoraConfig后,使用get_peft_model()函數創建一個PeftModel。
它需要一個基本模型 —— 您可以從Transformer庫中加載,LoraConfig 包含 如何配置模型 以使用LoRA進行訓練的參數。
加載要微調的基本模型。
from transformers import AutoModelForSeq2SeqLMmodel = AutoModelForSeq2SeqLM.from_pretrained("bigscience/mt0-large")
使用get_peft_model() 函數包裝基本模型和 peft_config
以創建PeftModel。
要了解模型中可訓練參數的數量,請使用print_trainable_parameters
方法。
from peft import get_peft_modelmodel = get_peft_model(model, peft_config)
model.print_trainable_parameters()
"output: trainable params: 2359296 || all params: 1231940608 || trainable%: 0.19151053100118282"
在 bigscience/mt0-large’s 1.2B 參數中,您只訓練了其中的 0.19%!
就是這樣🎉!
現在你可以用 Transformer Trainer、Accelerate 或任何自定義PyTorch 訓練循環來訓練模型。
例如,要使用Trainer類進行訓練,請使用一些訓練超參數設置一個TrainingArguments類。
training_args = TrainingArguments(output_dir="your-name/bigscience/mt0-large-lora",learning_rate=1e-3,per_device_train_batch_size=32,per_device_eval_batch_size=32,num_train_epochs=2,weight_decay=0.01,evaluation_strategy="epoch",save_strategy="epoch",load_best_model_at_end=True,
)
將模型、訓練參數、數據集、標記器和任何其他必要的組件 傳遞給Trainer,并調用 train 開始訓練。
trainer = Trainer(model=model,args=training_args,train_dataset=tokenized_datasets["train"],eval_dataset=tokenized_datasets["test"],tokenizer=tokenizer,data_collator=data_collator,compute_metrics=compute_metrics,
)trainer.train()
2、保存模型
模型完成訓練后,可以使用save_pretrained函數將模型保存到目錄中。
model.save_pretrained("output_dir")
您還可以使用push_to_hub函數將模型保存到 Hub (確保您已登錄到您的擁抱臉帳戶)。
from huggingface_hub import notebook_loginnotebook_login()
model.push_to_hub("your-name/bigscience/mt0-large-lora")
這兩種方法都只保存經過訓練的額外PEFT權重,這意味著存儲、傳輸和加載效率極高。
例如,這個用LoRA訓練的facebook/opt-350m模型只包含兩個文件:adapter_config.json
和adapter_model.safetensors
。
adapter_model.safetensors
文件只有6.3MB!
存儲在 Hub 上的350m模型的適配器權重只有約6MB,而模型權重的完整大小可以約700MB。
3、推理
查看AutoPeftModelAPI參考以獲取可用AutoPeftModel
類的完整列表。
使用AutoPeftModel類和from_pretrained方法輕松加載任何經過PEFT訓練的推理模型:
from peft import AutoPeftModelForCausalLM
from transformers import AutoTokenizer
import torchmodel = AutoPeftModelForCausalLM.from_pretrained("ybelkada/opt-350m-lora")
tokenizer = AutoTokenizer.from_pretrained("facebook/opt-350m")model = model.to("cuda")
model.eval()
inputs = tokenizer("Preheat the oven to 350 degrees and place the cookie dough", return_tensors="pt")outputs = model.generate(input_ids=inputs["input_ids"].to("cuda"), max_new_tokens=50)
print(tokenizer.batch_decode(outputs.detach().cpu().numpy(), skip_special_tokens=True)[0])"Preheat the oven to 350 degrees and place the cookie dough in the center of the oven. In a large bowl, combine the flour, baking powder, baking soda, salt, and cinnamon. In a separate bowl, combine the egg yolks, sugar, and vanilla."
對于AutoPeftModelFor
類未明確支持的其他任務(例如自動語音識別),您仍然可以使用基礎 AutoPeftModel類來加載任務的模型。
from peft import AutoPeftModelmodel = AutoPeftModel.from_pretrained("smangrul/openai-whisper-large-v2-LORA-colab")
4、后續步驟
現在您已經了解了如何使用其中一種PEFT方法訓練模型,我們鼓勵您嘗試一些其他方法,例如 prompt tuning。
這些步驟與快速導覽中顯示的步驟非常相似:
- 準備一個PeftConfig用于PEFT方法
- 使用get_peft_model()方法從配置和基本模型創建PeftModel
然后你可以隨心所欲地訓練它!要加載PEFT模型進行推理,可以使用AutoPeftModel類。
如果您有興趣為特定任務(如語義分割、多語言自動語音識別、DreamBooth、代幣分類等)使用另一種PEFT方法訓練模型,請隨意查看任務指南。
伊織 2024-07-05