CANN skills 是昇腾开源社区提供的「脚手架工具」集——不是算子、不是加速库、不是框架适配。它是辅助开发的命令行工具和脚本,帮助开发者在昇腾 NPU 上更快地上手、调试、部署。CANN 社区的同学用得最多的包括:算子开发脚手架(op-gen)、性能分析脚本(prof-parser)、容器化部署模板(docker-templates)、CI 辅助脚本(ci-helpers)。

算子开发脚手架(op-gen)

手写一个完整的 Ascend C 算子需要:Proto 定义、算子注册、kernel 实现、测试用例、CMakeLists.txt——五个文件,每个都有固定模板。op-gen 一次性生成全部。

# 安装 skills CLI
git clone https://atomgit.com/cann/skills
cd skills && pip install ./

# 生成一个新算子
ascend-skill op-gen \
    --name=LayerNormV2 \
    --type=vector \
    --inputs="x:float16[H,W] gamma:float16[H] beta:float16[H]" \
    --outputs="y:float16[H,W]" \
    --attributes="epsilon:float=1e-5"

# 生成的目录结构:
# my-layer-norm-v2/
# ├── ops-proto/
# │   └── layer_norm_v2.proto        # Proto 定义
# ├── kernels/
# │   └── layer_norm_v2_kernel.cpp   # Kernel 骨架代码
# ├── cmake/
# │   └── CMakeLists.txt             # 构建配置
# ├── test/
# │   ├── test_layer_norm_v2.py      # Python 测试
# │   └── test_data.py               # 测试数据生成
# └── README.md                      # 文档模板

生成的 kernel 骨架代码:

// kernels/layer_norm_v2_kernel.cpp(op-gen 自动生成)

#include "ascendc/ascend_c.h"
#include "ascendc/platform.h"

// op-gen 自动生成的算子类(包含标准结构)
class LayerNormV2 {
public:
    // 算子参数结构体(自动生成)
    struct Params {
        int H, W;
        float epsilon;
    };

    // 算子注册(自动生成)
    ASCENDC_OP_REGISTER(LayerNormV2, "layer_norm_v2");

    // Tiling 计算(需手动实现)
    static Params ComputeTiling(const OpContext& ctx) {
        // TODO: 填写 tiling 逻辑
        Params p;
        p.H = ctx.input_shape[0][1];  // auto-generated
        p.W = ctx.input_shape[0][2];  // auto-generated
        p.epsilon = ctx.attrs["epsilon"];
        return p;
    }

    // Kernel 入口(需手动实现核心逻辑)
    template <typename T>
    __aicore__ void Process(const Params& p,
                            GlobalTensor<T>& x,
                            GlobalTensor<T>& gamma,
                            GlobalTensor<T>& beta,
                            GlobalTensor<T>& y) {
        // TODO: 填写 kernel 实现
        // 分组处理(auto-generated block dispatch)
        for (int i = block_idx_x; i < p.H; i += grid_dim_x) {
            // 对每一行做 LayerNorm
            float mean = ComputeMean(x[i]);
            float var = ComputeVariance(x[i], mean);
            float inv_std = 1.0f / sqrtf(var + p.epsilon);

            for (int j = 0; j < p.W; j++) {
                float normed = (float(x[i][j]) - mean) * inv_std;
                y[i][j] = T(normed * float(gamma[j]) + float(beta[j]));
            }
        }
    }
};

op-gen 的价值:一个命令生成 95% 的代码(Proto 定义、算子注册、构建配置、测试框架)。开发者只需要填写 kernel 实现(Process 函数)和 tiling 逻辑(ComputeTiling),其他的骨架代码都是标准化的。

性能分析脚本(prof-parser)

msprof 输出 JSON 格式的 profiling 数据——200+ 个算子的 time/cube_util/vector_util/hbm_rw 在 500ms 的推理过程中采集到的数据可能生成 100KB 的 JSON。手动看是噩梦。prof-parser 自动提取关键指标。

