aclnnScale

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

  • Description: Computes the result of scale and bias on the input.

  • Formula:

    If bias is not provided, then

    y=x∗scaley=x*scale

    If bias is input, then

    y=x∗scale+biasy=x*scale + bias

    NOTE scale/bias supports broadcasting with X. The shape rules for scale/bias are as follows:

    • When scaleFromBlob is True (axis is converted to a positive number, and numAxes being -1 indicates up to the last axis):

      scaleShape is xShape[axis:axis + numAxes]

      biasShape is xShape[axis:axis + numAxes]

    • When scaleFromBlob is False (axis is converted to positive, and numAxes being -1 indicates up to the foremost axis):

      scaleShape is xShape[axis:axis + rank(scaleShape)]

      biasShape is xShape[axis:axis + rank(scaleShape)]

    • Example:

      • scaleFromBlob = True:

        xShape = [a, b, c, d, e, f] axis = 3 numAxes = 2 --> scaleShape = [d, e]

        xShape = [a, b, c, d, e, f] axis = 3 numAxes = 3 --> scaleShape = [d, e, f]

        xShape = [a, b, c, d, e, f] axis = 3 numAxes = -1 --> scaleShape = [d, e, f]

      • scaleFromBlob = False:

        xShape = [a, b, c, d, e, f] axis = 3 rank(scaleShape) = 2 --> scaleShape = [d, e]

        xShape = [a, b, c, d, e, f] axis = 3 rank(scaleShape) = 3 --> scaleShape = [d, e, f]

        xShape = [a, b, c, d, e, f] axis = 3 rank(scaleShape) = 1 --> scaleShape = [d]

Function Prototype

Each operator uses a two-phase API. You must first call "aclnnScaleGetWorkspaceSize" to obtain the workspace size required for computation and the executor containing the operator calculation process, and then call "aclnnScale" to execute the computation.

aclnnStatus aclnnScaleGetWorkspaceSize(
  const aclTensor* x,
  const aclTensor* scale,
  const aclTensor* bias,
  int64_t          axis,
  int64_t          numAxes,
  bool             scaleFromBlob,
  aclTensor*       y,
  uint64_t*        workspaceSize,
  aclOpExecutor**  executor)
aclnnStatus aclnnScale(
  void*          workspace,
  uint64_t       workspaceSize,
  aclOpExecutor* executor,
  aclrtStream    stream)

aclnnScaleGetWorkspaceSize

  • Parameters:

    Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor
    x (aclTensor*) Input Tensor that serves as the operator input. Supports empty tensors. FLOAT, FLOAT16, BFLOAT16 ND 0-8 √
    scale (aclTensor*) Input Tensor that serves as the operator input. Supports empty tensors. The data type needs to match the data type of x. The shape must meet broadcast requirements (see Function). FLOAT, FLOAT16, BFLOAT16 ND 0-8 √
    bias (aclTensor*) Optional input Tensor of the operator input. Supports empty tensors. When not empty, the data type needs to match the data type of scale, and the shape must be consistent with that of scale. FLOAT, FLOAT16, BFLOAT16 ND 0-8 √
    axis (int64_t) Input Specifies the starting axis for scale. Value range: [-x_rank, x_rank) (x_rank indicates the number of dimensions in the shape of x). - - - -
    numAxes (int64_t) Input Specifies the length of axes to scale. Value range >= -1. numAxes=-1 indicates scaling from axis to the last axis. - - - -
    scaleFromBlob (bool) Input Specifies the scaleFromBlob type.
    • True: scale from blob, performing scaling using numAxes + axis;
    • False: scale from input scale, performing scaling for the length of input scale starting from axis, with numAxes ignored.
    - - - -
    y (aclTensor*) Output Output tensor. Supports empty tensors. The data type needs to match the data type of x, and the shape dimensions are consistent with those of x. FLOAT, FLOAT16, BFLOAT16 ND 0-8 √
    workspaceSize (uint64_t*) Output Returns the workspace size requested by the Device. - - - - -
    executor (aclOpExecutor**) Output Returns the op executor, which contains the calculation process of the operator. - - - - -
  • Return value

    aclnnStatus: return status code. For details, see Error 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 x, scale, or y is a null pointer.
    ACLNN_ERR_PARAM_INVALID 161002 The data type of x is out of the supported range.
    When bias is not empty, the data type of bias does not match that of scale.
    The data type of scale does not match that of x.
    The data type of y does not match that of x.
    The shapes of x and y are inconsistent.
    When bias is not empty, the shapes of bias and scale are inconsistent.
    The shape dimensions of x and scale are greater than 8.
    The value of axis is not in the range of [-x_rank, x_rank).
    The value of numAxes is less than -1.
    scaleFromBlob is True, numAxes is 0, and the shape of scale is not [1].
    After axis is converted to a positive number, the sum of axis and numAxes is greater than x_rank.
    The shape of scale does not match the expected shape (for shape deduction, see Function).

