pytorch 中的 channels-last 内存布局格式

1,633 阅读8分钟

1. 什么是channels last

channels last内存格式是内存中排序 NCHW 张量的另一种方式。channels last张量以通道为最密集维度的方式排序(也就是按像素存储图像)。

例如,经典(连续)存储的NCHW 张量(在例子中是两个具有 3 个颜色通道的 4x4 图像)如下所示:

经典内存格式

参考图NCWH如下: image.png

channels last内存格式以不同的方式排序数据:

channels_last_memory_format

参考图NWHC如下: image.png

Pytorch 通过利用现有的 strides 结构来支持内存格式(并提供与现有模型的向后兼容性,包括 Eager、JIT 和 TorchScript)。例如,Channels last 格式中的 10x3x16x16 批次将具有等于 (768, 1, 48, 3) 的步幅。

channels last最后存储格式仅适用于 4D NCHW 张量。

2. 内存格式 API

以下是如何在连续格式和channels last存储格式之间转换张量。

经典 PyTorch 连续张量

import torch

N, C, H, W = 10, 3, 32, 32
x = torch.empty(N, C, H, W)
print(x.stride())  # Ouputs: (3072, 1024, 32, 1), 
# C=1024=32*32 (跨越1个通道) 
# N=3072=1024*3(跨越3通道)
(3072, 1024, 32, 1)

参考图NCWH如下: image.png

转换运算符

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)

参考图NWHC如下: image.png

返回连续

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())  # Ouputs: (3072, 1, 96, 3)
(3072, 1, 96, 3)

格式检查

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

有两个不同的API包含to和 contiguous. 建议在显式转换张量的内存格式时使用to

在一般情况下,这两个 API 的行为相同。然而,某些特殊情况,对于具有size大小的 4D 张量,在NCHW格式中且C==1H==1 && W==1 时,只有to会生成正确的步幅来表示channels-last内存格式。

这是因为在上述两种情况中的任何一种情况下,张量的内存格式都是不明确的,即具有size大小的N1HW在内存存储中既可以看作连续格式NCHW也可以看作channels-last NHWC,因为通道N=1。这种情况下,在给定的内存格式张量已经被认为是is_contiguous ,因此调用contiguous方法是空操作并且不会更新步幅。相反,to 会在尺寸为 1 的维度上以有意义的步幅重塑张量,以便正确表示预期的内存格式

special_x = torch.empty(4, 1, 4, 4) # 此处N=1
print(special_x.is_contiguous(memory_format=torch.channels_last))  # Ouputs: True
print(special_x.is_contiguous(memory_format=torch.contiguous_format))  # Ouputs: True
True
True

同样的事情也适用于显式排列 API permute。在可能发生歧义的特殊情况下,permute不保证产生正确携带预期内存格式的步幅。所以建议使用to显式调整内存格式以避免意外行为。

附带说明,在极端情况下,三个非批量维度都等于1(C==1 && H==1 && W==1 ),当前实现无法将张量标记为通道最后存储格式。

创建 channels last格式的张量

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

clone保留内存格式

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

tocudafloat... 保留内存格式

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

empty_like,*_like运算符保留内存格式

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

逐点运算符保留内存格式

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

Conv,使用 cudnn 后端的 Batchnorm 模块支持channels last (仅适用于 CudNN >= 7.6)。卷积模块与二元 p-wise 算子不同,channels last是主要的内存格式。IFF 所有输入都采用连续内存格式,运算符以连续内存格式产生输出。否则,输出将采用channels last格式。

if 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))  # Ouputs: True
True

当输入张量到达没有channels last支持的算子时,应该在内核中自动应用重排以恢复输入张量的连续性。这会引入开销并停止channels last的内存格式传播。然而,它保证了正确的输出。

3. 性能提升

在 GPU 和 CPU 上都可以使用channels last内存格式优化。在 GPU 上,在 NVidia 的硬件上观察到最显着的性能提升,Tensor Cores 支持以低精度运行 ( torch.float16)。与连续格式相比,我们能够获得超过 22% 的性能增益,同时使用“AMP(自动混合精度)”训练脚本。我们的脚本使用 NVidia github.com/NVIDIA/apex提供的 AMP 。

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% 的性能增益: alexnetmnasnet0_5mnasnet0_75mnasnet1_0mnasnet1_3mobilenet_v2resnet101resnet152resnet18resnet34resnet50resnext50_32x4dshufflenet_v2_x0_5shufflenet_v2_x1_0shufflenet_v2_x1_5shufflenet_v2_x2_0squeezenet1_0squeezenet1_1vgg11vgg11_bnvgg13vgg13_bnvgg16vgg16_bnvgg19vgg19_bnwide_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_2,wide_resnet50_2

4. 转换现有模型

Channels last格式支持不受现有模型的限制,因为任何模型都可以转换为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存储格式中具有其 4 维权重,将恢复channels_last存储格式并受益于更快的内核。

但是不支持channels_last的运算符确实会通过排列引入开销。或者,如果想提高转换模型的性能,可以调查并确定模型中最后不支持通道的运算符。

这意味着您需要根据支持的运算符列表github.com/pytorch/pyt…验证使用的运算符列表,或将内存格式检查引入急切执行模式并运行你的模型。

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

def contains_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


def print_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)


def check_wrapper(fn):
    name = fn.__name__

    def check_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()


def attribute(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)
Callable
__name__
List
__name__
Optional
'_SpecialForm' object has no attribute '__name__'
Tuple
__name__
Union
'_SpecialForm' object has no attribute '__name__'
Callable
__name__
Set
__name__
Union
'_SpecialForm' object has no attribute '__name__'

如果发现一个不支持channels_last张量的运算符并且您想做出贡献,请随时使用以下开发人员指南github.com/pytorch/pyt…

下面的代码是恢复的属性。

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

5.要做的工作

还有很多事情要做,比如:

  • 解决 N1HW 和 NC11 张量的歧义;
  • 测试分布式训练的支持;
  • 提高操作符覆盖率。

原文地址