由 PyTorch 团队

欢迎阅读 PyTorch 0.4.0 迁移指南。在本版本中,我们引入了许多令人兴奋的新功能和关键错误修复,旨在为用户提供更好、更简洁的界面。在本指南中,我们将介绍从先前版本迁移现有代码时最重要的更改:

  • TensorsVariables 已合并
  • 支持 0 维(标量) Tensors
  • 废弃了 volatile 标志
  • dtypesdevices 以及 Numpy 风格的 Tensor 创建函数
  • 编写设备无关的代码
  • nn.Module 中子模块、参数和缓冲区名称的新边缘情况约束

合并 TensorVariable 以及类

torch.Tensortorch.autograd.Variable 现在是同一类。更确切地说, torch.Tensor 能够跟踪历史并像旧的 Variable 一样行为; Variable 的包装仍然像以前一样工作,但返回一个类型为 torch.Tensor 的对象。这意味着你不再需要在代码的每个地方都使用 Variable 包装器了。

type()Tensor 已更改

注意,张量的 type() 现在不再反映数据类型。请使用 isinstance()x.type() 代替:

>>> x = torch.DoubleTensor([1, 1, 1])
>>> print(type(x))  # was torch.DoubleTensor
"<class 'torch.Tensor'>"
>>> print(x.type())  # OK: 'torch.DoubleTensor'
'torch.DoubleTensor'
>>> print(isinstance(x, torch.DoubleTensor))  # OK: True
True

autograd 现在何时开始跟踪历史?

requires_grad ,作为 autograd 的中心标志,现在是一个属性;之前用于 Variables 的相同规则现在适用于 Tensors ;当操作中的任何输入 Tensorrequires_grad=True 时, autograd 开始跟踪历史记录。例如,

>>> x = torch.ones(1)  # create a tensor with requires_grad=False (default)
>>> x.requires_grad
False
>>> y = torch.ones(1)  # another tensor with requires_grad=False
>>> z = x + y
>>> # both inputs have requires_grad=False. so does the output
>>> z.requires_grad
False
>>> # then autograd won't track this computation. let's verify!
>>> z.backward()
RuntimeError: element 0 of tensors does not require grad and does not have a grad_fn
>>>
>>> # now create a tensor with requires_grad=True
>>> w = torch.ones(1, requires_grad=True)
>>> w.requires_grad
True
>>> # add to the previous result that has require_grad=False
>>> total = w + z
>>> # the total sum now requires grad!
>>> total.requires_grad
True
>>> # autograd can compute the gradients as well
>>> total.backward()
>>> w.grad
tensor([ 1.])
>>> # and no computation is wasted to compute gradients for x, y and z, which don't require grad
>>> z.grad == x.grad == y.grad == None
True

操作 requires_grad 标志

除了直接设置属性外,您还可以使用 my_tensor.requires_grad_() 来更改此标志 in-place ,或者,如上述示例所示,在创建时通过参数传递(默认为 False ),例如,

>>> existing_tensor.requires_grad_()
>>> existing_tensor.requires_grad
True
>>> my_tensor = torch.zeros(3, 4, requires_grad=True)
>>> my_tensor.requires_grad
True

那么 .data? 呢?

.data 是获取底层 Tensor 的主要方式。在此合并之后,调用 y = x.data 仍然具有相似的语义。因此, y 将是一个与 x 共享相同数据的 Tensor ,与 x 的计算历史无关,并且具有 requires_grad=False

然而, .data 在某些情况下可能不安全。对 x.data 的任何更改都不会被 autograd 跟踪,如果需要 x 进行反向传递,则计算出的梯度将是不正确的。一个更安全的替代方案是使用 x.detach() ,它也会返回一个与 requires_grad=False 共享数据的 Tensor ,但如果需要 x 进行反向传递,则其就地更改将由 autograd 报告。

下面是 .datax.detach() 之间的差异示例(以及为什么我们通常推荐使用 detach )。

如果你使用 Tensor.detach() ,则梯度计算将保证是正确的。

