在昇腾 910B 上,如何调用内置国密算子?

解读

面试官真正想确认三件事:

  1. 你是否知道“国密算子”在昇腾 910B 上属于 CANN 的 AscendCL 层,而不是 Keras/TensorFlow 原生算子;
  2. 你是否能把 Keras 的计算图“捅”到 CANN 里,让国密算子真正跑在 910B 的 Vector Core 或 Cube Core 上;
  3. 你是否熟悉国内合规流程(算法备案、固件版本、白名单驱动)。
    回答时要把“Keras 层 → TensorFlow 自定义算子 → AscendCL 内核 → 国密库”这一整条链路讲清楚,并给出可落地的代码骨架和编译指令,才能证明“我不仅懂 Keras,还懂国产芯片和国密合规”。

知识点

  1. 国密算子在昇腾 910B 上的位置:CANN ≥ 6.3.RC1 把 SM2/SM3/SM4 做成 AscendCL 的 aclnnCrypto 系列,头文件 aclnn_crypto.h,库 libascend_crypto.so。
  2. TensorFlow 2.x 在昇腾的插件:tensorflow-plugin ≥ 23.0.RC2,提供 tf.ascend.* 命名空间,支持用 Custom Op 机制把 AscendCL kernel 挂到 TF 计算图。
  3. Keras 的扩展点:
    • 继承 tf.keras.layers.Layer,在 call() 里调用 tf.ascend.crypto.sm3 / sm4;
    • 或者继承 tf.keras.layers.Layer,在 call() 里用 tf.py_function 包装 AscendCL 的 aclnnCryptoSm3 / aclnnCryptoSm4Ex,再用 tf.function(experimental_compile=True) 把 XLA 图切到 Ascend。
  4. 合规要求:
    • 固件 ≥ 1.84.10.5,驱动 ≥ 23.0.RC2,且打开白名单 CONFIG_CRYPTO_ENABLE=1;
    • 算法模块需走国家密码管理局的“算法备案号”字段,编译时加 -DCRYPTO_SM3_OID=1.2.156.10197.1.401;
    • 生产环境需打开安全启动,否则算子会返回 ACL_ERROR_CRYPTO_DISABLED。
  5. 性能陷阱:
    • SM4-GCM 向量长度必须是 128 整数倍,否则 Cube Core 会回退到 CPU,吞吐掉 70%;
    • SM3 的初始向量 IV 必须放在 Device 端常量区,不要每轮从 Host 拷,否则 H2D 延迟把整体吞吐吃掉 30%。

答案

分三步落地,给出可直接抄的代码与编译脚本。

第一步:环境校验

npu-smi info -t board -i 0 | grep "Software Version"  # ≥ 23.0.RC2
cat /usr/local/Ascend/driver/tools/crypto_enable.conf  # 确保 CONFIG_CRYPTO_ENABLE=1

第二步:写 TensorFlow 自定义算子(以 SM3 摘要为例)

# sm3_op.cc
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/platform/default/logging.h"
#include "aclnn_crypto.h"

REGISTER_OP("AscendSm3")
    .Input("input: uint8")
    .Output("digest: uint8")
    .SetShapeFn([](::tensorflow::shape_inference::InferenceContext* c){
      c->set_output(0, c->MakeShape({32}));  // SM3 输出 32 B
      return Status::OK();
    });

class AscendSm3Op : public OpKernel {
 public:
  explicit AscendSm3Op(OpKernelConstruction* ctx) : OpKernel(ctx) {}
  void Compute(OpKernelContext* ctx) override {
    const Tensor& input = ctx->input(0);
    Tensor* output = nullptr;
    OP_REQUIRES_OK(ctx, ctx->allocate_output(0, TensorShape({32}), &output));
    auto in_flat = input.flat<uint8>();
    auto out_flat = output->flat<uint8>();
    aclrtStream stream = nullptr;
    aclrtCreateStream(&stream);
    aclnnCryptoSm3(
        in_flat.data(), in_flat.size(),
        out_flat.data(), stream);
    aclrtSynchronizeStream(stream);
    aclrtDestroyStream(stream);
  }
};

REGISTER_KERNEL_BUILDER(Name("AscendSm3").Device(DEVICE_ACL), AscendSm3Op);

编译

TF_CFLAGS=( $(python -c 'import tensorflow as tf; print(" ".join(tf.sysconfig.get_compile_flags()))') )
TF_LFLAGS=( $(python -c 'import tensorflow as tf; print(" ".join(tf.sysconfig.get_link_flags()))') )
g++ -std=c++17 -fPIC -D_GLIBCXX_USE_CXX11_ABI=0 -O2 \
  -I/usr/local/Ascend/acllib/include \
  sm3_op.cc -shared -o ascend_sm3_op.so \
  ${TF_CFLAGS[@]} ${TF_LFLAGS[@]} \
  -L/usr/local/Ascend/acllib/lib64 -lascendcl -laclnn_crypto

第三步:Keras 层封装

import tensorflow as tf
ascend_sm3 = tf.load_op_library('./ascend_sm3_op.so')

class Sm3Layer(tf.keras.layers.Layer):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
    @tf.function
    def call(self, inputs):
        # inputs: [B, L] uint8
        flat = tf.reshape(inputs, [-1])
        digest = ascend_sm3.ascend_sm3(flat)
        return tf.reshape(digest, [-1, 32])  # [B, 32]

# 使用示例
x = tf.keras.Input(shape=(None,), dtype=tf.uint8)
y = Sm3Layer()(x)
model = tf.keras.Model(x, y)
model.compile(optimizer='adam', loss='mse')

验证

import hashlib, numpy as np
data = np.frombuffer(b'abc', dtype=np.uint8)
pred = model.predict(data[np.newaxis, :])
ref  = np.frombuffer(hashlib.sm3(b'abc').digest(), dtype=np.uint8)
assert np.array_equal(pred[0], ref)

至此,Keras 层在昇腾 910B 上成功调用内置国密 SM3 算子,SM2/SM4 同理,只需把 aclnnCryptoSm2Sign / aclnnCryptoSm4Enc 按同样套路注册即可。

拓展思考

  1. 如果团队不想写 C++,CANN 6.3 之后会把 SM3/SM4 以 tf.ascend.crypto.* 的方式直接暴露成 Python API,届时只需在 Keras 层里调 tf.ascend.crypto.sm3,不再需要自定义算子;但面试官想听的是“如果官方还没封装,你怎么兜底”,所以务必把上面的 Custom Op 方案讲透。
  2. 国密算子一旦打开安全启动,Profiling 会被强制关闭,性能调优只能看 npu-smi 的 util;要提前准备 micro-benchmark 脚本,把吞吐、延时、Cube/Vector 利用率三个指标跑在 CI 里,避免上线后被动救火。
  3. 多卡场景下,SM2 签名需要同步 nonce,否则同一批次不同卡会产出不同 r 值,导致验签失败;解决方法是把 nonce 生成放到 Host 端,通过 tf.collective.all_gather 同步后再下发到每张卡的 AscendCL 内核。