aclnnDynamicQuant
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 dynamic quantization on the input tensor.
Formula:
- If smoothScalesOptional is not provided:
- If smoothScalesOptional is provided:
Where row_max represents the maximum value of each row, and dtypeMax is the maximum value of the output data type.
Function Prototype
Each operator uses a two-phase API. You must first call the "aclnnDynamicQuantGetWorkspaceSize" API to obtain the workspace size required for computation and the executor containing the computation process of the operator, and then call the "aclnnDynamicQuant" API to perform the computation.
aclnnStatus aclnnDynamicQuantGetWorkspaceSize(
const aclTensor* x,
const aclTensor* smoothScalesOptional,
const aclTensor* yOut,
const aclTensor* scaleOut,
uint64_t* workspaceSize,
aclOpExecutor** executor)aclnnStatus aclnnDynamicQuant(
void *workspace,
uint64_t workspaceSize,
aclOpExecutor *executor,
aclrtStream stream)aclnnDynamicQuantGetWorkspaceSize
Parameters:
Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor x (aclTensor*) Input Input tensor of the operator. Corresponds to `x` in the formula. Supports empty tensors. FLOAT16, BFLOAT16 ND 2-8 √ smoothScalesOptional (aclTensor*) Input smoothScales input of the operator. Corresponds to `smoothScalesOptional` in the formula description. - Empty tensors are supported.
- The data type must be the same as that of x.
- The shape dimension is the same as the last dimension of x.
FLOAT16, BFLOAT16 ND 1 √ yOut (aclTensor*) Output Quantized output tensor. This is `yOut` in the corresponding formula. - Empty tensors are supported.
- 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, FLOAT8_E4M3FN, FLOAT8_E5M2, HIFLOAT8, INT32 ND 2-8 √ scaleOut (aclTensor*) Output Scale used for quantization. `scaleOut` in the corresponding formula. - Supports empty tensors.
- Shape dimensions are the shape of x excluding the last dimension.
FLOAT32 ND 1-7 √ workspaceSize (uint64_t*) Output Returns the size of the workspace to be requested on the Device. - - - - - executor (aclOpExecutor**) Output Returns the op executor, which contains the operator computation flow. - - - - - Atlas A2 products andAtlas A3 products : The data type of the output parameteryOutsupports only INT4, INT8, and INT32.
Atlas inference products andAtlas training products :- The data type of the input
xandsmoothScalesOptionalsupports only FLOAT16. - The data type of the output parameter
yOutonly supports INT8. - The input parameter
smoothScalesOptionalis a reserved parameter and does not participate in computation in the current version.
- The data type of the input
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 x or out parameter is a null pointer. ACLNN_ERR_PARAM_INVALID 161002 The data type, data format, or dimensions of the parameter are out of the supported range. If the data type of yOut is INT4, the last dimension of x or yOut is not an even number. If the data type of yOut is INT32, the last dimension of x must not be divisible by 8. ACLNN_ERR_INNER_CREATE_EXECUTOR 561001 Failed to create aclOpExecutor internally.
aclnnDynamicQuant
Parameters:
Parameter Input/Output Description workspace Input Workspace memory address allocated on the device. workspaceSize Input Workspace size allocated on the device, obtained by calling the first-phase API aclnnDynamicQuantGetWorkspaceSize. executor Input Op executor, which contains the computation flow of the operator. stream Input Stream for task execution. 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 yOut is INT4, the last dimension of x and yOut must be divisible by 2. Non-contiguous tensors are not supported.
- When the data type of yOut is INT32, the last dimension of x must be divisible by 8.
Atlas inference products ,Atlas training products : the last dimension of x must be divisible by 32. Only symmetric quantization is supported for now, and the BFLOAT16 data type is not supported.- Deterministic computation:
- aclnnDynamicQuant defaults to a deterministic implementation.
Example
The following 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.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, (int)resultData[i]);
}
}
int Init(int32_t deviceId, aclrtStream* stream) {
// Boilerplate code 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 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;
}
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 = 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 according to the API.
int rowNum = 4;
int rowLen = 32;
std::vector<int64_t> xShape = {rowNum, rowLen};
std::vector<int64_t> smoothShape = {rowLen};
std::vector<int64_t> yShape = {rowNum, rowLen};
std::vector<int64_t> scaleShape = {rowNum};
void* xDeviceAddr = nullptr;
void* smoothDeviceAddr = nullptr;
void* yDeviceAddr = nullptr;
void* scaleDeviceAddr = nullptr;
aclTensor* x = nullptr;
aclTensor* smooth = nullptr;
aclTensor* y = nullptr;
aclTensor* scale = nullptr;
std::vector<aclFloat16> xHostData;
std::vector<aclFloat16> smoothHostData;
std::vector<int8_t> yHostData;
std::vector<float> scaleHostData;
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);
}
for (int k = 0; k < rowLen; ++k) {
float value2 = k * rowLen + 1;
smoothHostData.push_back(aclFloatToFloat16(value2));
}
// Create the x aclTensor.
ret = CreateAclTensor(xHostData, xShape, &xDeviceAddr, aclDataType::ACL_FLOAT16, &x);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// Create the smooth aclTensor.
ret = CreateAclTensor(smoothHostData, smoothShape, &smoothDeviceAddr, aclDataType::ACL_FLOAT16, &smooth);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// Create the y aclTensor.
ret = CreateAclTensor(yHostData, yShape, &yDeviceAddr, aclDataType::ACL_INT8, &y);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// Create the scale aclTensor.
ret = CreateAclTensor(scaleHostData, scaleShape, &scaleDeviceAddr, aclDataType::ACL_FLOAT, &scale);
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 aclnnDynamicQuant.
ret = aclnnDynamicQuantGetWorkspaceSize(x, smooth, y, scale, &workspaceSize, &executor);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnDynamicQuantGetWorkspaceSize 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 aclnnDynamicQuant.
ret = aclnnDynamicQuant(workspaceAddr, workspaceSize, executor, stream);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnDynamicQuant failed. ERROR: %d\n", ret); return ret);
// 4. (boilerplate) Wait synchronously until the task is 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 host memory. Modify it according to the specific API definition.
PrintOutResult(yShape, &yDeviceAddr);
// 6. Release the aclTensor. Modify it according to the specific API definition.
aclDestroyTensor(x);
aclDestroyTensor(smooth);
aclDestroyTensor(y);
aclDestroyTensor(scale);
// 7. Release device resources.
aclrtFree(xDeviceAddr);
aclrtFree(smoothDeviceAddr);
aclrtFree(yDeviceAddr);
aclrtFree(scaleDeviceAddr);
if (workspaceSize > 0) {
aclrtFree(workspaceAddr);
}
aclrtDestroyStream(stream);
aclrtResetDevice(deviceId);
aclFinalize();
return 0;
}