opensi·si

Low-Rank Adaptation (LoRA) is a PEFT method that decomposes a large matrix into two smaller low-rank matrices. This drastically reduces the number of parameters that need to be…

LoRA

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

Low-Rank Adaptation (LoRA) is a PEFT method that decomposes a large matrix into two smaller low-rank matrices. This drastically reduces the number of parameters that need to be fine-tuned.

The abstract from the paper is:

An important paradigm of natural language processing consists of large-scale pre-training on general domain data and adaptation to particular tasks or domains. As we pre-train larger models, full fine-tuning, which retrains all model parameters, becomes less feasible. Using GPT-3 175B as an example -- deploying independent instances of fine-tuned models, each with 175B parameters, is prohibitively expensive. We propose Low-Rank Adaptation, or LoRA, which freezes the pre-trained model weights and injects trainable rank decomposition matrices into each layer of the Transformer architecture, greatly reducing the number of trainable parameters for downstream tasks. Compared to GPT-3 175B fine-tuned with Adam, LoRA can reduce the number of trainable parameters by 10,000 times and the GPU memory requirement by 3 times. LoRA performs on-par or better than fine-tuning in model quality on RoBERTa, DeBERTa, GPT-2, and GPT-3, despite having fewer trainable parameters, a higher training throughput, and, unlike adapters, no additional inference latency. We also provide an empirical investigation into rank-deficiency in language model adaptation, which sheds light on the efficacy of LoRA. We release a package that facilitates the integration of LoRA with PyTorch models and provide our implementations and model checkpoints for RoBERTa, DeBERTa, and GPT-2 at this https URL.

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

This approach has a number of advantages:

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

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

You can initialize the low-rank matrices with different use-cases in mind - task awareness (CorDA, EVA, Astra), faster convergence (PiSSA), mitigating quantizations (LoftQ) - just to name a few use-cases. Read about the different initializations below. The default initialization is for LoRA to be a no-op, to gradually learn new behavior without interfering much with the existing model.

Usage

The size of the low-rank update matrices is determined by the rank or r. A higher rank means the model has more parameters to train, but it also means the model has more learning capacity. In the following example, you'll target the query and value matrices of the attention blocks. Other important parameters to set are lora_alpha (scaling factor), bias (whether none, all or only the LoRA bias parameters should be trained), and modules_to_save (the modules apart from the LoRA layers to be trained and saved). All of these parameters - and more - are found in the LoraConfig.

from peft import LoraConfig, get_peft_model

config = LoraConfig(
    r=16,
    lora_alpha=16,
    target_modules=["query", "value"],
    lora_dropout=0.1,
    bias="none",
    modules_to_save=["classifier"],
)
model = get_peft_model(model, config)
model.print_healthcheck()

Benchmark overview

Initialization

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

For transformers.Conv1D layers, such as GPT-2's projections, use fan_in_fan_out=True because their weights are stored as (in_features, out_features) rather than the nn.Linear layout. Supported weight-based initializers use the Linear layout for decomposition and restore the stored layout when updating the base weights. LoRA-GA's "stable" scaling also uses the output dimension regardless of the storage layout.

It is also possible to pass init_lora_weights="gaussian". As the name suggests, this initializes weight A with a Gaussian distribution and zeros for weight B (this is how Diffusers initializes LoRA weights).

from peft import LoraConfig

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

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

from peft import LoraConfig

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

NoRA

Normalized Low-Rank Adaptation (NoRA) normalizes the LoRA down-projection matrices. PEFT applies this normalization only at initialization through init_lora_weights="nora" in LoraConfig: it normalizes the columns of the randomly initialized LoRA A weight and initializes the LoRA B weight to zero. Both matrices remain trainable, and the base weights are left unchanged.

For a linear layer, the adapter weight update is ΔW=sBA\Delta W = sBA, where AA has shape (r, in_features), BB has shape (out_features, r), and ss is the LoRA scaling factor. NoRA starts from the random A weight created by the LoRA linear layer and normalizes each column across the rank dimension:

A:,j←A:,jmax⁡(∥A:,j∥2,10−6),B←0. A_{:,j} \leftarrow \frac{A_{:,j}}{\max(\lVert A_{:,j} \rVert_2, 10^{-6})}, \qquad B \leftarrow 0.

