aclnnMlaPrologV2WeightNz
Note: This API will be deprecated in later versions. Use the latest API aclnnMlaPrologV3WeightNz instead.
Applicable Products
Ascend 950PR&950DT products : Not supported
Atlas A3 products : Supported
Atlas A2 products : Supported
Atlas 200I/500 A2 inference products : Not supported
Atlas inference products : Not supported
Atlas training products : Not supported
Function
Description: In inference scenarios, this API performs the pre-processing computation for Multi-Head Latent Attention. The main computation process is divided into five paths:
- First, the input $x$ is multiplied by $W^{DQ}$ for downsampling and RmsNorm, and then split into two paths. The first path is multiplied by $W^{UQ}$ and $W^{UK}$ and undergoes two upsampling operations to obtain $q^N$. The second path is multiplied by $W^{QR}$ and then undergoes rotary position encoding (ROPE) to obtain $q^R$.
- The third path: the input $x$ is multiplied by $W^{DKV}$ for downsampling and RmsNorm, then passed 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.
- The weight parameters WeightDq, WeightUqQr, and WeightDkvKr must be passed in NZ format.
Formula:
RmsNormformula:$$ \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 Query includes downsampling, RmsNorm, and two upsampling operations.
$$ c^Q = RmsNorm(x \cdot W^{DQ}) $$$$ q^C = c^Q \cdot W^{UQ} $$$$ q^N = q^C \cdot W^{UK} $$Performs rotary position encoding (ROPE) to the query.
$$ q^R = 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} = RmsNorm(x \cdot W^{DKV}) $$$$ k^C = Cache(c^{KV}) $$Performs rotary position encoding (ROPE) to the key and stores the result in the cache.
$$ k^R = Cache(ROPE(x \cdot W^{KR})) $$The calculation formula of Dequant Scale Query Nope:
$$ dequantScaleQNope = {RowMax(abs(q^{N})) / 127} $$$$ q^{N} = {round(q^{N} / dequantScaleQNope)} $$
Function Prototype
Each operator uses a two-phase API. First call the "aclnnMlaPrologV2WeightNzGetWorkspaceSize" API to obtain the input parameters and calculate the required workspace size based on the process, and then call the "aclnnMlaPrologV2WeightNz" API to perform the calculation.
aclnnStatus aclnnMlaPrologV2WeightNzGetWorkspaceSize(
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,
const aclTensor *cacheIndex,
aclTensor *kvCacheRef,
aclTensor *krCacheRef,
const aclTensor *dequantScaleXOptional,
const aclTensor *dequantScaleWDqOptional,
const aclTensor *dequantScaleWUqQrOptional,
const aclTensor *dequantScaleWDkvKrOptional,
const aclTensor *quantScaleCkvOptional,
const aclTensor *quantScaleCkrOptional,
const aclTensor *smoothScalesCqOptional,
double rmsnormEpsilonCq,
double rmsnormEpsilonCkv,
char *cacheModeOptional,
const aclTensor *queryOut,
const aclTensor *queryRopeOut,
const aclTensor *dequantScaleQNopeOutOptional,
uint64_t *workspaceSize,
aclOpExecutor **executor)aclnnStatus aclnnMlaPrologV2WeightNz(
void *workspace,
uint64_t workspaceSize,
aclOpExecutor *executor,
const aclrtStream stream)aclnnMlaPrologV2WeightNzGetWorkspaceSize
Parameters
Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor tokenX Input Input tensor for calculating Query and Key in the formula. - Supports empty tensors with B=0,S=0,T=0.
BFLOAT16, INT8 ND - BS axis combination: (T,He)
- BS non-axis-combined: (B,S,He)× weightDq Input Downsampling weight matrix WDQ for calculating Query in the formula. Empty tensors are not supported. BFLOAT16, INT8 FRACTAL_NZ (He,Hcq) × weightUqQr Input Upsampling weight matrix WUQ for calculating Query and position encoding weight matrix WQR in the formula. - Empty tensors are not supported
- If dtype is INT8 (quantization use case): the input must be per-tensor quantized; dequantScaleWUqQrOptional is required when the output is non-quantized; dequantScaleWUqQrOptional, quantScaleCkvOptional, and quantScaleCkrOptional are required when the output is quantized; smoothScalesCqOptional is optional
- If dtype is BFLOAT16 (non-quantized use case): dequantScaleWUqQrOptional, quantScaleCkvOptional, quantScaleCkrOptional, and smoothScalesCqOptional must be set to null pointers
BFLOAT16, INT8 FRACTAL_NZ (Hcq,N*(D+Dr)) × weightUk Input Upsampling weight WUK used to calculate 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 calculate the Key in the formula. Empty tensors are not supported. BFLOAT16, INT8 FRACTAL_NZ (He,Hckv+Dr) × rmsnormGammaCq Input The γ parameter in the RmsNorm formula for calculating cQ. Empty tensors are not supported. BFLOAT16 ND (Hcq) × rmsnormGammaCkv Input The γ parameter in the RmsNorm formula for calculating cKV. Empty tensors are not supported. BFLOAT16 ND (Hckv) × ropeSin Input Sine parameter matrix used to calculate the rotary position encoding. Empty tensors with B=0, S=0, T=0 are supported. BFLOAT16 ND - BS axis combination: (T,Dr)
- BS non-axis-combined: (B,S,Dr)× ropeCos Input Cosine parameter matrix used to calculate the rotary position encoding. Empty tensors with B=0,S=0,T=0 are supported. BFLOAT16 ND - BS axis combination: (T,Dr)
- BS non-axis-combined: (B,S,Dr)× cacheIndex Input Index used to store kvCache and krCache. - Empty tensors with B=0, S=0, T=0 are supported.
- The value range must be within [0,BlockNum*BlockSize).
INT64 ND - BS axis combination: (T)
- BS non-axis-combined: (B,S)× kvCacheRef Input aclTensor used for cache indexing. The calculation result is updated in place (corresponding to kC in the formula). - Supports empty tensors where B=0 and Skv=0
- Nkv is associated with N, and N is a hyperparameter. Therefore, Nkv cannot be set to 0
BFLOAT16, INT8 ND (BlockNum,BlockSize,Nkv,Hckv) Only the first axis can be non-contiguous; all other axes must be contiguous krCacheRef Input Cache used for key position encoding. The calculation result is updated in place (corresponding to kR in the formula). - Supports empty tensors with B=0, Skv=0.
- Nkv is associated with N. N is a hyperparameter. Therefore, Nkv cannot be 0.
BFLOAT16, INT8 ND (BlockNum,BlockSize,Nkv,Dr) Only the first axis can be non-contiguous; all other axes must be contiguous dequantScaleXOptional Input Dequantization parameter of tokenX. Supports the ND data format FLOAT ND - BS axis combination: (T)
- BS non-axis-combined: (B*S,1)× dequantScaleWDqOptional Input Dequantization parameter of weightDq. Supported data format: ND FLOAT ND (1,Hcq) × dequantScaleWUqQrOptional Input Per-channel parameter used for dequantization after the MatmulQcQr matrix multiplication. Non-empty Tensor is supported (required only in the INT8 dtype use case). FLOAT ND (1,N*(D+Dr)) × dequantScaleWDkvKrOptional Input Dequantization parameters for weightDkvKr. Only the ND data format is supported FLOAT ND (1, Hckv+Dr) × quantScaleCkvOptional Input Parameter for quantizing the kvCache output data. Supports non-empty Tensor (required only for the INT8 dtype use case) FLOAT ND (1,Hckv) × quantScaleCkrOptional Input Parameter used to quantize the krCache output data. Supports non-empty Tensor (required only for the INT8 dtype use case) FLOAT ND (1,Dr) × smoothScalesCqOptional Input Parameter for dynamic quantization of the RmsNormCq output. Supports non-empty tensors (passed only for the INT8 dtype use case). FLOAT ND (1,Hcq) rmsnormEpsilonCq Input The ε parameter in the RmsNorm formula for calculating cQ. - 1e-05 is recommended if not specified by the user.
- Only the double data type is supported.
DOUBLE - - - rmsnormEpsilonCkv Input The ε parameter in the RmsNorm formula for calculating cKV. - If not explicitly specified, 1e-05 is recommended.
- Only the double type is supported.
DOUBLE - - - cacheModeOptional Input Indicates the mode of kvCache. - If not explicitly specified, "PA_BSND" is recommended.
- Only the char* type is supported.
- Optional values: "PA_BSND" and "PA_NZ".
CHAR* - - - queryOut Output Output tensor of Query in the formula (corresponding to qN). - BFLOAT16, INT8 ND - BS axis combination: (T,N,Hckv)
- BS non-axis-combined: (B,S,N,Hckv)× queryRopeOut Output Output tensor of Query position encoding in the formula (corresponding to qR). - BFLOAT16 ND - BS axis combination: (T,N,Dr)
- BS non-axis-combined: (B,S,N,Dr)× dequantScaleQNopeOutOptional Output Dequantization parameter for the Query output. - FLOAT ND - BS axis combination: (T,1)
- BS non-axis-combined: (B*S,1)× workspaceSize Output Returns the size of the workspace to be requested on the Device. - Used only for output; no input configuration required.
- Data type is uint64_t*.
- - - - executor Output Returns the op executor, which contains the operator calculation process. - Used for output results only. No input configuration is required.
- Data type is aclOpExecutor**.
- - - - Return Value
aclnnStatus: Return status code. For details, see aclnn Return Codes.
The first-phase API performs input parameter validation and returns an error in the following scenarios:
Return Value Error Code Description ACLNN_ERR_PARAM_NULLPTR 161001 A null pointer exists in a required parameter (such as an input/output parameter that the API depends on). 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 (for example, the Runtime service is not started, or memory application fails). ACLNN_ERR_INNER_TILING_ERROR 561002 An exception occurs during tiling, or the dtype or shape of an input parameter is incorrect.
aclnnMlaPrologV2WeightNz
Parameters
Parameter Type Meaning workspace void* Workspace memory address allocated on the Device. workspaceSize uint64_t Size of the workspace allocated on the Device, obtained by calling the first-phase API aclnnMlaPrologV2WeightNzGetWorkspaceSize. executor aclOpExecutor* Executor containing the operator calculation process. stream aclrtStream Stream for executing tasks. Return Value
aclnnStatus: return status code. For details, see aclnn return codes.
Constraints
- Deterministic computation:
- aclnnMlaPrologV2WeightNz defaults to a deterministic implementation.
Meaning of shape format fields
| Field Name | Full Name/Meaning | Value Rule and Description |
|---|---|---|
| B | Batch (batch size of input samples) | Value range: 0-65536 |
| S | Seq-Length (sequence length of input samples) | Value range: no limit |
| He | Hidden-Size (hidden layer size) | Fixed value: 1024, 2048, 3072, 4096, 5120, 6144, 7168, 7680, 8192 |
| Hcq | q low-rank matrix dimension | Fixed value: 1536 |
| N | Head-Num (number of heads) | Value range: 1, 2, 4, 8, 16, 32, 64, 128 |
| Hckv | kv low-rank matrix dimension | Fixed value: 512 |
| D | qk dimension excluding position encoding | Fixed value: 128 |
| 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 | Value is ⌈B*Skv/BlockSize⌉, the rounded-up result of B*Skv/BlockSize (Skv indicates the sequence length of kv, and 0 is allowed). |
| BlockSize | Block size in the PagedAttention use case | Value range: 16-1024, and a multiple of 16 |
| T | Size after BS axis concatenation |
|
shape constraints
- Dimensions of weight_dq, weight_uq_qr, and weight_dkv_kr in the non-transposed case: (k, n).
- Shape constraints:
- If the dimension of tokenX uses BS concatenated axis, i.e., (T, He)
- The shape of ropeSin and ropeCos is (T, Dr)
- The shape of cacheIndex is (T).
- The shape of dequantScaleXOptional is (T, 1).
- The shape of queryOut is (T, N, Hckv).
- The shape of queryRopeOut is (T, N, Dr).
- In the int8 full quantization scenario, the shape of dequantScaleQNopeOutOptional is (T, N, 1); in other scenarios, it is (1).
- 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)
- The shape of cacheIndex is (B, S)
- The shape of dequantScaleXOptional is (B*S, 1)
- The shape of queryOut is (B, S, N, Hckv)
- The shape of queryRopeOut is (B, S, N, Dr).
- In the int8 full quantization scenario, the shape of dequantScaleQNopeOutOptional is (B*S, N, 1); in other scenarios, it is (1).
- 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.
- If the dimension of tokenX uses BS concatenated axis, i.e., (T, He)
Supported use cases of the aclnnMlaPrologV2WeightNz API
| Use Case | Meaning | |
|---|---|---|
| Non-quantized | Input: all inputs are non-quantized data Output: all outputs are non-quantized data |
|
| Partial quantization | Non-quantized kv_cache | Input: weightUqQr takes pertoken quantized data, and all other inputs are non-quantized data Output: all outputs return non-quantized data |
| Quantized kv_cache | Input: weightUqQr takes pertoken quantized data, kvCacheRef and krCacheRef take perchannel quantized data, and all other inputs are non-quantized data Output: kvCacheRef and krCacheRef return perchannel quantized data, and all other outputs return non-quantized data |
|
| int8 full quantization | Non-quantized kv_cache | Inputs: tokenX uses pertoken quantized data, weightDq, weightUqQr, and weightDkvKr use perchannel quantized data, and the other inputs are all non-quantized data. Outputs: all outputs are non-quantized data. |
| kv_cache quantization | Inputs: tokenX uses pertoken quantized data, weightDq, weightUqQr, and weightDkvKr use perchannel quantized data, kvCacheRef uses pertensor quantized data, and the other inputs are all non-quantized data. Outputs: queryOut returns pertoken_head quantized data, the output kvCacheRef returns pertensor quantized data, and the other outputs are non-quantized data. |
|
dtype and shape constraints of parameters in different quantization use cases
- In different quantization scenarios, the dtype and shape combinations of parameters must meet the following conditions:
| Parameter | Non-quantized use case | Partial quantization use case | int8 full quantization use case | |||||||
|---|---|---|---|---|---|---|---|---|---|---|
| kv_cache non-quantized | Quantized kv_cache | Non-quantized kv_cache | Quantized kv_cache | |||||||
| dtype | shape | dtype | shape | dtype | shape | dtype | shape | dtype | shape | |
| tokenX | BFLOAT16 | · (B,S,He) · (T, He) |
BFLOAT16 | · (B,S,He) · (T, He) |
BFLOAT16 | · (B,S,He) · (T, He) |
INT8 | · (B,S,He) · (T, He) |
INT8 | · (B,S,He) · (T, He) |
| weightDq | BFLOAT16 | (He, Hcq) | BFLOAT16 | (He, Hcq) | BFLOAT16 | (He, Hcq) | INT8 | (He, Hcq) | INT8 | (He, Hcq) |
| weightUqQr | BFLOAT16 | (Hcq, N*(D+Dr)) | INT8 | (Hcq, N*(D+Dr)) | INT8 | (Hcq, N*(D+Dr)) | INT8 | (Hcq, N*(D+Dr)) | INT8 | (Hcq, N*(D+Dr)) |
| weightUk | BFLOAT16 | (N, D, Hckv) | BFLOAT16 | (N, D, Hckv) | BFLOAT16 | (N, D, Hckv) | BFLOAT16 | (N, D, Hckv) | BFLOAT16 | (N, D, Hckv) |
| weightDkvKr | BFLOAT16 | (He, Hckv+Dr) | BFLOAT16 | (He, Hckv+Dr) | BFLOAT16 | (He, Hckv+Dr) | INT8 | (He, Hckv+Dr) | INT8 | (He, Hckv+Dr) |
| rmsnormGammaCq | BFLOAT16 | (Hcq) | BFLOAT16 | (Hcq) | BFLOAT16 | (Hcq) | BFLOAT16 | (Hcq) | BFLOAT16 | (Hcq) |
| rmsnormGammaCkv | BFLOAT16 | (Hckv) | BFLOAT16 | (Hckv) | BFLOAT16 | (Hckv) | BFLOAT16 | (Hckv) | BFLOAT16 | (Hckv) |
| ropeSin | BFLOAT16 | · (B,S,Dr) · (T, Dr ) |
BFLOAT16 | · (B,S,Dr) · (T, Dr ) |
BFLOAT16 | · (B,S,Dr) · (T, Dr ) |
BFLOAT16 | · (B,S,Dr) · (T, Dr ) |
BFLOAT16 | · (B,S,Dr) · (T, Dr ) |
| ropeCos | BFLOAT16 | · (B,S,Dr) · (T, Dr ) |
BFLOAT16 | · (B,S,Dr) · (T, Dr ) |
BFLOAT16 | · (B,S,Dr) · (T, Dr ) |
BFLOAT16 | · (B,S,Dr) · (T, Dr ) |
BFLOAT16 | · (B,S,Dr) · (T, Dr ) |
| cacheIndex | INT64 | · (B,S) · (T) |
INT64 | · (B,S) · (T) |
INT64 | · (B,S) · (T) |
INT64 | · (B,S) · (T) |
INT64 | · (B,S) · (T) |
| kvCacheRef | BFLOAT16 | (BlockNum, BlockSize, Nkv, Hckv) | BFLOAT16 | (BlockNum, BlockSize, Nkv, Hckv) | INT8 | (BlockNum, BlockSize, Nkv, Hckv) | BFLOAT16 | (BlockNum, BlockSize, Nkv, Hckv) | INT8 | (BlockNum, BlockSize, Nkv, Hckv) |
| krCacheRef | BFLOAT16 | (BlockNum, BlockSize, Nkv, Dr) | BFLOAT16 | (BlockNum, BlockSize, Nkv, Dr) | INT8 | (BlockNum, BlockSize, Nkv, Dr) | BFLOAT16 | (BlockNum, BlockSize, Nkv, Dr) | BFLOAT16 | (BlockNum, BlockSize, Nkv, Dr) |
| dequantScaleXOptional | No assignment required. | - | No assignment required. | - | No assignment required. | - | FLOAT | · (B*S, 1) · (T, 1) |
FLOAT | · (B*S, 1) · (T, 1) |
| dequantScaleWDqOptional | No assignment required. | - | No assignment required. | - | No assignment required. | - | FLOAT | (1, Hcq) | FLOAT | (1, Hcq) |
| dequantScaleWUqQrOptional | No assignment required. | - | FLOAT | (1, N*(D+Dr)) | FLOAT | (1, N*(D+Dr)) | FLOAT | (1, N*(D+Dr)) | FLOAT | (1, N*(D+Dr)) |
| dequantScaleWDkvKrOptional | No assignment required. | - | No assignment required | - | No assignment required | - | FLOAT | (1, Hckv+Dr) | FLOAT | (1, Hckv+Dr) |
| quantScaleCkvOptional | No assignment required | - | No assignment required | - | FLOAT | (1, Hckv) | No assignment required | - | FLOAT | (1, Hckv) |
| quantScaleCkrOptional | No assignment required | - | No assignment required | - | FLOAT | (1, Dr) | No assignment required | - | No assignment required | - |
| smoothScalesCqOptional | No assignment required. | - | FLOAT | (1, Hcq) | FLOAT | (1, Hcq) | FLOAT | (1, Hcq) | FLOAT | (1, Hcq) |
| queryOut | BFLOAT16 | · (B, S, N, Hckv) · (T, N, Hckv) |
BFLOAT16 | · (B, S, N, Hckv) · (T, N, Hckv) |
BFLOAT16 | · (B, S, N, Hckv) · (T, N, Hckv) |
BFLOAT16 | · (B, S, N, Hckv) · (T, N, Hckv) |
INT8 | · (B, S, N, Hckv) · (T, N, Hckv) |
| queryRopeOut | BFLOAT16 | · (B, S, N, Dr) · (T, N, Dr) |
BFLOAT16 | · (B, S, N, Dr) · (T, N, Dr) |
BFLOAT16 | · (B, S, N, Dr) · (T, N, Dr) |
BFLOAT16 | · (B, S, N, Dr) · (T, N, Dr) |
BFLOAT16 | · (B, S, N, Dr) · (T, N, Dr) |
| dequantScaleQNopeOutOptional | No assignment required. | - | No assignment required. | - | No assignment required. | - | No assignment required. | - | FLOAT | · (B*S, N, 1) · (T, N, 1) |
Example
The following sample code applies to
#include <iostream>
#include <vector>
#include <cstdint>
#include "acl/acl.h"
#include "aclnnop/aclnn_mla_prolog_v2_weight_nz.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 memory on the device.
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 memory on the host.
ret = aclrtMalloc(hostAddr, size, ACL_MEM_MALLOC_HUGE_FIRST);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtMalloc failed. ERROR: %d\n", ret); return ret);
// 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-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;
}
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-side 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-side memory.
ret = aclrtMalloc(hostAddr, size, ACL_MEM_MALLOC_HUGE_FIRST);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtMalloc failed. ERROR: %d\n", ret); return ret);
// 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) {
int64_t h = shapeND[0];
int64_t w = shapeND[1];
int64_t h0 = 16;
int64_t w0 = 32U / 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/stream. For details, see the list of AscendCL public APIs.
// Fill in deviceId based on the actual device.
int32_t deviceId = 0;
aclrtStream stream;
auto ret = Init(deviceId, &stream);
// Handle the check based on the actual situation.
CHECK_RET(ret == 0, LOG_PRINT("Init acl failed. ERROR: %d\n", ret); return ret);
// 2. Construct the 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, 512}; // 1, Hckv
std::vector<int64_t> smoothScaleCqShape = {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* smoothScaleCqDeviceAddr = 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* smoothScaleCqHostAddr = 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* smoothScaleCq = nullptr;
aclTensor* query = nullptr;
aclTensor* queryRope = nullptr;
aclTensor* dequantScaleQNope = nullptr;
// Convert the shapes of the three NZ-format variables.
ret = TransToNZShape(weightDqShape, sizeof(int8_t));
CHECK_RET(ret == 0, LOG_PRINT("trans NZ shape failed. \n"); return ret);
ret = TransToNZShape(weightUqQrShape, sizeof(int8_t));
CHECK_RET(ret == 0, LOG_PRINT("trans NZ shape failed. \n"); return ret);
ret = TransToNZShape(weightDkvKrShape, sizeof(int8_t));
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 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 dequantScaleWDq aclTensor.
ret = CreateAclTensorND(dequantScaleWDqShape, &dequantScaleWDqDeviceAddr, &dequantScaleWDqHostAddr, aclDataType::ACL_FLOAT, &dequantScaleWDq);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// Create dequantScaleWUqQr aclTensor.
ret = CreateAclTensorND(dequantScaleWUqQrShape, &dequantScaleWUqQrDeviceAddr, &dequantScaleWUqQrHostAddr, aclDataType::ACL_FLOAT, &dequantScaleWUqQr);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// Create dequantScaleWDkvKr aclTensor.
ret = CreateAclTensorND(dequantScaleWDkvKrShape, &dequantScaleWDkvKrDeviceAddr, &dequantScaleWDkvKrHostAddr, aclDataType::ACL_FLOAT, &dequantScaleWDkvKr);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// Create quantScaleCkv aclTensor.
ret = CreateAclTensorND(quantScaleCkvShape, &quantScaleCkvDeviceAddr, &quantScaleCkvHostAddr, aclDataType::ACL_FLOAT, &quantScaleCkv);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// Create smoothScaleCq aclTensor.
ret = CreateAclTensorND(smoothScaleCqShape, &smoothScaleCqDeviceAddr, &smoothScaleCqHostAddr, aclDataType::ACL_FLOAT, &smoothScaleCq);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// Create 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. Change it to the specific API.
uint64_t workspaceSize = 0;
aclOpExecutor* executor = nullptr;
// Call the aclnnMlaPrologV2WeightNz first-phase API.
ret = aclnnMlaPrologV2WeightNzGetWorkspaceSize(tokenX, weightDq, weightUqQr, weightUk, weightDkvKr, rmsnormGammaCq, rmsnormGammaCkv, ropeSin, ropeCos, cacheIndex, kvCache, krCache,
dequantScaleX, dequantScaleWDq, dequantScaleWUqQr, dequantScaleWDkvKr, quantScaleCkv, nullptr, smoothScaleCq, rmsnormEpsilonCq, rmsnormEpsilonCkv, cacheMode,
query, queryRope, dequantScaleQNope, &workspaceSize, &executor);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnMlaPrologV2WeightNzGetWorkspaceSize 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 > 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 aclnnMlaPrologV2WeightNz second-phase API.
ret = aclnnMlaPrologV2WeightNz(workspaceAddr, workspaceSize, executor, stream);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnMlaPrologV2WeightNz failed. ERROR: %d\n", ret); return ret);
// 4. Boilerplate. Wait for the task execution to complete synchronously.
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 according to the 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);
// 6. Release aclTensor and aclScalar. Modify the code according to the 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(smoothScaleCq);
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(smoothScaleCqDeviceAddr);
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(smoothScaleCqHostAddr);
aclrtFree(queryHostAddr);
aclrtFree(queryRopeHostAddr);
aclrtFree(dequantScaleQNopeHostAddr);
if (workspaceSize > 0) {
aclrtFree(workspaceAddr);
}
aclrtDestroyStream(stream);
aclrtResetDevice(deviceId);
aclFinalize();
return 0;
}