aclnnIndexFill&aclnnInplaceIndexFill

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: Replaces the values at positions specified by index with value along the given dim of input self. The computation result is deterministic.

  • Example: The input self is:

    [[1, 2, 3],
    
    [4, 5, 6],
    
    [7, 8, 9]]

    If dim = 0, index = [0, 2], and value = 0, the calculation result of the operator is:

    [[0, 0, 0],
    
    [4, 5, 6],
    
    [0, 0, 0]]

    If dim = 1, index = [0, 2], and value = 0, the calculation result of the operator is:

    [[0, 2, 0],
    
    [0, 5, 0],
    
    [0, 8, 0]]

Function Prototype

  • aclnnIndexFill and aclnnInplaceIndexFill implement the same function. The differences are as follows. Select the appropriate operator based on your use case.
    • aclnnIndexFill: A new output tensor object must be created to store the computation result.
    • aclnnInplaceIndexFill: No new output tensor object is required. The computation result is directly stored in the memory of the input tensor.
  • Each operator uses a two-phase API. You must first call the "aclnnIndexFillGetWorkspaceSize" or "aclnnInplaceIndexFillGetWorkspaceSize" API to obtain the workspace size required for the computation and the executor containing the operator computation process, and then call the "aclnnIndexFill" or "aclnnInplaceIndexFill" API to perform the computation.
  aclnnStatus aclnnIndexFillGetWorkspaceSize(
   const aclTensor*        self,
   int64_t           dim,
   const aclTensor*  index,
   const aclScalar*  value,
   aclTensor*        out,
   uint64_t*         workspaceSize,
   aclOpExecutor**   executor)
aclnnStatus aclnnIndexFill(
 void          *workspace,
 uint64_t       workspaceSize,
 aclOpExecutor *executor,
 aclrtStream    stream)
aclnnStatus aclnnInplaceIndexFillGetWorkspaceSize(
 aclTensor*       self,
 int64_t          dim,
 const aclTensor* index,
 const aclScalar* value,
 uint64_t*        workspaceSize,
 aclOpExecutor**  executor)
aclnnStatus aclnnInplaceIndexFill(
 void             *workspace,
 uint64_t          workspaceSize,
 aclOpExecutor    *executor,
 aclrtStream       stream)

aclnnIndexFillGetWorkspaceSize

  • Parameters

    Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor
    self Input self in the function example, that is, the tensor whose values at specified positions are to be replaced with value. - FLOAT16, FLOAT, INT32, INT64, BOOL, BFLOAT16, INT8, UINT8, INT16, DOUBLE ND 0-8 √
    dim Input Specifies the dimension of self to be filled. When self is 1-8 dimensional, the value range of dim is [-self.dim(), self.dim()). When self is 0-dimensional, the value range of dim is [-1, 1). int64 - - -
    index Input Specifies the indices to be filled in self along dim. Each element value must be smaller than the size of self along dim. Negative values are supported. Out-of-range values are supported and are skipped. INT32, INT64 - - -
    value Input Specifies the data value for filling. Must be convertible to the data type of self. Consistent with the data type range of self - - -
    out Output The specified output tensor. - Same as self ND Same as self √
    workspaceSize Output Returns the workspace size to be allocated on the Device side. - - - - -
    executor Output Returns the op executor containing the operator computation flow. - - - - -
    - Atlas A2 products and Atlas A3 products: data types FLOAT16, FLOAT, INT32, INT64, BOOL, and BFLOAT16 are supported. - Ascend 950PR&950DT products: data types FLOAT16, FLOAT, INT32, INT64, BOOL, BFLOAT16, INT8, UINT8, INT16, and DOUBLE are supported.
  • 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 input self, index, value, or out is a null pointer.
    ACLNN_ERR_PARAM_INVALID 161002 The data types of self, index, and value are not within the supported range.
    The absolute value of dim exceeds the maximum dim value of self or exceeds 8.
    The shapes of self and out are different.
    The data types of self and out are different.

aclnnIndexFill

  • Parameters

    Parameter Input/Output Description
    workspace Input Workspace memory address allocated on the Device side.
    workspaceSize Input Workspace size allocated on the Device side, obtained by the first-phase API aclnnIndexFillGetWorkspaceSize.
    executor Input Executor of the op. It contains the computation process of the operator.
    stream Input Stream for executing the task.
  • Return Value

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

aclnnInplaceIndexFillGetWorkspaceSize

  • Parameters

    Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor
    self Input Tensor whose values at specified positions are to be replaced with value. - FLOAT16, FLOAT, INT32, INT64, BOOL, BFLOAT16, INT8, UINT8, INT16, DOUBLE ND 0-8 √
    dim Input Specifies the dimension along which self is filled. When self has 1-8 dimensions, the value range of dim is [-self.dim(), self.dim()). When self has 0 dimensions, the value range of dim is [-1, 1). int64 - - -
    index Input Specifies the indices of self to be filled along dim. Each element value is smaller than the size of the corresponding dim of self. Negative values are supported. Out-of-bounds values are supported and are directly skipped. INT32, INT64 - - -
    value Input Specifies the value used for filling. - Same range as the data type of self - - -
    workspaceSize Output Returns the workspace size to be allocated on the Device side. - - - - -
    executor Output Returns the op executor containing the operator computation flow. - - - - -
    - Atlas A2 products and Atlas A3 products: The supported data types are FLOAT16, FLOAT, INT32, INT64, BOOL, and BFLOAT16. - Ascend 950PR&950DT products: The supported data types are FLOAT16, FLOAT, INT32, INT64, BOOL, BFLOAT16, INT8, UINT8, INT16, and DOUBLE.
  • 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 input self, index, or value is a null pointer.
    ACLNN_ERR_PARAM_INVALID 161002 The data type of self, index, or value is not within the supported range.
    The absolute value of dim exceeds the maximum dim of self or exceeds 8 dimensions.

