aclnnClaGateQuant

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: A fused operator that performs the combined computation of weighted merging of two CLA (Cross-Layer Attention) head-wise gates and dynamic block quantization. It first applies Sigmoid gating to the Attention outputs of the Global/CLA branch and the Local/SWA branch and merges them with weights, then reshapes the merged result into [T, K] (K = N*D) for block-based dynamic quantization, and outputs low-precision FP8/FP4 tensors and the corresponding E8M0 scaling factors. When dstType is FLOAT8_E4M3FN or FLOAT8_E5M2, the algorithm for computing mxscale is specified by the value of scaleAlg. The quantization mode is controlled by dualAxisFlag: in single-axis mode (dualAxisFlag=0, default), only one set of quantized data is output along the K direction ([1,32] block, row-wise), and a null pointer is passed for colDataOut / colScaleOut; in dual-axis mode (dualAxisFlag=1), col-wise quantized data is additionally output along the T direction ([32,1] block, col-wise).

  • Formula:

    Stage 1: CLA gate fusion

    • Two head-wise Sigmoid gating paths (z_g and z_l are the gate logits of the two paths):

      sg=σ(zg),sl=σ(zl)s_g = \sigma(z_g), \qquad s_l = \sigma(z_l)

      where σ(x)=11+e−x\sigma(x) = \dfrac{1}{1 + e^{-x}} is the Sigmoid function.

    • CLA gate fusion (per token, per head):

      merged[t,n,d]=sg[t,n]⋅Og[t,n,d]+sl[t,n]⋅Ol[t,n,d]merged[t, n, d] = s_g[t, n] \cdot O_g[t, n, d] + s_l[t, n] \cdot O_l[t, n, d]
    • Logical matrix before quantization:

      X=reshape⁡(merged,[T,K]),K=N×DX = \operatorname{reshape}(merged, [T, K]), \qquad K = N \times D

    Stage 2: dual-axis dynamic block quantization

    • Use case 1: When scaleAlg is 0, that is, the OCP Microscaling Formats (Mx) Specification implementation:
      • Row-wise quantization (K direction): Groups X into groups of 32 numbers along the K dimension, and each group of 32 numbers {{Vi}i=132}\{\{V_i\}_{i=1}^{32}\} is quantized to {mxscale_row,{Pi}i=132}\{mxscale\_row, \{P_i\}_{i=1}^{32}\}

        shared_exp=floor(log2(maxi(∣Vi∣)))−emaxshared\_exp = floor(log_2(max_i(|V_i|))) - emax mxscale_row=2shared_expmxscale\_row = 2^{shared\_exp} Pi=cast_to_dst_type(Vi/mxscale_row,round_mode), i from 1 to 32P_i = cast\_to\_dst\_type(V_i/mxscale\_row, round\_mode), \space i\space from\space 1\space to\space 32
      • Col-wise quantization (T direction, only when dualAxisFlag=1): Groups X along the T dimension into groups of 32 values, where each group of 32 values {{Vj}j=132}\{\{V_j\}_{j=1}^{32}\} is quantized to {mxscale_col,{Pj}j=132}\{mxscale\_col, \{P_j\}_{j=1}^{32}\}

        shared_exp=floor(log2(maxj(∣Vj∣)))−emaxshared\_exp = floor(log_2(max_j(|V_j|))) - emax mxscale_col=2shared_expmxscale\_col = 2^{shared\_exp} Pj=cast_to_dst_type(Vj/mxscale_col,round_mode), j from 1 to 32P_j = cast\_to\_dst\_type(V_j/mxscale\_col, round\_mode), \space j\space from\space 1\space to\space 32
      • The PiP_{i} obtained by Row-wise quantization forms the output rowDataOut according to the corresponding positions of ViV_{i}, and mxscale_row forms the output rowScaleOut according to the corresponding grouping on the K dimension (the scales of every two adjacent groups form a pair and are stored in the last dimension, with the shape [T, ceil(ND/64), 2]; 0 is filled by even padding when the last group contains fewer than two). The PjP_{j} obtained by Col-wise quantization forms the output colDataOut according to the corresponding positions of VjV_{j}, and mxscale_col forms the output colScaleOut according to the corresponding grouping on the T dimension (with the shape [ceil(T/64), ND, 2], likewise filled with 0 by even padding).

      • emax: The exponent of the maximum normal number of the corresponding data type.

