aclnnGemm

Applicable Products

ProductSupported
Atlas A3 training products/Atlas A3 inference products√
Atlas A2 training products/Atlas A2 inference products√
Atlas 200I/500 A2 inference products×
Atlas inference products√
Atlas training products√

Function

  • Operator function: Computes α multiplied by the product of A and B, then summed with the product of β and input C.

  • Formula:

    • If transA is non-zero, A is transposed before computation; similarly, if transB is non-zero, B is transposed.

      out=α(A@B)+βCout = α (A @ B) + β C
    • If both transA and transB are non-zero, the formula is:

      out=α(AT@BT)+βCout = α (A^T @ B^T) + βC

Function Prototype

Each operator uses a two-phase API. You must first call the "aclnnGemmGetWorkspaceSize" API to obtain the input parameters and calculate the required workspace size based on the computation process, and then call the "aclnnGemm" API to perform the computation.

aclnnStatus aclnnGemmGetWorkspaceSize(
  const aclTensor *A,
  const aclTensor *B,
  const aclTensor *C,
  float           alpha,
  float           beta,
  int64_t         transA,
  int64_t         transB,
  aclTensor       *out,
  int8_t          cubeMathType,
  uint64_t        *workspaceSize,
  aclOpExecutor   **executor)
aclnnStatus aclnnGemm(
  void          *workspace,
  uint64_t      workspaceSize,
  aclOpExecutor *executor,
  aclrtStream   stream)

aclnnGemmGetWorkspaceSize

  • Parameters:

    Parameter Input/Output Description Instruction Data Type Data Format Dimension (Shape) Non-contiguous Tensor
    A Input Input A in the formula, an aclTensor on the Device side.
    • The data type needs to have a mutual deduction relationship with C and B.
    • The shape (or the shape after transposition) must satisfy the multiplication condition with B.
    BFLOAT16, FLOAT16, FLOAT32 ND 2 √
    B Input Input B in the formula, an aclTensor on the Device side.
    • The data type needs to form a mutual derivation relationship with C and A.
    • The shape (or the shape after transpose) needs to satisfy the multiplication condition with A.
    BFLOAT16, FLOAT16, FLOAT32 ND 2 √
    C Input Input C in the formula, an aclTensor on the Device side.
    • The data type needs to have a deduction relationship with the result of A@B after computation.
    • The shape needs to be consistent with the result of A@B after computation or satisfy the broadcast relationship.
    BFLOAT16, FLOAT16, FLOAT32 ND 2 √
    alpha Input Input α in the formula. A floating-point type on the host side, representing the scaling factor for the product of A and B. - float - - -
    beta Input Input β in the formula. Floating-point type on the host side, representing the coefficient of C. - float - - -
    transA Input transA in the formula, an integer type on the host side, indicating whether matrix A needs to be transposed. Non-zero indicates transpose, and matrix A is [K, M]. Zero indicates no transpose, and matrix A is [M, K]. - int64_t - - -
    transB Input Input transB in the formula, an integer type on the host side, indicating whether matrix B needs to be transposed. A non-zero value indicates transpose, with B matrix being [N, K]; zero indicates no transpose, with B matrix being [K, N]. - int64_t - - -
    out Output The out in the formula, which is an aclTensor on the Device side. Its data type must form a deduction relationship with C, and its shape must be consistent with the result after A@B computation. - BFLOAT16, FLOAT16, FLOAT32 ND 2 -
    cubeMathType Input Host-side integer type, which determines the computation logic to be used by the Cube unit. If the input data types have a deduction relationship, this parameter processes the data type after deduction by default. The supported enumeration values are as follows:
    • 0: KEEP_DTYPE. Keeps the input data type for computation.
    • 1: ALLOW_FP32_DOWN_PRECISION. Allows converting the input data type to a lower precision for computation.
    • 2: USE_FP16. Allows converting the input data type to FLOAT16 for computation.
    • 3: USE_HF32. Supports reducing the input precision to the HFLOAT32 data type for computation.
    INT8 - - -
    workspaceSize Output Returns the workspace size to be allocated on the Device side. - - - - -
    executor Output Returns the operator executor, which contains the operator computation process. - - - - -
    • Atlas A2 training products/Atlas A2 inference products, Atlas A3 training products/Atlas A3 inference products:

      • A supports the following data types: BFLOAT16, FLOAT16, and FLOAT32.

      • B supports the following data types: BFLOAT16, FLOAT16, and FLOAT32.

      • C supports the following data types: BFLOAT16, FLOAT16, and FLOAT32.

      • out supports the following data types: BFLOAT16, FLOAT16, and FLOAT32.

      • cubeMathType=1: When the input data type is FLOAT32, it is converted to HFLOAT32 for computation. When the input is of other data types, no processing is performed.

      • cubeMathType=2: This option is not supported when the input data type is BFLOAT16.

      • cubeMathType=3: When the input data type is FLOAT32, it will be converted to HFLOAT32 for computation. This option is not supported when the input is of other data types.

    • Atlas training products, Atlas inference products:

      • A supports the following data types: FLOAT16 and FLOAT32.

      • B supports the following data types: FLOAT16 and FLOAT32.

      • C supports the following data types: FLOAT16 and FLOAT32.

      • The out data type supports FLOAT16 and FLOAT32.

      • BFLOAT16 data type is not supported.

      • When the input data type is FLOAT32, cubeMathType=0 is not supported.

      • For cubeMathType=1, when the input data type is FLOAT32, it is converted to FLOAT16 for computation. When the input is of other data types, no processing is performed.

      • cubeMathType=3 is not supported.

  • Return value:

    aclnnStatus: return code. For details, see aclnn Return Code.

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 The input A, B, C, or out is a null pointer.
ACLNN_ERR_PARAM_INVALID 161002 The data type or data format is not within the supported range.
A or B is not 2-dimensional, or during computation, the shape does not satisfy the equality relationship of the k dimension between [m, k] and [k, n].
self cannot be broadcast with batch1@batch2.
C and the result after AB computation do not satisfy the broadcast relationship.
The shapes of out and the result after AB computation are inconsistent.
cubeMathType is an invalid value.

