一、报错提示
FutureWarning: Non-finite norm encountered in torch.nn.utils.clip_grad_norm_; continuing anyway. Note that the default behavior will change in a future release to error out if a non-finite total norm is encountered. At that point, setting error_if_nonfinite=false will be required to retain the old behavior. torch.nn.utils.clip_grad_norm_(WAP_model.parameters(), clip_c)
pytorch进行FutureWarning警告之后,train和valid的loss计算值都显示为Nan。
二、调试过程
在loss.backward()之前的loss都是有值的,没有出现Nan,但是进行梯度计算时产生了Nan。
1、使用autograd.detect_anomaly()开启自动求导的异常值检测。
开始引入torch.autograd:
import torch.autograd as autograd
在loss.backward()外侧加上autograd.detect_anomaly():
with autograd.detect_anomaly():
loss.backward()
产生报错:ExpBackward。于是考察网络中所有与exp有关的计算,检查是否有值溢出。
RuntimeError: Function 'ExpBackward' returned nan values in its 0th output.
2、使用torch.isnan().sum()>0,torch.isinf().sum()>0检测某个tensor中是否有异常值。
beta = torch.exp(z1) / (torch.exp(z0)[:, None] + torch.exp(z1) + 1e-5)
if torch.isnan(torch.exp(z1)).sum()>0:
print('expz1_nan')
if torch.isinf(torch.exp(z1)).sum()>0:
print('expz1_inf')
if torch.isnan(torch.exp(z0)).sum()>0:
print('expz0_nan')
if torch.isinf(torch.exp(z0)).sum()>0:
print('expz0_inf')
再次debug,发现torch.exp(z0)的某次运算过程产生了inf值:
torch.exp(z0)产生了inf值,于是往上查看z0是否有异常值:
z0为92时,计算e的92次方产生了上溢,所以对应的exp计算出现了inf,反向传播求梯度时这个位置无法正确进行求值,因此报错。
三、解决思路
1、利用softmax函数冗余性,看下面这个例子
import math
import numpy as np
def softmax(inp):