aclnnTransposeQuantBatchMatMulWeightNz
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 quantized matrix multiplication of tensors x1 and x2. Compared with the existing aclnnTransposeQuantBatchMatMul API, the new API supports only x1 in ND format and x2 in NZ format, and only supports 3-dimensional x1 and 5-dimensional x2. It supports the MX quantization mode. Tensor transpose is supported, and the transpose sequence changes according to the input number sequence. permX1 represents the transpose sequence of tensor x1, and permX2 represents the transpose sequence of tensor x2. The dimension whose sequence value is 0 is the batch dimension, and the other two dimensions are used for matrix multiplication.
Example: (viewshape perspective corresponding to the conversion of x2 from NZ to ND)
- 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. Call "aclnnTransposeQuantBatchMatMulWeightNzGetWorkspaceSize" first to obtain the workspace size, and then call "aclnnTransposeQuantBatchMatMulWeightNz" to perform the computation.
aclnnStatus aclnnTransposeQuantBatchMatMulWeightNzGetWorkspaceSize(
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 aclnnTransposeQuantBatchMatMulWeightNz(
void *workspace,
uint64_t workspaceSize,
aclOpExecutor *executor,
const aclrtStream stream);aclnnTransposeQuantBatchMatMulWeightNzGetWorkspaceSize
Parameters:
Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor x1 (aclTensor*) Input Represents the first matrix in the matrix multiplication. The data type must satisfy the data type deduction rule with x2 (see deduction relationship and Constraints). FLOAT8_E4M3FN ND 3 √ x2 (aclTensor*) Input Represents the second matrix in the matrix multiplication. - The data type must satisfy the data type deduction rules with x1 (see Deduction Relationship and Constraints).
- The k dimension of x2 must be the same size as the K dimension of x1.
FLOAT8_E4M3FN NZ 5 √ bias (aclTensor*) Input Represents the bias matrix of matmul. Reserved parameter, not supported currently. - - - - x1Scale (aclTensor*) Input Represents the quantization coefficients of the left matrix. The required shape is (M, B, K/64, 2). FLOAT8_E8M0 ND 4 √ x2Scale (aclTensor*) Input Represents the quantization coefficients of the right matrix. - When permX2 is [0, 1, 2], the required shape is (B, K/64, N, 2).
- When permX2 is [0, 2, 1], the required shape is (B, N, K/64, 2).
FLOAT8_E8M0 ND 4 √ dtype (int32_t) Input Used to specify the data type of the output matrix. Supported values: 1 and 27. - If the value is 1, the output matrix type is FLOAT16.
- If the value is 27, the output matrix type is BFLOAT16.
INT32 - - - groupSize (int64_t) Input Used to specify the quantization group sizes in the M, N, and K dimensions. Composed of the three values groupSizeM, groupSizeN, and groupSizeK in three dimensions, each occupying 16 bits and together occupying the lower 48 bits of groupSize of the int64_t type (the value of the upper 16 bits of groupSize is invalid). INT64 - - - permX1 (aclIntArray*) Input Represents the transpose sequence of the first matrix in the matrix multiplication, in the form of an aclIntArray on the host. Supports [1, 0, 2]. INT64 - 1 - permX2 (aclIntArray*) Input Represents the transpose sequence of the second matrix in the matrix multiplication, in the form of an aclIntArray on the host. [0, 1, 2] or [0, 2, 1] is supported. INT64 - 1 - permY (aclIntArray*) Input Represents the transpose sequence of the matmul output matrix, aclIntArray on the host. Supported value: [1, 0, 2]. INT64 - 1 - batchSplitFactor (int32_t) Input Specifies the splitting size of dimension B in the matrix multiplication output matrix. Host-side integer. Currently, only the value 1 is supported. Currently, only the value 1 is supported. INT32 - - - out (aclTensor*) Output Output matrix of the matrix multiplication, i.e., out in the formula. Empty tensors are not supported. BFLOAT16, FLOAT16 ND 3 √ workspaceSize Output Returns the workspace size to be requested on the Device. - - - - - executor Output Returns the op executor containing the operator computation process. - - - - - 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, x1Scale, x2Scale, permX1, permX2, and permY are null pointers. ACLNN_ERR_PARAM_INVALID 161002 The data type of x1, x2, x1Scale, x2Scale, or out is not within the supported range. The shape of x1, x2, x1Scale, x2Scale, or out does not meet the validation conditions. The dimension size of the ViewShape of x1 or x2 is not equal to 3. batchSplitFactor is not within the supported range. The values of permX1, permX2, and permY are not within the supported range. The StorageFormat of x2 is not FORMAT_FRACTAL_NZ.
aclnnTransposeQuantBatchMatMulWeightNz
Parameters:
Parameter Input/Output Description workspace Input Workspace memory address on the Device. workspaceSize Input Size of the workspace to allocate on the Device, obtained by calling the first-phase API aclnnTransposeQuantBatchMatMulWeightNzGetWorkspaceSize. executor Input Op executor that contains the operator computation flow. stream Input Stream for executing tasks. Return value
aclnnStatus: return status code. For details, see aclnn Return Codes.
Constraints
- Deterministic computation: aclnnTransposeQuantBatchMatMulWeightNz defaults to a deterministic implementation.
Ascend 950PR&950DT products :- x1 supports only 3 dimensions, and x2 supports only the Ascend proprietary format. Before calling this API, x2 must be converted from ND to the Ascend proprietary format.
- K supports only multiples of 64. groupSizeM and groupSizeN of groupSize support only 0 or 1, and groupSizeK supports only 32.
- 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
Example code is as follows and is for reference only. For details about compilation and execution, 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"
#include "aclnnop/aclnn_npu_format_cast.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;
}
// BF16-to-float conversion function
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 {
// Denormalized 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-bit fraction.
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 Device-side 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-side data to 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 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 aclCreateTensor 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();
}
template <typename T>
int CreateAclTensorWithFormat(
const std::vector<T>& hostData, const std::vector<int64_t>& shape, int64_t** storageShape,
uint64_t* storageShapeSize, void** deviceAddr, aclDataType dataType, aclTensor** tensor, aclFormat format)
{
auto size = hostData.size() * sizeof(T);
// Call aclrtMalloc to allocate device-side 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-side data to 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 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];
}
*tensor = aclCreateTensor(
shape.data(), shape.size(), dataType, strides.data(), 0, format, *storageShape, *storageShapeSize, *deviceAddr);
return 0;
}
int AclnnTransposeQuantBatchMatMulWeightNzTest(int32_t deviceId, aclrtStream& stream)
{
auto ret = Init(deviceId, &stream);
// Handle the check as needed.
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("Init acl failed. ERROR: %d\n", ret); return ret);
// 2. Construct the input and output. The construction is custom based on 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, Batch, static_cast<int64_t>(K / 64), 2};
std::vector<int64_t> x2ScaleShape = {Batch, static_cast<int64_t>(K / 64), N, 2};
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;
void* x2NzDeviceAddr = nullptr;
aclTensor* x1 = nullptr;
aclTensor* x2 = nullptr;
aclTensor* x1Scale = nullptr;
aclTensor* x2Scale = nullptr;
aclTensor* out = nullptr;
aclTensor* x2NZ = 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 the 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 the 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 the x1Scale aclTensor.
ret = CreateAclTensor(x1ScaleHostData, x1ScaleShape, &x1ScaleDeviceAddr, aclDataType::ACL_FLOAT8_E8M0, &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 the x2Scale aclTensor.
ret = CreateAclTensor(x2ScaleHostData, x2ScaleShape, &x2ScaleDeviceAddr, aclDataType::ACL_FLOAT8_E8M0, &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 the 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());
// 3. Convert the weight tensor from ND format to NZ format by calling the npu_format_cast API.
aclDataType additionalDtype = aclDataType::ACL_FLOAT8_E4M3FN;
aclDataType srcDtype = aclDataType::ACL_FLOAT8_E4M3FN;
int64_t* dstShape = nullptr;
uint64_t dstShapeSize = 0;
int actualFormat;
aclOpExecutor* executor = nullptr;
uint64_t formatCastWorkspaceSize = 0;
void* formatCastWorkspaceAddr = nullptr;
// Compute the shape and format of the target tensor.
ret = aclnnNpuFormatCastCalculateSizeAndFormat(x2, 29, additionalDtype, &dstShape, &dstShapeSize, &actualFormat);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnNpuFormatCastCalculateSizeAndFormat failed. ERROR: %d\n", ret);
return ret);
ret = CreateAclTensorWithFormat(
x2HostData, x2Shape, &dstShape, &dstShapeSize, &x2NzDeviceAddr, srcDtype, &x2NZ,
static_cast<aclFormat>(actualFormat));
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("CreateAclTensorWithFormat failed. ERROR: %d\n", ret); return ret);
// Call the first-phase API aclnnNpuFormatCastGetWorkspaceSize.
ret = aclnnNpuFormatCastGetWorkspaceSize(x2, x2NZ, &formatCastWorkspaceSize, &executor);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnNpuFormatCastGetWorkspaceSize failed. ERROR: %d\n", ret); return ret);
// Allocate device memory based on the workspaceSize computed by the first-phase API.
if (formatCastWorkspaceSize > 0) {
ret = aclrtMalloc(&formatCastWorkspaceAddr, formatCastWorkspaceSize, ACL_MEM_MALLOC_HUGE_FIRST);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("allocate format cast workspace failed. ERROR: %d\n", ret); return ret);
}
// Call the second-phase API of aclnnNpuFormatCast.
ret = aclnnNpuFormatCast(formatCastWorkspaceAddr, formatCastWorkspaceSize, executor, stream);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnNpuFormatCast failed. ERROR: %d\n", ret); return ret);
// 4. Synchronously wait for the format conversion task to complete.
ret = aclrtSynchronizeStream(stream);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtSynchronizeStream failed. ERROR: %d\n", ret); return ret);
uint64_t tqbmmWorkspaceSize = 0;
std::unique_ptr<void, aclError (*)(void*)> executorAddrPtr(nullptr, aclrtFree);
int32_t batchSplitFactor = 1;
int64_t groupSize = 32;
int32_t dtype = 27; // bf16
// aclnnTransposeQuantBatchMatMulWeightNz API call example
// 3. Call the CANN operator library API and change it to the specific API name.
// Call the first-phase API of aclnnTransposeQuantBatchMatMulWeightNz.
ret = aclnnTransposeQuantBatchMatMulWeightNzGetWorkspaceSize(
x1, x2NZ, (const aclTensor*)nullptr, x1Scale, x2Scale, dtype, groupSize, permX1, permX2, permY,
batchSplitFactor, out, &tqbmmWorkspaceSize, &executor);
CHECK_RET(ret == ACL_SUCCESS,
LOG_PRINT("aclnnTransposeQuantBatchMatMulWeightNzGetWorkspaceSize failed. ERROR: %d\n", ret);
return ret);
// Allocate device memory based on the workspaceSize calculated by the first-phase API.
void* workspaceAddr = nullptr;
if (tqbmmWorkspaceSize > 0) {
ret = aclrtMalloc(&workspaceAddr, tqbmmWorkspaceSize, 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 second-phase API of aclnnTransposeQuantBatchMatMulWeightNz.
ret = aclnnTransposeQuantBatchMatMulWeightNz(workspaceAddr, tqbmmWorkspaceSize, executor, stream);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnTransposeQuantBatchMatMulWeightNz 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-side memory to the Host side. Modify the code according to 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 the device/stream. For details, see the acl API reference.
// Fill in deviceId based on your actual device.
int32_t deviceId = 0;
aclrtStream stream;
auto ret = AclnnTransposeQuantBatchMatMulWeightNzTest(deviceId, stream);
CHECK_FREE_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnTransposeQuantBatchMatMulWeightNzTest failed. ERROR: %d\n", ret);
return ret);
Finalize(deviceId, stream);
return 0;
}