aclnnFlatQuantV3

📄 View Source Code

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

  • Differences from the V2 version:

    • The V3 version adds the groupList and groupListType parameters to specify the quantization grouping.
    • The V2 version adds the dstTypeMax parameter to control the maximum value of the target data type in pergroup quantization mode (corresponding to the float4_e2m1 output type).
    • The V1 version does not support customizing the maximum value of the target data type and defaults to the maximum value representable by the target precision.
  • User selection suggestions:

    • Select the V3 version if you need to specify quantization grouping.
    • Select the V2 and V3 versions if you need to customize the maximum value of the target data type for float4_e2m1 quantization (range 6.0-12.0).
    • If quantization is not grouped, the default maximum value of the target precision and the INT4/INT32 quantized output type are used, all V1, V2, and V3 versions are applicable.
    • For use cases that require finer control over the quantization range to optimize model performance or accuracy, the V2 and V3 versions are recommended.
  • Description: This fused operator performs two small matrix multiplications on the input matrix x at a time, that is, right-multiplying by the input matrix kroneckerP2 and left-multiplying by the input matrix kroneckerP1, and then quantizes the matrix multiplication result. Currently, pertoken and pergroup quantization modes are supported, corresponding to the INT4 and FLOAT4_E2M1 quantized output types respectively.

  • Matrix multiplication formula:

    1. Input x is right-multiplied by kroneckerP2:

      x′=x@kroneckerP2x' = x @ kroneckerP2
    2. Left-multiply x' by kroneckerP1:

      x′′=kroneckerP1@x′x'' = kroneckerP1@x'
  • Quantization calculation mode:

    pertoken quantization mode:

    1. Compute the maximum absolute value along dimension 0 of x'' and divide it by (7 / clipRatio) to calculate the quantization scale for quantization to the INT4 format:

      quantScale=[max(abs(x′′[0,:,:])),max(abs(x′′[1,:,:])),...,max(abs(x′′[M−1,:,:]))]/(7/clipRatio)quantScale = [max(abs(x''[0,:,:])),max(abs(x''[1,:,:])),...,max(abs(x''[M-1,:,:]))]/(7 / clipRatio)
    2. Calculate the output out:

      out=x′′/quantScaleout = x'' / quantScale

    pergroup quantization mode:

    • When dstTypeMax = 0.0:

      1. After matrix multiplication, x'' has a shape of [M,N1,N2]. To calculate mx_quantize in the pergroup quantization mode, reshape it to [M,N1*N2], denoted as x2.

      2. Group x2 along the second dimension by groupsize. Each group contains elements e0,e1...e31. Calculate emax.

        emax=max(e0,e1....e31)emax = max(e0,e1....e31)
      3. Calculate reduceMaxValue and sharedExp.

        reduceMaxValue=log2(reduceMax(x2),groupSize=32)reduceMaxValue = log2(reduceMax(x2),groupSize=32) sharedExp[M,N1∗N2/32]=reduceMaxValue−emaxsharedExp[M,N1*N2/32] = reduceMaxValue -emax
      4. Calculate quantScale.

        quantScale[M,N1∗N2/32]=2sharedExp[M,N1∗N2/32]quantScale[M,N1*N2/32] = 2 ^ {sharedExp[M,N1*N2/32]}
      5. One quantScale is shared per groupsize. Calculate out.

        out=x2/quantScaleout = x2 / quantScale
    • When dstTypeMax = 6.0/7.0:

      • The input x is grouped along the axis dimension in groups of k = blocksize elements, and each group of k numbers {{Vi}i=1k}\{\{V_i\}_{i=1}^{k}\} is dynamically quantized to {mxscale1,{Pi}i=1k}\{mxscale1, \{P_i\}_{i=1}^{k}\}, k = blocksize:

        shared_exp={ceil(log2(maxi(∣Vi∣)))−emax, iftheprecedingone/twohighbitsofthemantissa are 1, and the mantissa is not all 0floor(log2(maxi(∣Vi∣)))−emax, otherwiseshared\_exp = \begin{cases} ceil(log_2(max_i(|V_i|))) - emax, & \text{ if} the preceding one/two high bits of the mantissa \text{ are 1, and the mantissa is not all 0} \\ floor(log_2(max_i(|V_i|))) - emax, & \text{ otherwise} \end{cases} \\ Pi=cast_to_dst_type(Vi/mxscale,round_mode), i from 1 to blocksizeP_i = cast\_to\_dst\_type(V_i/mxscale, round\_mode), \space i\space from\space 1\space to\space blocksize\\
      • ​The quantized PiP_{i} are combined into the output yOut according to the positions of the corresponding ViV_{i}, and mxscale is combined into the output mxscaleOut according to the corresponding groupings along the axis dimension.

    • When dstTypeMax != 0.0/6.0/7.0:

      • Divide the long vector into blocks, each with a length of k. Compute a block scale factor Sfp32bS_{fp32}^b for each block individually, and then map all elements within the block to the target low-precision type FP8 using the same Sfp32bS_{fp32}^b. If the last block has fewer than k elements, treat the missing values as 0 and process it as a complete block.

      • Find the maximum absolute value of the elements in the block:

        Amax(Dfp32b)=max({∣di∣}i=1k)Amax(D_{fp32}^b)=max(\{|d_{i}|\}_{i=1}^{k})
      • Map FP32 to the range representable by the target data type FP8. When dst_max_value=0, Amax(DType)Amax(DType) is the maximum value representable by the target precision; when dst_max_value!=0, Amax(DType)Amax(DType) is the value passed in for dst_max_value.

        Sfp32b=Amax(Dfp32b)Amax(DType)S_{fp32}^b = \frac{Amax(D_{fp32}^b)}{Amax(DType)}
      • Convert the block quantization scale factor Sfp32bS_{fp32}^b to a scale value Sue8m0bS_{ue8m0}^b representable in the FP8 format.

      • Extract the unbiased exponent EintbE_{int}^b and the mantissa MfixpbM_{fixp}^b from the floating-point quantization scale factor Sfp32bS_{fp32}^b of the block.

      • To ensure no overflow during quantization, round up the exponent and keep it within the representable range of FP8:

        Eintb={Eintb+1, ifSfp32b is a normal number, andEintb<254 andMfixpb>0Eintb, otherwiseE_{int}^b = \begin{cases} E_{int}^b + 1, & \text{ if} S_{fp32}^b \text{ is a normal number, and} E_{int}^b < 254 \text{ and} M_{fixp}^b > 0 \\ E_{int}^b, & \text{ otherwise} \end{cases}
      • Calculate the block scale factor: Sue8m0b=2EintbS_{ue8m0}^b=2^{E_{int}^b}

      • Calculate the block conversion factor: Rfp32b=1fp32(Sue8m0b)R_{fp32}^b=\frac{1}{fp32(S_{ue8m0}^b)}

      • Apply to the final quantization step. For each element within a block, di=DType(dfp32i⋅Rfp32n)d^i = DType(d_{fp32}^i \cdot R_{fp32}^n). The final quantized output is (Sb,[di]i=1k)\left(S^b, [d^i]_{i=1}^k\right), where SbS^b represents the block scale factor, i.e., Sue8m0bS_{ue8m0}^b, and [di]i=1k[d^i]_{i=1}^k represents the quantized data within the block.

      • ​The quantized PiP_{i} are combined into the output yOut according to the positions of the corresponding ViV_{i}, and mxscale is combined into the output mxscaleOut according to the corresponding groupings along the axis dimension.

Function Prototype

Each operator uses a two-phase API. Call aclnnFlatQuantV3GetWorkspaceSize first to obtain the workspace size required for the calculation and the executor that includes the calculation process of the operator, and then call aclnnFlatQuantV3 to perform the calculation.

aclnnStatus aclnnFlatQuantV3GetWorkspaceSize(
  const aclTensor *x,
  const aclTensor *kroneckerP1,
  const aclTensor *kroneckerP2,
  const aclTensor *groupListOptional,
  double           clipRatio,
  double           dstTypeMax,
  int64_t          groupListType,
  aclTensor       *out,
  aclTensor       *quantScale,
  uint64_t        *workspaceSize,
  aclOpExecutor  **executor)
aclnnStatus aclnnFlatQuantV3(
    void          *workspace,
    uint64_t       workspaceSize,
    aclOpExecutor *executor,
    aclrtStream    stream)

aclnnFlatQuantV3GetWorkspaceSize

  • Parameters:

    Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor
    x (aclTensor*) Input Original input data, corresponding to `x` in the formula.
    • Empty tensors are not supported.
    • Shape is [M, N1, N2], where M is not greater than 262144, and N1 and N2 are not greater than 256.
    • If the data type of out is INT32, N2 must be a multiple of 8.
    • If the data type of out is INT4, N2 must be an even number.
    • If the data type of out is FLOAT4_E2M1, N2 must be an even number.
    FLOAT16, BFLOAT16 ND 3 √
    kroneckerP1 (aclTensor*) Input The first calculation matrix input, corresponding to `kroneckerP1` in the formula.
    • Does not support empty tensors.
    • Shape is [N1, N1], and N1 is consistent with the N1 dimension in x.
    • Data type is consistent with the data type of input parameter x.
    FLOAT16, BFLOAT16 ND 2 √
    kroneckerP2 (aclTensor*) Input Calculation matrix 2 of the input, corresponding to `kroneckerP2` in the formula.
    • Does not support empty tensors.
    • Shape is [N2, N2], where N2 is consistent with the N2 dimension in x. Shape [0,0] is supported only in the perGroup scenario, indicating that the operator does not use the right matrix for calculation and only performs left matrix multiplication.
    • Data type is consistent with the data type of input parameter x.
    FLOAT16, BFLOAT16 ND 2 √
    groupListOptional (aclTensor*) Optional input Represents the quantization group size distribution of input `x`.
    • Does not support empty tensors.
    • When groupListType is 0 or 1, the shape is [G]. When groupListType is 2, the shape is [G, 2]. G indicates the number of groups and must be less than or equal to 1024.
    INT64 ND 1-2 √
    clipRatio (double) Input Controls the clipping ratio for quantization, corresponding to `clipRatio` in the formula.
    • Input data range: (0, 1].
    - - - -
    dstTypeMax (double) Input Represents the value of maxType, which is Amax(DType) in the corresponding formula.
    • Supported values: 0.0 and 6.0-12.0. A value of 0.0 indicates that this parameter is not used; a value of 6.0-12.0 indicates the maximum value of the target data type. This value can be set only when the data type is FLOAT4_E2M1.
    - - - -
    groupListType (int64) Input Indicates the grouping mode of the groupList input.
    • When groupListOptional is not nullptr, values 0, 1, and 2 are supported.
    - - - -
    out (aclTensor*) Output Output tensor, corresponding to out in the formula.
    • Does not support empty tensors.
    • If the data type is INT32, the last dimension of shape is 1/8 of the last dimension of input x, and the other dimensions are consistent with x.
    • If the data type is INT4, the shape is consistent with input x.
    • If the data type is FLOAT4_E2M1, the shape is [M,N1*N2].
    INT4, INT32, FLOAT4_E2M1 ND 3 or 2 √
    quantScale (aclTensor*) Output Quantization factor of the output, corresponding to quantScale in the formula.
    • Empty tensors are not supported.
    • When the quantized output type is INT4 or INT32, the shape is [M], where M is consistent with the M dimension of x, and the data type is FLOAT32.
    • When the quantized output type is FLOAT4_E2M1, the shape is [M,ceildiv(N1*N2,64),2], and the data type is FLOAT8_E8M0.
    FLOAT32, FLOAT8_E8M0 ND 1 or 3 √
    workspaceSize (uint64_t*) Output Returns the workspace size that needs to be applied by the user on the Device side. - - - - -
    executor (aclOpExecutor**) Output Returns the op executor, which includes the calculation process of the operator. - - - - -
  • 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:

    Error Code Error code Description
    ACLNN_ERR_PARAM_NULLPTR 161001 Required inputs (x, kroneckerP1, kroneckerP2) or required outputs (out, quantScale) in the input parameters are null pointers.
    ACLNN_ERR_PARAM_INVALID 161002 The data type or data format of x, kroneckerP1, kroneckerP2, out, or quantScale is not supported.
    The data type of kroneckerP1 or kroneckerP2 is inconsistent with that of x.
    The dimension of x is not 3.
    The first dimension of x exceeds the range [1, 262144], the second dimension exceeds [1, 256], or the third dimension exceeds [1, 256].
    The dimension of kroneckerP1 is not 2, or the first and second dimensions are inconsistent with the second dimension of x.
    In the perToken scenario, the dimension of kroneckerP2 is not 2, or the first and second dimensions are inconsistent with the third dimension of x.
    In the INT4 or INT32 scenario, the dimension of quantScale is not 1, or the first dimension is inconsistent with the first dimension of x.
    In the FLOAT4_E2M1 scenario, the dimension of quantScale is not 3, or the first dimension is inconsistent with the first dimension of x.
    The value of clipRatio is out of the range (0, 1].
    When the data type of out is INT4, the tail axis size of the shape of x is not even, or the shape of x is inconsistent with the shape of out.
    When the data type of out is INT32, the tail axis of the shape of x is not 8 times the tail axis size of the shape of out, or the non-tail-axis sizes of the shapes of x and out are inconsistent.
    When the data type of out is INT32, the tail axis of the shape of x is not 8 times the tail axis size of the shape of out, or the non-tail-axis sizes of the shapes of x and out are inconsistent.
    The data type, dimension, shape, or parameter value of groupList and groupListType does not meet the constraints.

aclnnFlatQuantV3

  • Parameters:

    Parameter Input/Output Description
    workspace Input Workspace memory address applied by the Device side.
    workspaceSize Input Size of the workspace applied by the Device side, obtained by calling the first-phase API aclnnFlatQuantV3GetWorkspaceSize.
    executor Input Executor of the operator, which includes the calculation flow of the operator.
    stream Input Stream for task execution.
  • Return Value

    aclnnStatus: return status code. For details, see aclnn Return Codes.

Constraints

  • The parameters groupListOptional and groupListType must meet the following constraints:
    • Ascend 950PR&950DT products:
      • groupListOptional supports only nullptr.
    • Atlas A3 products and Atlas A2 products:
      • When groupListOptional is not nullptr:
        • The value of groupListType must be selected from [0, 1, 2].
        • When groupListType is 0 or 1, the shape is [G]. When groupListType is 2, the shape is [G, 2]. G indicates the number of groups and must be less than or equal to 1024.
        • The values of groupListOptional must meet the following conditions. Otherwise, the output cannot be guaranteed to meet expectations:
          • When groupListType is 0, groupListOptional must be a non-negative monotonically non-decreasing sequence, indicating the cumsum result (cumulative sum) of the size of each group after grouping. The last value must be less than or equal to the first dimension of the tensor in x.
          • When groupListType is 1, groupListOptional must be a non-negative sequence, indicating the size of each group after grouping. The sum of the values must be less than or equal to the first dimension of the tensor in x.
          • When groupListType is 2, groupListOptional must be a non-negative sequence. The data layout is [[groupIdx0, groupSize0], [groupIdx1, groupSize1]...], where groupSize indicates the size of each group after grouping. The sum of the values in the second column must be less than or equal to the first dimension of the tensor in x.
  • Deterministic computation:
    • aclnnFlatQuantV3 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_flat_quant_v3.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 shape_size = 1;
    for (auto i : shape) {
        shape_size *= i;
    }
    return shape_size;
}

int Init(int32_t deviceId, aclrtStream* stream)
{
    // Boilerplate: initialize resources.
    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 the 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;
}

int main()
{
    // 1. (Boilerplate) Initialize the device/stream. For details, see the acl API reference.
    // Set deviceId based on the actual device.
    int32_t deviceId = 0;
    aclrtStream stream;
    auto ret = Init(deviceId, &stream);
    // Handle the check as needed.
    CHECK_RET(ret == 0, LOG_PRINT("Init acl failed. ERROR: %d\n", ret); return ret);
    // 2. Construct the input and output. Customize the construction based on the API.
    std::vector<int64_t> xShape = {16, 16, 16};
    std::vector<int64_t> kroneckerP1Shape = {16, 16};
    std::vector<int64_t> kroneckerP2Shape = {16, 16};
    std::vector<int64_t> outShape = {16, 16, 2};
    std::vector<int64_t> quantScaleShape = {16};
    void* xDeviceAddr = nullptr;
    void* kroneckerP1DeviceAddr = nullptr;
    void* kroneckerP2DeviceAddr = nullptr;
    void* outDeviceAddr = nullptr;
    void* quantScaleDeviceAddr = nullptr;
    aclTensor* x = nullptr;
    aclTensor* kroneckerP1 = nullptr;
    aclTensor* kroneckerP2 = nullptr;
    aclTensor* out = nullptr;
    aclTensor* quantScale = nullptr;
    double clipRatio = 1.0;
    double dstTypeMax = 0.0;
    int64_t groupListType = 0;
    std::vector<aclFloat16> xHostData(16 * 16 * 16, aclFloatToFloat16(1));
    std::vector<aclFloat16> kroneckerP1HostData(16 * 16, aclFloatToFloat16(1));
    std::vector<aclFloat16> kroneckerP2HostData(16 * 16, aclFloatToFloat16(1));
    std::vector<int32_t> outHostData(16 * 16 * 2, 1);
    std::vector<float> quantScaleHostData(16, 0);
    // Create the x aclTensor.
    ret = CreateAclTensor(xHostData, xShape, &xDeviceAddr, aclDataType::ACL_FLOAT16, &x);
    CHECK_RET(ret == ACL_SUCCESS, return ret);

    // Create the kroneckerP1 aclTensor.
    ret = CreateAclTensor(kroneckerP1HostData, kroneckerP1Shape, &kroneckerP1DeviceAddr, aclDataType::ACL_FLOAT16,
                          &kroneckerP1);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    // Create the kroneckerP2 aclTensor.
    ret = CreateAclTensor(kroneckerP2HostData, kroneckerP2Shape, &kroneckerP2DeviceAddr, aclDataType::ACL_FLOAT16,
                          &kroneckerP2);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    // Create the out aclTensor.
    ret = CreateAclTensor(outHostData, outShape, &outDeviceAddr, aclDataType::ACL_INT32, &out);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    // Create the quantScale aclTensor.
    ret = CreateAclTensor(quantScaleHostData, quantScaleShape, &quantScaleDeviceAddr, aclDataType::ACL_FLOAT,
                          &quantScale);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    // 3. Call the CANN operator library API. Replace it with the specific API.
    uint64_t workspaceSize = 0;
    aclOpExecutor* executor;
    // Call the first-phase API of aclnnFlatQuantV3.
    ret = aclnnFlatQuantV3GetWorkspaceSize(x, kroneckerP1, kroneckerP2, nullptr, clipRatio, dstTypeMax, groupListType,
                                           out, quantScale, &workspaceSize, &executor);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnFlatQuantV3GetWorkspaceSize failed. ERROR: %d\n", ret); return ret);
    // Allocate device memory based on the workspaceSize computed 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 aclnnFlatQuantV3.
    ret = aclnnFlatQuantV3(workspaceAddr, workspaceSize, executor, stream);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnFlatQuantV3 failed. ERROR: %d\n", ret); return ret);
    // 4. (boilerplate) Synchronize and 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 and copy the result on the device memory to the host side. Modify it according to the specific API definition.
    auto size = GetShapeSize(outShape);
    std::vector<int32_t> resultData(size, 0);
    ret = aclrtMemcpy(resultData.data(), resultData.size() * sizeof(resultData[0]), outDeviceAddr,
                      size * sizeof(int32_t), ACL_MEMCPY_DEVICE_TO_HOST);
    CHECK_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]);
    }

    auto quantScaleSize = GetShapeSize(quantScaleShape);
    std::vector<float> quantScaleResultData(quantScaleSize, 0);
    ret = aclrtMemcpy(quantScaleResultData.data(), quantScaleResultData.size() * sizeof(quantScaleResultData[0]),
                      quantScaleDeviceAddr, quantScaleSize * sizeof(float), ACL_MEMCPY_DEVICE_TO_HOST);
    CHECK_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 < quantScaleSize; i++) {
        LOG_PRINT("result[%ld] is: %f\n", i, quantScaleResultData[i]);
    }

    // 6. Release aclTensor. Modify it according to the specific API definition.
    aclDestroyTensor(x);
    aclDestroyTensor(kroneckerP1);
    aclDestroyTensor(kroneckerP2);
    aclDestroyTensor(out);
    aclDestroyTensor(quantScale);

    // 7. Release device resources. Modify it according to the specific API definition.
    aclrtFree(xDeviceAddr);
    aclrtFree(kroneckerP1DeviceAddr);
    aclrtFree(kroneckerP2DeviceAddr);
    aclrtFree(outDeviceAddr);
    aclrtFree(quantScaleDeviceAddr);
    if (workspaceSize > 0) {
        aclrtFree(workspaceAddr);
    }
    aclrtDestroyStream(stream);
    aclrtResetDevice(deviceId);
    aclFinalize();
    return 0;
}