此为pytorch使用过程中遇到的些许问题,及相应解决方法。
目录
目录
2、报错:RuntimeError: set_sizes_contiguous is not allowed on Tensor created from .data or .detach()
3、报错:RuntimeError: expected device cuda:0 and dtype Byte but got device cuda:0 and dtype Bool
5、ImportError: torch.utils.ffi is deprecated. Please use cpp extensions instead. (未解决)
7、cuDNN error: CUDNN_STATUS_INTERNAL_ERROR on cudnn.benchmark = True
8、RuntimeError: CUDA error: invalid device ordinal
10、RuntimeError: CUDA error: no kernel image is available for execution on the device (2020-12-16)
13、Pytorch中的张量Tensor、tensor、from_numpy、as_tensor间的区别
15、在 BatchNorm 之前关闭 bias (2021-3-22)
17、ImportError: No module named IPython
环境:Ubuntu 18.04 + CUDA 10.0 + Anaconda
1、安装并测试 warp-CTC
1、安装 warp-CTC
首先需要安装并激活pytorch环境:conda activate pytorch 。因为warp-CTC的编译过程中,需要用到pytorch 环境中相关文件,不然即使编译通过,最后测试warp-CTC的时候也会失败。(pytorch 虚拟环境的安装请参见 here)
激活pytorch后:
git clone https://github.com/SeanNaren/warp-ctc.git
cd warp-ctc
mkdir build; cd build
cmake ..
make
cd ../pytorch_binding
python setup.py install
(如果pytorch版本改变,最好将 warp-ctc 文件夹删除,然后重新编译、安装一遍。
如果出现 ********.so 文件不存在或未定义等情况,查看下是不是自己环境不对 或 权限不够,然后重新编译、安装。)
2、测试 warp-CTC
首先进入 warp-CTC 中 pytorch_binding 下的 tests 目录中:
cd ../pytorch_binding/tests
测试cpu:
python test_cpu.py
成功结果如下:
测试gpu:
python test_gpu.py
成功结果如下:
2、报错:RuntimeError: set_sizes_contiguous is not allowed on Tensor created from .data or .detach()
原因:pytorch版本问题
解决方法:
将 v.data.resize_(data.size()).copy_(data)
修改为 v.resize_(data.size()).copy_(data)
3、报错:RuntimeError: expected device cuda:0 and dtype Byte but got device cuda:0 and dtype Bool
问题:pytorch版本不对
解决方法:将 pytorch 由 1.2.0 降至 1.1.0 版本
4、使用 conda 降低 pytorch 的版本
# 如问题 3 所述,降低到 1.1.0 版本
conda install pytorch=1.1.0 -c soumith
也可以使用 pip 对 pytorch 进行降级,但是基于 conda 包管理显然更简便。再之,本文中的 pytorch 环境就是基于conda安装的。
降低了 pytorch 版本后,需要注意之前的 warp-ctc 需要重新编译、安装。
记得将之前的 warp-ctc 删除干净再安装,不然有可能报错:ImportError: /home/****/.cache/Python-Eggs/warpctc_pytorch-0.1-py2.7-linux-x86_64.egg-tmp/warpctc_pytorch/_warp_ctc.so: undefined symbol: _ZN3c1019NonVariableTypeMode10is_enabledEv
此时需要将文件:_warp_ctc.so 删除
rm /home/****/.cache/Python-Eggs/warpctc_pytorch-0.1-py2.7-linux-x86_64.egg-tmp/warpctc_pytorch/_warp_ctc.so
然后再重新编译、安装 warp-ctc 。
5、ImportError: torch.utils.ffi is deprecated. Please use cpp extensions instead. (未解决)
编译 Nvidia 的 Flownet2 的时候遇到的问题。
原因:在PyTorch 的新版本 中 torch.utils.ffi被弃用了,需要用其他包来替代。
一个可能的解决方案是:
from torch.utils.ffi import create_extension
修改成
from torch.utils.cpp_extension import BuildExtension
然后,将 ffi = create_extension(...) 修改成
ffi = BuildExtension(...)
然而,我修改后,还是出现了 TypeError: dist must be a Distribution instance 的问题,并未解决。
6、RuntimeError: CUDA error: no kernel image is available for execution on the device (nms_cuda at /tmp/pip-req-build-8d3_7_rq/torchvision/csrc/cuda/nms_cuda.cu:127)
原因:版本不兼容问题。
You installed or built a version of torchvision incompatible with your environment.
解决方案:
将目前的 pytorch 和 torchvision(1.3版本)卸载了,重新装成 1.2 的就行了。
7、cuDNN error: CUDNN_STATUS_INTERNAL_ERROR on cudnn.benchmark = True
原因:GPU 过多。
Same problem on current official 1.0.1 when pushing batch size to more than 3 per gpu (on multi gpu context). Works when batch_size/ngpu <= 3. Problem only with Group norm layers
解决方案:指定到某一个GPU就行。
8、RuntimeError: CUDA error: invalid device ordinal
原因:多GPU卡的机器中,0号被同事占用,但是载入程序中,即使使用了 torch.cuda.set_device(1) 等,也是报错,原因是之前的model还是会默认载入到GPU:0中。
解决方案:直接在终端中执行:
export CUDA_VISIBLE_DEVICES=2 && python main.py
9、pytorch 中指定 GPU 的几种方式
1)同TF,在终端中设定
CUDA_VISIBLE_DEVICES=1 python main.py
2) 代码中设定:
# 建议使用该方法
import os
os.environ["CUDA_VISIBLE_DEVICES"] = "0,1"
3)使用 set_device
# 不建议使用该方法
import torch
torch.cuda.set_device(1)
官方建议使用CUDA_VISIBLE_DEVICES,不建议使用 set_device 函数。
10、RuntimeError: CUDA error: no kernel image is available for execution on the device (2020-12-16)
原因:pytorch的版本和显卡的计算能力不匹配。
提示报错:Tesla K40m with CUDA capability sm_35 is not compatible with the current PyTorch installation.
The current PyTorch install supports CUDA capabilities sm_37 sm_50 sm_60 sm_61 sm_70 sm_75 compute_37.
组里服务器上的显卡太旧了,还是Tesla K40m,虽然CUDA Version:10.2,如果按照pytorch官网的指令:
conda install pytorch torchvision torchaudio cudatoolkit=10.2 -c pytorch
安装的是pytorch的1.7.1的版本,但是从pytorch 1.3.0以后,就不支持Tesla K40m了。
解决方法:在Tesla K40m上,安装pytorch 1.2.0的版本就行了。
conda install pytorch==1.2.0 torchvision==0.4.0 cudatoolkit=10.0 -c pytorch
11、 使用自动混合精度(AMP)
PyTorch 1.6 版本包括对 PyTorch 的自动混合精度训练的本地实现。这里想说的是,与单精度 (FP32) 相比,某些运算在半精度 (FP16) 下运行更快,而不会损失准确率。AMP 会自动决定应该以哪种精度执行哪种运算。这样既可以加快训练速度,又可以减少内存占用。
在最好的情况下,AMP 的使用情况如下:
import torch
# Creates once at the beginning of training
scaler = torch.cuda.amp.GradScaler()
for data, label in data_iter:
optimizer.zero_grad()
# Casts operations to mixed precision
with torch.cuda.amp.autocast():
loss = model(data)
# Scales the loss, and calls backward()
# to create scaled gradients
scaler.scale(loss).backward()
# Unscales gradients and calls
# or skips optimizer.step()
scaler.step(optimizer)
# Updates the scale for next iteration
scaler.update()
12、 CUDNN 基准加速
如果模型架构保持不变、输入大小保持不变,可设置 torch.backends.cudnn.benchmark = True,对模型训练进行加速,有时候也有降低内存。
13、Pytorch中的张量Tensor、tensor、from_numpy、as_tensor间的区别
Tensor与tensor的区别在于方法名中t的大小写,大写字母T(Tensor)是类构造函数,第二种小写是工厂函数(简单的理解就是函数中嵌套函数(闭包的一种应用))。torch.as_tensor 和 torch.from_numpy 也是工厂函数。
构造函数在构造一个张量时使用全局缺省值,而工厂函数则根据输入推断数据类型。通过torch.get_default_dtype()可以查看dtype的全局缺省值是float32。工厂函数是根据传入的数据选择一个dtype。
使用区别:
Tensor 和 tensor 不受数组改变的影响;from_numpy 和 as_tensor,两个张量包含了更改后数组中的相同数据。from_numpy 和 as_tensor 可以映射数组的情况。这种差异是由每个创建选项中分配内存的方式造成的。
Tensor 和 tensor 在内存中创建一个额外的数据副本(深拷贝,不共享内存),
from_numpy 和 as_tensor 是数组在内存中共享数据(浅拷贝,共享内存)。
不同之处就是在于对内存的共享。
torch.as_tensor() 和 torch.from_numpy() 函数使得numpy数组与Pytorch张量之间切换可以非常快,
因为创建新的Pytorch张量时,数据是共享的,而不是后台复制的。
共享数据比复制数据更有效使用更少的内存。
因为数据没有写到内存中的两个位置,而是只有一个位置。
具体用哪一种?
torch.tensor()是经常使用的,但是会复制数据。
如果想做内存优化,使用torch.as_tensor(),相比于 torch.from_numpy(),torch.as_tensor()函数可以接受任何像Python数据结构这样的数组。
14、使用梯度裁剪
关于避免 RNN 中的梯度爆炸的问题,已经有一些实验和理论证实,梯度裁剪(gradient = min(gradient, threshold))可以加速收敛。
HuggingFace 的 Transformer 实现就是一个非常清晰的例子,说明了如何使用梯度裁剪。本文中提到的其他一些方法,如 AMP 也可以用。
在 PyTorch 中可以使用 torch.nn.utils.clip_grad_norm_来实现。
15、在 BatchNorm 之前关闭 bias (2021-3-22)
在开始 BatchNormalization 层之前关闭 bias 层。
对于一个 2-D 卷积层,可以将 bias 关键字设置为 False:torch.nn.Conv2d(..., bias=False, ...)。
16、“RuntimeError: Make sure the makedot executables are on your system's path” after installing makedot 2.38 (2021-8-19)
pytorch画图时遇到的问题,pip install torchviz 后,由于权限的关系出错。
方法:pip uninstall torchviz后,conda install python-graphviz, 然后再次pip install torchviz。问题就消失了。
17、ImportError: No module named IPython
还是pytorch画图时遇到的问题,解决:
conda install -c anaconda ipython