aclnnGatherNd

Applicable Products

ProductSupported
Ascend 950PR/Ascend 950DT√
Atlas A3 training products/Atlas A3 inference products√
Atlas A2 training products/Atlas A2 inference products√
Atlas 200I/500 A2 inference products×
Atlas inference products×
Atlas training products×

Function

  • Description: For an input tensor self with dimension r≥1 and an input tensor indices with dimension q≥1, data slices are gathered into an output tensor out with dimension (q-1) + (r - indices_shape[-1]). indices is a q-dimensional integer tensor, which can be viewed as a q-1-dimensional special tensor composed of Index Pairs (each Index Pair is a one-dimensional tensor of length indices_shape[-1], and each Index Pair points to a slice in self).

  • Formula:

    • If indices_shape[-1] > r, it is an invalid scenario.

    • If indices_shape[-1] = r, the dimension of the output tensor out is q-1, that is, the shape of out is [indices_shape[0:q-1]], and the elements in out are the elements at the index pair positions of self. (See Example 1.)

    • If indices_shape[-1] < r, the dimension of the output tensor out is (q-1) + (r - indices_shape[-1]). Let c = indices_shape[-1], that is, the shape of out is [indices_shape[0:q-1], self_shape[c:r]], and out consists of slices at the index pair positions of self. (See Examples 2, 3, and 4.)

    The constraints on r, q, and indices_shape[-1] are as follows:

    • r ≥ 1 and q ≥ 1 must be satisfied.

    • The value of indices_shape[-1] must be in the range [1, r] (inclusive).

    • Each element of indices must be within the range [-s, s-1] (where s is the value on each axis of self_shape), i.e., -self_shape[i] ≤ indices[...,i] ≤ self_shape[i]-1.

  • Example:

    Example1:
      self: [[0, 1],[2, 3]]       # self_shape=[2, 2], r=2
      indices: [[0, 0], [1, 1]]   # indices_shape=[2, 2], q=2, indices_shape[-1]=2
      out: [0, 3]                 # out_shape=[2]
    Example2:
      self: [[0, 1],[2, 3]]       # self_shape=[2, 2], r=2
      indices: [[1], [0]]         # indices_shape=[2, 1], q=2, indices_shape[-1]=1
      out: [[2, 3], [0, 1]]       # out_shape=[2, 2]
    Example3:
      self: [[[0, 1],[2, 3]], [[4, 5],[6, 7]]]   # self_shape=[2, 2, 2], r=3
      indices: [[0, 1], [1, 0]]                  # indices_shape=[2, 2], q=2, indices_shape[-1]=2
      out: [[2, 3], [4, 5]]                      # out_shape=[2, 2]
    Example4:
      self: [[[0, 1],[2, 3]], [[4, 5],[6, 7]]]   # self_shape=[2, 2, 2], r=3
      indices: [[[0, 1]], [[1, 0]]]              # indices_shape=[2, 1, 2], q=3, indices_shape[-1]=2
      out: [[[2, 3]], [[4, 5]]]                  # out_shape=[2, 1, 2]

Function Prototype

Each operator is divided into a two-phase API. The "aclnnGatherNdGetWorkspaceSize" API must be called first to obtain the workspace size required for computation and the executor that encapsulates the operator computation flow. Then, the "aclnnGatherNd" API is called to perform the computation.

aclnnStatus aclnnGatherNdGetWorkspaceSize(
 const aclTensor *self,
 const aclTensor *indices,
 bool             negativeIndexSupport,
 aclTensor       *out,
 uint64_t        *workspaceSize,
 aclOpExecutor  **executor)
aclnnStatus aclnnGatherNd(
 void          *workspace,
 uint64_t       workspaceSize,
 aclOpExecutor *executor,
 aclrtStream    stream)

aclnnGatherNdGetWorkspaceSize

  • Parameters

    Parameter Input/Output Description Instruction Data Type Data Format Dimension (Shape) Non-Contiguous Tensor
    self Input Input aclTensor. - INT64,INT32,INT8,UINT8,BOOL,FLOAT,FLOAT16,BFLOAT16,DOUBLE,INT16,UINT16,UINT32,UINT64 ND 1-8 √
    indices Input Input aclTensor. - INT32, INT64 ND - √
    negativeIndexSupport Input Whether the ONNX model contains negative indices. When set to True, indicates that the ONNX model contains negative indices; when set to False, indicates that the indices are within a valid range and no negative indices exist. BOOL - - -
    out Output Output aclTensor. The data type must be the same as self. Same as self. ND - √
    workspaceSize Output Returns the workspace size to be requested on the Device side. - - - - -
    executor Output Returns the operator executor, which contains the operator computation flow. - - - - -
    • Atlas A2 training products/Atlas A2 inference products and Atlas A3 training products/Atlas A3 inference products: DOUBLE, INT16, UINT16, UINT32, and UINT64 data types are not supported.
  • Return Value

    aclnnStatus: return code. For details, see aclnn Return Code.

    The first-phase API performs input parameter validation and returns an error in the following scenarios:

    Return Value Error Code Description
    ACLNN_ERR_PARAM_NULLPTR 161001 The self and out parameters are null pointers.
    ACLNN_ERR_PARAM_INVALID 161002 The data type of the self parameter is not within the supported range.
    The number of dimensions of self or indices is less than 1 or greater than 8.
    The data types of self and out are inconsistent.

