PyTorch 入门指南
学习 PyTorch
图像和视频
音频
后端
强化学习
在生产环境中部署 PyTorch 模型
Profiling PyTorch
代码变换与FX
前端API
扩展 PyTorch
模型优化
并行和分布式训练
边缘端的 ExecuTorch
推荐系统
多模态

(测试版) PyTorch 中的 Channels Last 内存格式

作者: Vitaly Fedyunin

什么是 Channels Last

Channels last 内存格式是一种替代的 NCHW 张量在内存中的排列方式,它保留了维度顺序。Channels last 张量以一种使得通道成为最密集维度(即按像素存储图像)的方式排列。

例如,经典的(连续的)NCHW 张量存储(在我们的例子中是两张 4x4 图像,每张图像有 3 个颜色通道)看起来像这样:

经典内存格式

通道优先内存格式以不同的方式排列数据:

channels_last_memory_format

PyTorch 通过利用现有的步幅结构来支持内存格式(并提供与现有模型的向后兼容性,包括 eager、JIT 和 TorchScript)。例如,一个 10x3x16x16 的批次在 Channels last 格式下的步幅将为 (768, 1, 48, 3)。

Channels last 内存格式目前仅针对 4D NCHW 张量实现。

内存格式 API

以下是如何在连续内存格式和通道最后内存格式之间转换张量。

经典 PyTorch 连续张量

importtorch

N, C, H, W = 10, 3, 32, 32
x = torch.empty(N, C, H, W)
print(x.stride())  # Outputs: (3072, 1024, 32, 1)
(3072, 1024, 32, 1)

转换操作符

x = x.to(memory_format=torch.channels_last)
print(x.shape)  # Outputs: (10, 3, 32, 32) as dimensions order preserved
print(x.stride())  # Outputs: (3072, 1, 96, 3)
torch.Size([10, 3, 32, 32])
(3072, 1, 96, 3)

返回连续内存布局

x = x.to(memory_format=torch.contiguous_format)
print(x.stride())  # Outputs: (3072, 1024, 32, 1)
(3072, 1024, 32, 1)

替代方案

x = x.contiguous(memory_format=torch.channels_last)
print(x.stride())  # Outputs: (3072, 1, 96, 3)
(3072, 1, 96, 3)

格式检查

print(x.is_contiguous(memory_format=torch.channels_last))  # Outputs: True
True

tocontiguous 这两个 API 之间存在一些细微差异。我们建议在显式转换张量的内存格式时使用 to

在一般情况下,这两个 API 的行为是相同的。然而,在某些特殊情况下,对于一个大小为 NCHW 的 4D 张量,当 C==1H==1 && W==1 时,只有 to 会生成一个合适的步幅来表示通道最后的内存格式。

这是因为在上述两种情况下,张量的内存格式是模糊的,即一个大小为 N1HW 的连续张量在内存存储中既是连续的,也是通道最后的。因此,它们已经被视为给定内存格式下的 is_contiguous,因此 contiguous 调用将变为无操作,并且不会更新步幅。相反,to 会重新调整张量的步幅,以便在大小为 1 的维度上生成有意义的步幅,从而正确表示预期的内存格式。

special_x = torch.empty(4, 1, 4, 4)
print(special_x.is_contiguous(memory_format=torch.channels_last))  # Outputs: True
print(special_x.is_contiguous(memory_format=torch.contiguous_format))  # Outputs: True
True
True

同样适用于显式排列 API permute。在可能产生歧义的特殊情况下,permute 并不保证生成能够正确传递预期内存格式的步幅。我们建议使用带有明确内存格式的 to 来避免意外行为。

另外需要注意的是,在极端情况下,当三个非批次维度都等于 1 时(C==1 && H==1 && W==1),当前的实现无法将张量标记为 channels last 内存格式。

创建为 channels last 格式。

x = torch.empty(N, C, H, W, memory_format=torch.channels_last)
print(x.stride())  # Outputs: (3072, 1, 96, 3)
(3072, 1, 96, 3)

clone 保留内存格式

y = x.clone()
print(y.stride())  # Outputs: (3072, 1, 96, 3)
(3072, 1, 96, 3)

to, cuda, float … 保留内存格式

if torch.cuda.is_available():
    y = x.cuda()
    print(y.stride())  # Outputs: (3072, 1, 96, 3)