Since B is zero, the adapter weight update is zero before training. With bias="none" and lora_bias=False, the adapter initially preserves the base model output. NoRA does not require a calibration dataset or a weight decomposition.

Important For NoRA, the recommended setting is lora_alpha equal to r (a 1:1 alpha/rank ratio), for example, r=8, lora_alpha=8. With the default use_rslora=False, this keeps a scaling factor of 1; enabling rank-stabilized LoRA changes it to lora_alpha / sqrt(r).

The following example applies NoRA to two linear layers in a small PyTorch model:

from torch import nn

from peft import LoraConfig, get_peft_model

model = nn.Sequential(
    nn.Linear(32, 32),
    nn.ReLU(),
    nn.Linear(32, 16),
)

config = LoraConfig(
    r=8,
    lora_alpha=8,
    target_modules=["0", "2"],
    init_lora_weights="nora",
    bias="none",
    lora_bias=False,
    use_rslora=False,
)
model = get_peft_model(model, config)
model.print_healthcheck()

For a Transformers model, set target_modules to the names of the linear layers you want to adapt, such as ["q_proj", "v_proj"] when those names are present in the model.

NoRA uses the existing LoRA configuration, training, saving, and loading APIs, so there is no separate NoraConfig or NoraModel class. For the shared configuration and model APIs, see LoraConfig and LoraModel.

NoRA supports torch.nn.Linear target modules or nn.Parameters passed directly with target_parameters. It is not supported for embeddings, conv layers, etc.

PiSSA

PiSSA initializes the LoRA adapter using the principal singular values and singular vectors. This straightforward modification allows PiSSA to converge more rapidly than LoRA and ultimately attain superior performance. Moreover, PiSSA reduces the quantization error compared to QLoRA, leading to further enhancements.

Configure the initialization method to "pissa", which may take several minutes to execute SVD on the pre-trained model:

from peft import LoraConfig
config = LoraConfig(init_lora_weights="pissa", ...)

Alternatively, execute fast SVD, which takes only a few seconds. The number of iterations determines the trade-off between the error and computation time:

lora_config = LoraConfig(init_lora_weights="pissa_niter_[number of iters]", ...)

For detailed instruction on using PiSSA, please follow these instructions.

MiCA

MiCA (Minor Component Adaptation) is a complement to PiSSA: instead of initializing from the principal singular components, MiCA uses the minor ones. Concretely, with W = U Σ V^T, MiCA sets B = U[:, -r:] (the r left singular vectors associated with the smallest singular values) and A = 0. During training, only A is updated; B is frozen. The intuition is that the minor singular directions are largely unused by the pretrained task and therefore offer a more "plastic" subspace for injecting new knowledge while preserving pretrained capabilities.

Because A == 0 at init, the adapter contribution B · A == 0 and the model output is preserved exactly at step 0 — no residual subtraction on the base weight is needed (unlike PiSSA). Since only A is trainable, the trainable parameter count for matching r is roughly half that of LoRA.

from peft import LoraConfig
config = LoraConfig(init_lora_weights="mica", r=16, target_modules=["q_proj", "v_proj"], ...)

MiCA currently supports nn.Linear and nn.Embedding target modules. The chosen rank must satisfy r <= min(in_features, out_features) for linear layers and r <= min(num_embeddings, embedding_dim) for embedding layers. For detailed usage, see these instructions.

MiCA is primarily intended for continued pretraining / domain-adaptive pretraining. In that setting, use the base model, not an instruction- or chat-tuned checkpoint, for the SVD initialization and MiCA training. After training, merge the adapter into the base model weights and use the resulting adapted base model as the starting point for subsequent instruction/chat tuning.

CorDA

CorDA builds task-aware LoRA adapters from weight decomposition oriented by the context of downstream task to learn (instruction-previewed mode, IPM) or world knowledge to maintain (knowledge-preserved mode, KPM). The KPM not only achieves better performance than LoRA on fine-tuning tasks, but also mitigates the catastrophic forgetting of pre-trained world knowledge. When preserving pre-trained knowledge is not a concern, the IPM is favored because it can further accelerate convergence and enhance the fine-tuning performance.

You need to configure the initialization method to "corda", and specify the mode of IPM or KPM and the dataset to collect covariance matrices.

