aclnnQuantMax
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: Quantizes input x based on the input scale, and computes amax, the maximum absolute value of input x.
Formula:
In the formula, indicates the input tensor, indicates the quantization scale factor, specifies the output type, specifies the rounding mode, and is the maximum absolute value of all elements in the input tensor.
Function Prototype
Each operator uses a two-phase API. You must first call the "aclnnQuantMaxGetWorkspaceSize" API to obtain the workspace size required for computation and the executor containing the computation process, and then call the "aclnnQuantMax" API to perform the computation.
aclnnStatus aclnnQuantMaxGetWorkspaceSize(
const aclTensor *x,
const aclTensor *scale,
char *roundMode,
int64_t dstType,
const aclTensor *y,
const aclTensor *amax,
uint64_t *workspaceSize,
aclOpExecutor **executor)aclnnStatus aclnnQuantMax(
void *workspace,
uint64_t workspaceSize,
aclOpExecutor *executor,
aclrtStream stream)aclnnQuantMaxGetWorkspaceSize
Parameters
Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor x(aclTensor*) Input Input tensor to be quantized, corresponding to x in the formula. - Empty tensor is supported.
FLOAT, FLOAT16, BFLOAT16 ND 1-8 √ scale (aclTensor*) Input Quantization scale factor, corresponding to scale in the formula. - Empty tensors are not supported.
- The shape is fixed to [1].
FLOAT ND 1 - roundMode (char*) Input Specifies the rounding mode. - When dstType is 34, roundMode supports "round" and "hybrid".
- When dstType is 35 or 36, roundMode supports "rint".
- - - - dstType (int64_t) Input Specifies the quantized data type of the output. 34=HIFLOAT8, 35=FLOAT8_E5M2, 36=FLOAT8_E4M3. - Value range: {34, 35, 36}.
- - - - y (aclTensor*) Output Quantized output tensor, corresponding to y in the formula. - The data type is determined by dstType.
- The shape is the same as that of x.
HIFLOAT8, FLOAT8_E5M2, FLOAT8_E4M3 ND 1-8 √ amax (aclTensor*) Output Maximum absolute value of x, corresponding to amax in the formula. - The data type must be the same as that of x.
- The shape is fixed to [1].
FLOAT, FLOAT16, BFLOAT16 ND 1 - workspaceSize (uint64_t*) Output Returns the size of the workspace to be allocated on the Device. - - - - - executor (aclOpExecutor**) Output Returns the op executor, which contains the operator calculation process. - - - - - 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 x, scale, y, or amax is a null pointer. ACLNN_ERR_PARAM_INVALID 161002 The data type of x is not supported. The data type of scale is not FLOAT. The value of dstType is not in the range of {34, 35, 36}. The value of roundMode is invalid. The dimension of x is not in the range of 1-8, or the shapes of scale and amax are not [1].
aclnnQuantMax
Parameters
Parameter Input/Output Description workspace Input Workspace memory address allocated on the Device. workspaceSize Input Workspace size allocated on the Device, obtained by the first-phase API aclnnQuantMaxGetWorkspaceSize. executor Input Op executor, containing the operator computation flow. stream Input Stream for task execution. Return Value
aclnnStatus: return status code. For details, see aclnn Return Codes.
Constraints
- Deterministic computation:
- aclnnQuantMax 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 <memory>
#include <vector>
#include <cmath>
#include "acl/acl.h"
#include "aclnnop/aclnn_quant_max.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;
}
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-side 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);
// 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 aclnnQuantMaxTest(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);
LOG_PRINT("Init acl success.\n");
std::vector<int64_t> xShape = {4, 4};
std::vector<int64_t> scaleShape = {1};
std::vector<int64_t> amaxShape = {1};
// The selected values of x can cover multiple cases.
std::vector<float> xHostData = {1.0f, -2.0f, 3.0f, -4.0f, 5.0f, -6.0f, 7.0f, -8.0f,
0.5f, -0.5f, 0.0f, 448.0f, -448.0f, 0.125f, -0.125f, 2.5f};
// scale = 1.0
std::vector<float> scaleHostData = {1.0f};
// The output y is initialized to 0.
std::vector<uint8_t> yHostData(GetShapeSize(xShape), 0);
// amax is initialized to 0.
std::vector<float> amaxHostData = {0.0f};
void* xDeviceAddr = nullptr;
void* scaleDeviceAddr = nullptr;
void* yDeviceAddr = nullptr;
void* amaxDeviceAddr = nullptr;
aclTensor* xTensor = nullptr;
aclTensor* scaleTensor = nullptr;
aclTensor* yTensor = nullptr;
aclTensor* amaxTensor = nullptr;
// Create input x tensor
ret = CreateAclTensor(xHostData, xShape, &xDeviceAddr, aclDataType::ACL_FLOAT, &xTensor);
std::unique_ptr<aclTensor, aclnnStatus (*)(const aclTensor*)> xTensorPtr(xTensor, aclDestroyTensor);
std::unique_ptr<void, aclError (*)(void*)> xDeviceAddrPtr(xDeviceAddr, aclrtFree);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// Create scale tensor (float, shape [1])
ret = CreateAclTensor(scaleHostData, scaleShape, &scaleDeviceAddr, aclDataType::ACL_FLOAT, &scaleTensor);
std::unique_ptr<aclTensor, aclnnStatus (*)(const aclTensor*)> scaleTensorPtr(scaleTensor, aclDestroyTensor);
std::unique_ptr<void, aclError (*)(void*)> scaleDeviceAddrPtr(scaleDeviceAddr, aclrtFree);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// Create output y tensor (FLOAT8_E4M3FN, same shape as x)
ret = CreateAclTensor(yHostData, xShape, &yDeviceAddr, aclDataType::ACL_FLOAT8_E4M3FN, &yTensor);
std::unique_ptr<aclTensor, aclnnStatus (*)(const aclTensor*)> yTensorPtr(yTensor, aclDestroyTensor);
std::unique_ptr<void, aclError (*)(void*)> yDeviceAddrPtr(yDeviceAddr, aclrtFree);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// Create output amax tensor (float, shape [1])
ret = CreateAclTensor(amaxHostData, amaxShape, &amaxDeviceAddr, aclDataType::ACL_FLOAT, &amaxTensor);
std::unique_ptr<aclTensor, aclnnStatus (*)(const aclTensor*)> amaxTensorPtr(amaxTensor, aclDestroyTensor);
std::unique_ptr<void, aclError (*)(void*)> amaxDeviceAddrPtr(amaxDeviceAddr, aclrtFree);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// 3. Call quant_max API
int64_t dstType = 36; // FLOAT8_E4M3FN
char* roundMode = const_cast<char*>("rint");
uint64_t workspaceSize = 0;
aclOpExecutor* executor = nullptr;
// First stage: get workspace size
ret = aclnnQuantMaxGetWorkspaceSize(
xTensor, scaleTensor, roundMode, dstType, yTensor, amaxTensor, &workspaceSize, &executor);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnQuantMaxGetWorkspaceSize failed. ERROR: %d\n", ret); return ret);
LOG_PRINT("aclnnQuantMaxGetWorkspaceSize success, workspaceSize: %lu\n", workspaceSize);
// Allocate workspace
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);
}
// Second stage: execute
ret = aclnnQuantMax(workspaceAddr, workspaceSize, executor, stream);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnQuantMax failed. ERROR: %d\n", ret); return ret);
// 4. Synchronize stream
ret = aclrtSynchronizeStream(stream);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtSynchronizeStream failed. ERROR: %d\n", ret); return ret);
LOG_PRINT("aclnnQuantMax execution success.\n");
// 5. Get results
// Copy y (FLOAT8_E4M3FN) back to host
auto ySize = GetShapeSize(xShape);
std::vector<uint8_t> yOutData(ySize, 0);
ret = aclrtMemcpy(
yOutData.data(), ySize * sizeof(uint8_t), yDeviceAddr, ySize * sizeof(uint8_t), ACL_MEMCPY_DEVICE_TO_HOST);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("copy y from device to host failed. ERROR: %d\n", ret); return ret);
// Copy amax back to host
std::vector<float> amaxOutData(1, 0);
ret = aclrtMemcpy(amaxOutData.data(), sizeof(float), amaxDeviceAddr, sizeof(float), ACL_MEMCPY_DEVICE_TO_HOST);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("copy amax from device to host failed. ERROR: %d\n", ret); return ret);
// Print results
auto size = GetShapeSize(xShape);
for (int64_t i = 0; i < size; i++) {
LOG_PRINT("yOut[%ld] is: %d\n", i, yOutData[i]);
}
LOG_PRINT("amaxOut is: %f\n", amaxOutData[0]);
return ACL_SUCCESS;
}
int main()
{
// 1. (boilerplate) Initialize device/stream. Refer to the acl API manual.
// Set deviceId based on the actual device.
int32_t deviceId = 0;
aclrtStream stream;
auto ret = aclnnQuantMaxTest(deviceId, stream);
CHECK_FREE_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnQuantMaxTest failed. ERROR: %d\n", ret); return ret);
Finalize(deviceId, stream);
LOG_PRINT("All test cases passed!\n");
return 0;
}