深度学习系列72:torch-tensorrt入门

1. 安装

坑非常多,清华源阿里源都不行。使用官网源下载,这里的121可以改成你需要的东西:

python -m pip install torch torch-tensorrt tensorrt --extra-index-url https://download.pytorch.org/whl/cu121

2. 原理

我们来看一个实例:这是一个用于支持 torchscript 到 TensorRT 转换的项目。上面的代码用于将 addmm 运算展开成数个算子,方便后续映射 TensorRT 算子。

复制代码
void UnpackAddMM(std::shared_ptr<torch::jit::Graph>& graph) {
  // TensorRT implicitly adds a flatten layer in front of FC layers if necessary
  // 用于匹配的模式
  std::string addmm_pattern = R"IR(
    graph(%b, %x, %w, %beta, %alpha):
      %out: Tensor = aten::addmm(%b, %x, %w, %beta, %alpha)
      return (%out))IR";
  // 用于替换的模式
  std::string mm_add_pattern = R"IR(
    graph(%b, %x, %w, %beta, %alpha):
      %mm: Tensor = aten::matmul(%x, %w)
      %bias: Tensor = aten::mul(%b, %beta)
      %out: Tensor = aten::add(%bias, %mm, %alpha)
      return (%out))IR";

  // 创建子图重写器并注册匹配模式和替换模式
  torch::jit::SubgraphRewriter unpack_addmm;
  unpack_addmm.RegisterRewritePattern(addmm_pattern, mm_add_pattern);
  // 遍历graph,完成重写
  unpack_addmm.runOnGraph(graph);
  LOG_GRAPH("Post unpack addmm: " << *graph);
}

3. 简单例子

复制代码
import torch
def origin_func(x):
    x = x**2
    x = x**3
    return x

x = torch.rand(1, 2, 3, 4)
jit_model = torch.jit.trace(origin_func, x)
print(jit_model.graph)

# 匹配用的子图定义,注意常量必须为[value=2]属性
pattern = """
    graph(%x):
        %const_2 = prim::Constant[value=2]()
        %out = aten::pow(%x, %const_2)
        return (%out)
"""
# 替换用的子图定义
replacement = """
    graph(%x):
        %out = aten::mul(%x, %x)
        return (%out)
"""
torch._C._jit_pass_custom_pattern_based_rewrite_graph(pattern, replacement,jit_model.graph)
print(jit_model.graph)
相关推荐
霍小毛2 分钟前
破局工业智能化:数字孪生+AI+智慧SCADA平台,重构企业高效运营新范式
人工智能·重构
爱喝热水的呀哈喽3 分钟前
gpt:RAG步骤
人工智能·python·机器学习
ViiTor_AI4 分钟前
AI短剧译制Pipeline实战
人工智能
feng14566 分钟前
OpenSREClaw - 混沌工程驱动的风险防控利器
人工智能
QiZhang | UESTC7 分钟前
InstructGPT_论文精读笔记
人工智能·笔记·深度学习
侃谈科技圈10 分钟前
模型之外,声网定义了AI交互新标准
人工智能
weixin_5536544811 分钟前
ChatGPT好用还是Gemini好用?
人工智能·chatgpt·大模型
阿文的代码库12 分钟前
机器学习评价指标之转换化为二分类任务
人工智能·分类·数据挖掘
余衫马13 分钟前
Microsoft Semantic Kernel 实战:使用内核参数实现一个简单的对话机器人
人工智能·microsoft·ai·agent·智能体
搞科研的小刘选手13 分钟前
【大连市计算机学会主办】第三届图像处理、智能控制与计算机工程国际学术会议(IPICE 2026)
图像处理·人工智能·深度学习·算法·计算机·数据挖掘·智能控制