@torch.no_grad()
def run_model():
    # Assume `model` and `dataset` is in context...
    model.eval()
    for batch in dataset:
        model(**batch)

corda_config = CordaConfig(
    corda_method="kpm",
)
lora_config = LoraConfig(
    init_lora_weights="corda",
    corda_config=corda_config,
)
preprocess_corda(model, lora_config, run_model=run_model)
peft_model = get_peft_model(model, lora_config)

For detailed instruction on using CorDA, please follow these instructions.

Astra

Astra builds task-aware LoRA adapters from the tail eigenvectors of the covariance matrix of the module output activations, estimated from a small calibration dataset of the downstream task. The pretrained weight is projected onto the subspace spanned by the tail eigenvectors to initialize the adapter, which constrains the update to the activation subspace that is most relevant for the downstream task and speeds up convergence.

You need to configure the initialization method to "astra", explicitly set target_modules, and provide the calibration dataset to collect covariance matrices.

@torch.no_grad()
def run_model():
    # Assume `model` and `dataset` is in context...
    model.eval()
    for batch in dataset:
        model(**batch)

from peft.tuners.lora import AstraConfig, preprocess_astra

astra_config = AstraConfig()
lora_config = LoraConfig(
    init_lora_weights="astra",
    target_modules=["q_proj", "v_proj"],
    astra_config=astra_config,
)
preprocess_astra(model, lora_config, run_model=run_model)
peft_model = get_peft_model(model, lora_config)

For detailed instruction on using Astra, please follow these instructions.

OLoRA

OLoRA utilizes QR decomposition to initialize the LoRA adapters. OLoRA translates the base weights of the model by a factor of their QR decompositions, i.e., it mutates the weights before performing any training on them. This approach significantly improves stability, accelerates convergence speed, and ultimately achieves superior performance.

You just need to pass a single additional option to use OLoRA:

from peft import LoraConfig
config = LoraConfig(init_lora_weights="olora", ...)

For more advanced usage, please refer to our documentation.

EVA

EVA performs SVD on the input activations of each layer and uses the right-singular vectors to initialize LoRA weights. It is therefore a data-driven initialization scheme. Furthermore EVA adaptively allocates ranks across layers based on their "explained variance ratio" - a metric derived from the SVD analysis.

You can use EVA by setting init_lora_weights="eva" and defining EvaConfig in LoraConfig:

from peft import LoraConfig, EvaConfig
peft_config = LoraConfig(
    init_lora_weights = "eva",
    eva_config = EvaConfig(rho = 2.0),
    ...
)

The parameter rho (≥ 1.0) determines how much redistribution is allowed. When rho=1.0 and r=16, LoRA adapters are limited to exactly 16 ranks, preventing any redistribution from occurring. A recommended value for EVA with redistribution is 2.0, meaning the maximum rank allowed for a layer is 2r.

It is recommended to perform EVA initialization on an accelerator(e.g. CUDA GPU, Intel XPU) as it is much faster. To optimize the amount of available memory for EVA, you can use the low_cpu_mem_usage flag in get_peft_model:

peft_model = get_peft_model(model, peft_config, low_cpu_mem_usage=True)

Then, call initialize_lora_eva_weights to initialize the EVA weights (in most cases the dataloader used for eva initialization can be the same as the one used for finetuning):

initialize_lora_eva_weights(peft_model, dataloader)

EVA works out of the box with bitsandbytes. Simply initialize the model with quantization_config and call initialize_lora_eva_weights as usual.

Tip For further instructions on using EVA, please refer to our documentation.

LoftQ

When quantizing the base model for QLoRA training, consider using the LoftQ initialization, which has been shown to improve performance when training quantized models. The idea is that the LoRA weights are initialized such that the quantization error is minimized. To use LoftQ, follow these instructions.

Tip Learn more about how PEFT works with quantization and how to use LoftQ in the Quantization guide.

rsLoRA

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

from peft import LoraConfig

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

LoRA-GA

LoRA-GA (Low-Rank Adaptation with Gradient Approximation) initializes the adapter weights by performing SVD on estimated gradients, so that the weights are aligning closer to full-finetuning for faster convergence.

This method requires an initialization function to estimate the gradients before beginning the actual training:

from peft.tuners.lora import preprocess_loraga

