# collections

id: 723c70ce-cf85-47df-965e-e8b9401a5390
name: chroma-db-peft
database_id: 00000000-0000-0000-0000-000000000000
config_json_str:
{"hnsw_configuration": {"space": "l2", "ef_construction": 100, "ef_search": 10, "num_threads": 8, "M": 16, "resize_factor": 1.2, "batch_size": 100, "sync_threshold": 1000, "_type": "HNSWConfigurationInternal"}, "_type": "CollectionConfigurationInternal"}


# embedding_metadata

key: _node_content
string_value:
{"id_": "40b25b89-3219-463e-a622-53fea5fa47d9", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/peft/quicktour", "title": "Quicktour", "tokens": 1893, "retrieve_doc": true, "source": "peft"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "daf19ac8-41e3-43aa-ab50-1909d8ebcba9", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/peft/quicktour", "title": "Quicktour", "tokens": 1893, "retrieve_doc": true, "source": "peft"}, "hash": "d0903411981d954f5a738ac0d7c3c18955243168c7170ebdd7501154bbb76131", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "b46489a6-5c91-4305-a5a9-3552800cfb5d", "node_type": "1", "metadata": {}, "hash": "52465a1ba212d545de70a78329bcec45d4e223d1556da7c2f0e4dad53f512370", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 0, "end_char_idx": 2873, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
# Quicktour

PEFT offers parameter-efficient methods for finetuning large pretrained models. The traditional paradigm is to finetune all of a model's parameters for each downstream task, but this is becoming exceedingly costly and impractical because of the enormous number of parameters in models today. Instead, it is more efficient to train a smaller number of prompt parameters or use a reparametrization method like low-rank adaptation (LoRA) to reduce the number of trainable parameters.

This quicktour will show you PEFT's main features and how you can train or run inference on large models that would typically be inaccessible on consumer devices.

## Train

Each PEFT method is defined by a [`PeftConfig`] class that stores all the important parameters for building a [`PeftModel`]. For example, to train with LoRA, load and create a [`LoraConfig`] class and specify the following parameters:

- `task_type`: the task to train for (sequence-to-sequence language modeling in this case)
- `inference_mode`: whether you're using the model for inference or not
- `r`: the dimension of the low-rank matrices
- `lora_alpha`: the scaling factor for the low-rank matrices
- `lora_dropout`: the dropout probability of the LoRA layers

```python
from peft import LoraConfig, TaskType

peft_config = LoraConfig(task_type=TaskType.SEQ_2_SEQ_LM, inference_mode=False, r=8, lora_alpha=32, lora_dropout=0.1)
```

<Tip>

See the [`LoraConfig`] reference for more details about other parameters you can adjust, such as the modules to target or the bias type.

</Tip>

Once the [`LoraConfig`] is setup, create a [`PeftModel`] with the [`get_peft_model`] function. It takes a base model - which you can load from the Transformers library - and the [`LoraConfig`] containing the parameters for how to configure a model for training with LoRA.

Load the base model you want to finetune.

```python
from transformers import AutoModelForSeq2SeqLM

model = AutoModelForSeq2SeqLM.from_pretrained("bigscience/mt0-large")
```

Wrap the base model and `peft_config` with the [`get_peft_model`] function to create a [`PeftModel`]. To get a sense of the number of trainable parameters in your model, use the [`print_trainable_parameters`] method.

```python
from peft import get_peft_model

model = get_peft_model(model, peft_config)
model.print_trainable_parameters()
"output: trainable params: 2359296 || all params: 1231940608 || trainable%: 0.19151053100118282"
```

Out of [bigscience/mt0-large's](https://huggingface.co/bigscience/mt0-large) 1.2B parameters, you're only training 0.19% of them!

That is it 🎉! Now you can train the model with the Transformers [`~transformers.Trainer`], Accelerate, or any custom PyTorch training loop.

For example, to train with the [`~transformers.Trainer`] class, setup a [`~transformers.TrainingArguments`] class with some training hyperparameters.


key: _node_content
string_value:
{"id_": "b46489a6-5c91-4305-a5a9-3552800cfb5d", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/peft/quicktour", "title": "Quicktour", "tokens": 1893, "retrieve_doc": true, "source": "peft"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "daf19ac8-41e3-43aa-ab50-1909d8ebcba9", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/peft/quicktour", "title": "Quicktour", "tokens": 1893, "retrieve_doc": true, "source": "peft"}, "hash": "d0903411981d954f5a738ac0d7c3c18955243168c7170ebdd7501154bbb76131", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "40b25b89-3219-463e-a622-53fea5fa47d9", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/peft/quicktour", "title": "Quicktour", "tokens": 1893, "retrieve_doc": true, "source": "peft"}, "hash": "6929cf04ae57218447b5dd4f0ea8ac458ab74880d41eef190c5ff1fcdb5023fc", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "020fddcb-db8e-4113-9673-612a491b1fdf", "node_type": "1", "metadata": {}, "hash": "f3e629583225ef8ce5afc48558446a515bfc2495a614ca6951c5ea0c0181fe45", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 1554, "end_char_idx": 4554, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
</Tip>

Once the [`LoraConfig`] is setup, create a [`PeftModel`] with the [`get_peft_model`] function. It takes a base model - which you can load from the Transformers library - and the [`LoraConfig`] containing the parameters for how to configure a model for training with LoRA.

Load the base model you want to finetune.

```python
from transformers import AutoModelForSeq2SeqLM

model = AutoModelForSeq2SeqLM.from_pretrained("bigscience/mt0-large")
```

Wrap the base model and `peft_config` with the [`get_peft_model`] function to create a [`PeftModel`]. To get a sense of the number of trainable parameters in your model, use the [`print_trainable_parameters`] method.

```python
from peft import get_peft_model

model = get_peft_model(model, peft_config)
model.print_trainable_parameters()
"output: trainable params: 2359296 || all params: 1231940608 || trainable%: 0.19151053100118282"
```

Out of [bigscience/mt0-large's](https://huggingface.co/bigscience/mt0-large) 1.2B parameters, you're only training 0.19% of them!

That is it 🎉! Now you can train the model with the Transformers [`~transformers.Trainer`], Accelerate, or any custom PyTorch training loop.

For example, to train with the [`~transformers.Trainer`] class, setup a [`~transformers.TrainingArguments`] class with some training hyperparameters.

```py
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,
)
```

Pass the model, training arguments, dataset, tokenizer, and any other necessary component to the [`~transformers.Trainer`], and call [`~transformers.Trainer.train`] to start training.

```py
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()
```

### Save model

After your model is finished training, you can save your model to a directory using the [`~transformers.PreTrainedModel.save_pretrained`] function.

```py
model.save_pretrained("output_dir")
```

You can also save your model to the Hub (make sure you're logged in to your Hugging Face account first) with the [`~transformers.PreTrainedModel.push_to_hub`] function.

```python
from huggingface_hub import notebook_login

notebook_login()
model.push_to_hub("your-name/bigscience/mt0-large-lora")
```

Both methods only save the extra PEFT weights that were trained, meaning it is super efficient to store, transfer, and load. For example, this [facebook/opt-350m](https://huggingface.co/ybelkada/opt-350m-lora) model trained with LoRA only contains two files: `adapter_config.json` and `adapter_model.safetensors`. The `adapter_model.safetensors` file is just 6.3MB!


key: _node_content
string_value:
{"id_": "020fddcb-db8e-4113-9673-612a491b1fdf", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/peft/quicktour", "title": "Quicktour", "tokens": 1893, "retrieve_doc": true, "source": "peft"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "daf19ac8-41e3-43aa-ab50-1909d8ebcba9", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/peft/quicktour", "title": "Quicktour", "tokens": 1893, "retrieve_doc": true, "source": "peft"}, "hash": "d0903411981d954f5a738ac0d7c3c18955243168c7170ebdd7501154bbb76131", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "b46489a6-5c91-4305-a5a9-3552800cfb5d", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/peft/quicktour", "title": "Quicktour", "tokens": 1893, "retrieve_doc": true, "source": "peft"}, "hash": "a9cb96c38fcef8cc734c65239bfde6284c0b9d2c7a1cbbd364f113bd0fbf878e", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "cbf9769f-3223-462b-83ad-ac0498ed2c11", "node_type": "1", "metadata": {}, "hash": "572d7321cc13ce3ef0bab8c3c29bf6d84a7ca695893a1ca506cafcef437ad491", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 3397, "end_char_idx": 6526, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
```py
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()
```

### Save model

After your model is finished training, you can save your model to a directory using the [`~transformers.PreTrainedModel.save_pretrained`] function.

```py
model.save_pretrained("output_dir")
```

You can also save your model to the Hub (make sure you're logged in to your Hugging Face account first) with the [`~transformers.PreTrainedModel.push_to_hub`] function.

```python
from huggingface_hub import notebook_login

notebook_login()
model.push_to_hub("your-name/bigscience/mt0-large-lora")
```

Both methods only save the extra PEFT weights that were trained, meaning it is super efficient to store, transfer, and load. For example, this [facebook/opt-350m](https://huggingface.co/ybelkada/opt-350m-lora) model trained with LoRA only contains two files: `adapter_config.json` and `adapter_model.safetensors`. The `adapter_model.safetensors` file is just 6.3MB!

<div class="flex flex-col justify-center">
  <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/peft/PEFT-hub-screenshot.png"/>
  <figcaption class="text-center">The adapter weights for a opt-350m model stored on the Hub are only ~6MB compared to the full size of the model weights, which can be ~700MB.</figcaption>
</div>

## Inference

<Tip>

Take a look at the [AutoPeftModel](package_reference/auto_class) API reference for a complete list of available `AutoPeftModel` classes.

</Tip>

Easily load any PEFT-trained model for inference with the [`AutoPeftModel`] class and the [`~transformers.PreTrainedModel.from_pretrained`] method:

```py
from peft import AutoPeftModelForCausalLM
from transformers import AutoTokenizer
import torch

model = 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."
```

For other tasks that aren't explicitly supported with an `AutoPeftModelFor` class - such as automatic speech recognition - you can still use the base [`AutoPeftModel`] class to load a model for the task.

```py
from peft import AutoPeftModel

model = AutoPeftModel.from_pretrained("smangrul/openai-whisper-large-v2-LORA-colab")
```

## Next steps

Now that you've seen how to train a model with one of the PEFT methods, we encourage you to try out some of the other methods like prompt tuning.


key: _node_content
string_value:
{"id_": "cbf9769f-3223-462b-83ad-ac0498ed2c11", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/peft/quicktour", "title": "Quicktour", "tokens": 1893, "retrieve_doc": true, "source": "peft"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "daf19ac8-41e3-43aa-ab50-1909d8ebcba9", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/peft/quicktour", "title": "Quicktour", "tokens": 1893, "retrieve_doc": true, "source": "peft"}, "hash": "d0903411981d954f5a738ac0d7c3c18955243168c7170ebdd7501154bbb76131", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "020fddcb-db8e-4113-9673-612a491b1fdf", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/peft/quicktour", "title": "Quicktour", "tokens": 1893, "retrieve_doc": true, "source": "peft"}, "hash": "75c40fd9e2011fae6717e67539ad766dc18e4c28aa802b99560d5fa4b142eb58", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 5077, "end_char_idx": 7109, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
</Tip>

Easily load any PEFT-trained model for inference with the [`AutoPeftModel`] class and the [`~transformers.PreTrainedModel.from_pretrained`] method:

```py
from peft import AutoPeftModelForCausalLM
from transformers import AutoTokenizer
import torch

model = 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."
```

For other tasks that aren't explicitly supported with an `AutoPeftModelFor` class - such as automatic speech recognition - you can still use the base [`AutoPeftModel`] class to load a model for the task.

```py
from peft import AutoPeftModel

model = AutoPeftModel.from_pretrained("smangrul/openai-whisper-large-v2-LORA-colab")
```

## Next steps

Now that you've seen how to train a model with one of the PEFT methods, we encourage you to try out some of the other methods like prompt tuning. The steps are very similar to the ones shown in the quicktour:

1. prepare a [`PeftConfig`] for a PEFT method
2. use the [`get_peft_model`] method to create a [`PeftModel`] from the configuration and base model

Then you can train it however you like! To load a PEFT model for inference, you can use the [`AutoPeftModel`] class.

Feel free to also take a look at the task guides if you're interested in training a model with another PEFT method for a specific task such as semantic segmentation, multilingual automatic speech recognition, DreamBooth, token classification, and more.


key: _node_content
string_value:
{"id_": "3eb9046f-e67d-4fb6-95c9-f18f6ada71f4", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/peft/install", "title": "Installation", "tokens": 376, "retrieve_doc": true, "source": "peft"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "03f15d50-d92f-477d-841f-b44151184594", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/peft/install", "title": "Installation", "tokens": 376, "retrieve_doc": true, "source": "peft"}, "hash": "e572d410e2768b9554d546daf644a4667f654d04a41e796cb484d6bc3de05ad4", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 0, "end_char_idx": 822, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
# Installation

Before you start, you will need to setup your environment, install the appropriate packages, and configure 🤗 PEFT. 🤗 PEFT is tested on **Python 3.8+**.

🤗 PEFT is available on PyPI, as well as GitHub:

## PyPI

To install 🤗 PEFT from PyPI:

```bash
pip install peft
```

## Source

New features that haven't been released yet are added every day, which also means there may be some bugs. To try them out, install from the GitHub repository:

```bash
pip install git+https://github.com/huggingface/peft
```

If you're working on contributing to the library or wish to play with the source code and see live 
results as you run the code, an editable version can be installed from a locally-cloned version of the 
repository:

```bash
git clone https://github.com/huggingface/peft
cd peft
pip install -e .
```


key: _node_content
string_value:
{"id_": "067afd6b-0046-4212-8f56-9b7a7cf3fd44", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/peft/index", "title": "PEFT", "tokens": 907, "retrieve_doc": true, "source": "peft"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "2032e4cf-d000-426e-a1ef-fdc11966cf04", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/peft/index", "title": "PEFT", "tokens": 907, "retrieve_doc": true, "source": "peft"}, "hash": "15571d4d15958305baaf78e90f114a6be4086568c6dff4f01acd15b535e55179", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 0, "end_char_idx": 2971, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
# PEFT

🤗 PEFT (Parameter-Efficient Fine-Tuning) is a library for efficiently adapting large pretrained models to various downstream applications without fine-tuning all of a model's parameters because it is prohibitively costly. PEFT methods only fine-tune a small number of (extra) model parameters - significantly decreasing computational and storage costs - while yielding performance comparable to a fully fine-tuned model. This makes it more accessible to train and store large language models (LLMs) on consumer hardware.

PEFT is integrated with the Transformers, Diffusers, and Accelerate libraries to provide a faster and easier way to load, train, and use large models for inference.

<div class="mt-10">
  <div class="w-full flex flex-col space-y-4 md:space-y-0 md:grid md:grid-cols-2 md:gap-y-4 md:gap-x-5">
    <a class="!no-underline border dark:border-gray-700 p-5 rounded-lg shadow hover:shadow-lg" href="quicktour"
      ><div class="w-full text-center bg-gradient-to-br from-blue-400 to-blue-500 rounded-lg py-1.5 font-semibold mb-5 text-white text-lg leading-relaxed">Get started</div>
      <p class="text-gray-700">Start here if you're new to 🤗 PEFT to get an overview of the library's main features, and how to train a model with a PEFT method.</p>
    </a>
    <a class="!no-underline border dark:border-gray-700 p-5 rounded-lg shadow hover:shadow-lg" href="./task_guides/image_classification_lora"
      ><div class="w-full text-center bg-gradient-to-br from-indigo-400 to-indigo-500 rounded-lg py-1.5 font-semibold mb-5 text-white text-lg leading-relaxed">How-to guides</div>
      <p class="text-gray-700">Practical guides demonstrating how to apply various PEFT methods across different types of tasks like image classification, causal language modeling, automatic speech recognition, and more. Learn how to use 🤗 PEFT with the DeepSpeed and Fully Sharded Data Parallel scripts.</p>
    </a>
    <a class="!no-underline border dark:border-gray-700 p-5 rounded-lg shadow hover:shadow-lg" href="./conceptual_guides/lora"
      ><div class="w-full text-center bg-gradient-to-br from-pink-400 to-pink-500 rounded-lg py-1.5 font-semibold mb-5 text-white text-lg leading-relaxed">Conceptual guides</div>
      <p class="text-gray-700">Get a better theoretical understanding of how LoRA and various soft prompting methods help reduce the number of trainable parameters to make training more efficient.</p>
   </a>
    <a class="!no-underline border dark:border-gray-700 p-5 rounded-lg shadow hover:shadow-lg" href="./package_reference/config"
      ><div class="w-full text-center bg-gradient-to-br from-purple-400 to-purple-500 rounded-lg py-1.5 font-semibold mb-5 text-white text-lg leading-relaxed">Reference</div>
      <p class="text-gray-700">Technical descriptions of how 🤗 PEFT classes and methods work.</p>
    </a>
  </div>
</div>

<iframe
	src="https://stevhliu-peft-methods.hf.space"
	frameborder="0"
	width="850"
	height="620"
></iframe>


key: _node_content
string_value:
{"id_": "e4448ce3-0ad4-42ab-89fe-9741e3675c4d", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/peft/conceptual_guides/ia3", "title": "IA3", "tokens": 903, "retrieve_doc": true, "source": "peft"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "2acfd969-0b16-41c4-993e-8e66e042bb2a", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/peft/conceptual_guides/ia3", "title": "IA3", "tokens": 903, "retrieve_doc": true, "source": "peft"}, "hash": "3367fb90ef387daaa9d3d21b5b1a813e22e5ac363b219faf6ab1dae58ad01ab3", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 0, "end_char_idx": 3375, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
# IA3 

This conceptual guide gives a brief overview of [IA3](https://arxiv.org/abs/2205.05638), a parameter-efficient fine tuning technique that is 
intended to improve over [LoRA](./lora).

To make fine-tuning more efficient, IA3 (Infused Adapter by Inhibiting and Amplifying Inner Activations) 
rescales inner activations with learned vectors. These learned vectors are injected in the attention and feedforward modules 
in a typical transformer-based architecture. These learned vectors are the only trainable parameters during fine-tuning, and thus the original 
weights remain frozen. Dealing with learned vectors (as opposed to learned low-rank updates to a weight matrix like LoRA)
keeps the number of trainable parameters much smaller. 

Being similar to LoRA, IA3 carries many of the same advantages: 

* IA3 makes fine-tuning more efficient by drastically reducing the number of trainable parameters. (For T0, an IA3 model only has about 0.01% trainable parameters, while even LoRA has > 0.1%)
* The original pre-trained weights are kept frozen, which means you can have multiple lightweight and portable IA3 models for various downstream tasks built on top of them.
* Performance of models fine-tuned using IA3 is comparable to the performance of fully fine-tuned models.
* IA3 does not add any inference latency because adapter weights can be merged with the base model.

In principle, IA3 can be applied to any subset of weight matrices in a neural network to reduce the number of trainable
parameters. Following the authors' implementation, IA3 weights are added to the key, value and feedforward layers
of a Transformer model. To be specific, for transformer models, IA3 weights are added to the outputs of key and value layers, and to the input of the second feedforward layer
in each transformer block.

Given the target layers for injecting IA3 parameters, the number of trainable parameters
can be determined based on the size of the weight matrices.


## Common IA3 parameters in PEFT

As with other methods supported by PEFT, to fine-tune a model using IA3, you need to:

1. Instantiate a base model.
2. Create a configuration (`IA3Config`) where you define IA3-specific parameters.
3. Wrap the base model with `get_peft_model()` to get a trainable `PeftModel`.
4. Train the `PeftModel` as you normally would train the base model.

`IA3Config` allows you to control how IA3 is applied to the base model through the following parameters:

- `target_modules`: The modules (for example, attention blocks) to apply the IA3 vectors.
- `feedforward_modules`: The list of modules to be treated as feedforward layers in `target_modules`. While learned vectors are multiplied with
the output activation for attention blocks, the vectors are multiplied with the input for classic feedforward layers. Note that `feedforward_modules` must be a subset of `target_modules`.
- `modules_to_save`: List of modules apart from IA3 layers to be set as trainable and saved in the final checkpoint. These typically include model's custom head that is randomly initialized for the fine-tuning task.

## Example Usage

For the task of sequence classification, one can initialize the IA3 config for a Llama model as follows:

```py
peft_config = IA3Config(
    task_type=TaskType.SEQ_CLS, target_modules=["k_proj", "v_proj", "down_proj"], feedforward_modules=["down_proj"]
)
```


key: _node_content
string_value:
{"id_": "5c85b40e-7e5e-42a5-9e18-df00f8ba1d21", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/peft/conceptual_guides/oft", "title": "Orthogonal Finetuning (OFT and BOFT)", "tokens": 1680, "retrieve_doc": true, "source": "peft"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "cea0ca4f-6ba5-4b55-911a-e3234292ff2f", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/peft/conceptual_guides/oft", "title": "Orthogonal Finetuning (OFT and BOFT)", "tokens": 1680, "retrieve_doc": true, "source": "peft"}, "hash": "422d6931e7d2f25de7bdf990eedef1ceb167fe303adaf96752e07e0437556830", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "5e4f9d68-2594-4de0-a88f-64bfc2a1a53e", "node_type": "1", "metadata": {}, "hash": "5675374c1cdb06f2c59bab06616532dc5d719a97851579582605be3407d94740", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 0, "end_char_idx": 3547, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
# Orthogonal Finetuning (OFT and BOFT) 

This conceptual guide gives a brief overview of [OFT](https://arxiv.org/abs/2306.07280) and [BOFT](https://arxiv.org/abs/2311.06243), a parameter-efficient fine-tuning technique that utilizes orthogonal matrix to multiplicatively transform the pretrained weight matrices.

To achieve efficient fine-tuning, OFT represents the weight updates with an orthogonal transformation. The orthogonal transformation is parameterized by an orthogonal matrix multiplied to the pretrained weight matrix. These new matrices can be trained to adapt to the new data while keeping the overall number of changes low. The original weight matrix remains frozen and doesn’t receive any further adjustments. To produce the final results, both the original and the adapted weights are multiplied togethor.

Orthogonal Butterfly (BOFT) generalizes OFT with Butterfly factorization and further improves its parameter efficiency and finetuning flexibility. In short, OFT can be viewed as a special case of BOFT. Different from LoRA that uses additive low-rank weight updates, BOFT uses multiplicative orthogonal weight updates. The comparison is shown below.

<div class="flex justify-center">
    <img src="https://raw.githubusercontent.com/wy1iu/butterfly-oft/main/assets/BOFT_comparison.png"/>
</div>


BOFT has some advantages compared to LoRA: 

* BOFT proposes a simple yet generic way to finetune pretrained models to downstream tasks, yielding a better preservation of pretraining knowledge and a better parameter efficiency.
* Through the orthogonality, BOFT introduces a structural constraint, i.e., keeping the [hyperspherical energy](https://arxiv.org/abs/1805.09298) unchanged during finetuning. This can effectively reduce the forgetting of pretraining knowledge.
* BOFT uses the butterfly factorization to efficiently parameterize the orthogonal matrix, which yields a compact yet expressive learning space (i.e., hypothesis class).
* The sparse matrix decomposition in BOFT brings in additional inductive biases that are beneficial to generalization.

In principle, BOFT can be applied to any subset of weight matrices in a neural network to reduce the number of trainable parameters. Given the target layers for injecting BOFT parameters, the number of trainable parameters can be determined based on the size of the weight matrices.

## Merge OFT/BOFT weights into the base model

Similar to LoRA, the weights learned by OFT/BOFT can be integrated into the pretrained weight matrices using the merge_and_unload() function. This function merges the adapter weights with the base model which allows you to effectively use the newly merged model as a standalone model.

<div class="flex justify-center">
    <img src="https://raw.githubusercontent.com/wy1iu/butterfly-oft/main/assets/boft_merge.png"/>
</div>

This works because during training, the orthogonal weight matrix (R in the diagram above) and the pretrained weight matrices are separate. But once training is complete, these weights can actually be merged (multiplied) into a new weight matrix that is equivalent.

## Utils for OFT / BOFT

### Common OFT / BOFT parameters in PEFT

As with other methods supported by PEFT, to fine-tune a model using OFT or BOFT, you need to:

1. Instantiate a base model.
2. Create a configuration (`OFTConfig` or `BOFTConfig`) where you define OFT/BOFT-specific parameters.
3. Wrap the base model with `get_peft_model()` to get a trainable `PeftModel`.
4. Train the `PeftModel` as you normally would train the base model.


key: _node_content
string_value:
{"id_": "5e4f9d68-2594-4de0-a88f-64bfc2a1a53e", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/peft/conceptual_guides/oft", "title": "Orthogonal Finetuning (OFT and BOFT)", "tokens": 1680, "retrieve_doc": true, "source": "peft"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "cea0ca4f-6ba5-4b55-911a-e3234292ff2f", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/peft/conceptual_guides/oft", "title": "Orthogonal Finetuning (OFT and BOFT)", "tokens": 1680, "retrieve_doc": true, "source": "peft"}, "hash": "422d6931e7d2f25de7bdf990eedef1ceb167fe303adaf96752e07e0437556830", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "5c85b40e-7e5e-42a5-9e18-df00f8ba1d21", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/peft/conceptual_guides/oft", "title": "Orthogonal Finetuning (OFT and BOFT)", "tokens": 1680, "retrieve_doc": true, "source": "peft"}, "hash": "41cdedaf263ae4a0e3eb51a426a854d3c7c4f881b4348841e08ffc11d04a157f", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 3550, "end_char_idx": 6498, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
### BOFT-specific paramters

`BOFTConfig` allows you to control how OFT/BOFT is applied to the base model through the following parameters:

- `boft_block_size`: the BOFT matrix block size across different layers, expressed in `int`. Smaller block size results in sparser update matrices with fewer trainable paramters. **Note**, please choose `boft_block_size` to be divisible by most layer's input dimension (`in_features`), e.g., 4, 8, 16. Also, please only 
specify either `boft_block_size` or `boft_block_num`, but not both simultaneously or leaving both to 0, because `boft_block_size` x `boft_block_num` must equal the layer's input dimension.
- `boft_block_num`: the number of BOFT matrix blocks across different layers, expressed in `int`. Fewer blocks result in sparser update matrices with fewer trainable paramters. **Note**, please choose `boft_block_num` to be divisible by most layer's input dimension (`in_features`), e.g., 4, 8, 16. Also, please only 
specify either `boft_block_size` or `boft_block_num`, but not both simultaneously or leaving both to 0, because `boft_block_size` x `boft_block_num` must equal the layer's input dimension.
- `boft_n_butterfly_factor`: the number of butterfly factors. **Note**, for `boft_n_butterfly_factor=1`, BOFT is the same as vanilla OFT, for `boft_n_butterfly_factor=2`, the effective block size of OFT becomes twice as big and the number of blocks become half.
- `bias`: specify if the `bias` parameters should be trained. Can be `"none"`, `"all"` or `"boft_only"`.
- `boft_dropout`: specify the probability of multiplicative dropout.
- `target_modules`: The modules (for example, attention blocks) to inject the OFT/BOFT matrices.
- `modules_to_save`: List of modules apart from OFT/BOFT matrices to be set as trainable and saved in the final checkpoint. These typically include model's custom head that is randomly initialized for the fine-tuning task.



## BOFT Example Usage

For an example of the BOFT method application to various downstream tasks, please refer to the following guides:

Take a look at the following step-by-step guides on how to finetune a model with BOFT:
- [Dreambooth finetuning with BOFT](../task_guides/boft_dreambooth) 
- [Controllable generation finetuning with BOFT (ControlNet)](../task_guides/boft_controlnet) 

For the task of image classification, one can initialize the BOFT config for a DinoV2 model as follows:

```py
import transformers
from transformers import AutoModelForSeq2SeqLM, BOFTConfig
from peft import BOFTConfig, get_peft_model

config = BOFTConfig(
    boft_block_size=4,
    boft_n_butterfly_factor=2,
    target_modules=["query", "value", "key", "output.dense", "mlp.fc1", "mlp.fc2"],
    boft_dropout=0.1,
    bias="boft_only",
    modules_to_save=["classifier"],
)

model = transformers.Dinov2ForImageClassification.from_pretrained(
    "facebook/dinov2-large",
    num_labels=100,
)

boft_model = get_peft_model(model, config)
```


key: _node_content
string_value:
{"id_": "79ee5b45-2baf-45b6-988d-26bc81543b48", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/peft/conceptual_guides/adapter", "title": "Adapters", "tokens": 2143, "retrieve_doc": true, "source": "peft"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "7c26e19a-6aa2-4a4f-9d20-ca888c5dc6fd", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/peft/conceptual_guides/adapter", "title": "Adapters", "tokens": 2143, "retrieve_doc": true, "source": "peft"}, "hash": "ac53697511122efe02b2dbd92af6a68e2aee086bb881aa9a09ee96e86f657853", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "53576411-edec-4c5e-9ef4-51d62bc5ec6c", "node_type": "1", "metadata": {}, "hash": "00b46beaab7b5c213a19a51a02c70b6c47730b8c87b13de7e20753e57cdc7365", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 0, "end_char_idx": 3674, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
# Adapters

Adapter-based methods add extra trainable parameters after the attention and fully-connected layers of a frozen pretrained model to reduce memory-usage and speed up training. The method varies depending on the adapter, it could simply be an extra added layer or it could be expressing the weight updates ∆W as a low-rank decomposition of the weight matrix. Either way, the adapters are typically small but demonstrate comparable performance to a fully finetuned model and enable training larger models with fewer resources.

This guide will give you a brief overview of the adapter methods supported by PEFT (if you're interested in learning more details about a specific method, take a look at the linked paper).

## Low-Rank Adaptation (LoRA)

<Tip>

LoRA is one of the most popular PEFT methods and a good starting point if you're just getting started with PEFT. It was originally developed for large language models but it is a tremendously popular training method for diffusion models because of its efficiency and effectiveness.

</Tip>

As mentioned briefly earlier, [LoRA](https://hf.co/papers/2106.09685) is a technique that accelerates finetuning large models while consuming less memory.

LoRA represents the weight updates ∆W with two smaller matrices (called *update matrices*) through low-rank decomposition. These new matrices can be trained to adapt to the new data while keeping the overall number of parameters low. The original weight matrix remains frozen and doesn't receive any further updates. To produce the final results, the original and extra adapted weights are combined. You could also merge the adapter weights with the base model to eliminate inference latency.

<div class="flex justify-center">
    <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/peft/lora_animated.gif"/>
</div>

This approach has a number of advantages:

* LoRA makes finetuning more efficient by drastically reducing the number of trainable parameters.
* The original pretrained weights are kept frozen, which means you can have multiple lightweight and portable LoRA models for various downstream tasks built on top of them.
* LoRA is orthogonal to other parameter-efficient methods and can be combined with many of them.
* Performance of models finetuned using LoRA is comparable to the performance of fully finetuned models.

In principle, LoRA can be applied to any subset of weight matrices in a neural network to reduce the number of trainable parameters. However, for simplicity and further parameter efficiency, LoRA is typically only applied to the attention blocks in Transformer models. The resulting number of trainable parameters in a LoRA model depends on the size of the update matrices, which is determined mainly by the rank `r` and the shape of the original weight matrix.

<div class="flex justify-center">
    <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/peft/lora.png"/>
</div>
<small><a href="https://hf.co/papers/2103.10385">Navigating Text-To-Image Customization: From LyCORIS Fine-Tuning to Model Evaluation</a></small>

## Low-Rank Hadamard Product (LoHa)

Low-rank decomposition can impact performance because the weight updates are limited to the low-rank space, which can constrain a model's expressiveness. However, you don't necessarily want to use a larger rank because it increases the number of trainable parameters. To address this, [LoHa](https://huggingface.co/papers/2108.06098) (a method originally developed for computer vision) was applied to diffusion models where the ability to generate diverse images is an important consideration.


key: _node_content
string_value:
{"id_": "53576411-edec-4c5e-9ef4-51d62bc5ec6c", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/peft/conceptual_guides/adapter", "title": "Adapters", "tokens": 2143, "retrieve_doc": true, "source": "peft"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "7c26e19a-6aa2-4a4f-9d20-ca888c5dc6fd", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/peft/conceptual_guides/adapter", "title": "Adapters", "tokens": 2143, "retrieve_doc": true, "source": "peft"}, "hash": "ac53697511122efe02b2dbd92af6a68e2aee086bb881aa9a09ee96e86f657853", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "79ee5b45-2baf-45b6-988d-26bc81543b48", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/peft/conceptual_guides/adapter", "title": "Adapters", "tokens": 2143, "retrieve_doc": true, "source": "peft"}, "hash": "866873e89220c890bbbd7201a8d000fdef25e420f95621f723b6b7f2e6a86c51", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "a2a01153-3e4a-419a-a64c-b892471f67e5", "node_type": "1", "metadata": {}, "hash": "a1b6773f0f0a298e94d45f404e7291d3200af58347b93aa94dc7d8816afa580d", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 2008, "end_char_idx": 5464, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
* The original pretrained weights are kept frozen, which means you can have multiple lightweight and portable LoRA models for various downstream tasks built on top of them.
* LoRA is orthogonal to other parameter-efficient methods and can be combined with many of them.
* Performance of models finetuned using LoRA is comparable to the performance of fully finetuned models.

In principle, LoRA can be applied to any subset of weight matrices in a neural network to reduce the number of trainable parameters. However, for simplicity and further parameter efficiency, LoRA is typically only applied to the attention blocks in Transformer models. The resulting number of trainable parameters in a LoRA model depends on the size of the update matrices, which is determined mainly by the rank `r` and the shape of the original weight matrix.

<div class="flex justify-center">
    <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/peft/lora.png"/>
</div>
<small><a href="https://hf.co/papers/2103.10385">Navigating Text-To-Image Customization: From LyCORIS Fine-Tuning to Model Evaluation</a></small>

## Low-Rank Hadamard Product (LoHa)

Low-rank decomposition can impact performance because the weight updates are limited to the low-rank space, which can constrain a model's expressiveness. However, you don't necessarily want to use a larger rank because it increases the number of trainable parameters. To address this, [LoHa](https://huggingface.co/papers/2108.06098) (a method originally developed for computer vision) was applied to diffusion models where the ability to generate diverse images is an important consideration. LoHa should also work with general model types, but the embedding layers aren't currently implemented in PEFT.

LoHa uses the [Hadamard product](https://en.wikipedia.org/wiki/Hadamard_product_(matrices)) (element-wise product) instead of the matrix product. ∆W is represented by four smaller matrices instead of two - like in LoRA - and each pair of these low-rank matrices are combined with the Hadamard product. As a result, ∆W can have the same number of trainable parameters but a higher rank and expressivity.

## Low-Rank Kronecker Product (LoKr)

[LoKr](https://hf.co/papers/2309.14859) is very similar to LoRA and LoHa, and it is also mainly applied to diffusion models, though you could also use it with other model types. LoKr replaces the matrix product with the [Kronecker product](https://en.wikipedia.org/wiki/Kronecker_product) instead. The Kronecker product decomposition creates a block matrix which preserves the rank of the original weight matrix. Another benefit of the Kronecker product is that it can be vectorized by stacking the matrix columns. This can speed up the process because you're avoiding fully reconstructing ∆W.

## Orthogonal Finetuning (OFT)

<div class="flex justify-center">
    <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/peft/oft.png"/>
</div>
<small><a href="https://hf.co/papers/2306.07280">Controlling Text-to-Image Diffusion by Orthogonal Finetuning</a></small>

[OFT](https://hf.co/papers/2306.07280) is a method that primarily focuses on preserving a pretrained model's generative performance in the finetuned model. It tries to maintain the same cosine similarity (hyperspherical energy) between all pairwise neurons in a layer because this better captures the semantic information among neurons.


key: _node_content
string_value:
{"id_": "a2a01153-3e4a-419a-a64c-b892471f67e5", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/peft/conceptual_guides/adapter", "title": "Adapters", "tokens": 2143, "retrieve_doc": true, "source": "peft"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "7c26e19a-6aa2-4a4f-9d20-ca888c5dc6fd", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/peft/conceptual_guides/adapter", "title": "Adapters", "tokens": 2143, "retrieve_doc": true, "source": "peft"}, "hash": "ac53697511122efe02b2dbd92af6a68e2aee086bb881aa9a09ee96e86f657853", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "53576411-edec-4c5e-9ef4-51d62bc5ec6c", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/peft/conceptual_guides/adapter", "title": "Adapters", "tokens": 2143, "retrieve_doc": true, "source": "peft"}, "hash": "699ba9b1f94ed90127862c7d45129abec261a22cab41583a6e39f9f1c6962bef", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "2255e8ad-ccfa-40de-9a2d-ff3da62c75a4", "node_type": "1", "metadata": {}, "hash": "5de2b0fea01399d1d4cf1deaed3bbde38d09700f4a9518aa4da60daf23845848", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 3933, "end_char_idx": 7335, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
∆W is represented by four smaller matrices instead of two - like in LoRA - and each pair of these low-rank matrices are combined with the Hadamard product. As a result, ∆W can have the same number of trainable parameters but a higher rank and expressivity.

## Low-Rank Kronecker Product (LoKr)

[LoKr](https://hf.co/papers/2309.14859) is very similar to LoRA and LoHa, and it is also mainly applied to diffusion models, though you could also use it with other model types. LoKr replaces the matrix product with the [Kronecker product](https://en.wikipedia.org/wiki/Kronecker_product) instead. The Kronecker product decomposition creates a block matrix which preserves the rank of the original weight matrix. Another benefit of the Kronecker product is that it can be vectorized by stacking the matrix columns. This can speed up the process because you're avoiding fully reconstructing ∆W.

## Orthogonal Finetuning (OFT)

<div class="flex justify-center">
    <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/peft/oft.png"/>
</div>
<small><a href="https://hf.co/papers/2306.07280">Controlling Text-to-Image Diffusion by Orthogonal Finetuning</a></small>

[OFT](https://hf.co/papers/2306.07280) is a method that primarily focuses on preserving a pretrained model's generative performance in the finetuned model. It tries to maintain the same cosine similarity (hyperspherical energy) between all pairwise neurons in a layer because this better captures the semantic information among neurons. This means OFT is more capable at preserving the subject and it is better for controllable generation (similar to [ControlNet](https://huggingface.co/docs/diffusers/using-diffusers/controlnet)).

OFT preserves the hyperspherical energy by learning an orthogonal transformation for neurons to keep the cosine similarity between them unchanged. In practice, this means taking the matrix product of an orthogonal matrix with the pretrained weight matrix. However, to be parameter-efficient, the orthogonal matrix is represented as a block-diagonal matrix with rank `r` blocks. Whereas LoRA reduces the number of trainable parameters with low-rank structures, OFT reduces the number of trainable parameters with a sparse block-diagonal matrix structure.

## Orthogonal Butterfly (BOFT)

[BOFT](https://hf.co/papers/2311.06243) is a method that primarily focuses on preserving a pretrained model's generative performance in the finetuned model. It tries to maintain the same cosine similarity (hyperspherical energy) between all pairwise neurons in a layer because this better captures the semantic information among neurons. This means OFT is more capable at preserving the subject and it is better for controllable generation (similar to [ControlNet](https://huggingface.co/docs/diffusers/using-diffusers/controlnet)).

OFT preserves the hyperspherical energy by learning an orthogonal transformation for neurons to keep the cosine similarity between them unchanged. In practice, this means taking the matrix product of an orthogonal matrix with the pretrained weight matrix. However, to be parameter-efficient, the orthogonal matrix is represented as a block-diagonal matrix with rank `r` blocks. Whereas LoRA reduces the number of trainable parameters with low-rank structures, OFT reduces the number of trainable parameters with a sparse block-diagonal matrix structure.


key: _node_content
string_value:
{"id_": "2255e8ad-ccfa-40de-9a2d-ff3da62c75a4", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/peft/conceptual_guides/adapter", "title": "Adapters", "tokens": 2143, "retrieve_doc": true, "source": "peft"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "7c26e19a-6aa2-4a4f-9d20-ca888c5dc6fd", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/peft/conceptual_guides/adapter", "title": "Adapters", "tokens": 2143, "retrieve_doc": true, "source": "peft"}, "hash": "ac53697511122efe02b2dbd92af6a68e2aee086bb881aa9a09ee96e86f657853", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "a2a01153-3e4a-419a-a64c-b892471f67e5", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/peft/conceptual_guides/adapter", "title": "Adapters", "tokens": 2143, "retrieve_doc": true, "source": "peft"}, "hash": "499702e44cacc787282eeae4c67029a759f3b364966b21b7c77733a7136755d6", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "a0789bbc-bbde-4b76-b8ce-285c404e9576", "node_type": "1", "metadata": {}, "hash": "2a3e42a25ba8f6514f47be48eec9fceb6303722c20da8ff87bf4a6b519e59043", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 5465, "end_char_idx": 8814, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
This means OFT is more capable at preserving the subject and it is better for controllable generation (similar to [ControlNet](https://huggingface.co/docs/diffusers/using-diffusers/controlnet)).

OFT preserves the hyperspherical energy by learning an orthogonal transformation for neurons to keep the cosine similarity between them unchanged. In practice, this means taking the matrix product of an orthogonal matrix with the pretrained weight matrix. However, to be parameter-efficient, the orthogonal matrix is represented as a block-diagonal matrix with rank `r` blocks. Whereas LoRA reduces the number of trainable parameters with low-rank structures, OFT reduces the number of trainable parameters with a sparse block-diagonal matrix structure.

## Orthogonal Butterfly (BOFT)

[BOFT](https://hf.co/papers/2311.06243) is a method that primarily focuses on preserving a pretrained model's generative performance in the finetuned model. It tries to maintain the same cosine similarity (hyperspherical energy) between all pairwise neurons in a layer because this better captures the semantic information among neurons. This means OFT is more capable at preserving the subject and it is better for controllable generation (similar to [ControlNet](https://huggingface.co/docs/diffusers/using-diffusers/controlnet)).

OFT preserves the hyperspherical energy by learning an orthogonal transformation for neurons to keep the cosine similarity between them unchanged. In practice, this means taking the matrix product of an orthogonal matrix with the pretrained weight matrix. However, to be parameter-efficient, the orthogonal matrix is represented as a block-diagonal matrix with rank `r` blocks. Whereas LoRA reduces the number of trainable parameters with low-rank structures, OFT reduces the number of trainable parameters with a sparse block-diagonal matrix structure.

## Adaptive Low-Rank Adaptation (AdaLoRA)

[AdaLoRA](https://hf.co/papers/2303.10512) manages the parameter budget introduced from LoRA by allocating more parameters - in other words, a higher rank `r` - for important weight matrices that are better adapted for a task and pruning less important ones. The rank is controlled by a method similar to singular value decomposition (SVD). The ∆W is parameterized with two orthogonal matrices and a diagonal matrix which contains singular values. This parametrization method avoids iteratively applying SVD which is computationally expensive. Based on this method, the rank of ∆W is adjusted according to an importance score. ∆W is divided into triplets and each triplet is scored according to its contribution to model performance. Triplets with low importance scores are pruned and triplets with high importance scores are kept for finetuning.

## Llama-Adapter

[Llama-Adapter](https://hf.co/papers/2303.16199) is a method for adapting Llama into a instruction-following model. To help adapt the model for instruction-following, the adapter is trained with a 52K instruction-output dataset.

A set of of learnable adaption prompts are prefixed to the input instruction tokens. These are inserted into the upper layers of the model because it is better to learn with the higher-level semantics of the pretrained model. The instruction-output tokens prefixed to the input guide the adaption prompt to generate a contextual response.


key: _node_content
string_value:
{"id_": "a0789bbc-bbde-4b76-b8ce-285c404e9576", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/peft/conceptual_guides/adapter", "title": "Adapters", "tokens": 2143, "retrieve_doc": true, "source": "peft"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "7c26e19a-6aa2-4a4f-9d20-ca888c5dc6fd", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/peft/conceptual_guides/adapter", "title": "Adapters", "tokens": 2143, "retrieve_doc": true, "source": "peft"}, "hash": "ac53697511122efe02b2dbd92af6a68e2aee086bb881aa9a09ee96e86f657853", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "2255e8ad-ccfa-40de-9a2d-ff3da62c75a4", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/peft/conceptual_guides/adapter", "title": "Adapters", "tokens": 2143, "retrieve_doc": true, "source": "peft"}, "hash": "78905eebcb3ae183b92b13019d8ed48096558d90a09d4b57026cb7c2215ca26c", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 6929, "end_char_idx": 9443, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
In practice, this means taking the matrix product of an orthogonal matrix with the pretrained weight matrix. However, to be parameter-efficient, the orthogonal matrix is represented as a block-diagonal matrix with rank `r` blocks. Whereas LoRA reduces the number of trainable parameters with low-rank structures, OFT reduces the number of trainable parameters with a sparse block-diagonal matrix structure.

## Adaptive Low-Rank Adaptation (AdaLoRA)

[AdaLoRA](https://hf.co/papers/2303.10512) manages the parameter budget introduced from LoRA by allocating more parameters - in other words, a higher rank `r` - for important weight matrices that are better adapted for a task and pruning less important ones. The rank is controlled by a method similar to singular value decomposition (SVD). The ∆W is parameterized with two orthogonal matrices and a diagonal matrix which contains singular values. This parametrization method avoids iteratively applying SVD which is computationally expensive. Based on this method, the rank of ∆W is adjusted according to an importance score. ∆W is divided into triplets and each triplet is scored according to its contribution to model performance. Triplets with low importance scores are pruned and triplets with high importance scores are kept for finetuning.

## Llama-Adapter

[Llama-Adapter](https://hf.co/papers/2303.16199) is a method for adapting Llama into a instruction-following model. To help adapt the model for instruction-following, the adapter is trained with a 52K instruction-output dataset.

A set of of learnable adaption prompts are prefixed to the input instruction tokens. These are inserted into the upper layers of the model because it is better to learn with the higher-level semantics of the pretrained model. The instruction-output tokens prefixed to the input guide the adaption prompt to generate a contextual response.

<div class="flex justify-center">
    <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/peft/llama-adapter.png"/>
</div>
<small><a href="https://hf.co/papers/2303.16199">LLaMA-Adapter: Efficient Fine-tuning of Language Models with Zero-init Attention</a></small>

To avoid adding noise to the tokens, the adapter uses zero-initialized attention. On top of this, the adapter adds a learnable gating factor (initialized with zeros) to progressively add information to the model during training. This prevents overwhelming the model's pretrained knowledge with the newly learned instructions.


key: _node_content
string_value:
{"id_": "752cea53-3235-4d8a-a1b3-082794483d86", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/peft/conceptual_guides/prompting", "title": "Soft prompts", "tokens": 1568, "retrieve_doc": true, "source": "peft"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "5934c8df-3775-4b71-a129-2fffb7c3e281", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/peft/conceptual_guides/prompting", "title": "Soft prompts", "tokens": 1568, "retrieve_doc": true, "source": "peft"}, "hash": "9ced6c306fe65a64f13a8b54c6b09cdadc0dc9194bcdb8a53ed2d63c25163117", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "70582d42-ca4e-43c1-a53e-bdda3e73dd03", "node_type": "1", "metadata": {}, "hash": "393ae6aa986ae952811a898e9002e7d5bec13b9e76da120c93466e145bf57cd3", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 0, "end_char_idx": 3590, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
<!--⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be
rendered properly in your Markdown viewer.
-->

# Soft prompts

Training large pretrained language models is very time-consuming and compute-intensive. As they continue to grow in size, there is increasing interest in more efficient training methods such as *prompting*. Prompting primes a frozen pretrained model for a specific downstream task by including a text prompt that describes the task or even demonstrates an example of the task. With prompting, you can avoid fully training a separate model for each downstream task, and use the same frozen pretrained model instead. This is a lot easier because you can use the same model for several different tasks, and it is significantly more efficient to train and store a smaller set of prompt parameters than to train all the model's parameters.

There are two categories of prompting methods:

- hard prompts are manually handcrafted text prompts with discrete input tokens; the downside is that it requires a lot of effort to create a good prompt
- soft prompts are learnable tensors concatenated with the input embeddings that can be optimized to a dataset; the downside is that they aren't human readable because you aren't matching these "virtual tokens" to the embeddings of a real word

This conceptual guide provides a brief overview of the soft prompt methods included in 🤗 PEFT: prompt tuning, prefix tuning, P-tuning, and multitask prompt tuning.

## Prompt tuning

<div class="flex justify-center">
    <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/peft/prompt-tuning.png"/>
</div>
<small>Only train and store a significantly smaller set of task-specific prompt parameters <a href="https://hf.co/papers/2104.08691">(image source)</a>.</small>

[Prompt tuning](https://hf.co/papers/2104.08691) was developed for text classification tasks on T5 models, and all downstream tasks are cast as a text generation task. For example, sequence classification usually assigns a single class label to a sequence of text. By casting it as a text generation task, the tokens that make up the class label are *generated*. Prompts are added to the input as a series of tokens. Typically, the model parameters are fixed which means the prompt tokens are also fixed by the model parameters.

The key idea behind prompt tuning is that prompt tokens have their own parameters that are updated independently. This means you can keep the pretrained model's parameters frozen, and only update the gradients of the prompt token embeddings. The results are comparable to the traditional method of training the entire model, and prompt tuning performance scales as model size increases.

Take a look at [Prompt tuning for causal language modeling](../task_guides/clm-prompt-tuning) for a step-by-step guide on how to train a model with prompt tuning.

## Prefix tuning

<div class="flex justify-center">
    <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/peft/prefix-tuning.png"/>
</div>
<small>Optimize the prefix parameters for each task <a href="https://hf.co/papers/2101.00190">(image source)</a>.</small>

[Prefix tuning](https://hf.co/papers/2101.00190) was designed for natural language generation (NLG) tasks on GPT models. It is very similar to prompt tuning; prefix tuning also prepends a sequence of task-specific vectors to the input that can be trained and updated while keeping the rest of the pretrained model's parameters frozen.


key: _node_content
string_value:
{"id_": "70582d42-ca4e-43c1-a53e-bdda3e73dd03", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/peft/conceptual_guides/prompting", "title": "Soft prompts", "tokens": 1568, "retrieve_doc": true, "source": "peft"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "5934c8df-3775-4b71-a129-2fffb7c3e281", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/peft/conceptual_guides/prompting", "title": "Soft prompts", "tokens": 1568, "retrieve_doc": true, "source": "peft"}, "hash": "9ced6c306fe65a64f13a8b54c6b09cdadc0dc9194bcdb8a53ed2d63c25163117", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "752cea53-3235-4d8a-a1b3-082794483d86", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/peft/conceptual_guides/prompting", "title": "Soft prompts", "tokens": 1568, "retrieve_doc": true, "source": "peft"}, "hash": "93e9d07f9c2501a89a13f4b7a9a8a116db36b1b7b62f99f73a0c7d050f4cf8fb", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "4f229d6d-6782-4bf7-8812-8dc9803f5f77", "node_type": "1", "metadata": {}, "hash": "e2d965caa696bebd52d4fde8cf0bf98d8ea7fba47756c6c41468deff0fe0502f", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 2042, "end_char_idx": 5660, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
For example, sequence classification usually assigns a single class label to a sequence of text. By casting it as a text generation task, the tokens that make up the class label are *generated*. Prompts are added to the input as a series of tokens. Typically, the model parameters are fixed which means the prompt tokens are also fixed by the model parameters.

The key idea behind prompt tuning is that prompt tokens have their own parameters that are updated independently. This means you can keep the pretrained model's parameters frozen, and only update the gradients of the prompt token embeddings. The results are comparable to the traditional method of training the entire model, and prompt tuning performance scales as model size increases.

Take a look at [Prompt tuning for causal language modeling](../task_guides/clm-prompt-tuning) for a step-by-step guide on how to train a model with prompt tuning.

## Prefix tuning

<div class="flex justify-center">
    <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/peft/prefix-tuning.png"/>
</div>
<small>Optimize the prefix parameters for each task <a href="https://hf.co/papers/2101.00190">(image source)</a>.</small>

[Prefix tuning](https://hf.co/papers/2101.00190) was designed for natural language generation (NLG) tasks on GPT models. It is very similar to prompt tuning; prefix tuning also prepends a sequence of task-specific vectors to the input that can be trained and updated while keeping the rest of the pretrained model's parameters frozen. 

The main difference is that the prefix parameters are inserted in **all** of the model layers, whereas prompt tuning only adds the prompt parameters to the model input embeddings. The prefix parameters are also optimized by a separate feed-forward network (FFN) instead of training directly on the soft prompts because it causes instability and hurts performance. The FFN is discarded after updating the soft prompts.

As a result, the authors found that prefix tuning demonstrates comparable performance to fully finetuning a model, despite having 1000x fewer parameters, and it performs even better in low-data settings.

Take a look at [Prefix tuning for conditional generation](../task_guides/seq2seq-prefix-tuning) for a step-by-step guide on how to train a model with prefix tuning.

## P-tuning

<div class="flex justify-center">
    <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/peft/p-tuning.png"/>
</div>
<small>Prompt tokens can be inserted anywhere in the input sequence, and they are optimized by a prompt encoder <a href="https://hf.co/papers/2103.10385">(image source)</a>.</small>

[P-tuning](https://hf.co/papers/2103.10385) is designed for natural language understanding (NLU) tasks and all language models. 
It is another variation of a soft prompt method; P-tuning also adds a trainable embedding tensor that can be optimized to find better prompts, and it uses a prompt encoder (a bidirectional long-short term memory network or LSTM) to optimize the prompt parameters. Unlike prefix tuning though:

- the prompt tokens can be inserted anywhere in the input sequence, and it isn't restricted to only the beginning
- the prompt tokens are only added to the input instead of adding them to every layer of the model
- introducing *anchor* tokens can improve performance because they indicate characteristics of a component in the input sequence

The results suggest that P-tuning is more efficient than manually crafting prompts, and it enables GPT-like models to compete with BERT-like models on NLU tasks.


key: _node_content
string_value:
{"id_": "4f229d6d-6782-4bf7-8812-8dc9803f5f77", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/peft/conceptual_guides/prompting", "title": "Soft prompts", "tokens": 1568, "retrieve_doc": true, "source": "peft"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "5934c8df-3775-4b71-a129-2fffb7c3e281", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/peft/conceptual_guides/prompting", "title": "Soft prompts", "tokens": 1568, "retrieve_doc": true, "source": "peft"}, "hash": "9ced6c306fe65a64f13a8b54c6b09cdadc0dc9194bcdb8a53ed2d63c25163117", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "70582d42-ca4e-43c1-a53e-bdda3e73dd03", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/peft/conceptual_guides/prompting", "title": "Soft prompts", "tokens": 1568, "retrieve_doc": true, "source": "peft"}, "hash": "f2af67c8bb0bed7d4a8d6b2714f084cf6297ae67d2dea0c05e12fba580f873cb", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 3957, "end_char_idx": 7365, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
The FFN is discarded after updating the soft prompts.

As a result, the authors found that prefix tuning demonstrates comparable performance to fully finetuning a model, despite having 1000x fewer parameters, and it performs even better in low-data settings.

Take a look at [Prefix tuning for conditional generation](../task_guides/seq2seq-prefix-tuning) for a step-by-step guide on how to train a model with prefix tuning.

## P-tuning

<div class="flex justify-center">
    <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/peft/p-tuning.png"/>
</div>
<small>Prompt tokens can be inserted anywhere in the input sequence, and they are optimized by a prompt encoder <a href="https://hf.co/papers/2103.10385">(image source)</a>.</small>

[P-tuning](https://hf.co/papers/2103.10385) is designed for natural language understanding (NLU) tasks and all language models. 
It is another variation of a soft prompt method; P-tuning also adds a trainable embedding tensor that can be optimized to find better prompts, and it uses a prompt encoder (a bidirectional long-short term memory network or LSTM) to optimize the prompt parameters. Unlike prefix tuning though:

- the prompt tokens can be inserted anywhere in the input sequence, and it isn't restricted to only the beginning
- the prompt tokens are only added to the input instead of adding them to every layer of the model
- introducing *anchor* tokens can improve performance because they indicate characteristics of a component in the input sequence

The results suggest that P-tuning is more efficient than manually crafting prompts, and it enables GPT-like models to compete with BERT-like models on NLU tasks.

Take a look at [P-tuning for sequence classification](../task_guides/ptuning-seq-classification) for a step-by-step guide on how to train a model with P-tuning.

## Multitask prompt tuning

<div class="flex justify-center">
    <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/peft/mpt.png"/>
</div>
<small><a href="https://hf.co/papers/2303.02861">Multitask prompt tuning enables parameter-efficient transfer learning</a>.</small>

[Multitask prompt tuning (MPT)](https://hf.co/papers/2303.02861) learns a single prompt from data for multiple task types that can be shared for different target tasks. Other existing approaches learn a separate soft prompt for each task that need to be retrieved or aggregated for adaptation to target tasks. MPT consists of two stages:

1. source training - for each task, its soft prompt is decomposed into task-specific vectors. The task-specific vectors are multiplied together to form another matrix W, and the Hadamard product is used between W and a shared prompt matrix P to generate a task-specific prompt matrix. The task-specific prompts are distilled into a single prompt matrix that is shared across all tasks. This prompt is trained with multitask training.
2. target adaptation - to adapt the single prompt for a target task, a target prompt is initialized and expressed as the Hadamard product of the shared prompt matrix and the task-specific low-rank prompt matrix.

<div class="flex justify-center">
    <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/peft/mpt-decomposition.png"/>
</div>
<small><a href="https://hf.co/papers/2103.10385">Prompt decomposition</a>.</small>


key: _node_content
string_value:
{"id_": "85fb2e03-b135-4005-af20-61bd5f8297cb", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/peft/accelerate/deepspeed", "title": "DeepSpeed", "tokens": 5684, "retrieve_doc": true, "source": "peft"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "a955182e-7443-4eeb-bde7-b1f855ec2128", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/peft/accelerate/deepspeed", "title": "DeepSpeed", "tokens": 5684, "retrieve_doc": true, "source": "peft"}, "hash": "a8f3a08892343bb16b602d1d372b58e4b913a6acb9e638cfd34b438f3febffe8", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "15f257c9-1f4e-4895-812c-64b5012a3a33", "node_type": "1", "metadata": {}, "hash": "4e22b3bed5a7d9a131acbdcbdc4860fd36966da825220196afd9b28bc29815ce", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 0, "end_char_idx": 3151, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
<!--⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be
rendered properly in your Markdown viewer.
-->

# DeepSpeed

[DeepSpeed](https://www.deepspeed.ai/) is a library designed for speed and scale for distributed training of large models with billions of parameters. At its core is the Zero Redundancy Optimizer (ZeRO) that shards optimizer states (ZeRO-1), gradients (ZeRO-2), and parameters (ZeRO-3) across data parallel processes. This drastically reduces memory usage, allowing you to scale your training to billion parameter models. To unlock even more memory efficiency, ZeRO-Offload reduces GPU compute and memory by leveraging CPU resources during optimization.

Both of these features are supported in 🤗 Accelerate, and you can use them with 🤗 PEFT. 

## Compatibility with `bitsandbytes` quantization + LoRA

Below is a table that summarizes the compatibility between PEFT's LoRA, [`bitsandbytes`](https://github.com/TimDettmers/bitsandbytes) library and DeepSpeed Zero stages with respect to fine-tuning. DeepSpeed Zero-1 and 2 will have no effect at inference as stage 1 shards the optimizer states and stage 2 shards the optimizer states and gradients:

| DeepSpeed stage   | Is compatible? |
|---|---|
| Zero-1 |  🟢 |
| Zero-2   |  🟢 |
| Zero-3  |  🟢 |

For DeepSpeed Stage 3 + QLoRA, please refer to the section [Use PEFT QLoRA and DeepSpeed with ZeRO3 for finetuning large models on multiple GPUs](#use-peft-qlora-and-deepspeed-with-zero3-for-finetuning-large-models-on-multiple-gpus) below.

For confirming these observations, we ran the SFT (Supervised Fine-tuning) [offical example scripts](https://github.com/huggingface/trl/tree/main/examples) of the [Transformers Reinforcement Learning (TRL) library](https://github.com/huggingface/trl) using QLoRA + PEFT and the accelerate configs available [here](https://github.com/huggingface/trl/tree/main/examples/accelerate_configs). We ran these experiments on a 2x NVIDIA T4 GPU.

# Use PEFT and DeepSpeed with ZeRO3 for finetuning large models on multiple devices and multiple nodes

This section of guide will help you learn how to use our DeepSpeed [training script](https://github.com/huggingface/peft/blob/main/examples/sft/train.py) for performing SFT. You'll configure the script to do SFT (supervised fine-tuning) of Llama-70B model with LoRA and ZeRO-3 on 8xH100 80GB GPUs on a single machine. You can configure it to scale to multiple machines by changing the accelerate config.

## Configuration

Start by running the following command to [create a DeepSpeed configuration file](https://huggingface.co/docs/accelerate/quicktour#launching-your-distributed-script) with 🤗 Accelerate. The `--config_file` flag allows you to save the configuration file to a specific location, otherwise it is saved as a `default_config.yaml` file in the 🤗 Accelerate cache.

The configuration file is used to set the default options when you launch the training script.

```bash
accelerate config --config_file deepspeed_config.yaml
```

You'll be asked a few questions about your setup, and configure the following arguments.


key: _node_content
string_value:
{"id_": "15f257c9-1f4e-4895-812c-64b5012a3a33", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/peft/accelerate/deepspeed", "title": "DeepSpeed", "tokens": 5684, "retrieve_doc": true, "source": "peft"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "a955182e-7443-4eeb-bde7-b1f855ec2128", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/peft/accelerate/deepspeed", "title": "DeepSpeed", "tokens": 5684, "retrieve_doc": true, "source": "peft"}, "hash": "a8f3a08892343bb16b602d1d372b58e4b913a6acb9e638cfd34b438f3febffe8", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "85fb2e03-b135-4005-af20-61bd5f8297cb", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/peft/accelerate/deepspeed", "title": "DeepSpeed", "tokens": 5684, "retrieve_doc": true, "source": "peft"}, "hash": "7e9d8060314e14318b38514bd7ef2d363471ab2e6e8544fc2fe9b996941f5d4d", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "cc8e6baa-d5ab-4283-8b97-293ad919a0f9", "node_type": "1", "metadata": {}, "hash": "bab63b5f55f768fe8f5ce85aa6f09a1caba586dcac2512924762bfd435a35d4b", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 1577, "end_char_idx": 4587, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
For confirming these observations, we ran the SFT (Supervised Fine-tuning) [offical example scripts](https://github.com/huggingface/trl/tree/main/examples) of the [Transformers Reinforcement Learning (TRL) library](https://github.com/huggingface/trl) using QLoRA + PEFT and the accelerate configs available [here](https://github.com/huggingface/trl/tree/main/examples/accelerate_configs). We ran these experiments on a 2x NVIDIA T4 GPU.

# Use PEFT and DeepSpeed with ZeRO3 for finetuning large models on multiple devices and multiple nodes

This section of guide will help you learn how to use our DeepSpeed [training script](https://github.com/huggingface/peft/blob/main/examples/sft/train.py) for performing SFT. You'll configure the script to do SFT (supervised fine-tuning) of Llama-70B model with LoRA and ZeRO-3 on 8xH100 80GB GPUs on a single machine. You can configure it to scale to multiple machines by changing the accelerate config.

## Configuration

Start by running the following command to [create a DeepSpeed configuration file](https://huggingface.co/docs/accelerate/quicktour#launching-your-distributed-script) with 🤗 Accelerate. The `--config_file` flag allows you to save the configuration file to a specific location, otherwise it is saved as a `default_config.yaml` file in the 🤗 Accelerate cache.

The configuration file is used to set the default options when you launch the training script.

```bash
accelerate config --config_file deepspeed_config.yaml
```

You'll be asked a few questions about your setup, and configure the following arguments. In this example, you'll use ZeRO-3 so make sure you pick those options.

```bash
`zero_stage`: [0] Disabled, [1] optimizer state partitioning, [2] optimizer+gradient state partitioning and [3] optimizer+gradient+parameter partitioning
`gradient_accumulation_steps`: Number of training steps to accumulate gradients before averaging and applying them. Pass the same value as you would pass via cmd argument else you will encounter mismatch error.
`gradient_clipping`: Enable gradient clipping with value. Don't set this as you will be passing it via cmd arguments.
`offload_optimizer_device`: [none] Disable optimizer offloading, [cpu] offload optimizer to CPU, [nvme] offload optimizer to NVMe SSD. Only applicable with ZeRO >= Stage-2. Set this as `none` as don't want to enable offloading.
`offload_param_device`: [none] Disable parameter offloading, [cpu] offload parameters to CPU, [nvme] offload parameters to NVMe SSD. Only applicable with ZeRO Stage-3. Set this as `none` as don't want to enable offloading.
`zero3_init_flag`: Decides whether to enable `deepspeed.zero.Init` for constructing massive models. Only applicable with ZeRO Stage-3. Set this to `True`.
`zero3_save_16bit_model`: Decides whether to save 16-bit model weights when using ZeRO Stage-3. Set this to `True`.
`mixed_precision`: `no` for FP32 training, `fp16` for FP16 mixed-precision training and `bf16` for BF16 mixed-precision training. Set this to `True`.


key: _node_content
string_value:
{"id_": "cc8e6baa-d5ab-4283-8b97-293ad919a0f9", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/peft/accelerate/deepspeed", "title": "DeepSpeed", "tokens": 5684, "retrieve_doc": true, "source": "peft"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "a955182e-7443-4eeb-bde7-b1f855ec2128", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/peft/accelerate/deepspeed", "title": "DeepSpeed", "tokens": 5684, "retrieve_doc": true, "source": "peft"}, "hash": "a8f3a08892343bb16b602d1d372b58e4b913a6acb9e638cfd34b438f3febffe8", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "15f257c9-1f4e-4895-812c-64b5012a3a33", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/peft/accelerate/deepspeed", "title": "DeepSpeed", "tokens": 5684, "retrieve_doc": true, "source": "peft"}, "hash": "2d0627e65740cf39ed16a9fcefe119f934763804ad46f57d6cc9135768750573", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "003cab88-7ccd-41d0-8d57-450ae58bac93", "node_type": "1", "metadata": {}, "hash": "90cbde9599a974dc385108ddc233a509fee79f90aa00e2e3fdffa8577ceebf8f", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 2996, "end_char_idx": 6882, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
```bash
accelerate config --config_file deepspeed_config.yaml
```

You'll be asked a few questions about your setup, and configure the following arguments. In this example, you'll use ZeRO-3 so make sure you pick those options.

```bash
`zero_stage`: [0] Disabled, [1] optimizer state partitioning, [2] optimizer+gradient state partitioning and [3] optimizer+gradient+parameter partitioning
`gradient_accumulation_steps`: Number of training steps to accumulate gradients before averaging and applying them. Pass the same value as you would pass via cmd argument else you will encounter mismatch error.
`gradient_clipping`: Enable gradient clipping with value. Don't set this as you will be passing it via cmd arguments.
`offload_optimizer_device`: [none] Disable optimizer offloading, [cpu] offload optimizer to CPU, [nvme] offload optimizer to NVMe SSD. Only applicable with ZeRO >= Stage-2. Set this as `none` as don't want to enable offloading.
`offload_param_device`: [none] Disable parameter offloading, [cpu] offload parameters to CPU, [nvme] offload parameters to NVMe SSD. Only applicable with ZeRO Stage-3. Set this as `none` as don't want to enable offloading.
`zero3_init_flag`: Decides whether to enable `deepspeed.zero.Init` for constructing massive models. Only applicable with ZeRO Stage-3. Set this to `True`.
`zero3_save_16bit_model`: Decides whether to save 16-bit model weights when using ZeRO Stage-3. Set this to `True`.
`mixed_precision`: `no` for FP32 training, `fp16` for FP16 mixed-precision training and `bf16` for BF16 mixed-precision training. Set this to `True`.
```

Once this is done, the corresponding config should look like below and you can find it in config folder at [deepspeed_config.yaml](https://github.com/huggingface/peft/blob/main/examples/sft/configs/deepspeed_config.yaml):

```yml
compute_environment: LOCAL_MACHINE                                                                                                                                           
debug: false
deepspeed_config:
  deepspeed_multinode_launcher: standard
  gradient_accumulation_steps: 4
  offload_optimizer_device: none
  offload_param_device: none
  zero3_init_flag: true
  zero3_save_16bit_model: true
  zero_stage: 3
distributed_type: DEEPSPEED
downcast_bf16: 'no'
machine_rank: 0
main_training_function: main
mixed_precision: bf16
num_machines: 1
num_processes: 8
rdzv_backend: static
same_network: true
tpu_env: []
tpu_use_cluster: false
tpu_use_sudo: false
use_cpu: false
```

## Launch command

The launch command is available at [run_peft_deepspeed.sh](https://github.com/huggingface/peft/blob/main/examples/sft/run_peft_deepspeed.sh) and it is also shown below:
```bash
accelerate launch --config_file "configs/deepspeed_config.yaml"  train.py \
--seed 100 \
--model_name_or_path "meta-llama/Llama-2-70b-hf" \
--dataset_name "smangrul/ultrachat-10k-chatml" \
--chat_template_format "chatml" \
--add_special_tokens False \
--append_concat_token False \
--splits "train,test" \
--max_seq_len 2048 \
--num_train_epochs 1 \
--logging_steps 5 \
--log_level "info" \
--logging_strategy "steps" \
--evaluation_strategy "epoch" \
--save_strategy "epoch" \
--push_to_hub \
--hub_private_repo True \
--hub_strategy "every_save" \
--bf16 True \
--packing True \
--learning_rate 1e-4 \
--lr_scheduler_type "cosine" \
--weight_decay 1e-4 \
--warmup_ratio 0.0 \
--max_grad_norm 1.0 \
--output_dir "llama-sft-lora-deepspeed" \
--per_device_train_batch_size 8 \
--per_device_eval_batch_size 8 \
--gradient_accumulation_steps 4 \
--gradient_checkpointing True \
--use_reentrant False \
--dataset_text_field "content" \
--use_flash_attn True \
--use_peft_lora True \
--lora_r 8 \
--lora_alpha 16 \
--lora_dropout 0.1 \
--lora_target_modules "all-linear" \
--use_4bit_quantization False
```

Notice that we are using LoRA with  rank=8, alpha=16 and targeting all linear layers.


key: _node_content
string_value:
{"id_": "003cab88-7ccd-41d0-8d57-450ae58bac93", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/peft/accelerate/deepspeed", "title": "DeepSpeed", "tokens": 5684, "retrieve_doc": true, "source": "peft"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "a955182e-7443-4eeb-bde7-b1f855ec2128", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/peft/accelerate/deepspeed", "title": "DeepSpeed", "tokens": 5684, "retrieve_doc": true, "source": "peft"}, "hash": "a8f3a08892343bb16b602d1d372b58e4b913a6acb9e638cfd34b438f3febffe8", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "cc8e6baa-d5ab-4283-8b97-293ad919a0f9", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/peft/accelerate/deepspeed", "title": "DeepSpeed", "tokens": 5684, "retrieve_doc": true, "source": "peft"}, "hash": "331f4be617b173d0f88190a512cffddce6964aaa28ee813d7af9af2f5d407098", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "3cf38603-377a-413b-981d-adbdd95ea831", "node_type": "1", "metadata": {}, "hash": "846e2a44cdc7b16e37a7704e3e55d9cba0efca8a882f1be3b6654002d2e375b9", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 6883, "end_char_idx": 9379, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
We are passing the deepspeed config file and finetuning 70B Llama model on a subset of the ultrachat dataset.

## The important parts

Let's dive a little deeper into the script so you can see what's going on, and understand how it works.

The first thing to know is that the script uses DeepSpeed for distributed training as the DeepSpeed config has been passed. The `SFTTrainer` class handles all the heavy lifting of creating the PEFT model using the peft config that is passed. After that, when you call `trainer.train()`, `SFTTrainer` internally uses 🤗 Accelerate to prepare the model, optimizer and trainer using the DeepSpeed config to create DeepSpeed engine which is then trained. The main code snippet is below:

```python
# trainer
trainer = SFTTrainer(
    model=model,
    tokenizer=tokenizer,
    args=training_args,
    train_dataset=train_dataset,
    eval_dataset=eval_dataset,
    peft_config=peft_config,
    packing=data_args.packing,
    dataset_kwargs={
        "append_concat_token": data_args.append_concat_token,
        "add_special_tokens": data_args.add_special_tokens,
    },
    dataset_text_field=data_args.dataset_text_field,
    max_seq_length=data_args.max_seq_length,
)
trainer.accelerator.print(f"{trainer.model}")

# train
checkpoint = None
if training_args.resume_from_checkpoint is not None:
    checkpoint = training_args.resume_from_checkpoint
trainer.train(resume_from_checkpoint=checkpoint)

# saving final model
trainer.save_model()
```

## Memory usage

In the above example, the memory consumed per GPU is 64 GB (80%) as seen in the screenshot below:

<div class="flex justify-center">
    <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/peft/peft_deepspeed_mem_usage.png"/>
</div>
<small>GPU memory usage for the training run</small>

## More resources
You can also refer this blog post [Falcon 180B Finetuning using 🤗 PEFT and DeepSpeed](https://medium.com/@sourabmangrulkar/falcon-180b-finetuning-using-peft-and-deepspeed-b92643091d99) on how to finetune 180B Falcon model on 16 A100 GPUs on 2 machines.


# Use PEFT QLoRA and DeepSpeed with ZeRO3 for finetuning large models on multiple GPUs

In this section, we will look at how to use QLoRA and DeepSpeed Stage-3 for finetuning 70B llama model on 2X40GB GPUs.
For this, we first need `bitsandbytes>=0.43.0`, `accelerate>=0.28.0`, `transformers>4.38.2`, `trl>0.7.11` and `peft>0.9.0`. We need to set `zero3_init_flag` to true when using Accelerate config.


key: _node_content
string_value:
{"id_": "3cf38603-377a-413b-981d-adbdd95ea831", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/peft/accelerate/deepspeed", "title": "DeepSpeed", "tokens": 5684, "retrieve_doc": true, "source": "peft"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "a955182e-7443-4eeb-bde7-b1f855ec2128", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/peft/accelerate/deepspeed", "title": "DeepSpeed", "tokens": 5684, "retrieve_doc": true, "source": "peft"}, "hash": "a8f3a08892343bb16b602d1d372b58e4b913a6acb9e638cfd34b438f3febffe8", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "003cab88-7ccd-41d0-8d57-450ae58bac93", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/peft/accelerate/deepspeed", "title": "DeepSpeed", "tokens": 5684, "retrieve_doc": true, "source": "peft"}, "hash": "c5c5e93ba5a37a9a519fc6aff103784203e97c4216ee520362dc0937b6505f5d", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "a79822c2-3c5a-4030-9205-85b2241983d8", "node_type": "1", "metadata": {}, "hash": "137acbe3d5a648966d550c6e35f4b4a9931f0520677e3bf75f773b1f468e49e4", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 8978, "end_char_idx": 11724, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
# Use PEFT QLoRA and DeepSpeed with ZeRO3 for finetuning large models on multiple GPUs

In this section, we will look at how to use QLoRA and DeepSpeed Stage-3 for finetuning 70B llama model on 2X40GB GPUs.
For this, we first need `bitsandbytes>=0.43.0`, `accelerate>=0.28.0`, `transformers>4.38.2`, `trl>0.7.11` and `peft>0.9.0`. We need to set `zero3_init_flag` to true when using Accelerate config. Below is the config which can be found at [deepspeed_config_z3_qlora.yaml](https://github.com/huggingface/peft/blob/main/examples/sft/configs/deepspeed_config_z3_qlora.yaml):

```yml
compute_environment: LOCAL_MACHINE                                                                                                                                           
debug: false
deepspeed_config:
  deepspeed_multinode_launcher: standard
  offload_optimizer_device: none
  offload_param_device: none
  zero3_init_flag: true
  zero3_save_16bit_model: true
  zero_stage: 3
distributed_type: DEEPSPEED
downcast_bf16: 'no'
machine_rank: 0
main_training_function: main
mixed_precision: bf16
num_machines: 1
num_processes: 2
rdzv_backend: static
same_network: true
tpu_env: []
tpu_use_cluster: false
tpu_use_sudo: false
use_cpu: false
```

Launch command is given below which is available at [run_peft_qlora_deepspeed_stage3.sh](https://github.com/huggingface/peft/blob/main/examples/sft/run_peft_deepspeed.sh):
```
accelerate launch --config_file "configs/deepspeed_config_z3_qlora.yaml"  train.py \
--seed 100 \
--model_name_or_path "meta-llama/Llama-2-70b-hf" \
--dataset_name "smangrul/ultrachat-10k-chatml" \
--chat_template_format "chatml" \
--add_special_tokens False \
--append_concat_token False \
--splits "train,test" \
--max_seq_len 2048 \
--num_train_epochs 1 \
--logging_steps 5 \
--log_level "info" \
--logging_strategy "steps" \
--evaluation_strategy "epoch" \
--save_strategy "epoch" \
--push_to_hub \
--hub_private_repo True \
--hub_strategy "every_save" \
--bf16 True \
--packing True \
--learning_rate 1e-4 \
--lr_scheduler_type "cosine" \
--weight_decay 1e-4 \
--warmup_ratio 0.0 \
--max_grad_norm 1.0 \
--output_dir "llama-sft-qlora-dsz3" \
--per_device_train_batch_size 2 \
--per_device_eval_batch_size 2 \
--gradient_accumulation_steps 2 \
--gradient_checkpointing True \
--use_reentrant True \
--dataset_text_field "content" \
--use_flash_attn True \
--use_peft_lora True \
--lora_r 8 \
--lora_alpha 16 \
--lora_dropout 0.1 \
--lora_target_modules "all-linear" \
--use_4bit_quantization True \
--use_nested_quant True \
--bnb_4bit_compute_dtype "bfloat16" \
--bnb_4bit_quant_storage_dtype "bfloat16"
```

Notice the new argument being passed `bnb_4bit_quant_storage_dtype` which denotes the data type for packing the 4-bit parameters.


key: _node_content
string_value:
{"id_": "a79822c2-3c5a-4030-9205-85b2241983d8", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/peft/accelerate/deepspeed", "title": "DeepSpeed", "tokens": 5684, "retrieve_doc": true, "source": "peft"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "a955182e-7443-4eeb-bde7-b1f855ec2128", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/peft/accelerate/deepspeed", "title": "DeepSpeed", "tokens": 5684, "retrieve_doc": true, "source": "peft"}, "hash": "a8f3a08892343bb16b602d1d372b58e4b913a6acb9e638cfd34b438f3febffe8", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "3cf38603-377a-413b-981d-adbdd95ea831", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/peft/accelerate/deepspeed", "title": "DeepSpeed", "tokens": 5684, "retrieve_doc": true, "source": "peft"}, "hash": "3af7059f34e85d08284b0ec018b7d50bbce4c55784a2f8a5ba0bc04d9e9be4ab", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "8dcc06e3-90f4-460b-8b67-71fe6b26ee5d", "node_type": "1", "metadata": {}, "hash": "2c0465f219113ebe965f2dd8c41d03164d29d5de9370a195390572a4eae1268d", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 11725, "end_char_idx": 14850, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
For example, when it is set to `bfloat16`, **32/4 = 8** 4-bit params are packed together post quantization.

In terms of training code, the important code changes are: 

```diff
...

bnb_config = BitsAndBytesConfig(
    load_in_4bit=args.use_4bit_quantization,
    bnb_4bit_quant_type=args.bnb_4bit_quant_type,
    bnb_4bit_compute_dtype=compute_dtype,
    bnb_4bit_use_double_quant=args.use_nested_quant,
+   bnb_4bit_quant_storage=quant_storage_dtype,
)

...

model = AutoModelForCausalLM.from_pretrained(
    args.model_name_or_path,
    quantization_config=bnb_config,
    trust_remote_code=True,
    attn_implementation="flash_attention_2" if args.use_flash_attn else "eager",
+   torch_dtype=quant_storage_dtype or torch.float32,
)
```

Notice that `torch_dtype` for `AutoModelForCausalLM` is same as the `bnb_4bit_quant_storage` data type. That's it. Everything else is handled by Trainer and TRL.

## Memory usage

In the above example, the memory consumed per GPU is **36.6 GB**. Therefore, what took 8X80GB GPUs with DeepSpeed Stage 3+LoRA and a couple of 80GB GPUs with DDP+QLoRA now requires 2X40GB GPUs. This makes finetuning of large models more accessible.

# Use PEFT and DeepSpeed with ZeRO3 and CPU Offloading for finetuning large models on a single GPU
This section of guide will help you learn how to use our DeepSpeed [training script](https://github.com/huggingface/peft/blob/main/examples/conditional_generation/peft_lora_seq2seq_accelerate_ds_zero3_offload.py). You'll configure the script to train a large model for conditional generation with ZeRO-3 and CPU Offload.

<Tip>

💡 To help you get started, check out our example training scripts for [causal language modeling](https://github.com/huggingface/peft/blob/main/examples/causal_language_modeling/peft_lora_clm_accelerate_ds_zero3_offload.py) and [conditional generation](https://github.com/huggingface/peft/blob/main/examples/conditional_generation/peft_lora_seq2seq_accelerate_ds_zero3_offload.py). You can adapt these scripts for your own applications or even use them out of the box if your task is similar to the one in the scripts.

</Tip>

## Configuration

Start by running the following command to [create a DeepSpeed configuration file](https://huggingface.co/docs/accelerate/quicktour#launching-your-distributed-script) with 🤗 Accelerate. The `--config_file` flag allows you to save the configuration file to a specific location, otherwise it is saved as a `default_config.yaml` file in the 🤗 Accelerate cache.

The configuration file is used to set the default options when you launch the training script.

```bash
accelerate config --config_file ds_zero3_cpu.yaml
```

You'll be asked a few questions about your setup, and configure the following arguments. In this example, you'll use ZeRO-3 along with CPU-Offload so make sure you pick those options.

```bash
`zero_stage`: [0] Disabled, [1] optimizer state partitioning, [2] optimizer+gradient state partitioning and [3] optimizer+gradient+parameter partitioning
`gradient_accumulation_steps`: Number of training steps to accumulate gradients before averaging and applying them.


key: _node_content
string_value:
{"id_": "8dcc06e3-90f4-460b-8b67-71fe6b26ee5d", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/peft/accelerate/deepspeed", "title": "DeepSpeed", "tokens": 5684, "retrieve_doc": true, "source": "peft"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "a955182e-7443-4eeb-bde7-b1f855ec2128", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/peft/accelerate/deepspeed", "title": "DeepSpeed", "tokens": 5684, "retrieve_doc": true, "source": "peft"}, "hash": "a8f3a08892343bb16b602d1d372b58e4b913a6acb9e638cfd34b438f3febffe8", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "a79822c2-3c5a-4030-9205-85b2241983d8", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/peft/accelerate/deepspeed", "title": "DeepSpeed", "tokens": 5684, "retrieve_doc": true, "source": "peft"}, "hash": "12bef7d390b1547dae9eae1178de204561ee12ddaea73b61da3909017aede897", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "d3820256-7fc0-4dbf-b361-dcd054f2d829", "node_type": "1", "metadata": {}, "hash": "f6330bc74bc55339c1f0f862843496ef5b85a291838e229ebb6862d275af21be", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 13211, "end_char_idx": 15953, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
You'll configure the script to train a large model for conditional generation with ZeRO-3 and CPU Offload.

<Tip>

💡 To help you get started, check out our example training scripts for [causal language modeling](https://github.com/huggingface/peft/blob/main/examples/causal_language_modeling/peft_lora_clm_accelerate_ds_zero3_offload.py) and [conditional generation](https://github.com/huggingface/peft/blob/main/examples/conditional_generation/peft_lora_seq2seq_accelerate_ds_zero3_offload.py). You can adapt these scripts for your own applications or even use them out of the box if your task is similar to the one in the scripts.

</Tip>

## Configuration

Start by running the following command to [create a DeepSpeed configuration file](https://huggingface.co/docs/accelerate/quicktour#launching-your-distributed-script) with 🤗 Accelerate. The `--config_file` flag allows you to save the configuration file to a specific location, otherwise it is saved as a `default_config.yaml` file in the 🤗 Accelerate cache.

The configuration file is used to set the default options when you launch the training script.

```bash
accelerate config --config_file ds_zero3_cpu.yaml
```

You'll be asked a few questions about your setup, and configure the following arguments. In this example, you'll use ZeRO-3 along with CPU-Offload so make sure you pick those options.

```bash
`zero_stage`: [0] Disabled, [1] optimizer state partitioning, [2] optimizer+gradient state partitioning and [3] optimizer+gradient+parameter partitioning
`gradient_accumulation_steps`: Number of training steps to accumulate gradients before averaging and applying them.
`gradient_clipping`: Enable gradient clipping with value.
`offload_optimizer_device`: [none] Disable optimizer offloading, [cpu] offload optimizer to CPU, [nvme] offload optimizer to NVMe SSD. Only applicable with ZeRO >= Stage-2.
`offload_param_device`: [none] Disable parameter offloading, [cpu] offload parameters to CPU, [nvme] offload parameters to NVMe SSD. Only applicable with ZeRO Stage-3.
`zero3_init_flag`: Decides whether to enable `deepspeed.zero.Init` for constructing massive models. Only applicable with ZeRO Stage-3.
`zero3_save_16bit_model`: Decides whether to save 16-bit model weights when using ZeRO Stage-3.
`mixed_precision`: `no` for FP32 training, `fp16` for FP16 mixed-precision training and `bf16` for BF16 mixed-precision training. 
```

An example [configuration file](https://github.com/huggingface/peft/blob/main/examples/conditional_generation/accelerate_ds_zero3_cpu_offload_config.yaml) might look like the following. The most important thing to notice is that `zero_stage` is set to `3`, and `offload_optimizer_device` and `offload_param_device` are set to the `cpu`.


key: _node_content
string_value:
{"id_": "d3820256-7fc0-4dbf-b361-dcd054f2d829", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/peft/accelerate/deepspeed", "title": "DeepSpeed", "tokens": 5684, "retrieve_doc": true, "source": "peft"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "a955182e-7443-4eeb-bde7-b1f855ec2128", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/peft/accelerate/deepspeed", "title": "DeepSpeed", "tokens": 5684, "retrieve_doc": true, "source": "peft"}, "hash": "a8f3a08892343bb16b602d1d372b58e4b913a6acb9e638cfd34b438f3febffe8", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "8dcc06e3-90f4-460b-8b67-71fe6b26ee5d", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/peft/accelerate/deepspeed", "title": "DeepSpeed", "tokens": 5684, "retrieve_doc": true, "source": "peft"}, "hash": "b7bc127db86909cbe51ffce506bb75c7444b9c708a88a64a0d17d110efce6b23", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "219ad062-1c4a-45b0-955b-1898daa6e5b2", "node_type": "1", "metadata": {}, "hash": "730c2eb16a938c850f1c2e84cd5f258d0e4cf803536104dab55bda3f7c9fd1a7", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 14477, "end_char_idx": 17438, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
In this example, you'll use ZeRO-3 along with CPU-Offload so make sure you pick those options.

```bash
`zero_stage`: [0] Disabled, [1] optimizer state partitioning, [2] optimizer+gradient state partitioning and [3] optimizer+gradient+parameter partitioning
`gradient_accumulation_steps`: Number of training steps to accumulate gradients before averaging and applying them.
`gradient_clipping`: Enable gradient clipping with value.
`offload_optimizer_device`: [none] Disable optimizer offloading, [cpu] offload optimizer to CPU, [nvme] offload optimizer to NVMe SSD. Only applicable with ZeRO >= Stage-2.
`offload_param_device`: [none] Disable parameter offloading, [cpu] offload parameters to CPU, [nvme] offload parameters to NVMe SSD. Only applicable with ZeRO Stage-3.
`zero3_init_flag`: Decides whether to enable `deepspeed.zero.Init` for constructing massive models. Only applicable with ZeRO Stage-3.
`zero3_save_16bit_model`: Decides whether to save 16-bit model weights when using ZeRO Stage-3.
`mixed_precision`: `no` for FP32 training, `fp16` for FP16 mixed-precision training and `bf16` for BF16 mixed-precision training. 
```

An example [configuration file](https://github.com/huggingface/peft/blob/main/examples/conditional_generation/accelerate_ds_zero3_cpu_offload_config.yaml) might look like the following. The most important thing to notice is that `zero_stage` is set to `3`, and `offload_optimizer_device` and `offload_param_device` are set to the `cpu`.

```yml
compute_environment: LOCAL_MACHINE
deepspeed_config:
  gradient_accumulation_steps: 1
  gradient_clipping: 1.0
  offload_optimizer_device: cpu
  offload_param_device: cpu
  zero3_init_flag: true
  zero3_save_16bit_model: true
  zero_stage: 3
distributed_type: DEEPSPEED
downcast_bf16: 'no'
dynamo_backend: 'NO'
fsdp_config: {}
machine_rank: 0
main_training_function: main
megatron_lm_config: {}
mixed_precision: 'no'
num_machines: 1
num_processes: 1
rdzv_backend: static
same_network: true
use_cpu: false
```

## The important parts

Let's dive a little deeper into the script so you can see what's going on, and understand how it works.

Within the [`main`](https://github.com/huggingface/peft/blob/2822398fbe896f25d4dac5e468624dc5fd65a51b/examples/conditional_generation/peft_lora_seq2seq_accelerate_ds_zero3_offload.py#L103) function, the script creates an [`~accelerate.Accelerator`] class to initialize all the necessary requirements for distributed training.

<Tip>

💡 Feel free to change the model and dataset inside the `main` function. If your dataset format is different from the one in the script, you may also need to write your own preprocessing function. 

</Tip>

The script also creates a configuration for the 🤗 PEFT method you're using, which in this case, is LoRA. The [`LoraConfig`] specifies the task type and important parameters such as the dimension of the low-rank matrices, the matrices scaling factor, and the dropout probability of the LoRA layers.


key: _node_content
string_value:
{"id_": "219ad062-1c4a-45b0-955b-1898daa6e5b2", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/peft/accelerate/deepspeed", "title": "DeepSpeed", "tokens": 5684, "retrieve_doc": true, "source": "peft"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "a955182e-7443-4eeb-bde7-b1f855ec2128", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/peft/accelerate/deepspeed", "title": "DeepSpeed", "tokens": 5684, "retrieve_doc": true, "source": "peft"}, "hash": "a8f3a08892343bb16b602d1d372b58e4b913a6acb9e638cfd34b438f3febffe8", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "d3820256-7fc0-4dbf-b361-dcd054f2d829", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/peft/accelerate/deepspeed", "title": "DeepSpeed", "tokens": 5684, "retrieve_doc": true, "source": "peft"}, "hash": "1346aa36bba955fc7ed7f1cb1b20d8e1a2e6789a253b3904af584f588897aebd", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "c3be1601-192a-43aa-833e-509552a20eed", "node_type": "1", "metadata": {}, "hash": "333b2d0480bf207e89fa8b7f0c1af185fd2978f43842c92fc9022bcc486ac57d", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 15955, "end_char_idx": 18828, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
```yml
compute_environment: LOCAL_MACHINE
deepspeed_config:
  gradient_accumulation_steps: 1
  gradient_clipping: 1.0
  offload_optimizer_device: cpu
  offload_param_device: cpu
  zero3_init_flag: true
  zero3_save_16bit_model: true
  zero_stage: 3
distributed_type: DEEPSPEED
downcast_bf16: 'no'
dynamo_backend: 'NO'
fsdp_config: {}
machine_rank: 0
main_training_function: main
megatron_lm_config: {}
mixed_precision: 'no'
num_machines: 1
num_processes: 1
rdzv_backend: static
same_network: true
use_cpu: false
```

## The important parts

Let's dive a little deeper into the script so you can see what's going on, and understand how it works.

Within the [`main`](https://github.com/huggingface/peft/blob/2822398fbe896f25d4dac5e468624dc5fd65a51b/examples/conditional_generation/peft_lora_seq2seq_accelerate_ds_zero3_offload.py#L103) function, the script creates an [`~accelerate.Accelerator`] class to initialize all the necessary requirements for distributed training.

<Tip>

💡 Feel free to change the model and dataset inside the `main` function. If your dataset format is different from the one in the script, you may also need to write your own preprocessing function. 

</Tip>

The script also creates a configuration for the 🤗 PEFT method you're using, which in this case, is LoRA. The [`LoraConfig`] specifies the task type and important parameters such as the dimension of the low-rank matrices, the matrices scaling factor, and the dropout probability of the LoRA layers. If you want to use a different 🤗 PEFT method, make sure you replace `LoraConfig` with the appropriate [class](../package_reference/tuners).

```diff
 def main():
+    accelerator = Accelerator()
     model_name_or_path = "facebook/bart-large"
     dataset_name = "twitter_complaints"
+    peft_config = LoraConfig(
         task_type=TaskType.SEQ_2_SEQ_LM, inference_mode=False, r=8, lora_alpha=32, lora_dropout=0.1
     )
```

Throughout the script, you'll see the [`~accelerate.Accelerator.main_process_first`] and [`~accelerate.Accelerator.wait_for_everyone`] functions which help control and synchronize when processes are executed.

The [`get_peft_model`] function takes a base model and the [`peft_config`] you prepared earlier to create a [`PeftModel`]:

```diff
  model = AutoModelForSeq2SeqLM.from_pretrained(model_name_or_path)
+ model = get_peft_model(model, peft_config)
```

Pass all the relevant training objects to 🤗 Accelerate's [`~accelerate.Accelerator.prepare`] which makes sure everything is ready for training:

```py
model, train_dataloader, eval_dataloader, test_dataloader, optimizer, lr_scheduler = accelerator.prepare(
    model, train_dataloader, eval_dataloader, test_dataloader, optimizer, lr_scheduler
)
```

The next bit of code checks whether the DeepSpeed plugin is used in the `Accelerator`, and if the plugin exists, then we check if we are using ZeRO-3.


key: _node_content
string_value:
{"id_": "c3be1601-192a-43aa-833e-509552a20eed", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/peft/accelerate/deepspeed", "title": "DeepSpeed", "tokens": 5684, "retrieve_doc": true, "source": "peft"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "a955182e-7443-4eeb-bde7-b1f855ec2128", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/peft/accelerate/deepspeed", "title": "DeepSpeed", "tokens": 5684, "retrieve_doc": true, "source": "peft"}, "hash": "a8f3a08892343bb16b602d1d372b58e4b913a6acb9e638cfd34b438f3febffe8", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "219ad062-1c4a-45b0-955b-1898daa6e5b2", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/peft/accelerate/deepspeed", "title": "DeepSpeed", "tokens": 5684, "retrieve_doc": true, "source": "peft"}, "hash": "d4dd8b9cfaeb99206930bec67a5284a6337ce7b320ec96f529ce966c339b9e0b", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "57c0b56a-3be5-43dd-86d5-533b194ceb5c", "node_type": "1", "metadata": {}, "hash": "ddbacb08848a001afbdaca34feff51d6ed7b926aa72728a0ab22536f19ffec13", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 17246, "end_char_idx": 19976, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
The [`LoraConfig`] specifies the task type and important parameters such as the dimension of the low-rank matrices, the matrices scaling factor, and the dropout probability of the LoRA layers. If you want to use a different 🤗 PEFT method, make sure you replace `LoraConfig` with the appropriate [class](../package_reference/tuners).

```diff
 def main():
+    accelerator = Accelerator()
     model_name_or_path = "facebook/bart-large"
     dataset_name = "twitter_complaints"
+    peft_config = LoraConfig(
         task_type=TaskType.SEQ_2_SEQ_LM, inference_mode=False, r=8, lora_alpha=32, lora_dropout=0.1
     )
```

Throughout the script, you'll see the [`~accelerate.Accelerator.main_process_first`] and [`~accelerate.Accelerator.wait_for_everyone`] functions which help control and synchronize when processes are executed.

The [`get_peft_model`] function takes a base model and the [`peft_config`] you prepared earlier to create a [`PeftModel`]:

```diff
  model = AutoModelForSeq2SeqLM.from_pretrained(model_name_or_path)
+ model = get_peft_model(model, peft_config)
```

Pass all the relevant training objects to 🤗 Accelerate's [`~accelerate.Accelerator.prepare`] which makes sure everything is ready for training:

```py
model, train_dataloader, eval_dataloader, test_dataloader, optimizer, lr_scheduler = accelerator.prepare(
    model, train_dataloader, eval_dataloader, test_dataloader, optimizer, lr_scheduler
)
```

The next bit of code checks whether the DeepSpeed plugin is used in the `Accelerator`, and if the plugin exists, then we check if we are using ZeRO-3. This conditional flag is used when calling `generate` function call during inference for syncing GPUs when the model parameters are sharded:

```py
is_ds_zero_3 = False
if getattr(accelerator.state, "deepspeed_plugin", None):
    is_ds_zero_3 = accelerator.state.deepspeed_plugin.zero_stage == 3
```

Inside the training loop, the usual `loss.backward()` is replaced by 🤗 Accelerate's [`~accelerate.Accelerator.backward`] which uses the correct `backward()` method based on your configuration:

```diff
  for epoch in range(num_epochs):
      with TorchTracemalloc() as tracemalloc:
          model.train()
          total_loss = 0
          for step, batch in enumerate(tqdm(train_dataloader)):
              outputs = model(**batch)
              loss = outputs.loss
              total_loss += loss.detach().float()
+             accelerator.backward(loss)
              optimizer.step()
              lr_scheduler.step()
              optimizer.zero_grad()
```

That is all! The rest of the script handles the training loop, evaluation, and even pushes it to the Hub for you.

## Train

Run the following command to launch the training script.


key: _node_content
string_value:
{"id_": "57c0b56a-3be5-43dd-86d5-533b194ceb5c", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/peft/accelerate/deepspeed", "title": "DeepSpeed", "tokens": 5684, "retrieve_doc": true, "source": "peft"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "a955182e-7443-4eeb-bde7-b1f855ec2128", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/peft/accelerate/deepspeed", "title": "DeepSpeed", "tokens": 5684, "retrieve_doc": true, "source": "peft"}, "hash": "a8f3a08892343bb16b602d1d372b58e4b913a6acb9e638cfd34b438f3febffe8", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "c3be1601-192a-43aa-833e-509552a20eed", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/peft/accelerate/deepspeed", "title": "DeepSpeed", "tokens": 5684, "retrieve_doc": true, "source": "peft"}, "hash": "78f5401e4f6de8ba06a71e1ef8e95e632b61b3a9efb458408e019028eeb580a5", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "e6f097aa-031f-4028-8f18-806775b50423", "node_type": "1", "metadata": {}, "hash": "954d41d9139549f58ae1ed83463ac48ac0bb86ef8e0817ee758c8334aca8a97c", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 18829, "end_char_idx": 21931, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
This conditional flag is used when calling `generate` function call during inference for syncing GPUs when the model parameters are sharded:

```py
is_ds_zero_3 = False
if getattr(accelerator.state, "deepspeed_plugin", None):
    is_ds_zero_3 = accelerator.state.deepspeed_plugin.zero_stage == 3
```

Inside the training loop, the usual `loss.backward()` is replaced by 🤗 Accelerate's [`~accelerate.Accelerator.backward`] which uses the correct `backward()` method based on your configuration:

```diff
  for epoch in range(num_epochs):
      with TorchTracemalloc() as tracemalloc:
          model.train()
          total_loss = 0
          for step, batch in enumerate(tqdm(train_dataloader)):
              outputs = model(**batch)
              loss = outputs.loss
              total_loss += loss.detach().float()
+             accelerator.backward(loss)
              optimizer.step()
              lr_scheduler.step()
              optimizer.zero_grad()
```

That is all! The rest of the script handles the training loop, evaluation, and even pushes it to the Hub for you.

## Train

Run the following command to launch the training script. Earlier, you saved the configuration file to `ds_zero3_cpu.yaml`, so you'll need to pass the path to the launcher with the `--config_file` argument like this:

```bash
accelerate launch --config_file ds_zero3_cpu.yaml examples/peft_lora_seq2seq_accelerate_ds_zero3_offload.py
```

You'll see some output logs that track memory usage during training, and once it's completed, the script returns the accuracy and compares the predictions to the labels:

```bash
GPU Memory before entering the train : 1916
GPU Memory consumed at the end of the train (end-begin): 66
GPU Peak Memory consumed during the train (max-begin): 7488
GPU Total Peak Memory consumed during the train (max): 9404
CPU Memory before entering the train : 19411
CPU Memory consumed at the end of the train (end-begin): 0
CPU Peak Memory consumed during the train (max-begin): 0
CPU Total Peak Memory consumed during the train (max): 19411
epoch=4: train_ppl=tensor(1.0705, device='cuda:0') train_epoch_loss=tensor(0.0681, device='cuda:0')
100%|████████████████████████████████████████████████████████████████████████████████████████████| 7/7 [00:27<00:00,  3.92s/it]
GPU Memory before entering the eval : 1982
GPU Memory consumed at the end of the eval (end-begin): -66
GPU Peak Memory consumed during the eval (max-begin): 672
GPU Total Peak Memory consumed during the eval (max): 2654
CPU Memory before entering the eval : 19411
CPU Memory consumed at the end of the eval (end-begin): 0
CPU Peak Memory consumed during the eval (max-begin): 0
CPU Total Peak Memory consumed during the eval (max): 19411
accuracy=100.0
eval_preds[:10]=['no complaint', 'no complaint', 'complaint', 'complaint', 'no complaint', 'no complaint', 'no complaint', 'complaint', 'complaint', 'no complaint']
dataset['train'][label_column][:10]=['no complaint', 'no complaint', 'complaint', 'complaint', 'no complaint', 'no complaint', 'no complaint', 'complaint', 'complaint', 'no complaint']
```

# Caveats
1.


key: _node_content
string_value:
{"id_": "e6f097aa-031f-4028-8f18-806775b50423", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/peft/accelerate/deepspeed", "title": "DeepSpeed", "tokens": 5684, "retrieve_doc": true, "source": "peft"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "a955182e-7443-4eeb-bde7-b1f855ec2128", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/peft/accelerate/deepspeed", "title": "DeepSpeed", "tokens": 5684, "retrieve_doc": true, "source": "peft"}, "hash": "a8f3a08892343bb16b602d1d372b58e4b913a6acb9e638cfd34b438f3febffe8", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "57c0b56a-3be5-43dd-86d5-533b194ceb5c", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/peft/accelerate/deepspeed", "title": "DeepSpeed", "tokens": 5684, "retrieve_doc": true, "source": "peft"}, "hash": "16f2c1cc245bd4d9767cacba11ed1f03ce8386ba7cc3a0ad1b47f61c4eb6628c", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 21932, "end_char_idx": 22373, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
Merging when using PEFT and DeepSpeed is currently unsupported and will raise error.
2. When using CPU offloading, the major gains from using PEFT to shrink the optimizer states and gradients to that of the adapter weights would be realized on CPU RAM and there won't be savings with respect to GPU memory.
3. DeepSpeed Stage 3 and qlora when used with CPU offloading leads to more GPU memory usage when compared to disabling CPU offloading.


key: _node_content
string_value:
{"id_": "fd19470a-c232-49bc-9b4e-21397c58138c", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/peft/accelerate/fsdp", "title": "Fully Sharded Data Parallel", "tokens": 3543, "retrieve_doc": true, "source": "peft"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "e7f67aa5-3f03-4f0f-a66f-26e86d4c200d", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/peft/accelerate/fsdp", "title": "Fully Sharded Data Parallel", "tokens": 3543, "retrieve_doc": true, "source": "peft"}, "hash": "f24545eac4680c6e541d1631f4209b1d76c48e7e1c0c985a3760d14bbf1cbe46", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "4c0ea43b-1010-4f4f-88b3-88a1f7f335ed", "node_type": "1", "metadata": {}, "hash": "bb17d6578658b265b0a8a1bee48436ebc259a182983d03744f5e6424db30a693", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 0, "end_char_idx": 1852, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
<!--⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be
rendered properly in your Markdown viewer.
-->

# Fully Sharded Data Parallel

[Fully sharded data parallel](https://pytorch.org/docs/stable/fsdp.html) (FSDP) is developed for distributed training of large pretrained models up to 1T parameters. FSDP achieves this by sharding the model parameters, gradients, and optimizer states across data parallel processes and it can also offload sharded model parameters to a CPU. The memory efficiency afforded by FSDP allows you to scale training to larger batch or model sizes.

Both of these features are supported in 🤗 Accelerate, and you can use them with 🤗 PEFT. 

# Use PEFT and FSDP
This section of guide will help you learn how to use our DeepSpeed [training script](https://github.com/huggingface/peft/blob/main/examples/sft/train.py) for performing SFT. You'll configure the script to do SFT (supervised fine-tuning) of Llama-70B model with LoRA and FSDP on 8xH100 80GB GPUs on a single machine. You can configure it to scale to multiple machines by changing the accelerate config.

## Configuration

Start by running the following command to [create a FSDP configuration file](https://huggingface.co/docs/accelerate/quicktour#launching-your-distributed-script) with 🤗 Accelerate. The `--config_file` flag allows you to save the configuration file to a specific location, otherwise it is saved as a `default_config.yaml` file in the 🤗 Accelerate cache.

The configuration file is used to set the default options when you launch the training script.

```bash
accelerate config --config_file fsdp_config.yaml
```

You'll be asked a few questions about your setup, and configure the following arguments. In this example, you'll answer the questionnaire as shown in the image below.


key: _node_content
string_value:
{"id_": "4c0ea43b-1010-4f4f-88b3-88a1f7f335ed", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/peft/accelerate/fsdp", "title": "Fully Sharded Data Parallel", "tokens": 3543, "retrieve_doc": true, "source": "peft"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "e7f67aa5-3f03-4f0f-a66f-26e86d4c200d", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/peft/accelerate/fsdp", "title": "Fully Sharded Data Parallel", "tokens": 3543, "retrieve_doc": true, "source": "peft"}, "hash": "f24545eac4680c6e541d1631f4209b1d76c48e7e1c0c985a3760d14bbf1cbe46", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "fd19470a-c232-49bc-9b4e-21397c58138c", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/peft/accelerate/fsdp", "title": "Fully Sharded Data Parallel", "tokens": 3543, "retrieve_doc": true, "source": "peft"}, "hash": "5d95bc72532cc471552246006875ed2fdfa823ef0aeac28046f394eba56d5475", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "2dfb8639-8667-492a-86ff-10e2400c4398", "node_type": "1", "metadata": {}, "hash": "f68c55ae1bbf2d0abd713fe743e242a446f0c32b8f02ca09b48aae70a30dec30", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 166, "end_char_idx": 4303, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
-->

# Fully Sharded Data Parallel

[Fully sharded data parallel](https://pytorch.org/docs/stable/fsdp.html) (FSDP) is developed for distributed training of large pretrained models up to 1T parameters. FSDP achieves this by sharding the model parameters, gradients, and optimizer states across data parallel processes and it can also offload sharded model parameters to a CPU. The memory efficiency afforded by FSDP allows you to scale training to larger batch or model sizes.

Both of these features are supported in 🤗 Accelerate, and you can use them with 🤗 PEFT. 

# Use PEFT and FSDP
This section of guide will help you learn how to use our DeepSpeed [training script](https://github.com/huggingface/peft/blob/main/examples/sft/train.py) for performing SFT. You'll configure the script to do SFT (supervised fine-tuning) of Llama-70B model with LoRA and FSDP on 8xH100 80GB GPUs on a single machine. You can configure it to scale to multiple machines by changing the accelerate config.

## Configuration

Start by running the following command to [create a FSDP configuration file](https://huggingface.co/docs/accelerate/quicktour#launching-your-distributed-script) with 🤗 Accelerate. The `--config_file` flag allows you to save the configuration file to a specific location, otherwise it is saved as a `default_config.yaml` file in the 🤗 Accelerate cache.

The configuration file is used to set the default options when you launch the training script.

```bash
accelerate config --config_file fsdp_config.yaml
```

You'll be asked a few questions about your setup, and configure the following arguments. In this example, you'll answer the questionnaire as shown in the image below.
<div class="flex justify-center">
    <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/peft/fsdp-peft-config.png"/>
</div>
<small>Creating Accelerate's config to use FSDP</small>

Once this is done, the corresponding config should look like below and you can find it in config folder at [fsdp_config.yaml](https://github.com/huggingface/peft/blob/main/examples/sft/configs/fsdp_config.yaml):

```yml
compute_environment: LOCAL_MACHINE
debug: false
distributed_type: FSDP
downcast_bf16: 'no'
fsdp_config:
  fsdp_auto_wrap_policy: TRANSFORMER_BASED_WRAP
  fsdp_backward_prefetch: BACKWARD_PRE
  fsdp_cpu_ram_efficient_loading: true
  fsdp_forward_prefetch: false
  fsdp_offload_params: false
  fsdp_sharding_strategy: FULL_SHARD
  fsdp_state_dict_type: SHARDED_STATE_DICT
  fsdp_sync_module_states: true
  fsdp_use_orig_params: false
machine_rank: 0
main_training_function: main
mixed_precision: bf16
num_machines: 1
num_processes: 8
rdzv_backend: static
same_network: true
tpu_env: []
tpu_use_cluster: false
tpu_use_sudo: false
use_cpu: false
```

## Launch command

The launch command is available at [run_peft_fsdp.sh](https://github.com/huggingface/peft/blob/main/examples/sft/run_peft_fsdp.sh) and it is also shown below:
```bash
accelerate launch --config_file "configs/fsdp_config.yaml"  train.py \
--seed 100 \
--model_name_or_path "meta-llama/Llama-2-70b-hf" \
--dataset_name "smangrul/ultrachat-10k-chatml" \
--chat_template_format "chatml" \
--add_special_tokens False \
--append_concat_token False \
--splits "train,test" \
--max_seq_len 2048 \
--num_train_epochs 1 \
--logging_steps 5 \
--log_level "info" \
--logging_strategy "steps" \
--evaluation_strategy "epoch" \
--save_strategy "epoch" \
--push_to_hub \
--hub_private_repo True \
--hub_strategy "every_save" \
--bf16 True \
--packing True \
--learning_rate 1e-4 \
--lr_scheduler_type "cosine" \
--weight_decay 1e-4 \
--warmup_ratio 0.0 \
--max_grad_norm 1.0 \
--output_dir "llama-sft-lora-fsdp" \
--per_device_train_batch_size 8 \
--per_device_eval_batch_size 8 \
--gradient_accumulation_steps 4 \
--gradient_checkpointing True \
--use_reentrant False \
--dataset_text_field "content" \
--use_flash_attn True \
--use_peft_lora True \
--lora_r 8 \
--lora_alpha 16 \
--lora_dropout 0.1 \
--lora_target_modules "all-linear" \
--use_4bit_quantization False
```

Notice that we are using LoRA with  rank=8, alpha=16 and targeting all linear layers.


key: _node_content
string_value:
{"id_": "2dfb8639-8667-492a-86ff-10e2400c4398", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/peft/accelerate/fsdp", "title": "Fully Sharded Data Parallel", "tokens": 3543, "retrieve_doc": true, "source": "peft"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "e7f67aa5-3f03-4f0f-a66f-26e86d4c200d", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/peft/accelerate/fsdp", "title": "Fully Sharded Data Parallel", "tokens": 3543, "retrieve_doc": true, "source": "peft"}, "hash": "f24545eac4680c6e541d1631f4209b1d76c48e7e1c0c985a3760d14bbf1cbe46", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "4c0ea43b-1010-4f4f-88b3-88a1f7f335ed", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/peft/accelerate/fsdp", "title": "Fully Sharded Data Parallel", "tokens": 3543, "retrieve_doc": true, "source": "peft"}, "hash": "37dddc47a5e41d7a60faf0694254323dea6172486df629c21b6d1707de2aaba7", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "8e6a0b9e-6225-40ef-9833-ac4312da5734", "node_type": "1", "metadata": {}, "hash": "b970ca0032147316c61e405ff862758072b30b22c85f13ba71a40ee71c5634a8", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 4304, "end_char_idx": 7064, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
We are passing the FSDP config file and finetuning the 70B Llama model on a subset of the [ultrachat dataset](https://huggingface.co/datasets/HuggingFaceH4/ultrachat_200k).

## The important parts

Let's dive a little deeper into the script so you can see what's going on, and understand how it works.

The first thing to know is that the script uses FSDP for distributed training as the FSDP config has been passed. The `SFTTrainer` class handles all the heavy lifting of creating PEFT model using the peft config that is passed. After that when you call `trainer.train()`, Trainer internally uses 🤗 Accelerate to prepare model, optimizer and trainer using the FSDP config to create FSDP wrapped model which is then trained. The main code snippet is below:

```python
# trainer
trainer = SFTTrainer(
    model=model,
    tokenizer=tokenizer,
    args=training_args,
    train_dataset=train_dataset,
    eval_dataset=eval_dataset,
    peft_config=peft_config,
    packing=data_args.packing,
    dataset_kwargs={
        "append_concat_token": data_args.append_concat_token,
        "add_special_tokens": data_args.add_special_tokens,
    },
    dataset_text_field=data_args.dataset_text_field,
    max_seq_length=data_args.max_seq_length,
)
trainer.accelerator.print(f"{trainer.model}")
if model_args.use_peft_lora:
    # handle PEFT+FSDP case
    trainer.model.print_trainable_parameters()
    if getattr(trainer.accelerator.state, "fsdp_plugin", None):
        from peft.utils.other import fsdp_auto_wrap_policy

        fsdp_plugin = trainer.accelerator.state.fsdp_plugin
        fsdp_plugin.auto_wrap_policy = fsdp_auto_wrap_policy(trainer.model)

# train
checkpoint = None
if training_args.resume_from_checkpoint is not None:
    checkpoint = training_args.resume_from_checkpoint
trainer.train(resume_from_checkpoint=checkpoint)

# saving final model
if trainer.is_fsdp_enabled:
    trainer.accelerator.state.fsdp_plugin.set_state_dict_type("FULL_STATE_DICT")
trainer.save_model()
```


Here, one main thing to note currently when using FSDP with PEFT is that `use_orig_params` needs to be `False` to realize GPU memory savings. Due to `use_orig_params=False`, the auto wrap policy for FSDP needs to change so that trainable and non-trainable parameters are wrapped separately. This is done by the code snippt below which uses the util function `fsdp_auto_wrap_policy` from PEFT:

```
if getattr(trainer.accelerator.state, "fsdp_plugin", None):
    from peft.utils.other import fsdp_auto_wrap_policy

    fsdp_plugin = trainer.accelerator.state.fsdp_plugin
    fsdp_plugin.auto_wrap_policy = fsdp_auto_wrap_policy(trainer.model)
```

## Memory usage

In the above example, the memory consumed per GPU is  72-80 GB (90-98%) as seen in the screenshot below.


key: _node_content
string_value:
{"id_": "8e6a0b9e-6225-40ef-9833-ac4312da5734", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/peft/accelerate/fsdp", "title": "Fully Sharded Data Parallel", "tokens": 3543, "retrieve_doc": true, "source": "peft"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "e7f67aa5-3f03-4f0f-a66f-26e86d4c200d", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/peft/accelerate/fsdp", "title": "Fully Sharded Data Parallel", "tokens": 3543, "retrieve_doc": true, "source": "peft"}, "hash": "f24545eac4680c6e541d1631f4209b1d76c48e7e1c0c985a3760d14bbf1cbe46", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "2dfb8639-8667-492a-86ff-10e2400c4398", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/peft/accelerate/fsdp", "title": "Fully Sharded Data Parallel", "tokens": 3543, "retrieve_doc": true, "source": "peft"}, "hash": "0974b68e64515697838868161597a638ee2ffa3605321584584a6444759c1614", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "adefef1a-8c07-4d95-b819-77f16adeed0e", "node_type": "1", "metadata": {}, "hash": "c23ca357ef2216764e91b73579ed062d257eedbf16a99cd37abcdf66c112ad64", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 6296, "end_char_idx": 8497, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
Here, one main thing to note currently when using FSDP with PEFT is that `use_orig_params` needs to be `False` to realize GPU memory savings. Due to `use_orig_params=False`, the auto wrap policy for FSDP needs to change so that trainable and non-trainable parameters are wrapped separately. This is done by the code snippt below which uses the util function `fsdp_auto_wrap_policy` from PEFT:

```
if getattr(trainer.accelerator.state, "fsdp_plugin", None):
    from peft.utils.other import fsdp_auto_wrap_policy

    fsdp_plugin = trainer.accelerator.state.fsdp_plugin
    fsdp_plugin.auto_wrap_policy = fsdp_auto_wrap_policy(trainer.model)
```

## Memory usage

In the above example, the memory consumed per GPU is  72-80 GB (90-98%) as seen in the screenshot below. The slight increase in GPU memory at the end is when saving the model using `FULL_STATE_DICT` state dict type instead of the `SHARDED_STATE_DICT` so that the model has adapter weights that can be loaded normally with `from_pretrained` method during inference:

<div class="flex justify-center">
    <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/peft/peft_fsdp_mem_usage.png"/>
</div>
<small>GPU memory usage for the training run</small>

# Use PEFT QLoRA and FSDP for finetuning large models on multiple GPUs

In this section, we will look at how to use QLoRA and FSDP for finetuning 70B llama model on 2X24GB GPUs. [Answer.AI](https://www.answer.ai/) in collaboration with bitsandbytes and Hugging Face 🤗 open sourced code enabling the usage of FSDP+QLoRA and explained the whole process in their insightful blogpost [You can now train a 70b language model at home](https://www.answer.ai/posts/2024-03-06-fsdp-qlora.html). This is now integrated in Hugging Face ecosystem. 

For this, we first need `bitsandbytes>=0.43.0`, `accelerate>=0.28.0`, `transformers>4.38.2`, `trl>0.7.11` and `peft>0.9.0`. We need to set `fsdp_cpu_ram_efficient_loading=true`, `fsdp_use_orig_params=false` and `fsdp_offload_params=true`(cpu offloading) when using Accelerate config. When not using accelerate launcher, you can alternately set the environment variable `export FSDP_CPU_RAM_EFFICIENT_LOADING=true`.


key: _node_content
string_value:
{"id_": "adefef1a-8c07-4d95-b819-77f16adeed0e", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/peft/accelerate/fsdp", "title": "Fully Sharded Data Parallel", "tokens": 3543, "retrieve_doc": true, "source": "peft"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "e7f67aa5-3f03-4f0f-a66f-26e86d4c200d", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/peft/accelerate/fsdp", "title": "Fully Sharded Data Parallel", "tokens": 3543, "retrieve_doc": true, "source": "peft"}, "hash": "f24545eac4680c6e541d1631f4209b1d76c48e7e1c0c985a3760d14bbf1cbe46", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "8e6a0b9e-6225-40ef-9833-ac4312da5734", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/peft/accelerate/fsdp", "title": "Fully Sharded Data Parallel", "tokens": 3543, "retrieve_doc": true, "source": "peft"}, "hash": "76a6a52b696610e53a5e88ba616d38c934ab3559b2a6c9e5319b39b6b0ebd64f", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "affe674b-31d1-4257-ac7c-f2ad116e4068", "node_type": "1", "metadata": {}, "hash": "e076b03ce0e4933675f199d10e14388b2ad84892cbad3c37a0ac77d73b5ab138", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 7065, "end_char_idx": 11159, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
The slight increase in GPU memory at the end is when saving the model using `FULL_STATE_DICT` state dict type instead of the `SHARDED_STATE_DICT` so that the model has adapter weights that can be loaded normally with `from_pretrained` method during inference:

<div class="flex justify-center">
    <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/peft/peft_fsdp_mem_usage.png"/>
</div>
<small>GPU memory usage for the training run</small>

# Use PEFT QLoRA and FSDP for finetuning large models on multiple GPUs

In this section, we will look at how to use QLoRA and FSDP for finetuning 70B llama model on 2X24GB GPUs. [Answer.AI](https://www.answer.ai/) in collaboration with bitsandbytes and Hugging Face 🤗 open sourced code enabling the usage of FSDP+QLoRA and explained the whole process in their insightful blogpost [You can now train a 70b language model at home](https://www.answer.ai/posts/2024-03-06-fsdp-qlora.html). This is now integrated in Hugging Face ecosystem. 

For this, we first need `bitsandbytes>=0.43.0`, `accelerate>=0.28.0`, `transformers>4.38.2`, `trl>0.7.11` and `peft>0.9.0`. We need to set `fsdp_cpu_ram_efficient_loading=true`, `fsdp_use_orig_params=false` and `fsdp_offload_params=true`(cpu offloading) when using Accelerate config. When not using accelerate launcher, you can alternately set the environment variable `export FSDP_CPU_RAM_EFFICIENT_LOADING=true`.  Here, we will be using accelerate config and below is the config which can be found at [fsdp_config_qlora.yaml](https://github.com/huggingface/peft/blob/main/examples/sft/configs/fsdp_config_qlora.yaml):

```yml
compute_environment: LOCAL_MACHINE                                                                                                                                           
debug: false                                                                                                                                                                 
distributed_type: FSDP
downcast_bf16: 'no'
fsdp_config:
  fsdp_auto_wrap_policy: TRANSFORMER_BASED_WRAP
  fsdp_backward_prefetch: BACKWARD_PRE
  fsdp_cpu_ram_efficient_loading: true
  fsdp_forward_prefetch: false
  fsdp_offload_params: true
  fsdp_sharding_strategy: FULL_SHARD
  fsdp_state_dict_type: SHARDED_STATE_DICT
  fsdp_sync_module_states: true
  fsdp_use_orig_params: false
machine_rank: 0
main_training_function: main
mixed_precision: 'no'
num_machines: 1
num_processes: 2
rdzv_backend: static
same_network: true
tpu_env: []
tpu_use_cluster: false
tpu_use_sudo: false
use_cpu: false
```

Launch command is given below which is available at [run_peft_qlora_fsdp.sh](https://github.com/huggingface/peft/blob/main/examples/sft/run_peft_qlora_fsdp.sh):
```
accelerate launch --config_file "configs/fsdp_config_qlora.yaml"  train.py \
--seed 100 \
--model_name_or_path "meta-llama/Llama-2-70b-hf" \
--dataset_name "smangrul/ultrachat-10k-chatml" \
--chat_template_format "chatml" \
--add_special_tokens False \
--append_concat_token False \
--splits "train,test" \
--max_seq_len 2048 \
--num_train_epochs 1 \
--logging_steps 5 \
--log_level "info" \
--logging_strategy "steps" \
--evaluation_strategy "epoch" \
--save_strategy "epoch" \
--push_to_hub \
--hub_private_repo True \
--hub_strategy "every_save" \
--bf16 True \
--packing True \
--learning_rate 1e-4 \
--lr_scheduler_type "cosine" \
--weight_decay 1e-4 \
--warmup_ratio 0.0 \
--max_grad_norm 1.0 \
--output_dir "llama-sft-qlora-fsdp" \
--per_device_train_batch_size 2 \
--per_device_eval_batch_size 2 \
--gradient_accumulation_steps 2 \
--gradient_checkpointing True \
--use_reentrant True \
--dataset_text_field "content" \
--use_flash_attn True \
--use_peft_lora True \
--lora_r 8 \
--lora_alpha 16 \
--lora_dropout 0.1 \
--lora_target_modules "all-linear" \
--use_4bit_quantization True \
--use_nested_quant True \
--bnb_4bit_compute_dtype "bfloat16" \
--bnb_4bit_quant_storage_dtype "bfloat16"
```

Notice the new argument being passed, `bnb_4bit_quant_storage_dtype`, which denotes the data type for packing the 4-bit parameters.


key: _node_content
string_value:
{"id_": "affe674b-31d1-4257-ac7c-f2ad116e4068", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/peft/accelerate/fsdp", "title": "Fully Sharded Data Parallel", "tokens": 3543, "retrieve_doc": true, "source": "peft"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "e7f67aa5-3f03-4f0f-a66f-26e86d4c200d", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/peft/accelerate/fsdp", "title": "Fully Sharded Data Parallel", "tokens": 3543, "retrieve_doc": true, "source": "peft"}, "hash": "f24545eac4680c6e541d1631f4209b1d76c48e7e1c0c985a3760d14bbf1cbe46", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "adefef1a-8c07-4d95-b819-77f16adeed0e", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/peft/accelerate/fsdp", "title": "Fully Sharded Data Parallel", "tokens": 3543, "retrieve_doc": true, "source": "peft"}, "hash": "bf968998bf944d85afb9f716d0a9e62ce7b3f995eaf6a3e8608bd6c380b639db", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 11160, "end_char_idx": 13671, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
For example, when it is set to `bfloat16`, **16/4 = 4** 4-bit params are packed together post quantization. When using mixed precision training with `bfloat16`, `bnb_4bit_quant_storage_dtype` can be either `bfloat16` for pure `bfloat16` finetuning, or `float32` for automatic mixed precision (this consumes more GPU memory). When using mixed precision training with `float16`, `bnb_4bit_quant_storage_dtype` should be set to `float32` for stable automatic mixed precision training.

In terms of training code, the important code changes are: 

```diff
...

bnb_config = BitsAndBytesConfig(
    load_in_4bit=args.use_4bit_quantization,
    bnb_4bit_quant_type=args.bnb_4bit_quant_type,
    bnb_4bit_compute_dtype=compute_dtype,
    bnb_4bit_use_double_quant=args.use_nested_quant,
+   bnb_4bit_quant_storage=quant_storage_dtype,
)

...

model = AutoModelForCausalLM.from_pretrained(
    args.model_name_or_path,
    quantization_config=bnb_config,
    trust_remote_code=True,
    attn_implementation="flash_attention_2" if args.use_flash_attn else "eager",
+   torch_dtype=quant_storage_dtype or torch.float32,
)
```

Notice that `torch_dtype` for `AutoModelForCausalLM` is same as the `bnb_4bit_quant_storage` data type. That's it. Everything else is handled by Trainer and TRL.

## Memory usage

In the above example, the memory consumed per GPU is **19.6 GB** while CPU RAM usage is around **107 GB**. When disabling CPU offloading, the GPU memory usage is  **35.6 GB/ GPU**. Therefore, what took 16X80GB GPUs for full finetuning, 8X80GB GPUs with FSDP+LoRA, and a couple of 80GB GPUs with DDP+QLoRA, now requires 2X24GB GPUs. This makes finetuning of large models more accessible.

## More resources
You can also refer the [llama-recipes](https://github.com/facebookresearch/llama-recipes/?tab=readme-ov-file#fine-tuning) repo and [Getting started with Llama](https://llama.meta.com/get-started/#fine-tuning) guide on how to finetune using FSDP and PEFT.

## Caveats
1. Merging when using PEFT and FSDP is currently unsupported and will raise error.
2. Passing `modules_to_save` config parameter to is untested at present.
3. GPU Memory saving when using CPU Offloading is untested at present.
4. When using FSDP+QLoRA, `paged_adamw_8bit` currently results in an error when saving a checkpoint.
5. DoRA training with FSDP should work (albeit at lower speed than LoRA). If combined with bitsandbytes (QDoRA), 4-bit quantization should also work, but 8-bit quantization has known issues and is not recommended.


key: _node_content
string_value:
{"id_": "548832f3-2b94-4ee6-b939-d8527dbf110e", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/peft/tutorial/peft_integrations", "title": "PEFT integrations", "tokens": 1791, "retrieve_doc": true, "source": "peft"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "2a71f379-096e-4f75-9455-6162fc8ba2cb", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/peft/tutorial/peft_integrations", "title": "PEFT integrations", "tokens": 1791, "retrieve_doc": true, "source": "peft"}, "hash": "beee27f402e7f8e884ebb561a6e03714e8a0baab4c163b7e6c4b3756d4860328", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "408c1885-7ef3-40b1-9fbe-93a404a49476", "node_type": "1", "metadata": {}, "hash": "5879ce00922e12702e5d40196aa0b57c85504d5c8fe23ac53848b70dac520b27", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 0, "end_char_idx": 2588, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
# PEFT integrations

PEFT's practical benefits extends to other Hugging Face libraries like [Diffusers](https://hf.co/docs/diffusers) and [Transformers](https://hf.co/docs/transformers). One of the main benefits of PEFT is that an adapter file generated by a PEFT method is a lot smaller than the original model, which makes it super easy to manage and use multiple adapters. You can use one pretrained base model for multiple tasks by simply loading a new adapter finetuned for the task you're solving. Or you can combine multiple adapters with a text-to-image diffusion model to create new effects.

This tutorial will show you how PEFT can help you manage adapters in Diffusers and Transformers.

## Diffusers

Diffusers is a generative AI library for creating images and videos from text or images with diffusion models. LoRA is an especially popular training method for diffusion models because you can very quickly train and share diffusion models to generate images in new styles. To make it easier to use and try multiple LoRA models, Diffusers uses the PEFT library to help manage different adapters for inference.

For example, load a base model and then load the [artificialguybr/3DRedmond-V1](https://huggingface.co/artificialguybr/3DRedmond-V1) adapter for inference with the [`load_lora_weights`](https://huggingface.co/docs/diffusers/v0.24.0/en/api/loaders/lora#diffusers.loaders.LoraLoaderMixin.load_lora_weights) method. The `adapter_name` argument in the loading method is enabled by PEFT and allows you to set a name for the adapter so it is easier to reference.

```py
import torch
from diffusers import DiffusionPipeline

pipeline = DiffusionPipeline.from_pretrained(
    "stabilityai/stable-diffusion-xl-base-1.0", torch_dtype=torch.float16
).to("cuda")
pipeline.load_lora_weights(
    "peft-internal-testing/artificialguybr__3DRedmond-V1", 
    weight_name="3DRedmond-3DRenderStyle-3DRenderAF.safetensors", 
    adapter_name="3d"
)
image = pipeline("sushi rolls shaped like kawaii cat faces").images[0]
image
```

<div class="flex justify-center">
    <img src="https://huggingface.co/datasets/ybelkada/documentation-images/resolve/main/test-lora-diffusers.png"/>
</div>

Now let's try another cool LoRA model, [ostris/super-cereal-sdxl-lora](https://huggingface.co/ostris/super-cereal-sdxl-lora). All you need to do is load and name this new adapter with `adapter_name`, and use the [`set_adapters`](https://huggingface.co/docs/diffusers/api/loaders/unet#diffusers.loaders.UNet2DConditionLoadersMixin.set_adapters) method to set it as the currently active adapter.


key: _node_content
string_value:
{"id_": "408c1885-7ef3-40b1-9fbe-93a404a49476", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/peft/tutorial/peft_integrations", "title": "PEFT integrations", "tokens": 1791, "retrieve_doc": true, "source": "peft"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "2a71f379-096e-4f75-9455-6162fc8ba2cb", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/peft/tutorial/peft_integrations", "title": "PEFT integrations", "tokens": 1791, "retrieve_doc": true, "source": "peft"}, "hash": "beee27f402e7f8e884ebb561a6e03714e8a0baab4c163b7e6c4b3756d4860328", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "548832f3-2b94-4ee6-b939-d8527dbf110e", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/peft/tutorial/peft_integrations", "title": "PEFT integrations", "tokens": 1791, "retrieve_doc": true, "source": "peft"}, "hash": "66f34336f5392a473d5a36a286f0c143dcbaaededcc5fe9b089f9029ad34941c", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "7ab5296e-8baa-49ee-adcb-9306e9158f3f", "node_type": "1", "metadata": {}, "hash": "0a64614eb2ccf66d3526343f47936963cb04dacff61b0b8980cb94569d986f18", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 1438, "end_char_idx": 4387, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
The `adapter_name` argument in the loading method is enabled by PEFT and allows you to set a name for the adapter so it is easier to reference.

```py
import torch
from diffusers import DiffusionPipeline

pipeline = DiffusionPipeline.from_pretrained(
    "stabilityai/stable-diffusion-xl-base-1.0", torch_dtype=torch.float16
).to("cuda")
pipeline.load_lora_weights(
    "peft-internal-testing/artificialguybr__3DRedmond-V1", 
    weight_name="3DRedmond-3DRenderStyle-3DRenderAF.safetensors", 
    adapter_name="3d"
)
image = pipeline("sushi rolls shaped like kawaii cat faces").images[0]
image
```

<div class="flex justify-center">
    <img src="https://huggingface.co/datasets/ybelkada/documentation-images/resolve/main/test-lora-diffusers.png"/>
</div>

Now let's try another cool LoRA model, [ostris/super-cereal-sdxl-lora](https://huggingface.co/ostris/super-cereal-sdxl-lora). All you need to do is load and name this new adapter with `adapter_name`, and use the [`set_adapters`](https://huggingface.co/docs/diffusers/api/loaders/unet#diffusers.loaders.UNet2DConditionLoadersMixin.set_adapters) method to set it as the currently active adapter.

```py
pipeline.load_lora_weights(
    "ostris/super-cereal-sdxl-lora", 
    weight_name="cereal_box_sdxl_v1.safetensors", 
    adapter_name="cereal"
)
pipeline.set_adapters("cereal")
image = pipeline("sushi rolls shaped like kawaii cat faces").images[0]
image
```

<div class="flex justify-center">
    <img src="https://huggingface.co/datasets/ybelkada/documentation-images/resolve/main/test-lora-diffusers-2.png"/>
</div>

Finally, you can call the [`disable_lora`](https://huggingface.co/docs/diffusers/api/loaders/unet#diffusers.loaders.UNet2DConditionLoadersMixin.disable_lora) method to restore the base model.

```py
pipeline.disable_lora()
```

Learn more about how PEFT supports Diffusers in the [Inference with PEFT](https://huggingface.co/docs/diffusers/tutorials/using_peft_for_inference) tutorial.

## Transformers

🤗 [Transformers](https://hf.co/docs/transformers) is a collection of pretrained models for all types of tasks in all modalities. You can load these models for training or inference. Many of the models are large language models (LLMs), so it makes sense to integrate PEFT with Transformers to manage and train adapters.

Load a base pretrained model to train.

```py
from transformers import AutoModelForCausalLM

model = AutoModelForCausalLM.from_pretrained("facebook/opt-350m")
```

Next, add an adapter configuration to specify how to adapt the model parameters. Call the [`~PeftModel.add_adapter`] method to add the configuration to the base model.

```py
from peft import LoraConfig

peft_config = LoraConfig(
    lora_alpha=16,
    lora_dropout=0.1,
    r=64,
    bias="none",
    task_type="CAUSAL_LM"
)
model.add_adapter(peft_config)
```

Now you can train the model with Transformer's [`~transformers.Trainer`] class or whichever training framework you prefer.


key: _node_content
string_value:
{"id_": "7ab5296e-8baa-49ee-adcb-9306e9158f3f", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/peft/tutorial/peft_integrations", "title": "PEFT integrations", "tokens": 1791, "retrieve_doc": true, "source": "peft"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "2a71f379-096e-4f75-9455-6162fc8ba2cb", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/peft/tutorial/peft_integrations", "title": "PEFT integrations", "tokens": 1791, "retrieve_doc": true, "source": "peft"}, "hash": "beee27f402e7f8e884ebb561a6e03714e8a0baab4c163b7e6c4b3756d4860328", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "408c1885-7ef3-40b1-9fbe-93a404a49476", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/peft/tutorial/peft_integrations", "title": "PEFT integrations", "tokens": 1791, "retrieve_doc": true, "source": "peft"}, "hash": "f2987d875c9e1d26ed7684beb437c0472c93df5892125fd809edb239ae2ab68a", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "9de4bac2-c8ba-4646-92be-5be6f602e305", "node_type": "1", "metadata": {}, "hash": "cfd468203abad5001477ccee51bab74472fb516e9cd4d90d4c8650b0fb64f6a6", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 3208, "end_char_idx": 6099, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
```py
pipeline.disable_lora()
```

Learn more about how PEFT supports Diffusers in the [Inference with PEFT](https://huggingface.co/docs/diffusers/tutorials/using_peft_for_inference) tutorial.

## Transformers

🤗 [Transformers](https://hf.co/docs/transformers) is a collection of pretrained models for all types of tasks in all modalities. You can load these models for training or inference. Many of the models are large language models (LLMs), so it makes sense to integrate PEFT with Transformers to manage and train adapters.

Load a base pretrained model to train.

```py
from transformers import AutoModelForCausalLM

model = AutoModelForCausalLM.from_pretrained("facebook/opt-350m")
```

Next, add an adapter configuration to specify how to adapt the model parameters. Call the [`~PeftModel.add_adapter`] method to add the configuration to the base model.

```py
from peft import LoraConfig

peft_config = LoraConfig(
    lora_alpha=16,
    lora_dropout=0.1,
    r=64,
    bias="none",
    task_type="CAUSAL_LM"
)
model.add_adapter(peft_config)
```

Now you can train the model with Transformer's [`~transformers.Trainer`] class or whichever training framework you prefer.

To use the newly trained model for inference, the [`~transformers.AutoModel`] class uses PEFT on the backend to load the adapter weights and configuration file into a base pretrained model.

```py
from transformers import AutoModelForCausalLM

model = AutoModelForCausalLM.from_pretrained("peft-internal-testing/opt-350m-lora")
```

Alternatively, you can use transformers [Pipelines](https://huggingface.co/docs/transformers/en/main_classes/pipelines) to load the model for conveniently running inference:

```py
from transformers import pipeline

model = pipeline("text-generation", "peft-internal-testing/opt-350m-lora")
print(model("Hello World"))
```

If you're interested in comparing or using more than one adapter, you can call the [`~PeftModel.add_adapter`] method to add the adapter configuration to the base model. The only requirement is the adapter type must be the same (you can't mix a LoRA and LoHa adapter).

```py
from transformers import AutoModelForCausalLM
from peft import LoraConfig

model = AutoModelForCausalLM.from_pretrained("facebook/opt-350m")
model.add_adapter(lora_config_1, adapter_name="adapter_1")
```

Call [`~PeftModel.add_adapter`] again to attach a new adapter to the base model.

```py
model.add_adapter(lora_config_2, adapter_name="adapter_2")
```

Then you can use [`~PeftModel.set_adapter`] to set the currently active adapter.

```py
model.set_adapter("adapter_1")
output = model.generate(**inputs)
print(tokenizer.decode(output_disabled[0], skip_special_tokens=True))
```

To disable the adapter, call the [disable_adapters](https://github.com/huggingface/transformers/blob/4e3490f79b40248c53ee54365a9662611e880892/src/transformers/integrations/peft.py#L313) method.


key: _node_content
string_value:
{"id_": "9de4bac2-c8ba-4646-92be-5be6f602e305", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/peft/tutorial/peft_integrations", "title": "PEFT integrations", "tokens": 1791, "retrieve_doc": true, "source": "peft"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "2a71f379-096e-4f75-9455-6162fc8ba2cb", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/peft/tutorial/peft_integrations", "title": "PEFT integrations", "tokens": 1791, "retrieve_doc": true, "source": "peft"}, "hash": "beee27f402e7f8e884ebb561a6e03714e8a0baab4c163b7e6c4b3756d4860328", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "7ab5296e-8baa-49ee-adcb-9306e9158f3f", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/peft/tutorial/peft_integrations", "title": "PEFT integrations", "tokens": 1791, "retrieve_doc": true, "source": "peft"}, "hash": "47d2b9d1f6b405839931f407cd7c0000863228ba0043bdd257995b73f1b19c54", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 4580, "end_char_idx": 6480, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
```py
from transformers import AutoModelForCausalLM

model = AutoModelForCausalLM.from_pretrained("peft-internal-testing/opt-350m-lora")
```

Alternatively, you can use transformers [Pipelines](https://huggingface.co/docs/transformers/en/main_classes/pipelines) to load the model for conveniently running inference:

```py
from transformers import pipeline

model = pipeline("text-generation", "peft-internal-testing/opt-350m-lora")
print(model("Hello World"))
```

If you're interested in comparing or using more than one adapter, you can call the [`~PeftModel.add_adapter`] method to add the adapter configuration to the base model. The only requirement is the adapter type must be the same (you can't mix a LoRA and LoHa adapter).

```py
from transformers import AutoModelForCausalLM
from peft import LoraConfig

model = AutoModelForCausalLM.from_pretrained("facebook/opt-350m")
model.add_adapter(lora_config_1, adapter_name="adapter_1")
```

Call [`~PeftModel.add_adapter`] again to attach a new adapter to the base model.

```py
model.add_adapter(lora_config_2, adapter_name="adapter_2")
```

Then you can use [`~PeftModel.set_adapter`] to set the currently active adapter.

```py
model.set_adapter("adapter_1")
output = model.generate(**inputs)
print(tokenizer.decode(output_disabled[0], skip_special_tokens=True))
```

To disable the adapter, call the [disable_adapters](https://github.com/huggingface/transformers/blob/4e3490f79b40248c53ee54365a9662611e880892/src/transformers/integrations/peft.py#L313) method.

```py
model.disable_adapters()
```

The [enable_adapters](https://github.com/huggingface/transformers/blob/4e3490f79b40248c53ee54365a9662611e880892/src/transformers/integrations/peft.py#L336) can be used to enable the adapters again.

If you're curious, check out the [Load and train adapters with PEFT](https://huggingface.co/docs/transformers/main/peft) tutorial to learn more.


key: _node_content
string_value:
{"id_": "398575f8-18d5-424a-bd82-c11a75815a8f", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/peft/tutorial/peft_model_config", "title": "PEFT configurations and models", "tokens": 1940, "retrieve_doc": true, "source": "peft"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "7f1ab84f-2798-4f42-8b9b-abcd93b6f2ba", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/peft/tutorial/peft_model_config", "title": "PEFT configurations and models", "tokens": 1940, "retrieve_doc": true, "source": "peft"}, "hash": "36f7eede49bcbb1fbca50686517a245cfc6d4d7d3a86c2d0d5cb453d0dbc1f4a", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "8fabf2be-be71-4fe3-868c-6eadf068c377", "node_type": "1", "metadata": {}, "hash": "15f881a3a252100013d50c57e82c58285fd4f1a90e5b98e59fd06d971f83e975", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 0, "end_char_idx": 2656, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
# PEFT configurations and models

The sheer size of today's large pretrained models - which commonly have billions of parameters - present a significant training challenge because they require more storage space and more computational power to crunch all those calculations. You'll need access to powerful GPUs or TPUs to train these large pretrained models which is expensive, not widely accessible to everyone, not environmentally friendly, and not very practical. PEFT methods address many of these challenges. There are several types of PEFT methods (soft prompting, matrix decomposition, adapters), but they all focus on the same thing, reduce the number of trainable parameters. This makes it more accessible to train and store large models on consumer hardware.

The PEFT library is designed to help you quickly train large models on free or low-cost GPUs, and in this tutorial, you'll learn how to setup a configuration to apply a PEFT method to a pretrained base model for training. Once the PEFT configuration is setup, you can use any training framework you like (Transformer's [`~transformers.Trainer`] class, [Accelerate](https://hf.co/docs/accelerate), a custom PyTorch training loop).

## PEFT configurations

<Tip>

Learn more about the parameters you can configure for each PEFT method in their respective API reference page.

</Tip>

A configuration stores important parameters that specify how a particular PEFT method should be applied.

For example, take a look at the following [`LoraConfig`](https://huggingface.co/ybelkada/opt-350m-lora/blob/main/adapter_config.json) for applying LoRA and [`PromptEncoderConfig`](https://huggingface.co/smangrul/roberta-large-peft-p-tuning/blob/main/adapter_config.json) for applying p-tuning (these configuration files are already JSON-serialized). Whenever you load a PEFT adapter, it is a good idea to check whether it has an associated adapter_config.json file which is required.

<hfoptions id="config">
<hfoption id="LoraConfig">

```json
{
  "base_model_name_or_path": "facebook/opt-350m", #base model to apply LoRA to
  "bias": "none",
  "fan_in_fan_out": false,
  "inference_mode": true,
  "init_lora_weights": true,
  "layers_pattern": null,
  "layers_to_transform": null,
  "lora_alpha": 32,
  "lora_dropout": 0.05,
  "modules_to_save": null,
  "peft_type": "LORA", #PEFT method type
  "r": 16,
  "revision": null,
  "target_modules": [
    "q_proj", #model modules to apply LoRA to (query and value projection layers)
    "v_proj"
  ],
  "task_type": "CAUSAL_LM" #type of task to train model on
}
```

You can create your own configuration for training by initializing a [`LoraConfig`].


key: _node_content
string_value:
{"id_": "8fabf2be-be71-4fe3-868c-6eadf068c377", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/peft/tutorial/peft_model_config", "title": "PEFT configurations and models", "tokens": 1940, "retrieve_doc": true, "source": "peft"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "7f1ab84f-2798-4f42-8b9b-abcd93b6f2ba", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/peft/tutorial/peft_model_config", "title": "PEFT configurations and models", "tokens": 1940, "retrieve_doc": true, "source": "peft"}, "hash": "36f7eede49bcbb1fbca50686517a245cfc6d4d7d3a86c2d0d5cb453d0dbc1f4a", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "398575f8-18d5-424a-bd82-c11a75815a8f", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/peft/tutorial/peft_model_config", "title": "PEFT configurations and models", "tokens": 1940, "retrieve_doc": true, "source": "peft"}, "hash": "4fd119e835cf269dfeffca87417e8f93a31f34ac22075e206e21424360a3d30c", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "179c5e3c-e0c6-4932-b63c-9c4459366d9b", "node_type": "1", "metadata": {}, "hash": "9384209e7d7115ffbbe481ba46ef191c0f6008d7f83f90fa1b971f5491311589", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 1201, "end_char_idx": 3488, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
## PEFT configurations

<Tip>

Learn more about the parameters you can configure for each PEFT method in their respective API reference page.

</Tip>

A configuration stores important parameters that specify how a particular PEFT method should be applied.

For example, take a look at the following [`LoraConfig`](https://huggingface.co/ybelkada/opt-350m-lora/blob/main/adapter_config.json) for applying LoRA and [`PromptEncoderConfig`](https://huggingface.co/smangrul/roberta-large-peft-p-tuning/blob/main/adapter_config.json) for applying p-tuning (these configuration files are already JSON-serialized). Whenever you load a PEFT adapter, it is a good idea to check whether it has an associated adapter_config.json file which is required.

<hfoptions id="config">
<hfoption id="LoraConfig">

```json
{
  "base_model_name_or_path": "facebook/opt-350m", #base model to apply LoRA to
  "bias": "none",
  "fan_in_fan_out": false,
  "inference_mode": true,
  "init_lora_weights": true,
  "layers_pattern": null,
  "layers_to_transform": null,
  "lora_alpha": 32,
  "lora_dropout": 0.05,
  "modules_to_save": null,
  "peft_type": "LORA", #PEFT method type
  "r": 16,
  "revision": null,
  "target_modules": [
    "q_proj", #model modules to apply LoRA to (query and value projection layers)
    "v_proj"
  ],
  "task_type": "CAUSAL_LM" #type of task to train model on
}
```

You can create your own configuration for training by initializing a [`LoraConfig`].

```py
from peft import LoraConfig, TaskType

lora_config = LoraConfig(
    r=16,
    target_modules=["q_proj", "v_proj"],
    task_type=TaskType.CAUSAL_LM,
    lora_alpha=32,
    lora_dropout=0.05
)
```

</hfoption>
<hfoption id="PromptEncoderConfig">

```json
{
  "base_model_name_or_path": "roberta-large", #base model to apply p-tuning to
  "encoder_dropout": 0.0,
  "encoder_hidden_size": 128,
  "encoder_num_layers": 2,
  "encoder_reparameterization_type": "MLP",
  "inference_mode": true,
  "num_attention_heads": 16,
  "num_layers": 24,
  "num_transformer_submodules": 1,
  "num_virtual_tokens": 20,
  "peft_type": "P_TUNING", #PEFT method type
  "task_type": "SEQ_CLS", #type of task to train model on
  "token_dim": 1024
}
```

You can create your own configuration for training by initializing a [`PromptEncoderConfig`].


key: _node_content
string_value:
{"id_": "179c5e3c-e0c6-4932-b63c-9c4459366d9b", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/peft/tutorial/peft_model_config", "title": "PEFT configurations and models", "tokens": 1940, "retrieve_doc": true, "source": "peft"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "7f1ab84f-2798-4f42-8b9b-abcd93b6f2ba", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/peft/tutorial/peft_model_config", "title": "PEFT configurations and models", "tokens": 1940, "retrieve_doc": true, "source": "peft"}, "hash": "36f7eede49bcbb1fbca50686517a245cfc6d4d7d3a86c2d0d5cb453d0dbc1f4a", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "8fabf2be-be71-4fe3-868c-6eadf068c377", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/peft/tutorial/peft_model_config", "title": "PEFT configurations and models", "tokens": 1940, "retrieve_doc": true, "source": "peft"}, "hash": "d1bff5f4b9f302033b47c83de79a0f7201a895a59eef695d62a14d40b86aaca0", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "ca333f33-48d7-4fc2-bc2a-ec0097a074d1", "node_type": "1", "metadata": {}, "hash": "0dca32dbc6b30a8d4750dd4fc6c707c48b55494552a6d8d9eeaa7c6f2dd343d2", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 2658, "end_char_idx": 5290, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
```py
from peft import LoraConfig, TaskType

lora_config = LoraConfig(
    r=16,
    target_modules=["q_proj", "v_proj"],
    task_type=TaskType.CAUSAL_LM,
    lora_alpha=32,
    lora_dropout=0.05
)
```

</hfoption>
<hfoption id="PromptEncoderConfig">

```json
{
  "base_model_name_or_path": "roberta-large", #base model to apply p-tuning to
  "encoder_dropout": 0.0,
  "encoder_hidden_size": 128,
  "encoder_num_layers": 2,
  "encoder_reparameterization_type": "MLP",
  "inference_mode": true,
  "num_attention_heads": 16,
  "num_layers": 24,
  "num_transformer_submodules": 1,
  "num_virtual_tokens": 20,
  "peft_type": "P_TUNING", #PEFT method type
  "task_type": "SEQ_CLS", #type of task to train model on
  "token_dim": 1024
}
```

You can create your own configuration for training by initializing a [`PromptEncoderConfig`].

```py
from peft import PromptEncoderConfig, TaskType

p_tuning_config = PromptEncoderConfig(
    encoder_reparameterization_type="MLP",
    encoder_hidden_size=128,
    num_attention_heads=16,
    num_layers=24,
    num_transformer_submodules=1,
    num_virtual_tokens=20,
    token_dim=1024,
    task_type=TaskType.SEQ_CLS
)
```

</hfoption>
</hfoptions>

## PEFT models

With a PEFT configuration in hand, you can now apply it to any pretrained model to create a [`PeftModel`]. Choose from any of the state-of-the-art models from the [Transformers](https://hf.co/docs/transformers) library, a custom model, and even new and unsupported transformer architectures.

For this tutorial, load a base [facebook/opt-350m](https://huggingface.co/facebook/opt-350m) model to finetune.

```py
from transformers import AutoModelForCausalLM

model = AutoModelForCausalLM.from_pretrained("facebook/opt-350m")
```

Use the [`get_peft_model`] function to create a [`PeftModel`] from the base facebook/opt-350m model and the `lora_config` you created earlier.

```py
from peft import get_peft_model

lora_model = get_peft_model(model, lora_config)
lora_model.print_trainable_parameters()
"trainable params: 1,572,864 || all params: 332,769,280 || trainable%: 0.472659014678278"
```

Now you can train the [`PeftModel`] with your preferred training framework! After training, you can save your model locally with [`~PeftModel.save_pretrained`] or upload it to the Hub with the [`~transformers.PreTrainedModel.push_to_hub`] method.

```py
# save locally
lora_model.save_pretrained("your-name/opt-350m-lora")

# push to Hub
lora_model.push_to_hub("your-name/opt-350m-lora")
```

To load a [`PeftModel`] for inference, you'll need to provide the [`PeftConfig`] used to create it and the base model it was trained from.


key: _node_content
string_value:
{"id_": "ca333f33-48d7-4fc2-bc2a-ec0097a074d1", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/peft/tutorial/peft_model_config", "title": "PEFT configurations and models", "tokens": 1940, "retrieve_doc": true, "source": "peft"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "7f1ab84f-2798-4f42-8b9b-abcd93b6f2ba", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/peft/tutorial/peft_model_config", "title": "PEFT configurations and models", "tokens": 1940, "retrieve_doc": true, "source": "peft"}, "hash": "36f7eede49bcbb1fbca50686517a245cfc6d4d7d3a86c2d0d5cb453d0dbc1f4a", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "179c5e3c-e0c6-4932-b63c-9c4459366d9b", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/peft/tutorial/peft_model_config", "title": "PEFT configurations and models", "tokens": 1940, "retrieve_doc": true, "source": "peft"}, "hash": "7111e30ebfd35b4c6c3358ba550f431effe1cca95507cd67214639c93cfe1b73", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 3970, "end_char_idx": 6903, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
Choose from any of the state-of-the-art models from the [Transformers](https://hf.co/docs/transformers) library, a custom model, and even new and unsupported transformer architectures.

For this tutorial, load a base [facebook/opt-350m](https://huggingface.co/facebook/opt-350m) model to finetune.

```py
from transformers import AutoModelForCausalLM

model = AutoModelForCausalLM.from_pretrained("facebook/opt-350m")
```

Use the [`get_peft_model`] function to create a [`PeftModel`] from the base facebook/opt-350m model and the `lora_config` you created earlier.

```py
from peft import get_peft_model

lora_model = get_peft_model(model, lora_config)
lora_model.print_trainable_parameters()
"trainable params: 1,572,864 || all params: 332,769,280 || trainable%: 0.472659014678278"
```

Now you can train the [`PeftModel`] with your preferred training framework! After training, you can save your model locally with [`~PeftModel.save_pretrained`] or upload it to the Hub with the [`~transformers.PreTrainedModel.push_to_hub`] method.

```py
# save locally
lora_model.save_pretrained("your-name/opt-350m-lora")

# push to Hub
lora_model.push_to_hub("your-name/opt-350m-lora")
```

To load a [`PeftModel`] for inference, you'll need to provide the [`PeftConfig`] used to create it and the base model it was trained from.

```py
from peft import PeftModel, PeftConfig

config = PeftConfig.from_pretrained("ybelkada/opt-350m-lora")
model = AutoModelForCausalLM.from_pretrained(config.base_model_name_or_path)
lora_model = PeftModel.from_pretrained(model, "ybelkada/opt-350m-lora")
```

<Tip>

By default, the [`PeftModel`] is set for inference, but if you'd like to train the adapter some more you can set `is_trainable=True`.

```py
lora_model = PeftModel.from_pretrained(model, "ybelkada/opt-350m-lora", is_trainable=True)
```

</Tip>

The [`PeftModel.from_pretrained`] method is the most flexible way to load a [`PeftModel`] because it doesn't matter what model framework was used (Transformers, timm, a generic PyTorch model). Other classes, like [`AutoPeftModel`], are just a convenient wrapper around the base [`PeftModel`], and makes it easier to load PEFT models directly from the Hub or locally where the PEFT weights are stored.

```py
from peft import AutoPeftModelForCausalLM

lora_model = AutoPeftModelForCausalLM.from_pretrained("ybelkada/opt-350m-lora")
```

Take a look at the [AutoPeftModel](package_reference/auto_class) API reference to learn more about the [`AutoPeftModel`] classes.

## Next steps

With the appropriate [`PeftConfig`], you can apply it to any pretrained model to create a [`PeftModel`] and train large powerful models faster on freely available GPUs! To learn more about PEFT configurations and models, the following guide may be helpful:

* Learn how to configure a PEFT method for models that aren't from Transformers in the [Working with custom models](../developer_guides/custom_models) guide.


key: _node_content
string_value:
{"id_": "7dc04332-381b-4024-a0c0-063e67bed354", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/peft/package_reference/peft_model", "title": "Models", "tokens": 452, "retrieve_doc": true, "source": "peft"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "63325d9c-168d-42a1-b71d-8ffab0f1a746", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/peft/package_reference/peft_model", "title": "Models", "tokens": 452, "retrieve_doc": true, "source": "peft"}, "hash": "734e54070125d80cc73779d82b70dcc5fc23e84b9a6654f7dd9335368bad14d0", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 0, "end_char_idx": 1670, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
<!--⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be
rendered properly in your Markdown viewer.
-->

# Models

[`PeftModel`] is the base model class for specifying the base Transformer model and configuration to apply a PEFT method to. The base `PeftModel` contains methods for loading and saving models from the Hub.

## PeftModel

[[autodoc]] PeftModel
    - all

## PeftModelForSequenceClassification

A `PeftModel` for sequence classification tasks.

[[autodoc]] PeftModelForSequenceClassification
    - all

## PeftModelForTokenClassification

A `PeftModel` for token classification tasks.

[[autodoc]] PeftModelForTokenClassification
    - all

## PeftModelForCausalLM

A `PeftModel` for causal language modeling.

[[autodoc]] PeftModelForCausalLM
    - all

## PeftModelForSeq2SeqLM

A `PeftModel` for sequence-to-sequence language modeling.

[[autodoc]] PeftModelForSeq2SeqLM
    - all

## PeftModelForQuestionAnswering

A `PeftModel` for question answering.

[[autodoc]] PeftModelForQuestionAnswering
    - all

## PeftModelForFeatureExtraction

A `PeftModel` for getting extracting features/embeddings from transformer models.

[[autodoc]] PeftModelForFeatureExtraction
    - all

## PeftMixedModel

A `PeftModel` for mixing different adapter types (e.g. LoRA and LoHa).

[[autodoc]] PeftMixedModel
    - all

## Utilities

[[autodoc]] utils.cast_mixed_precision_params

[[autodoc]] get_peft_model

[[autodoc]] inject_adapter_in_model

[[autodoc]] utils.get_peft_model_state_dict

[[autodoc]] utils.prepare_model_for_kbit_training

[[autodoc]] get_layer_status

[[autodoc]] get_model_status


key: _node_content
string_value:
{"id_": "5b551f48-226f-4013-9834-201a341df431", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/peft/package_reference/boft", "title": "BOFT", "tokens": 538, "retrieve_doc": true, "source": "peft"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "70d13768-fd7e-46c9-a06d-08a7aa50c392", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/peft/package_reference/boft", "title": "BOFT", "tokens": 538, "retrieve_doc": true, "source": "peft"}, "hash": "cbf4acf59d6db8eaf5d779b95e124476463b2e388b7d49bb45dcf30e9c962275", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 0, "end_char_idx": 1884, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
# BOFT

[Orthogonal Butterfly (BOFT)](https://hf.co/papers/2311.06243) is a generic method designed for finetuning foundation models. It improves the paramter efficiency of the finetuning paradigm -- Orthogonal Finetuning (OFT), by taking inspiration from Cooley-Tukey fast Fourier transform, showing favorable results across finetuning different foundation models, including large vision transformers, large language models and text-to-image diffusion models.

The abstract from the paper is:

*Large foundation models are becoming ubiquitous, but training them from scratch is prohibitively expensive. Thus, efficiently adapting these powerful models to downstream tasks is increasingly important. In this paper, we study a principled finetuning paradigm -- Orthogonal Finetuning (OFT) -- for downstream task adaptation. Despite demonstrating good generalizability, OFT still uses a fairly large number of trainable parameters due to the high dimensionality of orthogonal matrices. To address this, we start by examining OFT from an information transmission perspective, and then identify a few key desiderata that enable better parameter-efficiency. Inspired by how the Cooley-Tukey fast Fourier transform algorithm enables efficient information transmission, we propose an efficient orthogonal parameterization using butterfly structures. We apply this parameterization to OFT, creating a novel parameter-efficient finetuning method, called Orthogonal Butterfly (BOFT). By subsuming OFT as a special case, BOFT introduces a generalized orthogonal finetuning framework. Finally, we conduct an extensive empirical study of adapting large vision transformers, large language models, and text-to-image diffusion models to various downstream tasks in vision and language*.

## BOFTConfig

[[autodoc]] tuners.boft.config.BOFTConfig

## BOFTModel

[[autodoc]] tuners.boft.model.BOFTModel


key: _node_content
string_value:
{"id_": "e9ee9675-df29-41f4-b7ba-bc8c761e7f41", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/peft/package_reference/llama_adapter", "title": "Llama-Adapter", "tokens": 544, "retrieve_doc": true, "source": "peft"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "c13b9961-53cd-40fc-a4ee-bc2c01211b38", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/peft/package_reference/llama_adapter", "title": "Llama-Adapter", "tokens": 544, "retrieve_doc": true, "source": "peft"}, "hash": "a57dc51f189af4a02b19a5a32f632c9e84fed3becfb7fa8800963255eed8ea0e", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 0, "end_char_idx": 1734, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
# Llama-Adapter

[Llama-Adapter](https://hf.co/papers/2303.16199) is a PEFT method specifically designed for turning Llama into an instruction-following model. The Llama model is frozen and only a set of adaptation prompts prefixed to the input instruction tokens are learned. Since randomly initialized modules inserted into the model can cause the model to lose some of its existing knowledge, Llama-Adapter uses zero-initialized attention with zero gating to progressively add the instructional prompts to the model.

The abstract from the paper is:

*We present LLaMA-Adapter, a lightweight adaption method to efficiently fine-tune LLaMA into an instruction-following model. Using 52K self-instruct demonstrations, LLaMA-Adapter only introduces 1.2M learnable parameters upon the frozen LLaMA 7B model, and costs less than one hour for fine-tuning on 8 A100 GPUs. Specifically, we adopt a set of learnable adaption prompts, and prepend them to the input text tokens at higher transformer layers. Then, a zero-init attention mechanism with zero gating is proposed, which adaptively injects the new instructional cues into LLaMA, while effectively preserves its pre-trained knowledge. With efficient training, LLaMA-Adapter generates high-quality responses, comparable to Alpaca with fully fine-tuned 7B parameters. Furthermore, our approach can be simply extended to multi-modal input, e.g., images, for image-conditioned LLaMA, which achieves superior reasoning capacity on ScienceQA. We release our code at https://github.com/ZrrSkywalker/LLaMA-Adapter*.

## AdaptionPromptConfig

[[autodoc]] tuners.adaption_prompt.config.AdaptionPromptConfig

## AdaptionPromptModel

[[autodoc]] tuners.adaption_prompt.model.AdaptionPromptModel


key: _node_content
string_value:
{"id_": "4616517c-bd4a-4773-af9d-125229420260", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/peft/package_reference/layernorm_tuning", "title": "LayerNorm Tuning", "tokens": 609, "retrieve_doc": true, "source": "peft"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "a2da301c-c12e-4fbf-aece-685fc537deb4", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/peft/package_reference/layernorm_tuning", "title": "LayerNorm Tuning", "tokens": 609, "retrieve_doc": true, "source": "peft"}, "hash": "6751ef8af926d71033019b5632956d6a8aa167a771ea0d59e9105ba193488efa", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 0, "end_char_idx": 2080, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
# LayerNorm Tuning

LayerNorm Tuning ([LN Tuning](https://huggingface.co/papers/2312.11420)) is a PEFT method that only fine-tunes the parameters of the LayerNorm layers in a model.
The paper has tested the performance of this method on large language models and has shown that it can achieve strong performance with a significant reduction in the number of trainable parameters and GPU memory usage.
However, the method is not limited to language models and can be applied to any model that uses LayerNorm layers.
In this implementation, the default is that all layernorm layers inside a model is finetuned, but it could be used to target other layer types such as `MLP` or `Attention` layers, this can be done by specifying the `target_modules` in the `LNTuningConfig`.

The abstract from the paper is:

*This paper introduces an efficient strategy to transform Large Language Models (LLMs) into Multi-Modal Large Language Models (MLLMs). By conceptualizing this transformation as a domain adaptation process, i.e., transitioning from text understanding to embracing multiple modalities, we intriguingly note that, within each attention block, tuning LayerNorm suffices to yield strong performance. Moreover, when benchmarked against other tuning approaches like full parameter finetuning or LoRA, its benefits on efficiency are substantial. For example, when compared to LoRA on a 13B model scale, performance can be enhanced by an average of over 20% across five multi-modal tasks, and meanwhile, results in a significant reduction of trainable parameters by 41.9% and a decrease in GPU memory usage by 17.6%. On top of this LayerNorm strategy, we showcase that selectively tuning only with conversational data can improve efficiency further. Beyond these empirical outcomes, we provide a comprehensive analysis to explore the role of LayerNorm in adapting LLMs to the multi-modal domain and improving the expressive power of the model.*

## LNTuningConfig

[[autodoc]] tuners.ln_tuning.config.LNTuningConfig

## LNTuningModel

[[autodoc]] tuners.ln_tuning.model.LNTuningModel


key: _node_content
string_value:
{"id_": "e74f7041-5111-44ad-a2b0-6b65fd1668e2", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/peft/package_reference/ia3", "title": "IA3", "tokens": 558, "retrieve_doc": true, "source": "peft"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "f4a8dc5c-4875-4edc-9cfd-4dfa718d5d71", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/peft/package_reference/ia3", "title": "IA3", "tokens": 558, "retrieve_doc": true, "source": "peft"}, "hash": "636416b9c7d25072c712deb67eedc25f3573df7c1f03e7a608e2dad00b2ddb4f", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 0, "end_char_idx": 1848, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
# IA3

Infused Adapter by Inhibiting and Amplifying Inner Activations, or [IA3](https://hf.co/papers/2205.05638), is a method that adds three learned vectors to rescale the keys and values of the self-attention and encoder-decoder attention layers, and the intermediate activation of the position-wise feed-forward network.

The abstract from the paper is:

*Few-shot in-context learning (ICL) enables pre-trained language models to perform a previously-unseen task without any gradient-based training by feeding a small number of training examples as part of the input. ICL incurs substantial computational, memory, and storage costs because it involves processing all of the training examples every time a prediction is made. Parameter-efficient fine-tuning (PEFT) (e.g. adapter modules, prompt tuning, sparse update methods, etc.) offers an alternative paradigm where a small set of parameters are trained to enable a model to perform the new task. In this paper, we rigorously compare few-shot ICL and PEFT and demonstrate that the latter offers better accuracy as well as dramatically lower computational costs. Along the way, we introduce a new PEFT method called (IA)^3 that scales activations by learned vectors, attaining stronger performance while only introducing a relatively tiny amount of new parameters. We also propose a simple recipe based on the T0 model called T-Few that can be applied to new tasks without task-specific tuning or modifications. We validate the effectiveness of T-Few on completely unseen tasks by applying it to the RAFT benchmark, attaining super-human performance for the first time and outperforming the state-of-the-art by 6% absolute. All of the code used in our experiments is publicly available*.

## IA3Config

[[autodoc]] tuners.ia3.config.IA3Config

## IA3Model

[[autodoc]] tuners.ia3.model.IA3Model


key: _node_content
string_value:
{"id_": "ea370a43-c710-4b15-a6dd-b443018736b1", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/peft/package_reference/adalora", "title": "AdaLoRA", "tokens": 562, "retrieve_doc": true, "source": "peft"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "7dbed465-5642-465d-93dd-2fbe367947ae", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/peft/package_reference/adalora", "title": "AdaLoRA", "tokens": 562, "retrieve_doc": true, "source": "peft"}, "hash": "8ba439ee61d8e3052dc4f28ae0693cb039774edf1c76e98b0a05f6b6163da63a", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 0, "end_char_idx": 2017, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
# AdaLoRA

[AdaLoRA](https://hf.co/papers/2303.10512) is a method for optimizing the number of trainable parameters to assign to weight matrices and layers, unlike LoRA, which distributes parameters evenly across all modules. More parameters are budgeted for important weight matrices and layers while less important ones receive fewer parameters.

The abstract from the paper is:

*Fine-tuning large pre-trained language models on downstream tasks has become an important paradigm in NLP. However, common practice fine-tunes all of the parameters in a pre-trained model, which becomes prohibitive when a large number of downstream tasks are present. Therefore, many fine-tuning methods are proposed to learn incremental updates of pre-trained weights in a parameter efficient way, e.g., low-rank increments. These methods often evenly distribute the budget of incremental updates across all pre-trained weight matrices, and overlook the varying importance of different weight parameters. As a consequence, the fine-tuning performance is suboptimal. To bridge this gap, we propose AdaLoRA, which adaptively allocates the parameter budget among weight matrices according to their importance score. In particular, AdaLoRA parameterizes the incremental updates in the form of singular value decomposition. Such a novel approach allows us to effectively prune the singular values of unimportant updates, which is essentially to reduce their parameter budget but circumvent intensive exact SVD computations. We conduct extensive experiments with several pre-trained models on natural language processing, question answering, and natural language generation to validate the effectiveness of AdaLoRA. Results demonstrate that AdaLoRA manifests notable improvement over baselines, especially in the low budget settings. Our code is publicly available at https://github.com/QingruZhang/AdaLoRA*.

## AdaLoraConfig

[[autodoc]] tuners.adalora.config.AdaLoraConfig

## AdaLoraModel

[[autodoc]] tuners.adalora.model.AdaLoraModel


key: _node_content
string_value:
{"id_": "65d26e8a-5bf9-47c3-81d6-bb37fb7bea50", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/peft/package_reference/prompt_tuning", "title": "Prompt tuning", "tokens": 504, "retrieve_doc": true, "source": "peft"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "a0c30fa2-681e-4ae8-9b24-9c5f52a1b4e4", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/peft/package_reference/prompt_tuning", "title": "Prompt tuning", "tokens": 504, "retrieve_doc": true, "source": "peft"}, "hash": "c0f3438301e0873a09ad0d7df1866e8850298b4c9bad50cb7315cf14a0df6feb", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 0, "end_char_idx": 1638, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
# Prompt tuning

[Prompt tuning](https://hf.co/papers/2104.08691) adds task-specific prompts to the input, and these prompt parameters are updated independently of the pretrained model parameters which are frozen.

The abstract from the paper is:

*In this work, we explore "prompt tuning", a simple yet effective mechanism for learning "soft prompts" to condition frozen language models to perform specific downstream tasks. Unlike the discrete text prompts used by GPT-3, soft prompts are learned through backpropagation and can be tuned to incorporate signal from any number of labeled examples. Our end-to-end learned approach outperforms GPT-3's "few-shot" learning by a large margin. More remarkably, through ablations on model size using T5, we show that prompt tuning becomes more competitive with scale: as models exceed billions of parameters, our method "closes the gap" and matches the strong performance of model tuning (where all model weights are tuned). This finding is especially relevant in that large models are costly to share and serve, and the ability to reuse one frozen model for multiple downstream tasks can ease this burden. Our method can be seen as a simplification of the recently proposed "prefix tuning" of Li and Liang (2021), and we provide a comparison to this and other similar approaches. Finally, we show that conditioning a frozen model with soft prompts confers benefits in robustness to domain transfer, as compared to full model tuning*.

## PromptTuningConfig

[[autodoc]] tuners.prompt_tuning.config.PromptTuningConfig

## PromptEmbedding

[[autodoc]] tuners.prompt_tuning.model.PromptEmbedding


key: _node_content
string_value:
{"id_": "f2c4c23b-4340-439c-96d3-14980316c5c8", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/peft/package_reference/tuners", "title": "Tuners", "tokens": 288, "retrieve_doc": true, "source": "peft"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "8a47c710-25be-4d7a-8d1e-1c73a7510405", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/peft/package_reference/tuners", "title": "Tuners", "tokens": 288, "retrieve_doc": true, "source": "peft"}, "hash": "45573e9e41c717a7b2cd5b1a3da833079bbfe376b6c0e7ff55ed72cf029ba4ca", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 0, "end_char_idx": 544, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
# Tuners

A tuner (or adapter) is a module that can be plugged into a `torch.nn.Module`. [`BaseTuner`] base class for other tuners and provides shared methods and attributes for preparing an adapter configuration and replacing a target module with the adapter module. [`BaseTunerLayer`] is a base class for adapter layers. It offers methods and attributes for managing adapters such as activating and disabling adapters.

## BaseTuner

[[autodoc]] tuners.tuners_utils.BaseTuner

## BaseTunerLayer

[[autodoc]] tuners.tuners_utils.BaseTunerLayer


key: _node_content
string_value:
{"id_": "d4bad56d-80d0-4cec-b035-e46e61f5806b", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/peft/package_reference/multitask_prompt_tuning", "title": "Multitask prompt tuning", "tokens": 475, "retrieve_doc": true, "source": "peft"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "588015fb-a2a2-4ee4-83b5-e22715c9d294", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/peft/package_reference/multitask_prompt_tuning", "title": "Multitask prompt tuning", "tokens": 475, "retrieve_doc": true, "source": "peft"}, "hash": "4eec57590220074b8942f8b61bc742a608ec681de263aadac8e681da749c02bc", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 0, "end_char_idx": 1512, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
# Multitask prompt tuning

[Multitask prompt tuning](https://huggingface.co/papers/2303.02861)  decomposes the soft prompts of each task into a single learned transferable prompt instead of a separate prompt for each task. The single learned prompt can be adapted for each task by multiplicative low rank updates.

The abstract from the paper is:

*Prompt tuning, in which a base pretrained model is adapted to each task via conditioning on learned prompt vectors, has emerged as a promising approach for efficiently adapting large language models to multiple downstream tasks. However, existing methods typically learn soft prompt vectors from scratch, and it has not been clear how to exploit the rich cross-task knowledge with prompt vectors in a multitask learning setting. We propose multitask prompt tuning (MPT), which first learns a single transferable prompt by distilling knowledge from multiple task-specific source prompts. We then learn multiplicative low rank updates to this shared prompt to efficiently adapt it to each downstream target task. Extensive experiments on 23 NLP datasets demonstrate that our proposed approach outperforms the state-of-the-art methods, including the full finetuning baseline in some cases, despite only tuning 0.035% as many task-specific parameters*.

## MultitaskPromptTuningConfig

[[autodoc]] tuners.multitask_prompt_tuning.config.MultitaskPromptTuningConfig

## MultitaskPromptEmbedding

[[autodoc]] tuners.multitask_prompt_tuning.model.MultitaskPromptEmbedding


key: _node_content
string_value:
{"id_": "2b369f2a-b116-475b-b3b2-d2d5dbd253ab", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/peft/package_reference/lora", "title": "LoRA", "tokens": 467, "retrieve_doc": true, "source": "peft"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "3877c5d7-e417-4961-8825-3077d0a02c23", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/peft/package_reference/lora", "title": "LoRA", "tokens": 467, "retrieve_doc": true, "source": "peft"}, "hash": "0cfcc6e4a37b702c4db63008864e82d6a9cb07b713a7cb6e3a8bd2eed23f2c86", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 0, "end_char_idx": 1364, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
# LoRA

Low-Rank Adaptation ([LoRA](https://huggingface.co/papers/2309.15223)) is a PEFT method that decomposes a large matrix into two smaller low-rank matrices in the attention layers. This drastically reduces the number of parameters that need to be fine-tuned.

The abstract from the paper is:

*We propose a neural language modeling system based on low-rank adaptation (LoRA) for speech recognition output rescoring. Although pretrained language models (LMs) like BERT have shown superior performance in second-pass rescoring, the high computational cost of scaling up the pretraining stage and adapting the pretrained models to specific domains limit their practical use in rescoring. Here we present a method based on low-rank decomposition to train a rescoring BERT model and adapt it to new domains using only a fraction (0.08%) of the pretrained parameters. These inserted matrices are optimized through a discriminative training objective along with a correlation-based regularization loss. The proposed low-rank adaptation Rescore-BERT (LoRB) architecture is evaluated on LibriSpeech and internal datasets with decreased training times by factors between 5.4 and 3.6.*.

## LoraConfig

[[autodoc]] tuners.lora.config.LoraConfig

## LoraModel

[[autodoc]] tuners.lora.model.LoraModel

## Utility

[[autodoc]] utils.loftq_utils.replace_lora_weights_loftq


key: _node_content
string_value:
{"id_": "15aab946-2d88-404d-ad42-ff0fc6e6c17e", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/peft/package_reference/vera", "title": "VeRA: Vector-based Random Matrix Adaptation", "tokens": 756, "retrieve_doc": true, "source": "peft"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "bf8b8755-4c9d-4e5b-a373-40377d1a383a", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/peft/package_reference/vera", "title": "VeRA: Vector-based Random Matrix Adaptation", "tokens": 756, "retrieve_doc": true, "source": "peft"}, "hash": "a966022ee2c4040c9e940a76708928ed3402c488a512b5ded5c1d4d3b65d65b4", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 0, "end_char_idx": 2700, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
# VeRA: Vector-based Random Matrix Adaptation

[VeRA](https://huggingface.co/papers/2310.11454) is a parameter-efficient fine-tuning technique that is similar to LoRA but requires even fewer extra parameters while promising similar or even better performance. As such, it is particularly useful when the parameter budget is very limited, e.g. when scaling to very large models. The reduction of the count of trainable parameters is achieved by sharing the same low-rank matrices across all layers, and only training two additional vectors per layer.

When saving the adapter parameters, it's possible to eschew storing the low rank matrices by setting `save_projection=False` on the `VeraConfig`. In that case, these matrices will be restored based on the fixed random seed from the `projection_prng_key` argument. This cuts down on the size of the checkpoint, but we cannot guarantee reproducibility on all devices and for all future versions of PyTorch. If you want to ensure reproducibility, set `save_projection=True` (which is the default).

To handle different shapes of adapted layers, VeRA initializes shared A and B matrices with the largest required size for each dimension. During the forward pass, submatrices A and B for a given layer are sliced out from these shared matrices and used as described in the paper. For example, adapting two linear layers of shapes (100, 20) and (80, 50) will create A and B matrices of shapes (rank, 50) and (100, rank) respectively. Then, to adapt a layer of shape (100, 20), submatrices A and B of shapes (rank, 20) and (100, rank) will be extracted.

VeRA currently has the following constraints:

- Only `nn.Linear` layers are supported.
- Quantized layers are not supported.

If these constraints don't work for your use case, use LoRA instead.

The abstract from the paper is:

> Low-rank adapation (LoRA) is a popular method that reduces the number of trainable parameters when finetuning large language models, but still faces acute storage challenges when scaling to even larger models or deploying numerous per-user or per-task adapted models. In this work, we present Vector-based Random Matrix Adaptation (VeRA), which significantly reduces the number of trainable parameters compared to LoRA, yet maintains the same performance. It achieves this by using a single pair of low-rank matrices shared across all layers and learning small scaling vectors instead. We demonstrate its effectiveness on the GLUE and E2E benchmarks, image classification tasks, and show its application in instruction-tuning of 7B and 13B language models.

## VeRAConfig

[[autodoc]] tuners.vera.config.VeraConfig

## VeRAModel

[[autodoc]] tuners.vera.model.VeraModel


key: _node_content
string_value:
{"id_": "ff4b12f5-8502-4ab9-b3b0-5dd1cb699396", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/peft/package_reference/config", "title": "Configuration", "tokens": 193, "retrieve_doc": true, "source": "peft"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "e75c8416-a546-48ec-ba75-167de1c6d227", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/peft/package_reference/config", "title": "Configuration", "tokens": 193, "retrieve_doc": true, "source": "peft"}, "hash": "3a6c33d6e8f128a6679644783bea19d306625bb345a62906da6b0395b598d282", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 0, "end_char_idx": 843, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
<!--⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be
rendered properly in your Markdown viewer.
-->

# Configuration

[`PeftConfigMixin`] is the base configuration class for storing the adapter configuration of a [`PeftModel`], and [`PromptLearningConfig`] is the base configuration class for soft prompt methods (p-tuning, prefix tuning, and prompt tuning). These base classes contain methods for saving and loading model configurations from the Hub, specifying the PEFT method to use, type of task to perform, and model configurations like number of layers and number of attention heads.

## PeftConfigMixin

[[autodoc]] config.PeftConfigMixin
    - all

## PeftConfig

[[autodoc]] PeftConfig
    - all

## PromptLearningConfig

[[autodoc]] PromptLearningConfig
    - all


key: _node_content
string_value:
{"id_": "4642bd87-d505-41df-8091-fb559f56e2d4", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/peft/package_reference/loha", "title": "LoHa", "tokens": 472, "retrieve_doc": true, "source": "peft"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "e7ae3ec6-d10b-48b6-917a-77aa94ecb4cb", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/peft/package_reference/loha", "title": "LoHa", "tokens": 472, "retrieve_doc": true, "source": "peft"}, "hash": "e155eb1d0fe0f5ea693f67bf1b4688555076b075ffc6f1b21dacfc4b0b788cdb", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 0, "end_char_idx": 1471, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
# LoHa

Low-Rank Hadamard Product ([LoHa](https://huggingface.co/papers/2108.06098)), is similar to LoRA except it approximates the large weight matrix with more low-rank matrices and combines them with the Hadamard product. This method is even more parameter-efficient than LoRA and achieves comparable performance.

The abstract from the paper is:

*In this work, we propose a communication-efficient parameterization, FedPara, for federated learning (FL) to overcome the burdens on frequent model uploads and downloads. Our method re-parameterizes weight parameters of layers using low-rank weights followed by the Hadamard product. Compared to the conventional low-rank parameterization, our FedPara method is not restricted to low-rank constraints, and thereby it has a far larger capacity. This property enables to achieve comparable performance while requiring 3 to 10 times lower communication costs than the model with the original layers, which is not achievable by the traditional low-rank methods. The efficiency of our method can be further improved by combining with other efficient FL optimizers. In addition, we extend our method to a personalized FL application, pFedPara, which separates parameters into global and local ones. We show that pFedPara outperforms competing personalized FL methods with more than three times fewer parameters*.

## LoHaConfig

[[autodoc]] tuners.loha.config.LoHaConfig

## LoHaModel

[[autodoc]] tuners.loha.model.LoHaModel


key: _node_content
string_value:
{"id_": "b3d974db-fff5-4b61-9198-6dea5704a0d4", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/peft/package_reference/auto_class", "title": "AutoPeftModels", "tokens": 406, "retrieve_doc": true, "source": "peft"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "17a0e136-892c-4770-8bf6-77618e5311fa", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/peft/package_reference/auto_class", "title": "AutoPeftModels", "tokens": 406, "retrieve_doc": true, "source": "peft"}, "hash": "1687cbcaa2dde64f3e62c79d91e5a386e8895d4c173d4d0ee638e907cff87209", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 0, "end_char_idx": 931, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
# AutoPeftModels

The `AutoPeftModel` classes loads the appropriate PEFT model for the task type by automatically inferring it from the configuration file. They are designed to quickly and easily load a PEFT model in a single line of code without having to worry about which exact model class you need or manually loading a [`PeftConfig`].

## AutoPeftModel

[[autodoc]] auto.AutoPeftModel
    - from_pretrained

## AutoPeftModelForCausalLM

[[autodoc]] auto.AutoPeftModelForCausalLM

## AutoPeftModelForSeq2SeqLM

[[autodoc]] auto.AutoPeftModelForSeq2SeqLM

## AutoPeftModelForSequenceClassification

[[autodoc]] auto.AutoPeftModelForSequenceClassification

## AutoPeftModelForTokenClassification

[[autodoc]] auto.AutoPeftModelForTokenClassification

## AutoPeftModelForQuestionAnswering

[[autodoc]] auto.AutoPeftModelForQuestionAnswering

## AutoPeftModelForFeatureExtraction

[[autodoc]] auto.AutoPeftModelForFeatureExtraction


key: _node_content
string_value:
{"id_": "68c99811-76e0-451f-a665-c5cc5a2d046b", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/peft/package_reference/fourierft", "title": "FourierFT: Discrete Fourier Transformation Fine-Tuning", "tokens": 562, "retrieve_doc": true, "source": "peft"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "c896464e-21f9-4814-b6c5-116dfccbc42d", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/peft/package_reference/fourierft", "title": "FourierFT: Discrete Fourier Transformation Fine-Tuning", "tokens": 562, "retrieve_doc": true, "source": "peft"}, "hash": "a27cf076f5a4f11b7dd22c68f92a7b4ee42d09324bf1c7666a52d32c814b0692", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 0, "end_char_idx": 1921, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
# FourierFT: Discrete Fourier Transformation Fine-Tuning

[FourierFT](https://huggingface.co/papers/2405.03003) is a parameter-efficient fine-tuning technique that leverages Discrete Fourier Transform to compress the model's tunable weights. This method outperforms LoRA in the GLUE benchmark and common ViT classification tasks using much less parameters.

FourierFT currently has the following constraints:

- Only `nn.Linear` layers are supported.
- Quantized layers are not supported.

If these constraints don't work for your use case, consider other methods instead.

The abstract from the paper is:

> Low-rank adaptation (LoRA) has recently gained much interest in fine-tuning foundation models. It effectively reduces the number of trainable parameters by incorporating low-rank matrices A and B to represent the weight change, i.e., Delta W=BA. Despite LoRA's progress, it faces storage challenges when handling extensive customization adaptations or larger base models. In this work, we aim to further compress trainable parameters by enjoying the powerful expressiveness of the Fourier transform. Specifically, we introduce FourierFT, which treats Delta W as a matrix in the spatial domain and learns only a small fraction of its spectral coefficients. With the trained spectral coefficients, we implement the inverse discrete Fourier transform to recover Delta W. Empirically, our FourierFT method shows comparable or better performance with fewer parameters than LoRA on various tasks, including natural language understanding, natural language generation, instruction tuning, and image classification. For example, when performing instruction tuning on the LLaMA2-7B model, FourierFT surpasses LoRA with only 0.064M trainable parameters, compared to LoRA's 33.5M.

## FourierFTConfig

[[autodoc]] tuners.fourierft.config.FourierFTConfig

## FourierFTModel

[[autodoc]] tuners.fourierft.model.FourierFTModel


key: _node_content
string_value:
{"id_": "1b719fd1-b73a-4893-8ea8-7b680d54652c", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/peft/package_reference/p_tuning", "title": "P-tuning", "tokens": 474, "retrieve_doc": true, "source": "peft"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "5b9f6e81-5eb8-4fc3-aec3-b2c3051f2fed", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/peft/package_reference/p_tuning", "title": "P-tuning", "tokens": 474, "retrieve_doc": true, "source": "peft"}, "hash": "3da9718298c73aa418d8a1e4527acd249171096a2d00b324c7d6ed91767dc17c", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 0, "end_char_idx": 1439, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
# P-tuning

[P-tuning](https://hf.co/papers/2103.10385) adds trainable prompt embeddings to the input that is optimized by a prompt encoder to find a better prompt, eliminating the need to manually design prompts. The prompt tokens can be added anywhere in the input sequence, and p-tuning also introduces anchor tokens for improving performance.

The abstract from the paper is:

*While GPTs with traditional fine-tuning fail to achieve strong results on natural language understanding (NLU), we show that GPTs can be better than or comparable to similar-sized BERTs on NLU tasks with a novel method P-tuning -- which employs trainable continuous prompt embeddings. On the knowledge probing (LAMA) benchmark, the best GPT recovers 64\% (P@1) of world knowledge without any additional text provided during test time, which substantially improves the previous best by 20+ percentage points. On the SuperGlue benchmark, GPTs achieve comparable and sometimes better performance to similar-sized BERTs in supervised learning. Importantly, we find that P-tuning also improves BERTs' performance in both few-shot and supervised settings while largely reducing the need for prompt engineering. Consequently, P-tuning outperforms the state-of-the-art approaches on the few-shot SuperGlue benchmark.*.

## PromptEncoderConfig

[[autodoc]] tuners.p_tuning.config.PromptEncoderConfig

## PromptEncoder

[[autodoc]] tuners.p_tuning.model.PromptEncoder


key: _node_content
string_value:
{"id_": "5ae90ba7-c4ac-406b-b931-8bd279135ca8", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/peft/package_reference/merge_utils", "title": "Model merge", "tokens": 282, "retrieve_doc": true, "source": "peft"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "6f206698-b766-4baf-b99c-634ecdbd82c0", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/peft/package_reference/merge_utils", "title": "Model merge", "tokens": 282, "retrieve_doc": true, "source": "peft"}, "hash": "24fe8e3962bd13e7b37a630d61392ea5baddd9e790261273beacdf9b5db64f23", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 0, "end_char_idx": 460, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
# Model merge

PEFT provides several internal utilities for [merging LoRA adapters](../developer_guides/model_merging) with the TIES and DARE methods.

[[autodoc]] utils.merge_utils.prune

[[autodoc]] utils.merge_utils.calculate_majority_sign_mask

[[autodoc]] utils.merge_utils.disjoint_merge

[[autodoc]] utils.merge_utils.task_arithmetic

[[autodoc]] utils.merge_utils.ties

[[autodoc]] utils.merge_utils.dare_linear

[[autodoc]] utils.merge_utils.dare_ties


key: _node_content
string_value:
{"id_": "6eb9086b-52e2-4bf4-b58c-838b920addfb", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/peft/package_reference/peft_types", "title": "PEFT types", "tokens": 224, "retrieve_doc": true, "source": "peft"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "865dd701-2602-4967-9364-4bc8c11a0adb", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/peft/package_reference/peft_types", "title": "PEFT types", "tokens": 224, "retrieve_doc": true, "source": "peft"}, "hash": "0a5a2da2339682b70f8078ef3a4b7855c9ce55c13a872abeb7bc60375386bbc9", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 0, "end_char_idx": 219, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
# PEFT types

[`PeftType`] includes the supported adapters in PEFT, and [`TaskType`] includes PEFT-supported tasks.

## PeftType

[[autodoc]] utils.peft_types.PeftType

## TaskType

[[autodoc]] utils.peft_types.TaskType


key: _node_content
string_value:
{"id_": "f630a35e-314d-4f9f-bf4e-3021d2981faa", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/peft/package_reference/poly", "title": "Polytropon", "tokens": 976, "retrieve_doc": true, "source": "peft"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "7d1a4634-5c71-4c6f-8f0c-d5532ace7523", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/peft/package_reference/poly", "title": "Polytropon", "tokens": 976, "retrieve_doc": true, "source": "peft"}, "hash": "7b847d0f05bd8c611d26aab4e3dc0643911706d7ce8e6bcdaf772ce55343e1c7", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "b2a3c142-754a-4877-a60f-aecd685d193c", "node_type": "1", "metadata": {}, "hash": "9aaca8e31a6177bf8cec81c2d4b81eb2019a76ed607e45ae89441d48d44cf8d9", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 0, "end_char_idx": 3705, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
# Polytropon

[Polytropon](https://hf.co/papers/2202.13914) is a multitask model with a number of different LoRA adapters in it's "inventory". The model learns the correct combination of adapters from the inventory with a routing function to choose the best subset of modules for a specific task. PEFT also supports [Multi-Head Adapter Routing (MHR)](https://hf.co/papers/2211.03831) for Polytropon which builds on and improves the routing function by combining the adapter heads more granularly. The adapter heads are separated into disjoint blocks and a different routing function is learned for each one, allowing for more expressivity.

<hfoptions id="paper">
<hfoption id="Combining Modular Skills in Multitask Learning">

The abstract from the paper is:

*A modular design encourages neural models to disentangle and recombine different facets of knowledge to generalise more systematically to new tasks. In this work, we assume that each task is associated with a subset of latent discrete skills from a (potentially small) inventory. In turn, skills correspond to parameter-efficient (sparse / low-rank) model parameterisations. By jointly learning these and a task-skill allocation matrix, the network for each task is instantiated as the average of the parameters of active skills. To favour non-trivial soft partitions of skills across tasks, we experiment with a series of inductive biases, such as an Indian Buffet Process prior and a two-speed learning rate. We evaluate our latent-skill model on two main settings: 1) multitask reinforcement learning for grounded instruction following on 8 levels of the BabyAI platform; and 2) few-shot adaptation of pre-trained text-to-text generative models on CrossFit, a benchmark comprising 160 NLP tasks. We find that the modular design of a network significantly increases sample efficiency in reinforcement learning and few-shot generalisation in supervised learning, compared to baselines with fully shared, task-specific, or conditionally generated parameters where knowledge is entangled across tasks. In addition, we show how discrete skills help interpretability, as they yield an explicit hierarchy of tasks.*

</hfoption>
<hfoption id="Multi-Head Adapter Routing for Cross-Task Generalization">

The abstract from the paper is:

*Parameter-efficient fine-tuning (PEFT) for cross-task generalization consists in pre-training adapters on a multi-task training set before few-shot adaptation to test tasks. Polytropon [Ponti et al., 2023] (Poly) jointly learns an inventory of adapters and a routing function that selects a (variable-size) subset of adapters for each task during both pre-training and few-shot adaptation. In this paper, we investigate the role that adapter routing plays in its success and design new variants based on our findings. First, we build on the intuition that finer-grained routing provides more expressivity. Hence, we propose MHR (Multi-Head Routing), which combines subsets of adapter parameters and outperforms Poly under a comparable parameter budget; by only fine-tuning the routing function and not the adapters (MHR-z), we achieve competitive performance with extreme parameter efficiency. Second, we find that Poly/MHR performance is a result of better multi-task optimization, rather than modular inductive biases that facilitate adapter recombination and local adaptation, as previously hypothesized. In fact, we find that MHR exhibits higher gradient alignment between tasks than any other method. Since this implies that routing is only crucial during multi-task pre-training, we propose MHR-mu, which discards routing and fine-tunes the average of the pre-trained adapters during few-shot adaptation.


key: _node_content
string_value:
{"id_": "b2a3c142-754a-4877-a60f-aecd685d193c", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/peft/package_reference/poly", "title": "Polytropon", "tokens": 976, "retrieve_doc": true, "source": "peft"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "7d1a4634-5c71-4c6f-8f0c-d5532ace7523", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/peft/package_reference/poly", "title": "Polytropon", "tokens": 976, "retrieve_doc": true, "source": "peft"}, "hash": "7b847d0f05bd8c611d26aab4e3dc0643911706d7ce8e6bcdaf772ce55343e1c7", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "f630a35e-314d-4f9f-bf4e-3021d2981faa", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/peft/package_reference/poly", "title": "Polytropon", "tokens": 976, "retrieve_doc": true, "source": "peft"}, "hash": "8b356614c969d5dda65e9672e6f7e05a0c4b96a61ee14d8164d7d288f5e92ee1", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 1761, "end_char_idx": 3925, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
We find that the modular design of a network significantly increases sample efficiency in reinforcement learning and few-shot generalisation in supervised learning, compared to baselines with fully shared, task-specific, or conditionally generated parameters where knowledge is entangled across tasks. In addition, we show how discrete skills help interpretability, as they yield an explicit hierarchy of tasks.*

</hfoption>
<hfoption id="Multi-Head Adapter Routing for Cross-Task Generalization">

The abstract from the paper is:

*Parameter-efficient fine-tuning (PEFT) for cross-task generalization consists in pre-training adapters on a multi-task training set before few-shot adaptation to test tasks. Polytropon [Ponti et al., 2023] (Poly) jointly learns an inventory of adapters and a routing function that selects a (variable-size) subset of adapters for each task during both pre-training and few-shot adaptation. In this paper, we investigate the role that adapter routing plays in its success and design new variants based on our findings. First, we build on the intuition that finer-grained routing provides more expressivity. Hence, we propose MHR (Multi-Head Routing), which combines subsets of adapter parameters and outperforms Poly under a comparable parameter budget; by only fine-tuning the routing function and not the adapters (MHR-z), we achieve competitive performance with extreme parameter efficiency. Second, we find that Poly/MHR performance is a result of better multi-task optimization, rather than modular inductive biases that facilitate adapter recombination and local adaptation, as previously hypothesized. In fact, we find that MHR exhibits higher gradient alignment between tasks than any other method. Since this implies that routing is only crucial during multi-task pre-training, we propose MHR-mu, which discards routing and fine-tunes the average of the pre-trained adapters during few-shot adaptation. This establishes MHR-mu as an effective method for single-adapter fine-tuning.*.

</hfoption>
</hfoptions>

## PolyConfig

[[autodoc]] tuners.poly.config.PolyConfig

## PolyModel

[[autodoc]] tuners.poly.model.PolyModel


key: _node_content
string_value:
{"id_": "a17cbce8-214b-45da-b09d-e4391b482c27", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/peft/package_reference/oft", "title": "OFT", "tokens": 522, "retrieve_doc": true, "source": "peft"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "995bb5f5-0d66-4ec5-9844-3f7882ef0cc3", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/peft/package_reference/oft", "title": "OFT", "tokens": 522, "retrieve_doc": true, "source": "peft"}, "hash": "f3ca16c78fe957ed1a12aeb2ed0f25a9ab34ae9452bb3b2c8dd93366cd836580", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 0, "end_char_idx": 1794, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
# OFT

[Orthogonal Finetuning (OFT)](https://hf.co/papers/2306.07280) is a method developed for adapting text-to-image diffusion models. It works by reparameterizing the pretrained weight matrices with it's orthogonal matrix to preserve information in the pretrained model. To reduce the number of parameters, OFT introduces a block-diagonal structure in the orthogonal matrix.

The abstract from the paper is:

*Large text-to-image diffusion models have impressive capabilities in generating photorealistic images from text prompts. How to effectively guide or control these powerful models to perform different downstream tasks becomes an important open problem. To tackle this challenge, we introduce a principled finetuning method -- Orthogonal Finetuning (OFT), for adapting text-to-image diffusion models to downstream tasks. Unlike existing methods, OFT can provably preserve hyperspherical energy which characterizes the pairwise neuron relationship on the unit hypersphere. We find that this property is crucial for preserving the semantic generation ability of text-to-image diffusion models. To improve finetuning stability, we further propose Constrained Orthogonal Finetuning (COFT) which imposes an additional radius constraint to the hypersphere. Specifically, we consider two important finetuning text-to-image tasks: subject-driven generation where the goal is to generate subject-specific images given a few images of a subject and a text prompt, and controllable generation where the goal is to enable the model to take in additional control signals. We empirically show that our OFT framework outperforms existing methods in generation quality and convergence speed*.

## OFTConfig

[[autodoc]] tuners.oft.config.OFTConfig

## OFTModel

[[autodoc]] tuners.oft.model.OFTModel


key: _node_content
string_value:
{"id_": "6fd79e96-580c-42e8-9bb9-7787ac0bd859", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/peft/package_reference/adapter_utils", "title": "LyCORIS", "tokens": 318, "retrieve_doc": true, "source": "peft"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "faa6d64b-be02-4499-9b9f-65cdb9a0ded3", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/peft/package_reference/adapter_utils", "title": "LyCORIS", "tokens": 318, "retrieve_doc": true, "source": "peft"}, "hash": "d2d990522f6dda7c3c52f82c8f2d5a1cd3b4601a59a38b8b0d20cf6d8c164046", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 0, "end_char_idx": 520, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
# LyCORIS

[LyCORIS](https://hf.co/papers/2309.14859) (Lora beYond Conventional methods, Other Rank adaptation Implementations for Stable diffusion) are LoRA-like matrix decomposition adapters that modify the cross-attention layer of the UNet. The [LoHa](loha) and [LoKr](lokr) methods inherit from the `Lycoris` classes here.

## LycorisConfig

[[autodoc]] tuners.lycoris_utils.LycorisConfig

## LycorisLayer

[[autodoc]] tuners.lycoris_utils.LycorisLayer

## LycorisTuner

[[autodoc]] tuners.lycoris_utils.LycorisTuner


key: _node_content
string_value:
{"id_": "9029697c-02ee-4362-b90d-5d257e8768f8", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/peft/package_reference/prefix_tuning", "title": "Prefix tuning", "tokens": 449, "retrieve_doc": true, "source": "peft"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "50f0fad4-5864-46df-8b2d-c7daf54af76f", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/peft/package_reference/prefix_tuning", "title": "Prefix tuning", "tokens": 449, "retrieve_doc": true, "source": "peft"}, "hash": "ace4c74a78b9989c51a230ad79c241791a07a89df97ca9e5acf73fd5214bd8e9", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 0, "end_char_idx": 1380, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
# Prefix tuning

[Prefix tuning](https://hf.co/papers/2101.00190) prefixes a series of task-specific vectors to the input sequence that can be learned while keeping the pretrained model frozen. The prefix parameters are inserted in all of the model layers.

The abstract from the paper is:

*Fine-tuning is the de facto way to leverage large pretrained language models to perform downstream tasks. However, it modifies all the language model parameters and therefore necessitates storing a full copy for each task. In this paper, we propose prefix-tuning, a lightweight alternative to fine-tuning for natural language generation tasks, which keeps language model parameters frozen, but optimizes a small continuous task-specific vector (called the prefix). Prefix-tuning draws inspiration from prompting, allowing subsequent tokens to attend to this prefix as if it were "virtual tokens". We apply prefix-tuning to GPT-2 for table-to-text generation and to BART for summarization. We find that by learning only 0.1\% of the parameters, prefix-tuning obtains comparable performance in the full data setting, outperforms fine-tuning in low-data settings, and extrapolates better to examples with topics unseen during training*.

## PrefixTuningConfig

[[autodoc]] tuners.prefix_tuning.config.PrefixTuningConfig

## PrefixEncoder

[[autodoc]] tuners.prefix_tuning.model.PrefixEncoder


key: _node_content
string_value:
{"id_": "b8aca223-09ae-4af7-b9c3-9a675ea2659d", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/peft/package_reference/lokr", "title": "LoKr", "tokens": 277, "retrieve_doc": true, "source": "peft"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "36fe44e2-f831-4c81-9028-9ec22754ef5e", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/peft/package_reference/lokr", "title": "LoKr", "tokens": 277, "retrieve_doc": true, "source": "peft"}, "hash": "ff4b8b326973fece15243daf72021e7ebdc8d074ece8c5043f37e606d1311ec7", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 0, "end_char_idx": 429, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
# LoKr

Low-Rank Kronecker Product ([LoKr](https://hf.co/papers/2309.14859)), is a LoRA-variant method that approximates the large weight matrix with two low-rank matrices and combines them with the Kronecker product. LoKr also provides an optional third low-rank matrix to provide better control during fine-tuning.

## LoKrConfig

[[autodoc]] tuners.lokr.config.LoKrConfig

## LoKrModel

[[autodoc]] tuners.lokr.model.LoKrModel


key: _node_content
string_value:
{"id_": "ee8bb23b-9ae7-45d4-a081-8f2a38f571ed", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/peft/developer_guides/mixed_models", "title": "Mixed adapter types", "tokens": 659, "retrieve_doc": true, "source": "peft"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "e4d3747c-04f5-4a74-9305-251517a129c7", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/peft/developer_guides/mixed_models", "title": "Mixed adapter types", "tokens": 659, "retrieve_doc": true, "source": "peft"}, "hash": "2f6ea15f66eea267a75fc037cc258b4ffb10b03d52a4d8c4e15d3a864eb261e8", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 0, "end_char_idx": 2190, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
# Mixed adapter types

Normally, it isn't possible to mix different adapter types in 🤗 PEFT. You can create a PEFT model with two different LoRA adapters (which can have different config options), but it is not possible to combine a LoRA and LoHa adapter. With [`PeftMixedModel`] however, this works as long as the adapter types are compatible. The main purpose of allowing mixed adapter types is to combine trained adapters for inference. While it is possible to train a mixed adapter model, this has not been tested and is not recommended.

To load different adapter types into a PEFT model, use [`PeftMixedModel`] instead of [`PeftModel`]:

```py
from peft import PeftMixedModel

base_model = ...  # load the base model, e.g. from transformers
# load first adapter, which will be called "default"
peft_model = PeftMixedModel.from_pretrained(base_model, <path_to_adapter1>)
peft_model.load_adapter(<path_to_adapter2>, adapter_name="other")
peft_model.set_adapter(["default", "other"])
```

The [`~PeftMixedModel.set_adapter`] method is necessary to activate both adapters, otherwise only the first adapter would be active. You can keep adding more adapters by calling [`~PeftModel.add_adapter`] repeatedly.

[`PeftMixedModel`] does not support saving and loading mixed adapters. The adapters should already be trained, and loading the model requires a script to be run each time.

## Tips

- Not all adapter types can be combined. See [`peft.tuners.mixed.COMPATIBLE_TUNER_TYPES`](https://github.com/huggingface/peft/blob/1c1c7fdaa6e6abaa53939b865dee1eded82ad032/src/peft/tuners/mixed/model.py#L35) for a list of compatible types. An error will be raised if you try to combine incompatible adapter types.
- It is possible to mix multiple adapters of the same type which can be useful for combining adapters with very different configs.
- If you want to combine a lot of different adapters, the most performant way to do it is to consecutively add the same adapter types. For example, add LoRA1, LoRA2, LoHa1, LoHa2 in this order, instead of LoRA1, LoHa1, LoRA2, and LoHa2. While the order can affect the output, there is no inherently *best* order, so it is best to choose the fastest one.


key: _node_content
string_value:
{"id_": "b9cf0cda-b3f5-4f60-95a9-57e94a4dbf94", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/peft/developer_guides/troubleshooting", "title": "Troubleshooting", "tokens": 3077, "retrieve_doc": true, "source": "peft"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "080325dc-449a-4057-acc2-ba96494d508a", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/peft/developer_guides/troubleshooting", "title": "Troubleshooting", "tokens": 3077, "retrieve_doc": true, "source": "peft"}, "hash": "8395d6dfa6752383b9872f6ee5643171ddd149a81b5cc070ca4a103a9c4abcc9", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "d89d87da-c79f-4430-9e9b-f0888cdef102", "node_type": "1", "metadata": {}, "hash": "d2f70d87a7708ecd38ce103e5faa8ee177a5e1a350184d5ce6a11efea0a9fef8", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 0, "end_char_idx": 2916, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
# Troubleshooting

If you encounter any issue when using PEFT, please check the following list of common issues and their solutions.

## Examples don't work

Examples often rely on the most recent package versions, so please ensure they're up-to-date. In particular, check the following package versions:

- `peft`
- `transformers`
- `accelerate`
- `torch`

In general, you can update the package version by running this command inside your Python environment:

```bash
python -m pip install -U <package_name>
```

Installing PEFT from source is useful for keeping up with the latest developments:

```bash
python -m pip install git+https://github.com/huggingface/peft
```

## ValueError: Attempting to unscale FP16 gradients

This error probably occurred because the model was loaded with `torch_dtype=torch.float16` and then used in an automatic mixed precision (AMP) context, e.g. by setting `fp16=True` in the [`~transformers.Trainer`] class from 🤗 Transformers. The reason is that when using AMP, trainable weights should never use fp16. To make this work without loading the whole model in fp32, add the following to your code:

```python
peft_model = get_peft_model(...)

# add this:
for param in model.parameters():
    if param.requires_grad:
        param.data = param.data.float()

# proceed as usual
trainer = Trainer(model=peft_model, fp16=True, ...)
trainer.train()
```

Alternatively, you can use the [`~utils.cast_mixed_precision_params`] function to correctly cast the weights:

```python
from peft import cast_mixed_precision_params

peft_model = get_peft_model(...)
cast_mixed_precision_params(peft_model, dtype=torch.float16)

# proceed as usual
trainer = Trainer(model=peft_model, fp16=True, ...)
trainer.train()
```

<Tip>

Starting from PEFT verion v0.12.0, PEFT automatically promotes the dtype of adapter weights from `torch.float16` and `torch.bfloat16` to `torch.float32` where appropriate. To _prevent_ this behavior, you can pass `autocast_adapter_dtype=False` to [`~get_peft_model`], to [`~PeftModel.from_pretrained`], and to [`~PeftModel.load_adapter`].

</Tip>

## Bad results from a loaded PEFT model

There can be several reasons for getting a poor result from a loaded PEFT model which are listed below. If you're still unable to troubleshoot the problem, see if anyone else had a similar [issue](https://github.com/huggingface/peft/issues) on GitHub, and if you can't find any, open a new issue.

When opening an issue, it helps a lot if you provide a minimal code example that reproduces the issue. Also, please report if the loaded model performs at the same level as the model did before fine-tuning, if it performs at a random level, or if it is only slightly worse than expected. This information helps us identify the problem more quickly.

### Random deviations

If your model outputs are not exactly the same as previous runs, there could be an issue with random elements.


key: _node_content
string_value:
{"id_": "d89d87da-c79f-4430-9e9b-f0888cdef102", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/peft/developer_guides/troubleshooting", "title": "Troubleshooting", "tokens": 3077, "retrieve_doc": true, "source": "peft"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "080325dc-449a-4057-acc2-ba96494d508a", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/peft/developer_guides/troubleshooting", "title": "Troubleshooting", "tokens": 3077, "retrieve_doc": true, "source": "peft"}, "hash": "8395d6dfa6752383b9872f6ee5643171ddd149a81b5cc070ca4a103a9c4abcc9", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "b9cf0cda-b3f5-4f60-95a9-57e94a4dbf94", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/peft/developer_guides/troubleshooting", "title": "Troubleshooting", "tokens": 3077, "retrieve_doc": true, "source": "peft"}, "hash": "3524d599c00d8619816ccdac260bf4bcf6ea7870dce2d5301eff87c98c4b055f", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "9f6f9e4e-5953-4941-b6d1-681bcf79970f", "node_type": "1", "metadata": {}, "hash": "5ff0a4b4616f9ecb4905fa70b35345593a473ddfa3c3ebc99ee0359711cdda85", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 1918, "end_char_idx": 5481, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
To _prevent_ this behavior, you can pass `autocast_adapter_dtype=False` to [`~get_peft_model`], to [`~PeftModel.from_pretrained`], and to [`~PeftModel.load_adapter`].

</Tip>

## Bad results from a loaded PEFT model

There can be several reasons for getting a poor result from a loaded PEFT model which are listed below. If you're still unable to troubleshoot the problem, see if anyone else had a similar [issue](https://github.com/huggingface/peft/issues) on GitHub, and if you can't find any, open a new issue.

When opening an issue, it helps a lot if you provide a minimal code example that reproduces the issue. Also, please report if the loaded model performs at the same level as the model did before fine-tuning, if it performs at a random level, or if it is only slightly worse than expected. This information helps us identify the problem more quickly.

### Random deviations

If your model outputs are not exactly the same as previous runs, there could be an issue with random elements. For example:

1. please ensure it is in `.eval()` mode, which is important, for instance, if the model uses dropout
2. if you use [`~transformers.GenerationMixin.generate`] on a language model, there could be random sampling, so obtaining the same result requires setting a random seed
3. if you used quantization and merged the weights, small deviations are expected due to rounding errors

### Incorrectly loaded model

Please ensure that you load the model correctly. A common error is trying to load a _trained_ model with [`get_peft_model`] which is incorrect. Instead, the loading code should look like this:

```python
from peft import PeftModel, PeftConfig

base_model = ...  # to load the base model, use the same code as when you trained it
config = PeftConfig.from_pretrained(peft_model_id)
peft_model = PeftModel.from_pretrained(base_model, peft_model_id)
```

### Randomly initialized layers

For some tasks, it is important to correctly configure `modules_to_save` in the config to account for randomly initialized layers. 

As an example, this is necessary if you use LoRA to fine-tune a language model for sequence classification because 🤗 Transformers adds a randomly initialized classification head on top of the model. If you do not add this layer to `modules_to_save`, the classification head won't be saved. The next time you load the model, you'll get a _different_ randomly initialized classification head, resulting in completely different results.

PEFT tries to correctly guess the `modules_to_save` if you provide the `task_type` argument in the config. This should work for transformers models that follow the standard naming scheme. It is always a good idea to double check though because we can't guarantee all models follow the naming scheme.

When you load a transformers model that has randomly initialized layers, you should see a warning along the lines of:

```
Some weights of <MODEL> were not initialized from the model checkpoint at <ID> and are newly initialized: [<LAYER_NAMES>].
You should probably TRAIN this model on a down-stream task to be able to use it for predictions and inference.
```

The mentioned layers should be added to `modules_to_save` in the config to avoid the described problem.

### Extending the vocabulary

For many language fine-tuning tasks, extending the model's vocabulary is necessary since new tokens are being introduced. This requires extending the embedding layer to account for the new tokens and also storing the embedding layer in addition to the adapter weights when saving the adapter.


key: _node_content
string_value:
{"id_": "9f6f9e4e-5953-4941-b6d1-681bcf79970f", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/peft/developer_guides/troubleshooting", "title": "Troubleshooting", "tokens": 3077, "retrieve_doc": true, "source": "peft"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "080325dc-449a-4057-acc2-ba96494d508a", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/peft/developer_guides/troubleshooting", "title": "Troubleshooting", "tokens": 3077, "retrieve_doc": true, "source": "peft"}, "hash": "8395d6dfa6752383b9872f6ee5643171ddd149a81b5cc070ca4a103a9c4abcc9", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "d89d87da-c79f-4430-9e9b-f0888cdef102", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/peft/developer_guides/troubleshooting", "title": "Troubleshooting", "tokens": 3077, "retrieve_doc": true, "source": "peft"}, "hash": "4d9d5015cda1cef2cd8054457bdc9c5635331510627c1da6181e1ce983cccdcd", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "f87f4ef7-69f8-4e41-a10b-1c9722eec035", "node_type": "1", "metadata": {}, "hash": "a1343d5e18881a6c72516cd373b1360e389f827a3ea97bae6bd926483a00ab4d", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 3956, "end_char_idx": 7263, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
As an example, this is necessary if you use LoRA to fine-tune a language model for sequence classification because 🤗 Transformers adds a randomly initialized classification head on top of the model. If you do not add this layer to `modules_to_save`, the classification head won't be saved. The next time you load the model, you'll get a _different_ randomly initialized classification head, resulting in completely different results.

PEFT tries to correctly guess the `modules_to_save` if you provide the `task_type` argument in the config. This should work for transformers models that follow the standard naming scheme. It is always a good idea to double check though because we can't guarantee all models follow the naming scheme.

When you load a transformers model that has randomly initialized layers, you should see a warning along the lines of:

```
Some weights of <MODEL> were not initialized from the model checkpoint at <ID> and are newly initialized: [<LAYER_NAMES>].
You should probably TRAIN this model on a down-stream task to be able to use it for predictions and inference.
```

The mentioned layers should be added to `modules_to_save` in the config to avoid the described problem.

### Extending the vocabulary

For many language fine-tuning tasks, extending the model's vocabulary is necessary since new tokens are being introduced. This requires extending the embedding layer to account for the new tokens and also storing the embedding layer in addition to the adapter weights when saving the adapter.

Save the embedding layer by adding it to the `target_modules` of the config. The embedding layer name must follow the standard naming scheme from Transformers. For example, the Mistral config could look like this:

```python
config = LoraConfig(..., target_modules=["embed_tokens", "lm_head", "q_proj", "v_proj"])
```

Once added to `target_modules`, PEFT automatically stores the embedding layer when saving the adapter if the model has the [`~transformers.PreTrainedModel.get_input_embeddings`] and [`~transformers.PreTrainedModel.get_output_embeddings`]. This is generally the case for Transformers models.

If the model's embedding layer doesn't follow the Transformer's naming scheme, you can still save it by manually passing `save_embedding_layers=True` when saving the adapter:

```python
model = get_peft_model(...)
# train the model
model.save_pretrained("my_adapter", save_embedding_layers=True)
```

For inference, load the base model first and resize it the same way you did before you trained the model. After you've resized the base model, you can load the PEFT checkpoint.

For a complete example, please check out [this notebook](https://github.com/huggingface/peft/blob/main/examples/causal_language_modeling/peft_lora_clm_with_additional_tokens.ipynb).

### Check layer and model status

Sometimes a PEFT model can end up in a bad state, especially when handling multiple adapters. There can be some confusion around what adapters exist, which one is active, which one is merged, etc. To help investigate this issue, call the [`~peft.PeftModel.get_layer_status`] and the [`~peft.PeftModel.get_model_status`] methods. 

The [`~peft.PeftModel.get_layer_status`] method gives you a detailed overview of each targeted layer's active, merged, and available adapters.


key: _node_content
string_value:
{"id_": "f87f4ef7-69f8-4e41-a10b-1c9722eec035", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/peft/developer_guides/troubleshooting", "title": "Troubleshooting", "tokens": 3077, "retrieve_doc": true, "source": "peft"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "080325dc-449a-4057-acc2-ba96494d508a", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/peft/developer_guides/troubleshooting", "title": "Troubleshooting", "tokens": 3077, "retrieve_doc": true, "source": "peft"}, "hash": "8395d6dfa6752383b9872f6ee5643171ddd149a81b5cc070ca4a103a9c4abcc9", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "9f6f9e4e-5953-4941-b6d1-681bcf79970f", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/peft/developer_guides/troubleshooting", "title": "Troubleshooting", "tokens": 3077, "retrieve_doc": true, "source": "peft"}, "hash": "b54756583eede28361a2cb5696a3fae5bb437e8cb17ffeebdc86f1e428af83fe", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "13ce8483-a060-43e3-95a9-e00b7cd1a09b", "node_type": "1", "metadata": {}, "hash": "7da36c7399678a1f6d4f7bd9ee8dbbf18807a86213969527ef2a483a3f88138d", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 5483, "end_char_idx": 9037, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
Save the embedding layer by adding it to the `target_modules` of the config. The embedding layer name must follow the standard naming scheme from Transformers. For example, the Mistral config could look like this:

```python
config = LoraConfig(..., target_modules=["embed_tokens", "lm_head", "q_proj", "v_proj"])
```

Once added to `target_modules`, PEFT automatically stores the embedding layer when saving the adapter if the model has the [`~transformers.PreTrainedModel.get_input_embeddings`] and [`~transformers.PreTrainedModel.get_output_embeddings`]. This is generally the case for Transformers models.

If the model's embedding layer doesn't follow the Transformer's naming scheme, you can still save it by manually passing `save_embedding_layers=True` when saving the adapter:

```python
model = get_peft_model(...)
# train the model
model.save_pretrained("my_adapter", save_embedding_layers=True)
```

For inference, load the base model first and resize it the same way you did before you trained the model. After you've resized the base model, you can load the PEFT checkpoint.

For a complete example, please check out [this notebook](https://github.com/huggingface/peft/blob/main/examples/causal_language_modeling/peft_lora_clm_with_additional_tokens.ipynb).

### Check layer and model status

Sometimes a PEFT model can end up in a bad state, especially when handling multiple adapters. There can be some confusion around what adapters exist, which one is active, which one is merged, etc. To help investigate this issue, call the [`~peft.PeftModel.get_layer_status`] and the [`~peft.PeftModel.get_model_status`] methods. 

The [`~peft.PeftModel.get_layer_status`] method gives you a detailed overview of each targeted layer's active, merged, and available adapters.

```python
>>> from transformers import AutoModel
>>> from peft import get_peft_model, LoraConfig

>>> model_id = "google/flan-t5-small"
>>> model = AutoModel.from_pretrained(model_id)
>>> model = get_peft_model(model, LoraConfig())

>>> model.get_layer_status()
[TunerLayerStatus(name='model.encoder.block.0.layer.0.SelfAttention.q',
                  module_type='lora.Linear',
                  enabled=True,
                  active_adapters=['default'],
                  merged_adapters=[],
                  requires_grad={'default': True},
                  available_adapters=['default']),
 TunerLayerStatus(name='model.encoder.block.0.layer.0.SelfAttention.v',
                  module_type='lora.Linear',
                  enabled=True,
                  active_adapters=['default'],
                  merged_adapters=[],
                  requires_grad={'default': True},
                  available_adapters=['default']),
...]

>>> model.get_model_status()
TunerModelStatus(
    base_model_type='T5Model',
    adapter_model_type='LoraModel',
    peft_types={'default': 'LORA'},
    trainable_params=344064,
    total_params=60855680,
    num_adapter_layers=48,
    enabled=True,
    active_adapters=['default'],
    merged_adapters=[],
    requires_grad={'default': True},
    available_adapters=['default'],
)
```

In the model state output, you should look out for entries that say `"irregular"`. This means PEFT detected an inconsistent state in the model. For instance, if `merged_adapters="irregular"`, it means that for at least one adapter, it was merged on some target modules but not on others. The inference results will most likely be incorrect as a result.

The best way to resolve this issue is to reload the whole model and adapter checkpoint(s).


key: _node_content
string_value:
{"id_": "13ce8483-a060-43e3-95a9-e00b7cd1a09b", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/peft/developer_guides/troubleshooting", "title": "Troubleshooting", "tokens": 3077, "retrieve_doc": true, "source": "peft"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "080325dc-449a-4057-acc2-ba96494d508a", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/peft/developer_guides/troubleshooting", "title": "Troubleshooting", "tokens": 3077, "retrieve_doc": true, "source": "peft"}, "hash": "8395d6dfa6752383b9872f6ee5643171ddd149a81b5cc070ca4a103a9c4abcc9", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "f87f4ef7-69f8-4e41-a10b-1c9722eec035", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/peft/developer_guides/troubleshooting", "title": "Troubleshooting", "tokens": 3077, "retrieve_doc": true, "source": "peft"}, "hash": "a1600899f548bbb8ab6039aae217786354e5ae1b7d31218193c5801f7000fe2f", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "74e55f3a-d261-44cf-8840-55aa4fd85d87", "node_type": "1", "metadata": {}, "hash": "3424987fc654717cf762c13a9d94ebc16589ad173d8a4f48a5824c30bd49a727", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 7265, "end_char_idx": 9601, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
```python
>>> from transformers import AutoModel
>>> from peft import get_peft_model, LoraConfig

>>> model_id = "google/flan-t5-small"
>>> model = AutoModel.from_pretrained(model_id)
>>> model = get_peft_model(model, LoraConfig())

>>> model.get_layer_status()
[TunerLayerStatus(name='model.encoder.block.0.layer.0.SelfAttention.q',
                  module_type='lora.Linear',
                  enabled=True,
                  active_adapters=['default'],
                  merged_adapters=[],
                  requires_grad={'default': True},
                  available_adapters=['default']),
 TunerLayerStatus(name='model.encoder.block.0.layer.0.SelfAttention.v',
                  module_type='lora.Linear',
                  enabled=True,
                  active_adapters=['default'],
                  merged_adapters=[],
                  requires_grad={'default': True},
                  available_adapters=['default']),
...]

>>> model.get_model_status()
TunerModelStatus(
    base_model_type='T5Model',
    adapter_model_type='LoraModel',
    peft_types={'default': 'LORA'},
    trainable_params=344064,
    total_params=60855680,
    num_adapter_layers=48,
    enabled=True,
    active_adapters=['default'],
    merged_adapters=[],
    requires_grad={'default': True},
    available_adapters=['default'],
)
```

In the model state output, you should look out for entries that say `"irregular"`. This means PEFT detected an inconsistent state in the model. For instance, if `merged_adapters="irregular"`, it means that for at least one adapter, it was merged on some target modules but not on others. The inference results will most likely be incorrect as a result.

The best way to resolve this issue is to reload the whole model and adapter checkpoint(s). Ensure that you don't perform any incorrect operations on the model, e.g. manually merging adapters on some modules but not others.

Convert the layer status into a pandas `DataFrame` for an easier visual inspection.

```python
from dataclasses import asdict
import pandas as pd

df = pd.DataFrame(asdict(layer) for layer in model.get_layer_status())
```

It is possible to get this information for non-PEFT models if they are using PEFT layers under the hood, but some information like the `base_model_type` or the `peft_types` cannot be determined in that case.


key: _node_content
string_value:
{"id_": "74e55f3a-d261-44cf-8840-55aa4fd85d87", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/peft/developer_guides/troubleshooting", "title": "Troubleshooting", "tokens": 3077, "retrieve_doc": true, "source": "peft"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "080325dc-449a-4057-acc2-ba96494d508a", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/peft/developer_guides/troubleshooting", "title": "Troubleshooting", "tokens": 3077, "retrieve_doc": true, "source": "peft"}, "hash": "8395d6dfa6752383b9872f6ee5643171ddd149a81b5cc070ca4a103a9c4abcc9", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "13ce8483-a060-43e3-95a9-e00b7cd1a09b", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/peft/developer_guides/troubleshooting", "title": "Troubleshooting", "tokens": 3077, "retrieve_doc": true, "source": "peft"}, "hash": "3785f197eef5a5f61973f505dd61c19a46976c1c70bfe91650d52b37e96c830c", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "8a3b295a-631b-43e2-ba89-c0caaab3eacc", "node_type": "1", "metadata": {}, "hash": "4df93fc0b71268c03ade5b4083757a21464b8247819fd33c7277bf4a9c8b10bb", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 8676, "end_char_idx": 11925, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
This means PEFT detected an inconsistent state in the model. For instance, if `merged_adapters="irregular"`, it means that for at least one adapter, it was merged on some target modules but not on others. The inference results will most likely be incorrect as a result.

The best way to resolve this issue is to reload the whole model and adapter checkpoint(s). Ensure that you don't perform any incorrect operations on the model, e.g. manually merging adapters on some modules but not others.

Convert the layer status into a pandas `DataFrame` for an easier visual inspection.

```python
from dataclasses import asdict
import pandas as pd

df = pd.DataFrame(asdict(layer) for layer in model.get_layer_status())
```

It is possible to get this information for non-PEFT models if they are using PEFT layers under the hood, but some information like the `base_model_type` or the `peft_types` cannot be determined in that case. As an example, you can call this on a [diffusers](https://huggingface.co/docs/diffusers/index) model like so:

```python
>>> import torch
>>> from diffusers import StableDiffusionPipeline
>>> from peft import get_model_status, get_layer_status

>>> path = "runwayml/stable-diffusion-v1-5"
>>> lora_id = "takuma104/lora-test-text-encoder-lora-target"
>>> pipe = StableDiffusionPipeline.from_pretrained(path, torch_dtype=torch.float16)
>>> pipe.load_lora_weights(lora_id, adapter_name="adapter-1")
>>> pipe.load_lora_weights(lora_id, adapter_name="adapter-2")
>>> pipe.set_lora_device(["adapter-2"], "cuda")
>>> get_layer_status(pipe.text_encoder)
[TunerLayerStatus(name='text_model.encoder.layers.0.self_attn.k_proj',
                  module_type='lora.Linear',
                  enabled=True,
                  active_adapters=['adapter-2'],
                  merged_adapters=[],
                  requires_grad={'adapter-1': False, 'adapter-2': True},
                  available_adapters=['adapter-1', 'adapter-2'],
                  devices={'adapter-1': ['cpu'], 'adapter-2': ['cuda']}),
 TunerLayerStatus(name='text_model.encoder.layers.0.self_attn.v_proj',
                  module_type='lora.Linear',
                  enabled=True,
                  active_adapters=['adapter-2'],
                  merged_adapters=[],
                  requires_grad={'adapter-1': False, 'adapter-2': True},
                  devices={'adapter-1': ['cpu'], 'adapter-2': ['cuda']}),
...]

>>> get_model_status(pipe.unet)
TunerModelStatus(
    base_model_type='other',
    adapter_model_type='None',
    peft_types={},
    trainable_params=797184,
    total_params=861115332,
    num_adapter_layers=128,
    enabled=True,
    active_adapters=['adapter-2'],
    merged_adapters=[],
    requires_grad={'adapter-1': False, 'adapter-2': True},
    available_adapters=['adapter-1', 'adapter-2'],
    devices={'adapter-1': ['cpu'], 'adapter-2': ['cuda']},
)
```

## Reproducibility

### Models using batch norm

When loading a trained PEFT model where the base model uses batch norm (e.g. `torch.nn.BatchNorm1d` or `torch.nn.BatchNorm2d`), you may find that you cannot reproduce the exact same outputs. This is because the batch norm layers keep track of running stats during training, but these stats are not part of the PEFT checkpoint.


key: _node_content
string_value:
{"id_": "8a3b295a-631b-43e2-ba89-c0caaab3eacc", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/peft/developer_guides/troubleshooting", "title": "Troubleshooting", "tokens": 3077, "retrieve_doc": true, "source": "peft"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "080325dc-449a-4057-acc2-ba96494d508a", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/peft/developer_guides/troubleshooting", "title": "Troubleshooting", "tokens": 3077, "retrieve_doc": true, "source": "peft"}, "hash": "8395d6dfa6752383b9872f6ee5643171ddd149a81b5cc070ca4a103a9c4abcc9", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "74e55f3a-d261-44cf-8840-55aa4fd85d87", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/peft/developer_guides/troubleshooting", "title": "Troubleshooting", "tokens": 3077, "retrieve_doc": true, "source": "peft"}, "hash": "d626626c7e7b8f1185897e526aef02cda06a6c0eac90d230b590519a605dd5d5", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 11676, "end_char_idx": 13075, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
`torch.nn.BatchNorm1d` or `torch.nn.BatchNorm2d`), you may find that you cannot reproduce the exact same outputs. This is because the batch norm layers keep track of running stats during training, but these stats are not part of the PEFT checkpoint. Therefore, when you load the PEFT model, the running stats of the base model will be used (i.e. from before training with PEFT).

Depending on your use case, this may not be a big deal. If, however, you need your outputs to be 100% reproducible, you can achieve this by adding the batch norm layers to `modules_to_save`. Below is an example of this using resnet and LoRA. Notice that we set `modules_to_save=["classifier", "normalization"]`. We need the `"classifier"` argument because our task is image classification, and we add the `"normalization"` argument to ensure that the batch norm layers are saved in the PEFT checkpoint.

```python
from transformers import AutoModelForImageClassification
from peft import LoraConfig, get_peft_model

model_id = "microsoft/resnet-18"
base_model = AutoModelForImageClassification.from_pretrained(self.model_id)
config = LoraConfig(
    target_modules=["convolution"],
    modules_to_save=["classifier", "normalization"],
),
```

Depending on the type of model you use, the batch norm layers could have different names than `"normalization"`, so please ensure that the name matches your model architecture.


key: _node_content
string_value:
{"id_": "d8166dca-49e3-4674-9930-75c1f7fda0de", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/peft/developer_guides/lora", "title": "LoRA", "tokens": 5004, "retrieve_doc": true, "source": "peft"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "dcfe3317-4cf4-4f88-a58f-e4b1bbcbf95e", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/peft/developer_guides/lora", "title": "LoRA", "tokens": 5004, "retrieve_doc": true, "source": "peft"}, "hash": "d7f9d6c9638ad92fa339ddcb55d6b31c1ef2d7119faab2bfd5c6bdbe3c997bd1", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "10ef9859-85a6-48ee-a11e-d7b13ae3d55e", "node_type": "1", "metadata": {}, "hash": "d036a2d6906f2e8b6361d08d3b370114b5e05c1c648164fb045cad146e712a33", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 0, "end_char_idx": 3319, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
# LoRA

LoRA is low-rank decomposition method to reduce the number of trainable parameters which speeds up finetuning large models and uses less memory. In PEFT, using LoRA is as easy as setting up a [`LoraConfig`] and wrapping it with [`get_peft_model`] to create a trainable [`PeftModel`].

This guide explores in more detail other options and features for using LoRA.

## Initialization

The initialization of LoRA weights is controlled by the parameter `init_lora_weights` in [`LoraConfig`]. By default, PEFT initializes LoRA weights with Kaiming-uniform for weight A and zeros for weight B resulting in an identity transform (same as the reference [implementation](https://github.com/microsoft/LoRA)).

It is also possible to pass `init_lora_weights="gaussian"`. As the name suggests, this initializes weight A with a Gaussian distribution and zeros for weight B (this is how [Diffusers](https://huggingface.co/docs/diffusers/index) initializes LoRA weights).

```py
from peft import LoraConfig

config = LoraConfig(init_lora_weights="gaussian", ...)
```

There is also an option to set `init_lora_weights=False` which is useful for debugging and testing. This should be the only time you use this option. When choosing this option, the LoRA weights are initialized such that they do *not* result in an identity transform.

```py
from peft import LoraConfig

config = LoraConfig(init_lora_weights=False, ...)
```

### PiSSA
[PiSSA](https://arxiv.org/abs/2404.02948) initializes the LoRA adapter using the principal singular values and singular vectors. This straightforward modification allows PiSSA to converge more rapidly than LoRA and ultimately attain superior performance. Moreover, PiSSA reduces the quantization error compared to QLoRA, leading to further enhancements. 

Configure the initialization method to "pissa", which may take several minutes to execute SVD on the pre-trained model:
```python
from peft import LoraConfig
config = LoraConfig(init_lora_weights="pissa", ...)
```
Alternatively, execute fast SVD, which takes only a few seconds. The number of iterations determines the trade-off between the error and computation time:
```python
lora_config = LoraConfig(init_lora_weights="pissa_niter_[number of iters]", ...) 
```
For detailed instruction on using PiSSA, please follow [these instructions](https://github.com/fxmeng/peft/tree/main/examples/pissa_finetuning).

### OLoRA
[OLoRA](https://arxiv.org/abs/2406.01775) utilizes QR decomposition to initialize the LoRA adapters. OLoRA translates the base weights of the model by a factor of their QR decompositions, i.e., it mutates the weights before performing any training on them. This approach significantly improves stability, accelerates convergence speed, and ultimately achieves superior performance.

You just need to pass a single additional option to use OLoRA:
```python
from peft import LoraConfig
config = LoraConfig(init_lora_weights="olora", ...)
```
For more advanced usage, please refer to our [documentation](https://github.com/huggingface/peft/tree/main/examples/olora_finetuning).
### LoftQ

#### Standard approach

When quantizing the base model for QLoRA training, consider using the [LoftQ initialization](https://arxiv.org/abs/2310.08659), which has been shown to improve performance when training quantized models.


key: _node_content
string_value:
{"id_": "10ef9859-85a6-48ee-a11e-d7b13ae3d55e", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/peft/developer_guides/lora", "title": "LoRA", "tokens": 5004, "retrieve_doc": true, "source": "peft"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "dcfe3317-4cf4-4f88-a58f-e4b1bbcbf95e", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/peft/developer_guides/lora", "title": "LoRA", "tokens": 5004, "retrieve_doc": true, "source": "peft"}, "hash": "d7f9d6c9638ad92fa339ddcb55d6b31c1ef2d7119faab2bfd5c6bdbe3c997bd1", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "d8166dca-49e3-4674-9930-75c1f7fda0de", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/peft/developer_guides/lora", "title": "LoRA", "tokens": 5004, "retrieve_doc": true, "source": "peft"}, "hash": "1d4c5e5a6e71b982288bb5959b03eac834fded9309b035b286a1a7edad849f2f", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "9abbb73c-5786-4d6a-b1c5-596b4dcee4d7", "node_type": "1", "metadata": {}, "hash": "ef4a227d517731f124e42908c65b35327a0daad9d0666d086d6614232f0b0496", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 1684, "end_char_idx": 4903, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
Moreover, PiSSA reduces the quantization error compared to QLoRA, leading to further enhancements. 

Configure the initialization method to "pissa", which may take several minutes to execute SVD on the pre-trained model:
```python
from peft import LoraConfig
config = LoraConfig(init_lora_weights="pissa", ...)
```
Alternatively, execute fast SVD, which takes only a few seconds. The number of iterations determines the trade-off between the error and computation time:
```python
lora_config = LoraConfig(init_lora_weights="pissa_niter_[number of iters]", ...) 
```
For detailed instruction on using PiSSA, please follow [these instructions](https://github.com/fxmeng/peft/tree/main/examples/pissa_finetuning).

### OLoRA
[OLoRA](https://arxiv.org/abs/2406.01775) utilizes QR decomposition to initialize the LoRA adapters. OLoRA translates the base weights of the model by a factor of their QR decompositions, i.e., it mutates the weights before performing any training on them. This approach significantly improves stability, accelerates convergence speed, and ultimately achieves superior performance.

You just need to pass a single additional option to use OLoRA:
```python
from peft import LoraConfig
config = LoraConfig(init_lora_weights="olora", ...)
```
For more advanced usage, please refer to our [documentation](https://github.com/huggingface/peft/tree/main/examples/olora_finetuning).
### LoftQ

#### Standard approach

When quantizing the base model for QLoRA training, consider using the [LoftQ initialization](https://arxiv.org/abs/2310.08659), which has been shown to improve performance when training quantized models. The idea is that the LoRA weights are initialized such that the quantization error is minimized. To use LoftQ, follow [these instructions](https://github.com/huggingface/peft/tree/main/examples/loftq_finetuning).

In general, for LoftQ to work best, it is recommended to target as many layers with LoRA as possible, since those not targeted cannot have LoftQ applied. This means that passing `LoraConfig(..., target_modules="all-linear")` will most likely give the best results. Also, you should use `nf4` as quant type in your quantization config when using 4bit quantization, i.e. `BitsAndBytesConfig(load_in_4bit=True, bnb_4bit_quant_type="nf4")`.

#### A more convienient way

An easier but more limited way to apply LoftQ initialization is to use the convenience function `replace_lora_weights_loftq`. This takes the quantized PEFT model as input and replaces the LoRA weights in-place with their LoftQ-initialized counterparts.

```python
from peft import replace_lora_weights_loftq
from transformers import BitsAndBytesConfig

bnb_config = BitsAndBytesConfig(load_in_4bit=True, ...)
base_model = AutoModelForCausalLM.from_pretrained(..., quantization_config=bnb_config)
# note: don't pass init_lora_weights="loftq" or loftq_config!
lora_config = LoraConfig(task_type="CAUSAL_LM")
peft_model = get_peft_model(base_model, lora_config)
replace_lora_weights_loftq(peft_model)
```

`replace_lora_weights_loftq` also allows you to pass a `callback` argument to give you more control over which layers should be modified or not, which empirically can improve the results quite a lot.


key: _node_content
string_value:
{"id_": "9abbb73c-5786-4d6a-b1c5-596b4dcee4d7", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/peft/developer_guides/lora", "title": "LoRA", "tokens": 5004, "retrieve_doc": true, "source": "peft"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "dcfe3317-4cf4-4f88-a58f-e4b1bbcbf95e", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/peft/developer_guides/lora", "title": "LoRA", "tokens": 5004, "retrieve_doc": true, "source": "peft"}, "hash": "d7f9d6c9638ad92fa339ddcb55d6b31c1ef2d7119faab2bfd5c6bdbe3c997bd1", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "10ef9859-85a6-48ee-a11e-d7b13ae3d55e", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/peft/developer_guides/lora", "title": "LoRA", "tokens": 5004, "retrieve_doc": true, "source": "peft"}, "hash": "67daf2a04636f581860d3ae103dcb4bcaa4a3096f3c241551a71fb762e707480", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "7bb3cb86-aa8d-4fcd-a433-1d3179950c91", "node_type": "1", "metadata": {}, "hash": "32d3073c0e0de1da8952cfeb1016fdf4b564e2b6578093d32add9c46940ca9ba", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 3320, "end_char_idx": 6355, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
The idea is that the LoRA weights are initialized such that the quantization error is minimized. To use LoftQ, follow [these instructions](https://github.com/huggingface/peft/tree/main/examples/loftq_finetuning).

In general, for LoftQ to work best, it is recommended to target as many layers with LoRA as possible, since those not targeted cannot have LoftQ applied. This means that passing `LoraConfig(..., target_modules="all-linear")` will most likely give the best results. Also, you should use `nf4` as quant type in your quantization config when using 4bit quantization, i.e. `BitsAndBytesConfig(load_in_4bit=True, bnb_4bit_quant_type="nf4")`.

#### A more convienient way

An easier but more limited way to apply LoftQ initialization is to use the convenience function `replace_lora_weights_loftq`. This takes the quantized PEFT model as input and replaces the LoRA weights in-place with their LoftQ-initialized counterparts.

```python
from peft import replace_lora_weights_loftq
from transformers import BitsAndBytesConfig

bnb_config = BitsAndBytesConfig(load_in_4bit=True, ...)
base_model = AutoModelForCausalLM.from_pretrained(..., quantization_config=bnb_config)
# note: don't pass init_lora_weights="loftq" or loftq_config!
lora_config = LoraConfig(task_type="CAUSAL_LM")
peft_model = get_peft_model(base_model, lora_config)
replace_lora_weights_loftq(peft_model)
```

`replace_lora_weights_loftq` also allows you to pass a `callback` argument to give you more control over which layers should be modified or not, which empirically can improve the results quite a lot. To see a more elaborate example of this, check out [this notebook](https://github.com/huggingface/peft/blob/main/examples/loftq_finetuning/LoftQ_weight_replacement.ipynb).

`replace_lora_weights_loftq` implements only one iteration step of LoftQ. This means that only the LoRA weights are updated, instead of iteratevily updating LoRA weights and quantized base model weights. This may lead to lower performance but has the advantage that we can use the original quantized weights derived from the base model, instead of having to keep an extra copy of modified quantized weights. Whether this tradeoff is worthwhile depends on the use case.

At the moment, `replace_lora_weights_loftq` has these additional limitations:

- Model files must be stored as a `safetensors` file.
- Only bitsandbytes 4bit quantization is supported.

<Tip>

Learn more about how PEFT works with quantization in the [Quantization](quantization) guide.

</Tip>

### Rank-stabilized LoRA

Another way to initialize [`LoraConfig`] is with the [rank-stabilized LoRA (rsLoRA)](https://huggingface.co/papers/2312.03732) method. The LoRA architecture scales each adapter during every forward pass by a fixed scalar which is set at initialization and depends on the rank `r`. The scalar is given by `lora_alpha/r` in the original implementation, but rsLoRA uses `lora_alpha/math.sqrt(r)` which stabilizes the adapters and increases the performance potential from using a higher `r`.


key: _node_content
string_value:
{"id_": "7bb3cb86-aa8d-4fcd-a433-1d3179950c91", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/peft/developer_guides/lora", "title": "LoRA", "tokens": 5004, "retrieve_doc": true, "source": "peft"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "dcfe3317-4cf4-4f88-a58f-e4b1bbcbf95e", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/peft/developer_guides/lora", "title": "LoRA", "tokens": 5004, "retrieve_doc": true, "source": "peft"}, "hash": "d7f9d6c9638ad92fa339ddcb55d6b31c1ef2d7119faab2bfd5c6bdbe3c997bd1", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "9abbb73c-5786-4d6a-b1c5-596b4dcee4d7", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/peft/developer_guides/lora", "title": "LoRA", "tokens": 5004, "retrieve_doc": true, "source": "peft"}, "hash": "3f67d36da4ce52a5e17d66abe5d5d626d8e5fe5d5a8e33c83fb44f00ad3cf9b9", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "41f0efb5-5b6a-4aa3-b953-64764bfa2f4b", "node_type": "1", "metadata": {}, "hash": "dd6177676f3fb7ce80764a23ad031083a63785f509341ebfde630fd14cc494e5", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 4904, "end_char_idx": 8081, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
To see a more elaborate example of this, check out [this notebook](https://github.com/huggingface/peft/blob/main/examples/loftq_finetuning/LoftQ_weight_replacement.ipynb).

`replace_lora_weights_loftq` implements only one iteration step of LoftQ. This means that only the LoRA weights are updated, instead of iteratevily updating LoRA weights and quantized base model weights. This may lead to lower performance but has the advantage that we can use the original quantized weights derived from the base model, instead of having to keep an extra copy of modified quantized weights. Whether this tradeoff is worthwhile depends on the use case.

At the moment, `replace_lora_weights_loftq` has these additional limitations:

- Model files must be stored as a `safetensors` file.
- Only bitsandbytes 4bit quantization is supported.

<Tip>

Learn more about how PEFT works with quantization in the [Quantization](quantization) guide.

</Tip>

### Rank-stabilized LoRA

Another way to initialize [`LoraConfig`] is with the [rank-stabilized LoRA (rsLoRA)](https://huggingface.co/papers/2312.03732) method. The LoRA architecture scales each adapter during every forward pass by a fixed scalar which is set at initialization and depends on the rank `r`. The scalar is given by `lora_alpha/r` in the original implementation, but rsLoRA uses `lora_alpha/math.sqrt(r)` which stabilizes the adapters and increases the performance potential from using a higher `r`.

```py
from peft import LoraConfig

config = LoraConfig(use_rslora=True, ...)
```

### Weight-Decomposed Low-Rank Adaptation (DoRA)

This technique decomposes the updates of the weights into two parts, magnitude and direction. Direction is handled by normal LoRA, whereas the magnitude is handled by a separate learnable parameter. This can improve the performance of LoRA, especially at low ranks. For more information on DoRA, see  https://arxiv.org/abs/2402.09353.

```py
from peft import LoraConfig

config = LoraConfig(use_dora=True, ...)
```

If parts of the model or the DoRA adapter are offloaded to CPU you can get a significant speedup at the cost of some temporary (ephemeral) VRAM overhead by using `ephemeral_gpu_offload=True` in `config.runtime_config`.

```py
from peft import LoraConfig, LoraRuntimeConfig

config = LoraConfig(use_dora=True, runtime_config=LoraRuntimeConfig(ephemeral_gpu_offload=True), ...)
```

A `PeftModel` with a DoRA adapter can also be loaded with `ephemeral_gpu_offload=True` flag using the `from_pretrained` method as well as the `load_adapter` method.

```py
from peft import PeftModel

model = PeftModel.from_pretrained(base_model, peft_model_id, ephemeral_gpu_offload=True)
```

#### Caveats

- DoRA only supports linear and Conv2d layers at the momement.
- DoRA introduces a bigger overhead than pure LoRA, so it is recommended to merge weights for inference, see [`LoraModel.merge_and_unload`]. 
- DoRA should work with weights quantized with bitsandbytes ("QDoRA"). However, issues have been reported when using QDoRA with DeepSpeed Zero2.

### QLoRA-style training

The default LoRA settings in PEFT add trainable weights to the query and value layers of each attention block.


key: _node_content
string_value:
{"id_": "41f0efb5-5b6a-4aa3-b953-64764bfa2f4b", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/peft/developer_guides/lora", "title": "LoRA", "tokens": 5004, "retrieve_doc": true, "source": "peft"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "dcfe3317-4cf4-4f88-a58f-e4b1bbcbf95e", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/peft/developer_guides/lora", "title": "LoRA", "tokens": 5004, "retrieve_doc": true, "source": "peft"}, "hash": "d7f9d6c9638ad92fa339ddcb55d6b31c1ef2d7119faab2bfd5c6bdbe3c997bd1", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "7bb3cb86-aa8d-4fcd-a433-1d3179950c91", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/peft/developer_guides/lora", "title": "LoRA", "tokens": 5004, "retrieve_doc": true, "source": "peft"}, "hash": "8052600aa93d2c4c791667506b5587df01f5359cd7765f6ae941815e6a3b57a5", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "dc806092-eac8-47cf-b2ab-ba52a5912591", "node_type": "1", "metadata": {}, "hash": "f38d1c566fa3ac593b0ea049d060a7fa6ffe472317a845e9fa599ff4d4cad160", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 6583, "end_char_idx": 9713, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
Direction is handled by normal LoRA, whereas the magnitude is handled by a separate learnable parameter. This can improve the performance of LoRA, especially at low ranks. For more information on DoRA, see  https://arxiv.org/abs/2402.09353.

```py
from peft import LoraConfig

config = LoraConfig(use_dora=True, ...)
```

If parts of the model or the DoRA adapter are offloaded to CPU you can get a significant speedup at the cost of some temporary (ephemeral) VRAM overhead by using `ephemeral_gpu_offload=True` in `config.runtime_config`.

```py
from peft import LoraConfig, LoraRuntimeConfig

config = LoraConfig(use_dora=True, runtime_config=LoraRuntimeConfig(ephemeral_gpu_offload=True), ...)
```

A `PeftModel` with a DoRA adapter can also be loaded with `ephemeral_gpu_offload=True` flag using the `from_pretrained` method as well as the `load_adapter` method.

```py
from peft import PeftModel

model = PeftModel.from_pretrained(base_model, peft_model_id, ephemeral_gpu_offload=True)
```

#### Caveats

- DoRA only supports linear and Conv2d layers at the momement.
- DoRA introduces a bigger overhead than pure LoRA, so it is recommended to merge weights for inference, see [`LoraModel.merge_and_unload`]. 
- DoRA should work with weights quantized with bitsandbytes ("QDoRA"). However, issues have been reported when using QDoRA with DeepSpeed Zero2.

### QLoRA-style training

The default LoRA settings in PEFT add trainable weights to the query and value layers of each attention block. But [QLoRA](https://hf.co/papers/2305.14314), which adds trainable weights to all the linear layers of a transformer model, can provide performance equal to a fully finetuned model. To apply LoRA to all the linear layers, like in QLoRA, set `target_modules="all-linear"` (easier than specifying individual modules by name which can vary depending on the architecture).

```py
config = LoraConfig(target_modules="all-linear", ...)
```

### Memory efficient Layer Replication with LoRA

An approach used to improve the performance of models is to expand a model by duplicating layers in the model to build a larger model from a pretrained model of a given size. For example increasing a 7B model to a 10B model as described in the [SOLAR](https://arxiv.org/abs/2312.15166) paper. PEFT LoRA supports this kind of expansion in a memory efficient manner that supports further fine-tuning using LoRA adapters attached to the layers post replication of the layers. The replicated layers do not take additional memory as they share the underlying weights so the only additional memory required is the memory for the adapter weights. To use this feature you would create a config with the `layer_replication` argument.

```py
config = LoraConfig(layer_replication=[[0,4], [2,5]], ...)
```

Assuming the original model had 5 layers `[0, 1, 2 ,3, 4]`, this would create a model with 7 layers arranged as `[0, 1, 2, 3, 2, 3, 4]`. This follows the [mergekit](https://github.com/arcee-ai/mergekit) pass through merge convention where sequences of layers specified as start inclusive and end exclusive tuples are stacked to build the final model.


key: _node_content
string_value:
{"id_": "dc806092-eac8-47cf-b2ab-ba52a5912591", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/peft/developer_guides/lora", "title": "LoRA", "tokens": 5004, "retrieve_doc": true, "source": "peft"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "dcfe3317-4cf4-4f88-a58f-e4b1bbcbf95e", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/peft/developer_guides/lora", "title": "LoRA", "tokens": 5004, "retrieve_doc": true, "source": "peft"}, "hash": "d7f9d6c9638ad92fa339ddcb55d6b31c1ef2d7119faab2bfd5c6bdbe3c997bd1", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "41f0efb5-5b6a-4aa3-b953-64764bfa2f4b", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/peft/developer_guides/lora", "title": "LoRA", "tokens": 5004, "retrieve_doc": true, "source": "peft"}, "hash": "6c10131efcd22e7e049057a3defcfc1d1bb7e149fad02663ae84740faaec9bb2", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "30ed2b36-b888-4186-a66b-3303f82f76c3", "node_type": "1", "metadata": {}, "hash": "8ffb3715c6d7b6e85190d557135514d4b9f0c905d6e7bd6afa2788db5cdd025d", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 8082, "end_char_idx": 10561, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
But [QLoRA](https://hf.co/papers/2305.14314), which adds trainable weights to all the linear layers of a transformer model, can provide performance equal to a fully finetuned model. To apply LoRA to all the linear layers, like in QLoRA, set `target_modules="all-linear"` (easier than specifying individual modules by name which can vary depending on the architecture).

```py
config = LoraConfig(target_modules="all-linear", ...)
```

### Memory efficient Layer Replication with LoRA

An approach used to improve the performance of models is to expand a model by duplicating layers in the model to build a larger model from a pretrained model of a given size. For example increasing a 7B model to a 10B model as described in the [SOLAR](https://arxiv.org/abs/2312.15166) paper. PEFT LoRA supports this kind of expansion in a memory efficient manner that supports further fine-tuning using LoRA adapters attached to the layers post replication of the layers. The replicated layers do not take additional memory as they share the underlying weights so the only additional memory required is the memory for the adapter weights. To use this feature you would create a config with the `layer_replication` argument.

```py
config = LoraConfig(layer_replication=[[0,4], [2,5]], ...)
```

Assuming the original model had 5 layers `[0, 1, 2 ,3, 4]`, this would create a model with 7 layers arranged as `[0, 1, 2, 3, 2, 3, 4]`. This follows the [mergekit](https://github.com/arcee-ai/mergekit) pass through merge convention where sequences of layers specified as start inclusive and end exclusive tuples are stacked to build the final model. Each layer in the final model gets its own distinct set of LoRA adpaters.

[Fewshot-Metamath-OrcaVicuna-Mistral-10B](https://huggingface.co/abacusai/Fewshot-Metamath-OrcaVicuna-Mistral-10B) is an example of a model trained using this method on Mistral-7B expanded to 10B. The
[adapter_config.json](https://huggingface.co/abacusai/Fewshot-Metamath-OrcaVicuna-Mistral-10B/blob/main/adapter_config.json) shows a sample LoRA adapter config applying this method for fine-tuning.

## Optimizers

LoRA training can optionally include special purpose optimizers. Currently the only such optimizer is LoRA+.

### LoRA+ optimized LoRA

LoRA training can be optimized using [LoRA+](https://arxiv.org/abs/2402.12354), which uses different learning rates for the adapter matrices A and B, shown to increase finetuning speed by up to 2x and performance by 1-2%.


key: _node_content
string_value:
{"id_": "30ed2b36-b888-4186-a66b-3303f82f76c3", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/peft/developer_guides/lora", "title": "LoRA", "tokens": 5004, "retrieve_doc": true, "source": "peft"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "dcfe3317-4cf4-4f88-a58f-e4b1bbcbf95e", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/peft/developer_guides/lora", "title": "LoRA", "tokens": 5004, "retrieve_doc": true, "source": "peft"}, "hash": "d7f9d6c9638ad92fa339ddcb55d6b31c1ef2d7119faab2bfd5c6bdbe3c997bd1", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "dc806092-eac8-47cf-b2ab-ba52a5912591", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/peft/developer_guides/lora", "title": "LoRA", "tokens": 5004, "retrieve_doc": true, "source": "peft"}, "hash": "04806c6f95f57aa90a5f7a6bc9a59a61c9990db05f0e147be0460ba3a427a481", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "9c6a2ea2-87b5-451f-990b-b082bd0a76a5", "node_type": "1", "metadata": {}, "hash": "ebe80864749b622188c74addb060fea3c5a4061b51ed5cf56a2f9b526ba84c7c", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 9207, "end_char_idx": 11827, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
To use this feature you would create a config with the `layer_replication` argument.

```py
config = LoraConfig(layer_replication=[[0,4], [2,5]], ...)
```

Assuming the original model had 5 layers `[0, 1, 2 ,3, 4]`, this would create a model with 7 layers arranged as `[0, 1, 2, 3, 2, 3, 4]`. This follows the [mergekit](https://github.com/arcee-ai/mergekit) pass through merge convention where sequences of layers specified as start inclusive and end exclusive tuples are stacked to build the final model. Each layer in the final model gets its own distinct set of LoRA adpaters.

[Fewshot-Metamath-OrcaVicuna-Mistral-10B](https://huggingface.co/abacusai/Fewshot-Metamath-OrcaVicuna-Mistral-10B) is an example of a model trained using this method on Mistral-7B expanded to 10B. The
[adapter_config.json](https://huggingface.co/abacusai/Fewshot-Metamath-OrcaVicuna-Mistral-10B/blob/main/adapter_config.json) shows a sample LoRA adapter config applying this method for fine-tuning.

## Optimizers

LoRA training can optionally include special purpose optimizers. Currently the only such optimizer is LoRA+.

### LoRA+ optimized LoRA

LoRA training can be optimized using [LoRA+](https://arxiv.org/abs/2402.12354), which uses different learning rates for the adapter matrices A and B, shown to increase finetuning speed by up to 2x and performance by 1-2%.

```py
from peft import LoraConfig, get_peft_model
from peft.optimizers import create_loraplus_optimizer
from transformers import Trainer
import bitsandbytes as bnb

base_model = ...
config = LoraConfig(...)
model = get_peft_model(base_model, config)

optimizer = create_loraplus_optimizer(
    model=model,
    optimizer_cls=bnb.optim.Adam8bit,
    lr=5e-5,
    loraplus_lr_ratio=16,
)
scheduler = None

...
trainer = Trainer(
    ...,
    optimizers=(optimizer, scheduler),
)
```

## Merge LoRA weights into the base model

While LoRA is significantly smaller and faster to train, you may encounter latency issues during inference due to separately loading the base model and the LoRA adapter. To eliminate latency, use the [`~LoraModel.merge_and_unload`] function to merge the adapter weights with the base model. This allows you to use the newly merged model as a standalone model. The [`~LoraModel.merge_and_unload`] function doesn't keep the adapter weights in memory.

Below is a diagram that explains the intuition of LoRA adapter merging:

<div class="flex justify-center">
    <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/peft/lora_diagram.png"/>
</div>

We show in the snippets below how to run that using PEFT.


key: _node_content
string_value:
{"id_": "9c6a2ea2-87b5-451f-990b-b082bd0a76a5", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/peft/developer_guides/lora", "title": "LoRA", "tokens": 5004, "retrieve_doc": true, "source": "peft"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "dcfe3317-4cf4-4f88-a58f-e4b1bbcbf95e", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/peft/developer_guides/lora", "title": "LoRA", "tokens": 5004, "retrieve_doc": true, "source": "peft"}, "hash": "d7f9d6c9638ad92fa339ddcb55d6b31c1ef2d7119faab2bfd5c6bdbe3c997bd1", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "30ed2b36-b888-4186-a66b-3303f82f76c3", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/peft/developer_guides/lora", "title": "LoRA", "tokens": 5004, "retrieve_doc": true, "source": "peft"}, "hash": "edc6f8545db621d44f1c9c9dad0af7c4fb2fbfe2b2990222a3730c46ac0c1061", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "aead6548-1117-4ef8-8ccf-63a09c503cf4", "node_type": "1", "metadata": {}, "hash": "54c009eff3815d7a94466f546412fecf5b44ea757849f62aad994c9a252e2f0b", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 10189, "end_char_idx": 12984, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
## Optimizers

LoRA training can optionally include special purpose optimizers. Currently the only such optimizer is LoRA+.

### LoRA+ optimized LoRA

LoRA training can be optimized using [LoRA+](https://arxiv.org/abs/2402.12354), which uses different learning rates for the adapter matrices A and B, shown to increase finetuning speed by up to 2x and performance by 1-2%.

```py
from peft import LoraConfig, get_peft_model
from peft.optimizers import create_loraplus_optimizer
from transformers import Trainer
import bitsandbytes as bnb

base_model = ...
config = LoraConfig(...)
model = get_peft_model(base_model, config)

optimizer = create_loraplus_optimizer(
    model=model,
    optimizer_cls=bnb.optim.Adam8bit,
    lr=5e-5,
    loraplus_lr_ratio=16,
)
scheduler = None

...
trainer = Trainer(
    ...,
    optimizers=(optimizer, scheduler),
)
```

## Merge LoRA weights into the base model

While LoRA is significantly smaller and faster to train, you may encounter latency issues during inference due to separately loading the base model and the LoRA adapter. To eliminate latency, use the [`~LoraModel.merge_and_unload`] function to merge the adapter weights with the base model. This allows you to use the newly merged model as a standalone model. The [`~LoraModel.merge_and_unload`] function doesn't keep the adapter weights in memory.

Below is a diagram that explains the intuition of LoRA adapter merging:

<div class="flex justify-center">
    <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/peft/lora_diagram.png"/>
</div>

We show in the snippets below how to run that using PEFT.

```py
from transformers import AutoModelForCausalLM
from peft import PeftModel

base_model = AutoModelForCausalLM.from_pretrained("mistralai/Mistral-7B-v0.1")
peft_model_id = "alignment-handbook/zephyr-7b-sft-lora"
model = PeftModel.from_pretrained(base_model, peft_model_id)
model.merge_and_unload()
```

If you need to keep a copy of the weights so you can unmerge the adapter later or delete and load different ones, you should use the [`~LoraModel.merge_adapter`] function instead. Now you have the option to use [`~LoraModel.unmerge_adapter`] to return the base model.

```py
from transformers import AutoModelForCausalLM
from peft import PeftModel

base_model = AutoModelForCausalLM.from_pretrained("mistralai/Mistral-7B-v0.1")
peft_model_id = "alignment-handbook/zephyr-7b-sft-lora"
model = PeftModel.from_pretrained(base_model, peft_model_id)
model.merge_adapter()

# unmerge the LoRA layers from the base model
model.unmerge_adapter()
```

The [`~LoraModel.add_weighted_adapter`] function is useful for merging multiple LoRAs into a new adapter based on a user provided weighting scheme in the `weights` parameter. Below is an end-to-end example.


key: _node_content
string_value:
{"id_": "aead6548-1117-4ef8-8ccf-63a09c503cf4", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/peft/developer_guides/lora", "title": "LoRA", "tokens": 5004, "retrieve_doc": true, "source": "peft"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "dcfe3317-4cf4-4f88-a58f-e4b1bbcbf95e", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/peft/developer_guides/lora", "title": "LoRA", "tokens": 5004, "retrieve_doc": true, "source": "peft"}, "hash": "d7f9d6c9638ad92fa339ddcb55d6b31c1ef2d7119faab2bfd5c6bdbe3c997bd1", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "9c6a2ea2-87b5-451f-990b-b082bd0a76a5", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/peft/developer_guides/lora", "title": "LoRA", "tokens": 5004, "retrieve_doc": true, "source": "peft"}, "hash": "ff2bf532402b9b9ee7c9c1dbe84cebd14d2488cbf96e746afac0db8ae0149562", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "271c9921-4e1b-4820-94da-e7abd858eb3a", "node_type": "1", "metadata": {}, "hash": "ff5a69aac8fe6e5ee50731fc653daa8de1f3c7a98d7b697881807ef5f1579821", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 11448, "end_char_idx": 14290, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
The [`~LoraModel.merge_and_unload`] function doesn't keep the adapter weights in memory.

Below is a diagram that explains the intuition of LoRA adapter merging:

<div class="flex justify-center">
    <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/peft/lora_diagram.png"/>
</div>

We show in the snippets below how to run that using PEFT.

```py
from transformers import AutoModelForCausalLM
from peft import PeftModel

base_model = AutoModelForCausalLM.from_pretrained("mistralai/Mistral-7B-v0.1")
peft_model_id = "alignment-handbook/zephyr-7b-sft-lora"
model = PeftModel.from_pretrained(base_model, peft_model_id)
model.merge_and_unload()
```

If you need to keep a copy of the weights so you can unmerge the adapter later or delete and load different ones, you should use the [`~LoraModel.merge_adapter`] function instead. Now you have the option to use [`~LoraModel.unmerge_adapter`] to return the base model.

```py
from transformers import AutoModelForCausalLM
from peft import PeftModel

base_model = AutoModelForCausalLM.from_pretrained("mistralai/Mistral-7B-v0.1")
peft_model_id = "alignment-handbook/zephyr-7b-sft-lora"
model = PeftModel.from_pretrained(base_model, peft_model_id)
model.merge_adapter()

# unmerge the LoRA layers from the base model
model.unmerge_adapter()
```

The [`~LoraModel.add_weighted_adapter`] function is useful for merging multiple LoRAs into a new adapter based on a user provided weighting scheme in the `weights` parameter. Below is an end-to-end example.

First load the base model:

```python
from transformers import AutoModelForCausalLM
from peft import PeftModel
import torch

base_model = AutoModelForCausalLM.from_pretrained(
    "mistralai/Mistral-7B-v0.1", torch_dtype=torch.float16, device_map="auto"
)
```

Then we load the first adapter: 

```python
peft_model_id = "alignment-handbook/zephyr-7b-sft-lora"
model = PeftModel.from_pretrained(base_model, peft_model_id, adapter_name="sft")
```

Then load a different adapter and merge it with the first one:

```python
weighted_adapter_name = "sft-dpo"
model.load_adapter("alignment-handbook/zephyr-7b-dpo-lora", adapter_name="dpo")
model.add_weighted_adapter(
    adapters=["sft", "dpo"],
    weights=[0.7, 0.3],
    adapter_name=weighted_adapter_name,
    combination_type="linear"
)
model.set_adapter(weighted_adapter_name)
```

<Tip>

There are several supported methods for `combination_type`. Refer to the [documentation](../package_reference/lora#peft.LoraModel.add_weighted_adapter) for more details. Note that "svd" as the `combination_type` is not supported when using `torch.float16` or `torch.bfloat16` as the datatype.

</Tip>

Now, perform inference:

```python
tokenizer = AutoTokenizer.from_pretrained("mistralai/Mistral-7B-v0.1")

prompt = "Hey, are you conscious? Can you talk to me?"


key: _node_content
string_value:
{"id_": "271c9921-4e1b-4820-94da-e7abd858eb3a", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/peft/developer_guides/lora", "title": "LoRA", "tokens": 5004, "retrieve_doc": true, "source": "peft"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "dcfe3317-4cf4-4f88-a58f-e4b1bbcbf95e", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/peft/developer_guides/lora", "title": "LoRA", "tokens": 5004, "retrieve_doc": true, "source": "peft"}, "hash": "d7f9d6c9638ad92fa339ddcb55d6b31c1ef2d7119faab2bfd5c6bdbe3c997bd1", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "aead6548-1117-4ef8-8ccf-63a09c503cf4", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/peft/developer_guides/lora", "title": "LoRA", "tokens": 5004, "retrieve_doc": true, "source": "peft"}, "hash": "6b870e338b23617e75f2b675dbf86b848ea7f17fe65f7e04ef6a2f10b0327582", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "96c8784a-2375-43ed-b30f-7adca398d781", "node_type": "1", "metadata": {}, "hash": "d0151d9561325bb40bb62cec8859ca4630bad3d89d146646e0d498d53e18d81c", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 12953, "end_char_idx": 15943, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
Below is an end-to-end example.

First load the base model:

```python
from transformers import AutoModelForCausalLM
from peft import PeftModel
import torch

base_model = AutoModelForCausalLM.from_pretrained(
    "mistralai/Mistral-7B-v0.1", torch_dtype=torch.float16, device_map="auto"
)
```

Then we load the first adapter: 

```python
peft_model_id = "alignment-handbook/zephyr-7b-sft-lora"
model = PeftModel.from_pretrained(base_model, peft_model_id, adapter_name="sft")
```

Then load a different adapter and merge it with the first one:

```python
weighted_adapter_name = "sft-dpo"
model.load_adapter("alignment-handbook/zephyr-7b-dpo-lora", adapter_name="dpo")
model.add_weighted_adapter(
    adapters=["sft", "dpo"],
    weights=[0.7, 0.3],
    adapter_name=weighted_adapter_name,
    combination_type="linear"
)
model.set_adapter(weighted_adapter_name)
```

<Tip>

There are several supported methods for `combination_type`. Refer to the [documentation](../package_reference/lora#peft.LoraModel.add_weighted_adapter) for more details. Note that "svd" as the `combination_type` is not supported when using `torch.float16` or `torch.bfloat16` as the datatype.

</Tip>

Now, perform inference:

```python
tokenizer = AutoTokenizer.from_pretrained("mistralai/Mistral-7B-v0.1")

prompt = "Hey, are you conscious? Can you talk to me?"
inputs = tokenizer(prompt, return_tensors="pt")
inputs = {k: v.to("cuda") for k, v in inputs.items()}

with torch.no_grad():
    generate_ids = model.generate(**inputs, max_length=30)
outputs = tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
print(outputs)
```

## Load adapters

Adapters can be loaded onto a pretrained model with [`~PeftModel.load_adapter`], which is useful for trying out different adapters whose weights aren't merged. Set the active adapter weights with the [`~LoraModel.set_adapter`] function.

```py
from transformers import AutoModelForCausalLM
from peft import PeftModel

base_model = AutoModelForCausalLM.from_pretrained("mistralai/Mistral-7B-v0.1")
peft_model_id = "alignment-handbook/zephyr-7b-sft-lora"
model = PeftModel.from_pretrained(base_model, peft_model_id)

# load different adapter
model.load_adapter("alignment-handbook/zephyr-7b-dpo-lora", adapter_name="dpo")

# set adapter as active
model.set_adapter("dpo")
```

To return the base model, you could use [`~LoraModel.unload`] to unload all of the LoRA modules or [`~LoraModel.delete_adapter`] to delete the adapter entirely.

```py
# unload adapter
model.unload()

# delete adapter
model.delete_adapter("dpo")
```

## Inference with different LoRA adapters in the same batch

Normally, each inference batch has to use the same adapter(s) in PEFT. This can sometimes be annoying, because we may have batches that contain samples intended to be used with different LoRA adapters. For example, we could have a base model that works well in English and two more LoRA adapters, one for French and one for German.


key: _node_content
string_value:
{"id_": "96c8784a-2375-43ed-b30f-7adca398d781", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/peft/developer_guides/lora", "title": "LoRA", "tokens": 5004, "retrieve_doc": true, "source": "peft"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "dcfe3317-4cf4-4f88-a58f-e4b1bbcbf95e", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/peft/developer_guides/lora", "title": "LoRA", "tokens": 5004, "retrieve_doc": true, "source": "peft"}, "hash": "d7f9d6c9638ad92fa339ddcb55d6b31c1ef2d7119faab2bfd5c6bdbe3c997bd1", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "271c9921-4e1b-4820-94da-e7abd858eb3a", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/peft/developer_guides/lora", "title": "LoRA", "tokens": 5004, "retrieve_doc": true, "source": "peft"}, "hash": "eebe5adaf5f46cdc14861e6b790cf55cdc092e46385a1fbf30768449f81cebb1", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "54dedaaf-07db-4dcf-aa3f-35d4f1369ebc", "node_type": "1", "metadata": {}, "hash": "ef1abaec055fa67a7cebed575c5c21aa9cdbad366bcb7ada6e51eb3941d8757e", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 14785, "end_char_idx": 17497, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
Set the active adapter weights with the [`~LoraModel.set_adapter`] function.

```py
from transformers import AutoModelForCausalLM
from peft import PeftModel

base_model = AutoModelForCausalLM.from_pretrained("mistralai/Mistral-7B-v0.1")
peft_model_id = "alignment-handbook/zephyr-7b-sft-lora"
model = PeftModel.from_pretrained(base_model, peft_model_id)

# load different adapter
model.load_adapter("alignment-handbook/zephyr-7b-dpo-lora", adapter_name="dpo")

# set adapter as active
model.set_adapter("dpo")
```

To return the base model, you could use [`~LoraModel.unload`] to unload all of the LoRA modules or [`~LoraModel.delete_adapter`] to delete the adapter entirely.

```py
# unload adapter
model.unload()

# delete adapter
model.delete_adapter("dpo")
```

## Inference with different LoRA adapters in the same batch

Normally, each inference batch has to use the same adapter(s) in PEFT. This can sometimes be annoying, because we may have batches that contain samples intended to be used with different LoRA adapters. For example, we could have a base model that works well in English and two more LoRA adapters, one for French and one for German. Usually, we would have to split our batches such that each batch only contains samples of one of the languages, we cannot combine different languages in the same batch.

Thankfully, it is possible to mix different LoRA adapters in the same batch using the `adapter_name` argument. Below, we show an examle of how this works in practice. First, let's load the base model, English, and the two adapters, French and German, like this:

```python
from transformers import AutoTokenizer, AutoModelForCausalLM
from peft import PeftModel

model_id = ...
tokenizer = AutoTokenizer.from_pretrained(model_id)

model = AutoModelForCausalLM.from_pretrained(model_id)
# load the LoRA adapter for French
peft_model = PeftModel.from_pretrained(model, <path>, adapter_name="adapter_fr")
# next, load the LoRA adapter for German
peft_model.load_adapter(<path>, adapter_name="adapter_de")
```

Now, we want to generate text on a sample that contains all three languages: The first three samples are in English, the next three are in French, and the last three are in German. We can use the `adapter_names` argument to specify which adapter to use for each sample. Since our base model is used for English, we use the special string `"__base__"` for these samples. For the next three samples, we indicate the adapter name of the French LoRA fine-tune, in this case `"adapter_fr"`. For the last three samples, we indicate the adapter name of the German LoRA fine-tune, in this case `"adapter_de"`. This way, we can use the base model and the two adapters in a single batch.


key: _node_content
string_value:
{"id_": "54dedaaf-07db-4dcf-aa3f-35d4f1369ebc", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/peft/developer_guides/lora", "title": "LoRA", "tokens": 5004, "retrieve_doc": true, "source": "peft"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "dcfe3317-4cf4-4f88-a58f-e4b1bbcbf95e", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/peft/developer_guides/lora", "title": "LoRA", "tokens": 5004, "retrieve_doc": true, "source": "peft"}, "hash": "d7f9d6c9638ad92fa339ddcb55d6b31c1ef2d7119faab2bfd5c6bdbe3c997bd1", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "96c8784a-2375-43ed-b30f-7adca398d781", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/peft/developer_guides/lora", "title": "LoRA", "tokens": 5004, "retrieve_doc": true, "source": "peft"}, "hash": "f222d5501254e06185f4d9675bdd762fb5065738499fb6e2a6d7726e09d585cf", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "ac106dc4-f5c7-4eff-8fd3-3041c7e4c2ad", "node_type": "1", "metadata": {}, "hash": "c2e917841febca1dac9ffac308eb61271d2349e174dfdb77a5032463e8ba5ddb", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 15814, "end_char_idx": 19092, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
For example, we could have a base model that works well in English and two more LoRA adapters, one for French and one for German. Usually, we would have to split our batches such that each batch only contains samples of one of the languages, we cannot combine different languages in the same batch.

Thankfully, it is possible to mix different LoRA adapters in the same batch using the `adapter_name` argument. Below, we show an examle of how this works in practice. First, let's load the base model, English, and the two adapters, French and German, like this:

```python
from transformers import AutoTokenizer, AutoModelForCausalLM
from peft import PeftModel

model_id = ...
tokenizer = AutoTokenizer.from_pretrained(model_id)

model = AutoModelForCausalLM.from_pretrained(model_id)
# load the LoRA adapter for French
peft_model = PeftModel.from_pretrained(model, <path>, adapter_name="adapter_fr")
# next, load the LoRA adapter for German
peft_model.load_adapter(<path>, adapter_name="adapter_de")
```

Now, we want to generate text on a sample that contains all three languages: The first three samples are in English, the next three are in French, and the last three are in German. We can use the `adapter_names` argument to specify which adapter to use for each sample. Since our base model is used for English, we use the special string `"__base__"` for these samples. For the next three samples, we indicate the adapter name of the French LoRA fine-tune, in this case `"adapter_fr"`. For the last three samples, we indicate the adapter name of the German LoRA fine-tune, in this case `"adapter_de"`. This way, we can use the base model and the two adapters in a single batch.

```python
inputs = tokenizer(
    [
        "Hello, my dog is cute",
        "Hello, my cat is awesome",
        "Hello, my fish is great",
        "Salut, mon chien est mignon",
        "Salut, mon chat est génial",
        "Salut, mon poisson est super",
        "Hallo, mein Hund ist süß",
        "Hallo, meine Katze ist toll",
        "Hallo, mein Fisch ist großartig",
    ],
    return_tensors="pt",
    padding=True,
)

adapter_names = [
    "__base__", "__base__", "__base__",
    "adapter_fr", "adapter_fr", "adapter_fr",
    "adapter_de", "adapter_de", "adapter_de",
]
output = peft_model.generate(**inputs, adapter_names=adapter_names, max_new_tokens=20)
```

Note that the order does not matter here, i.e. the samples in the batch don't need to be grouped by adapter as in the example above. We just need to ensure that the `adapter_names` argument is aligned correctly with the samples.

### Caveats

Using this features has some drawbacks, namely:

- It only works for inference, not for training.
- Disabling adapters using the `with model.disable_adapter()` context takes precedence over `adapter_names`.
- You cannot pass `adapter_names` when some adapter weights where merged with base weight using the `merge_adapter` method. Please unmerge all adapters first by calling `model.unmerge_adapter()`.
- For obvious reasons, this cannot be used after calling `merge_and_unload()`, since all the LoRA adapters will be merged into the base weights in this case.
- This feature does not currently work with DoRA, so set `use_dora=False` in your `LoraConfig` if you want to use it.


key: _node_content
string_value:
{"id_": "ac106dc4-f5c7-4eff-8fd3-3041c7e4c2ad", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/peft/developer_guides/lora", "title": "LoRA", "tokens": 5004, "retrieve_doc": true, "source": "peft"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "dcfe3317-4cf4-4f88-a58f-e4b1bbcbf95e", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/peft/developer_guides/lora", "title": "LoRA", "tokens": 5004, "retrieve_doc": true, "source": "peft"}, "hash": "d7f9d6c9638ad92fa339ddcb55d6b31c1ef2d7119faab2bfd5c6bdbe3c997bd1", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "54dedaaf-07db-4dcf-aa3f-35d4f1369ebc", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/peft/developer_guides/lora", "title": "LoRA", "tokens": 5004, "retrieve_doc": true, "source": "peft"}, "hash": "a71973311f0e43041afcb77bfe94eece861111f5144ef55f6c12f8475c9b6eab", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 17499, "end_char_idx": 19925, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
```python
inputs = tokenizer(
    [
        "Hello, my dog is cute",
        "Hello, my cat is awesome",
        "Hello, my fish is great",
        "Salut, mon chien est mignon",
        "Salut, mon chat est génial",
        "Salut, mon poisson est super",
        "Hallo, mein Hund ist süß",
        "Hallo, meine Katze ist toll",
        "Hallo, mein Fisch ist großartig",
    ],
    return_tensors="pt",
    padding=True,
)

adapter_names = [
    "__base__", "__base__", "__base__",
    "adapter_fr", "adapter_fr", "adapter_fr",
    "adapter_de", "adapter_de", "adapter_de",
]
output = peft_model.generate(**inputs, adapter_names=adapter_names, max_new_tokens=20)
```

Note that the order does not matter here, i.e. the samples in the batch don't need to be grouped by adapter as in the example above. We just need to ensure that the `adapter_names` argument is aligned correctly with the samples.

### Caveats

Using this features has some drawbacks, namely:

- It only works for inference, not for training.
- Disabling adapters using the `with model.disable_adapter()` context takes precedence over `adapter_names`.
- You cannot pass `adapter_names` when some adapter weights where merged with base weight using the `merge_adapter` method. Please unmerge all adapters first by calling `model.unmerge_adapter()`.
- For obvious reasons, this cannot be used after calling `merge_and_unload()`, since all the LoRA adapters will be merged into the base weights in this case.
- This feature does not currently work with DoRA, so set `use_dora=False` in your `LoraConfig` if you want to use it.
- There is an expected overhead for inference with `adapter_names`, especially if the amount of different adapters in the batch is high. This is because the batch size is effectively reduced to the number of samples per adapter. If runtime performance is your top priority, try the following:
  - Increase the batch size.
  - Try to avoid having a large number of different adapters in the same batch, prefer homogeneous batches. This can be achieved by buffering samples with the same adapter and only perform inference with a small handfull of different adapters.
  - Take a look at alternative implementations such as [LoRAX](https://github.com/predibase/lorax), [punica](https://github.com/punica-ai/punica), or [S-LoRA](https://github.com/S-LoRA/S-LoRA), which are specialized to work with a large number of different adapters.


key: _node_content
string_value:
{"id_": "ebc6af36-b221-4445-939d-ba7788c22bc0", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/peft/developer_guides/custom_models", "title": "Custom models", "tokens": 3842, "retrieve_doc": true, "source": "peft"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "28be4234-a3e5-4ef6-97d1-7a8c8c57ff8e", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/peft/developer_guides/custom_models", "title": "Custom models", "tokens": 3842, "retrieve_doc": true, "source": "peft"}, "hash": "f07eb5625e8d53aa533339337f7a581384cdf5d991cc351a3ce6956fbd60c213", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "48531abe-9cc2-4528-bad4-c02be4c2b9b1", "node_type": "1", "metadata": {}, "hash": "5c487d37a39a95b6f191d18a1c4b9ba33eca99e99aa8f4081b29ab55137ffae1", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 0, "end_char_idx": 3097, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
# Custom models

Some fine-tuning techniques, such as prompt tuning, are specific to language models. That means in 🤗 PEFT, it is
assumed a 🤗 Transformers model is being used. However, other fine-tuning techniques - like
[LoRA](../conceptual_guides/lora) - are not restricted to specific model types.

In this guide, we will see how LoRA can be applied to a multilayer perceptron, a computer vision model from the [timm](https://huggingface.co/docs/timm/index) library, or a new 🤗 Transformers architecture.

## Multilayer perceptron

Let's assume that we want to fine-tune a multilayer perceptron with LoRA. Here is the definition:

```python
from torch import nn


class MLP(nn.Module):
    def __init__(self, num_units_hidden=2000):
        super().__init__()
        self.seq = nn.Sequential(
            nn.Linear(20, num_units_hidden),
            nn.ReLU(),
            nn.Linear(num_units_hidden, num_units_hidden),
            nn.ReLU(),
            nn.Linear(num_units_hidden, 2),
            nn.LogSoftmax(dim=-1),
        )

    def forward(self, X):
        return self.seq(X)
```

This is a straightforward multilayer perceptron with an input layer, a hidden layer, and an output layer.

<Tip>

For this toy example, we choose an exceedingly large number of hidden units to highlight the efficiency gains
from PEFT, but those gains are in line with more realistic examples.

</Tip>

There are a few linear layers in this model that could be tuned with LoRA. When working with common 🤗 Transformers
models, PEFT will know which layers to apply LoRA to, but in this case, it is up to us as a user to choose the layers.
To determine the names of the layers to tune:

```python
print([(n, type(m)) for n, m in MLP().named_modules()])
```

This should print:

```
[('', __main__.MLP),
 ('seq', torch.nn.modules.container.Sequential),
 ('seq.0', torch.nn.modules.linear.Linear),
 ('seq.1', torch.nn.modules.activation.ReLU),
 ('seq.2', torch.nn.modules.linear.Linear),
 ('seq.3', torch.nn.modules.activation.ReLU),
 ('seq.4', torch.nn.modules.linear.Linear),
 ('seq.5', torch.nn.modules.activation.LogSoftmax)]
```

Let's say we want to apply LoRA to the input layer and to the hidden layer, those are `'seq.0'` and `'seq.2'`. Moreover,
let's assume we want to update the output layer without LoRA, that would be `'seq.4'`. The corresponding config would
be:

```python
from peft import LoraConfig

config = LoraConfig(
    target_modules=["seq.0", "seq.2"],
    modules_to_save=["seq.4"],
)
```

With that, we can create our PEFT model and check the fraction of parameters trained:

```python
from peft import get_peft_model

model = MLP()
peft_model = get_peft_model(model, config)
peft_model.print_trainable_parameters()
# prints trainable params: 56,164 || all params: 4,100,164 || trainable%: 1.369798866581922
```

Finally, we can use any training framework we like, or write our own fit loop, to train the `peft_model`.

For a complete example, check out [this notebook](https://github.com/huggingface/peft/blob/main/examples/multilayer_perceptron/multilayer_perceptron_lora.ipynb).


key: _node_content
string_value:
{"id_": "48531abe-9cc2-4528-bad4-c02be4c2b9b1", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/peft/developer_guides/custom_models", "title": "Custom models", "tokens": 3842, "retrieve_doc": true, "source": "peft"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "28be4234-a3e5-4ef6-97d1-7a8c8c57ff8e", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/peft/developer_guides/custom_models", "title": "Custom models", "tokens": 3842, "retrieve_doc": true, "source": "peft"}, "hash": "f07eb5625e8d53aa533339337f7a581384cdf5d991cc351a3ce6956fbd60c213", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "ebc6af36-b221-4445-939d-ba7788c22bc0", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/peft/developer_guides/custom_models", "title": "Custom models", "tokens": 3842, "retrieve_doc": true, "source": "peft"}, "hash": "8e46a1662cd9344d6fe3f4ff1bbae191dc15390f9b229518e092b08b1e6f764c", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "763a5716-0c79-4600-ac8a-3cc0f3d105a2", "node_type": "1", "metadata": {}, "hash": "5b2973a013ec1ae6e35a9b894d0a096fc1bfb5562f746d8662ebb1c7734be15e", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 1631, "end_char_idx": 3867, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
To determine the names of the layers to tune:

```python
print([(n, type(m)) for n, m in MLP().named_modules()])
```

This should print:

```
[('', __main__.MLP),
 ('seq', torch.nn.modules.container.Sequential),
 ('seq.0', torch.nn.modules.linear.Linear),
 ('seq.1', torch.nn.modules.activation.ReLU),
 ('seq.2', torch.nn.modules.linear.Linear),
 ('seq.3', torch.nn.modules.activation.ReLU),
 ('seq.4', torch.nn.modules.linear.Linear),
 ('seq.5', torch.nn.modules.activation.LogSoftmax)]
```

Let's say we want to apply LoRA to the input layer and to the hidden layer, those are `'seq.0'` and `'seq.2'`. Moreover,
let's assume we want to update the output layer without LoRA, that would be `'seq.4'`. The corresponding config would
be:

```python
from peft import LoraConfig

config = LoraConfig(
    target_modules=["seq.0", "seq.2"],
    modules_to_save=["seq.4"],
)
```

With that, we can create our PEFT model and check the fraction of parameters trained:

```python
from peft import get_peft_model

model = MLP()
peft_model = get_peft_model(model, config)
peft_model.print_trainable_parameters()
# prints trainable params: 56,164 || all params: 4,100,164 || trainable%: 1.369798866581922
```

Finally, we can use any training framework we like, or write our own fit loop, to train the `peft_model`.

For a complete example, check out [this notebook](https://github.com/huggingface/peft/blob/main/examples/multilayer_perceptron/multilayer_perceptron_lora.ipynb).

## timm models

The [timm](https://huggingface.co/docs/timm/index) library contains a large number of pretrained computer vision models.
Those can also be fine-tuned with PEFT. Let's check out how this works in practice.

To start, ensure that timm is installed in the Python environment:

```bash
python -m pip install -U timm
```

Next we load a timm model for an image classification task:

```python
import timm

num_classes = ...
model_id = "timm/poolformer_m36.sail_in1k"
model = timm.create_model(model_id, pretrained=True, num_classes=num_classes)
```

Again, we need to make a decision about what layers to apply LoRA to. Since LoRA supports 2D conv layers, and since
those are a major building block of this model, we should apply LoRA to the 2D conv layers.


key: _node_content
string_value:
{"id_": "763a5716-0c79-4600-ac8a-3cc0f3d105a2", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/peft/developer_guides/custom_models", "title": "Custom models", "tokens": 3842, "retrieve_doc": true, "source": "peft"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "28be4234-a3e5-4ef6-97d1-7a8c8c57ff8e", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/peft/developer_guides/custom_models", "title": "Custom models", "tokens": 3842, "retrieve_doc": true, "source": "peft"}, "hash": "f07eb5625e8d53aa533339337f7a581384cdf5d991cc351a3ce6956fbd60c213", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "48531abe-9cc2-4528-bad4-c02be4c2b9b1", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/peft/developer_guides/custom_models", "title": "Custom models", "tokens": 3842, "retrieve_doc": true, "source": "peft"}, "hash": "9faaa7111d8bbd92fabe8d86e84cddf7a830005a6f3fff9613636ea296b04814", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "b40f3929-d586-4dd3-9fe4-9eaf105c0d09", "node_type": "1", "metadata": {}, "hash": "a3d640b1a4850e33d4799b8727f1a7ad3edbd82f47a28f6b8208154464cd235f", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 2936, "end_char_idx": 6348, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
For a complete example, check out [this notebook](https://github.com/huggingface/peft/blob/main/examples/multilayer_perceptron/multilayer_perceptron_lora.ipynb).

## timm models

The [timm](https://huggingface.co/docs/timm/index) library contains a large number of pretrained computer vision models.
Those can also be fine-tuned with PEFT. Let's check out how this works in practice.

To start, ensure that timm is installed in the Python environment:

```bash
python -m pip install -U timm
```

Next we load a timm model for an image classification task:

```python
import timm

num_classes = ...
model_id = "timm/poolformer_m36.sail_in1k"
model = timm.create_model(model_id, pretrained=True, num_classes=num_classes)
```

Again, we need to make a decision about what layers to apply LoRA to. Since LoRA supports 2D conv layers, and since
those are a major building block of this model, we should apply LoRA to the 2D conv layers. To identify the names of
those layers, let's look at all the layer names:

```python
print([(n, type(m)) for n, m in model.named_modules()])
```

This will print a very long list, we'll only show the first few:

```
[('', timm.models.metaformer.MetaFormer),
 ('stem', timm.models.metaformer.Stem),
 ('stem.conv', torch.nn.modules.conv.Conv2d),
 ('stem.norm', torch.nn.modules.linear.Identity),
 ('stages', torch.nn.modules.container.Sequential),
 ('stages.0', timm.models.metaformer.MetaFormerStage),
 ('stages.0.downsample', torch.nn.modules.linear.Identity),
 ('stages.0.blocks', torch.nn.modules.container.Sequential),
 ('stages.0.blocks.0', timm.models.metaformer.MetaFormerBlock),
 ('stages.0.blocks.0.norm1', timm.layers.norm.GroupNorm1),
 ('stages.0.blocks.0.token_mixer', timm.models.metaformer.Pooling),
 ('stages.0.blocks.0.token_mixer.pool', torch.nn.modules.pooling.AvgPool2d),
 ('stages.0.blocks.0.drop_path1', torch.nn.modules.linear.Identity),
 ('stages.0.blocks.0.layer_scale1', timm.models.metaformer.Scale),
 ('stages.0.blocks.0.res_scale1', torch.nn.modules.linear.Identity),
 ('stages.0.blocks.0.norm2', timm.layers.norm.GroupNorm1),
 ('stages.0.blocks.0.mlp', timm.layers.mlp.Mlp),
 ('stages.0.blocks.0.mlp.fc1', torch.nn.modules.conv.Conv2d),
 ('stages.0.blocks.0.mlp.act', torch.nn.modules.activation.GELU),
 ('stages.0.blocks.0.mlp.drop1', torch.nn.modules.dropout.Dropout),
 ('stages.0.blocks.0.mlp.norm', torch.nn.modules.linear.Identity),
 ('stages.0.blocks.0.mlp.fc2', torch.nn.modules.conv.Conv2d),
 ('stages.0.blocks.0.mlp.drop2', torch.nn.modules.dropout.Dropout),
 ('stages.0.blocks.0.drop_path2', torch.nn.modules.linear.Identity),
 ('stages.0.blocks.0.layer_scale2', timm.models.metaformer.Scale),
 ('stages.0.blocks.0.res_scale2', torch.nn.modules.linear.Identity),
 ('stages.0.blocks.1', timm.models.metaformer.MetaFormerBlock),
 ('stages.0.blocks.1.norm1', timm.layers.norm.GroupNorm1),
 ('stages.0.blocks.1.token_mixer', timm.models.metaformer.Pooling),
 ('stages.0.blocks.1.token_mixer.pool', torch.nn.modules.pooling.AvgPool2d),
 ...
 ('head.global_pool.flatten', torch.nn.modules.linear.Identity),
 ('head.norm', timm.layers.norm.LayerNorm2d),
 ('head.flatten', torch.nn.modules.flatten.Flatten),
 ('head.drop', torch.nn.modules.linear.Identity),
 ('head.fc', torch.nn.modules.linear.Linear)]
 ]
```

Upon closer inspection, we see that the 2D conv layers have names such as `"stages.0.blocks.0.mlp.fc1"` and
`"stages.0.blocks.0.mlp.fc2"`.


key: _node_content
string_value:
{"id_": "b40f3929-d586-4dd3-9fe4-9eaf105c0d09", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/peft/developer_guides/custom_models", "title": "Custom models", "tokens": 3842, "retrieve_doc": true, "source": "peft"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "28be4234-a3e5-4ef6-97d1-7a8c8c57ff8e", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/peft/developer_guides/custom_models", "title": "Custom models", "tokens": 3842, "retrieve_doc": true, "source": "peft"}, "hash": "f07eb5625e8d53aa533339337f7a581384cdf5d991cc351a3ce6956fbd60c213", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "763a5716-0c79-4600-ac8a-3cc0f3d105a2", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/peft/developer_guides/custom_models", "title": "Custom models", "tokens": 3842, "retrieve_doc": true, "source": "peft"}, "hash": "e43e8ecfdf56ee9c24cfe137585e4f1911c6366f72324a726e9fdf1e8ad72cf0", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "c10f700a-de15-4bb0-a0e7-0c21b2ddcb80", "node_type": "1", "metadata": {}, "hash": "0d0c92e82d7092acac39fee2d0f7cb4976bfcdd3b21817f9178f08f8974a177b", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 6349, "end_char_idx": 9414, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
How can we match those layer names specifically? You can write a [regular
expressions](https://docs.python.org/3/library/re.html) to match the layer names. For our case, the regex
`r".*\.mlp\.fc\d"` should do the job.

Furthermore, as in the first example, we should ensure that the output layer, in this case the classification head, is
also updated. Looking at the end of the list printed above, we can see that it's named `'head.fc'`. With that in mind,
here is our LoRA config:

```python
config = LoraConfig(target_modules=r".*\.mlp\.fc\d", modules_to_save=["head.fc"])
```

Then we only need to create the PEFT model by passing our base model and the config to `get_peft_model`:

```python
peft_model = get_peft_model(model, config)
peft_model.print_trainable_parameters()
# prints trainable params: 1,064,454 || all params: 56,467,974 || trainable%: 1.88505789139876
```

This shows us that we only need to train less than 2% of all parameters, which is a huge efficiency gain.

For a complete example, check out [this notebook](https://github.com/huggingface/peft/blob/main/examples/image_classification/image_classification_timm_peft_lora.ipynb).

## New transformers architectures

When new popular transformers architectures are released, we do our best to quickly add them to PEFT. If you come across a transformers model that is not supported out of the box, don't worry, it will most likely still work if the config is set correctly. Specifically, you have to identify the layers that should be adapted and set them correctly when initializing the corresponding config class, e.g. `LoraConfig`. Here are some tips to help with this.

As a first step, it is a good idea is to check the existing models for inspiration. You can find them inside of [constants.py](https://github.com/huggingface/peft/blob/main/src/peft/utils/constants.py) in the PEFT repository. Often, you'll find a similar architecture that uses the same names. For example, if the new model architecture is a variation of the "mistral" model and you want to apply LoRA, you can see that the entry for "mistral" in `TRANSFORMERS_MODELS_TO_LORA_TARGET_MODULES_MAPPING` contains `["q_proj", "v_proj"]`. This tells you that for "mistral" models, the `target_modules` for LoRA should be `["q_proj", "v_proj"]`:

```python
from peft import LoraConfig, get_peft_model

my_mistral_model = ...
config = LoraConfig(
    target_modules=["q_proj", "v_proj"],
    ...,  # other LoRA arguments
)
peft_model = get_peft_model(my_mistral_model, config)
```

If that doesn't help, check the existing modules in your model architecture with the `named_modules` method and try to identify the attention layers, especially the key, query, and value layers. Those will often have names such as `c_attn`, `query`, `q_proj`, etc. The key layer is not always adapted, and ideally, you should check whether including it results in better performance.

Additionally, linear layers are common targets to be adapted (e.g. in [QLoRA paper](https://arxiv.org/abs/2305.14314), authors suggest to adapt them as well).


key: _node_content
string_value:
{"id_": "c10f700a-de15-4bb0-a0e7-0c21b2ddcb80", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/peft/developer_guides/custom_models", "title": "Custom models", "tokens": 3842, "retrieve_doc": true, "source": "peft"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "28be4234-a3e5-4ef6-97d1-7a8c8c57ff8e", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/peft/developer_guides/custom_models", "title": "Custom models", "tokens": 3842, "retrieve_doc": true, "source": "peft"}, "hash": "f07eb5625e8d53aa533339337f7a581384cdf5d991cc351a3ce6956fbd60c213", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "b40f3929-d586-4dd3-9fe4-9eaf105c0d09", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/peft/developer_guides/custom_models", "title": "Custom models", "tokens": 3842, "retrieve_doc": true, "source": "peft"}, "hash": "f47dd33ceb84b93bb18414b48e779f6bc6da1ae39aa8d3b1e4672918c4c91028", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "c03dc387-261d-4fb4-be9f-7036f920e9df", "node_type": "1", "metadata": {}, "hash": "71a9c2037532ef64cf30613285a620c1c2edec93f4c8be9af33a72cec46c9283", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 7944, "end_char_idx": 10879, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
`LoraConfig`. Here are some tips to help with this.

As a first step, it is a good idea is to check the existing models for inspiration. You can find them inside of [constants.py](https://github.com/huggingface/peft/blob/main/src/peft/utils/constants.py) in the PEFT repository. Often, you'll find a similar architecture that uses the same names. For example, if the new model architecture is a variation of the "mistral" model and you want to apply LoRA, you can see that the entry for "mistral" in `TRANSFORMERS_MODELS_TO_LORA_TARGET_MODULES_MAPPING` contains `["q_proj", "v_proj"]`. This tells you that for "mistral" models, the `target_modules` for LoRA should be `["q_proj", "v_proj"]`:

```python
from peft import LoraConfig, get_peft_model

my_mistral_model = ...
config = LoraConfig(
    target_modules=["q_proj", "v_proj"],
    ...,  # other LoRA arguments
)
peft_model = get_peft_model(my_mistral_model, config)
```

If that doesn't help, check the existing modules in your model architecture with the `named_modules` method and try to identify the attention layers, especially the key, query, and value layers. Those will often have names such as `c_attn`, `query`, `q_proj`, etc. The key layer is not always adapted, and ideally, you should check whether including it results in better performance.

Additionally, linear layers are common targets to be adapted (e.g. in [QLoRA paper](https://arxiv.org/abs/2305.14314), authors suggest to adapt them as well). Their names will often contain the strings `fc` or `dense`.

If you want to add a new model to PEFT, please create an entry in [constants.py](https://github.com/huggingface/peft/blob/main/src/peft/utils/constants.py) and open a pull request on the [repository](https://github.com/huggingface/peft/pulls). Don't forget to update the [README](https://github.com/huggingface/peft#models-support-matrix) as well.

## Verify parameters and layers

You can verify whether you've correctly applied a PEFT method to your model in a few ways.

* Check the fraction of parameters that are trainable with the [`~PeftModel.print_trainable_parameters`] method. If this number is lower or higher than expected, check the model `repr` by printing the model. This shows the names of all the layer types in the model. Ensure that only the intended target layers are replaced by the adapter layers. For example, if LoRA is applied to `nn.Linear` layers, then you should only see `lora.Linear` layers being used.

```py
peft_model.print_trainable_parameters()
```

* Another way you can view the adapted layers is to use the `targeted_module_names` attribute to list the name of each module that was adapted.

```python
print(peft_model.targeted_module_names)
```

## Unsupported module types

Methods like LoRA only work if the target modules are supported by PEFT. For example, it's possible to apply LoRA to `nn.Linear` and `nn.Conv2d` layers, but not, for instance, to `nn.LSTM`.


key: _node_content
string_value:
{"id_": "c03dc387-261d-4fb4-be9f-7036f920e9df", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/peft/developer_guides/custom_models", "title": "Custom models", "tokens": 3842, "retrieve_doc": true, "source": "peft"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "28be4234-a3e5-4ef6-97d1-7a8c8c57ff8e", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/peft/developer_guides/custom_models", "title": "Custom models", "tokens": 3842, "retrieve_doc": true, "source": "peft"}, "hash": "f07eb5625e8d53aa533339337f7a581384cdf5d991cc351a3ce6956fbd60c213", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "c10f700a-de15-4bb0-a0e7-0c21b2ddcb80", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/peft/developer_guides/custom_models", "title": "Custom models", "tokens": 3842, "retrieve_doc": true, "source": "peft"}, "hash": "4e0d232c8776e1f0815bb8b2a936b67df671f8a21528beea7717ca817d717faa", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "bbfae8d1-10ee-43a1-a919-c1fd373019bd", "node_type": "1", "metadata": {}, "hash": "335ba5ff2a2d338c9281c5f4083251ad927b07c4181524ace9fd4c6a257a1aa7", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 9256, "end_char_idx": 12525, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
Additionally, linear layers are common targets to be adapted (e.g. in [QLoRA paper](https://arxiv.org/abs/2305.14314), authors suggest to adapt them as well). Their names will often contain the strings `fc` or `dense`.

If you want to add a new model to PEFT, please create an entry in [constants.py](https://github.com/huggingface/peft/blob/main/src/peft/utils/constants.py) and open a pull request on the [repository](https://github.com/huggingface/peft/pulls). Don't forget to update the [README](https://github.com/huggingface/peft#models-support-matrix) as well.

## Verify parameters and layers

You can verify whether you've correctly applied a PEFT method to your model in a few ways.

* Check the fraction of parameters that are trainable with the [`~PeftModel.print_trainable_parameters`] method. If this number is lower or higher than expected, check the model `repr` by printing the model. This shows the names of all the layer types in the model. Ensure that only the intended target layers are replaced by the adapter layers. For example, if LoRA is applied to `nn.Linear` layers, then you should only see `lora.Linear` layers being used.

```py
peft_model.print_trainable_parameters()
```

* Another way you can view the adapted layers is to use the `targeted_module_names` attribute to list the name of each module that was adapted.

```python
print(peft_model.targeted_module_names)
```

## Unsupported module types

Methods like LoRA only work if the target modules are supported by PEFT. For example, it's possible to apply LoRA to `nn.Linear` and `nn.Conv2d` layers, but not, for instance, to `nn.LSTM`. If you find a layer class you want to apply PEFT to is not supported, you can:

 - define a custom mapping to dynamically dispatch custom modules in LoRA
 -  open an [issue](https://github.com/huggingface/peft/issues) and request the feature where maintainers will implement it or guide you on how to implement it yourself if demand for this module type is sufficiently high

### Experimental support for dynamic dispatch of custom modules in LoRA

> [!WARNING]
> This feature is experimental and subject to change, depending on its reception by the community. We will introduce a public and stable API if there is significant demand for it.

PEFT supports an experimental API for custom module types for LoRA. Let's assume you have a LoRA implementation for LSTMs. Normally, you would not be able to tell PEFT to use it, even if it would theoretically work with PEFT. However, this is possible with dynamic dispatch of custom layers.

The experimental API currently looks like this:

```python
class MyLoraLSTMLayer:
    ...

base_model = ...  # load the base model that uses LSTMs

# add the LSTM layer names to target_modules
config = LoraConfig(..., target_modules=["lstm"])
# define a mapping from base layer type to LoRA layer type
custom_module_mapping = {nn.LSTM: MyLoraLSTMLayer}
# register the new mapping
config._register_custom_module(custom_module_mapping)
# after registration, create the PEFT model
peft_model = get_peft_model(base_model, config)
# do training
```

<Tip>

When you call [`get_peft_model`], you will see a warning because PEFT does not recognize the targeted module type. In this case, you can ignore this warning.


key: _node_content
string_value:
{"id_": "bbfae8d1-10ee-43a1-a919-c1fd373019bd", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/peft/developer_guides/custom_models", "title": "Custom models", "tokens": 3842, "retrieve_doc": true, "source": "peft"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "28be4234-a3e5-4ef6-97d1-7a8c8c57ff8e", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/peft/developer_guides/custom_models", "title": "Custom models", "tokens": 3842, "retrieve_doc": true, "source": "peft"}, "hash": "f07eb5625e8d53aa533339337f7a581384cdf5d991cc351a3ce6956fbd60c213", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "c03dc387-261d-4fb4-be9f-7036f920e9df", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/peft/developer_guides/custom_models", "title": "Custom models", "tokens": 3842, "retrieve_doc": true, "source": "peft"}, "hash": "e4c36706bb8bf30757a0644a5b7a4f07e28fcbe6b5d054c2315803155be8c443", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "57196c6f-98af-4d2b-8d8d-ecea80b13e4d", "node_type": "1", "metadata": {}, "hash": "59f8141b8e00761f09fdbc25bef2ee022bcec178ebe378b99421dba8eb97343d", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 10880, "end_char_idx": 14083, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
If you find a layer class you want to apply PEFT to is not supported, you can:

 - define a custom mapping to dynamically dispatch custom modules in LoRA
 -  open an [issue](https://github.com/huggingface/peft/issues) and request the feature where maintainers will implement it or guide you on how to implement it yourself if demand for this module type is sufficiently high

### Experimental support for dynamic dispatch of custom modules in LoRA

> [!WARNING]
> This feature is experimental and subject to change, depending on its reception by the community. We will introduce a public and stable API if there is significant demand for it.

PEFT supports an experimental API for custom module types for LoRA. Let's assume you have a LoRA implementation for LSTMs. Normally, you would not be able to tell PEFT to use it, even if it would theoretically work with PEFT. However, this is possible with dynamic dispatch of custom layers.

The experimental API currently looks like this:

```python
class MyLoraLSTMLayer:
    ...

base_model = ...  # load the base model that uses LSTMs

# add the LSTM layer names to target_modules
config = LoraConfig(..., target_modules=["lstm"])
# define a mapping from base layer type to LoRA layer type
custom_module_mapping = {nn.LSTM: MyLoraLSTMLayer}
# register the new mapping
config._register_custom_module(custom_module_mapping)
# after registration, create the PEFT model
peft_model = get_peft_model(base_model, config)
# do training
```

<Tip>

When you call [`get_peft_model`], you will see a warning because PEFT does not recognize the targeted module type. In this case, you can ignore this warning.

</Tip>

By supplying a custom mapping, PEFT first checks the base model's layers against the custom mapping and dispatches to the custom LoRA layer type if there is a match. If there is no match, PEFT checks the built-in LoRA layer types for a match.

Therefore, this feature can also be used to override existing dispatch logic, e.g. if you want to use your own LoRA layer for `nn.Linear` instead of using the one provided by PEFT.

When creating your custom LoRA module, please follow the same rules as the [existing LoRA modules](https://github.com/huggingface/peft/blob/main/src/peft/tuners/lora/layer.py). Some important constraints to consider:

- The custom module should inherit from `nn.Module` and `peft.tuners.lora.layer.LoraLayer`.
- The `__init__` method of the custom module should have the positional arguments `base_layer` and `adapter_name`. After this, there are additional `**kwargs` that you are free to use or ignore.
- The learnable parameters should be stored in an `nn.ModuleDict` or `nn.ParameterDict`, where the key corresponds to the name of the specific adapter (remember that a model can have more than one adapter at a time).
- The name of these learnable parameter attributes should start with `"lora_"`, e.g. `self.lora_new_param = ...`.
- Some methods are optional, e.g. you only need to implement `merge` and `unmerge` if you want to support weight merging.

Currently, the information about the custom module does not persist when you save the model. When loading the model, you have to register the custom modules again.


key: _node_content
string_value:
{"id_": "57196c6f-98af-4d2b-8d8d-ecea80b13e4d", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/peft/developer_guides/custom_models", "title": "Custom models", "tokens": 3842, "retrieve_doc": true, "source": "peft"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "28be4234-a3e5-4ef6-97d1-7a8c8c57ff8e", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/peft/developer_guides/custom_models", "title": "Custom models", "tokens": 3842, "retrieve_doc": true, "source": "peft"}, "hash": "f07eb5625e8d53aa533339337f7a581384cdf5d991cc351a3ce6956fbd60c213", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "bbfae8d1-10ee-43a1-a919-c1fd373019bd", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/peft/developer_guides/custom_models", "title": "Custom models", "tokens": 3842, "retrieve_doc": true, "source": "peft"}, "hash": "38fae3f1845dcc84639185279b37bea16ec2d7953acc3350311dbcac2d1c1b01", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 12483, "end_char_idx": 14907, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
In this case, you can ignore this warning.

</Tip>

By supplying a custom mapping, PEFT first checks the base model's layers against the custom mapping and dispatches to the custom LoRA layer type if there is a match. If there is no match, PEFT checks the built-in LoRA layer types for a match.

Therefore, this feature can also be used to override existing dispatch logic, e.g. if you want to use your own LoRA layer for `nn.Linear` instead of using the one provided by PEFT.

When creating your custom LoRA module, please follow the same rules as the [existing LoRA modules](https://github.com/huggingface/peft/blob/main/src/peft/tuners/lora/layer.py). Some important constraints to consider:

- The custom module should inherit from `nn.Module` and `peft.tuners.lora.layer.LoraLayer`.
- The `__init__` method of the custom module should have the positional arguments `base_layer` and `adapter_name`. After this, there are additional `**kwargs` that you are free to use or ignore.
- The learnable parameters should be stored in an `nn.ModuleDict` or `nn.ParameterDict`, where the key corresponds to the name of the specific adapter (remember that a model can have more than one adapter at a time).
- The name of these learnable parameter attributes should start with `"lora_"`, e.g. `self.lora_new_param = ...`.
- Some methods are optional, e.g. you only need to implement `merge` and `unmerge` if you want to support weight merging.

Currently, the information about the custom module does not persist when you save the model. When loading the model, you have to register the custom modules again.

```python
# saving works as always and includes the parameters of the custom modules
peft_model.save_pretrained(<model-path>)

# loading the model later:
base_model = ...
# load the LoRA config that you saved earlier
config = LoraConfig.from_pretrained(<model-path>)
# register the custom module again, the same way as the first time
custom_module_mapping = {nn.LSTM: MyLoraLSTMLayer}
config._register_custom_module(custom_module_mapping)
# pass the config instance to from_pretrained:
peft_model = PeftModel.from_pretrained(model, tmp_path / "lora-custom-module", config=config)
```

If you use this feature and find it useful, or if you encounter problems, let us know by creating an issue or a discussion on GitHub. This allows us to estimate the demand for this feature and add a public API if it is sufficiently high.


key: _node_content
string_value:
{"id_": "916716a1-6ed9-42fb-a721-1c0e0c5ff9ec", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/peft/developer_guides/torch_compile", "title": "torch.compile", "tokens": 828, "retrieve_doc": true, "source": "peft"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "8c6fab7e-70ee-4bcc-9082-88baf848ac87", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/peft/developer_guides/torch_compile", "title": "torch.compile", "tokens": 828, "retrieve_doc": true, "source": "peft"}, "hash": "e9207286ad2262c8f980020a5d659ab9ca39ca90a4a8b31ce23b9230ec8652cd", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 0, "end_char_idx": 2792, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
# torch.compile

In PEFT, [torch.compile](https://pytorch.org/tutorials/intermediate/torch_compile_tutorial.html) works for some but not all features. The reason why it won't always work is because PEFT is highly dynamic in certain places (loading and switching between multiple adapters, for instance), which can cause trouble for `torch.compile`. In other places, `torch.compile` may work, but won't be as fast as expected because of graph breaks.

If you don't see an error, it doesn't necessarily mean that `torch.compile` worked correctly. It might give you an output, but the output is incorrect. This guide describes what works with `torch.compile` and what doesn't.

> [!TIP]
> Unless indicated otherwise, the default `torch.compile` settings were used.

## Training and inference with `torch.compile`

These features **work** with `torch.compile`. Everything listed below was tested with a causal LM:

- Training with `Trainer` from 🤗 transformers
- Training with a custom PyTorch loop
- Inference
- Generation

The following adapters were tested successfully:

- AdaLoRA
- BOFT
- IA³
- Layer Norm Tuning
- LoHa
- LoRA
- LoRA + DoRA
- OFT
- VeRA
- HRA

The following adapters **don't work** correctly for training or inference when using `torch.compile`:

- LoKr
- LoRA targeting embedding layers

## Advanced PEFT features with `torch.compile`

Below are some of the more advanced PEFT features that **work**. They were all tested with LoRA.

- `modules_to_save` (i.e. `config = LoraConfig(..., modules_to_save=...)`)
- Merging adapters (one or multiple)
- Merging multiple adapters into one adapter (i.e. calling `model.add_weighted_adapter(...)`)

Generally, we can expect that if a feature works correctly with LoRA and is also supported by other adapter types, it should also work for that adapter type.

The more advanced PEFT features below **don't work** in conjunction with `torch.compile`. Tests were run with LoRA:

- Using PEFT adapters with quantization (bitsandbytes)
- Inference with multiple adapters
- Unloading (i.e. calling `model.merge_and_unload()`)
- Disabling adapters (i.e. using `with model.disable_adapter()`)
- Mixed adapter batches (i.e. calling `model(batch, adapter_names=["__base__", "default", "other", ...])`)

## Test cases

All the use cases listed above are tested inside of [`peft/tests/test_torch_compile.py`](https://github.com/huggingface/peft/blob/main/tests/test_torch_compile.py). If you want to check in more detail how we tested a certain feature, please go to that file and check the test that corresponds to your use case.

> [!TIP]
> If you have another use case where you know that `torch.compile` does or does not work with PEFT, please contribute by letting us know or by opening a PR to add this use case to the covered test cases.


key: _node_content
string_value:
{"id_": "5abef790-ee44-4f3d-bd93-97a3225ff91e", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/peft/developer_guides/checkpoint", "title": "PEFT checkpoint format", "tokens": 3329, "retrieve_doc": true, "source": "peft"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "f6468a0c-8aa0-41ac-b07b-60a444da384c", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/peft/developer_guides/checkpoint", "title": "PEFT checkpoint format", "tokens": 3329, "retrieve_doc": true, "source": "peft"}, "hash": "b5a16eafb9f7797e65ffc2b56e056a1313df363eff570e9b50f1b7654f395a7f", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "185e7294-7cb7-4826-8fed-e5aa1a2839b3", "node_type": "1", "metadata": {}, "hash": "46c15d137e660365839ab7b14e8558f2b68871f3703ab6ab171aa0e654f6098e", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 0, "end_char_idx": 3252, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
# PEFT checkpoint format

This document describes how PEFT's checkpoint files are structured and how to convert between the PEFT format and other formats.

## PEFT files

PEFT (parameter-efficient fine-tuning) methods only update a small subset of a model's parameters rather than all of them. This is nice because checkpoint files can generally be much smaller than the original model files and are easier to store and share. However, this also means that to load a PEFT model, you need to have the original model available as well.

When you call [`~PeftModel.save_pretrained`] on a PEFT model, the PEFT model saves three files, described below:

1. `adapter_model.safetensors` or `adapter_model.bin`

By default, the model is saved in the `safetensors` format, a secure alternative to the `bin` format, which is known to be susceptible to [security vulnerabilities](https://huggingface.co/docs/hub/security-pickle) because it uses the pickle utility under the hood. Both formats store the same `state_dict` though, and are interchangeable.

The `state_dict` only contains the parameters of the adapter module, not the base model. To illustrate the difference in size, a normal BERT model requires ~420MB of disk space, whereas an IA³ adapter on top of this BERT model only requires ~260KB.

2. `adapter_config.json`

The `adapter_config.json` file contains the configuration of the adapter module, which is necessary to load the model. Below is an example of an `adapter_config.json` for an IA³ adapter with standard settings applied to a BERT model:

```json
{
  "auto_mapping": {
    "base_model_class": "BertModel",
    "parent_library": "transformers.models.bert.modeling_bert"
  },
  "base_model_name_or_path": "bert-base-uncased",
  "fan_in_fan_out": false,
  "feedforward_modules": [
    "output.dense"
  ],
  "inference_mode": true,
  "init_ia3_weights": true,
  "modules_to_save": null,
  "peft_type": "IA3",
  "revision": null,
  "target_modules": [
    "key",
    "value",
    "output.dense"
  ],
  "task_type": null
}
```

The configuration file contains:

- the adapter module type stored, `"peft_type": "IA3"`
- information about the base model like `"base_model_name_or_path": "bert-base-uncased"`
- the revision of the model (if any), `"revision": null`

If the base model is not a pretrained Transformers model, the latter two entries will be `null`. Other than that, the settings are all related to the specific IA³ adapter that was used to fine-tune the model.

3. `README.md`

The generated `README.md` is the model card of a PEFT model and contains a few pre-filled entries. The intent of this is to make it easier to share the model with others and to provide some basic information about the model. This file is not needed to load the model.

## Convert to PEFT format

When converting from another format to the PEFT format, we require both the `adapter_model.safetensors` (or `adapter_model.bin`) file and the `adapter_config.json` file.

### adapter_model

For the model weights, it is important to use the correct mapping from parameter name to value for PEFT to load the file. Getting this mapping right is an exercise in checking the implementation details, as there is no generally agreed upon format for PEFT adapters.


key: _node_content
string_value:
{"id_": "185e7294-7cb7-4826-8fed-e5aa1a2839b3", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/peft/developer_guides/checkpoint", "title": "PEFT checkpoint format", "tokens": 3329, "retrieve_doc": true, "source": "peft"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "f6468a0c-8aa0-41ac-b07b-60a444da384c", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/peft/developer_guides/checkpoint", "title": "PEFT checkpoint format", "tokens": 3329, "retrieve_doc": true, "source": "peft"}, "hash": "b5a16eafb9f7797e65ffc2b56e056a1313df363eff570e9b50f1b7654f395a7f", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "5abef790-ee44-4f3d-bd93-97a3225ff91e", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/peft/developer_guides/checkpoint", "title": "PEFT checkpoint format", "tokens": 3329, "retrieve_doc": true, "source": "peft"}, "hash": "036aa092c3a8f0019354d2360147339e9b86dfd2f2aa9c5f71f051a67a79c22d", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "b6e5b779-99c2-4b17-bbb1-eaacf5c75777", "node_type": "1", "metadata": {}, "hash": "b3331765c8d40943785f02cac1b5642168a59d901d3e4baf2ba7665ee4878133", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 2371, "end_char_idx": 5238, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
Other than that, the settings are all related to the specific IA³ adapter that was used to fine-tune the model.

3. `README.md`

The generated `README.md` is the model card of a PEFT model and contains a few pre-filled entries. The intent of this is to make it easier to share the model with others and to provide some basic information about the model. This file is not needed to load the model.

## Convert to PEFT format

When converting from another format to the PEFT format, we require both the `adapter_model.safetensors` (or `adapter_model.bin`) file and the `adapter_config.json` file.

### adapter_model

For the model weights, it is important to use the correct mapping from parameter name to value for PEFT to load the file. Getting this mapping right is an exercise in checking the implementation details, as there is no generally agreed upon format for PEFT adapters.

Fortunately, figuring out this mapping is not overly complicated for common base cases. Let's look at a concrete example, the [`LoraLayer`](https://github.com/huggingface/peft/blob/main/src/peft/tuners/lora/layer.py):

```python
# showing only part of the code

class LoraLayer(BaseTunerLayer):
    # All names of layers that may contain (trainable) adapter weights
    adapter_layer_names = ("lora_A", "lora_B", "lora_embedding_A", "lora_embedding_B")
    # All names of other parameters that may contain adapter-related parameters
    other_param_names = ("r", "lora_alpha", "scaling", "lora_dropout")

    def __init__(self, base_layer: nn.Module, **kwargs) -> None:
        self.base_layer = base_layer
        self.r = {}
        self.lora_alpha = {}
        self.scaling = {}
        self.lora_dropout = nn.ModuleDict({})
        self.lora_A = nn.ModuleDict({})
        self.lora_B = nn.ModuleDict({})
        # For Embedding layer
        self.lora_embedding_A = nn.ParameterDict({})
        self.lora_embedding_B = nn.ParameterDict({})
        # Mark the weight as unmerged
        self._disable_adapters = False
        self.merged_adapters = []
        self.use_dora: dict[str, bool] = {}
        self.lora_magnitude_vector: Optional[torch.nn.ParameterDict] = None  # for DoRA
        self._caches: dict[str, Any] = {}
        self.kwargs = kwargs
```

In the `__init__` code used by all `LoraLayer` classes in PEFT, there are a bunch of parameters used to initialize the model, but only a few are relevant for the checkpoint file: `lora_A`, `lora_B`, `lora_embedding_A`, and `lora_embedding_B`. These parameters are listed in the class attribute `adapter_layer_names` and contain the learnable parameters, so they must be included in the checkpoint file. All the other parameters, like the rank `r`, are derived from the `adapter_config.json` and must be included there (unless the default value is used).

Let's check the `state_dict` of a PEFT LoRA model applied to BERT.


key: _node_content
string_value:
{"id_": "b6e5b779-99c2-4b17-bbb1-eaacf5c75777", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/peft/developer_guides/checkpoint", "title": "PEFT checkpoint format", "tokens": 3329, "retrieve_doc": true, "source": "peft"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "f6468a0c-8aa0-41ac-b07b-60a444da384c", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/peft/developer_guides/checkpoint", "title": "PEFT checkpoint format", "tokens": 3329, "retrieve_doc": true, "source": "peft"}, "hash": "b5a16eafb9f7797e65ffc2b56e056a1313df363eff570e9b50f1b7654f395a7f", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "185e7294-7cb7-4826-8fed-e5aa1a2839b3", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/peft/developer_guides/checkpoint", "title": "PEFT checkpoint format", "tokens": 3329, "retrieve_doc": true, "source": "peft"}, "hash": "7d92964105909aa48c68734f48fbde7f73c1b13d7c2f702bc95e5cde9f318826", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "bde6c775-d81f-4a27-938d-5aa6f92c8166", "node_type": "1", "metadata": {}, "hash": "b347cb92f736563ad20f7ec4f14fe4b6341be9f918d66d57f70cb6bf71e86313", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 4860, "end_char_idx": 7984, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
These parameters are listed in the class attribute `adapter_layer_names` and contain the learnable parameters, so they must be included in the checkpoint file. All the other parameters, like the rank `r`, are derived from the `adapter_config.json` and must be included there (unless the default value is used).

Let's check the `state_dict` of a PEFT LoRA model applied to BERT. When printing the first five keys using the default LoRA settings (the remaining keys are the same, just with different layer numbers), we get:

- `base_model.model.encoder.layer.0.attention.self.query.lora_A.weight` 
- `base_model.model.encoder.layer.0.attention.self.query.lora_B.weight` 
- `base_model.model.encoder.layer.0.attention.self.value.lora_A.weight` 
- `base_model.model.encoder.layer.0.attention.self.value.lora_B.weight` 
- `base_model.model.encoder.layer.1.attention.self.query.lora_A.weight`
- etc.

Let's break this down:

- By default, for BERT models, LoRA is applied to the `query` and `value` layers of the attention module. This is why you see `attention.self.query` and `attention.self.value` in the key names for each layer.
- LoRA decomposes the weights into two low-rank matrices, `lora_A` and `lora_B`. This is where `lora_A` and `lora_B` come from in the key names.
- These LoRA matrices are implemented as `nn.Linear` layers, so the parameters are stored in the `.weight` attribute (`lora_A.weight`, `lora_B.weight`).
- By default, LoRA isn't applied to BERT's embedding layer, so there are _no entries_ for `lora_A_embedding` and `lora_B_embedding`.
- The keys of the `state_dict` always start with `"base_model.model."`. The reason is that, in PEFT, we wrap the base model inside a tuner-specific model (`LoraModel` in this case), which itself is wrapped in a general PEFT model (`PeftModel`). For this reason, these two prefixes are added to the keys. When converting to the PEFT format, it is required to add these prefixes.

<Tip>

This last point is not true for prefix tuning techniques like prompt tuning. There, the extra embeddings are directly stored in the `state_dict` without any prefixes added to the keys.

</Tip>

When inspecting the parameter names in the loaded model, you might be surprised to find that they look a bit different, e.g. `base_model.model.encoder.layer.0.attention.self.query.lora_A.default.weight`. The difference is the *`.default`* part in the second to last segment. This part exists because PEFT generally allows the addition of multiple adapters at once (using an `nn.ModuleDict` or `nn.ParameterDict` to store them). For example, if you add another adapter called "other", the key for that adapter would be `base_model.model.encoder.layer.0.attention.self.query.lora_A.other.weight`.

When you call [`~PeftModel.save_pretrained`], the adapter name is stripped from the keys. The reason is that the adapter name is not an important part of the model architecture; it is just an arbitrary name. When loading the adapter, you could choose a totally different name, and the model would still work the same way. This is why the adapter name is not stored in the checkpoint file.


key: _node_content
string_value:
{"id_": "bde6c775-d81f-4a27-938d-5aa6f92c8166", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/peft/developer_guides/checkpoint", "title": "PEFT checkpoint format", "tokens": 3329, "retrieve_doc": true, "source": "peft"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "f6468a0c-8aa0-41ac-b07b-60a444da384c", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/peft/developer_guides/checkpoint", "title": "PEFT checkpoint format", "tokens": 3329, "retrieve_doc": true, "source": "peft"}, "hash": "b5a16eafb9f7797e65ffc2b56e056a1313df363eff570e9b50f1b7654f395a7f", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "b6e5b779-99c2-4b17-bbb1-eaacf5c75777", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/peft/developer_guides/checkpoint", "title": "PEFT checkpoint format", "tokens": 3329, "retrieve_doc": true, "source": "peft"}, "hash": "62d65183e3728172fe10018f0b5c59ea1eaf254345d33bf72782f7d9efcc6bea", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "c0cb792a-386d-431d-9ff7-fd0e8350f658", "node_type": "1", "metadata": {}, "hash": "5acd588aaa9ae4bd42b665c39338b4e4dfd860f27f6ad29573828d865799e6cd", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 6287, "end_char_idx": 8890, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
- By default, LoRA isn't applied to BERT's embedding layer, so there are _no entries_ for `lora_A_embedding` and `lora_B_embedding`.
- The keys of the `state_dict` always start with `"base_model.model."`. The reason is that, in PEFT, we wrap the base model inside a tuner-specific model (`LoraModel` in this case), which itself is wrapped in a general PEFT model (`PeftModel`). For this reason, these two prefixes are added to the keys. When converting to the PEFT format, it is required to add these prefixes.

<Tip>

This last point is not true for prefix tuning techniques like prompt tuning. There, the extra embeddings are directly stored in the `state_dict` without any prefixes added to the keys.

</Tip>

When inspecting the parameter names in the loaded model, you might be surprised to find that they look a bit different, e.g. `base_model.model.encoder.layer.0.attention.self.query.lora_A.default.weight`. The difference is the *`.default`* part in the second to last segment. This part exists because PEFT generally allows the addition of multiple adapters at once (using an `nn.ModuleDict` or `nn.ParameterDict` to store them). For example, if you add another adapter called "other", the key for that adapter would be `base_model.model.encoder.layer.0.attention.self.query.lora_A.other.weight`.

When you call [`~PeftModel.save_pretrained`], the adapter name is stripped from the keys. The reason is that the adapter name is not an important part of the model architecture; it is just an arbitrary name. When loading the adapter, you could choose a totally different name, and the model would still work the same way. This is why the adapter name is not stored in the checkpoint file.

<Tip>

If you call `save_pretrained("some/path")` and the adapter name is not `"default"`, the adapter is stored in a sub-directory with the same name as the adapter. So if the name is "other", it would be stored inside of `some/path/other`.

</Tip>

In some circumstances, deciding which values to add to the checkpoint file can become a bit more complicated. For example, in PEFT, DoRA is implemented as a special case of LoRA. If you want to convert a DoRA model to PEFT, you should create a LoRA checkpoint with extra entries for DoRA. You can see this in the `__init__` of the previous `LoraLayer` code:

```python
self.lora_magnitude_vector: Optional[torch.nn.ParameterDict] = None  # for DoRA
```

This indicates that there is an optional extra parameter per layer for DoRA.

### adapter_config

All the other information needed to load a PEFT model is contained in the `adapter_config.json` file.


key: _node_content
string_value:
{"id_": "c0cb792a-386d-431d-9ff7-fd0e8350f658", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/peft/developer_guides/checkpoint", "title": "PEFT checkpoint format", "tokens": 3329, "retrieve_doc": true, "source": "peft"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "f6468a0c-8aa0-41ac-b07b-60a444da384c", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/peft/developer_guides/checkpoint", "title": "PEFT checkpoint format", "tokens": 3329, "retrieve_doc": true, "source": "peft"}, "hash": "b5a16eafb9f7797e65ffc2b56e056a1313df363eff570e9b50f1b7654f395a7f", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "bde6c775-d81f-4a27-938d-5aa6f92c8166", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/peft/developer_guides/checkpoint", "title": "PEFT checkpoint format", "tokens": 3329, "retrieve_doc": true, "source": "peft"}, "hash": "71b9f5f8e1a1ce36c75f41bc948cf7dbc774ccc52defdd2a23eaa07e43fc3276", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "5c55c686-8faa-45dd-8975-95c171f619ee", "node_type": "1", "metadata": {}, "hash": "f4ebd25dc46ccd6211ee4a3c6dc94c393b087fbb262904920babf7a0e0c676f2", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 7204, "end_char_idx": 10217, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


