Stage Harbor release files 2001-2500
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- tasks/tasksmith-0d2d1e298e86/tests/source/docs/source/package_reference/hotswap.md +80 -0
- tasks/tasksmith-0d2d1e298e86/tests/source/docs/source/package_reference/hra.md +40 -0
- tasks/tasksmith-0d2d1e298e86/tests/source/docs/source/package_reference/ia3.md +79 -0
- tasks/tasksmith-0d2d1e298e86/tests/source/docs/source/package_reference/layernorm_tuning.md +45 -0
- tasks/tasksmith-0d2d1e298e86/tests/source/docs/source/package_reference/lily.md +52 -0
- tasks/tasksmith-0d2d1e298e86/tests/source/docs/source/package_reference/llama_adapter.md +47 -0
- tasks/tasksmith-0d2d1e298e86/tests/source/docs/source/package_reference/loha.md +90 -0
- tasks/tasksmith-0d2d1e298e86/tests/source/docs/source/package_reference/lokr.md +64 -0
- tasks/tasksmith-0d2d1e298e86/tests/source/docs/source/package_reference/lora.md +1097 -0
- tasks/tasksmith-0d2d1e298e86/tests/source/docs/source/package_reference/lora_conversion.md +155 -0
- tasks/tasksmith-0d2d1e298e86/tests/source/docs/source/package_reference/lora_variant_bdlora.md +20 -0
- tasks/tasksmith-0d2d1e298e86/tests/source/docs/source/package_reference/lora_variant_dora.md +83 -0
- tasks/tasksmith-0d2d1e298e86/tests/source/docs/source/package_reference/lora_variant_monteclora.md +54 -0
- tasks/tasksmith-0d2d1e298e86/tests/source/docs/source/package_reference/lora_variant_velora.md +52 -0
- tasks/tasksmith-0d2d1e298e86/tests/source/docs/source/package_reference/merge_utils.md +33 -0
- tasks/tasksmith-0d2d1e298e86/tests/source/docs/source/package_reference/miss.md +102 -0
- tasks/tasksmith-0d2d1e298e86/tests/source/docs/source/package_reference/multitask_prompt_tuning.md +55 -0
- tasks/tasksmith-0d2d1e298e86/tests/source/docs/source/package_reference/oft.md +98 -0
- tasks/tasksmith-0d2d1e298e86/tests/source/docs/source/package_reference/osf.md +254 -0
- tasks/tasksmith-0d2d1e298e86/tests/source/docs/source/package_reference/p_tuning.md +70 -0
- tasks/tasksmith-0d2d1e298e86/tests/source/docs/source/package_reference/peanut.md +64 -0
- tasks/tasksmith-0d2d1e298e86/tests/source/docs/source/package_reference/peft_model.md +77 -0
- tasks/tasksmith-0d2d1e298e86/tests/source/docs/source/package_reference/peft_types.md +27 -0
- tasks/tasksmith-0d2d1e298e86/tests/source/docs/source/package_reference/poly.md +48 -0
- tasks/tasksmith-0d2d1e298e86/tests/source/docs/source/package_reference/prefix_tuning.md +123 -0
- tasks/tasksmith-0d2d1e298e86/tests/source/docs/source/package_reference/prompt_tuning.md +74 -0
- tasks/tasksmith-0d2d1e298e86/tests/source/docs/source/package_reference/psoft.md +139 -0
- tasks/tasksmith-0d2d1e298e86/tests/source/docs/source/package_reference/pvera.md +51 -0
- tasks/tasksmith-0d2d1e298e86/tests/source/docs/source/package_reference/randlora.md +56 -0
- tasks/tasksmith-0d2d1e298e86/tests/source/docs/source/package_reference/road.md +42 -0
- tasks/tasksmith-0d2d1e298e86/tests/source/docs/source/package_reference/shira.md +46 -0
- tasks/tasksmith-0d2d1e298e86/tests/source/docs/source/package_reference/tinylora.md +52 -0
- tasks/tasksmith-0d2d1e298e86/tests/source/docs/source/package_reference/trainable_tokens.md +61 -0
- tasks/tasksmith-0d2d1e298e86/tests/source/docs/source/package_reference/tuners.md +27 -0
- tasks/tasksmith-0d2d1e298e86/tests/source/docs/source/package_reference/vblora.md +51 -0
- tasks/tasksmith-0d2d1e298e86/tests/source/docs/source/package_reference/vera.md +50 -0
- tasks/tasksmith-0d2d1e298e86/tests/source/docs/source/package_reference/waveft.md +46 -0
- tasks/tasksmith-0d2d1e298e86/tests/source/docs/source/package_reference/xlora.md +62 -0
- tasks/tasksmith-0d2d1e298e86/tests/source/docs/source/quicktour.md +230 -0
- tasks/tasksmith-0d2d1e298e86/tests/source/examples/KappaTune/README.md +215 -0
- tasks/tasksmith-0d2d1e298e86/tests/source/examples/KappaTune/experiments_kappatune_peft.py +162 -0
- tasks/tasksmith-0d2d1e298e86/tests/source/examples/adamss_finetuning/README.md +203 -0
- tasks/tasksmith-0d2d1e298e86/tests/source/examples/adamss_finetuning/glue_adamss_asa_example.py +382 -0
- tasks/tasksmith-0d2d1e298e86/tests/source/examples/adamss_finetuning/glue_adamss_asa_manual_example.py +411 -0
- tasks/tasksmith-0d2d1e298e86/tests/source/examples/adamss_finetuning/image_classification_adamss_asa.py +452 -0
- tasks/tasksmith-0d2d1e298e86/tests/source/examples/adamss_finetuning/test_adamss_quick.py +176 -0
- tasks/tasksmith-0d2d1e298e86/tests/source/examples/alora_finetuning/README.md +76 -0
- tasks/tasksmith-0d2d1e298e86/tests/source/examples/alora_finetuning/alora_finetuning.py +259 -0
- tasks/tasksmith-0d2d1e298e86/tests/source/examples/arrow_multitask/arrow_phi3_mini.py +383 -0
- tasks/tasksmith-0d2d1e298e86/tests/source/examples/arrow_multitask/requirements.txt +8 -0
tasks/tasksmith-0d2d1e298e86/tests/source/docs/source/package_reference/hotswap.md
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!--⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be
|
| 2 |
+
rendered properly in your Markdown viewer.
|
| 3 |
+
-->
|
| 4 |
+
|
| 5 |
+
# Hotswapping adapters
|
| 6 |
+
|
| 7 |
+
The idea of hotswapping an adapter is the following: We can already load multiple adapters, e.g. two LoRAs, at the same time. But sometimes, we want to load one LoRA and then replace its weights in-place with the LoRA weights of another adapter. This is now possible the `hotswap_adapter` function.
|
| 8 |
+
|
| 9 |
+
In general, this should be faster than deleting one adapter and loading the adapter in its place, which would be the how to achieve the same final outcome without hotswapping. Another advantage of hotswapping is that it prevents re-compilation in case the PEFT model is already compiled using `torch.compile`. This can save quite a lot of time.
|
| 10 |
+
|
| 11 |
+
## Example without `torch.compile`
|
| 12 |
+
|
| 13 |
+
```python
|
| 14 |
+
import torch
|
| 15 |
+
from transformers import AutoModelForCausalLM
|
| 16 |
+
from peft import PeftModel
|
| 17 |
+
from peft.utils.hotswap import hotswap_adapter
|
| 18 |
+
|
| 19 |
+
model_id = ...
|
| 20 |
+
inputs = ...
|
| 21 |
+
device = ...
|
| 22 |
+
model = AutoModelForCausalLM.from_pretrained(model_id).to(device)
|
| 23 |
+
|
| 24 |
+
# load lora 0
|
| 25 |
+
model = PeftModel.from_pretrained(model, <path-adapter-0>)
|
| 26 |
+
with torch.inference_mode():
|
| 27 |
+
output_adapter_0 = model(inputs)
|
| 28 |
+
|
| 29 |
+
# replace the "default" lora adapter with the new one
|
| 30 |
+
hotswap_adapter(model, <path-adapter-1>, adapter_name="default", torch_device=device)
|
| 31 |
+
with torch.inference_mode():
|
| 32 |
+
output_adapter_1 = model(inputs).logits
|
| 33 |
+
```
|
| 34 |
+
|
| 35 |
+
## Example with `torch.compile`
|
| 36 |
+
|
| 37 |
+
```python
|
| 38 |
+
import torch
|
| 39 |
+
from transformers import AutoModelForCausalLM
|
| 40 |
+
from peft import PeftModel
|
| 41 |
+
from peft.utils.hotswap import hotswap_adapter, prepare_model_for_compiled_hotswap
|
| 42 |
+
|
| 43 |
+
model_id = ...
|
| 44 |
+
inputs = ...
|
| 45 |
+
device = ...
|
| 46 |
+
max_rank = ... # maximum rank among all LoRA adapters that will be used
|
| 47 |
+
model = AutoModelForCausalLM.from_pretrained(model_id).to(device)
|
| 48 |
+
|
| 49 |
+
# load lora 0
|
| 50 |
+
model = PeftModel.from_pretrained(model, <path-adapter-0>)
|
| 51 |
+
# Prepare the model to allow hotswapping even if ranks/scalings of 2nd adapter differ.
|
| 52 |
+
# You can skip this step if all ranks and scalings are identical.
|
| 53 |
+
prepare_model_for_compiled_hotswap(model, target_rank=max_rank)
|
| 54 |
+
model = torch.compile(model)
|
| 55 |
+
with torch.inference_mode():
|
| 56 |
+
output_adapter_0 = model(inputs)
|
| 57 |
+
|
| 58 |
+
# replace the "default" lora adapter with the new one
|
| 59 |
+
hotswap_adapter(model, <path-adapter-1>, adapter_name="default", torch_device=device)
|
| 60 |
+
with torch.inference_mode():
|
| 61 |
+
output_adapter_1 = model(inputs).logits
|
| 62 |
+
```
|
| 63 |
+
|
| 64 |
+
Note that if you want to hotswap weights that were added through `target_parameters`, i.e. that directly target an `nn.Parameter`, re-compilation and/or graph breaks cannot be prevented. Therefore, it is recommended to avoid using `target_parameters` together with compiled models and hotswapping.
|
| 65 |
+
|
| 66 |
+
## Caveats
|
| 67 |
+
|
| 68 |
+
Hotswapping works with transformers models and diffusers models. However, there are some caveats:
|
| 69 |
+
|
| 70 |
+
- Right now, only LoRA is properly supported.
|
| 71 |
+
- It only works for the same PEFT method, so no swapping LoRA and LoHa, for example.
|
| 72 |
+
- The adapter that is being swapped in must target the same layers as the previous adapter or a subset of those layers. It cannot target new layers. Therefore, if possible, start with the adapter that targets most layers.
|
| 73 |
+
|
| 74 |
+
## API
|
| 75 |
+
|
| 76 |
+
[[autodoc]] utils.hotswap.hotswap_adapter
|
| 77 |
+
- all
|
| 78 |
+
|
| 79 |
+
[[autodoc]] utils.hotswap.hotswap_adapter_from_state_dict
|
| 80 |
+
- all
|
tasks/tasksmith-0d2d1e298e86/tests/source/docs/source/package_reference/hra.md
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!--Copyright 2024 The HuggingFace Team. All rights reserved.
|
| 2 |
+
|
| 3 |
+
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
|
| 4 |
+
the License. You may obtain a copy of the License at
|
| 5 |
+
|
| 6 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
| 7 |
+
|
| 8 |
+
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
|
| 9 |
+
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
|
| 10 |
+
specific language governing permissions and limitations under the License.
|
| 11 |
+
|
| 12 |
+
⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be
|
| 13 |
+
rendered properly in your Markdown viewer.
|
| 14 |
+
|
| 15 |
+
-->
|
| 16 |
+
|
| 17 |
+
# Bridging The Gap between Low-rank and Orthogonal Adaptation via Householder Reflection Adaptation (HRA)
|
| 18 |
+
|
| 19 |
+
<div class="flex justify-center">
|
| 20 |
+
<img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/peft/hra.png"/>
|
| 21 |
+
</div>
|
| 22 |
+
<small><a href="https://huggingface.co/papers/2405.17484">Bridging The Gap between Low-rank and Orthogonal Adaptation via Householder Reflection Adaptation</a></small>
|
| 23 |
+
|
| 24 |
+
[HRA](https://huggingface.co/papers/2405.17484) provides a new perspective connecting LoRA to OFT, which means it can harness the advantages of both strategies, by leveraging [Householder reflections](https://en.wikipedia.org/wiki/Householder_transformation) to reduce parameters and computation costs while penalizing the loss of pre-training knowledge. It consistently achieves better performance with fewer trainable parameters and outperforms state-of-the-art adapters across different models, including large language models (LLMs) and conditional image generators.
|
| 25 |
+
|
| 26 |
+
HRA constructs a chain of `r` trainable Householder reflections (HRs). Because the Householder reflection matrix is an orthogonal matrix and the product of orthogonal matrices is also an orthogonal matrix, HRA satisfies the theoretical guarantee of Orthogonal Finetuning (OFT). Meanwhile, HRA can also be viewed as a low-rank fine-tuning adapter. The higher `r`, the more trainable parameters, resulting in a larger model capacity and better performance. Besides, due to the chain structure, the orthogonality of HR planes impacts the capacity and regularity of HRA. To achieve a trade-off between the model capacity and regularity, an orthogonality regularizer of the HR planes is added to the loss function. The weight \\(\lambda\\) can control the strength of the regularizer.
|
| 27 |
+
|
| 28 |
+
The abstract from the paper is:
|
| 29 |
+
|
| 30 |
+
> While following different technical routes, both low-rank and orthogonal adaptation techniques can efficiently adapt large-scale pre-training models in specific tasks or domains based on a small piece of trainable parameters. In this study, we bridge the gap between these two techniques, proposing a simple but effective adaptation method based on Householder reflections. Given a pre-trained model, our method fine-tunes its layers by multiplying each frozen weight matrix with an orthogonal matrix constructed by a chain of learnable Householder reflections (HRs). This HR-based orthogonal fine-tuning is equivalent to an adaptive low-rank adaptation. Moreover, we show that the orthogonality of the reflection planes corresponding to the HRs impacts the model capacity and regularity. The analysis motivates us to regularize the orthogonality of the HRs, leading to different implementations of the proposed Householder reflection adaptation (HRA) method. Compared with state-of-the-art methods, HRA achieves superior performance with fewer learnable parameters when adapting large language models and conditional image generators. The code is available at [peft](https://github.com/huggingface/peft/tree/main/src/peft/tuners/hra) and [HRA](https://github.com/DaShenZi721/HRA).
|
| 31 |
+
|
| 32 |
+
# API
|
| 33 |
+
|
| 34 |
+
## HRAConfig
|
| 35 |
+
|
| 36 |
+
[[autodoc]] tuners.hra.config.HRAConfig
|
| 37 |
+
|
| 38 |
+
## HRAModel
|
| 39 |
+
|
| 40 |
+
[[autodoc]] tuners.hra.model.HRAModel
|
tasks/tasksmith-0d2d1e298e86/tests/source/docs/source/package_reference/ia3.md
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!--Copyright 2023 The HuggingFace Team. All rights reserved.
|
| 2 |
+
|
| 3 |
+
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
|
| 4 |
+
the License. You may obtain a copy of the License at
|
| 5 |
+
|
| 6 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
| 7 |
+
|
| 8 |
+
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
|
| 9 |
+
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
|
| 10 |
+
specific language governing permissions and limitations under the License.
|
| 11 |
+
|
| 12 |
+
⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be
|
| 13 |
+
rendered properly in your Markdown viewer.
|
| 14 |
+
|
| 15 |
+
-->
|
| 16 |
+
|
| 17 |
+
# IA3
|
| 18 |
+
|
| 19 |
+
<div class="flex justify-center">
|
| 20 |
+
<img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/peft/ia3.png"/>
|
| 21 |
+
</div>
|
| 22 |
+
<small>IA3 introduces three vectors, lv, lk and lff to scale value, key and feed-forward activations <a href="https://hf.co/papers/2205.05638">(image source)</a>.</small>
|
| 23 |
+
|
| 24 |
+
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.
|
| 25 |
+
|
| 26 |
+
The abstract from the paper is:
|
| 27 |
+
|
| 28 |
+
*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*.
|
| 29 |
+
|
| 30 |
+
To make fine-tuning more efficient, IA3 (Infused Adapter by Inhibiting and Amplifying Inner Activations)
|
| 31 |
+
rescales inner activations with learned vectors. These learned vectors are injected in the attention and feedforward modules
|
| 32 |
+
in a typical transformer-based architecture. These learned vectors are the only trainable parameters during fine-tuning, and thus the original
|
| 33 |
+
weights remain frozen. Dealing with learned vectors (as opposed to learned low-rank updates to a weight matrix like LoRA)
|
| 34 |
+
keeps the number of trainable parameters much smaller.
|
| 35 |
+
|
| 36 |
+
Being similar to [LoRA](./lora), IA3 carries many of the same advantages:
|
| 37 |
+
|
| 38 |
+
* 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%)
|
| 39 |
+
* 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.
|
| 40 |
+
* Performance of models fine-tuned using IA3 is comparable to the performance of fully fine-tuned models.
|
| 41 |
+
* IA3 does not add any inference latency because adapter weights can be merged with the base model.
|
| 42 |
+
|
| 43 |
+
In principle, IA3 can be applied to any subset of weight matrices in a neural network to reduce the number of trainable
|
| 44 |
+
parameters. Following the authors' implementation, IA3 weights are added to the key, value and feedforward layers
|
| 45 |
+
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
|
| 46 |
+
in each transformer block.
|
| 47 |
+
|
| 48 |
+
Given the target layers for injecting IA3 parameters, the number of trainable parameters
|
| 49 |
+
can be determined based on the size of the weight matrices.
|
| 50 |
+
|
| 51 |
+
## Usage
|
| 52 |
+
|
| 53 |
+
For the task of sequence classification, one can initialize the IA3 config for a Llama model as follows:
|
| 54 |
+
|
| 55 |
+
```py
|
| 56 |
+
peft_config = IA3Config(
|
| 57 |
+
task_type=TaskType.SEQ_CLS, target_modules=["k_proj", "v_proj", "down_proj"], feedforward_modules=["down_proj"]
|
| 58 |
+
)
|
| 59 |
+
```
|
| 60 |
+
|
| 61 |
+
## Benchmark overview
|
| 62 |
+
|
| 63 |
+
<iframe
|
| 64 |
+
src="https://peft-internal-testing-peft-method-comparison-embed.hf.space/?highlight[type]=IA3"
|
| 65 |
+
frameborder="0"
|
| 66 |
+
width="850"
|
| 67 |
+
height="1000"
|
| 68 |
+
></iframe>
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
# API
|
| 72 |
+
|
| 73 |
+
## IA3Config
|
| 74 |
+
|
| 75 |
+
[[autodoc]] tuners.ia3.config.IA3Config
|
| 76 |
+
|
| 77 |
+
## IA3Model
|
| 78 |
+
|
| 79 |
+
[[autodoc]] tuners.ia3.model.IA3Model
|
tasks/tasksmith-0d2d1e298e86/tests/source/docs/source/package_reference/layernorm_tuning.md
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!--Copyright 2024 The HuggingFace Team. All rights reserved.
|
| 2 |
+
|
| 3 |
+
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
|
| 4 |
+
the License. You may obtain a copy of the License at
|
| 5 |
+
|
| 6 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
| 7 |
+
|
| 8 |
+
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
|
| 9 |
+
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
|
| 10 |
+
specific language governing permissions and limitations under the License.
|
| 11 |
+
|
| 12 |
+
⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be
|
| 13 |
+
rendered properly in your Markdown viewer.
|
| 14 |
+
|
| 15 |
+
-->
|
| 16 |
+
|
| 17 |
+
# LayerNorm Tuning
|
| 18 |
+
|
| 19 |
+
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.
|
| 20 |
+
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.
|
| 21 |
+
However, the method is not limited to language models and can be applied to any model that uses LayerNorm layers.
|
| 22 |
+
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`.
|
| 23 |
+
|
| 24 |
+
The abstract from the paper is:
|
| 25 |
+
|
| 26 |
+
*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.*
|
| 27 |
+
|
| 28 |
+
## Benchmark overview
|
| 29 |
+
|
| 30 |
+
<iframe
|
| 31 |
+
src="https://peft-internal-testing-peft-method-comparison-embed.hf.space/?highlight[type]=LN_TUNING"
|
| 32 |
+
frameborder="0"
|
| 33 |
+
width="850"
|
| 34 |
+
height="1000"
|
| 35 |
+
></iframe>
|
| 36 |
+
|
| 37 |
+
# API
|
| 38 |
+
|
| 39 |
+
## LNTuningConfig
|
| 40 |
+
|
| 41 |
+
[[autodoc]] tuners.ln_tuning.config.LNTuningConfig
|
| 42 |
+
|
| 43 |
+
## LNTuningModel
|
| 44 |
+
|
| 45 |
+
[[autodoc]] tuners.ln_tuning.model.LNTuningModel
|
tasks/tasksmith-0d2d1e298e86/tests/source/docs/source/package_reference/lily.md
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!--Copyright 2026 The HuggingFace Team. All rights reserved.
|
| 2 |
+
|
| 3 |
+
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
|
| 4 |
+
the License. You may obtain a copy of the License at
|
| 5 |
+
|
| 6 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
| 7 |
+
|
| 8 |
+
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
|
| 9 |
+
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
|
| 10 |
+
specific language governing permissions and limitations under the License.
|
| 11 |
+
|
| 12 |
+
⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be
|
| 13 |
+
rendered properly in your Markdown viewer.
|
| 14 |
+
|
| 15 |
+
-->
|
| 16 |
+
|
| 17 |
+
# Lily: Low-Rank Interconnected Adaptation across Layers
|
| 18 |
+
|
| 19 |
+
[Lily](https://huggingface.co/papers/2407.09946) is a parameter-efficient fine-tuning technique that introduces cross-layer weight sharing for adapter matrices. Instead of learning an independent AB pair per layer as in LoRA, Lily uses **locally shared A adapters** (each A is shared across a block of `stride_A` consecutive layers) and **globally shared B experts** (a small pool of `num_B` B adapters is shared across all layers). At each forward pass, a lightweight data-dependent router computes a softmax-weighted combination of the B experts to produce the effective B for that layer and input.
|
| 20 |
+
|
| 21 |
+
This sharing can reduce the total number of adapter matrices from `2N` (standard LoRA) to `N / stride_A + num_B`, freeing up the parameter budget to use a **much larger rank `r`** — typically `2×`–`4×` what you would use in LoRA. Higher rank and better interconnectivity increase the effective rank of the weight update `ΔW = A × combined_B`, leading to better adaptation performance.
|
| 22 |
+
|
| 23 |
+
Because the B combination is **data-dependent** (the router weights depend on the input activations at runtime), `merge` and `unmerge` are **not supported**. If weight merging is required for your deployment, consider other methods such as LoRA instead.
|
| 24 |
+
|
| 25 |
+
Lily currently has the following additional constraints:
|
| 26 |
+
- Only `nn.Linear` layers are supported.
|
| 27 |
+
- Quantized layers are not supported.
|
| 28 |
+
|
| 29 |
+
If these constraints don't work for your use case, consider other methods instead.
|
| 30 |
+
|
| 31 |
+
The abstract from the paper is:
|
| 32 |
+
|
| 33 |
+
> Low-rank adaptation (LoRA) is a widely used parameter-efficient fine-tuning (PEFT) method that learns weight updates ΔW = AB for pretrained weights W through low-rank adapters A and B. While LoRA ensures hardware efficiency, its low-rank weight updates limit adaptation performance. In this paper, we propose low-rank interconnected adaptation across layers (Lily), a novel PEFT method that introduces an interconnected framework with locally shared A and globally shared B experts. This structure eliminates redundant per-layer AB pairs, enabling higher-rank ΔW with equal or fewer parameters. To enhance expressiveness, we use data-dependent routers to determine A-B interconnections, preventing B experts from converging to the same behavior and improving representational power across domains. Experiments across modalities, architectures, and model sizes demonstrate Lily's superior performance and efficiency.
|
| 34 |
+
|
| 35 |
+
## Benchmark overview
|
| 36 |
+
|
| 37 |
+
<iframe
|
| 38 |
+
src="https://peft-internal-testing-peft-method-comparison-embed.hf.space/?highlight[type]=LILY"
|
| 39 |
+
frameborder="0"
|
| 40 |
+
width="850"
|
| 41 |
+
height="1000"
|
| 42 |
+
></iframe>
|
| 43 |
+
|
| 44 |
+
# API
|
| 45 |
+
|
| 46 |
+
## LilyConfig
|
| 47 |
+
|
| 48 |
+
[[autodoc]] tuners.lily.config.LilyConfig
|
| 49 |
+
|
| 50 |
+
## LilyModel
|
| 51 |
+
|
| 52 |
+
[[autodoc]] tuners.lily.model.LilyModel
|
tasks/tasksmith-0d2d1e298e86/tests/source/docs/source/package_reference/llama_adapter.md
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!--Copyright 2023 The HuggingFace Team. All rights reserved.
|
| 2 |
+
|
| 3 |
+
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
|
| 4 |
+
the License. You may obtain a copy of the License at
|
| 5 |
+
|
| 6 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
| 7 |
+
|
| 8 |
+
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
|
| 9 |
+
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
|
| 10 |
+
specific language governing permissions and limitations under the License.
|
| 11 |
+
|
| 12 |
+
⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be
|
| 13 |
+
rendered properly in your Markdown viewer.
|
| 14 |
+
|
| 15 |
+
-->
|
| 16 |
+
|
| 17 |
+
# Llama-Adapter
|
| 18 |
+
|
| 19 |
+
<div class="flex justify-center">
|
| 20 |
+
<img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/peft/llama-adapter.png"/>
|
| 21 |
+
</div>
|
| 22 |
+
<small><a href="https://hf.co/papers/2303.16199">LLaMA-Adapter: Efficient Fine-tuning of Language Models with Zero-init Attention</a></small>
|
| 23 |
+
|
| 24 |
+
[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.
|
| 25 |
+
|
| 26 |
+
The abstract from the paper is:
|
| 27 |
+
|
| 28 |
+
*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*.
|
| 29 |
+
|
| 30 |
+
## Benchmark overview
|
| 31 |
+
|
| 32 |
+
<iframe
|
| 33 |
+
src="https://peft-internal-testing-peft-method-comparison-embed.hf.space/?highlight[type]=ADAPTION_PROMPT"
|
| 34 |
+
frameborder="0"
|
| 35 |
+
width="850"
|
| 36 |
+
height="1000"
|
| 37 |
+
></iframe>
|
| 38 |
+
|
| 39 |
+
# API
|
| 40 |
+
|
| 41 |
+
## AdaptionPromptConfig
|
| 42 |
+
|
| 43 |
+
[[autodoc]] tuners.adaption_prompt.config.AdaptionPromptConfig
|
| 44 |
+
|
| 45 |
+
## AdaptionPromptModel
|
| 46 |
+
|
| 47 |
+
[[autodoc]] tuners.adaption_prompt.model.AdaptionPromptModel
|
tasks/tasksmith-0d2d1e298e86/tests/source/docs/source/package_reference/loha.md
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!--Copyright 2023 The HuggingFace Team. All rights reserved.
|
| 2 |
+
|
| 3 |
+
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
|
| 4 |
+
the License. You may obtain a copy of the License at
|
| 5 |
+
|
| 6 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
| 7 |
+
|
| 8 |
+
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
|
| 9 |
+
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
|
| 10 |
+
specific language governing permissions and limitations under the License.
|
| 11 |
+
|
| 12 |
+
⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be
|
| 13 |
+
rendered properly in your Markdown viewer.
|
| 14 |
+
|
| 15 |
+
-->
|
| 16 |
+
|
| 17 |
+
# LoHa
|
| 18 |
+
|
| 19 |
+
<div class="flex justify-center">
|
| 20 |
+
<img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/peft/lora.png"/>
|
| 21 |
+
</div>
|
| 22 |
+
<small><a href="https://hf.co/papers/2103.10385">Navigating Text-To-Image Customization: From LyCORIS Fine-Tuning to Model Evaluation</a></small>
|
| 23 |
+
|
| 24 |
+
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. LoHa was originally proposed for federated learning (FedPara) but works well as a general-purpose PEFT method, and is especially popular for fine-tuning image generation models such as Stable Diffusion.
|
| 25 |
+
|
| 26 |
+
> **Note:** LoHa is part of the [LyCORIS](./adapter_utils) family of adapters. Its close relative [LoKr](./lokr) uses the Kronecker product instead of the Hadamard product.
|
| 27 |
+
|
| 28 |
+
The abstract from the paper is:
|
| 29 |
+
|
| 30 |
+
*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.*
|
| 31 |
+
|
| 32 |
+
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 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 support for embedding layers isn't currently implemented in PEFT.
|
| 33 |
+
|
| 34 |
+
LoHa uses the [Hadamard product](https://en.wikipedia.org/wiki/Hadamard_product_(matrices)) (element-wise product) instead of the matrix product. $\Delta 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, $\Delta W$ can have the same number of trainable parameters but a higher rank and expressivity.
|
| 35 |
+
|
| 36 |
+
## When to use LoHa
|
| 37 |
+
|
| 38 |
+
LoHa is a good choice when:
|
| 39 |
+
|
| 40 |
+
- You are fine-tuning **image generation models** (Stable Diffusion UNet or text encoder), where it is most widely used.
|
| 41 |
+
- You want **higher effective rank** than LoRA for the same number of trainable parameters, since the Hadamard product of two low-rank matrices spans a larger subspace than a single low-rank product.
|
| 42 |
+
- You want to **combine different PEFT methods** at inference time using [`PeftMixedModel`](./peft_model#peft.PeftMixedModel), for example LoHa together with LoKr.
|
| 43 |
+
|
| 44 |
+
LoHa supports linear and Conv2d layers. For tasks that additionally require embedding layer adaptation, consider [LoRA](./lora) instead.
|
| 45 |
+
|
| 46 |
+
## Usage
|
| 47 |
+
|
| 48 |
+
```python
|
| 49 |
+
from diffusers import StableDiffusionPipeline
|
| 50 |
+
from peft import LoHaConfig, get_peft_model
|
| 51 |
+
|
| 52 |
+
config_unet = LoHaConfig(
|
| 53 |
+
r=8,
|
| 54 |
+
alpha=8,
|
| 55 |
+
target_modules=[
|
| 56 |
+
"to_k",
|
| 57 |
+
"to_q",
|
| 58 |
+
"to_v",
|
| 59 |
+
"to_out.0",
|
| 60 |
+
"proj_in",
|
| 61 |
+
"proj_out",
|
| 62 |
+
],
|
| 63 |
+
rank_dropout=0.0,
|
| 64 |
+
module_dropout=0.0,
|
| 65 |
+
use_effective_conv2d=True,
|
| 66 |
+
)
|
| 67 |
+
|
| 68 |
+
pipeline = StableDiffusionPipeline.from_pretrained("runwayml/stable-diffusion-v1-5")
|
| 69 |
+
pipeline.unet = get_peft_model(pipeline.unet, config_unet)
|
| 70 |
+
pipeline.unet.print_trainable_parameters()
|
| 71 |
+
```
|
| 72 |
+
|
| 73 |
+
## Benchmark overview
|
| 74 |
+
|
| 75 |
+
<iframe
|
| 76 |
+
src="https://peft-internal-testing-peft-method-comparison-embed.hf.space/?highlight[type]=LOHA"
|
| 77 |
+
frameborder="0"
|
| 78 |
+
width="850"
|
| 79 |
+
height="1000"
|
| 80 |
+
></iframe>
|
| 81 |
+
|
| 82 |
+
# API
|
| 83 |
+
|
| 84 |
+
## LoHaConfig
|
| 85 |
+
|
| 86 |
+
[[autodoc]] tuners.loha.config.LoHaConfig
|
| 87 |
+
|
| 88 |
+
## LoHaModel
|
| 89 |
+
|
| 90 |
+
[[autodoc]] tuners.loha.model.LoHaModel
|
tasks/tasksmith-0d2d1e298e86/tests/source/docs/source/package_reference/lokr.md
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!--Copyright 2023 The HuggingFace Team. All rights reserved.
|
| 2 |
+
|
| 3 |
+
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
|
| 4 |
+
the License. You may obtain a copy of the License at
|
| 5 |
+
|
| 6 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
| 7 |
+
|
| 8 |
+
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
|
| 9 |
+
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
|
| 10 |
+
specific language governing permissions and limitations under the License.
|
| 11 |
+
|
| 12 |
+
⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be
|
| 13 |
+
rendered properly in your Markdown viewer.
|
| 14 |
+
|
| 15 |
+
-->
|
| 16 |
+
|
| 17 |
+
# LoKr
|
| 18 |
+
|
| 19 |
+
<div class="flex justify-center">
|
| 20 |
+
<img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/peft/lora.png"/>
|
| 21 |
+
</div>
|
| 22 |
+
<small><a href="https://hf.co/papers/2103.10385">Navigating Text-To-Image Customization: From LyCORIS Fine-Tuning to Model Evaluation</a></small>
|
| 23 |
+
|
| 24 |
+
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](https://en.wikipedia.org/wiki/Kronecker_product). LoKr also provides an optional third low-rank matrix to provide better control during fine-tuning. By expresseing the weight update matrix as a decomposition of a Kronecker product, creating a block matrix, LoKr is able to preserve the rank of the original weight matrix. The size of the smaller matrices are determined by its *rank* or `r`. 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.
|
| 25 |
+
|
| 26 |
+
The abstract from the paper is:
|
| 27 |
+
|
| 28 |
+
*Text-to-image generative models have garnered immense attention for their ability to produce high-fidelity images from text prompts. Among these, Stable Diffusion distinguishes itself as a leading open-source model in this fast-growing field. However, the intricacies of fine-tuning these models pose multiple challenges from new methodology integration to systematic evaluation. Addressing these issues, this paper introduces LyCORIS [Lora beYond Conventional methods, Other Rank adaptation Implementations for Stable diffusion](https://github.com/KohakuBlueleaf/LyCORIS), an open-source library that offers a wide selection of fine-tuning methodologies for Stable Diffusion. Furthermore, we present a thorough framework for the systematic assessment of varied fine-tuning techniques. This framework employs a diverse suite of metrics and delves into multiple facets of fine-tuning, including hyperparameter adjustments and the evaluation with different prompt types across various concept categories. Through this comprehensive approach, our work provides essential insights into the nuanced effects of fine-tuning parameters, bridging the gap between state-of-the-art research and practical application.*
|
| 29 |
+
|
| 30 |
+
## Usage
|
| 31 |
+
|
| 32 |
+
```py
|
| 33 |
+
from peft import LoKrConfig, get_peft_model
|
| 34 |
+
|
| 35 |
+
config = LoKrConfig(
|
| 36 |
+
r=16,
|
| 37 |
+
alpha=16,
|
| 38 |
+
target_modules=["query", "value"],
|
| 39 |
+
module_dropout=0.1,
|
| 40 |
+
modules_to_save=["classifier"],
|
| 41 |
+
)
|
| 42 |
+
model = get_peft_model(model, config)
|
| 43 |
+
model.print_trainable_parameters()
|
| 44 |
+
"trainable params: 116,069 || all params: 87,172,042 || trainable%: 0.13314934162033282"
|
| 45 |
+
```
|
| 46 |
+
|
| 47 |
+
## Benchmark overview
|
| 48 |
+
|
| 49 |
+
<iframe
|
| 50 |
+
src="https://peft-internal-testing-peft-method-comparison-embed.hf.space/?highlight[type]=LOKR"
|
| 51 |
+
frameborder="0"
|
| 52 |
+
width="850"
|
| 53 |
+
height="1000"
|
| 54 |
+
></iframe>
|
| 55 |
+
|
| 56 |
+
# API
|
| 57 |
+
|
| 58 |
+
## LoKrConfig
|
| 59 |
+
|
| 60 |
+
[[autodoc]] tuners.lokr.config.LoKrConfig
|
| 61 |
+
|
| 62 |
+
## LoKrModel
|
| 63 |
+
|
| 64 |
+
[[autodoc]] tuners.lokr.model.LoKrModel
|
tasks/tasksmith-0d2d1e298e86/tests/source/docs/source/package_reference/lora.md
ADDED
|
@@ -0,0 +1,1097 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!--Copyright 2023-present The HuggingFace Team. All rights reserved.
|
| 2 |
+
|
| 3 |
+
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
|
| 4 |
+
the License. You may obtain a copy of the License at
|
| 5 |
+
|
| 6 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
| 7 |
+
|
| 8 |
+
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
|
| 9 |
+
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
|
| 10 |
+
specific language governing permissions and limitations under the License.
|
| 11 |
+
|
| 12 |
+
⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be
|
| 13 |
+
rendered properly in your Markdown viewer.
|
| 14 |
+
|
| 15 |
+
-->
|
| 16 |
+
|
| 17 |
+
# LoRA
|
| 18 |
+
|
| 19 |
+
> [!TIP]
|
| 20 |
+
> 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.
|
| 21 |
+
|
| 22 |
+
Low-Rank Adaptation ([LoRA](https://huggingface.co/papers/2106.09685)) is a PEFT method that decomposes a large matrix into two smaller low-rank matrices. This drastically reduces the number of parameters that need to be fine-tuned.
|
| 23 |
+
|
| 24 |
+
The abstract from the paper is:
|
| 25 |
+
|
| 26 |
+
*An important paradigm of natural language processing consists of large-scale pre-training on general domain data and adaptation to particular tasks or domains. As we pre-train larger models, full fine-tuning, which retrains all model parameters, becomes less feasible. Using GPT-3 175B as an example -- deploying independent instances of fine-tuned models, each with 175B parameters, is prohibitively expensive. We propose Low-Rank Adaptation, or LoRA, which freezes the pre-trained model weights and injects trainable rank decomposition matrices into each layer of the Transformer architecture, greatly reducing the number of trainable parameters for downstream tasks. Compared to GPT-3 175B fine-tuned with Adam, LoRA can reduce the number of trainable parameters by 10,000 times and the GPU memory requirement by 3 times. LoRA performs on-par or better than fine-tuning in model quality on RoBERTa, DeBERTa, GPT-2, and GPT-3, despite having fewer trainable parameters, a higher training throughput, and, unlike adapters, no additional inference latency. We also provide an empirical investigation into rank-deficiency in language model adaptation, which sheds light on the efficacy of LoRA. We release a package that facilitates the integration of LoRA with PyTorch models and provide our implementations and model checkpoints for RoBERTa, DeBERTa, and GPT-2 at [this https URL](https://github.com/microsoft/LoRA).*
|
| 27 |
+
|
| 28 |
+
LoRA represents the weight updates $\Delta 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.
|
| 29 |
+
|
| 30 |
+
<div class="flex justify-center">
|
| 31 |
+
<img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/peft/lora_animated.gif"/>
|
| 32 |
+
</div>
|
| 33 |
+
|
| 34 |
+
This approach has a number of advantages:
|
| 35 |
+
|
| 36 |
+
* LoRA makes finetuning more efficient by drastically reducing the number of trainable parameters.
|
| 37 |
+
* 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.
|
| 38 |
+
* LoRA is orthogonal to other parameter-efficient methods and can be combined with many of them.
|
| 39 |
+
* Performance of models finetuned using LoRA is comparable to the performance of fully finetuned models.
|
| 40 |
+
|
| 41 |
+
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 - it may be worth targeting other layers as well. 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.
|
| 42 |
+
|
| 43 |
+
You can initialize the low-rank matrices with different use-cases in mind - task awareness (CoRDA, EVA), faster convergence (PiSSA), mitigating quantizations (LoftQ) - just to name a few use-cases. Read about the different initializations [below](#initialization). The default initialization is for LoRA to be a no-op, to gradually learn new behavior without interfering much with the existing model.
|
| 44 |
+
|
| 45 |
+
## Usage
|
| 46 |
+
|
| 47 |
+
The size of the low-rank update matrices is determined by the *rank* or `r`. A higher rank means the model has more parameters to train, but it also means the model has more learning capacity. In the following example, you'll target the *query* and *value* matrices of the attention blocks. Other important parameters to set are `lora_alpha` (scaling factor), `bias` (whether `none`, `all` or only the LoRA bias parameters should be trained), and `modules_to_save` (the modules apart from the LoRA layers to be trained and saved). All of these parameters - and more - are found in the [`LoraConfig`].
|
| 48 |
+
|
| 49 |
+
```py
|
| 50 |
+
from peft import LoraConfig, get_peft_model
|
| 51 |
+
|
| 52 |
+
config = LoraConfig(
|
| 53 |
+
r=16,
|
| 54 |
+
lora_alpha=16,
|
| 55 |
+
target_modules=["query", "value"],
|
| 56 |
+
lora_dropout=0.1,
|
| 57 |
+
bias="none",
|
| 58 |
+
modules_to_save=["classifier"],
|
| 59 |
+
)
|
| 60 |
+
model = get_peft_model(model, config)
|
| 61 |
+
model.print_trainable_parameters()
|
| 62 |
+
"trainable params: 667,493 || all params: 86,543,818 || trainable%: 0.7712775047664294"
|
| 63 |
+
```
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
## Benchmark overview
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
<iframe
|
| 70 |
+
src="https://peft-internal-testing-peft-method-comparison-embed.hf.space/?highlight[type]=LORA"
|
| 71 |
+
frameborder="0"
|
| 72 |
+
width="850"
|
| 73 |
+
height="1000"
|
| 74 |
+
></iframe>
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
## Initialization
|
| 78 |
+
|
| 79 |
+
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)).
|
| 80 |
+
|
| 81 |
+
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).
|
| 82 |
+
|
| 83 |
+
```py
|
| 84 |
+
from peft import LoraConfig
|
| 85 |
+
|
| 86 |
+
config = LoraConfig(init_lora_weights="gaussian", ...)
|
| 87 |
+
```
|
| 88 |
+
|
| 89 |
+
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.
|
| 90 |
+
|
| 91 |
+
```py
|
| 92 |
+
from peft import LoraConfig
|
| 93 |
+
|
| 94 |
+
config = LoraConfig(init_lora_weights=False, ...)
|
| 95 |
+
```
|
| 96 |
+
|
| 97 |
+
<hfoptions id="initializations">
|
| 98 |
+
<hfoption id="PiSSA">
|
| 99 |
+
[PiSSA](https://huggingface.co/papers/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.
|
| 100 |
+
|
| 101 |
+
Configure the initialization method to "pissa", which may take several minutes to execute SVD on the pre-trained model:
|
| 102 |
+
```python
|
| 103 |
+
from peft import LoraConfig
|
| 104 |
+
config = LoraConfig(init_lora_weights="pissa", ...)
|
| 105 |
+
```
|
| 106 |
+
Alternatively, execute fast SVD, which takes only a few seconds. The number of iterations determines the trade-off between the error and computation time:
|
| 107 |
+
```python
|
| 108 |
+
lora_config = LoraConfig(init_lora_weights="pissa_niter_[number of iters]", ...)
|
| 109 |
+
```
|
| 110 |
+
For detailed instruction on using PiSSA, please follow [these instructions](https://github.com/huggingface/peft/tree/main/examples/pissa_finetuning).
|
| 111 |
+
</hfoption>
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
<hfoption id="MiCA">
|
| 115 |
+
[MiCA](https://arxiv.org/abs/2604.01694) (Minor Component Adaptation) is a complement to PiSSA: instead of initializing from the *principal* singular components, MiCA uses the *minor* ones. Concretely, with `W = U Σ V^T`, MiCA sets `B = U[:, -r:]` (the `r` left singular vectors associated with the smallest singular values) and `A = 0`. During training, only `A` is updated; `B` is frozen. The intuition is that the minor singular directions are largely unused by the pretrained task and therefore offer a more "plastic" subspace for injecting new knowledge while preserving pretrained capabilities.
|
| 116 |
+
|
| 117 |
+
Because `A == 0` at init, the adapter contribution `B · A == 0` and the model output is preserved exactly at step 0 — no residual subtraction on the base weight is needed (unlike PiSSA). Since only `A` is trainable, the trainable parameter count for matching `r` is roughly half that of LoRA.
|
| 118 |
+
|
| 119 |
+
```python
|
| 120 |
+
from peft import LoraConfig
|
| 121 |
+
config = LoraConfig(init_lora_weights="mica", r=16, target_modules=["q_proj", "v_proj"], ...)
|
| 122 |
+
```
|
| 123 |
+
|
| 124 |
+
MiCA currently supports `nn.Linear` and `nn.Embedding` target modules. The chosen rank must satisfy `r <= min(in_features, out_features)` for linear layers and `r <= min(num_embeddings, embedding_dim)` for embedding layers. For detailed usage, see [these instructions](https://github.com/huggingface/peft/tree/main/examples/mica_finetuning).
|
| 125 |
+
|
| 126 |
+
MiCA is primarily intended for continued pretraining / domain-adaptive pretraining. In that setting, use the base model, not an instruction- or chat-tuned checkpoint, for the SVD initialization and MiCA training. After training, merge the adapter into the base model weights and use the resulting adapted base model as the starting point for subsequent instruction/chat tuning.
|
| 127 |
+
</hfoption>
|
| 128 |
+
|
| 129 |
+
<hfoption id="CorDA">
|
| 130 |
+
[CorDA](https://huggingface.co/papers/2406.05223) builds task-aware LoRA adapters from weight decomposition oriented by the context of downstream task to learn (instruction-previewed mode, IPM) or world knowledge to maintain (knowledge-preserved mode, KPM). The KPM not only achieves better performance than LoRA on fine-tuning tasks, but also mitigates the catastrophic forgetting of pre-trained world knowledge. When preserving pre-trained knowledge is not a concern, the IPM is favored because it can further accelerate convergence and enhance the fine-tuning performance.
|
| 131 |
+
|
| 132 |
+
You need to configure the initialization method to "corda", and specify the mode of IPM or KPM and the dataset to collect covariance matrices.
|
| 133 |
+
|
| 134 |
+
```py
|
| 135 |
+
@torch.no_grad()
|
| 136 |
+
def run_model():
|
| 137 |
+
# Assume `model` and `dataset` is in context...
|
| 138 |
+
model.eval()
|
| 139 |
+
for batch in dataset:
|
| 140 |
+
model(**batch)
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
corda_config = CordaConfig(
|
| 144 |
+
corda_method="kpm",
|
| 145 |
+
)
|
| 146 |
+
lora_config = LoraConfig(
|
| 147 |
+
init_lora_weights="corda",
|
| 148 |
+
corda_config=corda_config,
|
| 149 |
+
)
|
| 150 |
+
preprocess_corda(model, lora_config, run_model=run_model)
|
| 151 |
+
peft_model = get_peft_model(model, lora_config)
|
| 152 |
+
```
|
| 153 |
+
|
| 154 |
+
For detailed instruction on using CorDA, please follow [these instructions](https://github.com/huggingface/peft/tree/main/examples/corda_finetuning).
|
| 155 |
+
</hfoption>
|
| 156 |
+
|
| 157 |
+
<hfoption id="OLoRA">
|
| 158 |
+
[OLoRA](https://huggingface.co/papers/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.
|
| 159 |
+
|
| 160 |
+
You just need to pass a single additional option to use OLoRA:
|
| 161 |
+
```python
|
| 162 |
+
from peft import LoraConfig
|
| 163 |
+
config = LoraConfig(init_lora_weights="olora", ...)
|
| 164 |
+
```
|
| 165 |
+
For more advanced usage, please refer to our [documentation](https://github.com/huggingface/peft/tree/main/examples/olora_finetuning).
|
| 166 |
+
</hfoption>
|
| 167 |
+
|
| 168 |
+
<hfoption id="EVA">
|
| 169 |
+
[EVA](https://huggingface.co/papers/2410.07170) performs SVD on the input activations of each layer and uses the right-singular vectors to initialize LoRA weights. It is therefore a data-driven initialization scheme. Furthermore EVA adaptively allocates ranks across layers based on their "explained variance ratio" - a metric derived from the SVD analysis.
|
| 170 |
+
|
| 171 |
+
You can use EVA by setting `init_lora_weights="eva"` and defining [`EvaConfig`] in [`LoraConfig`]:
|
| 172 |
+
```python
|
| 173 |
+
from peft import LoraConfig, EvaConfig
|
| 174 |
+
peft_config = LoraConfig(
|
| 175 |
+
init_lora_weights = "eva",
|
| 176 |
+
eva_config = EvaConfig(rho = 2.0),
|
| 177 |
+
...
|
| 178 |
+
)
|
| 179 |
+
```
|
| 180 |
+
The parameter `rho` (≥ 1.0) determines how much redistribution is allowed. When `rho=1.0` and `r=16`, LoRA adapters are limited to exactly 16 ranks, preventing any redistribution from occurring. A recommended value for EVA with redistribution is 2.0, meaning the maximum rank allowed for a layer is 2r.
|
| 181 |
+
|
| 182 |
+
It is recommended to perform EVA initialization on an accelerator(e.g. CUDA GPU, Intel XPU) as it is much faster. To optimize the amount of available memory for EVA, you can use the `low_cpu_mem_usage` flag in [`get_peft_model`]:
|
| 183 |
+
```python
|
| 184 |
+
peft_model = get_peft_model(model, peft_config, low_cpu_mem_usage=True)
|
| 185 |
+
```
|
| 186 |
+
Then, call [`initialize_lora_eva_weights`] to initialize the EVA weights (in most cases the dataloader used for eva initialization can be the same as the one used for finetuning):
|
| 187 |
+
```python
|
| 188 |
+
initialize_lora_eva_weights(peft_model, dataloader)
|
| 189 |
+
```
|
| 190 |
+
EVA works out of the box with bitsandbytes. Simply initialize the model with `quantization_config` and call [`initialize_lora_eva_weights`] as usual.
|
| 191 |
+
|
| 192 |
+
> [!TIP]
|
| 193 |
+
> For further instructions on using EVA, please refer to our [documentation](https://github.com/huggingface/peft/tree/main/examples/eva_finetuning).
|
| 194 |
+
</hfoption>
|
| 195 |
+
|
| 196 |
+
<hfoption id="LoftQ">
|
| 197 |
+
When quantizing the base model for QLoRA training, consider using the [LoftQ initialization](https://huggingface.co/papers/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).
|
| 198 |
+
|
| 199 |
+
> [!TIP]
|
| 200 |
+
> Learn more about how PEFT works with quantization and how to use LoftQ in the [Quantization](../developer_guides/quantization) guide.
|
| 201 |
+
</hfoption>
|
| 202 |
+
|
| 203 |
+
<hfoption id="rsLoRA">
|
| 204 |
+
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`.
|
| 205 |
+
|
| 206 |
+
```py
|
| 207 |
+
from peft import LoraConfig
|
| 208 |
+
|
| 209 |
+
config = LoraConfig(use_rslora=True, ...)
|
| 210 |
+
```
|
| 211 |
+
</hfoption>
|
| 212 |
+
|
| 213 |
+
<hfoption id="LoRA-GA">
|
| 214 |
+
[LoRA-GA](https://hf.co/papers/2407.05000) (Low-Rank Adaptation with Gradient Approximation) initializes the adapter
|
| 215 |
+
weights by performing SVD on estimated gradients, so that the weights are aligning closer to full-finetuning for faster
|
| 216 |
+
convergence.
|
| 217 |
+
|
| 218 |
+
This method requires an initialization function to estimate the gradients
|
| 219 |
+
before beginning the actual training:
|
| 220 |
+
|
| 221 |
+
```python
|
| 222 |
+
from peft.tuners.lora import preprocess_loraga
|
| 223 |
+
|
| 224 |
+
def train_step():
|
| 225 |
+
"""Run forward and backward passes for gradient estimation."""
|
| 226 |
+
dataloader_iter = iter(grad_dataloader)
|
| 227 |
+
for _ in range(N):
|
| 228 |
+
batch = next(dataloader_iter)
|
| 229 |
+
batch = {k: v.to(device) for k, v in batch.items()}
|
| 230 |
+
outputs = model(**batch)
|
| 231 |
+
loss = outputs.loss
|
| 232 |
+
loss.backward()
|
| 233 |
+
|
| 234 |
+
preprocess_loraga(model, lora_config, train_step)
|
| 235 |
+
```
|
| 236 |
+
|
| 237 |
+
#### Usage Tips
|
| 238 |
+
|
| 239 |
+
- **Gradient Estimation**: LoRA-GA requires a gradient estimation phase before model initialization. Use `preprocess_loraga()` with a `train_step` callback to compute gradients over a small number of training batches (typically 64-128 batches).
|
| 240 |
+
|
| 241 |
+
- **Initialization Strategies**: LoRA-GA supports four direction strategies (`direction`): `"ArBr"`, `"A2rBr"`, `"ArB2r"` (default), and `"random"`, and four scaling strategies (`scale`): `"stable"` (default), `"weight_svd"`, `"gd_scale"`, and `"unit"`. The default combination provides the best balance of convergence speed and stability.
|
| 242 |
+
|
| 243 |
+
- **Base Weight Modification**: Unlike standard LoRA, LoRA-GA modifies the base model weights during initialization by subtracting a scaled version of the low-rank approximation. This enables better alignment with full fine-tuning gradients. Since base weights are modified, use `save_pretrained()` with the `save_embedding_layers` argument or `save_mutated_as_lora` pattern to properly save the adapter.
|
| 244 |
+
|
| 245 |
+
- **Computational Overhead**: The gradient estimation adds a small overhead during initialization (typically 1-2 minutes for 64 batches), but this is quickly amortized by faster convergence during training.
|
| 246 |
+
|
| 247 |
+
- **Compatibility**: LoRA-GA requires full-precision weights and does not support quantized models. Can be combined with other LoRA variants like DoRA.
|
| 248 |
+
</hfoption>
|
| 249 |
+
</hfoptions>
|
| 250 |
+
|
| 251 |
+
## Training
|
| 252 |
+
|
| 253 |
+
This section shows how to handle more complex training scenarios instead of only applying a low-rank adapter to the model and feed data.
|
| 254 |
+
|
| 255 |
+
### QLoRA-style training
|
| 256 |
+
|
| 257 |
+
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).
|
| 258 |
+
|
| 259 |
+
```py
|
| 260 |
+
config = LoraConfig(target_modules="all-linear", ...)
|
| 261 |
+
```
|
| 262 |
+
|
| 263 |
+
For more information about how to apply quantization to PEFT adapters, refer to the [quantization guide](../developer_guides/quantization).
|
| 264 |
+
|
| 265 |
+
### Memory efficient Layer Replication with LoRA
|
| 266 |
+
|
| 267 |
+
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://huggingface.co/papers/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.
|
| 268 |
+
|
| 269 |
+
```py
|
| 270 |
+
config = LoraConfig(layer_replication=[[0,4], [2,5]], ...)
|
| 271 |
+
```
|
| 272 |
+
|
| 273 |
+
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 adapters.
|
| 274 |
+
|
| 275 |
+
[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
|
| 276 |
+
[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.
|
| 277 |
+
|
| 278 |
+
### Fine grained control over ranks and alpha (scaling)
|
| 279 |
+
|
| 280 |
+
By default, all layers targeted with LoRA will have the same rank `r` and the same `lora_alpha` (which determines the LoRA scaling), depending on what was specified in the [`LoraConfig`]. In some cases, however, you may want to indicate different values for different layers. This is possible by passing the `rank_pattern` and `alpha_pattern` arguments to [`LoraConfig`]. These arguments should be dictionaries with the key being the layer name and the value being the rank/alpha value. The keys can be [regular expressions](https://docs.python.org/3/library/re.html) (regex). All LoRA layers that are not explicitly mentioned in `rank_pattern` and `alpha_pattern` will take the default `r` and `lora_alpha` values.
|
| 281 |
+
|
| 282 |
+
To give an example, let's assume that we have a model with the following structure:
|
| 283 |
+
|
| 284 |
+
```python
|
| 285 |
+
>>> print(model)
|
| 286 |
+
Outer(
|
| 287 |
+
(foo): Linear(...)
|
| 288 |
+
(module): Middle(
|
| 289 |
+
(foo): Linear(...)
|
| 290 |
+
(foobar): Linear(...)
|
| 291 |
+
(module): Inner(
|
| 292 |
+
(foo): Linear(...)
|
| 293 |
+
(barfoo): Linear(...)
|
| 294 |
+
)
|
| 295 |
+
)
|
| 296 |
+
)
|
| 297 |
+
```
|
| 298 |
+
|
| 299 |
+
- `rank_pattern={"foo": 42}` will match all 3 `foo` layers. Neither `foobar` nor `barfoo` are matched.
|
| 300 |
+
- `rank_pattern={"^foo": 42}` will only match the `foo` layer of the model, but neither `module.foo` nor `module.module.foo`. This is because the `^` means "start of string" when using regular expressions, and only `foo` starts with `"foo"`, the other layer names have prefixes.
|
| 301 |
+
- `rank_pattern={"^module.foo": 42}` matches only `module.foo`, but not `module.module.foo`, for the same reason.
|
| 302 |
+
- `rank_pattern={"module.foo": 42}` matches both `module.foo` and `module.module.foo`, but not `foo`.
|
| 303 |
+
- `rank_pattern={"^foo": 42, "^module.module.foo": 55}` matches `foo` and `module.module.foo`, respectively, but not `module.foo`.
|
| 304 |
+
- There is no need to indicate `$` to mark the end of the match, as this is added automatically by PEFT.
|
| 305 |
+
|
| 306 |
+
The same logic applies to `alpha_pattern`. If you're in doubt, don't try to get fancy with regular expressions -- just pass the full name for each module with a different rank/alpha, preceded by the `^` prefix, and you should be good.
|
| 307 |
+
|
| 308 |
+
### Automatically detect viable target modules
|
| 309 |
+
|
| 310 |
+
[`peft.helpers.KappaTuneSelector`] implements the condition-number-based target selection strategy from the [KappaTune paper](https://arxiv.org/abs/2506.16289). It scans every `nn.Linear` module and, for models where MoE expert weights are stored as fused 3D `nn.Parameter` tensors (e.g. Llama-4, Qwen3-MoE), also those parameters, computes the matrix condition number κ = σ_max / σ_min for each, and selects the most isotropic layers (lowest κ). These isotropic layers serve as ideal candidates for fine-tuning, since their high-entropy nature allows them to absorb new information more readily, leaving the specialized, anisotropic layers intact to mitigate catastrophic forgetting during continual learning.
|
| 311 |
+
|
| 312 |
+
Use [`peft.helpers.find_kappa_target_modules`] as a one-liner to get the optimal `target_modules` for `LoraConfig`:
|
| 313 |
+
|
| 314 |
+
```python
|
| 315 |
+
from peft import LoraConfig, get_peft_model
|
| 316 |
+
from peft.helpers import find_kappa_target_modules
|
| 317 |
+
|
| 318 |
+
model = AutoModelForCausalLM.from_pretrained("mistralai/Mixtral-8x7B-Instruct-v0.1")
|
| 319 |
+
|
| 320 |
+
targets = find_kappa_target_modules(model, top_p=0.2)
|
| 321 |
+
config = LoraConfig(
|
| 322 |
+
target_modules=targets["target_modules"],
|
| 323 |
+
target_parameters=targets["target_parameters"] if stable_modules_dic["target_parameters"] else None,
|
| 324 |
+
r=64,
|
| 325 |
+
lora_alpha=32,
|
| 326 |
+
task_type="CAUSAL_LM",
|
| 327 |
+
)
|
| 328 |
+
peft_model = get_peft_model(model, config)
|
| 329 |
+
```
|
| 330 |
+
|
| 331 |
+
See a complete example [here](https://github.com/huggingface/peft/blob/main/examples/KappaTune/experiments_kappatune_peft.py).
|
| 332 |
+
|
| 333 |
+
### Targeting `nn.Parameter` directly
|
| 334 |
+
|
| 335 |
+
Generally, you should use `target_modules` to target the module (e.g. `nn.Linear`). However, in some circumstances, this is not possible. E.g., in many mixture of expert (MoE) layers in HF Transformers, instead of using `nn.Linear`, an `nn.Parameter` is used. PEFT normally overwrites the `forward` method for LoRA, but for `nn.Parameter`, there is none. Therefore, to apply LoRA to that parameter, it needs to be targeted with `target_parameters`. As an example, for [Llama4](https://huggingface.co/collections/meta-llama/llama-4-67f0c30d9fe03840bc9d0164), you can pass: `target_parameters=['feed_forward.experts.gate_up_proj', 'feed_forward.experts.down_proj]`.
|
| 336 |
+
|
| 337 |
+
Note that when targeting expert parameters, PEFT can add a substantial runtime overhead. The reason is that PEFT always materializes the LoRA contribution for _each expert_ even if only a small amount of experts is required. During training, this is less relevant since, over the course of the sequence, typically a large fraction of experts is activated at least once. However, during inference, normally a KV cache is used and we thus need to only compute the last token, which means that only a small amount of experts is activated. Therefore, using LoRA on MoE layers can result in a substantial slowdown at inference time. The recommendation is thus to merge the weights (`model.merge_adapter()` or `model = model.merge_and_unload()`). This removes the PEFT overhead.
|
| 338 |
+
|
| 339 |
+
A more detailed investigation of this issue can be found on this [pull request on MoE optimization](https://github.com/huggingface/peft/pull/3139).
|
| 340 |
+
|
| 341 |
+
#### Caveats
|
| 342 |
+
|
| 343 |
+
- At the moment, this argument allows to target 2-dim or 3-dim `nn.Parameter`s. It is assumed that in the case of a 3-dim parameter, the 0th dimension is the expert dimension.
|
| 344 |
+
- Multiple LoRA adapters (added via `model.add_adapter` or `model.load_adapter`) that use `target_parameters` are supported, but all of them must target the same set of parameters.
|
| 345 |
+
|
| 346 |
+
#### MoE expert parameters and vLLM
|
| 347 |
+
|
| 348 |
+
Some MoE models in Transformers store expert weights as `nn.Parameter` tensors (often 3D), not `nn.Linear` modules.
|
| 349 |
+
To apply LoRA to those experts, use `target_parameters` and set a per-layer rank with `rank_pattern`:
|
| 350 |
+
|
| 351 |
+
```python
|
| 352 |
+
num_experts = getattr(model.config, "num_local_experts", None) or model.config.num_experts
|
| 353 |
+
effective_r = max(1, r // num_experts)
|
| 354 |
+
config = LoraConfig(
|
| 355 |
+
r=r,
|
| 356 |
+
lora_alpha=32,
|
| 357 |
+
target_modules=["q_proj", "v_proj"],
|
| 358 |
+
target_parameters=[
|
| 359 |
+
# Mixtral / Qwen3-MoE / GPT-OSS
|
| 360 |
+
"mlp.experts.gate_up_proj",
|
| 361 |
+
"mlp.experts.down_proj",
|
| 362 |
+
# Llama4
|
| 363 |
+
# "feed_forward.experts.gate_up_proj",
|
| 364 |
+
# "feed_forward.experts.down_proj",
|
| 365 |
+
],
|
| 366 |
+
rank_pattern={
|
| 367 |
+
"experts.gate_up_proj": effective_r,
|
| 368 |
+
"experts.down_proj": effective_r,
|
| 369 |
+
},
|
| 370 |
+
)
|
| 371 |
+
```
|
| 372 |
+
|
| 373 |
+
This keeps the total LoRA parameter budget similar to dense layers (see [LoRA Without Regret](https://thinkingmachines.ai/blog/lora/) by Schulman et. al.). Non-expert modules use the default rank `r`.
|
| 374 |
+
|
| 375 |
+
Accelerated inference with the fine-tuned model is possible with, for example, [vLLM](https://vllm.ai/) which supports fused MoE expert layers since v0.11.2.
|
| 376 |
+
|
| 377 |
+
### Efficiently train tokens alongside LoRA
|
| 378 |
+
|
| 379 |
+
PEFT LoRA adapters support adding new tokens with the `trainable_token_indices` parameter. This allows tuning of other tokens alongside fine-tuning specific layers. Only the specified tokens are trained and all other tokens are untouched. It saves memory and doesn't throw away learned context from existing token embeddings unlike training the whole embedding matrix. Under the hood this method uses the layer of [`TrainableTokensModel`].
|
| 380 |
+
|
| 381 |
+
```py
|
| 382 |
+
# for layer 'embed_tokens'
|
| 383 |
+
config = LoraConfig(trainable_token_indices=[idx_1, idx_2, ...], ...)
|
| 384 |
+
|
| 385 |
+
# specific embedding layer
|
| 386 |
+
config = LoraConfig(trainable_token_indices={'emb_tokens': [idx_1, idx_2, ...]}, ...)
|
| 387 |
+
```
|
| 388 |
+
|
| 389 |
+
In the snippet below we show how to add new tokens to the model and how to train it alongside the other layers in the model.
|
| 390 |
+
|
| 391 |
+
```py
|
| 392 |
+
from transformers import AutoTokenizer, AutoModelForCausalLM
|
| 393 |
+
from peft import get_peft_model, LoraConfig
|
| 394 |
+
|
| 395 |
+
base_model = AutoModelForCausalLM.from_pretrained("mistralai/Mistral-7B-v0.1")
|
| 396 |
+
tokenizer = AutoTokenizer.from_pretrained("mistralai/Mistral-7B-v0.1")
|
| 397 |
+
|
| 398 |
+
# we define our new tokens and add them to the tokenizer as special tokens
|
| 399 |
+
special_tokens = ['<|start_think|>', '<|stop_think|>']
|
| 400 |
+
tokenizer.add_special_tokens({'additional_special_tokens': special_tokens})
|
| 401 |
+
|
| 402 |
+
# make room for new tokens in the embedding matrix if it isn't big enough already
|
| 403 |
+
base_model.resize_token_embeddings(max(len(tokenizer), base_model.model.embed_tokens.num_embeddings))
|
| 404 |
+
|
| 405 |
+
# typical LoRA config with `trainable_token_indices` targeting embedding layer `embed_tokens`
|
| 406 |
+
# and specifically our new tokens we just added
|
| 407 |
+
lora_config = LoraConfig(
|
| 408 |
+
target_modules='all-linear',
|
| 409 |
+
trainable_token_indices={'embed_tokens': tokenizer.convert_tokens_to_ids(special_tokens)},
|
| 410 |
+
)
|
| 411 |
+
peft_model = get_peft_model(base_model, lora_config)
|
| 412 |
+
|
| 413 |
+
# proceed to train the model like normal
|
| 414 |
+
[...]
|
| 415 |
+
```
|
| 416 |
+
|
| 417 |
+
The token weights are saved as a part of the adapter state dict alongside the LoRA weights. Full fine-tuning and saving the embedding matrix would have stored a much bigger file.
|
| 418 |
+
|
| 419 |
+
To give a bit of an indication how much VRAM can be saved, a rudimentary comparison of the above example was made between training the embedding matrix fully (`modules_to_save=["embed_tokens"]`), using a LoRA for the embedding matrix (`target_modules=[..., "embed_tokens"]`, rank 32) and trainable tokens (`trainable_token_indices=[...]`, 6 tokens):
|
| 420 |
+
|
| 421 |
+
| | Trainable Tokens | LoRA | Full Fine-tuning |
|
| 422 |
+
| --------: | :--------------: | :--------: | :--------------: |
|
| 423 |
+
| VRAM | 15,562 MB | 15,581MB | ~16,500MB |
|
| 424 |
+
| Influence | 6 tokens | all tokens | all tokens |
|
| 425 |
+
|
| 426 |
+
### Weight tying
|
| 427 |
+
|
| 428 |
+
Many causal LMs use **weight tying**, where two or more weights share the same underlying parameters. In the most common case, the input embedding weights (`embed_tokens`) and output projection weights (`lm_head`) share the same tensor. This is because it reduces parameters and usually preserves model quality.
|
| 429 |
+
|
| 430 |
+
It's not always obvious how PEFT deals with these tied weights when they are targeted for fine-tuning. For LoRA, the `ensure_weight_tying` on the [`LoraConfig`] controls whether PEFT should explicitly keep adapter-side updates tied for those layers. In practice, this can affect `modules_to_save`, `target_modules`, and `trainable_token_indices`. Note that this logic partially relies on convention when it comes to naming the layers (`"embed_tokens"`, `"lm_head"`) and proper working cannot be guaranteed if those conventions are not used.
|
| 431 |
+
|
| 432 |
+
The tables below summarize expected behavior.
|
| 433 |
+
|
| 434 |
+
#### `modules_to_save`
|
| 435 |
+
|
| 436 |
+
| Base model weights tied | `ensure_weight_tying` | `LoraConfig` shape | Behavior |
|
| 437 |
+
|-------------------------|-----------------------|-----------------------------------------------------|--------------------------------------------------------------|
|
| 438 |
+
| No | `False` | `modules_to_save=["embed_tokens"]` or `["lm_head"]` | Add `ModulesToSaveWrapper` on selected layer only |
|
| 439 |
+
| No | `True` | `modules_to_save=["embed_tokens"]` or `["lm_head"]` | Warn, then add `ModulesToSaveWrapper` on selected layer only |
|
| 440 |
+
| Yes | `False` | `modules_to_save=["embed_tokens"]` or `["lm_head"]` | Treat as separate |
|
| 441 |
+
| Yes | `True` | `modules_to_save=["embed_tokens"]` or `["lm_head"]` | Wrap tied layers and keep wrappers tied |
|
| 442 |
+
| No | `False` | `modules_to_save=["embed_tokens", "lm_head"]` | Treat as separate |
|
| 443 |
+
| No | `True` | `modules_to_save=["embed_tokens", "lm_head"]` | Warn, then treat as separate |
|
| 444 |
+
| Yes | `False` | `modules_to_save=["embed_tokens", "lm_head"]` | Warn, then treat as separate |
|
| 445 |
+
| Yes | `True` | `modules_to_save=["embed_tokens", "lm_head"]` | Keep `ModulesToSaveWrapper`s tied |
|
| 446 |
+
|
| 447 |
+
#### `target_modules`
|
| 448 |
+
|
| 449 |
+
| Base model weights tied | `ensure_weight_tying` | `LoraConfig` shape | Behavior |
|
| 450 |
+
|-------------------------|-----------------------|----------------------------------------------------|--------------------------------------------|
|
| 451 |
+
| No | `False` | `target_modules=["embed_tokens"]` or `["lm_head"]` | Add LoRA on selected layer only |
|
| 452 |
+
| No | `True` | `target_modules=["embed_tokens"]` or `["lm_head"]` | Warn, then add LoRA on selected layer only |
|
| 453 |
+
| Yes | `False` | `target_modules=["embed_tokens"]` or `["lm_head"]` | Treat as separate |
|
| 454 |
+
| Yes | `True` | `target_modules=["embed_tokens"]` or `["lm_head"]` | Keep LoRA adapters tied |
|
| 455 |
+
| No | `False` | `target_modules=["embed_tokens", "lm_head"]` | Treat as separate |
|
| 456 |
+
| No | `True` | `target_modules=["embed_tokens", "lm_head"]` | Warn, then treat as separate |
|
| 457 |
+
| Yes | `False` | `target_modules=["embed_tokens", "lm_head"]` | Warn, then treat as separate |
|
| 458 |
+
| Yes | `True` | `target_modules=["embed_tokens", "lm_head"]` | Keep LoRA adapters tied |
|
| 459 |
+
|
| 460 |
+
#### `trainable_token_indices`
|
| 461 |
+
|
| 462 |
+
For trainable tokens, we have the additional complication that even if the LM head and embeddings are tied, as a user I may want to fine-tune *different* tokens on them. In the example table below, we thus differentiate between fine-tuning the same and fine-tuning different tokens.
|
| 463 |
+
|
| 464 |
+
| Base model weights tied | `ensure_weight_tying` | `LoraConfig` shape | Behavior |
|
| 465 |
+
|-------------------------|-----------------------|-----------------------------------------------------------------------|------------------------------------------------|
|
| 466 |
+
| No | `False` | `trainable_token_indices=[1, 2, 3]` | Trainable tokens on embeddings only |
|
| 467 |
+
| No | `True` | `trainable_token_indices=[1, 2, 3]` | Warn, then trainable tokens on embeddings only |
|
| 468 |
+
| Yes | `False` | `trainable_token_indices=[1, 2, 3]` | Tied trainable tokens |
|
| 469 |
+
| Yes | `True` | `trainable_token_indices=[1, 2, 3]` | Tied trainable tokens |
|
| 470 |
+
| No | `False` | `trainable_token_indices={"lm_head": [1, 2], "embed_tokens": [1, 2]}` | Treat as separate |
|
| 471 |
+
| No | `True` | `trainable_token_indices={"lm_head": [1, 2], "embed_tokens": [1, 2]}` | Warn, then treat as separate |
|
| 472 |
+
| Yes | `False` | `trainable_token_indices={"lm_head": [1, 2], "embed_tokens": [1, 2]}` | Tied trainable tokens |
|
| 473 |
+
| Yes | `True` | `trainable_token_indices={"lm_head": [1, 2], "embed_tokens": [1, 2]}` | Tied trainable tokens |
|
| 474 |
+
| No | `False` | `trainable_token_indices={"lm_head": [1, 2], "embed_tokens": [3, 4]}` | Treat as separate |
|
| 475 |
+
| No | `True` | `trainable_token_indices={"lm_head": [1, 2], "embed_tokens": [3, 4]}` | Warn, then treat as separate |
|
| 476 |
+
| Yes | `False` | `trainable_token_indices={"lm_head": [1, 2], "embed_tokens": [3, 4]}` | Treat as separate |
|
| 477 |
+
| Yes | `True` | `trainable_token_indices={"lm_head": [1, 2], "embed_tokens": [3, 4]}` | Error |
|
| 478 |
+
|
| 479 |
+
For users, this means:
|
| 480 |
+
|
| 481 |
+
- In general, if you want to fine-tune weights that are tied and want to keep them tied, pass `ensure_weight_tying=True`.
|
| 482 |
+
- If your base model's weights are untied, `ensure_weight_tying=True` cannot force tying and only warns.
|
| 483 |
+
- For `trainable_token_indices`, tied layers must use the same token indices when `ensure_weight_tying=True`.
|
| 484 |
+
|
| 485 |
+
## Optimizers
|
| 486 |
+
|
| 487 |
+
LoRA training can optionally include special purpose optimizers. Currently PEFT supports LoRA-FA and LoRA+.
|
| 488 |
+
|
| 489 |
+
### LoRA-FA Optimizer
|
| 490 |
+
|
| 491 |
+
LoRA training can be more effective and efficient using LoRA-FA, as described in [LoRA-FA](https://huggingface.co/papers/2308.03303). LoRA-FA reduces activation memory consumption by fixing the matrix A and only tuning the matrix B. During training, the gradient of B is optimized to approximate the full parameter fine-tuning gradient. Moreover, the memory consumption of LoRA-FA is not sensitive to the rank (since it erases the activation of $A$), therefore it can improve performance by enlarging lora rank without increasing memory consumption.
|
| 492 |
+
|
| 493 |
+
```py
|
| 494 |
+
from peft import LoraConfig, get_peft_model
|
| 495 |
+
from peft.optimizers import create_lorafa_optimizer
|
| 496 |
+
from transformers import Trainer, get_cosine_schedule_with_warmup
|
| 497 |
+
|
| 498 |
+
base_model = AutoModelForCausalLM.from_pretrained("meta-llama/Meta-Llama-3-8B-Instruct")
|
| 499 |
+
|
| 500 |
+
config = LoraConfig(...)
|
| 501 |
+
model = get_peft_model(base_model, config)
|
| 502 |
+
|
| 503 |
+
optimizer = create_lorafa_optimizer(
|
| 504 |
+
model=model,
|
| 505 |
+
r=128,
|
| 506 |
+
lora_alpha=32,
|
| 507 |
+
lr=7e-5,
|
| 508 |
+
)
|
| 509 |
+
|
| 510 |
+
scheduler = get_cosine_schedule_with_warmup(
|
| 511 |
+
optimizer,
|
| 512 |
+
num_warmup_steps=100,
|
| 513 |
+
num_training_steps=1000,
|
| 514 |
+
)
|
| 515 |
+
|
| 516 |
+
trainer = Trainer(
|
| 517 |
+
...,
|
| 518 |
+
optimizers=(optimizer, scheduler),
|
| 519 |
+
)
|
| 520 |
+
```
|
| 521 |
+
|
| 522 |
+
### LoRA+ optimized LoRA
|
| 523 |
+
|
| 524 |
+
LoRA training can be optimized using [LoRA+](https://huggingface.co/papers/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%.
|
| 525 |
+
|
| 526 |
+
```py
|
| 527 |
+
from peft import LoraConfig, get_peft_model
|
| 528 |
+
from peft.optimizers import create_loraplus_optimizer
|
| 529 |
+
from transformers import Trainer
|
| 530 |
+
import bitsandbytes as bnb
|
| 531 |
+
|
| 532 |
+
base_model = ...
|
| 533 |
+
config = LoraConfig(...)
|
| 534 |
+
model = get_peft_model(base_model, config)
|
| 535 |
+
|
| 536 |
+
optimizer = create_loraplus_optimizer(
|
| 537 |
+
model=model,
|
| 538 |
+
optimizer_cls=bnb.optim.Adam8bit,
|
| 539 |
+
lr=5e-5,
|
| 540 |
+
loraplus_lr_ratio=16,
|
| 541 |
+
)
|
| 542 |
+
scheduler = None
|
| 543 |
+
|
| 544 |
+
...
|
| 545 |
+
trainer = Trainer(
|
| 546 |
+
...,
|
| 547 |
+
optimizers=(optimizer, scheduler),
|
| 548 |
+
)
|
| 549 |
+
```
|
| 550 |
+
|
| 551 |
+
|
| 552 |
+
## Post-Training
|
| 553 |
+
|
| 554 |
+
This section shows potential post-processing methods for trained adapters.
|
| 555 |
+
|
| 556 |
+
|
| 557 |
+
### Merge LoRA weights into the base model
|
| 558 |
+
|
| 559 |
+
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.
|
| 560 |
+
|
| 561 |
+
Below is a diagram that explains the intuition of LoRA adapter merging:
|
| 562 |
+
|
| 563 |
+
<div class="flex justify-center">
|
| 564 |
+
<img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/peft/lora_diagram.png"/>
|
| 565 |
+
</div>
|
| 566 |
+
|
| 567 |
+
We show in the snippets below how to run that using PEFT.
|
| 568 |
+
|
| 569 |
+
```py
|
| 570 |
+
from transformers import AutoModelForCausalLM
|
| 571 |
+
from peft import PeftModel
|
| 572 |
+
|
| 573 |
+
base_model = AutoModelForCausalLM.from_pretrained("mistralai/Mistral-7B-v0.1")
|
| 574 |
+
peft_model_id = "alignment-handbook/zephyr-7b-sft-lora"
|
| 575 |
+
model = PeftModel.from_pretrained(base_model, peft_model_id)
|
| 576 |
+
model = model.merge_and_unload()
|
| 577 |
+
```
|
| 578 |
+
|
| 579 |
+
It is important to assign the returned model to a variable and use it, [`~LoraModel.merge_and_unload`] is not an in-place operation. 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.
|
| 580 |
+
|
| 581 |
+
```py
|
| 582 |
+
from transformers import AutoModelForCausalLM
|
| 583 |
+
from peft import PeftModel
|
| 584 |
+
|
| 585 |
+
base_model = AutoModelForCausalLM.from_pretrained("mistralai/Mistral-7B-v0.1")
|
| 586 |
+
peft_model_id = "alignment-handbook/zephyr-7b-sft-lora"
|
| 587 |
+
model = PeftModel.from_pretrained(base_model, peft_model_id)
|
| 588 |
+
model.merge_adapter()
|
| 589 |
+
|
| 590 |
+
# unmerge the LoRA layers from the base model
|
| 591 |
+
model.unmerge_adapter()
|
| 592 |
+
```
|
| 593 |
+
|
| 594 |
+
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.
|
| 595 |
+
|
| 596 |
+
First load the base model:
|
| 597 |
+
|
| 598 |
+
```python
|
| 599 |
+
from transformers import AutoModelForCausalLM
|
| 600 |
+
from peft import PeftModel
|
| 601 |
+
import torch
|
| 602 |
+
|
| 603 |
+
base_model = AutoModelForCausalLM.from_pretrained(
|
| 604 |
+
"mistralai/Mistral-7B-v0.1", dtype=torch.float16, device_map="auto"
|
| 605 |
+
)
|
| 606 |
+
```
|
| 607 |
+
|
| 608 |
+
Then we load the first adapter:
|
| 609 |
+
|
| 610 |
+
```python
|
| 611 |
+
peft_model_id = "alignment-handbook/zephyr-7b-sft-lora"
|
| 612 |
+
model = PeftModel.from_pretrained(base_model, peft_model_id, adapter_name="sft")
|
| 613 |
+
```
|
| 614 |
+
|
| 615 |
+
Then load a different adapter and merge it with the first one:
|
| 616 |
+
|
| 617 |
+
```python
|
| 618 |
+
weighted_adapter_name = "sft-dpo"
|
| 619 |
+
model.load_adapter("alignment-handbook/zephyr-7b-dpo-lora", adapter_name="dpo")
|
| 620 |
+
model.add_weighted_adapter(
|
| 621 |
+
adapters=["sft", "dpo"],
|
| 622 |
+
weights=[0.7, 0.3],
|
| 623 |
+
adapter_name=weighted_adapter_name,
|
| 624 |
+
combination_type="linear"
|
| 625 |
+
)
|
| 626 |
+
model.set_adapter(weighted_adapter_name)
|
| 627 |
+
```
|
| 628 |
+
|
| 629 |
+
> [!TIP]
|
| 630 |
+
> 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.
|
| 631 |
+
|
| 632 |
+
Now, perform inference:
|
| 633 |
+
|
| 634 |
+
```python
|
| 635 |
+
device = torch.accelerator.current_accelerator().type if hasattr(torch, "accelerator") else "cuda"
|
| 636 |
+
|
| 637 |
+
tokenizer = AutoTokenizer.from_pretrained("mistralai/Mistral-7B-v0.1")
|
| 638 |
+
|
| 639 |
+
prompt = "Hey, are you conscious? Can you talk to me?"
|
| 640 |
+
inputs = tokenizer(prompt, return_tensors="pt")
|
| 641 |
+
inputs = {k: v.to(device) for k, v in inputs.items()}
|
| 642 |
+
|
| 643 |
+
with torch.no_grad():
|
| 644 |
+
generate_ids = model.generate(**inputs, max_length=30)
|
| 645 |
+
outputs = tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
|
| 646 |
+
print(outputs)
|
| 647 |
+
```
|
| 648 |
+
|
| 649 |
+
### Recovering base model performance via intruder dimension reduction
|
| 650 |
+
|
| 651 |
+
The paper [LoRA vs Full Fine-tuning: An Illusion of Equivalence](https://huggingface.co/papers/2410.21228) argues that LoRA training introduces extra dimensions into the weights that have very little in common with the already learnt weights and lead to forgetting of already learned information. PEFT implements the suggested mitigation in [`peft.tuners.lora.intruders.reduce_intruder_dimension`].
|
| 652 |
+
|
| 653 |
+
The mitigation will take a PEFT model with a loaded LoRA and create a new, modified adapter that is loaded alongside the existing adapter and now the active adapter.
|
| 654 |
+
|
| 655 |
+
Example usage:
|
| 656 |
+
|
| 657 |
+
```python
|
| 658 |
+
from peft.tuners.lora.intruders import reduce_intruder_dimension
|
| 659 |
+
|
| 660 |
+
peft_model = AutoPeftModelForCausalLM.from_pretrained('hubnemo/llama-3.2b-metamathqa-lora64')
|
| 661 |
+
|
| 662 |
+
reduce_intruder_dimension(
|
| 663 |
+
peft_model,
|
| 664 |
+
mitigation_lambda=0.75,
|
| 665 |
+
)
|
| 666 |
+
|
| 667 |
+
peft_model.generate(...)
|
| 668 |
+
```
|
| 669 |
+
|
| 670 |
+
There are a few hyper-parameters that can be used for tuning the effectiveness of the mitigation but, as evidenced in Figure 8 of the paper, it will always be a trade-off between task accuracy learned by the adapter and forgetting of the base model's knowledge. The mitigation will remove information from the adapter to reduce the impact on forgetting previous knowledge but this also means that some information about the task learned by the adapter is lost as well.
|
| 671 |
+
|
| 672 |
+
While the defaults are set to deliver a good trade-off between the two factors it is not guaranteed that the defaults will hold for your adapter, your model and your data, therefore it is wise to have a benchmark ready to measure the effect.
|
| 673 |
+
|
| 674 |
+
## Load adapters
|
| 675 |
+
|
| 676 |
+
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.
|
| 677 |
+
|
| 678 |
+
```py
|
| 679 |
+
from transformers import AutoModelForCausalLM
|
| 680 |
+
from peft import PeftModel
|
| 681 |
+
|
| 682 |
+
base_model = AutoModelForCausalLM.from_pretrained("mistralai/Mistral-7B-v0.1")
|
| 683 |
+
peft_model_id = "alignment-handbook/zephyr-7b-sft-lora"
|
| 684 |
+
model = PeftModel.from_pretrained(base_model, peft_model_id)
|
| 685 |
+
|
| 686 |
+
# load different adapter
|
| 687 |
+
model.load_adapter("alignment-handbook/zephyr-7b-dpo-lora", adapter_name="dpo")
|
| 688 |
+
|
| 689 |
+
# set adapter as active
|
| 690 |
+
model.set_adapter("dpo")
|
| 691 |
+
```
|
| 692 |
+
|
| 693 |
+
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. [`~LoraModel.unload`] is not an in-place operation, remember to assign the returned model to a variable and use it.
|
| 694 |
+
|
| 695 |
+
```py
|
| 696 |
+
# unload adapter
|
| 697 |
+
model = model.unload()
|
| 698 |
+
|
| 699 |
+
# delete adapter
|
| 700 |
+
model.delete_adapter("dpo")
|
| 701 |
+
```
|
| 702 |
+
|
| 703 |
+
## Tensor Parallelism
|
| 704 |
+
|
| 705 |
+
LoRA supports [Tensor Parallelism (TP)](https://huggingface.co/docs/transformers/main/en/perf_train_gpu_many#tensor-parallelism) as provided by Transformers. When a base model is loaded with a `tp_plan`, PEFT automatically detects the TP configuration of each target module and adds the appropriate hooks to the LoRA adapter weights so that they participate correctly in the tensor-parallel computation.
|
| 706 |
+
|
| 707 |
+
> [!WARNING]
|
| 708 |
+
> Tensor Parallelism support for LoRA requires `transformers >= 5.4.0`.
|
| 709 |
+
|
| 710 |
+
Usage is identical to the standard LoRA workflow — simply load the base model with a `tp_plan` before wrapping it with PEFT:
|
| 711 |
+
|
| 712 |
+
```py
|
| 713 |
+
from transformers import AutoModelForCausalLM
|
| 714 |
+
from peft import get_peft_model, LoraConfig
|
| 715 |
+
|
| 716 |
+
model = AutoModelForCausalLM.from_pretrained("meta-llama/Llama-3.1-8B", tp_plan="auto")
|
| 717 |
+
lora_config = LoraConfig(r=16, target_modules=["q_proj", "v_proj"])
|
| 718 |
+
model = get_peft_model(model, lora_config)
|
| 719 |
+
```
|
| 720 |
+
|
| 721 |
+
Saving and loading work as usual via `save_pretrained` / `from_pretrained`. PEFT gathers the sharded adapter weights back to full tensors before saving, so checkpoints are portable and independent of the number of devices used during training.
|
| 722 |
+
|
| 723 |
+
|
| 724 |
+
## Inference
|
| 725 |
+
|
| 726 |
+
This section showcases what you can do during inference time with LoRA, such as uncoupling the adapter.
|
| 727 |
+
|
| 728 |
+
### Activated LoRA (aLoRA)
|
| 729 |
+
|
| 730 |
+
Activated LoRA (aLoRA) is a low rank adapter architecture for causal LMs that reuses the existing base model KV cache for more efficient inference. This approach is best suited for inference pipelines which rely on the base model for most tasks/generations, but use aLoRA adapter(s) to perform specialized task(s) within the chain. For example, checking or correcting generated outputs of the base model. In these settings, inference times can be sped up by an order of magnitude or more. For more information on aLoRA and many example use cases, see the aLoRA [paper](https://huggingface.co/papers/2504.12397).
|
| 731 |
+
|
| 732 |
+
This technique scans for the last occurrence of an invocation sequence (`alora_invocation_tokens`) in each input (this can be as short as 1 token). It activates the adapter weights on tokens starting with the beginning of the invocation sequence. Any inputs after the invocation sequence are also adapted, and all generated tokens will use the adapted weights. Weights on prior tokens are left un-adapted, making the cache for those tokens interchangeable with base model cache due to the causal attention mask in causal LMs. Usage is very similar to standard LoRA. The key difference is that the invocation sequence must be specified when the adapter is created:
|
| 733 |
+
|
| 734 |
+
```py
|
| 735 |
+
from peft import LoraConfig
|
| 736 |
+
|
| 737 |
+
config = LoraConfig(alora_invocation_tokens=alora_invocation_tokens, task_type="CAUSAL_LM", ...)
|
| 738 |
+
```
|
| 739 |
+
|
| 740 |
+
alora_invocation_tokens` is a list of integer token ids. Given a desired invocation string, this can be obtained as:
|
| 741 |
+
```py
|
| 742 |
+
invocation_string = "placeholder"
|
| 743 |
+
alora_invocation_tokens = tokenizer.encode(invocation_string, add_special_tokens=False).
|
| 744 |
+
```
|
| 745 |
+
The tokenizer is the base model's tokenizer. Use `add_special_tokens=False` to avoid adding `SOS`/`EOS` tokens in our search string (which will most likely cause the search to fail).
|
| 746 |
+
|
| 747 |
+
**Notes**
|
| 748 |
+
* aLoRA is only supported for `task_type=CAUSAL_LM` tasks due to its focus on cache reuse.
|
| 749 |
+
* Since the weights are adapted on fewer tokens, often (not always) aLoRA requires higher rank (`r`) than LoRA. `r=32` can be a good starting point.
|
| 750 |
+
* aLoRA weights cannot be merged into the base model by definition, since the adapter weights are selectively applied to a subset of tokens. Attempts to merge will throw errors.
|
| 751 |
+
* Beam search is not yet supported.
|
| 752 |
+
* It is generally not recommended to add new tokens to the tokenizer that are not present in the base model. This can complicate the target use case of both the base model and adapter model operating on overlapping context. You can workaround this by adding [trainable tokens](../package_reference/trainable_tokens) to the base model prior to training the adapter.
|
| 753 |
+
|
| 754 |
+
#### Choice of invocation sequence and SFT design
|
| 755 |
+
|
| 756 |
+
You must add the `alora_invocation_tokens` sequence because it is not added automatically. We recommend activating the adapter weights early (at the start of any adapter-specific prompting), but after any long inputs, to maximize model performance without compromising cache reuse. As with any model,
|
| 757 |
+
formatting should be consistent between train and test.
|
| 758 |
+
|
| 759 |
+
Consider the following example, where the base model has a chat template,
|
| 760 |
+
and the goal is to train the adapter to generate a desired output.
|
| 761 |
+
|
| 762 |
+
* Option 1: If there is no task-specific prompt, i.e. the input is a chat history with the `assistant` prompt, then the chat template's `assistant` prompt (e.g. `<|start_of_role|>assistant<|end_of_role|>`) is a natural choice for the invocation string. See the model's chat template to find the prompt for the model.
|
| 763 |
+
* Option 2: If there is a task-specific prompt for the adapter that describes the task the adapter is learning, and that prompt is put as a `user` turn immediately prior to the generation, then the chat template's `user` prompt (e.g. `<|start_of_role|>user<|end_of_role|>`) is a natural choice for the invocation string.
|
| 764 |
+
|
| 765 |
+
After deciding on an invocation string, get the model tokenizer and obtain `alora_invocation_tokens` as
|
| 766 |
+
```py
|
| 767 |
+
alora_invocation_tokens = tokenizer.encode(invocation_string, add_special_tokens=False).
|
| 768 |
+
```
|
| 769 |
+
|
| 770 |
+
An example inference setup is at [alora finetuning](https://github.com/huggingface/peft/blob/main/examples/alora_finetuning/alora_finetuning.py).
|
| 771 |
+
|
| 772 |
+
> [!NOTE]
|
| 773 |
+
> If using custom strings for the invocation string, make sure that the start and end of the string are special tokens to avoid issues with tokenization at the boundaries.
|
| 774 |
+
|
| 775 |
+
To see why, imagine that 'a', 'b', 'c', and 'ab' are tokens in your tokenizer (numbers 1, 2, 3, 4 respectively). Suppose that your alora_invocation_tokens = [2, 3]. Now imagine your input string is "abc". Because "ab" is a token, this will get tokenized as [4,3]. So the alora_invocation_tokens will fail to be found, despite the string "bc" being in it. If the start and end of the invocation string are special tokens, however, this failure case will never happen since special tokens are never tokenized into the same token with other characters.
|
| 776 |
+
|
| 777 |
+
#### Using (and reusing) cache for generation
|
| 778 |
+
The main purpose of aLoRA is to make KV cache interchangeable between the base model and aLoRA adapter models **prior to the invocation sequence** since base and adapted KV values are not compatible. Specifically, keys and values stored during one model generation can be used in subsequent generations to avoid expensive prefill operations for context tokens. When sharing cache between the base model and aLoRA adapters, there are 2 main patterns:
|
| 779 |
+
1. The base model has generated something, and an aLoRA adapter is then called to do a follow-up generation. For example, the base model answers a question, and an aLoRA trained to detect hallucinations checks the base model response.
|
| 780 |
+
2. An aLoRA adapter has generated something, and the base model or a different aLoRA adapter is called to do a follow-up generation where there is partial context overlap with the original aLoRA. For example, the user provides a query, and an aLoRA rewrites the query to be more self-contained and improve retrieval in a RAG system. Then, documents are retrieved and loaded into context, aLoRA checks if these documents are relevant to the question, and then the base model generates an answer.
|
| 781 |
+
|
| 782 |
+
|
| 783 |
+
To demonstrate the above behaviors when using caching, we're using [DynamicCache](https://huggingface.co/docs/transformers/en/kv_cache) from `transformers`. Take care to ensure that adapted cache values are not mixed with base cache values. In particular, an extra step is required for sharing the cache when there is partial context overlap (pattern 2).
|
| 784 |
+
|
| 785 |
+
**Pattern 1: Base model followed by aLoRA** Here, the entire input and generation from the base model is input into the aLoRA adapter, along with the invocation sequence:
|
| 786 |
+
```
|
| 787 |
+
from transformers import DynamicCache
|
| 788 |
+
...
|
| 789 |
+
cache = DynamicCache()
|
| 790 |
+
inputs_base = tokenizer(prompt_base, return_tensors="pt")
|
| 791 |
+
# Generate from base model and save cache
|
| 792 |
+
with model_alora.disable_adapter():
|
| 793 |
+
output = model_alora.generate(inputs_base["input_ids"].to(device),attention_mask=inputs_base["attention_mask"].to(device),past_key_values = cache,return_dict_in_generate=True)
|
| 794 |
+
output_text_base = tokenizer.decode(output.sequences[0])
|
| 795 |
+
cache = output.past_key_values
|
| 796 |
+
|
| 797 |
+
# Generate with aLoRA adapter from cache
|
| 798 |
+
prompt_alora = output_text + INVOCATION_STRING
|
| 799 |
+
inputs_alora = tokenizer(prompt_alora, return_tensors="pt").to(device)
|
| 800 |
+
output = model_alora.generate(**inputs_alora, past_key_values=cache)
|
| 801 |
+
output_text_alora = tokenizer.decode(output[0])
|
| 802 |
+
|
| 803 |
+
# Note: cache is now tainted with adapter values and cannot be used in base model from here on!
|
| 804 |
+
```
|
| 805 |
+
|
| 806 |
+
**Pattern 2: aLoRA generation followed by base model (or another aLoRA) with partial context overlap** Here, we prefill the shared context using the base model, and then generate.
|
| 807 |
+
|
| 808 |
+
```
|
| 809 |
+
from transformers import DynamicCache
|
| 810 |
+
import copy
|
| 811 |
+
...
|
| 812 |
+
cache = DynamicCache()
|
| 813 |
+
inputs_shared = tokenizer(prompt_shared, return_tensors="pt").to(device)
|
| 814 |
+
|
| 815 |
+
# Prefill from base model and save cache
|
| 816 |
+
with model_alora.disable_adapter():
|
| 817 |
+
with torch.no_grad():
|
| 818 |
+
model_alora(**inputs_shared, past_key_values=cache)
|
| 819 |
+
cache_copy = copy.deepcopy(cache)
|
| 820 |
+
|
| 821 |
+
# Generate from aLoRA using prefilled cache
|
| 822 |
+
prompt_alora = prompt_shared + INVOCATION_STRING
|
| 823 |
+
inputs_alora = tokenizer(prompt_alora, return_tensors="pt").to(device)
|
| 824 |
+
output = model_alora.generate(**inputs_alora, past_key_values=cache)
|
| 825 |
+
output_text_alora = tokenizer.decode(output[0])
|
| 826 |
+
|
| 827 |
+
# Generate from base model using saved cache not tainted by aLoRA KV values
|
| 828 |
+
prompt_base = prompt_shared
|
| 829 |
+
inputs_base = tokenizer(prompt_base, return_tensors="pt").to(device)
|
| 830 |
+
with model_alora.disable_adapter():
|
| 831 |
+
output = model_alora.generate(**inputs_base, past_key_values=cache_copy)
|
| 832 |
+
output_text_base = tokenizer.decode(output[0])
|
| 833 |
+
```
|
| 834 |
+
|
| 835 |
+
|
| 836 |
+
### Inference with different LoRA adapters in the same batch
|
| 837 |
+
|
| 838 |
+
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.
|
| 839 |
+
|
| 840 |
+
Thankfully, it is possible to mix different LoRA adapters in the same batch using the `adapter_name` argument. Below, we show an example of how this works in practice. First, let's load the base model, English, and the two adapters, French and German, like this:
|
| 841 |
+
|
| 842 |
+
```python
|
| 843 |
+
from transformers import AutoTokenizer, AutoModelForCausalLM
|
| 844 |
+
from peft import PeftModel
|
| 845 |
+
|
| 846 |
+
model_id = ...
|
| 847 |
+
tokenizer = AutoTokenizer.from_pretrained(model_id)
|
| 848 |
+
|
| 849 |
+
model = AutoModelForCausalLM.from_pretrained(model_id)
|
| 850 |
+
# load the LoRA adapter for French
|
| 851 |
+
peft_model = PeftModel.from_pretrained(model, <path>, adapter_name="adapter_fr")
|
| 852 |
+
# next, load the LoRA adapter for German
|
| 853 |
+
peft_model.load_adapter(<path>, adapter_name="adapter_de")
|
| 854 |
+
```
|
| 855 |
+
|
| 856 |
+
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.
|
| 857 |
+
|
| 858 |
+
```python
|
| 859 |
+
inputs = tokenizer(
|
| 860 |
+
[
|
| 861 |
+
"Hello, my dog is cute",
|
| 862 |
+
"Hello, my cat is awesome",
|
| 863 |
+
"Hello, my fish is great",
|
| 864 |
+
"Salut, mon chien est mignon",
|
| 865 |
+
"Salut, mon chat est génial",
|
| 866 |
+
"Salut, mon poisson est super",
|
| 867 |
+
"Hallo, mein Hund ist süß",
|
| 868 |
+
"Hallo, meine Katze ist toll",
|
| 869 |
+
"Hallo, mein Fisch ist großartig",
|
| 870 |
+
],
|
| 871 |
+
return_tensors="pt",
|
| 872 |
+
padding=True,
|
| 873 |
+
)
|
| 874 |
+
|
| 875 |
+
adapter_names = [
|
| 876 |
+
"__base__", "__base__", "__base__",
|
| 877 |
+
"adapter_fr", "adapter_fr", "adapter_fr",
|
| 878 |
+
"adapter_de", "adapter_de", "adapter_de",
|
| 879 |
+
]
|
| 880 |
+
output = peft_model.generate(**inputs, adapter_names=adapter_names, max_new_tokens=20)
|
| 881 |
+
```
|
| 882 |
+
|
| 883 |
+
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.
|
| 884 |
+
|
| 885 |
+
Additionally, the same approach also works with the `modules_to_save` feature, which allows for saving and reusing specific neural network layers, such as custom heads for classification tasks, across different LoRA adapters.
|
| 886 |
+
|
| 887 |
+
#### Caveats
|
| 888 |
+
|
| 889 |
+
Using this feature has some drawbacks, namely:
|
| 890 |
+
|
| 891 |
+
- It only works for inference, not for training.
|
| 892 |
+
- Disabling adapters using the `with model.disable_adapter()` context takes precedence over `adapter_names`.
|
| 893 |
+
- You cannot pass `adapter_names` when some adapter weights were merged with base weight using the `merge_adapter` method. Please unmerge all adapters first by calling `model.unmerge_adapter()`.
|
| 894 |
+
- 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.
|
| 895 |
+
- This feature does not currently work with DoRA, so set `use_dora=False` in your `LoraConfig` if you want to use it.
|
| 896 |
+
- The `modules_to_save` feature is currently only supported for the layers of types `Linear`, `Embedding`, `Conv2d` and `Conv1d`.
|
| 897 |
+
- 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:
|
| 898 |
+
- Increase the batch size.
|
| 899 |
+
- 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 handful of different adapters.
|
| 900 |
+
- 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.
|
| 901 |
+
|
| 902 |
+
|
| 903 |
+
### Composing and Reusing LoRA Adapters
|
| 904 |
+
#### Arrow
|
| 905 |
+
[Arrow](https://huggingface.co/papers/2405.11157) is a modular routing algorithm designed to combine multiple pre-trained task-specific LoRA adapters to solve a given task, similar to [Polytropon](poly) but without the need for fine-tuning. Rather than merging all adapters naively, Arrow introduces a **gradient-free, token-wise mixture-of-experts (MoE) routing mechanism**. At inference time, it first computes a _prototype_ for each LoRA by extracting the top right singular vector from its SVD decomposition. Each token representation is then compared to these prototypes via cosine similarity to obtain routing coefficients. Tokens are assigned to the top-k most relevant LoRA adapters, with the coefficients normalized through softmax, and their outputs linearly combined. This allows effective reuse of existing LoRA modules for new tasks and leads to stronger zero-shot generalization.
|
| 906 |
+
|
| 907 |
+
In PEFT, Arrow is enabled through [`ArrowConfig]` and `create_arrow_model`. You can also configure parameters such as `top_k` (the number of LoRA adapters combined per token), `router_temperature` (the softmax temperature applied to the routing coefficients), and `rng_seed` (for reproducibility).
|
| 908 |
+
|
| 909 |
+
```py
|
| 910 |
+
from peft import create_arrow_model, ArrowConfig
|
| 911 |
+
from transformers import AutoModelForCausalLM
|
| 912 |
+
|
| 913 |
+
# Loading the model
|
| 914 |
+
base_model = AutoModelForCausalLM.from_pretrained("microsoft/Phi-3-mini-4k-instruct")
|
| 915 |
+
|
| 916 |
+
# Creating the Arrow config
|
| 917 |
+
arrow_config = ArrowConfig(
|
| 918 |
+
top_k=3,
|
| 919 |
+
router_temperature=1.0,
|
| 920 |
+
rng_seed=42,
|
| 921 |
+
)
|
| 922 |
+
|
| 923 |
+
# The LoRA adapters below were trained on a clustered FLAN dataset.
|
| 924 |
+
# Task clustering was performed using the Model-Based Clustering (MBC) method,
|
| 925 |
+
# as described in the Arrow paper.
|
| 926 |
+
# While one could train a separate LoRA for each task and let Arrow route tokens among them,
|
| 927 |
+
# training LoRAs on clusters of tasks instead provides an indirect optimization for
|
| 928 |
+
# transfer across the multi-task dataset.
|
| 929 |
+
task_specific_adapter_paths = [
|
| 930 |
+
f"TahaBa/phi3-mini-clustered-flan/ts_expert_{i}" for i in range(10)
|
| 931 |
+
]
|
| 932 |
+
|
| 933 |
+
# Creating the Arrow model
|
| 934 |
+
model = create_arrow_model(
|
| 935 |
+
base_model=base_model,
|
| 936 |
+
task_specific_adapter_paths=task_specific_adapter_paths,
|
| 937 |
+
arrow_config=arrow_config,
|
| 938 |
+
)
|
| 939 |
+
|
| 940 |
+
# Now the forward path could be called on this model, like a normal PeftModel.
|
| 941 |
+
```
|
| 942 |
+
|
| 943 |
+
Furthermore, you can add or remove adapters after calling ```create_arrow_model```—for example, to fine-tune a new adapter or discard an unnecessary one. Once the adapters are in place, you can activate the ```"arrow_router"``` for inference to use Arrow. Note that if you add a new LoRA adapter after ```create_arrow_model``` and want to fine-tune it, you must explicitly set the new adapter as active, since ```"arrow_router"``` is activated by default in ```create_arrow_model```.
|
| 944 |
+
|
| 945 |
+
```py
|
| 946 |
+
from trl import SFTTrainer, SFTConfig
|
| 947 |
+
|
| 948 |
+
# Adding a new adapter and activating it
|
| 949 |
+
model.add_adapter(adapter_name='new_adapter')
|
| 950 |
+
model.set_adapter('new_adapter')
|
| 951 |
+
|
| 952 |
+
# Now the model could be trained along the `new_adapter`.
|
| 953 |
+
trainer = SFTTrainer(
|
| 954 |
+
model=model,
|
| 955 |
+
args=SFTConfig(...),
|
| 956 |
+
...
|
| 957 |
+
)
|
| 958 |
+
|
| 959 |
+
# Once the training is done, you can activate `arrow_router` and use it in inference
|
| 960 |
+
model.set_adapter('arrow_router') # Model is ready to be used at inference time now
|
| 961 |
+
```
|
| 962 |
+
|
| 963 |
+
#### GenKnowSub
|
| 964 |
+
[GenKnowSub](https://aclanthology.org/2025.acl-short.54/) augments Arrow by purifying task-specific LoRA adapters before routing. The key idea is to subtract general knowledge encoded in LoRA space—based on the [forgetting-via-negation principle](https://huggingface.co/papers/2212.04089)—so that task adapters become more isolated and focused on task-relevant signals. Concretely, GenKnowSub estimates a low-dimensional “general” subspace from a set of general (non task-specific) LoRA adapters and removes this component from each task adapter’s LoRA update prior to Arrow’s token-wise routing. This typically improves compositionality and reduces interference when combining many task adapters.
|
| 965 |
+
|
| 966 |
+
In PEFT, enable GenKnowSub by setting ```use_gks=True``` in ArrowConfig, and providing ```general_adapter_paths``` in ```create_arrow_model```:
|
| 967 |
+
|
| 968 |
+
```py
|
| 969 |
+
from peft import create_arrow_model, ArrowConfig
|
| 970 |
+
from transformers import AutoModelForCausalLM
|
| 971 |
+
|
| 972 |
+
# Loading the model
|
| 973 |
+
base_model = AutoModelForCausalLM.from_pretrained("microsoft/Phi-3-mini-4k-instruct")
|
| 974 |
+
|
| 975 |
+
# Creating the Arrow config
|
| 976 |
+
arrow_config = ArrowConfig(
|
| 977 |
+
top_k=3,
|
| 978 |
+
router_temperature=1.0,
|
| 979 |
+
use_gks=True,
|
| 980 |
+
rng_seed=42,
|
| 981 |
+
)
|
| 982 |
+
|
| 983 |
+
# Path to task-specific, trained on flan clustered dataset (as we explained before.)
|
| 984 |
+
task_specific_adapter_paths = [
|
| 985 |
+
f"TahaBa/phi3-mini-clustered-flan/ts_expert_{i}" for i in range(10)
|
| 986 |
+
]
|
| 987 |
+
# These general adapters are trained on English, German, and French Wikipedia dataset,
|
| 988 |
+
# with causal language modelling objective, each pair like: (507 token tsentence, 5 token completion), and the loss computed on the completion
|
| 989 |
+
general_adapter_paths = [
|
| 990 |
+
"TahaBa/phi3-mini-general-adapters/cluster0_batch16_prop1.0_langen/checkpoint-17",
|
| 991 |
+
"TahaBa/phi3-mini-general-adapters/cluster0_batch16_prop1.0_langfr/checkpoint-35",
|
| 992 |
+
"TahaBa/phi3-mini-general-adapters/cluster0_batch16_prop1.0_langger/checkpoint-17"
|
| 993 |
+
]
|
| 994 |
+
|
| 995 |
+
# Creating the Arrow model
|
| 996 |
+
model = create_arrow_model(
|
| 997 |
+
base_model=base_model,
|
| 998 |
+
task_specific_adapter_paths=task_specific_adapter_paths,
|
| 999 |
+
general_adapter_paths=general_adapter_paths,
|
| 1000 |
+
arrow_config=arrow_config,
|
| 1001 |
+
)
|
| 1002 |
+
|
| 1003 |
+
# Now the forward path could be called on this model, like a normal PeftModel.
|
| 1004 |
+
```
|
| 1005 |
+
To encode general knowledge, GenKnowSub subtracts the average of the provided general adapters from each task-specific adapter once, before routing begins. Furthermore, the ability to add or remove adapters after calling ```create_arrow_model``` (as described in the Arrow section) is still supported in this case.
|
| 1006 |
+
|
| 1007 |
+
> [!TIP]
|
| 1008 |
+
> **Things to keep in mind when using Arrow + GenKnowSub:**
|
| 1009 |
+
>
|
| 1010 |
+
> - All LoRA adapters (task-specific and general) must share the same ```rank``` and ```target_modules```.
|
| 1011 |
+
>
|
| 1012 |
+
> - Any inconsistency in these settings will raise an error in ```create_arrow_model```.
|
| 1013 |
+
>
|
| 1014 |
+
> - Having different scaling factors (```lora_alpha```) across task adapters is supported — Arrow handles them automatically.
|
| 1015 |
+
>
|
| 1016 |
+
> - Merging the ```"arrow_router"``` is not supported, due to its dynamic routing behavior.
|
| 1017 |
+
>
|
| 1018 |
+
> - In create_arrow_model, task adapters are loaded as ```task_i``` and general adapters as ```gks_j``` (where ```i``` and ```j``` are indices). The function ensures consistency of ```target_modules```, ```rank```, and whether adapters are applied to ```Linear``` or ```Linear4bit``` layers. It then adds the ```"arrow_router"``` module and activates it. Any customization of this process requires overriding ```create_arrow_model```.
|
| 1019 |
+
>
|
| 1020 |
+
> - This implementation is compatible with 4-bit quantization (via bitsandbytes):
|
| 1021 |
+
>
|
| 1022 |
+
> ```py
|
| 1023 |
+
> from transformers import AutoModelForCausalLM, BitsAndBytesConfig
|
| 1024 |
+
> import torch
|
| 1025 |
+
>
|
| 1026 |
+
> # Quantisation config
|
| 1027 |
+
> bnb_config = BitsAndBytesConfig(
|
| 1028 |
+
> load_in_4bit=True,
|
| 1029 |
+
> bnb_4bit_quant_type="nf4",
|
| 1030 |
+
> bnb_4bit_compute_dtype=torch.bfloat16,
|
| 1031 |
+
> bnb_4bit_use_double_quant=False,
|
| 1032 |
+
> )
|
| 1033 |
+
>
|
| 1034 |
+
> # Loading the model
|
| 1035 |
+
> base_model = AutoModelForCausalLM.from_pretrained(
|
| 1036 |
+
> "microsoft/Phi-3-mini-4k-instruct",
|
| 1037 |
+
> dtype=torch.bfloat16,
|
| 1038 |
+
> device_map="auto",
|
| 1039 |
+
> quantization_config=bnb_config,
|
| 1040 |
+
> )
|
| 1041 |
+
>
|
| 1042 |
+
> # Now call create_arrow_model() as we explained before.
|
| 1043 |
+
> ```
|
| 1044 |
+
|
| 1045 |
+
# API
|
| 1046 |
+
|
| 1047 |
+
## LoraConfig
|
| 1048 |
+
|
| 1049 |
+
[[autodoc]] tuners.lora.config.LoraConfig
|
| 1050 |
+
|
| 1051 |
+
## LoraModel
|
| 1052 |
+
|
| 1053 |
+
[[autodoc]] tuners.lora.model.LoraModel
|
| 1054 |
+
|
| 1055 |
+
|
| 1056 |
+
## Utility
|
| 1057 |
+
|
| 1058 |
+
### ArrowConfig
|
| 1059 |
+
|
| 1060 |
+
[[autodoc]] tuners.lora.config.ArrowConfig
|
| 1061 |
+
|
| 1062 |
+
### LoftQ
|
| 1063 |
+
|
| 1064 |
+
[[autodoc]] utils.loftq_utils.replace_lora_weights_loftq
|
| 1065 |
+
|
| 1066 |
+
|
| 1067 |
+
### Eva
|
| 1068 |
+
|
| 1069 |
+
#### EvaConfig
|
| 1070 |
+
|
| 1071 |
+
[[autodoc]] tuners.lora.config.EvaConfig
|
| 1072 |
+
|
| 1073 |
+
#### initialize_lora_eva_weights
|
| 1074 |
+
|
| 1075 |
+
[[autodoc]] tuners.lora.eva.initialize_lora_eva_weights
|
| 1076 |
+
|
| 1077 |
+
#### get_eva_state_dict
|
| 1078 |
+
|
| 1079 |
+
[[autodoc]] tuners.lora.eva.get_eva_state_dict
|
| 1080 |
+
|
| 1081 |
+
|
| 1082 |
+
### LoraGAConfig
|
| 1083 |
+
|
| 1084 |
+
[[autodoc]] tuners.lora.config.LoraGAConfig
|
| 1085 |
+
|
| 1086 |
+
#### Utilities
|
| 1087 |
+
|
| 1088 |
+
[[autodoc]] tuners.lora.loraga.estimate_gradients
|
| 1089 |
+
|
| 1090 |
+
[[autodoc]] tuners.lora.loraga.preprocess_loraga
|
| 1091 |
+
|
| 1092 |
+
|
| 1093 |
+
## Intruder Dimension Reduction
|
| 1094 |
+
|
| 1095 |
+
[[autodoc]] tuners.lora.intruders.reduce_intruder_dimension
|
| 1096 |
+
|
| 1097 |
+
|
tasks/tasksmith-0d2d1e298e86/tests/source/docs/source/package_reference/lora_conversion.md
ADDED
|
@@ -0,0 +1,155 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!--⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be
|
| 2 |
+
rendered properly in your Markdown viewer.
|
| 3 |
+
-->
|
| 4 |
+
|
| 5 |
+
# LoRA conversion
|
| 6 |
+
|
| 7 |
+
Functions that allow to convert non-LoRA PEFT models to LoRA models.
|
| 8 |
+
|
| 9 |
+
## Description
|
| 10 |
+
|
| 11 |
+
PEFT supports dozens of different parameter effficient fine-tuning techniques. The most popular one by far is LoRA. This means that many other packages support LoRA too. For example, [Diffusers](https://huggingface.co/docs/diffusers/main/en/api/loaders/lora) allows to load LoRA adapters to change the capabilities of diffusion models. [vLLM](https://docs.vllm.ai/en/stable/features/lora/) allows serving models with LoRA adapters. This is nice but unfortunately, all the other, non-LoRA PEFT methods are rarely supported. Therefore, even if another PEFT method would work better for your specific use case, you may be prevented from using it because downstream packages offer no support.
|
| 12 |
+
|
| 13 |
+
Here we present a potential solution. PEFT offers two functions, [`save_as_lora`] and [`convert_to_lora`], which allow to convert a PEFT adapter into a LoRA adapter. Not all PEFT methods support this for now, but if they do, it means you can start with the PEFT method that works best for you and then later use it as if it were a LoRA adapter.
|
| 14 |
+
|
| 15 |
+
## Example
|
| 16 |
+
|
| 17 |
+
The LoRA rank for the converted adapter can either be set to a fixed rank by passing an int > 0 to the `rank` argument, or a dynamic rank, which adapts to each layer, by passing a float between 0 and 1 to the `rank` argument. Dynamic ranks can potentially be more efficient (same performance with fewer parameters).
|
| 18 |
+
|
| 19 |
+
### Fixed LoRA rank
|
| 20 |
+
|
| 21 |
+
The usage of [`save_as_lora`] is relatively straightforward:
|
| 22 |
+
|
| 23 |
+
```python
|
| 24 |
+
from peft import get_peft_model, save_as_lora
|
| 25 |
+
|
| 26 |
+
# first load and train your non-LoRA PEFT model as normal
|
| 27 |
+
base_model = ...
|
| 28 |
+
non_lora_config = ...
|
| 29 |
+
model = get_peft_model(base_model, non_lora_config)
|
| 30 |
+
# check that this PEFT method can indeed be converted to LoRA
|
| 31 |
+
assert model.supports_lora_conversion()
|
| 32 |
+
... # train the model
|
| 33 |
+
|
| 34 |
+
# the rank of the LoRA adapter that you want to convert to
|
| 35 |
+
target_rank = 64
|
| 36 |
+
# save as a LoRA checkpoint
|
| 37 |
+
save_as_lora(output_path, model, rank=target_rank)
|
| 38 |
+
```
|
| 39 |
+
|
| 40 |
+
This will create a LoRA checkpoint at `output_path` that you can load like any other LoRA adapter, or use in downstream packages such as Diffusers or vLLM.
|
| 41 |
+
|
| 42 |
+
The [`convert_to_lora`] function is useful if you don't want to save the converted LoRA adapter but instead want to use the converted weights right away, for example to perform evaluations:
|
| 43 |
+
|
| 44 |
+
```python
|
| 45 |
+
from peft import convert_to_lora, get_peft_model, set_peft_model_state_dict
|
| 46 |
+
|
| 47 |
+
base_model = ...
|
| 48 |
+
non_lora_config = ...
|
| 49 |
+
model = get_peft_model(base_model, non_lora_config)
|
| 50 |
+
... # train the model
|
| 51 |
+
|
| 52 |
+
# get the lora config and state dict of the converted lora model
|
| 53 |
+
lora_config, lora_state_dict = convert_to_lora(model, rank=target_rank)
|
| 54 |
+
# reload the base model, or use model.unload()
|
| 55 |
+
base_model = ...
|
| 56 |
+
# apply the lora config to the base model
|
| 57 |
+
lora_model = get_peft_model(base_model, lora_config)
|
| 58 |
+
# load the LoRA weights onto the base model
|
| 59 |
+
set_peft_model_state_dict(lora_model, state_dict)
|
| 60 |
+
```
|
| 61 |
+
|
| 62 |
+
### Dynamic LoRA rank
|
| 63 |
+
|
| 64 |
+
In the examples above, we used a fixed LoRA rank for conversion. However, it is conceivable that some layers don't require a high rank to be accurately converted, while other layers require a higher rank. To accommodate this, PEFT offers the option to pass a float between 0 and 1 as the `rank` argument. Let's say you pass `rank=0.5`. This means that for each layer, the rank for the LoRA adapter is chosen such that the LoRA adapter explains 50% of the variance in weight introduced by original adapter. In more technical terms, under the hood we perform a [Singular Value Decomposition](https://en.wikipedia.org/wiki/Singular_value_decomposition) on the weight contribution of the adapter and then take the top singular values that, when normalized, sum up to the passed value.
|
| 65 |
+
|
| 66 |
+
```python
|
| 67 |
+
# set a dynamic rank by passing a float
|
| 68 |
+
threshold = 0.7
|
| 69 |
+
# save as a LoRA checkpoint
|
| 70 |
+
save_as_lora(output_path, model, rank=threshold)
|
| 71 |
+
# get the lora config and state dict directly:
|
| 72 |
+
lora_config, lora_state_dict = convert_to_lora(model, rank=threshold)
|
| 73 |
+
# inspect the different ranks per layer:
|
| 74 |
+
print(lora_config.rank_pattern)
|
| 75 |
+
```
|
| 76 |
+
|
| 77 |
+
Using this type of dynamic LoRA rank can be useful if the contribution of the different layers varies a lot. The disadvantage is that it could mean that some layers will have a very high LoRA rank, which can lead to memory spikes. Please test what works best for your use case.
|
| 78 |
+
|
| 79 |
+
### Compiling the model
|
| 80 |
+
|
| 81 |
+
For large models, doing the conversion may take some time; for instance each PEFT module has to go through an SVD computation. By passing `compile_kwargs` to [`save_as_lora`] or [`convert_to_lora`], you can apply [`torch.compile`](https://docs.pytorch.org/docs/stable/generated/torch.compile.html) to the conversion function and potentially speed up the process. The `compile_kwargs` are a dict of keyword arguments that are passed to `torch.compile` (empty dict also works). Below is an example:
|
| 82 |
+
|
| 83 |
+
```python
|
| 84 |
+
compile_kwargs = {"dynamic": True, "mode": "max-autotune-no-cudagraphs", "fullgraph": True}
|
| 85 |
+
save_as_lora(output_path, model, rank=rank, compile_kwargs=compile_kwargs)
|
| 86 |
+
```
|
| 87 |
+
|
| 88 |
+
### LoRA to LoRA conversion
|
| 89 |
+
|
| 90 |
+
It is also possible to convert a LoRA adapter into another LoRA adapter. Why would you want to do that? There is one reason, namely if you want to reduce the rank of the LoRA adapter. If, after training, you want to shrink the LoRA adapter, use [`save_as_lora`] or [`convert_to_lora`] and pass a smaller rank. This will give you a new LoRA adapter that has a smaller memory and storage footprint.
|
| 91 |
+
|
| 92 |
+
## Metrics
|
| 93 |
+
|
| 94 |
+
### Non-LoRA to LoRA conversion
|
| 95 |
+
|
| 96 |
+
Of course, converting one PEFT adapter into another adapter is a lossy process. The new adapter will most likely not perform as well as the initial adapter. Therefore, it is highly advised to **evaluate the converted LoRA adapter**. This way, you can make sure that the converted adapter performs well enough for your use case. The general rule applies that the higher the rank of the LoRA adapter, the better it will approximate your initial adapter. This means that the converted LoRA adapter may require more parameters than the original adapter to achieve a similar performanace.
|
| 97 |
+
|
| 98 |
+
To give an example, here are some numbers that were derived on the [PEFT MetaMathQA benchmark](https://github.com/huggingface/peft/tree/main/method_comparison/MetaMathQA). For this, a [LoHa](https://huggingface.co/docs/peft/package_reference/loha) adapter was used to fine-tune `meta-llama/Llama-3.2-3B` on MetaMathQA and evaluated on GSM8K. The initial LoKr adapter had rank 32, resulting in 18,350,080 trainable parameters and a test accuracy of 41.85%. Evaluation required 12.25 GB of memory. The checkpoint was converted into LoRA with different values for the `rank`. The resulting outcome is:
|
| 99 |
+
|
| 100 |
+
| rank | trainable parameters | test accuracy (%) | accuracy change | memory reserved (max, GB) | memory increase |
|
| 101 |
+
|------|---------------------:|------------------:|----------------:|--------------------------:|----------------:|
|
| 102 |
+
| 8 | 2293760 | 37.60 | -4.25 | 12.41 | 0.16 |
|
| 103 |
+
| 16 | 4587520 | 38.89 | -2.96 | 12.15 | -0.10 |
|
| 104 |
+
| 32 | 9175040 | 40.11 | -1.74 | 12.41 | 0.16 |
|
| 105 |
+
| 64 | 18350080 | 39.20 | -2.65 | 12.18 | -0.07 |
|
| 106 |
+
| | | | | | |
|
| 107 |
+
| 0.4 | 2428928 | 37.60 | -4.25 | 12.41 | 0.16 |
|
| 108 |
+
| 0.5 | 4761600 | 40.18 | -1.67 | 12.41 | 0.16 |
|
| 109 |
+
| 0.6 | 8857600 | 39.42 | -2.43 | 12.41 | 0.16 |
|
| 110 |
+
| 0.7 | 16230400 | 39.04 | -2.81 | 12.15 | -0.10 |
|
| 111 |
+
|
| 112 |
+
As you can see, we can attain a test accuracy that comes close to the original LoHa adapter if the rank is sufficiently high. Choosing the right rank is a tradeoff between model performance and model efficiency. To reproduce this experiment, follow the script at https://github.com/huggingface/peft/tree/main/scripts/evaluate-lora-conversion.py.
|
| 113 |
+
|
| 114 |
+
Note that the number of trainable parameters cannot be translated one to one into memory usage. Some PEFT methods require more, some less memory, even with the same number of trainable parameters. Therefore, even if after conversion, the LoRA adapter has more parameters than the original one, it could still be more memory efficient when serving.
|
| 115 |
+
|
| 116 |
+
### LoRA to LoRA conversion
|
| 117 |
+
|
| 118 |
+
Similar to the experiment above, we can also evaluate LoRA to LoRA conversion (i.e. LoRA compression). Here, we start with a LoRA adapter of rank 64 trained on the same setup as above with RS-LoRA. The initial adapter has 18,350,080 trainable parameters, a test accuracy of 52.92%, and requires 12.58 GB of memory for evaluation. The following table shows the results of converting this adapter to LoRA adapters of smaller rank:
|
| 119 |
+
|
| 120 |
+
| rank | trainable parameters | test accuracy (%) | accuracy change | memory reserved (max, GB) | memory increase |
|
| 121 |
+
|------|---------------------:|------------------:|----------------:|--------------------------:|----------------:|
|
| 122 |
+
| 8 | 2293760 | 43.37 | -9.55 | 12.38 | -0.20 |
|
| 123 |
+
| 16 | 4587520 | 48.90 | -4.02 | 12.38 | -0.20 |
|
| 124 |
+
| 32 | 9175040 | 51.48 | -1.44 | 12.49 | -0.09 |
|
| 125 |
+
| 48 | 13762560 | 52.01 | -0.91 | 12.38 | -0.20 |
|
| 126 |
+
| | | | | | |
|
| 127 |
+
| 0.5 | 2150400 | 44.12 | -8.80 | 12.37 | -0.21 |
|
| 128 |
+
| 0.6 | 3082240 | 47.54 | -5.38 | 12.37 | -0.21 |
|
| 129 |
+
| 0.7 | 4448256 | 50.49 | -2.43 | 12.37 | -0.21 |
|
| 130 |
+
| 0.8 | 6510592 | 50.11 | -2.81 | 12.37 | -0.21 |
|
| 131 |
+
| 0.9 | 10022912 | 51.55 | -1.37 | 12.38 | -0.20 |
|
| 132 |
+
| 0.95 | 12976128 | 52.62 | -0.30 | 12.39 | -0.19 |
|
| 133 |
+
|
| 134 |
+
So for instance for rank 0.95, we can close the accuracy gap to just 0.3 percentage points while reducing the number of parameters by 30%. Also note that these compressed LoRAs can be better than directly training them on the lower rank -- e.g. for rank 32, training directly results in a test accuracy of 48.22%, while conversion from rank 64 results in 51.48%.
|
| 135 |
+
|
| 136 |
+
## Caveats
|
| 137 |
+
|
| 138 |
+
There are some limitations to the LoRA conversion. As mentioned above, a reduction in performance is expected and the converted LoRA will most likely be less parameter efficient than the original adapter. Moreover, LoRA conversion has these limitations:
|
| 139 |
+
|
| 140 |
+
- Right now, only adapters applied to linear layers can be converted.
|
| 141 |
+
- Not all PEFT methods currently support LoRA conversion.
|
| 142 |
+
|
| 143 |
+
If there is a lot of demand to extend LoRA conversion, please let us know by creating a [GitHub discussion](https://github.com/huggingface/peft/discussions) and we will make it work with more layer types and PEFT methods.
|
| 144 |
+
|
| 145 |
+
## API
|
| 146 |
+
|
| 147 |
+
### Convert a non-LoRA model to a LoRA model, return the `LoraConfig` and `state_dict`
|
| 148 |
+
|
| 149 |
+
[[autodoc]] tuners.lora.conversion.convert_to_lora
|
| 150 |
+
- all
|
| 151 |
+
|
| 152 |
+
### Convert a non-LoRA model to a LoRA model, save the adapter checkpoint and config at the given path
|
| 153 |
+
|
| 154 |
+
[[autodoc]] tuners.lora.conversion.save_as_lora
|
| 155 |
+
- all
|
tasks/tasksmith-0d2d1e298e86/tests/source/docs/source/package_reference/lora_variant_bdlora.md
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Block-Diagonal LoRA for Eliminating Communication Overhead in Tensor Parallel LoRA Serving
|
| 2 |
+
|
| 3 |
+
Block-Diagonal LoRA (BD-LoRA) is a LoRA variant in which some LoRA factors are constrained to be block-diagonal. This allows faster serving by eliminating communication overheads
|
| 4 |
+
when running inference on multiple GPUs. Despite the block-diagonal constraint, BD-LoRA is similarly performant to vanilla LoRA at similar parameter counts.
|
| 5 |
+
|
| 6 |
+
BD-LoRA is designed to be used with tensor parallelism, which means sharding the weights of a model among multiple GPUs. A popular sharding strategy is the [Megatron Sharding Strategy](https://arxiv.org/abs/1909.08053). For two linear layers $W_1$, $W_2$ that follow each other (for example the up and down projections in a transformer MLP module), we will shard the first layer in a column-parallel way (which requires LoRA B to be block-diagonal) and the second layer in a row-parallel way (which requires LoRA A to be block-diagonal). For the attention module, this can be similarly achieved by taking the Q, K and V projections together as $W_1$ and the out projection as $W_2$, sharding accordingly. This sharding allows a compatible inference engine to distribute each block-diagonal shard over a a different GPU, cutting the need to communicate partial results among GPUs. In the image below, you can see the exact sharding strategy and how this saves computational efforts.
|
| 7 |
+
|
| 8 |
+
Paper: https://hf.co/papers/2510.23346
|
| 9 |
+
|
| 10 |
+
<div>
|
| 11 |
+
<img src="https://github.com/huggingface/peft/blob/main/examples/bdlora_finetuning/bdlora-sharding.png?raw=true" width="800"/>
|
| 12 |
+
</div>
|
| 13 |
+
|
| 14 |
+
### Performance, rank and parameter count
|
| 15 |
+
BD-LoRA achieves similar performance to LoRA (see image below, or the `method_comparison` folder in the peft repository root) at the same parameter count. However, as every other factor in BD-LoRA is block-diagonal, a BD-LoRA adapter will have less parameters than a LoRA adapter at the same rank. The performance of BD-LoRA is only competitive when the rank is then increased accordingly. We provide example code for rank-matching at the end of this example notebook.
|
| 16 |
+
|
| 17 |
+
<div>
|
| 18 |
+
<img src="https://github.com/huggingface/peft/blob/main/examples/bdlora_finetuning/bdlora-performance.png?raw=true" width="600"/>
|
| 19 |
+
</div>
|
| 20 |
+
|
tasks/tasksmith-0d2d1e298e86/tests/source/docs/source/package_reference/lora_variant_dora.md
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!--Copyright 2026-present The HuggingFace Team. All rights reserved.
|
| 2 |
+
|
| 3 |
+
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
|
| 4 |
+
the License. You may obtain a copy of the License at
|
| 5 |
+
|
| 6 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
| 7 |
+
|
| 8 |
+
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
|
| 9 |
+
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
|
| 10 |
+
specific language governing permissions and limitations under the License.
|
| 11 |
+
|
| 12 |
+
⚠️ Note that this file is in Markdown but contains specific syntax for our doc-builder (similar to MDX) that may not be
|
| 13 |
+
rendered properly in your Markdown viewer.
|
| 14 |
+
|
| 15 |
+
-->
|
| 16 |
+
|
| 17 |
+
# Weight-Decomposed Low-Rank Adaptation (DoRA)
|
| 18 |
+
|
| 19 |
+
> [!NOTE]
|
| 20 |
+
> This is a variant of LoRA and therefore everything that is possible with LoRA is valid for this method except otherwise stated on this page.
|
| 21 |
+
|
| 22 |
+
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://huggingface.co/papers/2402.09353.
|
| 23 |
+
|
| 24 |
+
```py
|
| 25 |
+
from peft import LoraConfig
|
| 26 |
+
|
| 27 |
+
config = LoraConfig(use_dora=True, ...)
|
| 28 |
+
```
|
| 29 |
+
|
| 30 |
+
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`.
|
| 31 |
+
|
| 32 |
+
```py
|
| 33 |
+
from peft import LoraConfig, LoraRuntimeConfig
|
| 34 |
+
|
| 35 |
+
config = LoraConfig(use_dora=True, runtime_config=LoraRuntimeConfig(ephemeral_gpu_offload=True), ...)
|
| 36 |
+
```
|
| 37 |
+
|
| 38 |
+
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.
|
| 39 |
+
|
| 40 |
+
```py
|
| 41 |
+
from peft import PeftModel
|
| 42 |
+
|
| 43 |
+
model = PeftModel.from_pretrained(base_model, peft_model_id, ephemeral_gpu_offload=True)
|
| 44 |
+
```
|
| 45 |
+
|
| 46 |
+
## Optimization
|
| 47 |
+
|
| 48 |
+
DoRA is optimized (computes faster and takes less memory) for models in the evaluation mode, or when dropout is set to 0. We reuse the
|
| 49 |
+
base result at those times to get the speedup.
|
| 50 |
+
Running [dora finetuning](https://github.com/huggingface/peft/blob/main/examples/dora_finetuning/dora_finetuning.py)
|
| 51 |
+
with `CUDA_VISIBLE_DEVICES=0 ZE_AFFINITY_MASK=0 time python examples/dora_finetuning/dora_finetuning.py --quantize --lora_dropout 0 --batch_size 16 --eval_step 2 --use_dora` on a 4090 with gradient accumulation set to 2 and max step to 20 resulted with the following observations:
|
| 52 |
+
|
| 53 |
+
| | Without Optimization | With Optimization |
|
| 54 |
+
| :--: | :--: | :--: |
|
| 55 |
+
| train runtime (sec) | 359.7298 | **279.2676** |
|
| 56 |
+
| train samples per second | 1.779 | **2.292** |
|
| 57 |
+
| train steps per second | 0.056 | **0.072** |
|
| 58 |
+
|
| 59 |
+
Moreover, it is possible to further increase runtime performance of DoRA by using the [`DoraCaching`] helper context. This requires the model to be in `eval` mode:
|
| 60 |
+
|
| 61 |
+
```py
|
| 62 |
+
from peft.helpers import DoraCaching
|
| 63 |
+
|
| 64 |
+
model.eval()
|
| 65 |
+
with DoraCaching():
|
| 66 |
+
output = model(inputs)
|
| 67 |
+
```
|
| 68 |
+
|
| 69 |
+
For [`meta-llama/Llama-3.1-8B`](https://huggingface.co/meta-llama/Llama-3.1-8B), the [DoRA caching benchmark script](https://github.com/huggingface/peft/blob/main/examples/dora_finetuning/dora-caching.py) shows that, compared to LoRA:
|
| 70 |
+
|
| 71 |
+
- DoRA without caching requires 139% more time
|
| 72 |
+
- DoRA without caching requires 4% more memory
|
| 73 |
+
- DoRA with caching requires 17% more time
|
| 74 |
+
- DoRA with caching requires 41% more memory
|
| 75 |
+
|
| 76 |
+
Caching can thus make inference with DoRA significantly faster but it also requires significantly more memory. Ideally, if the use case allows it, just merge the DoRA adapter to avoid both memory and runtime overhead.
|
| 77 |
+
|
| 78 |
+
## Caveats
|
| 79 |
+
|
| 80 |
+
- DoRA only supports embedding, linear, and Conv2d layers at the moment.
|
| 81 |
+
- DoRA introduces a bigger overhead than pure LoRA, so it is recommended to merge weights for inference, see [`LoraModel.merge_and_unload`].
|
| 82 |
+
- DoRA should work with weights quantized with bitsandbytes ("QDoRA"). However, issues have been reported when using QDoRA with DeepSpeed Zero2.
|
| 83 |
+
|
tasks/tasksmith-0d2d1e298e86/tests/source/docs/source/package_reference/lora_variant_monteclora.md
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# MonteCLoRA (Monte Carlo Low-Rank Adaptation)
|
| 2 |
+
|
| 3 |
+
> [!NOTE]
|
| 4 |
+
> This is a variant of LoRA and therefore everything that is possible with LoRA is valid for this method except otherwise stated on this page.
|
| 5 |
+
|
| 6 |
+
MonteCLoRA wraps a standard LoRA adapter with a small variational module that draws Monte Carlo samples of stochastic perturbations on top of the LoRA `A` matrix during training. Concretely, it learns variational parameters (a Wishart-based covariance, a per-sample multivariate-normal noise term, and a Dirichlet weighting over the samples) and adds the resulting averaged perturbation to `lora_A` at every forward pass. A KL-divergence + entropy term is added to the training loss to keep these variational parameters anchored to a sensible prior. At inference time the sampler is disabled and MonteCLoRA behaves exactly like a regular LoRA adapter, so there is **no extra inference cost or extra parameters to merge**. For the full method see https://huggingface.co/papers/2411.04358.
|
| 7 |
+
|
| 8 |
+
You may want to consider MonteCLoRA when:
|
| 9 |
+
|
| 10 |
+
- You are fine-tuning on a small or noisy dataset and want stronger regularization than vanilla LoRA. The Monte Carlo averaging and the KL term together act as a Bayesian-style regularizer.
|
| 11 |
+
- You want better uncertainty calibration / robustness from your adapter without paying extra cost at inference time (the variational machinery is training-only).
|
| 12 |
+
- Vanilla LoRA is overfitting and lowering `r` or increasing `lora_dropout` is not enough.
|
| 13 |
+
|
| 14 |
+
You probably do *not* need MonteCLoRA when you have a large, clean dataset and vanilla LoRA already trains stably — in that regime the extra variational parameters mostly add training overhead without much benefit.
|
| 15 |
+
|
| 16 |
+
To enable MonteCLoRA, pass a `MontecloraConfig` to `LoraConfig`:
|
| 17 |
+
|
| 18 |
+
```py
|
| 19 |
+
from peft import LoraConfig, MontecloraConfig
|
| 20 |
+
|
| 21 |
+
monteclora_config = MontecloraConfig(
|
| 22 |
+
num_samples=8, # number of Monte Carlo samples per forward pass
|
| 23 |
+
sample_scaler=1e-4, # magnitude of the variational perturbation
|
| 24 |
+
kl_loss_weight=1e-5, # weight of the KL term added to the training loss
|
| 25 |
+
)
|
| 26 |
+
config = LoraConfig(
|
| 27 |
+
r=16,
|
| 28 |
+
lora_alpha=32,
|
| 29 |
+
target_modules=["q_proj", "v_proj"],
|
| 30 |
+
monteclora_config=monteclora_config,
|
| 31 |
+
)
|
| 32 |
+
```
|
| 33 |
+
|
| 34 |
+
During training you must add the variational regularization loss to the task loss. The simplest way is to call [`LoraModel._get_monteclora_loss`] on the underlying `LoraModel`:
|
| 35 |
+
|
| 36 |
+
```py
|
| 37 |
+
task_loss = ... # standard loss returned by your model
|
| 38 |
+
monteclora_loss = model._get_monteclora_loss() # 0.0 if MonteCLoRA is not used
|
| 39 |
+
total_loss = task_loss + monteclora_loss
|
| 40 |
+
total_loss.backward()
|
| 41 |
+
```
|
| 42 |
+
|
| 43 |
+
If you train with the HF `Trainer`, you can simply mix in [`peft.helpers.MontecloraTrainerMixin`] which does this for you in `compute_loss`:
|
| 44 |
+
|
| 45 |
+
```py
|
| 46 |
+
from transformers import Trainer
|
| 47 |
+
from peft.helpers import MontecloraTrainerMixin
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
class MontecloraTrainer(MontecloraTrainerMixin, Trainer):
|
| 51 |
+
pass
|
| 52 |
+
```
|
| 53 |
+
|
| 54 |
+
A complete working example is available at [`examples/monteclora_finetuning`](https://github.com/huggingface/peft/tree/main/examples/monteclora_finetuning).
|
tasks/tasksmith-0d2d1e298e86/tests/source/docs/source/package_reference/lora_variant_velora.md
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!--Copyright 2026-present The HuggingFace Team. All rights reserved.
|
| 2 |
+
|
| 3 |
+
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
|
| 4 |
+
the License. You may obtain a copy of the License at
|
| 5 |
+
|
| 6 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
| 7 |
+
|
| 8 |
+
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
|
| 9 |
+
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
|
| 10 |
+
specific language governing permissions and limitations under the License.
|
| 11 |
+
|
| 12 |
+
⚠️ Note that this file is in Markdown but contains specific syntax for our doc-builder (similar to MDX) that may not be
|
| 13 |
+
rendered properly in your Markdown viewer.
|
| 14 |
+
|
| 15 |
+
-->
|
| 16 |
+
|
| 17 |
+
### VeLoRA
|
| 18 |
+
|
| 19 |
+
> [!NOTE]
|
| 20 |
+
> This is a variant of LoRA and therefore everything that is possible with LoRA is valid for this method except otherwise stated on this page.
|
| 21 |
+
|
| 22 |
+
[VeLoRA](https://huggingface.co/papers/2405.17991) is a LoRA variant that reduces training memory by compressing the activations saved for the LoRA in the forward pass and then reconstructing them in the backwards pass to implement the update rules. In PEFT, VeLoRA is configured as a LoRA variant through the `velora_config` argument on [`LoraConfig`].
|
| 23 |
+
|
| 24 |
+
```py
|
| 25 |
+
from peft import LoraConfig, VeloraConfig
|
| 26 |
+
|
| 27 |
+
config = LoraConfig(
|
| 28 |
+
target_modules=["q_proj", "v_proj"],
|
| 29 |
+
velora_config=VeloraConfig(
|
| 30 |
+
num_groups=64,
|
| 31 |
+
scale=0.2,
|
| 32 |
+
init_type="batch_average",
|
| 33 |
+
),
|
| 34 |
+
)
|
| 35 |
+
```
|
| 36 |
+
|
| 37 |
+
VeLoRA is applied to every LoRA layer selected by `target_modules`. `num_groups` controls how the input activation depth is split before compression. If the activation depth is not evenly divisible by `num_groups`, VeLoRA pads the grouped representation internally and removes the padding after reconstruction. `scale` rescales the reconstructed activations during the backward pass, and `init_type` chooses how the projection is initialized.
|
| 38 |
+
|
| 39 |
+
Use `batch_average_once` to initialize the projection from the first training batch, `batch_average` to update it from every training forward pass, or `random` to initialize it immediately from a random normalized vector.
|
| 40 |
+
|
| 41 |
+
Below are some results with the [MetaMathQA benchmark](https://github.com/huggingface/peft/tree/main/method_comparison/MetaMathQA).
|
| 42 |
+
|
| 43 |
+
| Variant | Training Loss | Max Memory (GiB) | Tokens/sec |
|
| 44 |
+
|---|---:|---:|---:|
|
| 45 |
+
| LoRA | 0.5427 | 27.69 | 2366.2 |
|
| 46 |
+
| LoRA + GC | 0.5426 | 13.17 | 1671.8 |
|
| 47 |
+
| LoRA+VeLoRA | 0.5427 | 19.94 | 2057.6 |
|
| 48 |
+
|
| 49 |
+
#### Caveats
|
| 50 |
+
|
| 51 |
+
- VeLoRA is currently supported on standard LoRA linear layers only.
|
| 52 |
+
|
tasks/tasksmith-0d2d1e298e86/tests/source/docs/source/package_reference/merge_utils.md
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!--Copyright 2024 The HuggingFace Team. All rights reserved.
|
| 2 |
+
|
| 3 |
+
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
|
| 4 |
+
the License. You may obtain a copy of the License at
|
| 5 |
+
|
| 6 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
| 7 |
+
|
| 8 |
+
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
|
| 9 |
+
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
|
| 10 |
+
specific language governing permissions and limitations under the License.
|
| 11 |
+
|
| 12 |
+
⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be
|
| 13 |
+
rendered properly in your Markdown viewer.
|
| 14 |
+
|
| 15 |
+
-->
|
| 16 |
+
|
| 17 |
+
# Model merge
|
| 18 |
+
|
| 19 |
+
PEFT provides several internal utilities for [merging LoRA adapters](../developer_guides/model_merging) with the TIES and DARE methods.
|
| 20 |
+
|
| 21 |
+
[[autodoc]] utils.merge_utils.prune
|
| 22 |
+
|
| 23 |
+
[[autodoc]] utils.merge_utils.calculate_majority_sign_mask
|
| 24 |
+
|
| 25 |
+
[[autodoc]] utils.merge_utils.disjoint_merge
|
| 26 |
+
|
| 27 |
+
[[autodoc]] utils.merge_utils.task_arithmetic
|
| 28 |
+
|
| 29 |
+
[[autodoc]] utils.merge_utils.ties
|
| 30 |
+
|
| 31 |
+
[[autodoc]] utils.merge_utils.dare_linear
|
| 32 |
+
|
| 33 |
+
[[autodoc]] utils.merge_utils.dare_ties
|
tasks/tasksmith-0d2d1e298e86/tests/source/docs/source/package_reference/miss.md
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!--Copyright 2025 The HuggingFace Team. All rights reserved.
|
| 2 |
+
|
| 3 |
+
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
|
| 4 |
+
the License. You may obtain a copy of the License at
|
| 5 |
+
|
| 6 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
| 7 |
+
|
| 8 |
+
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
|
| 9 |
+
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
|
| 10 |
+
specific language governing permissions and limitations under the License.
|
| 11 |
+
|
| 12 |
+
⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be
|
| 13 |
+
rendered properly in your Markdown viewer.
|
| 14 |
+
|
| 15 |
+
-->
|
| 16 |
+
|
| 17 |
+
# MiSS
|
| 18 |
+
|
| 19 |
+
[MiSS (Matrix Shard Sharing)](https://arxiv.org/abs/2409.15371) is a PEFT method that achieves a good balance between model performance and computational efficiency. It requires only a single trainable matrix and introduces a shard-sharing mechanism distinct from LoRA.
|
| 20 |
+
|
| 21 |
+
The abstract from the paper is:
|
| 22 |
+
|
| 23 |
+
*Parameter-Efficient Fine-Tuning (PEFT) methods, particularly Low-Rank Adaptation (LoRA), effectively reduce the number of trainable parameters in Large Language Models (LLMs). However, as model scales continue to grow, the demand for computational resources remains a significant challenge. Existing LoRA variants often struggle to strike an optimal balance between adaptability (model performance and convergence speed) and efficiency (computational overhead, memory usage, and initialization time). This paper introduces MiSS (Matrix Shard Sharing), a novel PEFT approach that addresses this trade-off through a simple shard-sharing mechanism. MiSS leverages the insight that a low-rank adaptation can be achieved by decomposing the weight matrix into multiple fragment matrices and utilizing a shared, trainable common fragment. This method constructs the low-rank update matrix through the replication of these shared, partitioned shards. We also propose a hardware-efficient and broadly applicable implementation for MiSS. Extensive experiments conducted on a range of tasks, alongside a systematic analysis of computational performance, demonstrate MiSS's superiority. The results show that MiSS significantly outperforms standard LoRA and its prominent variants in both model performance metrics and computational efficiency, including initialization speed and training throughput. By effectively balancing expressive power and resource utilization, MiSS offers a compelling solution for efficiently adapting large-scale models.*
|
| 24 |
+
|
| 25 |
+
## Benchmark overview
|
| 26 |
+
|
| 27 |
+
<iframe
|
| 28 |
+
src="https://peft-internal-testing-peft-method-comparison-embed.hf.space/?highlight[type]=MISS"
|
| 29 |
+
frameborder="0"
|
| 30 |
+
width="850"
|
| 31 |
+
height="1000"
|
| 32 |
+
></iframe>
|
| 33 |
+
|
| 34 |
+
## When to use MiSS
|
| 35 |
+
|
| 36 |
+
MiSS is a good choice when:
|
| 37 |
+
|
| 38 |
+
- You want faster initialization and higher training throughput than advanced LoRA initialization schemes that use expensive setups (such as PiSSA, LoRA-GA, or OLoRA).
|
| 39 |
+
- You want a drop-in alternative to LoRA with minimal configuration changes.
|
| 40 |
+
|
| 41 |
+
If you need stronger expressiveness at the cost of some efficiency, consider the `bat` initialization variant (see below).
|
| 42 |
+
|
| 43 |
+
## init_weights modes
|
| 44 |
+
|
| 45 |
+
MiSS supports three initialization modes via the `init_weights` parameter:
|
| 46 |
+
|
| 47 |
+
- `True` (default): Standard MiSS initialization. Best starting point for most use cases.
|
| 48 |
+
- `"bat"`: Enables nonlinear updates across different shards. Produces better results than standard MiSS but uses more memory and is approximately twice as slow. Use this when performance is the priority over efficiency.
|
| 49 |
+
- `"mini"`: Uses a smaller rank along the `out_features` dimension, controlled by `mini_r`. This reduces trainable parameters further. When using this mode, `mini_r` must be set and `out_features` must be divisible by `mini_r`.
|
| 50 |
+
|
| 51 |
+
## Quick start
|
| 52 |
+
|
| 53 |
+
```python
|
| 54 |
+
import torch
|
| 55 |
+
from peft import MissConfig, get_peft_model
|
| 56 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 57 |
+
|
| 58 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 59 |
+
"meta-llama/Llama-2-7b-hf",
|
| 60 |
+
torch_dtype=torch.bfloat16,
|
| 61 |
+
device_map="auto"
|
| 62 |
+
)
|
| 63 |
+
tokenizer = AutoTokenizer.from_pretrained("meta-llama/Llama-2-7b-hf")
|
| 64 |
+
tokenizer.pad_token_id = tokenizer.eos_token_id
|
| 65 |
+
|
| 66 |
+
# Standard MiSS
|
| 67 |
+
config = MissConfig(
|
| 68 |
+
r=64,
|
| 69 |
+
miss_dropout=0.01,
|
| 70 |
+
task_type="CAUSAL_LM"
|
| 71 |
+
)
|
| 72 |
+
|
| 73 |
+
# BAT variant — better performance, more memory
|
| 74 |
+
# config = MissConfig(
|
| 75 |
+
# r=64,
|
| 76 |
+
# init_weights="bat",
|
| 77 |
+
# task_type="CAUSAL_LM"
|
| 78 |
+
# )
|
| 79 |
+
|
| 80 |
+
# Mini variant — fewer trainable parameters
|
| 81 |
+
# config = MissConfig(
|
| 82 |
+
# r=64,
|
| 83 |
+
# init_weights="mini",
|
| 84 |
+
# mini_r=8,
|
| 85 |
+
# task_type="CAUSAL_LM"
|
| 86 |
+
# )
|
| 87 |
+
|
| 88 |
+
model = get_peft_model(model, config)
|
| 89 |
+
model.print_trainable_parameters()
|
| 90 |
+
```
|
| 91 |
+
|
| 92 |
+
For a full fine-tuning example including training and inference, see the [MiSS fine-tuning example](https://github.com/huggingface/peft/tree/main/examples/miss_finetuning).
|
| 93 |
+
|
| 94 |
+
# API
|
| 95 |
+
|
| 96 |
+
## MissConfig
|
| 97 |
+
|
| 98 |
+
[[autodoc]] tuners.miss.config.MissConfig
|
| 99 |
+
|
| 100 |
+
## MissModel
|
| 101 |
+
|
| 102 |
+
[[autodoc]] tuners.miss.model.MissModel
|
tasks/tasksmith-0d2d1e298e86/tests/source/docs/source/package_reference/multitask_prompt_tuning.md
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!--Copyright 2023 The HuggingFace Team. All rights reserved.
|
| 2 |
+
|
| 3 |
+
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
|
| 4 |
+
the License. You may obtain a copy of the License at
|
| 5 |
+
|
| 6 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
| 7 |
+
|
| 8 |
+
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
|
| 9 |
+
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
|
| 10 |
+
specific language governing permissions and limitations under the License.
|
| 11 |
+
|
| 12 |
+
⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be
|
| 13 |
+
rendered properly in your Markdown viewer.
|
| 14 |
+
|
| 15 |
+
-->
|
| 16 |
+
|
| 17 |
+
# Multitask prompt tuning
|
| 18 |
+
|
| 19 |
+
[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.
|
| 20 |
+
|
| 21 |
+
The abstract from the paper is:
|
| 22 |
+
|
| 23 |
+
*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*.
|
| 24 |
+
|
| 25 |
+
<div class="flex justify-center">
|
| 26 |
+
<img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/peft/mpt.png"/>
|
| 27 |
+
</div>
|
| 28 |
+
<small><a href="https://hf.co/papers/2303.02861">Multitask prompt tuning enables parameter-efficient transfer learning</a>.</small>
|
| 29 |
+
|
| 30 |
+
MPT consists of two stages:
|
| 31 |
+
|
| 32 |
+
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.
|
| 33 |
+
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.
|
| 34 |
+
|
| 35 |
+
<div class="flex justify-center">
|
| 36 |
+
<img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/peft/mpt-decomposition.png"/>
|
| 37 |
+
</div>
|
| 38 |
+
<small><a href="https://hf.co/papers/2103.10385">Prompt decomposition</a>.</small>
|
| 39 |
+
|
| 40 |
+
## Benchmark overview
|
| 41 |
+
|
| 42 |
+
There is no benchmark for this method yet. Feel free to contribute an experiment
|
| 43 |
+
configuration but make sure to first create an issue
|
| 44 |
+
[here](https://github.com/huggingface/peft/issues).
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
# API
|
| 48 |
+
|
| 49 |
+
## MultitaskPromptTuningConfig
|
| 50 |
+
|
| 51 |
+
[[autodoc]] tuners.multitask_prompt_tuning.config.MultitaskPromptTuningConfig
|
| 52 |
+
|
| 53 |
+
## MultitaskPromptEmbedding
|
| 54 |
+
|
| 55 |
+
[[autodoc]] tuners.multitask_prompt_tuning.model.MultitaskPromptEmbedding
|
tasks/tasksmith-0d2d1e298e86/tests/source/docs/source/package_reference/oft.md
ADDED
|
@@ -0,0 +1,98 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!--Copyright 2023 The HuggingFace Team. All rights reserved.
|
| 2 |
+
|
| 3 |
+
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
|
| 4 |
+
the License. You may obtain a copy of the License at
|
| 5 |
+
|
| 6 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
| 7 |
+
|
| 8 |
+
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
|
| 9 |
+
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
|
| 10 |
+
specific language governing permissions and limitations under the License.
|
| 11 |
+
|
| 12 |
+
⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be
|
| 13 |
+
rendered properly in your Markdown viewer.
|
| 14 |
+
|
| 15 |
+
-->
|
| 16 |
+
|
| 17 |
+
# OFT
|
| 18 |
+
|
| 19 |
+
<div class="flex justify-center">
|
| 20 |
+
<img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/peft/oft.png"/>
|
| 21 |
+
</div>
|
| 22 |
+
<small><a href="https://hf.co/papers/2306.07280">Controlling Text-to-Image Diffusion by Orthogonal Finetuning</a></small>
|
| 23 |
+
|
| 24 |
+
[Orthogonal Finetuning (OFT)](https://hf.co/papers/2306.07280) and [OFTv2](https://huggingface.co/papers/2506.19847) is a method developed for adapting text-to-image diffusion models. It works by reparameterizing the pretrained weight matrices with its 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 method primarily focuses on preserving a pretrained model's generative performance in the finetuned model. It tries to maintain the same cosine similarity ([hyperspherical energy](https://huggingface.co/papers/1805.09298)) 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)).
|
| 25 |
+
|
| 26 |
+
The abstract from the paper is:
|
| 27 |
+
|
| 28 |
+
*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*.
|
| 29 |
+
|
| 30 |
+
OFT preserves the hyperspherical energy by learning an orthogonal transformation for neurons to keep the cosine similarity between them unchanged, potentially leading to less forgetting of previous learnt knowledge. 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.
|
| 31 |
+
|
| 32 |
+
## Benchmark overview
|
| 33 |
+
|
| 34 |
+
<iframe
|
| 35 |
+
src="https://peft-internal-testing-peft-method-comparison-embed.hf.space/?highlight[type]=OFT"
|
| 36 |
+
frameborder="0"
|
| 37 |
+
width="850"
|
| 38 |
+
height="1000"
|
| 39 |
+
></iframe>
|
| 40 |
+
|
| 41 |
+
## Merge OFT weights into the base model
|
| 42 |
+
|
| 43 |
+
Similar to LoRA, the weights learned by OFT can be integrated into the pretrained weight matrices using the [`~OFTModel.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.
|
| 44 |
+
|
| 45 |
+
## OFT Example Usage
|
| 46 |
+
|
| 47 |
+
For using OFT for quantized finetuning with [TRL](https://github.com/huggingface/trl) for `SFT`, `PPO`, or `DPO` fine-tuning, follow the following outline:
|
| 48 |
+
|
| 49 |
+
```py
|
| 50 |
+
from transformers import AutoTokenizer, AutoModelForCausalLM, BitsAndBytesConfig
|
| 51 |
+
from trl import SFTTrainer
|
| 52 |
+
from peft import OFTConfig
|
| 53 |
+
|
| 54 |
+
if use_quantization:
|
| 55 |
+
bnb_config = BitsAndBytesConfig(
|
| 56 |
+
load_in_4bit=True,
|
| 57 |
+
bnb_4bit_quant_type="nf4",
|
| 58 |
+
bnb_4bit_compute_dtype=torch.bfloat16,
|
| 59 |
+
bnb_4bit_use_double_quant=True,
|
| 60 |
+
bnb_4bit_quant_storage=torch.bfloat16,
|
| 61 |
+
)
|
| 62 |
+
|
| 63 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 64 |
+
"model_name",
|
| 65 |
+
quantization_config=bnb_config
|
| 66 |
+
)
|
| 67 |
+
tokenizer = AutoTokenizer.from_pretrained("model_name")
|
| 68 |
+
|
| 69 |
+
# Configure OFT
|
| 70 |
+
peft_config = OFTConfig(
|
| 71 |
+
oft_block_size=32,
|
| 72 |
+
use_cayley_neumann=True,
|
| 73 |
+
target_modules="all-linear",
|
| 74 |
+
bias="none",
|
| 75 |
+
task_type="CAUSAL_LM"
|
| 76 |
+
)
|
| 77 |
+
|
| 78 |
+
trainer = SFTTrainer(
|
| 79 |
+
model=model,
|
| 80 |
+
train_dataset=ds['train'],
|
| 81 |
+
peft_config=peft_config,
|
| 82 |
+
processing_class=tokenizer,
|
| 83 |
+
args=training_arguments,
|
| 84 |
+
data_collator=collator,
|
| 85 |
+
)
|
| 86 |
+
|
| 87 |
+
trainer.train()
|
| 88 |
+
```
|
| 89 |
+
|
| 90 |
+
# API
|
| 91 |
+
|
| 92 |
+
## OFTConfig
|
| 93 |
+
|
| 94 |
+
[[autodoc]] tuners.oft.config.OFTConfig
|
| 95 |
+
|
| 96 |
+
## OFTModel
|
| 97 |
+
|
| 98 |
+
[[autodoc]] tuners.oft.model.OFTModel
|
tasks/tasksmith-0d2d1e298e86/tests/source/docs/source/package_reference/osf.md
ADDED
|
@@ -0,0 +1,254 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!--Copyright 2025 The HuggingFace Team. All rights reserved.
|
| 2 |
+
|
| 3 |
+
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
|
| 4 |
+
the License. You may obtain a copy of the License at
|
| 5 |
+
|
| 6 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
| 7 |
+
|
| 8 |
+
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
|
| 9 |
+
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
|
| 10 |
+
specific language governing permissions and limitations under the License.
|
| 11 |
+
|
| 12 |
+
⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be
|
| 13 |
+
rendered properly in your Markdown viewer.
|
| 14 |
+
|
| 15 |
+
-->
|
| 16 |
+
|
| 17 |
+
# OSF (Orthogonal Subspace Fine-tuning)
|
| 18 |
+
|
| 19 |
+
Orthogonal Subspace Fine-tuning ([OSF](https://huggingface.co/papers/2504.07097)) is a PEFT method designed for continual learning that constrains parameter updates to be orthogonal to previously important directions. This approach enables full fine-tuning while preventing catastrophic forgetting without requiring additional parameters or storing previous gradients.
|
| 20 |
+
|
| 21 |
+
The abstract from the paper is:
|
| 22 |
+
|
| 23 |
+
*Continual learning in large language models (LLMs) is prone to catastrophic forgetting, where adapting to new tasks significantly degrades performance on previously learned ones. Existing methods typically rely on low-rank, parameter-efficient updates that limit the model's expressivity and introduce additional parameters per task, leading to scalability issues. To address these limitations, we propose a novel continual full fine-tuning approach leveraging adaptive singular value decomposition (SVD). Our method dynamically identifies task-specific low-rank parameter subspaces and constrains updates to be orthogonal to critical directions associated with prior tasks, thus effectively minimizing interference without additional parameter overhead or storing previous task gradients. We evaluate our approach extensively on standard continual learning benchmarks using both encoder-decoder (T5-Large) and decoder-only (LLaMA-2 7B) models, spanning diverse tasks including classification, generation, and reasoning. Empirically, our method achieves state-of-the-art results, up to 7% higher average accuracy than recent baselines like O-LoRA, and notably maintains the model's general linguistic capabilities, instruction-following accuracy, and safety throughout the continual learning process by reducing forgetting to near-negligible levels. Our adaptive SVD framework effectively balances model plasticity and knowledge retention, providing a practical, theoretically grounded, and computationally scalable solution for continual learning scenarios in large language models.*
|
| 24 |
+
|
| 25 |
+
## How OSF Works
|
| 26 |
+
|
| 27 |
+
OSF decomposes each weight matrix into high-rank (frozen) and low-rank (trainable) components using SVD:
|
| 28 |
+
|
| 29 |
+
```
|
| 30 |
+
W = U_high * S_high * V_high^T + U_low * S_low * V_low^T
|
| 31 |
+
```
|
| 32 |
+
|
| 33 |
+
Where:
|
| 34 |
+
- `U_high, S_high, V_high`: Preserve important directions from previous tasks (frozen)
|
| 35 |
+
- `U_low, S_low, V_low`: Allow adaptation to new tasks (trainable)
|
| 36 |
+
|
| 37 |
+
During training, gradients are projected to be orthogonal to the high-rank subspace, ensuring updates don't interfere with previously learned knowledge.
|
| 38 |
+
|
| 39 |
+
## Basic Usage
|
| 40 |
+
|
| 41 |
+
```python
|
| 42 |
+
import torch
|
| 43 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 44 |
+
from peft import OSFConfig, get_peft_model
|
| 45 |
+
|
| 46 |
+
# Load base model
|
| 47 |
+
model = AutoModelForCausalLM.from_pretrained("gpt2")
|
| 48 |
+
|
| 49 |
+
# Configure OSF
|
| 50 |
+
config = OSFConfig(
|
| 51 |
+
target_modules=["c_attn", "c_proj"], # Target attention layers
|
| 52 |
+
effective_rank=8, # Default rank for decomposition
|
| 53 |
+
rank_pattern={"c_attn": 16} # Override rank for specific modules
|
| 54 |
+
)
|
| 55 |
+
|
| 56 |
+
# Apply OSF
|
| 57 |
+
model = get_peft_model(model, config)
|
| 58 |
+
|
| 59 |
+
# Train as usual
|
| 60 |
+
optimizer = torch.optim.AdamW(model.parameters(), lr=3e-4)
|
| 61 |
+
|
| 62 |
+
tokenizer = AutoTokenizer.from_pretrained("gpt2")
|
| 63 |
+
tokenizer.pad_token = tokenizer.eos_token
|
| 64 |
+
|
| 65 |
+
inputs = tokenizer("Hello world", return_tensors="pt", padding=True)
|
| 66 |
+
loss = model(**inputs, labels=inputs.input_ids).loss
|
| 67 |
+
loss.backward()
|
| 68 |
+
optimizer.step()
|
| 69 |
+
optimizer.zero_grad()
|
| 70 |
+
```
|
| 71 |
+
|
| 72 |
+
## Configuration Options
|
| 73 |
+
|
| 74 |
+
### Target Modules
|
| 75 |
+
|
| 76 |
+
You can specify target modules in several ways:
|
| 77 |
+
|
| 78 |
+
```python
|
| 79 |
+
# Specific module names
|
| 80 |
+
config = OSFConfig(target_modules=["q_proj", "k_proj", "v_proj", "o_proj"])
|
| 81 |
+
|
| 82 |
+
# All linear layers
|
| 83 |
+
config = OSFConfig(target_modules="all-linear")
|
| 84 |
+
|
| 85 |
+
# Model-specific defaults (automatically detected)
|
| 86 |
+
config = OSFConfig() # Uses model-appropriate defaults
|
| 87 |
+
```
|
| 88 |
+
|
| 89 |
+
### Effective Rank Configuration
|
| 90 |
+
|
| 91 |
+
Control the preserved/trainable subspaces:
|
| 92 |
+
|
| 93 |
+
```python
|
| 94 |
+
# Global preserved rank (applies to all target modules)
|
| 95 |
+
config = OSFConfig(effective_rank=16) # preserves top-16 singular directions; trains the rest
|
| 96 |
+
|
| 97 |
+
# Automatic preserved rank (50% of the smaller matrix dimension per target)
|
| 98 |
+
config = OSFConfig(effective_rank=None)
|
| 99 |
+
|
| 100 |
+
# Per-module preserved-rank overrides
|
| 101 |
+
config = OSFConfig(
|
| 102 |
+
effective_rank=8,
|
| 103 |
+
rank_pattern={
|
| 104 |
+
"q_proj": 16, # Higher rank for query projection
|
| 105 |
+
"gate_proj": 4 # Lower rank for gate projection
|
| 106 |
+
}
|
| 107 |
+
)
|
| 108 |
+
|
| 109 |
+
# Fractional preserved rank is supported (interpreted per-target as fraction * min_dim)
|
| 110 |
+
config = OSFConfig(effective_rank=0.8) # preserve 80% of min_dim; train remaining 20%
|
| 111 |
+
config = OSFConfig(rank_pattern={"q_proj": 0.5}) # preserve 50% on q_proj, others use global/default
|
| 112 |
+
```
|
| 113 |
+
|
| 114 |
+
Note: OSF's `effective_rank` is the preserved (frozen) rank, not the trainable rank. The trainable rank equals `min(weight.shape) - effective_rank`. This differs from LoRA's `r`, which directly specifies the trainable rank.
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
## Training Advice for Continual Learning
|
| 118 |
+
|
| 119 |
+
### Sequential Task Learning
|
| 120 |
+
|
| 121 |
+
OSF is specifically designed for learning tasks sequentially. Between tasks, recompute the SVD so the preserved subspace reflects the latest weights. One simple way is to re-wrap the updated base model with OSF again:
|
| 122 |
+
|
| 123 |
+
```python
|
| 124 |
+
# Task 1: train on domain A with initial preserved subspace
|
| 125 |
+
r = 8 # initial effective rank to preserve
|
| 126 |
+
model = get_peft_model(base_model, OSFConfig(effective_rank=r))
|
| 127 |
+
train_task(model, task_1_data)
|
| 128 |
+
|
| 129 |
+
# Task 2: recompute SVD on updated weights and increase preserved subspace
|
| 130 |
+
base_model = model.unload() # unwrap base model without assuming internals
|
| 131 |
+
r += 4 # grow preserved subspace to include Task 1 knowledge
|
| 132 |
+
model = get_peft_model(base_model, OSFConfig(effective_rank=r))
|
| 133 |
+
train_task(model, task_2_data)
|
| 134 |
+
|
| 135 |
+
# Task 3: recompute again and expand preserved subspace further
|
| 136 |
+
base_model = model.unload()
|
| 137 |
+
r += 4
|
| 138 |
+
model = get_peft_model(base_model, OSFConfig(effective_rank=r))
|
| 139 |
+
train_task(model, task_3_data)
|
| 140 |
+
```
|
| 141 |
+
|
| 142 |
+
### Budget Allocation for Task Sequences
|
| 143 |
+
|
| 144 |
+
When training on a known sequence of n tasks, one effective strategy is to progressively allocate model capacity to balance learning new tasks while preserving previous knowledge:
|
| 145 |
+
|
| 146 |
+
- **Task 1**: Use full capacity (train everything)
|
| 147 |
+
- **Task 2**: Freeze 1/n of model capacity, train remaining (n-1)/n capacity
|
| 148 |
+
- **Task 3**: Freeze 2/n of model capacity, train remaining (n-2)/n capacity
|
| 149 |
+
- **Task n**: Freeze (n-1)/n of model capacity, use 1/n capacity for final task
|
| 150 |
+
|
| 151 |
+
This approach ensures each task gets adequate learning capacity while progressively preserving more knowledge from previous tasks.
|
| 152 |
+
|
| 153 |
+
```python
|
| 154 |
+
# Example: 4-task sequence with progressive budget allocation
|
| 155 |
+
n_tasks = 4
|
| 156 |
+
max_preserved_rank = 512 # Upper bound for preserved rank per target (heuristic)
|
| 157 |
+
|
| 158 |
+
for task_id in range(n_tasks):
|
| 159 |
+
# Freeze increases over time; trainable capacity shrinks
|
| 160 |
+
preserved_fraction = (task_id + 1) / n_tasks
|
| 161 |
+
preserved_rank = int(max_preserved_rank * preserved_fraction)
|
| 162 |
+
|
| 163 |
+
config = OSFConfig(
|
| 164 |
+
target_modules=["q_proj", "k_proj", "v_proj", "o_proj"],
|
| 165 |
+
effective_rank=preserved_rank,
|
| 166 |
+
)
|
| 167 |
+
|
| 168 |
+
print(
|
| 169 |
+
f"Task {task_id + 1}: Preserving rank {preserved_rank} "
|
| 170 |
+
f"({preserved_fraction:.1%} of max_preserved_rank - {max_preserved_rank} frozen); trainable rank = min_dim - preserved_rank"
|
| 171 |
+
)
|
| 172 |
+
|
| 173 |
+
model = get_peft_model(base_model, config)
|
| 174 |
+
train_task(model, task_data[task_id])
|
| 175 |
+
```
|
| 176 |
+
|
| 177 |
+
### Best Practices
|
| 178 |
+
|
| 179 |
+
1. **Effective Rank Selection**: Start with `effective_rank=None` (auto sets rank to 50% of the smaller weight dimension per target module) and adjust based on task complexity
|
| 180 |
+
2. **Learning Rate**: Use smaller learning rates (1e-5 to 1e-4) compared to standard fine-tuning
|
| 181 |
+
3. **Task Importance**: Use `rank_pattern` to allocate more capacity to critical modules
|
| 182 |
+
4. **Model Architecture**: OSF works best with transformer architectures having clear attention and MLP separations
|
| 183 |
+
5. **Capacity Planning**: For known task sequences, use progressive budget allocation (1/n, 2/n, ..., (n-1)/n freezing) to balance plasticity and stability
|
| 184 |
+
|
| 185 |
+
### Memory Considerations
|
| 186 |
+
|
| 187 |
+
OSF modifies weights in-place and doesn't add parameters, making it memory-efficient:
|
| 188 |
+
|
| 189 |
+
```python
|
| 190 |
+
# Memory usage remains close to base model
|
| 191 |
+
print(f"Base model parameters: {base_model.num_parameters():,}")
|
| 192 |
+
print(f"OSF model parameters: {osf_model.num_parameters():,}") # Similar count
|
| 193 |
+
```
|
| 194 |
+
|
| 195 |
+
## Advanced Usage
|
| 196 |
+
|
| 197 |
+
### Custom Target Modules
|
| 198 |
+
|
| 199 |
+
For models with non-standard architectures:
|
| 200 |
+
|
| 201 |
+
```python
|
| 202 |
+
config = OSFConfig(
|
| 203 |
+
target_modules=["dense", "intermediate.dense"], # Custom layer names
|
| 204 |
+
effective_rank=12,
|
| 205 |
+
rank_pattern={"dense": 8, "intermediate.dense": 16}
|
| 206 |
+
)
|
| 207 |
+
```
|
| 208 |
+
|
| 209 |
+
### Integration with Other Methods
|
| 210 |
+
|
| 211 |
+
OSF can be combined with other techniques:
|
| 212 |
+
|
| 213 |
+
```python
|
| 214 |
+
# Use with gradient checkpointing for memory efficiency
|
| 215 |
+
model.gradient_checkpointing_enable()
|
| 216 |
+
|
| 217 |
+
# Apply weight decay selectively (regularizes low-rank factors to limit drift/overfitting in continual updates; keep small)
|
| 218 |
+
optimizer = torch.optim.AdamW([
|
| 219 |
+
{"params": [p for n, p in model.named_parameters() if "U_low" in n], "weight_decay": 0.01},
|
| 220 |
+
{"params": [p for n, p in model.named_parameters() if "S_low" in n], "weight_decay": 0.001},
|
| 221 |
+
{"params": [p for n, p in model.named_parameters() if "V_low" in n], "weight_decay": 0.01},
|
| 222 |
+
], lr=1e-4)
|
| 223 |
+
```
|
| 224 |
+
|
| 225 |
+
## Benchmark overview
|
| 226 |
+
|
| 227 |
+
<iframe
|
| 228 |
+
src="https://peft-internal-testing-peft-method-comparison-embed.hf.space/?highlight[type]=OSF"
|
| 229 |
+
frameborder="0"
|
| 230 |
+
width="850"
|
| 231 |
+
height="1000"
|
| 232 |
+
></iframe>
|
| 233 |
+
|
| 234 |
+
# API
|
| 235 |
+
|
| 236 |
+
## OSFConfig
|
| 237 |
+
|
| 238 |
+
[[autodoc]] tuners.osf.config.OSFConfig
|
| 239 |
+
|
| 240 |
+
## OSFModel
|
| 241 |
+
|
| 242 |
+
[[autodoc]] tuners.osf.model.OSFModel
|
| 243 |
+
|
| 244 |
+
## Utility Functions
|
| 245 |
+
|
| 246 |
+
### Weight Decomposition
|
| 247 |
+
|
| 248 |
+
[[autodoc]] tuners.osf.utils.decompose_weight_matrix
|
| 249 |
+
|
| 250 |
+
[[autodoc]] tuners.osf.utils.reconstruct_weight_matrix
|
| 251 |
+
|
| 252 |
+
### Gradient Projection
|
| 253 |
+
|
| 254 |
+
[[autodoc]] tuners.osf.utils.project_gradient_to_orthogonal_space
|
tasks/tasksmith-0d2d1e298e86/tests/source/docs/source/package_reference/p_tuning.md
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!--Copyright 2023 The HuggingFace Team. All rights reserved.
|
| 2 |
+
|
| 3 |
+
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
|
| 4 |
+
the License. You may obtain a copy of the License at
|
| 5 |
+
|
| 6 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
| 7 |
+
|
| 8 |
+
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
|
| 9 |
+
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
|
| 10 |
+
specific language governing permissions and limitations under the License.
|
| 11 |
+
|
| 12 |
+
⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be
|
| 13 |
+
rendered properly in your Markdown viewer.
|
| 14 |
+
|
| 15 |
+
-->
|
| 16 |
+
|
| 17 |
+
# P-tuning
|
| 18 |
+
|
| 19 |
+
<div class="flex justify-center">
|
| 20 |
+
<img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/peft/p-tuning.png"/>
|
| 21 |
+
</div>
|
| 22 |
+
<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>
|
| 23 |
+
|
| 24 |
+
[P-tuning](https://hf.co/papers/2103.10385) is designed for natural language understanding (NLU) tasks and all language models.
|
| 25 |
+
|
| 26 |
+
The abstract from the paper is:
|
| 27 |
+
|
| 28 |
+
*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.*.
|
| 29 |
+
|
| 30 |
+
The method 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. A prompt encoder (a bidirectional long-short term memory network or LSTM) is used to optimize the prompt parameters. Unlike prefix tuning:
|
| 31 |
+
|
| 32 |
+
- the prompt tokens can be inserted anywhere in the input sequence, and it isn't restricted to only the beginning
|
| 33 |
+
- the prompt tokens are only added to the input instead of adding them to every layer of the model
|
| 34 |
+
- introducing *anchor* tokens can improve performance because they indicate characteristics of a component in the input sequence
|
| 35 |
+
|
| 36 |
+
The paper's 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.
|
| 37 |
+
|
| 38 |
+
## Usage
|
| 39 |
+
|
| 40 |
+
Create a [`PromptEncoderConfig`] with the task type, the number of virtual tokens to add and learn, and the hidden size of the encoder for learning the prompt parameters.
|
| 41 |
+
|
| 42 |
+
```py
|
| 43 |
+
from peft import PromptEncoderConfig, get_peft_model
|
| 44 |
+
|
| 45 |
+
peft_config = PromptEncoderConfig(task_type="CAUSAL_LM", num_virtual_tokens=20, encoder_hidden_size=128)
|
| 46 |
+
model = get_peft_model(model, peft_config)
|
| 47 |
+
model.print_trainable_parameters()
|
| 48 |
+
"trainable params: 300,288 || all params: 559,514,880 || trainable%: 0.05366935013417338"
|
| 49 |
+
```
|
| 50 |
+
|
| 51 |
+
## Benchmark overview
|
| 52 |
+
|
| 53 |
+
<iframe
|
| 54 |
+
src="https://peft-internal-testing-peft-method-comparison-embed.hf.space/?highlight[type]=P_TUNING"
|
| 55 |
+
frameborder="0"
|
| 56 |
+
width="850"
|
| 57 |
+
height="1000"
|
| 58 |
+
></iframe>
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
# API
|
| 62 |
+
|
| 63 |
+
## PromptEncoderConfig
|
| 64 |
+
|
| 65 |
+
[[autodoc]] tuners.p_tuning.config.PromptEncoderConfig
|
| 66 |
+
|
| 67 |
+
## PromptEncoder
|
| 68 |
+
|
| 69 |
+
[[autodoc]] tuners.p_tuning.model.PromptEncoder
|
| 70 |
+
|
tasks/tasksmith-0d2d1e298e86/tests/source/docs/source/package_reference/peanut.md
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!--Copyright 2026 The HuggingFace Team. All rights reserved.
|
| 2 |
+
|
| 3 |
+
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
|
| 4 |
+
the License. You may obtain a copy of the License at
|
| 5 |
+
|
| 6 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
| 7 |
+
|
| 8 |
+
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
|
| 9 |
+
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
|
| 10 |
+
specific language governing permissions and limitations under the License.
|
| 11 |
+
|
| 12 |
+
⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be
|
| 13 |
+
rendered properly in your Markdown viewer.
|
| 14 |
+
|
| 15 |
+
-->
|
| 16 |
+
|
| 17 |
+
# PEANuT: Parameter-Efficient Adaptation with Weight-aware Neural Tweakers
|
| 18 |
+
|
| 19 |
+
[PEANuT](https://arxiv.org/abs/2410.01870) is a parameter-efficient fine-tuning technique that introduces
|
| 20 |
+
weight-aware neural tweakers to generate adapter updates from the frozen pretrained weights themselves. Instead of
|
| 21 |
+
learning a purely linear low-rank update as in LoRA, PEANuT conditions the adapter transformation on the base weight,
|
| 22 |
+
which makes the update rule more expressive while keeping the number of trainable parameters small.
|
| 23 |
+
|
| 24 |
+
PEANuT uses an input projection `A`, an output projection `B`, and optional intermediate residual encoder/decoder
|
| 25 |
+
pairs with non-linear activations. This makes it possible to model more complex update patterns than weight-agnostic
|
| 26 |
+
linear adapters while still remaining within the PEFT setting.
|
| 27 |
+
|
| 28 |
+
PEANuT currently has the following tradeoffs:
|
| 29 |
+
|
| 30 |
+
Pros:
|
| 31 |
+
- Higher theoretical expressiveness than linear low-rank updates.
|
| 32 |
+
- Better performance than LoRA on a range of tasks under similar budgets.
|
| 33 |
+
- Works well in very low-parameter regimes, for example around `0.2M` trainable parameters.
|
| 34 |
+
|
| 35 |
+
Cons:
|
| 36 |
+
- Higher memory usage than LoRA, because `ΔW` is explicitly constructed before being applied.
|
| 37 |
+
- Slower training and inference than LoRA, and deeper intermediate layers increase the overhead further.
|
| 38 |
+
- The non-linearity can require more careful hyperparameter tuning, especially learning rate and related optimization settings.
|
| 39 |
+
|
| 40 |
+
If these tradeoffs do not fit your use case, consider other PEFT methods such as LoRA.
|
| 41 |
+
|
| 42 |
+
The abstract from the paper is:
|
| 43 |
+
|
| 44 |
+
> Fine-tuning large pre-trained foundation models often yields excellent downstream performance but is prohibitively expensive when updating all parameters. Parameter-efficient fine-tuning (PEFT) methods such as LoRA alleviate this by introducing lightweight update modules, yet they commonly rely on weight-agnostic linear approximations, limiting their expressiveness. In this work, we propose PEANuT, a novel PEFT framework that introduces weight-aware neural tweakers, compact neural modules that generate task-adaptive updates conditioned on frozen pre-trained weights. PEANuT provides a flexible yet efficient way to capture complex update patterns without full model tuning. We theoretically show that PEANuT achieves equivalent or greater expressivity than existing linear PEFT methods with comparable or fewer parameters. Extensive experiments across four benchmarks with over twenty datasets demonstrate that PEANuT consistently outperforms strong baselines in both NLP and vision tasks, while maintaining low computational overhead.
|
| 45 |
+
|
| 46 |
+
## Benchmark overview
|
| 47 |
+
|
| 48 |
+
<iframe
|
| 49 |
+
src="https://peft-internal-testing-peft-method-comparison-embed.hf.space/?highlight[type]=PEANUT"
|
| 50 |
+
frameborder="0"
|
| 51 |
+
width="850"
|
| 52 |
+
height="1000"
|
| 53 |
+
></iframe>
|
| 54 |
+
|
| 55 |
+
# API
|
| 56 |
+
|
| 57 |
+
## PeanutConfig
|
| 58 |
+
|
| 59 |
+
[[autodoc]] tuners.peanut.config.PeanutConfig
|
| 60 |
+
|
| 61 |
+
## PeanutModel
|
| 62 |
+
|
| 63 |
+
[[autodoc]] tuners.peanut.model.PeanutModel
|
| 64 |
+
|
tasks/tasksmith-0d2d1e298e86/tests/source/docs/source/package_reference/peft_model.md
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!--⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be
|
| 2 |
+
rendered properly in your Markdown viewer.
|
| 3 |
+
-->
|
| 4 |
+
|
| 5 |
+
# Models
|
| 6 |
+
|
| 7 |
+
[`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.
|
| 8 |
+
|
| 9 |
+
## PeftModel
|
| 10 |
+
|
| 11 |
+
[[autodoc]] PeftModel
|
| 12 |
+
- all
|
| 13 |
+
|
| 14 |
+
## PeftModelForSequenceClassification
|
| 15 |
+
|
| 16 |
+
A `PeftModel` for sequence classification tasks.
|
| 17 |
+
|
| 18 |
+
[[autodoc]] PeftModelForSequenceClassification
|
| 19 |
+
- all
|
| 20 |
+
|
| 21 |
+
## PeftModelForTokenClassification
|
| 22 |
+
|
| 23 |
+
A `PeftModel` for token classification tasks.
|
| 24 |
+
|
| 25 |
+
[[autodoc]] PeftModelForTokenClassification
|
| 26 |
+
- all
|
| 27 |
+
|
| 28 |
+
## PeftModelForCausalLM
|
| 29 |
+
|
| 30 |
+
A `PeftModel` for causal language modeling.
|
| 31 |
+
|
| 32 |
+
[[autodoc]] PeftModelForCausalLM
|
| 33 |
+
- all
|
| 34 |
+
|
| 35 |
+
## PeftModelForSeq2SeqLM
|
| 36 |
+
|
| 37 |
+
A `PeftModel` for sequence-to-sequence language modeling.
|
| 38 |
+
|
| 39 |
+
[[autodoc]] PeftModelForSeq2SeqLM
|
| 40 |
+
- all
|
| 41 |
+
|
| 42 |
+
## PeftModelForQuestionAnswering
|
| 43 |
+
|
| 44 |
+
A `PeftModel` for question answering.
|
| 45 |
+
|
| 46 |
+
[[autodoc]] PeftModelForQuestionAnswering
|
| 47 |
+
- all
|
| 48 |
+
|
| 49 |
+
## PeftModelForFeatureExtraction
|
| 50 |
+
|
| 51 |
+
A `PeftModel` for getting extracting features/embeddings from transformer models.
|
| 52 |
+
|
| 53 |
+
[[autodoc]] PeftModelForFeatureExtraction
|
| 54 |
+
- all
|
| 55 |
+
|
| 56 |
+
## PeftMixedModel
|
| 57 |
+
|
| 58 |
+
A `PeftModel` for mixing different adapter types (e.g. LoRA and LoHa).
|
| 59 |
+
|
| 60 |
+
[[autodoc]] PeftMixedModel
|
| 61 |
+
- all
|
| 62 |
+
|
| 63 |
+
## Utilities
|
| 64 |
+
|
| 65 |
+
[[autodoc]] utils.cast_mixed_precision_params
|
| 66 |
+
|
| 67 |
+
[[autodoc]] get_peft_model
|
| 68 |
+
|
| 69 |
+
[[autodoc]] inject_adapter_in_model
|
| 70 |
+
|
| 71 |
+
[[autodoc]] utils.get_peft_model_state_dict
|
| 72 |
+
|
| 73 |
+
[[autodoc]] utils.prepare_model_for_kbit_training
|
| 74 |
+
|
| 75 |
+
[[autodoc]] get_layer_status
|
| 76 |
+
|
| 77 |
+
[[autodoc]] get_model_status
|
tasks/tasksmith-0d2d1e298e86/tests/source/docs/source/package_reference/peft_types.md
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!--Copyright 2023 The HuggingFace Team. All rights reserved.
|
| 2 |
+
|
| 3 |
+
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
|
| 4 |
+
the License. You may obtain a copy of the License at
|
| 5 |
+
|
| 6 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
| 7 |
+
|
| 8 |
+
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
|
| 9 |
+
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
|
| 10 |
+
specific language governing permissions and limitations under the License.
|
| 11 |
+
|
| 12 |
+
⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be
|
| 13 |
+
rendered properly in your Markdown viewer.
|
| 14 |
+
|
| 15 |
+
-->
|
| 16 |
+
|
| 17 |
+
# PEFT types
|
| 18 |
+
|
| 19 |
+
[`PeftType`] includes the supported adapters in PEFT, and [`TaskType`] includes PEFT-supported tasks.
|
| 20 |
+
|
| 21 |
+
## PeftType
|
| 22 |
+
|
| 23 |
+
[[autodoc]] utils.peft_types.PeftType
|
| 24 |
+
|
| 25 |
+
## TaskType
|
| 26 |
+
|
| 27 |
+
[[autodoc]] utils.peft_types.TaskType
|
tasks/tasksmith-0d2d1e298e86/tests/source/docs/source/package_reference/poly.md
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!--Copyright 2024 The HuggingFace Team. All rights reserved.
|
| 2 |
+
|
| 3 |
+
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
|
| 4 |
+
the License. You may obtain a copy of the License at
|
| 5 |
+
|
| 6 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
| 7 |
+
|
| 8 |
+
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
|
| 9 |
+
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
|
| 10 |
+
specific language governing permissions and limitations under the License.
|
| 11 |
+
|
| 12 |
+
⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be
|
| 13 |
+
rendered properly in your Markdown viewer.
|
| 14 |
+
|
| 15 |
+
-->
|
| 16 |
+
|
| 17 |
+
# Polytropon
|
| 18 |
+
|
| 19 |
+
[Polytropon](https://hf.co/papers/2202.13914) is a multitask model with a number of different LoRA adapters in its "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.
|
| 20 |
+
|
| 21 |
+
<hfoptions id="paper">
|
| 22 |
+
<hfoption id="Combining Modular Skills in Multitask Learning">
|
| 23 |
+
|
| 24 |
+
The abstract from the paper is:
|
| 25 |
+
|
| 26 |
+
*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.*
|
| 27 |
+
|
| 28 |
+
</hfoption>
|
| 29 |
+
<hfoption id="Multi-Head Adapter Routing for Cross-Task Generalization">
|
| 30 |
+
|
| 31 |
+
The abstract from the paper is:
|
| 32 |
+
|
| 33 |
+
*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.*.
|
| 34 |
+
|
| 35 |
+
</hfoption>
|
| 36 |
+
</hfoptions>
|
| 37 |
+
|
| 38 |
+
In case you want to try out routing without training first, you can check out the [Arrow LoRA variant](./lora#Arrow).
|
| 39 |
+
|
| 40 |
+
# API
|
| 41 |
+
|
| 42 |
+
## PolyConfig
|
| 43 |
+
|
| 44 |
+
[[autodoc]] tuners.poly.config.PolyConfig
|
| 45 |
+
|
| 46 |
+
## PolyModel
|
| 47 |
+
|
| 48 |
+
[[autodoc]] tuners.poly.model.PolyModel
|
tasks/tasksmith-0d2d1e298e86/tests/source/docs/source/package_reference/prefix_tuning.md
ADDED
|
@@ -0,0 +1,123 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!--Copyright 2023 The HuggingFace Team. All rights reserved.
|
| 2 |
+
|
| 3 |
+
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
|
| 4 |
+
the License. You may obtain a copy of the License at
|
| 5 |
+
|
| 6 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
| 7 |
+
|
| 8 |
+
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
|
| 9 |
+
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
|
| 10 |
+
specific language governing permissions and limitations under the License.
|
| 11 |
+
|
| 12 |
+
⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be
|
| 13 |
+
rendered properly in your Markdown viewer.
|
| 14 |
+
|
| 15 |
+
-->
|
| 16 |
+
|
| 17 |
+
# Prefix tuning
|
| 18 |
+
|
| 19 |
+
<div class="flex justify-center">
|
| 20 |
+
<img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/peft/prefix-tuning.png"/>
|
| 21 |
+
</div>
|
| 22 |
+
<small>Optimize the prefix parameters for each task <a href="https://hf.co/papers/2101.00190">(image source)</a>.</small>
|
| 23 |
+
|
| 24 |
+
[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.
|
| 25 |
+
|
| 26 |
+
The abstract from the paper is:
|
| 27 |
+
|
| 28 |
+
*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*.
|
| 29 |
+
|
| 30 |
+
**Note** For encoder-decoder models (seq2seq), the prefix is only applied to the decoder, which does not correspond to the paper specification (see e.g. Figure 2). Prefix tuning can still be fine-tuned on these model architectures but the performance could be sub-par; consider using other PEFT methods for encoder-decoder models.
|
| 31 |
+
|
| 32 |
+
Prefix tuning is very similar to [prompt tuning](../package_reference/prompt_tuning). 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.
|
| 33 |
+
|
| 34 |
+
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.
|
| 35 |
+
|
| 36 |
+
## Basic Usage
|
| 37 |
+
|
| 38 |
+
Create a [`PrefixTuningConfig`] with the task type and number of virtual tokens to add and learn.
|
| 39 |
+
|
| 40 |
+
```py
|
| 41 |
+
from peft import PrefixTuningConfig, get_peft_model
|
| 42 |
+
|
| 43 |
+
peft_config = PrefixTuningConfig(task_type="CAUSAL_LM", num_virtual_tokens=20)
|
| 44 |
+
model = get_peft_model(model, peft_config)
|
| 45 |
+
model.print_trainable_parameters()
|
| 46 |
+
"trainable params: 983,040 || all params: 560,197,632 || trainable%: 0.1754809274167014"
|
| 47 |
+
```
|
| 48 |
+
|
| 49 |
+
## Possible Initializations
|
| 50 |
+
|
| 51 |
+
By default, prefix tuning uses randomly initialized virtual tokens. There's also the option to initialize the vectors
|
| 52 |
+
to be close to a no-op (initialized to zero, it will still shift the probability mass a bit).
|
| 53 |
+
This means that the KV-cache injected prefixes have less impact from the beginning and reduces the variance in training
|
| 54 |
+
performance.
|
| 55 |
+
|
| 56 |
+
PEFT also provides utilities to initialize a prefix-tuning adapter from an existing KV cache prefix (for example, from
|
| 57 |
+
the first `p` tokens of a prompt/corpus). This is only supported when `prefix_projection=False` (the default), because
|
| 58 |
+
in that case the learned parameters are the KV prefix itself.
|
| 59 |
+
|
| 60 |
+
```py
|
| 61 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 62 |
+
|
| 63 |
+
from peft import PrefixTuningConfig, get_peft_model, initialize_kv_prefix_from_text
|
| 64 |
+
|
| 65 |
+
base = AutoModelForCausalLM.from_pretrained("gpt2")
|
| 66 |
+
tok = AutoTokenizer.from_pretrained("gpt2")
|
| 67 |
+
|
| 68 |
+
peft_cfg = PrefixTuningConfig(task_type="CAUSAL_LM", num_virtual_tokens=20, prefix_projection=False)
|
| 69 |
+
model = get_peft_model(base, peft_cfg)
|
| 70 |
+
|
| 71 |
+
initialize_kv_prefix_from_text(
|
| 72 |
+
model,
|
| 73 |
+
tok,
|
| 74 |
+
text="...a long context with at least num_virtual_tokens tokens...",
|
| 75 |
+
use_chat_template=False,
|
| 76 |
+
)m peft import PrefixTuningConfig, get_peft_model, initialize_kv_prefix_from_text
|
| 77 |
+
|
| 78 |
+
base = AutoModelForCausalLM.from_pretrained("gpt2")
|
| 79 |
+
tok = AutoTokenizer.from_pretrained("gpt2")
|
| 80 |
+
|
| 81 |
+
peft_cfg = PrefixTuningConfig(task_type="CAUSAL_LM", num_virtual_tokens=20, prefix_projection=False)
|
| 82 |
+
model = get_peft_model(base, peft_cfg)
|
| 83 |
+
|
| 84 |
+
initialize_kv_prefix_from_text(
|
| 85 |
+
model,
|
| 86 |
+
tok,
|
| 87 |
+
text="...a long context with at least num_virtual_tokens tokens...",
|
| 88 |
+
use_chat_template=False,
|
| 89 |
+
)
|
| 90 |
+
|
| 91 |
+
```
|
| 92 |
+
|
| 93 |
+
Make sure the text is long enough to produce at least `num_virtual_tokens` tokens, otherwise initialization will fail.
|
| 94 |
+
|
| 95 |
+
As a guideline:
|
| 96 |
+
|
| 97 |
+
* start with a neutral starting sequence using `initialize_kv_prefix_from_text`, it can be a very short string like
|
| 98 |
+
"Question: "
|
| 99 |
+
* if that doesn't help, use a longer sequence with task relevance (i.e. an engineered prompt), giving you more virtual
|
| 100 |
+
tokens to fit but also more steering of the model
|
| 101 |
+
* if it is not possible to use an initialization text or you want to quickly check if prefix tuning is viable at all,
|
| 102 |
+
use a zero init without projection
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
## Benchmark overview
|
| 106 |
+
|
| 107 |
+
<iframe
|
| 108 |
+
src="https://peft-internal-testing-peft-method-comparison-embed.hf.space/?highlight[type]=PREFIX_TUNING"
|
| 109 |
+
frameborder="0"
|
| 110 |
+
width="850"
|
| 111 |
+
height="1000"
|
| 112 |
+
></iframe>
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
# API
|
| 116 |
+
|
| 117 |
+
## PrefixTuningConfig
|
| 118 |
+
|
| 119 |
+
[[autodoc]] tuners.prefix_tuning.config.PrefixTuningConfig
|
| 120 |
+
|
| 121 |
+
## PrefixEncoder
|
| 122 |
+
|
| 123 |
+
[[autodoc]] tuners.prefix_tuning.model.PrefixEncoder
|
tasks/tasksmith-0d2d1e298e86/tests/source/docs/source/package_reference/prompt_tuning.md
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!--Copyright 2023 The HuggingFace Team. All rights reserved.
|
| 2 |
+
|
| 3 |
+
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
|
| 4 |
+
the License. You may obtain a copy of the License at
|
| 5 |
+
|
| 6 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
| 7 |
+
|
| 8 |
+
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
|
| 9 |
+
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
|
| 10 |
+
specific language governing permissions and limitations under the License.
|
| 11 |
+
|
| 12 |
+
⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be
|
| 13 |
+
rendered properly in your Markdown viewer.
|
| 14 |
+
|
| 15 |
+
-->
|
| 16 |
+
|
| 17 |
+
# Prompt tuning
|
| 18 |
+
|
| 19 |
+
<div class="flex justify-center">
|
| 20 |
+
<img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/peft/prompt-tuning.png"/>
|
| 21 |
+
</div>
|
| 22 |
+
<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>
|
| 23 |
+
|
| 24 |
+
[Prompt tuning](https://hf.co/papers/2104.08691) adds a task-specific, virtual prompt to the input that consists of trainable vectors in the embedding space. The virtual token parameters are updated independently of the pretrained model parameters which are frozen.
|
| 25 |
+
|
| 26 |
+
The abstract from the paper is:
|
| 27 |
+
|
| 28 |
+
*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*.
|
| 29 |
+
|
| 30 |
+
In contrast to [prefix tuning](../package_reference/prefix_tuning), only the
|
| 31 |
+
input of the first layer receives the virtual tokens.
|
| 32 |
+
|
| 33 |
+
## Usage
|
| 34 |
+
|
| 35 |
+
There are two decisions to take: how many virtual tokens are added to the
|
| 36 |
+
input of the model (`num_virtual_tokens`) - this will define how many
|
| 37 |
+
trainable parameters there will be - and how these tokens are initialized.
|
| 38 |
+
|
| 39 |
+
Create a [`PromptTuningConfig`] with the task type, the initial prompt tuning text to train the model with, the number of virtual tokens to add and learn, and a tokenizer.
|
| 40 |
+
|
| 41 |
+
```py
|
| 42 |
+
from peft import PromptTuningConfig, PromptTuningInit, get_peft_model
|
| 43 |
+
|
| 44 |
+
prompt_tuning_init_text = "Classify if the tweet is a complaint or no complaint.\n"
|
| 45 |
+
peft_config = PromptTuningConfig(
|
| 46 |
+
task_type="CAUSAL_LM",
|
| 47 |
+
prompt_tuning_init=PromptTuningInit.TEXT,
|
| 48 |
+
num_virtual_tokens=len(tokenizer(prompt_tuning_init_text)["input_ids"]),
|
| 49 |
+
prompt_tuning_init_text=prompt_tuning_init_text,
|
| 50 |
+
tokenizer_name_or_path="bigscience/bloomz-560m",
|
| 51 |
+
)
|
| 52 |
+
model = get_peft_model(model, peft_config)
|
| 53 |
+
model.print_trainable_parameters()
|
| 54 |
+
"trainable params: 8,192 || all params: 559,222,784 || trainable%: 0.0014648902430985358"
|
| 55 |
+
```
|
| 56 |
+
|
| 57 |
+
## Benchmark overview
|
| 58 |
+
|
| 59 |
+
<iframe
|
| 60 |
+
src="https://peft-internal-testing-peft-method-comparison-embed.hf.space/?highlight[type]=PROMPT_TUNING"
|
| 61 |
+
frameborder="0"
|
| 62 |
+
width="850"
|
| 63 |
+
height="1000"
|
| 64 |
+
></iframe>
|
| 65 |
+
|
| 66 |
+
# API
|
| 67 |
+
|
| 68 |
+
## PromptTuningConfig
|
| 69 |
+
|
| 70 |
+
[[autodoc]] tuners.prompt_tuning.config.PromptTuningConfig
|
| 71 |
+
|
| 72 |
+
## PromptEmbedding
|
| 73 |
+
|
| 74 |
+
[[autodoc]] tuners.prompt_tuning.model.PromptEmbedding
|
tasks/tasksmith-0d2d1e298e86/tests/source/docs/source/package_reference/psoft.md
ADDED
|
@@ -0,0 +1,139 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!--Copyright 2026 The HuggingFace Team. All rights reserved.
|
| 2 |
+
|
| 3 |
+
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
|
| 4 |
+
the License. You may obtain a copy of the License at
|
| 5 |
+
|
| 6 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
| 7 |
+
|
| 8 |
+
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
|
| 9 |
+
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
|
| 10 |
+
specific language governing permissions and limitations under the License.
|
| 11 |
+
|
| 12 |
+
⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be
|
| 13 |
+
rendered properly in your Markdown viewer.
|
| 14 |
+
|
| 15 |
+
-->
|
| 16 |
+
|
| 17 |
+
# PSOFT
|
| 18 |
+
|
| 19 |
+
[PSOFT](https://hf.co/papers/2505.11235) is an Orthogonal Fine-Tuning (OFT)-based parameter-efficient fine-tuning method that preserves the geometric relationships of pre-trained weight column vectors while achieving a balanced trade-off between performance and multi-dimensional efficiency, including parameter count, memory usage, and computational cost. By restricting orthogonal transformations to a low-rank principal subspace derived from pre-trained weights, PSOFT bridges the gap between LoRA and OFT, providing both theoretical guarantees and practical adaptability. Its effectiveness is validated through extensive evaluations on diverse benchmarks, including GLUE, VTAB-1K, GSM8K, MATH, and commonsense reasoning benchmarks.
|
| 20 |
+
|
| 21 |
+
- Only `nn.Linear` layers are supported.
|
| 22 |
+
- Quantized layers are not supported.
|
| 23 |
+
|
| 24 |
+
The abstract from the paper is:
|
| 25 |
+
|
| 26 |
+
*Driven by the rapid growth of model parameters, parameter-efficient fine-tuning (PEFT) has become essential for adapting large models to diverse downstream tasks under constrained computational resources. Within this paradigm, orthogonal fine-tuning and its variants preserve semantic representations of pre-trained models, but struggle to achieve both expressiveness and efficiency in terms of parameter counts, memory, and computation. To overcome this limitation, we propose efficient Orthogonal Fine-Tuning with Principal Subspace adaptation (PSOFT), which confines orthogonal transformations to the principal subspace of pre-trained weights. Specifically, PSOFT constructs this subspace via matrix decomposition to enable compatible transformations, establishes a theoretical condition that strictly maintains the geometry of this subspace for essential semantic preservation, and introduces efficient tunable vectors that gradually relax orthogonality during training to enhance adaptability. Extensive experiments on 35 NLP and CV tasks across four representative models demonstrate that PSOFT offers a practical and scalable solution to simultaneously achieve semantic preservation, expressiveness, and multi-dimensional efficiency in PEFT.*
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
## How PSOFT Works
|
| 30 |
+
|
| 31 |
+
PSOFT decomposes each weight matrix $W_{pre}$ into $W_{pri}$ and $W_{res}$ using SVD:
|
| 32 |
+
$W_{\text{pre}} = U S V^\top$
|
| 33 |
+
|
| 34 |
+
The principal subspace $W_{\text{pri}} = U_r S_r V_r^\top = AB$ is constructed from the top-$r$ singular components:
|
| 35 |
+
|
| 36 |
+
$W_{\text{pre}} = W_{\text{pri}} + W_{\text{res}} = AB + W_{\text{res}},$
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
$W_{\text{ps-tuned}} = ARB + W_{\text{res}}.$ (PSOFT-SO: PSOFT with strict orthogonality)
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
$W_{\text{ps-tuned}} = A \, \mathrm{diag}(\alpha) \, R \, \mathrm{diag}(\beta) \, B + W_{\text{res}}.$ (PSOFT-RO: PSOFT with relaxed orthogonality)
|
| 43 |
+
|
| 44 |
+
During training, $A$, $B$, and $W_{\text{res}}$ are frozen, and only $R$ (or $R$ with $\alpha$ and $\beta$) is trainable.
|
| 45 |
+
|
| 46 |
+
For compatibility with the PEFT framework (which expects additive weight updates), PSOFT is implemented in the following additive form:
|
| 47 |
+
$W_{\text{ps-tuned}} = W_{\text{pre}} + A (R - I_r) B$
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
## Trainable Parameters
|
| 51 |
+
|
| 52 |
+
After applying PSOFT:
|
| 53 |
+
|
| 54 |
+
- The original model weights ($A$, $B$, and $W_{\text{res}}$) are frozen.
|
| 55 |
+
- Only the orthogonal matrix $R$ (and optionally $\alpha$, $\beta$) are trainable.
|
| 56 |
+
- No additional bias parameters are introduced.
|
| 57 |
+
|
| 58 |
+
## Basic Usage
|
| 59 |
+
```python
|
| 60 |
+
import torch
|
| 61 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 62 |
+
from peft import PsoftConfig, get_peft_model
|
| 63 |
+
|
| 64 |
+
# Load base model
|
| 65 |
+
model_id = "facebook/opt-125m"
|
| 66 |
+
model = AutoModelForCausalLM.from_pretrained(model_id)
|
| 67 |
+
|
| 68 |
+
# Configure PSOFT
|
| 69 |
+
config = PsoftConfig(
|
| 70 |
+
r=32, # the dimension of trainable matrix R,
|
| 71 |
+
psoft_alpha=32, # scaling factor (typically set to r in PSOFT),
|
| 72 |
+
target_modules=["q_proj", "v_proj"], # target attention projection layers
|
| 73 |
+
ab_svd_init="psoft_init", # principal subspace initialization
|
| 74 |
+
psoft_svd="full", # SVD method
|
| 75 |
+
psoft_orth=True, # enable orthogonal R (Cayley parameterization)
|
| 76 |
+
psoft_mag_a=True, # enable tunable vector alpha
|
| 77 |
+
psoft_mag_b=True, # enable tunable vector beta
|
| 78 |
+
use_cayley_neumann=False, # disable Cayley–Neumann approximation
|
| 79 |
+
num_cayley_neumann_terms=5, # number of Neumann series terms
|
| 80 |
+
cayley_neumann_eps=None, # improve numerical stability
|
| 81 |
+
)
|
| 82 |
+
|
| 83 |
+
# Apply PSOFT
|
| 84 |
+
model = get_peft_model(model, config)
|
| 85 |
+
model.train()
|
| 86 |
+
|
| 87 |
+
tokenizer = AutoTokenizer.from_pretrained(model_id)
|
| 88 |
+
tokenizer.pad_token = tokenizer.eos_token
|
| 89 |
+
|
| 90 |
+
# Train
|
| 91 |
+
inputs = tokenizer("Hello world", return_tensors="pt", padding=True)
|
| 92 |
+
loss = model(**inputs, labels=inputs["input_ids"]).loss
|
| 93 |
+
loss.backward()
|
| 94 |
+
|
| 95 |
+
trainable = [p for p in model.parameters() if p.requires_grad]
|
| 96 |
+
optimizer = torch.optim.AdamW(trainable, lr=5e-4)
|
| 97 |
+
optimizer.step()
|
| 98 |
+
optimizer.zero_grad(set_to_none=True)
|
| 99 |
+
```
|
| 100 |
+
## Configuration Options
|
| 101 |
+
|
| 102 |
+
### Different Mode
|
| 103 |
+
|
| 104 |
+
(PSOFT-SO: PSOFT with strict orthogonality)
|
| 105 |
+
|
| 106 |
+
```python
|
| 107 |
+
config = PsoftConfig(psoft_orth=True,psoft_mag_a=False,psoft_mag_b=False)
|
| 108 |
+
```
|
| 109 |
+
|
| 110 |
+
(PSOFT-RO: PSOFT with relaxed orthogonality)
|
| 111 |
+
```python
|
| 112 |
+
config = PsoftConfig(psoft_orth=True,psoft_mag_a=True,psoft_mag_b=True)
|
| 113 |
+
```
|
| 114 |
+
|
| 115 |
+
### Best Practices
|
| 116 |
+
1. **Rank Choice**: Smaller ranks (e.g., `32–128`) are suitable for simpler tasks, while larger ranks (e.g., `64–256`) provide greater expressiveness for more complex tasks at the cost of increased parameters and computation.
|
| 117 |
+
2. **Scaling Factor**: The scaling factor is typically set to $r$ in PSOFT.
|
| 118 |
+
3. **Learning Rate**: Use standard learning rates (e.g., `1e-4` to `5e-3`) for stable training.
|
| 119 |
+
4. **SVD Initialization**: The `lowrank` option is more memory- and compute-efficient than `full`, making it more suitable for large models.
|
| 120 |
+
5. **Cayley–Neumann Approximation**: When the rank is large, enabling the Cayley–Neumann approximation can significantly improve computational efficiency, while the benefit is less pronounced for small ranks. In practice, a small number of Neumann series terms (typically `5`) usually provides a good balance between accuracy and efficiency.
|
| 121 |
+
|
| 122 |
+
## Benchmark overview
|
| 123 |
+
|
| 124 |
+
<iframe
|
| 125 |
+
src="https://peft-internal-testing-peft-method-comparison-embed.hf.space/?highlight[type]=PSOFT"
|
| 126 |
+
frameborder="0"
|
| 127 |
+
width="850"
|
| 128 |
+
height="1000"
|
| 129 |
+
></iframe>
|
| 130 |
+
|
| 131 |
+
# API
|
| 132 |
+
|
| 133 |
+
## PsoftConfig
|
| 134 |
+
|
| 135 |
+
[[autodoc]] tuners.psoft.config.PsoftConfig
|
| 136 |
+
|
| 137 |
+
## PsoftModel
|
| 138 |
+
|
| 139 |
+
[[autodoc]] tuners.psoft.model.PsoftModel
|
tasks/tasksmith-0d2d1e298e86/tests/source/docs/source/package_reference/pvera.md
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!--Copyright 2025 The HuggingFace Team. All rights reserved.
|
| 2 |
+
|
| 3 |
+
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
|
| 4 |
+
the License. You may obtain a copy of the License at
|
| 5 |
+
|
| 6 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
| 7 |
+
|
| 8 |
+
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
|
| 9 |
+
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
|
| 10 |
+
specific language governing permissions and limitations under the License.
|
| 11 |
+
|
| 12 |
+
⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be
|
| 13 |
+
rendered properly in your Markdown viewer.
|
| 14 |
+
|
| 15 |
+
-->
|
| 16 |
+
|
| 17 |
+
# PVeRA: Probabilistic Vector-Based Random Matrix Adaptation
|
| 18 |
+
|
| 19 |
+
[PVeRA](https://huggingface.co/papers/2512.07703) is a parameter-efficient fine-tuning technique that is base on VeRA, in the family of the LoRA-based adapters. It keeps the very low parameter budget of VeRA, but increases the performance by learning a distribution of latent adaptations. This also enables models adapted with PVeRA to generate Monte Carlo confidence interval estimates, by sampling from the learned distribution at inference.
|
| 20 |
+
|
| 21 |
+
When saving the adapter parameters, it's possible to eschew storing the low rank matrices by setting `save_projection=False` on the `PveraConfig`. 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).
|
| 22 |
+
|
| 23 |
+
To handle different shapes of adapted layers, PVeRA 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.
|
| 24 |
+
|
| 25 |
+
PVeRA currently has the following constraint:
|
| 26 |
+
|
| 27 |
+
- Only `nn.Linear` layers are supported.
|
| 28 |
+
- The latent representation is not easily accessible, for training using the KL divergence.
|
| 29 |
+
|
| 30 |
+
The abstract from the paper is:
|
| 31 |
+
|
| 32 |
+
> Large foundation models have emerged in the last years and are pushing performance boundaries for a variety of tasks. Training or even finetuning such models demands vast datasets and computational resources, which are often scarce and costly. Adaptation methods provide a computationally efficient solution to address these limitations by allowing such models to be finetuned on small amounts of data and computing power. This is achieved by appending new trainable modules to frozen backbones with only a fraction of the trainable parameters and fitting only these modules on novel tasks. Recently, the VeRA adapter was shown to excel in parameter-efficient adaptations by utilizing a pair of frozen random low-rank matrices shared across all layers. In this paper, we propose PVeRA, a probabilistic version of the VeRA adapter, which modifies the low-rank matrices of VeRA in a probabilistic manner. This modification naturally allows handling inherent ambiguities in the input and allows for different sampling configurations during training and testing. A comprehensive evaluation was performed on the VTAB-1k benchmark and seven adapters, with PVeRA outperforming VeRA and other adapters.
|
| 33 |
+
|
| 34 |
+
## Benchmark overview
|
| 35 |
+
|
| 36 |
+
<iframe
|
| 37 |
+
src="https://peft-internal-testing-peft-method-comparison-embed.hf.space/?highlight[type]=PVERA"
|
| 38 |
+
frameborder="0"
|
| 39 |
+
width="850"
|
| 40 |
+
height="1000"
|
| 41 |
+
></iframe>
|
| 42 |
+
|
| 43 |
+
# API
|
| 44 |
+
|
| 45 |
+
## PveraConfig
|
| 46 |
+
|
| 47 |
+
[[autodoc]] tuners.pvera.config.PveraConfig
|
| 48 |
+
|
| 49 |
+
## PveraModel
|
| 50 |
+
|
| 51 |
+
[[autodoc]] tuners.pvera.model.PveraModel
|
tasks/tasksmith-0d2d1e298e86/tests/source/docs/source/package_reference/randlora.md
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!--Copyright 2025 The HuggingFace Team. All rights reserved.
|
| 2 |
+
|
| 3 |
+
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
|
| 4 |
+
the License. You may obtain a copy of the License at
|
| 5 |
+
|
| 6 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
| 7 |
+
|
| 8 |
+
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
|
| 9 |
+
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
|
| 10 |
+
specific language governing permissions and limitations under the License.
|
| 11 |
+
|
| 12 |
+
⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be
|
| 13 |
+
rendered properly in your Markdown viewer.
|
| 14 |
+
|
| 15 |
+
-->
|
| 16 |
+
|
| 17 |
+
# RandLora: Full-rank parameter-efficient fine-tuning of large models
|
| 18 |
+
[RandLora](https://huggingface.co/papers/2502.00987) is a parameter-efficient fine-tuning technique that is similar to [LoRA](https://huggingface.co/papers/2106.09685) and [VeRA](https://huggingface.co/papers/2310.11454) but performs full rank updates to improve performance. RandLora can be particularly useful when adapting large model to hard tasks that require complex updates while preserving the parameter efficiency of LoRA. The full rank update of RandLora is achieved by linearly scaling random bases. The random bases are a collection of multiple low rank matrices such that the summation of their ranks if greater or equal to the full rank of the parameter matrices. The trainable parameters of RandLora are two diagonal matrices (vectors) that get multiplied with the right hand low rank random bases, in a similar way to VeRA's update. To maintain low memory usage, RandLora uses a custom function that prevents storing unnecessary bases in memory for backpropagation.
|
| 19 |
+
|
| 20 |
+
RandLora presents the noteworthy difference that contrary to other LoRA-like PEFT algorithm, increasing RandLora's random base ranks increases the amount of trainable parameters. Because number of bases x bases rank is constant in RandLora, reducing the rank will increase the number of random bases, hence the number of base-specific trainable diagonal bases.
|
| 21 |
+
|
| 22 |
+
Because reducing the rank of RandLora's random bases will increase their number, RandLora can become slower to train than LoRA for very small ranks where typically, ranks below 4 with result in a large training time increase. This does not affect inference though as the RandLora adapters can be merged into the pretrained weight matrices.
|
| 23 |
+
|
| 24 |
+
RandLora additionally supports training with sparse, ternary random bases (only containing -1, 0 and 1). These bases are as described in [Bingham et al.](https://cs-people.bu.edu/evimaria/cs565/kdd-rp.pdf) and [Ping et al.](https://hastie.su.domains/Papers/Ping/KDD06_rp.pdf) and could theoretically be used to reduce compute needs by performing aggregations instead of matrix multiplications to create the weight update. This is not currently supported. Although it does not currently reduce compute, using sparse random bases in RandLora can reduce overfitting in some cases. For users interested in using sparse ternary bases, the `sparse` option is recommended over the `very_sparse` one that can reduce performance.
|
| 25 |
+
|
| 26 |
+
Similarly to VeRA, when saving the RandLora's 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).
|
| 27 |
+
|
| 28 |
+
As in Vera and to handle different shapes of adapted layers, RandLora 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.
|
| 29 |
+
|
| 30 |
+
RandLora currently has the following constraint:
|
| 31 |
+
|
| 32 |
+
- Only `nn.Linear` layers are supported.
|
| 33 |
+
|
| 34 |
+
The abstract from the paper is:
|
| 35 |
+
|
| 36 |
+
> Low-Rank Adaptation (LoRA) and its variants have shown impressive results in reducing the number of trainable parameters and memory requirements of large transformer networks while maintaining fine-tuning performance. The low-rank nature of the weight update inherently limits the representation power of fine-tuned models, however, thus potentially compromising performance on complex tasks. This raises a critical question: when a performance gap between LoRA and standard fine-tuning is observed, is it due to the reduced number of trainable parameters or the rank deficiency?
|
| 37 |
+
This paper aims to answer this question by introducing RandLora, a parameter-efficient method that performs full-rank updates using a learned linear combinations of low-rank, non-trainable random matrices. Our method limits the number of trainable parameters by restricting optimization to diagonal scaling matrices applied to the fixed random matrices. This allows us to effectively overcome the low-rank limitations while maintaining parameter and memory efficiency during training. Through extensive experimentation across vision, language, and vision-language benchmarks, we systematically evaluate the limitations of LoRA and existing random basis methods. Our findings reveal that full-rank updates are beneficial across vision and language tasks individually, and even more so for vision-language tasks, where RandLora significantly reduces---and sometimes eliminates---the performance gap between standard fine-tuning and LoRA, demonstrating its efficacy.
|
| 38 |
+
|
| 39 |
+
## Benchmark overview
|
| 40 |
+
|
| 41 |
+
<iframe
|
| 42 |
+
src="https://peft-internal-testing-peft-method-comparison-embed.hf.space/?highlight[type]=RANDLORA"
|
| 43 |
+
frameborder="0"
|
| 44 |
+
width="850"
|
| 45 |
+
height="1000"
|
| 46 |
+
></iframe>
|
| 47 |
+
|
| 48 |
+
# API
|
| 49 |
+
|
| 50 |
+
## RandLoraConfig
|
| 51 |
+
|
| 52 |
+
[[autodoc]] tuners.randlora.config.RandLoraConfig
|
| 53 |
+
|
| 54 |
+
## RandLoraModel
|
| 55 |
+
|
| 56 |
+
[[autodoc]] tuners.randlora.model.RandLoraModel
|
tasks/tasksmith-0d2d1e298e86/tests/source/docs/source/package_reference/road.md
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!--Copyright 2025 The HuggingFace Team. All rights reserved.
|
| 2 |
+
|
| 3 |
+
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
|
| 4 |
+
the License. You may obtain a copy of the License at
|
| 5 |
+
|
| 6 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
| 7 |
+
|
| 8 |
+
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
|
| 9 |
+
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
|
| 10 |
+
specific language governing permissions and limitations under the License.
|
| 11 |
+
|
| 12 |
+
⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be
|
| 13 |
+
rendered properly in your Markdown viewer.
|
| 14 |
+
|
| 15 |
+
-->
|
| 16 |
+
|
| 17 |
+
# RoAd
|
| 18 |
+
|
| 19 |
+
[RoAd](https://huggingface.co/papers/2409.00119) is a parameter‑efficient fine‑tuning technique that adapts large language models by learning a small set of 2×2 rotation matrices (and optional scaling factors) applied to pairs of hidden dimensions. RoAd achieves competitive or superior performance compared to other PEFT methods with under 0.1% trainable parameters. Unlike LoRA’s batched low‑rank updates, RoAd’s sparse rotations reformulate to simple element‑wise operations, yielding significantly higher serving throughput when handling heterogeneous requests in the same batch, i.e. serving multiple adapters simultaneously. Moreover, RoAd integrates seamlessly into a distributed interchange intervention framework, interpreting its sparse 2D rotations as task-specific interventions within learned subspaces of hidden representations. These orthogonal subspaces can be composed to merge multiple task-specific behaviors—like multilingual capabilities or instruction following—without additional fine-tuning, enabling modular, interpretable adaptations in LLMs.
|
| 20 |
+
|
| 21 |
+
Finetuning with RoAd typically requires higher learning rate compared to LoRA or similar methods, around 1e-3. Currently RoAd only supports linear layers and it can be used on models quantized with bitsandbytes (4-bit or 8-bit).
|
| 22 |
+
|
| 23 |
+
For running inference with different RoAd adapters in the same batch see [Inference with different LoRA adapters in the same batch](lora#inference-with-different-lora-adapters-in-the-same-batch).
|
| 24 |
+
|
| 25 |
+
## Benchmark overview
|
| 26 |
+
|
| 27 |
+
<iframe
|
| 28 |
+
src="https://peft-internal-testing-peft-method-comparison-embed.hf.space/?highlight[type]=ROAD"
|
| 29 |
+
frameborder="0"
|
| 30 |
+
width="850"
|
| 31 |
+
height="1000"
|
| 32 |
+
></iframe>
|
| 33 |
+
|
| 34 |
+
# API
|
| 35 |
+
|
| 36 |
+
## RoadConfig
|
| 37 |
+
|
| 38 |
+
[[autodoc]] tuners.road.config.RoadConfig
|
| 39 |
+
|
| 40 |
+
## RoadModel
|
| 41 |
+
|
| 42 |
+
[[autodoc]] tuners.road.model.RoadModel
|
tasks/tasksmith-0d2d1e298e86/tests/source/docs/source/package_reference/shira.md
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!--Copyright 2025 The HuggingFace Team. All rights reserved.
|
| 2 |
+
|
| 3 |
+
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
|
| 4 |
+
the License. You may obtain a copy of the License at
|
| 5 |
+
|
| 6 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
| 7 |
+
|
| 8 |
+
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
|
| 9 |
+
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
|
| 10 |
+
specific language governing permissions and limitations under the License.
|
| 11 |
+
|
| 12 |
+
⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be
|
| 13 |
+
rendered properly in your Markdown viewer.
|
| 14 |
+
|
| 15 |
+
-->
|
| 16 |
+
|
| 17 |
+
# Sparse High Rank Adapters
|
| 18 |
+
|
| 19 |
+
Sparse High Rank Adapters or [SHiRA](https://huggingface.co/papers/2406.13175) is an alternate type of adapter and has been found to have significant advantages over the low rank adapters. Specifically, SHiRA achieves better accuracy than LoRA for a variety of vision and language tasks. It also offers simpler and higher quality multi-adapter fusion by significantly reducing concept loss, a common problem faced by low rank adapters. SHiRA directly finetunes a small number of the base model's parameters to finetune the model on any adaptation task.
|
| 20 |
+
|
| 21 |
+
SHiRA currently has the following constraint:
|
| 22 |
+
|
| 23 |
+
- Only `nn.Linear` layers are supported.
|
| 24 |
+
|
| 25 |
+
The abstract from the paper is:
|
| 26 |
+
|
| 27 |
+
> Low Rank Adaptation (LoRA) has gained massive attention in the recent generative AI research. One of the main advantages of LoRA is its ability to be fused with pretrained models, adding no overhead during inference. However, from a mobile deployment standpoint, we can either avoid inference overhead in the fused mode but lose the ability to switch adapters rapidly, or suffer significant (up to 30% higher) inference latency while enabling rapid switching in the unfused mode. LoRA also exhibits concept-loss when multiple adapters are used concurrently. In this paper, we propose Sparse High Rank Adapters (SHiRA), a new paradigm which incurs no inference overhead, enables rapid switching, and significantly reduces concept-loss. Specifically, SHiRA can be trained by directly tuning only 1-2% of the base model weights while leaving others unchanged. This results in a highly sparse adapter which can be switched directly in the fused mode. We further provide theoretical and empirical insights on how high sparsity in SHiRA can aid multi-adapter fusion by reducing concept loss. Our extensive experiments on LVMs and LLMs demonstrate that finetuning only a small fraction of the parameters in the base model significantly outperforms LoRA while enabling both rapid switching and multi-adapter fusion. Finally, we provide a latency- and memory-efficient SHiRA implementation based on Parameter-Efficient Finetuning (PEFT) Library which trains at nearly the same speed as LoRA while consuming up to 16% lower peak GPU memory, thus making SHiRA easy to adopt for practical use cases. To demonstrate rapid switching benefits during inference, we show that loading SHiRA on a base model can be 5x-16x faster than LoRA fusion on a CPU.
|
| 28 |
+
|
| 29 |
+
## Benchmark overview
|
| 30 |
+
|
| 31 |
+
<iframe
|
| 32 |
+
src="https://peft-internal-testing-peft-method-comparison-embed.hf.space/?highlight[type]=SHIRA"
|
| 33 |
+
frameborder="0"
|
| 34 |
+
width="850"
|
| 35 |
+
height="1000"
|
| 36 |
+
></iframe>
|
| 37 |
+
|
| 38 |
+
# API
|
| 39 |
+
|
| 40 |
+
## ShiraConfig
|
| 41 |
+
|
| 42 |
+
[[autodoc]] tuners.shira.config.ShiraConfig
|
| 43 |
+
|
| 44 |
+
## ShiraModel
|
| 45 |
+
|
| 46 |
+
[[autodoc]] tuners.shira.model.ShiraModel
|
tasks/tasksmith-0d2d1e298e86/tests/source/docs/source/package_reference/tinylora.md
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!--Copyright 2025 The HuggingFace Team. All rights reserved.
|
| 2 |
+
|
| 3 |
+
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
|
| 4 |
+
the License. You may obtain a copy of the License at
|
| 5 |
+
|
| 6 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
| 7 |
+
|
| 8 |
+
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
|
| 9 |
+
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
|
| 10 |
+
specific language governing permissions and limitations under the License.
|
| 11 |
+
|
| 12 |
+
⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be
|
| 13 |
+
rendered properly in your Markdown viewer.
|
| 14 |
+
|
| 15 |
+
-->
|
| 16 |
+
|
| 17 |
+
# TinyLoRA: Learning to Reason in 13 Parameters
|
| 18 |
+
|
| 19 |
+
[TinyLoRA](https://huggingface.co/papers/2602.04118) is an extremely parameter-efficient fine-tuning technique that builds upon the [LoRA-XS](https://huggingface.co/papers/2405.17604) approach by using SVD decomposition of frozen weights and projecting a tiny trainable vector through fixed random tensors. When combined with reinforcement learning (RL) training methods like GRPO, TinyLoRA can achieve competitive performance with as few as 1-13 trainable parameters.
|
| 20 |
+
|
| 21 |
+
The key innovation of TinyLoRA is replacing the trainable low-rank matrix R with a weighted sum of fixed random projection matrices: `R = Σᵢ vᵢ Pᵢ`, where `v ∈ R^u` is a tiny trainable vector of dimension `u` and `Pᵢ` are fixed random matrices. This dramatically reduces the number of trainable parameters while maintaining competitive performance.
|
| 22 |
+
|
| 23 |
+
TinyLoRA supports weight tying through the `weight_tying` parameter, a ratio between 0.0 and 1.0 that controls how many modules share the same trainable vector `v`. Setting `weight_tying=0.0` (the default) means no sharing, while `weight_tying=1.0` means full sharing across all target modules — achieving extreme parameter efficiency with just a single vector of `u` trainable parameters for the entire model.
|
| 24 |
+
|
| 25 |
+
When saving the adapter parameters, it's possible to eschew storing the random projection matrices by setting `save_projection=False` on the `TinyLoraConfig`. In that case, these matrices will be restored based on the fixed random seed from the `projection_seed` 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).
|
| 26 |
+
|
| 27 |
+
TinyLoRA currently has the following constraints:
|
| 28 |
+
|
| 29 |
+
- Only `nn.Linear`, `nn.Embedding`, and `transformers.pytorch_utils.Conv1D` layers are supported.
|
| 30 |
+
|
| 31 |
+
The abstract from the paper is:
|
| 32 |
+
|
| 33 |
+
> Recent research has shown that language models can learn to reason, often via reinforcement learning. Some work even trains low-rank parameterizations for reasoning, but conventional LoRA cannot scale below the model dimension. We question whether even rank=1 LoRA is necessary for learning to reason and propose TinyLoRA, a method for scaling low-rank adapters to sizes as small as one parameter. Within our new parameterization, we are able to train the 8B parameter size of Qwen2.5 to 91% accuracy on GSM8K with only 13 trained parameters in bf16 (26 total bytes). We find this trend holds in general: we are able to recover 90% of performance improvements while training 1000x fewer parameters across a suite of more difficult learning-to-reason benchmarks such as AIME, AMC, and MATH500. Notably, we are only able to achieve such strong performance with RL: models trained using SFT require 100-1000x larger updates to reach the same performance.
|
| 34 |
+
|
| 35 |
+
## Benchmark overview
|
| 36 |
+
|
| 37 |
+
<iframe
|
| 38 |
+
src="https://peft-internal-testing-peft-method-comparison-embed.hf.space/?highlight[type]=TINYLORA"
|
| 39 |
+
frameborder="0"
|
| 40 |
+
width="850"
|
| 41 |
+
height="1000"
|
| 42 |
+
></iframe>
|
| 43 |
+
|
| 44 |
+
# API
|
| 45 |
+
|
| 46 |
+
## TinyLoraConfig
|
| 47 |
+
|
| 48 |
+
[[autodoc]] tuners.tinylora.config.TinyLoraConfig
|
| 49 |
+
|
| 50 |
+
## TinyLoraModel
|
| 51 |
+
|
| 52 |
+
[[autodoc]] tuners.tinylora.model.TinyLoraModel
|
tasks/tasksmith-0d2d1e298e86/tests/source/docs/source/package_reference/trainable_tokens.md
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!--Copyright 2025 The HuggingFace Team. All rights reserved.
|
| 2 |
+
|
| 3 |
+
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
|
| 4 |
+
the License. You may obtain a copy of the License at
|
| 5 |
+
|
| 6 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
| 7 |
+
|
| 8 |
+
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
|
| 9 |
+
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
|
| 10 |
+
specific language governing permissions and limitations under the License.
|
| 11 |
+
|
| 12 |
+
⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be
|
| 13 |
+
rendered properly in your Markdown viewer.
|
| 14 |
+
|
| 15 |
+
-->
|
| 16 |
+
|
| 17 |
+
# Trainable Tokens
|
| 18 |
+
|
| 19 |
+
The Trainable Tokens method provides a way to target specific token embeddings for fine-tuning without resorting to
|
| 20 |
+
training the full embedding matrix or using an adapter on the embedding matrix. It is based on the initial implementation from
|
| 21 |
+
[here](https://github.com/huggingface/peft/pull/1541).
|
| 22 |
+
|
| 23 |
+
The method only targets specific tokens and selectively trains the token indices you specify. Consequently the
|
| 24 |
+
required RAM will be lower and disk memory is also significantly lower than storing the full fine-tuned embedding matrix.
|
| 25 |
+
|
| 26 |
+
Some preliminary benchmarks acquired with [this script](https://github.com/huggingface/peft/blob/main/scripts/train_memory.py)
|
| 27 |
+
suggest that for `gemma-2-2b` (which has a rather large embedding matrix) you can save ~4 GiB VRAM with Trainable Tokens
|
| 28 |
+
over fully fine-tuning the embedding matrix. While LoRA will use comparable amounts of VRAM it might also target
|
| 29 |
+
tokens you don't want to be changed. Note that these are just indications and varying embedding matrix sizes might skew
|
| 30 |
+
these numbers a bit.
|
| 31 |
+
|
| 32 |
+
Note that this method does not add tokens for you, you have to add tokens to the tokenizer yourself and resize the
|
| 33 |
+
embedding matrix of the model accordingly. This method will only re-train the embeddings for the tokens you specify.
|
| 34 |
+
This method can also be used in conjunction with LoRA layers! See [the LoRA documentation](lora#efficiently-train-tokens-alongside-lora).
|
| 35 |
+
|
| 36 |
+
> [!TIP]
|
| 37 |
+
> Saving the model with [`~PeftModel.save_pretrained`] or retrieving the state dict using
|
| 38 |
+
> [`get_peft_model_state_dict`] when adding new tokens may save the full embedding matrix instead of only the difference
|
| 39 |
+
> as a precaution because the embedding matrix was resized. To save space you can disable this behavior by setting
|
| 40 |
+
> `save_embedding_layers=False` when calling `save_pretrained`. This is safe to do as long as you don't modify the
|
| 41 |
+
> embedding matrix through other means as well, as such changes will be not tracked by trainable tokens.
|
| 42 |
+
|
| 43 |
+
## Benchmark overview
|
| 44 |
+
|
| 45 |
+
<iframe
|
| 46 |
+
src="https://peft-internal-testing-peft-method-comparison-embed.hf.space/?highlight[type]=TRAINABLE_TOKENS"
|
| 47 |
+
frameborder="0"
|
| 48 |
+
width="850"
|
| 49 |
+
height="1000"
|
| 50 |
+
></iframe>
|
| 51 |
+
|
| 52 |
+
# API
|
| 53 |
+
|
| 54 |
+
## TrainableTokensConfig
|
| 55 |
+
|
| 56 |
+
[[autodoc]] tuners.trainable_tokens.config.TrainableTokensConfig
|
| 57 |
+
|
| 58 |
+
## TrainableTokensModel
|
| 59 |
+
|
| 60 |
+
[[autodoc]] tuners.trainable_tokens.model.TrainableTokensModel
|
| 61 |
+
|
tasks/tasksmith-0d2d1e298e86/tests/source/docs/source/package_reference/tuners.md
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!--Copyright 2023 The HuggingFace Team. All rights reserved.
|
| 2 |
+
|
| 3 |
+
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
|
| 4 |
+
the License. You may obtain a copy of the License at
|
| 5 |
+
|
| 6 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
| 7 |
+
|
| 8 |
+
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
|
| 9 |
+
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
|
| 10 |
+
specific language governing permissions and limitations under the License.
|
| 11 |
+
|
| 12 |
+
⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be
|
| 13 |
+
rendered properly in your Markdown viewer.
|
| 14 |
+
|
| 15 |
+
-->
|
| 16 |
+
|
| 17 |
+
# Tuners
|
| 18 |
+
|
| 19 |
+
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.
|
| 20 |
+
|
| 21 |
+
## BaseTuner
|
| 22 |
+
|
| 23 |
+
[[autodoc]] tuners.tuners_utils.BaseTuner
|
| 24 |
+
|
| 25 |
+
## BaseTunerLayer
|
| 26 |
+
|
| 27 |
+
[[autodoc]] tuners.tuners_utils.BaseTunerLayer
|
tasks/tasksmith-0d2d1e298e86/tests/source/docs/source/package_reference/vblora.md
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!--Copyright 2024 The HuggingFace Team. All rights reserved.
|
| 2 |
+
|
| 3 |
+
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
|
| 4 |
+
the License. You may obtain a copy of the License at
|
| 5 |
+
|
| 6 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
| 7 |
+
|
| 8 |
+
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
|
| 9 |
+
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
|
| 10 |
+
specific language governing permissions and limitations under the License.
|
| 11 |
+
|
| 12 |
+
⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be
|
| 13 |
+
rendered properly in your Markdown viewer.
|
| 14 |
+
|
| 15 |
+
-->
|
| 16 |
+
|
| 17 |
+
# VB-LoRA: Extreme Parameter Efficient Fine-Tuning with Vector Banks
|
| 18 |
+
|
| 19 |
+
## Overview
|
| 20 |
+
|
| 21 |
+
[VB-LoRA](https://huggingface.co/papers/2405.15179) is a parameter-efficient fine-tuning technique that extends LoRA by learning a fine-grained parameter-sharing scheme at the sub-vector level, achieving significantly higher parameter efficiency. This makes VB-LoRA especially useful in scenarios where storage and transmission costs are critical. It works by decomposing low-rank matrices—from different layers and modules such as K, Q, V, and FFN—into sub-vectors, which are then globally shared through a vector bank.
|
| 22 |
+
|
| 23 |
+
The abstract from the paper is:
|
| 24 |
+
|
| 25 |
+
*As the adoption of large language models increases and the need for per-user or per-task model customization grows, the parameter-efficient fine-tuning (PEFT) methods, such as low-rank adaptation (LoRA) and its variants, incur substantial storage and transmission costs. To further reduce stored parameters, we introduce a "divide-and-share" paradigm that breaks the barriers of low-rank decomposition across matrix dimensions, modules and layers by sharing parameters globally via a vector bank. As an instantiation of the paradigm to LoRA, our proposed VB-LoRA composites all the low-rank matrices of LoRA from a shared vector bank with a differentiable top-k admixture module. VB-LoRA achieves extreme parameter efficiency while maintaining comparable or better performance compared to state-of-the-art PEFT methods. Extensive experiments demonstrate the effectiveness of VB-LoRA on natural language understanding, natural language generation, and instruction tuning tasks. When fine-tuning the Llama2-13B model, VB-LoRA only uses 0.4% of LoRA's stored parameters, yet achieves superior results.*
|
| 26 |
+
|
| 27 |
+
## Usage Tips
|
| 28 |
+
|
| 29 |
+
- VB-LoRA utilizes a sparse top-k module to learn the sharing mechanism. When saving adapter parameters, you can either save only the top-k weights and their indices by setting `save_only_topk_weights = True` in `VBLoRAConfig`, or save all the trainable logits by setting it to `False`. Enabling `save_only_topk_weights = True` significantly reduces storage space; for instance, in Llama2-7B, the storage file size decreases from 308MB to 2.5MB. Note that models saved with `save_only_topk_weights = True` are intended for merging or inference only and cannot be used to resume training.
|
| 30 |
+
|
| 31 |
+
- VB-LoRA has two sets of training parameters: vector bank parameters and logit parameters. In practice, we found that logit parameters require a higher learning rate, while vector bank parameters require a lower learning rate. When using the AdamW optimizer, typical learning rates are 0.01 for logits and 0.001 for vector bank parameters.
|
| 32 |
+
|
| 33 |
+
## Benchmark overview
|
| 34 |
+
|
| 35 |
+
<iframe
|
| 36 |
+
src="https://peft-internal-testing-peft-method-comparison-embed.hf.space/?highlight[type]=VBLORA"
|
| 37 |
+
frameborder="0"
|
| 38 |
+
width="850"
|
| 39 |
+
height="1000"
|
| 40 |
+
></iframe>
|
| 41 |
+
|
| 42 |
+
# API
|
| 43 |
+
|
| 44 |
+
## VBLoRAConfig
|
| 45 |
+
|
| 46 |
+
[[autodoc]] tuners.vblora.config.VBLoRAConfig
|
| 47 |
+
|
| 48 |
+
## VBLoRAModel
|
| 49 |
+
|
| 50 |
+
[[autodoc]] tuners.vblora.model.VBLoRAModel
|
| 51 |
+
|
tasks/tasksmith-0d2d1e298e86/tests/source/docs/source/package_reference/vera.md
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!--Copyright 2024 The HuggingFace Team. All rights reserved.
|
| 2 |
+
|
| 3 |
+
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
|
| 4 |
+
the License. You may obtain a copy of the License at
|
| 5 |
+
|
| 6 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
| 7 |
+
|
| 8 |
+
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
|
| 9 |
+
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
|
| 10 |
+
specific language governing permissions and limitations under the License.
|
| 11 |
+
|
| 12 |
+
⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be
|
| 13 |
+
rendered properly in your Markdown viewer.
|
| 14 |
+
|
| 15 |
+
-->
|
| 16 |
+
|
| 17 |
+
# VeRA: Vector-based Random Matrix Adaptation
|
| 18 |
+
|
| 19 |
+
[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.
|
| 20 |
+
|
| 21 |
+
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).
|
| 22 |
+
|
| 23 |
+
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.
|
| 24 |
+
|
| 25 |
+
VeRA currently has the following constraint:
|
| 26 |
+
|
| 27 |
+
- Only `nn.Linear` layers are supported.
|
| 28 |
+
|
| 29 |
+
The abstract from the paper is:
|
| 30 |
+
|
| 31 |
+
> Low-rank adaptation (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.
|
| 32 |
+
|
| 33 |
+
## Benchmark overview
|
| 34 |
+
|
| 35 |
+
<iframe
|
| 36 |
+
src="https://peft-internal-testing-peft-method-comparison-embed.hf.space/?highlight[type]=VERA"
|
| 37 |
+
frameborder="0"
|
| 38 |
+
width="850"
|
| 39 |
+
height="1000"
|
| 40 |
+
></iframe>
|
| 41 |
+
|
| 42 |
+
# API
|
| 43 |
+
|
| 44 |
+
## VeRAConfig
|
| 45 |
+
|
| 46 |
+
[[autodoc]] tuners.vera.config.VeraConfig
|
| 47 |
+
|
| 48 |
+
## VeRAModel
|
| 49 |
+
|
| 50 |
+
[[autodoc]] tuners.vera.model.VeraModel
|
tasks/tasksmith-0d2d1e298e86/tests/source/docs/source/package_reference/waveft.md
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!--Copyright 2025 The HuggingFace Team. All rights reserved.
|
| 2 |
+
|
| 3 |
+
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
|
| 4 |
+
the License. You may obtain a copy of the License at
|
| 5 |
+
|
| 6 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
| 7 |
+
|
| 8 |
+
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
|
| 9 |
+
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
|
| 10 |
+
specific language governing permissions and limitations under the License.
|
| 11 |
+
|
| 12 |
+
⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be
|
| 13 |
+
rendered properly in your Markdown viewer.
|
| 14 |
+
|
| 15 |
+
-->
|
| 16 |
+
|
| 17 |
+
# WaveFT: Wavelet Fine-Tuning
|
| 18 |
+
|
| 19 |
+
[WaveFT](https://huggingface.co/papers/2505.12532) is a novel parameter-efficient fine-tuning (PEFT) method that introduces sparse updates in the **wavelet domain** of residual matrices. Unlike LoRA, which is constrained by discrete low-rank choices, WaveFT enables fine-grained control over the number of trainable parameters by directly learning a sparse set of coefficients in the transformed space. These coefficients are then mapped back to the weight domain via the Inverse Discrete Wavelet Transform (IDWT), producing high-rank updates without incurring inference overhead.
|
| 20 |
+
|
| 21 |
+
WaveFT currently has the following constraint:
|
| 22 |
+
|
| 23 |
+
- Only `nn.Linear` layers are supported.
|
| 24 |
+
|
| 25 |
+
The abstract from the paper is:
|
| 26 |
+
|
| 27 |
+
>Efficiently adapting large foundation models is critical, especially with tight compute and memory budgets. Parameter-Efficient Fine-Tuning (PEFT) methods such as LoRA offer limited granularity and effectiveness in few-parameter regimes. We propose Wavelet Fine-Tuning (WaveFT), a novel PEFT method that learns highly sparse updates in the wavelet domain of residual matrices. WaveFT allows precise control of trainable parameters, offering fine-grained capacity adjustment and excelling with remarkably low parameter count, potentially far fewer than LoRA’s minimum—ideal for extreme parameter-efficient scenarios. Evaluated on personalized text-to-image generation using Stable Diffusion XL as baseline, WaveFT significantly outperforms LoRA and other PEFT methods, especially at low parameter counts; achieving superior subject fidelity, prompt alignment, and image diversity.
|
| 28 |
+
|
| 29 |
+
## Benchmark overview
|
| 30 |
+
|
| 31 |
+
<iframe
|
| 32 |
+
src="https://peft-internal-testing-peft-method-comparison-embed.hf.space/?highlight[type]=WAVEFT"
|
| 33 |
+
frameborder="0"
|
| 34 |
+
width="850"
|
| 35 |
+
height="1000"
|
| 36 |
+
></iframe>
|
| 37 |
+
|
| 38 |
+
# API
|
| 39 |
+
|
| 40 |
+
## WaveFTConfig
|
| 41 |
+
|
| 42 |
+
[[autodoc]] tuners.waveft.config.WaveFTConfig
|
| 43 |
+
|
| 44 |
+
## WaveFTModel
|
| 45 |
+
|
| 46 |
+
[[autodoc]] tuners.waveft.model.WaveFTModel
|
tasks/tasksmith-0d2d1e298e86/tests/source/docs/source/package_reference/xlora.md
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!--Copyright 2023 The HuggingFace Team. All rights reserved.
|
| 2 |
+
|
| 3 |
+
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
|
| 4 |
+
the License. You may obtain a copy of the License at
|
| 5 |
+
|
| 6 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
| 7 |
+
|
| 8 |
+
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
|
| 9 |
+
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
|
| 10 |
+
specific language governing permissions and limitations under the License.
|
| 11 |
+
|
| 12 |
+
⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be
|
| 13 |
+
rendered properly in your Markdown viewer.
|
| 14 |
+
|
| 15 |
+
-->
|
| 16 |
+
|
| 17 |
+
# X-LoRA
|
| 18 |
+
|
| 19 |
+
Mixture of LoRA Experts ([X-LoRA](https://huggingface.co/papers/2402.07148)) is a PEFT method enabling sparse or dense mixture of LoRA experts based on a high granularity (token, layer, sequence) scalings matrix. This leverages frozen LoRA adapters and a frozen base model to drastically reduces the number of parameters that need to be fine-tuned.
|
| 20 |
+
|
| 21 |
+
A unique aspect of X-LoRA is its versatility: it can be applied to any `transformers` base model with LoRA adapters. This means that, despite the mixture of experts strategy, no changes to the model code must be made.
|
| 22 |
+
|
| 23 |
+
The below graphic demonstrates how the scalings change for different prompts for each token. This highlights the activation of different adapters as the generation progresses and the sequence creates new context.
|
| 24 |
+
|
| 25 |
+

|
| 26 |
+
|
| 27 |
+
For each step, X-LoRA requires the base model to be run twice: first, to get hidden states without any LoRA adapters, and secondly, the hidden states are used to calculate scalings which are applied to the LoRA adapters and the model is run a second time. The output of the second run is the result of the model step.
|
| 28 |
+
|
| 29 |
+
Ultimately, X-LoRA allows the model to reflect upon its knowledge because of the dual forward pass scheme, and dynamically reconfigure the architecture.
|
| 30 |
+
|
| 31 |
+
The abstract from the paper is:
|
| 32 |
+
|
| 33 |
+
*We report a mixture of expert strategy to create fine-tuned large language models using a deep layer-wise token-level approach based on low-rank adaptation (LoRA). Starting with a set of pre-trained LoRA adapters, our gating strategy uses the hidden states to dynamically mix adapted layers, allowing the resulting X-LoRA model to draw upon different capabilities and create never-before-used deep layer-wise combinations to solve tasks. The design is inspired by the biological principles of universality and diversity, where neural network building blocks are reused in different hierarchical manifestations. Hence, the X-LoRA model can be easily implemented for any existing large language model (LLM) without a need for modifications of the underlying structure. We develop a tailored X-LoRA model that offers scientific capabilities including forward/inverse analysis tasks and enhanced reasoning capability, focused on biomaterial analysis, protein mechanics and design. The impact of this work include access to readily expandable and adaptable models with strong domain knowledge and the capability to integrate across areas of knowledge. Featuring experts in biology, mathematics, reasoning, bio-inspired materials, mechanics and materials, chemistry, protein biophysics, mechanics and quantum-mechanics based molecular properties, we conduct a series of physics-focused case studies. We examine knowledge recall, protein mechanics forward/inverse tasks, protein design, adversarial agentic modeling including ontological knowledge graph construction, as well as molecular design. The model is capable not only of making quantitative predictions of nanomechanical properties of proteins or quantum mechanical molecular properties, but also reasons over the results and correctly predicts likely mechanisms that explain distinct molecular behaviors.*.
|
| 34 |
+
|
| 35 |
+
Please cite X-LoRA as:
|
| 36 |
+
```bibtex
|
| 37 |
+
@article{10.1063/5.0203126,
|
| 38 |
+
author = {Buehler, Eric L. and Buehler, Markus J.},
|
| 39 |
+
title = "{X-LoRA: Mixture of low-rank adapter experts, a flexible framework for large language models with applications in protein mechanics and molecular design}",
|
| 40 |
+
journal = {APL Machine Learning},
|
| 41 |
+
volume = {2},
|
| 42 |
+
number = {2},
|
| 43 |
+
pages = {026119},
|
| 44 |
+
year = {2024},
|
| 45 |
+
month = {05},
|
| 46 |
+
abstract = "{We report a mixture of expert strategy to create fine-tuned large language models using a deep layer-wise token-level approach based on low-rank adaptation (LoRA). Starting with a set of pre-trained LoRA adapters, our gating strategy uses the hidden states to dynamically mix adapted layers, allowing the resulting X-LoRA model to draw upon different capabilities and create never-before-used deep layer-wise combinations to solve tasks. The design is inspired by the biological principles of universality and diversity, where neural network building blocks are reused in different hierarchical manifestations. Hence, the X-LoRA model can be easily implemented for any existing large language model without a need for modifications of the underlying structure. We develop a tailored X-LoRA model that offers scientific capabilities, including forward/inverse analysis tasks and enhanced reasoning capability, focused on biomaterial analysis, protein mechanics, and design. The impact of this work includes access to readily expandable and adaptable models with strong domain knowledge and the capability to integrate across areas of knowledge. Featuring experts in biology, mathematics, reasoning, bio-inspired materials, mechanics and materials, chemistry, protein biophysics, mechanics, and quantum-mechanics based molecular properties, we conduct a series of physics-focused case studies. We examine knowledge recall, protein mechanics forward/inverse tasks, protein design, adversarial agentic modeling including ontological knowledge graph construction, and molecular design. The model is capable not only of making quantitative predictions of nanomechanical properties of proteins or quantum mechanical molecular properties but also reasoning over the results and correctly predicting likely mechanisms that explain distinct molecular behaviors.}",
|
| 47 |
+
issn = {2770-9019},
|
| 48 |
+
doi = {10.1063/5.0203126},
|
| 49 |
+
url = {https://doi.org/10.1063/5.0203126},
|
| 50 |
+
eprint = {https://pubs.aip.org/aip/aml/article-pdf/doi/10.1063/5.0203126/19964043/026119\_1\_5.0203126.pdf},
|
| 51 |
+
}
|
| 52 |
+
```
|
| 53 |
+
|
| 54 |
+
# API
|
| 55 |
+
|
| 56 |
+
## XLoraConfig
|
| 57 |
+
|
| 58 |
+
[[autodoc]] tuners.xlora.config.XLoraConfig
|
| 59 |
+
|
| 60 |
+
## XLoraModel
|
| 61 |
+
|
| 62 |
+
[[autodoc]] tuners.xlora.model.XLoraModel
|
tasks/tasksmith-0d2d1e298e86/tests/source/docs/source/quicktour.md
ADDED
|
@@ -0,0 +1,230 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!--Copyright 2023 The HuggingFace Team. All rights reserved.
|
| 2 |
+
|
| 3 |
+
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
|
| 4 |
+
the License. You may obtain a copy of the License at
|
| 5 |
+
|
| 6 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
| 7 |
+
|
| 8 |
+
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
|
| 9 |
+
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
|
| 10 |
+
specific language governing permissions and limitations under the License.
|
| 11 |
+
|
| 12 |
+
⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be
|
| 13 |
+
rendered properly in your Markdown viewer.
|
| 14 |
+
|
| 15 |
+
-->
|
| 16 |
+
|
| 17 |
+
# Quicktour
|
| 18 |
+
|
| 19 |
+
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.
|
| 20 |
+
|
| 21 |
+
<div class="flex justify-center">
|
| 22 |
+
<div class="flex flex-col basis-1/4 pt-5">
|
| 23 |
+
<i>PEFT can be thought of as a framework for adding trainable parameters to arbitrary places in existing models ("base models"). Specific PEFT methods arrange the trainable parameters in certain ways or modify the training process to achieve fine-tuning performance comparable to training all parameters of the base model.</i>
|
| 24 |
+
</div>
|
| 25 |
+
<div class="flex flex-col basis-3/4 pl-10 pr-10"><img style="border: 0;box-shadow: none;border-radius: 0;" src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/peft/adapter_installation.png" width="100%"></div>
|
| 26 |
+
</div>
|
| 27 |
+
|
| 28 |
+
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.
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
## PEFT configuration and model
|
| 32 |
+
|
| 33 |
+
For any PEFT method, you'll need to create a configuration which contains all the parameters that specify how the PEFT method should be applied, most importantly which layers of the existing model to target with trainable parameters. Once the configuration is setup, pass it to the [`~peft.get_peft_model`] function along with the base model to create a trainable [`PeftModel`].
|
| 34 |
+
|
| 35 |
+
Let's use [LoRA](./package_reference/lora) as an example but only discuss common parameters - you might want to use one of the [many other PEFT methods](./methods/overview).
|
| 36 |
+
The configuration usually entails this:
|
| 37 |
+
|
| 38 |
+
- `target_modules`: which modules of the base model to adapt
|
| 39 |
+
- `task_type` (default: `None`, see [available `TaskType`s](package_reference/peft_types#peft.TaskType)): the nature of the trained task; if provided may help to automatically save relevant layers alongside the adapter weights or warn you about incompatibilities
|
| 40 |
+
- `inference_mode` (default: `False`): whether you're using the model for inference or not
|
| 41 |
+
|
| 42 |
+
Depending on the PEFT method you choose you will add specific parameters that, for example, determine the size of the update matrices.
|
| 43 |
+
Here's an example of a config you may encounter in the wild:
|
| 44 |
+
|
| 45 |
+
```python
|
| 46 |
+
from peft import LoraConfig, TaskType
|
| 47 |
+
|
| 48 |
+
peft_config = LoraConfig(target_modules=["q_proj"], task_type=TaskType.CAUSAL_LM, inference_mode=False, r=8, lora_alpha=32, lora_dropout=0.1)
|
| 49 |
+
```
|
| 50 |
+
|
| 51 |
+
> [!TIP]
|
| 52 |
+
> See the [configuration guide](guides/peft_model_config) for more details on how the PEFT configuration works under the hood.
|
| 53 |
+
|
| 54 |
+
Once the [`LoraConfig`] is set up, create a [`PeftModel`] with the [`get_peft_model`] function. It takes a base model - which you can (but don't have to) load from the Transformers library - and the [`LoraConfig`] containing the parameters for how to configure a model for training with LoRA.
|
| 55 |
+
|
| 56 |
+
Load the base model you want to finetune.
|
| 57 |
+
|
| 58 |
+
```python
|
| 59 |
+
from transformers import AutoModelForCausalLM
|
| 60 |
+
|
| 61 |
+
model = AutoModelForCausalLM.from_pretrained("meta-llama/Llama-3.2-1B")
|
| 62 |
+
```
|
| 63 |
+
|
| 64 |
+
Now wrap the base model and `peft_config` with the [`get_peft_model`] function to create a [`PeftModel`].
|
| 65 |
+
|
| 66 |
+
<div class="flex justify-center">
|
| 67 |
+
<div class="flex flex-col basis-2/4">
|
| 68 |
+
<p>
|
| 69 |
+
Wrapping means that PEFT replaces the targeted layers (here: all <code>q_proj</code> layers) with the adapter-specific layer for the target layer's type. Since we're dealing with linear layers, it will be, in this case, a <code>lora.Linear</code> layer. <b>Note</b> that these changes are done in-place to save memory, so your base model is now modified.
|
| 70 |
+
</p>
|
| 71 |
+
<p>
|
| 72 |
+
Note that we've only specified <code>q_proj</code> but in actuality we are targeting all <code>model.layers[:].self_attn.q_proj</code> layers. This is because PEFT searches for matching suffixes by default. Pass a string with a regular expression if you want to target more complex layer patterns.
|
| 73 |
+
</p>
|
| 74 |
+
</div>
|
| 75 |
+
<div class="flex flex-col basis-2/4 pl-10 pr-10"><img style="border: 0;box-shadow: none;border-radius: 0;" src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/peft/adapter_attention_targeting.png" width="600px"></div>
|
| 76 |
+
</div>
|
| 77 |
+
|
| 78 |
+
<div class="flex justify-center">
|
| 79 |
+
<div class="flex flex-col basis-2/4 pr-10"><img style="border: 0;box-shadow: none;border-radius: 0;" src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/peft/adapter_layer_wrapping.png" width="1000px"></div>
|
| 80 |
+
<div class="flex flex-col basis-2/4">
|
| 81 |
+
<p>
|
| 82 |
+
The base model's layer will be wrapped, retained and not trained while new, trainable weights are added and are combined. How these new weights are structured and combined with the weights of the base model is a good portion of what sets the different PEFT methods apart.
|
| 83 |
+
</p>
|
| 84 |
+
</div>
|
| 85 |
+
</div>
|
| 86 |
+
|
| 87 |
+
To get a sense of the number of trainable parameters in your model, use the [`print_trainable_parameters`] method.
|
| 88 |
+
|
| 89 |
+
```python
|
| 90 |
+
from peft import get_peft_model
|
| 91 |
+
|
| 92 |
+
peft_model = get_peft_model(model, peft_config)
|
| 93 |
+
peft_model.print_trainable_parameters()
|
| 94 |
+
"output: trainable params: 524,288 || all params: 1,236,338,688 || trainable%: 0.0424"
|
| 95 |
+
```
|
| 96 |
+
|
| 97 |
+
Out of [meta-llama/Llama-3.2-1B's](https://huggingface.co/meta-llama/Llama-3.2-1B) 1B parameters, you're only training 0.04% of them!
|
| 98 |
+
|
| 99 |
+
That is it 🎉! Now you can train the model with the Transformers [`~transformers.Trainer`], Accelerate, or any custom PyTorch training loop.
|
| 100 |
+
|
| 101 |
+
For example, to train with the [`~transformers.Trainer`] class, setup a [`~transformers.TrainingArguments`] class with some training hyperparameters.
|
| 102 |
+
|
| 103 |
+
```py
|
| 104 |
+
training_args = TrainingArguments(
|
| 105 |
+
output_dir="your-name/meta-llama/my-llama3.2-adapter",
|
| 106 |
+
learning_rate=1e-3,
|
| 107 |
+
per_device_train_batch_size=32,
|
| 108 |
+
per_device_eval_batch_size=32,
|
| 109 |
+
num_train_epochs=2,
|
| 110 |
+
weight_decay=0.01,
|
| 111 |
+
eval_strategy="epoch",
|
| 112 |
+
save_strategy="epoch",
|
| 113 |
+
load_best_model_at_end=True,
|
| 114 |
+
)
|
| 115 |
+
```
|
| 116 |
+
|
| 117 |
+
Pass the model, training arguments, dataset, tokenizer, and any other necessary component to the [`~transformers.Trainer`], and call [`~transformers.Trainer.train`] to start training.
|
| 118 |
+
|
| 119 |
+
```py
|
| 120 |
+
trainer = Trainer(
|
| 121 |
+
model=peft_model,
|
| 122 |
+
args=training_args,
|
| 123 |
+
train_dataset=tokenized_datasets["train"],
|
| 124 |
+
eval_dataset=tokenized_datasets["test"],
|
| 125 |
+
data_collator=data_collator,
|
| 126 |
+
compute_metrics=compute_metrics,
|
| 127 |
+
)
|
| 128 |
+
|
| 129 |
+
trainer.train()
|
| 130 |
+
```
|
| 131 |
+
|
| 132 |
+
### Save model
|
| 133 |
+
|
| 134 |
+
After your model is finished training, you can save your model to a directory using the [`~PeftModel.save_pretrained`] function.
|
| 135 |
+
|
| 136 |
+
```py
|
| 137 |
+
peft_model.save_pretrained("output_dir")
|
| 138 |
+
```
|
| 139 |
+
|
| 140 |
+
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.
|
| 141 |
+
|
| 142 |
+
```python
|
| 143 |
+
from huggingface_hub import notebook_login
|
| 144 |
+
|
| 145 |
+
notebook_login()
|
| 146 |
+
peft_model.push_to_hub("your-name/my-llama3.2-adapter")
|
| 147 |
+
```
|
| 148 |
+
|
| 149 |
+
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!
|
| 150 |
+
|
| 151 |
+
<div class="flex flex-col justify-center">
|
| 152 |
+
<img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/peft/PEFT-hub-screenshot.png"/>
|
| 153 |
+
<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>
|
| 154 |
+
</div>
|
| 155 |
+
|
| 156 |
+
## Inference
|
| 157 |
+
|
| 158 |
+
> [!TIP]
|
| 159 |
+
> Take a look at the [AutoPeftModel](package_reference/auto_class) API reference for a complete list of available `AutoPeftModel` classes.
|
| 160 |
+
|
| 161 |
+
Easily load any PEFT-trained model for inference with the [`AutoPeftModel`] class and the [`~transformers.PreTrainedModel.from_pretrained`] method:
|
| 162 |
+
|
| 163 |
+
```py
|
| 164 |
+
from peft import AutoPeftModelForCausalLM
|
| 165 |
+
from transformers import AutoTokenizer
|
| 166 |
+
import torch
|
| 167 |
+
|
| 168 |
+
peft_model = AutoPeftModelForCausalLM.from_pretrained("ybelkada/opt-350m-lora")
|
| 169 |
+
tokenizer = AutoTokenizer.from_pretrained("facebook/opt-350m")
|
| 170 |
+
|
| 171 |
+
peft_model = peft_model.to("cuda")
|
| 172 |
+
peft_model.eval()
|
| 173 |
+
inputs = tokenizer("Preheat the oven to 350 degrees and place the cookie dough", return_tensors="pt")
|
| 174 |
+
|
| 175 |
+
outputs = peft_model.generate(input_ids=inputs["input_ids"].to("cuda"), max_new_tokens=50)
|
| 176 |
+
print(tokenizer.batch_decode(outputs.detach().cpu().numpy(), skip_special_tokens=True)[0])
|
| 177 |
+
|
| 178 |
+
"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."
|
| 179 |
+
```
|
| 180 |
+
|
| 181 |
+
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.
|
| 182 |
+
|
| 183 |
+
```py
|
| 184 |
+
from peft import AutoPeftModel
|
| 185 |
+
|
| 186 |
+
peft_model = AutoPeftModel.from_pretrained("smangrul/openai-whisper-large-v2-LORA-colab")
|
| 187 |
+
```
|
| 188 |
+
|
| 189 |
+
The most general way of loading a trained PEFT adapter onto a model is to use [`~PeftModel.from_pretrained`]:
|
| 190 |
+
|
| 191 |
+
```py
|
| 192 |
+
from transformers import AutoPeftModelForCausalLM
|
| 193 |
+
from peft import PeftModel
|
| 194 |
+
|
| 195 |
+
base_model = AutoModelForCausalLM.from_pretrained("meta-llama/llama3.2-1B")
|
| 196 |
+
peft_model = PeftModel.from_pretrained(base_model, "my-user/my-llama-adapter") # you can also pass a directory instead of a hub path
|
| 197 |
+
```
|
| 198 |
+
|
| 199 |
+
## Multiple adapters
|
| 200 |
+
|
| 201 |
+
PEFT supports installing multiple adapters (of the same kind, in this document this would be LoRA) on top of a base model. When you call `get_peft_model` there is only one adapter named `"default"` but you can add as many additional adapters as you want by calling `peft_model.add_adapter(adapter_name=...)`.
|
| 202 |
+
|
| 203 |
+
<div class="flex justify-center">
|
| 204 |
+
<div class="flex flex-col basis-2/4">
|
| 205 |
+
<p>
|
| 206 |
+
This works because the wrapped layer actually has a unique set of trainable weights for each adapter name. Not every adapter is active and trainable by default. You have to explicitly enable adapters by name before they are active. This allows you to quickly swap between adapters where task-specific knowledge is needed or serve different use-cases on top of one model.
|
| 207 |
+
</p>
|
| 208 |
+
</div>
|
| 209 |
+
<div class="flex flex-col basis-2/4 pl-10 pr-10"><img style="border: 0;box-shadow: none;border-radius: 0;" src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/peft/adapter_layer_wrapping_multi_adapter.png" width="1000px"></div>
|
| 210 |
+
</div>
|
| 211 |
+
|
| 212 |
+
Just remember to call `peft_model.set_adapter(<adapter_name>)` first to enable the adapter.
|
| 213 |
+
|
| 214 |
+
Quick example:
|
| 215 |
+
|
| 216 |
+
```py
|
| 217 |
+
peft_model.add_adapter(adapter_name='new_adapter')
|
| 218 |
+
peft_model.set_adapter('new_adapter')
|
| 219 |
+
```
|
| 220 |
+
|
| 221 |
+
## Next steps
|
| 222 |
+
|
| 223 |
+
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:
|
| 224 |
+
|
| 225 |
+
1. prepare a [`PeftConfig`] for a PEFT method, e.g. a [`LoraConfig`] or some other config (see the [method overview](methods/overview))
|
| 226 |
+
2. use the [`get_peft_model`] method to create a [`PeftModel`] from the configuration and base model
|
| 227 |
+
|
| 228 |
+
Then you can train it however you like! To load a PEFT model for inference, you can use the [`AutoPeftModel`] class.
|
| 229 |
+
|
| 230 |
+
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.
|
tasks/tasksmith-0d2d1e298e86/tests/source/examples/KappaTune/README.md
ADDED
|
@@ -0,0 +1,215 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# KappaTune Experiment
|
| 2 |
+
|
| 3 |
+
This script compares different fine-tuning strategies on a downstream task (gsm8k) while measuring **catastrophic forgetting** on a general-knowledge control dataset (WikiText). For further details see the [KappaTune paper](https://arxiv.org/abs/2506.16289).
|
| 4 |
+
|
| 5 |
+
- **Baseline**: No adaptation
|
| 6 |
+
- **LoRA_Global**: Classic LoRA on common projections (`q_proj`, `k_proj`, `o_proj`, `v_proj`, `gate_proj`, `up_proj`, `down_proj` )
|
| 7 |
+
- **KappaTune_LoRA**: The new `KappaTuneSelector` with relative selection (`top_p=0.2`)
|
| 8 |
+
|
| 9 |
+
The goal is to show that KappaTune achieves similar task adaptation **while forgetting less** of the original pre-trained knowledge.
|
| 10 |
+
|
| 11 |
+
KappaTune is recommended when catastrophic forgetting is a concern. If your fine-tuning data is closely aligned with the model's pretraining distribution, it can even decrease general/Wiki perplexity. This is the case of fine-tuning on math data like GSM8K (adopted in this experiment) for some models. Then unrestricted LoRA over all layers may yield better results, since it reinforces pre-training.
|
| 12 |
+
|
| 13 |
+
### Key hyperparameters to play with
|
| 14 |
+
|
| 15 |
+
| Hyperparameter | Location | Default | What it controls | Recommendation |
|
| 16 |
+
|-------------------------------|-----------------------------------|------------------|-------------------------------------------------------|-----------------------------------------------------|
|
| 17 |
+
| `top_p` | KappaTune block | `0.2` | Fraction of best (lowest κ) modules selected | 0.1–0.3 (lower = more conservative) |
|
| 18 |
+
| `num_modules` | KappaTune block (alternative) | `None` | Fixed number of modules | Use instead of `top_p` for strict budget |
|
| 19 |
+
| `r` (rank) | Both LoRA configs | `16` / `190` | LoRA rank (controls trainable parameters) | Keep total trainable params similar between runs |
|
| 20 |
+
| `LR` (learning rate) | Top of script | `2e-4` | Training speed and stability | 1e-4 – 5e-4 |
|
| 21 |
+
| `num_train_epochs` | Top of script | `10` | Total training steps | Increase for stronger adaptation |
|
| 22 |
+
| `MODEL_ID` | Top of script | DeepSeek-V2-Lite | Base model | Try Mistral, Qwen, etc. MoE yields the best results |
|
| 23 |
+
| `max_dim_size_to_analyze` | `KappaTuneSelector` | `16384` | Max matrix size for SVD (memory / speed trade-off) | Increase only if you have very high VRAM |
|
| 24 |
+
|
| 25 |
+
## Expected results
|
| 26 |
+
|
| 27 |
+
Running the script with default parameters produces the following behavior.
|
| 28 |
+
|
| 29 |
+
<details>
|
| 30 |
+
<summary><strong>KappaTune (training log)</strong></summary>
|
| 31 |
+
|
| 32 |
+
```text
|
| 33 |
+
========================================
|
| 34 |
+
>>> EXPERIMENT: KappaTune_LoRA
|
| 35 |
+
========================================
|
| 36 |
+
[KappaTune] Selecting target modules using PEFT KappaTuneSelector...
|
| 37 |
+
trainable params: 219,188,480 (0.47%)
|
| 38 |
+
#trainable tensors: 370
|
| 39 |
+
#trainable params: 219,188,480
|
| 40 |
+
{'loss': 1.2208, 'grad_norm': 0.15972940623760223, 'learning_rate': 0.00019666666666666666, 'epoch': 0.87}
|
| 41 |
+
{'loss': 1.07, 'grad_norm': 0.26267319917678833, 'learning_rate': 0.00019250000000000002, 'epoch': 1.7}
|
| 42 |
+
{'loss': 1.0124, 'grad_norm': 0.2723085284233093, 'learning_rate': 0.00018833333333333335, 'epoch': 2.52}
|
| 43 |
+
{'loss': 0.9436, 'grad_norm': 0.29701513051986694, 'learning_rate': 0.00018416666666666665, 'epoch': 3.35}
|
| 44 |
+
{'loss': 0.9114, 'grad_norm': 0.3046768009662628, 'learning_rate': 0.00018, 'epoch': 4.17}
|
| 45 |
+
{'loss': 0.8915, 'grad_norm': 0.47676295042037964, 'learning_rate': 0.00017583333333333334, 'epoch': 5.0}
|
| 46 |
+
{'loss': 0.8728, 'grad_norm': 0.24124978482723236, 'learning_rate': 0.00017166666666666667, 'epoch': 5.87}
|
| 47 |
+
{'loss': 0.8385, 'grad_norm': 0.20988021790981293, 'learning_rate': 0.0001675, 'epoch': 6.7}
|
| 48 |
+
{'loss': 0.8389, 'grad_norm': 0.21968263387680054, 'learning_rate': 0.00016333333333333334, 'epoch': 7.52}
|
| 49 |
+
{'loss': 0.8224, 'grad_norm': 0.04499625042080879, 'learning_rate': 0.00015916666666666667, 'epoch': 8.35}
|
| 50 |
+
{'loss': 0.7997, 'grad_norm': 0.05307907983660698, 'learning_rate': 0.000155, 'epoch': 9.17}
|
| 51 |
+
{'loss': 0.8057, 'grad_norm': 0.05258958786725998, 'learning_rate': 0.00015083333333333333, 'epoch': 10.0}
|
| 52 |
+
{'loss': 0.7907, 'grad_norm': 0.05647141858935356, 'learning_rate': 0.00014666666666666666, 'epoch': 10.87}
|
| 53 |
+
{'loss': 0.7804, 'grad_norm': 0.07924238592386246, 'learning_rate': 0.00014250000000000002, 'epoch': 11.7}
|
| 54 |
+
{'loss': 0.7705, 'grad_norm': 0.03199317678809166, 'learning_rate': 0.00013833333333333333, 'epoch': 12.52}
|
| 55 |
+
{'loss': 0.76, 'grad_norm': 0.030626816675066948, 'learning_rate': 0.00013416666666666666, 'epoch': 13.35}
|
| 56 |
+
{'loss': 0.7456, 'grad_norm': 0.03376801684498787, 'learning_rate': 0.00013000000000000002, 'epoch': 14.17}
|
| 57 |
+
{'loss': 0.7352, 'grad_norm': 0.045162301510572433, 'learning_rate': 0.00012583333333333335, 'epoch': 15.0}
|
| 58 |
+
{'loss': 0.7221, 'grad_norm': 0.04105797037482262, 'learning_rate': 0.00012166666666666667, 'epoch': 15.87}
|
| 59 |
+
{'loss': 0.7118, 'grad_norm': 0.04653630033135414, 'learning_rate': 0.00011750000000000001, 'epoch': 16.7}
|
| 60 |
+
{'loss': 0.7071, 'grad_norm': 0.0477643646299839, 'learning_rate': 0.00011333333333333334, 'epoch': 17.52}
|
| 61 |
+
{'loss': 0.67, 'grad_norm': 0.05408667400479317, 'learning_rate': 0.00010916666666666666, 'epoch': 18.35}
|
| 62 |
+
{'loss': 0.6753, 'grad_norm': 0.05562206730246544, 'learning_rate': 0.000105, 'epoch': 19.17}
|
| 63 |
+
{'loss': 0.6529, 'grad_norm': 0.08778411149978638, 'learning_rate': 0.00010083333333333334, 'epoch': 20.0}
|
| 64 |
+
{'loss': 0.6356, 'grad_norm': 0.07903064042329788, 'learning_rate': 9.666666666666667e-05, 'epoch': 20.87}
|
| 65 |
+
{'loss': 0.6198, 'grad_norm': 0.08349727094173431, 'learning_rate': 9.250000000000001e-05, 'epoch': 21.7}
|
| 66 |
+
{'loss': 0.604, 'grad_norm': 0.08645208925008774, 'learning_rate': 8.833333333333333e-05, 'epoch': 22.52}
|
| 67 |
+
{'loss': 0.5897, 'grad_norm': 0.09194190055131912, 'learning_rate': 8.416666666666668e-05, 'epoch': 23.35}
|
| 68 |
+
{'loss': 0.5649, 'grad_norm': 0.10126981139183044, 'learning_rate': 8e-05, 'epoch': 24.17}
|
| 69 |
+
{'loss': 0.5483, 'grad_norm': 0.13687381148338318, 'learning_rate': 7.583333333333334e-05, 'epoch': 25.0}
|
| 70 |
+
{'loss': 0.5323, 'grad_norm': 0.13106191158294678, 'learning_rate': 7.166666666666667e-05, 'epoch': 25.87}
|
| 71 |
+
{'loss': 0.5147, 'grad_norm': 0.1281006783246994, 'learning_rate': 6.750000000000001e-05, 'epoch': 26.7}
|
| 72 |
+
{'loss': 0.4941, 'grad_norm': 0.1377001851797104, 'learning_rate': 6.333333333333333e-05, 'epoch': 27.52}
|
| 73 |
+
{'loss': 0.4845, 'grad_norm': 0.14247003197669983, 'learning_rate': 5.916666666666667e-05, 'epoch': 28.35}
|
| 74 |
+
{'loss': 0.4669, 'grad_norm': 0.14682190120220184, 'learning_rate': 5.500000000000001e-05, 'epoch': 29.17}
|
| 75 |
+
{'loss': 0.454, 'grad_norm': 0.19749927520751953, 'learning_rate': 5.0833333333333333e-05, 'epoch': 30.0}
|
| 76 |
+
{'loss': 0.4323, 'grad_norm': 0.1622404158115387, 'learning_rate': 4.666666666666667e-05, 'epoch': 30.87}
|
| 77 |
+
{'loss': 0.4274, 'grad_norm': 0.15755769610404968, 'learning_rate': 4.25e-05, 'epoch': 31.7}
|
| 78 |
+
{'loss': 0.4086, 'grad_norm': 0.1696886271238327, 'learning_rate': 3.8333333333333334e-05, 'epoch': 32.52}
|
| 79 |
+
{'loss': 0.4006, 'grad_norm': 0.14865559339523315, 'learning_rate': 3.4166666666666666e-05, 'epoch': 33.35}
|
| 80 |
+
{'loss': 0.3934, 'grad_norm': 0.14790022373199463, 'learning_rate': 3e-05, 'epoch': 34.17}
|
| 81 |
+
{'loss': 0.3777, 'grad_norm': 0.20866677165031433, 'learning_rate': 2.5833333333333336e-05, 'epoch': 35.0}
|
| 82 |
+
{'loss': 0.3712, 'grad_norm': 0.17520156502723694, 'learning_rate': 2.1666666666666667e-05, 'epoch': 35.87}
|
| 83 |
+
{'loss': 0.3668, 'grad_norm': 0.16120171546936035, 'learning_rate': 1.75e-05, 'epoch': 36.7}
|
| 84 |
+
{'loss': 0.3583, 'grad_norm': 0.16624851524829865, 'learning_rate': 1.3333333333333333e-05, 'epoch': 37.52}
|
| 85 |
+
{'loss': 0.357, 'grad_norm': 0.15067771077156067, 'learning_rate': 9.166666666666666e-06, 'epoch': 38.35}
|
| 86 |
+
{'loss': 0.3524, 'grad_norm': 0.15819120407104492, 'learning_rate': 5e-06, 'epoch': 39.17}
|
| 87 |
+
{'loss': 0.3466, 'grad_norm': 0.1855546236038208, 'learning_rate': 8.333333333333333e-07, 'epoch': 40.0}
|
| 88 |
+
{'train_runtime': 2871.3103, 'train_samples_per_second': 12.538, 'train_steps_per_second': 0.084, 'train_loss': 0.6427203471461932, 'epoch': 40.0}
|
| 89 |
+
|
| 90 |
+
========================================
|
| 91 |
+
>>> EXPERIMENT: Baseline
|
| 92 |
+
========================================
|
| 93 |
+
|
| 94 |
+
========================================
|
| 95 |
+
>>> EXPERIMENT: LoRA_Global
|
| 96 |
+
========================================
|
| 97 |
+
trainable params: 218,103,808 || all params: 46,920,896,512 || trainable%: 0.4648
|
| 98 |
+
{'loss': 1.2122, 'grad_norm': 0.03368454799056053, 'learning_rate': 0.00019666666666666666, 'epoch': 0.87}
|
| 99 |
+
{'loss': 1.0674, 'grad_norm': 0.04771586135029793, 'learning_rate': 0.00019250000000000002, 'epoch': 1.7}
|
| 100 |
+
{'loss': 0.9889, 'grad_norm': 0.030208367854356766, 'learning_rate': 0.00018833333333333335, 'epoch': 2.52}
|
| 101 |
+
{'loss': 0.9269, 'grad_norm': 0.0202629417181015, 'learning_rate': 0.00018416666666666665, 'epoch': 3.35}
|
| 102 |
+
{'loss': 0.9146, 'grad_norm': 0.01595970056951046, 'learning_rate': 0.00018, 'epoch': 4.17}
|
| 103 |
+
{'loss': 0.8983, 'grad_norm': 0.017851779237389565, 'learning_rate': 0.00017583333333333334, 'epoch': 5.0}
|
| 104 |
+
{'loss': 0.8914, 'grad_norm': 0.01525798998773098, 'learning_rate': 0.00017166666666666667, 'epoch': 5.87}
|
| 105 |
+
{'loss': 0.8733, 'grad_norm': 0.01363384909927845, 'learning_rate': 0.0001675, 'epoch': 6.7}
|
| 106 |
+
{'loss': 0.8712, 'grad_norm': 0.014126025140285492, 'learning_rate': 0.00016333333333333334, 'epoch': 7.52}
|
| 107 |
+
{'loss': 0.8673, 'grad_norm': 0.01614651270210743, 'learning_rate': 0.00015916666666666667, 'epoch': 8.35}
|
| 108 |
+
{'loss': 0.8461, 'grad_norm': 0.014323701150715351, 'learning_rate': 0.000155, 'epoch': 9.17}
|
| 109 |
+
{'loss': 0.8519, 'grad_norm': 0.022168157622218132, 'learning_rate': 0.00015083333333333333, 'epoch': 10.0}
|
| 110 |
+
{'loss': 0.8326, 'grad_norm': 0.017714861780405045, 'learning_rate': 0.00014666666666666666, 'epoch': 10.87}
|
| 111 |
+
{'loss': 0.8258, 'grad_norm': 0.01950528658926487, 'learning_rate': 0.00014250000000000002, 'epoch': 11.7}
|
| 112 |
+
{'loss': 0.8142, 'grad_norm': 0.021654563024640083, 'learning_rate': 0.00013833333333333333, 'epoch': 12.52}
|
| 113 |
+
{'loss': 0.803, 'grad_norm': 0.027227576822042465, 'learning_rate': 0.00013416666666666666, 'epoch': 13.35}
|
| 114 |
+
{'loss': 0.7892, 'grad_norm': 0.0281345397233963, 'learning_rate': 0.00013000000000000002, 'epoch': 14.17}
|
| 115 |
+
{'loss': 0.7759, 'grad_norm': 0.04052634909749031, 'learning_rate': 0.00012583333333333335, 'epoch': 15.0}
|
| 116 |
+
{'loss': 0.7614, 'grad_norm': 0.03630959987640381, 'learning_rate': 0.00012166666666666667, 'epoch': 15.87}
|
| 117 |
+
{'loss': 0.7474, 'grad_norm': 0.04881247878074646, 'learning_rate': 0.00011750000000000001, 'epoch': 16.7}
|
| 118 |
+
{'loss': 0.7449, 'grad_norm': 0.04792051389813423, 'learning_rate': 0.00011333333333333334, 'epoch': 17.52}
|
| 119 |
+
{'loss': 0.707, 'grad_norm': 0.059059303253889084, 'learning_rate': 0.00010916666666666666, 'epoch': 18.35}
|
| 120 |
+
{'loss': 0.713, 'grad_norm': 0.05515185743570328, 'learning_rate': 0.000105, 'epoch': 19.17}
|
| 121 |
+
{'loss': 0.6907, 'grad_norm': 0.09590236097574234, 'learning_rate': 0.00010083333333333334, 'epoch': 20.0}
|
| 122 |
+
{'loss': 0.6736, 'grad_norm': 0.07875961065292358, 'learning_rate': 9.666666666666667e-05, 'epoch': 20.87}
|
| 123 |
+
{'loss': 0.663, 'grad_norm': 0.08937060832977295, 'learning_rate': 9.250000000000001e-05, 'epoch': 21.7}
|
| 124 |
+
{'loss': 0.6445, 'grad_norm': 0.0950784757733345, 'learning_rate': 8.833333333333333e-05, 'epoch': 22.52}
|
| 125 |
+
{'loss': 0.6387, 'grad_norm': 0.08285810798406601, 'learning_rate': 8.416666666666668e-05, 'epoch': 23.35}
|
| 126 |
+
{'loss': 0.6182, 'grad_norm': 0.1019740179181099, 'learning_rate': 8e-05, 'epoch': 24.17}
|
| 127 |
+
{'loss': 0.6045, 'grad_norm': 0.1708088219165802, 'learning_rate': 7.583333333333334e-05, 'epoch': 25.0}
|
| 128 |
+
{'loss': 0.5959, 'grad_norm': 0.12375958263874054, 'learning_rate': 7.166666666666667e-05, 'epoch': 25.87}
|
| 129 |
+
{'loss': 0.5877, 'grad_norm': 0.1316744089126587, 'learning_rate': 6.750000000000001e-05, 'epoch': 26.7}
|
| 130 |
+
{'loss': 0.5698, 'grad_norm': 0.11958763003349304, 'learning_rate': 6.333333333333333e-05, 'epoch': 27.52}
|
| 131 |
+
{'loss': 0.5653, 'grad_norm': 0.11063854396343231, 'learning_rate': 5.916666666666667e-05, 'epoch': 28.35}
|
| 132 |
+
{'loss': 0.5502, 'grad_norm': 0.11866016685962677, 'learning_rate': 5.500000000000001e-05, 'epoch': 29.17}
|
| 133 |
+
{'loss': 0.5458, 'grad_norm': 0.1533481925725937, 'learning_rate': 5.0833333333333333e-05, 'epoch': 30.0}
|
| 134 |
+
{'loss': 0.5316, 'grad_norm': 0.13474972546100616, 'learning_rate': 4.666666666666667e-05, 'epoch': 30.87}
|
| 135 |
+
{'loss': 0.5269, 'grad_norm': 0.13297690451145172, 'learning_rate': 4.25e-05, 'epoch': 31.7}
|
| 136 |
+
{'loss': 0.5175, 'grad_norm': 0.13090570271015167, 'learning_rate': 3.8333333333333334e-05, 'epoch': 32.52}
|
| 137 |
+
{'loss': 0.5108, 'grad_norm': 0.1196967139840126, 'learning_rate': 3.4166666666666666e-05, 'epoch': 33.35}
|
| 138 |
+
{'loss': 0.5062, 'grad_norm': 0.13541598618030548, 'learning_rate': 3e-05, 'epoch': 34.17}
|
| 139 |
+
{'loss': 0.4965, 'grad_norm': 0.202300563454628, 'learning_rate': 2.5833333333333336e-05, 'epoch': 35.0}
|
| 140 |
+
{'loss': 0.492, 'grad_norm': 0.14462313055992126, 'learning_rate': 2.1666666666666667e-05, 'epoch': 35.87}
|
| 141 |
+
{'loss': 0.4898, 'grad_norm': 0.1338396966457367, 'learning_rate': 1.75e-05, 'epoch': 36.7}
|
| 142 |
+
{'loss': 0.4833, 'grad_norm': 0.11928340792655945, 'learning_rate': 1.3333333333333333e-05, 'epoch': 37.52}
|
| 143 |
+
{'loss': 0.4805, 'grad_norm': 0.1199464276432991, 'learning_rate': 9.166666666666666e-06, 'epoch': 38.35}
|
| 144 |
+
{'loss': 0.4801, 'grad_norm': 0.1222926527261734, 'learning_rate': 5e-06, 'epoch': 39.17}
|
| 145 |
+
{'loss': 0.4729, 'grad_norm': 0.14248400926589966, 'learning_rate': 8.333333333333333e-07, 'epoch': 40.0}
|
| 146 |
+
{'train_runtime': 2779.2046, 'train_samples_per_second': 12.953, 'train_steps_per_second': 0.086, 'train_loss': 0.7012442946434021, 'epoch': 40.0}
|
| 147 |
+
|
| 148 |
+
======================================================================
|
| 149 |
+
METHOD | gsm8k PPL (Task train) | gsm8k PPL (Task test) | Wiki PPL (General/control)
|
| 150 |
+
----------------------------------------------------------------------
|
| 151 |
+
KappaTune | 1.4410 | 3.2826 | 13.7780
|
| 152 |
+
Baseline | 3.6899 | 3.4668 | 13.9841
|
| 153 |
+
LoRA_Global | 1.6593 | 3.5648 | 26.6836
|
| 154 |
+
======================================================================
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
```
|
| 158 |
+
|
| 159 |
+
</details>
|
| 160 |
+
|
| 161 |
+
## Dense model with varying training effort
|
| 162 |
+
|
| 163 |
+
Since we are using small datasets, the adaptation effort is small, as is the risk of forgetting. To evaluate catastrophic forgetting during intensive fine-tuning we need big datasets or overfitting a small dataset. Therefore, I ran a set of experiments that track the performance of a dense LLM (Llama 8B) trained on the IMDB dataset over extended epochs, proxying the heavy gradient updates typical of massive datasets. The experiments use the same Python script, changing just these parameters:
|
| 164 |
+
|
| 165 |
+
```python
|
| 166 |
+
MODEL_ID = "unsloth/Meta-Llama-3.1-8B-Instruct"
|
| 167 |
+
imdb_ds = load_dataset("imdb", split="train[:1000]").train_test_split(test_size=0.1)
|
| 168 |
+
imdb_tokenized = imdb_ds.map(format_imdb).map(
|
| 169 |
+
lambda x: tokenizer(x["text"], padding="max_length", truncation=True, max_length=256),
|
| 170 |
+
batched=True, remove_columns=imdb_ds["train"].column_names
|
| 171 |
+
)
|
| 172 |
+
if method_name == "LoRA_Global":
|
| 173 |
+
Target_modules = [
|
| 174 |
+
"q_proj",
|
| 175 |
+
"k_proj",
|
| 176 |
+
"v_proj",
|
| 177 |
+
"o_proj",
|
| 178 |
+
"gate_proj",
|
| 179 |
+
"up_proj",
|
| 180 |
+
"down_proj"
|
| 181 |
+
]
|
| 182 |
+
lora_config = LoraConfig(
|
| 183 |
+
r=12,
|
| 184 |
+
target_modules=Target_modules,
|
| 185 |
+
task_type=TaskType.CAUSAL_LM, lora_dropout=0.05
|
| 186 |
+
)
|
| 187 |
+
model = get_peft_model(model, lora_config)
|
| 188 |
+
model.print_trainable_parameters()
|
| 189 |
+
LR=2e-4
|
| 190 |
+
STP= #VAR <from 4 to 20>
|
| 191 |
+
elif method_name == "KappaTune_LoRA":
|
| 192 |
+
stable_modules_dic = find_kappa_target_modules(model, top_p=0.2)
|
| 193 |
+
lora_config = LoraConfig(
|
| 194 |
+
r=64,
|
| 195 |
+
target_modules = stable_modules_dic["target_modules"],
|
| 196 |
+
target_parameters = stable_modules_dic["target_parameters"] if stable_modules_dic["target_parameters"] else None,
|
| 197 |
+
task_type=TaskType.CAUSAL_LM,
|
| 198 |
+
lora_dropout=0.05,
|
| 199 |
+
)
|
| 200 |
+
model = get_peft_model(model, lora_config)
|
| 201 |
+
model.print_trainable_parameters()
|
| 202 |
+
trainable = [(n, p.shape, p.numel()) for n, p in model.named_parameters() if p.requires_grad]
|
| 203 |
+
LR = 2e-4
|
| 204 |
+
STP = # VAR <from 6 to 60>
|
| 205 |
+
|
| 206 |
+
```
|
| 207 |
+
|
| 208 |
+
The figure below plots task-specific adaptation (IMDB perplexity) against general knowledge retention (control Wiki perplexity). The results reveal a distinct divergence: while both methods perform comparably under light training loads, pushing into deeper convergence exposes KappaTune's structural advantage. As the model tightly fits the target data, standard LoRA exhibits a steep degradation in general knowledge (higher Wiki PPL), whereas KappaTune maintains a significantly flatter trajectory. This demonstrates its superior ability to isolate new learning and mitigate catastrophic forgetting even under sustained training pressure.
|
| 209 |
+
|
| 210 |
+
|
| 211 |
+
<img width="778" height="536" alt="image" src="https://github.com/user-attachments/assets/4cbbcaa2-e433-48cf-8764-67498462f686" />
|
| 212 |
+
|
| 213 |
+
|
| 214 |
+
In case of using this test framework for different experiments, it's worth highlighting that size matters.
|
| 215 |
+
KappaTune shows the strongest gains on larger models (≥7B) and especially on MoE architectures (many independent expert modules). In small, dense models, the benefit is reduced because there is a limited variety of independent tensors to choose from. A fair comparison of catastrophic forgetting should make both methods reach roughly the same level of adaptation to the new task (similar training PPL). Matching on test PPL is not sufficient, because the same test PPL can be achieved through overfitting (more forgetting) or underfitting (less forgetting).
|
tasks/tasksmith-0d2d1e298e86/tests/source/examples/KappaTune/experiments_kappatune_peft.py
ADDED
|
@@ -0,0 +1,162 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gc
|
| 2 |
+
import math
|
| 3 |
+
|
| 4 |
+
import torch
|
| 5 |
+
from datasets import load_dataset
|
| 6 |
+
from transformers import (
|
| 7 |
+
AutoModelForCausalLM,
|
| 8 |
+
AutoTokenizer,
|
| 9 |
+
BitsAndBytesConfig,
|
| 10 |
+
DataCollatorForLanguageModeling,
|
| 11 |
+
Trainer,
|
| 12 |
+
TrainingArguments,
|
| 13 |
+
)
|
| 14 |
+
|
| 15 |
+
from peft import LoraConfig, TaskType, get_peft_model, prepare_model_for_kbit_training
|
| 16 |
+
from peft.helpers import find_kappa_target_modules
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
# ==========================================
|
| 20 |
+
# 1. Data Preparation
|
| 21 |
+
# ==========================================
|
| 22 |
+
MODEL_ID = "mistralai/Mixtral-8x7B-Instruct-v0.1"
|
| 23 |
+
tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)
|
| 24 |
+
tokenizer.pad_token = tokenizer.eos_token
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def format_gsm8k(example):
|
| 28 |
+
return {"text": f"Question: {example['question']}\nAnswer: {example['answer']}"}
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
print("Loading and preprocessing datasets...")
|
| 32 |
+
gsm8k_ds = load_dataset("gsm8k", "main", split="train[:1000]").train_test_split(test_size=0.1)
|
| 33 |
+
gsm8k_tokenized = gsm8k_ds.map(format_gsm8k).map(
|
| 34 |
+
lambda x: tokenizer(x["text"], padding="max_length", truncation=True, max_length=256),
|
| 35 |
+
batched=True,
|
| 36 |
+
remove_columns=["question", "answer", "text"],
|
| 37 |
+
)
|
| 38 |
+
|
| 39 |
+
wiki_ds = load_dataset("wikitext", "wikitext-2-raw-v1", split="test[:400]")
|
| 40 |
+
wiki_tokenized = wiki_ds.filter(lambda x: len(x["text"]) > 20).map(
|
| 41 |
+
lambda x: tokenizer(x["text"], padding="max_length", truncation=True, max_length=256),
|
| 42 |
+
batched=True,
|
| 43 |
+
remove_columns=wiki_ds.column_names,
|
| 44 |
+
)
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
# ==========================================
|
| 48 |
+
# 2. Experiment Engine
|
| 49 |
+
# ==========================================
|
| 50 |
+
def evaluate_perplexity(model, dataset, name="Dataset"):
|
| 51 |
+
model.eval()
|
| 52 |
+
total_loss = 0
|
| 53 |
+
data_collator = DataCollatorForLanguageModeling(tokenizer, mlm=False)
|
| 54 |
+
dataloader = torch.utils.data.DataLoader(dataset, batch_size=2, collate_fn=data_collator)
|
| 55 |
+
|
| 56 |
+
with torch.no_grad():
|
| 57 |
+
for i, batch in enumerate(dataloader):
|
| 58 |
+
batch = {k: v.to(model.device) for k, v in batch.items()}
|
| 59 |
+
outputs = model(**batch, use_cache=False)
|
| 60 |
+
total_loss += outputs.loss.item()
|
| 61 |
+
if i >= 40:
|
| 62 |
+
break
|
| 63 |
+
return math.exp(total_loss / (i + 1))
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def run_experiment(method_name):
|
| 67 |
+
print(f"\n{'=' * 40}\n>>> EXPERIMENT: {method_name}\n{'=' * 40}")
|
| 68 |
+
|
| 69 |
+
bnb_config = BitsAndBytesConfig(
|
| 70 |
+
load_in_4bit=True,
|
| 71 |
+
bnb_4bit_quant_type="nf4",
|
| 72 |
+
bnb_4bit_compute_dtype=torch.bfloat16,
|
| 73 |
+
bnb_4bit_use_double_quant=True,
|
| 74 |
+
)
|
| 75 |
+
|
| 76 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 77 |
+
MODEL_ID, quantization_config=bnb_config, trust_remote_code=True, device_map="auto"
|
| 78 |
+
)
|
| 79 |
+
model = prepare_model_for_kbit_training(model)
|
| 80 |
+
|
| 81 |
+
# Configure PEFT based on method
|
| 82 |
+
if method_name == "LoRA_Global":
|
| 83 |
+
Target_modules = ["q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "up_proj", "down_proj"]
|
| 84 |
+
lora_config = LoraConfig(r=256, target_modules=Target_modules, task_type=TaskType.CAUSAL_LM, lora_dropout=0.05)
|
| 85 |
+
model = get_peft_model(model, lora_config)
|
| 86 |
+
model.print_trainable_parameters()
|
| 87 |
+
LR = 2e-4
|
| 88 |
+
STP = 40
|
| 89 |
+
|
| 90 |
+
elif method_name == "KappaTune_LoRA":
|
| 91 |
+
print(" [KappaTune] Selecting target modules using PEFT KappaTuneSelector...")
|
| 92 |
+
|
| 93 |
+
# Relative selection‚ works on any architecture
|
| 94 |
+
stable_modules_dic = find_kappa_target_modules(model, top_p=0.2)
|
| 95 |
+
|
| 96 |
+
lora_config = LoraConfig(
|
| 97 |
+
r=85,
|
| 98 |
+
target_modules=stable_modules_dic["target_modules"],
|
| 99 |
+
target_parameters=stable_modules_dic["target_parameters"]
|
| 100 |
+
if stable_modules_dic["target_parameters"]
|
| 101 |
+
else None,
|
| 102 |
+
task_type=TaskType.CAUSAL_LM,
|
| 103 |
+
lora_dropout=0.05,
|
| 104 |
+
)
|
| 105 |
+
|
| 106 |
+
model = get_peft_model(model, lora_config)
|
| 107 |
+
model.print_trainable_parameters()
|
| 108 |
+
trainable = [(n, p.shape, p.numel()) for n, p in model.named_parameters() if p.requires_grad]
|
| 109 |
+
|
| 110 |
+
print(f"#trainable tensors: {len(trainable)}")
|
| 111 |
+
print(f"#trainable params: {sum(x[2] for x in trainable):,}")
|
| 112 |
+
|
| 113 |
+
LR = 2e-4
|
| 114 |
+
STP = 40 # or whatever step count you prefer for fair comparison
|
| 115 |
+
|
| 116 |
+
if method_name != "Baseline":
|
| 117 |
+
args = TrainingArguments(
|
| 118 |
+
output_dir=f"./{method_name}_out",
|
| 119 |
+
per_device_train_batch_size=40,
|
| 120 |
+
gradient_accumulation_steps=4,
|
| 121 |
+
learning_rate=LR,
|
| 122 |
+
num_train_epochs=STP,
|
| 123 |
+
bf16=True,
|
| 124 |
+
logging_steps=5,
|
| 125 |
+
save_strategy="no",
|
| 126 |
+
report_to="none",
|
| 127 |
+
)
|
| 128 |
+
trainer = Trainer(
|
| 129 |
+
model=model,
|
| 130 |
+
args=args,
|
| 131 |
+
train_dataset=gsm8k_tokenized["train"],
|
| 132 |
+
data_collator=DataCollatorForLanguageModeling(tokenizer, mlm=False),
|
| 133 |
+
)
|
| 134 |
+
trainer.train()
|
| 135 |
+
|
| 136 |
+
t_ppl_test = evaluate_perplexity(model, gsm8k_tokenized["test"], "gsm8k")
|
| 137 |
+
t_ppl_train = evaluate_perplexity(model, gsm8k_tokenized["train"], "gsm8k")
|
| 138 |
+
f_ppl = evaluate_perplexity(model, wiki_tokenized, "WikiText")
|
| 139 |
+
|
| 140 |
+
del model
|
| 141 |
+
gc.collect()
|
| 142 |
+
torch.cuda.empty_cache()
|
| 143 |
+
return t_ppl_test, t_ppl_train, f_ppl
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
# ==========================================
|
| 147 |
+
# 3. Results (same table as paper)
|
| 148 |
+
# ==========================================
|
| 149 |
+
results = {}
|
| 150 |
+
|
| 151 |
+
results["KappaTune"] = run_experiment("KappaTune_LoRA")
|
| 152 |
+
results["Baseline"] = run_experiment("Baseline")
|
| 153 |
+
results["LoRA_Global"] = run_experiment("LoRA_Global")
|
| 154 |
+
|
| 155 |
+
print("\n" + "=" * 70)
|
| 156 |
+
print(
|
| 157 |
+
f"{'METHOD':<15} | {'gsm8k PPL (Task train)':<18} | {'gsm8k PPL (Task test)':<18} | {'Wiki PPL (General/control)':<18}"
|
| 158 |
+
)
|
| 159 |
+
print("-" * 70)
|
| 160 |
+
for m, (tpte, tptr, fp) in results.items():
|
| 161 |
+
print(f"{m:<15} | {tptr:<18.4f} | {tpte:<18.4f} | {fp:<18.4f}")
|
| 162 |
+
print("=" * 70)
|
tasks/tasksmith-0d2d1e298e86/tests/source/examples/adamss_finetuning/README.md
ADDED
|
@@ -0,0 +1,203 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# AdaMSS Fine-tuning
|
| 2 |
+
|
| 3 |
+
## Introduction
|
| 4 |
+
|
| 5 |
+
AdaMSS (Adaptive Matrix Decomposition with Subspace Selection) is a parameter-efficient fine-tuning method that decomposes weight matrices using SVD into low-rank subspaces. It uses only **~0.07%** of original trainable parameters (e.g., 59K for ViT-Base vs 86M full fine-tuning) while maintaining competitive performance.
|
| 6 |
+
|
| 7 |
+
The method optionally supports **ASA** (Adaptive Subspace Allocation) for dynamic subspace selection during training, further improving efficiency and performance.
|
| 8 |
+
|
| 9 |
+
See the [paper](https://neurips.cc/virtual/2025/poster/119606) for more details.
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
## Installation & Quick Test
|
| 13 |
+
|
| 14 |
+
Install from local source:
|
| 15 |
+
```bash
|
| 16 |
+
cd peft-main && pip install -e .
|
| 17 |
+
pip install transformers datasets torch torchvision evaluate accelerate scikit-learn
|
| 18 |
+
```
|
| 19 |
+
|
| 20 |
+
Verify installation:
|
| 21 |
+
```bash
|
| 22 |
+
python -c "from peft import AdamssConfig; print('AdaMSS ready')"
|
| 23 |
+
```
|
| 24 |
+
|
| 25 |
+
## Detailed Code Explanation
|
| 26 |
+
|
| 27 |
+
**Core AdaMSS Configuration:**
|
| 28 |
+
```python
|
| 29 |
+
from peft import AdamssConfig, get_peft_model
|
| 30 |
+
|
| 31 |
+
# Configure AdaMSS with ASA
|
| 32 |
+
config = AdamssConfig(
|
| 33 |
+
r=100, # SVD rank (full decomposition rank)
|
| 34 |
+
num_subspaces=10, # Number of subspaces (K) - initial capacity
|
| 35 |
+
subspace_rank=3, # Rank per subspace (ri) - use 1 for NLU, 3 for Vision
|
| 36 |
+
target_modules=["query", "value"], # Target attention layers
|
| 37 |
+
use_asa=True, # Enable Adaptive Subspace Allocation
|
| 38 |
+
asa_target_subspaces=5, # Target active subspaces (ASA reduces K→5)
|
| 39 |
+
init_warmup=50, # Start ASA after 50 steps
|
| 40 |
+
final_warmup=1000, # Complete masking by step 1000
|
| 41 |
+
mask_interval=100, # Update mask every 100 steps
|
| 42 |
+
modules_to_save=["classifier"], # Modules to train without decomposition
|
| 43 |
+
)
|
| 44 |
+
peft_model = get_peft_model(model, config)
|
| 45 |
+
```
|
| 46 |
+
|
| 47 |
+
**Option A – With HuggingFace Trainer (callback):**
|
| 48 |
+
```python
|
| 49 |
+
from peft.tuners.adamss.asa_callback import AdamssAsaCallback
|
| 50 |
+
|
| 51 |
+
# The callback is a thin wrapper around model.update_and_allocate()
|
| 52 |
+
trainer = Trainer(
|
| 53 |
+
model=peft_model,
|
| 54 |
+
callbacks=[AdamssAsaCallback()],
|
| 55 |
+
# ... other arguments
|
| 56 |
+
)
|
| 57 |
+
trainer.train()
|
| 58 |
+
```
|
| 59 |
+
|
| 60 |
+
**Option B – Custom training loop (no Trainer needed):**
|
| 61 |
+
```python
|
| 62 |
+
for step, batch in enumerate(dataloader):
|
| 63 |
+
loss = peft_model(**batch).loss
|
| 64 |
+
loss.backward()
|
| 65 |
+
optimizer.step()
|
| 66 |
+
peft_model.base_model.update_and_allocate(step) # ← all ASA logic in one call
|
| 67 |
+
optimizer.zero_grad()
|
| 68 |
+
```
|
| 69 |
+
|
| 70 |
+
**Key Points:**
|
| 71 |
+
- **Parameterization**: Total params = `r × (d_in + d_out)`, split into K subspaces of rank `ri` each
|
| 72 |
+
- **ASA Mechanism**: Dynamically selects `asa_target_subspaces` most important subspaces from initial `num_subspaces`
|
| 73 |
+
- **Warmup Schedule**: ASA gradually increases masking strength from `init_warmup` to `final_warmup`
|
| 74 |
+
- **Vision vs NLU**: Use `subspace_rank=3` for vision, `subspace_rank=1` for NLU tasks
|
| 75 |
+
|
| 76 |
+
## Use the training example scripts
|
| 77 |
+
|
| 78 |
+
### Vision Tasks (Image Classification)
|
| 79 |
+
|
| 80 |
+
Run the provided script with your configuration:
|
| 81 |
+
```bash
|
| 82 |
+
python examples/adamss_finetuning/image_classification_adamss_asa.py \
|
| 83 |
+
--model_name_or_path google/vit-base-patch16-224-in21k \
|
| 84 |
+
--dataset_name cifar10 \
|
| 85 |
+
--adamss_r 100 \
|
| 86 |
+
--adamss_k 10 \
|
| 87 |
+
--adamss_ri 3 \
|
| 88 |
+
--use_asa \
|
| 89 |
+
--asa_target_subspaces 5 \
|
| 90 |
+
--output_dir ./output
|
| 91 |
+
```
|
| 92 |
+
|
| 93 |
+
### NLU Tasks (GLUE Benchmark)
|
| 94 |
+
|
| 95 |
+
Run GLUE tasks (e.g., CoLA) with ASA:
|
| 96 |
+
```bash
|
| 97 |
+
python examples/adamss_finetuning/glue_adamss_asa_example.py \
|
| 98 |
+
--dataset_name cola \
|
| 99 |
+
--adamss_r 100 \
|
| 100 |
+
--adamss_k 10 \
|
| 101 |
+
--adamss_ri 1 \
|
| 102 |
+
--use_asa \
|
| 103 |
+
--asa_target_subspaces 5 \
|
| 104 |
+
--num_epochs 100 \
|
| 105 |
+
--batch_size 32 \
|
| 106 |
+
--output_dir ./output_cola_asa
|
| 107 |
+
```
|
| 108 |
+
|
| 109 |
+
Without ASA (fixed K=10):
|
| 110 |
+
```bash
|
| 111 |
+
python examples/adamss_finetuning/glue_adamss_asa_example.py \
|
| 112 |
+
--dataset_name cola \
|
| 113 |
+
--adamss_r 100 \
|
| 114 |
+
--adamss_k 10 \
|
| 115 |
+
--adamss_ri 1 \
|
| 116 |
+
--num_epochs 100 \
|
| 117 |
+
--batch_size 32 \
|
| 118 |
+
--output_dir ./output_cola_no_asa
|
| 119 |
+
```
|
| 120 |
+
|
| 121 |
+
### AdamssConfig Parameters
|
| 122 |
+
|
| 123 |
+
| Parameter | Type | Default | Description |
|
| 124 |
+
|-----------|------|---------|-------------|
|
| 125 |
+
| `r` | int | 100 | SVD decomposition rank |
|
| 126 |
+
| `num_subspaces` | int | 10 | Number of subspaces (K) |
|
| 127 |
+
| `subspace_rank` | int | 3 | Rank per subspace (ri) |
|
| 128 |
+
| `target_modules` | list | - | Modules to apply AdaMSS (e.g., ["query", "value"]) |
|
| 129 |
+
| `use_asa` | bool | False | Enable Adaptive Subspace Allocation |
|
| 130 |
+
| `asa_target_subspaces` | int | None | Target active subspaces when ASA enabled |
|
| 131 |
+
| `modules_to_save` | list | None | Modules to train without decomposition |
|
| 132 |
+
|
| 133 |
+
### AdamssAsaCallback
|
| 134 |
+
|
| 135 |
+
The ASA callback reads all parameters from `AdamssConfig`. Import it directly:
|
| 136 |
+
|
| 137 |
+
```python
|
| 138 |
+
from peft.tuners.adamss.asa_callback import AdamssAsaCallback
|
| 139 |
+
```
|
| 140 |
+
|
| 141 |
+
ASA-related config parameters:
|
| 142 |
+
|
| 143 |
+
| Parameter | Type | Default | Description |
|
| 144 |
+
|-----------|------|---------|-------------|
|
| 145 |
+
| `init_warmup` | int | 50 | Steps before starting masking |
|
| 146 |
+
| `final_warmup` | int | 1000 | Steps to reach target active subspaces |
|
| 147 |
+
| `mask_interval` | int | 100 | Steps between subspace selection updates |
|
| 148 |
+
| `asa_importance_beta` | float | 0.85 | EMA decay for importance tracking |
|
| 149 |
+
| `asa_uncertainty_beta` | float | 0.85 | EMA decay for uncertainty tracking |
|
| 150 |
+
| `asa_schedule_exponent` | float | 3.0 | Exponent for masking schedule |
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
## Experimental Results
|
| 154 |
+
|
| 155 |
+
### NLU Tasks (GLUE Benchmark)
|
| 156 |
+
|
| 157 |
+
Results with AdaMSS + ASA (100 epochs, seed=0):
|
| 158 |
+
|
| 159 |
+
| Task | Model | AdaMSS Params | Metric | Score |
|
| 160 |
+
|------|-------|---------------|--------|-------|
|
| 161 |
+
| CoLA | RoBERTa-base | 27.0K (ASA K→5) | Matthews | **0.6466** |
|
| 162 |
+
| CoLA | RoBERTa-large | 64.8K (ASA K→5) | Matthews | **0.7093** |
|
| 163 |
+
| MRPC | RoBERTa-base | 27.2K (ASA K→5) | Accuracy | **0.8824** |
|
| 164 |
+
| MRPC | RoBERTa-large | 66.7K (ASA K→5) | Accuracy | **0.9044** |
|
| 165 |
+
|
| 166 |
+
**Notes:**
|
| 167 |
+
- Configuration: r=100, K=10→5 (ASA), ri=1
|
| 168 |
+
- AdaMSS active params with ASA (5 out of 10 subspaces selected)
|
| 169 |
+
- Full AdaMSS capacity: 97K (large) / 42K (base)
|
| 170 |
+
- Training: 100 epochs, batch_size=32, warmup_ratio=0.06
|
| 171 |
+
|
| 172 |
+
### Vision Tasks (Image Classification)
|
| 173 |
+
|
| 174 |
+
Results with AdaMSS on Stanford Cars (10 epochs, seed=0):
|
| 175 |
+
|
| 176 |
+
| Model | Method | AdaMSS Params | Test Accuracy |
|
| 177 |
+
|-------|--------|---------------|---------------|
|
| 178 |
+
| ViT-Base | AdaMSS (no ASA) | 121K (K=10) | **82.15%** |
|
| 179 |
+
| ViT-Base | AdaMSS + ASA | 75.0K (K→5) | **80.45%** |
|
| 180 |
+
|
| 181 |
+
**Notes:**
|
| 182 |
+
- Configuration: r=100, K=10, ri=3, 10 epochs, batch_size=32
|
| 183 |
+
- ASA dynamically selects 5 out of 10 subspaces (75K active from 121K total)
|
| 184 |
+
|
| 185 |
+
|
| 186 |
+
|
| 187 |
+
## Citation
|
| 188 |
+
|
| 189 |
+
If you use AdaMSS in your research, please cite:
|
| 190 |
+
|
| 191 |
+
```bibtex
|
| 192 |
+
@inproceedings{zheng2025adamss,
|
| 193 |
+
title={AdaMSS: Adaptive Multi-Subspace Approach for Parameter-Efficient Fine-Tuning},
|
| 194 |
+
author={Zheng, Jingjing and Lu, Wanglong and Dong, Yiming and Ji, Chaojie and Cao, Yankai and Lin, Zhouchen},
|
| 195 |
+
booktitle={The Thirty-ninth Annual Conference on Neural Information Processing Systems},
|
| 196 |
+
year={2025},
|
| 197 |
+
}
|
| 198 |
+
```
|
| 199 |
+
|
| 200 |
+
## Reference
|
| 201 |
+
|
| 202 |
+
- [AdaMSS Paper](https://neurips.cc/virtual/2025/loc/san-diego/poster/119606)
|
| 203 |
+
- [PEFT Documentation](https://huggingface.co/docs/peft)
|
tasks/tasksmith-0d2d1e298e86/tests/source/examples/adamss_finetuning/glue_adamss_asa_example.py
ADDED
|
@@ -0,0 +1,382 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
GLUE Task Fine-tuning with AdaMSS and ASA
|
| 3 |
+
|
| 4 |
+
This script demonstrates how to fine-tune RoBERTa on GLUE tasks using AdaMSS
|
| 5 |
+
with Adaptive Subspace Allocation (ASA) for efficient parameter updates.
|
| 6 |
+
|
| 7 |
+
Example usage:
|
| 8 |
+
# CoLA with RoBERTa-base, 100 epochs
|
| 9 |
+
python glue_adamss_asa_example.py --dataset_name cola --num_epochs 100 --seed 0
|
| 10 |
+
|
| 11 |
+
# With ASA enabled (K: 10→5)
|
| 12 |
+
python glue_adamss_asa_example.py --dataset_name cola --num_epochs 100 --use_asa --asa_target_subspaces 5
|
| 13 |
+
|
| 14 |
+
# MRPC with RoBERTa-large
|
| 15 |
+
python glue_adamss_asa_example.py --dataset_name mrpc --model_name_or_path roberta-large --num_epochs 10
|
| 16 |
+
|
| 17 |
+
Requirements:
|
| 18 |
+
pip install peft transformers datasets torch evaluate scikit-learn
|
| 19 |
+
"""
|
| 20 |
+
|
| 21 |
+
from dataclasses import dataclass, field
|
| 22 |
+
|
| 23 |
+
import evaluate
|
| 24 |
+
import numpy as np
|
| 25 |
+
import torch
|
| 26 |
+
from datasets import load_dataset
|
| 27 |
+
from torch.optim import AdamW
|
| 28 |
+
from transformers import (
|
| 29 |
+
AutoModelForSequenceClassification,
|
| 30 |
+
AutoTokenizer,
|
| 31 |
+
EvalPrediction,
|
| 32 |
+
HfArgumentParser,
|
| 33 |
+
Trainer,
|
| 34 |
+
TrainingArguments,
|
| 35 |
+
)
|
| 36 |
+
|
| 37 |
+
from peft import AdamssConfig, get_peft_model
|
| 38 |
+
from peft.tuners.adamss.asa_callback import AdamssAsaCallback
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
# Table 19: Hyperparameters for GLUE tasks (from paper)
|
| 42 |
+
HYPERPARAMS = {
|
| 43 |
+
"roberta-base": {
|
| 44 |
+
"sst2": {"lr": 0.001, "head_lr": 0.005, "wd": 0.0005},
|
| 45 |
+
"mrpc": {"lr": 0.01, "head_lr": 0.0005, "wd": 0.0},
|
| 46 |
+
"cola": {"lr": 0.001, "head_lr": 0.005, "wd": 0.005},
|
| 47 |
+
"qnli": {"lr": 0.001, "head_lr": 0.005, "wd": 0.005},
|
| 48 |
+
"rte": {"lr": 0.0005, "head_lr": 0.005, "wd": 0.005},
|
| 49 |
+
"stsb": {"lr": 0.001, "head_lr": 0.005, "wd": 0.005},
|
| 50 |
+
},
|
| 51 |
+
"roberta-large": {
|
| 52 |
+
"sst2": {"lr": 0.001, "head_lr": 0.0005, "wd": 0.0},
|
| 53 |
+
"mrpc": {"lr": 0.001, "head_lr": 0.00005, "wd": 0.005},
|
| 54 |
+
"cola": {"lr": 0.005, "head_lr": 0.0005, "wd": 0.1},
|
| 55 |
+
"qnli": {"lr": 0.0005, "head_lr": 0.05, "wd": 0.005},
|
| 56 |
+
"rte": {"lr": 0.005, "head_lr": 0.005, "wd": 0.5},
|
| 57 |
+
"stsb": {"lr": 0.001, "head_lr": 0.0005, "wd": 0.0005},
|
| 58 |
+
},
|
| 59 |
+
}
|
| 60 |
+
|
| 61 |
+
TASK_METRICS = {
|
| 62 |
+
"cola": "matthews_correlation",
|
| 63 |
+
"stsb": "pearson",
|
| 64 |
+
"mrpc": "accuracy",
|
| 65 |
+
"qqp": "accuracy",
|
| 66 |
+
"sst2": "accuracy",
|
| 67 |
+
"qnli": "accuracy",
|
| 68 |
+
"rte": "accuracy",
|
| 69 |
+
}
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
@dataclass
|
| 73 |
+
class AdaMSSTrainingArguments:
|
| 74 |
+
"""Arguments for AdaMSS training on GLUE tasks."""
|
| 75 |
+
|
| 76 |
+
# Model and Dataset
|
| 77 |
+
model_name_or_path: str = field(
|
| 78 |
+
default="roberta-base", metadata={"help": "Model identifier: roberta-base or roberta-large"}
|
| 79 |
+
)
|
| 80 |
+
dataset_name: str = field(default="cola", metadata={"help": "GLUE task: cola, mrpc, sst2, qnli, rte, stsb"})
|
| 81 |
+
|
| 82 |
+
# AdaMSS Configuration
|
| 83 |
+
adamss_r: int = field(default=100, metadata={"help": "SVD rank"})
|
| 84 |
+
adamss_k: int = field(default=10, metadata={"help": "Number of subspaces (K)"})
|
| 85 |
+
adamss_ri: int = field(default=1, metadata={"help": "Subspace rank (rk), use 1 for NLU"})
|
| 86 |
+
|
| 87 |
+
# ASA Configuration
|
| 88 |
+
use_asa: bool = field(default=False, metadata={"help": "Enable Adaptive Subspace Allocation"})
|
| 89 |
+
asa_target_subspaces: int = field(default=5, metadata={"help": "Target active subspaces for ASA"})
|
| 90 |
+
asa_init_warmup: int = field(default=5, metadata={"help": "ASA init warmup in EPOCHS"})
|
| 91 |
+
asa_final_warmup: int = field(default=95, metadata={"help": "ASA final warmup in EPOCHS"})
|
| 92 |
+
asa_mask_interval: int = field(default=10, metadata={"help": "ASA mask interval in EPOCHS"})
|
| 93 |
+
asa_importance_beta: float = field(default=0.85, metadata={"help": "EMA coefficient for importance"})
|
| 94 |
+
asa_uncertainty_beta: float = field(default=0.85, metadata={"help": "EMA coefficient for uncertainty"})
|
| 95 |
+
asa_schedule_exponent: float = field(default=3.0, metadata={"help": "ASA schedule exponent"})
|
| 96 |
+
|
| 97 |
+
# Training Configuration
|
| 98 |
+
num_epochs: int = field(default=100, metadata={"help": "Number of training epochs"})
|
| 99 |
+
batch_size: int = field(default=32, metadata={"help": "Batch size per device"})
|
| 100 |
+
max_length: int = field(default=512, metadata={"help": "Maximum sequence length"})
|
| 101 |
+
warmup_ratio: float = field(default=0.06, metadata={"help": "Warmup ratio"})
|
| 102 |
+
|
| 103 |
+
# Other
|
| 104 |
+
seed: int = field(default=0, metadata={"help": "Random seed"})
|
| 105 |
+
output_dir: str = field(default="./output", metadata={"help": "Output directory"})
|
| 106 |
+
cache_dir: str = field(default="./cache", metadata={"help": "Cache directory"})
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def get_dataset(args: AdaMSSTrainingArguments, tokenizer):
|
| 110 |
+
"""Load and tokenize GLUE dataset."""
|
| 111 |
+
# Load dataset
|
| 112 |
+
raw_datasets = load_dataset("glue", args.dataset_name, cache_dir=args.cache_dir)
|
| 113 |
+
|
| 114 |
+
# Get sentence keys
|
| 115 |
+
sentence_keys = {
|
| 116 |
+
"cola": ("sentence", None),
|
| 117 |
+
"mrpc": ("sentence1", "sentence2"),
|
| 118 |
+
"qnli": ("question", "sentence"),
|
| 119 |
+
"rte": ("sentence1", "sentence2"),
|
| 120 |
+
"sst2": ("sentence", None),
|
| 121 |
+
"stsb": ("sentence1", "sentence2"),
|
| 122 |
+
}
|
| 123 |
+
sentence1_key, sentence2_key = sentence_keys[args.dataset_name]
|
| 124 |
+
|
| 125 |
+
# Tokenize
|
| 126 |
+
def preprocess_function(examples):
|
| 127 |
+
texts = (
|
| 128 |
+
(examples[sentence1_key],) if sentence2_key is None else (examples[sentence1_key], examples[sentence2_key])
|
| 129 |
+
)
|
| 130 |
+
result = tokenizer(*texts, truncation=True, max_length=args.max_length, padding="max_length")
|
| 131 |
+
result["labels"] = examples["label"]
|
| 132 |
+
return result
|
| 133 |
+
|
| 134 |
+
# Remove original text columns but keep label
|
| 135 |
+
columns_to_remove = [col for col in raw_datasets["train"].column_names if col != "label"]
|
| 136 |
+
tokenized_datasets = raw_datasets.map(
|
| 137 |
+
preprocess_function,
|
| 138 |
+
batched=True,
|
| 139 |
+
remove_columns=columns_to_remove,
|
| 140 |
+
desc="Tokenizing dataset",
|
| 141 |
+
)
|
| 142 |
+
|
| 143 |
+
train_ds = tokenized_datasets["train"]
|
| 144 |
+
val_ds = tokenized_datasets["validation"]
|
| 145 |
+
test_ds = tokenized_datasets["validation"] # Use validation as test for GLUE
|
| 146 |
+
|
| 147 |
+
return train_ds, val_ds, test_ds
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
def main():
|
| 151 |
+
# Parse arguments
|
| 152 |
+
parser = HfArgumentParser(AdaMSSTrainingArguments)
|
| 153 |
+
args = parser.parse_args_into_dataclasses()[0]
|
| 154 |
+
|
| 155 |
+
# Set seed
|
| 156 |
+
torch.manual_seed(args.seed)
|
| 157 |
+
np.random.seed(args.seed)
|
| 158 |
+
|
| 159 |
+
# Get model short name
|
| 160 |
+
model_short = "roberta-large" if "large" in args.model_name_or_path else "roberta-base"
|
| 161 |
+
|
| 162 |
+
# Get hyperparameters from Table 19
|
| 163 |
+
if model_short in HYPERPARAMS and args.dataset_name in HYPERPARAMS[model_short]:
|
| 164 |
+
hp = HYPERPARAMS[model_short][args.dataset_name]
|
| 165 |
+
else:
|
| 166 |
+
hp = {"lr": 0.001, "head_lr": 0.005, "wd": 0.005}
|
| 167 |
+
print(f"Using default hyperparameters for {model_short}/{args.dataset_name}")
|
| 168 |
+
|
| 169 |
+
# Print configuration
|
| 170 |
+
print("=" * 80)
|
| 171 |
+
print(f"AdaMSS {'with ASA' if args.use_asa else 'without ASA'} - GLUE: {args.dataset_name.upper()}")
|
| 172 |
+
print("=" * 80)
|
| 173 |
+
print(f" Model: {model_short}")
|
| 174 |
+
print(f" AdaMSS: r={args.adamss_r}, K={args.adamss_k}, ri={args.adamss_ri}")
|
| 175 |
+
if args.use_asa:
|
| 176 |
+
print(f" ASA: K={args.adamss_k} → target={args.asa_target_subspaces}")
|
| 177 |
+
print(f" Hyperparameters (Table 19): lr={hp['lr']}, head_lr={hp['head_lr']}, wd={hp['wd']}")
|
| 178 |
+
print(f" Training: {args.num_epochs} epochs, batch_size={args.batch_size}, seed={args.seed}")
|
| 179 |
+
print("=" * 80 + "\n")
|
| 180 |
+
|
| 181 |
+
# Load tokenizer
|
| 182 |
+
tokenizer = AutoTokenizer.from_pretrained(args.model_name_or_path, cache_dir=args.cache_dir)
|
| 183 |
+
|
| 184 |
+
# Load dataset
|
| 185 |
+
print(f"Loading {args.dataset_name} dataset...")
|
| 186 |
+
train_ds, val_ds, _test_ds = get_dataset(args, tokenizer)
|
| 187 |
+
|
| 188 |
+
# Determine task type
|
| 189 |
+
is_regression = args.dataset_name == "stsb"
|
| 190 |
+
if not is_regression:
|
| 191 |
+
label_list = train_ds.features["label"].names
|
| 192 |
+
num_labels = len(label_list)
|
| 193 |
+
else:
|
| 194 |
+
num_labels = 1
|
| 195 |
+
|
| 196 |
+
print(f"Dataset loaded - Task: {'regression' if is_regression else 'classification'}\n")
|
| 197 |
+
|
| 198 |
+
# Load model
|
| 199 |
+
print(f"Loading {model_short}...")
|
| 200 |
+
model = AutoModelForSequenceClassification.from_pretrained(
|
| 201 |
+
args.model_name_or_path,
|
| 202 |
+
num_labels=num_labels,
|
| 203 |
+
cache_dir=args.cache_dir,
|
| 204 |
+
)
|
| 205 |
+
|
| 206 |
+
# Convert epoch-based ASA parameters to step-based (before config creation)
|
| 207 |
+
steps_per_epoch = len(train_ds) // args.batch_size
|
| 208 |
+
if len(train_ds) % args.batch_size != 0:
|
| 209 |
+
steps_per_epoch += 1
|
| 210 |
+
|
| 211 |
+
asa_init_warmup_steps = args.asa_init_warmup * steps_per_epoch
|
| 212 |
+
asa_final_warmup_steps = args.asa_final_warmup * steps_per_epoch
|
| 213 |
+
asa_mask_interval_steps = args.asa_mask_interval * steps_per_epoch
|
| 214 |
+
|
| 215 |
+
# Apply AdaMSS
|
| 216 |
+
print("\nApplying AdaMSS...")
|
| 217 |
+
config = AdamssConfig(
|
| 218 |
+
r=args.adamss_r,
|
| 219 |
+
num_subspaces=args.adamss_k,
|
| 220 |
+
subspace_rank=args.adamss_ri,
|
| 221 |
+
target_modules=["query", "value"],
|
| 222 |
+
use_asa=args.use_asa,
|
| 223 |
+
asa_target_subspaces=args.asa_target_subspaces if args.use_asa else None,
|
| 224 |
+
init_warmup=asa_init_warmup_steps if args.use_asa else None,
|
| 225 |
+
final_warmup=asa_final_warmup_steps if args.use_asa else None,
|
| 226 |
+
mask_interval=asa_mask_interval_steps if args.use_asa else None,
|
| 227 |
+
asa_importance_beta=args.asa_importance_beta if args.use_asa else None,
|
| 228 |
+
asa_uncertainty_beta=args.asa_uncertainty_beta if args.use_asa else None,
|
| 229 |
+
asa_schedule_exponent=args.asa_schedule_exponent if args.use_asa else None,
|
| 230 |
+
modules_to_save=["classifier"],
|
| 231 |
+
)
|
| 232 |
+
|
| 233 |
+
model = get_peft_model(model, config)
|
| 234 |
+
model.print_trainable_parameters()
|
| 235 |
+
|
| 236 |
+
# Print detailed parameter breakdown (same logic as exec_adamss_peft_glue.py)
|
| 237 |
+
print("\n[Detailed Parameter Breakdown]")
|
| 238 |
+
head_params = [p for n, p in model.named_parameters() if ("classifier" in n or "score" in n) and p.requires_grad]
|
| 239 |
+
other_params = [
|
| 240 |
+
p for n, p in model.named_parameters() if ("classifier" not in n and "score" not in n) and p.requires_grad
|
| 241 |
+
]
|
| 242 |
+
head_count = sum(p.numel() for p in head_params)
|
| 243 |
+
adapter_count = sum(p.numel() for p in other_params)
|
| 244 |
+
print(f"Classifier Head Params: {head_count:,}")
|
| 245 |
+
print(f"AdaMSS Adapter Params: {adapter_count:,}")
|
| 246 |
+
print(f"Total Trainable Params: {head_count + adapter_count:,}")
|
| 247 |
+
|
| 248 |
+
# Debug: print parameter names to verify
|
| 249 |
+
if adapter_count == 0:
|
| 250 |
+
print("\nWARNING: No AdaMSS parameters found!")
|
| 251 |
+
print("All trainable parameter names:")
|
| 252 |
+
for n, p in model.named_parameters():
|
| 253 |
+
if p.requires_grad:
|
| 254 |
+
print(f" {n}: {p.numel():,} params")
|
| 255 |
+
|
| 256 |
+
# GPU memory
|
| 257 |
+
if torch.cuda.is_available():
|
| 258 |
+
torch.cuda.empty_cache()
|
| 259 |
+
torch.cuda.reset_peak_memory_stats()
|
| 260 |
+
print("\n[GPU Memory - Before Training]")
|
| 261 |
+
print(f"Allocated: {torch.cuda.memory_allocated() / 1024**3:.2f} GB")
|
| 262 |
+
print(f"Reserved: {torch.cuda.memory_reserved() / 1024**3:.2f} GB")
|
| 263 |
+
|
| 264 |
+
# Setup ASA callback
|
| 265 |
+
callbacks = []
|
| 266 |
+
if args.use_asa:
|
| 267 |
+
print("\nSetting up ASA callback...")
|
| 268 |
+
|
| 269 |
+
print("\n[ASA Configuration]")
|
| 270 |
+
print(f"Dataset size: {len(train_ds)}, Batch size: {args.batch_size}")
|
| 271 |
+
print(f"Steps per epoch: {steps_per_epoch}")
|
| 272 |
+
print(f"Total training steps: {steps_per_epoch * args.num_epochs}")
|
| 273 |
+
print("ASA warmup (epochs → steps):")
|
| 274 |
+
print(f" init_warmup: {args.asa_init_warmup} epochs → {asa_init_warmup_steps} steps")
|
| 275 |
+
print(f" final_warmup: {args.asa_final_warmup} epochs → {asa_final_warmup_steps} steps")
|
| 276 |
+
print(f" mask_interval: {args.asa_mask_interval} epochs → {asa_mask_interval_steps} steps\n")
|
| 277 |
+
|
| 278 |
+
asa_callback = AdamssAsaCallback()
|
| 279 |
+
callbacks.append(asa_callback)
|
| 280 |
+
|
| 281 |
+
# Training configuration
|
| 282 |
+
print("\n[Training Configuration]")
|
| 283 |
+
print(f"Dataset size: {len(train_ds)}, Batch size: {args.batch_size}")
|
| 284 |
+
steps_per_epoch = len(train_ds) // args.batch_size
|
| 285 |
+
if len(train_ds) % args.batch_size != 0:
|
| 286 |
+
steps_per_epoch += 1
|
| 287 |
+
print(f"Steps per epoch: {steps_per_epoch}")
|
| 288 |
+
print(f"Total training steps: {steps_per_epoch * args.num_epochs}")
|
| 289 |
+
|
| 290 |
+
# Metrics
|
| 291 |
+
metric = evaluate.load("glue", args.dataset_name)
|
| 292 |
+
|
| 293 |
+
def compute_metrics(p: EvalPrediction):
|
| 294 |
+
preds = p.predictions[0] if isinstance(p.predictions, tuple) else p.predictions
|
| 295 |
+
preds = np.squeeze(preds) if is_regression else np.argmax(preds, axis=1)
|
| 296 |
+
return metric.compute(predictions=preds, references=p.label_ids)
|
| 297 |
+
|
| 298 |
+
# Training arguments
|
| 299 |
+
training_args = TrainingArguments(
|
| 300 |
+
output_dir=args.output_dir,
|
| 301 |
+
num_train_epochs=args.num_epochs,
|
| 302 |
+
per_device_train_batch_size=args.batch_size,
|
| 303 |
+
per_device_eval_batch_size=args.batch_size,
|
| 304 |
+
learning_rate=hp["lr"],
|
| 305 |
+
weight_decay=hp["wd"],
|
| 306 |
+
warmup_ratio=args.warmup_ratio,
|
| 307 |
+
eval_strategy="epoch",
|
| 308 |
+
save_strategy="epoch",
|
| 309 |
+
load_best_model_at_end=True,
|
| 310 |
+
metric_for_best_model=TASK_METRICS.get(args.dataset_name, "accuracy"),
|
| 311 |
+
greater_is_better=True,
|
| 312 |
+
logging_steps=100,
|
| 313 |
+
seed=args.seed,
|
| 314 |
+
report_to="none",
|
| 315 |
+
remove_unused_columns=False, # PEFT wraps forward(*args, **kwargs)
|
| 316 |
+
label_names=["labels"], # Explicitly tell Trainer where labels are
|
| 317 |
+
)
|
| 318 |
+
|
| 319 |
+
# Custom optimizer with different LR for head
|
| 320 |
+
optimizer_grouped_parameters = [
|
| 321 |
+
{
|
| 322 |
+
"params": [
|
| 323 |
+
p for n, p in model.named_parameters() if ("classifier" in n or "score" in n) and p.requires_grad
|
| 324 |
+
],
|
| 325 |
+
"lr": hp["head_lr"],
|
| 326 |
+
},
|
| 327 |
+
{
|
| 328 |
+
"params": [
|
| 329 |
+
p
|
| 330 |
+
for n, p in model.named_parameters()
|
| 331 |
+
if ("classifier" not in n and "score" not in n) and p.requires_grad
|
| 332 |
+
],
|
| 333 |
+
"lr": hp["lr"],
|
| 334 |
+
},
|
| 335 |
+
]
|
| 336 |
+
optimizer = AdamW(optimizer_grouped_parameters, weight_decay=hp["wd"])
|
| 337 |
+
|
| 338 |
+
# Create trainer
|
| 339 |
+
trainer = Trainer(
|
| 340 |
+
model=model,
|
| 341 |
+
args=training_args,
|
| 342 |
+
train_dataset=train_ds,
|
| 343 |
+
eval_dataset=val_ds,
|
| 344 |
+
compute_metrics=compute_metrics,
|
| 345 |
+
optimizers=(optimizer, None),
|
| 346 |
+
callbacks=callbacks,
|
| 347 |
+
)
|
| 348 |
+
|
| 349 |
+
# Train
|
| 350 |
+
print("\n" + "=" * 80)
|
| 351 |
+
print("Starting training...")
|
| 352 |
+
print("=" * 80 + "\n")
|
| 353 |
+
|
| 354 |
+
train_result = trainer.train()
|
| 355 |
+
|
| 356 |
+
# GPU memory stats
|
| 357 |
+
if torch.cuda.is_available():
|
| 358 |
+
print("\n[GPU Memory - Peak During Training]")
|
| 359 |
+
print(f"Peak Allocated: {torch.cuda.max_memory_allocated() / 1024**3:.2f} GB")
|
| 360 |
+
print(f"Peak Reserved: {torch.cuda.max_memory_reserved() / 1024**3:.2f} GB")
|
| 361 |
+
|
| 362 |
+
# Print best metric
|
| 363 |
+
if trainer.state.best_metric is not None:
|
| 364 |
+
metric_name = TASK_METRICS.get(args.dataset_name, "accuracy")
|
| 365 |
+
print("\n[Best Model Info]")
|
| 366 |
+
print(f"Best {metric_name}: {trainer.state.best_metric:.4f}")
|
| 367 |
+
|
| 368 |
+
# Final evaluation on validation set
|
| 369 |
+
print("\n" + "=" * 80)
|
| 370 |
+
print("Final evaluation on validation set...")
|
| 371 |
+
print("=" * 80 + "\n")
|
| 372 |
+
|
| 373 |
+
final_metrics = trainer.evaluate(val_ds)
|
| 374 |
+
print(f"\nFinal Validation Results: {final_metrics}")
|
| 375 |
+
|
| 376 |
+
# Save model
|
| 377 |
+
trainer.save_model()
|
| 378 |
+
print(f"\nModel saved to {training_args.output_dir}")
|
| 379 |
+
|
| 380 |
+
|
| 381 |
+
if __name__ == "__main__":
|
| 382 |
+
main()
|
tasks/tasksmith-0d2d1e298e86/tests/source/examples/adamss_finetuning/glue_adamss_asa_manual_example.py
ADDED
|
@@ -0,0 +1,411 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
GLUE Task Fine-tuning with AdaMSS and Manual ASA
|
| 3 |
+
|
| 4 |
+
This script demonstrates how to manually call update_and_allocate() for ASA
|
| 5 |
+
instead of using AdamssAsaCallback. This approach is useful for custom training loops.
|
| 6 |
+
|
| 7 |
+
Note:
|
| 8 |
+
This is an alternative to using AdamssAsaCallback. Choose ONE approach:
|
| 9 |
+
- Use AdamssAsaCallback (recommended, see glue_adamss_asa_example.py)
|
| 10 |
+
- Use manual update_and_allocate() (this script, for custom control)
|
| 11 |
+
DO NOT use both together!
|
| 12 |
+
|
| 13 |
+
Example usage:
|
| 14 |
+
# CoLA with RoBERTa-base and manual ASA
|
| 15 |
+
python glue_adamss_asa_manual_example.py \
|
| 16 |
+
--dataset_name cola \
|
| 17 |
+
--use_asa \
|
| 18 |
+
--asa_target_subspaces 5 \
|
| 19 |
+
--num_epochs 100 \
|
| 20 |
+
--batch_size 32 \
|
| 21 |
+
--warmup_ratio 0.06 \
|
| 22 |
+
--seed 0 \
|
| 23 |
+
--output_dir ./output/cola_asa_manual
|
| 24 |
+
|
| 25 |
+
Requirements:
|
| 26 |
+
pip install peft transformers datasets torch evaluate scikit-learn
|
| 27 |
+
"""
|
| 28 |
+
|
| 29 |
+
from dataclasses import dataclass, field
|
| 30 |
+
|
| 31 |
+
import evaluate
|
| 32 |
+
import numpy as np
|
| 33 |
+
import torch
|
| 34 |
+
from datasets import load_dataset
|
| 35 |
+
from transformers import (
|
| 36 |
+
AutoModelForSequenceClassification,
|
| 37 |
+
AutoTokenizer,
|
| 38 |
+
EvalPrediction,
|
| 39 |
+
HfArgumentParser,
|
| 40 |
+
Trainer,
|
| 41 |
+
TrainingArguments,
|
| 42 |
+
set_seed,
|
| 43 |
+
)
|
| 44 |
+
|
| 45 |
+
from peft import AdamssConfig, get_peft_model
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
class CustomTrainerWithManualASA(Trainer):
|
| 49 |
+
"""
|
| 50 |
+
Custom Trainer that manually calls update_and_allocate() for ASA.
|
| 51 |
+
|
| 52 |
+
This demonstrates the manual approach as an alternative to using AdamssAsaCallback.
|
| 53 |
+
The update_and_allocate() method is called after optimizer.step() but before
|
| 54 |
+
zero_grad() to compute importance scores from gradients.
|
| 55 |
+
"""
|
| 56 |
+
|
| 57 |
+
def training_step(self, model, inputs, num_items_in_batch=None):
|
| 58 |
+
"""
|
| 59 |
+
Override training_step to add manual ASA update.
|
| 60 |
+
|
| 61 |
+
Training step sequence:
|
| 62 |
+
1. Forward pass
|
| 63 |
+
2. Backward pass (gradients computed)
|
| 64 |
+
3. Optimizer step (parameters updated)
|
| 65 |
+
4. >>> Manual ASA update (importance scoring & masking) <<<
|
| 66 |
+
5. Zero gradients
|
| 67 |
+
"""
|
| 68 |
+
model.train()
|
| 69 |
+
inputs = self._prepare_inputs(inputs)
|
| 70 |
+
|
| 71 |
+
# Forward & backward pass
|
| 72 |
+
with self.compute_loss_context_manager():
|
| 73 |
+
loss = self.compute_loss(model, inputs)
|
| 74 |
+
|
| 75 |
+
if self.args.gradient_accumulation_steps > 1:
|
| 76 |
+
loss = loss / self.args.gradient_accumulation_steps
|
| 77 |
+
|
| 78 |
+
self.accelerator.backward(loss)
|
| 79 |
+
|
| 80 |
+
# 🔑 Key: Manual ASA update after backward, before zero_grad
|
| 81 |
+
# This is where update_and_allocate() inspects gradients and applies masking
|
| 82 |
+
if (
|
| 83 |
+
hasattr(model, "base_model")
|
| 84 |
+
and hasattr(model.base_model, "update_and_allocate")
|
| 85 |
+
and (self.state.global_step + 1) % self.args.gradient_accumulation_steps == 0
|
| 86 |
+
):
|
| 87 |
+
# Only call if we're actually doing optimizer step (not accumulating)
|
| 88 |
+
model.base_model.update_and_allocate(self.state.global_step)
|
| 89 |
+
|
| 90 |
+
return loss.detach()
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
@dataclass
|
| 94 |
+
class AdaMSSArguments:
|
| 95 |
+
"""Arguments for AdaMSS configuration."""
|
| 96 |
+
|
| 97 |
+
# Basic AdaMSS parameters
|
| 98 |
+
adamss_r: int = field(default=100, metadata={"help": "SVD decomposition rank (R in paper)."})
|
| 99 |
+
adamss_k: int = field(default=10, metadata={"help": "Number of subspaces (K in paper)."})
|
| 100 |
+
adamss_ri: int = field(default=1, metadata={"help": "Subspace rank (rk in paper), typically 1 for NLU."})
|
| 101 |
+
|
| 102 |
+
# Training configuration
|
| 103 |
+
num_epochs: int = field(default=100, metadata={"help": "Number of training epochs."})
|
| 104 |
+
batch_size: int = field(default=32, metadata={"help": "Batch size per device."})
|
| 105 |
+
warmup_ratio: float = field(default=0.06, metadata={"help": "Warmup ratio."})
|
| 106 |
+
seed: int = field(default=0, metadata={"help": "Random seed."})
|
| 107 |
+
output_dir: str = field(default="./output", metadata={"help": "Output directory."})
|
| 108 |
+
|
| 109 |
+
# ASA parameters
|
| 110 |
+
use_asa: bool = field(default=False, metadata={"help": "Enable Adaptive Subspace Allocation (manual mode)."})
|
| 111 |
+
asa_target_subspaces: int = field(
|
| 112 |
+
default=5, metadata={"help": "Target number of active subspaces when ASA is enabled."}
|
| 113 |
+
)
|
| 114 |
+
asa_init_warmup: int = field(default=5, metadata={"help": "ASA warmup EPOCHS before starting masking."})
|
| 115 |
+
asa_final_warmup: int = field(default=95, metadata={"help": "ASA EPOCHS to reach target active subspaces."})
|
| 116 |
+
asa_mask_interval: int = field(default=10, metadata={"help": "EPOCHS between ASA updates."})
|
| 117 |
+
asa_importance_beta: float = field(default=0.85, metadata={"help": "EMA coefficient for importance."})
|
| 118 |
+
asa_uncertainty_beta: float = field(default=0.85, metadata={"help": "EMA coefficient for uncertainty."})
|
| 119 |
+
asa_schedule_exponent: float = field(default=3.0, metadata={"help": "ASA schedule exponent."})
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
@dataclass
|
| 123 |
+
class DataArguments:
|
| 124 |
+
"""Arguments for dataset configuration."""
|
| 125 |
+
|
| 126 |
+
dataset_name: str = field(default="cola", metadata={"help": "GLUE task name (cola, mrpc, qnli, rte, stsb, sst2)."})
|
| 127 |
+
max_length: int = field(default=512, metadata={"help": "Maximum sequence length."})
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
# Hyperparameters from Table 19 in the paper
|
| 131 |
+
HYPERPARAMS = {
|
| 132 |
+
"roberta-large": {
|
| 133 |
+
"cola": {"lr": 0.005, "head_lr": 0.0005, "wd": 0.1},
|
| 134 |
+
"mrpc": {"lr": 0.001, "head_lr": 0.00005, "wd": 0.005},
|
| 135 |
+
"qnli": {"lr": 0.0005, "head_lr": 0.05, "wd": 0.005},
|
| 136 |
+
"rte": {"lr": 0.005, "head_lr": 0.005, "wd": 0.5},
|
| 137 |
+
"stsb": {"lr": 0.001, "head_lr": 0.0005, "wd": 0.0005},
|
| 138 |
+
"sst2": {"lr": 0.001, "head_lr": 0.0005, "wd": 0.0},
|
| 139 |
+
},
|
| 140 |
+
"roberta-base": {
|
| 141 |
+
"cola": {"lr": 0.001, "head_lr": 0.005, "wd": 0.005},
|
| 142 |
+
"mrpc": {"lr": 0.01, "head_lr": 0.0005, "wd": 0.0},
|
| 143 |
+
"qnli": {"lr": 0.001, "head_lr": 0.005, "wd": 0.005},
|
| 144 |
+
"rte": {"lr": 0.0005, "head_lr": 0.005, "wd": 0.005},
|
| 145 |
+
"stsb": {"lr": 0.001, "head_lr": 0.005, "wd": 0.005},
|
| 146 |
+
"sst2": {"lr": 0.001, "head_lr": 0.005, "wd": 0.0005},
|
| 147 |
+
},
|
| 148 |
+
}
|
| 149 |
+
|
| 150 |
+
# Metrics for each task
|
| 151 |
+
TASK_METRICS = {
|
| 152 |
+
"cola": "matthews_correlation",
|
| 153 |
+
"stsb": "pearson",
|
| 154 |
+
"mrpc": "accuracy",
|
| 155 |
+
"qqp": "accuracy",
|
| 156 |
+
"sst2": "accuracy",
|
| 157 |
+
"qnli": "accuracy",
|
| 158 |
+
"rte": "accuracy",
|
| 159 |
+
}
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
def main():
|
| 163 |
+
# Parse arguments
|
| 164 |
+
parser = HfArgumentParser((DataArguments, AdaMSSArguments))
|
| 165 |
+
data_args, adamss_args = parser.parse_args_into_dataclasses()
|
| 166 |
+
|
| 167 |
+
# Set seed
|
| 168 |
+
set_seed(adamss_args.seed)
|
| 169 |
+
|
| 170 |
+
# Extract model name from output_dir or use default
|
| 171 |
+
if "roberta-large" in str(adamss_args.output_dir).lower():
|
| 172 |
+
model_name = "roberta-large"
|
| 173 |
+
else:
|
| 174 |
+
model_name = "roberta-base"
|
| 175 |
+
|
| 176 |
+
print("=" * 80)
|
| 177 |
+
print(f"AdaMSS with MANUAL ASA - GLUE Task: {data_args.dataset_name.upper()}")
|
| 178 |
+
print("=" * 80)
|
| 179 |
+
print(f"Model: {model_name}")
|
| 180 |
+
print(f"AdaMSS: r={adamss_args.adamss_r}, K={adamss_args.adamss_k}, ri={adamss_args.adamss_ri}")
|
| 181 |
+
|
| 182 |
+
# Get hyperparameters
|
| 183 |
+
if model_name in HYPERPARAMS and data_args.dataset_name in HYPERPARAMS[model_name]:
|
| 184 |
+
hp = HYPERPARAMS[model_name][data_args.dataset_name]
|
| 185 |
+
print(f"Hyperparameters (Table 19): lr={hp['lr']}, head_lr={hp['head_lr']}, wd={hp['wd']}")
|
| 186 |
+
else:
|
| 187 |
+
hp = {"lr": 0.001, "head_lr": 0.005, "wd": 0.005}
|
| 188 |
+
print(f"Using default hyperparameters: {hp}")
|
| 189 |
+
|
| 190 |
+
print(f"Training: {adamss_args.num_epochs} epochs, batch_size={adamss_args.batch_size}, seed={adamss_args.seed}")
|
| 191 |
+
|
| 192 |
+
if adamss_args.use_asa:
|
| 193 |
+
print(f"Manual ASA Mode: Target {adamss_args.asa_target_subspaces}/{adamss_args.adamss_k} subspaces")
|
| 194 |
+
print(f" Warmup epochs {adamss_args.asa_init_warmup} → {adamss_args.asa_final_warmup}")
|
| 195 |
+
print(" Using update_and_allocate() instead of AdamssAsaCallback")
|
| 196 |
+
|
| 197 |
+
# Load dataset
|
| 198 |
+
print(f"\nLoading {data_args.dataset_name} dataset...")
|
| 199 |
+
dataset = load_dataset("glue", data_args.dataset_name)
|
| 200 |
+
|
| 201 |
+
# Get task info
|
| 202 |
+
is_regression = data_args.dataset_name == "stsb"
|
| 203 |
+
if not is_regression:
|
| 204 |
+
label_list = dataset["train"].features["label"].names
|
| 205 |
+
num_labels = len(label_list)
|
| 206 |
+
else:
|
| 207 |
+
num_labels = 1
|
| 208 |
+
|
| 209 |
+
print(f"Dataset loaded - Task type: {'regression' if is_regression else 'classification'}")
|
| 210 |
+
|
| 211 |
+
# Load tokenizer and model
|
| 212 |
+
print(f"\nLoading {model_name}...")
|
| 213 |
+
tokenizer = AutoTokenizer.from_pretrained(model_name)
|
| 214 |
+
model = AutoModelForSequenceClassification.from_pretrained(
|
| 215 |
+
model_name,
|
| 216 |
+
num_labels=num_labels,
|
| 217 |
+
)
|
| 218 |
+
|
| 219 |
+
# Tokenize dataset
|
| 220 |
+
def preprocess_function(examples):
|
| 221 |
+
# Handle different GLUE tasks
|
| 222 |
+
if data_args.dataset_name in ["mrpc", "stsb", "qqp"]:
|
| 223 |
+
texts = (examples["sentence1"], examples["sentence2"])
|
| 224 |
+
elif data_args.dataset_name == "qnli":
|
| 225 |
+
texts = (examples["question"], examples["sentence"])
|
| 226 |
+
elif data_args.dataset_name == "rte":
|
| 227 |
+
texts = (examples["sentence1"], examples["sentence2"])
|
| 228 |
+
else: # cola, sst2, etc.
|
| 229 |
+
texts = (examples["sentence"],)
|
| 230 |
+
|
| 231 |
+
result = tokenizer(*texts, truncation=True, max_length=data_args.max_length, padding="max_length")
|
| 232 |
+
result["labels"] = examples["label"]
|
| 233 |
+
return result
|
| 234 |
+
|
| 235 |
+
print("Tokenizing dataset...")
|
| 236 |
+
# Remove all columns except label
|
| 237 |
+
columns_to_remove = [col for col in dataset["train"].column_names if col != "label"]
|
| 238 |
+
tokenized_datasets = dataset.map(
|
| 239 |
+
preprocess_function,
|
| 240 |
+
batched=True,
|
| 241 |
+
remove_columns=columns_to_remove,
|
| 242 |
+
)
|
| 243 |
+
|
| 244 |
+
train_ds = tokenized_datasets["train"]
|
| 245 |
+
val_ds = tokenized_datasets["validation"]
|
| 246 |
+
test_key = "test" if "test" in tokenized_datasets else "validation"
|
| 247 |
+
test_ds = tokenized_datasets[test_key]
|
| 248 |
+
|
| 249 |
+
# Create TrainingArguments manually (not parsed to avoid conflicts)
|
| 250 |
+
training_args = TrainingArguments(
|
| 251 |
+
output_dir=adamss_args.output_dir,
|
| 252 |
+
num_train_epochs=adamss_args.num_epochs,
|
| 253 |
+
per_device_train_batch_size=adamss_args.batch_size,
|
| 254 |
+
per_device_eval_batch_size=adamss_args.batch_size,
|
| 255 |
+
learning_rate=hp["lr"],
|
| 256 |
+
weight_decay=hp["wd"],
|
| 257 |
+
warmup_ratio=adamss_args.warmup_ratio,
|
| 258 |
+
eval_strategy="epoch",
|
| 259 |
+
save_strategy="epoch",
|
| 260 |
+
load_best_model_at_end=True,
|
| 261 |
+
metric_for_best_model=TASK_METRICS.get(data_args.dataset_name, "accuracy"),
|
| 262 |
+
greater_is_better=True,
|
| 263 |
+
logging_steps=100,
|
| 264 |
+
logging_strategy="steps",
|
| 265 |
+
seed=adamss_args.seed,
|
| 266 |
+
report_to="none",
|
| 267 |
+
remove_unused_columns=False, # PEFT wraps forward(*args, **kwargs)
|
| 268 |
+
label_names=["labels"], # Explicitly tell Trainer where labels are
|
| 269 |
+
)
|
| 270 |
+
|
| 271 |
+
# Configure AdaMSS with ASA parameters stored in config
|
| 272 |
+
print("\nApplying AdaMSS...")
|
| 273 |
+
|
| 274 |
+
# Convert epoch-based parameters to step-based for config
|
| 275 |
+
steps_per_epoch = len(train_ds) // adamss_args.batch_size
|
| 276 |
+
if len(train_ds) % adamss_args.batch_size != 0:
|
| 277 |
+
steps_per_epoch += 1
|
| 278 |
+
total_steps = adamss_args.num_epochs * steps_per_epoch
|
| 279 |
+
|
| 280 |
+
print("\n[Training Configuration]")
|
| 281 |
+
print(f"Dataset size: {len(train_ds)}")
|
| 282 |
+
print(f"Batch size: {adamss_args.batch_size}")
|
| 283 |
+
print(f"Steps per epoch: {steps_per_epoch}")
|
| 284 |
+
print(f"Total steps: {adamss_args.num_epochs} epochs × {steps_per_epoch} steps = {total_steps} steps")
|
| 285 |
+
|
| 286 |
+
asa_init_warmup_steps = adamss_args.asa_init_warmup * steps_per_epoch
|
| 287 |
+
asa_final_warmup_steps = adamss_args.asa_final_warmup * steps_per_epoch
|
| 288 |
+
asa_mask_interval_steps = adamss_args.asa_mask_interval * steps_per_epoch
|
| 289 |
+
|
| 290 |
+
if adamss_args.use_asa:
|
| 291 |
+
print("\n[ASA Configuration (Epoch → Step Conversion)]")
|
| 292 |
+
print(f" init warmup: {adamss_args.asa_init_warmup} epochs → {asa_init_warmup_steps} steps")
|
| 293 |
+
print(f" final warmup: {adamss_args.asa_final_warmup} epochs → {asa_final_warmup_steps} steps")
|
| 294 |
+
print(f" mask interval: {adamss_args.asa_mask_interval} epochs → {asa_mask_interval_steps} steps")
|
| 295 |
+
|
| 296 |
+
config = AdamssConfig(
|
| 297 |
+
r=adamss_args.adamss_r,
|
| 298 |
+
num_subspaces=adamss_args.adamss_k,
|
| 299 |
+
subspace_rank=adamss_args.adamss_ri,
|
| 300 |
+
target_modules=["query", "value"],
|
| 301 |
+
use_asa=adamss_args.use_asa,
|
| 302 |
+
asa_target_subspaces=adamss_args.asa_target_subspaces if adamss_args.use_asa else None,
|
| 303 |
+
# Store step-based ASA parameters in config
|
| 304 |
+
init_warmup=asa_init_warmup_steps if adamss_args.use_asa else None,
|
| 305 |
+
final_warmup=asa_final_warmup_steps if adamss_args.use_asa else None,
|
| 306 |
+
mask_interval=asa_mask_interval_steps if adamss_args.use_asa else None,
|
| 307 |
+
asa_importance_beta=adamss_args.asa_importance_beta if adamss_args.use_asa else None,
|
| 308 |
+
asa_uncertainty_beta=adamss_args.asa_uncertainty_beta if adamss_args.use_asa else None,
|
| 309 |
+
asa_schedule_exponent=adamss_args.asa_schedule_exponent if adamss_args.use_asa else None,
|
| 310 |
+
modules_to_save=["classifier"],
|
| 311 |
+
)
|
| 312 |
+
|
| 313 |
+
model = get_peft_model(model, config)
|
| 314 |
+
model.print_trainable_parameters()
|
| 315 |
+
|
| 316 |
+
# Print detailed parameter breakdown (same logic as exec_adamss_peft_glue.py)
|
| 317 |
+
print("\n[Detailed Parameter Breakdown]")
|
| 318 |
+
head_params = [p for n, p in model.named_parameters() if ("classifier" in n or "score" in n) and p.requires_grad]
|
| 319 |
+
other_params = [
|
| 320 |
+
p for n, p in model.named_parameters() if ("classifier" not in n and "score" not in n) and p.requires_grad
|
| 321 |
+
]
|
| 322 |
+
head_count = sum(p.numel() for p in head_params)
|
| 323 |
+
adapter_count = sum(p.numel() for p in other_params)
|
| 324 |
+
print(f"Classifier Head Params: {head_count:,}")
|
| 325 |
+
print(f"AdaMSS Adapter Params: {adapter_count:,}")
|
| 326 |
+
print(f"Total Trainable Params: {head_count + adapter_count:,}")
|
| 327 |
+
|
| 328 |
+
# GPU memory monitoring
|
| 329 |
+
if torch.cuda.is_available():
|
| 330 |
+
torch.cuda.empty_cache()
|
| 331 |
+
torch.cuda.reset_peak_memory_stats()
|
| 332 |
+
print("\n[GPU Memory - Before Training]")
|
| 333 |
+
print(f"Allocated: {torch.cuda.memory_allocated() / 1024**3:.2f} GB")
|
| 334 |
+
print(f"Reserved: {torch.cuda.memory_reserved() / 1024**3:.2f} GB")
|
| 335 |
+
|
| 336 |
+
# Metrics
|
| 337 |
+
metric = evaluate.load("glue", data_args.dataset_name)
|
| 338 |
+
|
| 339 |
+
def compute_metrics(p: EvalPrediction):
|
| 340 |
+
preds = p.predictions[0] if isinstance(p.predictions, tuple) else p.predictions
|
| 341 |
+
preds = np.squeeze(preds) if is_regression else np.argmax(preds, axis=1)
|
| 342 |
+
return metric.compute(predictions=preds, references=p.label_ids)
|
| 343 |
+
|
| 344 |
+
# Create custom optimizer with different LR for head
|
| 345 |
+
from torch.optim import AdamW
|
| 346 |
+
|
| 347 |
+
optimizer_grouped_parameters = [
|
| 348 |
+
{
|
| 349 |
+
"params": [
|
| 350 |
+
p for n, p in model.named_parameters() if ("classifier" in n or "score" in n) and p.requires_grad
|
| 351 |
+
],
|
| 352 |
+
"lr": hp["head_lr"],
|
| 353 |
+
},
|
| 354 |
+
{
|
| 355 |
+
"params": [
|
| 356 |
+
p
|
| 357 |
+
for n, p in model.named_parameters()
|
| 358 |
+
if ("classifier" not in n and "score" not in n) and p.requires_grad
|
| 359 |
+
],
|
| 360 |
+
"lr": hp["lr"],
|
| 361 |
+
},
|
| 362 |
+
]
|
| 363 |
+
optimizer = AdamW(optimizer_grouped_parameters, weight_decay=hp["wd"])
|
| 364 |
+
|
| 365 |
+
# Create trainer with custom class that calls update_and_allocate()
|
| 366 |
+
# Note: NO callbacks here - we're using manual approach
|
| 367 |
+
trainer = CustomTrainerWithManualASA(
|
| 368 |
+
model=model,
|
| 369 |
+
args=training_args,
|
| 370 |
+
train_dataset=train_ds,
|
| 371 |
+
eval_dataset=val_ds,
|
| 372 |
+
compute_metrics=compute_metrics,
|
| 373 |
+
optimizers=(optimizer, None),
|
| 374 |
+
)
|
| 375 |
+
|
| 376 |
+
# Train
|
| 377 |
+
print("\n" + "=" * 80)
|
| 378 |
+
print("Starting training...")
|
| 379 |
+
if adamss_args.use_asa:
|
| 380 |
+
print("Manual ASA: update_and_allocate() will be called in training_step")
|
| 381 |
+
print("=" * 80 + "\n")
|
| 382 |
+
|
| 383 |
+
train_result = trainer.train()
|
| 384 |
+
|
| 385 |
+
# GPU memory stats
|
| 386 |
+
if torch.cuda.is_available():
|
| 387 |
+
print("\n[GPU Memory - Peak During Training]")
|
| 388 |
+
print(f"Peak Allocated: {torch.cuda.max_memory_allocated() / 1024**3:.2f} GB")
|
| 389 |
+
print(f"Peak Reserved: {torch.cuda.max_memory_reserved() / 1024**3:.2f} GB")
|
| 390 |
+
|
| 391 |
+
# Print best metric
|
| 392 |
+
if trainer.state.best_metric is not None:
|
| 393 |
+
metric_name = TASK_METRICS.get(data_args.dataset_name, "accuracy")
|
| 394 |
+
print("\n[Best Model Info]")
|
| 395 |
+
print(f"Best {metric_name}: {trainer.state.best_metric:.4f}")
|
| 396 |
+
|
| 397 |
+
# Evaluate on validation set (use val_ds, not test_ds to avoid label issues)
|
| 398 |
+
print("\n" + "=" * 80)
|
| 399 |
+
print("Final evaluation on validation set...")
|
| 400 |
+
print("=" * 80 + "\n")
|
| 401 |
+
|
| 402 |
+
final_metrics = trainer.evaluate(val_ds)
|
| 403 |
+
print(f"\nFinal Validation Results: {final_metrics}")
|
| 404 |
+
|
| 405 |
+
# Save model
|
| 406 |
+
trainer.save_model()
|
| 407 |
+
print(f"\nModel saved to {training_args.output_dir}")
|
| 408 |
+
|
| 409 |
+
|
| 410 |
+
if __name__ == "__main__":
|
| 411 |
+
main()
|
tasks/tasksmith-0d2d1e298e86/tests/source/examples/adamss_finetuning/image_classification_adamss_asa.py
ADDED
|
@@ -0,0 +1,452 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Image Classification with AdaMSS and ASA Callback
|
| 3 |
+
|
| 4 |
+
This script demonstrates how to fine-tune a Vision Transformer (ViT) model
|
| 5 |
+
using AdaMSS (Adaptive Matrix Decomposition with Subspace Selection) and
|
| 6 |
+
ASA (Adaptive Subspace Allocation) callback from PEFT.
|
| 7 |
+
|
| 8 |
+
Example usage:
|
| 9 |
+
python image_classification_adamss_asa.py \\
|
| 10 |
+
--model_name_or_path google/vit-base-patch16-224-in21k \\
|
| 11 |
+
--dataset_name cifar10 \\
|
| 12 |
+
--adamss_r 100 \\
|
| 13 |
+
--adamss_k 10 \\
|
| 14 |
+
--adamss_ri 3 \\
|
| 15 |
+
--use_asa \\
|
| 16 |
+
--asa_target_subspaces 5 \\
|
| 17 |
+
--num_epochs 10 \\
|
| 18 |
+
--output_dir ./output
|
| 19 |
+
|
| 20 |
+
Requirements:
|
| 21 |
+
pip install peft transformers datasets torch torchvision evaluate
|
| 22 |
+
"""
|
| 23 |
+
|
| 24 |
+
from dataclasses import dataclass, field
|
| 25 |
+
from functools import partial
|
| 26 |
+
from typing import Optional
|
| 27 |
+
|
| 28 |
+
import evaluate
|
| 29 |
+
import torch
|
| 30 |
+
from datasets import load_dataset
|
| 31 |
+
from torchvision.transforms import (
|
| 32 |
+
CenterCrop,
|
| 33 |
+
Compose,
|
| 34 |
+
Normalize,
|
| 35 |
+
RandomHorizontalFlip,
|
| 36 |
+
RandomResizedCrop,
|
| 37 |
+
Resize,
|
| 38 |
+
ToTensor,
|
| 39 |
+
)
|
| 40 |
+
from transformers import (
|
| 41 |
+
AutoImageProcessor,
|
| 42 |
+
AutoModelForImageClassification,
|
| 43 |
+
HfArgumentParser,
|
| 44 |
+
Trainer,
|
| 45 |
+
TrainingArguments,
|
| 46 |
+
)
|
| 47 |
+
|
| 48 |
+
from peft import AdamssConfig, get_peft_model
|
| 49 |
+
from peft.tuners.adamss.asa_callback import AdamssAsaCallback
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
# Hyperparameters from Table 18 in the paper
|
| 53 |
+
HYPERPARAMS = {
|
| 54 |
+
"vit-large-patch16-224-in21k": {
|
| 55 |
+
"pets": {"lr": 0.001, "head_lr": 0.0005, "wd": 0.0005},
|
| 56 |
+
"cars": {"lr": 0.01, "head_lr": 0.005, "wd": 0.1},
|
| 57 |
+
"cifar10": {"lr": 0.01, "head_lr": 0.05, "wd": 0.1},
|
| 58 |
+
"cifar100": {"lr": 0.01, "head_lr": 0.05, "wd": 0.05},
|
| 59 |
+
"eurosat": {"lr": 0.01, "head_lr": 0.0005, "wd": 0.01},
|
| 60 |
+
"fgvc": {"lr": 0.01, "head_lr": 0.0005, "wd": 0.0005},
|
| 61 |
+
"resisc": {"lr": 0.01, "head_lr": 0.0005, "wd": 0.1},
|
| 62 |
+
},
|
| 63 |
+
"vit-base-patch16-224-in21k": {
|
| 64 |
+
"pets": {"lr": 0.005, "head_lr": 0.005, "wd": 0.0005},
|
| 65 |
+
"cars": {"lr": 0.01, "head_lr": 0.005, "wd": 0.0},
|
| 66 |
+
"cifar10": {"lr": 0.01, "head_lr": 0.005, "wd": 0.05},
|
| 67 |
+
"cifar100": {"lr": 0.01, "head_lr": 0.005, "wd": 0.05},
|
| 68 |
+
"eurosat": {"lr": 0.01, "head_lr": 0.0005, "wd": 0.05},
|
| 69 |
+
"fgvc": {"lr": 0.01, "head_lr": 0.005, "wd": 0.0005},
|
| 70 |
+
"resisc": {"lr": 0.01, "head_lr": 0.005, "wd": 0.0005},
|
| 71 |
+
},
|
| 72 |
+
}
|
| 73 |
+
|
| 74 |
+
# Model-specific K values (number of subspaces)
|
| 75 |
+
MODEL_K_VALUES = {
|
| 76 |
+
"vit-large-patch16-224-in21k": 16,
|
| 77 |
+
"vit-base-patch16-224-in21k": 10,
|
| 78 |
+
}
|
| 79 |
+
# Dataset configurations (matching exec_adamss_peft.py)
|
| 80 |
+
DATASET_CONFIGS = {
|
| 81 |
+
"cars": {
|
| 82 |
+
"train": "Multimodal-Fatima/StanfordCars_train",
|
| 83 |
+
"test": "Multimodal-Fatima/StanfordCars_test",
|
| 84 |
+
"img_col": "image",
|
| 85 |
+
"label_col": "label",
|
| 86 |
+
},
|
| 87 |
+
"cifar10": {
|
| 88 |
+
"train": "Multimodal-Fatima/CIFAR10_train",
|
| 89 |
+
"test": "Multimodal-Fatima/CIFAR10_test",
|
| 90 |
+
"img_col": "image",
|
| 91 |
+
"label_col": "label",
|
| 92 |
+
},
|
| 93 |
+
"cifar100": {
|
| 94 |
+
"train": "cifar100",
|
| 95 |
+
"test": "cifar100",
|
| 96 |
+
"img_col": "img",
|
| 97 |
+
"label_col": "fine_label",
|
| 98 |
+
},
|
| 99 |
+
"eurosat": {
|
| 100 |
+
"dataset": "timm/eurosat-rgb",
|
| 101 |
+
"img_col": "image",
|
| 102 |
+
"label_col": "label",
|
| 103 |
+
},
|
| 104 |
+
"pets": {
|
| 105 |
+
"train": "timm/oxford-iiit-pet",
|
| 106 |
+
"test": "timm/oxford-iiit-pet",
|
| 107 |
+
"img_col": "image",
|
| 108 |
+
"label_col": "label",
|
| 109 |
+
},
|
| 110 |
+
}
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
# Global preprocessing functions (to avoid closure issues with set_transform)
|
| 114 |
+
def _preprocess_images(examples, img_col, transforms):
|
| 115 |
+
"""Apply image transformations."""
|
| 116 |
+
examples["pixel_values"] = [transforms(img.convert("RGB")) for img in examples[img_col]]
|
| 117 |
+
return examples
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
def _collate_batch(examples, label_col):
|
| 121 |
+
"""Collate examples into a batch."""
|
| 122 |
+
pixel_values = torch.stack([ex["pixel_values"] for ex in examples])
|
| 123 |
+
labels = torch.tensor([ex[label_col] for ex in examples])
|
| 124 |
+
return {"pixel_values": pixel_values, "labels": labels}
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
@dataclass
|
| 128 |
+
class ImageClassificationArguments:
|
| 129 |
+
"""Arguments for image classification with AdaMSS and ASA."""
|
| 130 |
+
|
| 131 |
+
# Model configuration
|
| 132 |
+
model_name_or_path: str = field(
|
| 133 |
+
default="google/vit-base-patch16-224-in21k", metadata={"help": "Model identifier: vit-base or vit-large"}
|
| 134 |
+
)
|
| 135 |
+
dataset_name: str = field(
|
| 136 |
+
default="cifar10", metadata={"help": "Dataset: cifar10, cifar100, pets, cars, eurosat, fgvc, resisc"}
|
| 137 |
+
)
|
| 138 |
+
|
| 139 |
+
# AdaMSS Configuration
|
| 140 |
+
adamss_r: int = field(default=100, metadata={"help": "SVD rank"})
|
| 141 |
+
adamss_k: int = field(default=10, metadata={"help": "Number of subspaces (K), auto-set based on model"})
|
| 142 |
+
adamss_ri: int = field(default=3, metadata={"help": "Subspace rank (rk), use 3 for vision"})
|
| 143 |
+
|
| 144 |
+
# ASA Configuration
|
| 145 |
+
use_asa: bool = field(default=False, metadata={"help": "Enable Adaptive Subspace Allocation"})
|
| 146 |
+
asa_target_subspaces: int = field(default=5, metadata={"help": "Target active subspaces for ASA"})
|
| 147 |
+
asa_init_warmup: int = field(default=50, metadata={"help": "ASA init warmup in STEPS"})
|
| 148 |
+
asa_final_warmup: int = field(default=1000, metadata={"help": "ASA final warmup in STEPS"})
|
| 149 |
+
asa_mask_interval: int = field(default=100, metadata={"help": "ASA mask interval in STEPS"})
|
| 150 |
+
asa_importance_beta: float = field(default=0.85, metadata={"help": "EMA coefficient for importance"})
|
| 151 |
+
asa_uncertainty_beta: float = field(default=0.85, metadata={"help": "EMA coefficient for uncertainty"})
|
| 152 |
+
asa_schedule_exponent: float = field(default=3.0, metadata={"help": "ASA schedule exponent"})
|
| 153 |
+
|
| 154 |
+
# Training Configuration
|
| 155 |
+
num_epochs: int = field(default=10, metadata={"help": "Number of training epochs"})
|
| 156 |
+
batch_size: int = field(default=32, metadata={"help": "Batch size per device"})
|
| 157 |
+
warmup_ratio: float = field(default=0.0, metadata={"help": "Warmup ratio"})
|
| 158 |
+
max_train_samples: Optional[int] = field(default=None, metadata={"help": "Max training samples (for debug)"})
|
| 159 |
+
|
| 160 |
+
# Other
|
| 161 |
+
seed: int = field(default=0, metadata={"help": "Random seed"})
|
| 162 |
+
output_dir: str = field(default="./output", metadata={"help": "Output directory"})
|
| 163 |
+
cache_dir: Optional[str] = field(default=None, metadata={"help": "Cache directory"})
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
def prepare_transforms(image_processor):
|
| 167 |
+
"""Prepare image transformations."""
|
| 168 |
+
normalize = Normalize(mean=image_processor.image_mean, std=image_processor.image_std)
|
| 169 |
+
size = image_processor.size["height"]
|
| 170 |
+
|
| 171 |
+
train_transforms = Compose(
|
| 172 |
+
[
|
| 173 |
+
RandomResizedCrop(size),
|
| 174 |
+
RandomHorizontalFlip(),
|
| 175 |
+
ToTensor(),
|
| 176 |
+
normalize,
|
| 177 |
+
]
|
| 178 |
+
)
|
| 179 |
+
val_transforms = Compose(
|
| 180 |
+
[
|
| 181 |
+
Resize(size),
|
| 182 |
+
CenterCrop(size),
|
| 183 |
+
ToTensor(),
|
| 184 |
+
normalize,
|
| 185 |
+
]
|
| 186 |
+
)
|
| 187 |
+
return train_transforms, val_transforms
|
| 188 |
+
|
| 189 |
+
|
| 190 |
+
def main():
|
| 191 |
+
# Parse arguments
|
| 192 |
+
parser = HfArgumentParser(ImageClassificationArguments)
|
| 193 |
+
args = parser.parse_args_into_dataclasses()[0]
|
| 194 |
+
|
| 195 |
+
# Set seed
|
| 196 |
+
torch.manual_seed(args.seed)
|
| 197 |
+
|
| 198 |
+
# Auto-detect model type and set K value
|
| 199 |
+
model_name = args.model_name_or_path
|
| 200 |
+
model_type = None
|
| 201 |
+
for key in MODEL_K_VALUES:
|
| 202 |
+
if key in model_name:
|
| 203 |
+
model_type = key
|
| 204 |
+
break
|
| 205 |
+
|
| 206 |
+
if model_type is None:
|
| 207 |
+
# Default to base model
|
| 208 |
+
model_type = "vit-base-patch16-224-in21k"
|
| 209 |
+
print(f"Warning: Model type not recognized, defaulting to {model_type}")
|
| 210 |
+
|
| 211 |
+
# Override K value based on model type
|
| 212 |
+
args.adamss_k = MODEL_K_VALUES[model_type]
|
| 213 |
+
|
| 214 |
+
# Get hyperparameters from Table 18
|
| 215 |
+
if model_type in HYPERPARAMS and args.dataset_name in HYPERPARAMS[model_type]:
|
| 216 |
+
hp = HYPERPARAMS[model_type][args.dataset_name]
|
| 217 |
+
print(f"Using Table 18 hyperparameters for {model_type} + {args.dataset_name}")
|
| 218 |
+
print(f" lr={hp['lr']}, head_lr={hp['head_lr']}, wd={hp['wd']}")
|
| 219 |
+
else:
|
| 220 |
+
hp = {"lr": 0.01, "head_lr": 0.005, "wd": 0.0005}
|
| 221 |
+
print(f"Warning: No Table 18 hyperparameters found, using defaults: {hp}")
|
| 222 |
+
|
| 223 |
+
print("\n" + "=" * 80)
|
| 224 |
+
print(f"AdaMSS {'with ASA' if args.use_asa else 'without ASA'} - {args.dataset_name.upper()}")
|
| 225 |
+
print("=" * 80)
|
| 226 |
+
print(f"Model: {model_type}")
|
| 227 |
+
print(f"AdaMSS: r={args.adamss_r}, K={args.adamss_k}, ri={args.adamss_ri}")
|
| 228 |
+
if args.use_asa:
|
| 229 |
+
print(f"ASA: Target {args.asa_target_subspaces}/{args.adamss_k} subspaces")
|
| 230 |
+
print(f" Warmup steps {args.asa_init_warmup} → {args.asa_final_warmup}")
|
| 231 |
+
print(f"Training: {args.num_epochs} epochs, batch_size={args.batch_size}, seed={args.seed}")
|
| 232 |
+
print("=" * 80 + "\n")
|
| 233 |
+
|
| 234 |
+
# Get dataset configuration
|
| 235 |
+
if args.dataset_name not in DATASET_CONFIGS:
|
| 236 |
+
raise ValueError(f"Unsupported dataset: {args.dataset_name}. Supported: {list(DATASET_CONFIGS.keys())}")
|
| 237 |
+
|
| 238 |
+
config = DATASET_CONFIGS[args.dataset_name]
|
| 239 |
+
img_name = config["img_col"]
|
| 240 |
+
label_name = config["label_col"]
|
| 241 |
+
|
| 242 |
+
# Load dataset
|
| 243 |
+
print(f"Loading {args.dataset_name} dataset...")
|
| 244 |
+
if "dataset" in config:
|
| 245 |
+
# Single dataset with train/val/test splits (e.g., eurosat)
|
| 246 |
+
dataset = load_dataset(config["dataset"], cache_dir=args.cache_dir)
|
| 247 |
+
train_val = dataset["train"].train_test_split(test_size=0.1, seed=args.seed)
|
| 248 |
+
train_ds = train_val["train"]
|
| 249 |
+
val_ds = train_val["test"]
|
| 250 |
+
# Try 'test' split, fall back to 'val' if not available
|
| 251 |
+
if "test" in dataset:
|
| 252 |
+
test_ds = dataset["test"]
|
| 253 |
+
elif "val" in dataset:
|
| 254 |
+
test_ds = dataset["val"]
|
| 255 |
+
else:
|
| 256 |
+
print("Warning: No test/val split found, using validation set as test")
|
| 257 |
+
test_ds = val_ds
|
| 258 |
+
else:
|
| 259 |
+
# Separate train and test datasets (e.g., cars, cifar10)
|
| 260 |
+
train_val_ds = load_dataset(config["train"], split="train", cache_dir=args.cache_dir)
|
| 261 |
+
test_ds = load_dataset(config["test"], split="test", cache_dir=args.cache_dir)
|
| 262 |
+
|
| 263 |
+
# Split train into train and validation
|
| 264 |
+
train_val = train_val_ds.train_test_split(test_size=0.1, seed=args.seed)
|
| 265 |
+
train_ds = train_val["train"]
|
| 266 |
+
val_ds = train_val["test"]
|
| 267 |
+
|
| 268 |
+
print(f"Detected columns - Image: '{img_name}', Label: '{label_name}'")
|
| 269 |
+
|
| 270 |
+
# Limit train samples if specified (for quick testing)
|
| 271 |
+
if args.max_train_samples:
|
| 272 |
+
train_ds = train_ds.select(range(min(args.max_train_samples, len(train_ds))))
|
| 273 |
+
# Also limit validation for faster testing
|
| 274 |
+
val_ds = val_ds.select(range(min(5000, len(val_ds))))
|
| 275 |
+
|
| 276 |
+
labels = train_ds.features[label_name].names
|
| 277 |
+
num_classes = len(labels)
|
| 278 |
+
print(f"Dataset loaded: {len(train_ds)} train, {len(val_ds)} val, {len(test_ds)} test")
|
| 279 |
+
print(f" Number of classes: {num_classes}")
|
| 280 |
+
|
| 281 |
+
# Create label mappings
|
| 282 |
+
label2id = {label: i for i, label in enumerate(labels)}
|
| 283 |
+
id2label = dict(enumerate(labels))
|
| 284 |
+
|
| 285 |
+
# Load image processor
|
| 286 |
+
print("\nLoading image processor...")
|
| 287 |
+
image_processor = AutoImageProcessor.from_pretrained(
|
| 288 |
+
args.model_name_or_path,
|
| 289 |
+
cache_dir=args.cache_dir,
|
| 290 |
+
)
|
| 291 |
+
|
| 292 |
+
# Prepare transforms
|
| 293 |
+
train_transforms, val_transforms = prepare_transforms(image_processor)
|
| 294 |
+
|
| 295 |
+
# Use partial to bind parameters at module level (avoid set_transform closure issues)
|
| 296 |
+
train_ds.set_transform(partial(_preprocess_images, img_col=img_name, transforms=train_transforms))
|
| 297 |
+
val_ds.set_transform(partial(_preprocess_images, img_col=img_name, transforms=val_transforms))
|
| 298 |
+
test_ds.set_transform(partial(_preprocess_images, img_col=img_name, transforms=val_transforms))
|
| 299 |
+
|
| 300 |
+
# Data collator
|
| 301 |
+
collate_fn = partial(_collate_batch, label_col=label_name)
|
| 302 |
+
|
| 303 |
+
# Load base model
|
| 304 |
+
print("\nLoading base model...")
|
| 305 |
+
model = AutoModelForImageClassification.from_pretrained(
|
| 306 |
+
args.model_name_or_path,
|
| 307 |
+
num_labels=num_classes,
|
| 308 |
+
label2id=label2id,
|
| 309 |
+
id2label=id2label,
|
| 310 |
+
ignore_mismatched_sizes=True,
|
| 311 |
+
cache_dir=args.cache_dir,
|
| 312 |
+
)
|
| 313 |
+
|
| 314 |
+
# Configure AdaMSS
|
| 315 |
+
print("\nApplying AdaMSS...")
|
| 316 |
+
config = AdamssConfig(
|
| 317 |
+
r=args.adamss_r,
|
| 318 |
+
num_subspaces=args.adamss_k,
|
| 319 |
+
subspace_rank=args.adamss_ri,
|
| 320 |
+
target_modules=["query", "value"],
|
| 321 |
+
use_asa=args.use_asa,
|
| 322 |
+
asa_target_subspaces=args.asa_target_subspaces if args.use_asa else None,
|
| 323 |
+
init_warmup=args.asa_init_warmup if args.use_asa else None,
|
| 324 |
+
final_warmup=args.asa_final_warmup if args.use_asa else None,
|
| 325 |
+
mask_interval=args.asa_mask_interval if args.use_asa else None,
|
| 326 |
+
asa_importance_beta=args.asa_importance_beta if args.use_asa else None,
|
| 327 |
+
asa_uncertainty_beta=args.asa_uncertainty_beta if args.use_asa else None,
|
| 328 |
+
asa_schedule_exponent=args.asa_schedule_exponent if args.use_asa else None,
|
| 329 |
+
modules_to_save=["classifier"],
|
| 330 |
+
)
|
| 331 |
+
|
| 332 |
+
# Apply PEFT
|
| 333 |
+
model = get_peft_model(model, config)
|
| 334 |
+
model.print_trainable_parameters()
|
| 335 |
+
|
| 336 |
+
# Print detailed parameter breakdown (same logic as exec_adamss_peft.py)
|
| 337 |
+
print("\n[Detailed Parameter Breakdown]")
|
| 338 |
+
trainable_params = sum(p.numel() for p in model.parameters() if p.requires_grad)
|
| 339 |
+
head_params = sum(p.numel() for n, p in model.named_parameters() if "classifier" in n and p.requires_grad)
|
| 340 |
+
adamss_params = trainable_params - head_params
|
| 341 |
+
print(f"Classifier Head Params: {head_params:,}")
|
| 342 |
+
print(f"AdaMSS Adapter Params: {adamss_params:,}")
|
| 343 |
+
print(f"Total Trainable Params: {trainable_params:,}")
|
| 344 |
+
|
| 345 |
+
# Setup ASA callback if enabled
|
| 346 |
+
callbacks = []
|
| 347 |
+
if args.use_asa:
|
| 348 |
+
print("\nSetting up ASA callback...")
|
| 349 |
+
asa_callback = AdamssAsaCallback()
|
| 350 |
+
callbacks.append(asa_callback)
|
| 351 |
+
|
| 352 |
+
# Metrics
|
| 353 |
+
metric = evaluate.load("accuracy")
|
| 354 |
+
|
| 355 |
+
def compute_metrics(eval_pred):
|
| 356 |
+
preds = eval_pred.predictions
|
| 357 |
+
# Handle tuple outputs (logits, hidden_states)
|
| 358 |
+
if isinstance(preds, tuple):
|
| 359 |
+
preds = preds[0]
|
| 360 |
+
predictions = preds.argmax(axis=1)
|
| 361 |
+
return metric.compute(predictions=predictions, references=eval_pred.label_ids)
|
| 362 |
+
|
| 363 |
+
# Create TrainingArguments manually (not parsed to avoid conflicts)
|
| 364 |
+
training_args = TrainingArguments(
|
| 365 |
+
output_dir=args.output_dir,
|
| 366 |
+
num_train_epochs=args.num_epochs,
|
| 367 |
+
per_device_train_batch_size=args.batch_size,
|
| 368 |
+
per_device_eval_batch_size=args.batch_size,
|
| 369 |
+
learning_rate=hp["lr"],
|
| 370 |
+
weight_decay=hp["wd"],
|
| 371 |
+
warmup_ratio=args.warmup_ratio,
|
| 372 |
+
eval_strategy="epoch",
|
| 373 |
+
save_strategy="epoch",
|
| 374 |
+
load_best_model_at_end=True,
|
| 375 |
+
metric_for_best_model="accuracy",
|
| 376 |
+
greater_is_better=True,
|
| 377 |
+
logging_steps=100,
|
| 378 |
+
logging_strategy="steps",
|
| 379 |
+
seed=args.seed,
|
| 380 |
+
report_to="none",
|
| 381 |
+
remove_unused_columns=False, # Required for set_transform compatibility
|
| 382 |
+
label_names=["labels"], # Explicitly tell Trainer where labels are (PEFT hides model signature)
|
| 383 |
+
)
|
| 384 |
+
|
| 385 |
+
# Create custom optimizer with different LR for head
|
| 386 |
+
from torch.optim import AdamW
|
| 387 |
+
|
| 388 |
+
optimizer_grouped_parameters = [
|
| 389 |
+
{
|
| 390 |
+
"params": [p for n, p in model.named_parameters() if "classifier" in n and p.requires_grad],
|
| 391 |
+
"lr": hp["head_lr"],
|
| 392 |
+
},
|
| 393 |
+
{
|
| 394 |
+
"params": [p for n, p in model.named_parameters() if "classifier" not in n and p.requires_grad],
|
| 395 |
+
"lr": hp["lr"],
|
| 396 |
+
},
|
| 397 |
+
]
|
| 398 |
+
optimizer = AdamW(optimizer_grouped_parameters, weight_decay=hp["wd"])
|
| 399 |
+
|
| 400 |
+
# Create trainer
|
| 401 |
+
trainer = Trainer(
|
| 402 |
+
model=model,
|
| 403 |
+
args=training_args,
|
| 404 |
+
train_dataset=train_ds,
|
| 405 |
+
eval_dataset=val_ds,
|
| 406 |
+
data_collator=collate_fn,
|
| 407 |
+
compute_metrics=compute_metrics,
|
| 408 |
+
optimizers=(optimizer, None),
|
| 409 |
+
callbacks=callbacks,
|
| 410 |
+
)
|
| 411 |
+
|
| 412 |
+
# GPU memory monitoring
|
| 413 |
+
if torch.cuda.is_available():
|
| 414 |
+
torch.cuda.empty_cache()
|
| 415 |
+
torch.cuda.reset_peak_memory_stats()
|
| 416 |
+
print("\n[GPU Memory - Before Training]")
|
| 417 |
+
print(f"Allocated: {torch.cuda.memory_allocated() / 1024**3:.2f} GB")
|
| 418 |
+
print(f"Reserved: {torch.cuda.memory_reserved() / 1024**3:.2f} GB")
|
| 419 |
+
|
| 420 |
+
# Train
|
| 421 |
+
print("\n" + "=" * 80)
|
| 422 |
+
print("Starting training...")
|
| 423 |
+
print("=" * 80 + "\n")
|
| 424 |
+
|
| 425 |
+
train_result = trainer.train()
|
| 426 |
+
|
| 427 |
+
# GPU memory stats
|
| 428 |
+
if torch.cuda.is_available():
|
| 429 |
+
print("\n[GPU Memory - Peak During Training]")
|
| 430 |
+
print(f"Peak Allocated: {torch.cuda.max_memory_allocated() / 1024**3:.2f} GB")
|
| 431 |
+
print(f"Peak Reserved: {torch.cuda.max_memory_reserved() / 1024**3:.2f} GB")
|
| 432 |
+
|
| 433 |
+
# Print best metric
|
| 434 |
+
if trainer.state.best_metric is not None:
|
| 435 |
+
print("\n[Best Model Info]")
|
| 436 |
+
print(f"Best accuracy: {trainer.state.best_metric:.4f}")
|
| 437 |
+
|
| 438 |
+
# Evaluate on test set
|
| 439 |
+
print("\n" + "=" * 80)
|
| 440 |
+
print("Evaluating on test set...")
|
| 441 |
+
print("=" * 80 + "\n")
|
| 442 |
+
|
| 443 |
+
test_metrics = trainer.evaluate(test_ds, metric_key_prefix="test")
|
| 444 |
+
print(f"\nTest Accuracy: {test_metrics['test_accuracy']:.4f}")
|
| 445 |
+
|
| 446 |
+
# Save model
|
| 447 |
+
trainer.save_model()
|
| 448 |
+
print(f"\nModel saved to {training_args.output_dir}")
|
| 449 |
+
|
| 450 |
+
|
| 451 |
+
if __name__ == "__main__":
|
| 452 |
+
main()
|
tasks/tasksmith-0d2d1e298e86/tests/source/examples/adamss_finetuning/test_adamss_quick.py
ADDED
|
@@ -0,0 +1,176 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Quick test for AdaMSS example - runs 1 epoch on small subset
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
import sys
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
sys.path.insert(0, "/Users/onelong/Documents/WorkSpace/CodeSpace/AdaMSS-main/peft-main/src")
|
| 9 |
+
|
| 10 |
+
import evaluate
|
| 11 |
+
import torch
|
| 12 |
+
from datasets import load_dataset
|
| 13 |
+
from torchvision.transforms import (
|
| 14 |
+
CenterCrop,
|
| 15 |
+
Compose,
|
| 16 |
+
Normalize,
|
| 17 |
+
RandomHorizontalFlip,
|
| 18 |
+
RandomResizedCrop,
|
| 19 |
+
Resize,
|
| 20 |
+
ToTensor,
|
| 21 |
+
)
|
| 22 |
+
from transformers import AutoImageProcessor, AutoModelForImageClassification, Trainer, TrainingArguments
|
| 23 |
+
|
| 24 |
+
from peft import AdaMSSConfig, ASACallback, get_peft_model
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
print("=" * 80)
|
| 28 |
+
print("🧪 AdaMSS Quick Test")
|
| 29 |
+
print("=" * 80)
|
| 30 |
+
|
| 31 |
+
# Load small subset
|
| 32 |
+
print("\n📦 Loading CIFAR-10 (small subset for testing)...")
|
| 33 |
+
dataset = load_dataset("cifar10")
|
| 34 |
+
train_val = dataset["train"].train_test_split(test_size=0.1, seed=42)
|
| 35 |
+
train_ds = train_val["train"].select(range(100)) # Only 100 samples
|
| 36 |
+
val_ds = train_val["test"].select(range(50))
|
| 37 |
+
|
| 38 |
+
print(f"✅ Dataset: {len(train_ds)} train, {len(val_ds)} val")
|
| 39 |
+
|
| 40 |
+
# Prepare data
|
| 41 |
+
image_processor = AutoImageProcessor.from_pretrained("google/vit-base-patch16-224-in21k")
|
| 42 |
+
normalize = Normalize(mean=image_processor.image_mean, std=image_processor.image_std)
|
| 43 |
+
|
| 44 |
+
train_transforms = Compose(
|
| 45 |
+
[
|
| 46 |
+
RandomResizedCrop(image_processor.size["height"]),
|
| 47 |
+
RandomHorizontalFlip(),
|
| 48 |
+
ToTensor(),
|
| 49 |
+
normalize,
|
| 50 |
+
]
|
| 51 |
+
)
|
| 52 |
+
|
| 53 |
+
val_transforms = Compose(
|
| 54 |
+
[
|
| 55 |
+
Resize(image_processor.size["height"]),
|
| 56 |
+
CenterCrop(image_processor.size["height"]),
|
| 57 |
+
ToTensor(),
|
| 58 |
+
normalize,
|
| 59 |
+
]
|
| 60 |
+
)
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def preprocess_train(examples):
|
| 64 |
+
examples["pixel_values"] = [train_transforms(img.convert("RGB")) for img in examples["img"]]
|
| 65 |
+
return examples
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def preprocess_val(examples):
|
| 69 |
+
examples["pixel_values"] = [val_transforms(img.convert("RGB")) for img in examples["img"]]
|
| 70 |
+
return examples
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
train_ds.set_transform(preprocess_train)
|
| 74 |
+
val_ds.set_transform(preprocess_val)
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def collate_fn(examples):
|
| 78 |
+
pixel_values = torch.stack([example["pixel_values"] for example in examples])
|
| 79 |
+
labels = torch.tensor([example["label"] for example in examples])
|
| 80 |
+
return {"pixel_values": pixel_values, "labels": labels}
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
# Load model
|
| 84 |
+
print("\n🤖 Loading ViT model...")
|
| 85 |
+
model = AutoModelForImageClassification.from_pretrained(
|
| 86 |
+
"google/vit-base-patch16-224-in21k",
|
| 87 |
+
num_labels=10,
|
| 88 |
+
ignore_mismatched_sizes=True,
|
| 89 |
+
)
|
| 90 |
+
|
| 91 |
+
# Configure AdaMSS
|
| 92 |
+
print("\n⚙️ Applying AdaMSS...")
|
| 93 |
+
config = AdaMSSConfig(
|
| 94 |
+
r=100,
|
| 95 |
+
num_subspaces=10,
|
| 96 |
+
subspace_rank=3,
|
| 97 |
+
target_modules=["query", "value"],
|
| 98 |
+
use_asa=True,
|
| 99 |
+
target_kk=5,
|
| 100 |
+
modules_to_save=["classifier"],
|
| 101 |
+
)
|
| 102 |
+
|
| 103 |
+
model = get_peft_model(model, config)
|
| 104 |
+
print("\n📊 Parameter statistics:")
|
| 105 |
+
model.print_trainable_parameters()
|
| 106 |
+
|
| 107 |
+
# Setup ASA callback
|
| 108 |
+
print("\n🔥 Setting up ASA callback...")
|
| 109 |
+
asa_callback = ASACallback(
|
| 110 |
+
target_kk=5,
|
| 111 |
+
init_warmup=5,
|
| 112 |
+
final_warmup=20,
|
| 113 |
+
mask_interval=10,
|
| 114 |
+
)
|
| 115 |
+
|
| 116 |
+
# Metrics
|
| 117 |
+
metric = evaluate.load("accuracy")
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
def compute_metrics(eval_pred):
|
| 121 |
+
predictions = eval_pred.predictions.argmax(axis=1)
|
| 122 |
+
return metric.compute(predictions=predictions, references=eval_pred.label_ids)
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
# Training arguments
|
| 126 |
+
training_args = TrainingArguments(
|
| 127 |
+
output_dir="./test_adamss_output",
|
| 128 |
+
num_train_epochs=1,
|
| 129 |
+
per_device_train_batch_size=8,
|
| 130 |
+
per_device_eval_batch_size=8,
|
| 131 |
+
learning_rate=0.01,
|
| 132 |
+
weight_decay=0.0005,
|
| 133 |
+
eval_strategy="epoch",
|
| 134 |
+
save_strategy="no",
|
| 135 |
+
logging_steps=10,
|
| 136 |
+
remove_unused_columns=False,
|
| 137 |
+
label_names=["labels"], # Explicitly tell Trainer where labels are (PEFT hides model signature)
|
| 138 |
+
report_to="none",
|
| 139 |
+
)
|
| 140 |
+
|
| 141 |
+
# Create trainer
|
| 142 |
+
trainer = Trainer(
|
| 143 |
+
model=model,
|
| 144 |
+
args=training_args,
|
| 145 |
+
train_dataset=train_ds,
|
| 146 |
+
eval_dataset=val_ds,
|
| 147 |
+
data_collator=collate_fn,
|
| 148 |
+
compute_metrics=compute_metrics,
|
| 149 |
+
callbacks=[asa_callback],
|
| 150 |
+
)
|
| 151 |
+
|
| 152 |
+
# Train
|
| 153 |
+
print("\n" + "=" * 80)
|
| 154 |
+
print("🚀 Starting training (1 epoch on 100 samples)...")
|
| 155 |
+
print("=" * 80 + "\n")
|
| 156 |
+
|
| 157 |
+
try:
|
| 158 |
+
trainer.train()
|
| 159 |
+
print("\n✅ Training completed successfully!")
|
| 160 |
+
|
| 161 |
+
# Evaluate
|
| 162 |
+
metrics = trainer.evaluate()
|
| 163 |
+
print(f"\n📊 Validation Accuracy: {metrics['eval_accuracy']:.2%}")
|
| 164 |
+
|
| 165 |
+
print("\n" + "=" * 80)
|
| 166 |
+
print("✅ Test PASSED - AdaMSS example works correctly!")
|
| 167 |
+
print("=" * 80)
|
| 168 |
+
|
| 169 |
+
except Exception as e:
|
| 170 |
+
print("\n" + "=" * 80)
|
| 171 |
+
print(f"❌ Test FAILED: {e}")
|
| 172 |
+
print("=" * 80)
|
| 173 |
+
import traceback
|
| 174 |
+
|
| 175 |
+
traceback.print_exc()
|
| 176 |
+
sys.exit(1)
|
tasks/tasksmith-0d2d1e298e86/tests/source/examples/alora_finetuning/README.md
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Activated LoRA (aLoRA)
|
| 2 |
+
|
| 3 |
+
## Introduction
|
| 4 |
+
Activated LoRA (aLoRA) is an adapter that selectively activates its weights only after a given invocation sequence, ensuring that hidden states match the base model prior to this point. This allows reusing the base model KVs (stored in the KV cache) for tokens before the invocation,
|
| 5 |
+
enabling much faster real-world inference (e.g. vLLM) when switching between generation with the base model and generation with adapters.
|
| 6 |
+
See the [paper](https://huggingface.co/papers/2504.12397) for more details.
|
| 7 |
+
|
| 8 |
+
## Quick start (shown for Mistral 7B)
|
| 9 |
+
```python
|
| 10 |
+
import torch
|
| 11 |
+
from peft import LoraConfig, get_peft_model
|
| 12 |
+
from transformers import AutoTokenizer, AutoModelForCausalLM, Trainer, DataCollatorForLanguageModeling
|
| 13 |
+
from datasets import load_dataset
|
| 14 |
+
|
| 15 |
+
model = AutoModelForCausalLM.from_pretrained("mistralai/Mistral-7B-Instruct-v0.3", device_map="auto")
|
| 16 |
+
tokenizer = AutoTokenizer.from_pretrained("mistralai/Mistral-7B-Instruct-v0.3")
|
| 17 |
+
dataset = load_dataset("Lots-of-LoRAs/task1660_super_glue_question_generation", split="train")
|
| 18 |
+
|
| 19 |
+
invocation_string = "[/INST]" # End of user turn in Mistral chat template
|
| 20 |
+
invocation_tokens = tokenizer.encode(invocation_string, add_special_tokens=False)
|
| 21 |
+
|
| 22 |
+
lora_config = LoraConfig(
|
| 23 |
+
task_type="CAUSAL_LM",
|
| 24 |
+
alora_invocation_tokens=invocation_tokens,
|
| 25 |
+
r=32,
|
| 26 |
+
target_modules=["q_proj", "k_proj", "v_proj"],
|
| 27 |
+
)
|
| 28 |
+
|
| 29 |
+
peft_model = get_peft_model(model, lora_config)
|
| 30 |
+
data_collator = DataCollatorForLanguageModeling(tokenizer, mlm=False)
|
| 31 |
+
trainer = Trainer(
|
| 32 |
+
model=peft_model,
|
| 33 |
+
train_dataset=dataset,
|
| 34 |
+
dataset_text_field="text",
|
| 35 |
+
max_length=2048,
|
| 36 |
+
tokenizer=tokenizer,
|
| 37 |
+
data_collator=data_collator,
|
| 38 |
+
)
|
| 39 |
+
trainer.train()
|
| 40 |
+
peft_model.save_pretrained("alora-mistral-7b")
|
| 41 |
+
```
|
| 42 |
+
|
| 43 |
+
### Use the training example script directly
|
| 44 |
+
Pass the invocation string with `--invocation_string` when running the training example
|
| 45 |
+
script. For Mistral 7B, do:
|
| 46 |
+
```bash
|
| 47 |
+
python examples/alora_finetuning/alora_finetuning.py --base_model mistralai/Mistral-7B-Instruct-v0.3 --data_path Lots-of-LoRAs/task1660_super_glue_question_generation --invocation_string "[/INST]"
|
| 48 |
+
```
|
| 49 |
+
and similarly for Llama-3.2-3B-Instruct:
|
| 50 |
+
```bash
|
| 51 |
+
python examples/alora_finetuning/alora_finetuning.py --base_model meta-llama/Llama-3.2-3B-Instruct --data_path Lots-of-LoRAs/task1660_super_glue_question_generation --invocation_string "<|start_header_id|>assistant<|end_header_id|>"
|
| 52 |
+
```
|
| 53 |
+
|
| 54 |
+
### Full example of the script
|
| 55 |
+
```bash
|
| 56 |
+
python alora_finetuning.py \
|
| 57 |
+
--base_model "PATH_TO_MODEL" \
|
| 58 |
+
--data_path "PATH_TO_DATASET" \
|
| 59 |
+
--output_dir "PATH_TO_OUTPUT_DIR" \
|
| 60 |
+
--batch_size 1 \
|
| 61 |
+
--num_epochs 3 \
|
| 62 |
+
--learning_rate 3e-4 \
|
| 63 |
+
--cutoff_len 512 \
|
| 64 |
+
--val_set_size 500 \
|
| 65 |
+
--invocation_string "[/INST]" \
|
| 66 |
+
--quantize \
|
| 67 |
+
--eval_step 10 \
|
| 68 |
+
--save_step 100 \
|
| 69 |
+
--device "auto" \
|
| 70 |
+
--lora_r 32 \
|
| 71 |
+
--lora_alpha 32 \
|
| 72 |
+
--lora_dropout 0.05 \
|
| 73 |
+
--lora_target_modules "q_proj,k_proj,v_proj,o_proj,gate_proj,up_proj,down_proj" \
|
| 74 |
+
--hub_model_id "YOUR_HF_REPO" \
|
| 75 |
+
--push_to_hub
|
| 76 |
+
```
|
tasks/tasksmith-0d2d1e298e86/tests/source/examples/alora_finetuning/alora_finetuning.py
ADDED
|
@@ -0,0 +1,259 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
|
| 3 |
+
import torch
|
| 4 |
+
from datasets import load_dataset
|
| 5 |
+
from transformers import (
|
| 6 |
+
AutoModelForCausalLM,
|
| 7 |
+
AutoTokenizer,
|
| 8 |
+
BitsAndBytesConfig,
|
| 9 |
+
DataCollatorForLanguageModeling,
|
| 10 |
+
Trainer,
|
| 11 |
+
TrainingArguments,
|
| 12 |
+
)
|
| 13 |
+
|
| 14 |
+
from peft import LoraConfig, PeftModel, get_peft_model, prepare_model_for_kbit_training
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def train_model(
|
| 18 |
+
base_model: str,
|
| 19 |
+
data_path: str,
|
| 20 |
+
output_dir: str,
|
| 21 |
+
batch_size: int,
|
| 22 |
+
num_epochs: int,
|
| 23 |
+
learning_rate: float,
|
| 24 |
+
cutoff_len: int,
|
| 25 |
+
val_set_size: int,
|
| 26 |
+
invocation_string: str,
|
| 27 |
+
quantize: bool,
|
| 28 |
+
eval_step: int,
|
| 29 |
+
save_step: int,
|
| 30 |
+
device: str,
|
| 31 |
+
lora_r: int,
|
| 32 |
+
lora_alpha: int,
|
| 33 |
+
lora_dropout: float,
|
| 34 |
+
lora_target_modules: str,
|
| 35 |
+
hub_model_id: str,
|
| 36 |
+
push_to_hub: bool,
|
| 37 |
+
):
|
| 38 |
+
os.environ["TOKENIZERS_PARALLELISM"] = "false"
|
| 39 |
+
hf_token = os.getenv("HF_TOKEN")
|
| 40 |
+
|
| 41 |
+
if device == "auto":
|
| 42 |
+
device = torch.accelerator.current_accelerator().type if hasattr(torch, "accelerator") else "cuda"
|
| 43 |
+
else:
|
| 44 |
+
device = torch.device(device)
|
| 45 |
+
print(f"Using device: {device}")
|
| 46 |
+
|
| 47 |
+
tokenizer = AutoTokenizer.from_pretrained(base_model, token=hf_token)
|
| 48 |
+
tokenizer.pad_token = tokenizer.unk_token
|
| 49 |
+
invocation_tokens = tokenizer.encode(invocation_string, add_special_tokens=False)
|
| 50 |
+
|
| 51 |
+
if quantize:
|
| 52 |
+
if (torch.cuda.is_available() and torch.cuda.is_bf16_supported()) or torch.xpu.is_available():
|
| 53 |
+
bnb_4bit_compute_dtype = torch.bfloat16
|
| 54 |
+
else:
|
| 55 |
+
bnb_4bit_compute_dtype = torch.float16
|
| 56 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 57 |
+
base_model,
|
| 58 |
+
token=hf_token,
|
| 59 |
+
quantization_config=BitsAndBytesConfig(
|
| 60 |
+
load_in_4bit=True,
|
| 61 |
+
bnb_4bit_compute_dtype=bnb_4bit_compute_dtype,
|
| 62 |
+
bnb_4bit_use_double_quant=True,
|
| 63 |
+
bnb_4bit_quant_type="nf4",
|
| 64 |
+
),
|
| 65 |
+
)
|
| 66 |
+
model = prepare_model_for_kbit_training(model, use_gradient_checkpointing=True)
|
| 67 |
+
else:
|
| 68 |
+
model = AutoModelForCausalLM.from_pretrained(base_model, token=hf_token)
|
| 69 |
+
|
| 70 |
+
lora_config = LoraConfig(
|
| 71 |
+
task_type="CAUSAL_LM",
|
| 72 |
+
alora_invocation_tokens=invocation_tokens,
|
| 73 |
+
r=lora_r,
|
| 74 |
+
lora_alpha=lora_alpha,
|
| 75 |
+
target_modules=(lora_target_modules.split(",") if lora_target_modules else ["q_proj", "k_proj", "v_proj"]),
|
| 76 |
+
lora_dropout=lora_dropout,
|
| 77 |
+
bias="none",
|
| 78 |
+
)
|
| 79 |
+
|
| 80 |
+
model = get_peft_model(model, lora_config)
|
| 81 |
+
|
| 82 |
+
model.to(device)
|
| 83 |
+
tokenizer.pad_token = tokenizer.eos_token
|
| 84 |
+
|
| 85 |
+
dataset = load_dataset(data_path)
|
| 86 |
+
|
| 87 |
+
def tokenize_function(examples):
|
| 88 |
+
formatted_texts = [
|
| 89 |
+
tokenizer.apply_chat_template(
|
| 90 |
+
[
|
| 91 |
+
{"role": "user", "content": user_msg},
|
| 92 |
+
{"role": "assistant", "content": assistant_msg},
|
| 93 |
+
],
|
| 94 |
+
tokenize=False, # get plain text first
|
| 95 |
+
add_generation_prompt=False,
|
| 96 |
+
)
|
| 97 |
+
for user_msg, assistant_msg in zip(examples["input"], examples["output"])
|
| 98 |
+
]
|
| 99 |
+
|
| 100 |
+
# 2) Tokenize those texts
|
| 101 |
+
model_inputs = tokenizer(
|
| 102 |
+
formatted_texts,
|
| 103 |
+
padding="max_length",
|
| 104 |
+
truncation=True,
|
| 105 |
+
max_length=cutoff_len,
|
| 106 |
+
)
|
| 107 |
+
|
| 108 |
+
labels = []
|
| 109 |
+
for ids in model_inputs["input_ids"]:
|
| 110 |
+
labels.append([(token_id if token_id != tokenizer.pad_token_id else -100) for token_id in ids])
|
| 111 |
+
model_inputs["labels"] = labels
|
| 112 |
+
|
| 113 |
+
return model_inputs
|
| 114 |
+
|
| 115 |
+
# Tokenize the dataset and prepare for training
|
| 116 |
+
tokenized_datasets = dataset.map(tokenize_function, batched=True, remove_columns=dataset["train"].column_names)
|
| 117 |
+
|
| 118 |
+
# Data collator to dynamically pad the batched examples
|
| 119 |
+
data_collator = DataCollatorForLanguageModeling(tokenizer, mlm=False)
|
| 120 |
+
|
| 121 |
+
training_args = TrainingArguments(
|
| 122 |
+
output_dir=output_dir,
|
| 123 |
+
num_train_epochs=num_epochs,
|
| 124 |
+
per_device_train_batch_size=batch_size,
|
| 125 |
+
per_device_eval_batch_size=batch_size,
|
| 126 |
+
warmup_steps=100,
|
| 127 |
+
weight_decay=0.01,
|
| 128 |
+
logging_dir="./logs",
|
| 129 |
+
logging_steps=eval_step,
|
| 130 |
+
save_steps=save_step,
|
| 131 |
+
save_total_limit=2,
|
| 132 |
+
push_to_hub=push_to_hub,
|
| 133 |
+
hub_model_id=hub_model_id,
|
| 134 |
+
gradient_accumulation_steps=16,
|
| 135 |
+
fp16=True,
|
| 136 |
+
learning_rate=learning_rate,
|
| 137 |
+
hub_token=hf_token,
|
| 138 |
+
)
|
| 139 |
+
|
| 140 |
+
if torch.cuda.is_available():
|
| 141 |
+
torch.cuda.empty_cache()
|
| 142 |
+
elif torch.xpu.is_available():
|
| 143 |
+
torch.xpu.empty_cache()
|
| 144 |
+
|
| 145 |
+
trainer = Trainer(
|
| 146 |
+
model=model,
|
| 147 |
+
args=training_args,
|
| 148 |
+
train_dataset=tokenized_datasets["train"],
|
| 149 |
+
eval_dataset=tokenized_datasets["test"],
|
| 150 |
+
data_collator=data_collator,
|
| 151 |
+
)
|
| 152 |
+
|
| 153 |
+
trainer.train()
|
| 154 |
+
|
| 155 |
+
if push_to_hub:
|
| 156 |
+
trainer.push_to_hub(commit_message="Fine-tuned model")
|
| 157 |
+
|
| 158 |
+
model.save_pretrained(output_dir)
|
| 159 |
+
tokenizer.save_pretrained(output_dir)
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
def model_inference(model_path: str, adapter_path: str, prompt: str | None = None, data_path: str | None = None):
|
| 163 |
+
"""
|
| 164 |
+
Simple inference with the tuned aLoRA adapter. Optionally (reuse_cache = True) demonstrates
|
| 165 |
+
that the aLoRA adapter can (but does not need to) use KV cache created by the base model,
|
| 166 |
+
perhaps during a prior generation turn.
|
| 167 |
+
|
| 168 |
+
Purely for demonstration purposes. See the [paper](https://huggingface.co/papers/2504.12397)
|
| 169 |
+
for realistic multiturn cache reuse examples.
|
| 170 |
+
"""
|
| 171 |
+
if prompt is None:
|
| 172 |
+
# Use first row of test data
|
| 173 |
+
dataset = load_dataset(data_path)
|
| 174 |
+
prompt = dataset["test"][0]["input"]
|
| 175 |
+
tokenizer = AutoTokenizer.from_pretrained(model_path)
|
| 176 |
+
base_model = AutoModelForCausalLM.from_pretrained(model_path)
|
| 177 |
+
alora_model = PeftModel.from_pretrained(base_model, adapter_path)
|
| 178 |
+
chat = [{"role": "user", "content": prompt}]
|
| 179 |
+
text = tokenizer.apply_chat_template(chat, tokenize=False, add_generation_prompt=True)
|
| 180 |
+
inputs = tokenizer(text, return_tensors="pt").to(base_model.device)
|
| 181 |
+
|
| 182 |
+
# Generate answer with adapter
|
| 183 |
+
output_dict = alora_model.generate(**inputs, return_dict_in_generate=True, max_new_tokens=20)
|
| 184 |
+
alora_outputs = output_dict.sequences
|
| 185 |
+
|
| 186 |
+
# Print results
|
| 187 |
+
print(f"Prompt: {text}")
|
| 188 |
+
response = tokenizer.decode(alora_outputs[0][inputs["input_ids"].shape[1] :], skip_special_tokens=True)
|
| 189 |
+
print(f"Trained adapter response: {response}")
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
if __name__ == "__main__":
|
| 193 |
+
import argparse
|
| 194 |
+
|
| 195 |
+
parser = argparse.ArgumentParser(description="Fine-tune Mistral with Activated LoRA")
|
| 196 |
+
parser.add_argument(
|
| 197 |
+
"--base_model", type=str, default="mistralai/Mistral-7B-Instruct-v0.3", help="Base model path or name"
|
| 198 |
+
)
|
| 199 |
+
parser.add_argument(
|
| 200 |
+
"--data_path",
|
| 201 |
+
type=str,
|
| 202 |
+
default="Lots-of-LoRAs/task1660_super_glue_question_generation",
|
| 203 |
+
help="Dataset path or name",
|
| 204 |
+
)
|
| 205 |
+
parser.add_argument(
|
| 206 |
+
"--output_dir", type=str, default="path/to/output", help="Output directory for the fine-tuned model"
|
| 207 |
+
)
|
| 208 |
+
parser.add_argument("--batch_size", type=int, default=2, help="Batch size")
|
| 209 |
+
parser.add_argument("--num_epochs", type=int, default=1, help="Number of training epochs")
|
| 210 |
+
parser.add_argument("--learning_rate", type=float, default=1e-4, help="Learning rate")
|
| 211 |
+
parser.add_argument("--cutoff_len", type=int, default=2048, help="Cutoff length for tokenization")
|
| 212 |
+
parser.add_argument("--val_set_size", type=int, default=500, help="Validation set size")
|
| 213 |
+
parser.add_argument(
|
| 214 |
+
"--invocation_string",
|
| 215 |
+
type=str,
|
| 216 |
+
default="[/INST]",
|
| 217 |
+
help="String that activates the aLoRA adapter. Model dependent.",
|
| 218 |
+
)
|
| 219 |
+
parser.add_argument("--quantize", action="store_true", help="Use quantization")
|
| 220 |
+
parser.add_argument("--eval_step", type=int, default=10, help="Evaluation step interval")
|
| 221 |
+
parser.add_argument("--save_step", type=int, default=100, help="Save step interval")
|
| 222 |
+
parser.add_argument("--device", type=str, default="auto", help="Device to use for training")
|
| 223 |
+
parser.add_argument("--lora_r", type=int, default=32, help="LoRA rank")
|
| 224 |
+
parser.add_argument("--lora_alpha", type=int, default=32, help="LoRA alpha")
|
| 225 |
+
parser.add_argument("--lora_dropout", type=float, default=0.05, help="LoRA dropout rate")
|
| 226 |
+
parser.add_argument(
|
| 227 |
+
"--lora_target_modules", type=str, default=None, help="Comma-separated list of target modules for LoRA"
|
| 228 |
+
)
|
| 229 |
+
parser.add_argument(
|
| 230 |
+
"--hub_model_id",
|
| 231 |
+
type=str,
|
| 232 |
+
default="path/to/repo",
|
| 233 |
+
help="Repository name to push the model on the Hugging Face Hub",
|
| 234 |
+
)
|
| 235 |
+
parser.add_argument("--push_to_hub", action="store_true", help="Whether to push the model to Hugging Face Hub")
|
| 236 |
+
args = parser.parse_args()
|
| 237 |
+
train_model(
|
| 238 |
+
base_model=args.base_model,
|
| 239 |
+
data_path=args.data_path,
|
| 240 |
+
output_dir=args.output_dir,
|
| 241 |
+
batch_size=args.batch_size,
|
| 242 |
+
num_epochs=args.num_epochs,
|
| 243 |
+
learning_rate=args.learning_rate,
|
| 244 |
+
cutoff_len=args.cutoff_len,
|
| 245 |
+
val_set_size=args.val_set_size,
|
| 246 |
+
invocation_string=args.invocation_string,
|
| 247 |
+
quantize=args.quantize,
|
| 248 |
+
eval_step=args.eval_step,
|
| 249 |
+
save_step=args.save_step,
|
| 250 |
+
device=args.device,
|
| 251 |
+
lora_r=args.lora_r,
|
| 252 |
+
lora_alpha=args.lora_alpha,
|
| 253 |
+
lora_dropout=args.lora_dropout,
|
| 254 |
+
lora_target_modules=args.lora_target_modules,
|
| 255 |
+
hub_model_id=args.hub_model_id,
|
| 256 |
+
push_to_hub=args.push_to_hub,
|
| 257 |
+
)
|
| 258 |
+
print("Model trained. Running test inference.")
|
| 259 |
+
model_inference(model_path=args.base_model, adapter_path=args.output_dir, data_path=args.data_path)
|
tasks/tasksmith-0d2d1e298e86/tests/source/examples/arrow_multitask/arrow_phi3_mini.py
ADDED
|
@@ -0,0 +1,383 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2025-present the HuggingFace Inc. team.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
"""
|
| 16 |
+
This script provides a simple evaluation pipeline for multiple-choice reasoning datasets
|
| 17 |
+
(e.g., BoolQ, HellaSwag, ARC, OpenBookQA, Winogrande) with different composition strategies.
|
| 18 |
+
|
| 19 |
+
Usage examples:
|
| 20 |
+
python arrow_phi3_mini.py --strategy base --ds_name arc-challenge
|
| 21 |
+
python arrow_phi3_mini.py --strategy arrow --ds_name boolq
|
| 22 |
+
python arrow_phi3_mini.py --strategy gks --ds_name hswag
|
| 23 |
+
|
| 24 |
+
Key features:
|
| 25 |
+
- Supports three strategies:
|
| 26 |
+
• "base" → Evaluate the quantized base model directly
|
| 27 |
+
• "arrow" → Use Arrow modular routing with task-specific adapters
|
| 28 |
+
• "gks" → Use Arrow + GenKnowSub (subtracting general-domain knowledge)
|
| 29 |
+
- Loads evaluation datasets from the Hugging Face Hub
|
| 30 |
+
- Implements a batched evaluation loop that computes per-option likelihoods and selects
|
| 31 |
+
the answer with the lowest average loss
|
| 32 |
+
- Reports simple accuracy
|
| 33 |
+
|
| 34 |
+
Implementation details:
|
| 35 |
+
- The base model is quantized to 4-bit using `BitsAndBytesConfig` (nf4, bf16 compute).
|
| 36 |
+
- For Arrow and GKS, task-specific adapters are loaded from the Hugging Face Hub:
|
| 37 |
+
TahaBa/phi3-mini-clustered-flan/ts_expert_i
|
| 38 |
+
- Task-specific adapters were trained on 10 clusters of FLAN tasks.
|
| 39 |
+
- The clusters were created using Model-Based Clustering (MBC):
|
| 40 |
+
1. Train a LoRA adapter for each individual task.
|
| 41 |
+
2. Apply k-means clustering to group tasks based on these adapters.
|
| 42 |
+
3. Train a LoRA adapter for each resulting cluster.
|
| 43 |
+
For more details, see the Arrow paper: https://huggingface.co/papers/2405.11157
|
| 44 |
+
|
| 45 |
+
- For GKS, general adapters are loaded from:
|
| 46 |
+
TahaBa/phi3-mini-general-adapters/...
|
| 47 |
+
- These adapters were trained on English, French, and German Wikipedia data
|
| 48 |
+
using a causal language modeling objective with (507-token context → 5-token completion) pairs.
|
| 49 |
+
- This setup encodes general knowledge into the LoRA space, which can then be
|
| 50 |
+
subtracted from task-specific adapters during inference to isolate and purify them.
|
| 51 |
+
For more details, see the GenKnowSub paper: https://huggingface.co/papers/2505.10939
|
| 52 |
+
|
| 53 |
+
- `evaluate_on_multi_choice_batched` handles tokenization, masking context tokens,
|
| 54 |
+
and computing per-choice log-likelihoods for fair comparison.
|
| 55 |
+
- Accuracy is printed at the end for the selected dataset.
|
| 56 |
+
|
| 57 |
+
This script is mainly meant for demonstration purposes and lightweight evaluation,
|
| 58 |
+
not full-scale benchmarking (batch size / max length can be tuned).
|
| 59 |
+
|
| 60 |
+
=======================================================================================
|
| 61 |
+
|
| 62 |
+
Results (evaluated with microsoft/Phi-3-mini-4k-instruct, 4-bit quantization):
|
| 63 |
+
|
| 64 |
+
| Dataset | Base Acc. | Arrow Acc. | Arrow+GKS Acc. |
|
| 65 |
+
|--------------|-----------|------------|----------------|
|
| 66 |
+
| ARC-Challenge| 0.4515 | 0.5418 | 0.5585 |
|
| 67 |
+
| ARC-Easy | 0.6894 | 0.8404 | 0.8473 |
|
| 68 |
+
| Winogrande | 0.5769 | 0.6550 | 0.6724 |
|
| 69 |
+
| BoolQ | 0.8146 | 0.8030 | 0.8247 |
|
| 70 |
+
| OpenBookQA | 0.43 | 0.448 | 0.472 |
|
| 71 |
+
| HellaSwag | 0.7318 | 0.7150 | 0.7376 |
|
| 72 |
+
|
| 73 |
+
Observations:
|
| 74 |
+
- Arrow generally improves over the base model by routing tokens to the most relevant task adapters.
|
| 75 |
+
- Applying GKS (general knowledge subtraction) consistently gives further gains compared to Arrow and Base.
|
| 76 |
+
|
| 77 |
+
These numbers are not meant as leaderboard results, but as a sanity check
|
| 78 |
+
to verify that the implementation works as expected and demonstrates
|
| 79 |
+
the benefits of Arrow and GenKnowSub.
|
| 80 |
+
"""
|
| 81 |
+
|
| 82 |
+
import argparse
|
| 83 |
+
import random
|
| 84 |
+
|
| 85 |
+
import numpy as np
|
| 86 |
+
import torch
|
| 87 |
+
from datasets import load_dataset
|
| 88 |
+
from sklearn.metrics import accuracy_score
|
| 89 |
+
from tqdm import tqdm
|
| 90 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig
|
| 91 |
+
|
| 92 |
+
from peft import ArrowConfig, create_arrow_model
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
MODEL_NAME = "microsoft/Phi-3-mini-4k-instruct"
|
| 96 |
+
MODEL_MAX_LEN = 2048
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def parse_args():
|
| 100 |
+
parser = argparse.ArgumentParser(description="Training script with strategy selection")
|
| 101 |
+
|
| 102 |
+
parser.add_argument(
|
| 103 |
+
"--strategy",
|
| 104 |
+
type=str,
|
| 105 |
+
choices=["base", "arrow", "gks"],
|
| 106 |
+
default="base",
|
| 107 |
+
help="Training strategy to use: base, arrow, or gks",
|
| 108 |
+
)
|
| 109 |
+
parser.add_argument(
|
| 110 |
+
"--ds_name",
|
| 111 |
+
type=str,
|
| 112 |
+
choices=["boolq", "hswag", "arc-easy", "arc-challenge", "oqa", "wg"],
|
| 113 |
+
default="arc-challenge",
|
| 114 |
+
help="Dataset to use: boolq, hswag, arc-easy, arc-challenge, oqa, wg",
|
| 115 |
+
)
|
| 116 |
+
|
| 117 |
+
return parser.parse_args()
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
def read_test_dataset(ds_name):
|
| 121 |
+
if ds_name == "boolq":
|
| 122 |
+
ds = load_dataset("google/boolq", split="validation", trust_remote_code=True)
|
| 123 |
+
elif ds_name == "hswag":
|
| 124 |
+
ds = load_dataset("Rowan/hellaswag", split="validation", trust_remote_code=True)
|
| 125 |
+
elif ds_name == "arc-challenge":
|
| 126 |
+
ds = load_dataset("allenai/ai2_arc", "ARC-Challenge", split="validation", trust_remote_code=True)
|
| 127 |
+
elif ds_name == "arc-easy":
|
| 128 |
+
ds = load_dataset("allenai/ai2_arc", "ARC-Easy", split="validation", trust_remote_code=True)
|
| 129 |
+
elif ds_name == "oqa":
|
| 130 |
+
ds = load_dataset("allenai/openbookqa", split="validation", trust_remote_code=True)
|
| 131 |
+
elif ds_name == "wg":
|
| 132 |
+
ds = load_dataset("allenai/winogrande", "winogrande_xl", split="validation", trust_remote_code=True)
|
| 133 |
+
else:
|
| 134 |
+
raise f"Dataset {ds_name} is not supported yet."
|
| 135 |
+
|
| 136 |
+
return ds
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
def extract_input_content(ds_name, row):
|
| 140 |
+
if ds_name == "boolq":
|
| 141 |
+
return f"[passage]{row['passage']}[question]{row['question']}"
|
| 142 |
+
if ds_name == "hswag":
|
| 143 |
+
return row["ctx"]
|
| 144 |
+
if (ds_name == "arc-challenge") or (ds_name == "arc-easy"):
|
| 145 |
+
return row["question"]
|
| 146 |
+
if ds_name == "oqa":
|
| 147 |
+
return row["question_stem"]
|
| 148 |
+
if ds_name == "wg":
|
| 149 |
+
return row["sentence"]
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
def create_multi_choice_options(row, ds_name):
|
| 153 |
+
options_texts = []
|
| 154 |
+
content = extract_input_content(ds_name, row)
|
| 155 |
+
if ds_name == "boolq":
|
| 156 |
+
choices = ["true", "false"]
|
| 157 |
+
if ds_name == "hswag":
|
| 158 |
+
choices = row["endings"]
|
| 159 |
+
if (ds_name == "arc-challenge") or (ds_name == "arc-easy"):
|
| 160 |
+
choices = row["choices"]["text"]
|
| 161 |
+
if ds_name == "wg":
|
| 162 |
+
choices = [row["option1"], row["option2"]]
|
| 163 |
+
if ds_name == "oqa":
|
| 164 |
+
choices = row["choices"]["text"]
|
| 165 |
+
|
| 166 |
+
for choice in choices:
|
| 167 |
+
options_texts.append(f"<|user|>\n{content}<|end|>\n<|assistant|>{choice}<|end|>\n")
|
| 168 |
+
|
| 169 |
+
return options_texts
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
def extract_multi_choice_target_index(row, ds_name):
|
| 173 |
+
if ds_name == "boolq":
|
| 174 |
+
return 0 if row["answer"] is True else 1
|
| 175 |
+
if ds_name == "hswag":
|
| 176 |
+
return int(row["label"])
|
| 177 |
+
if (ds_name == "arc-challenge") or (ds_name == "arc-easy"):
|
| 178 |
+
return row["choices"]["label"].index(row["answerKey"])
|
| 179 |
+
if ds_name == "wg":
|
| 180 |
+
return int(row["answer"]) - 1
|
| 181 |
+
if ds_name == "oqa":
|
| 182 |
+
return row["choices"]["label"].index(row["answerKey"])
|
| 183 |
+
|
| 184 |
+
|
| 185 |
+
def set_seed(seed: int):
|
| 186 |
+
random.seed(seed)
|
| 187 |
+
np.random.seed(seed)
|
| 188 |
+
torch.manual_seed(seed)
|
| 189 |
+
if torch.cuda.is_available():
|
| 190 |
+
torch.cuda.manual_seed_all(seed)
|
| 191 |
+
elif hasattr(torch, "xpu") and torch.xpu.is_available():
|
| 192 |
+
torch.xpu.manual_seed_all(seed)
|
| 193 |
+
|
| 194 |
+
|
| 195 |
+
def compute_loglike_loss(logits, labels, reduction="none"):
|
| 196 |
+
bs = logits.size(0)
|
| 197 |
+
vocab_size = logits.size(-1)
|
| 198 |
+
labels = labels.squeeze(-1)
|
| 199 |
+
shift_logits = logits[..., :-1, :].contiguous()
|
| 200 |
+
shift_labels = labels[..., 1:].contiguous()
|
| 201 |
+
|
| 202 |
+
# Flatten the tokens
|
| 203 |
+
loss_fct = torch.nn.CrossEntropyLoss(reduction=reduction)
|
| 204 |
+
shift_logits = shift_logits.view(-1, vocab_size)
|
| 205 |
+
shift_labels = shift_labels.view(-1)
|
| 206 |
+
|
| 207 |
+
shift_labels = shift_labels.to(shift_logits.device)
|
| 208 |
+
loss = loss_fct(shift_logits, shift_labels)
|
| 209 |
+
|
| 210 |
+
# reshape back
|
| 211 |
+
if reduction == "none":
|
| 212 |
+
loss = loss.view((bs, -1))
|
| 213 |
+
non_zero_loss = (loss != 0).sum(dim=-1)
|
| 214 |
+
non_zero_loss[non_zero_loss == 0] = 1
|
| 215 |
+
loss = loss.sum(dim=-1) / non_zero_loss
|
| 216 |
+
|
| 217 |
+
return loss.float() # Convert to float32 before returning
|
| 218 |
+
|
| 219 |
+
|
| 220 |
+
def evaluate_on_multi_choice_batched(
|
| 221 |
+
eval_dataset, model, tokenizer, ds_name, labels, predictions, args, batch_size=32, max_length=512, device="auto"
|
| 222 |
+
):
|
| 223 |
+
# Local import to mirror your original function
|
| 224 |
+
model.eval()
|
| 225 |
+
|
| 226 |
+
if device == "auto":
|
| 227 |
+
device = torch.accelerator.current_accelerator().type if hasattr(torch, "accelerator") else "cuda"
|
| 228 |
+
else:
|
| 229 |
+
device = torch.device(device)
|
| 230 |
+
|
| 231 |
+
for start in tqdm(
|
| 232 |
+
range(0, len(eval_dataset), batch_size), total=(len(eval_dataset) + batch_size - 1) // batch_size
|
| 233 |
+
):
|
| 234 |
+
rows = [eval_dataset[i] for i in range(start, min(start + batch_size, len(eval_dataset)))]
|
| 235 |
+
|
| 236 |
+
# Build the flattened option texts for this batch
|
| 237 |
+
all_texts = []
|
| 238 |
+
options_per_sample = [] # number of options for each sample
|
| 239 |
+
ctx_lens_per_option = [] # context length replicated per option
|
| 240 |
+
|
| 241 |
+
for row in rows:
|
| 242 |
+
# options: ["<|user|>...<|assistant|>choiceA<|end|>", ...]
|
| 243 |
+
options = create_multi_choice_options(row, ds_name)
|
| 244 |
+
options_per_sample.append(len(options))
|
| 245 |
+
|
| 246 |
+
# compute context length once per sample (align with your -1 shift)
|
| 247 |
+
content = extract_input_content(ds_name, row)
|
| 248 |
+
context_prompt = f"<|user|>\n{content}<|end|>\n<|assistant|>"
|
| 249 |
+
ctx_len = len(tokenizer.encode(context_prompt)) - 1
|
| 250 |
+
|
| 251 |
+
all_texts.extend(options)
|
| 252 |
+
ctx_lens_per_option.extend([ctx_len] * len(options))
|
| 253 |
+
|
| 254 |
+
# collect gold label
|
| 255 |
+
labels.append(extract_multi_choice_target_index(row, ds_name))
|
| 256 |
+
|
| 257 |
+
# Tokenize all options in one go
|
| 258 |
+
tokenized = tokenizer(
|
| 259 |
+
all_texts,
|
| 260 |
+
return_tensors="pt",
|
| 261 |
+
padding=True,
|
| 262 |
+
truncation=True,
|
| 263 |
+
max_length=max_length,
|
| 264 |
+
)
|
| 265 |
+
tokenized = {k: v.to(device) for k, v in tokenized.items()}
|
| 266 |
+
|
| 267 |
+
# Create masked labels: ignore context and padding
|
| 268 |
+
masked_labels = tokenized["input_ids"].clone()
|
| 269 |
+
for i, ctx_len in enumerate(ctx_lens_per_option):
|
| 270 |
+
masked_labels[i, :ctx_len] = -100
|
| 271 |
+
masked_labels[tokenized["attention_mask"] == 0] = -100
|
| 272 |
+
|
| 273 |
+
with torch.no_grad():
|
| 274 |
+
logits = model(input_ids=tokenized["input_ids"], attention_mask=tokenized["attention_mask"]).logits
|
| 275 |
+
# per-sequence losses
|
| 276 |
+
losses = compute_loglike_loss(logits, masked_labels, reduction="none").detach().cpu()
|
| 277 |
+
|
| 278 |
+
# Reduce per sample (argmin across its options)
|
| 279 |
+
idx = 0
|
| 280 |
+
for n_opt in options_per_sample:
|
| 281 |
+
pred = torch.argmin(losses[idx : idx + n_opt]).item()
|
| 282 |
+
predictions.append(pred)
|
| 283 |
+
idx += n_opt
|
| 284 |
+
|
| 285 |
+
print(
|
| 286 |
+
f"Accuracy for dataset {args.ds_name} and strategy {args.strategy} is: {accuracy_score(labels, predictions)}"
|
| 287 |
+
)
|
| 288 |
+
|
| 289 |
+
|
| 290 |
+
if __name__ == "__main__":
|
| 291 |
+
args = parse_args()
|
| 292 |
+
print(f"Selected strategy: {args.strategy}")
|
| 293 |
+
print(f"Dataset name: {args.ds_name}")
|
| 294 |
+
|
| 295 |
+
# Loading the tokeniser
|
| 296 |
+
tokenizer = AutoTokenizer.from_pretrained(
|
| 297 |
+
MODEL_NAME,
|
| 298 |
+
use_fast=True,
|
| 299 |
+
padding_side="right",
|
| 300 |
+
model_max_length=MODEL_MAX_LEN,
|
| 301 |
+
)
|
| 302 |
+
|
| 303 |
+
# Quantisation config
|
| 304 |
+
bnb_config = BitsAndBytesConfig(
|
| 305 |
+
load_in_4bit=True,
|
| 306 |
+
bnb_4bit_quant_type="nf4",
|
| 307 |
+
bnb_4bit_compute_dtype=torch.bfloat16,
|
| 308 |
+
bnb_4bit_use_double_quant=False,
|
| 309 |
+
)
|
| 310 |
+
|
| 311 |
+
# Loading the model
|
| 312 |
+
base_model = AutoModelForCausalLM.from_pretrained(
|
| 313 |
+
MODEL_NAME,
|
| 314 |
+
dtype=torch.bfloat16,
|
| 315 |
+
device_map="auto",
|
| 316 |
+
quantization_config=bnb_config,
|
| 317 |
+
)
|
| 318 |
+
|
| 319 |
+
# Loading the test dataset
|
| 320 |
+
test_dataset = read_test_dataset(args.ds_name)
|
| 321 |
+
print(f"{args.ds_name} is loaded with size: {len(test_dataset)}.")
|
| 322 |
+
|
| 323 |
+
labels, predictions = [], []
|
| 324 |
+
if args.strategy == "base":
|
| 325 |
+
# Batch-wise inference
|
| 326 |
+
with torch.no_grad():
|
| 327 |
+
evaluate_on_multi_choice_batched(
|
| 328 |
+
test_dataset,
|
| 329 |
+
base_model,
|
| 330 |
+
tokenizer,
|
| 331 |
+
args.ds_name,
|
| 332 |
+
labels,
|
| 333 |
+
predictions,
|
| 334 |
+
args,
|
| 335 |
+
batch_size=64, # tune this
|
| 336 |
+
max_length=512, # tune if options are long
|
| 337 |
+
device="auto",
|
| 338 |
+
)
|
| 339 |
+
else:
|
| 340 |
+
general_adapter_paths = []
|
| 341 |
+
if args.strategy == "gks":
|
| 342 |
+
arrow_config = ArrowConfig(
|
| 343 |
+
top_k=3,
|
| 344 |
+
router_temperature=1.0,
|
| 345 |
+
use_gks=True,
|
| 346 |
+
)
|
| 347 |
+
# General adapter paths from the hub
|
| 348 |
+
general_adapter_paths = [
|
| 349 |
+
"TahaBa/phi3-mini-general-adapters/cluster0_batch16_prop1.0_langen/checkpoint-17",
|
| 350 |
+
"TahaBa/phi3-mini-general-adapters/cluster0_batch16_prop1.0_langfr/checkpoint-35",
|
| 351 |
+
"TahaBa/phi3-mini-general-adapters/cluster0_batch16_prop1.0_langger/checkpoint-17",
|
| 352 |
+
]
|
| 353 |
+
else:
|
| 354 |
+
arrow_config = ArrowConfig(
|
| 355 |
+
top_k=3,
|
| 356 |
+
router_temperature=1.0,
|
| 357 |
+
)
|
| 358 |
+
|
| 359 |
+
# Task-specific adapter paths from the hub
|
| 360 |
+
task_specific_adapter_paths = [f"TahaBa/phi3-mini-clustered-flan/ts_expert_{i}" for i in range(10)]
|
| 361 |
+
|
| 362 |
+
# Creating the Arrow model
|
| 363 |
+
model = create_arrow_model(
|
| 364 |
+
base_model=base_model,
|
| 365 |
+
task_specific_adapter_paths=task_specific_adapter_paths,
|
| 366 |
+
general_adapter_paths=general_adapter_paths,
|
| 367 |
+
arrow_config=arrow_config,
|
| 368 |
+
)
|
| 369 |
+
|
| 370 |
+
# Batch-wise inference
|
| 371 |
+
with torch.no_grad():
|
| 372 |
+
evaluate_on_multi_choice_batched(
|
| 373 |
+
test_dataset,
|
| 374 |
+
model,
|
| 375 |
+
tokenizer,
|
| 376 |
+
args.ds_name,
|
| 377 |
+
labels,
|
| 378 |
+
predictions,
|
| 379 |
+
args,
|
| 380 |
+
batch_size=32, # tune this
|
| 381 |
+
max_length=512, # tune if options are long
|
| 382 |
+
device="auto",
|
| 383 |
+
)
|
tasks/tasksmith-0d2d1e298e86/tests/source/examples/arrow_multitask/requirements.txt
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
torch
|
| 2 |
+
transformers
|
| 3 |
+
accelerate
|
| 4 |
+
datasets
|
| 5 |
+
scikit-learn
|
| 6 |
+
tqdm
|
| 7 |
+
numpy
|
| 8 |
+
bitsandbytes
|