aclnnSubs&aclnnInplaceSubs

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

Function

  • Description: Performs subtraction, with the minuend scaled by alpha.
  • Formula:outi=selfi−alpha×otherout_{i} = self_{i} - alpha \times other selfRefi=selfRefi−alpha×otherselfRef_{i} = selfRef_{i} - alpha \times other

Function Prototype

  • aclnnSubs and aclnnInplaceSubs implement the same function. The differences in usage are as follows. Select the appropriate operator based on your actual scenario.
    • aclnnSubs: Create a new output tensor object to store the computation result.
    • aclnnInplaceSubs: No need to create a new output tensor object. The computation result is stored directly in the memory of the input tensor.
  • Each operator uses a two-phase API. First, call "aclnnSubsGetWorkspaceSize" or "aclnnInplaceSubsGetWorkspaceSize" to obtain the input parameters and calculate the required workspace size based on the computation process, and then call "aclnnSubs" or "aclnnInplaceSubs" to perform the computation.
aclnnStatus aclnnSubsGetWorkspaceSize(
    const aclTensor* self,
    const aclScalar* other,
    const aclScalar* alpha,
    aclTensor*       out,
    uint64_t*        workspaceSize,
    aclOpExecutor**  executor)
aclnnStatus aclnnSubs(
    void*          workspace,
    uint64_t       workspaceSize,
    aclOpExecutor* executor,
    aclrtStream    stream)
aclnnStatus aclnnInplaceSubsGetWorkspaceSize(
    aclTensor* selfRef,
    const aclScalar* other,
    const aclScalar* alpha,
    uint64_t*        workspaceSize,
    aclOpExecutor**  executor)
aclnnStatus aclnnInplaceSubs(
    void*          workspace,
    uint64_t       workspaceSize,
    aclOpExecutor* executor,
    aclrtStream    stream)

aclnnSubsGetWorkspaceSize

  • 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 must satisfy the data type deduction rule with the data type of other (see deduction relationship). FLOAT, FLOAT16, DOUBLE, INT32, INT64, INT16, INT8, UINT8, BOOL, COMPLEX128, COMPLEX64, BFLOAT16 ND 0-8 √
    other (aclScalar*) Input other in the formula. The data type and the data type of self must satisfy the data type deduction rule (see deduction relationship). FLOAT, FLOAT16, DOUBLE, INT32, INT64, INT16, INT8, UINT8, BOOL, COMPLEX128, COMPLEX64, BFLOAT16 - - -
    alpha (aclScalar*) Input alpha in the formula. The data type must be convertible to the derived data type of self and other (see deduction relationship). FLOAT, FLOAT16, DOUBLE, INT32, INT64, INT16, INT8, UINT8, BOOL, COMPLEX128, COMPLEX64, BFLOAT16 - - -
    out (aclTensor*) Output out in the formula. The data type must be convertible from the data types of self and other after deduction (see conversion relationship). FLOAT, FLOAT16, DOUBLE, INT32, INT64, INT16, INT8, UINT8, BOOL, COMPLEX128, COMPLEX64, BFLOAT16 ND 0-8 √
    workspaceSize (uint64_t*) Output Workspace size to be allocated on the Device side. - - - - -
    executor (aclOpExecutor**) Output Returns the op executor, which contains the operator computation flow. - - - - -
    • Atlas inference products and Atlas training products: BFLOAT16 data type is not supported.
  • Return value:

    aclnnStatus: Return status code, see specifically 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 When self, other, alpha, or out is a null pointer.
    ACLNN_ERR_PARAM_INVALID 161002 The data type of self is not supported.
    self and other do not satisfy the data type deduction rule.
    The derived data type cannot be converted to the type of the specified output out.
    alpha cannot be converted to the derived data type of self and other.
    The shapes of self and out are inconsistent.
    The dimensions of self and out are greater than 8.

aclnnSubs

  • 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 from the first-phase API aclnnSubsGetWorkspaceSize.
    executor Input op executor, which contains the operator computation flow.
    stream Input Specifies the Stream for task execution.
  • Return value:

    aclnnStatus: return status code, see specifically aclnn return code.

aclnnInplaceSubsGetWorkspaceSize

  • Parameters:

    Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor
    selfRef (aclTensor*) Input selfRef in the formula. The data type and the data type of other must satisfy the data type deduction rule (see deduction relationship), and must be a data type convertible after deduction (see conversion relationship). FLOAT, FLOAT16, DOUBLE, INT32, INT64, INT16, INT8, UINT8, BOOL, COMPLEX128, COMPLEX64, BFLOAT16 ND 0-8 √
    other (aclScalar*) Input other in the formula. The data type must satisfy the deduction relationship with selfRef, and must be convertible after deduction (see conversion relationship). FLOAT, FLOAT16, DOUBLE, INT32, INT64, INT16, INT8, UINT8, BOOL, COMPLEX128, COMPLEX64, BFLOAT16 - - -
    alpha (aclScalar*) Input alpha in the formula. The data type must be convertible to the derived data types of selfRef and other (see deduction relationship). FLOAT, FLOAT16, DOUBLE, INT32, INT64, INT16, INT8, UINT8, BOOL, COMPLEX128, COMPLEX64, BFLOAT16 - - -
    workspaceSize (uint64_t*) Output Returns the workspace size to be applied on the side of the Device. - - - - -
    executor (aclOpExecutor**) Output Returns the op executor, which contains the operator computation flow. - - - - -
    • Atlas inference products and Atlas training products: BFLOAT16 data type is not supported.
  • Return value:

    aclnnStatus: Return status code, see specifically 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 When selfRef, other, or alpha is a null pointer.
    ACLNN_ERR_PARAM_INVALID 161002 The data type of selfRef is not supported.
    selfRef and other do not satisfy the data type deduction rule.
    The derived data type cannot be converted to the type of selfRef.
    alpha cannot be converted to the data type derived from selfRef and other.

