AdithyaSK HF Staff commited on
Commit
e047f13
·
verified ·
1 Parent(s): 5f41281

Stage Harbor release files 64001-64500

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. tasks/tasksmith-9aea936e30e4/tests/source/docs/source/package_reference/auto_class.md +48 -0
  2. tasks/tasksmith-9aea936e30e4/tests/source/docs/source/package_reference/boft.md +31 -0
  3. tasks/tasksmith-9aea936e30e4/tests/source/docs/source/package_reference/bone.md +33 -0
  4. tasks/tasksmith-9aea936e30e4/tests/source/docs/source/package_reference/c3a.md +43 -0
  5. tasks/tasksmith-9aea936e30e4/tests/source/docs/source/package_reference/cartridges.md +91 -0
  6. tasks/tasksmith-9aea936e30e4/tests/source/docs/source/package_reference/config.md +22 -0
  7. tasks/tasksmith-9aea936e30e4/tests/source/docs/source/package_reference/cpt.md +34 -0
  8. tasks/tasksmith-9aea936e30e4/tests/source/docs/source/package_reference/delora.md +40 -0
  9. tasks/tasksmith-9aea936e30e4/tests/source/docs/source/package_reference/fourierft.md +38 -0
  10. tasks/tasksmith-9aea936e30e4/tests/source/docs/source/package_reference/functional.md +37 -0
  11. tasks/tasksmith-9aea936e30e4/tests/source/docs/source/package_reference/gralora.md +32 -0
  12. tasks/tasksmith-9aea936e30e4/tests/source/docs/source/package_reference/helpers.md +27 -0
  13. tasks/tasksmith-9aea936e30e4/tests/source/docs/source/package_reference/hotswap.md +78 -0
  14. tasks/tasksmith-9aea936e30e4/tests/source/docs/source/package_reference/hra.md +32 -0
  15. tasks/tasksmith-9aea936e30e4/tests/source/docs/source/package_reference/ia3.md +31 -0
  16. tasks/tasksmith-9aea936e30e4/tests/source/docs/source/package_reference/layernorm_tuning.md +34 -0
  17. tasks/tasksmith-9aea936e30e4/tests/source/docs/source/package_reference/llama_adapter.md +31 -0
  18. tasks/tasksmith-9aea936e30e4/tests/source/docs/source/package_reference/loha.md +31 -0
  19. tasks/tasksmith-9aea936e30e4/tests/source/docs/source/package_reference/lokr.md +27 -0
  20. tasks/tasksmith-9aea936e30e4/tests/source/docs/source/package_reference/lora.md +96 -0
  21. tasks/tasksmith-9aea936e30e4/tests/source/docs/source/package_reference/lora_conversion.md +146 -0
  22. tasks/tasksmith-9aea936e30e4/tests/source/docs/source/package_reference/merge_utils.md +33 -0
  23. tasks/tasksmith-9aea936e30e4/tests/source/docs/source/package_reference/miss.md +32 -0
  24. tasks/tasksmith-9aea936e30e4/tests/source/docs/source/package_reference/multitask_prompt_tuning.md +31 -0
  25. tasks/tasksmith-9aea936e30e4/tests/source/docs/source/package_reference/oft.md +31 -0
  26. tasks/tasksmith-9aea936e30e4/tests/source/docs/source/package_reference/osf.md +243 -0
  27. tasks/tasksmith-9aea936e30e4/tests/source/docs/source/package_reference/p_tuning.md +31 -0
  28. tasks/tasksmith-9aea936e30e4/tests/source/docs/source/package_reference/peft_model.md +77 -0
  29. tasks/tasksmith-9aea936e30e4/tests/source/docs/source/package_reference/peft_types.md +27 -0
  30. tasks/tasksmith-9aea936e30e4/tests/source/docs/source/package_reference/poly.md +44 -0
  31. tasks/tasksmith-9aea936e30e4/tests/source/docs/source/package_reference/prefix_tuning.md +62 -0
  32. tasks/tasksmith-9aea936e30e4/tests/source/docs/source/package_reference/prompt_tuning.md +31 -0
  33. tasks/tasksmith-9aea936e30e4/tests/source/docs/source/package_reference/pvera.md +40 -0
  34. tasks/tasksmith-9aea936e30e4/tests/source/docs/source/package_reference/randlora.md +45 -0
  35. tasks/tasksmith-9aea936e30e4/tests/source/docs/source/package_reference/road.md +31 -0
  36. tasks/tasksmith-9aea936e30e4/tests/source/docs/source/package_reference/shira.md +35 -0
  37. tasks/tasksmith-9aea936e30e4/tests/source/docs/source/package_reference/trainable_tokens.md +50 -0
  38. tasks/tasksmith-9aea936e30e4/tests/source/docs/source/package_reference/tuners.md +27 -0
  39. tasks/tasksmith-9aea936e30e4/tests/source/docs/source/package_reference/vblora.md +40 -0
  40. tasks/tasksmith-9aea936e30e4/tests/source/docs/source/package_reference/vera.md +39 -0
  41. tasks/tasksmith-9aea936e30e4/tests/source/docs/source/package_reference/waveft.md +35 -0
  42. tasks/tasksmith-9aea936e30e4/tests/source/docs/source/package_reference/xlora.md +56 -0
  43. tasks/tasksmith-9aea936e30e4/tests/source/docs/source/quicktour.md +164 -0
  44. tasks/tasksmith-9aea936e30e4/tests/source/docs/source/task_guides/ia3.md +235 -0
  45. tasks/tasksmith-9aea936e30e4/tests/source/docs/source/task_guides/lora_based_methods.md +344 -0
  46. tasks/tasksmith-9aea936e30e4/tests/source/docs/source/task_guides/prompt_based_methods.md +302 -0
  47. tasks/tasksmith-9aea936e30e4/tests/source/docs/source/tutorial/peft_integrations.md +152 -0
  48. tasks/tasksmith-9aea936e30e4/tests/source/docs/source/tutorial/peft_model_config.md +179 -0
  49. tasks/tasksmith-9aea936e30e4/tests/source/examples/alora_finetuning/README.md +76 -0
  50. tasks/tasksmith-9aea936e30e4/tests/source/examples/alora_finetuning/alora_finetuning.py +259 -0
