pypto-gym:基于 PyPTO 框架的昇腾AI处理器算子开发样例项目

PyPTO-Gym 是基于 PyPTO 编程框架构建的算子与模型样例仓库

Branch91Tags2

PyPTO-Gym

🔥最新动态

  • 2026/10:PyPTO-Gym 仓的路径结构近期将做一定范围内的重构,重构后的目标旨在将 PyPTO-Gym 构建成 “PyPTO 算子的 Agent 语料基地及算子最佳实践查找基地”,当前任务仍在进行中,更多信息参见 重构内容。
  • 2026/06:PyPTO-Gym 项目首次上线,本仓原为 PyPTO 仓的 models 目录,现已拆分为独立仓,与主仓解耦演进。

🚀概述

PyPTO-Gym 是基于 PyPTO 编程框架构建的样例仓库,面向华为昇腾(Ascend)AI 处理器,使用 PyPTO 的 Tile 编程模型,提供融合算子开发样例和大模型适配样例。这些样例均基于 CANNBot 完成设计、开发与调优工作。本仓作为 PyPTO 的"算子训练场",方便开发者学习、复用与对比。

  • 编程框架:PyPTO,基于 Tile 的编程模型
  • 内容:融合算子样例 + 大模型适配样例

Pro 算子的构建、安装与测试见构建指南,算子接口的获取方式见 pypto_gym 包内文档(help(pypto_gym)、get_ops()、prewarm())。 .run 使用 --ops ALL(或省略 --ops)时,只构建 ops/pro/build_ops.yaml 中列出的算子;路径相对于 ops/pro,注释对应行即可取消该算子的构建。

核心特性

  • 大模型核心算子样例:覆盖 DeepSeek V3.2/V4/V4.1、Qwen3 系列、GLM V4.5、Gemma4-31B-it、Kimi K3、Ling 3.1、MiniMax M2.7/M3、LLaDA2-MoE 等模型的关键算子实现
  • 实验性算子样例:基于实验性目录 experimental,收录 Attention、Matmul、Vector 等基础算子的开发态样例
  • 大模型适配样例:提供融合算子入网适配样例,以及端到端模型推理与性能基准脚本
  • Agent 能力:提供模型整网适配 skills,提升大模型对接易用性

目标用户

  • 算法开发者:主要使用Tensor层次编程,快速实现和验证算法,专注于算法逻辑
  • 系统开发者:可在Tensor和PTO虚拟指令集层次上进行三方框架对接或集成,以及工具链开发

环境准备

当前仓库支持的 CANN 版本如下:

CANN 版本 Tensor模式支持情况 Pro模式支持情况
9.1.0 支持 不支持
9.2.0 支持 支持

pypto-gym 无需单独安装。请先参照 PyPTO 文档完成环境部署:

  • 环境部署:介绍项目基础环境的搭建,包括软件包和第三方依赖的获取和安装。
  • 编译安装:环境部署后,介绍如何快速获取或编译 PyPTO 软件包并安装。

PyPTO 环境就绪后,克隆本仓并设置运行时环境变量:

# 加载 CANN 环境
source /usr/local/Ascend/ascend-toolkit/set_env.sh

# 指定运行的 NPU 设备 ID(根据实际可用 chip 设置)
export TILE_FWK_DEVICE_ID=0

推荐将上述内容保存为 env_setup.sh,每次执行 source env_setup.sh 即可。

⚡️快速上手

算子

1. 运行部分算子测试

# 使用 pytest 执行 GLM V4.5 Attention
pytest tests/ops/glm_v4_5/test_glm_attention.py

# 使用 pytest 执行 GLM V4.5 目录所有算子测试
pytest tests/ops/glm_v4_5 -v --forked

2. 运行全部算子测试

pytest -v --forked

具体测试范围参考 pytest.ini 配置

3. 指定 SoC

# 指定 NPU device id(覆盖 TILE_FWK_DEVICE_ID 环境变量)
pytest tests/ops/glm_v4_5 -v --forked --device 1

4. 用例筛选说明

