# 故障排查与常见问题

如果您仍遇到与版本或依赖项相关的问题，请使用我们的 [Docker 映像](https://unsloth.ai/docs/zh/kai-shi-shi-yong/install/docker) 其中会预装所有内容。

{% hint style="success" %}
**如果您发现任何问题，请始终尝试更新 Unsloth。**

`pip install --upgrade --force-reinstall --no-cache-dir --no-deps unsloth unsloth_zoo`
{% endhint %}

### 要微调 Unsloth 不支持的新模型？

Unsloth 支持任何由 `transformers`支持的模型。如果某个模型不在我们的上传列表中或不能开箱即用，通常仍然受支持；一些较新的模型可能由于我们的优化需要少量手动调整。

在大多数情况下，您可以通过设置来启用兼容性： `trust_remote_code=True` 在您的微调脚本中。下面是使用的示例： [DeepSeek-OCR](https://unsloth.ai/docs/zh/mo-xing/tutorials/deepseek-ocr-how-to-run-and-fine-tune):

<pre class="language-python" data-expandable="true"><code class="lang-python">from huggingface_hub import snapshot_download
snapshot_download("unsloth/DeepSeek-OCR", local_dir = "deepseek_ocr")
model, tokenizer = FastVisionModel.from_pretrained(
    "./deepseek_ocr",
    load_in_4bit = False, # 使用 4bit 可减少内存使用。16bit LoRA 请设为 False。
    auto_model = AutoModel,
    <a data-footnote-ref href="#user-content-fn-1">trust_remote_code = True</a>, # 启用以支持新模型
    unsloth_force_compile = True,
    use_gradient_checkpointing = "unsloth", # 对于长上下文可设为 True 或 "unsloth"
)
</code></pre>

### 在 Unsloth 中运行效果良好，但导出并在其他平台运行后结果很差

您有时可能会遇到这样的问题：模型在 Unsloth 中运行并产生良好结果，但当您在 Ollama 或 vLLM 等其他平台上使用时，结果很差，或者得到无意义文本、无限生成 *或* 重复输&#x51FA;**.**

* 此错误最常见的原因是使用了 <mark style="background-color:blue;">**不正确的聊天模板**</mark>**.** 在 Unsloth 中训练模型时以及之后在 llama.cpp 或 Ollama 等其他框架中运行时，必须使用与训练时相同的聊天模板。从已保存模型进行推理时，应用正确的模板至关重要。
* 也可能是您的推理引擎添加了不必要的“序列开始”标记（或相反地缺少该标记），因此请务必同时检查这两种情况！
* <mark style="background-color:green;">**使用我们的会话笔记本强制设置聊天模板——这将修复大多数问题。**</mark>
  * Qwen-3 14B 会话笔记本 [**在 Colab 中打开**](https://colab.research.google.com/github/unslothai/notebooks/blob/main/nb/Qwen3_\(14B\)-Reasoning-Conversational.ipynb)
  * Gemma-3 4B 会话笔记本 [**在 Colab 中打开**](https://colab.research.google.com/github/unslothai/notebooks/blob/main/nb/Gemma3_\(4B\).ipynb)
  * Llama-3.2 3B 会话笔记本 [**在 Colab 中打开**](https://colab.research.google.com/github/unslothai/notebooks/blob/main/nb/Llama3.2_\(1B_and_3B\)-Conversational.ipynb)
  * Phi-4 14B 会话笔记本 [**在 Colab 中打开**](https://colab.research.google.com/github/unslothai/notebooks/blob/main/nb/Phi_4-Conversational.ipynb)
  * Mistral v0.3 7B 会话笔记本 [**在 Colab 中打开**](https://colab.research.google.com/github/unslothai/notebooks/blob/main/nb/Mistral_v0.3_\(7B\)-Conversational.ipynb)
  * **更多笔记本请见我们的** [**笔记本文档**](https://unsloth.ai/docs/zh/kai-shi-shi-yong/unsloth-notebooks)

### 保存为 GGUF / vLLM 16bit 崩溃

您可以尝试在保存期间通过更改来降低最大 GPU 使用率： `maximum_memory_usage`.

默认值是 `model.save_pretrained(..., maximum_memory_usage = 0.75)`。将其降低到例如 0.5 以使用 50% 的 GPU 峰值内存或更低。这可以减少保存过程中的 OOM 崩溃。

### 如何手动保存为 GGUF？

首先通过以下方式将模型保存为 16bit：

```python
model.save_pretrained_merged("merged_model", tokenizer, save_method = "merged_16bit",)
```

像下面这样从源码编译 llama.cpp：

```bash
apt-get update
apt-get install pciutils build-essential cmake curl libcurl4-openssl-dev -y
git clone https://github.com/ggerganov/llama.cpp
cmake llama.cpp -B llama.cpp/build \
    -DBUILD_SHARED_LIBS=ON -DGGML_CUDA=ON -DLLAMA_CURL=ON
cmake --build llama.cpp/build --config Release -j --clean-first --target llama-quantize llama-cli llama-gguf-split llama-mtmd-cli
cp llama.cpp/build/bin/llama-* llama.cpp
```

然后，将模型保存为 F16：

```bash
python llama.cpp/convert_hf_to_gguf.py merged_model \
    --outfile model-F16.gguf --outtype f16 \
    --split-max-size 50G
```

```bash
# 对于 BF16：
python llama.cpp/convert_hf_to_gguf.py merged_model \
    --outfile model-BF16.gguf --outtype bf16 \
    --split-max-size 50G
    
# 对于 Q8_0：
python llama.cpp/convert_hf_to_gguf.py merged_model \
    --outfile model-Q8_0.gguf --outtype q8_0 \
    --split-max-size 50G
```

### 为什么 Q8\_K\_XL 比 Q8\_0 GGUF 慢？

在 Mac 设备上，BF16 似乎可能比 F16 更慢。Q8\_K\_XL 会将某些层提升为 BF16，因此导致变慢。我们正在积极更改转换流程，使 F16 成为 Q8\_K\_XL 的默认选择以减少性能损失。

### 如何进行评估

要在训练过程中设置评估，您首先必须将数据集拆分为训练集和测试集。您应该 <mark style="background-color:green;">**始终对数据集的选择进行洗牌**</mark>，否则您的评估结果将不正确！

```python
new_dataset = dataset.train_test_split(
    test_size = 0.01, # 1% 用于测试集，也可以是行数的整数
    shuffle = True, # 应始终设置为 True！
    seed = 3407,
)

train_dataset = new_dataset["train"] # 训练用数据集
eval_dataset = new_dataset["test"] # 评估用数据集
```

然后，我们可以设置训练参数以启用评估。提醒：如果您设置了 `eval_steps = 1` 这意味着您在每一步都进行评估，这会非常非常慢。如果是这样，尝试将 eval\_dataset 大小减小到例如 100 行左右。

```python
from trl import SFTTrainer, SFTConfig
trainer = SFTTrainer(
    args = SFTConfig(
        fp16_full_eval = True,         # 设置此项以减少内存使用
        per_device_eval_batch_size = 2,# 增大此值会使用更多内存
        eval_accumulation_steps = 4,   # 您可以增加此项来包含更大的 batch_size
        eval_strategy = "steps",       # 每隔若干步或若干轮运行评估。
        eval_steps = 1,                # 每多少训练步执行一次评估
    ),
    train_dataset = new_dataset["train"],
    eval_dataset = new_dataset["test"],
    ...
)
trainer.train()
```

### 评估循环 - 内存不足或崩溃。

OOM 的常见原因是您将批量大小设置得过高。将其设置为低于 2 以使用更少的显存。同时使用 `fp16_full_eval=True` 在评估时使用 float16，这可将内存减少一半。

首先将训练数据集拆分为训练集和测试集。将 trainer 的评估设置为：

```python
new_dataset = dataset.train_test_split(test_size = 0.01)

from trl import SFTTrainer, SFTConfig
trainer = SFTTrainer(
    args = SFTConfig(
        fp16_full_eval = True,
        per_device_eval_batch_size = 2,
        eval_accumulation_steps = 4,
        eval_strategy = "steps",
        eval_steps = 1,
    ),
    train_dataset = new_dataset["train"],
    eval_dataset = new_dataset["test"],
    ...
)
```

这将避免 OOM 并使其略快一些。您也可以在 bf16 机器上使用 `bf16_full_eval=True` 默认情况下，截至 2025 年 6 月，Unsloth 应该已将这些标志默认开启。

### 如何实现早停（Early Stopping）？

如果您想在评估损失不再下降时停止微调/训练运行，可以使用早停来终止训练过程。使用 `EarlyStoppingCallback`.

像往常一样，设置您的 trainer 和评估数据集。下面用于在 `eval_loss` （评估损失）在大约 3 次评估后没有下降时停止训练运行。

```python
from trl import SFTConfig, SFTTrainer
trainer = SFTTrainer(
    args = SFTConfig(
        fp16_full_eval = True,
        per_device_eval_batch_size = 2,
        eval_accumulation_steps = 4,
        output_dir = "training_checkpoints", # 用于早停的已保存检查点位置
        save_strategy = "steps",             # 每 N 步保存模型
        save_steps = 10,                     # 多少步后我们保存模型
        save_total_limit = 3,                # 最多只保留 3 个已保存检查点以节省磁盘空间
        eval_strategy = "steps",             # 每 N 步评估一次
        eval_steps = 10,                     # 多少步后进行一次评估
        load_best_model_at_end = True,       # 早停必须使用
        metric_for_best_model = "eval_loss", # 我们用于早停的指标
        greater_is_better = False,           # 评估损失越低越好
    ),
    model = model,
    tokenizer = tokenizer,
    train_dataset = new_dataset["train"],
    eval_dataset = new_dataset["test"],
)
```

然后我们添加回调，该回调也可以自定义：

```python
from transformers import EarlyStoppingCallback
early_stopping_callback = EarlyStoppingCallback(
    early_stopping_patience = 3,     # 如果评估损失不下降，我们将等待多少次评估步
                                     # 例如损失可能会上升，但在 3 次评估后下降
    early_stopping_threshold = 0.0,  # 可以设置更高——设定在多大幅度的损失下降后
                                     # 我们才认为满足早停条件。例如 0.01 表示若损失从
                                     # 0.02 下降到 0.01，我们将考虑早停。
)
trainer.add_callback(early_stopping_callback)
```

然后像往常一样训练模型： `trainer.train() .`

### 下载卡在 90% 到 95%

如果您的模型在 90%、95% 处长时间卡住，您可以禁用一些快速下载过程以强制下载同步并打印更多错误信息。

只需使用 `UNSLOTH_STABLE_DOWNLOADS=1` 在任何 Unsloth 导入之前。

```python
import os
os.environ["UNSLOTH_STABLE_DOWNLOADS"] = "1"

from unsloth import FastLanguageModel
```

### RuntimeError: CUDA error: device-side assert triggered

重启并运行全部，但将此放在任何 Unsloth 导入之前。此外请尽快提交错误报告，谢谢！

```python
import os
os.environ["UNSLOTH_COMPILE_DISABLE"] = "1"
os.environ["UNSLOTH_DISABLE_FAST_GENERATION"] = "1"
```

### 您的数据集中所有标签都是 -100。训练损失将全部为 0。

这意味着您对 `train_on_responses_only` 的使用对该特定模型是不正确的。train\_on\_responses\_only 允许您屏蔽用户问题，并以更高的权重训练模型输出助手的回复。已知这可以提高约 1% 或更多的准确率。请参阅我们的 [**LoRA 超参数指南**](https://unsloth.ai/docs/zh/kai-shi-shi-yong/fine-tuning-llms-guide/lora-hyperparameters-guide) 以获取更多细节。

对于 Llama 3.1、3.2、3.3 类型的模型，请使用以下内容：

```python
from unsloth.chat_templates import train_on_responses_only
trainer = train_on_responses_only(
    trainer,
    instruction_part = "<|start_header_id|>user<|end_header_id|>\n\n",
    response_part = "<|start_header_id|>assistant<|end_header_id|>\n\n",
)
```

对于 Gemma 2、3、3n 模型，使用以下内容：

```python
from unsloth.chat_templates import train_on_responses_only
trainer = train_on_responses_only(
    trainer,
    instruction_part = "<start_of_turn>user\n",
    response_part = "<start_of_turn>model\n",
)
```

### Unsloth 性能比预期慢？

如果速度起初看起来较慢，很可能是因为 `torch.compile` 通常需要大约 \~5 分钟（或更长）来热身并完成编译。请确保在 **它完全加载之后** 再测量吞吐量，因为在较长的运行中，Unsloth 应该会快得多。

要禁用，请使用：

```python
import os
os.environ["UNSLOTH_COMPILE_DISABLE"] = "1"
```

### Gemma3nForConditionalGeneration 的某些权重未从模型检查点初始化

这是一个严重错误，因为这意味着某些权重未正确解析，会导致输出不正确。通常可以通过升级 Unsloth 来修复，

`pip install --upgrade --force-reinstall --no-cache-dir --no-deps unsloth unsloth_zoo`

然后升级 transformers 和 timm：

`pip install --upgrade --force-reinstall --no-cache-dir --no-deps transformers timm`

但如果问题仍然存在，请尽快提交错误报告！

### NotImplementedError: 需要 UTF-8 区域设置。得到的是 ANSI

参见 <https://github.com/googlecolab/colabtools/issues/3409>

在新单元格中运行以下内容：

```python
import locale
locale.getpreferredencoding = lambda: "UTF-8"
```

### 引用 Unsloth

如果您要引用我们模型上传的使用，请使用下面的 Bibtex。这适用于 Qwen3-30B-A3B-GGUF Q8\_K\_XL：

```
@misc{unsloth_2025_qwen3_30b_a3b,
  author       = {Unsloth AI and Han-Chen, Daniel and Han-Chen, Michael},
  title        = {Qwen3-30B-A3B-GGUF:Q8\_K\_XL},
  year         = {2025},
  publisher    = {Hugging Face},
  howpublished = {\url{https://huggingface.co/unsloth/Qwen3-30B-A3B-GGUF}}
}
```

要引用我们 Github 包或我们的一般工作：

```
@misc{unsloth,
  author       = {Unsloth AI and Han-Chen, Daniel and Han-Chen, Michael},
  title        = {Unsloth},
  year         = {2025},
  publisher    = {Github},
  howpublished = {\url{https://github.com/unslothai/unsloth}}
}
```

[^1]: 启用这行代码并查看是否可行。


---

# Agent Instructions: 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:

```
GET https://unsloth.ai/docs/zh/ji-chu/troubleshooting-and-faqs.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
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.
