Loading...

文章背景图

Unsloth:2-5倍速省显存大模型微调库安装与使用指南

2026-10-24
0
- 字
- 分钟
|

Unsloth:2-5倍速省显存大模型微调库安装与使用指南

一、官方信息

项目名称Unsloth
仓库地址https://github.com/unslothai/unsloth
官方网站https://unsloth.ai
最新更新持续高频迭代(2026-10-24)
Star 数15k+
项目定位通过手写 Triton Kernel 重写注意力与前向过程,让 LoRA 微调速度提升 2-5 倍、显存占用降低 70%

二、项目背景

Unsloth 由 Daniel Han 与团队创立,最初在 2023 年底以一系列 Twitter 技术博客走红。核心思路是:PyTorch 默认的注意力、RMSNorm、SwiGLU 等算子存在大量冗余计算,Unsloth 用手写 Triton kernel 重新实现这些算子,并融合反向传播,在数学等价的前提下把训练 FLOPs 降下来。

它兼容 HuggingFace Trainer 与 TRL,无需改动业务代码,只要把模型加载从 AutoModelForCausalLM.from_pretrained 换成 FastLanguageModel.from_pretrained,就能享受 2-5 倍训练加速。单张 24GB 3090/4090 即可微调 7B 模型,是个人开发者和学生做微调的神器。LLaMA-Factory、Axolotl 都已原生集成 Unsloth 后端。

三、核心特性

  • 2-5 倍训练加速:Triton 融合 Kernel,单卡训练 7B 模型从几小时缩到几十分钟。
  • 70% 显存节省:24GB 4090 可跑 7B QLoRA;48GB A6000 可跑 14B 全参数 LoRA。
  • 数学等价:loss 曲线与标准 HF 训练对齐,精度无损失。
  • 全模型支持:Llama、Qwen2/3、Mistral、Gemma、Phi、DeepSeek、Gpt-NeoX 等。
  • RLHF 全支持:SFT / DPO / ORPO / GRPO 开箱即用。
  • 云端免费 Colab:官方提供一键 Colab Notebook,免配置白嫖 T4/A100。
  • 导出广泛兼容:支持导出为 HuggingFace、GGUF、vLLM、Ollama 格式。

四、环境要求

  • 操作系统:Linux(Windows WSL2 也可;原生 Windows 不支持 Triton)
  • Python:3.10 ~ 3.12
  • GPU:NVIDIA 显卡,算力 ≥ 7.0(T4/3090/4090/A100/H100)
  • CUDA:11.8 / 12.1 / 12.4
  • PyTorch:2.1 ~ 2.5

五、详细部署步骤

方式一:pip 安装(推荐)

conda create -n unsloth python=3.11 -y
conda activate unsloth

# 安装 PyTorch(CUDA 12.1)
pip install torch==2.4.0 torchvision --index-url https://download.pytorch.org/whl/cu121

# 安装 unsloth
pip install unsloth

# 验证
python3 -c "from unsloth import FastLanguageModel; print('OK')"

方式二:源码安装

git clone https://github.com/unslothai/unsloth.git
cd unsloth
pip install -e . --no-build-isolation

方式三:Colab 一键跑(零成本体验)

打开 官方 Notebook,在 Colab 中选择 GPU(T4 免费 / A100 付费),逐格运行即可。

完整微调示例代码

# train.py
from unsloth import FastLanguageModel
import torch
from trl import SFTTrainer
from transformers import TrainingArguments
from datasets import load_dataset

# 1. 加载模型(4bit 量化 + Unsloth 优化)
model, tokenizer = FastLanguageModel.from_pretrained(
    model_name = "unsloth/Qwen2.5-7B-Instruct-bnb-4bit",
    max_seq_length = 2048,
    dtype = None,           # 自动检测
    load_in_4bit = True,
)

# 2. 挂上 LoRA
model = FastLanguageModel.get_peft_model(
    model,
    r = 16,
    lora_alpha = 16,
    lora_dropout = 0,
    target_modules = ["q_proj","k_proj","v_proj","o_proj",
                      "gate_proj","up_proj","down_proj"],
    use_gradient_checkpointing = "unsloth",
    random_state = 42,
)

# 3. 加载数据集(示例用 ShareGPT 格式)
dataset = load_dataset("json", data_files="my_data.jsonl", split="train")

# 4. 配置 Trainer
trainer = SFTTrainer(
    model = model,
    tokenizer = tokenizer,
    train_dataset = dataset,
    dataset_text_field = "text",
    max_seq_length = 2048,
    args = TrainingArguments(
        per_device_train_batch_size = 2,
        gradient_accumulation_steps = 4,
        warmup_steps = 10,
        max_steps = 100,
        learning_rate = 2e-4,
        fp16 = not torch.cuda.is_bf16_supported(),
        bf16 = torch.cuda.is_bf16_supported(),
        logging_steps = 10,
        optim = "adamw_8bit",
        weight_decay = 0.01,
        lr_scheduler_type = "linear",
        output_dir = "outputs",
    ),
)

# 5. 开始训练
trainer.train()

# 6. 保存 LoRA 权重
model.save_pretrained("lora_model")
tokenizer.save_pretrained("lora_model")

导出为 GGUF(给 Ollama/llama.cpp 用)

# 在训练脚本末尾加
model.save_pretrained_gguf("model_gguf", tokenizer, quantization_method = "q4_k_m")
# 生成 model_gguf/model.Q4_K_M.gguf,可直接 ollama create

DPO 对齐训练

from trl import DPOTrainer, DPOConfig

dpo_trainer = DPOTrainer(
    model = model,
    ref_model = None,    # Unsloth 自动创建 reference
    tokenizer = tokenizer,
    train_dataset = dataset,  # 需含 prompt/chosen/rejected 字段
    args = DPOConfig(
        per_device_train_batch_size = 2,
        gradient_accumulation_steps = 4,
        max_steps = 100,
        learning_rate = 5e-6,
        output_dir = "dpo_output",
    ),
)
dpo_trainer.train()

六、常见问题(FAQ)

Q1:报 "Triton not installed"?
A:pip install triton。Windows 原生不支持 Triton,必须用 WSL2。

Q2:支持 AMD 显卡吗?
A:最新版已支持 ROCm,安装时设 pip install unsloth[rocm]。

Q3:Unsloth 模型比普通模型差吗?
A:官方在公开 benchmark 中证明 loss 曲线对齐,精度无差异。

Q4:和 LLaMA-Factory 怎么配合?
A:LLaMA-Factory yaml 中加 use_unsloth: true 即可,无需改代码。

Q5:显存还是不够?
A:① 用 4bit 量化加载;② 减小 per_device_train_batch_size,增大 gradient_accumulation_steps;③ 开启 gradient_checkpointing;④ 切到更小模型(如 Qwen2.5-3B)。

七、跳转链接

评论交流

文章目录