(3072, 1, 96, 3)

empty_like, *_like 操作符保留内存格式

y = torch.empty_like(x)
print(y.stride())  # Outputs: (3072, 1, 96, 3)
(3072, 1, 96, 3)

逐点操作符保留内存格式

z = x + y
print(z.stride())  # Outputs: (3072, 1, 96, 3)
(3072, 1, 96, 3)

使用 cudnn 后端的 ConvBatchnorm 模块支持 channels last 格式(仅适用于 cuDNN >= 7.6)。与二元逐点操作符不同,卷积模块以 channels last 作为主导的内存格式。如果所有输入都是连续的内存格式,操作符将输出连续的内存格式。否则,输出将以 channels last 的内存格式呈现。

if torch.backends.cudnn.is_available() and torch.backends.cudnn.version() >= 7603:
    model = torch.nn.Conv2d(8, 4, 3).cuda().half()
    model = model.to(memory_format=torch.channels_last)  # Module parameters need to be channels last

    input = torch.randint(1, 10, (2, 8, 4, 4), dtype=torch.float32, requires_grad=True)
    input = input.to(device="cuda", memory_format=torch.channels_last, dtype=torch.float16)

    out = model(input)
    print(out.is_contiguous(memory_format=torch.channels_last))  # Outputs: True
True

当输入张量到达不支持 channels last 格式的运算符时,内核应自动应用置换操作以恢复输入张量的连续性。这会引入额外的开销并中断 channels last 内存格式的传播。尽管如此,它确保了输出结果的正确性。

性能提升

通道最后内存格式优化在 GPU 和 CPU 上均可用。在 GPU 上,最显著的性能提升出现在支持 Tensor Cores 的 NVIDIA 硬件上,且运行在降低精度(torch.float16)下。与连续格式相比,在使用‘AMP(自动混合精度)’训练脚本时,我们能够实现超过 22% 的性能提升。我们的脚本使用了 NVIDIA 提供的 AMP https://github.com/NVIDIA/apex

python main_amp.py -a resnet50 --b 200 --workers 16 --opt-level O2  ./data

# opt_level = O2
# keep_batchnorm_fp32 = None <class 'NoneType'>
# loss_scale = None <class 'NoneType'>
# CUDNN VERSION: 7603
# => creating model 'resnet50'
# Selected optimization level O2:  FP16 training with FP32 batchnorm and FP32 master weights.
# Defaults for this optimization level are:
# enabled                : True
# opt_level              : O2
# cast_model_type        : torch.float16
# patch_torch_functions  : False
# keep_batchnorm_fp32    : True
# master_weights         : True
# loss_scale             : dynamic
# Processing user overrides (additional kwargs that are not None)...
# After processing overrides, optimization options are:
# enabled                : True
# opt_level              : O2
# cast_model_type        : torch.float16
# patch_torch_functions  : False
# keep_batchnorm_fp32    : True
# master_weights         : True
# loss_scale             : dynamic
# Epoch: [0][10/125] Time 0.866 (0.866) Speed 230.949 (230.949) Loss 0.6735125184 (0.6735) Prec@1 61.000 (61.000) Prec@5 100.000 (100.000)
# Epoch: [0][20/125] Time 0.259 (0.562) Speed 773.481 (355.693) Loss 0.6968704462 (0.6852) Prec@1 55.000 (58.000) Prec@5 100.000 (100.000)
# Epoch: [0][30/125] Time 0.258 (0.461) Speed 775.089 (433.965) Loss 0.7877287269 (0.7194) Prec@1 51.500 (55.833) Prec@5 100.000 (100.000)
# Epoch: [0][40/125] Time 0.259 (0.410) Speed 771.710 (487.281) Loss 0.8285319805 (0.7467) Prec@1 48.500 (54.000) Prec@5 100.000 (100.000)
# Epoch: [0][50/125] Time 0.260 (0.380) Speed 770.090 (525.908) Loss 0.7370464802 (0.7447) Prec@1 56.500 (54.500) Prec@5 100.000 (100.000)
# Epoch: [0][60/125] Time 0.258 (0.360) Speed 775.623 (555.728) Loss 0.7592862844 (0.7472) Prec@1 51.000 (53.917) Prec@5 100.000 (100.000)
# Epoch: [0][70/125] Time 0.258 (0.345) Speed 774.746 (579.115) Loss 1.9698858261 (0.9218) Prec@1 49.500 (53.286) Prec@5 100.000 (100.000)
# Epoch: [0][80/125] Time 0.260 (0.335) Speed 770.324 (597.659) Loss 2.2505953312 (1.0879) Prec@1 50.500 (52.938) Prec@5 100.000 (100.000)

