aclnnTransposeQuantBatchMatMul
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: Performs the quantized matrix multiplication between tensor x1 and tensor x2 and supports the K-C, MX, and T-C quantization modes. Only 3D tensors are supported as input. Tensors support transposition, and the transpose sequence changes according to the input sequence. permX1 denotes the transpose sequence of tensor x1, and permX2 denotes the transpose sequence of tensor x2. A sequence value of 0 indicates the batch dimension, and matrix multiplication is performed on the other two dimensions.
Example: Assume that the shape of x1 is (M, B, K), the shape of x2 is (B, K, N), x1Scale and x2Scale are not None, and batchSplitFactor equals 1. The shape of the computed output out is (M, B, N).
Function Prototype
Each operator uses a two-phase API. You must first call the "aclnnTransposeQuantBatchMatMulGetWorkspaceSize" API to obtain input parameters and calculate the required workspace size based on the execution process, and then call the "aclnnTransposeQuantBatchMatMul" API to perform the computation.
aclnnStatus aclnnTransposeQuantBatchMatMulGetWorkspaceSize(
const aclTensor *x1,
const aclTensor *x2,
const aclTensor *bias,
const aclTensor *x1Scale,
const aclTensor *x2Scale,
int32_t dtype,
int64_t groupSize,
const aclIntArray *permX1,
const aclIntArray *permX2,
const aclIntArray *permY,
int32_t batchSplitFactor,
aclTensor *out,
uint64_t *workspaceSize,
aclOpExecutor **executor)aclnnStatus aclnnTransposeQuantBatchMatMul(
void *workspace,
uint64_t workspaceSize,
aclOpExecutor *executor,
const aclrtStream stream)aclnnTransposeQuantBatchMatMulGetWorkspaceSize
Parameters:
Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor x1 (aclTensor*) Input The first matrix in the matrix multiplication. - The data type must comply with the data type deduction rules with x2 (see Deduction Relationship and Constraints).
- Currently, only FLOAT8_E5M2, FLOAT8_E4M3FN, FLOAT4_E2M1, and HIFLOAT8 are supported.
FLOAT8_E5M2, FLOAT8_E4M3FN, FLOAT4_E2M1, HIFLOAT8 ND 3 √ x2 (aclTensor*) Input The second matrix in the matrix multiplication. - The data type must satisfy the data type deduction rule with x1 (see deduction relationship and Constraints).
- The k dimension of x2 must have the same size as the k dimension of x1.
- Currently, only the FLOAT8_E5M2, FLOAT8_E4M3FN, FLOAT4_E2M1, and HIFLOAT8 data types are supported.
FLOAT8_E5M2, FLOAT8_E4M3FN, FLOAT4_E2M1, HIFLOAT8 ND 3 √ bias (aclTensor*) Input Bias matrix of the matrix multiplication. Reserved parameter. Currently not supported. - - - - x1Scale (aclTensor*) Input Quantization scale of the left matrix. - K-C quantization scenario: the shape must be one-dimensional and equal to [m].
- MX quantization scenario: supports a four-dimensional shape.
- T-C quantization scenario: the shape can be empty. If not empty, it must be one-dimensional and equal to [1].
FLOAT32, FLOAT8_E8M0, UINT64, INT64 ND - √ x2Scale (aclTensor*) Input Indicates the quantization coefficients of the right matrix. - In K-C and T-C quantization scenarios, the shape is one-dimensional and must be [n].
- In MX quantization scenarios, the shape is four-dimensional.
FLOAT32, FLOAT8_E8M0, UINT64, INT64 ND - √ dtype (int32_t) Input Specifies the data type of the output matrix. Supported values: 1, 27, and 34. - If the value is 1, the output matrix type is FLOAT16.
- If the value is 27, the output matrix type is BFLOAT16.
- If the value is 34, the output matrix type is HIFLOAT8 (supported only for T-C quantization).
INT32 - - - groupSize (int64_t) Input Specifies the quantization group sizes along the m, n, and k dimensions. Concatenated from the three values groupSizeM, groupSizeN, and groupSizeK, each occupying 16 bits. The three values occupy the low 48 bits of the int64_t groupSize (the high 16 bits are invalid). INT64 - - - permX1 (aclIntArray*) Input Transpose sequence of the first matrix in the matrix multiplication, an aclIntArray on the host. Only [1, 0, 2] is supported. INT64 - 1 - permX2 (aclIntArray*) Input Matrix Representation of the transpose sequence of the second matrix in the matrix multiplication, aclIntArray on the host. - For the K-C quantization scenario, [0, 1, 2] is supported.
- For the MX and T-C quantization scenarios, [0, 1, 2] or [0, 2, 1] is supported.
INT64 - 1 - permY(aclIntArray*) Input Represents the transpose sequence of the matmul output matrix, which is an aclIntArray on the host. Only [1, 0, 2] is supported. INT64 - 1 - batchSplitFactor(int32_t) Input Specifies the split size of dimension B in the output matrix of the matrix multiplication. Integer on the Host side. Currently, only the value 1 is supported. Currently, only the value 1 is supported. INT32 - - - out(aclTensor*) Output Denotes the output matrix of the matrix multiplication, namely out in the formula. Empty tensors are not supported. BFLOAT16, FLOAT16, HIFLOAT8 ND 3 √ workspaceSize Output Returns the size of the workspace to be allocated on the Device. - - - - - executor Output Returns the op executor, which contains 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 x1, x2, out, x2Scale, permX1, permX2, or permY is a null pointer; x1Scale is a null pointer except in the T-C quantization scenario. ACLNN_ERR_PARAM_INVALID 161002 The data type of x1, x2, x1Scale, x2Scale, or out is not in the supported range. The shape of x1, x2, x1Scale, x2Scale, or out does not meet the validation conditions. The dimension size of x1, x2, permX1, permX2, and permY is not 3. batchSplitFactor is not in the supported range. The value of permX1, permX2, or permY is not in the supported range.
aclnnTransposeQuantBatchMatMul
Parameters:
Parameter Input/Output Description workspace Input Workspace memory address allocated on the Device. workspaceSize Input Workspace size allocated on the Device. It is obtained by calling the first-phase API aclnnTransposeQuantBatchMatMulGetWorkspaceSize. executor Input Executor of the op. It contains 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 description: aclnnTransposeQuantBatchMatMul defaults to a deterministic implementation.
Ascend 950PR&950DT products :- K-C Quantization Mode: K only supports 512, and N only supports 128. x1Scale and x2Scale only support 1 dimension, where x1Scale requires a shape of (M,) and x2Scale requires a shape of (N,). groupSize only supports the value 0; other values do not take effect. x1/x2 inputs support FLOAT8_E5M2 and FLOAT8_E4M3FN data types, and x1Scale/x2Scale only support the FLOAT32 data type.
- MX Quantization Mode: MXFP8 and MXFP4 data types are supported. K only supports multiples of 64. x1Scale and x2Scale only support 4 dimensions, where x1Scale requires a shape of (M, B, K/64, 2). When permX2 is [0, 1, 2], x2Scale requires a shape of (B, K/64, N, 2); when permX2 is [0, 2, 1], x2Scale requires a shape of (B, N, K/64, 2). groupSizeM and groupSizeN in groupSize only support 0 or 1, and groupSizeK only supports 32. x1/x2 inputs support FLOAT8_E4M3FN and FLOAT4_E2M1 data types, and x1Scale/x2Scale only support the FLOAT8_E8M0 data type.
- T-C Quantization Mode: Only static quantization is supported. x1Scale can be set to null or (1,), and x2Scale requires a shape of (N,). The groupSize configuration does not take effect. If x1Scale is not null, only the UINT64/INT64 data types are supported; x2Scale must be preprocessed by trans_quant_param to convert to the UINT64/INT64 data type; x1/x2 only support the HIFLOAT8 data type.
- Constraints on groupSize:
- Takes effect only in the MX quantization use case.
- The passed-in groupSize is internally decomposed into groupSizeM, groupSizeN, and groupSizeK according to the following formula. If one or more of them is 0, groupSizeM, groupSizeN, and groupSizeK are reset based on the input shapes of x1/x2/x1Scale/x2Scale for computation. Principle: If groupSizeM=0, the quantization group value along the M dimension is inferred by the API. The inference formula is groupSizeM = M / scaleM (M must be divisible by scaleM), where M is the same as M in the x1 shape, and scaleM is the same as M in the x1Scale shape.
Example
The following sample code is for reference only. For details about compiling and running, see Compile and Run Samples.
#include <iostream>
#include <memory>
#include <vector>
#include <limits>
#include <cmath>
#include "acl/acl.h"
#include "aclnnop/aclnn_transpose_quant_batch_mat_mul.h"
#define CHECK_RET(cond, return_expr) \
do { \
if (!(cond)) { \
return_expr; \
} \
} while (0)
#define CHECK_FREE_RET(cond, return_expr) \
do { \
if (!(cond)) { \
Finalize(deviceId, stream); \
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;
}
// Function for converting BF16 to float
float bf16_to_float(uint16_t bf16)
{
uint16_t sign = (bf16 >> 15) & 0x1;
uint16_t exp = (bf16 >> 7) & 0xFF; // 8-bit exponent
uint16_t mant = bf16 & 0x7F;
// Handle special values
if (exp == 0) {
if (mant == 0) {
return sign ? -0.0f : 0.0f;
} else {
// Denormal BF16 -> float
return (sign ? -1.0f : 1.0f) * (float)mant * (1.0f / (1 << 7) / std::ldexp(1.0, 126));
}
} else if (exp == 255) {
// Infinity or NaN
if (mant == 0) {
return sign ? -std::numeric_limits<float>::infinity() : std::numeric_limits<float>::infinity();
} else {
return std::numeric_limits<float>::quiet_NaN();
}
} else {
// Normalized number
float f_exp = (float)(exp - 127); // Offset by 127
float f_mant = (float)mant / (1 << 7); // 7 fractional bits
float f = (sign ? -1.0f : 1.0f) * (1.0f + f_mant) * (1 << (int)f_exp);
return f;
}
}
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 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;
}
void Finalize(int32_t deviceId, aclrtStream stream)
{
aclrtDestroyStream(stream);
aclrtResetDevice(deviceId);
aclFinalize();
}
int AclnnTransposeQuantBatchMatmulTest(int32_t deviceId, aclrtStream& stream)
{
auto ret = Init(deviceId, &stream);
// Handle the check according to your needs.
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("Init acl failed. ERROR: %d\n", ret); return ret);
// 2. Construct inputs and outputs. Customize the construction according to the API.
int32_t M = 32;
int32_t K = 512;
int32_t N = 128;
int32_t Batch = 16;
std::vector<int64_t> x1Shape = {M, Batch, K};
std::vector<int64_t> x2Shape = {Batch, K, N};
std::vector<int64_t> x1ScaleShape = {M};
std::vector<int64_t> x2ScaleShape = {N};
std::vector<int64_t> outShape = {M, Batch, N};
std::vector<int64_t> permX1Series = {1, 0, 2};
std::vector<int64_t> permX2Series = {0, 1, 2};
std::vector<int64_t> permYSeries = {1, 0, 2};
void* x1DeviceAddr = nullptr;
void* x2DeviceAddr = nullptr;
void* x1ScaleDeviceAddr = nullptr;
void* x2ScaleDeviceAddr = nullptr;
void* outDeviceAddr = nullptr;
aclTensor* x1 = nullptr;
aclTensor* x2 = nullptr;
aclTensor* x1Scale = nullptr;
aclTensor* x2Scale = nullptr;
aclTensor* out = nullptr;
std::vector<int8_t> x1HostData(GetShapeSize(x1Shape), 0x38);
std::vector<int8_t> x2HostData(GetShapeSize(x2Shape), 0x38);
std::vector<float> x1ScaleHostData(GetShapeSize(x1ScaleShape), 1);
std::vector<float> x2ScaleHostData(GetShapeSize(x2ScaleShape), 1);
std::vector<uint16_t> outHostData(GetShapeSize(outShape), 0); // bf16
// Create x1 aclTensor.
ret = CreateAclTensor(x1HostData, x1Shape, &x1DeviceAddr, aclDataType::ACL_FLOAT8_E4M3FN, &x1);
std::unique_ptr<aclTensor, aclnnStatus (*)(const aclTensor*)> x1TensorPtr(x1, aclDestroyTensor);
std::unique_ptr<void, aclError (*)(void*)> x1deviceAddrPtr(x1DeviceAddr, aclrtFree);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// Create x2 aclTensor.
ret = CreateAclTensor(x2HostData, x2Shape, &x2DeviceAddr, aclDataType::ACL_FLOAT8_E4M3FN, &x2);
std::unique_ptr<aclTensor, aclnnStatus (*)(const aclTensor*)> x2TensorPtr(x2, aclDestroyTensor);
std::unique_ptr<void, aclError (*)(void*)> x2deviceAddrPtr(x2DeviceAddr, aclrtFree);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// Create x1Scale aclTensor.
ret = CreateAclTensor(x1ScaleHostData, x1ScaleShape, &x1ScaleDeviceAddr, aclDataType::ACL_FLOAT, &x1Scale);
std::unique_ptr<aclTensor, aclnnStatus (*)(const aclTensor*)> x1ScaleTensorPtr(x1Scale, aclDestroyTensor);
std::unique_ptr<void, aclError (*)(void*)> x1ScaledeviceAddrPtr(x1ScaleDeviceAddr, aclrtFree);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// Create x2Scale aclTensor.
ret = CreateAclTensor(x2ScaleHostData, x2ScaleShape, &x2ScaleDeviceAddr, aclDataType::ACL_FLOAT, &x2Scale);
std::unique_ptr<aclTensor, aclnnStatus (*)(const aclTensor*)> x2ScaleTensorPtr(x2Scale, aclDestroyTensor);
std::unique_ptr<void, aclError (*)(void*)> x2ScaledeviceAddrPtr(x2ScaleDeviceAddr, aclrtFree);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// Create out aclTensor.
ret = CreateAclTensor(outHostData, outShape, &outDeviceAddr, aclDataType::ACL_BF16, &out);
std::unique_ptr<aclTensor, aclnnStatus (*)(const aclTensor*)> outTensorPtr(out, aclDestroyTensor);
std::unique_ptr<void, aclError (*)(void*)> outdeviceAddrPtr(outDeviceAddr, aclrtFree);
CHECK_RET(ret == ACL_SUCCESS, return ret);
aclIntArray* permX1 = aclCreateIntArray(permX1Series.data(), permX1Series.size());
aclIntArray* permX2 = aclCreateIntArray(permX2Series.data(), permX2Series.size());
aclIntArray* permY = aclCreateIntArray(permYSeries.data(), permYSeries.size());
uint64_t workspaceSize = 0;
aclOpExecutor* executor = nullptr;
std::unique_ptr<void, aclError (*)(void*)> executorAddrPtr(nullptr, aclrtFree);
int32_t batchSplitFactor = 1;
int64_t groupSize = 0;
int32_t dtype = 27; // bf16
// aclnnTransposeQuantBatchMatMul API call example
// 3. Call the CANN operator library API. Replace it with the actual API name.
// Call the aclnnTransposeQuantBatchMatMul first-phase API.
ret = aclnnTransposeQuantBatchMatMulGetWorkspaceSize(
x1, x2, (const aclTensor*)nullptr, x1Scale, x2Scale, dtype, groupSize, permX1, permX2, permY, batchSplitFactor,
out, &workspaceSize, &executor);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnTransposeQuantBatchMatMulGetWorkspaceSize 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);
executorAddrPtr.reset(workspaceAddr);
}
// Call the aclnnTransposeQuantBatchMatMul second-phase API.
ret = aclnnTransposeQuantBatchMatMul(workspaceAddr, workspaceSize, executor, stream);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnTransposeQuantBatchMatMul failed. ERROR: %d\n", ret); return ret);
// 4. (boilerplate) Wait for the task execution to finish synchronously.
ret = aclrtSynchronizeStream(stream);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtSynchronizeStream failed. ERROR: %d\n", ret); return ret);
// 5. Obtain the output value, copy the result from the Device side to the Host side, and modify it based on the specific API definition.
auto size = GetShapeSize(outShape);
std::vector<uint16_t> resultData(size, 0); // bf16
ret = aclrtMemcpy(
resultData.data(), resultData.size() * sizeof(resultData[0]), outDeviceAddr, 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);
float resultDataBF16 = 0;
for (int64_t i = 0; i < size; i++) {
resultDataBF16 = bf16_to_float(resultData[i]);
LOG_PRINT("result[%ld] is: %f\n", i, resultDataBF16);
}
return ACL_SUCCESS;
}
int main()
{
// 1. (boilerplate) Initialize device/stream. For details, see the acl API manual.
// Set deviceId based on the actual device.
int32_t deviceId = 0;
aclrtStream stream;
auto ret = AclnnTransposeQuantBatchMatmulTest(deviceId, stream);
CHECK_FREE_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnTransposeQuantBatchMatMulTest failed. ERROR: %d\n", ret);
return ret);
Finalize(deviceId, stream);
return 0;
}