peft README

The project's README from github.com/huggingface/peft. As one markdown file: README.md.

🤗 PEFT

State-of-the-art Parameter-Efficient Fine-Tuning (PEFT) methods

Fine-tuning large pretrained models is often prohibitively costly due to their scale. Parameter-Efficient Fine-Tuning (PEFT) methods enable efficient adaptation of large pretrained models to various downstream applications by only fine-tuning a small number of (extra) model parameters instead of all the model's parameters. This significantly decreases the computational and storage costs. Recent state-of-the-art PEFT techniques achieve performance comparable to fully fine-tuned models.

PEFT is integrated with Transformers for easy model training and inference, Diffusers for conveniently managing different adapters, and Accelerate for distributed training and inference for really big models.

[!TIP] Visit the PEFT organization to read about the PEFT methods implemented in the library and to see notebooks demonstrating how to apply these methods to a variety of downstream tasks. Click the "Watch repos" button on the organization page to be notified of newly implemented methods and notebooks!

Check the PEFT Adapters API Reference section for a list of supported PEFT methods, and read the Adapters, Soft prompts, and IA3 conceptual guides to learn more about how these methods work.

Quickstart

Install PEFT from pip:

pip install peft

Prepare a model for training with a PEFT method such as LoRA by wrapping the base model and PEFT configuration with get_peft_model. For the bigscience/mt0-large model, you're only training 0.19% of the parameters!

import torch
from transformers import AutoModelForCausalLM
from peft import LoraConfig, TaskType, get_peft_model

device = torch.accelerator.current_accelerator().type if hasattr(torch, "accelerator") else "cuda"
model_id = "Qwen/Qwen2.5-3B-Instruct"
model = AutoModelForCausalLM.from_pretrained(model_id, device_map=device)
peft_config = LoraConfig(
    r=16,
    lora_alpha=32,
    task_type=TaskType.CAUSAL_LM,
    # target_modules=["q_proj", "v_proj", ...]  # optionally indicate target modules
)
model = get_peft_model(model, peft_config)
model.print_trainable_parameters()
# prints: trainable params: 3,686,400 || all params: 3,089,625,088 || trainable%: 0.1193

# now perform training on your dataset, e.g. using transformers Trainer, then save the model
model.save_pretrained("qwen2.5-3b-lora")

To load a PEFT model for inference:

import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
from peft import PeftModel

device = torch.accelerator.current_accelerator().type if hasattr(torch, "accelerator") else "cuda"
model_id = "Qwen/Qwen2.5-3B-Instruct"
tokenizer = AutoTokenizer.from_pretrained(model_id)
model = AutoModelForCausalLM.from_pretrained(model_id, device_map=device)
model = PeftModel.from_pretrained(model, "qwen2.5-3b-lora")

inputs = tokenizer("Preheat the oven to 350 degrees and place the cookie dough", return_tensors="pt")
outputs = model.generate(**inputs.to(device), max_new_tokens=50)
print(tokenizer.decode(outputs[0], skip_special_tokens=True))

# prints something like: Preheat the oven to 350 degrees and place the cookie dough in a baking dish [...]

Why you should use PEFT

There are many benefits of using PEFT but the main one is the huge savings in compute and storage, making PEFT applicable to many different use cases.

High performance on consumer hardware

Consider the memory requirements for training the following models on the ought/raft/twitter_complaints dataset with an A100 80GB GPU with more than 64GB of CPU RAM.

Model Full Finetuning PEFT-LoRA PyTorch PEFT-LoRA DeepSpeed with CPU Offloading
bigscience/T0_3B (3B params) 47.14GB GPU / 2.96GB CPU 14.4GB GPU / 2.96GB CPU 9.8GB GPU / 17.8GB CPU
bigscience/mt0-xxl (12B params) OOM GPU 56GB GPU / 3GB CPU 22GB GPU / 52GB CPU
bigscience/bloomz-7b1 (7B params) OOM GPU 32GB GPU / 3.8GB CPU 18.1GB GPU / 35GB CPU

With LoRA you can fully finetune a 12B parameter model that would've otherwise run out of memory on the 80GB GPU, and comfortably fit and train a 3B parameter model. When you look at the 3B parameter model's performance, it is comparable to a fully finetuned model at a fraction of the GPU memory.

Submission Name Accuracy
Human baseline (crowdsourced) 0.897
Flan-T5 0.892
lora-t0-3b 0.863

[!TIP] The bigscience/T0_3B model performance isn't optimized in the table above. You can squeeze even more performance out of it by playing around with the input instruction templates, LoRA hyperparameters, and other training related hyperparameters. The final checkpoint size of this model is just 19MB compared to 11GB of the full bigscience/T0_3B model. Learn more about the advantages of finetuning with PEFT in this blog post.

Quantization

Quantization is another method for reducing the memory requirements of a model by representing the data in a lower precision. It can be combined with PEFT methods to make it even easier to train and load LLMs for inference.

Save compute and storage

PEFT can help you save storage by avoiding full finetuning of models on each of downstream task or dataset. In many cases, you're only finetuning a very small fraction of a model's parameters and each checkpoint is only a few MBs in size (instead of GBs). These smaller PEFT adapters demonstrate performance comparable to a fully finetuned model. If you have many datasets, you can save a lot of storage with a PEFT model and not have to worry about catastrophic forgetting or overfitting the backbone or base model.

PEFT integrations

PEFT is widely supported across the Hugging Face ecosystem because of the massive efficiency it brings to training and inference.

Diffusers

