> ## 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.

# 量化

> 使用量化训练减少内存

# 量化

量化通过使用较低精度存储模型权重来减少内存使用。

## 快速开始

```bash theme={null}
aitraining llm --train \
  --model meta-llama/Llama-3.2-8B \
  --data-path ./data.jsonl \
  --project-name quantized-model \
  --peft \
  --quantization int4
```

## Python API

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

params = LLMTrainingParams(
    model="meta-llama/Llama-3.2-8B",
    data_path="./data.jsonl",
    project_name="quantized-model",

    peft=True,
    quantization="int4",  # or "int8"
    lora_r=16,
)
```

## 量化选项

| 选项   | 内存减少  | 质量  |
| ---- | ----- | --- |
| None | 0%    | 最佳  |
| int8 | \~50% | 非常好 |
| int4 | \~75% | 良好  |

## 支持的任务

量化可用于：

| 任务      | Params 类            | 备注   |
| ------- | ------------------- | ---- |
| LLM     | `LLMTrainingParams` | 完全支持 |
| VLM     | `VLMTrainingParams` | 完全支持 |
| Seq2Seq | `Seq2SeqParams`     | 完全支持 |

### 4-bit (QLoRA)

最大内存节省：

```python theme={null}
params = LLMTrainingParams(
    ...
    quantization="int4",
)
```

### 8-bit

更好的质量，节省较少：

```python theme={null}
params = LLMTrainingParams(
    ...
    quantization="int8",
)
```

## 内存要求

### Llama 3.2 8B

| 配置          | 所需 VRAM |
| ----------- | ------- |
| 全精度         | \~64 GB |
| LoRA (fp16) | \~18 GB |
| LoRA + 8bit | \~12 GB |
| LoRA + 4bit | \~8 GB  |

### Gemma 2 27B

| 配置          | 所需 VRAM  |
| ----------- | -------- |
| 全精度         | \~108 GB |
| LoRA + 4bit | \~20 GB  |

## 最佳实践

### 与 LoRA 一起使用

量化**需要**启用 PEFT/LoRA：

```python theme={null}
params = LLMTrainingParams(
    ...
    peft=True,  # Required for quantized training
    quantization="int4",
)
```

<Warning>
  量化仅在 `peft=True` 时有效。如果未启用 PEFT，量化设置将被忽略。
</Warning>

### 调整学习率

量化训练通常受益于比默认值（`3e-5`）更高的学习率：

```python theme={null}
params = LLMTrainingParams(
    ...
    peft=True,
    quantization="int4",
    lr=2e-4,  # Higher LR works well with QLoRA
)
```

### 使用 Flash Attention

与 [Flash Attention](/advanced/flash-attention) 结合以提高速度：

```python theme={null}
params = LLMTrainingParams(
    ...
    quantization="int4",
    use_flash_attention_2=True,  # Requires Linux + CUDA + flash-attn package
)
```

## 使用量化模型进行推理

加载量化模型进行推理：

```python theme={null}
import torch
from transformers import AutoModelForCausalLM, BitsAndBytesConfig

# 4-bit config (matches AITraining defaults)
bnb_config = BitsAndBytesConfig(
    load_in_4bit=True,
    bnb_4bit_quant_type="nf4",
    bnb_4bit_compute_dtype=torch.float16,
    bnb_4bit_use_double_quant=False,
)

model = AutoModelForCausalLM.from_pretrained(
    "meta-llama/Llama-3.2-8B",
    quantization_config=bnb_config,
)
```

## 平台要求

<Warning>
  **量化仅在 Linux 上有效。** int4/int8 量化所需的 `bitsandbytes` 库仅在 Linux 系统上可用。
</Warning>

## Apple Silicon (MPS) 注意事项

量化**与 Apple Silicon MPS 不兼容**。在 M1/M2/M3 Mac 上使用量化时：

* 训练自动回退到 CPU
* 您会看到解释此情况的警告消息
* 要在 Mac 上更快训练，请跳过量化并仅使用 LoRA

```bash theme={null}
# 在 Apple Silicon 上 - 使用 LoRA 而不使用量化以获得 MPS 加速
aitraining llm --train \
  --model google/gemma-3-270m \
  --data-path ./data.jsonl \
  --project-name mac-training \
  --peft \
  --lora-r 16
```

用于手动控制的环境变量：

* `AUTOTRAIN_DISABLE_MPS=1` - 强制 CPU 训练
* `AUTOTRAIN_ENABLE_MPS=1` - 即使使用量化也强制 MPS（可能崩溃）

## 质量考虑

量化确实会略微降低质量。对于关键应用：

1. 在您的特定任务上测试
2. 与全精度基线进行比较
3. 如果质量更重要，考虑使用 8-bit

## 下一步

<CardGroup cols={2}>
  <Card title="LoRA/PEFT" href="/advanced/lora-peft">
    高效微调
  </Card>

  <Card title="Flash Attention" href="/advanced/flash-attention">
    速度优化
  </Card>
</CardGroup>
