聊聊Pytorch2.0的新特性

Pytorch2.0的核心是torch.compile,它能优化模型,提升运行速度,适用于训练和部署。TorchDynamo解析Python字节码,TorchInductor是神经网络编译器,两者旨在优化性能。虽然提升不比TensorRT显著,但使用简便且拓展性强。文章还提到了多个与Pytorch相关的编译和优化工具,并提供了性能测试示例。
部署运行你感兴趣的模型镜像

一句话概括下,Pytorch2.0的功能介绍核心就是:torch.compile

opt_module = torch.compile(module)

一行代码就能优化你的模型,优化后的模型和往常使用方式一样

速度会提升,比较重要的一点是:可以用于训练或者部署,训练可以传梯度

这次是带有AOT autograd

官方测试了三个模型仓库的模型,在A100的加速比如下:

在这里插入图片描述

看提速,提升没有超一倍,相比TensorRT(TensorRT优化的话,一般都是2-6倍左右,当然要算FP16)

torch.compile优化级别还是差些的,性能肯定不是极致,更不如纯手工优化后的

不过胜在好用以及拓展性强,可以应付大部分的训练和部署场景,使用起来很方便

吐槽的一点,现在和Pytorch沾边的库越来越多了,加速模型的,部署模型的,编译器类型的, 大概有这些:

  • torchscript(torch.jit)
  • lazy tensor
  • torch.fx
  • torch::deploy
  • AItemplate
  • nvfuser
  • TorchDynamo
  • TorchInductor
  • AOTAutograd
  • PrimTorch
  • torch_tensorrt
  • functorch
  • torch2trt

而这次2.0强调的是TorchDynamoTorchInductor

TorchDynamo: 是解析Python字节码,可以trace你的model

TorchInductor:是神经网络编译器,将pytorch模型lower为IR然后生成高性能的CUDA或者CPU代码

TorchDynamo相比fxjittrace,可以更方便地跟踪data-dependent分支,而且不像torch.script一样需要修改代码

感觉TorchDynamo就是加强普适版的fxtorchscript

TorchInductor就是编译器,有对应的IR(define-by-run IR)

然后可以利用tritoncodegen生成高性能的算子

triton这个名字有点歧义哈,这里指的不是triton-server-inference

而是一个类似于TVMscript的可以通过python语法去写高性能GPU程序的

在这里插入图片描述
深度学习编译器大繁荣的时代来了,啥都要编译来干了

不管是之前的torchscript还是torch.fx

以及新出的TorchDynamoTorchInductor,总之就是编译优化编译优化

在这里插入图片描述
编译器这块晦涩难懂,想要了解底层学习的,难度还是挺大(没时间学了)

希望Pytorch这个新的编译器,之后使用起来bug少一些,问题看起来直观一些…


这个Pytorch2.0版本其实就是1.14,只不过官方认为torch.compile这个功能意义重大,所以干脆2.0了

现在放出的是beta版,稳定版的话在明年3月

所以说对之前版本完全兼容

在这里插入图片描述
首先按照官网的要求来安装

pip3 install numpy --pre torch[dynamo] torchvision torchaudio --force-reinstall --extra-index-url https://download.pytorch.org/whl/nightly/cu117

然后跑几个模型试试,按照以下的方式进行测试

调用compiled_model = torch.compile(model)来对模型进行优化,对比优化前和优化后的速度以及余弦相似度

import torch
import time
import torch._dynamo
import torchvision.models as models

torch._dynamo.config.verbose=True
torch._dynamo.config.suppress_errors = True
torch.set_float32_matmul_precision('high')

model = models.resnet50().cuda()

print("prepare model and input")
dummy_input = torch.randn(1,3,1024,1024).cuda()

NITER = 300
print("warm...")
for _ in range(10):
    res = model(dummy_input)
    torch.cuda.synchronize()
    
print("begin eval ...")
torch.cuda.synchronize()
s = time.time()
for _ in range(NITER):
    res = model(dummy_input)
    torch.cuda.synchronize()
    
print('benchmark time (CUDA normal) (ms/iter)', (time.time() - s) / NITER * 1000)

compiled_model = torch.compile(model)
print("warm...")
for _ in range(10):
    res_compiled = compiled_model(dummy_input)
    torch.cuda.synchronize()
    
print("begin eval ...")
torch.cuda.synchronize()
s = time.time()
for _ in range(NITER):
    res_compiled = compiled_model(dummy_input)
    torch.cuda.synchronize()
    
print('benchmark time (torch.compiled) (ms/iter)', (time.time() - s) / NITER * 1000)
print("check res cosine_similarity")
assert (
    torch.nn.functional.cosine_similarity(
        res.flatten(), res_compiled.flatten(), dim=0
    )
    > 0.9999
)

