# 故障排除

有时会出现错误，但我们会提供帮助！本指南涵盖了我们遇到的一些最常见的问题以及解决方法。不过，本指南并非旨在全面收集所有 🤗 Transformers 问题。如需更多故障排除帮助，请尝试：

1. 在[论坛](https://discuss.huggingface.co/)上寻求帮助。你可以将问题发布到特定的分类中，例如[Beginners](https://discuss.huggingface.co/c/beginners/5)或[🤗 Transformers](https://discuss.huggingface.co/c/transformers/9)。请务必撰写描述清晰的论坛帖子，并附上可复现的代码，以最大程度提高问题得到解决的可能性！

2. 如果该问题与库相关的 bug，请在 🤗 Transformers 仓库中创建一个 [Issue](https://github.com/huggingface/transformers/issues/new/choose)。请尽可能多地提供描述该 bug 的信息，以便我们更好地查明问题所在并找到修复方法。

3. 如果您使用的是旧版本的 🤗 Transformers，请查阅 [迁移](https://github.com/huggingface/transformers/blob/main/MIGRATION_GUIDE_V5.md) 指南，因为不同版本之间引入了一些重要的更改。

如需了解有关故障排除和获取帮助的更多详细信息，请参阅 Hugging Face 课程的[第 8 章](https://huggingface.co/course/chapter8/1?fw=pt)。

## 防火墙隔离环境

在云环境和内网环境中，部分 GPU 实例被防火墙限制对外部连接的访问，从而导致连接错误。当您的脚本尝试下载模型权重或数据集时，下载过程会挂起，随后超时并显示以下消息：

```text
ValueError: Connection error, and we cannot find the requested files in the cached path.
Please try again or make sure your Internet connection is on.
```

在这种情况下，你应该尝试以[离线模式](installation#offline-mode)运行 🤗 Transformers，以避免连接错误。

## CUDA 内存不足

在缺乏合适硬件的情况下，训练拥有数百万参数的大模型可能颇具挑战。当 GPU 内存耗尽时，您可能会遇到以下常见错误：

```text
CUDA out of memory. Tried to allocate 256.00 MiB (GPU 0; 11.17 GiB total capacity; 9.70 GiB already allocated; 179.81 MiB free; 9.85 GiB reserved in total by PyTorch)
```

以下是一些您可以尝试的潜在解决方案，以减少内存使用：

- 将 [TrainingArguments](/docs/transformers/main/zh/main_classes/trainer#transformers.TrainingArguments) 中的 [per_device_train_batch_size](/docs/transformers/main/zh/main_classes/trainer#transformers.TrainingArguments.per_device_train_batch_size) 值减小。
- 尝试在 [TrainingArguments](/docs/transformers/main/zh/main_classes/trainer#transformers.TrainingArguments) 中使用 [gradient_accumulation_steps](/docs/transformers/main/zh/main_classes/trainer#transformers.TrainingArguments.gradient_accumulation_steps) 来有效增大整体批大小。

有关节省内存技术的更多详细信息，请参阅[优化概述](optimization_overview)。

## ImportError

您可能会遇到的另一个常见错误，尤其是在使用新发布的模型时，是 `ImportError`：

```text
ImportError: cannot import name 'ImageGPTImageProcessor' from 'transformers' (unknown location)
```

对于这些错误类型，请检查是否已安装最新版本的 🤗 Transformers，以便访问最新的模型：

```bash
pip install transformers --upgrade
```

## CUDA 错误：触发了设备端断言

有时，您可能会遇到一个通用的 CUDA 错误，提示设备代码中存在错误。

```text
RuntimeError: CUDA error: device-side assert triggered
```

建议先在 CPU 上运行代码，以获取更具描述性的错误信息。在代码开头添加以下环境变量以切换到 CPU：

```py
>>> import os

>>> os.environ["CUDA_VISIBLE_DEVICES"] = ""
```

另一种选择是从 GPU 获取更详细的回溯信息。在代码开头添加以下环境变量，即可让回溯信息指向错误的来源：

```py
>>> import os

>>> os.environ["CUDA_LAUNCH_BLOCKING"] = "1"
```

## 未屏蔽填充标记时输出不正确

在某些情况下，如果 `input_ids` 包含填充标记，输出 `hidden_state` 可能会不正确。为了演示，请加载一个模型和分词器。您可以访问模型的 `pad_token_id` 来查看其值。对于某些模型，`pad_token_id` 可能为 `None`，但您始终可以手动设置它。

```py
>>> from transformers import AutoModelForSequenceClassification
>>> import torch

>>> model = AutoModelForSequenceClassification.from_pretrained("google-bert/bert-base-uncased")
>>> model.config.pad_token_id
0
```

以下示例展示了未对填充标记进行掩码时的输出：

```py
>>> input_ids = torch.tensor([[7592, 2057, 2097, 2393, 9611, 2115], [7592, 0, 0, 0, 0, 0]])
>>> output = model(input_ids)
>>> print(output.logits)
tensor([[ 0.0082, -0.2307],
        [ 0.1317, -0.1683]], grad_fn=<AddmmBackward0>)
```

以下是第二个序列的实际输出：

```py
>>> input_ids = torch.tensor([[7592]])
>>> output = model(input_ids)
>>> print(output.logits)
tensor([[-0.1008, -0.4061]], grad_fn=<AddmmBackward0>)
```

大多数情况下，你应该向模型提供 `attention_mask`，以忽略填充标记，从而避免这种静默错误。现在，第二个序列的输出与其实际输出相匹配：

默认情况下，分词器会根据特定分词器的默认设置为您创建一个`attention_mask`。

```py
>>> attention_mask = torch.tensor([[1, 1, 1, 1, 1, 1], [1, 0, 0, 0, 0, 0]])
>>> output = model(input_ids, attention_mask=attention_mask)
>>> print(output.logits)
tensor([[ 0.0082, -0.2307],
        [-0.1008, -0.4061]], grad_fn=<AddmmBackward0>)
```

🤗 Transformers 不会自动创建 `attention_mask` 来屏蔽填充标记，即使提供了填充标记，原因如下：

- 某些模型没有填充标记。
- 在某些使用场景中，用户希望模型关注填充标记。

## ValueError: 此 AutoModel 类型无法识别配置类 XYZ

通常，我们建议使用 [AutoModel](/docs/transformers/main/zh/model_doc/auto#transformers.AutoModel) 类来加载模型的预训练实例。该类可以根据配置，自动推断并加载给定检查点中正确的架构。如果您在从检查点加载模型时看到此 `ValueError`，这意味着 Auto 类无法在给定检查点的配置与您试图加载的模型类型之间找到映射。最常见的情况是，检查点不支持特定的任务。例如，由于没有用于问答的 GPT2，您在以下示例中会看到此错误：

```py
>>> from transformers import AutoProcessor, AutoModelForQuestionAnswering

>>> processor = AutoProcessor.from_pretrained("openai-community/gpt2-medium")
>>> model = AutoModelForQuestionAnswering.from_pretrained("openai-community/gpt2-medium")
ValueError: Unrecognized configuration class <class 'transformers.models.gpt2.configuration_gpt2.GPT2Config'> for this kind of AutoModel: AutoModelForQuestionAnswering.
Model type should be one of AlbertConfig, BartConfig, BertConfig, BigBirdConfig, BigBirdPegasusConfig, BloomConfig, ...
```

