aclnnConstantPadNd

📄 View Source Code

Applicable Products

  • Ascend 950PR&950DT products: Not 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: Pads the input tensor self with the constant value specified by value, based on the pad parameter.

  • Formula:

    • Derivation formula for the shape of the out tensor:

      Assume the shape of input self is:[dim0in,dim1in,dim2in,dim3in]Assumepad=[dim3begin,dim3end,dim2begin,dim2end,dim1begin,dim1end,dim0begin,dim0end]\begin{aligned} &\text{Assume the shape of input self is:} \\ &[dim0_{in},dim1_{in}, dim2_{in}, dim3_{in}] &\text{Assume} \\ &pad = &[dim3_{begin},dim3_{end}, \\&&dim2_{begin},dim2_{end}, \\&&dim1_{begin},dim1_{end}, \\&&dim0_{begin},dim0_{end}] \end{aligned} Then the shape of output out is:[dim0out,dim1out,dim2out,dim3out]=[dim0begin+dim0in+dim0end,dim1begin+dim1in+dim1end,dim2begin+dim2in+dim2end,dim3begin+dim3in+dim3end]\begin{aligned} &\text{Then the shape of output out is:} \\ &[dim0_{out}, dim1_{out}, dim2_{out}, dim3_{out}] = &[dim0_{begin}+dim0_{in}+dim0_{end}, \\&&dim1_{begin}+dim1_{in}+dim1_{end}, \\&&dim2_{begin}+dim2_{in}+dim2_{end}, \\&&dim3_{begin}+dim3_{in}+dim3_{end}] \end{aligned}
    • Example 1: (When the pad array length equals twice the number of self dimensions)

      selfShape=[1,1,1,1,1]pad={0,1,2,3,4,5,6,7,8,9}outputShape=[8+1+9,6+1+7,4+1+5,2+1+3,0+1+1]=[18,14,10,6,2]\begin{aligned} selfShape &= [1, 1, 1, 1, 1]\\ pad &= \lbrace 0, 1, 2, 3, 4, 5, 6, 7, 8, 9\rbrace \\ outputShape &= [8+1+9, 6+1+7, 4+1+5, 2+1+3, 0+1+1]\\ &= [18,14,10,6,2] \end{aligned}
    • Example 2: (When the length of the pad array is less than twice the number of self dimensions)

      selfShape=[1,1,1,1,1]pad={0,1,2,3,4,5}outputShape=[0+1+0,0+1+0,4+1+5,2+1+3,0+1+1]=[1,1,10,6,2]\begin{aligned} selfShape &= [1, 1, 1, 1, 1]\\ pad &= \lbrace 0, 1, 2, 3, 4, 5\rbrace \\ outputShape &= [0+1+0, 0+1+0, 4+1+5, 2+1+3, 0+1+1]\\ &= [1,1,10,6,2] \end{aligned}

Function Prototype

Each operator uses a two-phase API. First, call the "aclnnConstantPadNdGetWorkspaceSize" API to obtain the workspace size required for computation and the executor containing the operator computation process. Then, call the "aclnnConstantPadNd" API to perform the computation.

  aclnnStatus aclnnConstantPadNdGetWorkspaceSize(
    const aclTensor*   self,
    const aclIntArray* pad,
    const aclScalar*   value,
    aclTensor*         out,
    uint64_t*          workspaceSize,
    aclOpExecutor**    executor)
    aclnnStatus aclnnConstantPadNd(
      void*          workspace,
      uint64_t       workspaceSize,
      aclOpExecutor* executor,
      aclrtStream    stream)

