aclnnInplaceScatterUpdate

πŸ“„ 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: Supported

Function

Updates the values in tensor data one by one with the values in tensor updates based on the specified axis axis and indices indices. This operator uses custom operator semantics and has no corresponding TensorFlow or PyTorch API.

  • Example: This operator has 3 inputs and one attribute: data, updates, indices, and axis. data is the tensor to be updated, updates is the tensor that stores the update data, indices indicates the update positions, and axis is the specified update dimension. Depending on whether indices is 1D or 2D, there are the following two use cases (when indices is 0D, it is equivalent to the 1D use case with shape (1), and axis 0 of updates must be 1 in this case):

    Use case 1: indices is 1D. The i-th element of indices corresponds to the i-th batch of updates (axis 0 of updates) and indicates the start offset on the axis dimension when that batch is written into the i-th batch of data.

    Sample input:
    data:(a, b, c, d)
    if axis = -2: updates:(n, b, e, d), indices[i] + e <= c
    if axis = -1: updates:(n, b, c, e), indices[i] + e <= d
    indices:(n,), n <= a
    data[i][j][indices[i]+k][l] = updates[i][j][k][l] # if dim = -2
    data[i][j][k][indices[i]+l] = updates[i][j][k][l] # if dim = -1

    Case 2: indices is 2-dimensional, with size 2 along axis 1. The i-th row of indices corresponds to the i-th batch of updates: indices[i][0] specifies the position along axis 0 of data to which the batch is written (different i values can write to different batches of data), and indices[i][1] specifies the starting offset along the axis dimension. The size s of updates along the axis dimension is the length written each time, and indices[i][1] + s must not exceed the size of data along the axis dimension.

    Sample input:
    data:(a, b, c, d)
    if axis = -2: updates:(n, b, e, d), indices[i][1] + e <= c
    if axis = -1: updates:(n, b, c, e), indices[i][1] + e <= d
    indices:(n, 2), indices[i][0] < a
    data[indices[i][0]][j][indices[i][1]+k][l] = updates[i][j][k][l] # if dim = -2
    data[indices[i][0]][j][k][indices[i][1]+l] = updates[i][j][k][l] # if dim = -1

Function Prototype

Each operator uses a two-phase API. Call the "aclnnInplaceScatterUpdateGetWorkspaceSize" API first to obtain the workspace size required for computation and the executor containing the operator computation process, and then call the "aclnnInplaceScatterUpdate" API to execute the computation.

aclnnStatus aclnnInplaceScatterUpdateGetWorkspaceSize(
    aclTensor*       data,
    const aclTensor* indices,
    const aclTensor* updates,
    int64_t          axis,
    uint64_t*        workspaceSize,
    aclOpExecutor**  executor)
aclnnStatus aclnnInplaceScatterUpdate(
    void*          workspace,
    uint64_t       workspaceSize,
    aclOpExecutor* executor,
    aclrtStream    stream)

aclnnInplaceScatterUpdateGetWorkspaceSize

  • Parameters

    Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor
    data (aclTensor*) Input/Output Tensor to be updated. The number of dimensions must be the same as that of updates. Empty tensors are not supported. INT8, UINT8, FLOAT16, FLOAT32, INT32, BFLOAT16, FLOAT8_E4M3FN, FLOAT8_E5M2, HIFLOAT8 ND 2-8 √
    indices (aclTensor*) Input Indices of positions to update. Only non-negative indices are supported, and indices must be within bounds. Empty tensors are not supported. INT32, INT64 ND 0-2 √
    updates (aclTensor*) Input Tensor that stores the update data. The data type must be the same as that of data, and the number of dimensions of the shape must be the same as that of the data shape. Empty tensors are not supported. INT8, UINT8, FLOAT16, FLOAT32, INT32, BFLOAT16, FLOAT8_E4M3FN, FLOAT8_E5M2, HIFLOAT8 ND 2-8 √
    axis (int64_t) Input Dimension along which to scatter. Value range: (-data_rank, data_rank), and axis cannot be 0. - - - -
    workspaceSize (uint64_t*) Output Returns the workspace size to be allocated on the device. - - - - -
    executor (aclOpExecutor**) Output Returns the op executor, which contains the operator computation flow. - - - - -
    • Atlas training products: Data types UINT8 and BFLOAT16 are not supported.
    • Ascend 950PR&950DT products: Data types such as FLOAT8_E4M3FN, FLOAT8_E5M2, and HIFLOAT8 are supported only on this model.
  • 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:

    Returns Error Codes Description
    ACLNN_ERR_PARAM_NULLPTR 161001 data, indices, or updates is a null pointer.
    ACLNN_ERR_PARAM_INVALID 161002 The data type of data, indices, or updates is out of the supported range.
    The data types of data and updates are different.
    data and updates have inconsistent numbers of dimensions.
    indices is not a 0D, 1D, or 2D tensor.
    If indices is 0D, the size of the 0th axis of updates is not 1.
    data, indices, or updates is a null tensor.

