前言

Unsloth 是目前最激进的微调加速方案——通过手动优化的 Triton kernel 和一系列工程技巧,把微调速度提升 2-5 倍,显存占用降低 50-80%。

最大的卖点是:在 Google Colab 的免费 T4 GPU(16GB 显存)上就能微调 7B 模型。

[!WARNING]
系统平台环境提醒:Unsloth 深度依赖针对 Linux 优化的 OpenAI Triton 算子,不支持原生 Windows(在 Windows CMD/PowerShell 下直接 pip 安装会导致 C++ 扩展编译失败)。Windows 用户请务必在 WSL2 (Ubuntu 22.04+) 或直接在 Google Colab / 云端 Linux GPU 实例 中运行。


一、加速与显存节省原理

为什么 Unsloth 能够实现 25 倍训练加速,且显存开销直降 50%80%?


二、安全安装指南(避免依赖地狱)

由于 PyTorch、CUDA、xFormers 与 Triton 的版本依赖极其敏感,强烈建议使用官方推荐的锁版本安装方案:

1. Colab 环境极速安装

1
2
3
# 在 Colab Notebook 首个单元格运行
!pip install "unsloth[colab-new] @ git+https://github.com/unslothai/unsloth.git"
!pip install --no-deps "xformers<0.0.28" "trl<0.9.0" peft accelerate bitsandbytes

2. Linux / WSL2 生产环境安装(CUDA 12.1+)

1
2
3
4
5
# 1. 确认 PyTorch 与 CUDA 正确安装
pip install torch torchvision --index-url https://download.pytorch.org/whl/cu121

# 2. 安装 Unsloth 及周边优化依赖
pip install "unsloth[cu121-torch230] @ git+https://github.com/unslothai/unsloth.git"

三、加载模型

1
2
3
4
5
6
7
8
9
from unsloth import FastLanguageModel
import torch

model, tokenizer = FastLanguageModel.from_pretrained(
model_name="unsloth/Qwen2.5-7B-Instruct-bnb-4bit", # Unsloth 预量化好的模型
max_seq_length=2048, # 根据你的数据长度调整
dtype=None, # None = 自动检测
load_in_4bit=True, # 4-bit 量化加载
)

Unsloth 已经预量化了很多常用模型,直接用带 -bnb-4bit 后缀的版本。支持的模型列表在 unsloth.ai 可以查。


四、挂载 LoRA 适配层

1
2
3
4
5
6
7
8
9
10
11
12
13
14
model = FastLanguageModel.get_peft_model(
model,
r=16, # LoRA rank
target_modules=[ # 对那些层加 LoRA
"q_proj", "k_proj", "v_proj", "o_proj",
"gate_proj", "up_proj", "down_proj",
],
lora_alpha=16,
lora_dropout=0, # 数据不多时设为 0
bias="none",
use_gradient_checkpointing="unsloth", # unsloth 优化的检查点
random_state=3407,
use_rslora=False,
)

五、准备数据

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
from datasets import Dataset

# 训练数据格式:每条包含 instruction、input(可选)、output
data = [
{"instruction": "将下面的文字翻译成英文", "input": "你好世界", "output": "Hello World"},
{"instruction": "将下面的文字翻译成英文", "input": "今天天气不错", "output": "The weather is nice today"},
# ... 更多数据
]

# 转成对话格式
def format_conversation(examples):
texts = []
for instruction, inp, output in zip(
examples["instruction"], examples["input"], examples["output"]
):
content = instruction
if inp:
content += f"\n{inp}"
messages = [
{"role": "user", "content": content},
{"role": "assistant", "content": output}
]
text = tokenizer.apply_chat_template(
messages, tokenize=False, add_generation_prompt=False
)
texts.append(text)
return {"text": texts}

dataset = Dataset.from_list(data)
dataset = dataset.map(format_conversation, batched=True)

六、开始训练

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
from trl import SFTTrainer
from transformers import TrainingArguments

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=5,
max_steps=60, # 先跑 60 步看效果,效果好再加
learning_rate=2e-4, # Unsloth 推荐的学习率
fp16=not torch.cuda.is_bf16_supported(),
bf16=torch.cuda.is_bf16_supported(),
logging_steps=10,
output_dir="./output",
optim="adamw_8bit",
seed=3407,
),
)

