aclnnMlaPrologV3WeightNz

📄 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

  • Function updates: (differences from aclnnMlaPrologV2weightNz)

    • Added scale correction factors for Query and Key, corresponding to qcQrScale ($\alpha_q$) and kcScale ($\alpha_{kv}$), respectively.
    • Added optional input parameters (for example, actualSeqLenOptional, kNopeClipAlphaOptional, queryNormFlag, weightQuantMode, kvCacheQuantMode, queryQuantMode, ckvkrRepoMode, quantScaleRepoMode, tileSize, queryNormOutOptional, and dequantScaleQNormOptional). Changed cache_mode from mandatory to optional.
    • Adjusted the name and position of the cacheIndex parameter, corresponding to the current cacheIndexOptional.
  • Description: For inference use cases, performs the pre-processing computation of Multi-Head Latent Attention. The main computation process is divided into seven paths:

    • First, the input $x$ is multiplied by $W^{DQ}$, downsampled, and normalized with RmsNorm. The result is then split into two branches. In the first branch, it is multiplied by $W^{UQ}$ and $W^{UK}$, upsampled twice, and then multiplied by the Query scale correction factor $\alpha_q$ to obtain $q^N$. In the second branch, it is multiplied by $W^{QR}$ and then goes through rotary position encoding (ROPE) to obtain $q^R$.
    • In the third path, the input $x$ is multiplied by $W^{DKV}$ for downsampling and RmsNorm, then multiplied by the Key scale correction factor $\alpha_{kv}$ and written into the Cache to obtain $k^C$;
    • The fourth path: the input $x$ is multiplied by $W^{KR}$, then undergoes rotary position encoding and is passed into another Cache to obtain $k^R$;
    • The fifth path: the quantization parameter obtained after the output $q^N$ undergoes DynamicQuant.
    • In the sixth path, when queryNormFlag=true, the input $x$ is multiplied by $W^{DQ}$ for downsampling and RmsNorm to obtain the compressed result $c^Q$, which is output as queryNormOutOptional.
    • In the seventh path, when queryNormFlag=true and in the quantization scenario (weightQuantMode≠0), DynamicQuant is performed on $c^Q$ to finally obtain the quantized queryNormOutOptional and the corresponding quantization parameter dequantScaleQNormOutOptional.
    • The weight parameters WeightDq, WeightUqQr, and WeightDkvKr need to be passed in NZ format.
  • Formula:

    RmsNorm formula:

    $$ \text{RmsNorm}(x) = \gamma \cdot \frac{x_i}{\text{RMS}(x)} $$
    $$ \text{RMS}(x) = \sqrt{\frac{1}{N} \sum_{i=1}^{N} x_i^2 + \epsilon} $$

    The computation formula of the query, including downsampling, RmsNorm, and two upsampling operations.

    $$ c^Q = \alpha_q\cdot\mathrm{RmsNorm}(x \cdot W^{DQ}) $$
    $$ q^C = c^Q \cdot W^{UQ} $$
    $ q^N = q^C \cdot W^{UK} $

    Where $\alpha_q$ is the scale correction parameter of the query.

    Performs rotary position encoding (ROPE) to the query.

    $$ q^R = \mathrm{ROPE}(c^Q \cdot W^{QR}) $$

    The computation formula of the key, including downsampling and RmsNorm. The computation result is stored in the cache.

    $$ c^{KV} = \alpha_{kv}\cdot\mathrm{RmsNorm}(x \cdot W^{DKV}) $$
    $ k^C = \mathrm{Cache}(c^{KV}) $

    $\alpha_{kv}$ is the scale correction parameter of the key.

    Performs rotary position encoding (ROPE) to the key and stores the result in the cache.

    $$ k^R = \mathrm{Cache}(\mathrm{ROPE}(x \cdot W^{KR})) $$

    Dequant Scale Query Nope Formula

    $$ \mathrm{dequantScaleQNope} = {\mathrm{RowMax}(\mathrm{abs}(q^{N})) / Q_{max}} $$
    $$ q^{N} = {\mathrm{round}(q^{N} / \mathrm{dequantScaleQNope})} $$

    Query Norm and Dequant Scale Query Norm formulas (output when queryNormFlag is set to true)

    Non-quantization scenario (weightQuantMode=0):

    $$ queryNorm = c^Q = \alpha_q\cdot\mathrm{RmsNorm}(x \cdot W^{DQ}) $$

    In this case, queryNorm is of the BFLOAT16 type, and dequantScaleQNorm is not output (nullptr).

    In quantization scenarios (weightQuantMode=1/2/4/5, per-token dynamic quantization), smoothScaleCq is optional. If smoothScaleCq is not passed, it is considered as 1.

    $$ \tilde{c}^Q = c^Q \cdot smoothScale $$
    $$ \mathrm{dequantScaleQNorm} = {\mathrm{RowMax}(\mathrm{abs}(\tilde{c}^Q)) / Q_{max}} $$
    $$ queryNorm = {\mathrm{round}(\tilde{c}^Q / \mathrm{dequantScaleQNorm})} $$

    mxfp8 quantization scenario (weightQuantMode=3, per-group dynamic quantization for every 32 elements, quantization parameter of the FLOAT8_E8M0 type):

    $$ \mathrm{dequantScaleQNorm} = 2^{\lfloor \mathrm{log}_2(\mathrm{GroupMax}(\mathrm{abs}(c^Q))) \rfloor - 8} $$
    $$ queryNorm = {\mathrm{cast\_to\_fp8}(c^Q / \mathrm{dequantScaleQNorm})} $$

    $Q_{max}$ is the maximum value of the quantized output type. The value of INT8 is 127, the value of FLOAT8_E4M3FN is 448, and the value of HIFLOAT8 is 32768. The value 8 is the maximum exponent emax of FLOAT8_E4M3FN.

Function Prototype

Each operator uses a two-phase API. The "aclnnMlaPrologV3WeightNzGetWorkspaceSize" API must be called first to obtain input parameters and calculate the required workspace size based on the process, and then the "aclnnMlaPrologV3WeightNz" API must be called to perform the computation.

aclnnStatus aclnnMlaPrologV3WeightNzGetWorkspaceSize(
    const aclTensor *tokenX,
    const aclTensor *weightDq,
    const aclTensor *weightUqQr,
    const aclTensor *weightUk,
    const aclTensor *weightDkvKr,
    const aclTensor *rmsnormGammaCq,
    const aclTensor *rmsnormGammaCkv,
    const aclTensor *ropeSin,
    const aclTensor *ropeCos,
    aclTensor       *kvCacheRef,
    aclTensor       *krCacheRef,
    const aclTensor *cacheIndexOptional,
    const aclTensor *dequantScaleXOptional,
    const aclTensor *dequantScaleWDqOptional,
    const aclTensor *dequantScaleWUqQrOptional,
    const aclTensor *dequantScaleWDkvKrOptional,
    const aclTensor *quantScaleCkvOptional,
    const aclTensor *quantScaleCkrOptional,
    const aclTensor *smoothScalesCqOptional,
    const aclTensor *actualSeqLenOptional,
    const aclTensor *kNopeClipAlphaOptional,
    double           rmsnormEpsilonCq,
    double           rmsnormEpsilonCkv,
    char            *cacheModeOptional,
    int64_t          weightQuantMode,
    int64_t          kvCacheQuantMode,
    int64_t          queryQuantMode,
    int64_t          ckvkrRepoMode,
    int64_t          quantScaleRepoMode,
    int64_t          tileSize,
    double           qcQrScale,
    double           kcScale,
    const aclTensor *queryOut,
    const aclTensor *queryRopeOut,
    const aclTensor *dequantScaleQNopeOutOptional,
    const aclTensor *queryNormOutOptional,
    const aclTensor *dequantScaleQNormOutOptional,
    uint64_t        *workspaceSize,
    aclOpExecutor  **executor)
aclnnStatus aclnnMlaPrologV3WeightNz(
  void             *workspace,
  uint64_t          workspaceSize,
  aclOpExecutor    *executor,
  const aclrtStream stream)

