CANN ops-nn aclnnGatherV2 接口详解:Gather 算子两段式调用、参数约束与 NPU 上机实战

原创2026-09-21 17:52:211,758 阅读
文章标签:人工智能深度学习算子库高性能计算模型量化AscendCANN

CANN ops-nn aclnnGatherV2 接口详解:Gather 算子两段式调用、参数约束与 NPU 上机实战

aclnnGatherV2 是 CANN ops-nn 算子库中 GatherV2 算子的 AscendCL 上层封装接口,用于从输入 Tensor 的指定维度 dim 按 index 下标提取元素。本文以 index/gather_v2/docs/aclnnGatherV2.md 为骨架,结合 op_api/aclnn_gather_v2.cpp、op_host/gather_v2_def.cpp 等仓库源码,完整说明该接口的功能语义、两段式调用流程、每个参数的取值约束、错误码行为以及可直接编译运行的上机示例,帮助你在 NPU 上快速、正确地使用 Gather 类算子。

功能语义与计算规则

接口功能:从输入 Tensor self 的指定维度 dim 中,按照 index 中给出的下标序号提取元素,将结果写入 out Tensor。

以二维输入张量 x=[123456789]x=\begin{bmatrix}1 & 2 & 3 \\ 4 & 5 & 6 \\ 7 & 8 & 9\end{bmatrix} 和索引张量 idx=[1, 0] 为例:

  • dim=0 的结果:y=[456123]y=\begin{bmatrix}4 & 5 & 6 \\ 1 & 2 & 3\end{bmatrix},即先取第 1 行(下标 1),再取第 0 行(下标 0);
  • dim=1 的结果:y=[215487]y=\begin{bmatrix}2 & 1\\ 5 & 4\\ 8 & 7\end{bmatrix},即对每一行分别按下标 [1, 0] 取列。

任意维度的下标映射公式

以 shape 为 (3,2,2) 的三维张量 x=[[[1,2],[3,4]],[[5,6],[7,8]],[[9,10],[11,12]]]x=\begin{bmatrix}[[1,&2],&[3,&4]], \\ [[5,&6],&[7,&8]], \\ [[9,&10],&[11,&12]]\end{bmatrix} 和 idx=[1, 0] 为例,设 x 张量 dim=0、1、2 对应的下标分别为 l,m,nl, m, n,idx 为一维(零维 index 视为 size 为 1 的一维),则:

  • dim 为 0:令 I=index[i]I=index[i],y[i][m][n]=x[I][m][n]y[i][m][n] = x[I][m][n];
  • dim 为 1:令 J=index[j]J=index[j],y[l][j][n]=x[l][J][n]y[l][j][n] = x[l][J][n];
  • dim 为 2:令 K=index[k]K=index[k],y[l][m][k]=x[l][m][K]y[l][m][k] = x[l][m][K]。

即:输出在 dim 维度上的长度被替换为 index 对应维度的长度,其余维度保持与 self 一致。这一语义与仓库 tests/assets/golden.py 中实现的 aclnn_gather_v2_golden(内部调用 tf.gather(tensor_x, index, axis=dim))完全对应,也与 TensorFlow tf.gather / PyTorch torch.gather 的轴语义对齐。

产品支持情况

产品 是否支持
Ascend 950PR / Ascend 950DT 支持
Atlas A3 训练系列产品 / Atlas A3 推理系列产品 支持
Atlas A2 训练系列产品 / Atlas A2 推理系列产品 支持
Atlas 200I/500 A2 推理产品 不支持
Atlas 推理系列产品 支持
Atlas 训练系列产品 支持

值得注意的是,上述“支持”指 aclnn 接口层的产品支持矩阵;而底层 op_host/gather_v2_def.cpp 中通过 AICore().AddConfig("ascend950", ...) / AddConfig("ascend350", ...) 注册的 AI Core 计算配置仅包含 ascend950 与 ascend350 两个硬件架构(可对照 op_host/config 下的 gather_v2_binary.json),说明部分产品形态下算子会经框架层图融合或降级路径执行。实际部署请以目标硬件的 CANN 版本支持清单为准。

两段式接口与函数原型