| DataType | Emax | | :-----------: | :--: | | FLOAT4_E2M1 | 2 | | FLOAT4_E1M2 | 0 | | FLOAT8_E4M3FN | 8 | | FLOAT8_E5M2 | 15 |

  • Use case 2: When scaleAlg is 1, only FP8 types are involved (round-up algorithm):
    • Row-wise quantization (K direction): Groups X along the K dimension into groups of 32 values (each group with a length of 32), computes a block scaling factor Sfp32bS_{fp32}^b separately for each group, and then maps all elements in each group to the target low-precision type FP8 using the same Sfp32bS_{fp32}^b. If the last group contains fewer than 32 elements, the missing values are treated as 0 and the group is processed as a complete group.

      • Find the maximum absolute value of the values in the group:Amax(Dfp32b)=max({∣di∣}i=132)Amax(D_{fp32}^b)=max(\{|d_{i}|\}_{i=1}^{32})
      • Maps FP32 to the range representable by the target data type FP8, where Amax(DType)Amax(DType) is the maximum value representable by the target precision (448 for FLOAT8_E4M3FN, 57344 for FLOAT8_E5M2)Sfp32b=Amax(Dfp32b)Amax(DType)S_{fp32}^b = \frac{Amax(D_{fp32}^b)}{Amax(DType)}
      • Convert the block scale factor Sfp32bS_{fp32}^b to the representable scale value Sue8m0bS_{ue8m0}^b in FP8 format.
      • Extract the unbiased exponent EintbE_{int}^b and mantissa MfixpbM_{fixp}^b from the block floating-point scale factor Sfp32bS_{fp32}^b.
      • 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+1, ifSfp32b is a subnormal number, andMfixpb>0.5Eintb, 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 + 1, & \text{ if} S_{fp32}^b \text{ is a subnormal number, and} M_{fixp}^b > 0.5 \\ E_{int}^b, & \text{ otherwise} \end{cases}
      • Calculate the block scaling factor: mxscale_row=Sue8m0b=2Eintbmxscale\_row=S_{ue8m0}^b=2^{E_{int}^b}
      • Calculate the block conversion factor: Rfp32b=1fp32(Sue8m0b)R_{fp32}^b=\frac{1}{fp32(S_{ue8m0}^b)}
      • Apply the final step of quantization. For each element within a group, Pi=cast_to_dst_type(dfp32i⋅Rfp32b)P_i = cast\_to\_dst\_type(d_{fp32}^i \cdot R_{fp32}^b), and the final quantized result of the Row-wise output is (mxscale_row,[Pi]i=132)\left(mxscale\_row, [P_i]_{i=1}^{32}\right), where mxscale_rowmxscale\_row indicates the block scaling factor, i.e., Sue8m0bS_{ue8m0}^b, and [Pi]i=132[P_i]_{i=1}^{32} indicates the quantized data within the group.
    • Col-wise quantization (T direction, only when dualAxisFlag=1): Meanwhile, group X along the T dimension in groups of 32 elements. Use the same rounding-up algorithm as Row-wise to independently calculate the block scaling factor for each group and perform quantization, obtaining mxscale_colmxscale\_col and {Pj}j=132\{P_j\}_{j=1}^{32}. The quantized result of the Col-wise output is (mxscale_col,[Pj]j=132)\left(mxscale\_col, [P_j]_{j=1}^{32}\right).

    • The Row-wise quantized PiP_{i} form the output rowDataOut according to the position of the corresponding ViV_{i}, and mxscale_row form the output rowScaleOut according to the grouping on the K dimension (the scales of every two adjacent groups form a pair, stored in the last dimension, with the shape [T, ceil(ND/64), 2]; when the last group has fewer than two, the even pad is filled with 0). The Col-wise quantized PjP_{j} form the output colDataOut according to the position of the corresponding VjV_{j}, and mxscale_col form the output colScaleOut according to the grouping on the T dimension (the shape is [ceil(T/64), ND, 2], and likewise the even pad is filled with 0).

Function Prototype

