aclnnFusedMatmulV2

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 matrix multiplication with general vector computation. Compared with aclnnFusedMatmul, this API adds the optional inputs alphaOptional and betaOptional, which scale the matrix multiplication result and x3, respectively. If a null pointer is passed for either parameter, the value defaults to 1.0. Choose the appropriate API as required.

  • Formula:

    y=OP((x1@x2+bias),x3)y = OP((x1 @ x2 + bias), x3)

    The OP type is defined by the fusedOpType input and supports the following:

    add operation:

    y=(x1@x2+bias)+x3y=(x1 @ x2 + bias) + x3

    mul operation:

    y=(x1@x2+bias)∗x3y=(x1 @ x2 + bias) ∗ x3

    gelu_tanh operation:

    y=gelu_tanh(x1@x2)y = gelu\_tanh(x1 @ x2)

    gelu_erf operation:

    y=gelu_erf(x1@x2)y = gelu\_erf(x1 @ x2)

    relu operation:

    y=relu(x1@x2+bias)y = relu(x1 @ x2 + bias)

    16cast32 operation:

    y=cast_float32(x1@x2+bias)y = cast\_float32(x1 @ x2 + bias)

    When aclnnFusedMatmulV2 is called with a non-default alphaOptional or betaOptional and fusedOpType is "add":

    y=alphaOptional∗(x1@x2)+betaOptional∗x3y = alphaOptional * (x1 @ x2) + betaOptional * x3

    This use case does not support bias. The operator completes the computation using the "scale_add" fusion mode internally.

Function Prototype

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

aclnnStatus aclnnFusedMatmulV2GetWorkspaceSize(
  const aclTensor *x1,
  const aclTensor *x2,
  const aclTensor *bias,
  const aclTensor *x3,
  const aclScalar *alphaOptional,
  const aclScalar *betaOptional,
  const char      *fusedOpType,
  int8_t           cubeMathType,
  const aclTensor *y,
  uint64_t        *workspaceSize,
  aclOpExecutor   **executor)
aclnnStatus aclnnFusedMatmulV2(
  void            *workspace,
  uint64_t         workspaceSize,
  aclOpExecutor   *executor,
  aclrtStream      stream)

