Skip to content

大语言模型微调 LLaMA-Factory



大模型训练方法


预训练(Pretraining)

  • 利用大规模 无监督语料 训练语言模型
  • 目标是让模型掌握 语言规律知识结构
  • 形成一个可泛化的 基础语言模型(Base Model)

常见预训练模型类型

模型名称 结构 训练目标 代表模型
BERT Encoder MLM(掩码语言建模) BERT、RoBERTa
GPT Decoder 自回归语言建模 GPT-2、GPT-3、GPT-4
T5 Encoder-Decoder 多任务统一建模 T5、mT5
Others 混合结构 Span 预测、对比学习等 ERNIE、GLM、UL2

预训练的核心流程

  1. 准备语料
    • 大规模无标签文本(维基百科、书籍、网页、代码等)
  2. 文本清洗与分词
    • 去噪声、规范化、使用 BPE/WordPiece 分词器
  3. 设计训练目标
    • 如 MLM、Causal LM、Next Sentence Prediction 等
  4. 搭建模型结构
    • Transformer 架构(Encoder/Decoder)
  5. 分布式训练
    • 使用 GPU/TPU 的数据并行、模型并行
  6. 训练优化与日志监控
    • 学习率调度、混合精度、梯度裁剪、loss 监控等

预训练的挑战

  • 计算资源昂贵
    • 单次训练可能需要数百万美元
  • 数据质量决定模型能力
    • 垃圾数据训练出的模型偏见强/效果差
  • 训练时间长
    • GPT-3 用 上万块 GPU 训练了数周
  • 工程复杂度高
    • 分布式系统、故障恢复、调度等均有挑战

微调(Finetuning)

大模型微调(Fine-tuning)是指在已经预训练好的大型语言模型基础上,使用特定的数据集进行进一步的训练,以使模型适应特定任务或领域。


为什么需要微调

原因 说明
通用模型不懂行业语言 如医疗、法律、金融专业词汇
通用模型输出不稳定 微调可使输出格式稳定、可控
提升特定任务表现 在少量标注数据下可显著提升效果
替代提示词工程失败场景 当 prompt 工程无法达到效果时,微调可更有效

微调方法

  • 全参数微调(Full Finetuning)对模型所有参数重新训练
  • Adapter Tuning 在模型每层中插入轻量模块(Adapter)与 LoRA 类似,但结构不同
  • LoRA(Low-Rank Adaptation)只训练少量插入层(低秩矩阵)


微调方法对比

对比维度 全参数微调(Full Finetuning) LoRA(Low-Rank Adaptation) Adapter 微调
参数更新范围 更新模型所有参数 仅更新插入的低秩矩阵(少量参数) 插入 adapter 模块,仅更新模块内参数
显存占用 低(仅占用少量新增权重)
训练速度
效果表现 最佳(可适应复杂任务) 接近全参微调(任务匹配时) 中等至好(适合分类、抽取等)
部署复杂度 模型体积大,不便部署 插入权重可合并或按需加载,部署灵活 模块需在推理时加载,需框架支持
适合场景 模型全定制、高资源条件 中小团队、任务多样化、资源有限 低资源场景、需要模块化结构支持的任务
主流框架支持 Transformers、Deepspeed HuggingFace PEFT、transformers transformers、AdapterHub 等

{.!text-xs}


总结建议

  • 全参数微调:当资源充足、追求最优精度,或模型完全自定义时首选。
  • LoRA:最佳性价比方案,推荐用于大多数企业级场景,尤其适合多任务。
  • Adapter:模块化强,适合研究场景或框架兼容性强的任务。

微调流程概览

  1. 准备数据集

    • 格式:JSON、CSV、Dataset 对象
    • 类型:指令数据、QA、分类数据等
  2. 选择基础模型

    • llama, baichuan, chatglm, mistral, bert
  3. 加载微调框架

    • 使用 HuggingFace transformers
    • 或 PEFT(Parameter Efficient Finetuning)
  4. 配置训练参数

    • 学习率、批大小、训练轮数、保存路径等
  5. 开始训练 + 保存权重

    • 可保存为 adapter 模块,或合并到模型中

