在机器翻译中,我们总是需要在注释和预测中切出第一个时间步( SOS标记)。
当使用batch_first=False时,切出第一个时间步仍然保持张量是连续的。
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。
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运行得更好?
发布于 2020-09-10 15:15:30
性能
batch_first=True和batch_first=False之间似乎没有太大的区别。请参考下面的脚本:
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上,结果如下:
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:]进行切片也看起来更干净。
https://stackoverflow.com/questions/63822152
复制相似问题