测试结果如下,输入都是torch.randn(1,3,1024,1024).cuda()

其中reduce-overheadmax-autotunetorch.compile函数中的优化参数

除了r50,我也试了下dla结构的模型,其中with_dcn是带了自定义cuda实现的pytorch-dcn算子

在这里插入图片描述
compile的优化细节还没有细看,可以简单看下官方的描述:

# API NOT FINAL
# default: optimizes for large models, low compile-time
#          and no extra memory usage
torch.compile(model)

# reduce-overhead: optimizes to reduce the framework overhead
#                and uses some extra memory. Helps speed up small models
torch.compile(model, mode="reduce-overhead")

# max-autotune: optimizes to produce the fastest model,
#               but takes a very long time to compile
torch.compile(model, mode="max-autotune")

reduce-overhead的意思是适合小模型

而max-autotune则是相当于trt或者tvm那样对整个模型进行编译优化了

选用这个的时候,compile的明显时间变长

我测试的几个模型没有明显提升甚至会编译失败,原因应该比较复杂,需要深入去看


放一个torch.compile的函数介绍:

def compile(model: Optional[Callable] = None, *,
            fullgraph: builtins.bool = False,
            dynamic: builtins.bool = False,
            backend: Union[str, Callable] = "inductor",
            mode: Union[str, None] = None,
            passes: Optional[Dict[str, Union[str, builtins.int, builtins.bool]]] = None,
            **kwargs) -> Callable:
    """
    Optimizes given model/function using Dynamo and specified backend

    Args:
       model (Callable): Module/function to optimize
       fullgraph (bool): Whether it is ok to break model into several subgraphs
       dynamic (bool): Use dynamic shape tracing
       backend (str or Callable): backend to be used
       mode (str): Can be either "default", "reduce-overhead" or "max-autotune"
       passes (dict): A dictionary of passes to the backend. Passes currently recognized by inductor backend:
                       - static-memory
                       - matmul-tune
                       - matmul-padding
                       - triton-autotune
                       - triton-bmm
                       - triton-mm
                       - triton-convolution
                       - rematerialize-threshold
                       - rematerialize-acc-threshold

    Example::

        @torch.compile(passes={"matmul-padding": True}, fullgraph=True)
        def foo(x):
            return torch.sin(x) + torch.cos(x)

    """

后续

Pytorch2.0的版本,可能Dynamo会成为主要的模型的parser替代torch.fx.tracetorch.jit.trace成为我们常用的工具

之后Pytorch转trt、转tvm、转乱七八槽一切也会慢慢往这个上头靠。。。


参考文献

  1. https://pytorch.org/get-started/pytorch-2.0
  2. https://mp.weixin.qq.com/s/yK_RDG6qB2rAOuMGqC5sWQ

您可能感兴趣的与本文相关的镜像

Python3.8

Python3.8

Conda
Python

Python 是一种高级、解释型、通用的编程语言,以其简洁易读的语法而闻名,适用于广泛的应用,包括Web开发、数据分析、人工智能和自动化脚本

### 安装PyTorch 2.0于Ubuntu系统 #### 准备工作 为了确保顺利安装PyTorch 2.0,在开始之前需确认已正确设置好环境。这包括但不限于更新系统的软件包列表并安装必要的依赖项。 #### 使用Conda创建虚拟环境 推荐通过Anaconda或Miniconda来管理Python环境及其依赖关系,这样可以更方便地处理不同项目之间的库冲突问题。对于特定版本的需求,比如这里提到的Python 3.8和CUDA 11.7组合,应该先建立一个新的conda环境[^4]: ```bash conda create --name pytorch_env python=3.8 conda activate pytorch_env ``` #### 安装PyTorch 2.0 访问官方提供的安装页面https://pytorch.org/get-started/locally/, 根据个人需求挑选适合的操作系统、包管理工具(此处选用`conda`)、Python版本以及CUDA版本。针对本案例中的配置——即Linux操作系统下的Python 3.8与CUDA 11.7兼容版PyTorch 2.0,可采用如下命令完成安装[^2]: ```bash conda install pytorch torchvision torchaudio cudatoolkit=11.7 -c pytorch-nightly ``` 注意:上述命令来源于官方网站最新发布的指导说明;如果需要安装旧版本如PyTorch 1.7,则应参照历史记录获取相应的安装指令,并适当调整参数以适应当前环境的要求[^3]。 #### 验证安装成功与否 最后一步是验证新安装的PyTorch是否能够正常运行。可以通过导入模块并在交互式解释器中打印其版本号来进行简单测试: ```python import torch print(torch.__version__) ```
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小鹏AI

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值