> For the complete documentation index, see [llms.txt](https://unsloth.ai/docs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://unsloth.ai/docs/zh/ji-chu-zhi-shi/troubleshooting-and-faqs.md).

# 故障排查与常见问题

解决问题的技巧，以及常见问题解答。

如果你仍然遇到任何版本或依赖项问题，请使用我们的 [Docker 镜像](/docs/zh/kuai-su-kai-shi/install/docker.md) 其中会预装好所有内容。

{% 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](/docs/zh/mo-xing/tutorials/deepseek-ocr-how-to-run-and-fine-tune.md):

<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 等其他框架中时也保持一致。从已保存的模型进行推理时，应用正确的模板至关重要。
* 也可能是因为你的推理引擎添加了不必要的 "start of sequence" 标记（或者相反，缺少该标记），因此请务必检查这两种情况！
* <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)
  * **更多笔记本请见我们的** [**笔记本文档**](/docs/zh/kuai-su-kai-shi/unsloth-notebooks.md)

### 保存为 GGUF / vLLM 16 位时崩溃

你可以尝试通过更改以下参数来降低保存期间的 GPU 最大使用量： `maximum_memory_usage`.

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

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

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

```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/ggml-org/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,   # 你可以增大此值来提高批量大小
        eval_strategy = "steps",       # 每隔几步或几个 epoch 运行一次评估。
        eval_steps = 1,                # 每多少个训练步进行一次评估
    ),
    train_dataset = new_dataset["train"],
    eval_dataset = new_dataset["test"],
    ...
)
trainer.train()
```

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

当你遇到 OOM 时，一个常见问题是你的批量大小设得太高。将其设为小于 2 以使用更少的 VRAM。还要使用 `fp16_full_eval=True` 以在评估中使用 float16，从而将内存减半。

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

```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_full_eval=True` 适用于 bf16 机器。到 2025 年 6 月为止，默认情况下 Unsloth 应该已经将这些标志设为默认开启。

### 我该如何进行早停？

如果你想因为评估损失没有下降而停止微调/训练运行，那么你可以使用早停来停止训练过程。使用 `EarlyStoppingCallback`.

像往常一样，设置好你的训练器和评估数据集。下面用于在以下情况下停止训练运行： `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 then 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 错误：触发了设备端断言

重新启动并运行全部，但请把这段放在开头，置于任何 Unsloth 导入之前。另外请尽快提交 bug 报告，谢谢！

```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 超参数指南**](/docs/zh/kuai-su-kai-shi/fine-tuning-llms-guide/lora-hyperparameters-guide.md) 了解更多细节。

对于 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`

不过如果问题仍然存在，请尽快提交 bug 报告！

### 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
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 by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

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

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

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.
