aclnnQuantConvolution
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 : Not supported
Atlas training products : Not supported
Function
Description: Performs 2D and 3D convolution computation with per-channel quantization. The convolution process is the same as that of the aclnnConvolution API.
Formula: Assume the input shape is , the weight shape is , the scale shape is , the bias shape is , and the output shape is , where indicates the batch size, is the number of channels, , , and are the depth, height and width of a sample, respectively, and , , and are the depth, height and width of the convolution kernel, respectively. The output is then expressed as:
where represents convolution. The convolution type (dilated convolution, grouped convolution) depends on the dimensions of the convolution input. represents the batch size, represents the number of channels, and , , and represent depth, height, and width, respectively. The formulas for calculating the corresponding output dimensions are as follows:
Function Prototype
Each operator consists of a two-phase API. First, call the aclnnQuantConvolutionGetWorkspaceSize API to obtain the workspace size required for computation and the executor that contains the computation process. Then, call the aclnnQuantConvolution API to execute the computation.
aclnnStatus aclnnQuantConvolutionGetWorkspaceSize(
const aclTensor *input,
const aclTensor *weight,
const aclTensor *bias,
const aclTensor *scale,
const aclTensor *offset,
const aclIntArray *stride,
const aclIntArray *padding,
const aclIntArray *dilation,
bool transposed,
const aclIntArray *outputPadding,
int64_t groups,
int32_t offsetx,
const char *roundMode,
aclTensor *output,
uint64_t *workspaceSize,
aclOpExecutor **executor)aclnnStatus aclnnQuantConvolution(
void *workspace,
const uint64_t workspaceSize,
aclOpExecutor *executor,
aclrtStream stream)aclnnQuantConvolutionGetWorkspaceSize
Parameters
Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor input (aclTensor*) Input input in the formula, represents the convolution input. - Does not support null tensors.
- Its data type must satisfy the data type deduction rules together with the data type of weight (see deduction relationship).
- The dimensions of input, weight, and output must be the same.
- N≥0, C≥1, D≥0, H≥0, W≥0.
INT8, FLOAT8_E4M3FN, HIFLOAT8 NCHW, NCDHW 4-5 √ weight (aclTensor*) Input weight in the formula, represents the convolution weight. - Does not support null tensors.
- The data type and the data type of input must comply with the data type deduction rules (see Deduction Relationship).
- The C dimension of its shape must be the same as the C dimension of input.
- All dimensions are greater than or equal to 1.
INT8, FLOAT8_E4M3FN, HIFLOAT8 NCHW, NCDHW 4-5 √ bias (aclTensor*) Input Bias in the formula, which represents the convolution bias. One-dimensional and equal to the first dimension of weight. BFLOAT16, FLOAT16, FLOAT, INT32 ND 1 √ scale (aclTensor*) Input scale in the formula, represents the quantization parameter. 1D and equal to the first dimension of weight. FLOAT, INT64, UINT64 ND 1 √ offset (aclTensor*) Input Reserved quantization parameter. Currently not yet supported. Passing a null pointer nullptr can be used. - - - - stride (aclIntArray*) Input Stride of the convolution scan. - The array length is 2 in 2D scenarios and 3 in 3D scenarios.
- strideH and strideW should be within the range [1,63].
- In conv3d scenarios, strideD should be within the range [1,1000000].
INT64 - - - padding (aclIntArray*) Input Padding for input. - The value should be ≥0.
- paddingH and paddingW should be within the range [0,255].
- In the conv3d scenario, paddingD should be within the range [0,1000000].
INT64 - - - dilation(aclIntArray*) Input The interval between elements in the convolution kernel. - In the 2D scenario, the array length is 2. In the 3D scenario, the array length is 3.
- The value should be >0.
- dilationH and dilationW should be within the range [1,255].
- In the conv3d scenario, dilationD should be within the range [1,1000000].
INT64 - - - transposed (bool) Input Reserved parameter. Indicates whether transposed quantized convolution is used. Currently not yet supported. Pass in false. BOOL - - - outputPadding(aclIntArray*) Input Reserved parameter. Represents the padding on all edges of the output in the case of transposed convolution. In the case of non-transposed convolution, this attribute configuration is ignored. Currently not yet supported. You can pass in the null pointer nullptr. INT64 - - - groups(int64_t) Input Represents the number of block connections from the input channel to the output channel. The value must be ≥1, and must satisfy groups*weight C dimension = input C dimension. INT64 - - - offsetx (int32_t) Input Represents the quantization factor. [-128,127] or 0 INT32 - - - roundMode (char*) Input Represents the rounding mode. rint, round, or nullptr CHAR* - - - output (aclTensor*) Output output in the formula, which represents the convolution output. - Does not support null Tensor output.
- The shape satisfies the deduction rules of convolution.
- The number of channels equals the first dimension of weight, and other dimensions are ≥ 0.
BFLOAT16, FLOAT16, FLOAT, FLOAT8_E4M3FN, HIFLOAT8 NCHW, NCDHW 4-5 √ workspaceSize (uint64_t*) Output Returns the workspace size to be applied on the Device side. - - - - - executor (aclOpExecutor**) Output Returns the op executor, which contains the operator computation flow. - - - - - 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 pointer-type input parameter is a null pointer. ACLNN_ERR_PARAM_INVALID 161002 The data types and data formats of input, weight, bias, scale, offset, and output are not within the supported range. The input shapes of stride, padding, and dilation are invalid. The groups input is invalid. The input shapes of scale and bias are invalid. The shape of output does not match the infershape result. Tensors passed in with any dimension of zero do not meet requirements. The spatial size of input after padding is smaller than the spatial size of weight (expanded by dilation, if dilation>1). The number of channels of weight and input does not meet requirements. Cases where stride or dilation is less than 0 do not meet requirements. The current processor does not support convolution. ACLNN_ERR_INNER_NULLPTR 561103 Internal API verification error, usually caused by input data or attribute specifications that are not within the supported range. ACLNN_ERR_RUNTIME_ERROR 361001 The API fails to call the NPU runtime interface, for example, SocVersion is not supported.
aclnnQuantConvolution
Parameters
Parameter Input/Output Description workspace Input Memory address of the workspace applied on the Device side. workspaceSize Input Workspace size applied on the Device side, obtained by the first-phase API aclnnQuantConvolutionGetWorkspaceSize. executor Input An op executor that contains the operator computation process. stream Input Specifies the stream for executing tasks. Return Value
aclnnStatus: Return status code. For details, see aclnn return codes.
Constraints
- Deterministic Computation
- aclnnQuantConvolution defaults to a deterministic implementation.
| Constraint Type | |
|---|---|
| input, weight | The data types FLOAT8_E4M3FN and HIFLOAT8 are not supported for input and weight, and the data format NCHW is not supported. |
| bias | The data type INT32 is not supported for bias; it is converted to FLOAT for computation. |
| scale | The data types INT64 and UINT64 are not supported for scale. |
| padding | The length of the padding array must be 3. |
| groups | The value of groups must be 1. |
| offsetx | offsetx is currently not yet supported. Pass in 0. |
| roundMode | roundMode is currently not yet supported. Pass in the null pointer nullptr. |
| output | The data type of output supports BFLOAT16 and FLOAT16, and the data format supports only NCDHW. |
| Other Constraints |
|
Example
The sample code is as follows and is for reference only. For details about compilation and execution, see Compile and Run Samples.
For different product models, use different main functions.
#include <iostream>
#include <memory>
#include <vector>
#include "acl/acl.h"
#include "aclnnop/aclnn_quant_convolution.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 shape_size = 1;
for (auto i: shape) {
shape_size *= i;
}
return shape_size;
}
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 memory on the device side.
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 side to the device-side 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_NCDHW,
shape.data(), shape.size(), *deviceAddr);
return 0;
}
template <typename T>
int CreateAclTensorND(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 side.
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 side to the device-side 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;
}
void Finalize(int32_t deviceId, aclrtStream& stream)
{
aclrtDestroyStream(stream);
aclrtResetDevice(deviceId);
aclFinalize();
}
int aclnnQuantConvolutionTest(int32_t deviceId, aclrtStream& stream, std::vector<aclDataType> dtypesInfo)
{
auto ret = Init(deviceId, &stream);
// Process check as needed.
CHECK_FREE_RET(ret == ACL_SUCCESS, LOG_PRINT("Init acl failed. ERROR: %d\n", ret); return ret);
// 2. Construct the input and output. Custom construction is required based on the API.
std::vector<int64_t> shapeInput = {2, 2, 32, 32, 32};
std::vector<int64_t> shapeWeight = {2, 2, 3, 3, 3};
std::vector<int64_t> shapeScale = {2};
std::vector<int64_t> shapeBias = {2};
std::vector<int64_t> shapeResult = {2, 2, 32, 32, 32};
std::vector<int64_t> convStrides;
std::vector<int64_t> convPads;
std::vector<int64_t> convDilations;
void* deviceDataA = nullptr;
void* deviceDataB = nullptr;
void* deviceDataScale = nullptr;
void* deviceDataBias = nullptr;
void* deviceDataResult = nullptr;
aclTensor* input = nullptr;
aclTensor* weight = nullptr;
aclTensor* scale= nullptr;
aclTensor* bias= nullptr;
aclTensor* result = nullptr;
std::vector<int8_t> inputData(GetShapeSize(shapeInput), 1);
std::vector<int8_t> weightData(GetShapeSize(shapeWeight), 1);
std::vector<float> biasData(GetShapeSize(shapeBias), 1);
std::vector<float> scaleData(GetShapeSize(shapeScale), 1);
std::vector<uint16_t> outputData(GetShapeSize(shapeResult), 1);
convStrides = {1, 1, 1};
convPads = {1, 1, 1};
convDilations = {1, 1, 1};
aclDataType inputDtype = dtypesInfo[0];
aclDataType weightDtype = dtypesInfo[1];
aclDataType biasDtype = dtypesInfo[2];
aclDataType scaleDtype = dtypesInfo[3];
aclDataType outputDtype = dtypesInfo[4];
// Create the input aclTensor.
ret = CreateAclTensor(inputData, shapeInput, &deviceDataA, inputDtype, &input);
std::unique_ptr<aclTensor, aclnnStatus (*)(const aclTensor *)> inputTensorPtr(input, aclDestroyTensor);
std::unique_ptr<void, aclError (*)(void *)> deviceDataAPtr(deviceDataA, aclrtFree);
CHECK_FREE_RET(ret == ACL_SUCCESS, return ret);
// Create the weight aclTensor.
ret = CreateAclTensor(weightData, shapeWeight, &deviceDataB, weightDtype, &weight);
std::unique_ptr<aclTensor, aclnnStatus (*)(const aclTensor *)> weightTensorPtr(weight, aclDestroyTensor);
std::unique_ptr<void, aclError (*)(void *)> deviceDataBPtr(deviceDataB, aclrtFree);
CHECK_FREE_RET(ret == ACL_SUCCESS, return ret);
// Create the scale.
ret = CreateAclTensorND(scaleData, shapeScale, &deviceDataScale, scaleDtype, &scale);
std::unique_ptr<aclTensor, aclnnStatus (*)(const aclTensor *)> scaleTensorPtr(scale, aclDestroyTensor);
std::unique_ptr<void, aclError (*)(void *)> deviceDataScalePtr(deviceDataScale, aclrtFree);
CHECK_FREE_RET(ret == ACL_SUCCESS, return ret);
// Create the bias.
ret = CreateAclTensorND(biasData, shapeBias, &deviceDataBias, biasDtype, &bias);
std::unique_ptr<aclTensor, aclnnStatus (*)(const aclTensor *)> biasTensorPtr(bias, aclDestroyTensor);
std::unique_ptr<void, aclError (*)(void *)> deviceDataBiasPtr(deviceDataBias, aclrtFree);
CHECK_FREE_RET(ret == ACL_SUCCESS, return ret);
// Create the out aclTensor.
ret = CreateAclTensor(outputData, shapeResult, &deviceDataResult, outputDtype, &result);
std::unique_ptr<aclTensor, aclnnStatus (*)(const aclTensor *)> outputTensorPtr(result, aclDestroyTensor);
std::unique_ptr<void, aclError (*)(void *)> deviceDataResultPtr(deviceDataResult, aclrtFree);
CHECK_FREE_RET(ret == ACL_SUCCESS, return ret);
aclIntArray *strides = aclCreateIntArray(convStrides.data(), 3);
std::unique_ptr<aclIntArray, aclnnStatus (*)(const aclIntArray *)> stridesPtr(strides, aclDestroyIntArray);
CHECK_FREE_RET(strides != nullptr, return ACL_ERROR_INTERNAL_ERROR);
aclIntArray *pads = aclCreateIntArray(convPads.data(), 3);
std::unique_ptr<aclIntArray, aclnnStatus (*)(const aclIntArray *)> padsPtr(pads, aclDestroyIntArray);
CHECK_FREE_RET(pads != nullptr, return ACL_ERROR_INTERNAL_ERROR);
aclIntArray *dilations = aclCreateIntArray(convDilations.data(), 3);
std::unique_ptr<aclIntArray, aclnnStatus (*)(const aclIntArray *)> dilationsPtr(dilations, aclDestroyIntArray);
CHECK_FREE_RET(dilations != nullptr, return ACL_ERROR_INTERNAL_ERROR);
// 3. Call the CANN operator library API. Change it to the specific API.
uint64_t workspaceSize = 0;
aclOpExecutor* executor;
// Call the first-phase API of aclnnConvolution.
ret = aclnnQuantConvolutionGetWorkspaceSize(input, weight, bias, scale, nullptr, strides, pads, dilations,
false, nullptr, 1, 0, nullptr, result, &workspaceSize, &executor);
CHECK_FREE_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnQuantConvolutionGetWorkspaceSize 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_FREE_RET(ret == ACL_SUCCESS, LOG_PRINT("allocate workspace failed. ERROR: %d\n", ret); return ret);
workspaceAddrPtr.reset(workspaceAddr);
}
// Call the second-phase API of aclnnConvolution.
ret = aclnnQuantConvolution(workspaceAddr, workspaceSize, executor, stream);
CHECK_FREE_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnQuantConvolution failed. ERROR: %d\n", ret); return ret);
// 4. (boilerplate) Synchronously wait for the task to complete.
ret = aclrtSynchronizeStream(stream);
CHECK_FREE_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtSynchronizeStream failed. ERROR: %d\n", ret); return ret);
// 5. Obtain the output values, and copy the result on the device memory to the host memory. Modify according to the definition of the specific API.
auto size = GetShapeSize(shapeResult);
std::vector<uint16_t> resultData(size, 0);
ret = aclrtMemcpy(resultData.data(), resultData.size() * sizeof(resultData[0]), deviceDataResult,
size * sizeof(uint16_t), ACL_MEMCPY_DEVICE_TO_HOST);
CHECK_FREE_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]);
}
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;
std::vector<aclDataType> dtypesInfo = {aclDataType::ACL_INT8, aclDataType::ACL_INT8, aclDataType::ACL_FLOAT,
aclDataType::ACL_FLOAT, aclDataType::ACL_BF16}; // Respective data types of input/weight/bias/scale/output
auto ret = aclnnQuantConvolutionTest(deviceId, stream, dtypesInfo);
CHECK_FREE_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnQuantConvolutionTest failed. ERROR: %d\n", ret); return ret);
Finalize(deviceId, stream);
return 0;
}