Pytorch计算Loss值为Nan的一种情况【exp计算溢出,利用softmax计算的冗余性解决】

一、报错提示

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):
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值