# 用 prof-parser 解析 profiling 数据
ascend-skill prof-parse \
    --input=msprof_output.json \
    --topk=10 \
    --min-utilization=0.5 \
    --output=prof_report.md

# 输出(prof_report.md):
# # Profile Report
#
# ## Top 10 Operations by Duration
# | Rank | Op Name              | Duration(ms) | % Total | Cube Util | Vector Util |
# |------|---------------------|-------------|---------|-----------|-------------|
# | 1    | MatMul_0             | 45.2        | 22.6%   | 92%       | 3%          |
# | 2    | FlashAttention_0     | 38.1        | 19.0%   | 85%       | 15%         |
# | 3    | Softmax_0            | 12.3        | 6.2%    | 0%        | 95%         |
# | 4    | LayerNorm_0          | 8.7         | 4.4%    | 0%        | 78%         |
# | 5    | Add_0                | 5.2         | 2.6%    | 0%        | 35%  ← 利用率低
#
# ## Low Utilization Operations (Vector Util < 50%)
# - Add_0: Vector Util 35%, DataCopy dominates (5.2ms total, 3.8ms DataCopy)
#   → Suggestion: Fuse Add_0 with previous operator to reduce HBM round trips
#
# ## HBM Bandwidth
# Avg HBM Read: 812 GB/s  (87% of peak 934 GB/s)
# Avg HBM Write: 423 GB/s (73% of peak 580 GB/s)

容器化部署模板(docker-templates)

CANN 社区用的 Docker 镜像有两类:开发镜像(带 gcc/cmake/pip)和生产镜像(只含运行时,体积小)。docker-templates 提供两种模板。

# skills/docker-templates/ascend-dev.Dockerfile

FROM ubuntu:22.04

# 基础开发环境
RUN apt-get update && apt-get install -y \
    gcc-11 g++-11 cmake python3-pip git

# 安装 CANN toolkit(从官方源)
ENV ASCEND_HOME=/usr/local/Ascend/ascend-toolkit/latest
COPY ascend-toolkit_8.0.0_linux-x86_64.run /tmp/
RUN /tmp/ascend-toolkit_8.0.0_linux-x86_64.run --install \
    --install-path=/usr/local/Ascend/ascend-toolkit

ENV LD_LIBRARY_PATH=$ASCEND_HOME/lib64:$LD_LIBRARY_PATH
ENV PATH=$ASCEND_HOME/bin:$PATH

# 安装开发依赖
RUN pip3 install torch_npu pyasc numpy
# skills/docker-templates/ascend-inference.Dockerfile

FROM ubuntu:22.04

# 只带运行时(体积小,适合容器化部署)
ENV ASCEND_HOME=/usr/local/Ascend/ascend-runtime/latest
COPY ascend-runtime_8.0.0_linux-x86_64.run /tmp/
RUN /tmp/ascend-runtime_8.0.0_linux-x86_64.run --install \
    --install-path=/usr/local/Ascend/ascend-runtime

ENV LD_LIBRARY_PATH=$ASCEND_HOME/lib64:$LD_LIBRARY_PATH

# 生产镜像不装 gcc/cmake/pip(减少攻击面)
# 模型和推理引擎由外层 kubectl 挂载进容器

生产镜像从开发镜像裁剪 ~800MB(去掉编译器、Python、git),更适合 K8s 高速拉取。

CI 辅助脚本(ci-helpers)

CANN 社区的 CI/CD 管道需要特殊的硬件(昇腾 NPU 卡)。GitHub Actions / Jenkins 的标准 runner 没有 NPU 硬件——需要自建 runner,自建 runner 的硬件管理比标准 runner 复杂(硬件故障、多 runner 资源竞争)。ci-helpers 提供自动化脚本。

# ci-helpers/run_tests.sh
# 在 CI runner 上执行算子测试

#!/bin/bash
set -e

# Step 1:获取可用 NPU(ci-helpers 自动检测未被占用的 NPU)
AVAILABLE_NPU=$(ascend-skill ci-get-npu --count=1)
export ASCEND_DEVICE_ID=$AVAILABLE_NPU

