Transformers documentation
调试
调试
调试分布式训练问题通常属于以下几类:数值问题、通信故障、运行时错误和构建错误。
下溢和上溢检测
当激活值或权重达到 inf 或 nan,或者 loss=NaN 时,会发生下溢和上溢。要检测这些问题,请在 TrainingArguments.debug() 中启用 DebugUnderflowOverflow 模块,或者将其导入并添加到您自己的训练循环中。
from transformers import TrainingArguments
args = TrainingArguments(
debug="underflow_overflow",
...
)from transformers.debug_utils import DebugUnderflowOverflow
debug_overflow = DebugUnderflowOverflow(model)DebugUnderflowOverflow 会在模型中插入钩子,以在每次前向调用后测试输入和输出变量以及对应的模型权重。当在激活值或权重的至少一个元素中检测到 inf 或 nan 时,该模块会打印如下所示的报告。
以下示例演示了使用 google/mt5-small 进行 fp16 混合精度训练。
Detected inf/nan during batch_number=0
Last 21 forward frames:
abs min abs max metadata
encoder.block.1.layer.1.DenseReluDense.dropout Dropout
0.00e+00 2.57e+02 input[0]
0.00e+00 2.85e+02 output
[...]
encoder.block.2.layer.0 T5LayerSelfAttention
6.78e-04 3.15e+03 input[0]
2.65e-04 3.42e+03 output[0]
None output[1]
2.25e-01 1.00e+04 output[2]
encoder.block.2.layer.1.layer_norm T5LayerNorm
8.69e-02 4.18e-01 weight
2.65e-04 3.42e+03 input[0]
1.79e-06 4.65e+00 output
encoder.block.2.layer.1.DenseReluDense.wi_0 Linear
2.17e-07 4.50e+00 weight
1.79e-06 4.65e+00 input[0]
2.68e-06 3.70e+01 output
encoder.block.2.layer.1.DenseReluDense.wi_1 Linear
8.08e-07 2.66e+01 weight
1.79e-06 4.65e+00 input[0]
1.27e-04 2.37e+02 output
encoder.block.2.layer.1.DenseReluDense.dropout Dropout
0.00e+00 8.76e+03 input[0]
0.00e+00 9.74e+03 output
encoder.block.2.layer.1.DenseReluDense.wo Linear
1.01e-06 6.44e+00 weight
0.00e+00 9.74e+03 input[0]
3.18e-04 6.27e+04 output
encoder.block.2.layer.1.DenseReluDense T5DenseGatedGeluDense
1.79e-06 4.65e+00 input[0]
3.18e-04 6.27e+04 output
encoder.block.2.layer.1.dropout Dropout
3.18e-04 6.27e+04 input[0]
0.00e+00 inf output第一行显示了发生错误的批次编号。在此情况下,错误发生在第 0 个批次。
每个帧都描述其报告所针对的模块。例如,下面的帧报告的是 encoder.block.2.layer.1.layer_norm,即编码器第二个块中第一层的层归一化。前向调用指向 T5LayerNorm。
encoder.block.2.layer.1.layer_norm T5LayerNorm 8.69e-02 4.18e-01 weight 2.65e-04 3.42e+03 input[0] 1.79e-06 4.65e+00 output
最后一帧报告了 Dropout.forward 函数,该函数调用了 DenseReluDense 类内部的 dropout 属性。溢出(inf)发生在编码器的第二个块中的第一个批次。最大的输入元素为 6.27e+04。
encoder.block.2.layer.1.DenseReluDense T5DenseGatedGeluDense
1.79e-06 4.65e+00 input[0]
3.18e-04 6.27e+04 output
encoder.block.2.layer.1.dropout Dropout
3.18e-04 6.27e+04 input[0]
0.00e+00 inf outputT5DenseGatedGeluDense.forward 的输出激活值最大达到了 6.27e+04,接近 fp16 的最大值 6.4e+04。在下一步中,Dropout 在将部分元素置零后对权重进行重新归一化,导致最大值超过 6.4e+04,从而引发溢出。
现在你已经知道错误发生的位置,请检查 modeling_t5.py 中的建模代码。
class T5DenseGatedGeluDense(nn.Module):
def __init__(self, config):
super().__init__()
self.wi_0 = nn.Linear(config.d_model, config.d_ff, bias=False)
self.wi_1 = nn.Linear(config.d_model, config.d_ff, bias=False)
self.wo = nn.Linear(config.d_ff, config.d_model, bias=False)
self.dropout = nn.Dropout(config.dropout_rate)
self.gelu_act = ACT2FN["gelu_new"]
def forward(self, hidden_states):
hidden_gelu = self.gelu_act(self.wi_0(hidden_states))
hidden_linear = self.wi_1(hidden_states)
hidden_states = hidden_gelu * hidden_linear
hidden_states = self.dropout(hidden_states)
hidden_states = self.wo(hidden_states)
return hidden_states一种修复方法是在数值变得过大之前几步切换到 fp32,这样在乘法或求和时数字就不会溢出。另一个选项是暂时禁用混合精度训练(amp)。
import torch
def forward(self, hidden_states):
device_type = hidden_states.device.type
if torch.is_autocast_enabled(device_type):
with torch.amp.autocast(device_type, enabled=False):
return self._forward(hidden_states)
else:
return self._forward(hidden_states)该报告仅涵盖完整帧的输入和输出。若要分析任意 forward 函数内部的中间值,请在每次 forward 调用后添加 detect_overflow,以跟踪 forwarded_states 中的 inf 或 nan。
from transformers.debug_utils import detect_overflow
class T5LayerFF(nn.Module):
[...]
def forward(self, hidden_states):
forwarded_states = self.layer_norm(hidden_states)
detect_overflow(forwarded_states, "after layer_norm")
forwarded_states = self.DenseReluDense(forwarded_states)
detect_overflow(forwarded_states, "after DenseReluDense")
return hidden_states + self.dropout(forwarded_states)配置 DebugUnderflowOverflow 打印的帧数。
from transformers.debug_utils import DebugUnderflowOverflow
debug_overflow = DebugUnderflowOverflow(model, max_frames_to_save=100)批量跟踪
DebugUnderflowOverflow 还可以追踪每个批次中的绝对最小值和最大值,同时禁用下溢和上溢检测。这有助于您定位模型中数值开始发散的位置。
下面的示例追踪了第 1 批和第 3 批(批次从零开始索引)。
debug_overflow = DebugUnderflowOverflow(model, trace_batch_nums=[1, 3]) *** Starting batch number=1 ***
abs min abs max metadata
shared Embedding
1.01e-06 7.92e+02 weight
0.00e+00 2.47e+04 input[0]
5.36e-05 7.92e+02 output
[...]
decoder.dropout Dropout
1.60e-07 2.27e+01 input[0]
0.00e+00 2.52e+01 output
decoder T5Stack
not a tensor output
lm_head Linear
1.01e-06 7.92e+02 weight
0.00e+00 1.11e+00 input[0]
6.06e-02 8.39e+01 output
T5ForConditionalGeneration
not a tensor output
*** Starting batch number=3 ***
abs min abs max metadata
shared Embedding
1.01e-06 7.92e+02 weight
0.00e+00 2.78e+04 input[0]
5.36e-05 7.92e+02 output
[...]DebugUnderflowOverflow 会报告许多帧,这有助于定位数值开始偏离的位置。如果你知道问题大约出现在第 150 个批次,可以将追踪范围聚焦于第 149 和第 150 个批次,以比较数值从何处开始产生差异。
您还可以在特定的批次编号后停止跟踪,例如第 3 个批次。
debug_overflow = DebugUnderflowOverflow(model, trace_batch_nums=[1, 3], abort_after_batch_num=3)通信
分布式训练需要进程间和节点间通信,这是常见的错误来源。
下载以下脚本以诊断网络问题,然后运行该脚本来测试 GPU 通信。下面的命令用于测试两个 GPU。请根据您的系统调整 --nproc_per_node 和 --nnodes。
wget https://raw.githubusercontent.com/huggingface/transformers/main/scripts/distributed/torch-distributed-gpu-test.py python -m torch.distributed.run --nproc_per_node 2 --nnodes 1 torch-distributed-gpu-test.py
如果两块 GPU 能够成功通信并分配内存,脚本会打印 OK。有关更多详细信息以及在 SLURM 环境中运行该脚本的方法,请参阅诊断脚本。
设置 NCCL_DEBUG=INFO 以获取详细的 NCCL 调试输出。
NCCL_DEBUG=INFO python -m torch.distributed.run --nproc_per_node 2 --nnodes 1 torch-distributed-gpu-test.py
DeepSpeed
遇到错误时,首先检查是否由 DeepSpeed 引起。请尝试在不使用 DeepSpeed 的情况下重新运行配置,如果错误仍然存在,请报告该问题。对于与 Transformers 集成无关的问题,请在 DeepSpeed 的 仓库 中提交 issue。
对于与 Transformers 集成相关的问题,请包含以下信息。
完整的 DeepSpeed 配置文件。
Trainer 的命令行参数,或者如果您自行编写 Trainer 配置脚本,则使用 TrainingArguments(请勿直接输出整个 TrainingArguments,因为它包含许多无关的条目)。
这些命令的输出。
python -c 'import torch; print(f"torch: {torch.__version__}")' python -c 'import transformers; print(f"transformers: {transformers.__version__}")' python -c 'import deepspeed; print(f"deepspeed: {deepspeed.__version__}")'一个指向 Google Colab 笔记本的链接,用于复现该问题。
一个标准的或非自定义的数据集,或一个用于复现该问题的现有示例。
启动时进程被终止
如果在启动过程中 DeepSpeed 进程被终止且没有回溯信息,则说明程序尝试分配的 CPU 内存超出了可用或允许的内存上限。在这两种情况下,操作系统内核都会终止该进程。
检查您的配置文件是否将 offload_optimizer、offload_param 或两者都配置为卸载到 CPU。
如果已配置 NVMe 和 ZeRO-3,请尝试将数据卸载到 NVMe。首先,估算模型的内存需求。
NaN 损失
NaN 损失通常发生在模型以 bf16 进行预训练,随后却以 fp16 使用的情况下(这在 TPU 训练的模型中尤为常见)。如果您的硬件支持(如 TPU、Ampere GPU 或更新的 GPU),请使用 fp32 或 bf16。
fp16 也可能导致溢出。如果您的配置文件如下所示,您可能会在日志中看到溢出错误。
{
"fp16": {
"enabled": "auto",
"loss_scale": 0,
"loss_scale_window": 1000,
"initial_scale_power": 16,
"hysteresis": 2,
"min_loss_scale": 1
}
}下面的 OVERFLOW! 错误表示 DeepSpeed 损失缩放器无法找到能够克服损失溢出的缩放系数。请尝试使用更高的 initial_scale_power 值(通常 32 即可生效)。
0%| | 0/189 [00:00<?, ?it/s] [deepscale] OVERFLOW! Rank 0 Skipping step. Attempted loss scale: 262144, reducing to 262144 1%|▌ | 1/189 [00:00<01:26, 2.17it/s] [deepscale] OVERFLOW! Rank 0 Skipping step. Attempted loss scale: 262144, reducing to 131072.0 1%|█▏ [...] [deepscale] OVERFLOW! Rank 0 Skipping step. Attempted loss scale: 1, reducing to 1 14%|████████████████▌ | 27/189 [00:14<01:13, 2.21it/s] [deepscale] OVERFLOW! Rank 0 Skipping step. Attempted loss scale: 1, reducing to 1 15%|█████████████████▏ | 28/189 [00:14<01:13, 2.18it/s] [deepscale] OVERFLOW! Rank 0 Skipping step. Attempted loss scale: 1, reducing to 1 15%|█████████████████▊ | 29/189 [00:15<01:13, 2.18it/s] [deepscale] OVERFLOW! Rank 0 Skipping step. Attempted loss scale: 1, reducing to 1 [...]
DeepSpeed CUDA
DeepSpeed 会编译 CUDA C++ 代码,这是需要 CUDA 的 PyTorch 扩展中常见的构建错误来源。这些错误取决于 CUDA 在您的系统上的安装方式。
pip install deepspeed
如有其他安装问题,请向 DeepSpeed 团队提交 issue。
不同的工具包
PyTorch 自带其 CUDA 工具包,但 DeepSpeed 要求系统范围内安装相同版本的 CUDA。如果你在 Python 环境中使用 cudatoolkit==10.2 安装了 PyTorch,那么还需要在系统中安装 CUDA 10.2。
具体位置因系统而异,但在 Unix 系统上,/usr/local/cuda-10.2 是最常见的路径。配置好 CUDA 并将其添加到 PATH 后,可使用以下命令查找安装位置。
which nvcc多个工具包
您的系统可能安装了多个 CUDA 工具包。
/usr/local/cuda-10.2 /usr/local/cuda-11.0
包安装程序通常会将路径设置为最后安装的版本。如果构建失败是因为找不到正确的 CUDA 版本,请配置 PATH 和 LD_LIBRARY_PATH 以指向正确的路径。
首先检查这些环境变量。
echo $PATH
echo $LD_LIBRARY_PATHPATH 列出了可执行文件的位置。LD_LIBRARY_PATH 列出了共享库的位置。前面的条目具有更高的优先级,多个条目之间使用 : 分隔。将正确的 CUDA 路径置于开头,以使其具有优先权。
# adjust the version and full path if needed
export PATH=/usr/local/cuda-10.2/bin:$PATH
export LD_LIBRARY_PATH=/usr/local/cuda-10.2/lib64:$LD_LIBRARY_PATH同时请验证所分配的目录是否存在。lib64 子目录中包含 CUDA .so 对象,例如 libcudart.so。请检查实际的文件名并相应地进行更新。
旧版本
旧版 CUDA 有时需要旧版编译器。例如,如果 CUDA 要求 gcc-7,但您的系统只有 gcc-9,构建将会失败。请安装所需的旧版编译器,并创建一个符号链接,以便 CUDA 构建系统能够找到它。
# adjust the path to your system
sudo ln -s /usr/bin/gcc-7 /usr/local/cuda-10.2/bin/gcc
sudo ln -s /usr/bin/g++-7 /usr/local/cuda-10.2/bin/g++预构建
如果您在安装 DeepSpeed 或运行时构建时仍遇到问题,请先预构建 DeepSpeed 模块。请运行以下命令进行本地构建。
git clone https://github.com/deepspeedai/DeepSpeed/
cd DeepSpeed
rm -rf build
TORCH_CUDA_ARCH_LIST="8.6" DS_BUILD_CPU_ADAM=1 DS_BUILD_UTILS=1 pip install . \
--global-option="build_ext" --global-option="-j8" --no-cache -v \
--disable-pip-version-check 2>&1 | tee build.log在构建命令中添加
DS_BUILD_AIO=1以使用 NVMe offload。请确保已在系统范围内安装 libaio-dev 软件包。
接下来,在 TORCH_CUDA_ARCH_LIST 中设置您的 GPU 架构。NVIDIA GPU 及其架构的完整列表位于 CUDA GPUs 页面。要查看与您的架构对应的 PyTorch 版本,请运行以下命令。
python -c "import torch; print(torch.cuda.get_arch_list())"使用以下命令查找 GPU 的架构。
CUDA_VISIBLE_DEVICES=0 python -c "import torch; print(torch.cuda.get_device_capability())"运行以下命令以查找 GPU 0 的架构。输出会显示 major 和 minor 值,它们共同构成 GPU 架构。下例中显示的架构为 8.6。
CUDA_VISIBLE_DEVICES=0 python -c "import torch; \
print(torch.cuda.get_device_properties(torch.device('cuda')))
"_CudaDeviceProperties(name='GeForce RTX 3090', major=8, minor=6, total_memory=24268MB, multi_processor_count=82)"如果结果为 8, 6,请设置 TORCH_CUDA_ARCH_LIST="8.6"。如果有多块不同架构的 GPU,请像 TORCH_CUDA_ARCH_LIST="6.1;8.6" 这样列出它们。
您可以省略 TORCH_CUDA_ARCH_LIST,让构建程序自动检测 GPU 架构,但这可能与目标机器上的实际 GPU 不匹配。显式设置架构更为可靠。
要在具有相同配置的多台机器上进行训练,请构建二进制 wheel。
git clone https://github.com/deepspeedai/DeepSpeed/
cd DeepSpeed
rm -rf build
TORCH_CUDA_ARCH_LIST="8.6" DS_BUILD_CPU_ADAM=1 DS_BUILD_UTILS=1 \
python setup.py build_ext -j8 bdist_wheel这将生成一个二进制 wheel 文件,例如 dist/deepspeed-0.3.13+8cd046f-cp38-cp38-linux_x86_64.whl。您可以将其安装在本地或另一台机器上。
pip install deepspeed-0.3.13+8cd046f-cp38-cp38-linux_x86_64.whl