为什么需要 LoRA

全量微调 7B 模型需要 50+ GB 显存。LoRA 通过低秩分解将可训练参数减少 1000 倍。

核心原理

在预训练权重旁添加低秩矩阵 A 和 B:

W=W+αABW' = W + \alpha \cdot AB

其中 ARd×rA \in \mathbb{R}^{d \times r}BRr×kB \in \mathbb{R}^{r \times k}rdr \ll d

from peft import LoraConfig
config = LoraConfig(r=16, lora_alpha=32, target_modules=["q_proj", "v_proj"])

QLoRA

在 LoRA 基础上加了 4-bit 量化,可以在单张 RTX 3090 上微调 LLaMA-65B。GPT 系列中很多衍生模型就是靠 LoRA 微调出来的,见 GPT 系列模型演进史