aclnnQuantMatmulActivationQuant
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: Fused quantized matrix multiplication, activation, and dynamic quantization computation. Currently supports the gelu activation (including gelu_tanh and gelu_erf) and the MX quantization mode. The minimum supported number of input dimensions is 2, and the maximum is 6. Similar APIs include aclnnMm (supports only 2D tensors as matrix multiplication inputs) and aclnnBatchMatMul (supports only 3D matrix multiplication, where the first dimension is the batch dimension). Based on these APIs, this API fuses the gelu activation and dynamic MX quantization to improve hardware computation efficiency.
Formula:
Ascend 950PR&950DT products :Supports the MX quantization mode. For the combinations of input and output data types 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 "aclnnQuantMatmulActivationQuantGetWorkspaceSize" first to obtain the workspace size required for the calculation and the executor that includes the calculation process of the operator, and then call "aclnnQuantMatmulActivationQuant" to perform the calculation.
aclnnStatus aclnnQuantMatmulActivationQuantGetWorkspaceSize(
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 aclnnQuantMatmulActivationQuant(
void *workspace,
uint64_t workspaceSize,
aclOpExecutor *executor,
aclrtStream stream)aclnnQuantMatmulActivationQuantGetWorkspaceSize
Parameters
Note: An optional input refers to an optional quantization parameter, and passing a null pointer is supported.
-
- x2 supports the non-contiguous tensor with the last two axes transposed, while the non-contiguous tensor in other scenarios is 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 x1, x2, x1Scale, x2Scale, yOut, or yScaleOut is a null pointer. ACLNN_ERR_PARAM_INVALID 161002 The data type or data format of x1, x2, biasOptional, x1ScaleOptional, x2Scale, yOut, or yScaleOut is not supported. The shape of x1, x2, biasOptional, x1ScaleOptional, x2Scale, yOut, or yScaleOut does not meet the verification requirements. x1, x2, biasOptional, x1ScaleOptional, x2Scale, yOut, or yScaleOut is an empty tensor. The values of activationType, quantMode, roundMode, scaleAlg, dstTypeMax, groupSize, or transposeX1 are out of the supported range.
aclnnQuantMatmulActivationQuant
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 by the first-phase API aclnnQuantMatmulActivationQuantGetWorkspaceSize. executor Input Op executor that includes the calculation flow of the operator. stream Input Specifies the stream for executing the task. Return value
aclnnStatus: return status code. For details, see aclnn Return Codes.
Constraints
Deterministic computation:
- aclnnQuantMatmulActivationQuant defaults to a deterministic implementation.
-
x1 only supports the ND format, and x2 only supports the ND format.
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.
When transposeX2 is false, the shape of x2 is (batch, k, n). When transposeX2 is true, the shape of x2 is (batch, n, k). Here, batch represents the first 0 to 4 dimensions, and 0 dimension means batch does not exist. k is consistent with k in the shape of x1.
The transpose states of x1 and x2 are determined by both the transpose flag and stride. Changing either one suffices (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 description of the shape when the flag is true above).
- Method 2: Keep the flag as false and pass in the tensor with a transposed view (the shape remains the shape when the flag is false; for example, x2 is (batch, k, n) and the second-to-last dimension of the stride is 1). The API automatically processes the tensor as transposed.
x1Scale and x2Scale do not carry transpose flags. Their shapes must be consistent with the transpose direction of x1 and x2 (x2Scale is (batch, n, ceil(k/64), 2) when transposed and (batch, ceil(k/64), n, 2) when non-transposed).
When the last two dimensions of x1 are equal (m = k) or the last two dimensions of x2 are equal (k = n), transpose is determined by the transposeX1/transposeX2 flags instead of the strides.
x1 supports non-contiguous tensors in the case of the last two axes transpose, but non-contiguous tensors in other use cases are not supported.
x2 supports non-contiguous tensors in the case of the last two axes transpose, but non-contiguous tensors in other use cases are not supported.
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 | | FLOAT8_E5M2 | FLOAT8_E5M2 | FLOAT8_E8M0 | FLOAT8_E8M0 | null/FLOAT32 | FLOAT8_E5M2 | FLOAT8_E8M0 | | FLOAT8_E4M3FN | FLOAT8_E5M2 | FLOAT8_E8M0 | FLOAT8_E8M0 | null/FLOAT32 | FLOAT8_E4M3FN | 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 - Non-transposed: (batch_x1, m, k)
- Non-transposed: (batch_x2, k, n)
- Transposed: (batch_x2, n, k)
- Non-transposed: (batch_x1, m, ceil(k / 64), 2)
- Non-transposed: (batch_x2, ceil(k / 64), n, 2)
- Transposed: (batch_x2, n, ceil(k / 64), 2)
(n,) or (batch_max, 1, n) (batch_max, m, ceil(n / 64), 2) [1, 1, 32] 4295032864 MX full quantization FLOAT8_E5M2 FLOAT8_E4M3FN - Non-transposed: (batch_x1, m, k)
- Non-transposed: (batch_x2, k, n)
- Transposed: (batch_x2, n, k)
- Non-transposed: (batch_x1, m, ceil(k / 64), 2)
- Non-transposed: (batch_x2, ceil(k / 64), n, 2)
- Transposed: (batch_x2, n, ceil(k / 64), 2)
(n,) or (batch_max, 1, n) (batch_max, m, ceil(n / 64), 2) [1, 1, 32] 4295032864 MX full quantization FLOAT8_E5M2 FLOAT8_E5M2 - Non-transposed: (batch_x1, m, k)
- Non-transposed: (batch_x2, k, n)
- Transposed: (batch_x2, n, k)
- Non-transposed: (batch_x1, m, ceil(k / 64), 2)
- Non-transposed: (batch_x2, ceil(k / 64), n, 2)
- Transposed: (batch_x2, n, ceil(k / 64), 2)
(n,) or (batch_max, 1, n) (batch_max, m, ceil(n / 64), 2) [1, 1, 32] 4295032864 MX full quantization FLOAT8_E4M3FN FLOAT8_E5M2 - Non-transposed: (batch_x1, m, k)
- Non-transposed: (batch_x2, k, n)
- Transposed: (batch_x2, n, k)
- Non-transposed: (batch_x1, m, ceil(k / 64), 2)
- Non-transposed: (batch_x2, ceil(k / 64), n, 2)
- Transposed: (batch_x2, n, ceil(k / 64), 2)
(n,) or (batch_max, 1, n) (batch_max, m, ceil(n / 64), 2) [1, 1, 32] 4295032864 MX full quantization FLOAT4_E2M1 FLOAT4_E2M1 - non-transposed: (batch_x1, m, k)
- transposed: (batch_x1, k, m)
- Non-transposed: (batch_x2, k, n)
- Transposed: (batch_x2, n, k)
- non-transposed: (batch_x1, m, ceil(k / 64), 2)
- transposed: (batch_x1, ceil(k / 64), m, 2)
- Non-transposed: (batch_x2, ceil(k / 64), n, 2)
- Transposed: (batch_x2, n, ceil(k / 64), 2)
(n,) or (batch_max, 1, n) (batch_max, m, ceil(n / 64), 2) [1, 1, 32] 4295032864 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):
- 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 sample code below is for reference only. For details about the compilation and execution process, see Compile and Run Samples.
x1 is FLOAT8_E4M3FN, x2 is FLOAT8_E4M3FN (ND format), x1Scale is FLOAT8_E8M0, x2Scale is FLOAT8_E8M0, activation is gelu_tanh, and scaleAlg is 0 (scenario 1).
#include <iostream>
#include <memory>
#include <cmath>
#include <vector>
#include "acl/acl.h"
#include "aclnnop/aclnn_quant_matmul_activation_quant.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 code: 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 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 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);
// Calculate the strides of the contiguous tensor.
std::vector<int64_t> strides(shape.size(), 1);
for (int64_t i = shape.size() - 2; i >= 0; i--) {
strides[i] = shape[i + 1] * strides[i + 1];
}
// Call the aclCreateTensor API to create an aclTensor.
*tensor = aclCreateTensor(shape.data(), shape.size(), dataType, strides.data(), 0, aclFormat::ACL_FORMAT_ND,
shape.data(), shape.size(), *deviceAddr);
return 0;
}
void Finalize(int32_t deviceId, aclrtStream stream)
{
aclrtDestroyStream(stream);
aclrtResetDevice(deviceId);
aclFinalize();
}
int AclnnQuantMatmulActivationQuantTest(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. Customize the construction based on the API.
int64_t m = 5;
int64_t k = 64;
int64_t n = 128;
bool transposeX1 = false;
bool transposeX2 = false;
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 = {k, n};
std::vector<int64_t> x1ScaleShape = {m, (k + MX_SCALE_BLOCK_SIZE - 1) / MX_SCALE_BLOCK_SIZE, 2};
std::vector<int64_t> x2ScaleShape = {(k + MX_SCALE_BLOCK_SIZE - 1) / MX_SCALE_BLOCK_SIZE, n, 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(k * n, 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((k + MX_SCALE_BLOCK_SIZE - 1) / MX_SCALE_BLOCK_SIZE * n * 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 x1 aclTensor.
ret = CreateAclTensor(x1HostData, x1Shape, &x1DeviceAddr, aclDataType::ACL_FLOAT8_E4M3FN, &x1);
std::unique_ptr<aclTensor, aclnnStatus (*)(const aclTensor*)> x1TensorPtr(x1, aclDestroyTensor);
std::unique_ptr<void, aclError (*)(void*)> x1DeviceAddrPtr(x1DeviceAddr, aclrtFree);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// Create x2 aclTensor.
ret = CreateAclTensor(x2HostData, x2Shape, &x2DeviceAddr, aclDataType::ACL_FLOAT8_E4M3FN, &x2);
std::unique_ptr<aclTensor, aclnnStatus (*)(const aclTensor*)> x2TensorPtr(x2, aclDestroyTensor);
std::unique_ptr<void, aclError (*)(void*)> x2DeviceAddrPtr(x2DeviceAddr, aclrtFree);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// Create x1Scale aclTensor.
ret = CreateAclTensor(x1ScaleHostData, x1ScaleShape, &x1ScaleDeviceAddr, aclDataType::ACL_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. Change it to the specific API name.
uint64_t workspaceSize = 0;
aclOpExecutor* executor = nullptr;
int64_t groupSizeValue = 4295032864;
char activationType[] = "gelu_tanh";
char quantMode[] = "mx";
char roundMode[] = "rint";
ret = aclnnQuantMatmulActivationQuantGetWorkspaceSize(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("aclnnQuantMatmulActivationQuantGetWorkspaceSize 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 second-phase API of aclnnQuantMatmulActivationQuant
ret = aclnnQuantMatmulActivationQuant(workspaceAddr, workspaceSize, executor, stream);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnQuantMatmulActivationQuant failed. ERROR: %d\n", ret); return ret);
// 4. (Boilerplate) Wait synchronously 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 values, copy the result from device memory to host memory, and modify it as required by 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 device/stream. For details, see the acl API documentation.
// Set deviceId based on the actual device.
int32_t deviceId = 0;
aclrtStream stream;
auto ret = AclnnQuantMatmulActivationQuantTest(deviceId, stream);
CHECK_FREE_RET(ret == ACL_SUCCESS, LOG_PRINT("AclnnQuantMatmulActivationQuantTest failed. ERROR: %d\n", ret);
return ret);
Finalize(deviceId, stream);
return 0;
}