aclnnGather

📄 View Source Code

Applicable Products

  • Ascend 950PR&950DT products: Supported
  • Atlas A3 products: Supported
  • Atlas A2 products: Supported
  • Atlas 200I/500 A2 inference products: Not supported
  • Atlas inference products: Not supported
  • Atlas training products: Not supported

Function

  • Description: Gathers data along a specified dimension dim of the input tensor.

  • Formula: Given a tensor selfself, a dimension dd, and an index tensor indexindex, let nn be the number of dimensions of selfself, idi_d denote the index along dimension dd, and indexidindex_{i_d} denote the idi_d-th index value of the index tensor indexindex along dimension dd. The gather operation along the specified dimension dd can be expressed by the following mathematical formula:

    gather(X,index,d)i0,i1,⋯ ,id−1,id+1,⋯ ,in−1=selfi0,i1,⋯ ,id−1,indexid,id+1,⋯ ,in−1gather(X,index,d)_{i_0,i_1,\cdots,i_{d-1},i_{d+1},\cdots,i_{n-1}} = self_{i_0,i_1,\cdots,i_{d-1},index_{i_d},i_{d+1},\cdots,i_{n-1}}
  • Example:

    • Example 1: Assume the input tensor self=[123456789]self=\begin{bmatrix}1 & 2 & 3\\ 4 & 5 & 6\\ 7 & 8 & 9\end{bmatrix}, the index tensor index=[0210]index=\begin{bmatrix}0 & 2\\ 1 & 0\end{bmatrix}, and dim=0dim = 0. Then the output tensor out=[1842]out=\begin{bmatrix}1 & 8\\ 4 & 2\end{bmatrix}. The specific computation process is as follows:

      out0,0=selfindex0,0,0=self0,0=1out0,1=selfindex0,1,1=self2,1=8out1,0=selfindex1,0,0=self1,0=4out1,1=selfindex1,1,1=self0,1=2\begin{aligned} out_{0,0}&=self_{index_{0,0}, 0}=self_{0,0}=1 \\ out_{0,1}&=self_{index_{0,1}, 1}=self_{2,1}=8 \\ out_{1,0}&=self_{index_{1,0}, 0}=self_{1,0}=4 \\ out_{1,1}&=self_{index_{1,1}, 1}=self_{0,1}=2 \end{aligned}
    • Example 2: Assume the input tensor self=[123456789]self=\begin{bmatrix}1 & 2 & 3\\ 4 & 5 & 6\\ 7 & 8 & 9\end{bmatrix}, the index tensor index=[0210]index=\begin{bmatrix}0 & 2\\ 1 & 0\end{bmatrix}, and dim=1dim = 1. Then the output tensor out=[1354]out=\begin{bmatrix}1 & 3\\ 5 & 4\end{bmatrix}. The specific computation process is as follows:

      out0,0=self0,index0,0=self0,0=1out0,1=self0,index0,1=self0,2=3out1,0=self1,index1,0=self1,1=5out1,1=self1,index1,1=self1,0=4\begin{aligned} out_{0,0}&=self_{0, index_{0,0}}=self_{0,0}=1 \\ out_{0,1}&=self_{0, index_{0,1}}=self_{0,2}=3 \\ out_{1,0}&=self_{1, index_{1,0}}=self_{1,1}=5 \\ out_{1,1}&=self_{1, index_{1,1}}=self_{1,0}=4 \end{aligned}

Function Prototype

Each operator uses a two-phase API. You must first call the "aclnnGatherGetWorkspaceSize" API to obtain the workspace size required for calculation and the executor that includes the operator calculation flow. Then, call the "aclnnGather" API to perform the calculation.

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