aclnnMlaPrologV3WeightNzGetWorkspaceSize

  • Parameters

    Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor
    tokenX Input Input tensor used in the formula to compute Query and Key. Supports empty tensors with B=0, S=0, T=0 BFLOAT16, FLOAT8_E4M3FN, INT8, HIFLOAT8 ND
    • BS merged axis: (T, He)
    • BS unmerged axis: (B, S, He)
    ×
    weightDq Input Downsampling weight matrix WDQ used in the formula to compute Query.
    Dimension representation without transposition: (k, n)
    Empty tensors are not supported. BFLOAT16, FLOAT8_E4M3FN, INT8, HIFLOAT8 FRACTAL_NZ (He, Hcq) ×
    weightUqQr Input Upsampling weight matrix WUQ and position encoding weight matrix WQR used to compute the Query in the formula.
    Dimensions when not transposed: (k, n)
    Empty tensors are not supported. BFLOAT16, INT8, FLOAT8_E4M3FN, HIFLOAT8 FRACTAL_NZ (Hcq, N*(D+Dr)) ×
    weightUk Input Upsampling weight WUK used to compute Key in the formula. Empty tensors are not supported. BFLOAT16 ND (N, D, Hckv) ×
    weightDkvKr Input Downsampling weight matrix WDKV and position encoding weight matrix WKR used to compute Key in the formula.
    Dimension representation when not transposed: (k, n)
    Empty tensors are not supported. BFLOAT16, FLOAT8_E4M3FN, INT8, HIFLOAT8 FRACTAL_NZ (He,Hckv+Dr) ×
    rmsnormGammaCq Input The γ parameter in the RmsNorm formula for computing cQ. Empty tensors are not supported BFLOAT16 ND (Hcq) ×
    rmsnormGammaCkv Input The γ parameter in the RmsNorm formula for computing cKV. Empty tensors are not supported. BFLOAT16 ND (Hckv) ×
    ropeSin Input Sine parameter matrix used to compute rotary position embedding. Empty tensors with B=0, S=0, T=0 are supported. BFLOAT16 ND
    • BS merged axis: (T,Dr)
    • BS non-merged axis: (B,S,Dr)
    ×
    ropeCos Input Cosine parameter matrix used to compute the rotary position embedding. Supports empty tensors with B=0, S=0, T=0. BFLOAT16 ND
    • BS merged axis: (T,Dr)
    • BS non-merged axis: (B,S,Dr)
    ×
    kvCacheRef Input/Output aclTensor for cache indexing. The calculation result is updated in place (corresponding to kC in the formula).
    • Empty tensors with B=0,Skv=0 are supported;
    • Nkv is associated with N, and N is a hyper-parameter. Therefore, Nkv cannot be 0.
    BFLOAT16, INT8, FLOAT8_E4M3FN, HIFLOAT8 ND
    • CacheMode="PA_BSND"/"PA_NZ"/"PA_BLK_BSND"/"PA_BLK_NZ": (BlockNum,BlockSize,Nkv,Dtile)
    • CacheMode="BSND": (B,S,Nkv,Dtile)
    • CacheMode="TND": (T,Nkv,Dtile)
    Only the first axis can be non-contiguous; all other axes must be contiguous.
    krCacheRef Input/Output Cache for key position encoding, updated in place with the computation result (corresponding to kR in the formula).
    • Supports empty tensors with B=0,Skv=0;
    • Nkv is associated with N, and N is a hyperparameter. Therefore, Nkv cannot be 0
    BFLOAT16, INT8 ND
    • CacheMode="PA_BSND"/"PA_NZ"/"PA_BLK_BSND"/"PA_BLK_NZ": (BlockNum,BlockSize,Nkv,Dr)
    • CacheMode="BSND": (B,S,Nkv,Dr)
    • When CacheMode="TND": (T,Nkv,Dr)
    • When ckvkrRepoMode=1: the shape should contain 0, and a shape of (0) is supported
    Only the first axis can be non-contiguous; the remaining axes must be contiguous.
    cacheIndexOptional Input Stores the indices of kvCache and krCache.
    • Empty tensors with B=0, S=0, T=0 are supported.
    • cacheMode="PA_BSND"/"PA_NZ": the value must be in the range [0,BlockNum*BlockSize).
    • cacheMode="PA_BLK_BSND"/"PA_BLK_NZ": the value must be in the range [0,BlockNum).
    • cacheMode="TND"/"BSND": nullptr
    INT64 ND
    • CacheMode="PA_BSND"/"PA_NZ":
      1. BS merged axis: (T)
      2. BS non-merged axis: (B,S)
    • CacheMode="PA_BLK_BSND"/"PA_BLK_NZ":
      1. BS merged axis: (Sum(⌈Si/BlockSize⌉)), where Si is the length of S in each Batch
      2. BS non-merged axis: (B,⌈S/BlockSize⌉)
    • CacheMode="TND"/"BSND": nullptr
    ×
    dequantScaleXOptional Input Dequantization parameter of tokenX. Empty tensors with B=0, S=0, T=0 are supported. (Required when weightQuantMode=2/3/4/5) FLOAT8_E8M0, FLOAT ND
    • weightQuantMode=2/4/5:
      1. BS merged axis: (T, 1)
      2. BS non-merged axis: (B*S,1)
    • weightQuantMode=3:
      1. BS merged axis: (T, He/32)
      2. BS non-merged axis: (B*S, He/32)
    ×
    dequantScaleWDqOptional Input Dequantization parameter of weightDq. Non-empty tensor is supported (required for weightQuantMode=2/3/4/5 use cases) FLOAT8_E8M0, FLOAT ND
    • weightQuantMode=2/4/5: (1,Hcq)
    • weightQuantMode=3: (Hcq, He/32)
    ×
    dequantScaleWUqQrOptional Input Per-channel parameter for dequantization after the MatmulQcQr matrix multiplication. Supports non-empty tensors (required when weightQuantMode=1/2/3/4/5) FLOAT, FLOAT8_E8M0 ND
    • weightQuantMode=1/2/4/5: (1,N*(D+Dr))
    • weightQuantMode=3: (N*(D+Dr), Hcq/32)
    ×
    dequantScaleWDkvKrOptional Input Dequantization parameters of weightDkvKr. Supports non-empty tensors (required for weightQuantMode=2/3/4/5 use cases) FLOAT8_E8M0, FLOAT ND
    • weightQuantMode=2/4/5: (1,Hckv+Dr)
    • weightQuantMode=3: (Hckv+Dr, He/32)
    ×
    quantScaleCkvOptional Input Parameters used to quantize the kvCache output data. Non-empty tensor supported (required for kvCacheQuantMode=1/2 use cases) FLOAT ND
    • kvCacheQuantMode=1: (1)
    • kvCacheQuantMode=2: (1,Hckv)
    ×
    quantScaleCkrOptional Input Parameter used to quantize the krCache output data. Non-empty tensor supported (required for kvCacheQuantMode=2 use cases) FLOAT ND (1,Dr) ×
    smoothScalesCqOptional Input Parameter for performing dynamic quantization on the RmsNormCq output. Non-empty Tensor supported (optional for weightQuantMode=1/2/4/5 use cases) FLOAT ND (1,Hcq) ×
    actualSeqLenOptional Input Represents the sequence length in each batch, stored as prefix sums. Required when BS is a merged axis and CacheMode="PA_BLK_BSND"/"PA_BLK_NZ" INT32 ND (B) ×
    kNopeClipAlphaOptional Input Scaling factor for the clip operation on kvCache. The shape is 1 in partial quantization per-token per-group use cases and int8 full quantization per-token per-group use cases; not supported in other use cases; empty tensors are not supported. FLOAT ND (1) ×
    rmsnormEpsilonCq Input The ε parameter in the RmsNorm formula for calculating cQ.
    • 1e-05 is recommended if not specified by the user.
    • Only the double type is supported.
    DOUBLE - - -
    rmsnormEpsilonCkv Input Parameter ε in the RmsNorm formula for computing cKV.
    • 1e-05 is recommended if not specified by the user.
    • Only the double type is supported.
    DOUBLE - - -
    cacheModeOptional Input Specifies the mode of kvCache.
    • If not specified by the user, "PA_BSND" is recommended.
    • Only the char* type is supported.
    • Options: "PA_BSND", "PA_NZ", "PA_BLK_BSND", "PA_BLK_NZ", "BSND", "TND"
    CHAR* - - -
    queryNormFlag Input Indicates whether to output queryNormOutOptional and dequantScaleQNormOutOptional. false: no output; true: output. The default value is false. BOOL - - -
    weightQuantMode Input Specifies the quantization mode of weightDq, weightUqQr, weightUk, and weightDkvKr.
    • 0 indicates no quantization
    • 1 indicates weightUqQr quantization
    • 2 indicates int8 quantization of weightDq, weightUqQr, and weightDkvKr
    • 3 indicates mxfp8 quantization of weightDq, weightUqQr, and weightDkvKr
    • 4 indicates fp8 quantization of weightDq, weightUqQr, and weightDkvKr
    • 5 indicates hif8 quantization of weightDq, weightUqQr, and weightDkvKr
    • Default value: 0
    INT - - -
    kvCacheQuantMode Input Specifies the quantization mode of kvCache. 0: non-quantization, 1: pertensor quantization, 2: perchannel quantization, 3: per-token per-group quantization. Default value: 0. INT64 - - -
    queryQuantMode Input Indicates the quantization mode of query. 0: non-quantization, 1: per-token-head quantization. Default value: 0. INT64 - - -
    ckvkrRepoMode Input Specifies the storage mode of kvCache and krCache. 0 indicates that kvCache and krCache are stored separately, and 1 indicates that they are stored together. Default value: 0 INT64 - - -
    quantScaleRepoMode Input Specifies the storage mode of the quantization scale. 0: the quantization scale and data are stored separately. 1: the quantization scale and data are stored together as the kvCacheRef output. Default value: 0. INT64 - - -
    tileSize Input Specifies the tile size for per-token per-group quantization. Valid only when kvCacheQuantMode is 3. Default value: 128 INT64 - - -
    qcQrScale Input Specifies the scale correction coefficients of the Query. 1.0 if not specified by the user DOUBLE - - -
    kcScale Input Scale correction coefficient for Key. 1.0 if not specified by the user DOUBLE - - -
    queryOut Output Output tensor of Query in the formula (corresponding to qN). - BFLOAT16, FLOAT8_E4M3FN, INT8, HIFLOAT8 ND
    • BS merged axis: (T,N,Hckv)
    • BS non-merged axis: (B,S,N,Hckv)
    ×
    queryRopeOut Output Output tensor of Query position encoding in the formula (corresponding to qR). - BFLOAT16 ND
    • BS merged axis: (T,N,Dr)
    • BS non-merged axis: (B,S,N,Dr)
    ×
    dequantScaleQNopeOutOptional Output Dequantization parameter of the Query output in the formula. Output when weightQuantMode=2/3/4/5; nullptr when weightQuantMode=0/1 FLOAT ND
    • BS merged axis: (T,N,1)
    • BS non-merged axis: (B*S,N,1)
    ×
    queryNormOutOptional Output Output tensor of tokenX after rmsNorm in the formula (corresponding to cQ). Output when queryNormFlag=true BFLOAT16, INT8, FLOAT8_E4M3FN, HIFLOAT8 ND
    • BS merged axis: (T,Hcq)
    • BS non-merged axis: (B,S,Hcq)
    ×
    dequantScaleQNormOutOptional Output Dequantization parameter of queryNormOutOptional. Output when queryNormFlag=true and weightQuantMode=1/2/3/4/5; nullptr when weightQuantMode=0 FLOAT, FLOAT8_E8M0 ND
    • weightQuantMode=1/2/4/5:
      1. BS merged axis: (T,1)
      2. BS non-merged axis: (B*S,1)
    • weightQuantMode=3:
      1. BS merged axis: (T, Hcq/32)
      2. BS non-merged axis: (B*S, Hcq/32)
    ×
    workspaceSize Output Returns the workspace size to be allocated on the device. Used only for output, with no input configuration required. Data type: uint64_t*. - - - -
    executor Output Returns the op executor containing the operator computation flow. Used only for output. No input configuration is required. Data type: aclOpExecutor**. - - - -
  • Atlas A3 products, Atlas A2 products:
    • The FLOAT8_E4M3FN and HIFLOAT8 data types are not supported for tokenX, weightDq, weightUqQr, weightDkvKr, kvCacheRef, queryOut, or queryNormOutOptional.
    • The FLOAT8_E8M0 data type is not supported for dequantScaleXOptional, dequantScaleWDqOptional, dequantScaleWUqQrOptional, dequantScaleWDkvKrOptional, or dequantScaleQNormOutOptional.
  • Return Value

    aclnnStatus: Returns the 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 null pointer exists in a required parameter (such as an input/output parameter on which the API core depends).
    ACLNN_ERR_PARAM_INVALID 161002 The shape (dimension/size) or dtype (data type) of an input parameter is not within the range supported by the API.
    ACLNN_ERR_RUNTIME_ERROR 361001 An exception occurs when the API calls the NPU Runtime API for memory (e.g., the Runtime service is not started, or memory allocation fails).
    ACLNN_ERR_INNER_TILING_ERROR 561002 An exception occurs during tiling, or the dtype or shape of the input parameter is incorrect.