测试用例通过 @pytest.mark.soc 标注适用芯片,conftest.py 会根据当前设备的 soc_version 自动过滤不适配的用例(显示为 SKIPPED)。部分规模较大的用例默认已使用 @pytest.mark.skip(reason="large test case") 标注,需手动移除 skip 标注后运行。

整网

1. 下载模型权重

python3 cannbot-skills/model/pypto-fused-op-integration/scripts/download_hf_model.py \
    --model-id Qwen/Qwen3-1.7B \
    --output-dir /path/to/models/Qwen3-1.7B

2. 入网适配

bash cannbot-skills/model/pypto-fused-op-integration/scripts/restore_model_patch.sh \
    /path/to/models/Qwen3-1.7B qwen3_1_7b

3. 验证

python3 modeling/transformers/qwen3_1_7b/ask_Qwen3-1.7B.py \
    --device 0 --prompt "你好" --use-pto \
    --model-path /path/to/models/Qwen3-1.7B

4. 使用限制

当前 PyPTO 在整网场景下存在以下限制:

  • 不支持多流并行:PyPTO 算子无法跨流并行执行,相关任务需在单流内串行调度。
  • 不支持 superkernel:整网场景下 PyPTO 算子不支持 superkernel 融合能力。

常见问题排查

Q: 报错 NPU out of memory

部分算子(如 sparse_flash_attention、gated_delta_rule)的 stitch_function_max_num 参数会影响 workspace 大小,公式为 workspace = totalSlot × (stitch_function_max_num + 1) × parallelism。可在 impl 文件对应 @pypto.frontend.jit 的 runtime_options 中降低该值(如从 128 降至 1)以减少内存占用,代价是降低并行度。

Q: 报错 npu_format_cast ACL error 500001

TBE(Tensor Boost Engine)初始化失败,通常由缺少 Python 依赖导致。执行以下命令修复:

pip install scipy decorator -i https://mirrors.aliyun.com/pypi/simple/

Q: 编译 PyPTO 时找不到 pto-isa 头文件

确认 PTO_TILE_LIB_CODE_PATH 指向 pto-isa 仓库根目录(含 include/ 子目录),且 pto-isa 版本与 PyPTO 兼容(建议两仓同步到最新)。

目录结构

