> ## Documentation Index
> Fetch the complete documentation index at: https://docs.monostate.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# LLM 训练

> 使用 CLI 训练大语言模型

# LLM 训练

`aitraining llm` 命令训练大语言模型，支持多种训练器和技术。

## 快速开始

```bash theme={null}
aitraining llm --train \
  --model google/gemma-3-270m \
  --data-path ./data \
  --project-name my-model \
  --trainer sft
```

## 可用训练器

| 训练器                           | 描述              |
| ----------------------------- | --------------- |
| `default` / `sft` / `generic` | 监督微调            |
| `dpo`                         | 直接偏好优化          |
| `orpo`                        | 优势比偏好优化         |
| `ppo`                         | 近端策略优化          |
| `grpo`                        | 群组相对策略优化（自定义环境） |
| `reward`                      | 奖励模型训练          |
| `distillation`                | 知识蒸馏            |

<Note>
  `generic` 是 `default` 的别名。三者（`default`、`sft`、`generic`）产生相同的行为。
</Note>

<Warning>
  **PPO 训练器要求**：PPO 需要 `--rl-reward-model-path`（训练好的奖励模型路径）或 `--model-ref`（用于 KL 散度的参考模型）。完整文档请参阅 [PPO 训练](/advanced/ppo-rl-training)。
</Warning>

<Warning>
  **GRPO 训练器要求**：GRPO 需要 `--rl-env-module`（Python 模块路径）和 `--rl-env-class`（类名）来指定自定义环境。完整文档请参阅 [GRPO 训练](/advanced/grpo-training)。
</Warning>

## 参数组

参数按逻辑分组：

### 基本参数

| Parameter        | Description             | Default               |
| ---------------- | ----------------------- | --------------------- |
| `--model`        | Base model to fine-tune | `google/gemma-3-270m` |
| `--data-path`    | Path to training data   | `data`                |
| `--project-name` | Output directory name   | `project-name`        |
| `--train-split`  | Training data split     | `train`               |
| `--valid-split`  | Validation data split   | `None`                |

<Note>
  **始终指定这些参数**：虽然 `--model`、`--data-path` 和 `--project-name` 有默认值，但您应该始终根据您的用例明确设置它们。`--project-name` 参数设置输出文件夹 - 使用 `--project-name ./models/my-experiment` 这样的路径来控制训练好的模型保存位置。
</Note>

### 训练配置

| Parameter                 | Description               | Default       |
| ------------------------- | ------------------------- | ------------- |
| `--trainer`               | Training method           | `default`     |
| `--epochs`                | Number of training epochs | `1`           |
| `--batch-size`            | Training batch size       | `2`           |
| `--lr`                    | Learning rate             | `3e-5`        |
| `--mixed-precision`       | fp16/bf16/None            | `None`        |
| `--gradient-accumulation` | Accumulation steps        | `4`           |
| `--warmup-ratio`          | Warmup ratio              | `0.1`         |
| `--optimizer`             | Optimizer                 | `adamw_torch` |
| `--scheduler`             | LR scheduler              | `linear`      |
| `--weight-decay`          | Weight decay              | `0.0`         |
| `--max-grad-norm`         | Max gradient norm         | `1.0`         |
| `--seed`                  | Random seed               | `42`          |

### 检查点与评估

| Parameter                  | Description                                             | Default |
| -------------------------- | ------------------------------------------------------- | ------- |
| `--eval-strategy`          | When to evaluate (`epoch`, `steps`, `no`)               | `epoch` |
| `--save-strategy`          | When to save (`epoch`, `steps`, `no`)                   | `epoch` |
| `--save-steps`             | Save every N steps (if save-strategy=steps)             | `500`   |
| `--save-total-limit`       | Max checkpoints to keep                                 | `1`     |
| `--logging-steps`          | Log every N steps (-1 for auto)                         | `-1`    |
| `--resume-from-checkpoint` | Resume from checkpoint path, or `auto` to detect latest | `None`  |

### 性能与内存

| Parameter                          | Description                                                           | Default |
| ---------------------------------- | --------------------------------------------------------------------- | ------- |
| `--auto-find-batch-size`           | Automatically find optimal batch size                                 | `False` |
| `--disable-gradient-checkpointing` | Disable memory optimization                                           | `False` |
| `--unsloth`                        | Use Unsloth for faster training (SFT only, llama/mistral/gemma/qwen2) | `False` |
| `--use-sharegpt-mapping`           | Use Unsloth's ShareGPT mapping                                        | `False` |
| `--use-flash-attention-2`          | Use Flash Attention 2 for faster training                             | `False` |
| `--attn-implementation`            | Attention implementation (`eager`, `sdpa`, `flash_attention_2`)       | `None`  |

<Note>
  **Unsloth 要求**：Unsloth 仅适用于 `sft`/`default` 训练器和特定模型架构（llama、mistral、gemma、qwen2）。详细信息请参阅 [Unsloth 集成](/advanced/unsloth-integration)。