>>> a = torch.tensor([1,2,3.], requires_grad = True)
>>> out = a.sigmoid()
>>> c = out.detach()
>>> c.zero_()
tensor([ 0.,  0.,  0.])

>>> out  # modified by c.zero_() !!
tensor([ 0.,  0.,  0.])

>>> out.sum().backward()  # Requires the original value of out, but that was overwritten by c.zero_()
RuntimeError: one of the variables needed for gradient computation has been modified by an

然而,使用 Tensor.data 可能不安全,并且当需要用于梯度计算的张量但在原地修改时,很容易导致错误的梯度。

>>> a = torch.tensor([1,2,3.], requires_grad = True)
>>> out = a.sigmoid()
>>> c = out.data
>>> c.zero_()
tensor([ 0.,  0.,  0.])

>>> out  # out  was modified by c.zero_()
tensor([ 0.,  0.,  0.])

>>> out.sum().backward()
>>> a.grad  # The result is very, very wrong because `out` changed!
tensor([ 0.,  0.,  0.])

支持 0 维(标量)张量

以前,对 Tensor 向量(一维张量)进行索引返回 Python 数字,而对 Variable 向量进行索引(不一致地!)返回大小为 (1,) 的向量!类似的行存在于减少函数中,例如 tensor.sum() 返回 Python 数字,但 variable.sum() 返回大小为 (1,) 的向量。

幸运的是,这个版本引入了 PyTorch 中的正确标量(0 维张量)支持!可以使用新的 torch.tensor 函数创建标量(稍后将会详细介绍;现在只需将其视为 PyTorch 的 numpy.array 等效物)。现在您可以执行如下操作:

>>> torch.tensor(3.1416)         # create a scalar directly
tensor(3.1416)
>>> torch.tensor(3.1416).size()  # scalar is 0-dimensional
torch.Size([])
>>> torch.tensor([3]).size()     # compare to a vector of size 1
torch.Size([1])
>>>
>>> vector = torch.arange(2, 6)  # this is a vector
>>> vector
tensor([ 2.,  3.,  4.,  5.])
>>> vector.size()
torch.Size([4])
>>> vector[3]                    # indexing into a vector gives a scalar
tensor(5.)
>>> vector[3].item()             # .item() gives the value as a Python number
5.0
>>> mysum = torch.tensor([2, 3]).sum()
>>> mysum
tensor(5)
>>> mysum.size()
torch.Size([])

累积损失

在 0.4.0 之前, loss 是一个 Variable 包裹的尺寸为 (1,) 的张量,但在 0.4.0 中 loss 现在是一个标量,具有 0 维度。对标量进行索引没有意义(现在会给出警告,但在 0.5.0 中将是一个硬错误)。使用 loss.item() 从标量获取 Python 数字。

注意,如果您在累积损失时不将其转换为 Python 数字,您可能会发现程序中的内存使用量增加。这是因为上述表达式的右侧曾经是一个 Python 浮点数,而现在是零维张量。因此,总损失累积了张量和它们的梯度历史,这可能会保留比必要的更大的 autograd 图很长时间。

volatile 标志的弃用

volatile ” 标志现在已弃用,没有任何效果。之前,任何涉及 Variablevolatile=True 的计算都不会被 autograd 跟踪。现在已被一系列更灵活的上下文管理器所取代,包括 torch.no_grad()torch.set_grad_enabled(grad_mode) 等。

>>> x = torch.zeros(1, requires_grad=True)
>>> with torch.no_grad():
...     y = x * 2
>>> y.requires_grad
False
>>>
>>> is_train = False
>>> with torch.set_grad_enabled(is_train):
...     y = x * 2
>>> y.requires_grad
False
>>> torch.set_grad_enabled(True)  # this can also be used as a function
>>> y = x * 2
>>> y.requires_grad
True
>>> torch.set_grad_enabled(False)
>>> y = x * 2
>>> y.requires_grad
False

dtypesdevices 以及 NumPy 风格的创建函数