aclnnGatherV2 遵循 CANN 算子库统一的两段式接口规范:必须先调用第一段接口 aclnnGatherV2GetWorkspaceSize 获取计算所需的 workspace 大小以及封装了算子计算流程的执行器 executor,再调用第二段接口 aclnnGatherV2 执行计算。

aclnnStatus aclnnGatherV2GetWorkspaceSize(
 const aclTensor *self,
 int64_t          dim,
 const aclTensor *index,
 aclTensor       *out,
 uint64_t        *workspaceSize,
 aclOpExecutor  **executor)
aclnnStatus aclnnGatherV2(
 void          *workspace,
 uint64_t       workspaceSize,
 aclOpExecutor *executor,
 aclrtStream    stream)

两个接口的函数声明位于仓库头文件 op_api/aclnn_gather_v2.h(ACLNN_API 导出),使用时只需包含头文件 aclnnop/aclnn_gather_v2.h。

aclnnGatherV2GetWorkspaceSize 参数详解

第一段接口负责入参校验 + workspace 大小计算 + 执行器构建,参数明细如下:

参数名 输入/输出 描述 使用说明 数据类型 数据格式 维度(shape) 非连续Tensor
self 输入 输入 aclTensor - FLOAT、FLOAT16、INT64、INT32、INT16、INT8、UINT8、BOOL、DOUBLE、COMPLEX64、COMPLEX128、BFLOAT16 ND 1-8 √
dim 输入 输入整数 取值范围在 [-self.dim(), self.dim()-1] 内 INT64 - - -
index 输入 输入 aclTensor 数据维度支持 1-8 维;数值取值范围在 [0, self.shape[dim]) 内(包含 0,不包含 self.shape[dim]) INT64、INT32 ND 1-8 √
out 输出 输出 aclTensor 数据类型需与 self 一致;维数等于 self 维数与 index 维数之和减一;除 dim 维扩展为与 index 的 shape 一致外,其他维长度与 self 相应维一致 与 self 一致 ND 1-8 -
workspaceSize 输出 返回需要在 Device 侧申请的 workspace 大小 - - - - -
executor 输出 返回 op 执行器,包含了算子计算流程 - - - - -

需要补充说明的细节:

  • dim 支持负值:源码 op_api/aclnn_gather_v2.cpp 的 CheckShape 中先校验 dim >= -selfDimSize && dim < selfDimSize(其中 selfDimSize 在 self 为 0 维时按 1 处理),随后对负 dim 执行 dim += selfDimSize 归一化,因此 dim=-1 等价于最后一维;
  • index 为 0 维:源码对 0 维 index 会先经 l0op::UnsqueezeNd 升维为 size 为 1 的一维再参与计算,与文档“零维 index 当成 size 为 1 的一维”的描述一致;
  • 空 Tensor 支持:self 或 index 为空 Tensor 时(HasEmptyTensor 分支),接口直接返回 workspaceSize = 0 并生成空执行器,不进入实际计算流程;
  • 非连续 Tensor:self、index 均支持非连续(stride 非紧凑)Tensor,第一段接口内部会通过 l0op::Contiguous 自动转连续后再计算,无需用户手动转置。

按硬件架构区分的 dtype 支持

第一段接口的 dtype 校验并非一成不变,源码中 GetDtypeSupportListByNpuArch() 按架构返回三份支持列表:

  • Atlas 推理系列产品 / Atlas 训练系列产品(DAV_1001 等):不支持 BFLOAT16(即文档中注释的约束“数据类型不支持 BFLOAT16”);
  • Atlas A3 / A2 系列(DAV_2201):额外支持 BFLOAT16;
  • Regbase 平台:在支持列表上再增加 UINT16、UINT32、UINT64 等无符号整型。

因此在移植代码时,若输入类型为 BFLOAT16,请先确认目标硬件架构是否在支持范围内。

输出 shape 的推导规则

out 的 shape 由 self.shape 与 index.shape 共同决定,仓库 op_host/gather_v2_infershape.cpp 与第一段接口的 CheckOutShape 实现了一致的推导逻辑:

  1. 取 self.shape[0..dim) 各维;
  2. 拼接 index 的全部维度(index 为 0 维时拼接 1);
  3. 再拼接 self.shape(dim+1..end) 各维。

