首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用`batch_first=False`,PyTorch RNN的效率更高?

使用`batch_first=False`,PyTorch RNN的效率更高?
EN

Stack Overflow用户
提问于 2020-09-10 10:54:06
回答 1查看 1.8K关注 0票数 4

在机器翻译中,我们总是需要在注释和预测中切出第一个时间步( SOS标记)。

当使用batch_first=False时,切出第一个时间步仍然保持张量是连续的。

代码语言:javascript
复制
import torch
batch_size = 128
seq_len = 12
embedding = 50

# Making a dummy output that is `batch_first=False`
batch_not_first = torch.randn((seq_len,batch_size,embedding))
batch_not_first = batch_first[1:].view(-1, embedding) # slicing out the first time step

然而,如果我们使用batch_first=True,在切片之后,张量不再是连续的。我们需要让它成为连续的,然后我们才能做不同的操作,比如view

代码语言:javascript
复制
batch_first = torch.randn((batch_size,seq_len,embedding))
batch_first[:,1:].view(-1, embedding) # slicing out the first time step

output>>>
"""
---------------------------------------------------------------------------
RuntimeError                              Traceback (most recent call last)
<ipython-input-8-a9bd590a1679> in <module>
----> 1 batch_first[:,1:].view(-1, embedding) # slicing out the first time step

RuntimeError: view size is not compatible with input tensor's size and stride (at least one dimension spans across two contiguous subspaces). Use .reshape(...) instead.
"""

这是否意味着,至少在机器翻译的上下文中,batch_first=False更好?因为它省去了我们做contiguous()的步骤。有没有哪种情况下batch_first=True运行得更好?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-09-10 15:15:30

性能

batch_first=Truebatch_first=False之间似乎没有太大的区别。请参考下面的脚本:

代码语言:javascript
复制
import time

import torch


def time_measure(batch_first: bool):
    torch.cuda.synchronize()
    layer = torch.nn.RNN(10, 20, batch_first=batch_first).cuda()
    if batch_first:
        inputs = torch.randn(100000, 7, 10).cuda()
    else:
        inputs = torch.randn(7, 100000, 10).cuda()

    start = time.perf_counter()

    for chunk in torch.chunk(inputs, 100000 // 64, dim=0 if batch_first else 1):
        _, last = layer(chunk)

    return time.perf_counter() - start


print(f"Time taken for batch_first=False: {time_measure(False)}")
print(f"Time taken for batch_first=True: {time_measure(True)}")

在我的设备(GTX1050Ti)、PyTorch 1.6.0和CUDA11.0上,结果如下:

代码语言:javascript
复制
Time taken for batch_first=False: 0.3275816479999776
Time taken for batch_first=True: 0.3159054920001836

(而且这两种情况都不同,所以没有什么是决定性的)。

代码可读性

当您想要使用其他需要batch作为0维度的PyTorch层时(这是几乎所有torch.nn层的情况,如torch.nn.Linear),batch_first=True更简单。

在这种情况下,如果指定了batch_first=False,则无论如何都必须permute返回张量。

机器翻译

这应该更好,因为tensor一直都是连续的,并且不需要复制数据。使用[1:]而不是[:,1:]进行切片也看起来更干净。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63822152

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档