pypto-gym/
├── cannbot-skills/                          # Agent skills(算子开发 / Pro / 模型适配 / 产物校验)
├── cmake/                                   # CMake 工具链与算子配置生成
├── docs/                                    # whl / .run 构建、安装与测试指南
├── modeling/                                # 模型端到端执行脚本
│   └── transformers/                        # 大模型推理示例
│       ├── infer.py                         # 通用推理入口
│       ├── download_hf_model.py             # HuggingFace 模型下载
│       ├── runtime_patch.py                 # PyPTO 运行时补丁覆盖层生成
│       ├── bench_qwen3_1_7b.sh              # Qwen3-1.7B 基准脚本
│       ├── deepseek-v2-lite-chat/           # DeepSeek V2 Lite Chat
│       ├── gemma4_31b_it/                   # Gemma4-31B-it
│       ├── gutenocr_3b/                     # GutenOCR-3B
│       ├── kimi_linear_48b_a3b/             # Kimi-Linear-48B-A3B
│       ├── llada2_moe/                      # LLaDA2-MoE
│       ├── minimax/                         # MiniMax M2.7
│       ├── openpangu_v5_7b/                 # openPangu-Embedded-7B
│       ├── phi_3_mini_4k_instruct/          # Phi-3-mini-4k-instruct
│       ├── qwen3_1_7b/                      # Qwen3-1.7B
│       ├── qwen3_5_9b/                      # Qwen3.5-9B
│       ├── qwen3_6_27b/                     # Qwen3.6-27B
│       ├── qwen3_vl_8b_instruct_unredacted_max/  # Qwen3-VL-8B
│       ├── spatial_ssrl_3b/                 # Spatial SSRL 3B
│       └── sample_inputs/                   # 公共样例输入
├── ops/                                     # 算子样例根目录
│   ├── pypto_tensor/                        # Tile 算子实现(整改中,后续将更名为tensor)
│   │   ├── arctic/                          # Arctic LSTM Speculator
│   │   ├── common_utils/                    # 公共工具(对比、日志、设备查询等)
│   │   ├── deepseek_v2_lite_chat/           # DeepSeek V2 Lite Chat MLA Prolog
│   │   ├── deepseek_v32_exp/                # DeepSeek V3.2 MLA / Sparse Attention / Lightning Indexer
│   │   ├── deepseek_v4/                     # DeepSeek V4 MLA / Compressor / Window Attention
│   │   ├── deepseek_v4_1/                   # DeepSeek V4.1 CSA2 Compressor
│   │   ├── gemma4_31b_it/                   # Gemma4-31B-it GQA Decode Attention / Softmax
│   │   ├── glm_v4_5/                        # GLM V4.5 Attention / MoE / FFN / Gate
│   │   ├── gutenocr_3b/                     # GutenOCR-3B RMSNorm / SwiGLU MLP / MRoPE
│   │   ├── kimi_linear_48b_a3b/             # Kimi-Linear-48B-A3B KDA
│   │   ├── ling_3_0_flash/                  # Ling 3.0 Flash KDA
│   │   ├── llada2/                          # LLaDA2 Liger Cross Entropy Loss
│   │   ├── llada2_moe/                      # LLaDA2-MoE Gate / Expert FFN / Grouped GEMM
│   │   ├── minimax/                         # MiniMax M2.7 MoE Grouped GEMM
│   │   ├── mtgr_segment_attention/          # MTGR Ragged Segment Attention
│   │   ├── openpangu_v5_7b/                 # openPangu-Embedded-7B 整层融合(单层 BSH)
│   │   ├── phi_3_mini_4k_instruct/          # Phi-3-mini-4k-instruct RMSNorm
│   │   ├── qat/                             # 量化感知训练(对称/非对称,per-tensor/channel/group)
│   │   ├── qwen3_1_7b/                      # Qwen3-1.7B RMSNorm + RoPE
│   │   ├── qwen3_5/                         # Qwen3.5 GDR 前向/反向
│   │   ├── qwen3_next/                      # Qwen3-Next Gated Delta Rule
│   │   ├── qwen3_vl_8b_instruct_unredacted_max/  # Qwen3-VL-8B RMSNorm
│   │   ├── spatial_ssrl_3b/                 # Spatial SSRL 3B RMSNorm + RoPE
│   │   └── experimental/                    # 实验性算子
│   ├── pypto_pro/                           # PyPTO Pro 算子(整改中,后续将合并到pro)
│   └── pro/                                 # Pro 二进制交付算子(op_host / op_kernel / tests)
│       ├── deepseek_v4_1/                   # DeepSeek V4.1 IFA Pro 算子
│       ├── kimi_k3/                         # Kimi K3 KDA / MLA 系列
│       ├── ling_3_1_flash/                  # Ling 3.1 Flash KDA 二进制算子
│       ├── experimental/                    # 实验性 Pro 二进制算子(conv / flex_attention)
│       └── build_ops.yaml                   # .run / whl 的 --ops ALL 构建清单
├── python/                                  # Python 包入口、JIT loader、Torch / ACLNN 绑定
├── scripts/                                 # .run 打包、安装与卸载脚本
├── src/
│   └── pypto_gym/
│       └── transformers/                    # 各个模型结构定义
├── tests/                                   # 测试用例
│   ├── common/                              # 公共测试调用层(op_caller 等)
│   ├── host/                                # 主机侧测试
│   ├── unit/                                # 构建、安装与绑定等单元测试
│   ├── ops/                                 # 算子测试(与 ops/ 对应)
│   └── README.md                            # 测试目录说明
├── tools/                                   # 代码生成校验等工具
├── build_ci.py                              # whl / .run 构建入口
├── conftest.py                              # pytest 调度(多卡 / 多 SoC 筛选)
├── CONTRIBUTING.md                          # 贡献指南
├── pytest.ini
├── pyproject.toml
├── setup.py
├── requirements.txt
├── LICENSE
├── OAT.xml
├── version.cmake
├── SECURITY.md
└── README.md