aclnnGatherGetWorkspaceSize

  • Parameters

    Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor
    self (aclTensor*) Input self in the formula. The data type needs to be consistent with out, and the number of dimensions needs to be consistent with index. DOUBLE, FLOAT16, BFLOAT16, FLOAT32, INT32, UINT32, INT64, UINT64, INT16, UINT16, INT8, UINT8, BOOL, FLOAT8_E5M2, FLOAT8_E4M3FN, FLOAT8_E8M0 - 0-8 √
    dim (int64_t) Input d in the formula. Value range [-self.dim(), self.dim() - 1] - - - -
    index (aclTensor*) Input The index in the formula. The number of dimensions needs to be consistent with that of self, and the shape needs to be consistent with that of out. Except for the dimension specified by dim, the size of each dimension needs to be less than or equal to the size of the corresponding dimension of self.
    The value in index indicates the subscript of the element in self along the axis specified by dim. Value range [-self.shape[dim], self.shape[dim] - 1]. Out-of-bound indices in index are not supported.
    INT32, INT64 - 0-8 √
    out (aclTensor*) Output Output aclTensor*. The data type needs to be consistent with self, and the shape needs to be consistent with index. Consistent with self - Consistent with index √
    workspaceSize(uint64_t*) Output Returns the workspace size to be applied by the Device side. - - - - -
    executor(aclOpExecutor**) Output Returns the op executor, which includes calculation processes of the operator. - - - - -
  • Atlas A2 products: The FLOAT8_E5M2, FLOAT8_E4M3FN, and FLOAT8_E8M0 data types are not supported for self.
  • Return Value

    aclnnStatus: return status code. For details, see aclnn Return Codes.

    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, index, or out is a null pointer.
    ACLNN_ERR_PARAM_INVALID 161002 The data type of self, index, or out is not supported.
    The data type of out and self is not consistent.
    The dimension of self and index is different.
    The dimension of self, index, or out is greater than 8.
    The shapes of out and index are inconsistent.
    The dimension specified by dim is out of the dimension range of self [-self.dim(), self.dim() - 1].
    Except for the dimension specified by dim, the size of index on other dimensions is greater than that of self.
    index is a non-empty tensor and the size of self on the dimension specified by dim is 0.

aclnnGather

  • Parameters

    Parameter Input/Output Description
    workspace Input Workspace memory address applied by the Device side.
    workspaceSize Input Workspace size applied by the Device side, obtained by the first-phase API aclnnGatherGetWorkspaceSize.
    executor Input Op executor, which includes calculation flow of the operator.
    stream Input Stream that specifies the task to execute.
  • Return Value

    aclnnStatus: return status code. For details, see aclnn Return Codes.

Constraints

  • Deterministic computation:
    • aclnnGather defaults to a deterministic implementation.

Example

The following sample code is for reference only. For details about compiling and running, see Compile and Run Samples.

#include <iostream>
#include <vector>
#include "acl/acl.h"
#include "aclnnop/aclnn_gather.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 for 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 memory on the device side.
  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);
  // Call aclrtMemcpy to copy data from the host side to the device-side memory.
  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 the 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 the aclCreateTensor API 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. For details, 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 the input and output. Custom construction is required based on the API.
  std::vector<int64_t> selfShape = {4, 2};
  std::vector<int64_t> indexShape = {4, 2};
  std::vector<int64_t> outShape = {4, 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, 4, 5, 6, 7};
  std::vector<int64_t> indexHostData = {0, 1, 2, 3, 3, 2, 1, 0};
  std::vector<float> outHostData(8, 0);
  int64_t dim = 0;
  // Create the self aclTensor.
  ret = CreateAclTensor(selfHostData, selfShape, &selfDeviceAddr, aclDataType::ACL_FLOAT, &self);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  // Create the index aclTensor.
  ret = CreateAclTensor(indexHostData, indexShape, &indexDeviceAddr, aclDataType::ACL_INT64, &index);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  // Create the 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. Change the API name to the actual one.
  uint64_t workspaceSize = 0;
  aclOpExecutor* executor;
  // Call the first-phase API of aclnnGather.
  ret = aclnnGatherGetWorkspaceSize(self, dim, index, out, &workspaceSize, &executor);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnGatherGetWorkspaceSize failed. ERROR: %d\n", ret); return ret);
  // Allocate device memory for workspace 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 aclnnGather.
  ret = aclnnGather(workspaceAddr, workspaceSize, executor, stream);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnGather failed. ERROR: %d\n", ret); return ret);
  // 4. (boilerplate) Synchronize and wait for the task 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 device side memory to the host side. Modify it according to the 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. Modify it according to the API definition.
  aclDestroyTensor(self);
  aclDestroyTensor(index);
  aclDestroyTensor(out);

  // 7. Release device resources.
  aclrtFree(selfDeviceAddr);
  aclrtFree(indexDeviceAddr);
  aclrtFree(outDeviceAddr);
  if (workspaceSize > 0) {
    aclrtFree(workspaceAddr);
  }
  aclrtDestroyStream(stream);
  aclrtResetDevice(deviceId);
  aclFinalize();

  return 0;
}