Sub topic 5
Rank, alpha, dropout and target modules
What this chapter assumes
You should know how a LoRA layer computes its output, as covered in the previous chapter. The frozen weight is W. The adapter adds two small matrices, A with shape (r, infeatures) and B with shape (outfeatures, r). The layer output is Wx + (alpha/r)·BAx. You should also be comfortable with PyTorch modules and with the names of the linear layers inside a transformer block.
This chapter covers the four settings that decide how large an adapter is, where it sits, and how strongly it changes the model. They are rank (r), alpha (lora_alpha), dropout (lora_dropout) and target modules (target_modules). The next chapter attaches an adapter with PEFT using these settings.
The four knobs at a glance
| Setting | PEFT name | What it controls | Typical starting value |
|---|---|---|---|
| Rank | `r` | Capacity: the inner width of A and B | 8 to 16 |
| Alpha | `lora_alpha` | Strength of the update, through the factor alpha/r | 2 × r, or equal to r |
| Dropout | `lora_dropout` | Regularization applied to the adapter input | 0.0 to 0.1 |
| Target modules | `target_modules` | Which linear layers get an adapter | Attention projections, or all linear layers |
Rank
The rank r is the number of columns in B and the number of rows in A. The product BA has shape (outfeatures, infeatures), the same as W, but its rank is at most r. A small r limits how much the update can express.
Rank sets the number of trainable parameters directly. One adapted layer adds r × (infeatures + outfeatures) parameters. For a 64 by 64 layer with r = 4, that is 4 × 128 = 512 parameters, against 4,096 in the base weight. For a 4096 by 4096 projection with r = 16, it is 16 × 8192 = 131,072 parameters, against about 16.8 million in the base weight, under 1%.
Parameters grow linearly with r. Doubling the rank doubles the adapter size, the optimizer state for it, and the adapter file on disk. Memory for the frozen base model does not change.
Choosing a rank:
- Tasks that change style, format or tone usually work well at r = 8 or 16.
- Tasks that teach new knowledge or complex behavior may need r = 32 to 128, but more rank does not guarantee better results.
- Past some point, extra rank gives no measurable gain on your evaluation set. Find that point by training at two or three ranks and comparing, which the evaluation chapter covers.
- A higher rank on a small dataset raises the risk of overfitting, because the adapter has more capacity to memorize.
Alpha and the scaling factor
Alpha does not add parameters. It sets the scaling factor alpha / r that multiplies the adapter output. In the chapter's example class, this is self.scale = alpha / r.
The scale matters because it changes the effective learning rate of the adapter. A larger scale makes each gradient step move the output more. Dividing by r keeps the update size roughly steady when you change the rank, so you can adjust r without retuning everything else. This is only approximate. Optimizers such as Adam and different initializations still interact with the scale.
Common conventions:
lora_alpha = 2 * ris a widely used default, giving a scale of 2.lora_alpha = rgives a scale of 1.- Keep alpha fixed and vary
ronly if you understand that the scale will then change.
Alpha and the learning rate are linked. Doubling alpha at a fixed r has an effect similar to raising the learning rate for the adapter. When training is unstable, lowering either one is a reasonable first step. Avoid changing both at once, because you will not know which change helped.
Rank-stabilized scaling
PEFT offers use_rslora=True. It replaces alpha/r with alpha/√r. At high ranks, plain alpha/r shrinks the update so much that larger ranks learn slowly. The square-root version avoids that. If you plan to use ranks of 64 or more, try it.
Dropout
lora_dropout applies dropout to the input of the adapter branch only. The frozen base path is not affected. The adapter computes its output from a randomly masked copy of x during training, and dropout is switched off at evaluation time.
Dropout is a regularizer. It helps when the dataset is small and the adapter begins to memorize examples. Typical values are 0.05 and 0.1.
Trade-offs to know:
- With large datasets and few epochs, dropout of 0.0 is common and often just as good.
- Dropout adds noise, so training loss falls more slowly. Compare validation loss, not training loss, when judging its effect.
- Some PEFT fast paths and kernels work only when dropout is 0, so check the documentation if you use an optimized backend.
Target modules
target_modules lists which layers receive adapters. PEFT matches names against the modules of the model. A name such as "q_proj" matches every module whose name ends with it, in every block.
A typical decoder block of a Llama or Qwen style model contains:
| Group | Module names | Role |
|---|---|---|
| Attention | `q_proj`, `k_proj`, `v_proj`, `o_proj` | Query, key, value and output projections |
| Feed-forward | `gate_proj`, `up_proj`, `down_proj` | The MLP, which holds most of the layer parameters |
The original LoRA paper adapted only the query and value projections. Later practice, including QLoRA, found that adapting all linear layers usually gives better quality at the same rank, at the cost of more adapter parameters.
Your options:
- A short list such as
["q_proj", "v_proj"]. This is the smallest adapter and works for light tasks. - All four attention projections, as in the PEFT example from this tutorial.
- Attention plus MLP names listed explicitly.
target_modules="all-linear", which targets every linear layer except the output head. The QLoRA example uses this.
Module names differ between architectures. GPT-2 uses c_attn, and other families use different names. Never copy a list from another model without checking. To see the real names, run this:
from transformers import AutoModelForCausalLM
model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen2.5-0.5B-Instruct")
names = {
name.split(".")[-1]
for name, module in model.named_modules()
if module.__class__.__name__ == "Linear"
}
print(sorted(names))The printout includes lm_head, the output layer. all-linear leaves it out on purpose.
A related setting is modules_to_save. It names layers that are trained fully and saved alongside the adapter. You need it when you add new tokens and must train the embedding layer, or when you train a classification head. These layers are not low-rank, so they cost real memory.
Counting the effect of your choices
The following script computes adapter size from the settings alone. It uses the dimensions of a model with hidden size 896 and an MLP width of 4864, similar to a small Qwen model, with simplified shapes. Treat the output as an estimate.
def lora_params(r, shapes):
"""shapes: list of (in_features, out_features) for each adapted layer."""
return sum(r * (i + o) for i, o in shapes)
hidden, mlp, layers = 896, 4864, 24
attention = [(hidden, hidden)] * 4
mlp_layers = [(hidden, mlp), (hidden, mlp), (mlp, hidden)]
for r in (8, 16, 64):
attn_only = layers * lora_params(r, attention)
everything = layers * lora_params(r, attention + mlp_layers)
print(f"r={r:>3} attention only: {attn_only:>10,} all linear: {everything:>10,}")Real Qwen models use grouped-query attention, so the key and value projections are narrower than shown. The real count is somewhat lower. The pattern holds: parameters scale linearly with r and grow by a large factor when MLP layers are included.
How the settings interact
A practical way to tune is to fix one setting at a time, in this order:
- Choose target modules. Start with all linear layers if memory allows.
- Choose
r= 16 and alpha = 32. - Tune the learning rate. Adapters usually tolerate higher rates than full fine-tuning, such as 1e-4 to 2e-4.
- Add dropout of 0.05 if validation loss rises while training loss keeps falling.
- Raise
ronly if the model underfits, meaning training loss stays high.
Common mistakes
- Wrong module names. PEFT raises an error saying the target modules were not found. Print the module names as shown above.
- Raising rank to fix overfitting. Higher rank adds capacity and usually worsens overfitting. Lower the rank, add dropout, or add data.
- Comparing runs with different alpha/r. A change from r = 8 to r = 64 at fixed alpha changes the scale from alpha/8 to alpha/64. Report both numbers.
- Treating adapter size as a quality measure. More parameters do not guarantee a better model.
Exercises
Exercise
A 2048 by 2048 linear layer is given a LoRA adapter with r = 8 and alpha = 16. How many trainable parameters does the adapter add, and what is the scaling factor?
Show answer
The adapter has A of shape (8, 2048) and B of shape (2048, 8), so 8 × 2048 + 2048 × 8 = 32,768 parameters. The scaling factor is alpha / r = 16 / 8 = 2.
Exercise
You change r from 16 to 64 and keep lora_alpha at 32. What happens to the scale, and why might the new run learn more slowly than you expect?
Show answer
The scale falls from 32/16 = 2 to 32/64 = 0.5, so the adapter output is multiplied by a smaller factor and each step changes the model less. You can raise alpha to keep the scale near 2, or try use_rslora=True, which scales by alpha divided by the square root of r.
Exercise
Training loss keeps falling but validation loss rises after the first epoch on a dataset of 500 examples. Name two changes to the LoRA settings that could help, and one change that would probably make it worse.
Show answer
Lowering r and adding or increasing lora_dropout (for example to 0.05 or 0.1) can reduce overfitting. Raising r would probably make it worse, because it gives the adapter more capacity to memorize the small dataset.