aclnnInplaceScatterUpdate

  • Parameters

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

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

Constraints

  • The 0th dimension of the updates shape is the same as that of the indices shape.

  • If indices is a 0-dimensional tensor, the 0th dimension of the updates shape is 1.

  • The 0th dimension of the updates shape is less than or equal to that of the data shape.

  • The shapes of updates and data must be the same on all axes except the axis axis and axis 0.

  • If the shape of indices is two-dimensional, axis 1 of the shape must be 2.

  • If the data type of indices is INT32, DtypeSize=4; if the data type is INT64, DtypeSize=8. IndicesShapeSize is the product of the shape of indices. The required UB = IndicesShapeSize * DtypeSize + 224. This API is not supported if the required UB is greater than the total UB size available for the corresponding AI processor version.

  • If indices contains duplicates, the results at the duplicate positions are not guaranteed.

  • Deterministic computation:

    • Ascend 950PR&950DT products: Default to a non-deterministic implementation. Deterministic computation can be enabled through aclrtSetSysParamOpt.
    • Atlas A3 products, Atlas A2 products, and Atlas training products: Default to a deterministic implementation.

Example

The following sample code 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_scatter_update.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 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);
  // Call aclrtMemcpy to copy host data to 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 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. For details, see the acl API reference.
  // 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 inputs and outputs as required by the API
  int64_t axis = -2;
  std::vector<int64_t> selfRefShape = {1, 1, 2, 8};
  std::vector<int64_t> indicesShape = {1};
  std::vector<int64_t> updatesShape = {1, 1, 1, 8};
  void* selfRefDeviceAddr = nullptr;
  void* indicesDeviceAddr = nullptr;
  void* updatesDeviceAddr = nullptr;
  aclTensor* selfRef = nullptr;
  aclTensor* indices = nullptr;
  aclTensor* updates = nullptr;
  std::vector<float> selfRefHostData = {1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2};
  std::vector<int64_t> indicesHostData = {1};
  std::vector<float> updatesHostData = {3, 3, 3, 3, 3, 3, 3, 3};

  // Create the selfRef aclTensor
  ret = CreateAclTensor(selfRefHostData, selfRefShape, &selfRefDeviceAddr, aclDataType::ACL_FLOAT, &selfRef);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  // Create the indices aclTensor.
  ret = CreateAclTensor(indicesHostData, indicesShape, &indicesDeviceAddr, aclDataType::ACL_INT64, &indices);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  // Create the updates aclTensor.
  ret = CreateAclTensor(updatesHostData, updatesShape, &updatesDeviceAddr, aclDataType::ACL_FLOAT, &updates);
  CHECK_RET(ret == ACL_SUCCESS, return ret);

  // 3. Call the CANN operator library API. Replace it with the actual API name.
  uint64_t workspaceSize = 0;
  aclOpExecutor* executor;
  // Call the aclnnInplaceScatterUpdate first-phase API.
  ret = aclnnInplaceScatterUpdateGetWorkspaceSize(selfRef, indices, updates, axis, &workspaceSize, &executor);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnInplaceScatterUpdateGetWorkspaceSize 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 aclnnInplaceScatterUpdate second-phase API.
  ret = aclnnInplaceScatterUpdate(workspaceAddr, workspaceSize, executor, stream);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnInplaceScatterUpdate failed. ERROR: %d\n", ret); return ret);

  // 4. (Boilerplate) Synchronously 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. Copy the result from device memory to host memory. Modify the code based on the specific API definition.
  auto size = GetShapeSize(selfRefShape);
  std::vector<float> resultData(size, 0);
  ret = aclrtMemcpy(resultData.data(), resultData.size() * sizeof(resultData[0]), selfRefDeviceAddr,
                    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 the code based on the specific API definition.
  aclDestroyTensor(selfRef);
  aclDestroyTensor(indices);
  aclDestroyTensor(updates);

  // 7. Release device resources.
  aclrtFree(selfRefDeviceAddr);
  aclrtFree(indicesDeviceAddr);
  aclrtFree(updatesDeviceAddr);
  if (workspaceSize > 0) {
    aclrtFree(workspaceAddr);
  }
  aclrtDestroyStream(stream);
  aclrtResetDevice(deviceId);
  aclFinalize();

  return 0;
}