def train_step():
    """Run forward and backward passes for gradient estimation."""
    dataloader_iter = iter(grad_dataloader)
    for _ in range(N):
        batch = next(dataloader_iter)
        batch = {k: v.to(device) for k, v in batch.items()}
        outputs = model(**batch)
        loss = outputs.loss
        loss.backward()

preprocess_loraga(model, lora_config, train_step)

Usage Tips

  • 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).

  • 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.

  • 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 pass path_initial_model_for_weight_conversion.

  • 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.

  • Compatibility: LoRA-GA requires full-precision weights and does not support quantized models. Can be combined with other LoRA variants like DoRA.

Training

This section shows how to handle more complex training scenarios instead of only applying a low-rank adapter to the model and feed data.

QLoRA-style training

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

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

For more information about how to apply quantization to PEFT adapters, refer to the quantization guide.

Memory efficient Layer Replication with LoRA

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

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

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

Fewshot-Metamath-OrcaVicuna-Mistral-10B is an example of a model trained using this method on Mistral-7B expanded to 10B. The adapter_config.json shows a sample LoRA adapter config applying this method for fine-tuning.

Fine grained control over ranks and alpha (scaling)

By default, all layers targeted with LoRA will have the same rank r and the same lora_alpha (which determines the LoRA scaling), depending on what was specified in the LoraConfig. In some cases, however, you may want to indicate different values for different layers. This is possible by passing the rank_pattern and alpha_pattern arguments to LoraConfig. These arguments should be dictionaries with the key being the layer name and the value being the rank/alpha value. The keys can be regular expressions (regex). All LoRA layers that are not explicitly mentioned in rank_pattern and alpha_pattern will take the default r and lora_alpha values.

To give an example, let's assume that we have a model with the following structure:

>>> print(model)
Outer(
  (foo): Linear(...)
  (module): Middle(
    (foo): Linear(...)
    (foobar): Linear(...)
    (module): Inner(
      (foo): Linear(...)
      (barfoo): Linear(...)
    )
  )
)
  • rank_pattern={"foo": 42} will match all 3 foo layers. Neither foobar nor barfoo are matched.
  • rank_pattern={"^foo": 42} will only match the foo layer of the model, but neither module.foo nor module.module.foo. This is because the ^ means "start of string" when using regular expressions, and only foo starts with "foo", the other layer names have prefixes.
  • rank_pattern={"^module.foo": 42} matches only module.foo, but not module.module.foo, for the same reason.
  • rank_pattern={"module.foo": 42} matches both module.foo and module.module.foo, but not foo.
  • rank_pattern={"^foo": 42, "^module.module.foo": 55} matches foo and module.module.foo, respectively, but not module.foo.
  • There is no need to indicate $ to mark the end of the match, as this is added automatically by PEFT.

The same logic applies to alpha_pattern. If you're in doubt, don't try to get fancy with regular expressions -- just pass the full name for each module with a different rank/alpha, preceded by the ^ prefix, and you should be good.

Automatically detect viable target modules

peft.helpers.KappaTuneSelector implements the condition-number-based target selection strategy from the KappaTune paper. It scans every nn.Linear module and, for models where MoE expert weights are stored as fused 3D nn.Parameter tensors (e.g. Llama-4, Qwen3-MoE), also those parameters, computes the matrix condition number κ = σ_max / σ_min for each, and selects the most isotropic layers (lowest κ). These isotropic layers serve as ideal candidates for fine-tuning, since their high-entropy nature allows them to absorb new information more readily, leaving the specialized, anisotropic layers intact to mitigate catastrophic forgetting during continual learning.

Use peft.helpers.find_kappa_target_modules as a one-liner to get the optimal target_modules for LoraConfig:

from peft import LoraConfig, get_peft_model
from peft.helpers import find_kappa_target_modules

model = AutoModelForCausalLM.from_pretrained("mistralai/Mixtral-8x7B-Instruct-v0.1")

targets = find_kappa_target_modules(model, top_p=0.2)
config = LoraConfig(
    target_modules=targets["target_modules"],
    target_parameters=targets["target_parameters"] if stable_modules_dic["target_parameters"] else None,
    r=64,
    lora_alpha=32,
    task_type="CAUSAL_LM",
)
peft_model = get_peft_model(model, config)

See a complete example here.

Targeting nn.Parameter directly