在 PyTorch 的早期版本中,我们通常将数据类型(例如 float 与 double)、设备类型(cpu 与 cuda)和布局(稠密与稀疏)一起指定为“张量类型”。例如, torch.cuda.sparse.DoubleTensor 是表示 Tensor 数据类型、位于 CUDA 设备上且具有 COO 稀疏张量布局的 double 类型。

在本次版本中,我们引入了 torch.dtypetorch.devicetorch.layout 类,以通过 NumPy 风格的创建函数更好地管理这些属性。

torch.dtype

以下是可用的 torch.dtype (数据类型)及其对应的张量类型完整列表。

数据 type torch.dtype 张量类型
32 位浮点数 torch.float32torch.float torch.*.FloatTensor
64 位浮点数 torch.float64torch.double torch.*.DoubleTensor
16 位浮点数 torch.float16torch.half torch.*.HalfTensor
8 位无符号整数 torch.uint8 torch.*.ByteTensor
8 位有符号整数 torch.int8 torch.*.CharTensor
16 位有符号整数 torch.int16torch.short torch.*.ShortTensor
32 位整数(有符号) torch.int32torch.int torch.*.IntTensor
64 位整数(有符号) torch.int64torch.long torch.*.LongTensor

张量的数据类型可以通过其 dtype 属性访问。

torch.device

torch.device 包含设备类型( 'cpu''cuda' )以及可选的设备序号(id)用于设备类型。它可以使用 torch.device('{device_type}')torch.device('{device_type}:{device_ordinal}') 初始化。

如果没有提供设备序号,则表示该设备类型的当前设备;例如, torch.device('cuda') 等同于 torch.device('cuda:X') ,其中 Xtorch.cuda.current_device() 的结果。

张量设备可以通过其 device 属性访问。

torch.layout

torch.layout 表示 Tensor 的数据布局。目前支持 torch.strided (默认的稠密张量)和 torch.sparse_coo (具有 COO 格式的稀疏张量)。

张量的布局可以通过其 layout 属性访问。

创建张量

创建 Tensor 的方法现在也接受 dtypedevicelayoutrequires_grad 选项来指定返回的 Tensor 的所需属性。例如,

>>> device = torch.device("cuda:1")
>>> x = torch.randn(3, 3, dtype=torch.float64, device=device)
tensor([[-0.6344,  0.8562, -1.2758],
        [ 0.8414,  1.7962,  1.0589],
        [-0.1369, -1.0462, -0.4373]], dtype=torch.float64, device='cuda:1')
>>> x.requires_grad  # default is False
False
>>> x = torch.zeros(3, requires_grad=True)
>>> x.requires_grad
True
torch.tensor(data, ...)

torch.tensor 是新增的 tensor 创建方法之一。它接受各种类型的 array-like 数据,并将包含的值复制到一个新的 Tensor 中。如前所述, torch.tensor 是 NumPy 的 numpy.array 构造函数的 PyTorch 等价物。与 torch.*Tensor 方法不同,您还可以通过这种方式创建零维的 Tensor (即标量)(单个 Python 数字在 torch.*Tensor methods 中被视为 Size)。此外,如果没有提供 dtype 参数,它将根据数据推断合适的 dtype 。这是从现有数据(如 Python 列表)创建 tensor 的推荐方法。例如,

>>> cuda = torch.device("cuda")
>>> torch.tensor([[1], [2], [3]], dtype=torch.half, device=cuda)
tensor([[ 1],
        [ 2],
        [ 3]], device='cuda:0')
>>> torch.tensor(1)               # scalar
tensor(1)
>>> torch.tensor([1, 2.3]).dtype  # type inferece
torch.float32
>>> torch.tensor([1, 2]).dtype    # type inferece
torch.int64