aclnnMlaPrologV3WeightNz

  • Parameters

    Parameter Type Description
    workspace void* Workspace memory address allocated on the Device.
    workspaceSize uint64_t Workspace memory size allocated on the Device, obtained by the first-phase API aclnnMlaPrologV3WeightNzGetWorkspaceSize.
    executor aclOpExecutor* op executor, which contains the operator computation flow.
    stream aclrtStream Stream where tasks are executed.
  • Return Value

    aclnnStatus: return status code. For details, see aclnn return codes.

Constraints

  • Deterministic computation:
    • aclnnMlaPrologV3WeightNz defaults to a deterministic implementation.
Description of shape format fields   
Field Name Full Name/Meaning Value Rules and Description
B Batch (input sample batch size) Value range: 0-65536
S Seq-Length (input sample sequence length) Value range: unlimited
He Head-Size (hidden layer size) Fixed values: 1024, 2048, 3072, 4096, 5120, 6144, 7168, 7680, 8192
Hcq Dimension of the q low-rank matrix Fixed values: 1536, 2048
N Head-Num (number of heads) Value range: 1-128
Hckv Dimension of the kv low-rank matrix Fixed value: 512
D qk dimension excluding position encoding Fixed values: 128, 192
Dr qk position encoding dimension Fixed value: 64
Nkv Number of kv heads Fixed value: 1
BlockNum Number of blocks in the PagedAttention use case
  • If CacheMode="PA_BSND"/"PA_NZ", the value is greater than or equal to ⌈(B * S) / BlockSize⌉.
  • If CacheMode="PA_BLK_BSND"/"PA_BLK_NZ", the value is greater than or equal to B * ⌈S / BlockSize⌉.

Note: In the BS coalescing use case, the S length in each batch can be different. Therefore, BlockNum must be greater than or equal to the sum of the S length divided by BlockSize and rounded up for each batch.

Example: If actualSeqLenOptional is [47, 151, 261, 422] and blocksize=128, the lengths in each batch are [47, 104, 110, 161]. Then BlockNum = ⌈47/128⌉ + ⌈104/128⌉ + ⌈110/128⌉ + ⌈161/128⌉ = 5

BlockSize Block size in the PagedAttention use case Value range: 16-1024, and a multiple of 16
T Size after BS coalescing
  • Value range: unlimited
  • Note: If BS coalescing is used, tokenX, ropeSin, and ropeCos are 2D, cacheIndex is 1D, and queryOut and queryRopeOut are 3D.
Dtile Size of the D dimension of kvCache
  • In the pertoken-pergroup quantization scenario, the fixed value is 656, which equals 512(Hckv) + 64(Dr)*2 + 4(Hckv/tileSize)*4.
  • In other scenarios, the fixed value is Hckv (512).
shape constraints
  • If the dimension of tokenX uses BS concatenated axis, i.e., (T, He)
    • The shape of ropeSin and ropeCos is (T, Dr)
    • When CacheMode is PA_BSND or PA_NZ, the shape of cacheIndex is (T).
    • When CacheMode is PA_BLK_BSND or PA_BLK_NZ, the shape of cacheIndex is (Sum(⌈Si/BlockSize⌉)), where S_i is the length of S in each batch.
    • When CacheMode is PA_BLK_BSND or PA_BLK_NZ, actualSeqLenOptional needs to be passed in, with dimension (B).
    • In the int8/fp8/hif8 fully quantized field, the shape of dequantScaleXOptional is (T, 1); in the mxfp8 fully quantized field, the shape of dequantScaleXOptional is (T, He/32).
    • The shape of queryOut is (T, N, Hckv).
    • The shape of queryRopeOut is (T, N, Dr).
    • In the int8/mxfp8/fp8/hif8 fully quantized field with kvCache pertensor quantization, the shape of dequantScaleQNopeOutOptional is (T, N, 1); in other scenarios, it is nullptr.
  • If the dimension of tokenX does not use BS concatenated axis, i.e., (B, S, He)
    • The shape of ropeSin and ropeCos is (B, S, Dr)
    • When CacheMode is PA_BSND or PA_NZ, the shape of cacheIndex is (B, S).
    • When CacheMode is PA_BLK_BSND or PA_BLK_NZ, the shape of cacheIndex is (B, ⌈S/BlockSize⌉).
    • In the int8/fp8/hif8 fully quantized scenario, the shape of dequantScaleXOptional is (B*S, 1); in the mxfp8 fully quantized scenario, the shape of dequantScaleXOptional is (B*S, He/32)
    • The shape of queryOut is (B, S, N, Hckv)
    • The shape of queryRopeOut is (B, S, N, Dr).
    • In the int8/mxfp8/fp8/hif8 fully quantized and kvCache pertensor quantization scenario, the shape of dequantScaleQNopeOutOptional is (B*S, N, 1); in other scenarios, it is nullptr
  • One or more of B, S, T, and Skv may be 0, meaning that input parameters whose shapes are related to B, S, T, or Skv may be null tensors. The remaining input parameters do not support null tensors.
    • If B, S, and T are 0, queryOut and queryRopeOut output null tensors, and kvCacheRef and krCacheRef are not updated.
    • If Skv is 0, queryOut, queryRopeOut, and dequantScaleQNopeOutOptional are computed normally, while kvCacheRef and krCacheRef are not updated, i.e., they output null tensors.
  • When CacheMode is BSND
    • tokenX should not use BS axis merging, that is, the dimensions are (B, S, He)
    • The dimensions of kvCache are (B,S,Nkv,Dr)
  • When CacheMode is TND
    • tokenX should use BS axis merging, that is, the dimensions are (T, He)
    • The dimensions of kvCache are (T,Nkv,Dr)
  • When ckvkrRepoMode is 1
    • The dimensions of krCache should include 0, and the supported shape is (0)
Special constraints
  • When actualSeqLenOptional is passed in, its last value must be consistent with T.
  • In pertoken-pergroup quantization mode, ckvkrRepoMode and quantScaleRepoMode must simultaneously be 1; in other quantization modes and the non-quantized field, ckvkrRepoMode and quantScaleRepoMode must simultaneously be 0.
  • In pertoken-pergroup quantization mode, CacheMode supports only PA_BSND, BSND, and TND.
  • When the value of ckvkrRepoMode is 1, krCache must be an empty tensor (that is, the product of its shape is 0).
  • In kvcache pertensor quantization mode, kvCacheQuantMode and queryQuantMode must simultaneously be 1.
Use cases supported by the aclnnMlaPrologV3WeightNz API
  • Atlas A2 products and Atlas A3 products: full quantization with fp8/hif8/mxfp8 is currently not supported.
  • Ascend 950PR&950DT products: all quantization use cases are currently supported.