Each operator uses a two-phase API. You must first call the "aclnnClaGateQuantGetWorkspaceSize" API to obtain the workspace size required for the calculation and the executor that includes the calculation process of the operator, and then call the "aclnnClaGateQuant" API to perform the calculation.

aclnnStatus aclnnClaGateQuantGetWorkspaceSize(
  const aclTensor *globalAttn,
  const aclTensor *localAttn,
  const aclTensor *globalGateLogits,
  const aclTensor *localGateLogits,
  const char       *roundMode,
  int64_t          scaleAlg,
  int64_t          dstType,
  const char       *inputAttnLayout,
  bool            dualAxisFlag,
  const aclTensor *rowDataOut,
  const aclTensor *rowScaleOut,
  const aclTensor *colDataOut,
  const aclTensor *colScaleOut,
  uint64_t        *workspaceSize,
  aclOpExecutor   **executor)
aclnnStatus aclnnClaGateQuant(
  void          *workspace,
  uint64_t       workspaceSize,
  aclOpExecutor *executor,
  aclrtStream    stream)

aclnnClaGateQuantGetWorkspaceSize

  • Parameters:

    Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor
    globalAttn (aclTensor*) Input Attention output of the Global/CLA branch, which is O_g in the formula.
    • Shape is [T, N, D], where T is a dynamic dimension (number of tokens on this rank).
    • Data type is consistent with localAttn; BF16/FP16 are supported.
    • Data format is ND (logical layout TND, specified by the inputAttnLayout parameter).
    • Null tensors are not supported.
    BFLOAT16, FLOAT16 ND 3 √
    localAttn (aclTensor*) Input Attention output of the Local/SWA branch, which is O_l in the formula.
    • Same shape as globalAttn: [T, N, D].
    • Same data type as globalAttn; supports BF16/FP16.
    • Data format: ND (logical layout TND).
    • Does not support null tensors.
    BFLOAT16, FLOAT16 ND 3 √
    globalGateLogits (aclTensor*) Input Pre-Sigmoid value z_g of the global gate.
    • Shape: [T, N], where T is consistent with the two inputs.
    • Same data type as globalAttn / localAttn.
    • Data format: ND.
    • Does not support null tensors.
    BFLOAT16, FLOAT16 ND 2 √
    localGateLogits (aclTensor*) Input Pre-Sigmoid value z_l of the local gate.
    • Shape is [T, N], where T is consistent with the two inputs.
    • Data type is consistent with globalAttn / localAttn.
    • Data format is ND.
    • Does not support null tensor.
    BFLOAT16, FLOAT16 ND 2 √
    roundMode (char*) Input Indicates the rounding mode for quantized data conversion, corresponding to round_mode in the formula.
    • When dstType is 35/36, indicating that the data types of the output rowDataOut and colDataOut are FLOAT8_E5M2/FLOAT8_E4M3FN, only {"rint"} is supported.
    • When dstType is 40/41, indicating that the data types of the output rowDataOut and colDataOut are FLOAT4_E2M1/FLOAT4_E1M2, {"rint", "floor", "round"} are supported.
    • If a null pointer is passed, the "rint" mode is used.
    STRING - - -
    scaleAlg (int64_t) Input Indicates the calculation method of rowScaleOut and colScaleOut.
    • Value range: {0, 1}. 0 indicates Case 1 (OCP Microscaling Formats (Mx) Specification implementation), and 1 indicates Case 2 (cuBLAS round-up algorithm, FP8 only).
    • Only scaleAlg 0 is supported when dstType is 40/41 (FP4).
    INT64 - - -
    dstType (int64_t) Input Indicates the data type of rowDataOut and colDataOut after the specified quantization conversion.
    • The value range is {35, 36, 40, 41}, corresponding to the data types of the outputs rowDataOut and colDataOut: {35: FLOAT8_E5M2, 36: FLOAT8_E4M3FN, 40: FLOAT4_E2M1, 41: FLOAT4_E1M2}.
    • When dstType is 40/41, K=N*D must be divisible by 4.
    INT64 - - -
    inputAttnLayout (char*) Input Layout format of the input globalAttn/localAttn tensors.
    • Currently, only the value TND is supported.
    STRING - - -
    dualAxisFlag (bool) Input Quantization mode.
    • false (default): single-axis quantization, outputs only one set of row-wise quantized data. In this case, colDataOut / colScaleOut must pass a null pointer, and the interface does not access col outputs; rowDataOut / rowScaleOut is bit-for-bit identical to the output in dual-axis mode.
    • true: dual-axis quantization, outputs both row-wise and col-wise quantized data.
    BOOL - - -
    rowDataOut (aclTensor*) Output Indicates the Row-wise quantized result of the fusion result, corresponding to Pi in the formula.
    • Shape is [T, N*D].
    • The data type is determined by dstType.
    FLOAT8_E5M2, FLOAT8_E4M3FN, FLOAT4_E2M1, FLOAT4_E1M2 ND 2 -
    rowScaleOut (aclTensor*) Output Indicates the quantization scale corresponding to each [1,32] group in Row-wise, which is mxscale_row in the corresponding formula.
    • The shape is [T, ceil(N*D/64), 2].
    • The data type is FLOAT8_E8M0.
    • Even padding is required, and the pad fill value is 0.
    FLOAT8_E8M0 ND 3 -
    colDataOut (aclTensor*) Output Indicates the Col-wise quantized result of the fused result, which is Pj in the corresponding formula.
    • When dualAxisFlag=1: shape is [T, N*D], and the data type is consistent with rowDataOut (the numeric encoding is usually different from rowDataOut).
    • When dualAxisFlag=0: pass a null pointer; the interface does not access this output.
    FLOAT8_E5M2, FLOAT8_E4M3FN, FLOAT4_E2M1, FLOAT4_E1M2 ND 2 -
    colScaleOut (aclTensor*) Output Indicates the quantization scale corresponding to each [32,1] grouping in the Col-wise direction, which is mxscale_col in the formula.
    • When dualAxisFlag=1: shape is [ceil(T/64), N*D, 2], and the data type is FLOAT8_E8M0.
    • Even padding is required, and the padding fill value is 0.
    • When dualAxisFlag=0: pass a null pointer; the interface does not access this output.
    FLOAT8_E8M0 ND 3 -
    workspaceSize (uint64_t*) Output Returns the workspace size to be applied by 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 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 globalAttn, localAttn, globalGateLogits, localGateLogits, rowDataOut, rowScaleOut, workspaceSize, or executor is a null pointer; when dualAxisFlag=1, colDataOut or colScaleOut is a null pointer.
    ACLNN_ERR_PARAM_INVALID 161002 The data types and data formats of globalAttn, localAttn, globalGateLogits, localGateLogits, roundMode, scaleAlg, dstType, rowDataOut, rowScaleOut, colDataOut, and colScaleOut are not supported.
    The shapes of globalAttn, localAttn, globalGateLogits, localGateLogits, rowDataOut, rowScaleOut, colDataOut, or colScaleOut do not meet the validation conditions (for example, the globalAttn/localAttn shapes are inconsistent, or the gate logits are not in [T, N]).
    roundMode, scaleAlg, or dstType does not match the currently supported values (for example, dstType is not in {35, 36, 40, 41}; K is not divisible by 4 or scaleAlg is not 0 when dstType is 40/41; roundMode is not "rint" for FP8 output).
    ACLNN_ERR_RUNTIME_ERROR 361001 The current platform is not among the supported platforms.
    ACLNN_ERR_INNER_TILING_ERROR 561002 Tiling or internal calculation error.

