aclnnGemm
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 : Supported
Function
- Description: 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.
If both transA and transB are non-zero, the formula is:
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. - The data type must form a deduction relationship with C and B.
- The shape (or the shape after transpose) must meet the multiplication condition with B.
BFLOAT16, FLOAT16, FLOAT32 ND 2 √ B Input Input B in the formula, an aclTensor on the Device. - The data type must have a deduction relationship with C and A.
- shape (or the shape after transpose) must satisfy the multiplication condition with A.
BFLOAT16, FLOAT16, FLOAT32 ND 2 √ C Input Input C in the formula, an aclTensor on the device. BFLOAT16, FLOAT16, FLOAT32 ND 1, 2 √ alpha Input Input α in the formula, a floating-point value on the host, indicating the coefficient of the product of A and B. - float - - - beta Input β in the formula, a floating-point value on the host, indicating the coefficient of C. - float - - - transA Input transA in the formula, host-side integer. It indicates whether matrix A needs to be transposed. A non-zero value indicates transpose, and matrix A is [K,M]. Zero indicates no transpose, and matrix A is [M, K]. - int64_t - - - transB Input transB in the formula, host-side integer. It indicates whether matrix B needs to be transposed. A non-zero value indicates transpose, and matrix B is [N, K]. Zero indicates no transpose, and matrix B is [K, N]. - int64_t - - - out Output out in the formula. Device-side aclTensor. The data type must have a deduction relationship with that of C, and the shape must be the same as the A@B computation result. - BFLOAT16, FLOAT16, FLOAT32 ND 2 - cubeMathType Input Integer on the Host. Determines the computation logic used by the Cube unit. If the input data types have a deduction relationship, this parameter processes the data types after deduction by default. Supported enumeration values are as follows: - 0: KEEP_DTYPE, which keeps the input data type for computation.
- 1: ALLOW_FP32_DOWN_PRECISION, which allows converting the input data type for computation at a lower precision.
- 2: USE_FP16, which allows converting the input data type to FLOAT16 for computation.
- 3: USE_HF32, which downgrades the input to data type HFLOAT32 for computation.
- 4: USE_FP32_ADD, which enables computation in high-precision mode.
INT8 - - - workspaceSize Output Returns the size of the workspace to be requested on the Device. - - - - - executor Output parameter Returns the op executor, which contains the operator computation flow. - - - - - Atlas A2 products ,Atlas A3 products :- A supports data types BFLOAT16, FLOAT16, and FLOAT32.
- B supports data types BFLOAT16, FLOAT16, and FLOAT32.
- C supports 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.
Ascend 950PR&950DT products :- 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.
- cubeMathType=4: when the input data type is FLOAT16/BFLOAT16, the gemm process performs the computation at a higher precision. In this case, broadcasting between input C and the matmul result matrix is currently not supported. When the input data type is FLOAT32 and any of the following conditions is met, the vector core is used for computation to improve result precision (this may degrade operator performance in some use cases). Condition 1: m equals 1 or n equals 1. Condition 2: A is transposed and B is not transposed.
Atlas training products ,Atlas inference products :- The data type of A supports FLOAT16 and FLOAT32.
- The data type of B supports FLOAT16 and FLOAT32.
- The data type of C supports FLOAT16 and FLOAT32.
- The data type of out 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 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 | A, B, C, or out is a null pointer. |
| ACLNN_ERR_PARAM_INVALID | 161002 | The data type and data format are out of the supported range. |
| A or B is not 2-dimensional, or the shapes do not satisfy the k dimension equality relationship between [m, k] and [k, n] during computation. | ||
| C and the computation result of A@B do not satisfy the broadcast relationship. | ||
| out and the AB computation result have inconsistent shapes. | ||
| cubeMathType is an invalid value. |
aclnnGemm
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 calling the first-phase API aclnnGemmGetWorkspaceSize. executor Input Op executor, containing the operator computation flow. stream Input Specifies the stream for executing tasks. Return value:
aclnnStatus: return status code. For details, see aclnn Return Codes.
Constraints
Deterministic computation description:
Ascend 950PR&950DT products : aclnnGemm defaults to a deterministic implementation.
Atlas A3 products ,Atlas A2 products : aclnnGemm defaults to a deterministic implementation.
Atlas training products ,Atlas inference products : aclnnGemm defaults to a deterministic implementation.
Ascend 950PR&950DT products :- When the data types of A and B are both FLOAT16 or both BFLOAT16, the computation precision of aclnnGemm is as follows:
- When the data type of out is FLOAT32, MatMul uses FLOAT32 for accumulation. The intermediate results of beta×C, alpha×(A@B), and the addition of the two parts are all in FLOAT32, and the final result is written to out in FLOAT32.
- When the data type of out is FLOAT16 or BFLOAT16 and cubeMathType=4, the preceding intermediate results are in FLOAT32, and the final result is converted to the data type specified for out.
- When the data type of out is FLOAT16 or BFLOAT16 and cubeMathType is not 4, the intermediate results are not converted to FLOAT32.
- When the shape of C is [n] or [1, n] and alpha=1 and beta=1, C is directly used as the bias input of MatMul, and the addition is performed inside MatMul.
- When the data types of A and B are both FLOAT16 or both BFLOAT16, the computation precision of aclnnGemm is as follows:
Atlas training products ,Atlas inference products : The Cube unit does not support FLOAT32 computation. If the input is FLOAT32, set cubeMathType=1 (ALLOW_FP32_DOWN_PRECISION) to allow the API to cast the data to FLOAT16 for internal computation.
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_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.
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);
// 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. For details, see the ACL API list.
// Fill in deviceId based on the actual device.
int32_t deviceId = 0;
aclrtStream stream;
auto ret = Init(deviceId, &stream);
// Handle the check as needed.
CHECK_RET(ret == 0, 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> 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 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.
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 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 aclnnGemm.
ret = aclnnGemm(workspaceAddr, workspaceSize, executor, stream);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnGemm failed. ERROR: %d\n", ret); return ret);
// 4. (Boilerplate) Synchronize and wait until the task is 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 according to 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 it according to the specific API definition.
aclDestroyTensor(A);
aclDestroyTensor(B);
aclDestroyTensor(C);
aclDestroyTensor(out);
// 7. Release device resources. Modify it according to the specific API definition.
aclrtFree(ADeviceAddr);
aclrtFree(BDeviceAddr);
aclrtFree(CDeviceAddr);
aclrtFree(outDeviceAddr);
if (workspaceSize > 0) {
aclrtFree(workspaceAddr);
}
aclrtDestroyStream(stream);
aclrtResetDevice(deviceId);
aclFinalize();
return 0;
}