aclnnMlaProlog
NOTICE: 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 four 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 involves multiplying the input $x$ by $W^{DKV}$ for downsampling and RmsNorm, and then passing the result into a cache to obtain $k^C$. The fourth path involves multiplying the input $x$ by $W^{KR}$, undergoing rotary position encoding, and then passing the result into another cache to obtain $k^R$.
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 the query, including 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})) $$
Function Prototype
Each operator uses a two-phase API. First, call the "aclnnMlaPrologGetWorkspaceSize" API to obtain the input parameters and calculate the workspace size required by the process. Then, call the "aclnnMlaProlog" API to perform the computation.
aclnnStatus aclnnMlaPrologGetWorkspaceSize(
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,
uint64_t *workspaceSize,
aclOpExecutor **executor)aclnnStatus aclnnMlaProlog(
void *workspace,
uint64_t workspaceSize,
aclOpExecutor *executor,
aclrtStream stream)aclnnMlaPrologGetWorkspaceSize
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. - Supports empty tensors with B=0, S=0, T=0.
BFLOAT16 ND - BS merged: (T,He)
- BS not merged: (B,S,He)
× weightDq Input Downsampling weight matrix WDQ used to compute Query in the formula. - Empty tensors are not supported.
BFLOAT16 FRACTAL_NZ (He,Hcq) × weightUqQr Input Up-sampling weight matrix WUQ and position encoding weight matrix WQR used to compute Query in the formula. - Empty tensors are not supported.
- dtype is INT8 (quantization use case):
- Must be a per-tensor quantization input.
- dequantScaleWUqQrOptional is required for non-quantized output.
- dequantScaleWUqQrOptional, quantScaleCkvOptional, and quantScaleCkrOptional are required for quantized output.
- smoothScalesCqOptional is optional.
- dtype is BFLOAT16 (non-quantization use case): dequantScaleWUqQrOptional, quantScaleCkvOptional, quantScaleCkrOptional, and smoothScalesCqOptional must be null pointers.
BFLOAT16, INT8 FRACTAL_NZ (Hcq,N*(D+Dr)) × weightUk Input Upsampling weight WUK used to compute Key in the formula. Empty tensors are not supported BFLOAT16 ND (N,D,Hckv) × weightDkvKr Input Downsampling weight matrix WDKV for computing Key and positional encoding weight matrix WKR in the formula. Empty tensors are not supported. BFLOAT16 FRACTAL_NZ (He,Hckv+Dr) × rmsnormGammaCq Input The γ parameter in the RmsNorm formula for computing cQ. Empty tensors are not supported. BFLOAT16 ND (Hcq) × rmsnormGammaCkv Input The γ parameter in the RmsNorm formula for computing cKV. Empty tensors are not supported. BFLOAT16 ND (Hckv) × ropeSin Input Sine parameter matrix used to compute the rotary position embedding. Supports empty tensors with B=0, S=0, T=0. BFLOAT16 ND - BS merged: (T,Dr)
- BS unmerged: (B,S,Dr)
× ropeCos Input Cosine parameter matrix used to compute the rotary position embedding. Supports empty tensors with B=0, S=0, and T=0. BFLOAT16 ND - BS merged: (T,Dr)
- BS unmerged: (B,S,Dr)
× cacheIndex Input Index used to store kvCache and krCache. - Supports empty tensors with B=0, S=0, T=0.
- The value range must be within [0,BlockNum*BlockSize).
INT64 ND - BS merged axes: (T)
- BS non-merged axes: (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 with B=0, Skv=0.
- Nkv is associated with N. N is a hyperparameter, so Nkv cannot be 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 positional encoding. The calculation result is updated in place (corresponding to kR in the formula). - Supports empty tensors with B=0 and Skv=0
- Nkv is associated with N, where N is a hyper-parameter. 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. The data format supports ND. FLOAT ND - BS merged: (T)
- BS not merged: (B*S,1)
× dequantScaleWDqOptional Input Dequantization parameter of weightDq. Supported data format: ND FLOAT ND (1,Hcq) × dequantScaleWUqQrOptional Input Per-channel parameter for dequantization after the MatmulQcQr matrix multiplication. Non-empty tensor (required only for the INT8 dtype use case) FLOAT ND (1,N*(D+Dr)) × dequantScaleWDkvKrOptional Input Dequantization parameter of weightDkvKr. Data format supports ND FLOAT ND (1, Hckv+Dr) × quantScaleCkvOptional Input Parameter for quantizing the kvCache output data. Supports a non-empty Tensor (required only for the INT8 dtype use case). FLOAT ND (1,Hckv) × quantScaleCkr Input Parameter used to quantize the krCache output data. Supports a non-empty Tensor (required only for the INT8 dtype use case). FLOAT ND (1,Dr) × smoothScalesCqOptional Input Parameter for performing dynamic quantization on the RmsNormCq output. Supports non-empty tensor (required only for the INT8 dtype use case). FLOAT ND (1,Hcq) × rmsnormEpsilonCq Input The ε parameter in the RmsNorm formula for computing cQ. - 1e-05 is recommended if not specified by the user.
- Only the double type is supported.
DOUBLE - - - rmsnormEpsilonCkv Input The ε parameter in the RmsNorm formula for computing cKV. - 1e-05 is recommended if not specified by the user
- Only the double type is supported
DOUBLE - - - cacheModeOptional Input Indicates the mode of kvCache. - If not specified by the user, "PA_BSND" is recommended.
- Only the char* type is supported.
- Valid values: "PA_BSND" and "PA_NZ".
CHAR* - - - queryOut Output Output tensor of Query in the formula (corresponding to qN). - BFLOAT16, INT8 ND - BS with merged axes: (T,N,Hckv)
- BS with non-merged axes: (B,S,N,Hckv)
× queryRopeOut Output Output tensor of Query positional encoding in the formula (corresponding to qR). - BFLOAT16 ND - BS with merged axes: (T,N,Dr)
- BS with non-merged axes: (B,S,N,Dr)
× workspaceSize Output Size of the workspace to be allocated on the Device. - Used only to store output results; no input configuration required.
- Data type: uint64_t*
- - - - executor Output Returns the op executor, which contains the operator computation flow. - For output only. No input configuration is required.
- Data type: aclOpExecutor**
- - - - Return Value
aclnnStatus: Return status code. For details, see aclnn return code.
The first-phase API performs input parameter validation and returns an error in the following scenarios:
Return Values Error Codes Description ACLNN_ERR_PARAM_NULLPTR 161001 A null pointer exists in a required parameter (such as the input/output parameters on which the API depends). ACLNN_ERR_PARAM_INVALID 161002 The shape (dimension/size) or dtype (data type) of the input parameter is not within the range supported by the API. ACLNN_ERR_RUNTIME_ERROR 361001 An exception occurs when the API calls NPU Runtime APIs for memory operations (for example, the Runtime service is not started or memory allocation fails). ACLNN_ERR_INNER_TILING_ERROR 561002 An exception occurs during tiling. The dtype or shape of the input parameter is incorrect.
aclnnMlaProlog
Parameters
Parameter Type Description workspace void* Address of the workspace memory allocated on the Device. workspaceSize uint64_t Size of the workspace allocated on the Device, obtained by the first-phase API aclnnMlaPrologGetWorkspaceSize. executor aclOpExecutor* op executor, containing the operator computation flow. stream aclrtStream Stream for executing the task. Return Value
aclnnStatus: return status code. For details, see aclnn Return Codes.
Constraints
- Deterministic computation:
- aclnnMlaProlog 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 |
|
Special constraints
- Dimensions of weight_dq, weight_uq_qr, and weight_dkv_kr in the non-transposed case: (k, n).
Use cases supported by the aclnnMlaProlog API
| Use Case | Meaning | |
|---|---|---|
| Non-quantized | Input: all inputs are non-quantized data. Output: all outputs are non-quantized data. |
|
| Partially quantized | kv_cache non-quantized | Input: weightUqQr takes per-token quantized data, and all other inputs are non-quantized data. Output: all outputs return non-quantized data. |
| kv_cache quantized | Input: weightUqQr takes per-token quantized data, kvCacheRef and krCacheRef take per-channel quantized data, and all other inputs are non-quantized data. Output: kvCacheRef and krCacheRef return per-channel quantized data, and other outputs return non-quantized data. |
|
dtype and shape constraints for parameters in different quantization use cases
In different quantization use cases, dtype and shape combinations of parameters must meet the following conditions:
| Parameter | Non-quantization use case | Partial quantization use case | ||||
|---|---|---|---|---|---|---|
| Non-quantized kv_cache | Quantized kv_cache | |||||
| 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) |
| weightDq | BFLOAT16 | (He, Hcq) | BFLOAT16 | (He, Hcq) | BFLOAT16 | (He, Hcq) |
| weightUqQr | BFLOAT16 | (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) |
| weightDkvKr | BFLOAT16 | (He, Hckv+Dr) | BFLOAT16 | (He, Hckv+Dr) | BFLOAT16 | (He, Hckv+Dr) |
| rmsnormGammaCq | BFLOAT16 | (Hcq) | BFLOAT16 | (Hcq) | BFLOAT16 | (Hcq) |
| rmsnormGammaCkv | 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 ) |
| ropeCos | 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) |
| kvCacheRef | BFLOAT16 | (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) |
| dequantScaleXOptional | No need to assign | - | No need to assign | - | No need to assign | - |
| dequantScaleWDqOptional | No assignment required | - | No assignment required | - | No assignment required | - |
| dequantScaleWUqQrOptional | No assignment required | - | FLOAT | (1, N*(D+Dr)) | FLOAT | (1, N*(D+Dr)) |
| dequantScaleWDkvKrOptional | No value assignment required | - | No value assignment required | - | No assignment required | - |
| quantScaleCkvOptional | No assignment required | - | No assignment required | - | FLOAT | (1, Hckv) |
| quantScaleCkrOptional | No assignment required | - | No assignment required | - | FLOAT | (1, Dr) |
| smoothScalesCqOptional | No assignment required | - | 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) |
| 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) |
| dequantScaleQNopeOutOptional | Requires no assignment. | - | No assignment required | - | No assignment required | - |
Example
The following sample code is for reference only. For details about compilation and execution, see Compile and Run Samples.
#include <iostream>
#include <vector>
#include "acl/acl.h"
#include "aclnnop/aclnn_mla_prolog.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 the aclCreateTensor API to create an aclTensor.
*tensor = aclCreateTensor(shape.data(), shape.size(), dataType, nullptr, 0, aclFormat::ACL_FORMAT_ND,
shape.data(), shape.size(), *deviceAddr);
// Call aclrtMemcpy to copy host-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 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 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) {
int64_t inputParam1 = shapeND[0];
int64_t inputParam2 = shapeND[1];
int64_t h0 = 16;
int64_t newParam1 = inputParam2 / h0;
int64_t newParam2 = inputParam1 / h0;
shapeND[0] = newParam1;
shapeND[1] = newParam2;
shapeND.emplace_back(h0);
shapeND.emplace_back(h0);
return 0;
}
int main() {
// 1. Boilerplate for device/stream initialization. See the AscendCL external 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 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, 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> queryShape = {8, 1, 32, 512}; // B,S,N,Hckv
std::vector<int64_t> queryRopeShape = {8, 1, 32, 64}; // B,S,N,Dr
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* queryDeviceAddr = nullptr;
void* queryRopeDeviceAddr = 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* queryHostAddr = nullptr;
void* queryRopeHostAddr = 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* query = nullptr;
aclTensor* queryRope = nullptr;
// Convert the shapes of the three NZ-format variables.
ret = TransToNZShape(weightDqShape);
CHECK_RET(ret == 0, LOG_PRINT("trans NZ shape failed.\n"); return ret);
ret = TransToNZShape(weightUqQrShape);
CHECK_RET(ret == 0, LOG_PRINT("trans NZ shape failed.\n"); return ret);
ret = TransToNZShape(weightDkvKrShape);
CHECK_RET(ret == 0, LOG_PRINT("trans NZ shape failed.\n"); return ret);
// Create the tokenX aclTensor.
ret = CreateAclTensorND(tokenXShape, &tokenXDeviceAddr, &tokenXHostAddr, aclDataType::ACL_BF16, &tokenX);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// Create the weightDq aclTensor.
ret = CreateAclTensorNZ(weightDqShape, &weightDqDeviceAddr, &weightDqHostAddr, aclDataType::ACL_BF16, &weightDq);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// Create the weightUqQr aclTensor.
ret = CreateAclTensorNZ(weightUqQrShape, &weightUqQrDeviceAddr, &weightUqQrHostAddr, aclDataType::ACL_BF16, &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_BF16, &weightDkvKr);
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 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 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_BF16, &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 query aclTensor.
ret = CreateAclTensorND(queryShape, &queryDeviceAddr, &queryHostAddr, aclDataType::ACL_BF16, &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);
// 3. Call a CANN operator library API. Replace it with the actual API.
uint64_t workspaceSize = 0;
aclOpExecutor* executor = nullptr;
// Call the first-phase API of aclnnMlaProlog.
ret = aclnnMlaPrologGetWorkspaceSize(tokenX, weightDq, weightUqQr, weightUk, weightDkvKr, rmsnormGammaCq, rmsnormGammaCkv, ropeSin, ropeCos, cacheIndex, kvCache, krCache, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, rmsnormEpsilonCq, rmsnormEpsilonCkv, cacheMode, query, queryRope, &workspaceSize, &executor);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnMlaPrologGetWorkspaceSize failed. ERROR: %d\n", ret); return ret);
// Allocate device memory based on the workspaceSize computed by the first-phase API.
void* workspaceAddr = nullptr;
if (workspaceSize > 0) {
ret = aclrtMalloc(&workspaceAddr, workspaceSize, ACL_MEM_MALLOC_HUGE_FIRST);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("allocate workspace failed. ERROR: %d\n", ret); return ret;);
}
// Call the second-phase API of aclnnMlaProlog.
ret = aclnnMlaProlog(workspaceAddr, workspaceSize, executor, stream);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnMlaProlog failed. ERROR: %d\n", ret); return ret);
// 4. Boilerplate. Wait synchronously for the task execution to complete.
ret = aclrtSynchronizeStream(stream);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtSynchronizeStream failed. ERROR: %d\n", ret); return ret);
// 5. Obtain the output values, copy the result on the device memory to the host, and modify the code based on the actual 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, and modify the code based on the actual 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(query);
aclDestroyTensor(queryRope);
// 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(queryDeviceAddr);
aclrtFree(queryRopeDeviceAddr);
// 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(queryHostAddr);
aclrtFree(queryRopeHostAddr);
if (workspaceSize > 0) {
aclrtFree(workspaceAddr);
}
aclrtDestroyStream(stream);
aclrtResetDevice(deviceId);
aclFinalize();
return 0;
}