aclnnQuantConvolutionWeightNz
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 3D convolution computation with per-channel quantization. Only the FRACTAL_Z_3D format is supported for weight. The convolution computation process is the same as that of the aclnnConvolution API.
Formula:
Assume that the shape of input is , the original shape of weight is , the shape of scale is , the shape of bias is , and the shape of output is , where represents 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 expressed as follows:
where represents convolution. The convolution type (dilated or grouped) depends on the dimensions of the convolution input. indicates the batch size, indicates the number of channels, and , , and indicate the depth, height, and width, respectively. The output dimensions are calculated as follows:
Function Prototype
Each operator uses a two-phase API. Call the aclnnQuantConvolutionWeightNzGetWorkspaceSize API first to obtain the workspace size required for the computation and the executor that contains the operator computation process, and then call the aclnnQuantConvolutionWeightNz API to perform the computation.
aclnnStatus aclnnQuantConvolutionWeightNzGetWorkspaceSize(
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 aclnnQuantConvolutionWeightNz(
void *workspace,
const uint64_t workspaceSize,
aclOpExecutor *executor,
aclrtStream stream)aclnnQuantConvolutionWeightNzGetWorkspaceSize
Parameters
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 A 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 0 do not meet the requirement. The spatial size of input after padding is smaller than the spatial size of weight after dilation expansion (if dilation > 1). The number of channels of weight and input does not meet the requirement. The shapes of weight before and after conversion do not conform to the conversion relationship. The stride or dilation less than 0 does not meet the requirement. Convolution is not supported on the current processor. ACLNN_ERR_INNER_NULLPTR 561103 Internal API verification error, usually because the specifications of input data or attributes are not within the supported range. ACLNN_ERR_RUNTIME_ERROR 361001 An exception occurs when the API calls the npu runtime, for example, the SocVersion is not supported.
aclnnQuantConvolutionWeightNz
Parameters
Parameter Input/Output Description workspace Input Workspace memory address applied on the Device side. workspaceSize Input Workspace size applied on the Device side, obtained by calling the first-phase API aclnnQuantConvolutionWeightNzGetWorkspaceSize. executor Input Executor of the operator, containing the operator computation process. stream Input Stream for executing the task. Return Value
aclnnStatus: return value. For details, see aclnn return codes.
Constraints
- Deterministic computation
- aclnnQuantConvolutionWeightNz defaults to a deterministic implementation.
| Constraint Type | |
|---|---|
| input, weight | - |
| bias | - |
| scale | - |
| padding | The array length of padding must be 3. |
| groups | The value of groups must be 1. |
| offsetx | offsetx is currently not supported. Pass in 0. |
| roundMode | roundMode is currently not supported. Pass in the null pointer nullptr. |
| output | - |
| Other Constraints |
|
Example
The following sample code is for reference only. For details about the compilation and execution process, see Compile and Run Samples.
For different product models, use different main functions.
The sample constructs the weight in FRACTAL_Z_3D format through the view/storage format setting APIs of aclTensor. It depends on the header file "aclnn/opdev/common_types.h", and the C++ standard should be C++14 or later during compilation (for example, add_compile_options(-std=c++17)).
#include <iostream>
#include <memory>
#include <vector>
#include "acl/acl.h"
#include "aclnn/opdev/common_types.h"
#include "aclnnop/aclnn_npu_format_cast.h"
#include "aclnnop/aclnn_quant_convolution.h"
// A macro with the same name is already defined in aclnn/opdev/common_types.h. Undefine it first to avoid macro redefinition warnings.
#undef CHECK_RET
#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 host-side data to 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);
// 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_NCDHW,
shape.data(), shape.size(), *deviceAddr);
return 0;
}
template <typename T>
int CreateAclTensorWithFormat(const std::vector<T>& hostData, const std::vector<int64_t>& shape, int64_t** storageShape, uint64_t* storageShapeSize, void** deviceAddr,
aclDataType dataType, aclTensor** tensor, aclFormat format) {
auto size = hostData.size() * 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 host-side data to 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);
// 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];
}
*tensor = aclCreateTensor(shape.data(), shape.size(), dataType, strides.data(), 0,
format, *storageShape, *storageShapeSize, *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 host-side data to 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 aclnnQuantConvolutionWeightNzTest(int32_t deviceId, aclrtStream& stream, std::vector<aclDataType> dtypesInfo)
{
auto ret = Init(deviceId, &stream);
// Handle the check as needed.
CHECK_FREE_RET(ret == ACL_SUCCESS, LOG_PRINT("Init acl failed. ERROR: %d\n", ret); return ret);
// 2. Construct the inputs and outputs as required by 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* deviceDataBNz = nullptr;
void* deviceDataScale = nullptr;
void* deviceDataBias = nullptr;
void* deviceDataResult = nullptr;
aclTensor* input = nullptr;
aclTensor* weight = nullptr;
aclTensor* weightNz = 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 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 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. Replace it with the specific API.
aclOpExecutor* executor;
void* workspaceAddrNz = nullptr;
int64_t* dstShape = nullptr;
uint64_t dstShapeSize = 0;
int actualFormat;
// Convert weight to FRACTAL_Z_3D.
// Calculate the shape and format of the target tensor.
ret = aclnnNpuFormatCastCalculateSizeAndFormat(weight, aclFormat::ACL_FRACTAL_Z_3D, -1, &dstShape, &dstShapeSize, &actualFormat);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnNpuFormatCastCalculateSizeAndFormat failed. ERROR: %d\n", ret); return ret);
// Converting NCDHW data to FRACTAL_Z_3D directly via aclnnNpuFormatCast is not supported in the current CANN version,
// so rearrange the weight data on the host in the FRACTAL_Z_3D layout (D*C1*H*W, N1, N0, C0), padding the aligned part with 0s,
// where C1=CEIL(Cin, C0), N1=CEIL(Cout, N0), N0=16, C0=32.
std::vector<int64_t> shapeWeightNz(dstShape, dstShape + dstShapeSize);
std::vector<int8_t> weightNzData(GetShapeSize(shapeWeightNz), 0);
const int64_t cOut = shapeWeight[0], cIn = shapeWeight[1];
const int64_t kD = shapeWeight[2], kH = shapeWeight[3], kW = shapeWeight[4];
const int64_t c1 = shapeWeightNz[0] / (kD * kH * kW);
const int64_t n1 = shapeWeightNz[1], n0 = shapeWeightNz[2], c0 = shapeWeightNz[3];
for (int64_t co = 0; co < cOut; co++) {
for (int64_t ci = 0; ci < cIn; ci++) {
for (int64_t d = 0; d < kD; d++) {
for (int64_t h = 0; h < kH; h++) {
for (int64_t w = 0; w < kW; w++) {
int64_t dim0 = ((d * c1 + ci / c0) * kH + h) * kW + w;
int64_t dstIdx = ((dim0 * n1 + co / n0) * n0 + co % n0) * c0 + ci % c0;
weightNzData[dstIdx] = weightData[(((co * cIn + ci) * kD + d) * kH + h) * kW + w];
}
}
}
}
}
// The viewShape/originalShape of weightNz is 5-dimensional NCDHW (the same dimensions as input/output), and the storageShape is 4-dimensional FRACTAL_Z_3D.
ret = CreateAclTensorWithFormat(weightNzData, shapeWeight, &dstShape, &dstShapeSize, &deviceDataBNz, weightDtype, &weightNz, aclFormat::ACL_FRACTAL_Z_3D);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("CreateAclTensorWithFormat failed. ERROR: %d\n", ret); return ret);
// After the tensor is created with FRACTAL_Z_3D by aclCreateTensor, set the view/original format and original shape to NCDHW so that the operator can correctly parse the N/C/D/H/W axis information of weight.
op::Shape weightNcdhwShape = {shapeWeight[0], shapeWeight[1], shapeWeight[2], shapeWeight[3], shapeWeight[4]};
weightNz->SetViewFormat(op::Format::FORMAT_NCDHW);
weightNz->SetOriginalFormat(op::Format::FORMAT_NCDHW);
weightNz->SetOriginalShape(weightNcdhwShape);
uint64_t workspaceSizeNz = 0;
// Call the first-phase API of aclnnConvolutionWeightNz.
ret = aclnnQuantConvolutionWeightNzGetWorkspaceSize(input, weightNz, bias, scale, nullptr, strides, pads, dilations,
false, nullptr, 1, 0, nullptr, result, &workspaceSizeNz, &executor);
CHECK_FREE_RET(ret == ACL_SUCCESS, LOG_PRINT(
"aclnnQuantConvolutionWeightNzGetWorkspaceSize failed. ERROR: %d\n", ret); return ret);
// Allocate device memory based on the workspaceSize calculated by the first-phase API.
std::unique_ptr<void, aclError (*)(void *)> workspaceAddrPtr(nullptr, aclrtFree);
if (workspaceSizeNz > 0) {
ret = aclrtMalloc(&workspaceAddrNz, workspaceSizeNz, ACL_MEM_MALLOC_HUGE_FIRST);
CHECK_FREE_RET(ret == ACL_SUCCESS, LOG_PRINT("allocate workspace failed. ERROR: %d\n", ret); return ret);
workspaceAddrPtr.reset(workspaceAddrNz);
}
// Call the second-phase API of aclnnConvolutionWeightNz.
ret = aclnnQuantConvolutionWeightNz(workspaceAddrNz, workspaceSizeNz, executor, stream);
CHECK_FREE_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnQuantConvolutionWeightNz failed. ERROR: %d\n", ret); return ret);
// 4. (boilerplate) Synchronize and wait for the task execution 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 value and copy the result from device memory to host memory. Modify the code based on the specific API definition.
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);
int64_t printSize = size > 10 ? 10 : size;
for (int64_t i = 0; i < printSize; i++) {
LOG_PRINT("result[%ld] is: %d\n", i, resultData[i]);
}
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;
std::vector<aclDataType> dtypesInfo = {aclDataType::ACL_INT8, aclDataType::ACL_INT8, aclDataType::ACL_FLOAT,
aclDataType::ACL_FLOAT, aclDataType::ACL_BF16}; // Datatypes of input/weight/bias/scale/output, respectively.
auto ret = aclnnQuantConvolutionWeightNzTest(deviceId, stream, dtypesInfo);
CHECK_FREE_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnQuantConvolutionWeightNzTest failed. ERROR: %d\n", ret); return ret);
Finalize(deviceId, stream);
return 0;
}