</Note>

### 后端与分布式

| Parameter               | Description                               | Default |
| ----------------------- | ----------------------------------------- | ------- |
| `--backend`             | Where to run (`local`, `spaces`)          | `local` |
| `--distributed-backend` | Distribution backend (`ddp`, `deepspeed`) | `None`  |
| `--ddp-timeout`         | DDP/NCCL timeout in seconds               | `7200`  |

<Note>
  **多 GPU 行为**：使用多个 GPU 且未设置 `--distributed-backend` 时，会自动使用 DDP。设置 `--distributed-backend deepspeed` 以进行 DeepSpeed Zero-3 优化。训练通过 Accelerate 启动。
</Note>

<Warning>
  **DeepSpeed 检查点**：使用 DeepSpeed 时，模型保存使用 `accelerator.get_state_dict()` 并解包模型。PEFT 适配器保存在 DeepSpeed 下的处理方式不同。
</Warning>

### PEFT/LoRA 参数

| Parameter          | Description               | Default      |
| ------------------ | ------------------------- | ------------ |
| `--peft`           | Enable LoRA training      | `False`      |
| `--lora-r`         | LoRA rank                 | `16`         |
| `--lora-alpha`     | LoRA alpha                | `32`         |
| `--lora-dropout`   | LoRA dropout              | `0.05`       |
| `--target-modules` | Modules to target         | `all-linear` |
| `--quantization`   | int4/int8 quantization    | `None`       |
| `--merge-adapter`  | Merge LoRA after training | `True`       |

### 数据处理

| Parameter                | Description                                                 | Default                |
| ------------------------ | ----------------------------------------------------------- | ---------------------- |
| `--text-column`          | Text column name                                            | `text`                 |
| `--block-size`           | Max sequence length                                         | `-1` (model default)   |
| `--model-max-length`     | Maximum model input length                                  | Auto-detect from model |
| `--padding`              | Padding side (`left` or `right`)                            | `right`                |
| `--add-eos-token`        | Append EOS token                                            | `True`                 |
| `--chat-template`        | Chat template to use                                        | Auto by trainer        |
| `--packing`              | Enable sequence packing (requires flash attention)          | `None`                 |
| `--auto-convert-dataset` | Auto-detect and convert dataset format                      | `False`                |
| `--max-samples`          | Limit dataset size for testing                              | `None`                 |
| `--save-processed-data`  | Save processed data: `auto`, `local`, `hub`, `both`, `none` | `auto`                 |

<Note>
  **聊天模板自动选择**：SFT/DPO/ORPO/Reward 训练器默认为 `tokenizer`（模型的内置模板）。对于纯文本训练，使用 `--chat-template none`。
</Note>

<Note>
  **处理后数据保存**：默认（`auto`），处理后的数据保存在本地 `{project}/data_processed/`。如果源数据集来自 Hub，也会作为私有数据集推送。原始列会重命名为 `_original_*` 以防止冲突。
</Note>

## 训练示例

### 使用 LoRA 的 SFT

```bash theme={null}
aitraining llm --train \
  --model meta-llama/Llama-3.2-1B \
  --data-path ./conversations.jsonl \
  --project-name llama-sft \
  --trainer sft \
  --peft \
  --lora-r 16 \
  --lora-alpha 32 \
  --epochs 3 \
  --batch-size 4
```

### DPO 训练

对于 DPO，您必须指定提示、选择和拒绝响应的列名：

```bash theme={null}
aitraining llm --train \
  --model meta-llama/Llama-3.2-1B \
  --data-path ./preferences.jsonl \
  --project-name llama-dpo \
  --trainer dpo \
  --prompt-text-column prompt \
  --text-column chosen \
  --rejected-text-column rejected \
  --dpo-beta 0.1 \
  --peft \
  --lora-r 16
```

<Warning>
  DPO 和 ORPO 需要指定 `--prompt-text-column` 和 `--rejected-text-column`。
</Warning>

### ORPO 训练

ORPO 结合了 SFT 和偏好优化：

```bash theme={null}
aitraining llm --train \
  --model google/gemma-2-2b \
  --data-path ./preferences.jsonl \
  --project-name gemma-orpo \
  --trainer orpo \
  --prompt-text-column prompt \
  --text-column chosen \
  --rejected-text-column rejected \
  --peft
```

### GRPO 训练

使用自定义奖励环境进行 Group Relative Policy Optimization 训练：

```bash theme={null}
aitraining llm --train \
  --model deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B \
  --trainer grpo \
  --rl-env-module my_envs.hotel_env \
  --rl-env-class HotelEnv \
  --rl-num-generations 4 \
  --rl-max-new-tokens 256 \
  --peft \
  --lr 1e-5
```