aclnnClaGateQuant

  • Parameters:

    Parameter Input/Output Description
    workspace Input Workspace memory address applied by the Device side.
    workspaceSize Input Workspace size applied by the Device side, obtained by the first-phase API aclnnClaGateQuantGetWorkspaceSize.
    executor Input Op executor, which includes the calculation flow of the operator.
    stream Input Specifies the stream for executing tasks.
  • Return value

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

Constraints

  • Deterministic computation: aclnnClaGateQuant defaults to a deterministic implementation.
  • The inputs globalAttn / localAttn must be 3D tensors with consistent shapes, [T, N, D]; N ∈ [1,128], D ∈ {128, 256}.
  • The inputs globalGateLogits / localGateLogits must be 2D tensors, [T, N], with data types consistent with globalAttn / localAttn.
  • When dstType is FLOAT4_E2M1/FLOAT4_E1M2, K=N*D must be divisible by 4.
  • The FP8 output types (FLOAT8_E5M2/FLOAT8_E4M3FN) support only the "rint" rounding mode.
  • The quantization block is fixed to 32: row-wise uses a [1,32] block (along the K direction), and col-wise uses a [32,1] block (along the T direction).
  • Shape constraints of rowScaleOut and colScaleOut:
    • rowScaleOut.shape[1] = ceil(ceil(ND/32) / 2) = ceil(ND/64).
    • rowScaleOut.shape[2] = 2.
    • colScaleOut.shape[0] = ceil(ceil(T/32) / 2) = ceil(T/64).
    • colScaleOut.shape[2] = 2.
    • Both require even padding, and the pad fill value is 0.
  • When dualAxisFlag=0 (single-axis mode), a null pointer must be passed for colDataOut / colScaleOut, and the API neither validates nor accesses the col outputs. rowDataOut / rowScaleOut are bitwise consistent with the outputs in dual-axis mode (dualAxisFlag=1).
  • Batch consistency:
    • Ascend 950PR&950DT products: single-axis defaults to a Batch-consistent implementation; dual-axis is supported by default when T is a multiple of 64, and not supported otherwise.