aclnnFusedMatmulV2GetWorkspaceSize

  • Parameters:

    Parameter Input/Output Description Instruction Data Type Data Format Dimension Non-contiguous
    x1 Input Represents the first matrix in the matrix multiplication, corresponding to x1 in the formula.
  • The data type must follow the data type deduction rules with x2 (see deduction relationship).
  • FLOAT16, BFLOAT16, FLOAT32 ND 2-6 (when fusedOpType is "" or "relu"); 2-3 (when fusedOpType is "add" or "mul"); 2 (other values) √
    x2 Input Represents the second matrix in the matrix multiplication, corresponding to x2 in the formula.
  • The data type must satisfy the data type deduction rule with x1 (see deduction relationship).
  • Data type consistent with x1 ND 2-6 (when fusedOpType is "", "relu"); 2-3 (when fusedOpType is "add", "mul"); 2 (for other values) √
    bias Input Represents the bias term, corresponding to bias in the formula.
  • Takes effect only when fusedOpType is "", "16cast32", "relu", "add", or "mul". For other cases, pass in a null pointer.
  • FLOAT16, BFLOAT16, FLOAT32 ND 1-2 √
    x3 Input Denotes the second matrix of the fusion operation, corresponding to x3 in the formula. Valid only when fusedOpType is "add" or "mul". In other cases, pass in a null pointer. Data type must be consistent with x1. ND 2-3 √
    alphaOptional Input Optional scaling coefficient used to scale the matmul result.
  • 1.0 when a null pointer is passed in.
  • FLOAT16, BFLOAT16, FLOAT32 - - -
    betaOptional Input Optional scaling coefficient used to scale x3.
  • Defaults to 1.0 if a null pointer is passed.
  • FLOAT16, BFLOAT16, FLOAT32 - - -
    fusedOpType Input Specifies the fusion mode supported by the Matmul operator, corresponding to OP in the formula.
  • The fusion mode must be one of "" (indicating no fusion), "16cast32", "add", "mul", "gelu_erf", "gelu_tanh", and "relu".
  • "scale_add" is a fusion mode used internally by the operator and cannot be directly passed in by users. When fusedOpType is "add" and alphaOptional or betaOptional is not 1, the operator uses "scale_add" internally, so this value may appear in run logs.
  • STRING - - -
    cubeMathType Input Specifies the computation logic of the Cube unit. If the input data types have a deduction relationship, this parameter processes the data types after deduction by default. The supported enumeration values are as follows:
    • 0: KEEP_DTYPE, which keeps the input data type for computation.
    • 1: ALLOW_FP32_DOWN_PRECISION, which supports computing the input data at a lower precision.
    • 2: USE_FP16, which supports downgrading the input to FLOAT16 for computation.
    • 3: USE_HF32, which supports downgrading the input to data type HFLOAT32 for computation.
    • 4: USE_FP32_ADD, which supports computing in high-precision mode.
    INT8 - - -
    y Output Represents the output matrix of the computation, corresponding to y in the formula.
  • The data type must be consistent with the deduced data types of x1 and x2 (see deduction relationship); when fusedOpType is "16cast32", the data type of y is fixed to FLOAT32.
  • FLOAT16, BFLOAT16, FLOAT32 ND 2-6 (when fusedOpType is "" or "relu"); 2-3 (when fusedOpType is "add" or "mul"); 2 (for other values) √
    workspaceSize Output Returns the workspace size that the user needs to allocate on the Device. - - - - -
    executor Output Returns the op executor that contains the computation process of the operator. - - - - -
    • Ascend 950PR&950DT products:
      • cubeMathType=1: This option is not supported when the input data type is FLOAT32; no processing is performed when the input is of other data types;
      • 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.
      • cubeMathType=4: The high-precision method is used only when all of the following conditions are met:
        • fusedOpType is "add" or "mul";
        • x1 and x2 must have the same number of dimensions, both 2D or both 3D;
        • x1, x2, and x3 must have the same data type, all BFLOAT16 or all FLOAT16.
  • 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 x1, x2, or y is a null pointer.
    When fusedOpType is add or mul, x3 is a null pointer.
    When fusedOpType is gelu_tanh or gelu_erf, bias is not a null pointer.
    ACLNN_ERR_PARAM_INVALID 161002 The data types of x1 and x2 are not in the supported range.
    The data format of x1, x2, or y is not within the supported range.
    The dimensions of x1, x2, or y do not meet requirements: 2-6 dimensions are supported when fusedOpType is "" or "relu"; 2-3 dimensions are supported when fusedOpType is "add" or "mul"; two dimensions, or three dimensions with a batch axis of 1, are supported when fusedOpType is "16cast32"; and two dimensions are supported for other values.
    The K-axis lengths of x1 and x2 used for matrix multiplication are inconsistent.
    When fusedOpType is "add" or "mul", the shape of x3 does not meet requirements: if x3 is two-dimensional, Shape[-2] and Shape[-1] must be consistent with Shape[-2] and Shape[-1] of y; if x3 is three-dimensional, Shape[-2] and Shape[-1] must be consistent with Shape[-2] and Shape[-1] of y, and the batch axis must be consistent with that of y or be 1.
    The input fusedOpType is not one of "", "16cast32", "add", "mul", "gelu_tanh", "gelu_erf", or "relu".
    Data type deduction cannot be performed for x1 and x2.
    If the input fusedOpType is one of "", "add", "mul", or "relu" and the input data type is FLOAT32, cubeMathType supports only 3.
    The data type of alphaOptional or betaOptional is not within the supported range, or the use case with non-default scaling coefficients does not meet the constraints.

aclnnFusedMatmulV2

  • Parameters:

    Parameter Input/Output Description
    workspace Input Workspace memory address requested on the Device side.
    workspaceSize Input Size of the workspace requested on the Device side, obtained by calling the first-phase API aclnnFusedMatmulV2GetWorkspaceSize.
    executor Input Op executor containing the operator computation flow.
    stream Input Specifies the stream for task execution.
  • Return value

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