算子总览

Tensor 模式算子

所属模型 算子 说明
arctic/ sum_lstm LSTM 推测器(Arctic-Inference),融合输入、RMSNorm、GELU、门控与细胞状态更新
deepseek_v2_lite_chat/ mla_prolog MLA Prolog 预计算
deepseek_v32_exp/ mla_prolog_quant, lightning_indexer_prolog_quant, sparse_flash_attention_quant, sparse_attention_antiquant, mla_indexer_prolog_quant, lightning_indexer_quant MLA Prolog、Lightning Indexer、稀疏注意力等量化/非量化算子
deepseek_v4/ mla_prolog_v4, mla_prolog_quant_v4, lightning_indexer_prolog_quant_v4, compressor, compress_flash_attention, sparse_compress_flash_attention, win_attention, hc_pre, quant_lightning_indexer_flash_attention MLA Prolog、压缩器、压缩/稀疏 Flash Attention、窗口注意力、量化 Lightning Indexer + Flash Attention 融合等算子
deepseek_v4_1/ csa2_compressor DeepSeek V4.1 CSA2 token 压缩器(前向 + 反向,支持 BSH/TH、ratio 1/2)
gemma4_31b_it/ gqa_decode_attn, attn_softmax GQA 解码注意力(KV 头均值,带宽降低 75%)、3-pass Softmax
glm_v4_5/ attention_pre_quant, attention, attention_fusion, gate, select_experts, ffn_shared_expert_quant, moe_fusion 注意力(含量化前处理与融合)、MoE 门控/专家选择/FFN/融合等算子
gutenocr_3b/ swiglu_mlp, rms_norm, mrope SwiGLU MLP、RMSNorm、多模态 RoPE
kimi_linear_48b_a3b/ kda_chunk, kda_fused_decode_step Kimi Delta Attention(线性注意力,prefill/chunk + decode)
llada2/ liger_cross_entropy Liger Cross Entropy Loss(前向 + 反向)
llada2_moe/ llada2_moe_grouped_gemm All-experts 单 Grouped GEMM(替代逐专家循环)
ling_3_0_flash/ chunk_kda, fused_recurrent_kda KDA 融合算子(Chunk / Recurrent)
minimax/ minimax_moe_grouped_gemm, minimax_m3_msa_indexer, minimax_m3_msa_sparse_decode, msa_main_branch MiniMax M2.7 / M3 MoE Grouped GEMM,M3 MSA Indexer / 稀疏 Decode / Main Branch
mtgr_segment_attention/ mtgr_ragged_segment_attention 可变长 Flash Attention 前向(4 段策略 mask 组合)
openpangu_v5_7b/ pangu_fused_layer_v2_bsh 整解码层融合(RMSNorm+QKV(+bias)+RoPE+KV-cache+GQA Attention+O proj(+bias)+RMSNorm+SwiGLU FFN);单层 BSH 动态 kernel,仅 decode
phi_3_mini_4k_instruct/ rms_norm RMSNorm(D=3072),支持 ACLGraph
qat/ symmetric_per_tensor, symmetric_per_channel, asymmetric_per_group 量化感知训练三模式(前向 + 反向)
qwen3_1_7b/ rms_norm_rope RMSNorm + RoPE 融合
qwen3_5/ gdr_fwd, gdr_bwd Chunk Gated Delta Rule 前向/反向
qwen3_next/ gated_delta_rule Chunk Gated Delta Rule,线性复杂度 O(n),支持 1K-1M+ 序列长度(覆盖 Qwen3.5-9B / Qwen3.6-27B 场景)
qwen3_vl_8b_instruct_unredacted_max/ rms_norm RMSNorm(hidden_size=2048)
spatial_ssrl_3b/ rms_norm, rope RMSNorm + RoPE(Vision 2D / 多模态 3D)
experimental/matmul/ gmm_mxfp8 MXFP8 GMM 算子
experimental/ops_transformer/ attention_worker_combine, engram, flash_attention_fp8, flash_attention_mha, flash_attention_mha_grad, flash_attention_score, flash_attention_score_grad, fused_swiglu, fused_swiglu_grad, kimi_attention_residuals, mla_prolog, mla_prolog_mxfp_quant_v3, mla_prolog_quant_hifp8_v3, page_attention_quant, sparse_attention_antiquant_fp8, sparse_attention_antiquant_kv_split, sparse_attention_grad_tnd, sparse_attention_tnd Flash Attention(MHA/Score/FP8,含量化/反向)、MLA Prolog(含量化)、SwiGLU、Page Attention、稀疏注意力、Engram、Kimi Attention Residuals 等算子

