添加链接
link之家
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
pytorch问题记录

pytorch问题记录

## 问题1

某个变量在前向计算时是一个值,在求梯度时变成了另一个值(inplace 操作导致),使得pytorch在反向梯度求导时产生了错误

问题展示

RuntimeError: one of the variables needed for gradient computation has been modified by an inplace operation: [torch.cuda.FloatTensor [128, 32, 32]], which is output 0 of SoftmaxBackward, is at version 1; expected version 0 instead. Hint: enable anomaly detection to find the operation that failed to compute its gradient, with torch.autograd.set_detect_anomaly(True).

问题代码

1. x+=1
2. attention[1] = 0

解决方案

1. x = x+1
2. temp = attention
temp[1] = 0

tips:

我是排查到问题语句,直接针对问题语句更改,若是不知道问题语句,可以重点看一下赋值语句~

## 问题2

问题展示

RuntimeError: element 0 of tensors does not require grad and does not have a

问题代码

loss = F.cross_entropy(outputs, labels)
loss.backward()

问题原因

loss不是可grad的变量

解决方案

loss = F.cross_entropy(outputs, labels)
# 报错--RuntimeError: element 0 of tensors does not require grad and does not have a
loss = loss.requires_grad_()
loss.backward()

## 问题3

问题展示

Pytorch RuntimeError: Expected tensor for argument #1 'indices' to have scalar type Long; but got CUDAType instead

问题代码

pos_emb = self.embedding(pos_emb)

解决方案

pos_emb = torch.tensor(pos_emb).to(torch.int64).to(self.config.device)

## 问题四

问题展示

zipfile.BadZipFile: File is not a zip file

问题代码

import gensim

解决方案

pip uninstall nltk

## 问题五

问题展示

NameError: name '__file__' is not defined

问题代码

path = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir))

解决方案

path = os.path.abspath(os.path.join(os.path.dirname("__file__"), os.pardir))

## 问题六

问题展示

stopiteration: Caught StopIteration in replica 0 on device 0.

问题代码

# 运行interpret-text/notebooks/text_classification 可视化时出错

解决方案

# 严格按照官方说明文档步骤进行,在运行前首先cuda要切换到interpret-text,再运行jupyter
conda activate interpret_gpu

## 问题七

问题展示

Ubuntu下pyhanlp安装失败,import的时候报错

解决方案

下载好data,hanlp-1.7.8.jar,hanlp.properties放在static下即可

## 问题八

问题描述

python有些安装包不兼容,但是暂时又找不到替代方案,只能用当前版本
在GPU下训练保存的代码,如何在CPU上加载?

解决方案

state_dict = torch.load(save_path, map_location=lambda storage, loc: storage)
# load params
from collections import OrderedDict
new_state_dict = OrderedDict()
for k, v in state_dict.items():
    name = k[7:] # remove `module.`
    new_state_dict[name] = v