关于 llm-fine-tuning
llm-fine-tuning 是帮助团队使用领域数据调整开源 LLM 的技能,涵盖 LoRA、QLoRA、分布式训练、对齐方法,以及用于部署的适配器导出。
主要功能
- 01LoRA 与 QLoRA 微调
- 02Axolotl 训练配置
- 03DeepSpeed 分布式训练
- 04DPO 与 RLHF 对齐流程
- 05用于部署的 LoRA 适配器合并
适用场景
- 01用法律或支持数据调整 LLM
- 02在 GPU 显存有限时微调模型
- 03运行多 GPU 分布式训练
- 04准备适配器用于生产服务
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ bagelhole/ devops-security-agent-skills --skill llm-fine-tuning安装后在 Claude Code 中输入/llm-fine-tuning确认已加载。
详细介绍
大模型微调基础设施
高效训练和微调开源大模型——从单 GPU 上的 LoRA,到多节点集群上的分布式全量微调。
何时使用此技能
在以下情况下使用此技能:
- 使用领域专用数据(法律、医疗、代码、支持服务)微调大模型
- 使用 QLoRA 在消费级 GPU 上微调 70B 模型
- 使用 DeepSpeed 或 FSDP 设置分布式训练
- 导出微调后的适配器,以便在生产环境中提供服务
- 实施 RLHF、DPO 或指令微调工作流
前提条件
- 配备 24GB 以上 VRAM 的 NVIDIA GPU(RTX 4090 / A100 / H100)
- CUDA 12.1+,且
nvidia-smi可正常运行 - 安装了
pip的 Python 3.10+ - Hugging Face 账户,以及用于访问受限模型的
HF_TOKEN - 500GB 以上磁盘空间,用于存放模型权重和训练数据
快速入门:QLoRA 微调
pip install transformers datasets trl peft bitsandbytes accelerate
python - <<'EOF'
from datasets import load_dataset
from transformers import AutoTokenizer, AutoModelForCausalLM, BitsAndBytesConfig
from peft import LoraConfig, get_peft_model
from trl import SFTTrainer, SFTConfig
import torch
model_id = "meta-llama/Llama-3.1-8B-Instruct"
# 4-bit quantization (QLoRA)
bnb_config = BitsAndBytesConfig(
load_in_4bit=True,
bnb_4bit_quant_type="nf4",
bnb_4bit_compute_dtype=torch.bfloat16,
bnb_4bit_use_double_quant=True,
)
model = AutoModelForCausalLM.from_pretrained(
model_id, quantization_config=bnb_config, device_map="auto"
)
tokenizer = AutoTokenizer.from_pretrained(model_id)
# LoRA configuration
peft_config = LoraConfig(
r=16, # rank
lora_alpha=32,
target_modules=["q_proj", "k_proj", "v_proj", "o_proj",
"gate_proj", "up_proj", "down_proj"],
lora_dropout=0.05,
bias="none",
task_type="CAUSAL_LM",
)
dataset = load_dataset("your-org/your-dataset", split="train")
trainer = SFTTrainer(
model=model,
args=SFTConfig(
output_dir="./output",
num_train_epochs=3,
per_device_train_batch_size=2,
gradient_accumulation_steps=8,
learning_rate=2e-4,
bf16=True,
logging_steps=10,
save_strategy="epoch",
report_to="wandb",
),
train_dataset=dataset,
peft_config=peft_config,
processing_class=tokenizer,
)
trainer.train()
trainer.save_model("./fine-tuned-model")
EOF
Axolotl(生产级微调框架)
# config.yaml — Axolotl QLoRA config for Llama 3.1
base_model: meta-llama/Llama-3.1-8B-Instruct
model_type: LlamaForCausalLM
tokenizer_type: PreTrainedTokenizerFast
load_in_4bit: true
adapter: qlora
lora_r: 32
lora_alpha: 64
lora_dropout: 0.05
lora_target_modules:
- q_proj
- k_proj
- v_proj
- o_proj
- gate_proj
- up_proj
- down_proj
datasets:
- path: your-org/your-dataset
type: alpaca # or sharegpt, chat_template, etc.
dataset_prepared_path: ./prepared-data
val_set_size: 0.05
output_dir: ./output
sequence_len: 4096
sample_packing: true # pack multiple short samples for efficiency
micro_batch_size: 2
gradient_accumulation_steps: 8
num_epochs: 3
learning_rate: 2e-4
optimizer: adamw_bnb_8bit
lr_scheduler: cosine
warmup_ratio: 0.05
bf16: true
flash_attention: true
logging_steps: 10
eval_steps: 100
save_steps: 200
wandb_project: my-fine-tune
# Run with Axolotl
pip install axolotl[flash-attn,deepspeed]
accelerate launch -m axolotl.cli.train config.yaml
使用 DeepSpeed 进行分布式训练
// deepspeed_zero3.json — ZeRO Stage 3 (split optimizer + gradients + params)
{
"zero_optimization": {
"stage": 3,
"offload_optimizer": {"device": "cpu", "pin_memory": true},
"offload_param": {"device": "cpu", "pin_memory": true},
"overlap_comm": true,
"contiguous_gradients": true,
"sub_group_size": 1e9,
"reduce_bucket_size": "auto",
"stage3_prefetch_bucket_size": "auto",
"stage3_param_persistence_threshold": "auto",
"stage3_max_live_parameters": 1e9,
"stage3_max_reuse_distance": 1e9,
"gather_16bit_weights_on_model_save": true
},
"bf16": {"enabled": true},
"gradient_clipping": 1.0,
"train_batch_size": "auto",
"train_micro_batch_size_per_gpu": "auto"
}
# Launch 4-GPU DeepSpeed training
deepspeed --num_gpus=4 train.py \
--deepspeed deepspeed_zero3.json \
--model_name meta-llama/Llama-3.1-70B-Instruct \
--output_dir ./output
DPO / RLHF 对齐
from trl import DPOTrainer, DPOConfig
from datasets import load_dataset
# Dataset format: {"prompt": ..., "chosen": ..., "rejected": ...}
dataset = load_dataset("your-org/preference-data")
trainer = DPOTrainer(
model=model,
ref_model=None, # None = implicit reference with peft
args=DPOConfig(
output_dir="./dpo-output",
beta=0.1, # KL divergence weight
num_train_epochs=1,
per_device_train_batch_size=1,
gradient_accumulation_steps=16,
learning_rate=5e-7,
bf16=True,
),
train_dataset=dataset["train"],
peft_config=peft_config,
processing_class=tokenizer,
)
trainer.train()
合并 LoRA 适配器以供部署
from peft import PeftModel
from transformers import AutoModelForCausalLM
# Load base model in full precision
base_model = AutoModelForCausalLM.from_pretrained(
"meta-llama/Llama-3.1-8B-Instruct",
torch_dtype=torch.bfloat16,
device_map="cpu",
)
# Load and merge LoRA adapter
model = PeftModel.from_pretrained(base_model, "./fine-tuned-model")
merged_model = model.merge_and_unload()
# Save merged model (ready for vLLM serving)
merged_model.save_pretrained("./merged-model", safe_serialization=True)
tokenizer.save_pretrained("./merged-model")
# Push to Hugging Face Hub
merged_model.push_to_hub("your-org/your-fine-tuned-model")
Kubernetes 训练任务
apiVersion: batch/v1
kind: Job
metadata:
name: llm-fine-tune
spec:
template:
spec:
restartPolicy: OnFailure
nodeSelector:
nvidia.com/gpu.product: A100-SXM4-80GB
containers:
- name: trainer
image: nvcr.io/nvidia/pytorch:24.05-py3
command: ["accelerate", "launch", "-m", "axolotl.cli.train", "/config/config.yaml"]
resources:
limits:
nvidia.com/gpu: "4"
memory: "320Gi"
requests:
nvidia.com/gpu: "4"
volumeMounts:
- name: config
mountPath: /config
- name: model-cache
mountPath: /root/.cache/huggingface
- name: output
mountPath: /output
env:
- name: HUGGING_FACE_HUB_TOKEN
valueFrom:
secretKeyRef:
name: hf-token
key: token
- name: WANDB_API_KEY
valueFrom:
secretKeyRef:
name: wandb-token
key: key
volumes:
- name: config
configMap:
name: axolotl-config
- name: model-cache
persistentVolumeClaim:
claimName: model-cache-pvc
- name: output
persistentVolumeClaim:
claimName: training-output-pvc
常见问题
| 问题 | 原因 | 解决方法 |
|---|---|---|
CUDA out of memory | 批次过大 | 减小 micro_batch_size;增大 gradient_accumulation_steps |
| 训练损失为 NaN | 学习率过高 | 将 LR 降至 1e-4 或 5e-5;添加预热 |
| 训练缓慢 | 未启用 Flash Attention | 安装 flash-attn;启用 flash_attention: true |
| 微调效果不佳 | 数据格式错误 | 验证数据集格式;检查与 sample_packing 的兼容性 |
| 合并适配器时出错 | 量化方式混用 | 在 CPU 上以 bf16 合并,而非使用 4-bit |
最佳实践
- 使用 Flash Attention 2——速度可提升 2–4 倍,且占用更少内存。
- 通过 W&B 或 MLflow 监控训练损失和评估损失;过拟合时,增加 dropout 或减少数据量。
- 使用留出的评估集(5–10%)进行验证;使用 MMLU 或自定义评估作为质量门槛。
- 先从 LoRA r=16 开始,再逐步提高——秩越高,参数越多,但收益会递减。
- 在 Axolotl 中使用
sample_packing,最大限度提高 GPU 对短序列的利用率。
相关技能
- vllm-server - 提供微调后模型的服务
- gpu-server-management - GPU 设置
- llm-inference-scaling - 大规模部署
- ai-pipeline-orchestration - 训练工作流
评论
支持 Markdown