aclnnQuantMatmulActivationQuantWeightNz
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: Fuses quantized matrix multiplication, activation, and dynamic quantization computation. Currently supports gelu activation (including gelu_tanh and gelu_erf) and MX quantization mode. The minimum supported input dimension is 2 and the maximum is 6. Similar APIs include aclnnMm (matrix multiplication that supports only 2D tensors as input) and aclnnBatchMatMul (matrix multiplication that supports only three dimensions, where the first dimension is the batch dimension). This API fuses gelu activation and dynamic MX quantization on top of the other APIs to improve hardware computing efficiency.
Formula:
Ascend 950PR&950DT products :Supports MX quantization mode. For the input and output data type combinations corresponding to different quantization modes, see Constraints.
QuantMatmul MX quantization mode
where gsM, gsN, and gsK represent groupSizeM, groupSizeN, and groupSizeK, respectively; x1Slice represents the vector with a length of groupSizeK in row m of x1, and x2Slice represents the vector with a length of groupSizeK in column n of x2; both are sliced along the K axis starting from j*groupSizeK, j takes values in the range [0, kLoops), kLoops = ceil(K / groupSizeK), and K is the length of the K axis; supports the last slice with a length less than groupSizeK. bias is included only in MX quantization mode.
Activation Formula
gelu_tanh (high-performance approximation):
gelu_erf:
Dynamic Quantization Formula
Scenario 1, when scaleAlg is 0:
- The input activationOut is grouped along the last axis by values, and each group of k values is dynamically quantized into
The quantized values form the output yOut according to the corresponding positions of , and mxscale is output as yScaleOut for each group along the last axis.
emax: The exponent of the maximum normal number of the corresponding data type.
DataType Emax FLOAT4_E2M1 2 FLOAT8_E4M3FN 8 FLOAT8_E5M2 15
Scenario 2: When scaleAlg is 1, only FP8 types are involved:
The input activationOut is divided into blocks of elements along the tail axis, and a block scale factor is computed for each block separately. All elements in the block are then mapped to the target low-precision type FP8 using the same . If the last block contains fewer than elements, the missing values are treated as 0 and the block is processed as a complete block.
Find the maximum absolute value in the block:
Map FP32 to within the range representable by the target data type FP8, where is the maximum value representable by the target precision:
Convert the block scale factor to the representable scale value in FP8 format.
Extract the unbiased exponent and mantissa from the block floating-point scale factor .
To ensure no overflow during quantization, round up the exponent and keep it within the representable range of FP8:
Calculate the block scale factor:
Calculate the block conversion factor:
Apply to the final quantization step. For each element within a block, . The final quantized output is , where represents the block scale factor, i.e., , and represents the quantized data within the block.
Use case 3: when scaleAlg is 2, only the FP4_E2M1 type is involved:
- When dstTypeMax = 0.0/6.0/7.0:
- The input x is grouped along the axis dimension in groups of k = blocksize elements, and each group of k numbers is dynamically quantized to , k = blocksize:
- The quantized are combined into the output yOut according to the positions of the corresponding , and mxscale is combined into the output mxscaleOut according to the corresponding groupings along the axis dimension.
- When dstTypeMax != 0.0/6.0/7.0:
- The long vector is divided into blocks, each with a length of k. A block scale factor is computed separately for each block, and then all elements in the block are mapped to the target low-precision type using the same . If the last block has fewer than k elements, the missing values are treated as 0, and the block is processed as a complete one.
- Find the maximum absolute value in the block:
- Map FP32 to within the range representable by the target data type, where if dst_max_value=0, is the maximum value representable by the target precision; if dst_max_value!=0, is the value passed in for dst_max_value.
- Convert the block quantization scale factor to a scale value representable in the FP8 format.
- Extract the unbiased exponent and the mantissa from the floating-point quantization scale factor of the block.
- To ensure no overflow during quantization, round up the exponent and keep it within the representable range of FP8:
- Calculate the block scale factor:
- Calculate the block conversion factor:
- Apply to the final quantization step. For each element within a block, . The final quantized output is , where represents the block scale factor, i.e., , and represents the quantized data within the block.
- The quantized are combined into the output yOut according to the positions of the corresponding , and mxscale is combined into the output mxscaleOut according to the corresponding groupings along the axis dimension.
- When dstTypeMax = 0.0/6.0/7.0:
Function Prototype
Each operator uses a two-phase API. Call the "aclnnQuantMatmulActivationQuantWeightNzGetWorkspaceSize" API first to obtain the workspace size required for the computation and the executor that contains the operator computation process, and then call the "aclnnQuantMatmulActivationQuantWeightNz" API to execute the computation.
aclnnStatus aclnnQuantMatmulActivationQuantWeightNzGetWorkspaceSize(
const aclTensor *x1,
const aclTensor *x2,
const aclTensor *x1ScaleOptional,
const aclTensor *x2Scale,
const aclTensor *biasOptional,
bool transposeX1,
bool transposeX2,
int64_t groupSize,
char *activationType,
char *quantMode,
char *roundMode,
int64_t scaleAlg,
double dstTypeMax,
aclTensor *yOut,
aclTensor *yScaleOut,
uint64_t *workspaceSize,
aclOpExecutor **executor)aclnnStatus aclnnQuantMatmulActivationQuantWeightNz(
void *workspace,
uint64_t workspaceSize,
aclOpExecutor *executor,
aclrtStream stream)aclnnQuantMatmulActivationQuantWeightNzGetWorkspaceSize
Parameters
Note: An optional input refers to an optional quantization parameter, and passing a null pointer is supported.
-
- x2 supports the non-contiguous tensor in the case where the last two axes are transposed. Non-contiguous tensors in other scenarios are not supported.
- Passing a non-zero value for groupSize is supported.
Return value
aclnnStatus: return status code. For details, see aclnn Return Codes.
The first-phase API performs input parameter validation and returns an error in the following scenarios:
Return Value Error Code Description ACLNN_ERR_PARAM_NULLPTR 161001 The input x1, x2, x1Scale, x2Scale, yOut, or yScaleOut is a null pointer. ACLNN_ERR_PARAM_INVALID 161002 The data type and data format of x1, x2, biasOptional, x1ScaleOptional, x2Scale, yOut, or yScaleOut are not within the supported range. The shape of x1, x2, biasOptional, x1ScaleOptional, x2Scale, yOut, or yScaleOut does not meet the validation conditions. x1, x2, biasOptional, x1ScaleOptional, x2Scale, yOut, or yScaleOut is an empty tensor. The values of activationType, quantMode, roundMode, scaleAlg, dstTypeMax, groupSize, and transposeX1 are not within the supported range.
aclnnQuantMatmulActivationQuantWeightNz
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 calling the first-phase API aclnnQuantMatmulActivationQuantWeightNzGetWorkspaceSize. executor Input Op executor. 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:
- aclnnQuantMatmulActivationQuantWeightNz defaults to a deterministic implementation.
-
x1 only supports the ND format, and x2 only supports the NZ format.
When k or n is 1, the weightNz feature cannot be used. This API does not support this use case.
Before calling this API, aclnnTransMatmulWeight or aclnnNpuFormatCast can be called to convert x2 in ND format to the NZ format. When using the converted x2, pad it with 0s to prevent dirty data from being introduced.
When transposeX1 is false, the shape of x1 is (batch, m, k). When transposeX1 is true, the shape of x1 is (batch, k, m). Here, batch represents the first 0 to 4 dimensions, where 0 dimension indicates that batch does not exist.
Shape of x2 when transposeX2 is false: (batch, n1, k1, k0, n0). Shape of x2 when transposeX2 is true: (batch, k1, n1, n0, k0). batch represents the preceding 0-4 dimensions, and 0 indicates that batch does not exist. k is the same as k in the shape of x1.
The transpose states of x1 and x2 are determined by both the transpose flags and strides. Changing either one is sufficient (the two methods are equivalent; do not use them together):
- Method 1: Set the corresponding flag transposeX1/transposeX2 to true and pass in the shape after transposition (see the preceding description of the shape when the flag is true).
- Method 2: Keep the flag as false and pass in the tensor as a transposed view (the shape remains the shape for false, for example, x2 is (batch, k, n) with the second-to-last dimension of the stride being 1). The API automatically processes the tensor as transposed.
x1Scale and x2Scale do not carry transposition flags. Their shapes must be consistent with the transposition states of x1 and x2 (when transposed, x2Scale is (batch, n, ceil(k/64), 2); when non-transposed, it is (batch, ceil(k/64), n, 2)).
When the last two dimensions of x1 are equal (m = k) or the last two dimensions of x2 are equal (k = n), determine the transposition state based on the transposeX1/transposeX2 flags instead of the stride.
x1 supports a non-contiguous tensor with the last two axes transposed. A non-contiguous tensor in other use cases is not supported.
x2 supports a non-contiguous tensor with the last two axes transposed. A non-contiguous tensor in other use cases is not supported.
If the data type of x1 is FLOAT8_E5M2, the data type of x2 must be FLOAT8_E4M3FN.
bias-related constraints:
- Optional parameter. Passing in a null pointer is supported, but an empty tensor is not supported.
- The data type must be FLOAT32.
- The shape can be 1D (n,) or 3D (batch, 1, n), where n is the same as n in x2.
- If y has a 2D, 4D, 5D, or 6D shape, the shape of bias only supports 1D (n,).
Constraints on groupSize:
- Takes effect only in the MX quantization mode.
- The input groupSize is internally decomposed into groupSizeM, groupSizeN, and groupSizeK according to the following formula. Currently, only [0, 0, 0] or [1, 1, 32] is supported, and [0, 0, 0] is automatically deduced as [1, 1, 32].
The shape of y supports 2-6 dimensions, in the format of (batch, m, n). batch may not exist. m must be the same as the m of x1, and n must be the same as the n of x2.
MX quantization use case constraints: - The input and output support the following data type combinations:
| x1 | x2 | x1Scale | x2Scale | Bias | y | yScale | |---------------|---------------|-------------|-------------|--------------|---------------------------|-------------| | FLOAT8_E4M3FN | FLOAT8_E4M3FN | FLOAT8_E8M0 | FLOAT8_E8M0 | null/FLOAT32 | FLOAT8_E4M3FN | FLOAT8_E8M0 | | FLOAT8_E5M2 | FLOAT8_E4M3FN | FLOAT8_E8M0 | FLOAT8_E8M0 | null/FLOAT32 | FLOAT8_E5M2 | FLOAT8_E8M0 | | FLOAT4_E2M1 | FLOAT4_E2M1 | FLOAT8_E8M0 | FLOAT8_E8M0 | null/FLOAT32 | FLOAT4_E2M1 | FLOAT8_E8M0 |
- Relationship among the x1 data type, x2 data type, x1, x2, x1Scale, x2Scale, and groupSize:| Quantization Type | x1 Data Type | x2 Data Type | x1 Shape | x2 Shape | x1Scale Shape | x2Scale Shape | Bias Shape | yScale Shape | [gsM, gsN, gsK] | groupSize | |-------|--------|--------|--------|--------|-------------|-------------|------------|---------------------------------------|--|--| |MX full quantization|FLOAT8_E4M3FN|FLOAT8_E4M3FN|
- Note: In the table above, gsM, gsK, and gsN represent groupSizeM, groupSizeK, and groupSizeN, respectively.
- In the MX quantization use case, the transpose attribute of x1 must be consistent with that of x1Scale, and the transpose attribute of x2 must be consistent with that of x2Scale.
- The data type of yOut is determined by the data type of x1, and the two must be the same.
- MXFP4 use case constraints (the data types of x1, x2, and y are all FLOAT4_E2M1):
- x1 does not support transposition, that is, transposeX1 cannot be set to true.
- scaleAlg only supports values 0 and 2.
- If scaleAlg is 2, dstTypeMax supports values 0.0 and 6.0-12.0.
- roundMode supports {"rint", "floor", "round"}.
- The inner axes of x1 and x2 must be even, and k must be greater than 2.
- The N dimension of y must be even.Example
The following sample code is for reference only. For details about compilation and execution, see Compile and Run Samples.
x1 is FLOAT8_E4M3FN, x2 is FLOAT8_E4M3FN (NZ format), x1Scale is FLOAT8_E8M0, x2Scale is FLOAT8_E8M0, the activation function is gelu_tanh, and scaleAlg is 0 (use case 1).
#include <iostream>
#include <memory>
#include <cmath>
#include <vector>
#include "acl/acl.h"
#include "aclnnop/aclnn_cast.h"
#include "aclnnop/aclnn_quant_matmul_activation_quant_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 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 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 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());
std::unique_ptr<const aclIntArray, aclnnStatus (*)(const aclIntArray*)> mat2SizePtr(mat2Size, aclDestroyIntArray);
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 allocate device memory (aligned size)
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 only the original ND data
auto originalSize = static_cast<size_t>(GetShapeSize(shape) * sizeof(T));
ret = aclrtMemcpy(*deviceAddr, originalSize, hostData.data(), originalSize, ACL_MEMCPY_HOST_TO_DEVICE);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtMemcpy failed. ERROR: %d\n", ret); return ret);
// Clear the remaining area to prevent dirty data
if (size > originalSize) {
ret = aclrtMemset(static_cast<uint8_t*>(*deviceAddr) + originalSize, size - originalSize, 0, size - originalSize);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtMemset 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];
}
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 AclnnQuantMatmulWeightNzActivationQuantTest(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 the inputs and outputs, which need to be custom-built according to the API.
int64_t m = 5;
int64_t k = 64;
int64_t n = 128;
bool transposeX1 = false;
bool transposeX2 = true;
constexpr int64_t MX_SCALE_BLOCK_SIZE = 64; // Scale block alignment size, used to calculate the scale shape.
std::vector<int64_t> x1Shape = {m, k};
std::vector<int64_t> x2Shape = {n, k};
std::vector<int64_t> x1ScaleShape = {m, (k + MX_SCALE_BLOCK_SIZE - 1) / MX_SCALE_BLOCK_SIZE, 2};
std::vector<int64_t> x2ScaleShape = {n, (k + MX_SCALE_BLOCK_SIZE - 1) / MX_SCALE_BLOCK_SIZE, 2};
std::vector<int64_t> outShape = {m, n};
std::vector<int64_t> outScaleShape = {m, (n + MX_SCALE_BLOCK_SIZE - 1) / MX_SCALE_BLOCK_SIZE, 2};
void* x1DeviceAddr = nullptr;
void* x2DeviceAddr = nullptr;
void* x1ScaleDeviceAddr = nullptr;
void* x2ScaleDeviceAddr = nullptr;
void* outDeviceAddr = nullptr;
void* outScaleDeviceAddr = nullptr;
aclTensor* x1 = nullptr;
aclTensor* x2 = nullptr;
aclTensor* x1Scale = nullptr;
aclTensor* x2Scale = nullptr;
aclTensor* bias = nullptr;
aclTensor* out = nullptr;
aclTensor* outScale = nullptr;
std::vector<uint8_t> x1HostData(m * k, 0b00111000); // 1.0 in float8_e4m3.
std::vector<uint8_t> x2HostData(n * k, 0b00111000); // 1.0 in float8_e4m3.
std::vector<uint8_t> x1ScaleHostData(m * (k + MX_SCALE_BLOCK_SIZE - 1) / MX_SCALE_BLOCK_SIZE * 2, 0b01111111); // 1.0 in float8_e8m0.
std::vector<uint8_t> x2ScaleHostData(n * (k + MX_SCALE_BLOCK_SIZE - 1) / MX_SCALE_BLOCK_SIZE * 2, 0b01111111); // 1.0 in float8_e8m0.
std::vector<uint8_t> outHostData(m * n, 0);
std::vector<uint8_t> outScaleHostData(m * (n + MX_SCALE_BLOCK_SIZE - 1) / MX_SCALE_BLOCK_SIZE * 2, 0);
// 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 in the AI processor-affine data layout format.
ret = CreateAclTensorX2(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_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 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 out aclTensor.
ret = CreateAclTensor(outHostData, outShape, &outDeviceAddr, aclDataType::ACL_FLOAT8_E4M3FN, &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);
// Create mxscale aclTensor.
ret = CreateAclTensor(outScaleHostData, outScaleShape, &outScaleDeviceAddr, aclDataType::ACL_FLOAT8_E8M0,
&outScale);
std::unique_ptr<aclTensor, aclnnStatus (*)(const aclTensor*)> outScaleTensorPtr(outScale, aclDestroyTensor);
std::unique_ptr<void, aclError (*)(void*)> outScaleDeviceAddrPtr(outScaleDeviceAddr, aclrtFree);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// 3. Call the CANN operator library API, and replace it with the specific API name.
uint64_t workspaceSize = 0;
aclOpExecutor* executor = 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);
// Allocate device memory according to the workspaceSize calculated by the first-phase API.
void* workspaceTransAddr = nullptr;
std::unique_ptr<void, aclError (*)(void*)> workspaceTransAddrPtr(nullptr, aclrtFree);
if (workspaceSize > 0) {
ret = aclrtMalloc(&workspaceTransAddr, workspaceSize, ACL_MEM_MALLOC_HUGE_FIRST);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("allocate workspace failed. ERROR: %d\n", ret); return ret);
workspaceTransAddrPtr.reset(workspaceTransAddr);
}
// Call the second-phase API of aclnnTransMatmulWeight.
ret = aclnnTransMatmulWeight(workspaceTransAddr, workspaceSize, executor, stream);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnTransMatmulWeight failed. ERROR: %d\n", ret); return ret);
workspaceSize = 0;
executor = nullptr;
int64_t groupSizeValue = 4295032864;
char activationType[] = "gelu_tanh";
char quantMode[] = "mx";
char roundMode[] = "rint";
ret = aclnnQuantMatmulActivationQuantWeightNzGetWorkspaceSize(
x1, x2, x1Scale, x2Scale, bias, transposeX1, transposeX2, groupSizeValue, activationType, quantMode, roundMode,
0, 0.0, out, outScale, &workspaceSize, &executor);
CHECK_RET(ret == ACL_SUCCESS,
LOG_PRINT("aclnnQuantMatmulActivationQuantWeightNzGetWorkspaceSize failed. ERROR: %d\n", ret);
return ret);
// Allocate device memory according to 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 second-phase API of aclnnQuantMatmulActivationQuantWeightNz.
ret = aclnnQuantMatmulActivationQuantWeightNz(workspaceAddr, workspaceSize, executor, stream);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnQuantMatmulActivationQuantWeightNz failed. ERROR: %d\n", ret);
return ret);
// 4. (Boilerplate) Synchronously wait for the 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 device memory to the host side. Modify it according to the specific API definition.
auto size = GetShapeSize(outShape);
std::vector<uint8_t> resultData(size, 0);
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: %d\n", i, resultData[i]);
}
size = GetShapeSize(outScaleShape);
std::vector<uint8_t> scaleData(size, 0);
ret = aclrtMemcpy(scaleData.data(), scaleData.size() * sizeof(scaleData[0]), outScaleDeviceAddr,
size * sizeof(scaleData[0]), ACL_MEMCPY_DEVICE_TO_HOST);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("copy scale result from device to host failed. ERROR: %d\n", ret);
return ret);
for (int64_t i = 0; i < size; i++) {
LOG_PRINT("scale[%ld] is: %d\n", i, scaleData[i]);
}
return ACL_SUCCESS;
}
int main()
{
// 1. (Boilerplate) Initialize the device/stream. For details, see the acl API documentation.
// Set deviceId based on the actual device in use.
int32_t deviceId = 0;
aclrtStream stream;
auto ret = AclnnQuantMatmulWeightNzActivationQuantTest(deviceId, stream);
CHECK_FREE_RET(ret == ACL_SUCCESS,
LOG_PRINT("AclnnQuantMatmulWeightNzActivationQuantTest failed. ERROR: %d\n", ret);
return ret);
Finalize(deviceId, stream);
return 0;
}