Use case Description
No quantization weight_quant_mode=0,kv_cache_quant_mode=0,query_quant_mode=0
Inputs: all inputs are non-quantized data.
Outputs: all outputs are non-quantized data.
Partial quantization kvCache without quantization weight_quant_mode=1,kv_cache_quant_mode=0,query_quant_mode=0
Inputs: weightUqQr is per-token quantized data, and all other inputs are non-quantized data. dequantScaleWUqQr must be provided, and smoothScalesCq is optional.
Outputs: all outputs return non-quantized data.
kvCache per-channel quantization weight_quant_mode=1,kv_cache_quant_mode=2,query_quant_mode=0
Inputs: weightUqQr is per-token quantized data, kvCacheRef and krCacheRef are per-channel quantized data, and all other inputs are non-quantized data. dequantScaleWUqQr, quantScaleCkv, and quant_scale_ckr must be provided, and smoothScalesCq is optional.
Outputs: kvCacheRef and krCacheRef return per-channel quantized data, and all other outputs return non-quantized data.
kvCache per-token per-group quantization weight_quant_mode=1,kv_cache_quant_mode=3,query_quant_mode=0
Input parameters: weightUqQr takes per-token quantized data, and the other input parameters take non-quantized data. The dequantScaleWUqQr field is mandatory, and the smoothScalesCq field is optional.
Output parameters: kvCacheRef returns per-token per-group quantized data, and the other output parameters return non-quantized data.
int8/fp8/hif8 full quantization kvCache non-quantization weight_quant_mode=2/4/5,kv_cache_quant_mode=0,query_quant_mode=0
Input parameters: tokenX takes per-token quantized data, weightDq, weightUqQr, and weightDkvKr take per-channel quantized data, and the other input parameters take non-quantized data. The dequantScaleX, dequantScaleWDq, dequantScaleWUqQr, and dequantScaleWDkvKr fields are mandatory, and the smoothScalesCq field is optional.
Output parameters: all output parameters return non-quantized data.
kvCache per-tensor quantization weight_quant_mode=2/4/5,kv_cache_quant_mode=1,query_quant_mode=1
Input parameters: tokenX takes per-token quantized data, weightDq, weightUqQr, and weightDkvKr take per-channel quantized data, kvCacheRef takes per-tensor quantized data, and the other input parameters take non-quantized data. The dequantScaleX, dequantScaleWDq, dequantScaleWUqQr, dequantScaleWDkvKr, and quantScaleCkv fields are mandatory, and the smoothScalesCq field is optional.
Output parameters: queryOut returns per-token-head quantized data, kvCacheRef returns per-tensor quantized data, and the other output parameters return non-quantized data.
kvCache per-token per-group quantization weight_quant_mode=2/4/5,kv_cache_quant_mode=3,query_quant_mode=0
Input parameters: tokenX takes per-token quantized data, weightDq, weightUqQr, and weightDkvKr take per-channel quantized data, and the other input parameters take non-quantized data. The dequantScaleX, dequantScaleWDq, dequantScaleWUqQr, and dequantScaleWDkvKr fields are mandatory, and the smoothScalesCq field is optional.
Output parameters: kvCacheRef returns per-token per-group quantized data, and the other output parameters return non-quantized data.
mxfp8 full quantization kvCache non-quantization weight_quant_mode=3,kv_cache_quant_mode=0,query_quant_mode=0
Input: tokenX passes in per-token quantized data, weightDq, weightUqQr, and weightDkvKr pass in per-channel quantized data, and the other inputs are non-quantized data. The dequantScaleX, dequantScaleWDq, dequantScaleWUqQr, and dequantScaleWDkvKr fields must be passed in
Output: all outputs return non-quantized data
kvCache per-tensor quantization weight_quant_mode=3,kv_cache_quant_mode=1,query_quant_mode=1
Input: tokenX passes in per-token quantized data, weightDq, weightUqQr, and weightDkvKr pass in per-channel quantized data, kvCacheRef passes in per-tensor quantized data, and the other inputs are non-quantized data. The dequantScaleX, dequantScaleWDq, dequantScaleWUqQr, dequantScaleWDkvKr, and quantScaleCkv fields must be passed in
Output: queryOut returns per-token-head quantized data, the kvCacheRef output returns per-tensor quantized data, and the other outputs return non-quantized data
kvCache per-token per-group quantization weight_quant_mode=3,kv_cache_quant_mode=3,query_quant_mode=0
Input: tokenX passes in per-token quantized data, weightDq, weightUqQr, and weightDkvKr pass in per-channel quantized data, and the other inputs are non-quantized data. The dequantScaleX, dequantScaleWDq, dequantScaleWUqQr, and dequantScaleWDkvKr fields must be passed in
Output: the kvCacheRef output returns per-token per-group quantized data, and the other outputs return non-quantized data
dtype constraints on parameters in different quantization scenarios
Parameter Non-quantization use case Partial quantization use case int8 full quantization use case mxfp8 full quantization use case fp8 full quantization use case hif8 full quantization use case
kvCache non-quantization kvCache per-channel quantization kvCache per-token per-group quantization kvCache non-quantization kvCache per-tensor quantization kvCache per-token per-group quantization kvCache non-quantization kvCache per-tensor quantization kvCache per-token per-group quantization kvCache non-quantization kvCache per-tensor quantization kvCache per-token per-group quantization kvCache non-quantization kvCache per-tensor quantization kvCache per-token per-group quantization
dtype dtype dtype dtype dtype dtype dtype dtype dtype dtype dtype dtype dtype dtype dtype dtype
tokenX BFLOAT16 BFLOAT16 BFLOAT16 BFLOAT16 INT8 INT8 INT8 FLOAT8_E4M3FN FLOAT8_E4M3FN FLOAT8_E4M3FN FLOAT8_E4M3FN FLOAT8_E4M3FN FLOAT8_E4M3FN HIFLOAT8 HIFLOAT8 HIFLOAT8
weightDq BFLOAT16 BFLOAT16 BFLOAT16 BFLOAT16 INT8 INT8 INT8 FLOAT8_E4M3FN FLOAT8_E4M3FN FLOAT8_E4M3FN FLOAT8_E4M3FN FLOAT8_E4M3FN FLOAT8_E4M3FN HIFLOAT8 HIFLOAT8 HIFLOAT8
weightUqQr BFLOAT16 INT8 INT8 INT8 INT8 INT8 INT8 FLOAT8_E4M3FN FLOAT8_E4M3FN FLOAT8_E4M3FN FLOAT8_E4M3FN FLOAT8_E4M3FN FLOAT8_E4M3FN HIFLOAT8 HIFLOAT8 HIFLOAT8
weightUk BFLOAT16 BFLOAT16 BFLOAT16 BFLOAT16 BFLOAT16 BFLOAT16 BFLOAT16 BFLOAT16 BFLOAT16 BFLOAT16 BFLOAT16 BFLOAT16 BFLOAT16 BFLOAT16 BFLOAT16 BFLOAT16
weightDkvKr BFLOAT16 BFLOAT16 BFLOAT16 BFLOAT16 INT8 INT8 INT8 FLOAT8_E4M3FN FLOAT8_E4M3FN FLOAT8_E4M3FN FLOAT8_E4M3FN FLOAT8_E4M3FN FLOAT8_E4M3FN HIFLOAT8 HIFLOAT8 HIFLOAT8
rmsnormGammaCq BFLOAT16 BFLOAT16 BFLOAT16 BFLOAT16 BFLOAT16 BFLOAT16 BFLOAT16 BFLOAT16 BFLOAT16 BFLOAT16 BFLOAT16 BFLOAT16 BFLOAT16 BFLOAT16 BFLOAT16 BFLOAT16
rmsnormGammaCkv BFLOAT16 BFLOAT16 BFLOAT16 BFLOAT16 BFLOAT16 BFLOAT16 BFLOAT16 BFLOAT16 BFLOAT16 BFLOAT16 BFLOAT16 BFLOAT16 BFLOAT16 BFLOAT16 BFLOAT16 BFLOAT16
ropeSin BFLOAT16 BFLOAT16 BFLOAT16 BFLOAT16 BFLOAT16 BFLOAT16 BFLOAT16 BFLOAT16 BFLOAT16 BFLOAT16 BFLOAT16 BFLOAT16 BFLOAT16 BFLOAT16 BFLOAT16 BFLOAT16
ropeCos BFLOAT16 BFLOAT16 BFLOAT16 BFLOAT16 BFLOAT16 BFLOAT16 BFLOAT16 BFLOAT16 BFLOAT16 BFLOAT16 BFLOAT16 BFLOAT16 BFLOAT16 BFLOAT16 BFLOAT16 BFLOAT16
kvCacheRef BFLOAT16 BFLOAT16 INT8 INT8 BFLOAT16 INT8 INT8 BFLOAT16 FLOAT8_E4M3FN FLOAT8_E4M3FN BFLOAT16 FLOAT8_E4M3FN FLOAT8_E4M3FN BFLOAT16 HIFLOAT8 HIFLOAT8
krCacheRef BFLOAT16 BFLOAT16 INT8 BFLOAT16 BFLOAT16 BFLOAT16 BFLOAT16 BFLOAT16 BFLOAT16 BFLOAT16 BFLOAT16 BFLOAT16 BFLOAT16 BFLOAT16 BFLOAT16 BFLOAT16
cacheIndexOptional INT64 INT64 INT64 INT64 INT64 INT64 INT64 INT64 INT64 INT64 INT64 INT64 INT64 INT64 INT64 INT64
dequantScaleXOptional NULLPTR NULLPTR NULLPTR NULLPTR FLOAT FLOAT FLOAT FLOAT8_E8M0 FLOAT8_E8M0 FLOAT8_E8M0 FLOAT FLOAT FLOAT FLOAT FLOAT FLOAT
dequantScaleWDqOptional NULLPTR NULLPTR NULLPTR NULLPTR FLOAT FLOAT FLOAT FLOAT8_E8M0 FLOAT8_E8M0 FLOAT8_E8M0 FLOAT FLOAT FLOAT FLOAT FLOAT FLOAT
dequantScaleWUqQrOptional NULLPTR FLOAT FLOAT FLOAT FLOAT FLOAT FLOAT FLOAT8_E8M0 FLOAT8_E8M0 FLOAT8_E8M0 FLOAT FLOAT FLOAT FLOAT FLOAT FLOAT
dequantScaleWDkvKrOptional NULLPTR NULLPTR NULLPTR NULLPTR FLOAT FLOAT FLOAT FLOAT8_E8M0 FLOAT8_E8M0 FLOAT8_E8M0 FLOAT FLOAT FLOAT FLOAT FLOAT FLOAT
quantScaleCkvOptional NULLPTR NULLPTR FLOAT NULLPTR NULLPTR FLOAT NULLPTR NULLPTR FLOAT NULLPTR NULLPTR FLOAT NULLPTR NULLPTR FLOAT NULLPTR
quantScaleCkrOptional NULLPTR NULLPTR FLOAT NULLPTR NULLPTR NULLPTR NULLPTR NULLPTR NULLPTR NULLPTR NULLPTR NULLPTR NULLPTR NULLPTR NULLPTR NULLPTR
smoothScalesCqOptional NULLPTR FLOAT FLOAT FLOAT FLOAT FLOAT FLOAT NULLPTR NULLPTR NULLPTR FLOAT FLOAT FLOAT FLOAT FLOAT FLOAT
kNopeClipAlphaOptional NULLPTR NULLPTR NULLPTR FLOAT NULLPTR NULLPTR FLOAT NULLPTR NULLPTR NULLPTR NULLPTR NULLPTR NULLPTR NULLPTR NULLPTR NULLPTR
queryOut BFLOAT16 BFLOAT16 BFLOAT16 BFLOAT16 BFLOAT16 INT8 BFLOAT16 BFLOAT16 FLOAT8_E4M3FN BFLOAT16 BFLOAT16 FLOAT8_E4M3FN BFLOAT16 BFLOAT16 HIFLOAT8 BFLOAT16
queryRopeOut BFLOAT16 BFLOAT16 BFLOAT16 BFLOAT16 BFLOAT16 BFLOAT16 BFLOAT16 BFLOAT16 BFLOAT16 BFLOAT16 BFLOAT16 BFLOAT16 BFLOAT16 BFLOAT16 BFLOAT16 BFLOAT16
dequantScaleQNopeOutOptional NULLPTR NULLPTR NULLPTR NULLPTR NULLPTR FLOAT NULLPTR NULLPTR FLOAT NULLPTR NULLPTR FLOAT NULLPTR NULLPTR FLOAT NULLPTR
queryNormOutOptional BFLOAT16 INT8 INT8 INT8 INT8 INT8 INT8 FLOAT8_E4M3FN FLOAT8_E4M3FN FLOAT8_E4M3FN FLOAT8_E4M3FN FLOAT8_E4M3FN FLOAT8_E4M3FN HIFLOAT8 HIFLOAT8 HIFLOAT8
dequantScaleQNormOutOptional NULLPTR FLOAT FLOAT FLOAT FLOAT FLOAT FLOAT FLOAT8_E8M0 FLOAT8_E8M0 FLOAT8_E8M0 FLOAT FLOAT FLOAT FLOAT FLOAT FLOAT