Pro 模式算子

所属模型 算子 说明
pro/deepseek_v4_1/ atten_epilogue, attn_prologue, compressor_v2, engram_gate, engram_gate_bwd, engram_hash, indexer_prologue_k, indexer_prologue_qw, kv_compress_epilog_v2, mega_mhc, mhc_post_fwd, mhc_pre_fuse, mixed_quant_sparse_flash_mla, mixed_quant_sparse_flash_mla_metadata, quant_lightning_indexer, quant_sparse_lightning_indexer DeepSeek V4.1 IFA Pro 算子(JIT 直调 + ACLNN 双路由交付形态)
pro/kimi_k3/ block_attn_res_update_rms_norm, commit_recurrent_kda_replayssm, flash_kda_cp_preprocess, fused_recurrent_kda_replayssm, fused_recurrent_kda_snapshot, kda_cp_main, mega_recurrent_kda, mega_recurrent_kda_replayssm, quant_mla_prolog Kimi K3 KDA / MLA 系列:CP 预处理、状态递推、replay/snapshot、整层融合等
pro/ling_3_1_flash/ flash_kda, fused_recurrent_kda Ling 3.1 Flash KDA 预编译单 kernel(ACLNN 交付)
pro/experimental/ conv2d, flex_attention NCHW Conv2D 高性能实现、mask 契约驱动的 FlexAttention
pypto_pro/llada2/ liger_cross_entropy_loss Liger Cross Entropy Loss(Pro 实现)
pypto_pro/ling_3_1_flash/ flash_kda, fused_recurrent_kda, mla_prolog_v3 Ling 3.1 Flash KDA(flash / recurrent)与 MLA Prolog V3
pypto_pro/experimental/ops_transformer/ engram_forward, engram_backward, gate_kkt_kda, inversion_kda_cube, wy_kda_block, chunk_h_kda, chunk_o_kda, sparse_flash_mla_softmax_l1_norm 实验性 Pro 算子(Engram、KDA、Sparse Flash MLA 等)
pypto_pro/experimental/quant_bmm_mxfp8/ quant_batch_matmul_mxfp8 MXFP8 批量矩阵乘(融合可选 FP32 bias)
pypto_pro/experimental/quant_gemm_mxfp8/ quant_matmul_mxfp8 MXFP8 二维矩阵乘(split-K / A 常驻 / 滑动窗口)

添加新算子

  1. 按实现形态与模型归属,在 ops/ 下选择或创建合适的目录(若是通用算子,放入对应的 experimental/ 子类)。
  2. 编写 kernel 实现文件,命名建议为 *_impl.py,对外暴露入口函数 / 配置类。
  3. 用 @pytest.mark.soc("950", "910") 标注适用 SoC,用 @pytest.mark.world_size(N) 标注多卡需求。
  4. 编写 README.md 说明算子语义、shape 范围与预期性能,以及对应测试文件路径。

详细规范参见 CONTRIBUTING.md。

关联资源

Agent 能力快速上手

PyPTO-Gym 提供 PyPTO 算子开发、PyPTO-Pro 算子开发、模型适配和算子产物校验四类 Agent 能力。完整索引与安装说明见 cannbot-skills/README.md,各场景的快速上手指南见:

相关信息

联系我们

Introduction

PyPTO-Gym 是基于 PyPTO 编程框架构建的算子与模型样例仓库

Customize your domain