深度学习 Transformer Pytorch 在pad时做attention mask 出现 nan问题分析 - 有些底层实现对数值非常敏感,很容易出现nan问题
深度学习 Transformer Pytorch 在pad时做attention mask 出现 nan问题分析
简要分析
做pad的序列由于不需要任何信息,被整体做了mask,即减去了-inf,得到了全为-inf的矩阵Pytorch 对全为-inf的矩阵做softmax会输出为nan所有有nan的运算都会导致结果nan。尽管这些nan数据有mask,但
n
a
n
−
i
n
f
=
n
a
n
nan-inf=nan
nan−inf=nan,导致nan会被传播到其他位置,从而导致mask无效,从而导致未被mask的数据也出现nan问题。
具体分析
使用gemm2模型推理,当batch_size>2时部分序列会输出全0,debug发现是logit出现nan,而导致nan的为torch.nn.functional.scaled_dot_product_attention函数。 scaled_dot_product_attention函数有多种底层实现,在Pytorch官方文档中也有介绍。有些底层实现对数值非常敏感,很容易出现nan问题。在使用非常小的数(非-inf)做mask时,Memory-Efficient Attention可能也会出现nan问题,而这种方法可能也是Pytorch自动选用的方法。下图为使用两种不同的实现得到的结果。
解决方案
使用bfloat16()进行推理,感觉这对llama2很有用。修改 attn_mask 的值,不要使用-inf,详细可参考github上的讨论。以Gemma为例,访问源码,修改min_dtype = torch.finfo(dtype).min为min_dtype = torch.finfo(dtype).min/2。该方法对Gemma很有用使用eager 或者 flash_attention_2 而不是 sdpa。在使用transformers加载模型时使用attn_implementation=attn_implementation以修改attention实现方式,例如:
model = transformers.AutoModelForCausalLM.from_pretrained( 拼多多帮助力入口
model_path,
device_map=device,
torch_dtype=torch.bfloat16,
attn_implementation="flash_attention_2",
)
参考
RuntimeError: probability tensor contains either inf, nan or element < 0 · Issue #380 · meta-llama/llama (github.com)SDPA produces NaN with padding mask · Issue #103749 · pytorch/pytorch (github.com)Gemma 2 returns NaN when using default attn (sdpa) with padding · Issue #32390 · huggingface/transformers (github.com)scaled_dot_product_attention produces nans with boolean attn_mask with zero rows. · Issue #103963 · pytorch/pytorch (github.com)Add a private _safe_softmax by drisspg · Pull Request #131060 · pytorch/pytorch (github.com)Parallel inference on generative models throws an exception · Issue #32217 · huggingface/transformers (github.com)
深度学习 Transformer Pytorch 在pad时做attention mask 出现 nan问题分析
推荐阅读