The iterative diffusion process consumes a lot of memory which can make it difficult to train. PEFT can help reduce the memory requirements and reduce the storage size of the final model checkpoint. For example, consider the memory required for training a Stable Diffusion model with LoRA on an A100 80GB GPU with more than 64GB of CPU RAM. The final model checkpoint size is only 8.8MB!

Model Full Finetuning PEFT-LoRA PEFT-LoRA with Gradient Checkpointing
CompVis/stable-diffusion-v1-4 27.5GB GPU / 3.97GB CPU 15.5GB GPU / 3.84GB CPU 8.12GB GPU / 3.77GB CPU

[!TIP] Take a look at the examples/lora_dreambooth/train_dreambooth.py training script to try training your own Stable Diffusion model with LoRA, and play around with the smangrul/peft-lora-sd-dreambooth Space which is running on a T4 instance. Learn more about the PEFT integration in Diffusers in this tutorial.

Transformers

PEFT is directly integrated with Transformers. After loading a model, call add_adapter to add a new PEFT adapter to the model:

from peft import LoraConfig
model = ...  # transformers model
peft_config = LoraConfig(...)
model.add_adapter(peft_config, adapter_name="lora_1")

To load a trained PEFT adapter, call load_adapter:

model = ...  # transformers model
model.load_adapter(<path-to-adapter>, adapter_name="lora_1")

And to switch between different adapters, call set_adapter:

model.set_adapter("lora_2")

The Transformers integration doesn't include all the functionalities offered in PEFT, such as methods for merging the adapter into the base model.

Accelerate

Accelerate is a library for distributed training and inference on various training setups and hardware (GPUs, TPUs, Apple Silicon, etc.). PEFT models work with Accelerate out of the box, making it really convenient to train really large models or use them for inference on consumer hardware with limited resources.

TRL

PEFT can also be applied to training LLMs with RLHF components such as the ranker and policy. Get started by reading:

Model support

Use this Space or check out the docs to find which models officially support a PEFT method out of the box. Even if you don't see a model listed below, you can manually configure the model config to enable PEFT for a model. Read the New transformers architecture guide to learn how.

Contribute

If you would like to contribute to PEFT, please check out our contribution guide.

Citing 🤗 PEFT

To use 🤗 PEFT in your publication, please cite it by using the following BibTeX entry.

@Misc{peft,
  title =        {{PEFT}: State-of-the-art Parameter-Efficient Fine-Tuning methods},
  author =       {Sourab Mangrulkar and Sylvain Gugger and Lysandre Debut and Younes Belkada and Sayak Paul and Benjamin Bossan and Marian Tietz},
  howpublished = {\url{https://github.com/huggingface/peft}},
  year =         {2022}
}

peft (huggingface/peft)

Searching Database…

21.8K ·GitHub
这是什么?这是 Hugging Face 的参数高效微调(Parameter-Efficient Fine-Tuning)方法库:微调大型预训练模型时,你只需训练少量额外参数,而不是全部参数,从而大幅降低算力和存储成本。
它是我在自己代码里用的库,还是一个独立的应用?它是一个 Python 库,在你自己的训练脚本里调用,深度集成在 Hugging Face 生态中:可以配合 Transformers 做模型训练、配合 Diffusers 处理扩散模型、配合 Accelerate 做分布式训练,以及配合 TRL 做 RLHF 风格的训练。
怎么把它加到我的训练代码里?先用 pip 安装,然后用 get_peft_model 把你的基础模型和 PEFT 配置包装起来——官方快速上手示例只用 0.19% 的参数就在 bigscience/mt0-large 上训练了 LoRA。
Transformers 集成包含了 PEFT 的全部功能吗?没有——它只是一个便利层,提供 add_adapter、load_adapter 和 set_adapter,但缺少 PEFT 的一些功能,比如把适配器合并进基础模型的方法。
微调 12B 这样的模型需要多大的 GPU?比全量微调需要的小得多:LoRA 训练 3B 模型只用了 14.4GB 显存,而全量微调要 47.14GB;一个全量微调时会显存溢出的 12B 模型用 56GB 就能训练;QLoRA 方案还能在 16GB 显存的 GPU 上训练 Llama-2-7b。
效果能和全量微调一样好吗?很接近:LoRA 微调后的 T0-3b 在示例基准上准确率为 0.863,Flan-T5 是 0.892,人类基线是 0.897。README 还提到,调整 LoRA 超参数和指令模板可以进一步缩小差距。
保存下来的检查点有多大?只有几 MB,而不是几 GB:3B 模型的 LoRA 检查点是 19MB,而完整模型要 11GB;Stable Diffusion 的 LoRA 检查点更是只有 8.8MB。你可以在不复制基础模型的情况下,保存很多针对不同任务的适配器。
能用在 Stable Diffusion 这类图像模型上吗?可以——通过 Diffusers 集成,Stable Diffusion v1-4 的 LoRA 训练显存占用从 27.5GB 降到 15.5GB(开启梯度检查点后是 8.12GB),仓库里还附带一个 DreamBooth 训练示例脚本。
能用它做 RLHF 或偏好优化吗?可以,通过 TRL 实现:README 里给出了 Mistral-7b 的 DPO 微调、在 24GB 消费级 GPU 上训练 20B 大模型的 RLHF 案例,以及涵盖监督微调、奖励建模和强化学习的 StackLLaMA 指南。
What are similar projects?halo, ms-swift, llm-action, trl, DiffSynth-Studio, ludwig, qlora, Soup
Size
33.1 MB
Stars
21.8K
Age
3y
Commits · 90 Days