aclnnDynamicQuantV2
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 : Supported
Function
Description: Performs per-token symmetric/asymmetric dynamic quantization on the input tensor. In MOE scenarios, the smoothScalesOptional of each expert is different and is distinguished based on the input groupIndexOptional.
Formula:
Symmetric quantization:
If smoothScalesOptional is not provided:
If smoothScalesOptional is provided:
Asymmetric quantization:
If smoothScalesOptional is not provided:
If smoothScalesOptional is provided:
where row_max denotes the maximum value of each row, row_min denotes the minimum value of each row, dtypeMax is the maximum value of the output data type, and dtypeMin is the minimum value of the output data type.
Function Prototype
Each operator uses a two-phase API. You must first call the "aclnnDynamicQuantV2GetWorkspaceSize" API to obtain the workspace size required for computation and the executor containing the operator computation process, and then call the "aclnnDynamicQuantV2" API to perform computation.
aclnnStatus aclnnDynamicQuantV2GetWorkspaceSize(
const aclTensor *x,
const aclTensor *smoothScalesOptional,
const aclTensor *groupIndexOptional,
int64_t dstType,
const aclTensor *yOut,
const aclTensor *scaleOut,
const aclTensor *offsetOut,
uint64_t *workspaceSize,
aclOpExecutor **executor)aclnnStatus aclnnDynamicQuantV2(
void *workspace,
uint64_t workspaceSize,
aclOpExecutor *executor,
aclrtStream stream)aclnnDynamicQuantV2GetWorkspaceSize
Parameters:
Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor x (aclTensor*) Input Tensor of the operator input. Corresponds to `x` in the corresponding formula. - Supports empty tensors.
FLOAT16, BFLOAT16 ND Greater than 1 dimension √ smoothScalesOptional (aclTensor*) Input smoothScales of the operator input. Corresponds to `smoothScalesOptional` in the corresponding formula description. - Supports empty tensors.
- The data type must be the same as that of x.
- If groupIndexOptional is not specified, the shape dimension is the same as the last dimension of x. If groupIndexOptional is specified, the shape has two dimensions, where the first dimension is the number of experts (not exceeding 1024) and the second dimension is the last dimension of x.
FLOAT16, BFLOAT16 ND 2 √ groupIndexOptional (aclTensor*) Input The groupIndex of the operator input. - Supports empty tensors.
- The shape supports only one dimension, and the dimension size equals the first dimension of smoothScalesOptional.
- If groupIndexOptional is not nullptr, smoothScalesOptional must not be nullptr.
INT32 ND 1 √ dstType(int64_t) Input Enum value corresponding to the type of output y. - The value is 2 if the type of output y is INT8, 29 if the type of y is INT4, and 3 if the type of y is INT32.
- - - - yOut (aclTensor*) Output Quantized output tensor. Corresponds to `yOut` in the corresponding formula. - Supports empty tensors.
- When the type is INT32, the last dimension of the shape is 1/8 of the last dimension of x, and the other dimensions are the same as those of x. For other types, the shape is the same as that of x.
INT4, INT8, INT32, FLOAT8_E4M3FN, FLOAT8_E5M2, HIFLOAT8 ND Greater than 1 dimension - scaleOut (aclTensor*) Output Scale used for quantization. `scaleOut` in the corresponding formula. - Supports empty tensors.
- Shape is the shape of x with the last dimension removed.
FLOAT32 ND Greater than 0 dimensions - offsetOut(aclTensor*) Output Offset used for quantization. `offset` in the corresponding formula. - Empty tensors are supported.
- The shape dimension is the shape of x with the last dimension removed.
FLOAT32 ND Greater than 0 dimensions - workspaceSize (uint64_t*) Output Returns the workspace size to be applied for on the Device. - - - - - executor (aclOpExecutor**) Output Returns the op executor containing the operator computation flow. - - - - - Atlas A2 products ,Atlas A3 products : The data type of output parameteryOutonly supports INT4, INT8, and INT32.
Atlas inference products ,Atlas training products :- The input parameter
xonly supports FLOAT16. - The input parameters
smoothScalesOptionalandgroupIndexOptionalare reserved parameters and do not participate in computation in the current version. - The input parameter
dstTypeonly supports being set to 2. - The output parameter
yOutonly supports INT8.
- The input parameter
Return Value
aclnnStatus: return status code. For details, see aclnn Error Codes.
The first-phase API performs input parameter validation and returns an error in the following scenarios:
Error Code Error Code Description ACLNN_ERR_PARAM_NULLPTR 161001 The input parameter x or yOut is a null pointer. ACLNN_ERR_PARAM_INVALID 161002 The data type, data format, or dimension of the parameters is out of the supported range. When the data type of yOut is INT4, the last dimension of x or yOut is not an even number. When the data type of yOut is INT32, the last dimension of x is not divisible by 8. ACLNN_ERR_INNER_CREATE_EXECUTOR 561001 Failed to create aclOpExecutor internally.
aclnnDynamicQuantV2
Parameters:
Parameter Input/Output Description workspace Input Pointer to the workspace memory allocated on the Device. workspaceSize Input Size of the workspace memory allocated on the Device, obtained by calling the first-phase API aclnnDynamicQuantV2GetWorkspaceSize. executor Input Op executor that contains the operator computation flow. stream Input Stream for executing tasks. Return Value
aclnnStatus: return status code. For details, see aclnn Error Codes.
Constraints
Atlas A2 products ,Atlas A3 products ,Ascend 950PR&950DT products :- If the data type of
yOutis INT4, the last dimensions ofxandyOutmust be divisible by 2. - If the data type of
yOutis INT32, the last dimension ofxmust be divisible by 8. - When groupIndexOptional is used, the number of experts must not exceed the product of all dimensions of x after removing the last dimension. The values of groupIndexOptional must form a non-decreasing array of values not less than zero, and the last value must be equal to the product of all dimensions of x after removing the last dimension. If this condition is not met, the result is meaningless.
- If the data type of
Atlas inference products ,Atlas training products : The last dimension of input x must be divisible by 32. Only symmetric quantization is supported temporarily, and the BFLOAT16 data type is not supported.
- Deterministic computation:
- aclnnDynamicQuantV2 defaults to a deterministic implementation.
Example
The sample code is for reference only. For details about compilation and execution, see Compile and Run Samples.
#include <iostream>
#include <vector>
#include "acl/acl.h"
#include "aclnnop/aclnn_dynamic_quant_v2.h"
#define CHECK_RET(cond, return_expr) \
do { \
if (!(cond)) { \
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;
}
void PrintOutResult(std::vector<int64_t>& shape, void** deviceAddr)
{
auto size = GetShapeSize(shape);
std::vector<int8_t> resultData(size, 0);
auto ret = aclrtMemcpy(resultData.data(), resultData.size() * sizeof(resultData[0]), *deviceAddr,
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);
for (int64_t i = 0; i < size; i++) {
LOG_PRINT("result[%ld] is: %d\n", i, resultData[i]);
}
}
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;
}
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 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;
}
int main()
{
// 1. (Boilerplate) Device/stream initialization. For details, see the acl API documentation.
// 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 inputs and outputs based on the API definitions.
int rowNum = 4;
int rowLen = 32;
int groupNum = 4;
std::vector<int64_t> xShape = {4, 32};
std::vector<int64_t> smoothShape = {groupNum, rowLen};
std::vector<int64_t> groupShape = {groupNum};
std::vector<int64_t> yShape = {4, 32};
std::vector<int64_t> scaleShape = {4};
std::vector<int64_t> offsetShape = {4};
void* xDeviceAddr = nullptr;
void* smoothDeviceAddr = nullptr;
void* groupDeviceAddr = nullptr;
void* yDeviceAddr = nullptr;
void* scaleDeviceAddr = nullptr;
void* offsetDeviceAddr = nullptr;
aclTensor* x = nullptr;
aclTensor* smooth = nullptr;
aclTensor* group = nullptr;
aclTensor* y = nullptr;
aclTensor* scale = nullptr;
aclTensor* offset = nullptr;
std::vector<float> xHostData;
std::vector<float> smoothHostData;
// groupIndex stores the cumulative number of rows handled by each expert. The last element must equal the total number of rows in x.
std::vector<int32_t> groupHostData = {1, 2, 3, rowNum};
std::vector<int8_t> yHostData;
std::vector<float> scaleHostData;
std::vector<float> offsetHostData;
for (int i = 0; i < rowNum; ++i) {
for (int j = 0; j < rowLen; ++j) {
float value1 = i * rowLen + j;
xHostData.push_back(aclFloatToFloat16(value1));
yHostData.push_back(0);
}
scaleHostData.push_back(0);
offsetHostData.push_back(0);
}
for (int m = 0; m < groupNum; ++m) {
for (int n = 0; n < rowLen; ++n) {
float value2 = m * rowLen + n;
smoothHostData.push_back(aclFloatToFloat16(value2));
}
}
// Create x aclTensor.
ret = CreateAclTensor(xHostData, xShape, &xDeviceAddr, aclDataType::ACL_FLOAT16, &x);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// Create smooth aclTensor.
ret = CreateAclTensor(smoothHostData, smoothShape, &smoothDeviceAddr, aclDataType::ACL_FLOAT16, &smooth);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// Create group aclTensor.
ret = CreateAclTensor(groupHostData, groupShape, &groupDeviceAddr, aclDataType::ACL_INT32, &group);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// Create y aclTensor.
ret = CreateAclTensor(yHostData, yShape, &yDeviceAddr, aclDataType::ACL_INT8, &y);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// Create scale aclTensor.
ret = CreateAclTensor(scaleHostData, scaleShape, &scaleDeviceAddr, aclDataType::ACL_FLOAT, &scale);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// Create offset aclTensor.
ret = CreateAclTensor(offsetHostData, offsetShape, &offsetDeviceAddr, aclDataType::ACL_FLOAT, &offset);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// 3. Call the CANN operator library API. Replace it with the actual API name.
uint64_t workspaceSize = 0;
aclOpExecutor* executor;
// Call the first-phase API of aclnnDynamicQuantV2.
ret = aclnnDynamicQuantV2GetWorkspaceSize(x, smooth, group, 2, y, scale, offset, &workspaceSize, &executor);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnDynamicQuantV2GetWorkspaceSize failed. ERROR: %d\n", ret);
return ret);
// Allocate device memory based on the workspaceSize calculated by the first-phase API.
void* workspaceAddr = nullptr;
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);
}
// Call the second-phase API of aclnnDynamicQuantV2.
ret = aclnnDynamicQuantV2(workspaceAddr, workspaceSize, executor, stream);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnDynamicQuantV2 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, copy the result on the device to the host, and modify it based on the definition of the specific API
PrintOutResult(yShape, &yDeviceAddr);
// 6. Release aclTensor and aclScalar, and modify them based on the definition of the specific API
aclDestroyTensor(x);
aclDestroyTensor(smooth);
aclDestroyTensor(group);
aclDestroyTensor(y);
aclDestroyTensor(scale);
aclDestroyTensor(offset);
// 7. Release device resources
aclrtFree(xDeviceAddr);
aclrtFree(smoothDeviceAddr);
aclrtFree(groupDeviceAddr);
aclrtFree(yDeviceAddr);
aclrtFree(scaleDeviceAddr);
aclrtFree(offsetDeviceAddr);
if (workspaceSize > 0) {
aclrtFree(workspaceAddr);
}
aclrtDestroyStream(stream);
aclrtResetDevice(deviceId);
aclFinalize();
return 0;
}