Closed
[torch_extension] import cann_ops_transformer 强制编译 5 个 eager 算子,影响首次加载耗时 #4154
PerrySkywalkerAdd on  Aug 5Closed at  Aug 7
PerrySkywalker
PerrySkywalkerCollaborators
Aug 5 Create

问题描述

import cann_ops_transformer 时,即使只使用其中一个算子,也会强制 JIT 编译 5 个算子的 C++ 扩展(.so),导致首次 import 耗时显著变长(数十秒到数分钟)。

根因分析

torch_extension/cann_ops_transformer/__init__.py:13 通过 from . import ops 触发 ops/__init__.py,后者在包顶层全量 import 所有算子模块。其中 5 个算子文件在模块顶层(非函数体内)调用了 OpBuilder.load(),模块加载即触发 torch.utils.cpp_extension.load() 编译 .cpp → .so:

文件 行号 模块级 load() 调用
ops/quant_flash_attn.py 227 op_module = quant_flash_attn_op_builder.load()
ops/moe_finalize_routing.py 89 _op_module = _moe_finalize_routing_builder.load()
ops/dense_lightning_indexer_softmax_lse.py 105 op_module = dense_lightning_indexer_softmax_lse_op_builder.load()
ops/inplace_partial_rotary_mul.py 101 inplace_partial_rotary_mul_op_builder.load()
ops/inplace_partial_rotary_mul_backward.py 85 inplace_partial_rotary_mul_backward_op_builder.load()

其余约 30 个算子(如 flash_attn、sparse_flash_mla、compressor 等)的 load() 调用均在 @impl 装饰的 dispatcher 函数体内(4 空格缩进),属于懒加载——首次调用算子时才编译,import 时只执行 OpBuilder() 注册 schema/meta。

影响

  1. 首次 import 耗时长:用户只用 flash_attn,却要为 quant_flash_attn 等 5 个未用算子支付编译开销(首次编译 + ninja 链接)。
  2. 依赖放大:quant_flash_attn 等 eager 算子的 .cpp 依赖对应的 ACLNN 头文件,若环境缺失相关头文件,会导致即使不用该算子也无法 import 整个包。
  3. 与文档示例不一致:README 的 Quick Start 给出 cann_ops_transformer.ops.abs(x) 的轻量用法预期,但实际 import 代价远高于此。

eager 加载的动机

inplace_partial_rotary_mul.py:98-100 注释说明:

# Pre-load the op module so that torch.compile / dynamo tracing does not
# encounter torch.utils.cpp_extension.load() at trace time (it is marked
# as "skipped" by the dynamo trace rules).

即这 5 个算子需在 torch.compile/dynamo trace 前加载好 .so,否则 dynamo 会把 cpp_extension.load() 当作 break-graph 的 skip 节点。

建议方案

  1. 懒加载改造(推荐):将这 5 个文件的模块级 load() 移入 dispatcher 函数体,并验证 dynamo trace 是否确实报错。若报错,可在 torch.compile 入口路径单独预热,而非在包 import 时全量编译。
  2. ops/__init__.py 改懒加载:用 __getattr__(PEP 562,见 comm_context.py:48 已有先例)延迟 import 子模块,使 import cann_ops_transformer 不触发任何算子模块加载。
  3. 显式预热 API:提供 cann_ops_transformer.warmup(ops=[...]) 让用户按需预热 dynamo 场景所需的算子,而非默认 eager。

复现

import time
t = time.time()
import cann_ops_transformer  # 触发 5 个 eager 算子编译
print(f"import cost: {time.time() - t:.1f}s")

首次运行可观察到明显编译耗时;删除 ~/.cache/torch_extensions/ 后复现稳定。

likedislike
PerrySkywalkerPerrySkywalkerCollaborators
Aug 5 changed custom category from 任务 to 缺陷
PerrySkywalkerPerrySkywalkerCollaborators
Aug 5 changed custom priority from 无优先级 to 主要
weihao18
weihao18Collaborators
Aug 5 Comments:

/assign @weihao18

likedislike
CANN-robotCANN-robotCollaborators
Aug 5 Assign weihao18 as responsible person
weihao18weihao18Collaborators
Aug 7 Associated pull request
CANN-robotCANN-robotCollaborators
Aug 7 Close issue
CANN-robotCANN-robotCollaborators
Aug 7 Added label: resolved