预训练 vs 微调 vs 提示词工程

对比维度 预训练(Pretraining) 微调(Finetuning) 提示词工程(Prompt Engineering)
定义 从头或继续训练大模型 在已有模型上用特定任务数据继续训练 通过设计输入提示引导模型完成任务
成本 极高(数据 + 算力) 中等(需要 GPU + 标注数据) 极低(仅改提示,无需训练)
技术门槛 极高(需掌握模型结构和训练流程) 中等(需了解 Transformer 微调方法) 低(只需设计 prompt)
开发周期 长(数周至数月) 中(几小时至几天) 快(分钟级)
代表方法 GPT、BERT 原始训练 全参数微调、LoRA、Adapter、PEFT Zero-shot、Few-shot、CoT、ReAct、RAG 等
适用场景 训练通用模型、大公司/学术 企业内部定制化模型(客服、风控、抽取) 快速原型、低资源任务、ChatGPT 类调用

{.!text-xs}


选择建议

  • 提示词工程:快速实验、小规模应用、无权重控制权时首选。
  • 微调:有少量数据、想提高任务精度,或需要自定义输出格式时。
  • 预训练:不建议个人或中小团队尝试,成本极高,仅适合模型研发者。

微调技术方案


llama-factory

LLaMA Factory 是一个易于使用且高效的大型语言模型训练和微调平台。使用 LLaMA Factory,您可以在本地微调数百个预训练模型,无需编写任何代码。框架功能包括: 模型:LLaMA、LLaVA、Mistral、Mixtral-MoE、Qwen、Yi、Gemma、Baichuan、ChatGLM、Phi 等。 训练器:(增量式)预训练、(多模态)指令监督微调、奖励模型训练、PPO 训练、DPO 训练、KTO 训练、ORPO 训练等。 计算精度:16 位全参数微调、冻结微调、LoRA 微调,以及基于 AQLM/AWQ/GPTQ/LLM.int8/HQQ/EETQ 的 2/3/4/5/6/8 位 QLoRA 微调。

\


llama-factory 安装

git clone --depth 1 https://github.com/hiyouga/LLaMA-Factory.git
cd LLaMA-Factory
uv sync --extra torch --extra metrics --prerelease=allow --python 3.10

基本使用

llamafactory-cli --help
----------------------------------------------------------------------
| Usage:                                                             |
|   llamafactory-cli api -h: launch an OpenAI-style API server       |
|   llamafactory-cli chat -h: launch a chat interface in CLI         |
|   llamafactory-cli eval -h: evaluate models                        |
|   llamafactory-cli export -h: merge LoRA adapters and export model |
|   llamafactory-cli train -h: train models                          |
|   llamafactory-cli webchat -h: launch a chat interface in Web UI   |
|   llamafactory-cli webui: launch LlamaBoard                        |
|   llamafactory-cli version: show version info                      |
----------------------------------------------------------------------

# 训练
llamafactory-cli train examples/train_lora/llama3_lora_sft.yaml

# 推理
llamafactory-cli chat examples/inference/llama3_lora_sft.yaml

# 合并
llamafactory-cli export examples/merge_lora/llama3_lora_sft.yaml

llamafactory-cli webui


训练数据集

