AI Hints
Home›Fine-Tuning LLMs Tutorial›LoRA with PEFT
Fine-Tuning LLMs · Lesson 43 of 120

Which Layers?

Target_modules.

⏱ 2 min read▶ Video at 1:09:24🎓 Free
Watch this lesson in the Fine-Tuning LLMs courseWatch on YouTube ↗Full Fine-Tuning LLMs course

LoRA attaches to linear layers. But a model has many kinds of linear layers. Which ones should get an adapter? That's what the target modules setting decides.

  • LoRA attaches to linear layers
  • There are many kinds
  • target_modules decides

The linear layers in our model

Let's find every linear layer, and add up its weights, grouped by name. Named modules walks through every part of the model. We keep only the linear ones. Then we print the totals, biggest first. Run it. The LM head is the biggest. It turns meaning into a score for every token. Then the three MLP grids. Then the four attention grids, q, o, k, and v.

app.pypython
from collections import Counter
from torch import nn
from transformers import AutoModelForCausalLM

model = AutoModelForCausalLM.from_pretrained("HuggingFaceTB/SmolLM2-135M-Instruct")
sizes = Counter()
for name, module in model.named_modules():
    if isinstance(module, nn.Linear):
        sizes[name.split(".")[-1]] += module.weight.numel()
for name, count in sizes.most_common():
    print(f"{name:10} {count:>12,} weights")
Output
lm_head      28,311,552 weights
gate_proj    26,542,080 weights
up_proj      26,542,080 weights
down_proj    26,542,080 weights
q_proj        9,953,280 weights
o_proj        9,953,280 weights
k_proj        3,317,760 weights
v_proj        3,317,760 weights

Common choices

There are two common choices. The original LoRA paper used only the attention grids, q proj and v proj. It's the cheapest option. Today, most people use all linear, which puts LoRA on every linear layer, except the LM head. It costs a little more, but usually learns better.

target_modulesTrainsNotes
["q_proj", "v_proj"]attention onlycheapest, the original paper
"all-linear"attention + MLPusually better, the common default
lm_head—normally left out

Summary

Let's recap. LoRA attaches to linear layers, chosen with target modules. q proj and v proj is the cheapest choice. And all linear usually learns best. Next, writing the LoRA settings in code.

Key takeaways
  • target_modules
  • q_proj + v_proj: cheap
  • all-linear: usually best
Next up: LoraConfig — the settings object