aclnnConstantPadNdGetWorkspaceSize

  • Parameters

    Parameter Input/Output Description Instruction Data Type Data Format Shape Non-contiguous Tensor
    self (aclTensor*) Input Original input data to be padded. - FLOAT, FLOAT16, INT32, INT64, INT16, INT8, UINT8, UINT16, UINT32, UINT64, BOOL, DOUBLE, COMPLEX64, COMPLEX128, BFLOAT16, HIFLOAT8, FLOAT8_E5M2, FLOAT8_E4M3FN, FLOAT8_E8M0, FLOAT4_E2M1, FLOAT4_E1M2. ND 0-8 √
    pad (aclIntArray*) Input Dimensions to be padded along each axis of the input. The array length must be an even number and cannot exceed twice the number of dimensions of self. INT64 - - -
    value (aclScalar*) Input Fill value of the padded part. - FLOAT, FLOAT16, INT32, INT64, INT16, INT8, UINT8, UINT16, UINT32, UINT64, BOOL, DOUBLE, COMPLEX64, COMPLEX128, BFLOAT16, HIFLOAT8, FLOAT8_E5M2, FLOAT8_E4M3FN, FLOAT8_E8M0, FLOAT6_E3M2, FLOAT6_E2M3, FLOAT4_E2M1, FLOAT4_E1M2. - - -
    out (aclTensor*) Output Output tensor Padded output result. Same as self. ND Dimensions are consistent with self. √
    workspaceSize (uint64_t*) Output Returns the size of the workspace to be allocated on the Device. - - - - -
    executor (aclOpExecutor**) Output Returns the op executor that contains the operator computation flow. - - - - -
    • Atlas training products and Atlas inference products: the following data types are not supported: BFLOAT16, HIFLOAT8, FLOAT8_E5M2, FLOAT8_E4M3FN, FLOAT8_E8M0, FLOAT4_E2M1, and FLOAT4_E1M2.
    • Atlas A3 products and Atlas A2 products: the following data types are not supported: HIFLOAT8, FLOAT8_E5M2, FLOAT8_E4M3FN, FLOAT8_E8M0, FLOAT4_E2M1, and FLOAT4_E1M2.
    • For CANN 9.0.0, when the data type of self is HIFLOAT8, FLOAT8_E5M2, FLOAT8_E4M3FN, or FLOAT8_E8M0, only the case where all bits of value are 0 is 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 self, pad, value, or out is a null pointer.
    ACLNN_ERR_INNER_NULLPTR 561103 Operator execution fails or variable initialization fails.
    ACLNN_ERR_PARAM_INVALID 161002 The data type of self, value, or out is not supported.
    The data type of self is inconsistent with that of out.
    The data types of self and value do not conform to the data type deduction rules.
    The shape derived from the shape of self and the input pad is inconsistent with the shape of out.
    The elements in pad are not even or exceed twice the number of dimensions of self.
    The number of dimensions of self or out is greater than 8.
    Each value in pad must not make the shape of out less than 0. If pad contains positive values, the shape of out must not contain 0.
    The data format of self is not ND, and the data format of out is inconsistent with that of self.
    If the data type of self is HIFLOAT8, FLOAT8_E5M2, FLOAT8_E4M3FN, FLOAT8_E8M0, FLOAT4_E2M1, or FLOAT4_E1M2, the elements in pad are negative numbers.
    For CANN 9.0.0, value is not 0 when the data type of self is HIFLOAT8, FLOAT8_E5M2, FLOAT8_E4M3FN, or FLOAT8_E8M0.

aclnnConstantPadNd

  • Parameters

    Parameter Input/Output Description
    workspace Input Workspace memory address requested on the Device.
    workspaceSize Input Workspace size requested on the Device, obtained by the first-phase API aclnnConstantPadNdGetWorkspaceSize.
    executor Input Op executor, which contains the operator computation flow.
    stream Input Stream for executing tasks.
  • Return value

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

Constraints

  • Deterministic computation:
    • aclnnConstantPadNd 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 <inttypes.h>
#include <vector>
#include "acl/acl.h"
#include "aclnnop/aclnn_constant_pad_nd.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 a 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 as required by the API.
  std::vector<int64_t> selfShape = {3, 3};
  std::vector<int64_t> outShape = {5, 5};
  void* selfDeviceAddr = nullptr;
  void* outDeviceAddr = nullptr;
  aclTensor* self = nullptr;
  aclIntArray* pad = nullptr;
  aclScalar* value = nullptr;
  aclTensor* out = nullptr;
  std::vector<float> selfHostData = {0, 1, 2, 3, 4, 5, 6, 7, 8};
  std::vector<float> outHostData(25, 0);
  float valueValue = 0.0f;
  std::vector<int64_t> padData = {1,1,1,1};
  // Create the self aclTensor.
  ret = CreateAclTensor(selfHostData, selfShape, &selfDeviceAddr, aclDataType::ACL_FLOAT, &self);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  // Create the pad array.
  pad = aclCreateIntArray(padData.data(), 4);
  CHECK_RET(pad != nullptr, return ret);
  // Create the value aclScalar.
  value = aclCreateScalar(&valueValue, aclDataType::ACL_FLOAT);
  CHECK_RET(value != nullptr, 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, and replace it with the actual API name.
  uint64_t workspaceSize = 0;
  aclOpExecutor* executor;
  // Call the first-phase API of aclnnConstantPadNd.
  ret = aclnnConstantPadNdGetWorkspaceSize(self, pad, value, out, &workspaceSize, &executor);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnConstantPadNdGetWorkspaceSize 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 aclnnConstantPadNd.
  ret = aclnnConstantPadNd(workspaceAddr, workspaceSize, executor, stream);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnConstantPadNd 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 and copy the result from device memory to the host side, which needs to be modified 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(float), 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[%" PRId64 "] is: %f\n", i, resultData[i]);
  }

  // 6. Release aclTensor and aclScalar, which needs to be modified based on the specific API definition.
  aclDestroyTensor(self);
  aclDestroyIntArray(pad);
  aclDestroyScalar(value);
  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;
}