Example

For Atlas A2 products and Atlas A3 products, the following sample code is for reference only. For details about the compilation and execution process, see Compile and Run Samples.

#include <iostream>
#include <cstring>
#include <vector>
#include <cstdint>
#include "acl/acl.h"
#include "aclnnop/aclnn_mla_prolog_v3_weight_nz.h"
#include<unistd.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 code 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 CreateAclTensorND(const std::vector<T>& shape, void** deviceAddr, void** hostAddr,
                    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 aclrtMalloc to allocate host memory.
    ret = aclrtMallocHost(hostAddr, size);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtMallocHost failed. ERROR: %d\n", ret); return ret);
    memset(*hostAddr, 0, size);
    // Call the aclCreateTensor API to create an aclTensor.
    *tensor = aclCreateTensor(shape.data(), shape.size(), dataType, nullptr, 0, aclFormat::ACL_FORMAT_ND,
                              shape.data(), shape.size(), *deviceAddr);
    // Call aclrtMemcpy to copy host data to device memory.
    ret = aclrtMemcpy(*deviceAddr, size, *hostAddr, GetShapeSize(shape)*aclDataTypeSize(dataType), ACL_MEMCPY_HOST_TO_DEVICE);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtMemcpy failed. ERROR: %d\n", ret); return ret);
    return 0;
}

template <typename T>
int CreateAclTensorNZ(const std::vector<T>& shape, void** deviceAddr, void** hostAddr,
                    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 aclrtMalloc to allocate host memory.
    ret = aclrtMallocHost(hostAddr, size);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtMallocHost failed. ERROR: %d\n", ret); return ret);
    memset(*hostAddr, 0, size);
    // Call aclCreateTensor to create an aclTensor.
    *tensor = aclCreateTensor(shape.data(), shape.size(), dataType, nullptr, 0, aclFormat::ACL_FORMAT_FRACTAL_NZ,
                              shape.data(), shape.size(), *deviceAddr);
    // Call aclrtMemcpy to copy host-side data to device-side memory.
    ret = aclrtMemcpy(*deviceAddr, size, *hostAddr, GetShapeSize(shape) * aclDataTypeSize(dataType), ACL_MEMCPY_HOST_TO_DEVICE);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtMemcpy failed. ERROR: %d\n", ret); return ret);
    return 0;
}

int TransToNZShape(std::vector<int64_t> &shapeND, size_t typeSize) {
    if (typeSize == static_cast<size_t>(0)) {
      return 0;
    }
    int64_t h = shapeND[0];
    int64_t w = shapeND[1];
    int64_t h0 = static_cast<int64_t>(16);
    int64_t w0 = static_cast<int64_t>(32) / static_cast<int64_t>(typeSize);
    int64_t h1 = h / h0;
    int64_t w1 = w / w0;
    shapeND[0] = w1;
    shapeND[1] = h1;
    shapeND.emplace_back(h0);
    shapeND.emplace_back(w0);
    return 0;
}