<Note>
  GRPO 为每个提示生成多个补全，通过您的环境评分（0-1），并优化策略。有关环境接口详情，请参阅 [GRPO 训练](/advanced/grpo-training)。
</Note>

### 知识蒸馏

训练较小的模型以模仿较大的模型：

```bash theme={null}
aitraining llm --train \
  --model google/gemma-3-270m \
  --teacher-model google/gemma-2-2b \
  --data-path ./prompts.jsonl \
  --project-name distilled-model \
  --use-distillation \
  --distill-temperature 3.0
```

<Note>
  蒸馏默认值：`--distill-temperature 3.0`、`--distill-alpha 0.7`、`--distill-max-teacher-length 512`
</Note>

## 日志记录与监控

### Weights & Biases（默认）

带有 LEET 可视化器的 W\&B 日志记录**默认启用**。LEET 可视化器直接在您的终端中显示实时训练指标。

```bash theme={null}
# W&B is on by default - just run training
aitraining llm --train \
  --model google/gemma-3-270m \
  --data-path ./data \
  --project-name my-model
```

To disable W\&B or the visualizer:

```bash theme={null}
# Disable W&B logging entirely
aitraining llm --train \
  --model google/gemma-3-270m \
  --data-path ./data \
  --project-name my-model \
  --log none

# Keep W&B but disable terminal visualizer
aitraining llm --train \
  --model google/gemma-3-270m \
  --data-path ./data \
  --project-name my-model \
  --no-wandb-visualizer
```

### TensorBoard

```bash theme={null}
aitraining llm --train \
  --model google/gemma-3-270m \
  --data-path ./data \
  --project-name my-model \
  --log tensorboard
```

## 推送到 Hugging Face Hub

上传您训练好的模型：

```bash theme={null}
aitraining llm --train \
  --model google/gemma-3-270m \
  --data-path ./data \
  --project-name my-model \
  --push-to-hub \
  --username your-username \
  --token $HF_TOKEN
```

<Note>
  存储库默认创建为**私有**。默认情况下，存储库将命名为 `{username}/{project-name}`。
</Note>

### 自定义存储库名称或组织

使用 `--repo-id` 推送到特定存储库，适用于：

* 推送到**组织**而不是个人账户
* 使用与本地 `project-name` **不同的存储库名称**

```bash theme={null}
# 推送到组织
aitraining llm --train \
  --model google/gemma-3-270m \
  --data-path ./data \
  --project-name ./local-training-output \
  --push-to-hub \
  --repo-id my-organization/my-custom-model-name \
  --token $HF_TOKEN

# 使用不同名称推送到个人账户
aitraining llm --train \
  --model google/gemma-3-270m \
  --data-path ./data \
  --project-name ./experiment-v3 \
  --push-to-hub \
  --repo-id your-username/production-model \
  --token $HF_TOKEN
```

| 参数                                   | 描述                           | 默认值                         |
| ------------------------------------ | ---------------------------- | --------------------------- |
| `--push-to-hub`                      | 启用推送到 Hub                    | `False`                     |
| `--hub-private` / `--no-hub-private` | 创建仓库为私有或公开                   | `True`（私有）                  |
| `--username`                         | HF 用户名（用于默认存储库命名）            | `None`                      |
| `--token`                            | HF API 令牌                    | `None`                      |
| `--repo-id`                          | 完整存储库 ID（如 `org/model-name`） | `{username}/{project-name}` |

<Warning>
  使用 `--repo-id` 时，不需要 `--username`，因为存储库 ID 已经指定了目标位置。但是，您仍然需要 `--token` 进行身份验证。
</Warning>

## 高级选项

### 超参数扫描

```bash theme={null}
aitraining llm --train \
  --model google/gemma-3-270m \
  --data-path ./data \
  --project-name sweep-experiment \
  --use-sweep \
  --sweep-backend optuna \
  --sweep-n-trials 10
```

### 增强评估

```bash theme={null}
aitraining llm --train \
  --model google/gemma-3-270m \
  --data-path ./data \
  --project-name my-model \
  --use-enhanced-eval \
  --eval-metrics "perplexity,bleu"
```

## 查看所有参数

查看特定训练器的所有参数：

```bash theme={null}
aitraining llm --trainer sft --help
aitraining llm --trainer dpo --help
```

## 下一步

<CardGroup cols={2}>
  <Card title="YAML 配置" href="/cli/yaml-configs">
    使用配置文件
  </Card>

  <Card title="DPO 训练" href="/advanced/dpo-training">
    深入了解 DPO
  </Card>

  <Card title="LoRA/PEFT" href="/advanced/lora-peft">
    高效微调
  </Card>

  <Card title="蒸馏" href="/advanced/prompt-distillation">
    知识蒸馏
  </Card>

  <Card title="GRPO 训练" href="/advanced/grpo-training">
    使用自定义环境的 RL
  </Card>
</CardGroup>