aclnnScale

  • Parameters:

    Parameter Input/Output Description
    workspace Input The workspace memory address requested by the Device.
    workspaceSize Input The workspace size requested by the Device. The value is obtained by calling the first-phase API aclnnScaleGetWorkspaceSize.
    executor Input Op executor, which contains the calculation flow of the operator.
    stream Input Specifies the stream for executing tasks.
  • Return value

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

Constraints

  • Deterministic computation:
    • aclnnScale defaults 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_scale.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. See the acl API manual.
  // Set deviceId based on the actual device in use.
  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. Customize the construction based on the API.
  std::vector<int64_t> selfShape = {4, 2};
  std::vector<int64_t> tensor1Shape = {4};
  std::vector<int64_t> tensor2Shape = {4};
  std::vector<int64_t> outShape = {4, 2};
  void* selfDeviceAddr = nullptr;
  void* tensor1DeviceAddr = nullptr;
  void* tensor2DeviceAddr = nullptr;
  void* outDeviceAddr = nullptr;
  aclTensor* self = nullptr;
  aclTensor* tensor1 = nullptr;
  aclTensor* tensor2 = nullptr;
  aclTensor* out = nullptr;

  std::vector<float> selfHostData = {0, 1, 2, 3, 4, 5, 6, 7};
  std::vector<float> tensor1HostData = {2, 2, 2, 2};
  std::vector<float> tensor2HostData = {2, 2, 2, 2};
  std::vector<float> outHostData = {0, 0, 0, 0, 0, 0, 0, 0};
  int64_t axis = 0;
  int64_t numAxes = 1;
  bool fromBlob = true;

  // Create the self aclTensor.
  ret = CreateAclTensor(selfHostData, selfShape, &selfDeviceAddr, aclDataType::ACL_FLOAT, &self);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  // Create the tensor1 aclTensor.
  ret = CreateAclTensor(tensor1HostData, tensor1Shape, &tensor1DeviceAddr, aclDataType::ACL_FLOAT, &tensor1);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  // Create the tensor2 aclTensor.
  ret = CreateAclTensor(tensor2HostData, tensor2Shape, &tensor2DeviceAddr, aclDataType::ACL_FLOAT, &tensor2);
  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. Replace it with the specific API name
  uint64_t workspaceSize = 0;
  aclOpExecutor* executor;
  // Call the first-phase API of aclnnScale
  ret = aclnnScaleGetWorkspaceSize(self, tensor1, tensor2, axis, numAxes, fromBlob,  out, &workspaceSize, &executor);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnScaleGetWorkspaceSize 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 aclnnScale
  ret = aclnnScale(workspaceAddr, workspaceSize, executor, stream);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnScale failed. ERROR: %d\n", ret); return ret);

  // 4. (Boilerplate) 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 memory to host memory. 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 resultData from device to host failed. ERROR: %d\n", ret);
            return ret);
  for (int64_t i = 0; i < size; i++) {
    LOG_PRINT("resultData[%ld] is: %f\n", i, resultData[i]);
  }

  // 6. Release aclTensor and aclScalar. Modify it based on the specific API definition
  aclDestroyTensor(self);
  aclDestroyTensor(tensor1);
  aclDestroyTensor(tensor2);
  aclDestroyTensor(out);

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

  return 0;
}