例如 self shape 为 {2, 2}、index shape 为 {2, 2}、dim=0 时,out shape 应为 {2, 2, 2}(这也是下方调用示例使用的 shape 组合)。

返回值与错误码

aclnnStatus 返回状态码,完整错误码定义参见 aclnn返回码。

第一段接口 aclnnGatherV2GetWorkspaceSize 完成入参校验,以下场景会直接报错返回:

返回值 错误码 描述
ACLNN_ERR_PARAM_NULLPTR 161001 参数 self、index、out 是空指针。
ACLNN_ERR_PARAM_INVALID 161002 参数 self、index 的数据类型不在支持的范围内。
ACLNN_ERR_PARAM_INVALID 161002 当 self.dim()=0 时,dim 取值不在 [-1, 0] 内;当 self.dim()>0 时,dim 取值不在 [-self.dim(), self.dim()-1] 内。
ACLNN_ERR_PARAM_INVALID 161002 self、index 的维数大于 8。
ACLNN_ERR_PARAM_INVALID 161002 self 和 out 的数据类型不一致。
ACLNN_ERR_PARAM_INVALID 161002 out 的 shape 不满足“除 dim 维扩展为 index 的 shape 外,其他维长度与 self 相应维一致”。

上述校验在 op_api/aclnn_gather_v2.cpp 的 CheckParams 中按“空指针 → dtype → shape → format”顺序依次执行:CheckNotNull 对应 161001;CheckDtypeValid(含 OP_CHECK_DTYPE_NOT_SAME(self, out) 与 INDEX_SUPPORT_LIST = {DT_INT32, DT_INT64} 检查)与 CheckShape(含 MAX_DIM_LEN = 8 与 dim 范围检查)对应 161002;CheckFormat 对 FORMAT_FRACTAL_NZ 仅打警告日志,不阻断执行。

aclnnGatherV2 执行接口

第二段接口在 workspace 就绪后提交异步计算任务,参数说明如下:

参数名 输入/输出 描述
workspace 输入 在 Device 侧申请的 workspace 内存地址。
workspaceSize 输入 在 Device 侧申请的 workspace 大小,由第一段接口 aclnnGatherV2GetWorkspaceSize 获取。
executor 输入 op 执行器,包含了算子计算流程。
stream 输入 指定执行任务的 Stream。

其内部实现非常简洁,核心是 CommonOpExecutorRun(workspace, workspaceSize, executor, stream),由框架统一完成算子下发与执行。

内部计算流程(源码级原理)

从 op_api/aclnn_gather_v2.cpp 头部注释可以还原 aclnnGatherV2 的完整计算图:

self            index        dim
  |               |          (workspace_3)
  \               |             |
 Contiguous     Contiguous      |
(workspace_0)  (workspace_2)    |
      \            |            /
       \          |           /
         \        |         /
          GatherV2(workspace_4)
                    |
                    |
                ViewCopy
                    |
                   out

具体步骤为:

  1. 连续性处理:self、index 分别经 l0op::Contiguous 转为连续 Tensor(对应 workspace_0 / workspace_2);
  2. 升维处理:若 index 为 0 维,经 l0op::UnsqueezeNd 升为一维;
  3. 核心计算:调用 l0op::GatherV2(selfContiguous, dim, indexParam, executor, 0, true) 完成 Gather 计算(workspace_4);
  4. 视图回写:若 out 是非连续 Tensor,通过 l0op::ViewCopy 将连续计算结果写入 out 的视图布局;
  5. workspace 汇总:*workspaceSize = uniqueExecutor->GetWorkspaceSize() 返回整条计算链所需 workspace 总量。

正是这种“Contiguous + 算子 + ViewCopy”的 L0 算子组合模式,使接口对外同时支持非连续输入 Tensor 与任意 1-8 维输入,且保证默认确定性实现(约束说明中已注明),确定性计算的详细约定可参考 determinism_compute.md。

调用示例(可直接编译运行)

下面示例来自 examples/test_aclnn_gather_v2.cpp,与文档调用示例等价,编译与运行方法参考编译与运行样例:

#include <iostream>
#include <vector>
#include "acl/acl.h"
#include "aclnnop/aclnn_gather_v2.h"

#define CHECK_RET(cond, return_expr) \
  do {                               \
    if (!(cond)) {                   \
      return_expr;                   \
    }                                \
  } while (0)

#define LOG_PRINT(message, ...)     \
  do {                              \
    printf(message, ##__VA_ARGS__); \
  } while (0)

int64_t GetShapeSize(const std::vector<int64_t>& shape) {
  int64_t shapeSize = 1;
  for (auto i : shape) {
    shapeSize *= i;
  }
  return shapeSize;
}

int Init(int32_t deviceId, aclrtStream* stream) {
  // 固定写法,资源初始化
  auto ret = aclInit(nullptr);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclInit failed. ERROR: %d\n", ret); return ret);
  ret = aclrtSetDevice(deviceId);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtSetDevice failed. ERROR: %d\n", ret); return ret);
  ret = aclrtCreateStream(stream);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtCreateStream failed. ERROR: %d\n", ret); return ret);
  return 0;
}

template <typename T>
int CreateAclTensor(const std::vector<T>& hostData, const std::vector<int64_t>& shape, void** deviceAddr,
                    aclDataType dataType, aclTensor** tensor) {
  auto size = GetShapeSize(shape) * sizeof(T);
  // 调用aclrtMalloc申请device侧内存
  auto ret = aclrtMalloc(deviceAddr, size, ACL_MEM_MALLOC_HUGE_FIRST);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtMalloc failed. ERROR: %d\n", ret); return ret);
  // 调用aclrtMemcpy将host侧数据拷贝到device侧内存上
  ret = aclrtMemcpy(*deviceAddr, size, hostData.data(), size, ACL_MEMCPY_HOST_TO_DEVICE);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtMemcpy failed. ERROR: %d\n", ret); return ret);

  // 计算连续tensor的strides
  std::vector<int64_t> strides(shape.size(), 1);
  for (int64_t i = shape.size() - 2; i >= 0; i--) {
    strides[i] = shape[i + 1] * strides[i + 1];
  }

  // 调用aclCreateTensor接口创建aclTensor
  *tensor = aclCreateTensor(shape.data(), shape.size(), dataType, strides.data(), 0, aclFormat::ACL_FORMAT_ND,
                            shape.data(), shape.size(), *deviceAddr);
  return 0;
}

int main() {
  // 1.(固定写法)device/stream初始化,参考acl API手册
  // 根据自己的实际device填写deviceId
  int32_t deviceId = 0;
  aclrtStream stream;
  auto ret = Init(deviceId, &stream);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("Init acl failed. ERROR: %d\n", ret); return ret);

  // 2. 构造输入与输出,需要根据API的接口自定义构造
  std::vector<int64_t> selfShape = {2, 2};
  std::vector<int64_t> indexShape = {2, 2};
  std::vector<int64_t> outShape = {2, 2, 2};
  void* selfDeviceAddr = nullptr;
  void* indexDeviceAddr = nullptr;
  void* outDeviceAddr = nullptr;
  aclTensor* self = nullptr;
  aclTensor* index = nullptr;
  aclTensor* out = nullptr;
  std::vector<float> selfHostData = {0, 1, 2, 3};
  std::vector<int64_t> indexHostData = {0, 1, 0, 1};
  std::vector<float> outHostData = {0, 0, 0, 0, 0, 0, 0, 0};
  int64_t dim = 0;
  // 创建self aclTensor
  ret = CreateAclTensor(selfHostData, selfShape, &selfDeviceAddr, aclDataType::ACL_FLOAT, &self);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  // 创建index aclTensor
  ret = CreateAclTensor(indexHostData, indexShape, &indexDeviceAddr, aclDataType::ACL_INT64, &index);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  // 创建out aclTensor
  ret = CreateAclTensor(outHostData, outShape, &outDeviceAddr, aclDataType::ACL_FLOAT, &out);
  CHECK_RET(ret == ACL_SUCCESS, return ret);

  // 3. 调用CANN算子库API,需要修改为具体的API名称
  uint64_t workspaceSize = 0;
  aclOpExecutor* executor;
  // 调用aclnnGatherV2第一段接口
  ret = aclnnGatherV2GetWorkspaceSize(self, dim, index, out, &workspaceSize, &executor);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnGatherV2GetWorkspaceSize failed. ERROR: %d\n", ret); return ret);
  // 根据第一段接口计算出的workspaceSize申请device内存
  void* workspaceAddr = nullptr;
  if (workspaceSize > 0) {
    ret = aclrtMalloc(&workspaceAddr, workspaceSize, ACL_MEM_MALLOC_HUGE_FIRST);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("allocate workspace failed. ERROR: %d\n", ret); return ret);
  }
  // 调用aclnnGatherV2第二段接口
  ret = aclnnGatherV2(workspaceAddr, workspaceSize, executor, stream);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnGatherV2 failed. ERROR: %d\n", ret); return ret);

  // 4.(固定写法)同步等待任务执行结束
  ret = aclrtSynchronizeStream(stream);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtSynchronizeStream failed. ERROR: %d\n", ret); return ret);

  // 5. 获取输出的值,将device侧内存上的结果拷贝至host侧,需要根据具体API的接口定义修改
  auto size = GetShapeSize(outShape);
  std::vector<float> resultData(size, 0);
  ret = aclrtMemcpy(resultData.data(), resultData.size() * sizeof(resultData[0]), outDeviceAddr,
                    size * sizeof(resultData[0]), ACL_MEMCPY_DEVICE_TO_HOST);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("copy result from device to host failed. ERROR: %d\n", ret); return ret);
  for (int64_t i = 0; i < size; i++) {
    LOG_PRINT("result[%ld] is: %f\n", i, resultData[i]);
  }

  // 6. 释放aclTensor和aclScalar,需要根据具体API的接口定义修改
  aclDestroyTensor(self);
  aclDestroyTensor(index);
  aclDestroyTensor(out);

  // 7. 释放device资源,需要根据具体API的接口定义修改
  aclrtFree(selfDeviceAddr);
  aclrtFree(indexDeviceAddr);
  aclrtFree(outDeviceAddr);
  if (workspaceSize > 0) {
    aclrtFree(workspaceAddr);
  }
  aclrtDestroyStream(stream);
  aclrtResetDevice(deviceId);
  aclFinalize();
  return 0;
}