传递 --channels-last true 允许以 Channels last 格式运行模型,观察到性能提升 22%。

python main_amp.py -a resnet50 --b 200 --workers 16 --opt-level O2 --channels-last true ./data

# opt_level = O2
# keep_batchnorm_fp32 = None <class 'NoneType'>
# loss_scale = None <class 'NoneType'>
#
# CUDNN VERSION: 7603
#
# => creating model 'resnet50'
# Selected optimization level O2:  FP16 training with FP32 batchnorm and FP32 master weights.
#
# Defaults for this optimization level are:
# enabled                : True
# opt_level              : O2
# cast_model_type        : torch.float16
# patch_torch_functions  : False
# keep_batchnorm_fp32    : True
# master_weights         : True
# loss_scale             : dynamic
# Processing user overrides (additional kwargs that are not None)...
# After processing overrides, optimization options are:
# enabled                : True
# opt_level              : O2
# cast_model_type        : torch.float16
# patch_torch_functions  : False
# keep_batchnorm_fp32    : True
# master_weights         : True
# loss_scale             : dynamic
#
# Epoch: [0][10/125] Time 0.767 (0.767) Speed 260.785 (260.785) Loss 0.7579724789 (0.7580) Prec@1 53.500 (53.500) Prec@5 100.000 (100.000)
# Epoch: [0][20/125] Time 0.198 (0.482) Speed 1012.135 (414.716) Loss 0.7007197738 (0.7293) Prec@1 49.000 (51.250) Prec@5 100.000 (100.000)
# Epoch: [0][30/125] Time 0.198 (0.387) Speed 1010.977 (516.198) Loss 0.7113101482 (0.7233) Prec@1 55.500 (52.667) Prec@5 100.000 (100.000)
# Epoch: [0][40/125] Time 0.197 (0.340) Speed 1013.023 (588.333) Loss 0.8943189979 (0.7661) Prec@1 54.000 (53.000) Prec@5 100.000 (100.000)
# Epoch: [0][50/125] Time 0.198 (0.312) Speed 1010.541 (641.977) Loss 1.7113249302 (0.9551) Prec@1 51.000 (52.600) Prec@5 100.000 (100.000)
# Epoch: [0][60/125] Time 0.198 (0.293) Speed 1011.163 (683.574) Loss 5.8537774086 (1.7716) Prec@1 50.500 (52.250) Prec@5 100.000 (100.000)
# Epoch: [0][70/125] Time 0.198 (0.279) Speed 1011.453 (716.767) Loss 5.7595844269 (2.3413) Prec@1 46.500 (51.429) Prec@5 100.000 (100.000)
# Epoch: [0][80/125] Time 0.198 (0.269) Speed 1011.827 (743.883) Loss 2.8196096420 (2.4011) Prec@1 47.500 (50.938) Prec@5 100.000 (100.000)

以下模型列表完全支持 Channels last 格式,并在 Volta 设备上展示了 8%-35% 的性能提升:alexnet, mnasnet0_5, mnasnet0_75, mnasnet1_0, mnasnet1_3, mobilenet_v2, resnet101, resnet152, resnet18, resnet34, resnet50, resnext50_32x4d, shufflenet_v2_x0_5, shufflenet_v2_x1_0, shufflenet_v2_x1_5, shufflenet_v2_x2_0, squeezenet1_0, squeezenet1_1, vgg11, vgg11_bn, vgg13, vgg13_bn, vgg16, vgg16_bn, vgg19, vgg19_bn, wide_resnet101_2, wide_resnet50_2

以下模型列表完全支持 Channels last 格式,在 Intel(R) Xeon(R) Ice Lake(或更新)CPU 上可带来 26%-76% 的性能提升:alexnetdensenet121densenet161densenet169googlenetinception_v3mnasnet0_5mnasnet1_0resnet101resnet152resnet18resnet34resnet50resnext101_32x8dresnext50_32x4dshufflenet_v2_x0_5shufflenet_v2_x1_0squeezenet1_0squeezenet1_1vgg11vgg11_bnvgg13vgg13_bnvgg16vgg16_bnvgg19vgg19_bnwide_resnet101_2wide_resnet50_2

