aclnnFusedQuantMatmulWeightNz
Applicable Products
| Product | Supported |
|---|---|
| × | |
| √ | |
| √ | |
| × | |
| × | |
| × |
Function
Description: Fused quantized matrix multiplication and Gelu computation.
Formula:
x1Scale, bias INT32 (no offset in this scenario):
x1Scale, bias BFLOAT16/FLOAT16/FLOAT32 (no offset in this scenario):
x1Scale without bias:
The OP type is defined by the fusedOpType input and supports the following:
gelu_tanh operation:
gelu_erf operation:
Function Prototype
Each operator is divided into a two-phase API. You must first call the "aclnnFusedQuantMatmulWeightNzGetWorkspaceSize" API to obtain the workspace size required for computation and the executor that contains the operator computation process, and then call the "aclnnFusedQuantMatmulWeightNz" API to perform the computation.
aclnnStatus aclnnFusedQuantMatmulWeightNzGetWorkspaceSize(
const aclTensor *x1,
const aclTensor *x2,
const aclTensor *x1Scale,
const aclTensor *x2Scale,
const aclTensor *yScaleOptional,
const aclTensor *x1OffsetOptional,
const aclTensor *x2OffsetOptional,
const aclTensor *yOffsetOptional,
const aclTensor *biasOptional,
const aclTensor *x3Optional,
const char *fusedOpType,
int64_t groupSizeOptional,
aclTensor *out,
uint64_t *workspaceSize,
aclOpExecutor **executor)aclnnStatus aclnnFusedQuantMatmulWeightNz(
void *workspace,
uint64_t workspaceSize,
aclOpExecutor *executor,
aclrtStream stream)aclnnFusedQuantMatmulWeightNzGetWorkspaceSize
Parameters:
Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor x1 Input Input x1 in the formula. INT4, INT8, INT32 ND 2-6 √ x2 Input Input x2 in the formula. - Supports the AI processor affinity data layout format.
- The size of the last dimension cannot exceed 65535.
INT4, INT8, INT32 NZ 2-6 √ x1Scale Input Represents the quantization parameter, i.e., x1Scale in the formula. - FLOAT32 ND 1 - x2Scale Input Represents the quantization parameter, i.e., the input x2Scale in the formula. - FLOAT32, BFLOAT16 ND 1 - yScaleOptional Input Quantization scale parameter for output y, used in static quantization. Reserved parameter. Not supported in the current version. Pass nullptr. - - - - x1OffsetOptional Input x1Offset in the formula. Reserved parameter. Not supported in the current version. Pass nullptr. - - - - x2OffsetOptional Input The input x2Offset in the formula. Reserved parameter. Not supported in the current version. Pass nullptr. - - - - yOffsetOptional Input Input yOffset in the formula. Reserved parameter. Not supported in the current version. Pass nullptr. - - - - biasOptional Input Input bias in the formula. Pass nullptr when there is no bias. INT32, FLOAT32, BFLOAT16, FLOAT16 ND 1, 3 - x3Optional Input Input for the fused binary operation. Currently only fused unary operations are supported. This is a reserved parameter and is not supported in the current version. Pass nullptr. - - - - fusedOpType Input Specifies the fusion mode supported by the QuantBatchMatmul operator, corresponding to the input fusedOpType in the formula. The fusion mode value must be either "gelu_erf" or "gelu_tanh". STRING - - - groupSizeOptional Input Specifies the quantization group size in the m, n, and k directions. Reserved parameter. Not supported in the current version. Pass nullptr. - - - - out Output The output out in the formula. - FLOAT16, BFLOAT16 ND 2-6 ✓ workspaceSize Output Returns the workspace size to be applied for on the device side. - - - - - executor Output Returns the operator executor, which contains the operator computation flow. - - - - - 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 x1, x2, x1Scale, x2Scale, or out is a null pointer. ACLNN_ERR_PARAM_INVALID 161002 The shape of x1, x2, biasOptional, x1Scale, x2Scale, or out does not meet the validation conditions. The data type or data format of x1, x2, biasOptional, x1Scale, x2Scale, or out is not within the supported range. x1, x2, biasOptional, x1Scale, x2Scale, or out is an empty tensor. The passed fusedOpType is neither "gelu_tanh" nor "gelu_erf". The passed yScaleOptional, x1OffsetOptional, x2OffsetOptional, yOffsetOptional, x3Optional, or groupSizeOptional parameter is currently unsupported.
aclnnFusedQuantMatmulWeightNz
Parameters:
Parameter Input/Output Description workspace Input The workspace memory address applied on the Device side. workspaceSize Input The workspace size applied on the Device side, obtained from the first-phase API aclnnFusedQuantMatmulWeightNzGetWorkspaceSize. executor Input Operator executor that 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 andAtlas inference products : aclnnFusedQuantMatmulWeightNz defaults to a deterministic implementation.
The input and output support the following data type combinations:
x1 x2 x1Scale x2Scale x2OffsetOptional yScaleOptional biasOptional yOffsetOptional out INT8 INT8 FLOAT32 FLOAT32/BFLOAT16 null null null/INT32/BFLOAT16/FLOAT32 null BFLOAT16 INT8 INT8 FLOAT32 FLOAT32 null null null/INT32/FLOAT16/FLOAT32 null FLOAT16 INT4/INT32 INT4/INT32 FLOAT32 FLOAT32/BFLOAT16 null null null/INT32/BFLOAT16/FLOAT32 null BFLOAT16 INT4/INT32 INT4/INT32 FLOAT32 FLOAT32 null null null/INT32/FLOAT16/FLOAT32 null FLOAT16 The current API supports x1 per-token quantization and x2 per-channel/per-tensor quantization. The constraints on the input dtype combinations of x1, x2, x1Scale, and x2Scale supported by different quantization modes are as follows:
The x1 data type supports INT8, INT32, and INT4.
When the data type is INT32 or INT4, it is an INT4 quantization scenario:
Currently, only ND input is supported.
Currently, only non-transposed input is supported.
The inner axis of x1 must be an even number.
When the data type is INT32, each INT32 value stores eight INT4 values, and the corresponding dimension representation is (batch, m, k // 8). k must be a multiple of 8.
x2 data type supports INT8, INT32, and INT4.
This API only supports x2 in NZ format. When x2 is in NZ format, k and n cannot be 1.
When the data type is INT32, each INT32 value stores eight INT4 values.
You can use the aclnnConvertWeightToINT4Pack API to convert x2 from INT32 (one INT32 stores one INT4 in bits 0–3) to INT32 (one INT32 stores eight INT4 values) or INT4 (one INT4 represents one INT4 value). For details, see aclnnConvertWeightToINT4Pack API.
In the AI processor affinity data layout, the shape supports 4 to 8 dimensions.
When transposed, the dimensions are: (batch, k1, n1, n0, k0), where batch may be absent, k0 = 32, n0 = 16. The k in x1 shape and k1 in x2 shape must satisfy the following relationship: ceil(k / 32) = k1.
When not transposed, the dimensions are: (batch, n1, k1, k0, n0), where batch may be absent, k0 = 16, n0 = 32. The k in x1 shape and k1 in x2 shape must satisfy the following relationship: ceil(k / 16) = k1.
The aclnnCalculateMatmulWeightSizeV2 API and aclnnTransMatmulWeight API can be used to convert the input format from ND to the AI processor affinity data layout.
The constraints on x1Scale are as follows:
- The shape supports one dimension with a shape of (m,), and the data type supports FLOAT32.
Constraints on x2Scale are as follows:
- The shape supports 1D, with a shape of (n,) or (1,), where n is consistent with n of x2. The data type supports FLOAT32 and BFLOAT16.
Constraints on biasOptional are as follows:
The shape supports 1D or 3D. In INT4 quantization scenarios, biasOptional only supports 1D with a shape of (n). For 3D, the biasOptional shape is (batch, 1, n).
The data type supports int32, float32, bfloat16, or float16.
The constraints for out are as follows: The shape supports 2 to 6 dimensions, (batch, m, n). The data type supports FLOAT16 and BFLOAT16.
Example
The following provides example code for reference only. For details about compilation and running, see Compile and Run Samples.
Atlas A3 training products/Atlas A3 inference products ,Atlas A2 training products/Atlas A2 inference products :
x1 is INT8, x2 is INT8, x1Scale is FLOAT32, and x2Scale is FLOAT32.
#include <iostream>
#include <memory>
#include <vector>
#include "acl/acl.h"
#include "aclnnop/aclnn_fused_quant_matmul_weight_nz.h"
#include "aclnnop/aclnn_trans_matmul_weight.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;
}
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 apply for 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);
// Copy the host-side data to the device-side memory by calling aclrtMemcpy.
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 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;
}
void Finalize(int32_t deviceId, aclrtStream stream)
{
aclrtDestroyStream(stream);
aclrtResetDevice(deviceId);
aclFinalize();
}
template <typename T>
int CreateAclTensorX2(
const std::vector<T>& hostData, const std::vector<int64_t>& shape, void** deviceAddr, aclDataType dataType,
aclTensor** tensor)
{
auto size = static_cast<uint64_t>(GetShapeSize(shape));
const aclIntArray* mat2Size = aclCreateIntArray(shape.data(), shape.size());
auto ret = aclnnCalculateMatmulWeightSizeV2(mat2Size, dataType, &size);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnCalculateMatmulWeightSizeV2 failed. ERROR: %d\n", ret); return ret);
size *= sizeof(T);
// Call aclrtMalloc to apply for device-side memory.
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 the host-side data to the device-side memory by calling aclrtMemcpy.
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];
}
std::vector<int64_t> storageShape;
storageShape.push_back(GetShapeSize(shape));
// Call the aclCreateTensor API to create an aclTensor.
*tensor = aclCreateTensor(
shape.data(), shape.size(), dataType, strides.data(), 0, aclFormat::ACL_FORMAT_ND, storageShape.data(),
storageShape.size(), *deviceAddr);
return 0;
}
int aclnnFusedQuantMatmulWeightNzTest(int32_t deviceId, 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. Custom construction is required based on the API.
std::vector<int64_t> x1Shape = {5, 32};
std::vector<int64_t> x2Shape = {32, 32};
std::vector<int64_t> x1ScaleShape = {5};
std::vector<int64_t> x2ScaleShape = {32};
std::vector<int64_t> outShape = {5, 32};
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(5 * 32, 1);
std::vector<int8_t> x2HostData(32 * 32, 1);
std::vector<float> x1ScaleHostData(5, 1);
std::vector<float> x2ScaleHostData(32, 1);
std::vector<uint16_t> outHostData(5 * 32, 1); // Actually in float16 half-precision format.
// Create the x1 aclTensor.
ret = CreateAclTensor(x1HostData, x1Shape, &x1DeviceAddr, aclDataType::ACL_INT8, &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 in AI processor affinity data layout format.
ret = CreateAclTensorX2(x2HostData, x2Shape, &x2DeviceAddr, aclDataType::ACL_INT8, &x2);
std::unique_ptr<aclTensor, aclnnStatus (*)(const aclTensor*)> x2HPTensorPtr(x2, aclDestroyTensor);
std::unique_ptr<void, aclError (*)(void*)> x2HPDeviceAddrPtr(x2DeviceAddr, aclrtFree);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// Create the 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 the 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 the out aclTensor.
ret = CreateAclTensor(outHostData, outShape, &outDeviceAddr, aclDataType::ACL_FLOAT16, &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);
int64_t groupSize = 0;
const char fusedOpType[] = "gelu_tanh";
// 3. Call the CANN operator library API. Replace with the actual API name.
uint64_t workspaceSize = 0;
aclOpExecutor* executor;
void* workspaceAddr = nullptr;
// Call the first-phase API of aclnnTransMatmulWeight.
ret = aclnnTransMatmulWeightGetWorkspaceSize(x2, &workspaceSize, &executor);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnTransMatmulWeightGetWorkspaceSize failed. ERROR: %d\n", ret);
return ret);
// Apply for device memory based on the workspaceSize calculated by the first-phase API.
std::unique_ptr<void, aclError (*)(void*)> workspaceAddrPtrTrans(nullptr, aclrtFree);
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);
workspaceAddrPtrTrans.reset(workspaceAddr);
}
// Call the second-phase API of aclnnTransMatmulWeight.
ret = aclnnTransMatmulWeight(workspaceAddr, workspaceSize, executor, stream);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnTransMatmulWeight failed. ERROR: %d\n", ret); return ret);
// Call the first-phase API of aclnnFusedQuantMatmulWeightNz.
workspaceSize = 0;
ret = aclnnFusedQuantMatmulWeightNzGetWorkspaceSize(
x1, x2, x1Scale, x2Scale, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, fusedOpType, groupSize, out,
&workspaceSize, &executor);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnFusedQuantMatmulWeightNzGetWorkspaceSize failed. ERROR: %d\n", ret);
return ret);
// Apply for device memory based on the workspaceSize calculated by the first-phase API.
std::unique_ptr<void, aclError (*)(void*)> workspaceAddrPtrNZ(nullptr, aclrtFree);
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);
workspaceAddrPtrNZ.reset(workspaceAddr);
}
// Call the second-phase API of aclnnFusedQuantMatmulWeightNz.
ret = aclnnFusedQuantMatmulWeightNz(workspaceAddr, workspaceSize, executor, stream);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnFusedQuantMatmulWeightNz 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<uint16_t> resultData(
size, 0); // In C language, fp16 data cannot be printed directly. It needs to be read as uint16 and manually converted to fp16 via binary.
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);
for (int64_t i = 0; i < size; i++) {
LOG_PRINT("result[%ld] is: %u\n", i, resultData[i]);
}
return ACL_SUCCESS;
}
int main()
{
// 1. (Boilerplate) Initialize device/stream. Refer to the ACL API manual.
// Fill in the deviceId based on your actual device.
int32_t deviceId = 0;
aclrtStream stream;
auto ret = aclnnFusedQuantMatmulWeightNzTest(deviceId, stream);
CHECK_FREE_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnFusedQuantMatmulWeightNzTest failed. ERROR: %d\n", ret); return ret);
Finalize(deviceId, stream);
return 0;
}