aclnnGemm

  • Parameters:

    Parameter Input/Output Description
    workspace Input Address of the workspace memory allocated on the Device side.
    workspaceSize Input Size of the workspace allocated on the Device side, obtained from the first-phase API aclnnGemmGetWorkspaceSize.
    executor Input Operator executor, which contains the operator computation flow.
    stream Input Specifies the stream for task execution.
  • Return value:

    aclnnStatus: return code. For details, see aclnn Return Code.

Constraints

  • Deterministic description:

    • Atlas training products, Atlas inference products: aclnnGemm defaults to a deterministic implementation.
  • Atlas training products, Atlas inference products: The Cube unit does not support FLOAT32 computation. When the input is FLOAT32, set cubeMathType=1 (ALLOW_FP32_DOWN_PRECISION) to allow the API to internally cast to FLOAT16 for computation.

Example

The following provides example code for reference only. For details about compilation and running, see Compile and Run Samples.

#include <iostream>
#include <vector>
#include "acl/acl.h"
#include "aclnnop/level2/aclnn_gemm.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 shape_size = 1;
  for (auto i : shape) {
    shape_size *= i;
  }
  return shape_size;
}

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);

  // Copy data from the host side 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);

  // Compute 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. See the acl external API list.
  // Set deviceId based on your actual device.
  int32_t deviceId = 0;
  aclrtStream stream;
  auto ret = Init(deviceId, &stream);
  // Handle the check based on your own needs.
  CHECK_RET(ret == 0, LOG_PRINT("Init acl failed. ERROR: %d\n", ret); return ret);
  // 2. Construct the input and output. Custom construction is required based on the API interface.
  std::vector<int64_t> AShape = {2, 2};
  std::vector<int64_t> BShape = {2, 2};
  std::vector<int64_t> CShape = {2, 2};
  std::vector<int64_t> outShape = {2, 2};
  void* ADeviceAddr = nullptr;
  void* BDeviceAddr = nullptr;
  void* CDeviceAddr = nullptr;
  void* outDeviceAddr = nullptr;
  aclTensor* A = nullptr;
  aclTensor* B = nullptr;
  aclTensor* C = nullptr;
  aclTensor* out = nullptr;
  std::vector<float> AHostData = {1, 2, 1, 2};
  std::vector<float> BHostData = {1, 2, 1, 2};
  std::vector<float> CHostData = {1, 1, 1, 1};
  std::vector<float> outHostData = {0, 0, 0, 0};
  float alpha = 1.0f;
  float beta = 2.0f;
  int64_t transA = 0;
  int64_t transB = 0;
  int8_t cubeMathType = 1;

  // Create A aclTensor.
  ret = CreateAclTensor(AHostData, AShape, &ADeviceAddr, aclDataType::ACL_FLOAT, &A);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  // Create B aclTensor.
  ret = CreateAclTensor(BHostData, BShape, &BDeviceAddr, aclDataType::ACL_FLOAT, &B);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  // Create C aclTensor.
  ret = CreateAclTensor(CHostData, CShape, &CDeviceAddr, aclDataType::ACL_FLOAT, &C);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  // Create the output aclTensor.
  ret = CreateAclTensor(outHostData, outShape, &outDeviceAddr, aclDataType::ACL_FLOAT, &out);
  CHECK_RET(ret == ACL_SUCCESS, return ret);

  // 3. Call the CANN operator library API.
  uint64_t workspaceSize = 0;
  aclOpExecutor* executor;
  // Call the first-phase API of aclnnGemm.
  ret = aclnnGemmGetWorkspaceSize(A, B, C, alpha, beta, transA, transB, out, cubeMathType, &workspaceSize, &executor);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnGemmGetWorkspaceSize 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 aclnnGemm.
  ret = aclnnGemm(workspaceAddr, workspaceSize, executor, stream);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnGemm failed. ERROR: %d\n", ret); return ret);
  // 4. (Boilerplate) Synchronously wait for 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 the device memory to the host memory. Modify 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[%ld] is: %f\n", i, resultData[i]);
  }

  // 6. Release aclTensor and aclScalar. Modify based on the specific API definition.
  aclDestroyTensor(A);
  aclDestroyTensor(B);
  aclDestroyTensor(C);
  aclDestroyTensor(out);

  // 7. Release device resources. Modify based on the specific API definition.
  aclrtFree(ADeviceAddr);
  aclrtFree(BDeviceAddr);
  aclrtFree(CDeviceAddr);
  aclrtFree(outDeviceAddr);
  if (workspaceSize > 0) {
    aclrtFree(workspaceAddr);
  }
  aclrtDestroyStream(stream);
  aclrtResetDevice(deviceId);
  aclFinalize();
  return 0;
}