1. nn.Module.cuda() 和 Tensor.cuda() 的作用效果差异

无论是对于模型还是数据,cuda()函数都能实现从CPU到GPU的内存迁移,但是他们的作用效果有所不同。

对于nn.Module:
model = model.cuda()  model.cuda() 
上面两句能够达到一样的效果,即对model自身进行的内存迁移。

对于Tensor:


和nn.Module不同,调用tensor.cuda()只是返回这个tensor对象在GPU内存上的拷贝,而不会对自身进行改变。因此必须对tensor进行重新赋值,即tensor=tensor.cuda().

例子:
model = create_a_model() tensor = torch.zeros([2,3,10,10]) model.cuda()
tensor.cuda() model(tensor)    # 会报错 tensor = tensor.cuda() model(tensor)    #
正常运行
 

2. PyTorch 0.4 计算累积损失的不同

以广泛使用的模式total_loss +=
loss.data[0]为例。Python0.4.0之前,loss是一个封装了(1,)张量的Variable,但Python0.4.0的loss现在是一个零维的标量。对标量进行
索引是没有意义的(似乎会报 invalid index to scalar variable
的错误)。使用loss.item()可以从标量中获取Python数字。所以改为:
total_loss += loss.item()

如果在累加损失时未将其转换为Python数字,则可能出现程序内存使用量增加的情况。这是因为上面表达式的右侧原本是一个Python浮点数,而它现在是一个零维张量。因此,总损失累加了张量和它们的梯度历史,这可能会产生很大的autograd
图,耗费内存和计算资源。

 

3. PyTorch 0.4 编写不限制设备的代码
# torch.device object used throughout this script device = torch.device("cuda"
if use_cuda else "cpu") model = MyRNN().to(device) # train total_loss= 0 for
input, target in train_loader:     input, target = input.to(device),
target.to(device)     hidden = input.new_zeros(*h_shape)       # has the same
device & dtype as `input`     ...                                 
                             # get loss and optimize     total_loss +=
loss.item() # test with torch.no_grad():                                    #
operations inside don't track history     for input, targetin test_loader:    
    ...
 

4. torch.Tensor.detach()的使用

detach()的官方说明如下:
Returns a new Tensor, detached from the current graph. The result will never
require gradient.
假设有模型A和模型B,我们需要将A的输出作为B的输入,但训练时我们只训练模型B. 那么可以这样做:

input_B = output_A.detach()

它可以使两个计算图的梯度传递断开,从而实现我们所需的功能。

 

5. ERROR: Unexpected bus error encountered in worker. This might be caused by
insufficient shared memory (shm)

出现这个错误的情况是,在服务器上的docker中运行训练代码时,batch size设置得过大,shared
memory不够(因为docker限制了shm).解决方法是,将Dataloader的num_workers设置为0.

 

6. pytorch中loss函数的参数设置

以CrossEntropyLoss为例:
CrossEntropyLoss(self, weight=None, size_average=None, ignore_index=-100,
reduce=None, reduction='elementwise_mean')
* 若 reduce = False,那么 size_average 参数失效,直接返回向量形式的 loss,即batch中每个元素对应的loss.
* 若 reduce = True,那么 loss 返回的是标量:
* 如果 size_average = True,返回 loss.mean().
* 如果 size_average = False,返回 loss.sum().
* weight : 输入一个1D的权值向量,为各个类别的loss加权,如下公式所示: 
* ignore_index : 选择要忽视的目标值,使其对输入梯度不作贡献。如果 size_average =
True,那么只计算不被忽视的目标的loss的均值。
* reduction : 可选的参数有:‘none’ | ‘elementwise_mean’ | ‘sum’, 正如参数的字面意思,不解释。
 

7. pytorch的可重复性问题

参考这篇博文: https://blog.csdn.net/hyk_1996/article/details/84307108
<https://blog.csdn.net/hyk_1996/article/details/84307108>

 

 

友情链接
KaDraw流程图
API参考文档
OK工具箱
云服务器优惠
阿里云优惠券
腾讯云优惠券
华为云优惠券
站点信息
问题反馈
邮箱:ixiaoyang8@qq.com
QQ群:637538335
关注微信