[
  {
    "instruction": "识别并解释给定列表中的两个科学理论:细胞理论和日心说。",
    "input": "",
    "output": "细胞理论是生物科学的一个理论,它认为所有生命体都是由微小的基本单元——细胞所构成。这是生物学的一个基础理论,认为细胞是所有生物的基本结构和功能单位,所有的生物都是由一个或多个细胞组成,细胞只能通过细胞分裂产生新的细胞
。这一理论由薛定谔、施瓦内和雪莱于1839年首次提出。\n\n日心说是指太阳是太阳系的中心,也就是说,行星围绕太阳旋转的理
论。这个理论打破了传统的地心说观点,认为地球并不是宇宙的中心。日心说的提出者是尼古拉·哥白尼,他在16世纪初发表了他的著作《天体运行论》,阐述了太阳系行星围绕太阳运行的模型,为天文学的发展做出了巨大贡献。"
  },
  {
    "instruction": "输入三支篮球队的名称并生成一个适当的口号。",
    "input": "输入:俄克拉荷马城雷霆队,芝加哥公牛队,布鲁克林网队。",
    "output": "输出: \"雷霆,公牛和网队:各显神通,角逐群雄!\""
  },
  {
    "instruction": "比较以下两位著名人物,使用特征列表并以句子形式提供输出。",
    "input": "人物1:阿尔伯特·爱因斯坦\n人物2:斯蒂芬·霍金\n特征:智力、教育、对世界的影响",
    "output": "阿尔伯特·爱因斯坦和斯蒂芬·霍金都是拥有极其出色智力的人物。两人都取得过非常高的教育成就,他们推进了科学发展并在世界范围内产生了深远的影响。爱因斯坦以其相对论和质能关系公式而闻名,而霍金以其关于黑洞和宇宙的发现而著称
。两位科学家都以其深厚的学识和非凡的贡献影响了世界。"

函数调用数据集

[
  {
    "conversations": [
      {
        "from": "human",
        "value": "我需要为John Doe生成一张发票。他购买了2个苹果,每个$1,以及3根香蕉,每根$0.5。"
      },
      {
        "from": "function_call",
        "value": "{\"name\": \"generate_invoice\", \"arguments\": {\"customer_name\": \"约翰·多伊\", \"items\": [{\"name\": \"苹果\", \"quantity\": 2, \"price\": 1}, {\"name\": \"香蕉\", \"quantity\": 3, \"price\": 0.5}]}}"
"name\": \"苹果\", \"quantity\": 2, \"price\": 1}, {\"name\": \"香蕉\", \"quantity\": 3, \"price\": 0.5}]}}"
      },
[
  {
    "conversations": [
      {
        "from": "human",
        "value": "我需要为John Doe生成一张发票。他购买了2个苹果,每个$1,以及3根香蕉,每根$0.5。"
      },
      {
        "from": "function_call",
        "value": "{\"name\": \"generate_invoice\", \"arguments\": {\"customer_name\": \"约翰·多伊\", \"items\": [{\
"name\": \"苹果\", \"quantity\": 2, \"price\": 1}, {\"name\": \"香蕉\", \"quantity\": 3, \"price\": 0.5}]}}"
      },
      {
        "from": "observation",
        "value": "{\"invoice_id\": \"INV12345\", \"customer_name\": \"约翰·多伊\", \"items\": [{\"name\": \"苹果\", \"quantity\": 2, \"price\": 1, \"total\": 2}, {\"name\": \"香蕉\", \"quantity\": 3, \"price\": 0.5, \"total\": 1.5}], \"total\": 3.5, \"status\": \"生成\"}"
      },
      {
        "from": "gpt",
        "value": "发票已成功生成。发票编号为INV12345。约翰·多伊的总金额为$3.5。发票包含2个苹果,总金额为$2,以及3根香蕉,总金额为$1.5。"
      }
    ],
    "tools": "[{\"name\": \"generate_invoice\", \"description\": \"生成发票\", \"parameters\": {\"type\": \"object\
", \"properties\": {\"customer_name\": {\"type\": \"string\", \"description\": \"客户名称\"}, \"items\": {\"type\":
 \"array\", \"items\": {\"type\": \"object\", \"properties\": {\"name\": {\"type\": \"string\", \"description\": \"
The item name\"}, \"quantity\": {\"type\": \"integer\", \"description\": \"The quantity of the item\"}, \"price\":
{\"type\": \"number\", \"description\": \"The price per unit\"}}, \"required\": [\"name\", \"quantity\", \"price\"]
}}}, \"required\": [\"customer_name\", \"items\"]}}, {\"name\": \"generate_password\", \"description\": \"生成随机
密码\", \"parameters\": {\"type\": \"object\", \"properties\": {\"length\": {\"type\": \"integer\", \"description\"
: \"密码的长度\"}}, \"required\": [\"length\"]}}]"
  },

多模态训练数据集

[
  {
    "messages": [
      {
        "content": "<image>Who are they?",
        "role": "user"
      },
      {
        "content": "They're Kane and Gretzka from Bayern Munich.",
        "role": "assistant"
      },
      {
        "content": "What are they doing?<image>",
        "role": "user"
      },
      {
        "content": "They are celebrating on the soccer field.",
        "role": "assistant"
      }
    ],
    "images": [
      "mllm_demo_data/1.jpg",
      "mllm_demo_data/1.jpg"
    ]
  },

开始训练

llamafactory-cli train examples/train_lora/llama3_lora_sft.yaml

llamafactory-cli train examples/train_lora/llama3_lora_sft.yaml \
    learning_rate=1e-5 \
    logging_steps=1



{.!grow-2}


mmlu_test 效果评估的训练集与测试集

\


效果评估

llamafactory-cli eval examples/train_lora/llama3_lora_eval.yaml

\

### examples/train_lora/llama3_lora_eval.yaml
### model
model_name_or_path: meta-llama/Meta-Llama-3-8B-Instruct
adapter_name_or_path: saves/llama3-8b/lora/sft # 可选项

### method
finetuning_type: lora

### dataset
task: mmlu_test # mmlu_test, ceval_validation, cmmlu_test
template: fewshot
lang: en
n_shot: 5

### output
save_dir: saves/llama3-8b/lora/eval

### eval
batch_size: 4

微调方案 PEFT

PEFT(参数高效微调)是一个库,用于高效地将大型预训练模型适配到各种下游应用,而无需对模型的所有参数进行微调,因为微调成本过高。PEFT 方法仅微调少量(额外的)模型参数,从而显著降低计算和存储成本,同时获得与完全微调模型相当的性能。这使得在消费级硬件上训练和存储大型语言模型 (LLM) 变得更加便捷。


PEFT 的使用

from peft import LoraConfig, TaskType

peft_config = LoraConfig(task_type=TaskType.SEQ_2_SEQ_LM, inference_mode=False, r=8, lora_alpha=32, lora_dropout=0.1)

from transformers import AutoModelForSeq2SeqLM

model = AutoModelForSeq2SeqLM.from_pretrained("bigscience/mt0-large")

from peft import get_peft_model

model = get_peft_model(model, peft_config)
model.print_trainable_parameters()
"output: trainable params: 2359296 || all params: 1231940608 || trainable%: 0.19151053100118282"

training_args = TrainingArguments(
    output_dir="your-name/bigscience/mt0-large-lora",
    learning_rate=1e-3,
    per_device_train_batch_size=32,
    per_device_eval_batch_size=32,
    num_train_epochs=2,
    weight_decay=0.01,
    eval_strategy="epoch",
    save_strategy="epoch",
    load_best_model_at_end=True,
)

trainer = Trainer(
    model=model,
    args=training_args,
    train_dataset=tokenized_datasets["train"],
    eval_dataset=tokenized_datasets["test"],
    tokenizer=tokenizer,
    data_collator=data_collator,
    compute_metrics=compute_metrics,
)

trainer.train()

model.save_pretrained("output_dir")

总结

预训练与微调都需要大量的数据,有比较大的成本,很难使用快速变化的业务。 对于大部分的通用人类任务与自动化任务,通用大模型的推理能力已经可以很好的处理,所以大部分情况下,我们不需要使用预训练与微调,提示词工程是更加实用的方案。