aclnnWeightQuantBatchMatmulV2
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 : Not supported
Function
- Description: Performs matrix multiplication with the input in a Fake Quantization scenario, and supports quantization computation on the output.
- Formula:
In the formula, is the input in the pseudo-quantization scenario, and its dequantization formula is
- When no quantization operation is required on the output, the formula is:
- When the output needs to be quantized, the quantization formula is:
Function Prototype
Each operator uses a two-phase API. You must first call the "aclnnWeightQuantBatchMatmulV2GetWorkspaceSize" API to obtain the workspace size required for the computation and the executor that includes the operator computation flow, and then call the "aclnnWeightQuantBatchMatmulV2" API to perform the computation.
aclnnStatus aclnnWeightQuantBatchMatmulV2GetWorkspaceSize(
const aclTensor *x,
const aclTensor *weight,
const aclTensor *antiquantScale,
const aclTensor *antiquantOffsetOptional,
const aclTensor *quantScaleOptional,
const aclTensor *quantOffsetOptional,
const aclTensor *biasOptional,
int antiquantGroupSize,
const aclTensor *y,
uint64_t *workspaceSize,
aclOpExecutor **executor)aclnnStatus aclnnWeightQuantBatchMatmulV2(
void *workspace,
uint64_t workspaceSize,
aclOpExecutor *executor,
aclrtStream stream)aclnnWeightQuantBatchMatmulV2GetWorkspaceSize
Parameters
Ascend 950PR&950DT products :- The superscript "1" in the data type column of the table above indicates a data type not supported by this series.
Atlas A2 products ,Atlas A3 products :- The superscript "2" in the data type column of the table above indicates a data type not supported by this series.
Atlas inference products :- The superscript "3" in the data type column of the table above indicates a data type not supported by this series.
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 null pointer is passed for a required parameter. ACLNN_ERR_PARAM_INVALID 161002 The shape dimensions of x, weight, antiquantScale, antiquantOffsetOptional, quantScaleOptional, quantOffsetOptional, biasOptional, and y do not meet requirements. The data types of x, weight, antiquantScale, antiquantOffsetOptional, quantScaleOptional, quantOffsetOptional, biasOptional, and y are not in the supported range. The reduce dimensions (k) of x and weight are not equal. When antiquantOffsetOptional is provided as input, its shape is different from that of antiquantScale. When quantOffsetOptional is provided as input, its shape is different from that of quantScale. The shape of biasOptional does not meet requirements. The value of antiquantGroupSize does not meet requirements. When quantOffsetOptional exists, quantScaleOptional is a null pointer. The k and n values of the input are not in the range [1, 65535]. When the x matrix is non-transposed, m is not in the range [1, 2^31-1]; when transposed, m is not in the range [1, 65535]. Empty tensor use cases are not supported. The contiguity of x, weight, antiquantScale, antiquantOffsetOptional, quantScaleOptional, quantOffsetOptional, biasOptional, and y does not meet requirements. When x is bfloat16 and weight is float4_e2m1 or float32, the bias data type supports only bfloat16. ACLNN_ERR_RUNTIME_ERROR 361001 The product model is not supported.
aclnnWeightQuantBatchMatmulV2
Parameters
Parameter Input/Output Description workspace Input Workspace memory address applied on the Device side. workspaceSize Input Workspace size applied on the Device side, obtained by the first-phase API aclnnWeightQuantBatchMatmulV2GetWorkspaceSize. executor Input Op executor. Includes 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
Atlas A2 products , Atlas A3 products
Deterministic computation description: Defaults to a non-deterministic implementation. Supports enabling deterministic computation through aclrtCtxSetSysParamOpt.
x(aclTensor *, computation input): If the matrix is non-transposed, m is in the range [1, 2^31-1]; if transposed, m is in the range [1, 65535].weight(aclTensor *, computation input): Supports 2 dimensions. The size of the Reduce dimension k must be equal to the size of the Reduce dimension k ofx. Data types INT8, INT4, and INT32 are supported. When the data format ofweightis FRACTAL_NZ and the data type is INT4 or INT32, or when the data format ofweightis ND and the data type is INT32, only the INT4Pack use case is supported. TheaclnnConvertWeightToINT4PackAPI must be used to complete the conversion from INT32 to INT4Pack and from ND to FRACTAL_NZ. For details, see the sample. If the data type is INT4, the inner axis ofweightmust be an even number. Non-contiguous tensor only supports the transpose use case. The shape is (k, n), where k represents the size of the first dimension of the matrix and n represents the size of the second dimension of the matrix. For different pseudo-quantization algorithm modes, the FRACTAL_NZ data format ofweightis supported only in the following use cases:- perchannel quantization mode:
- The data type of
weightis INT8, and the data type of y is non-INT8. - The data type of
weightis INT4/INT32,weightis transposed, and the data type of y is non-INT8.
- The data type of
- pergroup quantization mode: The data type of
weightis INT4/INT32,weightis non-transposed,xis non-transposed, antiquantGroupSize is 64 or 128, k is aligned to antiquantGroupSize, n is aligned to 64, and the data type of y is not INT8.
- perchannel quantization mode:
antiquantScale(aclTensor *, computation input): The data types include FLOAT16, BFLOAT16, UINT64, and INT64. (For FLOAT16 and BFLOAT16, the data type must remain consistent with inputx; for UINT64 and INT64,xsupports only FLOAT16 without transpose,weightsupports only INT8 with ND transpose, the mode supports only the perchannel quantization mode, quantScaleOptional and quantOffsetOptional must be null pointers, m supports only [1, 96], and k and n must be aligned to 64. First, call the aclnnCast API to convert data from FLOAT16 to FLOAT32. For details, see Cast. Then, call the aclnnTransQuantParamV2 API to convert data from FLOAT32 to UINT64. For details, see TransQuantParamV2.) Non-contiguous tensors support only the transpose scenario. For different Fake Quantization algorithm modes, the supported shapes ofantiquantScaleare as follows:- pertensor quantization mode: The input shape is (1,) or (1, 1).
- perchannel quantization mode: The input shape is (1, n) or (n,).
- pergroup quantization mode: The input shape is (⌈k/group_size⌉, n), where group_size indicates the size of each group into which k is divided.
antiquantOffsetOptional(aclTensor *, computation input): The data types include FLOAT16, BFLOAT16, and INT32. For FLOAT16 and BFLOAT16, the data type must remain consistent with the data type of inputx. For INT32, the value range is [-128, 127], x supports only FLOAT16, weight supports only INT8, andantiquantScalesupports only UINT64/INT64. Non-contiguous tensors support only the transpose scenario.quantScaleOptional(aclTensor *, computation input): The data type is UINT64, and the data format supports ND. Non-contiguous tensors are not supported. This is an optional input and is a null pointer when not needed. For different pseudo-quantization algorithm modes, the supported shapes are as follows:- pertensor quantization mode: The input shape is (1,) or (1, 1).
- perchannel quantization mode: The input shape is (1, n) or (n,).
quantOffsetOptional(aclTensor *, computation input): FLOAT data type is supported, and the data format supports ND. Optional input; a null pointer when not needed; when present, the shape must be consistent withquantScaleOptional. Non-contiguous tensors are not supported.biasOptional(aclTensor *, computation input): Supports 1D or 2D, with shape (n,) or (1, n). Supports the FLOAT16 and FLOAT data types. When the data type ofxis BFLOAT16, this parameter must be FLOAT; when the data type ofxis FLOAT16, this parameter must be FLOAT16.antiquantGroupSize(int, computation input): Specifies the groupSize input for the dequantization computation on the inputweightin pseudo-quantization pergroup and MX quantization mode, describing the size along the Reduce direction of the data to be dequantized corresponding to a group of dequantization parameters. Pass 0 when the pseudo-quantization algorithm is not pergroup or MX quantization mode; when the pseudo-quantization algorithm is pergroup quantization mode, the value range is [32, k-1] and the value must be a multiple of 32; in MX quantization mode, only 32 is supported.y(aclTensor *, computation output): Supports 2D, with shape (m, n). Supports the FLOAT16, BFLOAT16, and INT8 data types. WhenquantScaleOptionalis present, the data type is INT8; whenquantScaleOptionalis absent, the data type is FLOAT16 or BFLOAT16 and is consistent with the data type of inputx.Performance optimization suggestions:
- pertensor quantization mode: When the data format is ND, the transposed
weightinput is recommended; when the data format is FRACTAL_NZ, the non-transposedweightinput is recommended. - pergroup quantization mode: The non-transposed weight input is recommended.
- perchannel quantization mode: When the data format is ND, the transposed
weightinput is recommended; when the data format is FRACTAL_NZ, the non-transposedweightinput is recommended. When m is in the range [65, 96], antiquantScale of the UINT64 or INT64 data type is recommended.
- pertensor quantization mode: When the data format is ND, the transposed
Atlas inference products
Deterministic computation description: Defaults to a non-deterministic implementation. Supports enabling deterministic computation through aclrtCtxSetSysParamOpt.
x(aclTensor *, computation input): FLOAT16 data type is supported. The shape supports 2 to 6 dimensions, and the input shape must be (batch, m, k), where batch represents the batch size of matrices and supports 0 to 4 dimensions, m represents the size of the first dimension of a single batch matrix, and k represents the size of the second dimension of a single batch matrix. The batch dimension must satisfy the broadcast relationship with the batch dimension ofweight.When the pseudo-quantization algorithm mode is pertensor [quantization mode](../common/quant_mode_introduction.md), `m*k` cannot exceed 512000000.weight(aclTensor *, computation input): 2 to 6 dimensions are supported; the batch dimension must satisfy the broadcast relationship with the batch dimension ofx; INT8 data type is supported. Details are as follows:- When the data format is ND, the input shape must be (batch, k, n), where batch represents the batch size of the matrix and supports 0-4 dimensions, k represents the size of the 1st dimension of a single batch matrix, and n represents the size of the 2nd dimension of a single batch matrix.
- When the data format is FRACTAL_NZ:
- The input shape must be (batch, n, k), where batch indicates the batch size of the matrices, supporting 0 to 4 dimensions, k indicates the size of the first dimension of a single batch matrix, and n indicates the size of the second dimension of a single batch matrix.
- Used together with aclnnCalculateMatmulWeightSizeV2 and aclnnTransMatmulWeight to convert the input format from ND to FRACTAL_NZ.
antiquantScale(aclTensor *, computation input): The data type supports FLOAT16 and must remain consistent with the inputx. For different Fake Quantization algorithm modes, the supported shapes ofantiquantScaleare as follows:- pertensor quantization mode: the input shape is (1,) or (1, 1).
- perchannel quantization mode: the input shape is (n, 1) or (n,). Non-contiguous tensors are not supported.
- pergroup quantization mode: the input shape is related to the data format of
weight, as follows:- When the data format of
weightis ND, the input shape is (⌈k/group_size⌉, n), where group_size indicates the size of each group into which k is to be grouped. - When the data format of
weightis FRACTAL_NZ, the input shape is (n, ⌈k/group_size⌉), where group_size indicates the size of each group into which k is to be grouped.
- When the data format of
antiquantOffsetOptional(aclTensor *, computation input): The data type supports FLOAT16 and must remain consistent with the inputx.quantScaleOptional(aclTensor *, computation input): Reserved parameter, not used yet. Always pass in a null pointer.quantOffsetOptional(aclTensor *, computation input): Reserved parameter, not used yet. Always pass in a null pointer.biasOptional(aclTensor *, computation input): Supports the FLOAT16 data type. Supports 1-6 dimensions. With batch, the input shape must be (batch, 1, n), and the batch must remain consistent with the batch after broadcasting the batch dimensions of x and weight. Without batch, the input shape must be (n,) or (1, n).antiquantGroupSize(int, computation input): Supports the FLOAT16 data type. Supports 2-6 dimensions, with the shape (batch, m, n). batch can be omitted, and broadcasting of the batch dimensions of x and weight is supported. The output batch is the same as the batch after broadcasting, m is the same as m of x, and n is the same as n of weight.y(aclTensor *, computation output):
Ascend 950PR&950DT products
- Deterministic computation description: Defaults to a deterministic implementation.
General Constraints
- The m, k, and n dimensions of the
xandweightmatrices are in the range [1, 2^31-1]. The reduce dimension k ofweightmust be equal to the reduce dimension k ofx. - Supported quantization modes: pertensor quantization mode, perchannel quantization mode, pergroup quantization mode, and MX quantization mode.
xdoes not support transpose; therefore, non-contiguous tensors are not supported. weight supports non-contiguous tensors only in the transpose-only scenario; for antiquantScale and antiquantOffsetOptional, non-contiguous tensors are supported only in the transpose-only scenario, and the continuity requirements must remain consistent with weight.- Shapes supported by
antiquantScalefor different quantization modes:- pertensor quantization mode: (1,) or (1,1).
- perchannel quantization mode: input shape is (1, n) or (n,).
- pergroup quantization mode: input shape is (⌈k/group_size⌉, n), where group_size indicates the size of each group into which k is to be grouped.
- MX quantization mode: input shape is (⌈k/group_size⌉, n), where group_size indicates the size of each group into which k is to be grouped; only 32 is supported.
quantScaleOptionalandquantOffsetOptionalare reserved parameters and not yet in use. Always pass a null pointer.
A16W8 Scenario Constraints
- Input and Output Data Type Combination Requirements
- The m, k, and n dimensions of the
| x | Weight | Weight Format | antiquantScale | antiquantOffsetOptional | quantScaleOptional | quantOffsetOptional | biasOptional | antiquantGroupSize | y | Scenario Description |
| ---- | ------------------| --------------| -------------- | ------------------------| ------------------ | ------------------- | ------------ | ------------------ | ---- | ------- |
| FLOAT16/BFLOAT16 | INT8 | ND | Same as x | Same as x/null | null | null | Same as x/FLOAT (only when x is BFLOAT16)/null | pergroup: [32, k-1] and a multiple of 32
Other: 0 | Same as x | T & C & G quantization |
| FLOAT16/BFLOAT16 | HIFLOAT8/FLOAT8_E4M3FN | ND | Same as x | null | null | null | Same as x/null | 0 | Same as x | C quantization |
- Value relationships among x, weight, antiquantScale, antiquantOffsetOptional, biasOptional, and antiquantGroupSize:| Scenario Description | X Data Type | Weight Data Type | X Shape | Weight Shape | antiquantScale Shape | antiquantOffsetOptional Shape | biasOptional Shape | antiquantGroupSize | | ------- | -------- | ------------- | ------- | ------------ | -------------------- | ----------------------------- | ------------------ | ------------------ | | T quantization | FLOAT16/BFLOAT16 | INT8 | (m, k) | (k, n) | (1,) or (1,1) | (1,) or (1,1)/null | (n,) or (1,n)/null | 0 | | C quantization | FLOAT16/BFLOAT16 | INT8 | (m, k) | (k, n) | (1,n) or (n,) | (1,n) or (n,)/null | (n,) or (1,n)/null | 0 | | G quantization | FLOAT16/BFLOAT16 | INT8 | (m, k) | (k, n) | (⌈k/group_size⌉, n) | (⌈k/group_size⌉, n)/null | (n,) or (1,n)/null | [32, k-1] and a multiple of 32 | | C quantization | FLOAT16/BFLOAT16 | HIFLOAT8/FLOAT8_E4M3FN | (m, k) | (k, n) | (1,n) or (n,) | null | (n,) or (1,n)/null | 0 |
</details>
<a id="a16w4-scenario-constraints"></a>
<details>
<summary>A16W4 Scenario Constraints</summary>
- **Input and Output Data Type Combination Requirements**| x | Weight | Weight Format | antiquantScale | antiquantOffsetOptional | quantScaleOptional | quantOffsetOptional | biasOptional | antiquantGroupSize | y | Scenario Description |
| ---- | ------------------| --------------| -------------- | ------------------------| ------------------ | ------------------- | ------------ | ------------------ | ---- | ------- |
| FLOAT16/BFLOAT16 | INT4/INT32 | ND | Same as x | Same as x/null | null | null | Same as x/FLOAT (only when x is BFLOAT16)/null | 0 | Same as x | T quantization |
| FLOAT16/BFLOAT16 | INT4/INT32 | ND | Same as x | Same as x/null | null | null | Same as x/FLOAT (only when x is BFLOAT16)/null | pergroup: [32, k-1] and a multiple of 32
Other: 0 | Same as x | C & G quantization |
| FLOAT16/BFLOAT16 | FLOAT4_E2M1/FLOAT | ND | FLOAT8_E8M0 | null | null | null | Same as x/null | 32 | Same as x | MX quantization |
- Value relationships among x, weight, antiquantScale, antiquantOffsetOptional, biasOptional, and antiquantGroupSize:| Scenario Description | X Data Type | Weight Data Type | X Shape | Weight Shape | antiquantScale Shape | antiquantOffsetOptional Shape | biasOptional Shape | antiquantGroupSize | | ------- | -------- | ------------- | ------- | ------------ | -------------------- | ----------------------------- | ------------------ | ------------------ | | T quantization | FLOAT16/BFLOAT16 | INT4/INT32 | (m, k) | (k, n) | (1,) or (1,1) | (1,) or (1,1)/null | (n,) or (1,n)/null | 0 | | C quantization | FLOAT16/BFLOAT16 | INT4/INT32 | (m, k) | (k, n) | (1,n) or (n,) | (1,n) or (n,)/null | (n,) or (1,n)/null | 0 | | G quantization | FLOAT16/BFLOAT16 | INT4/INT32 | (m, k) | (k, n) | (⌈k/group_size⌉, n) | (⌈k/group_size⌉, n)/null | (n,) or (1,n)/null | [32, k-1] and a multiple of 32 | | MX quantization | FLOAT16/BFLOAT16 | FLOAT4_E2M1/FLOAT | (m, k) | (k, n) | (⌈k/32⌉, n) | null | (n,) or (1,n)/null | 32 |
- Description
In addition to [common constraints](#constraints), the other constraints are as follows:
- If the data type of `weight` is INT4 or FLOAT4_E2M1, the last dimension of weight must be 2-aligned. If the data type of `weight` is INT32 or FLOAT, the last dimension of weight must be 8-aligned.
- If the `weight` data type is INT32/FLOAT, it must be converted from INT32/FLOAT to closely-arranged INT4/FLOAT4_E2M1 in conjunction with the `aclnnConvertWeightToINT4Pack` API. For details, see [the sample](./aclnnConvertWeightToINT4Pack.md).
Performance Optimization Suggestions
- pertensor quantization mode: It is recommended to use the transposed
weightinput. - perchannel quantization mode: It is recommended to use the transposed
weightinput. - pergroup quantization mode and MX quantization mode: It is recommended to use the non-transposed
weightinput.
- pertensor quantization mode: It is recommended to use the transposed
Example
The following sample code is for reference only. For details about compilation and execution, see Compile and Run Samples.
Atlas A2 products ,Atlas A3 products ,Ascend 950PR&950DT products :
A16W8 example:
#include <iostream>
#include <memory>
#include <vector>
#include "acl/acl.h"
#include "aclnnop/aclnn_cast.h"
#include "aclnnop/aclnn_weight_quant_batch_matmul_v2.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: 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;
}
void Finalize(int32_t deviceId, aclrtStream stream)
{
aclrtDestroyStream(stream);
aclrtResetDevice(deviceId);
aclFinalize();
}
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 data from the host to the 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;
}
void PrintMat(std::vector<float> resultData, std::vector<int64_t> resultShape)
{
int64_t m = resultShape[0];
int64_t n = resultShape[1];
for (size_t i = 0; i < m; i++) {
printf(i == 0 ? "[[" : " [");
for (size_t j = 0; j < n; j++) {
printf(j == n - 1 ? "%.1f" : "%.1f, ", resultData[i * n + j]);
if (j == 2 && j + 3 < n) {
printf("..., ");
j = n - 4;
}
}
printf(i < m - 1 ? "],\n" : "]]\n");
if (i == 2 && i + 3 < m) {
printf(" ... \n");
i = m - 4;
}
}
}
int AclnnWeightQuantBatchMatmulV2Test(int32_t deviceId, aclrtStream stream)
{
int64_t m = 16;
int64_t k = 32;
int64_t n = 16;
std::vector<int64_t> xShape = {m, k};
std::vector<int64_t> weightShape = {k, n};
std::vector<int64_t> antiquantScaleShape = {n};
std::vector<int64_t> yShape = {m, n};
void* xDeviceAddr = nullptr;
void* weightDeviceAddr = nullptr;
void* antiquantScaleDeviceAddr = nullptr;
void* yDeviceAddr = nullptr;
aclTensor* x = nullptr;
aclTensor* weight = nullptr;
aclTensor* antiquantScale = nullptr;
aclTensor* y = nullptr;
// Fill with FP16 1.0; BF16 1.0 is 0b0011111110000000.
std::vector<uint16_t> xHostData(GetShapeSize(xShape), 0b0011110000000000); // 1.0 in fp16
std::vector<int8_t> weightHostData(GetShapeSize(weightShape), 1);
std::vector<uint16_t> antiquantScaleHostData(GetShapeSize(antiquantScaleShape), 0b0011110000000000);
std::vector<float> yHostData(GetShapeSize(yShape), 0);
// Create the x aclTensor, whose type can be ACL_FLOAT16/ACL_BFLOAT16.
auto ret = CreateAclTensor(xHostData, xShape, &xDeviceAddr, aclDataType::ACL_FLOAT16, &x);
std::unique_ptr<aclTensor, aclnnStatus (*)(const aclTensor*)> xTensorPtr(x, aclDestroyTensor);
std::unique_ptr<void, aclError (*)(void*)> xDeviceAddrPtr(xDeviceAddr, aclrtFree);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// Create the other aclTensor, whose type can be ACL_INT8/ACL_FLOAT8_E8M0/ACL_HIFLOAT8.
ret = CreateAclTensor(weightHostData, weightShape, &weightDeviceAddr, aclDataType::ACL_INT8, &weight);
std::unique_ptr<aclTensor, aclnnStatus (*)(const aclTensor*)> weightTensorPtr(weight, aclDestroyTensor);
std::unique_ptr<void, aclError (*)(void*)> weightDeviceAddrPtr(weightDeviceAddr, aclrtFree);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// Create the y aclTensor, which converts the output back to FP32.
ret = CreateAclTensor(yHostData, yShape, &yDeviceAddr, aclDataType::ACL_FLOAT, &y);
std::unique_ptr<aclTensor, aclnnStatus (*)(const aclTensor*)> yTensorPtr(y, aclDestroyTensor);
std::unique_ptr<void, aclError (*)(void*)> yDeviceAddrPtr(yDeviceAddr, aclrtFree);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// Create the antiquantScale aclTensor.
ret = CreateAclTensor(
antiquantScaleHostData, antiquantScaleShape, &antiquantScaleDeviceAddr, aclDataType::ACL_FLOAT16,
&antiquantScale);
std::unique_ptr<aclTensor, aclnnStatus (*)(const aclTensor*)> antiquantScaleTensorPtr(
antiquantScale, aclDestroyTensor);
std::unique_ptr<void, aclError (*)(void*)> antiquantScaleDeviceAddrPtr(antiquantScaleDeviceAddr, aclrtFree);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// Create the yFp16 aclTensor, the actual output of the computation, with a type consistent with x.
void* yFp16DeviceAddr = nullptr;
aclTensor* yFp16 = nullptr;
ret = CreateAclTensor(yHostData, yShape, &yFp16DeviceAddr, aclDataType::ACL_FLOAT16, &yFp16);
std::unique_ptr<aclTensor, aclnnStatus (*)(const aclTensor*)> yFp16TensorPtr(yFp16, aclDestroyTensor);
std::unique_ptr<void, aclError (*)(void*)> yFp16deviceAddrPtr(yFp16DeviceAddr, aclrtFree);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// 3. Call the CANN operator library API, and change it to the specific API name.
uint64_t workspaceSize = 0;
aclOpExecutor* executor;
void* workspaceAddr = nullptr;
// Call the aclnnWeightQuantBatchMatmulV2 first-phase API.
ret = aclnnWeightQuantBatchMatmulV2GetWorkspaceSize(
x, weight, antiquantScale, nullptr, nullptr, nullptr, nullptr, 0, yFp16, &workspaceSize, &executor);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnWeightQuantBatchMatmulV2GetWorkspaceSize failed. ERROR: %d\n", ret);
return ret);
// Allocate device memory based on the workspaceSize calculated by the first-phase API.
std::unique_ptr<void, aclError (*)(void*)> workspaceAddrPtr(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);
workspaceAddrPtr.reset(workspaceAddr);
}
// Call the second-phase API of aclnnWeightQuantBatchMatmulV2.
ret = aclnnWeightQuantBatchMatmulV2(workspaceAddr, workspaceSize, executor, stream);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnWeightQuantBatchMatmulV2 failed. ERROR: %d\n", ret); return ret);
// 4. (boilerplate) Synchronize and wait for task execution to complete.
ret = aclrtSynchronizeStream(stream);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtSynchronizeStream failed. ERROR: %d\n", ret); return ret);
// Convert the output to FP32.
workspaceSize = 0;
executor = nullptr;
ret = aclnnCastGetWorkspaceSize(yFp16, aclDataType::ACL_FLOAT, y, &workspaceSize, &executor);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnCastGetWorkspaceSize failed. ERROR: %d\n", ret); return ret);
// Allocate device memory based on the workspaceSize calculated by the first-phase API.
void* workspaceCastAddr = nullptr;
std::unique_ptr<void, aclError (*)(void*)> workspaceCastAddrPtr(nullptr, aclrtFree);
if (workspaceSize > 0) {
ret = aclrtMalloc(&workspaceCastAddr, workspaceSize, ACL_MEM_MALLOC_HUGE_FIRST);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("allocate workspace failed. ERROR: %d\n", ret); return ret);
workspaceCastAddrPtr.reset(workspaceCastAddr);
}
ret = aclnnCast(workspaceCastAddr, workspaceSize, executor, stream);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnCast failed. ERROR: %d\n", ret); return ret);
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 it based on 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);
PrintMat(resultData, yShape);
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 = Init(deviceId, &stream);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("Init acl failed. ERROR: %d\n", ret); return ret);
// 2. Construct the inputs and outputs. Customize the construction based on the API definition.
ret = AclnnWeightQuantBatchMatmulV2Test(deviceId, stream);
CHECK_FREE_RET(ret == ACL_SUCCESS, LOG_PRINT("AclnnWeightQuantBatchMatmulV2Test failed. ERROR: %d\n", ret);
return ret);
Finalize(deviceId, stream);
return 0;
}
Ascend 950PR&950DT products :
A16MxFp4 example: the aclnnConvertWeightToINT4Pack API must be called to assist the call:
#include <iostream>
#include <memory>
#include <vector>
#include "acl/acl.h"
#include "aclnnop/aclnn_cast.h"
#include "aclnnop/aclnn_npu_format_cast.h"
#include "aclnnop/aclnn_weight_quant_batch_matmul_v2.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)
template <typename T1>
inline T1 CeilDiv(T1 a, T1 b)
{
return b == 0 ? a : (a + b - 1) / b;
};
template <typename T1>
inline T1 CeilAlign(T1 a, T1 b)
{
return (a + b - 1) / b * b;
};
int64_t GetShapeSize(const std::vector<int64_t>& shape)
{
int64_t shapeSize = 1;
for (auto i : shape) {
shapeSize *= i;
}
return shapeSize;
}
extern "C" aclnnStatus aclnnConvertWeightToINT4PackGetWorkspaceSize(
const aclTensor* weight, const aclTensor* weightInt4Pack, uint64_t* workspaceSize, aclOpExecutor** executor);
extern "C" aclnnStatus aclnnConvertWeightToINT4Pack(
void* workspace, uint64_t workspaceSize, aclOpExecutor* executor, aclrtStream stream);
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 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 the 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 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;
}
template <typename T>
int CreateAclTensorB4(
const std::vector<T>& hostData, const std::vector<int64_t>& shape, void** deviceAddr, aclDataType dataType,
aclTensor** tensor, aclFormat format)
{
auto size = hostData.size() * 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 the 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 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 PrintMat(std::vector<float> resultData, std::vector<int64_t> resultShape)
{
int64_t m = resultShape[0];
int64_t n = resultShape[1];
for (size_t i = 0; i < m; i++) {
printf(i == 0 ? "[[" : " [");
for (size_t j = 0; j < n; j++) {
printf(j == n - 1 ? "%.1f" : "%.1f, ", resultData[i * n + j]);
if (j == 2 && j + 3 < n) {
printf("..., ");
j = n - 4;
}
}
printf(i < m - 1 ? "],\n" : "]]\n");
if (i == 2 && i + 3 < m) {
printf(" ... \n");
i = m - 4;
}
}
}
void Finalize(int32_t deviceId, aclrtStream stream)
{
aclrtDestroyStream(stream);
aclrtResetDevice(deviceId);
aclFinalize();
}
int AclnnWeightQuantBatchMatmulV2Test(int32_t deviceId, aclrtStream& stream)
{
auto ret = Init(deviceId, &stream);
aclDataType weightPackedDtype = aclDataType::ACL_FLOAT; // Optional: ACL_FLOAT type
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("Init acl failed. ERROR: %d\n", ret); return ret);
// 2. Construct the input and output. Customize the construction based on the API.
int64_t m = 16;
int64_t k = 64;
int64_t n = 64;
int64_t groupSize = 32;
int64_t weightDim0 = k;
int64_t weightDim1 = n;
bool isWeightTransposed = false;
std::vector<int64_t> xShape = {m, k};
std::vector<int64_t> weightShape = {k, n};
std::vector<int64_t> antiquantScaleShape = {k / groupSize, n};
std::vector<int64_t> yShape = {m, n};
void* xDeviceAddr = nullptr;
void* weightDeviceAddr = nullptr;
void* weightB4PackDeviceAddr = nullptr;
void* antiquantScaleDeviceAddr = nullptr;
void* yDeviceAddr = nullptr;
aclTensor* x = nullptr;
aclTensor* weight = nullptr;
aclTensor* y = nullptr;
aclTensor* antiquantScale = nullptr;
std::vector<int64_t> weightPackedShape;
weightPackedShape = {weightDim0, weightDim1 / 8};
std::vector<uint16_t> xHostData(GetShapeSize(xShape), 0b0011110000000000); // 1.0 in fp16
xHostData[0] = 0; // 0 in fp16, used to verify whether the result meets the requirement
std::vector<float> weightHostData(GetShapeSize(weightShape), 1.0); // 1.0 in fp32, converted to 1.0 in fp4_e2m1 after int4pack
std::vector<float> yHostData(GetShapeSize(yShape), 0);
std::vector<uint8_t> antiquantScaleHostData(GetShapeSize(antiquantScaleShape), 0b01111111); // 1.0 in fp8_e8m0
// Create the x aclTensor.
ret = CreateAclTensor(xHostData, xShape, &xDeviceAddr, aclDataType::ACL_FLOAT16, &x);
std::unique_ptr<aclTensor, aclnnStatus (*)(const aclTensor*)> xTensorPtr(x, aclDestroyTensor);
std::unique_ptr<void, aclError (*)(void*)> xDeviceAddrPtr(xDeviceAddr, aclrtFree);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// Create the other aclTensor.
ret = CreateAclTensor(weightHostData, weightShape, &weightDeviceAddr, aclDataType::ACL_FLOAT, &weight);
std::unique_ptr<aclTensor, aclnnStatus (*)(const aclTensor*)> weightTensorPtr(weight, aclDestroyTensor);
std::unique_ptr<void, aclError (*)(void*)> weightDeviceAddrPtr(weightDeviceAddr, aclrtFree);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// Create the y aclTensor.
ret = CreateAclTensor(yHostData, yShape, &yDeviceAddr, aclDataType::ACL_FLOAT, &y);
std::unique_ptr<aclTensor, aclnnStatus (*)(const aclTensor*)> yTensorPtr(y, aclDestroyTensor);
std::unique_ptr<void, aclError (*)(void*)> yDeviceAddrPtr(yDeviceAddr, aclrtFree);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// Create the antiquantScale aclTensor.
ret = CreateAclTensor(
antiquantScaleHostData, antiquantScaleShape, &antiquantScaleDeviceAddr, aclDataType::ACL_FLOAT8_E8M0,
&antiquantScale);
std::unique_ptr<aclTensor, aclnnStatus (*)(const aclTensor*)> antiquantScaleTensorPtr(
antiquantScale, aclDestroyTensor);
std::unique_ptr<void, aclError (*)(void*)> antiquantScaleDeviceAddrPtr(antiquantScaleDeviceAddr, aclrtFree);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// Create the yFp16 aclTensor.
void* yFp16DeviceAddr = nullptr;
aclTensor* yFp16 = nullptr;
ret = CreateAclTensor(yHostData, yShape, &yFp16DeviceAddr, aclDataType::ACL_FLOAT16, &yFp16);
std::unique_ptr<aclTensor, aclnnStatus (*)(const aclTensor*)> yFp16TensorPtr(yFp16, aclDestroyTensor);
std::unique_ptr<void, aclError (*)(void*)> yFp16DeviceAddrPtr(yFp16DeviceAddr, aclrtFree);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// 3. Call the CANN operator library API. Change it to the specific API name.
aclFormat weightFormat = aclFormat::ACL_FORMAT_ND;
aclTensor* weightPacked = nullptr;
std::vector<int8_t> weightB4PackHostData(n * k / 2, 0); // One B8 data item stores 2 B4 data items, so divide by 2 here.
// Create the weightInt4Pack aclTensor.
ret = CreateAclTensorB4(
weightB4PackHostData, weightPackedShape, &weightB4PackDeviceAddr, weightPackedDtype, &weightPacked,
weightFormat);
std::unique_ptr<aclTensor, aclnnStatus (*)(const aclTensor*)> weightPackedTensorPtr(weightPacked, aclDestroyTensor);
std::unique_ptr<void, aclError (*)(void*)> weightPackedDeviceAddrPtr(weightB4PackDeviceAddr, aclrtFree);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// Convert weight from int32 to int4pack.
uint64_t workspaceSize = 0;
aclOpExecutor* executor;
ret = aclnnConvertWeightToINT4PackGetWorkspaceSize(weight, weightPacked, &workspaceSize, &executor);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnConvertWeightToINT4PackGetWorkspaceSize failed. ERROR: %d\n", ret);
return ret);
void* workspacePackAddr = nullptr;
std::unique_ptr<void, aclError (*)(void*)> workspacePackAddrPtr(nullptr, aclrtFree);
if (workspaceSize > 0) {
ret = aclrtMalloc(&workspacePackAddr, workspaceSize, ACL_MEM_MALLOC_HUGE_FIRST);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("allocate workspace failed. ERROR: %d\n", ret); return ret);
workspacePackAddrPtr.reset(workspacePackAddr);
}
ret = aclnnConvertWeightToINT4Pack(workspacePackAddr, workspaceSize, executor, stream);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnConvertWeightToINT4Pack failed. ERROR: %d\n", ret); return ret);
// Call the aclnnWeightQuantBatchMatmulV2 first-phase API.
workspaceSize = 0;
executor = nullptr;
ret = aclnnWeightQuantBatchMatmulV2GetWorkspaceSize(
x, weightPacked, antiquantScale, nullptr, nullptr, nullptr, nullptr, groupSize, yFp16, &workspaceSize,
&executor);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnWeightQuantBatchMatmulV2GetWorkspaceSize failed. ERROR: %d\n", ret);
return ret);
// Allocate device memory based on the workspaceSize calculated by the first-phase API.
void* workspaceAddr = nullptr;
std::unique_ptr<void, aclError (*)(void*)> workspaceAddrPtr(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);
workspaceAddrPtr.reset(workspaceAddr);
}
// Call the aclnnWeightQuantBatchMatmulV2 second-phase API.
ret = aclnnWeightQuantBatchMatmulV2(workspaceAddr, workspaceSize, executor, stream);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnWeightQuantBatchMatmulV2 failed. ERROR: %d\n", ret); return ret);
// 4. (boilerplate) Synchronize and wait for the task execution to finish.
ret = aclrtSynchronizeStream(stream);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtSynchronizeStream failed. ERROR: %d\n", ret); return ret);
// Convert the output to FP32.
workspaceSize = 0;
executor = nullptr;
ret = aclnnCastGetWorkspaceSize(yFp16, aclDataType::ACL_FLOAT, y, &workspaceSize, &executor);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnCastGetWorkspaceSize failed. ERROR: %d\n", ret); return ret);
// Allocate device memory based on the workspaceSize calculated by the first-phase API.
void* workspaceCastAddr = nullptr;
std::unique_ptr<void, aclError (*)(void*)> workspaceCastAddrPtr(nullptr, aclrtFree);
if (workspaceSize > 0) {
ret = aclrtMalloc(&workspaceCastAddr, workspaceSize, ACL_MEM_MALLOC_HUGE_FIRST);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("allocate workspace failed. ERROR: %d\n", ret); return ret);
workspaceCastAddrPtr.reset(workspaceCastAddr);
}
ret = aclnnCast(workspaceCastAddr, workspaceSize, executor, stream);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnCast failed. ERROR: %d\n", ret); return ret);
ret = aclrtSynchronizeStream(stream);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtSynchronizeStream failed. ERROR: %d\n", ret); return ret);
// 5. Obtain the output values and copy the result on the device side to the host side. Modify it based on 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);
PrintMat(resultData, yShape);
return ACL_SUCCESS;
}
int main()
{
// 1. (Boilerplate) Initialize the device/stream. For details, see the acl API manual.
// Set deviceId based on the actual device.
int32_t deviceId = 0;
aclrtStream stream;
auto ret = AclnnWeightQuantBatchMatmulV2Test(deviceId, stream);
CHECK_FREE_RET(ret == ACL_SUCCESS, LOG_PRINT("AclnnWeightQuantBatchMatmulV2Test failed. ERROR: %d\n", ret);
return ret);
Finalize(deviceId, stream);
return 0;
}