aclnnInplaceIndexFill

  • Parameters

    Parameter Input/Output Description
    workspace Input Workspace memory address allocated on the Device side.
    workspaceSize Input Workspace size allocated on the Device side, obtained by the first-phase API aclnnInplaceIndexFillGetWorkspaceSize.
    executor Input Op executor, which contains the operator computation flow.
    stream Input Specifies the stream for task execution.
  • Return Value

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

Constraints

  • Deterministic computation:
    • aclnnIndexFill&aclnnInplaceIndexFill default to a deterministic implementation.

Example

The sample code is as follows and is for reference only. For details about compilation and execution, see Compile and Run Samples.

#include <iostream>
#include <vector>
#include "acl/acl.h"
#include "aclnnop/aclnn_index_fill.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 memory on the device side.
  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) Device/stream initialization. For details, see the acl API documentation.
  // 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, which are customized based on the API.
  std::vector<int64_t> selfShape = {3, 3};
  std::vector<int64_t> indexShape = {1};
  std::vector<int64_t> outShape = selfShape;
  void* selfDeviceAddr = nullptr;
  void* indexDeviceAddr = nullptr;
  void* outDeviceAddr = nullptr;
  aclTensor* self = nullptr;
  aclTensor* index = nullptr;
  aclScalar* value = nullptr;
  aclTensor* out = nullptr;
  std::vector<float> selfHostData = {0, 1, 2, 3, 4, 5, 6, 7, 8};
  std::vector<int64_t> indexHostData = {0};
  std::vector<float> outHostData = {0, 0, 0, 0, 0, 0, 0, 0, 0};
  int64_t dim = 1;
  float fillVal = 10;
  // 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);
  // Create the value aclScalar.
  value = aclCreateScalar(&fillVal, aclDataType::ACL_FLOAT);
  CHECK_RET(value != nullptr, return ret);

  // 3. Call the CANN operator library API. Replace it with the specific API name.
  uint64_t workspaceSize = 0;
  aclOpExecutor* executor;
  // Call the first-phase API of aclnnIndexFill.
  ret = aclnnIndexFillGetWorkspaceSize(self, dim, index, value, out, &workspaceSize, &executor);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnIndexFillGetWorkspaceSize failed. ERROR: %d\n", ret); return ret);
  // Allocate 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 aclnnIndexFill.
  ret = aclnnIndexFill(workspaceAddr, workspaceSize, executor, stream);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnIndexFill failed. ERROR: %d\n", ret); return ret);
  // 4. (Boilerplate) Synchronize and wait for the 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 on the device side to the host side. Modify it 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 the requested variables. Modify it based on the specific API definition.
  aclDestroyTensor(self);
  aclDestroyTensor(index);
  aclDestroyTensor(out);
  aclDestroyScalar(value);

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

aclnnInplaceIndexFill API call example code:

#include <iostream>
#include <vector>
#include "acl/acl.h"
#include "aclnnop/aclnn_index_fill.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 memory on the 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);
  // Call aclrtMemcpy to copy data from the host to the device 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, which need to be customized based on the API.
  std::vector<int64_t> selfShape = {3, 3};
  std::vector<int64_t> indexShape = {1};
  void* selfDeviceAddr = nullptr;
  void* indexDeviceAddr = nullptr;
  aclTensor* self = nullptr;
  aclTensor* index = nullptr;
  aclScalar* value = nullptr;
  std::vector<float> selfHostData = {0, 1, 2, 3, 4, 5, 6, 7, 8};
  std::vector<int64_t> indexHostData = {0};
  int64_t dim = 1;
  float fillVal = 10;
  // 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 value aclScalar.
  value = aclCreateScalar(&fillVal, aclDataType::ACL_FLOAT);
  CHECK_RET(value != nullptr, return ret);

  // 3. Call the CANN operator library API. Change it to the specific API name.
  uint64_t workspaceSize = 0;
  aclOpExecutor* executor;
  // Call the first-phase API of aclnnInplaceIndexFill.
  ret = aclnnInplaceIndexFillGetWorkspaceSize(self, dim, index, value, &workspaceSize, &executor);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnInplaceIndexFillGetWorkspaceSize failed. ERROR: %d\n", ret); return ret);
  // Allocate 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 aclnnInplaceIndexFill.
  ret = aclnnInplaceIndexFill(workspaceAddr, workspaceSize, executor, stream);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnInplaceIndexFill 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 values and copy the result from device memory to host memory. Modify it according to the definition of the specific API.
  auto size = GetShapeSize(selfShape);
  std::vector<float> resultData(size, 0);
  ret = aclrtMemcpy(resultData.data(), resultData.size() * sizeof(resultData[0]), selfDeviceAddr,
                    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 the aclTensor and aclScalar. Modify it according to the definition of the specific API.
  aclDestroyTensor(self);
  aclDestroyTensor(index);
  aclDestroyScalar(value);

  // 7. Release device resources. Modify it according to the definition of the specific API.
  aclrtFree(selfDeviceAddr);
  aclrtFree(indexDeviceAddr);
  if (workspaceSize > 0) {
    aclrtFree(workspaceAddr);
  }
  aclrtDestroyStream(stream);
  aclrtResetDevice(deviceId);
  aclFinalize();
  return 0;
}