trainer_stats = trainer.train()
print(f"训练完成,耗时: {trainer_stats.metrics['train_runtime']:.1f} 秒")

Unsloth 推荐的学习率参考:

基座模型 推荐学习率
Qwen2.5 2e-4
Llama 3.2 2e-4
DeepSeek 1e-4
Mistral 2e-4

七、推理测试

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# 切换到推理加速模式(调用 Unsloth 原生快速推理内核)
FastLanguageModel.for_inference(model)

def ask(instruction, input_text=""):
content = instruction
if input_text:
content += f"\n{input_text}"
messages = [{"role": "user", "content": content}]
text = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
inputs = tokenizer(text, return_tensors="pt").to("cuda")
outputs = model.generate(**inputs, max_new_tokens=256, temperature=0.3)
return tokenizer.decode(outputs[0], skip_special_tokens=True)

print(ask("将下面文字翻译成英文:", "机器学习很有趣"))

八、保存与多格式模型导出

Unsloth 提供了目前业界最优雅的一键合并与多格式导出 API:

1
2
3
4
5
6
7
8
9
# 1. 仅保存极小的 LoRA 权重(几十 MB,适合快速归档与版本迭代)
model.save_pretrained("./lora_weights")
tokenizer.save_pretrained("./lora_weights")

# 2. 合并为 16-bit 完整精度 Safetensors 模型(供 vLLM / HuggingFace 高并发部署)
model.save_pretrained_merged("./merged_16bit_model", tokenizer, save_method="merged_16bit")

# 3. 直接量化并导出为 GGUF 格式(供 Ollama / llama.cpp 轻量运行)
model.save_pretrained_gguf("./gguf_model", tokenizer, quantization_method="q4_k_m")

导出为 GGUF 后,即可直接利用 Ollama 载入:

1
2
3
4
5
6
7
8
# 编写极简 Modelfile
cat > Modelfile << EOF
FROM ./gguf_model/unsloth.Q4_K_M.gguf
EOF

# 导入 Ollama 并极速测试
ollama create my-fast-model -f Modelfile
ollama run my-fast-model

九、Colab 免费 GPU 完整执行流

  1. 打开 Google Colab,在菜单栏选择 运行时 → 更改运行时类型 → T4 GPU;
  2. 运行环境安全初始化指令:
    1
    2
    !pip install "unsloth[colab-new] @ git+https://github.com/unslothai/unsloth.git"
    !pip install --no-deps "xformers<0.0.28" "trl<0.9.0" peft accelerate bitsandbytes
  3. 挂载 Google Drive 保存产物:
    1
    2
    from google.colab import drive
    drive.mount('/content/drive')
  4. 运行训练代码,将最终权重存入 /content/drive/MyDrive/my_lora;
  5. 任务完成后主动断开运行时,避免空耗免费 GPU 额度。

Colab T4 (16GB 显存) 上的性能实测参考(QLoRA 微调 7B 模型):

数据量 Batch Size 训练用时 等效 Gradient Accumulation
200 条 2 ~8 分钟 4
500 条 2 ~20 分钟 4
1000 条 2 ~40 分钟 4
2000 条 2 ~80 分钟 4

Colab 免费版具有单次最长 3~4 小时的连续使用阈值,微调 2000 条以内的垂直场景数据完全可以在免费配额内无缝搞定。


十、Unsloth vs LLaMA-Factory 怎么选?

维度 Unsloth LLaMA-Factory
上手门槛 中等(Python 脚本级控制) 极低(零代码 Web UI)
训练吞吐与速度 极快(Triton 手写算子 2~5 倍加速) 正常标准速度
显存压缩极限 极致(减少 50%~80% 峰值显存) 正常 QLoRA 水平
模型与架构覆盖 主流架构(Qwen, Llama, Mistral, Gemma) 极广(100+ 模型架构全覆盖)
单卡 T4 跑 7B 极其从容且稳定 可以跑,但需极致压缩 Batch
操作系统 仅 Linux / WSL2 / Colab Windows / Linux / macOS 全支持

选型建议:

  • 如果你的显存极其吃紧(例如只有免费 Colab T4 或单张 12GB 显卡),且主要微调 Qwen 或 Llama,首选 Unsloth,速度与显存优势无出其右;
  • 如果你身处纯 Windows 办公环境,或者不想写代码、希望通过可视化拖拉拽完成数据与超参实验,首选 LLaMA-Factory。