-
Notifications
You must be signed in to change notification settings - Fork 2.3k
Mica #3260
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
sr-networks
wants to merge
5
commits into
huggingface:main
Choose a base branch
from
sr-networks:mica
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Mica #3260
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
26bdb48
FEAT Add MiCA (Minor Component Adaptation) as a LoRA variant
sr-networks 1ab020e
Merge branch 'main' into mica
sr-networks 50ecb0d
changes for ruff
sr-networks 23622a3
Update src/peft/tuners/lora/layer.py
sr-networks cd6bcae
Address MiCA trainability and embedding support
sr-networks File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,80 @@ | ||
| # MiCA: Minor Component Adaptation | ||
|
|
||
| ## Introduction ([Paper](https://arxiv.org/abs/2604.01694)) | ||
|
|
||
| Minor Component Adaptation (MiCA) is a parameter-efficient fine-tuning method closely related to LoRA. Like LoRA, MiCA inserts a low-rank update `ΔW = (α/r) · B · A` into a pretrained weight `W ∈ R^{out×in}`. Unlike LoRA, MiCA initializes the matrices from the singular value decomposition of `W` and trains only one of them: | ||
|
|
||
| - Compute the SVD `W = U Σ V^T`. | ||
| - Initialize `B = U[:, -r:]` — the `r` left singular vectors associated with the **smallest** singular values. | ||
| - Initialize `A = 0`. | ||
| - During training, optimize only `A`; `W` and `B` remain frozen. | ||
|
|
||
| The motivation is that the *minor* singular directions of a pretrained weight encode subspaces that are largely unused by the original task. Restricting adaptation to these directions provides a more "plastic" subspace for knowledge injection, with less risk of overwriting capabilities encoded in the dominant subspace. Empirically MiCA improves knowledge acquisition while reducing the trainable parameter footprint compared with LoRA at the same rank (because only `A` is trained, the parameter count is roughly halved for matching `r`). | ||
|
|
||
| Because `A == 0` at initialization, the adapter contribution `B · A == 0` and the model's forward output is preserved exactly at step 0 — no residual subtraction is needed on the base weight. | ||
|
|
||
| ## Quick Start | ||
|
|
||
| ```python | ||
| import torch | ||
| from peft import LoraConfig, get_peft_model | ||
| from transformers import AutoTokenizer, AutoModelForCausalLM | ||
| from trl import SFTConfig, SFTTrainer | ||
| from datasets import load_dataset | ||
|
|
||
| model = AutoModelForCausalLM.from_pretrained("meta-llama/Llama-2-7b-hf", dtype=torch.bfloat16, device_map="auto") | ||
| tokenizer = AutoTokenizer.from_pretrained("meta-llama/Llama-2-7b-hf") | ||
| tokenizer.pad_token_id = tokenizer.eos_token_id | ||
|
|
||
| lora_config = LoraConfig( | ||
| init_lora_weights="mica", | ||
| r=16, | ||
| lora_alpha=16, | ||
| target_modules=["q_proj", "v_proj"], | ||
| task_type="CAUSAL_LM", | ||
| ) | ||
| peft_model = get_peft_model(model, lora_config) | ||
| peft_model.print_trainable_parameters() | ||
|
|
||
| dataset = load_dataset("imdb", split="train[:1%]") | ||
| training_args = SFTConfig(dataset_text_field="text", max_length=128) | ||
| trainer = SFTTrainer( | ||
| model=peft_model, | ||
| args=training_args, | ||
| train_dataset=dataset, | ||
| processing_class=tokenizer, | ||
| ) | ||
| trainer.train() | ||
| peft_model.save_pretrained("mica-llama-2-7b") | ||
| ``` | ||
|
|
||
| To reload the trained adapter: | ||
|
|
||
| ```python | ||
| import torch | ||
| from peft import PeftModel | ||
| from transformers import AutoModelForCausalLM | ||
|
|
||
| model = AutoModelForCausalLM.from_pretrained( | ||
| "meta-llama/Llama-2-7b-hf", dtype=torch.bfloat16, device_map="auto" | ||
| ) | ||
| peft_model = PeftModel.from_pretrained(model, "mica-llama-2-7b") | ||
| ``` | ||
|
|
||
| ## Notes and limitations | ||
|
|
||
| - MiCA currently supports `nn.Linear` and `nn.Embedding` target modules. | ||
| - The chosen rank must satisfy `r <= min(in_features, out_features)` for linear layers and `r <= min(num_embeddings, embedding_dim)` for embedding layers; otherwise initialization raises `ValueError`. | ||
| - MiCA performs a full SVD per target weight at initialization. For 7B-scale models this is a one-time cost of seconds; for substantially larger weight matrices (e.g. 70B-scale) the cost grows. | ||
| - Combining MiCA with `use_dora=True` or other LoRA variants is not supported in this initial integration. | ||
|
|
||
| ## Citation | ||
|
|
||
| ``` | ||
| @article{rudiger2026mica, | ||
| title={MiCA Learns More Knowledge Than LoRA and Full Fine-Tuning}, | ||
| author={R{\"u}diger, Sten and Raschka, Sebastian}, | ||
| journal={arXiv preprint arXiv:2604.01694}, | ||
| year={2026} | ||
| } | ||
| ``` |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,80 @@ | ||
| # Copyright 2023-present the HuggingFace Inc. team. | ||
| # | ||
| # Licensed under the Apache License, Version 2.0 (the "License"); | ||
| # you may not use this file except in compliance with the License. | ||
| # You may obtain a copy of the License at | ||
| # | ||
| # http://www.apache.org/licenses/LICENSE-2.0 | ||
| # | ||
| # Unless required by applicable law or agreed to in writing, software | ||
| # distributed under the License is distributed on an "AS IS" BASIS, | ||
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| # See the License for the specific language governing permissions and | ||
| # limitations under the License. | ||
| """Minimal MiCA fine-tuning example. | ||
|
|
||
| Mirrors `examples/pissa_finetuning/pissa_finetuning.py` in spirit but with the MiCA-specific knobs only. MiCA | ||
| initializes `B` from the bottom-r left singular vectors of the base weight and freezes it during training; only | ||
| `A` is updated. Because `A == 0` at init, the adapter is a no-op on initialization and no residual subtraction | ||
| on the base weight is needed. | ||
| """ | ||
|
|
||
| from dataclasses import dataclass, field | ||
| from typing import Optional | ||
|
|
||
| import torch | ||
| from datasets import load_dataset | ||
| from transformers import AutoModelForCausalLM, AutoTokenizer, HfArgumentParser | ||
| from trl import SFTConfig, SFTTrainer | ||
|
|
||
| from peft import LoraConfig, get_peft_model | ||
|
|
||
|
|
||
| @dataclass | ||
| class ScriptArguments(SFTConfig): | ||
| base_model_name_or_path: Optional[str] = field(default=None, metadata={"help": "Name or path of the base model."}) | ||
| lora_r: int = field(default=16) | ||
| lora_alpha: int = field(default=16) | ||
| lora_dropout: float = field(default=0.0) | ||
| target_modules: Optional[str] = field( | ||
| default="q_proj,v_proj", | ||
| metadata={"help": "Comma-separated module names to adapt with MiCA."}, | ||
| ) | ||
| data_path: str = field(default="imdb", metadata={"help": "HF dataset path."}) | ||
| dataset_split: str = field(default="train[:1%]") | ||
| dataset_text_field: str = field(default="text") | ||
|
|
||
|
|
||
| def train(): | ||
| parser = HfArgumentParser(ScriptArguments) | ||
| args = parser.parse_args_into_dataclasses()[0] | ||
|
|
||
| model = AutoModelForCausalLM.from_pretrained(args.base_model_name_or_path, dtype=torch.bfloat16, device_map="auto") | ||
| tokenizer = AutoTokenizer.from_pretrained(args.base_model_name_or_path) | ||
| if tokenizer.pad_token_id is None: | ||
| tokenizer.pad_token_id = tokenizer.eos_token_id | ||
|
|
||
| lora_config = LoraConfig( | ||
| init_lora_weights="mica", | ||
| r=args.lora_r, | ||
| lora_alpha=args.lora_alpha, | ||
| lora_dropout=args.lora_dropout, | ||
| target_modules=[m.strip() for m in args.target_modules.split(",")], | ||
| task_type="CAUSAL_LM", | ||
| ) | ||
| peft_model = get_peft_model(model, lora_config) | ||
| peft_model.print_trainable_parameters() | ||
|
|
||
| dataset = load_dataset(args.data_path, split=args.dataset_split) | ||
| trainer = SFTTrainer( | ||
| model=peft_model, | ||
| args=args, | ||
| train_dataset=dataset, | ||
| processing_class=tokenizer, | ||
| ) | ||
| trainer.train() | ||
| peft_model.save_pretrained(args.output_dir) | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| train() |
30 changes: 30 additions & 0 deletions
30
method_comparison/MetaMathQA/experiments/lora/llama-3.2-3B-rank32-mica/adapter_config.json
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,30 @@ | ||
| { | ||
| "alpha_pattern": {}, | ||
| "auto_mapping": null, | ||
| "base_model_name_or_path": null, | ||
| "bias": "none", | ||
| "corda_config": null, | ||
| "eva_config": null, | ||
| "exclude_modules": null, | ||
| "fan_in_fan_out": false, | ||
| "inference_mode": false, | ||
| "init_lora_weights": "mica", | ||
| "layer_replication": null, | ||
| "layers_pattern": null, | ||
| "layers_to_transform": null, | ||
| "loftq_config": {}, | ||
| "lora_alpha": 64, | ||
| "lora_bias": false, | ||
| "lora_dropout": 0.0, | ||
| "megatron_config": null, | ||
| "megatron_core": "megatron.core", | ||
| "modules_to_save": null, | ||
| "peft_type": "LORA", | ||
| "r": 32, | ||
| "rank_pattern": {}, | ||
| "revision": null, | ||
| "target_modules": null, | ||
| "task_type": "CAUSAL_LM", | ||
| "use_dora": false, | ||
| "use_rslora": false | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.