> For the complete documentation index, see [llms.txt](https://docs.clore.ai/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.clore.ai/guides/guides_v2-zh/xun-lian/unsloth-finetune.md).

# Unsloth 2 倍更快微调

在 Clore.ai 上使用 Unsloth，以少 70% 的 VRAM 将 LLM 微调速度提升 2 倍

Unsloth 使用手工优化的 Triton 内核重写了 HuggingFace Transformers 中对性能至关重要的部分，带来 **2倍训练速度** 以及 **70% 显存减少** 且准确率零损失。它是即插即用的替代品——只需替换导入，你现有的 TRL/PEFT 脚本无需更改即可运行。

{% hint style="success" %}
所有示例都运行在通过以下方式租用的 GPU 服务器上： [CLORE.AI 市场](https://clore.ai/marketplace).
{% endhint %}

## 主要特性

* **2倍更快的训练** — 用于注意力、RoPE、交叉熵和 RMS 归一化的自定义 Triton 内核
* **— 显存减少 70%** — 智能梯度检查点和内存映射权重
* **即插即用的 HuggingFace 替代品** — 只需改一个导入，别的都不用
* **QLoRA / LoRA / 全量微调** — 开箱即支持所有模式
* **原生导出** — 可直接保存为 GGUF（所有量化类型）、LoRA 适配器，或合并后的 16 位模型
* **广泛的模型覆盖** — Llama 3.x、Mistral、Qwen 2.5、Gemma 2、DeepSeek-R1、Phi-4 等更多模型
* **免费且开源** （Apache 2.0）

## 需求

| 组件     | 最低             | 推荐             |
| ------ | -------------- | -------------- |
| GPU    | RTX 3060 12 GB | RTX 4090 24 GB |
| 显存     | 10 GB          | 24 GB          |
| 内存     | 16 GB          | 32 GB          |
| 磁盘     | 40 GB          | 80 GB          |
| CUDA   | 12.8+          | 12.8+          |
| Python | 3.10           | 3.11           |

**Clore.ai 价格：** RTX 4090 ≈ $0.14–0.42/小时 · RTX 3090 ≈ $0.07–0.21/小时 · RTX 3060 ≈ $0.03–0.07/小时

一个 4 位 QLoRA 的 7B 模型可放入 **约 10 GB 显存**，这使得即使是 RTX 3060 也可胜任。

## 快速开始

### 1. 安装 Unsloth

```bash
# 创建虚拟环境（推荐）
python -m venv /workspace/unsloth-env
source /workspace/unsloth-env/bin/activate

pip install --upgrade pip
pip install "unsloth[colab-new] @ git+https://github.com/unslothai/unsloth.git"
pip install --no-deps trl peft accelerate bitsandbytes xformers
```

### 2. 使用 4 位量化加载模型

```python
from unsloth import FastLanguageModel
import torch

model, tokenizer = FastLanguageModel.from_pretrained(
    model_name="unsloth/Meta-Llama-3.1-8B-Instruct-bnb-4bit",
    max_seq_length=2048,
    dtype=None,            # 自动检测（Ampere 上为 float16，Ada 上为 bfloat16）
    load_in_4bit=True,
)
```

### 3. 应用 LoRA 适配器

```python
model = FastLanguageModel.get_peft_model(
    model,
    r=16,
    target_modules=["q_proj", "k_proj", "v_proj", "o_proj",
                     "gate_proj", "up_proj", "down_proj"],
    lora_alpha=16,
    lora_dropout=0,
    bias="none",
    use_gradient_checkpointing="unsloth",   # 显存减少 70%
    random_state=42,
    use_rslora=False,
    loftq_config=None,
)
```

### 4. 准备数据并训练

```python
from datasets import load_dataset
from trl import SFTTrainer
from transformers import TrainingArguments

dataset = load_dataset("yahma/alpaca-cleaned", split="train")

trainer = SFTTrainer(
    model=model,
    tokenizer=tokenizer,
    train_dataset=dataset,
    dataset_text_field="text",
    max_seq_length=2048,
    dataset_num_proc=2,
    packing=True,
    args=TrainingArguments(
        per_device_train_batch_size=2,
        gradient_accumulation_steps=4,
        warmup_steps=10,
        num_train_epochs=1,
        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",
        seed=42,
        output_dir="/workspace/outputs",
    ),
)

stats = trainer.train()
print(f"Training loss: {stats.training_loss:.4f}")
```

## 导出模型

### 仅保存 LoRA 适配器

```python
model.save_pretrained("/workspace/lora-adapter")
tokenizer.save_pretrained("/workspace/lora-adapter")
```

### 合并并保存完整模型（float16）

```python
model.save_pretrained_merged(
    "/workspace/merged-model",
    tokenizer,
    save_method="merged_16bit",
)
```

### 导出为适用于 Ollama / llama.cpp 的 GGUF

```python
# 量化为 Q4_K_M（大小与质量的良好平衡）
model.save_pretrained_gguf(
    "/workspace/gguf-output",
    tokenizer,
    quantization_method="q4_k_m",
)

# 其他选项：q5_k_m、q8_0、f16
```

导出后，可使用 Ollama 提供服务：

```bash
# 创建一个 Ollama 模型文件
cat > Modelfile <<EOF
FROM /workspace/gguf-output/unsloth.Q4_K_M.gguf
TEMPLATE "{{ .System }}\n{{ .Prompt }}"
PARAMETER temperature 0.7
EOF

ollama create my-finetuned -f Modelfile
ollama run my-finetuned "Summarize the key points of transformers architecture"
```

## 使用示例

### 在自定义聊天数据集上微调

```python
from unsloth.chat_templates import get_chat_template

tokenizer = get_chat_template(tokenizer, chat_template="llama-3.1")

def format_chat(example):
    messages = [
        {"role": "system", "content": "You are a helpful assistant."},
        {"role": "user", "content": example["instruction"]},
        {"role": "assistant", "content": example["output"]},
    ]
    return {"text": tokenizer.apply_chat_template(messages, tokenize=False)}

dataset = dataset.map(format_chat)
```

### DPO / ORPO 对齐训练

```python
from trl import DPOTrainer, DPOConfig

dpo_trainer = DPOTrainer(
    model=model,
    ref_model=None,          # Unsloth 在内部处理参考模型
    args=DPOConfig(
        per_device_train_batch_size=2,
        gradient_accumulation_steps=4,
        learning_rate=5e-6,
        num_train_epochs=1,
        beta=0.1,
        output_dir="/workspace/dpo-output",
    ),
    train_dataset=dpo_dataset,
    tokenizer=tokenizer,
)
dpo_trainer.train()
```

## 显存使用参考

| 模型             | 量化   | 方法    | 显存      | GPU         |
| -------------- | ---- | ----- | ------- | ----------- |
| Llama 3.1 8B   | 4 位  | QLoRA | 约 10 GB | RTX 3060    |
| Llama 3.1 8B   | 16 位 | LoRA  | \~18 GB | RTX 3090    |
| Qwen 2.5 14B   | 4 位  | QLoRA | 约 14 GB | RTX 3090    |
| Mistral 7B     | 4 位  | QLoRA | 约 9 GB  | RTX 3060    |
| DeepSeek-R1 7B | 4 位  | QLoRA | 约 10 GB | RTX 3060    |
| Llama 3.3 70B  | 4 位  | QLoRA | 约 44 GB | 2× RTX 3090 |

## 提示

* **始终使用 `use_gradient_checkpointing="unsloth"`** — 这是最省显存的一项，且是 Unsloth 独有的
* **设置 `lora_dropout=0`** — Unsloth 的 Triton 内核针对零 dropout 做了优化，运行更快
* **使用 `packing=True`** 在 SFTTrainer 中使用，以避免短样本上的填充浪费
* **从 `r=16`** 作为 LoRA 的秩——只有在验证损失停滞时才增加到 32 或 64
* **使用 wandb 监控** — 添加 `report_to="wandb"` 到 TrainingArguments 中用于跟踪损失
* **batch size 调优** — 增加 `per_device_train_batch_size` 直到接近显存上限，然后通过以下参数补偿 `gradient_accumulation_steps`

## 故障排查

| 问题                       | 解决方案                                               |
| ------------------------ | -------------------------------------------------- |
| `OutOfMemoryError` 在训练期间 | 将批大小降为 1，降低 `max_seq_length`，或使用 4 位量化             |
| Triton 内核编译错误            | 运行 `pip install triton --upgrade` 并确保 CUDA 工具包版本匹配 |
| 第一步很慢（正在编译）              | 正常——Triton 会在首次运行时编译内核，之后会缓存                       |
| `bitsandbytes` CUDA 版本错误 | 安装匹配的版本： `pip install bitsandbytes --upgrade`      |
| 训练期间损失飙升                 | 将学习率降至 1e-4，并添加 warmup 步骤                          |
| GGUF 导出崩溃                | 确保有足够的内存（模型大小的 2 倍）和磁盘空间用于转换                       |

## 资源

* [Unsloth GitHub](https://github.com/unslothai/unsloth)
* [Unsloth Wiki — 所有笔记本](https://github.com/unslothai/unsloth/wiki)
* [CLORE.AI 市场](https://clore.ai/marketplace)


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://docs.clore.ai/guides/guides_v2-zh/xun-lian/unsloth-finetune.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