我们还增加了更多的 tensor 创建方法。其中一些有 torch.*_like 和/或 tensor.new_* 变体。

  • torch.*_like 接受一个输入 Tensor 而不是形状。它返回一个默认情况下具有与输入 Tensor 相同属性的 Tensor ,除非指定其他情况:

     >>> x = torch.randn(3, dtype=torch.float64)
     >>> torch.zeros_like(x)
     tensor([ 0.,  0.,  0.], dtype=torch.float64)
     >>> torch.zeros_like(x, dtype=torch.int)
     tensor([ 0,  0,  0], dtype=torch.int32)
    
  • 也可以创建具有与 tensor 相同属性的 Tensors ,但总是需要形状参数:

     >>> x = torch.randn(3, dtype=torch.float64)
     >>> x.new_ones(2)
     tensor([ 1.,  1.], dtype=torch.float64)
     >>> x.new_ones(4, dtype=torch.int)
     tensor([ 1,  1,  1,  1], dtype=torch.int32)
    

要指定所需的形状,您通常可以使用元组(例如, torch.zeros((2, 3)) )或可变参数(例如, torch.zeros(2, 3) )。

名称 返回 Tensor torch.*_like 变体 变体
torch.empty 未初始化的内存
torch.zeros 全零
torch.ones 全一
torch.full 填充给定的值
torch.rand 独立同分布的[0, 1)连续均匀分布  
torch.randn 独立同分布 Normal(0, 1)  
torch.randint 独立同分布的给定范围内的离散均匀分布  
torch.randperm 随机排列的 {0, 1, ..., n - 1}    
torch.tensor 复制自现有数据(列表、NumPy 数组等)  
torch.from_numpy* 来自 NumPy ndarray (共享存储而不复制)    
torch.arangetorch.range ,和 torch.linspace 给定范围内的均匀分布值    
torch.logspace 给定范围内的对数分布值    
torch.eye 单位矩阵    

*: torch.from_numpy 仅接受 NumPy ndarray 作为其输入参数。

编写设备无关的代码

PyTorch 的早期版本使得编写设备无关的代码变得困难(即无需修改即可在 CUDA 启用和仅 CPU 机器上运行的代码)。

PyTorch 0.4.0 通过两种方式使这变得更加容易:

  • 张量(Tensor)的 device 属性给出了所有张量的 torch.device( get_device 仅适用于 CUDA 张量)
  • to 方法可以轻松地将对象移动到不同的设备上(而不是根据上下文调用 cpu()cuda()

我们推荐以下模式:

# at beginning of the script
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")

...

# then whenever you get a new Tensor or Module
# this won't copy if they are already on the desired device
input = data.to(device)
model = MyModule(...).to(device)

nn.Module 中对子模块、参数和缓冲区名称的新边缘情况约束

如果 name 是空字符串或包含 "." ,则不再允许在 module.add_module(name, value)module.add_parameter(name, value)module.add_buffer(name, value) 中使用,因为这些名称可能导致 state_dict 中数据丢失。如果您正在加载包含此类名称的模块的检查点,请在加载之前更新模块定义并修补 state_dict

代码示例(综合应用)

为了了解 0.4.0 版本中推荐的总体更改,让我们快速看一下 0.3.1 和 0.4.0 中常见代码模式的示例:

  • 0.3.1(旧版本):
    model = MyRNN()
    if use_cuda:
        model = model.cuda()
    
    # train
    total_loss = 0
    for input, target in train_loader:
        input, target = Variable(input), Variable(target)
        hidden = Variable(torch.zeros(*h_shape))  # init hidden
        if use_cuda:
            input, target, hidden = input.cuda(), target.cuda(), hidden.cuda()
        ...  # get loss and optimize
        total_loss += loss.data[0]
    
    # evaluate
    for input, target in test_loader:
        input = Variable(input, volatile=True)
        if use_cuda:
            ...
        ...
    
  • 0.4.0(新版本):
    # 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()           # get Python number from 1-element Tensor
    
    # evaluate
    with torch.no_grad():                   # operations inside don't track history
        for input, target in test_loader:
            ...
    

感谢阅读!请参阅我们的文档和发行说明以获取更多详细信息。

祝您 PyTorch 愉快!