Generally, you should use target_modules to target the module (e.g. nn.Linear). However, in some circumstances, this is not possible. E.g., in many mixture of expert (MoE) layers in HF Transformers, instead of using nn.Linear, an nn.Parameter is used. PEFT normally overwrites the forward method for LoRA, but for nn.Parameter, there is none. Therefore, to apply LoRA to that parameter, it needs to be targeted with target_parameters. As an example, for Llama4, you can pass: target_parameters=['feed_forward.experts.gate_up_proj', 'feed_forward.experts.down_proj].

Note that when targeting expert parameters, PEFT can add a substantial runtime overhead. The reason is that PEFT always materializes the LoRA contribution for each expert even if only a small amount of experts is required. During training, this is less relevant since, over the course of the sequence, typically a large fraction of experts is activated at least once. However, during inference, normally a KV cache is used and we thus need to only compute the last token, which means that only a small amount of experts is activated. Therefore, using LoRA on MoE layers can result in a substantial slowdown at inference time. The recommendation is thus to merge the weights (model.merge_adapter() or model = model.merge_and_unload()). This removes the PEFT overhead.

A more detailed investigation of this issue can be found on this pull request on MoE optimization.

Caveats

  • At the moment, this argument allows to target 2-dim or 3-dim nn.Parameters. It is assumed that in the case of a 3-dim parameter, the 0th dimension is the expert dimension.
  • Multiple LoRA adapters (added via model.add_adapter or model.load_adapter) that use target_parameters are supported, but all of them must target the same set of parameters.

MoE expert parameters and vLLM

Some MoE models in Transformers store expert weights as nn.Parameter tensors (often 3D), not nn.Linear modules. To apply LoRA to those experts, use target_parameters and set a per-layer rank with rank_pattern:

num_experts = getattr(model.config, "num_local_experts", None) or model.config.num_experts
effective_r = max(1, r // num_experts)
config = LoraConfig(
    r=r,
    lora_alpha=32,
    target_modules=["q_proj", "v_proj"],
    target_parameters=[
        # Mixtral / Qwen3-MoE / GPT-OSS
        "mlp.experts.gate_up_proj",
        "mlp.experts.down_proj",
        # Llama4
        # "feed_forward.experts.gate_up_proj",
        # "feed_forward.experts.down_proj",
    ],
    rank_pattern={
        "experts.gate_up_proj": effective_r,
        "experts.down_proj": effective_r,
    },
)

This keeps the total LoRA parameter budget similar to dense layers (see LoRA Without Regret by Schulman et. al.). Non-expert modules use the default rank r.

Accelerated inference with the fine-tuned model is possible with, for example, vLLM which supports fused MoE expert layers since v0.11.2.

Efficiently train tokens alongside LoRA

PEFT LoRA adapters support adding new tokens with the trainable_token_indices parameter. This allows tuning of other tokens alongside fine-tuning specific layers. Only the specified tokens are trained and all other tokens are untouched. It saves memory and doesn't throw away learned context from existing token embeddings unlike training the whole embedding matrix. Under the hood this method uses the layer of TrainableTokensModel.

# for layer 'embed_tokens'
config = LoraConfig(trainable_token_indices=[idx_1, idx_2, ...], ...)

# specific embedding layer
config = LoraConfig(trainable_token_indices={'emb_tokens': [idx_1, idx_2, ...]}, ...)

In the snippet below we show how to add new tokens to the model and how to train it alongside the other layers in the model.

from transformers import AutoTokenizer, AutoModelForCausalLM
from peft import get_peft_model, LoraConfig

base_model = AutoModelForCausalLM.from_pretrained("mistralai/Mistral-7B-v0.1")
tokenizer = AutoTokenizer.from_pretrained("mistralai/Mistral-7B-v0.1")

# we define our new tokens and add them to the tokenizer as special tokens
special_tokens = ['<|start_think|>', '<|stop_think|>']
tokenizer.add_special_tokens({'additional_special_tokens': special_tokens})

# make room for new tokens in the embedding matrix if it isn't big enough already
base_model.resize_token_embeddings(max(len(tokenizer), base_model.model.embed_tokens.num_embeddings))

# typical LoRA config with `trainable_token_indices` targeting embedding layer `embed_tokens`
# and specifically our new tokens we just added
lora_config = LoraConfig(
    target_modules='all-linear',
    trainable_token_indices={'embed_tokens': tokenizer.convert_tokens_to_ids(special_tokens)},
)
peft_model = get_peft_model(base_model, lora_config)

# proceed to train the model like normal
[...]

The token weights are saved as a part of the adapter state dict alongside the LoRA weights. Full fine-tuning and saving the embedding matrix would have stored a much bigger file.

To give a bit of an indication how much VRAM can be saved, a rudimentary comparison of the above example was made between training the embedding matrix fully (modules_to_save=["embed_tokens"]), using a LoRA for the embedding matrix (target_modules=[..., "embed_tokens"], rank 32) and trainable tokens (trainable_token_indices=[...], 6 tokens):

Trainable Tokens LoRA Full Fine-tuning
VRAM 15,562 MB 15,581MB ~16,500MB
Influence 6 tokens all tokens all tokens

Weight tying

Many causal LMs use weight tying, where two or more weights share the same underlying parameters. In the most common case, the input embedding weights (embed_tokens) and output projection weights (lm_head) share the same tensor. This is because it reduces parameters and usually preserves model quality.

It's not always obvious how PEFT deals with these tied weights when they are targeted for fine-tuning. For LoRA, the ensure_weight_tying on the LoraConfig controls whether PEFT should explicitly keep adapter-side updates tied for those layers. In practice, this can affect modules_to_save, target_modules, and trainable_token_indices. Note that this logic partially relies on convention when it comes to naming the layers ("embed_tokens", "lm_head") and proper working cannot be guaranteed if those conventions are not used.

The tables below summarize expected behavior.

modules_to_save

Base model weights tied ensure_weight_tying LoraConfig shape Behavior
No False modules_to_save=["embed_tokens"] or ["lm_head"] Add ModulesToSaveWrapper on selected layer only
No True modules_to_save=["embed_tokens"] or ["lm_head"] Warn, then add ModulesToSaveWrapper on selected layer only
Yes False modules_to_save=["embed_tokens"] or ["lm_head"] Treat as separate
Yes True modules_to_save=["embed_tokens"] or ["lm_head"] Wrap tied layers and keep wrappers tied
No False modules_to_save=["embed_tokens", "lm_head"] Treat as separate
No True modules_to_save=["embed_tokens", "lm_head"] Warn, then treat as separate
Yes False modules_to_save=["embed_tokens", "lm_head"] Warn, then treat as separate
Yes True modules_to_save=["embed_tokens", "lm_head"] Keep ModulesToSaveWrappers tied

target_modules

Base model weights tied ensure_weight_tying LoraConfig shape Behavior
No False target_modules=["embed_tokens"] or ["lm_head"] Add LoRA on selected layer only
No True target_modules=["embed_tokens"] or ["lm_head"] Warn, then add LoRA on selected layer only
Yes False target_modules=["embed_tokens"] or ["lm_head"] Treat as separate
Yes True target_modules=["embed_tokens"] or ["lm_head"] Keep LoRA adapters tied
No False target_modules=["embed_tokens", "lm_head"] Treat as separate
No True target_modules=["embed_tokens", "lm_head"] Warn, then treat as separate
Yes False target_modules=["embed_tokens", "lm_head"] Warn, then treat as separate
Yes True target_modules=["embed_tokens", "lm_head"] Keep LoRA adapters tied

trainable_token_indices

For trainable tokens, we have the additional complication that even if the LM head and embeddings are tied, as a user I may want to fine-tune different tokens on them. In the example table below, we thus differentiate between fine-tuning the same and fine-tuning different tokens.

Tabla (13 filas)
Base model weights tied ensure_weight_tying LoraConfig shape Behavior
No False trainable_token_indices=[1, 2, 3] Trainable tokens on embeddings only
No True trainable_token_indices=[1, 2, 3] Warn, then trainable tokens on embeddings only
Yes False trainable_token_indices=[1, 2, 3] Tied trainable tokens
Yes True trainable_token_indices=[1, 2, 3] Tied trainable tokens
No False trainable_token_indices={"lm_head": [1, 2], "embed_tokens": [1, 2]} Treat as separate
No True trainable_token_indices={"lm_head": [1, 2], "embed_tokens": [1, 2]} Warn, then treat as separate
Yes False trainable_token_indices={"lm_head": [1, 2], "embed_tokens": [1, 2]} Tied trainable tokens
Yes True trainable_token_indices={"lm_head": [1, 2], "embed_tokens": [1, 2]} Tied trainable tokens
No False trainable_token_indices={"lm_head": [1, 2], "embed_tokens": [3, 4]} Treat as separate
No True trainable_token_indices={"lm_head": [1, 2], "embed_tokens": [3, 4]} Warn, then treat as separate
Yes False trainable_token_indices={"lm_head": [1, 2], "embed_tokens": [3, 4]} Treat as separate
Yes True trainable_token_indices={"lm_head": [1, 2], "embed_tokens": [3, 4]} Error

For users, this means:

  • In general, if you want to fine-tune weights that are tied and want to keep them tied, pass ensure_weight_tying=True.
  • If your base model's weights are untied, ensure_weight_tying=True cannot force tying and only warns.
  • For trainable_token_indices, tied layers must use the same token indices when ensure_weight_tying=True.

Optimizers

LoRA training can optionally include special purpose optimizers. Currently PEFT supports LoRA-FA, LoRA+, and Riemannian-preconditioned LoRA.

LoRA-FA Optimizer

LoRA training can be more effective and efficient using LoRA-FA, as described in LoRA-FA. LoRA-FA reduces activation memory consumption by fixing the matrix A and only tuning the matrix B. During training, the gradient of B is optimized to approximate the full parameter fine-tuning gradient. Moreover, the memory consumption of LoRA-FA is not sensitive to the rank (since it erases the activation of AA), therefore it can improve performance by enlarging lora rank without increasing memory consumption.

from peft import LoraConfig, get_peft_model
from peft.optimizers import create_lorafa_optimizer
from transformers import Trainer, get_cosine_schedule_with_warmup

base_model = AutoModelForCausalLM.from_pretrained("meta-llama/Meta-Llama-3-8B-Instruct")

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

optimizer = create_lorafa_optimizer(
    model=model,
    r=128,
    lora_alpha=32,
    lr=7e-5,
)

scheduler = get_cosine_schedule_with_warmup(
    optimizer,
    num_warmup_steps=100,
    num_training_steps=1000,
)

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

LoRA+ optimized LoRA

LoRA training can be optimized using LoRA+, which uses different learning rates for the adapter matrices A and B, shown to increase finetuning speed by up to 2x and performance by 1-2%.

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

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

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

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

Riemannian-preconditioned LoRA

LoRA training can be improved with a Riemannian preconditioner, as described in Riemannian Preconditioned LoRA. On every optimizer step, the gradients of the LoRA matrices AA and BB are multiplied by an r×rr \times r preconditioner that rescales the Euclidean gradient toward the Riemannian (scaled-gradient) direction on the low-rank matrix manifold, which better conditions the update and can improve convergence. Because the preconditioner is r×rr \times r, its memory and runtime overhead are small in the LoRA rank. create_riemannian_optimizer wraps any base optimizer class (e.g. torch.optim.AdamW or torch.optim.SGD): non-LoRA parameters are updated by the base optimizer unchanged, and only nn.Linear-shaped LoRA layers (lora_A / lora_B) are preconditioned.

from peft import LoraConfig, get_peft_model
from peft.optimizers import create_riemannian_optimizer
from transformers import Trainer, get_cosine_schedule_with_warmup
import torch

base_model = AutoModelForCausalLM.from_pretrained("meta-llama/Meta-Llama-3-8B-Instruct")

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

optimizer = create_riemannian_optimizer(
    model=model,
    optimizer_cls=torch.optim.AdamW,
    lr=5e-5,
    reg=1e-2,
)

scheduler = get_cosine_schedule_with_warmup(
    optimizer,
    num_warmup_steps=100,
    num_training_steps=1000,
)

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

reg is a damping term added to the r×rr \times r matrix diagonal before inversion; it stabilizes the preconditioner when a LoRA factor is (near) rank-deficient.

Post-Training

This section shows potential post-processing methods for trained adapters.

Merge LoRA weights into the base model

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

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

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

from transformers import AutoModelForCausalLM
from peft import PeftModel

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

It is important to assign the returned model to a variable and use it, LoraModel.merge_and_unload is not an in-place operation. If you need to keep a copy of the weights so you can unmerge the adapter later or delete and load different ones, you should use the LoraModel.merge_adapter function instead. Now you have the option to use LoraModel.unmerge_adapter to return the base model.

from transformers import AutoModelForCausalLM
from peft import PeftModel

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

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

Tip On a quantized model, unmerging is not exact: merging re-quantizes the base weight, and repeated merge and unmerge cycles can accumulate rounding error. See Merging adapters into quantized weights.

Warning If several adapters are active and only some of them are merged, the adapters that are not merged are silently not applied. This behavior will change in PEFT v1.0. See Merging only some of the active adapters.

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

First load the base model:

from transformers import AutoModelForCausalLM
from peft import PeftModel
import torch

base_model = AutoModelForCausalLM.from_pretrained(
    "mistralai/Mistral-7B-v0.1", dtype=torch.float16, device_map="auto"
)

Then we load the first adapter:

peft_model_id = "alignment-handbook/zephyr-7b-sft-lora"
model = PeftModel.from_pretrained(base_model, peft_model_id, adapter_name="sft")

Then load a different adapter and merge it with the first one:

weighted_adapter_name = "sft-dpo"
model.load_adapter("alignment-handbook/zephyr-7b-dpo-lora", adapter_name="dpo")
model.add_weighted_adapter(
    adapters=["sft", "dpo"],
    weights=[0.7, 0.3],
    adapter_name=weighted_adapter_name,
    combination_type="linear"
)
model.set_adapter(weighted_adapter_name)

Tip There are several supported methods for combination_type. Refer to the documentation for more details. Note that "svd" as the combination_type is not supported when using torch.float16 or torch.bfloat16 as the datatype.

Now, perform inference:

device = torch.accelerator.current_accelerator().type if hasattr(torch, "accelerator") else "cuda"

tokenizer = AutoTokenizer.from_pretrained("mistralai/Mistral-7B-v0.1")

prompt = "Hey, are you conscious? Can you talk to me?"
inputs = tokenizer(prompt, return_tensors="pt")
inputs = {k: v.to(device) for k, v in inputs.items()}

with torch.no_grad():
    generate_ids = model.generate(**inputs, max_length=30)
outputs = tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
print(outputs)

Recovering base model performance via intruder dimension reduction

The paper LoRA vs Full Fine-tuning: An Illusion of Equivalence argues that LoRA training introduces extra dimensions into the weights that have very little in common with the already learnt weights and lead to forgetting of already learned information. PEFT implements the suggested mitigation in peft.tuners.lora.intruders.reduce_intruder_dimension.

The mitigation will take a PEFT model with a loaded LoRA and create a new, modified adapter that is loaded alongside the existing adapter and now the active adapter.

Example usage:

from peft.tuners.lora.intruders import reduce_intruder_dimension

peft_model = AutoPeftModelForCausalLM.from_pretrained('hubnemo/llama-3.2b-metamathqa-lora64')

reduce_intruder_dimension(
    peft_model,
    mitigation_lambda=0.75,
)

peft_model.generate(...)

There are a few hyper-parameters that can be used for tuning the effectiveness of the mitigation but, as evidenced in Figure 8 of the paper, it will always be a trade-off between task accuracy learned by the adapter and forgetting of the base model's knowledge. The mitigation will remove information from the adapter to reduce the impact on forgetting previous knowledge but this also means that some information about the task learned by the adapter is lost as well.

While the defaults are set to deliver a good trade-off between the two factors it is not guaranteed that the defaults will hold for your adapter, your model and your data, therefore it is wise to have a benchmark ready to measure the effect.

Load adapters

Adapters can be loaded onto a pretrained model with PeftModel.load_adapter, which is useful for trying out different adapters whose weights aren't merged. Set the active adapter weights with the LoraModel.set_adapter function.

from transformers import AutoModelForCausalLM
from peft import PeftModel

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

# load different adapter
model.load_adapter("alignment-handbook/zephyr-7b-dpo-lora", adapter_name="dpo")

# set adapter as active
model.set_adapter("dpo")

To return the base model, you could use LoraModel.unload to unload all of the LoRA modules or LoraModel.delete_adapter to delete the adapter entirely. LoraModel.unload is not an in-place operation, remember to assign the returned model to a variable and use it.

# unload adapter
model = model.unload()

# delete adapter
model.delete_adapter("dpo")