aclnnInplaceSubs

  • 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 from the first-phase API aclnnInplaceSubsGetWorkspaceSize.
    executor Input Op executor, which contains the operator computation flow.
    stream Input Stream on which the task is executed.
  • Return value:

    aclnnStatus: return status code. See specifically aclnn return code.

Constraints

  • Deterministic computation:
    • aclnnSubs&aclnnInplaceSubs 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_sub.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); aclFinalize(); return ret);
  ret = aclrtCreateStream(stream);
  CHECK_RET(ret == ACL_SUCCESS,
            LOG_PRINT("aclrtCreateStream failed. ERROR: %d\n", ret);
            aclrtResetDevice(deviceId); aclFinalize(); 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 device/stream. For details, see the acl API reference.
  // Specify 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. The construction must be customized based on the API interface.
  std::vector<int64_t> selfShape = {4, 2};
  std::vector<int64_t> outShape = {4, 2};
  void* selfDeviceAddr = nullptr;
  void* outDeviceAddr = nullptr;
  aclTensor* self = nullptr;
  aclScalar* other = nullptr;
  aclScalar* alpha = nullptr;
  aclTensor* out = nullptr;
  std::vector<float> selfHostData = {0, 1, 2, 3, 4, 5, 6, 7};
  std::vector<float> outHostData(8, 0);
  float otherValue = 2.0f;
  float alphaValue = 1.2f;
  // Create the self aclTensor.
  ret = CreateAclTensor(selfHostData, selfShape, &selfDeviceAddr, aclDataType::ACL_FLOAT, &self);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  // Create the other aclScalar.
  other = aclCreateScalar(&otherValue, aclDataType::ACL_FLOAT);
  CHECK_RET(other != nullptr, return ret);
  // Create the alpha aclScalar.
  alpha = aclCreateScalar(&alphaValue, aclDataType::ACL_FLOAT);
  CHECK_RET(alpha != nullptr, return ret);
  // Create the out aclTensor
  ret = CreateAclTensor(outHostData, outShape, &outDeviceAddr, aclDataType::ACL_FLOAT, &out);
  CHECK_RET(ret == ACL_SUCCESS, return ret);

  // aclnnSubs API call example
  // 3. Call the CANN operator library API
  uint64_t workspaceSize = 0;
  aclOpExecutor* executor;
  // Call the first-phase API of aclnnSubs
  ret = aclnnSubsGetWorkspaceSize(self, other, alpha, out, &workspaceSize, &executor);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnSubsGetWorkspaceSize failed. ERROR: %d\n", ret); return ret);
  // Allocate device memory based on the workspaceSize computed 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 aclnnSubs
  ret = aclnnSubs(workspaceAddr, workspaceSize, executor, stream);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnSubs failed. ERROR: %d\n", ret); return ret);
  // 4. (Boilerplate) Synchronously wait for the task to finish
  ret = aclrtSynchronizeStream(stream);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtSynchronizeStream failed. ERROR: %d\n", ret); return ret);
  // 5. Get the output value and copy the result from the device-side memory to the host side
  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]);
  }

  // aclnnInplaceSubs API call example
  // 3. Call the CANN operator library API
  LOG_PRINT("\ntest aclnnInplaceSubs\n");
  // Call the first-phase API of aclnnInplaceSubs.
  ret = aclnnInplaceSubsGetWorkspaceSize(self, other, alpha, &workspaceSize, &executor);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnInplaceSubsGetWorkspaceSize failed. ERROR: %d\n", ret); return ret);
  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 aclnnInplaceSubs.
  ret = aclnnInplaceSubs(workspaceAddr, workspaceSize, executor, stream);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnInplaceSubs failed. ERROR: %d\n", ret); return ret);

  // 4. 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. Copy the result in the device-side memory to the host side.
  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 aclTensor and aclScalar, which needs to be modified based on the specific API definition.
  aclDestroyTensor(self);
  aclDestroyScalar(other);
  aclDestroyScalar(alpha);
  aclDestroyTensor(out);

  // 7. Release device resources, which needs to be modified based on the specific API definition.
  aclrtFree(selfDeviceAddr);
  aclrtFree(outDeviceAddr);
  if (workspaceSize > 0) {
    aclrtFree(workspaceAddr);
  }
  aclrtDestroyStream(stream);
  aclrtResetDevice(deviceId);
  aclFinalize();

  return 0;
}