> ## 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 端点

> 用于训练大语言模型的 API

# LLM 训练 API

LLM 训练的完整 API 参考。

## LLMTrainingParams

LLM 训练的主要配置类。

```python theme={null}
from autotrain.trainers.clm.params import LLMTrainingParams
```

### 基本参数

```python theme={null}
params = LLMTrainingParams(
    # Core parameters (always specify these)
    model="google/gemma-3-270m",       # Default: "google/gemma-3-270m"
    data_path="./data.jsonl",          # Default: "data"
    project_name="my-model",           # Default: "project-name"

    # Data splits
    train_split="train",               # Default: "train"
    valid_split=None,                  # Default: None
    max_samples=None,                  # Default: None (use all)
)
```

### 训练器选择

```python theme={null}
params = LLMTrainingParams(
    model="google/gemma-3-270m",
    data_path="./data.jsonl",
    project_name="my-model",

    trainer="sft",  # Default: "default" (pretraining). Options: sft, dpo, orpo, ppo, grpo, reward
)
```

### 训练超参数

```python theme={null}
params = LLMTrainingParams(
    model="google/gemma-3-270m",
    data_path="./data.jsonl",
    project_name="my-model",

    # Core hyperparameters (showing defaults)
    epochs=1,           # Default: 1
    batch_size=2,       # Default: 2
    lr=3e-5,            # Default: 3e-5
    warmup_ratio=0.1,   # Default: 0.1
    gradient_accumulation=4,  # Default: 4
    weight_decay=0.0,   # Default: 0.0
    max_grad_norm=1.0,  # Default: 1.0

    # Precision
    mixed_precision=None,  # Default: None (options: bf16, fp16, None)

    # Optimization
    optimizer="adamw_torch",  # Default: adamw_torch
    scheduler="linear",       # Default: linear
    seed=42,                  # Default: 42
)
```

### PEFT/LoRA 配置

```python theme={null}
params = LLMTrainingParams(
    model="meta-llama/Llama-3.2-1B",
    data_path="./data.jsonl",
    project_name="my-model",

    # Enable LoRA (default: False)
    peft=True,
    lora_r=16,           # Default: 16
    lora_alpha=32,       # Default: 32
    lora_dropout=0.05,   # Default: 0.05
    target_modules="all-linear",  # Default: all-linear

    # Quantization (optional)
    quantization="int4",  # Options: int4, int8, or None (default: None)

    # Merge after training (default is True - LoRA merged automatically)
    merge_adapter=True,
)
```

### 数据处理

```python theme={null}
params = LLMTrainingParams(
    model="google/gemma-3-270m",
    data_path="./data.jsonl",
    project_name="my-model",

    # Text processing
    text_column="text",
    block_size=-1,            # Default: -1 (model default)
    model_max_length=2048,    # 从模型配置自动检测（见下方说明）
    add_eos_token=True,       # Default: True
    padding="right",          # Default: "right"

    # Chat format
    chat_template=None,       # Auto-detect or specify
    apply_chat_template=True, # Default: True

    # Efficiency
    packing=None,             # Default: None (set True to enable)
    use_flash_attention_2=False,  # Default: False
    attn_implementation=None,     # Default: None
)
```

<Note>
  **model\_max\_length 自动检测**：此参数现在会从模型配置中自动检测。例如，Gemma 2（8192 tokens）和 Gemma 3（32K-128K tokens，取决于变体）将自动使用其原生上下文长度。默认值 2048 仅在自动检测失败时作为后备使用。显式设置可覆盖。
</Note>

### DPO 参数

```python theme={null}
params = LLMTrainingParams(
    model="meta-llama/Llama-3.2-1B",
    data_path="./preferences.jsonl",
    project_name="my-model",

    trainer="dpo",

    # DPO-specific
    dpo_beta=0.1,              # Default: 0.1
    max_prompt_length=128,     # Default: 128
    max_completion_length=None, # Default: None

    # Reference model (optional)
    model_ref=None,  # Uses same as model if None

    # Data columns (required for DPO)
    prompt_text_column="prompt",
    text_column="chosen",
    rejected_text_column="rejected",
)
```

### ORPO 参数

```python theme={null}
params = LLMTrainingParams(
    model="google/gemma-2-2b",
    data_path="./preferences.jsonl",
    project_name="my-model",

    trainer="orpo",

    # ORPO-specific
    dpo_beta=0.1,              # Default: 0.1
    max_prompt_length=128,     # Default: 128
    max_completion_length=None, # Default: None

    # Data columns (required for ORPO)
    prompt_text_column="prompt",
    text_column="chosen",
    rejected_text_column="rejected",
)
```

### GRPO 参数