示例执行逻辑说明:

  • self shape 为 {2, 2}、数据 {0, 1, 2, 3}(即 [0123]\begin{bmatrix}0 & 1 \\ 2 & 3\end{bmatrix}),index shape 为 {2, 2}、数据 {0, 1, 0, 1},dim=0,out shape 为 {2, 2, 2};
  • 按 dim=0 的映射公式,输出应为 [[[0,1],[2,3]], [[0,1],[2,3]]](两行分别由 index[0]=0、index[1]=1、index[2]=0、index[3]=1 索引得到);
  • workspace 大小可能为 0(例如空 Tensor 场景),因此申请内存前需判断 workspaceSize > 0,释放时同理。

测试与验证体系

仓库为 aclnnGatherV2 提供了完整的验证闭环,可作为你自测的参照:

其他调用方式与周边能力

除了 aclnn 两段式接口,GatherV2 算子还支持两种调用路径(见 index/gather_v2/README.md):

  • aclnn 调用:即本文主题,样例见 examples/test_aclnn_gather_v2.cpp;
  • 图模式调用:通过算子IR构图后执行,样例见 examples/test_geir_gather_v2.cpp,此模式下算子定义(op_host/gather_v2_def.cpp)还开放了 batch_dims(默认 0)与 negative_index_support(默认 false)两个可选属性;
  • 框架层插件:目录 framework 中提供了 ONNX、TensorFlow 到 GatherV2 的图转换插件(如 gather_onnx_plugin.cpp、gather_v2_tf_plugin.cpp),使主流训练框架的 Gather 算子可自动映射到本实现。

如需进一步了解底层概念,可参阅两段式接口、aclnn返回码、非连续Tensor说明与确定性计算等仓库文档。

登录后查看全文
ops-nn