SuperAPI AI 工具集

fine-tuning-customization

智能体与模型

查看项目

更新于 10-16 04:38

技能介绍

用途

该技能用于针对特定领域定制大语言模型,采用参数高效微调与对齐技术。它强调微调应作为最后手段:先尝试提示工程,再考虑 RAG,只有在提示工程不足、RAG 无法捕捉领域细微差别、需要固定输出格式、必须深度嵌入人设或风格,且拥有约 1000 条以上高质量样本时才进行微调。

主要能力

  • LoRA 与 QLoRA:参数高效微调,支持低秩适配器。QLoRA 使用动态 4 位量化,内存节省 75% 以上,质量与 LoRA 基线大致相同(Unsloth 恢复了精度损失)。LoRA 训练速度比 QLoRA 快 39%。70B LLaMA 在 QLoRA 下可低于 48GB 显存运行。
  • DPO 对齐:直接偏好优化,使用 {prompt, chosen, rejected} 格式的偏好数据集,配合冻结的参考模型进行训练。
  • 合成数据生成:使用教师模型生成训练样本,支持教师-学生训练与数据质量扩展。
  • 决策框架:提供“是否微调”的判断依据,对比提示工程、RAG 与微调的适用条件。

使用方式

LoRA/QLoRA 训练示例:

from unsloth import FastLanguageModel
from trl import SFTTrainer

# Load with 4-bit quantization (QLoRA)
model, tokenizer = FastLanguageModel.from_pretrained(
    model_name="unsloth/Meta-Llama-3.1-8B",
    max_seq_length=2048,
    load_in_4bit=True,
)

# Add LoRA adapters
model = FastLanguageModel.get_peft_model(
    model,
    r=16,              # Rank (16-64 typical)
    lora_alpha=32,     # Scaling (2x r)
    lora_dropout=0.05,
    target_modules=[
        "q_proj", "k_proj", "v_proj", "o_proj",  # Attention
        "gate_proj", "up_proj", "down_proj",      # MLP (QLoRA paper)
    ],
)

# Train
trainer = SFTTrainer(
    model=model,
    tokenizer=tokenizer,
    train_dataset=dataset,
    max_seq_length=2048,
)
trainer.train()

DPO 对齐示例:

from trl import DPOTrainer, DPOConfig

config = DPOConfig(
    learning_rate=5e-6,  # Lower for alignment
    beta=0.1,            # KL penalty coefficient
    per_device_train_batch_size=4,
    num_train_epochs=1,
)

# Preference dataset: {prompt, chosen, rejected}
trainer = DPOTrainer(
    model=model,
    ref_model=ref_model,  # Frozen reference
    args=config,
    train_dataset=preference_dataset,
    tokenizer=tokenizer,
)
trainer.train()

合成数据生成示例:

async def generate_synthetic(topic: str, n: int = 100) -> list[dict]:
    """Generate training examples using teacher model."""
    examples = []
    for _ in range(n):
        response = await client.chat.completions.create(
            model="gpt-5.2",  # Teacher
            messages=[{
                "role": "system",
                "content": f"Generate a training example about {topic}. "
                          "Include instruction and response."
            }],
            response_format={"type": "json_object"}
        )
        examples.append(json.loads(response.choices[0].message.content))
    return examples

关键超参数建议:学习率 2e-4(LoRA/QLoRA 标准);训练轮数 1-3(更多易过拟合);LoRA r 为 16-64(越高容量越大);LoRA alpha 为 2 倍 r;每设备批大小 4-8;预热比例 3%。

适用场景

  • 在消费级硬件上微调大模型。
  • 配置 LoRA 超参数、选择适配器目标模块。
  • 将模型对齐到人类偏好、创建偏好数据集。
  • 用 LLM 生成训练数据、实现教师-学生训练。
  • 判断何时适合微调、评估微调替代方案、评估数据需求。

限制与反模式

  • 禁止在未尝试替代方案前直接微调,应先尝试提示工程与 RAG。
  • 禁止使用低质量训练数据。
  • 禁止跳过评估,部署前必须评估。
  • 必须使用独立评估集(如按 10% 划分)。

相关技能

llm-evaluation(评估微调模型)、embeddings(何时改用嵌入)、rag-retrieval(何时 RAG 优于微调)、langfuse-observability(跟踪训练实验)。

详细文档

references/lora-qlora.md(参数高效微调)、references/dpo-alignment.md(直接偏好优化)、references/synthetic-data.md(训练数据生成)、references/when-to-finetune.md(决策框架)。