> 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/axolotl-training.md).

# Axolotl 通用微调

在 Clore.ai 上使用 Axolotl 进行基于 YAML 的 LLM 微调——LoRA、QLoRA、DPO、多 GPU

Axolotl 将 HuggingFace Transformers、PEFT、TRL 和 DeepSpeed 封装成一个由 YAML 驱动的统一接口。你只需在一个配置文件中定义模型、数据集、训练方法和超参数，然后用一条命令启动。标准工作流无需编写 Python 脚本。

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

## 主要特性

* **仅使用 YAML 的配置** —— 在一个文件中定义一切，无需 Python
* **所有训练方法** —— LoRA、QLoRA、全量微调、DPO、ORPO、KTO、RLHF
* **开箱即用的多 GPU 支持** —— 通过一个标志即可使用 DeepSpeed ZeRO 1/2/3 和 FSDP
* **样本打包** —— 将短样本连接起来以填满序列长度，吞吐量提升 3–5 倍
* **Flash Attention 2** —— 在受支持的硬件上自动节省显存
* **广泛的模型支持** —— Llama 3.x、Mistral、Qwen 2.5、Gemma 2、Phi-4、DeepSeek、Falcon
* **内置数据集格式** —— alpaca、sharegpt、chat\_template、completion 和自定义

## 需求

| 组件     | 最低             | 推荐                  |
| ------ | -------------- | ------------------- |
| GPU    | RTX 3060 12 GB | RTX 4090 24 GB（×2+） |
| 显存     | 12 GB          | 24+ GB              |
| 内存     | 16 GB          | 64 GB               |
| 磁盘     | 50 GB          | 100 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/小时

## 快速开始

### 1. 安装 Axolotl

```bash
# 克隆并安装
git clone https://github.com/OpenAccess-AI-Collective/axolotl.git
cd axolotl

pip install packaging ninja
pip install -e '.[flash-attn,deepspeed]'
```

或者使用 Docker 镜像（为保证可复现性，推荐）：

```bash
docker run --gpus all -it --rm \
  -v /workspace:/workspace \
  winglian/axolotl:main-latest
```

### 2. 创建配置文件

将其保存为 `config.yml`:

```yaml
base_model: meta-llama/Meta-Llama-3.1-8B-Instruct
model_type: LlamaForCausalLM
tokenizer_type: AutoTokenizer

load_in_4bit: true
adapter: qlora
lora_r: 32
lora_alpha: 16
lora_dropout: 0.05
lora_target_linear: true

datasets:
  - path: yahma/alpaca-cleaned
    type: alpaca

sequence_len: 2048
sample_packing: true
pad_to_sequence_len: true

wandb_project: axolotl-clore
wandb_name: llama3-qlora

output_dir: /workspace/axolotl-output

gradient_accumulation_steps: 4
micro_batch_size: 2
num_epochs: 1
learning_rate: 2e-4
optimizer: adamw_bnb_8bit
lr_scheduler: cosine
warmup_steps: 10

bf16: auto
flash_attention: true
gradient_checkpointing: true

logging_steps: 10
save_strategy: steps
save_steps: 500
eval_steps: 500

evals_per_epoch:
val_set_size: 0.02
```

### 3. 启动训练

```bash
# 单 GPU
accelerate launch -m axolotl.cli.train config.yml

# 多 GPU（所有可用 GPU）
accelerate launch --multi_gpu -m axolotl.cli.train config.yml
```

训练进度日志输出到 stdout，并可选输出到 Weights & Biases。

## 配置深度解析

### 数据集格式

Axolotl 原生支持多种输入格式：

```yaml
# Alpaca 风格（instruction / input / output）
datasets:
  - path: yahma/alpaca-cleaned
    type: alpaca

# ShareGPT 多轮对话
datasets:
  - path: anon8231489123/ShareGPT_Vicuna_unfiltered
    type: sharegpt
    conversation: chatml

# 对话模板（从 tokenizer 自动检测）
datasets:
  - path: HuggingFaceH4/ultrachat_200k
    type: chat_template
    field_messages: messages
    message_field_role: role
    message_field_content: content

# 本地 JSONL 文件
datasets:
  - path: /workspace/data/my_dataset.jsonl
    type: alpaca
    ds_type: json
```

### 使用 DeepSpeed 的多 GPU

创建 `deepspeed_zero2.json`:

```json
{
  "bf16": { "enabled": true },
  "zero_optimization": {
    "stage": 2,
    "offload_optimizer": { "device": "cpu" },
    "allgather_partitions": true,
    "allgather_bucket_size": 5e8,
    "reduce_scatter": true,
    "reduce_bucket_size": 5e8,
    "overlap_comm": true,
    "contiguous_gradients": true
  },
  "train_micro_batch_size_per_gpu": "auto",
  "gradient_accumulation_steps": "auto",
  "gradient_clipping": 1.0
}
```

