命名张量¶
命名张量允许用户为张量维度指定显式名称。 在大多数情况下,采用维度参数的操作将接受 维度名称,无需按位置跟踪维度。 此外,命名张量使用名称来自动检查 API 在运行时被正确使用,从而提供额外的安全性。名称可以 也可用于重新排列尺寸,例如,支持 “按名称广播”而不是“按位置广播”。
警告
命名的张量 API 是一个原型功能,可能会发生变化。
创建命名张量¶
Factory 函数现在采用一个关联名称的新参数
与每个维度。names
>>> torch.zeros(2, 3, names=('N', 'C'))
tensor([[0., 0., 0.],
[0., 0., 0.]], names=('N', 'C'))
命名维度与常规 Tensor 维度一样,是有序的。 是 的维度名称。tensor.names[i]
i
tensor
以下工厂函数支持命名张量:
命名维度¶
>>> imgs = torch.randn(1, 2, 2, 3 , names=('N', 'C', 'H', 'W'))
>>> imgs.names
('N', 'C', 'H', 'W')
>>> renamed_imgs = imgs.rename(H='height', W='width')
>>> renamed_imgs.names
('N', 'C', 'height', 'width)
命名张量可以与未命名张量共存;命名张量是 的实例。未命名的张量具有 -named 维度。叫
张量不需要命名所有维度。
None
>>> imgs = torch.randn(1, 2, 2, 3 , names=(None, 'C', 'H', 'W'))
>>> imgs.names
(None, 'C', 'H', 'W')
名称传播语义¶
命名张量使用名称自动检查 API 是否被调用 正确地在运行时。这发生在一个称为名称推理的过程中。 更正式地说,名称推理包括以下两个步骤:
检查名称:操作员可以在运行时执行自动检查 检查某些维度名称是否必须匹配。
传播名称:名称推理将名称传播到输出张量。
所有支持命名张量的操作都会传播名称。
>>> x = torch.randn(3, 3, names=('N', 'C'))
>>> x.abs().names
('N', 'C')
匹配语义¶
如果两个名称相等(字符串相等)或至少有一个名称是 ,则两个名称匹配。
Nones 本质上是一个特殊的 “wildcard” 名称。None
unify(A, B)
确定哪些名称 和 传播到输出。
如果两个名称匹配,则返回两个名称中更具体的名称。如果名称不匹配,则
然后它出错了。A
B
基本名称推理规则¶
让我们看看在
添加两个没有广播的 one-dim 张量。match
unify
x = torch.randn(3, names=('X',))
y = torch.randn(3)
z = torch.randn(3, names=('Z',))
检查名称:检查两个张量的名称是否匹配。
对于以下示例:
>>> # x + y # match('X', None) is True
>>> # x + z # match('X', 'Z') is False
>>> # x + x # match('X', 'X') is True
>>> x + z
Error when attempting to broadcast dims ['X'] and dims ['Z']: dim 'X' and dim 'Z' are at the same position from the right but do not match.
Propagate names:统一名称以选择要传播的名称。
在 的情况下,因为 more
具体比 。x + y
unify('X', None) = 'X'
'X'
None
>>> (x + y).names
('X',)
>>> (x + x).names
('X',)
有关名称推理规则的完整列表,请参阅命名张量运算符覆盖率。 以下是两个可能有用的常见操作:
二进制算术运算:统一输入中的名称
矩阵乘法运算:Contract away dims
按名称显式对齐¶
使用 or
对齐张量维度
by name 设置为指定的 ordering。这对于执行 “按名称广播” 很有用。
# This function is agnostic to the dimension ordering of `input`,
# as long as it has a `C` dimension somewhere.
def scale_channels(input, scale):
scale = scale.refine_names('C')
return input * scale.align_as(input)
>>> num_channels = 3
>>> scale = torch.randn(num_channels, names=('C',))
>>> imgs = torch.rand(3, 3, 3, num_channels, names=('N', 'H', 'W', 'C'))
>>> more_imgs = torch.rand(3, num_channels, 3, 3, names=('N', 'C', 'H', 'W'))
>>> videos = torch.randn(3, num_channels, 3, 3, 3, names=('N', 'C', 'H', 'W', 'D')
>>> scale_channels(imgs, scale)
>>> scale_channels(more_imgs, scale)
>>> scale_channels(videos, scale)
操纵尺寸¶
>>> tensor = torch.randn(2, 2, 2, 2, 2, 2)
>>> named_tensor = tensor.refine_names('A', 'B', 'C', 'D', 'E', 'F')
# Move the F (dim 5) and E dimension (dim 4) to the front while keeping
# the rest in the same order
>>> tensor.permute(5, 4, 0, 1, 2, 3)
>>> named_tensor.align_to('F', 'E', ...)
使用 和
展平和取消展平
维度。这些方法比
和 更
冗长,但对于阅读代码的人来说具有更多的语义意义。
>>> imgs = torch.randn(32, 3, 128, 128)
>>> named_imgs = imgs.refine_names('N', 'C', 'H', 'W')
>>> flat_imgs = imgs.view(32, -1)
>>> named_flat_imgs = named_imgs.flatten(['C', 'H', 'W'], 'features')
>>> named_flat_imgs.names
('N', 'features')
>>> unflattened_named_imgs = named_flat_imgs.unflatten('features', [('C', 3), ('H', 128), ('W', 128)])
>>> unflattened_named_imgs.names
('N', 'C', 'H', 'W')
Autograd 支持¶
Autograd 目前以有限的方式支持命名张量:autograd 忽略 names 的所有张量。梯度计算仍然是正确的,但我们失去了 名字给我们带来安全感。
>>> x = torch.randn(3, names=('D',))
>>> weight = torch.randn(3, names=('D',), requires_grad=True)
>>> loss = (x - weight).abs()
>>> grad_loss = torch.randn(3)
>>> loss.backward(grad_loss)
>>> weight.grad # Unnamed for now. Will be named in the future
tensor([-1.8107, -0.6357, 0.0783])
>>> weight.grad.zero_()
>>> grad_loss = grad_loss.refine_names('C')
>>> loss = (x - weight).abs()
# Ideally we'd check that the names of loss and grad_loss match but we don't yet.
>>> loss.backward(grad_loss)
>>> weight.grad
tensor([-1.8107, -0.6357, 0.0783])
当前支持的操作和子系统¶
子系统¶
支持 Autograd,请参阅 Autograd 支持。 由于梯度当前未命名,因此优化器可能有效,但未经测试。
NN 模块目前不受支持。这可能会导致在调用 具有命名张量输入的模块:
NN 模块参数未命名,因此输出可能会部分命名。
NN 模块前向传递的代码不支持命名张量,并且将 错误适当地出来。
我们也不支持以下子系统,尽管有些子系统可能会正常工作 的盒子:
命名张量 API 参考¶
在本节中,请找到命名张量特定 API 的文档。 有关如何通过其他 PyTorch 传播名称的全面参考 运算符,请参阅命名张量运算符覆盖率。
- 类 Torch 的 Torch 类张肌
- 名字¶
存储此张量的每个维度的名称。
names[idx]
对应于 Tensor 维度 的名称。 如果维度已命名,则名称为字符串,或者如果 dimension 未命名。idx
None
维度名称可以包含字符或下划线。此外,维度 name 必须是有效的 Python 变量名称(即,不以下划线开头)。
张量不能有两个同名的命名维度。
警告
命名的张量 API 是实验性的,可能会发生变化。
- rename(*names, **rename_map)[来源]¶
重命名 的维度名称。
self
有两个主要用途:
self.rename(**rename_map)
返回具有 dim 的 Tensor 视图 按照映射 中的指定重命名。rename_map
self.rename(*names)
返回 Tensor 上的视图,将 all 重命名为 使用. 用于在张量上放置名称。
self.rename(None)
不能同时指定 positional args
和 keyword args 。
rename_map
例子:
>>> imgs = torch.rand(2, 3, 5, 7, names=('N', 'C', 'H', 'W')) >>> renamed_imgs = imgs.rename(N='batch', C='channels') >>> renamed_imgs.names ('batch', 'channels', 'H', 'W') >>> renamed_imgs = imgs.rename(None) >>> renamed_imgs.names (None, None, None, None) >>> renamed_imgs = imgs.rename('batch', 'channel', 'height', 'width') >>> renamed_imgs.names ('batch', 'channel', 'height', 'width')
警告
命名的张量 API 是实验性的,可能会发生变化。
- refine_names(*names)[来源]¶
根据 优化 的维度名称。
self
优化是重命名的一种特殊情况,它会“提升”未命名的维度。 dim 可以细化为具有任何名称;命名的 dim 只能是 优化为具有相同的名称。
None
由于命名张量可以与未命名张量共存,因此优化名称 提供了一种编写命名张量感知代码的好方法,该代码适用于两者 命名和未命名的张量。
最多可以包含一个省略号 ()。 省略号贪婪地扩展;它就地展开以填充
到与使用 的相应索引 。
...
self.dim()
self.names
Python 2 不支持省略号,但可以使用字符串文字 而不是 () 。
'...'
- 参数
names (iterable of str) - 输出张量的所需名称。五月 最多包含一个省略号。
例子:
>>> imgs = torch.randn(32, 3, 128, 128) >>> named_imgs = imgs.refine_names('N', 'C', 'H', 'W') >>> named_imgs.names ('N', 'C', 'H', 'W') >>> tensor = torch.randn(2, 3, 5, 7, 11) >>> tensor = tensor.refine_names('A', ..., 'B', 'C') >>> tensor.names ('A', None, None, 'B', 'C')
警告
命名的张量 API 是实验性的,可能会发生变化。
- align_as(其他) 张量 ¶
排列张量的维度以匹配维度顺序 在 Tensor 中,为任何新名称添加 size-one 维度。
self
other
此操作对于按名称进行显式广播非常有用(请参阅示例)。
为了使用此方法,必须命名 的所有 dims 。 生成的张量是原始张量的视图。
self
的所有维度名称都必须存在于 中。 可能包含不在 ; Output Tensor 对于每个新名称都有一个大小为 1 的维度。
self
other.names
other
self.names
例子:
# Example 1: Applying a mask >>> mask = torch.randint(2, [127, 128], dtype=torch.bool).refine_names('W', 'H') >>> imgs = torch.randn(32, 128, 127, 3, names=('N', 'H', 'W', 'C')) >>> imgs.masked_fill_(mask.align_as(imgs), 0) # Example 2: Applying a per-channel-scale >>> def scale_channels(input, scale): >>> scale = scale.refine_names('C') >>> return input * scale.align_as(input) >>> num_channels = 3 >>> scale = torch.randn(num_channels, names=('C',)) >>> imgs = torch.rand(32, 128, 128, num_channels, names=('N', 'H', 'W', 'C')) >>> more_imgs = torch.rand(32, num_channels, 128, 128, names=('N', 'C', 'H', 'W')) >>> videos = torch.randn(3, num_channels, 128, 128, 128, names=('N', 'C', 'H', 'W', 'D')) # scale_channels is agnostic to the dimension order of the input >>> scale_channels(imgs, scale) >>> scale_channels(more_imgs, scale) >>> scale_channels(videos, scale)
警告
命名的张量 API 是实验性的,可能会发生变化。
- align_to(*names)[来源]¶
排列张量的维度以匹配顺序 在
中指定,为任何新名称添加 size-one dims。
self
为了使用此方法,必须命名 的所有 dims 。 生成的张量是原始张量的视图。
self
的所有维度名称都必须存在于
中。
可能包含不在 ; Output Tensor 对于每个新名称都有一个大小为 1 的维度。
self
self.names
最多可以包含一个省略号 ()。 省略号将展开,以等于 中未提及
的所有维度名称,并按其显示顺序排列 在。
...
self
self
Python 2 不支持省略号,但可以使用字符串文字 而不是 () 。
'...'
- 参数
names (iterable of str) – 所需的维度顺序 output 张量。最多可以包含一个展开的省略号 到所有未提及的 Dim 名称。
self
例子:
>>> tensor = torch.randn(2, 2, 2, 2, 2, 2) >>> named_tensor = tensor.refine_names('A', 'B', 'C', 'D', 'E', 'F') # Move the F and E dims to the front while keeping the rest in order >>> named_tensor.align_to('F', 'E', ...)
警告
命名的张量 API 是实验性的,可能会发生变化。
- flatten(dims, out_dim) 张量
展平为名称为 的单个维度 。
dims
out_dim
所有 dims 必须在张量中按顺序连续, 但不一定是 contigued in memory。
self
例子:
>>> imgs = torch.randn(32, 3, 128, 128, names=('N', 'C', 'H', 'W')) >>> flat_imgs = imgs.flatten(['C', 'H', 'W'], 'features') >>> flat_imgs.names, flat_imgs.shape (('N', 'features'), torch.Size([32, 49152]))
警告
命名的张量 API 是实验性的,可能会发生变化。