Chapter 08
LoRA / QLoRA / 全参微调切换
📌 commit 964f70e三档配置对照
XTuner 切微调粒度 = 改 model.lora 和 model.llm.quantization_config 两段。本章把三档配置直接列出来。
8.1三档对照
| 档 | lora 字段 | quantization_config | 典型显存 |
| 全参 | None | None | ~80 GB (7B) |
| LoRA | LoraConfig | None | ~22 GB |
| QLoRA | LoraConfig | BitsAndBytesConfig (4bit) | ~14 GB |
8.2全参 model 段
model = dict(
type=SupervisedFinetune,
use_varlen_attn=True,
llm=dict(
type=AutoModelForCausalLM.from_pretrained,
pretrained_model_name_or_path=pretrained_model_name_or_path,
trust_remote_code=True,
torch_dtype=torch.bfloat16,
),
# 注意没 lora 字段
)
8.3LoRA model 段
model = dict(
type=SupervisedFinetune,
use_varlen_attn=True,
llm=dict(
type=AutoModelForCausalLM.from_pretrained,
pretrained_model_name_or_path=pretrained_model_name_or_path,
trust_remote_code=True,
torch_dtype=torch.bfloat16,
),
lora=dict(
type=LoraConfig,
r=64, lora_alpha=16,
lora_dropout=0.1, bias='none',
task_type='CAUSAL_LM',
target_modules=['wqkv', 'wo', 'w1', 'w2', 'w3'], # InternLM2 命名
),
)
8.4QLoRA model 段
model = dict(
type=SupervisedFinetune,
use_varlen_attn=True,
llm=dict(
type=AutoModelForCausalLM.from_pretrained,
pretrained_model_name_or_path=pretrained_model_name_or_path,
trust_remote_code=True,
torch_dtype=torch.float16, # ★ QLoRA 用 fp16 compute
quantization_config=dict(
type=BitsAndBytesConfig,
load_in_4bit=True,
llm_int8_threshold=6.0,
llm_int8_has_fp16_weight=False,
bnb_4bit_compute_dtype=torch.float16,
bnb_4bit_use_double_quant=True,
bnb_4bit_quant_type='nf4',
),
),
lora=dict(
type=LoraConfig,
r=64, lora_alpha=16,
lora_dropout=0.1, bias='none',
task_type='CAUSAL_LM',
),
)
8.5target_modules 各模型对照
| 模型族 | target_modules |
| InternLM2 | ['wqkv', 'wo', 'w1', 'w2', 'w3'] |
| Llama-2 / 3 | ['q_proj','k_proj','v_proj','o_proj','gate_proj','up_proj','down_proj'] |
| Qwen2 | 同 Llama |
| Mistral / Mixtral | 同 Llama |
| Baichuan2 | ['W_pack','o_proj','gate_proj','up_proj','down_proj'] |
| ChatGLM3 | ['query_key_value','dense','dense_h_to_4h','dense_4h_to_h'] |
8.6三档常见 lr
| 档 | lr | 说明 |
| 全参 | 1e-5 ~ 5e-5 | 小 lr |
| LoRA | 2e-4 ~ 5e-4 | 10× 全参 |
| QLoRA | 2e-4 | 同 LoRA |
8.7合并 LoRA
# 1) pth → HF adapter
xtuner convert pth_to_hf ./cfg.py ./work_dirs/.../epoch_3.pth ./hf_adapter
# 2) 合并到 base
xtuner convert merge \
/path/to/base/model \
./hf_adapter \
./merged
# QLoRA 自动 dequantize 后 merge
8.8这章你需要带走的
- 三档切换:删/加
lora 和 quantization_config;
- QLoRA 用 fp16 compute_dtype;
- target_modules 看模型族;
- lr:全参 1-5e-5,LoRA/QLoRA 2e-4 起步;
xtuner convert pth_to_hf + merge 三步出 HF 模型。