tasks/tasksmith-9aea936e30e4/tests/source/docs/source/package_reference/auto_class.md ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ # AutoPeftModels
18
+
19
+ The `AutoPeftModel` classes loads the appropriate PEFT model for the task type by automatically inferring it from the configuration file. They are designed to quickly and easily load a PEFT model in a single line of code without having to worry about which exact model class you need or manually loading a [`PeftConfig`].
20
+
21
+ ## AutoPeftModel
22
+
23
+ [[autodoc]] auto.AutoPeftModel
24
+ - from_pretrained
25
+
26
+ ## AutoPeftModelForCausalLM
27
+
28
+ [[autodoc]] auto.AutoPeftModelForCausalLM
29
+
30
+ ## AutoPeftModelForSeq2SeqLM
31
+
32
+ [[autodoc]] auto.AutoPeftModelForSeq2SeqLM
33
+
34
+ ## AutoPeftModelForSequenceClassification
35
+
36
+ [[autodoc]] auto.AutoPeftModelForSequenceClassification
37
+
38
+ ## AutoPeftModelForTokenClassification
39
+
40
+ [[autodoc]] auto.AutoPeftModelForTokenClassification
41
+
42
+ ## AutoPeftModelForQuestionAnswering
43
+
44
+ [[autodoc]] auto.AutoPeftModelForQuestionAnswering
45
+
46
+ ## AutoPeftModelForFeatureExtraction
47
+
48
+ [[autodoc]] auto.AutoPeftModelForFeatureExtraction
tasks/tasksmith-9aea936e30e4/tests/source/docs/source/package_reference/boft.md ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ # BOFT
18
+
19
+ [Orthogonal Butterfly (BOFT)](https://hf.co/papers/2311.06243) is a generic method designed for finetuning foundation models. It improves the parameter efficiency of the finetuning paradigm -- Orthogonal Finetuning (OFT), by taking inspiration from Cooley-Tukey fast Fourier transform, showing favorable results across finetuning different foundation models, including large vision transformers, large language models and text-to-image diffusion models.
20
+
21
+ The abstract from the paper is:
22
+
23
+ *Large foundation models are becoming ubiquitous, but training them from scratch is prohibitively expensive. Thus, efficiently adapting these powerful models to downstream tasks is increasingly important. In this paper, we study a principled finetuning paradigm -- Orthogonal Finetuning (OFT) -- for downstream task adaptation. Despite demonstrating good generalizability, OFT still uses a fairly large number of trainable parameters due to the high dimensionality of orthogonal matrices. To address this, we start by examining OFT from an information transmission perspective, and then identify a few key desiderata that enable better parameter-efficiency. Inspired by how the Cooley-Tukey fast Fourier transform algorithm enables efficient information transmission, we propose an efficient orthogonal parameterization using butterfly structures. We apply this parameterization to OFT, creating a novel parameter-efficient finetuning method, called Orthogonal Butterfly (BOFT). By subsuming OFT as a special case, BOFT introduces a generalized orthogonal finetuning framework. Finally, we conduct an extensive empirical study of adapting large vision transformers, large language models, and text-to-image diffusion models to various downstream tasks in vision and language*.
24
+
25
+ ## BOFTConfig
26
+
27
+ [[autodoc]] tuners.boft.config.BOFTConfig
28
+
29
+ ## BOFTModel
30
+
31
+ [[autodoc]] tuners.boft.model.BOFTModel
tasks/tasksmith-9aea936e30e4/tests/source/docs/source/package_reference/bone.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
+ # Bone
18
+
19
+ DiSHA: Dimension-Sharding Adaptation ([DiSHA](https://huggingface.co/papers/2409.15371)) We introduce Dimension-Sharding Adaptation (DiSHA), which expands the PEFT design space to unlock lower intrinsic ranks and faster convergence by default. Building on DiSHA, we propose an efficient algorithm called Block-Affine Adaptation (Bone) structure and a non-linear update method called Block Affine Transformation Adaptation (BAT).
20
+
21
+
22
+ The abstract from the paper is:
23
+
24
+ Low-Rank Adaptation (LoRA) leverages the low intrinsic rank of weight updates in Large Language Models (LLMs), establishing a Parameter-Efficient Fine-Tuning (PEFT) paradigm. However, LoRA suffers from slow convergence. We introduce Dimension-Sharding Adaptation (DiSHA), which expands the PEFT design space to unlock lower intrinsic ranks and faster convergence by default. Within DiSHA's design space, we propose Block Affine Adaptation (Bone), a computationally efficient structure that delivers both high performance and efficiency. While certain DiSHA configurations may result in colinear updates to weight shards, we address this with Block Affine Transformation Adaptation (BAT), a nonlinear variant of DiSHA. BAT introduces nonlinearity by combining trainable matrices with original weight shards in a nonlinear manner, inducing nonlinearity in matrix updates without introducing additional parameters. Empirical results show that Bone, under the DiSHA framework, consistently outperforms LoRA variants in both NLG and NLU tasks, with significantly improved computational efficiency. Further analysis demonstrates that BAT enhances model capabilities by leveraging its nonlinear design.
25
+
26
+
27
+ ## BoneConfig
28
+
29
+ [[autodoc]] tuners.bone.config.BoneConfig
30
+
31
+ ## BoneModel
32
+
33
+ [[autodoc]] tuners.bone.model.BoneModel
tasks/tasksmith-9aea936e30e4/tests/source/docs/source/package_reference/c3a.md ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ # C3A: Parameter-Efficient Fine-Tuning via Circular Convolution
18
+
19
+ [C3A](https://huggingface.co/papers/2407.19342) is a parameter-efficient fine-tuning technique that leverages Circular Convolution to achieve high rank adaptation within reasonable resource limits.
20
+
21
+ Note that you should use a much larger learning rate (LR) for C3A than for other methods. For example, a LR of 1e-1 for C3A is a good starting point. Besides, a much smaller weight decay should be used. You can refer to the `method_comparison` folder for more details.
22
+
23
+ For the `block_size`, it affects tunable parameters and performance. To start with, you can choose a $\mathrm{gcd}(d_1,d_2)$ near $\frac{\sqrt{d_1 \times d_2}}{r}$, where $r$ is the rank for LoRA you would use for this task.
24
+
25
+ C3A currently has the following constraints:
26
+
27
+ - Only `nn.Linear` layers are supported.
28
+ - Quantized layers are not supported.
29
+ - The block size should be a common divisor of both the input and output sizes of target layers.
30
+
31
+ If these constraints don't work for your use case, consider other methods instead.
32
+
33
+ The abstract from the paper is:
34
+
35
+ > Low-Rank Adaptation (LoRA) has gained popularity for fine-tuning large foundation models, leveraging low-rank matrices $\mathbf{A}$ and $\mathbf{B}$ to represent weight changes (i.e., $\Delta \mathbf{W} = \mathbf{B} \mathbf{A}$). This method reduces trainable parameters and mitigates heavy memory consumption associated with full delta matrices by sequentially multiplying $\mathbf{A}$ and $\mathbf{B}$ with the activation. Despite its success, the intrinsic low-rank characteristic may limit its performance. Although several variants have been proposed to address this issue, they often overlook the crucial computational and memory efficiency brought by LoRA. In this paper, we propose Circular Convolution Adaptation (C3A), which not only achieves high-rank adaptation with enhanced performance but also excels in both computational power and memory utilization. Extensive experiments demonstrate that C3A consistently outperforms LoRA and its variants across various fine-tuning tasks.
36
+
37
+ ## C3AConfig
38
+
39
+ [[autodoc]] tuners.c3a.config.C3AConfig
40
+
41
+ ## C3AModel
42
+
43
+ [[autodoc]] tuners.c3a.model.C3AModel
tasks/tasksmith-9aea936e30e4/tests/source/docs/source/package_reference/cartridges.md ADDED
@@ -0,0 +1,91 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ # Cartridges
18
+
19
+ Cartridges are a prompt-learning method that stores a compressed long-context representation as a parameterized KV-cache
20
+ prefix. The core idea comes from the paper
21
+ [Cartridges: Lightweight and general-purpose long context representations via self-study](https://huggingface.co/papers/2506.06266).
22
+
23
+ For a high-level overview and motivation, see the blog post
24
+ [Cartridges: Storing long contexts in tiny caches with self-study](https://hazyresearch.stanford.edu/blog/2025-06-08-cartridges).
25
+
26
+ ## How Cartridges differ from Prefix Tuning
27
+
28
+ Both Prefix Tuning and Cartridges are served by injecting `past_key_values` (a prefix KV cache) into the base model.
29
+
30
+ - Prefix Tuning learns virtual token embeddings (and optionally an MLP projection) and produces a KV prefix.
31
+ - Cartridges learn the KV prefix itself directly (the per-layer key/value vectors for `p` virtual tokens), and are
32
+ designed to be initialized from real prefill KV (for example, the first `p` tokens of a corpus/system prompt).
33
+
34
+ The paper also recommends freezing the first token as an attention sink for stability (`num_frozen_tokens=1` is the
35
+ default).
36
+
37
+ ## Usage (inference)
38
+
39
+ Load a trained CARTRIDGE adapter and run generation:
40
+
41
+ ```py
42
+ from transformers import AutoModelForCausalLM, AutoTokenizer
43
+
44
+ from peft import PeftModel
45
+
46
+ model_id = "Qwen/Qwen2.5-0.5B-Instruct"
47
+ adapter_path = "path/to/cartridge_adapter"
48
+
49
+ base = AutoModelForCausalLM.from_pretrained(model_id)
50
+ model = PeftModel.from_pretrained(base, adapter_path)
51
+
52
+ tok = AutoTokenizer.from_pretrained(model_id)
53
+ if tok.pad_token is None:
54
+ tok.pad_token = tok.eos_token
55
+
56
+ out = model.generate(**tok("Question about the corpus:", return_tensors="pt"), max_new_tokens=64)
57
+ print(tok.decode(out[0], skip_special_tokens=True))
58
+ ```
59
+
60
+ If you need to create and initialize a cartridge before training, see the initialization options below.
61
+
62
+ ## Initialization options
63
+
64
+ The paper discusses a few practical initialization strategies:
65
+
66
+ - Random KV (default): create a `CartridgeConfig` and start training. This initializes the KV prefix randomly.
67
+ - KV from the first tokens of a prompt/corpus: use `initialize_kv_prefix_from_text(model, tokenizer, text=...)`. This
68
+ runs a prefill on `text` and copies the resulting KV cache for the first `num_virtual_tokens` into the adapter.
69
+ - KV from an existing cache: use `initialize_kv_prefix_from_past_key_values(model, past_key_values=...)` if you already
70
+ have a `past_key_values` object from a base-model prefill.
71
+
72
+ ## Training
73
+
74
+ The Cartridges paper proposes a SELF-STUDY distillation objective (a frozen base model provides teacher logits; the
75
+ CARTRIDGE adapter is trained so the student matches the teacher’s next-token distribution over the target segment).
76
+ PEFT keeps training logic out of the core library; see
77
+ `https://github.com/huggingface/peft/tree/main/examples/cartridge_self_study` for a reference workflow.
78
+ The example scripts use the frozen base model as the teacher and the adapted model as the student, so both share the
79
+ same underlying checkpoint.
80
+
81
+ ## Composition
82
+
83
+ To concatenate independently trained cartridges into a single adapter, use `compose_cartridge_adapters(...)`.
84
+
85
+ ## CartridgeConfig
86
+
87
+ [[autodoc]] tuners.cartridge.config.CartridgeConfig
88
+
89
+ ## CartridgeEncoder
90
+
91
+ [[autodoc]] tuners.cartridge.model.CartridgeEncoder
tasks/tasksmith-9aea936e30e4/tests/source/docs/source/package_reference/config.md ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ # Configuration
6
+
7
+ [`PeftConfigMixin`] is the base configuration class for storing the adapter configuration of a [`PeftModel`], and [`PromptLearningConfig`] is the base configuration class for soft prompt methods (p-tuning, prefix tuning, and prompt tuning). These base classes contain methods for saving and loading model configurations from the Hub, specifying the PEFT method to use, type of task to perform, and model configurations like number of layers and number of attention heads.
8
+
9
+ ## PeftConfigMixin
10
+
11
+ [[autodoc]] config.PeftConfigMixin
12
+ - all
13
+
14
+ ## PeftConfig
15
+
16
+ [[autodoc]] PeftConfig
17
+ - all
18
+
19
+ ## PromptLearningConfig
20
+
21
+ [[autodoc]] PromptLearningConfig
22
+ - all
tasks/tasksmith-9aea936e30e4/tests/source/docs/source/package_reference/cpt.md ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
9
+ ⚠️ Note that this file is in Markdown but contains specific syntax for our doc-builder (similar to MDX) that may not be
10
+ rendered properly in your Markdown viewer.
11
+ -->
12
+
13
+ # Context-aware Prompt Tuning: Advancing In-Context Learning with Adversarial Methods
14
+
15
+ [CPT](https://huggingface.co/papers/2410.17222) combines In-Context Learning (ICL), Prompt Tuning (PT), and adversarial optimization to improve few-shot learning by refining context embeddings. CPT updates the context tokens by optimizing both the context and the training examples, encapsulating them into a novel loss design that minimizes overfitting, enables more effective optimization, and drives significant improvements in classification tasks.
16
+
17
+ [//]: # ([CPT]&#40;https://huggingface.co/papers/2410.17222&#41; for the paper)
18
+
19
+ The abstract from the paper is:
20
+
21
+ > Large Language Models (LLMs) can perform few-shot learning using either optimization-based approaches or In-Context Learning (ICL). Optimization-based methods often suffer from overfitting, as they require updating a large number of parameters with limited data. In contrast, ICL avoids overfitting but typically underperforms compared to optimization-based methods and is highly sensitive to the selection, order, and format of demonstration examples. To overcome these challenges, we introduce Context-aware Prompt Tuning (CPT), a method inspired by ICL, Prompt Tuning (PT), and adversarial attacks. CPT builds on the ICL strategy of concatenating examples before the input, extending it by incorporating PT-like learning to refine the context embedding through iterative optimization, extracting deeper insights from the training examples. Our approach carefully modifies specific context tokens, considering the unique structure of the examples within the context. In addition to updating the context with PT-like optimization, CPT draws inspiration from adversarial attacks, adjusting the input based on the labels present in the context while preserving the inherent value of the user-provided data. To ensure robustness and stability during optimization, we employ a projected gradient descent algorithm, constraining token embeddings to remain close to their original values and safeguarding the quality of the context. Our method has demonstrated superior accuracy across multiple classification tasks using various LLM models, outperforming existing baselines and effectively addressing the overfitting challenge in few-shot learning.
22
+
23
+
24
+ Take a look at [Example](https://github.com/huggingface/peft/blob/main/examples/cpt_finetuning/README.md) for a step-by-step guide on how to train a model with CPT.
25
+
26
+
27
+ ## CPTConfig
28
+
29
+ [[autodoc]] tuners.cpt.config.CPTConfig
30
+
31
+ ## CPTEmbedding
32
+
33
+ [[autodoc]] tuners.cpt.model.CPTEmbedding
34
+
tasks/tasksmith-9aea936e30e4/tests/source/docs/source/package_reference/delora.md ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ # DeLoRA: Decoupled Low-rank Adaptation
18
+ [DeLoRA](https://huggingface.co/papers/2503.18225) is a parameter-efficient fine-tuning technique that implicitly maintains a Frobenius boundary with respect to the pretrained weights by normalizing and scaling learnable low-rank matrices. This effectively decouples the learning of directions (BA term) and magnitude (boundary term) of the weight updates, avoiding catastrophic shifts in the adapted weights and enhancing robustness to hyperparameter choices.
19
+
20
+ Note:
21
+ - use a learning rate 10-100x larger than for standard LoRA variants (typical values from 1e-3/1e-2/..)
22
+ - ensure the initial boundary parameter lambda is not too small (typical values around 10/15/..). Setting different lambdas to different layers is possible
23
+
24
+ DeLoRA currently has the following constraints:
25
+ - Only nn.Linear layers are supported.
26
+ - Quantized layers are not supported.
27
+
28
+ If these constraints don't work for your use case, consider other methods instead.
29
+
30
+ The abstract from the paper is:
31
+
32
+ > Parameter-Efficient FineTuning (PEFT) methods have recently gained significant popularity thanks to the widespread availability of large-scale pretrained models. These methods allow for quick adaptation to downstream tasks with minimal computational cost. However, popular finetuning methods such as LoRA exhibit limited robustness when it comes to hyperparameter choices or extended training regimes, preventing optimal out-of-the-box performance. In contrast, bounded approaches, such as ETHER, provide greater robustness but are limited to extremely low-rank adaptations and fixed-strength transformations, reducing their adaptation expressive power. In this work, we propose Decoupled Low-rank Adaptation (DeLoRA), a novel finetuning method that normalizes and scales learnable low-rank matrices. By bounding the distance of the transformation, DeLoRA effectively decouples the angular learning from the adaptation strength, enhancing robustness without compromising performance. Through evaluations on subject-driven image generation, natural language understanding, and instruction tuning, we show that DeLoRA matches or surpasses performance of competing PEFT methods, while exhibiting stronger robustness.
33
+
34
+ ## DeloraConfig
35
+
36
+ [[autodoc]] tuners.delora.config.DeloraConfig
37
+
38
+ ## DeloraModel
39
+
40
+ [[autodoc]] tuners.delora.model.DeloraModel
tasks/tasksmith-9aea936e30e4/tests/source/docs/source/package_reference/fourierft.md ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ # FourierFT: Discrete Fourier Transformation Fine-Tuning
18
+
19
+ [FourierFT](https://huggingface.co/papers/2405.03003) is a parameter-efficient fine-tuning technique that leverages Discrete Fourier Transform to compress the model's tunable weights. This method outperforms LoRA in the GLUE benchmark and common ViT classification tasks using much less parameters.
20
+
21
+ FourierFT currently has the following constraints:
22
+
23
+ - Only `nn.Linear` layers are supported.
24
+ - Quantized layers are not supported.
25
+
26
+ If these constraints don't work for your use case, consider other methods instead.
27
+
28
+ The abstract from the paper is:
29
+
30
+ > Low-rank adaptation (LoRA) has recently gained much interest in fine-tuning foundation models. It effectively reduces the number of trainable parameters by incorporating low-rank matrices A and B to represent the weight change, i.e., Delta W=BA. Despite LoRA's progress, it faces storage challenges when handling extensive customization adaptations or larger base models. In this work, we aim to further compress trainable parameters by enjoying the powerful expressiveness of the Fourier transform. Specifically, we introduce FourierFT, which treats Delta W as a matrix in the spatial domain and learns only a small fraction of its spectral coefficients. With the trained spectral coefficients, we implement the inverse discrete Fourier transform to recover Delta W. Empirically, our FourierFT method shows comparable or better performance with fewer parameters than LoRA on various tasks, including natural language understanding, natural language generation, instruction tuning, and image classification. For example, when performing instruction tuning on the LLaMA2-7B model, FourierFT surpasses LoRA with only 0.064M trainable parameters, compared to LoRA's 33.5M.
31
+
32
+ ## FourierFTConfig
33
+
34
+ [[autodoc]] tuners.fourierft.config.FourierFTConfig
35
+
36
+ ## FourierFTModel
37
+
38
+ [[autodoc]] tuners.fourierft.model.FourierFTModel
tasks/tasksmith-9aea936e30e4/tests/source/docs/source/package_reference/functional.md ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ # Functions for PEFT integration
6
+
7
+ A collection of functions that could be useful for non-PeftModel models, e.g. transformers or diffusers integration
8
+
9
+ The functions provided here can be considered "public API" of PEFT and hence are safe to be used by packages that provide PEFT integrations.
10
+
11
+ ## Cast the adapter weight dtypes
12
+ [[autodoc]] functional.cast_adapter_dtype
13
+ - all
14
+
15
+ ## Delete the PEFT adapter from model
16
+ [[autodoc]] functional.delete_adapter
17
+ - all
18
+
19
+ ## Get the state dict of the PEFT adapter
20
+ [[autodoc]] functional.get_peft_model_state_dict
21
+ - all
22
+
23
+ ## Inject a PEFT adapter into the model based on a PEFT config
24
+ [[autodoc]] functional.inject_adapter_in_model
25
+ - all
26
+
27
+ ## Set the active PEFT adapter(s) of the model
28
+ [[autodoc]] functional.set_adapter
29
+ - all
30
+
31
+ ## Set the `requires_grad` attribute of the specified adapters
32
+ [[autodoc]] functional.set_requires_grad
33
+ - all
34
+
35
+ ## Load the weights of the PEFT state dict into the model
36
+ [[autodoc]] functional.set_peft_model_state_dict
37
+ - all
tasks/tasksmith-9aea936e30e4/tests/source/docs/source/package_reference/gralora.md ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # GraLoRA
2
+
3
+ [**Granular Low-Rank Adaptation (GraLoRA)**](https://huggingface.co/papers/2505.20355) is a PEFT method designed to enhance the **expressivity** of low-rank adaptation while improving **robustness to outlier** activations, based on insights from well-known issues in quantization.
4
+
5
+ ![GraLoRA Overview](https://github.com/SqueezeBits/GraLoRA/raw/main/figure/gralora_overview.png)
6
+
7
+ Unlike standard LoRA, which applies a single low-rank adapter across the entire feature space, GraLoRA introduces a structured and fine-grained adaptation scheme. It divides the adaptation space into a grid of $𝑘^2$ smaller, independent adapter pairs, each responsible for a localized subset of the input and output dimensions. As a result, each adapter operates on a subspace that is $k$ times smaller in both dimensions than the original LoRA adapter.
8
+
9
+ This granular decomposition enables spatially localized and context-aware updates, effectively increasing representational capacity without additional parameters or computational cost. By isolating the influence of extreme activations within smaller subspaces, GraLoRA mitigates gradient distortion and preserves inter-channel balance during adaptation.
10
+
11
+ ---
12
+
13
+ The abstract from the paper is:
14
+
15
+ *Low-Rank Adaptation (LoRA) is a popular method for parameter-efficient fine-
16
+ tuning (PEFT) of generative models, valued for its simplicity and effectiveness.
17
+ Despite recent enhancements, LoRA still suffers from a fundamental limitation:
18
+ overfitting when the bottleneck is widened. It performs best at ranks 32–64, yet its
19
+ accuracy stagnates or declines at higher ranks, still falling short of full fine-tuning
20
+ (FFT) performance. We identify the root cause as LoRA’s structural bottleneck,
21
+ which introduces gradient entanglement to the unrelated input channels and distorts
22
+ gradient propagation. To address this, we introduce a novel structure, Granular
23
+ Low-Rank Adaptation (GraLoRA) that partitions weight matrices into sub-blocks,
24
+ each with its own low-rank adapter. With negligible computational or storage cost,
25
+ GraLoRA overcomes LoRA’s limitations, effectively increases the representational
26
+ capacity, and more closely approximates FFT behavior. Experiments on code
27
+ generation, commonsense reasoning, mathematical reasoning, general language
28
+ understanding, and image generation benchmarks show that GraLoRA consistently
29
+ outperforms LoRA and other baselines, achieving up to +8.5% absolute gain in
30
+ Pass@1 on HumanEval+. These improvements hold across model sizes and rank
31
+ settings, making GraLoRA a scalable and robust solution for PEFT.*
32
+
tasks/tasksmith-9aea936e30e4/tests/source/docs/source/package_reference/helpers.md ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ # Helper methods
6
+
7
+ A collection of helper functions for PEFT.
8
+
9
+ ## Checking if a model is a PEFT model
10
+
11
+ [[autodoc]] helpers.check_if_peft_model
12
+ - all
13
+
14
+ ## Temporarily Rescaling Adapter Scale in LoraLayer Modules
15
+
16
+ [[autodoc]] helpers.rescale_adapter_scale
17
+ - all
18
+
19
+ ## Context manager to disable input dtype casting in the `forward` method of LoRA layers
20
+
21
+ [[autodoc]] helpers.disable_input_dtype_casting
22
+ - all
23
+
24
+ ## Context manager to enable DoRA caching (faster at inference time but requires more memory)
25
+
26
+ [[autodoc]] helpers.DoraCaching
27
+ - all
tasks/tasksmith-9aea936e30e4/tests/source/docs/source/package_reference/hotswap.md ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ ## Caveats
65
+
66
+ Hotswapping works with transformers models and diffusers models. However, there are some caveats:
67
+
68
+ - Right now, only LoRA is properly supported.
69
+ - It only works for the same PEFT method, so no swapping LoRA and LoHa, for example.
70
+ - 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.
71
+
72
+ ## API
73
+
74
+ [[autodoc]] utils.hotswap.hotswap_adapter
75
+ - all
76
+
77
+ [[autodoc]] utils.hotswap.hotswap_adapter_from_state_dict
78
+ - all
tasks/tasksmith-9aea936e30e4/tests/source/docs/source/package_reference/hra.md ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ [HRA](https://huggingface.co/papers/2405.17484) is a simple but effective adapter-based fine-tuning method by leveraging Householder reflections. This method harnesses the advantages of both strategies, reducing 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.
20
+
21
+
22
+ The abstract from the paper is:
23
+
24
+ > 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).
25
+
26
+ ## HRAConfig
27
+
28
+ [[autodoc]] tuners.hra.config.HRAConfig
29
+
30
+ ## HRAModel
31
+
32
+ [[autodoc]] tuners.hra.model.HRAModel
tasks/tasksmith-9aea936e30e4/tests/source/docs/source/package_reference/ia3.md ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ 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.
20
+
21
+ The abstract from the paper is:
22
+
23
+ *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*.
24
+
25
+ ## IA3Config
26
+
27
+ [[autodoc]] tuners.ia3.config.IA3Config
28
+
29
+ ## IA3Model
30
+
31
+ [[autodoc]] tuners.ia3.model.IA3Model
tasks/tasksmith-9aea936e30e4/tests/source/docs/source/package_reference/layernorm_tuning.md ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ ## LNTuningConfig
29
+
30
+ [[autodoc]] tuners.ln_tuning.config.LNTuningConfig
31
+
32
+ ## LNTuningModel
33
+
34
+ [[autodoc]] tuners.ln_tuning.model.LNTuningModel
tasks/tasksmith-9aea936e30e4/tests/source/docs/source/package_reference/llama_adapter.md ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ [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.
20
+
21
+ The abstract from the paper is:
22
+
23
+ *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*.
24
+
25
+ ## AdaptionPromptConfig
26
+
27
+ [[autodoc]] tuners.adaption_prompt.config.AdaptionPromptConfig
28
+
29
+ ## AdaptionPromptModel
30
+
31
+ [[autodoc]] tuners.adaption_prompt.model.AdaptionPromptModel
tasks/tasksmith-9aea936e30e4/tests/source/docs/source/package_reference/loha.md ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ 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.
20
+
21
+ The abstract from the paper is:
22
+
23
+ *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*.
24
+
25
+ ## LoHaConfig
26
+
27
+ [[autodoc]] tuners.loha.config.LoHaConfig
28
+
29
+ ## LoHaModel
30
+
31
+ [[autodoc]] tuners.loha.model.LoHaModel
tasks/tasksmith-9aea936e30e4/tests/source/docs/source/package_reference/lokr.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
+ # LoKr
18
+
19
+ Low-Rank Kronecker Product ([LoKr](https://hf.co/papers/2309.14859)), is a LoRA-variant method that approximates the large weight matrix with two low-rank matrices and combines them with the Kronecker product. LoKr also provides an optional third low-rank matrix to provide better control during fine-tuning.
20
+
21
+ ## LoKrConfig
22
+
23
+ [[autodoc]] tuners.lokr.config.LoKrConfig
24
+
25
+ ## LoKrModel
26
+
27
+ [[autodoc]] tuners.lokr.model.LoKrModel
tasks/tasksmith-9aea936e30e4/tests/source/docs/source/package_reference/lora.md ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ # LoRA
18
+
19
+ Low-Rank Adaptation ([LoRA](https://huggingface.co/papers/2309.15223)) is a PEFT method that decomposes a large matrix into two smaller low-rank matrices in the attention layers. This drastically reduces the number of parameters that need to be fine-tuned.
20
+
21
+ The abstract from the paper is:
22
+
23
+ *We propose a neural language modeling system based on low-rank adaptation (LoRA) for speech recognition output rescoring. Although pretrained language models (LMs) like BERT have shown superior performance in second-pass rescoring, the high computational cost of scaling up the pretraining stage and adapting the pretrained models to specific domains limit their practical use in rescoring. Here we present a method based on low-rank decomposition to train a rescoring BERT model and adapt it to new domains using only a fraction (0.08%) of the pretrained parameters. These inserted matrices are optimized through a discriminative training objective along with a correlation-based regularization loss. The proposed low-rank adaptation Rescore-BERT (LoRB) architecture is evaluated on LibriSpeech and internal datasets with decreased training times by factors between 5.4 and 3.6.*.
24
+
25
+ ## LoraConfig
26
+
27
+ [[autodoc]] tuners.lora.config.LoraConfig
28
+
29
+ ## LoraModel
30
+
31
+ [[autodoc]] tuners.lora.model.LoraModel
32
+
33
+
34
+ ## Utility
35
+
36
+ ### ArrowConfig
37
+
38
+ [[autodoc]] tuners.lora.config.ArrowConfig
39
+
40
+ ### LoftQ
41
+
42
+ [[autodoc]] utils.loftq_utils.replace_lora_weights_loftq
43
+
44
+
45
+ ### Eva
46
+
47
+ #### EvaConfig
48
+
49
+ [[autodoc]] tuners.lora.config.EvaConfig
50
+
51
+ #### initialize_lora_eva_weights
52
+
53
+ [[autodoc]] tuners.lora.eva.initialize_lora_eva_weights
54
+
55
+ #### get_eva_state_dict
56
+
57
+ [[autodoc]] tuners.lora.eva.get_eva_state_dict
58
+
59
+
60
+ ## Variants
61
+
62
+ ### LoRA-GA
63
+
64
+ [LoRA-GA](https://hf.co/papers/2407.05000) (Low-Rank Adaptation with Gradient Approximation) improves upon standard LoRA by using gradient information during initialization to achieve faster convergence. Instead of random initialization, LoRA-GA performs SVD on estimated gradients to initialize adapter weights in a direction that aligns with full fine-tuning, resulting in 2-4x faster convergence with the same final performance.
65
+
66
+ The abstract from the paper is:
67
+
68
+ *Low-rank adaptation (LoRA) is a popular technique for parameter-efficient fine-tuning of large language models. However, LoRA's random initialization of adapter weights leads to slow convergence during the initial training phase. In this paper, we propose LoRA-GA (Low-Rank Adaptation with Gradient Approximation), a novel initialization method that leverages gradient information to initialize LoRA adapters. Specifically, we estimate gradients on a small set of training samples and perform singular value decomposition (SVD) to extract principal components. These components are used to initialize the adapter matrices, aligning the initial update direction with that of full fine-tuning. Our experiments across various tasks and model scales demonstrate that LoRA-GA achieves 2-4x faster convergence compared to standard LoRA while maintaining the same final performance. The method is orthogonal to existing LoRA variants and can be easily integrated with techniques like DoRA and LoRA+.*
69
+
70
+ #### Usage Tips
71
+
72
+ - **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).
73
+
74
+
75
+ - **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.
76
+
77
+ - **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.
78
+
79
+ - **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.
80
+
81
+ - **Compatibility**: LoRA-GA requires full-precision weights and does not support quantized models. Can be combined with other LoRA variants like DoRA.
82
+
83
+ #### LoraGAConfig
84
+
85
+ [[autodoc]] tuners.lora.config.LoraGAConfig
86
+
87
+ #### Utilities
88
+
89
+ [[autodoc]] tuners.lora.loraga.estimate_gradients
90
+
91
+ [[autodoc]] tuners.lora.loraga.preprocess_loraga
92
+
93
+
94
+ ## Intruder Dimension Reduction
95
+
96
+ [[autodoc]] tuners.lora.intruders.reduce_intruder_dimension
tasks/tasksmith-9aea936e30e4/tests/source/docs/source/package_reference/lora_conversion.md ADDED
@@ -0,0 +1,146 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 accomodate 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
+ ### LoRA to LoRA conversion
80
+
81
+ 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.
82
+
83
+ ## Metrics
84
+
85
+ ### Non-LoRA to LoRA conversion
86
+
87
+ 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 adaper, 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.
88
+
89
+ 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) 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:
90
+
91
+ | rank | trainable parameters | test accuracy (%) | accuracy change | memory reserved (max, GB) | memory increase |
92
+ |------|---------------------:|------------------:|----------------:|--------------------------:|----------------:|
93
+ | 8 | 2293760 | 37.60 | -4.25 | 12.41 | 0.16 |
94
+ | 16 | 4587520 | 38.89 | -2.96 | 12.15 | -0.10 |
95
+ | 32 | 9175040 | 40.11 | -1.74 | 12.41 | 0.16 |
96
+ | 64 | 18350080 | 39.20 | -2.65 | 12.18 | -0.07 |
97
+ | | | | | | |
98
+ | 0.4 | 2428928 | 37.60 | -4.25 | 12.41 | 0.16 |
99
+ | 0.5 | 4761600 | 40.18 | -1.67 | 12.41 | 0.16 |
100
+ | 0.6 | 8857600 | 39.42 | -2.43 | 12.41 | 0.16 |
101
+ | 0.7 | 16230400 | 39.04 | -2.81 | 12.15 | -0.10 |
102
+
103
+ 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.
104
+
105
+ 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.
106
+
107
+ ### LoRA to LoRA conversion
108
+
109
+ 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:
110
+
111
+ | rank | trainable parameters | test accuracy (%) | accuracy change | memory reserved (max, GB) | memory increase |
112
+ |------|---------------------:|------------------:|----------------:|--------------------------:|----------------:|
113
+ | 8 | 2293760 | 43.37 | -9.55 | 12.38 | -0.20 |
114
+ | 16 | 4587520 | 48.90 | -4.02 | 12.38 | -0.20 |
115
+ | 32 | 9175040 | 51.48 | -1.44 | 12.49 | -0.09 |
116
+ | 48 | 13762560 | 52.01 | -0.91 | 12.38 | -0.20 |
117
+ | | | | | | |
118
+ | 0.5 | 2150400 | 44.12 | -8.80 | 12.37 | -0.21 |
119
+ | 0.6 | 3082240 | 47.54 | -5.38 | 12.37 | -0.21 |
120
+ | 0.7 | 4448256 | 50.49 | -2.43 | 12.37 | -0.21 |
121
+ | 0.8 | 6510592 | 50.11 | -2.81 | 12.37 | -0.21 |
122
+ | 0.9 | 10022912 | 51.55 | -1.37 | 12.38 | -0.20 |
123
+ | 0.95 | 12976128 | 52.62 | -0.30 | 12.39 | -0.19 |
124
+
125
+ 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%.
126
+
127
+ ## Caveats
128
+
129
+ 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. Morever, LoRA conversion has these limitations:
130
+
131
+ - Right now, only adapters applied to linear layers can be converted.
132
+ - Not all PEFT methods currently support LoRA conversion.
133
+
134
+ If there is a lot of demand to extend LoRA conversion, please let us know and we will make it work with more layer types and PEFT methods.
135
+
136
+ ## API
137
+
138
+ ### Convert a non-LoRA model to a LoRA model, return the `LoraConfig` and `state_dict`
139
+
140
+ [[autodoc]] tuners.lora.conversion.convert_to_lora
141
+ - all
142
+
143
+ ### Convert a non-LoRA model to a LoRA model, save the adapter checkpoint and config at the given path
144
+
145
+ [[autodoc]] tuners.lora.conversion.save_as_lora
146
+ - all
tasks/tasksmith-9aea936e30e4/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-9aea936e30e4/tests/source/docs/source/package_reference/miss.md ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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: Balancing LoRA Performance and Efficiency with Simple Shard Sharing([MiSS](https://huggingface.co/papers/2409.15371)) is a novel PEFT method that adopts a low-rank structure, requires only a single trainable matrix, and introduces a new update mechanism distinct from LoRA, achieving an excellent balance between performance and efficiency.
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
+
26
+ ## MissConfig
27
+
28
+ [[autodoc]] tuners.miss.config.MissConfig
29
+
30
+ ## MissModel
31
+
32
+ [[autodoc]] tuners.miss.model.MissModel
tasks/tasksmith-9aea936e30e4/tests/source/docs/source/package_reference/multitask_prompt_tuning.md ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ ## MultitaskPromptTuningConfig
26
+
27
+ [[autodoc]] tuners.multitask_prompt_tuning.config.MultitaskPromptTuningConfig
28
+
29
+ ## MultitaskPromptEmbedding
30
+
31
+ [[autodoc]] tuners.multitask_prompt_tuning.model.MultitaskPromptEmbedding
tasks/tasksmith-9aea936e30e4/tests/source/docs/source/package_reference/oft.md ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ [Orthogonal Finetuning (OFT)](https://hf.co/papers/2306.07280) is a method developed for adapting text-to-image diffusion models. It works by reparameterizing the pretrained weight matrices with 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.
20
+
21
+ The abstract from the paper is:
22
+
23
+ *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*.
24
+
25
+ ## OFTConfig
26
+
27
+ [[autodoc]] tuners.oft.config.OFTConfig
28
+
29
+ ## OFTModel
30
+
31
+ [[autodoc]] tuners.oft.model.OFTModel
tasks/tasksmith-9aea936e30e4/tests/source/docs/source/package_reference/osf.md ADDED
@@ -0,0 +1,243 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ ## OSFConfig
226
+
227
+ [[autodoc]] tuners.osf.config.OSFConfig
228
+
229
+ ## OSFModel
230
+
231
+ [[autodoc]] tuners.osf.model.OSFModel
232
+
233
+ ## Utility Functions
234
+
235
+ ### Weight Decomposition
236
+
237
+ [[autodoc]] tuners.osf.utils.decompose_weight_matrix
238
+
239
+ [[autodoc]] tuners.osf.utils.reconstruct_weight_matrix
240
+
241
+ ### Gradient Projection
242
+
243
+ [[autodoc]] tuners.osf.utils.project_gradient_to_orthogonal_space
tasks/tasksmith-9aea936e30e4/tests/source/docs/source/package_reference/p_tuning.md ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ [P-tuning](https://hf.co/papers/2103.10385) adds trainable prompt embeddings to the input that is optimized by a prompt encoder to find a better prompt, eliminating the need to manually design prompts. The prompt tokens can be added anywhere in the input sequence, and p-tuning also introduces anchor tokens for improving performance.
20
+
21
+ The abstract from the paper is:
22
+
23
+ *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.*.
24
+
25
+ ## PromptEncoderConfig
26
+
27
+ [[autodoc]] tuners.p_tuning.config.PromptEncoderConfig
28
+
29
+ ## PromptEncoder
30
+
31
+ [[autodoc]] tuners.p_tuning.model.PromptEncoder
tasks/tasksmith-9aea936e30e4/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-9aea936e30e4/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-9aea936e30e4/tests/source/docs/source/package_reference/poly.md ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ ## PolyConfig
39
+
40
+ [[autodoc]] tuners.poly.config.PolyConfig
41
+
42
+ ## PolyModel
43
+
44
+ [[autodoc]] tuners.poly.model.PolyModel
tasks/tasksmith-9aea936e30e4/tests/source/docs/source/package_reference/prefix_tuning.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
+ # Prefix tuning
18
+
19
+ [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.
20
+
21
+ **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.
22
+
23
+ ## Initialize from a KV cache prefix
24
+
25
+ By default, prefix tuning is randomly initialized.
26
+
27
+ PEFT also provides utilities to initialize a prefix-tuning adapter from an existing KV cache prefix (for example, from
28
+ the first `p` tokens of a prompt/corpus). This is only supported when `prefix_projection=False` (the default), because
29
+ in that case the learned parameters are the KV prefix itself.
30
+
31
+ ```py
32
+ from transformers import AutoModelForCausalLM, AutoTokenizer
33
+
34
+ from peft import PrefixTuningConfig, get_peft_model, initialize_kv_prefix_from_text
35
+
36
+ base = AutoModelForCausalLM.from_pretrained("gpt2")
37
+ tok = AutoTokenizer.from_pretrained("gpt2")
38
+
39
+ peft_cfg = PrefixTuningConfig(task_type="CAUSAL_LM", num_virtual_tokens=20, prefix_projection=False)
40
+ model = get_peft_model(base, peft_cfg)
41
+
42
+ initialize_kv_prefix_from_text(
43
+ model,
44
+ tok,
45
+ text="...a long context with at least num_virtual_tokens tokens...",
46
+ use_chat_template=False,
47
+ )
48
+ ```
49
+
50
+ Make sure the text is long enough to produce at least `num_virtual_tokens` tokens, otherwise initialization will fail.
51
+
52
+ The abstract from the paper is:
53
+
54
+ *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*.
55
+
56
+ ## PrefixTuningConfig
57
+
58
+ [[autodoc]] tuners.prefix_tuning.config.PrefixTuningConfig
59
+
60
+ ## PrefixEncoder
61
+
62
+ [[autodoc]] tuners.prefix_tuning.model.PrefixEncoder
tasks/tasksmith-9aea936e30e4/tests/source/docs/source/package_reference/prompt_tuning.md ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ [Prompt tuning](https://hf.co/papers/2104.08691) adds task-specific prompts to the input, and these prompt parameters are updated independently of the pretrained model parameters which are frozen.
20
+
21
+ The abstract from the paper is:
22
+
23
+ *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*.
24
+
25
+ ## PromptTuningConfig
26
+
27
+ [[autodoc]] tuners.prompt_tuning.config.PromptTuningConfig
28
+
29
+ ## PromptEmbedding
30
+
31
+ [[autodoc]] tuners.prompt_tuning.model.PromptEmbedding
tasks/tasksmith-9aea936e30e4/tests/source/docs/source/package_reference/pvera.md ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ ## PveraConfig
35
+
36
+ [[autodoc]] tuners.pvera.config.PveraConfig
37
+
38
+ ## PveraModel
39
+
40
+ [[autodoc]] tuners.pvera.model.PveraModel
tasks/tasksmith-9aea936e30e4/tests/source/docs/source/package_reference/randlora.md ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 particulary usefull 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 intersted in using sparse ternary bases, the `sparse` option is recommended over the `very_sparse` one that can reduce perfromance.
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
+ ## RandLoraConfig
40
+
41
+ [[autodoc]] tuners.randlora.config.RandLoraConfig
42
+
43
+ ## RandLoraModel
44
+
45
+ [[autodoc]] tuners.randlora.model.RandLoraModel
tasks/tasksmith-9aea936e30e4/tests/source/docs/source/package_reference/road.md ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 simulatenously. 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](../developer_guides/lora#inference-with-different-lora-adapters-in-the-same-batch).
24
+
25
+ ## RoadConfig
26
+
27
+ [[autodoc]] tuners.road.config.RoadConfig
28
+
29
+ ## RoadModel
30
+
31
+ [[autodoc]] tuners.road.model.RoadModel
tasks/tasksmith-9aea936e30e4/tests/source/docs/source/package_reference/shira.md ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ ## ShiraConfig
30
+
31
+ [[autodoc]] tuners.shira.config.ShiraConfig
32
+
33
+ ## ShiraModel
34
+
35
+ [[autodoc]] tuners.shira.model.ShiraModel
tasks/tasksmith-9aea936e30e4/tests/source/docs/source/package_reference/trainable_tokens.md ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 developer guide](../developer_guides/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
+ ## TrainableTokensConfig
44
+
45
+ [[autodoc]] tuners.trainable_tokens.config.TrainableTokensConfig
46
+
47
+ ## TrainableTokensModel
48
+
49
+ [[autodoc]] tuners.trainable_tokens.model.TrainableTokensModel
50
+
tasks/tasksmith-9aea936e30e4/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-9aea936e30e4/tests/source/docs/source/package_reference/vblora.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
+ # 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 machanism. 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
+ ## VBLoRAConfig
34
+
35
+ [[autodoc]] tuners.vblora.config.VBLoRAConfig
36
+
37
+ ## VBLoRAModel
38
+
39
+ [[autodoc]] tuners.vblora.model.VBLoRAModel
40
+
tasks/tasksmith-9aea936e30e4/tests/source/docs/source/package_reference/vera.md ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 adapation (LoRA) is a popular method that reduces the number of trainable parameters when finetuning large language models, but still faces acute storage challenges when scaling to even larger models or deploying numerous per-user or per-task adapted models. In this work, we present Vector-based Random Matrix Adaptation (VeRA), which significantly reduces the number of trainable parameters compared to LoRA, yet maintains the same performance. It achieves this by using a single pair of low-rank matrices shared across all layers and learning small scaling vectors instead. We demonstrate its effectiveness on the GLUE and E2E benchmarks, image classification tasks, and show its application in instruction-tuning of 7B and 13B language models.
32
+
33
+ ## VeRAConfig
34
+
35
+ [[autodoc]] tuners.vera.config.VeraConfig
36
+
37
+ ## VeRAModel
38
+
39
+ [[autodoc]] tuners.vera.model.VeraModel
tasks/tasksmith-9aea936e30e4/tests/source/docs/source/package_reference/waveft.md ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ ## WaveFTConfig
30
+
31
+ [[autodoc]] tuners.waveft.config.WaveFTConfig
32
+
33
+ ## WaveFTModel
34
+
35
+ [[autodoc]] tuners.waveft.model.WaveFTModel
tasks/tasksmith-9aea936e30e4/tests/source/docs/source/package_reference/xlora.md ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ ![Token-by-token scalings](https://github.com/EricLBuehler/xlora/raw/master/res/token_by_token_scalings.gif)
26
+
27
+ The abstract from the paper is:
28
+
29
+ *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.*.
30
+
31
+ Please cite X-LoRA as:
32
+ ```bibtex
33
+ @article{10.1063/5.0203126,
34
+ author = {Buehler, Eric L. and Buehler, Markus J.},
35
+ title = "{X-LoRA: Mixture of low-rank adapter experts, a flexible framework for large language models with applications in protein mechanics and molecular design}",
36
+ journal = {APL Machine Learning},
37
+ volume = {2},
38
+ number = {2},
39
+ pages = {026119},
40
+ year = {2024},
41
+ month = {05},
42
+ 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.}",
43
+ issn = {2770-9019},
44
+ doi = {10.1063/5.0203126},
45
+ url = {https://doi.org/10.1063/5.0203126},
46
+ eprint = {https://pubs.aip.org/aip/aml/article-pdf/doi/10.1063/5.0203126/19964043/026119\_1\_5.0203126.pdf},
47
+ }
48
+ ```
49
+
50
+ ## XLoraConfig
51
+
52
+ [[autodoc]] tuners.xlora.config.XLoraConfig
53
+
54
+ ## XLoraModel
55
+
56
+ [[autodoc]] tuners.xlora.model.XLoraModel
tasks/tasksmith-9aea936e30e4/tests/source/docs/source/quicktour.md ADDED
@@ -0,0 +1,164 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ 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.
22
+
23
+ ## Train
24
+
25
+ Each PEFT method is defined by a [`PeftConfig`] class that stores all the important parameters for building a [`PeftModel`]. For example, to train with LoRA, load and create a [`LoraConfig`] class and specify the following parameters:
26
+
27
+ - `task_type`: the task to train for (sequence-to-sequence language modeling in this case)
28
+ - `inference_mode`: whether you're using the model for inference or not
29
+ - `r`: the dimension of the low-rank matrices
30
+ - `lora_alpha`: the scaling factor for the low-rank matrices
31
+ - `lora_dropout`: the dropout probability of the LoRA layers
32
+
33
+ ```python
34
+ from peft import LoraConfig, TaskType
35
+
36
+ peft_config = LoraConfig(task_type=TaskType.SEQ_2_SEQ_LM, inference_mode=False, r=8, lora_alpha=32, lora_dropout=0.1)
37
+ ```
38
+
39
+ > [!TIP]
40
+ > See the [`LoraConfig`] reference for more details about other parameters you can adjust, such as the modules to target or the bias type.
41
+
42
+ Once the [`LoraConfig`] is setup, create a [`PeftModel`] with the [`get_peft_model`] function. It takes a base model - which you can load from the Transformers library - and the [`LoraConfig`] containing the parameters for how to configure a model for training with LoRA.
43
+
44
+ Load the base model you want to finetune.
45
+
46
+ ```python
47
+ from transformers import AutoModelForSeq2SeqLM
48
+
49
+ model = AutoModelForSeq2SeqLM.from_pretrained("bigscience/mt0-large")
50
+ ```
51
+
52
+ Wrap the base model and `peft_config` with the [`get_peft_model`] function to create a [`PeftModel`]. To get a sense of the number of trainable parameters in your model, use the [`print_trainable_parameters`] method.
53
+
54
+ ```python
55
+ from peft import get_peft_model
56
+
57
+ model = get_peft_model(model, peft_config)
58
+ model.print_trainable_parameters()
59
+ "output: trainable params: 2359296 || all params: 1231940608 || trainable%: 0.19151053100118282"
60
+ ```
61
+
62
+ Out of [bigscience/mt0-large's](https://huggingface.co/bigscience/mt0-large) 1.2B parameters, you're only training 0.19% of them!
63
+
64
+ That is it 🎉! Now you can train the model with the Transformers [`~transformers.Trainer`], Accelerate, or any custom PyTorch training loop.
65
+
66
+ For example, to train with the [`~transformers.Trainer`] class, setup a [`~transformers.TrainingArguments`] class with some training hyperparameters.
67
+
68
+ ```py
69
+ training_args = TrainingArguments(
70
+ output_dir="your-name/bigscience/mt0-large-lora",
71
+ learning_rate=1e-3,
72
+ per_device_train_batch_size=32,
73
+ per_device_eval_batch_size=32,
74
+ num_train_epochs=2,
75
+ weight_decay=0.01,
76
+ eval_strategy="epoch",
77
+ save_strategy="epoch",
78
+ load_best_model_at_end=True,
79
+ )
80
+ ```
81
+
82
+ Pass the model, training arguments, dataset, tokenizer, and any other necessary component to the [`~transformers.Trainer`], and call [`~transformers.Trainer.train`] to start training.
83
+
84
+ ```py
85
+ trainer = Trainer(
86
+ model=model,
87
+ args=training_args,
88
+ train_dataset=tokenized_datasets["train"],
89
+ eval_dataset=tokenized_datasets["test"],
90
+ processing_class=tokenizer,
91
+ data_collator=data_collator,
92
+ compute_metrics=compute_metrics,
93
+ )
94
+
95
+ trainer.train()
96
+ ```
97
+
98
+ ### Save model
99
+
100
+ After your model is finished training, you can save your model to a directory using the [`~transformers.PreTrainedModel.save_pretrained`] function.
101
+
102
+ ```py
103
+ model.save_pretrained("output_dir")
104
+ ```
105
+
106
+ 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.
107
+
108
+ ```python
109
+ from huggingface_hub import notebook_login
110
+
111
+ notebook_login()
112
+ model.push_to_hub("your-name/bigscience/mt0-large-lora")
113
+ ```
114
+
115
+ 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!
116
+
117
+ <div class="flex flex-col justify-center">
118
+ <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/peft/PEFT-hub-screenshot.png"/>
119
+ <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>
120
+ </div>
121
+
122
+ ## Inference
123
+
124
+ > [!TIP]
125
+ > Take a look at the [AutoPeftModel](package_reference/auto_class) API reference for a complete list of available `AutoPeftModel` classes.
126
+
127
+ Easily load any PEFT-trained model for inference with the [`AutoPeftModel`] class and the [`~transformers.PreTrainedModel.from_pretrained`] method:
128
+
129
+ ```py
130
+ from peft import AutoPeftModelForCausalLM
131
+ from transformers import AutoTokenizer
132
+ import torch
133
+
134
+ model = AutoPeftModelForCausalLM.from_pretrained("ybelkada/opt-350m-lora")
135
+ tokenizer = AutoTokenizer.from_pretrained("facebook/opt-350m")
136
+
137
+ model = model.to("cuda")
138
+ model.eval()
139
+ inputs = tokenizer("Preheat the oven to 350 degrees and place the cookie dough", return_tensors="pt")
140
+
141
+ outputs = model.generate(input_ids=inputs["input_ids"].to("cuda"), max_new_tokens=50)
142
+ print(tokenizer.batch_decode(outputs.detach().cpu().numpy(), skip_special_tokens=True)[0])
143
+
144
+ "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."
145
+ ```
146
+
147
+ 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.
148
+
149
+ ```py
150
+ from peft import AutoPeftModel
151
+
152
+ model = AutoPeftModel.from_pretrained("smangrul/openai-whisper-large-v2-LORA-colab")
153
+ ```
154
+
155
+ ## Next steps
156
+
157
+ 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:
158
+
159
+ 1. prepare a [`PeftConfig`] for a PEFT method
160
+ 2. use the [`get_peft_model`] method to create a [`PeftModel`] from the configuration and base model
161
+
162
+ Then you can train it however you like! To load a PEFT model for inference, you can use the [`AutoPeftModel`] class.
163
+
164
+ 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-9aea936e30e4/tests/source/docs/source/task_guides/ia3.md ADDED
@@ -0,0 +1,235 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ # IA3
18
+
19
+ [IA3](../conceptual_guides/ia3) multiplies the model's activations (the keys and values in the self-attention and encoder-decoder attention blocks, and the intermediate activation of the position-wise feedforward network) by three learned vectors. This PEFT method introduces an even smaller number of trainable parameters than LoRA which introduces weight matrices instead of vectors. The original model's parameters are kept frozen and only these vectors are updated. As a result, it is faster, cheaper and more efficient to finetune for a new downstream task.
20
+
21
+ This guide will show you how to train a sequence-to-sequence model with IA3 to *generate a sentiment* given some financial news.
22
+
23
+ > [!TIP]
24
+ > Some familiarity with the general process of training a sequence-to-sequence would be really helpful and allow you to focus on how to apply IA3. If you’re new, we recommend taking a look at the [Translation](https://huggingface.co/docs/transformers/tasks/translation) and [Summarization](https://huggingface.co/docs/transformers/tasks/summarization) guides first from the Transformers documentation. When you’re ready, come back and see how easy it is to drop PEFT in to your training!
25
+
26
+ ## Dataset
27
+
28
+ You'll use the sentences_allagree subset of the [financial_phrasebank](https://huggingface.co/datasets/financial_phrasebank) dataset. This subset contains financial news with 100% annotator agreement on the sentiment label. Take a look at the [dataset viewer](https://huggingface.co/datasets/financial_phrasebank/viewer/sentences_allagree) for a better idea of the data and sentences you'll be working with.
29
+
30
+ Load the dataset with the [`~datasets.load_dataset`] function. This subset of the dataset only contains a train split, so use the [`~datasets.train_test_split`] function to create a train and validation split. Create a new `text_label` column so it is easier to understand what the `label` values `0`, `1`, and `2` mean.
31
+
32
+ ```py
33
+ from datasets import load_dataset
34
+
35
+ ds = load_dataset("financial_phrasebank", "sentences_allagree")
36
+ ds = ds["train"].train_test_split(test_size=0.1)
37
+ ds["validation"] = ds["test"]
38
+ del ds["test"]
39
+
40
+ classes = ds["train"].features["label"].names
41
+ ds = ds.map(
42
+ lambda x: {"text_label": [classes[label] for label in x["label"]]},
43
+ batched=True,
44
+ num_proc=1,
45
+ )
46
+
47
+ ds["train"][0]
48
+ {'sentence': 'It will be operated by Nokia , and supported by its Nokia NetAct network and service management system .',
49
+ 'label': 1,
50
+ 'text_label': 'neutral'}
51
+ ```
52
+
53
+ Load a tokenizer and create a preprocessing function that:
54
+
55
+ 1. tokenizes the inputs, pads and truncates the sequence to the `max_length`
56
+ 2. apply the same tokenizer to the labels but with a shorter `max_length` that corresponds to the label
57
+ 3. mask the padding tokens
58
+
59
+ ```py
60
+ from transformers import AutoTokenizer
61
+
62
+ text_column = "sentence"
63
+ label_column = "text_label"
64
+ max_length = 128
65
+
66
+ tokenizer = AutoTokenizer.from_pretrained("bigscience/mt0-large")
67
+
68
+ def preprocess_function(examples):
69
+ inputs = examples[text_column]
70
+ targets = examples[label_column]
71
+ model_inputs = tokenizer(inputs, max_length=max_length, padding="max_length", truncation=True, return_tensors="pt")
72
+ labels = tokenizer(targets, max_length=3, padding="max_length", truncation=True, return_tensors="pt")
73
+ labels = labels["input_ids"]
74
+ labels[labels == tokenizer.pad_token_id] = -100
75
+ model_inputs["labels"] = labels
76
+ return model_inputs
77
+ ```
78
+
79
+ Use the [`~datasets.Dataset.map`] function to apply the preprocessing function to the entire dataset.
80
+
81
+ ```py
82
+ processed_ds = ds.map(
83
+ preprocess_function,
84
+ batched=True,
85
+ num_proc=1,
86
+ remove_columns=ds["train"].column_names,
87
+ load_from_cache_file=False,
88
+ desc="Running tokenizer on dataset",
89
+ )
90
+ ```
91
+
92
+ Create a training and evaluation [`DataLoader`](https://pytorch.org/docs/stable/data.html#torch.utils.data.DataLoader), and set `pin_memory=True` to speed up data transfer to the accelerator during training if your dataset samples are on a CPU.
93
+
94
+ ```py
95
+ from torch.utils.data import DataLoader
96
+ from transformers import default_data_collator
97
+
98
+ train_ds = processed_ds["train"]
99
+ eval_ds = processed_ds["validation"]
100
+
101
+ batch_size = 8
102
+
103
+ train_dataloader = DataLoader(
104
+ train_ds, shuffle=True, collate_fn=default_data_collator, batch_size=batch_size, pin_memory=True
105
+ )
106
+ eval_dataloader = DataLoader(eval_ds, collate_fn=default_data_collator, batch_size=batch_size, pin_memory=True)
107
+ ```
108
+
109
+ ## Model
110
+
111
+ Now you can load a pretrained model to use as the base model for IA3. This guide uses the [bigscience/mt0-large](https://huggingface.co/bigscience/mt0-large) model, but you can use any sequence-to-sequence model you like.
112
+
113
+ ```py
114
+ from transformers import AutoModelForSeq2SeqLM
115
+
116
+ model = AutoModelForSeq2SeqLM.from_pretrained("bigscience/mt0-large")
117
+ ```
118
+
119
+ ### PEFT configuration and model
120
+
121
+ All PEFT methods need a configuration that contains and specifies all the parameters for how the PEFT method should be applied. Create an [`IA3Config`] with the task type and set the inference mode to `False`. You can find additional parameters for this configuration in the [API reference](../package_reference/ia3#ia3config).
122
+
123
+ > [!TIP]
124
+ > Call the [`~PeftModel.print_trainable_parameters`] method to compare the number of trainable parameters of [`PeftModel`] versus the number of parameters in the base model!
125
+
126
+ Once the configuration is setup, pass it to the [`get_peft_model`] function along with the base model to create a trainable [`PeftModel`].
127
+
128
+ ```py
129
+ from peft import IA3Config, get_peft_model
130
+
131
+ peft_config = IA3Config(task_type="SEQ_2_SEQ_LM")
132
+ model = get_peft_model(model, peft_config)
133
+ model.print_trainable_parameters()
134
+ "trainable params: 282,624 || all params: 1,229,863,936 || trainable%: 0.022980103060766553"
135
+ ```
136
+
137
+ ### Training
138
+
139
+ Set up an optimizer and learning rate scheduler.
140
+
141
+ ```py
142
+ import torch
143
+ from transformers import get_linear_schedule_with_warmup
144
+
145
+ lr = 8e-3
146
+ num_epochs = 3
147
+
148
+ optimizer = torch.optim.AdamW(model.parameters(), lr=lr)
149
+ lr_scheduler = get_linear_schedule_with_warmup(
150
+ optimizer=optimizer,
151
+ num_warmup_steps=0,
152
+ num_training_steps=(len(train_dataloader) * num_epochs),
153
+ )
154
+ ```
155
+
156
+ Move the model to the accelerator and create a training loop that reports the loss and perplexity for each epoch.
157
+
158
+ ```py
159
+ from tqdm import tqdm
160
+
161
+ device = torch.accelerator.current_accelerator().type if hasattr(torch, "accelerator") else "cuda"
162
+ model = model.to(device)
163
+
164
+ for epoch in range(num_epochs):
165
+ model.train()
166
+ total_loss = 0
167
+ for step, batch in enumerate(tqdm(train_dataloader)):
168
+ batch = {k: v.to(device) for k, v in batch.items()}
169
+ outputs = model(**batch)
170
+ loss = outputs.loss
171
+ total_loss += loss.detach().float()
172
+ loss.backward()
173
+ optimizer.step()
174
+ lr_scheduler.step()
175
+ optimizer.zero_grad()
176
+
177
+ model.eval()
178
+ eval_loss = 0
179
+ eval_preds = []
180
+ for step, batch in enumerate(tqdm(eval_dataloader)):
181
+ batch = {k: v.to(device) for k, v in batch.items()}
182
+ with torch.no_grad():
183
+ outputs = model(**batch)
184
+ loss = outputs.loss
185
+ eval_loss += loss.detach().float()
186
+ eval_preds.extend(
187
+ tokenizer.batch_decode(torch.argmax(outputs.logits, -1).detach().cpu().numpy(), skip_special_tokens=True)
188
+ )
189
+
190
+ eval_epoch_loss = eval_loss / len(eval_dataloader)
191
+ eval_ppl = torch.exp(eval_epoch_loss)
192
+ train_epoch_loss = total_loss / len(train_dataloader)
193
+ train_ppl = torch.exp(train_epoch_loss)
194
+ print(f"{epoch=}: {train_ppl=} {train_epoch_loss=} {eval_ppl=} {eval_epoch_loss=}")
195
+ ```
196
+
197
+ ## Share your model
198
+
199
+ After training is complete, you can upload your model to the Hub with the [`~transformers.PreTrainedModel.push_to_hub`] method. You'll need to login to your Hugging Face account first and enter your token when prompted.
200
+
201
+ ```py
202
+ from huggingface_hub import notebook_login
203
+
204
+ account = <your-hf-account-name>
205
+ peft_model_id = f"{account}/mt0-large-ia3"
206
+ model.push_to_hub(peft_model_id)
207
+ ```
208
+
209
+ ## Inference
210
+
211
+ To load the model for inference, use the [`~AutoPeftModelForSeq2SeqLM.from_pretrained`] method. Let's also load a sentence of financial news from the dataset to generate a sentiment for.
212
+
213
+ ```py
214
+ from peft import AutoPeftModelForSeq2SeqLM
215
+
216
+ device = torch.accelerator.current_accelerator().type if hasattr(torch, "accelerator") else "cuda"
217
+
218
+ model = AutoPeftModelForSeq2SeqLM.from_pretrained("<your-hf-account-name>/mt0-large-ia3").to(device)
219
+ tokenizer = AutoTokenizer.from_pretrained("bigscience/mt0-large")
220
+
221
+ i = 15
222
+ inputs = tokenizer(ds["validation"][text_column][i], return_tensors="pt")
223
+ print(ds["validation"][text_column][i])
224
+ "The robust growth was the result of the inclusion of clothing chain Lindex in the Group in December 2007 ."
225
+ ```
226
+
227
+ Call the [`~transformers.GenerationMixin.generate`] method to generate the predicted sentiment label.
228
+
229
+ ```py
230
+ with torch.no_grad():
231
+ inputs = {k: v.to(device) for k, v in inputs.items()}
232
+ outputs = model.generate(input_ids=inputs["input_ids"], max_new_tokens=10)
233
+ print(tokenizer.batch_decode(outputs.detach().cpu().numpy(), skip_special_tokens=True))
234
+ ['positive']
235
+ ```
tasks/tasksmith-9aea936e30e4/tests/source/docs/source/task_guides/lora_based_methods.md ADDED
@@ -0,0 +1,344 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ # LoRA methods
18
+
19
+ A popular way to efficiently train large models is to insert (typically in the attention blocks) smaller trainable matrices that are a low-rank decomposition of the delta weight matrix to be learnt during finetuning. The pretrained model's original weight matrix is frozen and only the smaller matrices are updated during training. This reduces the number of trainable parameters, reducing memory usage and training time which can be very expensive for large models.
20
+
21
+ There are several different ways to express the weight matrix as a low-rank decomposition, but [Low-Rank Adaptation (LoRA)](../conceptual_guides/adapter#low-rank-adaptation-lora) is the most common method. The PEFT library supports several other LoRA variants, such as [Low-Rank Hadamard Product (LoHa)](../conceptual_guides/adapter#low-rank-hadamard-product-loha), [Low-Rank Kronecker Product (LoKr)](../conceptual_guides/adapter#low-rank-kronecker-product-lokr), and [Adaptive Low-Rank Adaptation (AdaLoRA)](../conceptual_guides/adapter#adaptive-low-rank-adaptation-adalora). You can learn more about how these methods work conceptually in the [Adapters](../conceptual_guides/adapter) guide. If you're interested in applying these methods to other tasks and use cases like semantic segmentation, token classification, take a look at our [notebook collection](https://huggingface.co/collections/PEFT/notebooks-6573b28b33e5a4bf5b157fc1)!
22
+
23
+ Additionally, PEFT supports the [X-LoRA](../conceptual_guides/adapter#mixture-of-lora-experts-x-lora) Mixture of LoRA Experts method.
24
+
25
+ This guide will show you how to quickly train an image classification model - with a low-rank decomposition method - to identify the class of food shown in an image.
26
+
27
+ > [!TIP]
28
+ > Some familiarity with the general process of training an image classification model would be really helpful and allow you to focus on the low-rank decomposition methods. If you're new, we recommend taking a look at the [Image classification](https://huggingface.co/docs/transformers/tasks/image_classification) guide first from the Transformers documentation. When you're ready, come back and see how easy it is to drop PEFT in to your training!
29
+
30
+ Before you begin, make sure you have all the necessary libraries installed.
31
+
32
+ ```bash
33
+ pip install -q peft transformers datasets
34
+ ```
35
+
36
+ ## Dataset
37
+
38
+ In this guide, you'll use the [Food-101](https://huggingface.co/datasets/food101) dataset which contains images of 101 food classes (take a look at the [dataset viewer](https://huggingface.co/datasets/food101/viewer/default/train) to get a better idea of what the dataset looks like).
39
+
40
+ Load the dataset with the [`~datasets.load_dataset`] function.
41
+
42
+ ```py
43
+ from datasets import load_dataset
44
+
45
+ ds = load_dataset("food101")
46
+ ```
47
+
48
+ Each food class is labeled with an integer, so to make it easier to understand what these integers represent, you'll create a `label2id` and `id2label` dictionary to map the integer to its class label.
49
+
50
+ ```py
51
+ labels = ds["train"].features["label"].names
52
+ label2id, id2label = dict(), dict()
53
+ for i, label in enumerate(labels):
54
+ label2id[label] = i
55
+ id2label[i] = label
56
+
57
+ id2label[2]
58
+ "baklava"
59
+ ```
60
+
61
+ Load an image processor to properly resize and normalize the pixel values of the training and evaluation images.
62
+
63
+ ```py
64
+ from transformers import AutoImageProcessor
65
+
66
+ image_processor = AutoImageProcessor.from_pretrained("google/vit-base-patch16-224-in21k")
67
+ ```
68
+
69
+ You can also use the image processor to prepare some transformation functions for data augmentation and pixel scaling.
70
+
71
+ ```py
72
+ from torchvision.transforms import (
73
+ CenterCrop,
74
+ Compose,
75
+ Normalize,
76
+ RandomHorizontalFlip,
77
+ RandomResizedCrop,
78
+ Resize,
79
+ ToTensor,
80
+ )
81
+
82
+ normalize = Normalize(mean=image_processor.image_mean, std=image_processor.image_std)
83
+ train_transforms = Compose(
84
+ [
85
+ RandomResizedCrop(image_processor.size["height"]),
86
+ RandomHorizontalFlip(),
87
+ ToTensor(),
88
+ normalize,
89
+ ]
90
+ )
91
+
92
+ val_transforms = Compose(
93
+ [
94
+ Resize(image_processor.size["height"]),
95
+ CenterCrop(image_processor.size["height"]),
96
+ ToTensor(),
97
+ normalize,
98
+ ]
99
+ )
100
+
101
+ def preprocess_train(example_batch):
102
+ example_batch["pixel_values"] = [train_transforms(image.convert("RGB")) for image in example_batch["image"]]
103
+ return example_batch
104
+
105
+ def preprocess_val(example_batch):
106
+ example_batch["pixel_values"] = [val_transforms(image.convert("RGB")) for image in example_batch["image"]]
107
+ return example_batch
108
+ ```
109
+
110
+ Define the training and validation datasets, and use the [`~datasets.Dataset.set_transform`] function to apply the transformations on-the-fly.
111
+
112
+ ```py
113
+ train_ds = ds["train"]
114
+ val_ds = ds["validation"]
115
+
116
+ train_ds.set_transform(preprocess_train)
117
+ val_ds.set_transform(preprocess_val)
118
+ ```
119
+
120
+ Finally, you'll need a data collator to create a batch of training and evaluation data and convert the labels to `torch.tensor` objects.
121
+
122
+ ```py
123
+ import torch
124
+
125
+ def collate_fn(examples):
126
+ pixel_values = torch.stack([example["pixel_values"] for example in examples])
127
+ labels = torch.tensor([example["label"] for example in examples])
128
+ return {"pixel_values": pixel_values, "labels": labels}
129
+ ```
130
+
131
+ ## Model
132
+
133
+ Now let's load a pretrained model to use as the base model. This guide uses the [google/vit-base-patch16-224-in21k](https://huggingface.co/google/vit-base-patch16-224-in21k) model, but you can use any image classification model you want. Pass the `label2id` and `id2label` dictionaries to the model so it knows how to map the integer labels to their class labels, and you can optionally pass the `ignore_mismatched_sizes=True` parameter if you're finetuning a checkpoint that has already been finetuned.
134
+
135
+ ```py
136
+ from transformers import AutoModelForImageClassification, TrainingArguments, Trainer
137
+
138
+ model = AutoModelForImageClassification.from_pretrained(
139
+ "google/vit-base-patch16-224-in21k",
140
+ label2id=label2id,
141
+ id2label=id2label,
142
+ ignore_mismatched_sizes=True,
143
+ )
144
+ ```
145
+
146
+ ### PEFT configuration and model
147
+
148
+ Every PEFT method requires a configuration that holds all the parameters specifying how the PEFT method should be applied. Once the configuration is setup, pass it to the [`~peft.get_peft_model`] function along with the base model to create a trainable [`PeftModel`].
149
+
150
+ > [!TIP]
151
+ > Call the [`~PeftModel.print_trainable_parameters`] method to compare the number of parameters of [`PeftModel`] versus the number of parameters in the base model!
152
+
153
+ <hfoptions id="loras">
154
+ <hfoption id="LoRA">
155
+
156
+ [LoRA](../conceptual_guides/adapter#low-rank-adaptation-lora) decomposes the weight update matrix into *two* smaller matrices. The size of these low-rank matrices is determined by its *rank* or `r`. A higher rank means the model has more parameters to train, but it also means the model has more learning capacity. You'll also want to specify the `target_modules` which determine where the smaller matrices are inserted. For this guide, 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`].
157
+
158
+ ```py
159
+ from peft import LoraConfig, get_peft_model
160
+
161
+ config = LoraConfig(
162
+ r=16,
163
+ lora_alpha=16,
164
+ target_modules=["query", "value"],
165
+ lora_dropout=0.1,
166
+ bias="none",
167
+ modules_to_save=["classifier"],
168
+ )
169
+ model = get_peft_model(model, config)
170
+ model.print_trainable_parameters()
171
+ "trainable params: 667,493 || all params: 86,543,818 || trainable%: 0.7712775047664294"
172
+ ```
173
+
174
+ </hfoption>
175
+ <hfoption id="LoHa">
176
+
177
+ [LoHa](../conceptual_guides/adapter#low-rank-hadamard-product-loha) decomposes the weight update matrix into *four* smaller matrices and each pair of smaller matrices is combined with the Hadamard product. This allows the weight update matrix to keep the same number of trainable parameters when compared to LoRA, but with a higher rank (`r^2` for LoHA when compared to `2*r` for LoRA). The size of the smaller matrices is determined by its *rank* or `r`. You'll also want to specify the `target_modules` which determines where the smaller matrices are inserted. For this guide, you'll target the *query* and *value* matrices of the attention blocks. Other important parameters to set are `alpha` (scaling factor), and `modules_to_save` (the modules apart from the LoHa layers to be trained and saved). All of these parameters - and more - are found in the [`LoHaConfig`].
178
+
179
+ ```py
180
+ from peft import LoHaConfig, get_peft_model
181
+
182
+ config = LoHaConfig(
183
+ r=16,
184
+ alpha=16,
185
+ target_modules=["query", "value"],
186
+ module_dropout=0.1,
187
+ modules_to_save=["classifier"],
188
+ )
189
+ model = get_peft_model(model, config)
190
+ model.print_trainable_parameters()
191
+ "trainable params: 1,257,317 || all params: 87,133,642 || trainable%: 1.4429753779831676"
192
+ ```
193
+
194
+ </hfoption>
195
+ <hfoption id="LoKr">
196
+
197
+ [LoKr](../conceptual_guides/adapter#low-rank-kronecker-product-lokr) expresses the weight update matrix as a decomposition of a Kronecker product, creating a block matrix that is able to preserve the rank of the original weight matrix. The size of the smaller matrices are determined by its *rank* or `r`. You'll also want to specify the `target_modules` which determines where the smaller matrices are inserted. For this guide, you'll target the *query* and *value* matrices of the attention blocks. Other important parameters to set are `alpha` (scaling factor), and `modules_to_save` (the modules apart from the LoKr layers to be trained and saved). All of these parameters - and more - are found in the [`LoKrConfig`].
198
+
199
+ ```py
200
+ from peft import LoKrConfig, get_peft_model
201
+
202
+ config = LoKrConfig(
203
+ r=16,
204
+ alpha=16,
205
+ target_modules=["query", "value"],
206
+ module_dropout=0.1,
207
+ modules_to_save=["classifier"],
208
+ )
209
+ model = get_peft_model(model, config)
210
+ model.print_trainable_parameters()
211
+ "trainable params: 116,069 || all params: 87,172,042 || trainable%: 0.13314934162033282"
212
+ ```
213
+
214
+ </hfoption>
215
+ <hfoption id="AdaLoRA">
216
+
217
+ [AdaLoRA](../conceptual_guides/adapter#adaptive-low-rank-adaptation-adalora) efficiently manages the LoRA parameter budget by assigning important weight matrices more parameters and pruning less important ones. In contrast, LoRA evenly distributes parameters across all modules. You can control the average desired *rank* or `r` of the matrices, and which modules to apply AdaLoRA to with `target_modules`. Other important parameters to set are `lora_alpha` (scaling factor), and `modules_to_save` (the modules apart from the AdaLoRA layers to be trained and saved). All of these parameters - and more - are found in the [`AdaLoraConfig`].
218
+
219
+ ```py
220
+ from peft import AdaLoraConfig, get_peft_model
221
+
222
+ config = AdaLoraConfig(
223
+ r=8,
224
+ init_r=12,
225
+ tinit=200,
226
+ tfinal=1000,
227
+ deltaT=10,
228
+ target_modules=["query", "value"],
229
+ modules_to_save=["classifier"],
230
+ )
231
+ model = get_peft_model(model, config)
232
+ model.print_trainable_parameters()
233
+ "trainable params: 520,325 || all params: 87,614,722 || trainable%: 0.5938785036606062"
234
+ ```
235
+
236
+ </hfoption>
237
+ </hfoptions>
238
+
239
+ ### Training
240
+
241
+ For training, let's use the [`~transformers.Trainer`] class from Transformers. The [`Trainer`] contains a PyTorch training loop, and when you're ready, call [`~transformers.Trainer.train`] to start training. To customize the training run, configure the training hyperparameters in the [`~transformers.TrainingArguments`] class. With LoRA-like methods, you can afford to use a higher batch size and learning rate.
242
+
243
+ > [!WARNING]
244
+ > AdaLoRA has an [`~AdaLoraModel.update_and_allocate`] method that should be called at each training step to update the parameter budget and mask, otherwise the adaptation step is not performed. This requires writing a custom training loop or subclassing the [`~transformers.Trainer`] to incorporate this method. As an example, take a look at this [custom training loop](https://github.com/huggingface/peft/blob/912ad41e96e03652cabf47522cd876076f7a0c4f/examples/conditional_generation/peft_adalora_seq2seq.py#L120).
245
+
246
+ ```py
247
+ from transformers import TrainingArguments, Trainer
248
+
249
+ account = "stevhliu"
250
+ peft_model_id = f"{account}/google/vit-base-patch16-224-in21k-lora"
251
+ batch_size = 128
252
+
253
+ args = TrainingArguments(
254
+ peft_model_id,
255
+ remove_unused_columns=False,
256
+ eval_strategy="epoch",
257
+ save_strategy="epoch",
258
+ learning_rate=5e-3,
259
+ per_device_train_batch_size=batch_size,
260
+ gradient_accumulation_steps=4,
261
+ per_device_eval_batch_size=batch_size,
262
+ fp16=True,
263
+ num_train_epochs=5,
264
+ logging_steps=10,
265
+ load_best_model_at_end=True,
266
+ label_names=["labels"],
267
+ )
268
+ ```
269
+
270
+ Begin training with [`~transformers.Trainer.train`].
271
+
272
+ ```py
273
+ trainer = Trainer(
274
+ model,
275
+ args,
276
+ train_dataset=train_ds,
277
+ eval_dataset=val_ds,
278
+ processing_class=image_processor,
279
+ data_collator=collate_fn,
280
+ )
281
+ trainer.train()
282
+ ```
283
+
284
+ ## Share your model
285
+
286
+ Once training is complete, you can upload your model to the Hub with the [`~transformers.PreTrainedModel.push_to_hub`] method. You’ll need to login to your Hugging Face account first and enter your token when prompted.
287
+
288
+ ```py
289
+ from huggingface_hub import notebook_login
290
+
291
+ notebook_login()
292
+ ```
293
+
294
+ Call [`~transformers.PreTrainedModel.push_to_hub`] to save your model to your repositoy.
295
+
296
+ ```py
297
+ model.push_to_hub(peft_model_id)
298
+ ```
299
+
300
+ ## Inference
301
+
302
+ Let's load the model from the Hub and test it out on a food image.
303
+
304
+ ```py
305
+ from peft import PeftConfig, PeftModel
306
+ from transformers import AutoImageProcessor
307
+ from PIL import Image
308
+ import requests
309
+
310
+ config = PeftConfig.from_pretrained("stevhliu/vit-base-patch16-224-in21k-lora")
311
+ model = AutoModelForImageClassification.from_pretrained(
312
+ config.base_model_name_or_path,
313
+ label2id=label2id,
314
+ id2label=id2label,
315
+ ignore_mismatched_sizes=True,
316
+ )
317
+ model = PeftModel.from_pretrained(model, "stevhliu/vit-base-patch16-224-in21k-lora")
318
+
319
+ url = "https://huggingface.co/datasets/sayakpaul/sample-datasets/resolve/main/beignets.jpeg"
320
+ image = Image.open(requests.get(url, stream=True).raw)
321
+ image
322
+ ```
323
+
324
+ <div class="flex justify-center">
325
+ <img src="https://huggingface.co/datasets/sayakpaul/sample-datasets/resolve/main/beignets.jpeg">
326
+ </div>
327
+
328
+ Convert the image to RGB and return the underlying PyTorch tensors.
329
+
330
+ ```py
331
+ encoding = image_processor(image.convert("RGB"), return_tensors="pt")
332
+ ```
333
+
334
+ Now run the model and return the predicted class!
335
+
336
+ ```py
337
+ with torch.no_grad():
338
+ outputs = model(**encoding)
339
+ logits = outputs.logits
340
+
341
+ predicted_class_idx = logits.argmax(-1).item()
342
+ print("Predicted class:", model.config.id2label[predicted_class_idx])
343
+ "Predicted class: beignets"
344
+ ```
tasks/tasksmith-9aea936e30e4/tests/source/docs/source/task_guides/prompt_based_methods.md ADDED
@@ -0,0 +1,302 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ # Prompt-based methods
18
+
19
+ A prompt can describe a task or provide an example of a task you want the model to learn. Instead of manually creating these prompts, soft prompting methods add learnable parameters to the input embeddings that can be optimized for a specific task while keeping the pretrained model's parameters frozen. This makes it both faster and easier to finetune large language models (LLMs) for new downstream tasks.
20
+
21
+ The PEFT library supports several types of prompting methods (p-tuning, prefix tuning, prompt tuning) and you can learn more about how these methods work conceptually in the [Soft prompts](../conceptual_guides/prompting) guide. If you're interested in applying these methods to other tasks and use cases, take a look at our [notebook collection](https://huggingface.co/spaces/PEFT/soft-prompting)!
22
+
23
+ This guide will show you how to train a causal language model - with a soft prompting method - to *generate a classification* for whether a tweet is a complaint or not.
24
+
25
+ > [!TIP]
26
+ > Some familiarity with the general process of training a causal language model would be really helpful and allow you to focus on the soft prompting methods. If you're new, we recommend taking a look at the [Causal language modeling](https://huggingface.co/docs/transformers/tasks/language_modeling) guide first from the Transformers documentation. When you're ready, come back and see how easy it is to drop PEFT in to your training!
27
+
28
+ Before you begin, make sure you have all the necessary libraries installed.
29
+
30
+ ```bash
31
+ pip install -q peft transformers datasets
32
+ ```
33
+
34
+ ## Dataset
35
+
36
+ For this guide, you'll use the `twitter_complaints` subset of the [RAFT](https://huggingface.co/datasets/ought/raft) dataset. The `twitter_complaints` subset contains tweets labeled as `complaint` and `no complaint` and you can check out the [dataset viewer](https://huggingface.co/datasets/ought/raft/viewer/twitter_complaints) for a better idea of what the data looks like.
37
+
38
+ Use the [`~datasets.load_dataset`] function to load the dataset and create a new `text_label` column so it is easier to understand what the `Label` values, `1` and `2` mean.
39
+
40
+ ```py
41
+ from datasets import load_dataset
42
+
43
+ ds = load_dataset(
44
+ "parquet",
45
+ data_files={
46
+ "train": "hf://datasets/ought/raft@refs/convert/parquet/twitter_complaints/train/0000.parquet",
47
+ "test": "hf://datasets/ought/raft@refs/convert/parquet/twitter_complaints/test/0000.parquet"
48
+ }
49
+ )
50
+
51
+ classes = [k.replace("_", " ") for k in ds["train"].features["Label"].names]
52
+ ds = ds.map(
53
+ lambda x: {"text_label": [classes[label] for label in x["Label"]]},
54
+ batched=True,
55
+ num_proc=1,
56
+ )
57
+ ds["train"][0]
58
+ {"Tweet text": "@HMRCcustomers No this is my first job", "ID": 0, "Label": 2, "text_label": "no complaint"}
59
+ ```
60
+
61
+ Load a tokenizer, define the padding token to use, and determine the maximum length of the tokenized label.
62
+
63
+ ```py
64
+ from transformers import AutoTokenizer
65
+
66
+ tokenizer = AutoTokenizer.from_pretrained("bigscience/bloomz-560m")
67
+ if tokenizer.pad_token_id is None:
68
+ tokenizer.pad_token_id = tokenizer.eos_token_id
69
+ target_max_length = max([len(tokenizer(class_label)["input_ids"]) for class_label in classes])
70
+ print(target_max_length)
71
+ ```
72
+
73
+ Create a preprocessing function that tokenizes the tweet text and labels, pad the inputs and labels in each batch, create an attention mask, and truncate sequences to the `max_length`. Then convert the `input_ids`, `attention_mask`, and `labels` to PyTorch tensors.
74
+
75
+ ```py
76
+ import torch
77
+
78
+ max_length = 64
79
+
80
+ def preprocess_function(examples, text_column="Tweet text", label_column="text_label"):
81
+ batch_size = len(examples[text_column])
82
+ inputs = [f"{text_column} : {x} Label : " for x in examples[text_column]]
83
+ targets = [str(x) for x in examples[label_column]]
84
+ model_inputs = tokenizer(inputs)
85
+ labels = tokenizer(targets)
86
+ classes = [k.replace("_", " ") for k in ds["train"].features["Label"].names]
87
+ for i in range(batch_size):
88
+ sample_input_ids = model_inputs["input_ids"][i]
89
+ label_input_ids = labels["input_ids"][i]
90
+ model_inputs["input_ids"][i] = [tokenizer.pad_token_id] * (
91
+ max_length - len(sample_input_ids)
92
+ ) + sample_input_ids
93
+ model_inputs["attention_mask"][i] = [0] * (max_length - len(sample_input_ids)) + model_inputs[
94
+ "attention_mask"
95
+ ][i]
96
+ labels["input_ids"][i] = [-100] * (max_length - len(label_input_ids)) + label_input_ids
97
+ model_inputs["input_ids"][i] = torch.tensor(model_inputs["input_ids"][i][:max_length])
98
+ model_inputs["attention_mask"][i] = torch.tensor(model_inputs["attention_mask"][i][:max_length])
99
+ labels["input_ids"][i] = torch.tensor(labels["input_ids"][i][:max_length])
100
+ model_inputs["labels"] = labels["input_ids"]
101
+ return model_inputs
102
+ ```
103
+
104
+ Apply the preprocessing function to the entire dataset with the [`~datasets.Dataset.map`] function, and remove the unprocessed columns because the model won't need them.
105
+
106
+ ```py
107
+ processed_ds = ds.map(
108
+ preprocess_function,
109
+ batched=True,
110
+ num_proc=1,
111
+ remove_columns=ds["train"].column_names,
112
+ load_from_cache_file=False,
113
+ desc="Running tokenizer on dataset",
114
+ )
115
+ ```
116
+
117
+ Finally, create a training and evaluation [`DataLoader`](https://pytorch.org/docs/stable/data.html#torch.utils.data.DataLoader). You can set `pin_memory=True` to speed up the data transfer to the GPU during training if the samples in your dataset are on a CPU.
118
+
119
+ ```py
120
+ from torch.utils.data import DataLoader
121
+ from transformers import default_data_collator
122
+
123
+ train_ds = processed_ds["train"]
124
+ eval_ds = processed_ds["test"]
125
+
126
+ batch_size = 16
127
+
128
+ train_dataloader = DataLoader(train_ds, shuffle=True, collate_fn=default_data_collator, batch_size=batch_size, pin_memory=True)
129
+ eval_dataloader = DataLoader(eval_ds, collate_fn=default_data_collator, batch_size=batch_size, pin_memory=True)
130
+ ```
131
+
132
+ ## Model
133
+
134
+ Now let's load a pretrained model to use as the base model for the soft prompt method. This guide uses the [bigscience/bloomz-560m](https://huggingface.co/bigscience/bloomz-560m) model, but you can use any causal language model you want.
135
+
136
+ ```py
137
+ from transformers import AutoModelForCausalLM
138
+
139
+ model = AutoModelForCausalLM.from_pretrained("bigscience/bloomz-560m")
140
+ ```
141
+
142
+ ### PEFT configuration and model
143
+
144
+ 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. Once the configuration is setup, pass it to the [`~peft.get_peft_model`] function along with the base model to create a trainable [`PeftModel`].
145
+
146
+ > [!TIP]
147
+ > Call the [`~PeftModel.print_trainable_parameters`] method to compare the number of trainable parameters of [`PeftModel`] versus the number of parameters in the base model!
148
+
149
+ <hfoptions id="configurations">
150
+ <hfoption id="p-tuning">
151
+
152
+ [P-tuning](../conceptual_guides/prompting#p-tuning) adds a trainable embedding tensor where the prompt tokens can be added anywhere in the input sequence. 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.
153
+
154
+ ```py
155
+ from peft import PromptEncoderConfig, get_peft_model
156
+
157
+ peft_config = PromptEncoderConfig(task_type="CAUSAL_LM", num_virtual_tokens=20, encoder_hidden_size=128)
158
+ model = get_peft_model(model, peft_config)
159
+ model.print_trainable_parameters()
160
+ "trainable params: 300,288 || all params: 559,514,880 || trainable%: 0.05366935013417338"
161
+ ```
162
+
163
+ </hfoption>
164
+ <hfoption id="prefix tuning">
165
+
166
+ [Prefix tuning](../conceptual_guides/prompting#prefix-tuning) adds task-specific parameters in all of the model layers, which are optimized by a separate feed-forward network. Create a [`PrefixTuningConfig`] with the task type and number of virtual tokens to add and learn.
167
+
168
+ ```py
169
+ from peft import PrefixTuningConfig, get_peft_model
170
+
171
+ peft_config = PrefixTuningConfig(task_type="CAUSAL_LM", num_virtual_tokens=20)
172
+ model = get_peft_model(model, peft_config)
173
+ model.print_trainable_parameters()
174
+ "trainable params: 983,040 || all params: 560,197,632 || trainable%: 0.1754809274167014"
175
+ ```
176
+
177
+ </hfoption>
178
+ <hfoption id="prompt tuning">
179
+
180
+ [Prompt tuning](../conceptual_guides/prompting#prompt-tuning) formulates all tasks as a *generation* task and it adds a task-specific prompt to the input which is updated independently. The `prompt_tuning_init_text` parameter specifies how to finetune the model (in this case, it is classifying whether tweets are complaints or not). For the best results, the `prompt_tuning_init_text` should have the same number of tokens that should be predicted. To do this, you can set `num_virtual_tokens` to the number of tokens of the `prompt_tuning_init_text`.
181
+
182
+ 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.
183
+
184
+ ```py
185
+ from peft import PromptTuningConfig, PromptTuningInit, get_peft_model
186
+
187
+ prompt_tuning_init_text = "Classify if the tweet is a complaint or no complaint.\n"
188
+ peft_config = PromptTuningConfig(
189
+ task_type="CAUSAL_LM",
190
+ prompt_tuning_init=PromptTuningInit.TEXT,
191
+ num_virtual_tokens=len(tokenizer(prompt_tuning_init_text)["input_ids"]),
192
+ prompt_tuning_init_text=prompt_tuning_init_text,
193
+ tokenizer_name_or_path="bigscience/bloomz-560m",
194
+ )
195
+ model = get_peft_model(model, peft_config)
196
+ model.print_trainable_parameters()
197
+ "trainable params: 8,192 || all params: 559,222,784 || trainable%: 0.0014648902430985358"
198
+ ```
199
+
200
+ </hfoption>
201
+ </hfoptions>
202
+
203
+ ### Training
204
+
205
+ Set up an optimizer and learning rate scheduler.
206
+
207
+ ```py
208
+ from transformers import get_linear_schedule_with_warmup
209
+
210
+ lr = 3e-2
211
+ num_epochs = 50
212
+
213
+ optimizer = torch.optim.AdamW(model.parameters(), lr=lr)
214
+ lr_scheduler = get_linear_schedule_with_warmup(
215
+ optimizer=optimizer,
216
+ num_warmup_steps=0,
217
+ num_training_steps=(len(train_dataloader) * num_epochs),
218
+ )
219
+ ```
220
+
221
+ Move the model to the GPU and create a training loop that reports the loss and perplexity for each epoch.
222
+
223
+ ```py
224
+ from tqdm import tqdm
225
+
226
+ device = "cuda"
227
+ model = model.to(device)
228
+
229
+ for epoch in range(num_epochs):
230
+ model.train()
231
+ total_loss = 0
232
+ for step, batch in enumerate(tqdm(train_dataloader)):
233
+ batch = {k: v.to(device) for k, v in batch.items()}
234
+ outputs = model(**batch)
235
+ loss = outputs.loss
236
+ total_loss += loss.detach().float()
237
+ loss.backward()
238
+ optimizer.step()
239
+ lr_scheduler.step()
240
+ optimizer.zero_grad()
241
+
242
+ model.eval()
243
+ eval_loss = 0
244
+
245
+ for step, batch in enumerate(tqdm(eval_dataloader)):
246
+ batch = {k: v.to(device) for k, v in batch.items()}
247
+ with torch.no_grad():
248
+ outputs = model(**batch)
249
+ loss = outputs.loss
250
+ eval_loss += loss.detach().float()
251
+
252
+ eval_epoch_loss = eval_loss / len(eval_dataloader)
253
+ eval_ppl = torch.exp(eval_epoch_loss)
254
+ train_epoch_loss = total_loss / len(train_dataloader)
255
+ train_ppl = torch.exp(train_epoch_loss)
256
+ print(f"{epoch=}: {train_ppl=} {train_epoch_loss=} {eval_ppl=} {eval_epoch_loss=}")
257
+ ```
258
+
259
+ ## Share your model
260
+
261
+ Once training is complete, you can upload your model to the Hub with the [`~transformers.PreTrainedModel.push_to_hub`] method. You'll need to login to your Hugging Face account first and enter your token when prompted.
262
+
263
+ ```py
264
+ from huggingface_hub import notebook_login
265
+
266
+ account = <your-hf-account-name>
267
+ peft_model_id = f"{account}/bloomz-560-m-peft-method"
268
+ model.push_to_hub(peft_model_id)
269
+ ```
270
+
271
+ If you check the model file size in the repository, you’ll see that it is a lot smaller than a full sized model!
272
+
273
+ <div class="flex flex-col justify-center">
274
+ <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/peft/PEFT-hub-screenshot.png"/>
275
+ <figcaption class="text-center">For example, the adapter weights for a opt-350m model stored on the Hub are only ~6MB compared to the full model size which can be ~700MB.</figcaption>
276
+ </div>
277
+
278
+ ## Inference
279
+
280
+ Let's load the model for inference and test it out on a tweet!
281
+
282
+ ```py
283
+ from peft import AutoPeftModelForCausalLM
284
+
285
+ model = AutoPeftModelForCausalLM.from_pretrained("peft_model_id").to("cuda")
286
+ tokenizer = AutoTokenizer.from_pretrained("bigscience/bloomz-560m")
287
+
288
+ i = 15
289
+ inputs = tokenizer(f'{text_column} : {ds["test"][i]["Tweet text"]} Label : ', return_tensors="pt")
290
+ print(ds["test"][i]["Tweet text"])
291
+ "@NYTsupport i have complained a dozen times &amp; yet my papers are still thrown FAR from my door. Why is this so hard to resolve?"
292
+ ```
293
+
294
+ Call the [`~transformers.GenerationMixin.generate`] method to generate the predicted classification label.
295
+
296
+ ```py
297
+ with torch.no_grad():
298
+ inputs = {k: v.to(device) for k, v in inputs.items()}
299
+ outputs = model.generate(input_ids=inputs["input_ids"], max_new_tokens=10)
300
+ print(tokenizer.batch_decode(outputs.detach().cpu().numpy(), skip_special_tokens=True))
301
+ "['Tweet text : @NYTsupport i have complained a dozen times &amp; yet my papers are still thrown FAR from my door. Why is this so hard to resolve? Label : complaint']"
302
+ ```
tasks/tasksmith-9aea936e30e4/tests/source/docs/source/tutorial/peft_integrations.md ADDED
@@ -0,0 +1,152 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 integrations
18
+
19
+ PEFT's practical benefits extends to other Hugging Face libraries like [Diffusers](https://hf.co/docs/diffusers) and [Transformers](https://hf.co/docs/transformers). One of the main benefits of PEFT is that an adapter file generated by a PEFT method is a lot smaller than the original model, which makes it super easy to manage and use multiple adapters. You can use one pretrained base model for multiple tasks by simply loading a new adapter finetuned for the task you're solving. Or you can combine multiple adapters with a text-to-image diffusion model to create new effects.
20
+
21
+ This tutorial will show you how PEFT can help you manage adapters in Diffusers and Transformers.
22
+
23
+ ## Diffusers
24
+
25
+ Diffusers is a generative AI library for creating images and videos from text or images with diffusion models. LoRA is an especially popular training method for diffusion models because you can very quickly train and share diffusion models to generate images in new styles. To make it easier to use and try multiple LoRA models, Diffusers uses the PEFT library to help manage different adapters for inference.
26
+
27
+ For example, load a base model and then load the [artificialguybr/3DRedmond-V1](https://huggingface.co/artificialguybr/3DRedmond-V1) adapter for inference with the [`load_lora_weights`](https://huggingface.co/docs/diffusers/v0.24.0/en/api/loaders/lora#diffusers.loaders.LoraLoaderMixin.load_lora_weights) method. The `adapter_name` argument in the loading method is enabled by PEFT and allows you to set a name for the adapter so it is easier to reference.
28
+
29
+ ```py
30
+ import torch
31
+ from diffusers import DiffusionPipeline
32
+
33
+ pipeline = DiffusionPipeline.from_pretrained(
34
+ "stabilityai/stable-diffusion-xl-base-1.0", torch_dtype=torch.float16
35
+ ).to("cuda")
36
+ pipeline.load_lora_weights(
37
+ "peft-internal-testing/artificialguybr__3DRedmond-V1",
38
+ weight_name="3DRedmond-3DRenderStyle-3DRenderAF.safetensors",
39
+ adapter_name="3d"
40
+ )
41
+ image = pipeline("sushi rolls shaped like kawaii cat faces").images[0]
42
+ image
43
+ ```
44
+
45
+ <div class="flex justify-center">
46
+ <img src="https://huggingface.co/datasets/ybelkada/documentation-images/resolve/main/test-lora-diffusers.png"/>
47
+ </div>
48
+
49
+ Now let's try another cool LoRA model, [ostris/super-cereal-sdxl-lora](https://huggingface.co/ostris/super-cereal-sdxl-lora). All you need to do is load and name this new adapter with `adapter_name`, and use the [`set_adapters`](https://huggingface.co/docs/diffusers/api/loaders/unet#diffusers.loaders.UNet2DConditionLoadersMixin.set_adapters) method to set it as the currently active adapter.
50
+
51
+ ```py
52
+ pipeline.load_lora_weights(
53
+ "ostris/super-cereal-sdxl-lora",
54
+ weight_name="cereal_box_sdxl_v1.safetensors",
55
+ adapter_name="cereal"
56
+ )
57
+ pipeline.set_adapters("cereal")
58
+ image = pipeline("sushi rolls shaped like kawaii cat faces").images[0]
59
+ image
60
+ ```
61
+
62
+ <div class="flex justify-center">
63
+ <img src="https://huggingface.co/datasets/ybelkada/documentation-images/resolve/main/test-lora-diffusers-2.png"/>
64
+ </div>
65
+
66
+ Finally, you can call the [`disable_lora`](https://huggingface.co/docs/diffusers/api/loaders/unet#diffusers.loaders.UNet2DConditionLoadersMixin.disable_lora) method to restore the base model.
67
+
68
+ ```py
69
+ pipeline.disable_lora()
70
+ ```
71
+
72
+ Learn more about how PEFT supports Diffusers in the [Inference with PEFT](https://huggingface.co/docs/diffusers/tutorials/using_peft_for_inference) tutorial.
73
+
74
+ ## Transformers
75
+
76
+ 🤗 [Transformers](https://hf.co/docs/transformers) is a collection of pretrained models for all types of tasks in all modalities. You can load these models for training or inference. Many of the models are large language models (LLMs), so it makes sense to integrate PEFT with Transformers to manage and train adapters.
77
+
78
+ Load a base pretrained model to train.
79
+
80
+ ```py
81
+ from transformers import AutoModelForCausalLM
82
+
83
+ model = AutoModelForCausalLM.from_pretrained("facebook/opt-350m")
84
+ ```
85
+
86
+ Next, add an adapter configuration to specify how to adapt the model parameters. Call the [`~PeftModel.add_adapter`] method to add the configuration to the base model.
87
+
88
+ ```py
89
+ from peft import LoraConfig
90
+
91
+ peft_config = LoraConfig(
92
+ lora_alpha=16,
93
+ lora_dropout=0.1,
94
+ r=64,
95
+ bias="none",
96
+ task_type="CAUSAL_LM"
97
+ )
98
+ model.add_adapter(peft_config)
99
+ ```
100
+
101
+ Now you can train the model with Transformer's [`~transformers.Trainer`] class or whichever training framework you prefer.
102
+
103
+ To use the newly trained model for inference, the [`~transformers.AutoModel`] class uses PEFT on the backend to load the adapter weights and configuration file into a base pretrained model.
104
+
105
+ ```py
106
+ from transformers import AutoModelForCausalLM
107
+
108
+ model = AutoModelForCausalLM.from_pretrained("peft-internal-testing/opt-350m-lora")
109
+ ```
110
+
111
+ Alternatively, you can use transformers [Pipelines](https://huggingface.co/docs/transformers/en/main_classes/pipelines) to load the model for conveniently running inference:
112
+
113
+ ```py
114
+ from transformers import pipeline
115
+
116
+ model = pipeline("text-generation", "peft-internal-testing/opt-350m-lora")
117
+ print(model("Hello World"))
118
+ ```
119
+
120
+ If you're interested in comparing or using more than one adapter, you can call the [`~PeftModel.add_adapter`] method to add the adapter configuration to the base model. The only requirement is the adapter type must be the same (you can't mix a LoRA and LoHa adapter).
121
+
122
+ ```py
123
+ from transformers import AutoModelForCausalLM
124
+ from peft import LoraConfig
125
+
126
+ model = AutoModelForCausalLM.from_pretrained("facebook/opt-350m")
127
+ model.add_adapter(lora_config_1, adapter_name="adapter_1")
128
+ ```
129
+
130
+ Call [`~PeftModel.add_adapter`] again to attach a new adapter to the base model.
131
+
132
+ ```py
133
+ model.add_adapter(lora_config_2, adapter_name="adapter_2")
134
+ ```
135
+
136
+ Then you can use [`~PeftModel.set_adapter`] to set the currently active adapter.
137
+
138
+ ```py
139
+ model.set_adapter("adapter_1")
140
+ output = model.generate(**inputs)
141
+ print(tokenizer.decode(output_disabled[0], skip_special_tokens=True))
142
+ ```
143
+
144
+ To disable the adapter, call the [disable_adapters](https://github.com/huggingface/transformers/blob/4e3490f79b40248c53ee54365a9662611e880892/src/transformers/integrations/peft.py#L313) method.
145
+
146
+ ```py
147
+ model.disable_adapters()
148
+ ```
149
+
150
+ The [enable_adapters](https://github.com/huggingface/transformers/blob/4e3490f79b40248c53ee54365a9662611e880892/src/transformers/integrations/peft.py#L336) can be used to enable the adapters again.
151
+
152
+ If you're curious, check out the [Load and train adapters with PEFT](https://huggingface.co/docs/transformers/main/peft) tutorial to learn more.
tasks/tasksmith-9aea936e30e4/tests/source/docs/source/tutorial/peft_model_config.md ADDED
@@ -0,0 +1,179 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 configurations and models
18
+
19
+ The sheer size of today's large pretrained models - which commonly have billions of parameters - presents a significant training challenge because they require more storage space and more computational power to crunch all those calculations. You'll need access to powerful GPUs or TPUs to train these large pretrained models which is expensive, not widely accessible to everyone, not environmentally friendly, and not very practical. PEFT methods address many of these challenges. There are several types of PEFT methods (soft prompting, matrix decomposition, adapters), but they all focus on the same thing, reduce the number of trainable parameters. This makes it more accessible to train and store large models on consumer hardware.
20
+
21
+ The PEFT library is designed to help you quickly train large models on free or low-cost GPUs, and in this tutorial, you'll learn how to setup a configuration to apply a PEFT method to a pretrained base model for training. Once the PEFT configuration is setup, you can use any training framework you like (Transformer's [`~transformers.Trainer`] class, [Accelerate](https://hf.co/docs/accelerate), a custom PyTorch training loop).
22
+
23
+ ## PEFT configurations
24
+
25
+ > [!TIP]
26
+ > Learn more about the parameters you can configure for each PEFT method in their respective API reference page.
27
+
28
+ A configuration stores important parameters that specify how a particular PEFT method should be applied.
29
+
30
+ For example, take a look at the following [`LoraConfig`](https://huggingface.co/ybelkada/opt-350m-lora/blob/main/adapter_config.json) for applying LoRA and [`PromptEncoderConfig`](https://huggingface.co/smangrul/roberta-large-peft-p-tuning/blob/main/adapter_config.json) for applying p-tuning (these configuration files are already JSON-serialized). Whenever you load a PEFT adapter, it is a good idea to check whether it has an associated adapter_config.json file which is required.
31
+
32
+ <hfoptions id="config">
33
+ <hfoption id="LoraConfig">
34
+
35
+ ```json
36
+ {
37
+ "base_model_name_or_path": "facebook/opt-350m", #base model to apply LoRA to
38
+ "bias": "none",
39
+ "fan_in_fan_out": false,
40
+ "inference_mode": true,
41
+ "init_lora_weights": true,
42
+ "layers_pattern": null,
43
+ "layers_to_transform": null,
44
+ "lora_alpha": 32,
45
+ "lora_dropout": 0.05,
46
+ "modules_to_save": null,
47
+ "peft_type": "LORA", #PEFT method type
48
+ "r": 16,
49
+ "revision": null,
50
+ "target_modules": [
51
+ "q_proj", #model modules to apply LoRA to (query and value projection layers)
52
+ "v_proj"
53
+ ],
54
+ "task_type": "CAUSAL_LM" #type of task to train model on
55
+ }
56
+ ```
57
+
58
+ You can create your own configuration for training by initializing a [`LoraConfig`].
59
+
60
+ ```py
61
+ from peft import LoraConfig, TaskType
62
+
63
+ lora_config = LoraConfig(
64
+ r=16,
65
+ target_modules=["q_proj", "v_proj"],
66
+ task_type=TaskType.CAUSAL_LM,
67
+ lora_alpha=32,
68
+ lora_dropout=0.05
69
+ )
70
+ ```
71
+
72
+ </hfoption>
73
+ <hfoption id="PromptEncoderConfig">
74
+
75
+ ```json
76
+ {
77
+ "base_model_name_or_path": "roberta-large", #base model to apply p-tuning to
78
+ "encoder_dropout": 0.0,
79
+ "encoder_hidden_size": 128,
80
+ "encoder_num_layers": 2,
81
+ "encoder_reparameterization_type": "MLP",
82
+ "inference_mode": true,
83
+ "num_attention_heads": 16,
84
+ "num_layers": 24,
85
+ "num_transformer_submodules": 1,
86
+ "num_virtual_tokens": 20,
87
+ "peft_type": "P_TUNING", #PEFT method type
88
+ "task_type": "SEQ_CLS", #type of task to train model on
89
+ "token_dim": 1024
90
+ }
91
+ ```
92
+
93
+ You can create your own configuration for training by initializing a [`PromptEncoderConfig`].
94
+
95
+ ```py
96
+ from peft import PromptEncoderConfig, TaskType
97
+
98
+ p_tuning_config = PromptEncoderConfig(
99
+ encoder_reparameterization_type="MLP",
100
+ encoder_hidden_size=128,
101
+ num_attention_heads=16,
102
+ num_layers=24,
103
+ num_transformer_submodules=1,
104
+ num_virtual_tokens=20,
105
+ token_dim=1024,
106
+ task_type=TaskType.SEQ_CLS
107
+ )
108
+ ```
109
+
110
+ </hfoption>
111
+ </hfoptions>
112
+
113
+ ## PEFT models
114
+
115
+ With a PEFT configuration in hand, you can now apply it to any pretrained model to create a [`PeftModel`]. Choose from any of the state-of-the-art models from the [Transformers](https://hf.co/docs/transformers) library, a custom model, and even new and unsupported transformer architectures.
116
+
117
+ For this tutorial, load a base [facebook/opt-350m](https://huggingface.co/facebook/opt-350m) model to finetune.
118
+
119
+ ```py
120
+ from transformers import AutoModelForCausalLM
121
+
122
+ model = AutoModelForCausalLM.from_pretrained("facebook/opt-350m")
123
+ ```
124
+
125
+ Use the [`get_peft_model`] function to create a [`PeftModel`] from the base facebook/opt-350m model and the `lora_config` you created earlier.
126
+
127
+ ```py
128
+ from peft import get_peft_model
129
+
130
+ lora_model = get_peft_model(model, lora_config)
131
+ lora_model.print_trainable_parameters()
132
+ "trainable params: 1,572,864 || all params: 332,769,280 || trainable%: 0.472659014678278"
133
+ ```
134
+
135
+ > [!WARNING]
136
+ > When calling [`get_peft_model`], the base model will be modified *in-place*. That means, when calling [`get_peft_model`] on a model that was already modified in the same way before, this model will be further mutated. Therefore, if you would like to modify your PEFT configuration after having called [`get_peft_model()`] before, you would first have to unload the model with [`~LoraModel.unload`] and then call [`get_peft_model()`] with your new configuration. Alternatively, you can re-initialize the model to ensure a fresh, unmodified state before applying a new PEFT configuration.
137
+
138
+ Now you can train the [`PeftModel`] with your preferred training framework! After training, you can save your model locally with [`~PeftModel.save_pretrained`] or upload it to the Hub with the [`~transformers.PreTrainedModel.push_to_hub`] method.
139
+
140
+ ```py
141
+ # save locally
142
+ lora_model.save_pretrained("your-name/opt-350m-lora")
143
+
144
+ # push to Hub
145
+ lora_model.push_to_hub("your-name/opt-350m-lora")
146
+ ```
147
+
148
+ To load a [`PeftModel`] for inference, you'll need to provide the [`PeftConfig`] used to create it and the base model it was trained from.
149
+
150
+ ```py
151
+ from peft import PeftModel, PeftConfig
152
+
153
+ config = PeftConfig.from_pretrained("ybelkada/opt-350m-lora")
154
+ model = AutoModelForCausalLM.from_pretrained(config.base_model_name_or_path)
155
+ lora_model = PeftModel.from_pretrained(model, "ybelkada/opt-350m-lora")
156
+ ```
157
+
158
+ > [!TIP]
159
+ > By default, the [`PeftModel`] is set for inference, but if you'd like to train the adapter some more you can set `is_trainable=True`.
160
+ >
161
+ > ```py
162
+ > lora_model = PeftModel.from_pretrained(model, "ybelkada/opt-350m-lora", is_trainable=True)
163
+ > ```
164
+
165
+ The [`PeftModel.from_pretrained`] method is the most flexible way to load a [`PeftModel`] because it doesn't matter what model framework was used (Transformers, timm, a generic PyTorch model). Other classes, like [`AutoPeftModel`], are just a convenient wrapper around the base [`PeftModel`], and makes it easier to load PEFT models directly from the Hub or locally where the PEFT weights are stored.
166
+
167
+ ```py
168
+ from peft import AutoPeftModelForCausalLM
169
+
170
+ lora_model = AutoPeftModelForCausalLM.from_pretrained("ybelkada/opt-350m-lora")
171
+ ```
172
+
173
+ Take a look at the [AutoPeftModel](package_reference/auto_class) API reference to learn more about the [`AutoPeftModel`] classes.
174
+
175
+ ## Next steps
176
+
177
+ With the appropriate [`PeftConfig`], you can apply it to any pretrained model to create a [`PeftModel`] and train large powerful models faster on freely available GPUs! To learn more about PEFT configurations and models, the following guide may be helpful:
178
+
179
+ * Learn how to configure a PEFT method for models that aren't from Transformers in the [Working with custom models](../developer_guides/custom_models) guide.
tasks/tasksmith-9aea936e30e4/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-9aea936e30e4/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, data_path: str = 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)