aclnnInplaceQuantScatter

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: Supported
  • Atlas training products: Not supported

Function

First, quantize updates along the quantAxis. quantScales performs scaling on updates, and quantZeroPoints performs offset. Then, update the values at corresponding positions in selfRef one by one along the specified axis based on the index tensor indices, using the quantized values from updates.

Function Prototype

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

aclnnStatus aclnnInplaceQuantScatterGetWorkspaceSize(
  aclTensor       *selfRef,
  const aclTensor *indices,
  const aclTensor *updates,
  const aclTensor *quantScales,
  const aclTensor *quantZeroPoints,
  int64_t          axis,
  int64_t          quantAxis,
  int64_t          reduction,
  uint64_t         *workspaceSize,
  aclOpExecutor   **executor)
aclnnStatus aclnnInplaceQuantScatter(
  void          *workspace,
  uint64_t       workspaceSize,
  aclOpExecutor *executor,
  aclrtStream    stream)

aclnnInplaceQuantScatterGetWorkspaceSize

  • Parameters:

    Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor
    selfRef Input|Output Source data tensor. - INT8 ND 3 √
    indices Input Index tensor. The value range of indices is [0, selfRef.shape(axis) - updates.shape(axis)). INT32, INT64 ND 1 √
    updates Input Update data tensor. The number of dimensions of updates must be the same as that of selfRef. The dimension size of its first dimension must be equal to the first dimension size of indices and not greater than the first dimension size of selfRef. The axis size of its axis dimension must not be greater than the axis size of the axis dimension of selfRef. The dimension sizes of the remaining dimensions must be equal to the corresponding dimension sizes of selfRef. BFLOAT16, FLOAT16 ND Same as selfRef. √
    quantScales Input Quantization scale tensor. The number of elements must be equal to the axis size of updates along quantAxis. BFLOAT16, FLOAT32 ND 3 √
    quantZeroPoints Optional input Quantization offset tensor. The number of elements must equal the axis size of updates on quantAxis. BFLOAT16, INT32 ND 3 √
    axis Input The axis on updates used for updating. Only -2 is supported. - - - -
    quantAxis Input The axis on updates used for quantization. Supported values: -1 or len(updates.shape) - 1. - - - -
    reduction Input Specifies the data operation mode. Supported value: 1 (update). - - - -
    workspaceSize Output Size of the workspace that needs to be allocated on the Device side. - - - - -
    executor Output Returns the op executor containing the operator computation process. - - - - -
    • Atlas inference products:
      • BFLOAT16 data type is not supported.
    • Atlas inference products, Atlas A2 products, Atlas A3 products:
      • The last dimension size of selfRef and updates must be 32 Byte aligned.
  • 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 If a required input, output, or attribute is a null pointer, 161001 is returned.
    ACLNN_ERR_PARAM_INVALID 161002 The data type combinations of selfRef, indices, updates, quantScales, and quantZeroPoints are not within the supported range. For the supported combinations, see the constraints.
    The dimension counts of selfRef and updates are inconsistent.

aclnnInplaceQuantScatter

  • Parameters

    ParameterInput/OutputDescription
    workspaceInputWorkspace memory address allocated on the Device side.
    workspaceSizeInputWorkspace size allocated on the Device side. Obtained by the first-phase API aclnnInplaceQuantScatterGetWorkspaceSize.
    executorInput Op executor, containing the operator computation flow.
    streamInput Stream on which the task is executed.
  • Return Value

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

Constraints

  • Deterministic computation:

    • aclnnInplaceQuantScatter defaults to a deterministic implementation.
  • The indices must be one-dimensional. Out-of-bounds indexing is not supported and is not validated. The selfRef data segments mapped by indices must not overlap; otherwise, multiple executions may produce different results due to multi-core concurrency.

  • The data type input combinations of selfRef, indices, updates, quantScales, and quantZeroPoints include:

    • Atlas inference products:

| selfRef | Indices | Updates | quantScales | quantZeroPoints | |---|---|---|---|---| |INT8|INT32|FLOAT16|FLOAT32|INT32| |INT8|INT64|FLOAT16|FLOAT32|INT32|

  • Atlas A2 products, Atlas A3 products, Ascend 950PR&950DT products:

| selfRef | Indices | Updates | quantScales | quantZeroPoints | |---|---|---|---|---| |INT8|INT32|BFLOAT16|BFLOAT16|BFLOAT16| |INT8|INT64|BFLOAT16|BFLOAT16|BFLOAT16| |INT8|INT32|FLOAT16|FLOAT32|INT32| |INT8|INT64|FLOAT16|FLOAT32|INT32|

Example

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_quant_scatter.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-side 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-side data to 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 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 input and output. You need to construct them based on the API.
  std::vector<int64_t> selfRefShape = {1, 1, 32};
  std::vector<int64_t> indicesShape = {1};
  std::vector<int64_t> updatesShape = {1, 1, 32};
  std::vector<int64_t> quantScalesShape = {1, 1, 32};
  std::vector<int64_t> quantZeroPointsShape = {1, 1, 32};
  void* selfRefDeviceAddr = nullptr;
  void* indicesDeviceAddr = nullptr;
  void* updatesDeviceAddr = nullptr;
  void* quantScalesDeviceAddr = nullptr;
  void* quantZeroPointsDeviceAddr = nullptr;
  aclTensor* selfRef = nullptr;
  aclTensor* indices = nullptr;
  aclTensor* updates = nullptr;
  aclTensor* quantScales = nullptr;
  aclTensor* quantZeroPoints = nullptr;
  std::vector<int8_t> selfRefHostData(32, 0);
  std::vector<int32_t> indicesHostData{0};
  std::vector<uint16_t> updatesHostData(32, 15360);  // FP16 1.0 = 0x3C00 = 15360
  std::vector<float> quantScalesHostData(32, 0.5);
  std::vector<int32_t> quantZeroPointsHostData(32, 0);
  int64_t axis = -2;
  int64_t quantAxis = -1;
  int64_t reduction = 1;

  // Create the selfRef aclTensor.
  ret = CreateAclTensor(selfRefHostData, selfRefShape, &selfRefDeviceAddr, aclDataType::ACL_INT8, &selfRef);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  // Create the indices aclTensor.
  ret = CreateAclTensor(indicesHostData, indicesShape, &indicesDeviceAddr, aclDataType::ACL_INT32, &indices);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  // Create the updates aclTensor.
  ret = CreateAclTensor(updatesHostData, updatesShape, &updatesDeviceAddr, aclDataType::ACL_FLOAT16, &updates);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  // Create the quantScales aclTensor.
  ret = CreateAclTensor(quantScalesHostData, quantScalesShape, &quantScalesDeviceAddr, aclDataType::ACL_FLOAT,
                        &quantScales);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  // Create the quantZeroPoints aclTensor.
  ret = CreateAclTensor(quantZeroPointsHostData, quantZeroPointsShape, &quantZeroPointsDeviceAddr,
                        aclDataType::ACL_INT32, &quantZeroPoints);
  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 aclnnInplaceQuantScatter.
  ret = aclnnInplaceQuantScatterGetWorkspaceSize(selfRef, indices, updates, quantScales, quantZeroPoints, axis,
                                                 quantAxis, reduction, &workspaceSize, &executor);
  CHECK_RET(ret == ACL_SUCCESS,
            LOG_PRINT("aclnnInplaceQuantScatterGetWorkspaceSize 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 aclnnInplaceQuantScatter.
  ret = aclnnInplaceQuantScatter(workspaceAddr, workspaceSize, executor, stream);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnInplaceQuantScatter failed. ERROR: %d\n", ret); return ret);

  // 4. (Boilerplate) Synchronize and wait for the task execution to finish.
  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 the Device-side memory to the Host side, and modify it based on the specific API definition.
  auto size = GetShapeSize(selfRefShape);
  std::vector<int8_t> 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: %d\n", i, resultData[i]);
  }

  // 6. Release aclTensor and aclScalar, and modify it based on the specific API definition.
  aclDestroyTensor(selfRef);
  aclDestroyTensor(indices);
  aclDestroyTensor(updates);
  aclDestroyTensor(quantScales);
  aclDestroyTensor(quantZeroPoints);

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

  return 0;
}