Example

The following is sample code for reference only. For details about compilation and execution, see Compile and Run Samples.

#include <iostream>
#include <memory>
#include <vector>
#include "acl/acl.h"
#include "aclnnop/aclnn_cla_gate_quant.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 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;
}

void Finalize(int32_t deviceId, aclrtStream stream)
{
    aclrtDestroyStream(stream);
    aclrtResetDevice(deviceId);
    aclFinalize();
}

int aclnnClaGateQuantTest(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);

    // 2. Construct the inputs and outputs as required by the API.
    // Input globalAttn / localAttn shape: [T, N, D] = [256, 64, 128], K = N*D = 8192
    std::vector<int64_t> outShape = {256, 64, 128};
    // Input gate logits shape: [T, N] = [256, 64]
    std::vector<int64_t> logitsShape = {256, 64};
    // Quantized data output shape: [T, K] = [256, 8192]
    std::vector<int64_t> dataOutShape = {256, 8192};
    // rowScaleOut shape: [T, ceil(K/64), 2] = [256, 128, 2]
    std::vector<int64_t> rowScaleOutShape = {256, 128, 2};
    // colScaleOut shape: [ceil(T/64), K, 2] = [4, 8192, 2]
    std::vector<int64_t> colScaleOutShape = {4, 8192, 2};

    void* globalAttnDeviceAddr = nullptr;
    void* localAttnDeviceAddr = nullptr;
    void* globalGateLogitsDeviceAddr = nullptr;
    void* localGateLogitsDeviceAddr = nullptr;
    void* rowDataOutDeviceAddr = nullptr;
    void* rowScaleOutDeviceAddr = nullptr;
    void* colDataOutDeviceAddr = nullptr;
    void* colScaleOutDeviceAddr = nullptr;

    aclTensor* globalAttn = nullptr;
    aclTensor* localAttn = nullptr;
    aclTensor* globalGateLogits = nullptr;
    aclTensor* localGateLogits = nullptr;
    aclTensor* rowDataOut = nullptr;
    aclTensor* rowScaleOut = nullptr;
    aclTensor* colDataOut = nullptr;
    aclTensor* colScaleOut = nullptr;

    // Initialize the input data (BF16).
    std::vector<uint16_t> outHostData(256 * 64 * 128, 0);
    for (int64_t i = 0; i < 256 * 64 * 128; i++) {
        outHostData[i] = static_cast<uint16_t>(i % 100);
    }
    std::vector<uint16_t> logitsHostData(256 * 64, 0);
    for (int64_t i = 0; i < 256 * 64; i++) {
        logitsHostData[i] = static_cast<uint16_t>(i % 50);
    }
    std::vector<uint8_t> rowDataOutHostData(256 * 8192, 0);
    std::vector<uint8_t> rowScaleOutHostData(256 * 128 * 2, 0);
    std::vector<uint8_t> colDataOutHostData(256 * 8192, 0);
    std::vector<uint8_t> colScaleOutHostData(4 * 8192 * 2, 0);

    // Set the parameters.
    const char* roundMode = "rint";
    int64_t scaleAlg = 1;                    // cuBLAS
    int64_t dstType = 36;                    // FLOAT8_E4M3FN
    const char* layout = "TND";              // TND
    bool dualAxisFlag = true;                // Dual-axis quantization

    // Create the globalAttn aclTensor.
    ret = CreateAclTensor(outHostData, outShape, &globalAttnDeviceAddr, aclDataType::ACL_BF16, &globalAttn);
    std::unique_ptr<aclTensor, aclnnStatus (*)(const aclTensor*)> globalAttnTensorPtr(globalAttn, aclDestroyTensor);
    std::unique_ptr<void, aclError (*)(void*)> globalAttnDeviceAddrPtr(globalAttnDeviceAddr, aclrtFree);
    CHECK_RET(ret == ACL_SUCCESS, return ret);

    // Create the localAttn aclTensor.
    ret = CreateAclTensor(outHostData, outShape, &localAttnDeviceAddr, aclDataType::ACL_BF16, &localAttn);
    std::unique_ptr<aclTensor, aclnnStatus (*)(const aclTensor*)> localAttnTensorPtr(localAttn, aclDestroyTensor);
    std::unique_ptr<void, aclError (*)(void*)> localAttnDeviceAddrPtr(localAttnDeviceAddr, aclrtFree);
    CHECK_RET(ret == ACL_SUCCESS, return ret);

    // Create the globalGateLogits aclTensor.
    ret = CreateAclTensor(logitsHostData, logitsShape, &globalGateLogitsDeviceAddr, aclDataType::ACL_BF16, &globalGateLogits);
    std::unique_ptr<aclTensor, aclnnStatus (*)(const aclTensor*)> globalGateLogitsTensorPtr(globalGateLogits, aclDestroyTensor);
    std::unique_ptr<void, aclError (*)(void*)> globalGateLogitsDeviceAddrPtr(globalGateLogitsDeviceAddr, aclrtFree);
    CHECK_RET(ret == ACL_SUCCESS, return ret);

    // Create the localGateLogits aclTensor.
    ret = CreateAclTensor(logitsHostData, logitsShape, &localGateLogitsDeviceAddr, aclDataType::ACL_BF16, &localGateLogits);
    std::unique_ptr<aclTensor, aclnnStatus (*)(const aclTensor*)> localGateLogitsTensorPtr(localGateLogits, aclDestroyTensor);
    std::unique_ptr<void, aclError (*)(void*)> localGateLogitsDeviceAddrPtr(localGateLogitsDeviceAddr, aclrtFree);
    CHECK_RET(ret == ACL_SUCCESS, return ret);

    // Create the rowDataOut aclTensor.
    ret = CreateAclTensor(rowDataOutHostData, dataOutShape, &rowDataOutDeviceAddr, aclDataType::ACL_FLOAT8_E4M3FN, &rowDataOut);
    std::unique_ptr<aclTensor, aclnnStatus (*)(const aclTensor*)> rowDataOutTensorPtr(rowDataOut, aclDestroyTensor);
    std::unique_ptr<void, aclError (*)(void*)> rowDataOutDeviceAddrPtr(rowDataOutDeviceAddr, aclrtFree);
    CHECK_RET(ret == ACL_SUCCESS, return ret);

    // Create the rowScaleOut aclTensor.
    ret = CreateAclTensor(rowScaleOutHostData, rowScaleOutShape, &rowScaleOutDeviceAddr, aclDataType::ACL_FLOAT8_E8M0, &rowScaleOut);
    std::unique_ptr<aclTensor, aclnnStatus (*)(const aclTensor*)> rowScaleOutTensorPtr(rowScaleOut, aclDestroyTensor);
    std::unique_ptr<void, aclError (*)(void*)> rowScaleOutDeviceAddrPtr(rowScaleOutDeviceAddr, aclrtFree);
    CHECK_RET(ret == ACL_SUCCESS, return ret);

    // Create colDataOut aclTensor.
    ret = CreateAclTensor(colDataOutHostData, dataOutShape, &colDataOutDeviceAddr, aclDataType::ACL_FLOAT8_E4M3FN, &colDataOut);
    std::unique_ptr<aclTensor, aclnnStatus (*)(const aclTensor*)> colDataOutTensorPtr(colDataOut, aclDestroyTensor);
    std::unique_ptr<void, aclError (*)(void*)> colDataOutDeviceAddrPtr(colDataOutDeviceAddr, aclrtFree);
    CHECK_RET(ret == ACL_SUCCESS, return ret);

    // Create colScaleOut aclTensor.
    ret = CreateAclTensor(colScaleOutHostData, colScaleOutShape, &colScaleOutDeviceAddr, aclDataType::ACL_FLOAT8_E8M0, &colScaleOut);
    std::unique_ptr<aclTensor, aclnnStatus (*)(const aclTensor*)> colScaleOutTensorPtr(colScaleOut, aclDestroyTensor);
    std::unique_ptr<void, aclError (*)(void*)> colScaleOutDeviceAddrPtr(colScaleOutDeviceAddr, aclrtFree);
    CHECK_RET(ret == ACL_SUCCESS, return ret);

    // Call the CANN operator library API.
    uint64_t workspaceSize = 0;
    aclOpExecutor* executor;

    // Call the first-phase API of aclnnClaGateQuant (dual-axis quantization).
    ret = aclnnClaGateQuantGetWorkspaceSize(globalAttn, localAttn, globalGateLogits, localGateLogits,
        roundMode, scaleAlg, dstType, layout, dualAxisFlag,
        rowDataOut, rowScaleOut, colDataOut, colScaleOut, &workspaceSize, &executor);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnClaGateQuantGetWorkspaceSize 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_RET(ret == ACL_SUCCESS, LOG_PRINT("allocate workspace failed. ERROR: %d\n", ret); return ret);
        workspaceAddrPtr.reset(workspaceAddr);
    }

    // Call the second-phase API of aclnnClaGateQuant.
    ret = aclnnClaGateQuant(workspaceAddr, workspaceSize, executor, stream);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnClaGateQuant failed. ERROR: %d\n", ret); return ret);

    // (boilerplate) Synchronize and wait for the task to complete.
    ret = aclrtSynchronizeStream(stream);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtSynchronizeStream failed. ERROR: %d\n", ret); return ret);

    // Obtain the output value and copy the result from device memory to host memory.
    auto size1 = GetShapeSize(dataOutShape);
    auto size2 = GetShapeSize(dataOutShape);
    std::vector<uint8_t> rowDataOutData(size1, 0);
    std::vector<uint8_t> colDataOutData(size2, 0);

    ret = aclrtMemcpy(rowDataOutData.data(), rowDataOutData.size() * sizeof(uint8_t), rowDataOutDeviceAddr,
                      size1 * sizeof(uint8_t), ACL_MEMCPY_DEVICE_TO_HOST);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("copy rowDataOut from device to host failed. ERROR: %d\n", ret);
              return ret);
    ret = aclrtMemcpy(colDataOutData.data(), colDataOutData.size() * sizeof(uint8_t), colDataOutDeviceAddr,
                      size2 * sizeof(uint8_t), ACL_MEMCPY_DEVICE_TO_HOST);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("copy colDataOut from device to host failed. ERROR: %d\n", ret);
              return ret);

    // Print part of the output results.
    LOG_PRINT("rowDataOut first 10 elements:\n");
    for (int64_t i = 0; i < 10 && i < size1; i++) {
        LOG_PRINT("rowDataOut[%ld] = %d\n", i, rowDataOutData[i]);
    }
    LOG_PRINT("colDataOut first 10 elements:\n");
    for (int64_t i = 0; i < 10 && i < size2; i++) {
        LOG_PRINT("colDataOut[%ld] = %d\n", i, colDataOutData[i]);
    }

    return ACL_SUCCESS;
}

int main()
{
    // 1. (boilerplate) Initialize device/stream. For details, see the acl API manual.
    // Fill in deviceId according to your actual device.
    int32_t deviceId = 0;
    aclrtStream stream;
    auto ret = aclnnClaGateQuantTest(deviceId, stream);
    CHECK_FREE_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnClaGateQuantTest failed. ERROR: %d\n", ret); return ret);

    Finalize(deviceId, stream);
    return 0;
}