```python theme={null}
params = LLMTrainingParams(
    model="deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B",
    project_name="grpo-agent",

    trainer="grpo",

    # GRPO 特定参数（必需）
    rl_env_module="my_envs.hotel_env",   # 环境的 Python 模块路径
    rl_env_class="HotelEnv",             # 环境模块中的类名
    rl_num_generations=4,                # Default: 4 — 每个提示的补全数量

    # 共享 RL 参数（PPO 和 GRPO 共用）
    rl_kl_coef=0.1,           # Default: 0.1 — KL 散度惩罚（beta）
    rl_clip_range=0.2,        # Default: 0.2 — 裁剪范围（epsilon）
    rl_env_config=None,       # Default: None — 环境构造函数的 JSON 配置
    rl_max_new_tokens=256,    # Default: 128 — 每个补全的最大 token 数
    rl_top_k=50,              # Default: 50
    rl_top_p=1.0,             # Default: 1.0
    rl_temperature=1.0,       # Default: 1.0

    # vLLM 加速（可选）
    use_vllm=False,                    # Default: False — 启用 vLLM 加速生成
    vllm_mode="colocate",              # Default: "colocate" — 或 "server"
    vllm_gpu_memory_utilization=0.3,   # Default: 0.3 — vLLM 的 GPU 内存占比（colocate）
    vllm_server_url=None,              # Default: None — vLLM 服务器 URL（server 模式）
    vllm_tensor_parallel_size=1,       # Default: 1 — vLLM 张量并行 GPU 数量
    vllm_server_gpus=1,                # Default: 1 — vLLM 服务器预留 GPU
)
```

<Note>
  GRPO 不需要 `data_path` — 数据集由环境的 `build_dataset()` 方法构建。安装 `pip install aitraining[vllm]` 以获得 vLLM 支持。
</Note>

<Note>
  有关完整的环境接口（`build_dataset`、`score_episode`、`get_tools`），请参阅 [GRPO 训练](/advanced/grpo-training)。
</Note>

### 知识蒸馏

```python theme={null}
params = LLMTrainingParams(
    model="google/gemma-3-270m",           # Student
    teacher_model="google/gemma-2-2b",     # Teacher
    data_path="./prompts.jsonl",
    project_name="distilled-model",

    use_distillation=True,
    distill_temperature=3.0,   # Default: 3.0
    distill_alpha=0.7,         # Default: 0.7
    distill_max_teacher_length=512,  # Default: 512
)
```

### 日志记录和保存

```python theme={null}
params = LLMTrainingParams(
    model="google/gemma-3-270m",
    data_path="./data.jsonl",
    project_name="my-model",

    # Logging
    log="wandb",  # wandb, tensorboard, or None (default: wandb)
    logging_steps=-1,     # Default: -1 (auto)
    wandb_visualizer=True,  # Terminal visualizer
    wandb_token=None,       # W&B API token (optional)

    # Checkpointing
    save_strategy="steps",  # steps or epoch (default: epoch)
    save_steps=500,
    save_total_limit=1,   # Default: 1
    eval_strategy="steps",
)
```

### Hub 集成

```python theme={null}
params = LLMTrainingParams(
    model="google/gemma-3-270m",
    data_path="./data.jsonl",
    project_name="my-model",

    # Push to Hub
    push_to_hub=True,
    username="your-username",
    token="hf_...",
)
```

## 运行训练

```python theme={null}
from autotrain.project import AutoTrainProject

# Create and run project
project = AutoTrainProject(
    params=params,
    backend="local",
    process=True
)

job_id = project.create()
```

## 完整示例

```python theme={null}
from autotrain.trainers.clm.params import LLMTrainingParams
from autotrain.project import AutoTrainProject

# Full configuration
params = LLMTrainingParams(
    # Model
    model="meta-llama/Llama-3.2-1B",
    project_name="llama-production",

    # Data
    data_path="./conversations.jsonl",
    train_split="train",
    valid_split="validation",
    text_column="text",
    block_size=2048,

    # Training
    trainer="sft",
    epochs=3,
    batch_size=2,
    gradient_accumulation=8,
    lr=2e-5,
    warmup_ratio=0.1,
    mixed_precision="bf16",

    # LoRA
    peft=True,
    lora_r=32,
    lora_alpha=64,
    lora_dropout=0.05,

    # Optimization
    use_flash_attention_2=True,
    packing=True,
    auto_find_batch_size=True,
    unsloth=False,  # Use Unsloth for faster training

    # Distribution (for multi-GPU)
    distributed_backend=None,  # None for auto (DDP), or "deepspeed"

    # Logging
    log="wandb",
    logging_steps=-1,
    save_strategy="steps",
    save_steps=500,
    save_total_limit=1,

    # Hub
    push_to_hub=True,
    username="my-username",
    token="hf_...",
)

# Run training
project = AutoTrainProject(
    params=params,
    backend="local",
    process=True
)
job_id = project.create()
```

## 下一步

<CardGroup cols={2}>
  <Card title="Python SDK" href="/api/python-sdk">
    完整 SDK 参考
  </Card>

  <Card title="DPO Training" href="/advanced/dpo-training">
    DPO 深入解析
  </Card>
</CardGroup>
