aclnnConfusionTranspose

Applicable Products

  • Ascend 950PR&950DT products: Supported
  • Atlas A3 products: Not supported
  • Atlas A2 products: Not supported
  • Atlas 200I/500 A2 inference products: Not supported
  • Atlas inference products: Not supported
  • Atlas training products: Not supported

Function

  • Description:

    Fuses reshape and transpose operations.

  • Formula:

    1. When transposeFirst is False:y=transpose(reshape(x,shape),perm)y=transpose(reshape(x,shape),perm)
    2. When transposeFirst is True:y=reshape(transpose(x,perm),shape)y=reshape(transpose(x,perm),shape)

Function Prototype

Each operator consists of two-phase APIs. Call the "aclnnConfusionTransposeGetWorkspaceSize" API first to obtain the input parameters and calculate the required workspace size based on the computation flow, and then call the "aclnnConfusionTranspose" API to perform the computation.

aclnnStatus aclnnConfusionTransposeGetWorkspaceSize(
    const aclTensor    *x,
    const aclIntArray  *perm,
    const aclIntArray  *shape,
    bool                transpose_first,
    aclTensor          *out,
    uint64_t           *workspaceSize,
    aclOpExecutor      **executor)
aclnnStatus aclnnConfusionTranspose(
    void               *workspace,
    uint64_t            workspaceSize,
    aclOpExecutor      *executor,
    aclrtStream         stream)

aclnnConfusionTransposeGetWorkspaceSize

  • Parameters:

    Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor
    x (aclTensor*) Input/Output Input tensor, corresponding to x in the corresponding formula. Empty tensors are supported. INT8, INT16, INT32, INT64, UINT8, UINT16, UINT32, UINT64, FLOAT16, FLOAT, BFLOAT16 ND 1-8 -
    perm (aclIntArray*) Input Index of the axis before transposition corresponding to each axis after transposition, corresponding to perm in the corresponding formula. 1. Elements in this input must be unique and in the range [0, number of dims of perm - 1].
    2. When transpose_first is True, the length of perm must be the same as the length of the shape of x, that is, len(perm)=len(x_shape).
    3. When transpose_first is False, the length of perm must be the same as the length of the shape attribute input, that is, len(perm)=len(shape).
    INT64 - - -
    shape (aclIntArray*) Input Shape size after reshape, that is, shape in the corresponding formula. The product of all dimensions in shape must be equal to the total number of elements in input tensor x. INT64 - - -
    transpose_first (bool) Input Specifies whether to perform the transpose operation first. If the value is True, transpose is performed first; otherwise, reshape is performed first. BOOL - - -
    out(aclTensor*) Output Calculation result after reshape and transpose. - Same as input x Same as input x - -
    workspaceSize(uint64_t*) Output Returns the size of the workspace to be allocated on the Device side. - - - - -
    executor(aclOpExecutor**) Output Returns the op executor containing the operator computation flow. - - - - -
  • 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 x or out is a null pointer.
    ACLNN_ERR_PARAM_INVALID 161002 The data type of x or out is out of the supported range.
    ACLNN_ERR_INNER_NULLPTR 561103 Internal API verification error. Usually caused by the specs of input data or attributes being out of the supported range, or the shapes of inputs and outputs not meeting the requirements in Parameters.

aclnnConfusionTranspose

  • 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 by the first-phase API aclnnConfusionTransposeGetWorkspaceSize.
    executor Input opExecutor that contains the operator computation flow.
    stream Input Stream where tasks are executed.
  • Return value:

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

Constraints

  • Deterministic computation: aclnnConfusionTranspose defaults to a deterministic implementation.

    For example:

    Let shape_before be the data shape before the reshape operation, and shape_after be the data shape after the reshape operation,

    shape_before = [(ab),(cd),f,(gh)] shape_after = [a,(bc),d,e,(fg),h]

    The following shape_after is not allowed:

    shape_after_illegal = [a,b,d,e,(fg),(ch)]

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_confusion_transpose.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;
}

void PrintOutResult(std::vector<int64_t> &shape, void** deviceAddr) {
  auto size = GetShapeSize(shape);
  std::vector<float> resultData(size, 0);
  auto ret = aclrtMemcpy(resultData.data(), resultData.size() * sizeof(resultData[0]),
                         *deviceAddr, 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);
  for (int64_t i = 0; i < size; i++) {
    LOG_PRINT("result[%ld] is: %f\n", i, resultData[i]);
  }
}

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 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.
  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) Device/stream initialization. For details, see the acl API documentation.
  // 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 inputs and outputs as required by the API.

  // Create the input aclTensor.
  aclTensor* x = nullptr;
  std::vector<int64_t> xShape = {2, 4};
  std::vector<float> xHostData = {1, 2, 3, 4, 5, 6, 7, 8};
  void* xDeviceAddr = nullptr;
  ret = CreateAclTensor(xHostData, xShape, &xDeviceAddr, aclDataType::ACL_FLOAT, &x);
  CHECK_RET(ret == ACL_SUCCESS, return ret);

  // Create perm.
  aclIntArray* perm = nullptr;
  std::vector<int64_t> permData = {1, 0};
  perm = aclCreateIntArray(permData.data(), permData.size());
  CHECK_RET(perm != nullptr, return ret);

  // Create a shape.
  aclIntArray* shape = nullptr;
  std::vector<int64_t> shapeData = {2, 4};
  shape = aclCreateIntArray(shapeData.data(), shapeData.size());
  CHECK_RET(shape != nullptr, return ret);

  // Create transposeFirst.
  bool transposeFirst = true;

  // Create the output aclTensor.
  std::vector<int64_t> outShape = {2, 4};
  std::vector<float> outHostData(8, 1);
  aclTensor* out = nullptr;
  void* outDeviceAddr = nullptr;
  // 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 actual API name.
  uint64_t workspaceSize = 16 * 1024 * 1024;
  aclOpExecutor* executor;

  // Call the first-phase API of aclnnConfusionTranspose.
  ret = aclnnConfusionTransposeGetWorkspaceSize(x, perm, shape, transposeFirst, out, &workspaceSize, &executor);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnConfusionTransposeGetWorkspaceSize 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 aclnnConfusionTranspose.
  ret = aclnnConfusionTranspose(workspaceAddr, workspaceSize, executor, stream);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnConfusionTranspose failed. ERROR: %d\n", ret); return ret);

  // 4. (Boilerplate) Wait synchronously 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 and copy the result from device memory to the host side. Modify it based on the API definition.
  PrintOutResult(outShape, &outDeviceAddr);

  // 6. Release aclTensor. Modify the code as required by the specific API definition.
  aclDestroyTensor(x);
  aclDestroyTensor(out);

  // 7. Release device resources. Modify the code as required by the specific API definition.
  aclrtFree(xDeviceAddr);
  aclrtFree(outDeviceAddr);
  if (workspaceSize > 0) {
    aclrtFree(workspaceAddr);
  }
  aclrtDestroyStream(stream);
  aclrtResetDevice(deviceId);
  aclFinalize();

  return 0;
}