Constraints

  • Deterministic computation note:

    • Ascend 950PR&950DT products: aclnnFusedMatmulV2 defaults to a deterministic implementation.
  • When fusedOpType is "gelu_erf" or "gelu_tanh", the data types of x1 and x2 must be BFLOAT16 or FLOAT16, and only 2-dimensional x1, x2, and y are supported. When fusedOpType is "" or "relu", the data types of x1 and x2 must be FLOAT32 (cubeMathType supports only 3), BFLOAT16, or FLOAT16. When fusedOpType is "16cast32", the data types of x1 and x2 must be BFLOAT16 or FLOAT16, and x1, x2, and y can be 2-dimensional or 3-dimensional with the batch axis being 1. When fusedOpType is "add" or "mul", the data types of x1, x2, and x3 must be FLOAT32 (cubeMathType supports only 3), BFLOAT16, or FLOAT16.

  • When fusedOpType is "", "relu", "add", or "mul", in multi-dimensional use cases where broadcasting is not applicable, the batch dimensions must be the same.

  • When fusedOpType is "add" or "mul", in the BMM (3-dimensional) use case, x1, x2, and y support 3 dimensions. x3 supports 2-3 dimensions. A 2-dimensional x3 can be broadcast as a matrix for a 3-dimensional output. For a 3-dimensional x3, its batch axis must be the same as that of y or be 1.

  • When fusedOpType is "16cast32", the data type of the output y must be FLOAT32.

  • If x1 or x2 is an empty tensor, the values "", "relu", "gelu_erf", "gelu_tanh", "add", and "mul" of fusedOpType are supported, but the value "16cast32" is not supported.

  • In aclnnFusedMatmulV2, if alphaOptional or betaOptional is not 1, only the 3-dimensional "add" use case where B, M, N, and K are all greater than 0 is supported. This use case does not support bias, transposition, or batch axis broadcasting. The data types of x1, x2, x3, and y must all be FLOAT16 or BFLOAT16.

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_fused_matmul.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 device 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 data to 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 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 documentation.
  // Set deviceId according to 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.
  std::vector<int64_t> xShape = {16, 32};
  std::vector<int64_t> x2Shape = {32, 16};
  std::vector<int64_t> x3Shape = {16, 16};
  std::vector<int64_t> yShape = {16, 16};
  void* xDeviceAddr = nullptr;
  void* x2DeviceAddr = nullptr;
  void* x3DeviceAddr = nullptr;
  void* yDeviceAddr = nullptr;
  aclTensor* x = nullptr;
  aclTensor* x2 = nullptr;
  aclTensor* x3 = nullptr;
  aclTensor* y = nullptr;
  std::vector<float> xHostData(512, 1);
  std::vector<float> x2HostData(512, 1);
  std::vector<float> x3HostData(256, 1);
  std::vector<float> yHostData(256, 0);
  // Create the x aclTensor.
  ret = CreateAclTensor(xHostData, xShape, &xDeviceAddr, aclDataType::ACL_FLOAT16, &x);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  // Create the x2 aclTensor.
  ret = CreateAclTensor(x2HostData, x2Shape, &x2DeviceAddr, aclDataType::ACL_FLOAT16, &x2);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  // Create the x3 aclTensor.
  ret = CreateAclTensor(x3HostData, x3Shape, &x3DeviceAddr, aclDataType::ACL_FLOAT16, &x3);
  CHECK_RET(ret == ACL_SUCCESS, return ret);

  // Create the y aclTensor.
  ret = CreateAclTensor(yHostData, yShape, &yDeviceAddr, aclDataType::ACL_FLOAT16, &y);
  CHECK_RET(ret == ACL_SUCCESS, return ret);

  // 3. Call a CANN operator library API. Replace it with the specific API name.
  int8_t cubeMathType = 0;
  const char* fusedOpType = "add";
  uint64_t workspaceSize = 0;
  aclOpExecutor* executor = nullptr;
  // Call the first-phase API of aclnnFusedMatmulV2. If alphaOptional and betaOptional are null pointers, their values are 1.0.
  ret = aclnnFusedMatmulV2GetWorkspaceSize(x, x2, nullptr, x3, nullptr, nullptr, fusedOpType, cubeMathType, y,
                                            &workspaceSize, &executor);
  CHECK_RET(ret == ACL_SUCCESS,
            LOG_PRINT("aclnnFusedMatmulV2GetWorkspaceSize 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 aclnnFusedMatmulV2.
  ret = aclnnFusedMatmulV2(workspaceAddr, workspaceSize, executor, stream);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnFusedMatmulV2 failed. ERROR: %d\n", ret); return ret);

  // 4. (boilerplate) Synchronously 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 the device to the host. Modify the code as required by the specific API definition.
  auto size = GetShapeSize(yShape);
  std::vector<float> resultData(size, 0);
  ret = aclrtMemcpy(resultData.data(), resultData.size() * sizeof(resultData[0]), yDeviceAddr,
                    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. Destroy aclTensor and aclScalar. Modify the code as required by the specific API definition.
  aclDestroyTensor(x);
  aclDestroyTensor(x2);
  aclDestroyTensor(x3);
  aclDestroyTensor(y);

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