转换现有模型

通道最后(channels last)的支持并不局限于现有模型,因为只要输入(或某些权重)格式正确,任何模型都可以转换为通道最后格式,并通过图传播该格式。

# Need to be done once, after model initialization (or load)
model = model.to(memory_format=torch.channels_last)  # Replace with your model

# Need to be done for every input
input = input.to(memory_format=torch.channels_last)  # Replace with your input
output = model(input)

然而,并非所有运算符都完全转换为支持“channels last”格式(通常返回的是连续输出)。在上面发布的示例中,不支持“channels last”的层将停止内存格式的传播。尽管如此,由于我们已经将模型转换为“channels last”格式,这意味着每个卷积层的四维权重将以“channels last”内存格式存储,从而恢复“channels last”内存格式并受益于更快的计算内核。

但那些不支持“channels last”的运算符确实会通过重排引入开销。可选地,如果您想提高转换后模型的性能,可以调查并识别模型中不支持“channels last”的运算符。

这意味着您需要根据支持的运算符列表https://github.com/pytorch/pytorch/wiki/Operators-with-Channels-Last-support验证所使用的运算符,或者将内存格式检查引入到即时执行模式中并运行您的模型。

在运行以下代码后,如果运算符的输出与输入的内存格式不匹配,运算符将引发异常。

defcontains_cl(args):
    for t in args:
        if isinstance(t, torch.Tensor):
            if t.is_contiguous(memory_format=torch.channels_last) and not t.is_contiguous():
                return True
        elif isinstance(t, list) or isinstance(t, tuple):
            if contains_cl(list(t)):
                return True
    return False


defprint_inputs(args, indent=""):
    for t in args:
        if isinstance(t, torch.Tensor):
            print(indent, t.stride(), t.shape, t.device, t.dtype)
        elif isinstance(t, list) or isinstance(t, tuple):
            print(indent, type(t))
            print_inputs(list(t), indent=indent + "    ")
        else:
            print(indent, t)


defcheck_wrapper(fn):
    name = fn.__name__

    defcheck_cl(*args, **kwargs):
        was_cl = contains_cl(args)
        try:
            result = fn(*args, **kwargs)
        except Exception as e:
            print("`{}` inputs are:".format(name))
            print_inputs(args)
            print("-------------------")
            raise e
        failed = False
        if was_cl:
            if isinstance(result, torch.Tensor):
                if result.dim() == 4 and not result.is_contiguous(memory_format=torch.channels_last):
                    print(
                        "`{}` got channels_last input, but output is not channels_last:".format(name),
                        result.shape,
                        result.stride(),
                        result.device,
                        result.dtype,
                    )
                    failed = True
        if failed and True:
            print("`{}` inputs are:".format(name))
            print_inputs(args)
            raise Exception("Operator `{}` lost channels_last property".format(name))
        return result

    return check_cl


old_attrs = dict()


defattribute(m):
    old_attrs[m] = dict()
    for i in dir(m):
        e = getattr(m, i)
        exclude_functions = ["is_cuda", "has_names", "numel", "stride", "Tensor", "is_contiguous", "__class__"]
        if i not in exclude_functions and not i.startswith("_") and "__call__" in dir(e):
            try:
                old_attrs[m][i] = e
                setattr(m, i, check_wrapper(e))
            except Exception as e:
                print(i)
                print(e)


attribute(torch.Tensor)
attribute(torch.nn.functional)
attribute(torch)

如果您发现某个操作符不支持通道在后的张量,并且您希望贡献代码,请随意使用以下开发者指南 https://github.com/pytorch/pytorch/wiki/Writing-memory-format-aware-operators

以下代码用于恢复 torch 的属性。

for (m, attrs) in old_attrs.items():
    for (k, v) in attrs.items():
        setattr(m, k, v)

待办事项

还有许多事情需要完成,例如:

  • 解决 N1HWNC11 张量的歧义问题;

  • 测试分布式训练的支持情况;

  • 提升操作符的覆盖率。

如果您有反馈和/或改进建议,请通过创建 问题 告知我们。

本页目录