aclnnGatherNd

  • Parameters

    Parameter Input/Output Description
    workspace Input Address of the workspace memory applied for on the Device side.
    workspaceSize Input Size of the workspace applied for on the Device side, obtained through the first-phase API aclnnGatherNdGetWorkspaceSize.
    executor Input Op executor that contains the operator computation flow.
    stream Input Specifies the stream for task execution.
  • Return value

    aclnnStatus: return code. For details, see aclnn Return Code.

Constraints

  • Deterministic computation:

    • aclnnGatherNd defaults to a deterministic implementation.

Example

The following provides example code for reference only. For details about compilation and running, see Compile and Run Samples.

#include <iostream>
#include <vector>
#include "acl/acl.h"
#include "aclnnop/aclnn_gather_nd.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) {
  // Boilerplate: resource initialization.
  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);
  // Call aclrtMalloc to allocate device memory.
  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);
  // Copy host-side data to the device memory using aclrtMemcpy.
  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);

  // Calculate the strides of a contiguous tensor.
  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];
  }

  // Call aclCreateTensor to create an 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. (Boilerplate) Initialize the device/stream. See the ACL API manual.
  // Set deviceId based on the actual device.
  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. Construct input and output, and customize based on the API interface.
  std::vector<int64_t> selfShape = {2, 2};
  std::vector<int64_t> indicesShape = {2, 2};
  std::vector<int64_t> outShape = {2};
  void* selfDeviceAddr = nullptr;
  void* indicesDeviceAddr = nullptr;
  void* outDeviceAddr = nullptr;
  aclTensor* self = nullptr;
  aclTensor* indices = nullptr;
  bool negativeIndexSupport = true;
  aclTensor* out = nullptr;
  std::vector<float> selfHostData = {0, 1, 2, 3};
  std::vector<int64_t> indicesHostData = {0, 0, 1, 1};
  std::vector<float> outHostData = {0, 3};
  // Create self aclTensor.
  ret = CreateAclTensor(selfHostData, selfShape, &selfDeviceAddr, aclDataType::ACL_FLOAT, &self);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  // Create indices aclTensor.
  ret = CreateAclTensor(indicesHostData, indicesShape, &indicesDeviceAddr, aclDataType::ACL_INT64, &indices);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  // Create out aclTensor.
  ret = CreateAclTensor(outHostData, outShape, &outDeviceAddr, aclDataType::ACL_FLOAT, &out);
  CHECK_RET(ret == ACL_SUCCESS, return ret);

  // 3. Call the CANN operator library API, and modify to the specific API name.
  uint64_t workspaceSize = 0;
  aclOpExecutor* executor;
  // Call the first-phase API of aclnnGatherNd.
  ret = aclnnGatherNdGetWorkspaceSize(self, indices, negativeIndexSupport, out, &workspaceSize, &executor);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnGatherNdGetWorkspaceSize failed. ERROR: %d\n", ret); return ret);
  // Apply for device memory based on the workspaceSize calculated by the first-phase API.
  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);
  }
  // Call the second-phase API of aclnnGatherNd.
  ret = aclnnGatherNd(workspaceAddr, workspaceSize, executor, stream);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnGatherNd failed. ERROR: %d\n", ret); return ret);

  // 4. (Boilerplate) Synchronize and wait for task execution to complete.
  ret = aclrtSynchronizeStream(stream);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtSynchronizeStream failed. ERROR: %d\n", ret); return ret);

  // 5. Obtain the output value and copy the result from the device memory to the host memory. Modify this based on the specific API definition.
  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. Release aclTensor and aclScalar. Modify based on the specific API definition.
  aclDestroyTensor(self);
  aclDestroyTensor(indices);
  aclDestroyTensor(out);

  // 7. Release device resources. Modify based on the specific API definition.
  aclrtFree(selfDeviceAddr);
  aclrtFree(indicesDeviceAddr);
  aclrtFree(outDeviceAddr);
  if (workspaceSize > 0) {
    aclrtFree(workspaceAddr);
  }
  aclrtDestroyStream(stream);
  aclrtResetDevice(deviceId);
  aclFinalize();
  return 0;
}