添加到你的配置中：

```yaml
deepspeed: deepspeed_zero2.json
```

然后启动：

```bash
accelerate launch --num_processes 4 -m axolotl.cli.train config.yml
```

### DPO / ORPO 对齐

```yaml
base_model: meta-llama/Meta-Llama-3.1-8B-Instruct
rl: dpo
# 或：rl: orpo

datasets:
  - path: argilla/ultrafeedback-binarized-preferences
    type: chat_template.default
    field_messages: chosen
    field_chosen: chosen
    field_rejected: rejected

dpo_beta: 0.1
```

### 全量微调（无 LoRA）

```yaml
base_model: meta-llama/Meta-Llama-3.1-8B-Instruct

# 无适配器，无量化
adapter:
load_in_4bit: false
load_in_8bit: false

learning_rate: 5e-6
micro_batch_size: 1
gradient_accumulation_steps: 8
gradient_checkpointing: true
flash_attention: true
bf16: auto

deepspeed: deepspeed_zero3.json  # 8B+ 全量微调所需
```

## 使用示例

### 训练后推理

```bash
# 启动交互式推理
accelerate launch -m axolotl.cli.inference config.yml \
  --lora_model_dir /workspace/axolotl-output
```

### 将 LoRA 合并到基础模型

```bash
accelerate launch -m axolotl.cli.merge_lora config.yml \
  --lora_model_dir /workspace/axolotl-output \
  --output_dir /workspace/merged-model
```

### 预处理数据集（训练前验证）

```bash
python -m axolotl.cli.preprocess config.yml
```

这会对数据集进行分词并验证。适合在长时间训练前捕获格式错误。

## 显存使用参考

| 模型            | 方法         | GPU | 显存/显卡   | 配置                       |
| ------------- | ---------- | --- | ------- | ------------------------ |
| Llama 3.1 8B  | QLoRA 4bit | 1   | 约 12 GB | r=32, seq\_len=2048      |
| Llama 3.1 8B  | LoRA 16bit | 1   | 约 20 GB | r=16, seq\_len=2048      |
| Llama 3.1 8B  | 完整         | 2   | 约 22 GB | DeepSpeed ZeRO-3         |
| Qwen 2.5 14B  | QLoRA 4bit | 1   | \~16 GB | r=16, seq\_len=2048      |
| Llama 3.3 70B | QLoRA 4bit | 2   | 约 22 GB | r=16, seq\_len=2048      |
| Llama 3.3 70B | 完整         | 4   | 约 40 GB | DeepSpeed ZeRO-3+offload |

## 提示

* **始终启用 `sample_packing: true`** —— 单次提升最大的吞吐量改进（在短数据集上提升 3–5 倍）
* **使用 `flash_attention: true`** 在 Ampere+ GPU 上可节省 20–40% 显存
* **从 QLoRA 开始** 用于实验，只有当 LoRA 的效果达到瓶颈后再切换到全量微调
* **设置 `val_set_size: 0.02`** 用于在训练期间监控过拟合
* **先做预处理** —— 运行 `axolotl.cli.preprocess` 以在开始长时间运行前验证数据格式
* **使用 Docker 镜像** 用于可复现环境——避免依赖冲突
* **`lora_target_linear: true`** 将 LoRA 应用于所有线性层，通常比只针对注意力层更好

## 故障排查

| 问题                            | 解决方案                                                   |
| ----------------------------- | ------------------------------------------------------ |
| `OutOfMemoryError`            | 将 `micro_batch_size` 降低到 1，启用 `gradient_checkpointing` |
| 数据集格式错误                       | 运行 `python -m axolotl.cli.preprocess config.yml` 以进行调试 |
| `sample_packing` 第一个 epoch 较慢 | 正常——初始打包计算只需一次                                         |
| 多 GPU 训练卡住                    | 检查 NCCL： `export NCCL_DEBUG=INFO`，确保所有 GPU 都可见         |
| `flash_attention` 导入错误        | 安装： `pip install flash-attn --no-build-isolation`      |
| 损失没有下降                        | 将学习率降到 1e-4，增加 warmup，检查数据集质量                          |
| WandB 连接错误                    | 运行 `wandb login` 或者设置 `wandb_project:` 为空字符串           |

## 资源

* [Axolotl GitHub](https://github.com/OpenAccess-AI-Collective/axolotl)
* [示例配置](https://github.com/OpenAccess-AI-Collective/axolotl/tree/main/examples)
* [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/axolotl-training.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.
