Chapter 08

LoRA / QLoRA / 全参微调切换

📌 commit 964f70e三档配置对照

XTuner 切微调粒度 = 改 model.loramodel.llm.quantization_config 两段。本章把三档配置直接列出来。

8.1三档对照

lora 字段quantization_config典型显存
全参NoneNone~80 GB (7B)
LoRALoraConfigNone~22 GB
QLoRALoraConfigBitsAndBytesConfig (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
LoRA2e-4 ~ 5e-410× 全参
QLoRA2e-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这章你需要带走的