aclnnMlaPrologV4WeightNz

📄 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 aclnnMlaPrologV3weightNz)

    • Added the optional parameter doRope: controls whether to perform rotary position encoding on queryRopeOut and krCache. The default value is true. When doRope=true, non-empty valid ropeSin/ropeCos Tensors must be passed in. When doRope=false, RoPE is skipped and pass-through results are written; in this case, ropeSin/ropeCos must both be empty (nullptr or empty Tensors).
    • The range of N:Head-Num (number of heads) is adjusted to 1-128
  • 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}$ for downsampling and RmsNorm and then split into two paths. In the first path, the result is multiplied by $W^{UQ}$ and $W^{UK}$ through two upsampling operations and then multiplied by the Query scale correction factor $\alpha_q$ to obtain $q^N$. In the second path, the result is multiplied by $W^{QR}$; when doRope=true, rotary position encoding is applied to obtain $q^R$; when doRope=false, $c^Q \cdot W^{QR}$ is directly written out.
    • 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$;
    • In the fourth path, after the input $x$ is multiplied by $W^{KR}$, rotary position encoding is applied when doRope=true and the result is written into the Cache to obtain $k^R$; when doRope=false, $x \cdot W^{KR}$ is directly written into the Cache;
    • 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.

    Perform ROPE rotary position encoding on the Query (doRope=true)

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

    When doRope=false

    $$ q^R = 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.

    Perform ROPE rotary position encoding on the Key, and store the result in the cache (doRope=true)

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

    When doRope=false

    $$ k^R = \mathrm{Cache}(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. Call "aclnnMlaPrologV4WeightNzGetWorkspaceSize" first to obtain the input parameters and calculate the required workspace size based on the process, and then call "aclnnMlaPrologV4WeightNz" to perform the computation.

aclnnStatus aclnnMlaPrologV4WeightNzGetWorkspaceSize(
    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,
    bool             doRope,
    const aclTensor *queryOut,
    const aclTensor *queryRopeOut,
    const aclTensor *dequantScaleQNopeOutOptional,
    const aclTensor *queryNormOutOptional,
    const aclTensor *dequantScaleQNormOutOptional,
    uint64_t        *workspaceSize,
    aclOpExecutor  **executor)
aclnnStatus aclnnMlaPrologV4WeightNz(
  void             *workspace,
  uint64_t          workspaceSize,
  aclOpExecutor    *executor,
  const aclrtStream stream)

aclnnMlaPrologV4WeightNzGetWorkspaceSize

  • Parameters

    Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor
    tokenX Input Input tensor used to compute Query and Key in the formula. Empty tensors with B=0, S=0, T=0 are supported BFLOAT16, FLOAT8_E4M3FN, INT8, HIFLOAT8 ND
    • BS aligned axis: (T, He)
    • BS non-aligned axis: (B, S, He)
    ×
    weightDq Input Downsampling weight matrix WDQ used to compute Query in the formula.
    Dimension meanings 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.
    Dimension meanings without transposition: (k, n)
    Empty tensors are not supported. BFLOAT16, INT8, FLOAT8_E4M3FN, HIFLOAT8 FRACTAL_NZ (Hcq, N*(D+Dr)) ×
    weightUk Input Upsampling weight WUK of Key used in the Formula. Empty tensors are not supported. BFLOAT16 ND (N, D, Hckv) ×
    weightDkvKr Input Downsampling weight matrix WDKV for computing Key and position encoding weight matrix WKR in the Formula.
    Dimension representation in the non-transposed case: (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 for computing the rotary position encoding. Required when doRope=true. Empty tensors with B=0, S=0, T=0 are supported (indicating that the dimension length is 0). When doRope=false, both must be empty (nullptr). BFLOAT16 ND
    • BS aligned axis: (T,Dr)
    • BS non-aligned axis: (B,S,Dr)
    ×
    ropeCos Input Cosine parameter matrix for computing the rotary position encoding. Required when doRope=true; supports empty tensors with B=0, S=0, or T=0 (indicating the dimension length is 0). Must be empty (nullptr) when doRope=false. BFLOAT16 ND
    • BS aligned axis: (T,Dr)
    • BS non-aligned axis: (B,S,Dr)
    ×
    kvCacheRef Input/Output aclTensor used for cache indexing, with calculation results updated in place (corresponding to kC 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, 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. The computation result is updated in place (corresponding to kR in the Formula).
    • Supports empty tensors with B=0,Skv=0;
    • Nkv is associated with N, and N is a hyperparameter, so Nkv=0 is not supported.
    • When doRope=false: RoPE is skipped, and x·WKR is written directly to the cache; the shape is not affected.
    BFLOAT16, INT8 ND
    • CacheMode="PA_BSND"/"PA_NZ"/"PA_BLK_BSND"/"PA_BLK_NZ": (BlockNum,BlockSize,Nkv,Dr)
    • CacheMode="BSND": (B,S,Nkv,Dr)
    • CacheMode="TND": (T,Nkv,Dr)
    • When ckvkrRepoMode=1: the dimensions should include 0, and a shape of (0) is supported.
    Only the first axis can be non-contiguous; all other axes must be contiguous.
    cacheIndexOptional Input Index used to store kvCache and krCache.
    • Supports empty tensors with B=0, S=0, and T=0.
    • cacheMode="PA_BSND"/"PA_NZ": The value range must be within [0,BlockNum*BlockSize).
    • cacheMode="PA_BLK_BSND"/"PA_BLK_NZ": The value range must be within [0,BlockNum).
    • cacheMode="TND"/"BSND": nullptr.
    INT64 ND
    • CacheMode="PA_BSND"/"PA_NZ":
      1. BS aligned axis: (T)
      2. BS non-aligned axis: (B,S)
    • CacheMode="PA_BLK_BSND"/"PA_BLK_NZ":
      1. BS aligned axis: (Sum(⌈Si/BlockSize⌉)), where Si is the S length in each Batch.
      2. BS non-aligned axis: (B,⌈S/BlockSize⌉)
    • CacheMode="TND"/"BSND": nullptr
    ×
    dequantScaleXOptional Input Dequantization parameter of tokenX. Supports empty tensors with B=0, S=0, and T=0 (required when weightQuantMode=2/3/4/5). FLOAT8_E8M0, FLOAT ND
    • weightQuantMode=2/4/5:
      1. BS aligned axis: (T, 1)
      2. BS non-aligned axis: (B*S,1)
    • weightQuantMode=3:
      1. BS aligned axis: (T, He/32)
      2. BS non-aligned axis: (B*S, He/32)
    ×
    dequantScaleWDqOptional Input Dequantization parameter of weightDq. Supports non-empty tensors (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 perchannel parameter for dequantization after the MatmulQcQr matrix multiplication. Non-empty tensor (required for use cases where 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 parameter of weightDkvKr. Non-empty tensor (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 Parameter for quantizing the kvCache output data. Supports non-empty tensor (must be passed in use cases where kvCacheQuantMode=1/2) FLOAT ND
    • kvCacheQuantMode=1: (1)
    • kvCacheQuantMode=2: (1,Hckv)
    ×
    quantScaleCkrOptional Input Parameter for quantizing the output data of krCache. Supports non-empty tensor (must be passed in use cases where kvCacheQuantMode=2) FLOAT ND (1,Dr) ×
    smoothScalesCqOptional Input Parameter used to perform dynamic quantization on the RmsNormCq output. Non-empty Tensor supported (optional when weightQuantMode=1/2/4/5) FLOAT ND (1,Hcq) ×
    actualSeqLenOptional Input Represents the sequence length of each batch, stored as a prefix sum. Required when BS axes are aligned 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 the partial quantization per-token-per-group scenario and the int8 full quantization per-token-per-group scenario; not supported in other scenarios. Empty tensors are not supported. FLOAT ND (1) ×
    rmsnormEpsilonCq Input Parameter ε in the RmsNorm formula for computing cQ.
    • 1e-05 is recommended if not specified by the user.
    • Only the double data 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 data type is supported.
    DOUBLE - - -
    cacheModeOptional Input Indicates the mode of kvCache.
    • It is recommended to pass "PA_BSND" if not explicitly specified.
    • Only the char* type is supported.
    • Valid values: "PA_BSND", "PA_NZ", "PA_BLK_BSND", "PA_BLK_NZ", "BSND", "TND"
    CHAR* - - -
    queryNormFlag Input Indicates whether to output queryNormOutOptional and dequantScaleQNormOutOptional. false indicates no output, true indicates output. The default value is false. BOOL - - -
    weightQuantMode Input Represents the quantization mode of weightDq, weightUqQr, weightUk, and weightDkvKr.
    • 0 indicates non-quantized.
    • 1 indicates quantization of weightUqQr.
    • 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.
    • The default value is 0.
    INT - - -
    kvCacheQuantMode Input Represents the quantization mode of kvCache. 0 indicates non-quantized, 1 indicates pertensor quantization, 2 indicates perchannel quantization, 3 indicates per-token-per-group quantization, and the default value is 0. INT64 - - -
    queryQuantMode Input Indicates the quantization mode of query. 0 indicates non-quantized, 1 indicates per-token-head quantization, and the default value is 0. INT64 - - -
    ckvkrRepoMode Input Indicates the storage mode of kvCache and krCache. 0 indicates that kvCache and krCache are stored separately, and 1 indicates that kvCache and krCache are stored together. The default value is 0. INT64 - - -
    quantScaleRepoMode Input Specifies the storage mode of the quantization scale. 0 indicates that the quantization scale and data are stored separately. 1 indicates that the quantization scale and data are stored together as the kvCacheRef output. Default value: 0 INT64 - - -
    tileSize Input Indicates the size of each tile for per-token-per-group quantization. Valid only when kvCacheQuantMode is 3. The default value is 128 INT64 - - -
    qcQrScale Input Indicates the scale correction coefficient of Query. Must be set to 1.0 if not explicitly specified by the user. DOUBLE - - -
    kcScale Input Scale correction coefficient for Key. Must be set to 1.0 if not explicitly specified by the user. DOUBLE - - -
    doRope Input Specifies whether to perform rotary position encoding (RoPE) on queryRopeOut and krCache.
    • Default true: RoPE is performed; in this case, ropeSin/ropeCos must be non-empty valid tensors
    • false: RoPE is skipped and the pass-through result is written; in this case, ropeSin/ropeCos must both be empty (nullptr)
    BOOL - - -
    queryOut Output Output tensor of Query in the Formula (corresponding to qN). - BFLOAT16, FLOAT8_E4M3FN, INT8, HIFLOAT8 ND
    • BS aligned axis: (T,N,Hckv)
    • BS non-aligned axis: (B,S,N,Hckv)
    ×
    queryRopeOut Output The output tensor of Query position encoding in the Formula (corresponding to qR). When doRope=false: skips RoPE and directly outputs the cQ·WQR passthrough result. The shape is not affected. BFLOAT16 ND
    • BS aligned axis: (T,N,Dr)
    • BS non-aligned axis: (B,S,N,Dr)
    ×
    dequantScaleQNopeOutOptional Output The dequantization parameter of the Query output in the Formula. Output when weightQuantMode=2/3/4/5, nullptr when weightQuantMode=0/1. FLOAT ND
    • BS aligned axis: (T,N,1)
    • BS non-aligned 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 aligned axis: (T,Hcq)
    • BS non-aligned 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 aligned axis: (T,1)
      2. BS non-aligned axis: (B*S,1)
    • weightQuantMode=3:
      1. BS aligned axis: (T, Hcq/32)
      2. BS non-aligned axis: (B*S, Hcq/32)
    ×
    workspaceSize Output Returns the size of the workspace to be allocated on the device. Used only for output. No input configuration is required. The data type is uint64_t*. - - - -
    executor Output Returns the op executor, which contains the operator computation flow. Used only to output the result. 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 Values Error Code Description
    ACLNN_ERR_PARAM_NULLPTR 161001 The required parameters (such as input/output parameters on which the API core depends) contain a null pointer.
    ACLNN_ERR_PARAM_INVALID 161002 The shape (dimension/size) or dtype (data type) of the input parameters is out of the range supported by the API.
    ACLNN_ERR_RUNTIME_ERROR 361001 An exception occurs when the API calls the NPU Runtime API to allocate memory (for example, the Runtime service is not started or memory allocation fails).
    ACLNN_ERR_INNER_TILING_ERROR 561002 An exception occurs during tiling. The input parameter dtype or shape is incorrect.

aclnnMlaPrologV4WeightNz

  • Parameters

    Parameter Type Description
    workspace void* Memory address of the workspace allocated on the device.
    workspaceSize uint64_t Size of the workspace allocated on the device, obtained by the first-phase API aclnnMlaPrologV4WeightNzGetWorkspaceSize.
    executor aclOpExecutor* Operator executor, containing the operator computation process.
    stream aclrtStream Stream that executes tasks.
  • Return Value

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

Constraints

  • Deterministic computation:
    • aclnnMlaPrologV4WeightNz defaults to a deterministic implementation.
Description of shape format fields   
Field Name Full Name/Meaning Value Rules and Description
B Batch (batch size of input samples) Value range: 0-65536
S Seq-Length (sequence length of input samples) Value range: unlimited
He Head-Size (hidden layer size) Fixed value: 1024, 2048, 3072, 4096, 5120, 6144, 7168, 7680, 8192
Hcq Dimension of the low-rank q matrix Fixed value: 1536, 2048
N Head-Num (number of heads) Value range: 1-128
Hckv Dimension of the low-rank kv matrix Fixed value: 512
D qk dimension excluding position encoding Fixed value: 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
  • When CacheMode="PA_BSND"/"PA_NZ", the value must be greater than or equal to ⌈(B * S) / BlockSize⌉.
  • When CacheMode="PA_BLK_BSND"/"PA_BLK_NZ", the value must be greater than or equal to B * ⌈S / BlockSize⌉.

Note: In the BS axis fusion use case, the S length of each Batch can be different. Therefore, the value of BlockNum must be greater than or equal to the sum of the values obtained by rounding up the result of dividing the S length of each Batch by BlockSize.

Example: If the value of actualSeqLenOptional is [47, 151, 261, 422] and blocksize=128, the lengths in each Batch are [47, 104, 110, 161] respectively. In this case, BlockNum = ⌈47/128⌉ + ⌈104/128⌉ + ⌈110/128⌉ + ⌈161/128⌉ = 5.

BlockSize Block size in the PagedAttention use case Value range: 16-1024, and the value must be a multiple of 16
T Size after BS axis fusion
  • Value range: unlimited
  • Note: If BS axis fusion is used, tokenX is 2-dimensional, cacheIndex is 1-dimensional, and queryOut and queryRopeOut are 3-dimensional. When doRope=true, ropeSin and ropeCos are 2-dimensional. When doRope=false, ropeSin and ropeCos must simultaneously be empty.
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)
    • When doRope=true, the shapes of ropeSin and ropeCos are (T, Dr); when doRope=false, ropeSin and ropeCos must simultaneously be empty.
    • 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)
    • When doRope=true, the shapes of ropeSin and ropeCos are (B, S, Dr); when doRope=false, ropeSin and ropeCos must simultaneously be empty.
    • 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.
  • When doRope=false, ropeSin and ropeCos must simultaneously be empty (nullptr).
  • 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.
Supported use cases of the aclnnMlaPrologV4WeightNz API
  • Atlas A2 products and Atlas A3 products: Currently, fp8/hif8/mxfp8 full quantization scenarios are not supported.
  • Ascend 950PR&950DT products: Currently, all quantization scenarios are supported.
Use case Description
Non-quantized weight_quant_mode=0,kv_cache_quant_mode=0,query_quant_mode=0
Input: all inputs are non-quantized data.
Output: all outputs are non-quantized data.
Partial quantization Non-quantized kvCache weight_quant_mode=1,kv_cache_quant_mode=0,query_quant_mode=0
Input: weightUqQr takes per-token quantized data, and the other inputs are non-quantized data. The dequantScaleWUqQr field is mandatory, and the smoothScalesCq field is optional.
Output: all outputs return non-quantized data.
Per-channel quantized kvCache weight_quant_mode=1,kv_cache_quant_mode=2,query_quant_mode=0
Input: weightUqQr takes per-token quantized data, kvCacheRef and krCacheRef take per-channel quantized data, and the other inputs are non-quantized data. The dequantScaleWUqQr, quantScaleCkv, and quant_scale_ckr fields are mandatory, and the smoothScalesCq field is optional.
Output: kvCacheRef and krCacheRef return per-channel quantized data, and the 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: weightUqQr takes per-token quantized data, and the other inputs are non-quantized data. The dequantScaleWUqQr field is required, and the smoothScalesCq field is optional
Output: kvCacheRef returns per-token-per-group quantized data, and the other outputs return non-quantized data
int8/fp8/hif8 full quantization kvCache non-quantized weight_quant_mode=2/4/5,kv_cache_quant_mode=0,query_quant_mode=0
Input: tokenX takes per-token quantized data, weightDq, weightUqQr, and weightDkvKr take per-channel quantized data, and the other inputs are non-quantized data. The dequantScaleX, dequantScaleWDq, dequantScaleWUqQr, and dequantScaleWDkvKr fields are required, and the smoothScalesCq field is optional
Output: all outputs return non-quantized data
kvCache per-tensor quantization weight_quant_mode=2/4/5,kv_cache_quant_mode=1,query_quant_mode=1
Input: tokenX takes per-token quantized data, weightDq, weightUqQr, and weightDkvKr take per-channel quantized data, kvCacheRef takes per-tensor quantized data, and the other inputs are non-quantized data. The dequantScaleX, dequantScaleWDq, dequantScaleWUqQr, dequantScaleWDkvKr, and quantScaleCkv fields are required, and the smoothScalesCq field is optional
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=2/4/5,kv_cache_quant_mode=3,query_quant_mode=0
Input: tokenX takes per-token quantized data, weightDq, weightUqQr, and weightDkvKr take per-channel quantized data, and the other inputs are non-quantized data. The dequantScaleX, dequantScaleWDq, dequantScaleWUqQr, and dequantScaleWDkvKr fields are required, and the smoothScalesCq field is optional
Output: the kvCacheRef output returns per-token-per-group quantized data, and the other outputs return non-quantized data
mxfp8 full quantization kvCache non-quantized weight_quant_mode=3,kv_cache_quant_mode=0,query_quant_mode=0
Input: 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 must be passed in.
Output: All output parameters return non-quantized data.
kvCache per-tensor quantization weight_quant_mode=3,kv_cache_quant_mode=1,query_quant_mode=1
Input: 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 must be passed in.
Output: queryOut returns per-token-head quantized data, the kvCacheRef output parameter returns per-tensor quantized data, and the other output parameters 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 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 must be passed in.
Output: The kvCacheRef output parameter returns per-token-per-group quantized data, and the other output parameters return non-quantized data.
dtype constraints on parameters in different quantization scenarios
Parameter Non-quantized scenario Partial quantization scenario int8 full quantization scenario mxfp8 full quantization scenario fp8 full quantization scenario hif8 full quantization scenario
kvCache non-quantized kvCache perchannel quantization kvCache per-token-per-group quantization kvCache non-quantized kvCache pertensor quantization kvCache per-token-per-group quantization kvCache non-quantized kvCache per-tensor quantization kvCache per-token-per-group quantization kvCache non-quantized kvCache per-tensor quantization kvCache per-token-per-group quantization kvCache non-quantized 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

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

#include <iostream>
#include <cstring>
#include <vector>
#include <cstdint>
#include "acl/acl.h"
#include "aclnnop/aclnn_mla_prolog_v4_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 data from the 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 the aclCreateTensor API 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 the 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: device/stream initialization. For details, see the AscendCL public API list.
    // 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 inputs and outputs 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;
    bool doRope = true;
    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_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 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_INT8, &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_INT8, &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_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. Replace it with the specific API.
    uint64_t workspaceSize = 0;
    aclOpExecutor* executor = nullptr;
    // Call the first-phase API of aclnnMlaPrologV4WeightNz.
    ret = aclnnMlaPrologV4WeightNzGetWorkspaceSize(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, doRope,
      query, queryRope, dequantScaleQNope, nullptr, nullptr, &workspaceSize, &executor);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnMlaPrologV4WeightNzGetWorkspaceSize failed. ERROR: %d\n", ret); return ret);
    // Allocate device memory based on workspaceSize computed 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 aclnnMlaPrologV4WeightNz
    ret = aclnnMlaPrologV4WeightNz(workspaceAddr, workspaceSize, executor, stream);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnMlaPrologV4WeightNz 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 it based on the definition of the specific API.
    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 it based on the definition of the specific API.
    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_v4_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: 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 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 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 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;
}

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 the device and stream. For details, see the AscendCL API list.
  // Set deviceId based on the actual device.
  int32_t deviceId = 0;
  aclrtStream stream;
  auto ret = Init(deviceId, &stream);
  // Handle the check as required.
  CHECK_RET(ret == 0, LOG_PRINT("Init acl failed. ERROR: %d\n", ret); return ret);
  // 2. Construct inputs and outputs according to 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;
  bool doRope = true;
  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 tokenX aclTensor.
  ret = CreateAclTensorND(tokenXShape, &tokenXDeviceAddr, &tokenXHostAddr, aclDataType::ACL_FLOAT8_E4M3FN, &tokenX);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  // Create weightDq aclTensor.
  ret = CreateAclTensorNZ(weightDqShape, &weightDqDeviceAddr, &weightDqHostAddr, aclDataType::ACL_FLOAT8_E4M3FN, &weightDq);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  // Create weightUqQr aclTensor.
  ret = CreateAclTensorNZ(weightUqQrShape, &weightUqQrDeviceAddr, &weightUqQrHostAddr, aclDataType::ACL_FLOAT8_E4M3FN, &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_FLOAT8_E4M3FN, &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 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 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. Replace it with the actual API.
  uint64_t workspaceSize = 0;
  aclOpExecutor* executor = nullptr;
  // Call the first-phase API of aclnnMlaPrologV4WeightNz.
  ret = aclnnMlaPrologV4WeightNzGetWorkspaceSize(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, doRope,
      query, queryRope, dequantScaleQNope, nullptr, nullptr, &workspaceSize, &executor);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnMlaPrologV4WeightNzGetWorkspaceSize 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 aclnnMlaPrologV4WeightNz.
  ret = aclnnMlaPrologV4WeightNz(workspaceAddr, workspaceSize, executor, stream);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnMlaPrologV4WeightNz failed. ERROR: %d\n", ret); return ret);

  // 4. Boilerplate: wait synchronously for 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 the device side to the host side. 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 the 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(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);
}