Provides MRE (Minimal Reproducible Example) code templates for PyTorch npugraph_ex compilation mode, including standard compile and cache_compile patterns.
Ships in torch-npugraph-ex-skills. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them.
从零生成 npugraph_ex 模式代码时,使用以下模板。所有模板遵循 agent 定义的 MRE 三段式结构(import → def infer_one_step() → if __name__ == "__main__")和固定变量名(config、compiled_model、dummy_input、output)。
import torch
class <模型名>(torch.nn.Module):
def __init__(self):
super().__init__()
# <模型层定义>
def forward(self, x):
# <前向逻辑>
return x
def infer_one_step():
"""
<功能描述(一句话)>
关键配置:
- backend="npugraph_ex" — Capture & Replay,任务下沉 Device,降低 Host 调度开销
- fullgraph=True — 整图捕获,不允许断图
- dynamic=False — 固定 shape(npugraph_ex底层调用的aclgraph不支持动态 shape,开启dynamic=True执行过程中可能会有多张aclgraph)
- <其他核心配置项> — <作用说明>
"""
model = <模型名>().npu().eval()
compiled_model = torch.compile(
model,
backend="npugraph_ex",
fullgraph=True,
dynamic=False,
)
dummy_input = torch.randn(<shape>).npu()
output = compiled_model(dummy_input)
if __name__ == "__main__":
infer_one_step()
import torch
class <模型名>(torch.nn.Module):
def __init__(self):
super().__init__()
# <模型层定义>
self.cached_forward = torch.npu.npugraph_ex.inference.cache_compile(
self._forward,
dynamic=False,
# cache_dir=".torchair_cache", # 可选,指定缓存路径
)
def forward(self, dummy_input):
"""
<功能描述(一句话)>
关键配置:
- torch.npu.npugraph_ex.inference.cache_compile — 替代 torch.compile,缓存 Dynamo 编译结果
- dynamic=False — 固定 shape(npugraph_ex底层调用的aclgraph不支持动态 shape,开启dynamic=True执行过程中可能会有多张aclgraph)
- cache_dir — 缓存文件保存路径,默认 .torchair_cache
- <其他核心配置项> — <作用说明>
"""
return self.cached_forward(dummy_input)
def _forward(self, dummy_input):
# <实际推理逻辑>
pass
def infer_one_step():
model = <模型名>().npu().eval()
dummy_input = torch.randn(<shape>).npu()
output = model(dummy_input)
if __name__ == "__main__":
infer_one_step()
当用户需求涉及自定义算子 + 图模式时,将下方对应的代码块嵌入代码中:从零生成代码时插入 MRE 的 import 区域之后、def infer_one_step() 之前;脚本迁移时在用户脚本的适当位置插入。模型内通过 torch.ops.<namespace>.<op_name>(x) 调用该算子。算子实现体用 # <用户实现> 占位,不替用户编写算子内部逻辑。生成前须先读取 custom_op_graph/non_in_place_op_cases.md 或 in_place_op_cases.md 验证写法。
结果写入新 tensor,不修改输入:
@torch.library.custom_op("mylib::my_op", mutates_args=(), device_types="npu")
def my_op(x: torch.Tensor) -> torch.Tensor:
# <用户实现>
...
@my_op.register_fake
def _(x: torch.Tensor) -> torch.Tensor:
return torch.empty_like(x)
原地修改输入,如 kv_cache 更新:
@torch.library.custom_op("mylib::my_op_", mutates_args=("x",), device_types="npu")
def my_op_(x: torch.Tensor) -> None:
# <用户实现:原地修改 x>
...
@my_op_.register_fake
def _(x: torch.Tensor) -> None:
return None
关键点:
mutates_args必须准确声明被修改的参数名;device_types="npu"在 NPU 场景下必须指定;register_fake(Meta 推导函数)负责告知编译器输出 tensor 的 shape/dtype/device,不执行实际计算。
对齐 torchair 官方文档(docs/zh/custom_op_graph/non_in_place_op_cases.md / in_place_op_cases.md)的生产级注册路径:算子由 Ascend C 工程化方式实现,通过 op-plugin yaml 完成 PyTorch 算子原型注册和 Eager 适配,Python 侧用 torch.library.Library + @impl 注册 Meta 推导函数。调用方式为 torch.ops.npu.<op_name>(...)。
前置依赖(本模板不覆盖,需用户自行完成):
- 用 msOpGen 创建 Ascend C 算子工程,编译并部署
custom_opp_<os>_<arch>.run- 在
third_party/op-plugin/op_plugin/config/op_plugin_functions.yaml的custom:字段下添加算子 schema,并配置gen_opapi(out.size/out.dtype/exec: aclnnXxx)- 重新编译安装 torch_npu(
bash ci/build.sh --python=<ver>)本模板只生成 Python 侧的 Meta 注册骨架(生产建议落在
op_plugin/python/meta/_meta_registrations.py,此处以 inline 形式给出便于自洽 MRE)。
import torch
from torch.library import Library, impl
# 对应 op_plugin_functions.yaml 中的 schema:
# custom:
# - func: my_op(Tensor x, Tensor? y, Tensor[] z, float attr1, int attr2) -> Tensor
# op_api: all_version
# gen_opapi:
# out:
# size: x
# dtype: x
# exec: aclnnMyOp
m = Library("npu", "IMPL", "Meta")
@impl(m, "my_op")
def my_op_meta(x, y, z, attr1, attr2):
# <根据算子语义推导输出 shape/dtype>
return torch.empty_like(x)
# 调用方式:torch.ops.npu.my_op(x, y, z, attr1, attr2)
import torch
from torch.library import Library, impl
# 对应 op_plugin_functions.yaml 中的 schema:
# custom:
# - func: my_inplace(Tensor(a!) x, Tensor y) -> Tensor
# op_api: all_version
# gen_opapi:
# out:
# size: y
# dtype: y
# exec: aclnnMyInplace
m = Library("npu", "IMPL", "Meta")
@impl(m, "my_inplace")
def my_inplace_meta(x, y):
# 输出 shape/dtype 与 y 相同;不返回被修改的输入 x
return torch.empty_like(y)
# 调用方式:torch.ops.npu.my_inplace(x, y)
关键点:
- In-place 算子 schema 中被修改的输入必须用
Tensor(a!)标注,且不返回任何被修改的输入(PyTorch 2.6+ 自动函数化的硬性约束)- Meta 推导函数必须在
torch.compile执行前完成注册- npugraph_ex 模式下完成 Meta 注册即可入图,无需额外 Converter(aclgraph 直接 capture & replay Eager 算子调用,不走 Ascend IR)
- 函数化转换由 TorchAir 自动完成,无需手动实现
What SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
7 skills in this plugin
/torch-custom-ops-guide自定义算子入图完整指南。覆盖从零开发、Eager 算子适配 npugraph_ex 图模式(torch.library.custom_op / torch.library.Library)、Meta 推导函数编写等全流程。适用于两种纯 Python 自定义算子注册场景。关键词:custom_op、torch.library.Library、register_fake、meta、mutates_args。/torch-npugraph-ex-compile-error-diagnosisPyTorch 昇腾 NPU npugraph_ex 编译期报错诊断。覆盖 torch.compile 触发后 TorchDynamo / FX / AOTAutograd / npugraph_ex backend / ACL graph capture 阶段的报错排查,包括 Unsupported / graph break / BackendCompilerFailed / Meta 推导失败 / capture 失败等场景。本 skill 由 dfx-triage 路由进入。触发:当用户遇到 npugraph_ex 入图失败、graph break、BackendCompilerFailed、Meta 推导失败或 capture 失败时加载。关键词:入图失败、断图、graph break、BackendCompilerFailed、Meta、FakeTensor、aot_eager、capture。/torch-npugraph-ex-dfx-triagePyTorch 昇腾 NPU npugraph_ex DFX 问题分诊入口。统一执行首轮全量日志收集与最少闭环信息核对,按报错栈和现象将问题路由到 compile-error / runtime-error / accuracy / performance 四个专科 sub-skill。本 skill 不输出最终诊断结论,只完成「采集 + 分类 + 加载下游 skill」。触发:当用户报告 npugraph_ex 相关报错、断图、精度差异或性能回退、需要 debug/dump 定位时加载。关键词:问题定位、报错、断图、精度、性能、debug、dump、aot_eager。/torch-npugraph-ex-knowledgenpugraph_ex(aclgraph)模式使用指南。采用 Capture & Replay 方式将算子任务下沉至 Device 执行,减少 Host 调度开销,适用于固定 shape 在线推理低延迟场景。涵盖模式配置、FX Pass、编译缓存、多流并行、内存复用、静态 Kernel 编译、限核、性能优化、调试定位、自定义算子入图等。关键词:npugraph_ex、aclgraph、backend="npugraph_ex"、capture、replay、reduce-overhead、config.aclgraph_config。/torch-npugraph-ex-performance-diagnosisPyTorch 昇腾 NPU npugraph_ex 性能诊断(FX 图静态审计,聚焦冗余 tensor move 与疑似 reinplace 未命中)。处理「5 step 全部通过、但推理慢/Device 利用率低」阶段:基于 TORCH_COMPILE_DEBUG=1 产出的 FX 图序列与 debug.log,定位 reinplace_inplaceable_ops_pass(out-of-place→in-place)与 reinplace_input_mutated_ops(折叠输入侧 copy_)回填未完成留下的 copy_/clone/out-of-place 冗余,并识别 Compressor 等 Python wrapper 显式 clone/copy_ 经 Functionalize 后伪装成 reinplace 失败的版本型问题。本 skill 由 dfx-triage 路由进入;**不**处理 graph break / recompile / guard failure(归 compile-error-diagnosis)。触发:当用户报告 npugraph_ex 推理慢、性能回退、怀疑图里有多余搬运/拷贝、reinplace 没生效时加载。关键词:性能、慢、tensormove、tensor move、reinplace、functionalize、copy_、clone、auto_functionalized、compressor、remove_noop_ops、multi_stream、can_inplace、missed reinplacing、inplace_pass、input_inplace_pass、clone_input、TORCH_COMPILE_DEBUG。/torch-npugraph-ex-runtime-error-diagnosisPyTorch 昇腾 NPU npugraph_ex 运行时报错诊断。覆盖 ACL graph 已 capture 成功之后,replay / kernel launch / 通信 / 内存 / device API 阶段的报错排查,包括 aclnnXxx 算子失败、HCCL 错误、stream/event 同步、segfault、device side assert、OOM 等场景。本 skill 由 dfx-triage 路由进入。触发:当用户遇到 npugraph_ex replay / aclnn / HCCL / stream / OOM 等运行时报错时加载。关键词:runtime、ACL、aclnn、HCCL、stream、event、device side assert、segfault、OOM、CANN plog。/torch-npugraph-ex-skills:torch-npugraph-ex-templatefrom torch-npugraph-ex-skills
npx claudepluginhub hicann/cannbot-skills --plugin torch-npugraph-ex-skills2 plugins ship this exact skill · first indexed Oct 20, 2026
Other plugins' skills for the same job