# Step 2:编译算子(cmake 版本切换)
ascend-skill ci-build \
    --cmake-version=3.16 \
    --cann-version=8.0.0 \
    --build-dir=build_ci

# Step 3:运行测试
python3 test/test_ops.py --device=$ASCEND_DEVICE_ID

# Step 4:收集测试结果
ascend-skill ci-report \
    --test-log=test_results.log \
    --output-format=junit \
    --output=test_report.xml

踩坑一:op-gen 生成的 kernel 默认使用 FP16 但没做溢出保护

op-gen 的 LayerNorm 模板默认用 FP16 数据类型。但 (x - mean) * inv_std 的中间结果在 FP16 下可能溢出(x 和 mean 都是 0-1 范围,但 inv_std 可能很大——方差接近 1e-6 时 inv_std=1000)。FP16 最大值 65504——1000 × 1 = 1000,没溢出,但 inv_std = 1/sqrt(1e-6) = 1000000 时直接溢出。

修复:在 kernel 内部强制转 FP32 做中间计算。

// 错误:op-gen 默认模板
y[i][j] = (x[i][j] - mean) * inv_std * gamma[j] + beta[j];  // FP16

// 正确:手动改成 FP32
float normed = (float(x[i][j]) - mean) * inv_std;
float result = normed * float(gamma[j]) + float(beta[j]);
y[i][j] = half(result);  // 最后才转回 FP16

踩坑二:prof-parser 的 topk 对流水线并行的误解

两个算子流水线并行(Load A 和 Compute B 同时跑),prof-parser 找不到的 PipeBarrier 时间会归咎到前面的算子。实际问题是流水线气泡,不是算子慢。

# prof-parser 输出:
# MatMul_0: 45.2ms(22.6%)
# PipeBarrier_1: 15.3ms(7.7%)← 实际是流水线气泡,不是算子

# 正确解读:
# PipeBarrier_1 对应的 Compute B 依赖 Load A 的数据
# Load A 从 HBM 搬数据慢(HBM 带宽被其他进程竞争)
# → Compute B 等 Load A → PipeBarrier 时间被计入 B 的 profile
# 调优目标不是加速 B 的计算,而是优化 A 的数据搬运

踩坑三:Docker 模板中 LD_LIBRARY_PATH 和 K8s env 的交互

Kubernetes 的 Pod 环境变量优先级高于容器内的 LD_LIBRARY_PATH。如果 K8s deployment 的 env 覆盖了 LD_LIBRARY_PATH,CANN 的库目录被清掉——NPU 初始化失败。

修复:在 Dockerfile 里用 ldconfig 替代 LD_LIBRARY_PATH。

# 不要用 LD_LIBRARY_PATH(会被 K8s 覆盖)
# ENV LD_LIBRARY_PATH=$ASCEND_HOME/lib64:$LD_LIBRARY_PATH

# 改用 ldconfig(写入系统级库目录)
RUN echo "$ASCEND_HOME/lib64" > /etc/ld.so.conf.d/ascend.conf
RUN ldconfig
# K8s 不会覆盖系统级的 /etc/ld.so.conf.d/

skills 里的工具都是在 CANN 社区的日常开发实践中提炼出来的——op-gen 省掉脚手架代码的重复劳动,prof-parser 把 100KB JSON 变成可读的优化建议,Docker 模板统一开发和生产的镜像标准。这些工具不涉及 NPU 的硬件特性,但它们解决了「在 NPU 上做开发」这件事本身的高频摩擦——生成的脚手架、解析的性能数据、部署的 Docker 镜像。

Logo

AtomGit 是由开放原子开源基金会联合 CSDN 等生态伙伴共同推出的新一代开源与人工智能协作平台。平台坚持“开放、中立、公益”的理念,把代码托管、模型共享、数据集托管、智能体开发体验和算力服务整合在一起,为开发者提供从开发、训练到部署的一站式体验。

更多推荐