int main() {
    // 1. Boilerplate code for device/stream initialization. For details, see the list of AscendCL external APIs.
    // Set deviceId based on the actual device.
    int32_t deviceId = 0;
    aclrtStream stream;
    auto ret = Init(deviceId, &stream);
    // Handle check as required.
    CHECK_RET(ret == 0, LOG_PRINT("Init acl failed. ERROR: %d\n", ret); return ret);
    // 2. Construct input and output based on the API definition.
    std::vector<int64_t> tokenXShape = {8, 1, 7168};            // B,S,He
    std::vector<int64_t> weightDqShape = {7168, 1536};          // He,Hcq
    std::vector<int64_t> weightUqQrShape = {1536, 6144};        // Hcq,N*(D+Dr)
    std::vector<int64_t> weightUkShape = {32, 128, 512};        // N,D,Hckv
    std::vector<int64_t> weightDkvKrShape = {7168, 576};        // He,Hckv+Dr
    std::vector<int64_t> rmsnormGammaCqShape = {1536};          // Hcq
    std::vector<int64_t> rmsnormGammaCkvShape = {512};          // Hckv
    std::vector<int64_t> ropeSinShape = {8, 1, 64};             // B,S,Dr
    std::vector<int64_t> ropeCosShape = {8, 1, 64};             // B,S,Dr
    std::vector<int64_t> cacheIndexShape = {8, 1};              // B,S
    std::vector<int64_t> kvCacheShape = {16, 128, 1, 512};      // BlockNum,BlockSize,Nkv,Hckv
    std::vector<int64_t> krCacheShape = {16, 128, 1, 64};       // BlockNum,BlockSize,Nkv,Dr
    std::vector<int64_t> dequantScaleXShape = {8, 1};           // B*S, 1
    std::vector<int64_t> dequantScaleWDqShape = {1, 1536};      // 1, Hcq
    std::vector<int64_t> dequantScaleWUqQrShape = {1, 6144};    // 1, N*(D+Dr)
    std::vector<int64_t> dequantScaleWDkvKrShape = {1, 576};    // 1, Hckv+Dr
    std::vector<int64_t> quantScaleCkvShape = {1};              // 1
    std::vector<int64_t> smoothScalesCqShape = {1, 1536};       // 1, Hcq
    std::vector<int64_t> queryShape = {8, 1, 32, 512};          // B,S,N,Hckv
    std::vector<int64_t> queryRopeShape = {8, 1, 32, 64};       // B,S,N,Dr
    std::vector<int64_t> dequantScaleQNopeShape = {8, 32, 1};   // B*S, N, 1
    double rmsnormEpsilonCq = 1e-5;
    double rmsnormEpsilonCkv = 1e-5;
    char cacheMode[] = "PA_BSND";

    void* tokenXDeviceAddr = nullptr;
    void* weightDqDeviceAddr = nullptr;
    void* weightUqQrDeviceAddr = nullptr;
    void* weightUkDeviceAddr = nullptr;
    void* weightDkvKrDeviceAddr = nullptr;
    void* rmsnormGammaCqDeviceAddr = nullptr;
    void* rmsnormGammaCkvDeviceAddr = nullptr;
    void* ropeSinDeviceAddr = nullptr;
    void* ropeCosDeviceAddr = nullptr;
    void* cacheIndexDeviceAddr = nullptr;
    void* kvCacheDeviceAddr = nullptr;
    void* krCacheDeviceAddr = nullptr;
    void* dequantScaleXDeviceAddr = nullptr;
    void* dequantScaleWDqDeviceAddr = nullptr;
    void* dequantScaleWUqQrDeviceAddr = nullptr;
    void* dequantScaleWDkvKrDeviceAddr = nullptr;
    void* quantScaleCkvDeviceAddr = nullptr;
    void* smoothScalesCqDeviceAddr = nullptr;
    void* queryDeviceAddr = nullptr;
    void* queryRopeDeviceAddr = nullptr;
    void* dequantScaleQNopeDeviceAddr = nullptr;

    void* tokenXHostAddr = nullptr;
    void* weightDqHostAddr = nullptr;
    void* weightUqQrHostAddr = nullptr;
    void* weightUkHostAddr = nullptr;
    void* weightDkvKrHostAddr = nullptr;
    void* rmsnormGammaCqHostAddr = nullptr;
    void* rmsnormGammaCkvHostAddr = nullptr;
    void* ropeSinHostAddr = nullptr;
    void* ropeCosHostAddr = nullptr;
    void* cacheIndexHostAddr = nullptr;
    void* kvCacheHostAddr = nullptr;
    void* krCacheHostAddr = nullptr;
    void* dequantScaleXHostAddr = nullptr;
    void* dequantScaleWDqHostAddr = nullptr;
    void* dequantScaleWUqQrHostAddr = nullptr;
    void* dequantScaleWDkvKrHostAddr = nullptr;
    void* quantScaleCkvHostAddr = nullptr;
    void* smoothScalesCqHostAddr = nullptr;
    void* queryHostAddr = nullptr;
    void* queryRopeHostAddr = nullptr;
    void* dequantScaleQNopeHostAddr = nullptr;

    aclTensor* tokenX = nullptr;
    aclTensor* weightDq = nullptr;
    aclTensor* weightUqQr = nullptr;
    aclTensor* weightUk = nullptr;
    aclTensor* weightDkvKr = nullptr;
    aclTensor* rmsnormGammaCq = nullptr;
    aclTensor* rmsnormGammaCkv = nullptr;
    aclTensor* ropeSin = nullptr;
    aclTensor* ropeCos = nullptr;
    aclTensor* cacheIndex = nullptr;
    aclTensor* kvCache = nullptr;
    aclTensor* krCache = nullptr;
    aclTensor* dequantScaleX = nullptr;
    aclTensor* dequantScaleWDq = nullptr;
    aclTensor* dequantScaleWUqQr = nullptr;
    aclTensor* dequantScaleWDkvKr = nullptr;
    aclTensor* quantScaleCkv = nullptr;
    aclTensor* smoothScalesCq = nullptr;
    int64_t weightQuantMode = 2;
    int64_t kvQuantMode = 1;
    int64_t queryQuantMode = 1;
    int64_t ckvkrRepoMode = 0;
    int64_t quantScaleRepoMode = 0;
    int64_t tileSize = 128;
    double kNopeClipAlpha = 1.0f;
    double qcQrScale = 1.0f;
    double kcScale = 1.0f;
    aclTensor* query = nullptr;
    aclTensor* queryRope = nullptr;
    aclTensor* dequantScaleQNope = nullptr;

    // Convert the shapes of the three variables in NZ format.
    constexpr size_t EXAMPLE_INT8_SIZE = sizeof(int8_t);
    constexpr size_t EXAMPLE_BFLOAT16_SIZE = sizeof(int16_t);
    ret = TransToNZShape(weightDqShape, EXAMPLE_INT8_SIZE);
    CHECK_RET(ret == 0, LOG_PRINT("trans NZ shape failed.\n"); return ret);
    ret = TransToNZShape(weightUqQrShape, EXAMPLE_INT8_SIZE);
    CHECK_RET(ret == 0, LOG_PRINT("trans NZ shape failed.\n"); return ret);
    ret = TransToNZShape(weightDkvKrShape, EXAMPLE_INT8_SIZE);
    CHECK_RET(ret == 0, LOG_PRINT("trans NZ shape failed.\n"); return ret);

    // Create the tokenX aclTensor.
    ret = CreateAclTensorND(tokenXShape, &tokenXDeviceAddr, &tokenXHostAddr, aclDataType::ACL_INT8, &tokenX);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    // Create the weightDq aclTensor.
    ret = CreateAclTensorNZ(weightDqShape, &weightDqDeviceAddr, &weightDqHostAddr, aclDataType::ACL_INT8, &weightDq);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    // Create the weightUqQr aclTensor.
    ret = CreateAclTensorNZ(weightUqQrShape, &weightUqQrDeviceAddr, &weightUqQrHostAddr, aclDataType::ACL_INT8, &weightUqQr);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    // Create weightUk aclTensor.
    ret = CreateAclTensorND(weightUkShape, &weightUkDeviceAddr, &weightUkHostAddr, aclDataType::ACL_BF16, &weightUk);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    // Create weightDkvKr aclTensor.
    ret = CreateAclTensorNZ(weightDkvKrShape, &weightDkvKrDeviceAddr, &weightDkvKrHostAddr, aclDataType::ACL_INT8, &weightDkvKr);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    // Create rmsnormGammaCq aclTensor.
    ret = CreateAclTensorND(rmsnormGammaCqShape, &rmsnormGammaCqDeviceAddr, &rmsnormGammaCqHostAddr, aclDataType::ACL_BF16, &rmsnormGammaCq);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    // Create rmsnormGammaCkv aclTensor.
    ret = CreateAclTensorND(rmsnormGammaCkvShape, &rmsnormGammaCkvDeviceAddr, &rmsnormGammaCkvHostAddr, aclDataType::ACL_BF16, &rmsnormGammaCkv);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    // Create ropeSin aclTensor.
    ret = CreateAclTensorND(ropeSinShape, &ropeSinDeviceAddr, &ropeSinHostAddr, aclDataType::ACL_BF16, &ropeSin);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    // Create ropeCos aclTensor.
    ret = CreateAclTensorND(ropeCosShape, &ropeCosDeviceAddr, &ropeCosHostAddr, aclDataType::ACL_BF16, &ropeCos);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    // Create cacheIndex aclTensor.
    ret = CreateAclTensorND(cacheIndexShape, &cacheIndexDeviceAddr, &cacheIndexHostAddr, aclDataType::ACL_INT64, &cacheIndex);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    // Create kvCache aclTensor.
    ret = CreateAclTensorND(kvCacheShape, &kvCacheDeviceAddr, &kvCacheHostAddr, aclDataType::ACL_INT8, &kvCache);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    // Create krCache aclTensor.
    ret = CreateAclTensorND(krCacheShape, &krCacheDeviceAddr, &krCacheHostAddr, aclDataType::ACL_BF16, &krCache);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    // Create dequantScaleX aclTensor.
    ret = CreateAclTensorND(dequantScaleXShape, &dequantScaleXDeviceAddr, &dequantScaleXHostAddr, aclDataType::ACL_FLOAT, &dequantScaleX);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    // Create the dequantScaleWDq aclTensor.
    ret = CreateAclTensorND(dequantScaleWDqShape, &dequantScaleWDqDeviceAddr, &dequantScaleWDqHostAddr, aclDataType::ACL_FLOAT, &dequantScaleWDq);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    // Create the dequantScaleWUqQr aclTensor.
    ret = CreateAclTensorND(dequantScaleWUqQrShape, &dequantScaleWUqQrDeviceAddr, &dequantScaleWUqQrHostAddr, aclDataType::ACL_FLOAT, &dequantScaleWUqQr);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    // Create the dequantScaleWDkvKr aclTensor.
    ret = CreateAclTensorND(dequantScaleWDkvKrShape, &dequantScaleWDkvKrDeviceAddr, &dequantScaleWDkvKrHostAddr, aclDataType::ACL_FLOAT, &dequantScaleWDkvKr);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    // Create the quantScaleCkv aclTensor.
    ret = CreateAclTensorND(quantScaleCkvShape, &quantScaleCkvDeviceAddr, &quantScaleCkvHostAddr, aclDataType::ACL_FLOAT, &quantScaleCkv);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    // Create the smoothScalesCq aclTensor.
    ret = CreateAclTensorND(smoothScalesCqShape, &smoothScalesCqDeviceAddr, &smoothScalesCqHostAddr, aclDataType::ACL_FLOAT, &smoothScalesCq);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    // Create the query aclTensor.
    ret = CreateAclTensorND(queryShape, &queryDeviceAddr, &queryHostAddr, aclDataType::ACL_INT8, &query);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    // Create the queryRope aclTensor.
    ret = CreateAclTensorND(queryRopeShape, &queryRopeDeviceAddr, &queryRopeHostAddr, aclDataType::ACL_BF16, &queryRope);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    // Create the dequantScaleQNope aclTensor.
    ret = CreateAclTensorND(dequantScaleQNopeShape, &dequantScaleQNopeDeviceAddr, &dequantScaleQNopeHostAddr, aclDataType::ACL_FLOAT, &dequantScaleQNope);
    CHECK_RET(ret == ACL_SUCCESS, return ret);

    // 3. Call the CANN operator library API and replace it with the actual API.
    uint64_t workspaceSize = 0;
    aclOpExecutor* executor = nullptr;
    // Call the first-phase API of aclnnMlaPrologV3WeightNz.
    ret = aclnnMlaPrologV3WeightNzGetWorkspaceSize(tokenX, weightDq, weightUqQr, weightUk, weightDkvKr, rmsnormGammaCq, rmsnormGammaCkv, ropeSin, ropeCos, kvCache, krCache, cacheIndex,
      dequantScaleX, dequantScaleWDq, dequantScaleWUqQr, dequantScaleWDkvKr, quantScaleCkv, nullptr, smoothScalesCq, nullptr, nullptr,rmsnormEpsilonCq, rmsnormEpsilonCkv, cacheMode,
      weightQuantMode, kvQuantMode, queryQuantMode, ckvkrRepoMode, quantScaleRepoMode, tileSize, qcQrScale, kcScale,
      query, queryRope, dequantScaleQNope, nullptr, nullptr, &workspaceSize, &executor);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnMlaPrologV3WeightNzGetWorkspaceSize failed. ERROR: %d\n", ret); return ret);
    // Allocate device memory with the workspaceSize calculated by the first-phase API.
    void* workspaceAddr = nullptr;
    if (workspaceSize > static_cast<uint64_t>(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 aclnnMlaPrologV3WeightNz.
    ret = aclnnMlaPrologV3WeightNz(workspaceAddr, workspaceSize, executor, stream);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnMlaPrologV3WeightNz failed. ERROR: %d\n", ret); return ret);

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

    // 5. Obtain the output values and copy the result from device memory to host memory. Modify the code based on the specific API definition.
    auto size = GetShapeSize(queryShape);
    std::vector<float> resultData(size, 0);
    ret = aclrtMemcpy(resultData.data(), resultData.size() * sizeof(resultData[0]), queryDeviceAddr, size * 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 < size; i++) {
      LOG_PRINT("result[%ld] is: %f\n", i, resultData[i]);
    }
    // 6. Release aclTensor and aclScalar. Modify the code based on the specific API definition.
    aclDestroyTensor(tokenX);
    aclDestroyTensor(weightDq);
    aclDestroyTensor(weightUqQr);
    aclDestroyTensor(weightUk);
    aclDestroyTensor(weightDkvKr);
    aclDestroyTensor(rmsnormGammaCq);
    aclDestroyTensor(rmsnormGammaCkv);
    aclDestroyTensor(ropeSin);
    aclDestroyTensor(ropeCos);
    aclDestroyTensor(cacheIndex);
    aclDestroyTensor(kvCache);
    aclDestroyTensor(krCache);
    aclDestroyTensor(dequantScaleX);
    aclDestroyTensor(dequantScaleWDq);
    aclDestroyTensor(dequantScaleWUqQr);
    aclDestroyTensor(dequantScaleWDkvKr);
    aclDestroyTensor(quantScaleCkv);
    aclDestroyTensor(smoothScalesCq);
    aclDestroyTensor(query);
    aclDestroyTensor(queryRope);
    aclDestroyTensor(dequantScaleQNope);

    // 7. Release device resources.
    aclrtFree(tokenXDeviceAddr);
    aclrtFree(weightDqDeviceAddr);
    aclrtFree(weightUqQrDeviceAddr);
    aclrtFree(weightUkDeviceAddr);
    aclrtFree(weightDkvKrDeviceAddr);
    aclrtFree(rmsnormGammaCqDeviceAddr);
    aclrtFree(rmsnormGammaCkvDeviceAddr);
    aclrtFree(ropeSinDeviceAddr);
    aclrtFree(ropeCosDeviceAddr);
    aclrtFree(cacheIndexDeviceAddr);
    aclrtFree(kvCacheDeviceAddr);
    aclrtFree(krCacheDeviceAddr);
    aclrtFree(dequantScaleXDeviceAddr);
    aclrtFree(dequantScaleWDqDeviceAddr);
    aclrtFree(dequantScaleWUqQrDeviceAddr);
    aclrtFree(dequantScaleWDkvKrDeviceAddr);
    aclrtFree(quantScaleCkvDeviceAddr);
    aclrtFree(smoothScalesCqDeviceAddr);
    aclrtFree(queryDeviceAddr);
    aclrtFree(queryRopeDeviceAddr);
    aclrtFree(dequantScaleQNopeDeviceAddr);

    // 8. Release host resources.
    aclrtFree(tokenXHostAddr);
    aclrtFree(weightDqHostAddr);
    aclrtFree(weightUqQrHostAddr);
    aclrtFree(weightUkHostAddr);
    aclrtFree(weightDkvKrHostAddr);
    aclrtFree(rmsnormGammaCqHostAddr);
    aclrtFree(rmsnormGammaCkvHostAddr);
    aclrtFree(ropeSinHostAddr);
    aclrtFree(ropeCosHostAddr);
    aclrtFree(cacheIndexHostAddr);
    aclrtFree(kvCacheHostAddr);
    aclrtFree(krCacheHostAddr);
    aclrtFree(dequantScaleXHostAddr);
    aclrtFree(dequantScaleWDqHostAddr);
    aclrtFree(dequantScaleWUqQrHostAddr);
    aclrtFree(dequantScaleWDkvKrHostAddr);
    aclrtFree(quantScaleCkvHostAddr);
    aclrtFree(smoothScalesCqHostAddr);
    aclrtFree(queryHostAddr);
    aclrtFree(queryRopeHostAddr);
    aclrtFree(dequantScaleQNopeHostAddr);

    if (workspaceSize > static_cast<uint64_t>(0)) {
        aclrtFree(workspaceAddr);
    }
    aclrtDestroyStream(stream);
    aclrtResetDevice(deviceId);
    aclFinalize();

    return 0;
}

The sample code for Ascend 950PR&950DT products is as follows, for reference only.

#include <iostream>
#include <cstring>
#include <vector>
#include <cstdint>
#include "acl/acl.h"
#include "aclnnop/aclnn_mla_prolog_v3_weight_nz.h"
#include <unistd.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 CreateAclTensorND(const std::vector<T>& shape, void** deviceAddr, void** hostAddr,
                  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 aclrtMalloc to allocate host memory.
  ret = aclrtMallocHost(hostAddr, size);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtMallocHost failed. ERROR: %d\n", ret); return ret);
  memset(*hostAddr, 0, size);
  // Call aclCreateTensor to create an aclTensor.
  *tensor = aclCreateTensor(shape.data(), shape.size(), dataType, nullptr, 0, aclFormat::ACL_FORMAT_ND,
                            shape.data(), shape.size(), *deviceAddr);
  // Call aclrtMemcpy to copy data from host to device memory.
  ret = aclrtMemcpy(*deviceAddr, size, *hostAddr, GetShapeSize(shape) * aclDataTypeSize(dataType), ACL_MEMCPY_HOST_TO_DEVICE);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtMemcpy failed. ERROR: %d\n", ret); return ret);
  return 0;
}

template <typename T>
int CreateAclTensorNZ(const std::vector<T>& shape, void** deviceAddr, void** hostAddr,
                  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 aclrtMalloc to allocate host memory.
  ret = aclrtMallocHost(hostAddr, size);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtMallocHost failed. ERROR: %d\n", ret); return ret);
  memset(*hostAddr, 0, size);
  // Call aclCreateTensor to create an aclTensor.
  *tensor = aclCreateTensor(shape.data(), shape.size(), dataType, nullptr, 0, aclFormat::ACL_FORMAT_FRACTAL_NZ,
                            shape.data(), shape.size(), *deviceAddr);
  // Call aclrtMemcpy to copy data from host to device memory.
  ret = aclrtMemcpy(*deviceAddr, size, *hostAddr, GetShapeSize(shape) * aclDataTypeSize(dataType), ACL_MEMCPY_HOST_TO_DEVICE);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtMemcpy failed. ERROR: %d\n", ret); return ret);
  return 0;
}

int TransToNZShape(std::vector<int64_t> &shapeND, size_t typeSize) {
  if (typeSize == static_cast<size_t>(0)) {
      return 0;
  }
  int64_t h = shapeND[0];
  int64_t w = shapeND[1];
  int64_t h0 = static_cast<int64_t>(16);
  int64_t w0 = static_cast<int64_t>(32) / static_cast<int64_t>(typeSize);
  int64_t h1 = h / h0;
  int64_t w1 = w / w0;
  shapeND[0] = w1;
  shapeND[1] = h1;
  shapeND.emplace_back(h0);
  shapeND.emplace_back(w0);
  return 0;
}

int main() {
  // 1. Boilerplate: initialize device/stream. For details, see the list of AscendCL external APIs.
  // 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 tensors based on the API definition.
  std::vector<int64_t> tokenXShape = {8, 1, 7168};            // B,S,He
  std::vector<int64_t> weightDqShape = {7168, 1536};          // He,Hcq
  std::vector<int64_t> weightUqQrShape = {1536, 24576};        // Hcq,N*(D+Dr)
  std::vector<int64_t> weightUkShape = {128, 128, 512};        // N,D,Hckv
  std::vector<int64_t> weightDkvKrShape = {7168, 576};        // He,Hckv+Dr
  std::vector<int64_t> rmsnormGammaCqShape = {1536};          // Hcq
  std::vector<int64_t> rmsnormGammaCkvShape = {512};          // Hckv
  std::vector<int64_t> ropeSinShape = {8, 1, 64};             // B,S,Dr
  std::vector<int64_t> ropeCosShape = {8, 1, 64};             // B,S,Dr
  std::vector<int64_t> kvCacheShape = {1, 16, 1, 512};      // BlockNum,BlockSize,Nkv,Hckv
  std::vector<int64_t> krCacheShape = {1, 16, 1, 64};       // BlockNum,BlockSize,Nkv,Dr
  std::vector<int64_t> cacheIndexShape = {8, 1};              // B,S
  std::vector<int64_t> dequantScaleXShape = {8, 224};           // B*S, 1
  std::vector<int64_t> dequantScaleWDqShape = {1536, 224};      // 1, Hcq
  std::vector<int64_t> dequantScaleWUqQrShape = {24576, 48};    // 1, N*(D+Dr)
  std::vector<int64_t> dequantScaleWDkvKrShape = {576, 224};    // 1, Hckv+Dr
  std::vector<int64_t> quantScaleCkvShape = {1};    // 1
  std::vector<int64_t> queryShape = {8, 1, 128, 512};          // B,S,N,Hckv
  std::vector<int64_t> queryRopeShape = {8, 1, 128, 64};       // B,S,N,Dr
  std::vector<int64_t> dequantScaleQNopeShape = {8, 128, 1};   // B*S, N, 1
  double rmsnormEpsilonCq = 1e-5;
  double rmsnormEpsilonCkv = 1e-5;
  char cacheMode[] = "PA_BSND";

  void* tokenXDeviceAddr = nullptr;
  void* weightDqDeviceAddr = nullptr;
  void* weightUqQrDeviceAddr = nullptr;
  void* weightUkDeviceAddr = nullptr;
  void* weightDkvKrDeviceAddr = nullptr;
  void* rmsnormGammaCqDeviceAddr = nullptr;
  void* rmsnormGammaCkvDeviceAddr = nullptr;
  void* ropeSinDeviceAddr = nullptr;
  void* ropeCosDeviceAddr = nullptr;
  void* cacheIndexDeviceAddr = nullptr;
  void* kvCacheDeviceAddr = nullptr;
  void* krCacheDeviceAddr = nullptr;
  void* dequantScaleXDeviceAddr = nullptr;
  void* dequantScaleWDqDeviceAddr = nullptr;
  void* dequantScaleWUqQrDeviceAddr = nullptr;
  void* dequantScaleWDkvKrDeviceAddr = nullptr;
  void* quantScaleCkvDeviceAddr = nullptr;
  void* queryDeviceAddr = nullptr;
  void* queryRopeDeviceAddr = nullptr;
  void* dequantScaleQNopeDeviceAddr = nullptr;

  void* tokenXHostAddr = nullptr;
  void* weightDqHostAddr = nullptr;
  void* weightUqQrHostAddr = nullptr;
  void* weightUkHostAddr = nullptr;
  void* weightDkvKrHostAddr = nullptr;
  void* rmsnormGammaCqHostAddr = nullptr;
  void* rmsnormGammaCkvHostAddr = nullptr;
  void* ropeSinHostAddr = nullptr;
  void* ropeCosHostAddr = nullptr;
  void* cacheIndexHostAddr = nullptr;
  void* kvCacheHostAddr = nullptr;
  void* krCacheHostAddr = nullptr;
  void* dequantScaleXHostAddr = nullptr;
  void* dequantScaleWDqHostAddr = nullptr;
  void* dequantScaleWUqQrHostAddr = nullptr;
  void* dequantScaleWDkvKrHostAddr = nullptr;
  void* quantScaleCkvHostAddr = nullptr;
  void* queryHostAddr = nullptr;
  void* queryRopeHostAddr = nullptr;
  void* dequantScaleQNopeHostAddr = nullptr;

  aclTensor* tokenX = nullptr;
  aclTensor* weightDq = nullptr;
  aclTensor* weightUqQr = nullptr;
  aclTensor* weightUk = nullptr;
  aclTensor* weightDkvKr = nullptr;
  aclTensor* rmsnormGammaCq = nullptr;
  aclTensor* rmsnormGammaCkv = nullptr;
  aclTensor* ropeSin = nullptr;
  aclTensor* ropeCos = nullptr;
  aclTensor* kvCache = nullptr;
  aclTensor* krCache = nullptr;
  aclTensor* cacheIndex = nullptr;
  aclTensor* dequantScaleX = nullptr;
  aclTensor* dequantScaleWDq = nullptr;
  aclTensor* dequantScaleWUqQr = nullptr;
  aclTensor* dequantScaleWDkvKr = nullptr;
  aclTensor* quantScaleCkv = nullptr;
  int64_t weightQuantMode = 3;
  int64_t kvQuantMode = 1;
  int64_t queryQuantMode = 1;
  int64_t ckvkrRepoMode = 0;
  int64_t quantScaleRepoMode = 0;
  int64_t tileSize = 128;
  double qcQrScale = 1.0f;
  double kcScale = 1.0f;
  aclTensor* query = nullptr;
  aclTensor* queryRope = nullptr;
  aclTensor* dequantScaleQNope = nullptr;

  // Convert the shapes of the three NZ-format variables.
  constexpr size_t EXAMPLE_INT8_SIZE = sizeof(int8_t);
  constexpr size_t EXAMPLE_BFLOAT16_SIZE = sizeof(int16_t);
  ret = TransToNZShape(weightDqShape, EXAMPLE_INT8_SIZE);
  CHECK_RET(ret == 0, LOG_PRINT("trans NZ shape failed.\n"); return ret);
  ret = TransToNZShape(weightUqQrShape, EXAMPLE_INT8_SIZE);
  CHECK_RET(ret == 0, LOG_PRINT("trans NZ shape failed.\n"); return ret);
  ret = TransToNZShape(weightDkvKrShape, EXAMPLE_INT8_SIZE);
  CHECK_RET(ret == 0, LOG_PRINT("trans NZ shape failed.\n"); return ret);

  // Create the tokenX aclTensor.
  ret = CreateAclTensorND(tokenXShape, &tokenXDeviceAddr, &tokenXHostAddr, aclDataType::ACL_FLOAT8_E4M3FN, &tokenX);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  // Create the weightDq aclTensor.
  ret = CreateAclTensorNZ(weightDqShape, &weightDqDeviceAddr, &weightDqHostAddr, aclDataType::ACL_FLOAT8_E4M3FN, &weightDq);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  // Create the weightUqQr aclTensor.
  ret = CreateAclTensorNZ(weightUqQrShape, &weightUqQrDeviceAddr, &weightUqQrHostAddr, aclDataType::ACL_FLOAT8_E4M3FN, &weightUqQr);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  // Create the weightUk aclTensor.
  ret = CreateAclTensorND(weightUkShape, &weightUkDeviceAddr, &weightUkHostAddr, aclDataType::ACL_BF16, &weightUk);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  // Create the weightDkvKr aclTensor.
  ret = CreateAclTensorNZ(weightDkvKrShape, &weightDkvKrDeviceAddr, &weightDkvKrHostAddr, aclDataType::ACL_FLOAT8_E4M3FN, &weightDkvKr);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  // Create the rmsnormGammaCq aclTensor.
  ret = CreateAclTensorND(rmsnormGammaCqShape, &rmsnormGammaCqDeviceAddr, &rmsnormGammaCqHostAddr, aclDataType::ACL_BF16, &rmsnormGammaCq);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  // Create the rmsnormGammaCkv aclTensor.
  ret = CreateAclTensorND(rmsnormGammaCkvShape, &rmsnormGammaCkvDeviceAddr, &rmsnormGammaCkvHostAddr, aclDataType::ACL_BF16, &rmsnormGammaCkv);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  // Create the ropeSin aclTensor.
  ret = CreateAclTensorND(ropeSinShape, &ropeSinDeviceAddr, &ropeSinHostAddr, aclDataType::ACL_BF16, &ropeSin);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  // Create the ropeCos aclTensor.
  ret = CreateAclTensorND(ropeCosShape, &ropeCosDeviceAddr, &ropeCosHostAddr, aclDataType::ACL_BF16, &ropeCos);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  // Create the cacheIndex aclTensor.
  ret = CreateAclTensorND(cacheIndexShape, &cacheIndexDeviceAddr, &cacheIndexHostAddr, aclDataType::ACL_INT64, &cacheIndex);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  // Create the kvCache aclTensor.
  ret = CreateAclTensorND(kvCacheShape, &kvCacheDeviceAddr, &kvCacheHostAddr, aclDataType::ACL_FLOAT8_E4M3FN, &kvCache);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  // Create the krCache aclTensor.
  ret = CreateAclTensorND(krCacheShape, &krCacheDeviceAddr, &krCacheHostAddr, aclDataType::ACL_BF16, &krCache);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  // Create the dequantScaleX aclTensor.
  ret = CreateAclTensorND(dequantScaleXShape, &dequantScaleXDeviceAddr, &dequantScaleXHostAddr, aclDataType::ACL_FLOAT8_E8M0, &dequantScaleX);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  // Create the dequantScaleWDq aclTensor.
  ret = CreateAclTensorND(dequantScaleWDqShape, &dequantScaleWDqDeviceAddr, &dequantScaleWDqHostAddr, aclDataType::ACL_FLOAT8_E8M0, &dequantScaleWDq);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  // Create the dequantScaleWUqQr aclTensor.
  ret = CreateAclTensorND(dequantScaleWUqQrShape, &dequantScaleWUqQrDeviceAddr, &dequantScaleWUqQrHostAddr, aclDataType::ACL_FLOAT8_E8M0, &dequantScaleWUqQr);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  // Create the dequantScaleWDkvKr aclTensor.
  ret = CreateAclTensorND(dequantScaleWDkvKrShape, &dequantScaleWDkvKrDeviceAddr, &dequantScaleWDkvKrHostAddr, aclDataType::ACL_FLOAT8_E8M0, &dequantScaleWDkvKr);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  // Create the quantScaleCkv aclTensor.
  ret = CreateAclTensorND(quantScaleCkvShape, &quantScaleCkvDeviceAddr, &quantScaleCkvHostAddr, aclDataType::ACL_FLOAT, &quantScaleCkv);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  // Create the query aclTensor.
  ret = CreateAclTensorND(queryShape, &queryDeviceAddr, &queryHostAddr, aclDataType::ACL_FLOAT8_E4M3FN, &query);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  // Create queryRope aclTensor.
  ret = CreateAclTensorND(queryRopeShape, &queryRopeDeviceAddr, &queryRopeHostAddr, aclDataType::ACL_BF16, &queryRope);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  // Create dequantScaleQNope aclTensor.
  ret = CreateAclTensorND(dequantScaleQNopeShape, &dequantScaleQNopeDeviceAddr, &dequantScaleQNopeHostAddr, aclDataType::ACL_FLOAT, &dequantScaleQNope);
  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 = nullptr;
  // Call the first-phase API of aclnnMlaPrologV3WeightNz.
  ret = aclnnMlaPrologV3WeightNzGetWorkspaceSize(tokenX, weightDq, weightUqQr, weightUk, weightDkvKr, rmsnormGammaCq, rmsnormGammaCkv, ropeSin, ropeCos, kvCache, krCache, cacheIndex,
      dequantScaleX, dequantScaleWDq, dequantScaleWUqQr, dequantScaleWDkvKr, quantScaleCkv, nullptr, nullptr, nullptr, nullptr, rmsnormEpsilonCq, rmsnormEpsilonCkv, cacheMode,
      weightQuantMode, kvQuantMode, queryQuantMode, ckvkrRepoMode, quantScaleRepoMode, tileSize, qcQrScale, kcScale,
      query, queryRope, dequantScaleQNope, nullptr, nullptr, &workspaceSize, &executor);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnMlaPrologV3WeightNzGetWorkspaceSize failed. ERROR: %d\n", ret); return ret);
  // Allocate device memory based on the workspaceSize calculated by the first-phase API.
  void* workspaceAddr = nullptr;
  if (workspaceSize > static_cast<uint64_t>(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 aclnnMlaPrologV3WeightNz.
  ret = aclnnMlaPrologV3WeightNz(workspaceAddr, workspaceSize, executor, stream);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnMlaPrologV3WeightNz failed. ERROR: %d\n", ret); return ret);

  // 4. Boilerplate. Synchronously 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 values and copy the results from device memory to host memory. Modify the code according to the specific API definition.
  auto size = GetShapeSize(queryShape);
  std::vector<float> resultData(size, 0);
  ret = aclrtMemcpy(resultData.data(), resultData.size() * sizeof(resultData[0]), queryDeviceAddr, size * 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 < size; i++) {
      LOG_PRINT("result[%ld] is: %f\n", i, resultData[i]);
  }
  // 6. Release aclTensor and aclScalar. Modify the code according to the specific API definition.
  aclDestroyTensor(tokenX);
  aclDestroyTensor(weightDq);
  aclDestroyTensor(weightUqQr);
  aclDestroyTensor(weightUk);
  aclDestroyTensor(weightDkvKr);
  aclDestroyTensor(rmsnormGammaCq);
  aclDestroyTensor(rmsnormGammaCkv);
  aclDestroyTensor(ropeSin);
  aclDestroyTensor(ropeCos);
  aclDestroyTensor(cacheIndex);
  aclDestroyTensor(kvCache);
  aclDestroyTensor(krCache);
  aclDestroyTensor(dequantScaleX);
  aclDestroyTensor(dequantScaleWDq);
  aclDestroyTensor(dequantScaleWUqQr);
  aclDestroyTensor(dequantScaleWDkvKr);
  aclDestroyTensor(quantScaleCkv);
  aclDestroyTensor(query);
  aclDestroyTensor(queryRope);
  aclDestroyTensor(dequantScaleQNope);

  // 7. Release device resources.
  aclrtFree(tokenXDeviceAddr);
  aclrtFree(weightDqDeviceAddr);
  aclrtFree(weightUqQrDeviceAddr);
  aclrtFree(weightUkDeviceAddr);
  aclrtFree(weightDkvKrDeviceAddr);
  aclrtFree(rmsnormGammaCqDeviceAddr);
  aclrtFree(rmsnormGammaCkvDeviceAddr);
  aclrtFree(ropeSinDeviceAddr);
  aclrtFree(ropeCosDeviceAddr);
  aclrtFree(cacheIndexDeviceAddr);
  aclrtFree(kvCacheDeviceAddr);
  aclrtFree(krCacheDeviceAddr);
  aclrtFree(dequantScaleXDeviceAddr);
  aclrtFree(dequantScaleWDqDeviceAddr);
  aclrtFree(dequantScaleWUqQrDeviceAddr);
  aclrtFree(dequantScaleWDkvKrDeviceAddr);
  aclrtFree(quantScaleCkvDeviceAddr);
  aclrtFree(queryDeviceAddr);
  aclrtFree(queryRopeDeviceAddr);
  aclrtFree(dequantScaleQNopeDeviceAddr);

  // 8. Release host resources.
  aclrtFree(tokenXHostAddr);
  aclrtFree(weightDqHostAddr);
  aclrtFree(weightUqQrHostAddr);
  aclrtFree(weightUkHostAddr);
  aclrtFree(weightDkvKrHostAddr);
  aclrtFree(rmsnormGammaCqHostAddr);
  aclrtFree(rmsnormGammaCkvHostAddr);
  aclrtFree(ropeSinHostAddr);
  aclrtFree(ropeCosHostAddr);
  aclrtFree(cacheIndexHostAddr);
  aclrtFree(kvCacheHostAddr);
  aclrtFree(krCacheHostAddr);
  aclrtFree(dequantScaleXHostAddr);
  aclrtFree(dequantScaleWDqHostAddr);
  aclrtFree(dequantScaleWUqQrHostAddr);
  aclrtFree(dequantScaleWDkvKrHostAddr);
  aclrtFree(quantScaleCkvHostAddr);
  aclrtFree(queryHostAddr);
  aclrtFree(queryRopeHostAddr);
  aclrtFree(dequantScaleQNopeHostAddr);

  if (workspaceSize > static_cast<uint64_t>(0)) {
      aclrtFree(workspaceAddr);
  }
  aclrtDestroyStream(stream);
  aclrtResetDevice(deviceId);
  aclFinalize();

  _exit(0);
}