aclnnDenseLightningIndexerGradKLLoss
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
Description: The DenseLightningIndexerGradKlLoss operator is the backward operator of LightningIndexer and additionally integrates loss computation. The LightningIndexer operator selects the TopK items with the highest intrinsic relevance between QueryToken and KeyToken, reducing the Attention computation in long-sequence use cases and improving the inference and training performance of long-sequence networks. In the dense use case, the query, key, query_index, and key_index inputs of LightningIndexerGrad do not need to be sparsified.
Formula:
Formula for calculating the Top-k value:
$$ I_{t,:}=W_{t,:}@ReLU(\tilde{q}_{t,:}@\tilde{K}_{:t,:}^\top) $$- $W_{t,:}$ is the $weights$ corresponding to the $t$-th token;
- $\tilde{q}_{t,:}$ is the result of merging the $G$ query heads corresponding to the $t$-th token in the $\tilde{q}$ matrix;
- $\tilde{K}_{:t,:}$ is the $\tilde{K}$ matrix with $t$ rows.
Formula for the forward Softmax:
$$ p_{t,:} = \text{Softmax}(q_{t,:} @ K_{:t,:}^\top/\sqrt{d}) $$- $p_{t,:}$ is the Softmax result corresponding to the $t$-th token;
- $q_{t,:}$ is the result of merging the $G$ query heads corresponding to the $t$-th token in the $q$ matrix;
- ${K}_{:t,:}$ is the $K$ matrix with $t$ rows.
npu_lightning_indexer is trained separately, and the corresponding loss function is:
$$ Loss{=}\sum_tD_{KL}(p_{t,:}||Softmax(I_{t,:})) $$where $p_{t,:}$ is the target distribution, obtained by summing the main attention score over all heads and then applying L1 normalization to the sum along the context direction. $D_{KL}$ denotes the KL divergence, expressed as:
$$ D_{KL}(a||b){=}\sum_ia_i\mathrm{log}{\left(\frac{a_i}{b_i}\right)} $$The gradient expression of the loss can be obtained by deduction:
$$ dI\mathop{{}}\nolimits_{{t,:}}=Softmax \left( I\mathop{{}}\nolimits_{{t,:}} \left) -p\mathop{{}}\nolimits_{{t,:}}\right. \right. $$The gradients of the weights, query, and key matrices can be computed using the chain rule:
$$ dW\mathop{{}}\nolimits_{{t,:}}=dI\mathop{{}}\nolimits_{{t,:}}\text{@} \left( ReLU \left( S\mathop{{}}\nolimits_{{t,:}} \left) \left) \mathop{{}}\nolimits^{\top}\right. \right. \right. \right. $$$$ d\mathop{{\tilde{q}}}\nolimits_{{t,:}}=dS\mathop{{}}\nolimits_{{t,:}}@\tilde{K}\mathop{{}}\nolimits_{{:t,:}} $$$$ d\tilde{K}\mathop{{}}\nolimits_{{:t,:}}=\left(dS\mathop{{}}\nolimits_{{t,:}} \left) \mathop{{}}\nolimits^{\top}@\tilde{q}\mathop{{}}\nolimits_{{:t, :}}\right. \right. $$where $S$ is the result of the matrix multiplication between $\tilde{q}$ and $K$.
Function Prototype
The operator execution API is a two-phase API. First call the "aclnnDenseLightningIndexerGradKLLossGetWorkspaceSize" API to obtain the input parameters and calculate the required workspace size based on the computation process. Then call the "aclnnDenseLightningIndexerGradKLLoss" API to execute the computation.
aclnnStatus aclnnDenseLightningIndexerGradKLLossGetWorkspaceSize(
const aclTensor *query,
const aclTensor *key,
const aclTensor *queryIndex,
const aclTensor *keyIndex,
const aclTensor *weights,
const aclTensor *softmaxMax,
const aclTensor *softmaxSum,
const aclTensor *softmaxMaxIndex,
const aclTensor *softmaxSumIndex,
const aclTensor *queryRope,
const aclTensor *keyRope,
const aclIntArray *actualSeqLengthsQuery,
const aclIntArray *actualSeqLengthsKey,
double scaleValue,
char *layout,
int64_t sparseMode,
int64_t preTokens,
int64_t nextTokens,
const aclTensor *dQueryIndex,
const aclTensor *dKeyIndex,
const aclTensor *dWeights,
const aclTensor *loss,
uint64_t *workspaceSize,
aclOpExecutor **executor)aclnnStatus aclnnDenseLightningIndexerGradKLLoss(
void *workspace,
uint64_t workspaceSize,
aclOpExecutor *executor,
aclrtStream stream)aclnnDenseLightningIndexerGradKLLossGetWorkspaceSize
Parameters:
Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor query (aclTensor*) Input Input Q of the attention structure. - B: support generalization.
- S1: support generalization.
- N1: 128, 64, 32.
- D: 128.
- T1: accumulated S1 across multiple batches.
FLOAT16, BFLOAT16 ND (B,S1,N1,D);(T1,N1,D) × key (aclTensor*) Input Input K of the attention structure. - B: Supports generalization and keeps consistent with the B of query.
- S2: Supports generalization.
- N2: Equals N1.
- D: 128.
- T2: Accumulates S2 across multiple batches.
FLOAT16, BFLOAT16 ND (B,S2,N2,D);(T2,N2,D) × queryIndex (aclTensor*) Input Input queryIndex of the lightningIndexer structure. - B: Supports generalization and keeps consistent with the B of query.
- S1: Supports generalization.
- Nidx1: 64, 32, 16, 8.
- D: 128.
- T1: Accumulates S1 across multiple batches.
FLOAT16, BFLOAT16 ND (B,S1,Nidx1,D);(T1,Nidx1,D) × keyIndex(aclTensor*) Input Input keyIndex of the lightningIndexer structure. - B: Support generalization and keep consistent with B of query.
- S2: Support generalization.
- Nidx2: 1.
- D: 128.
- T2: Accumulation of S2 across multiple batches.
FLOAT16, BFLOAT16 ND (B,S2,Nidx2,D);(T2,Nidx2,D) × weights(aclTensor*) Input Weights. - B: Supports generalization and keeps consistent with the B of query.
- S1: Supports generalization and keeps consistent with the S1 of query.
- Nidx1: 64, 32, 16, 8.
- T1: Accumulation of S1 of multiple batches.
FLOAT16, BFLOAT16, FLOAT32 ND (B,S1,Nidx1);(T1,Nidx1) × softmaxMax(aclTensor*) Input aclTensor on the Device side, the intermediate output of the attention forward computation. - B: supports generalization and keeps consistent with the B of query.
- N2: equals N1.
- S1: supports generalization and keeps consistent with the S1 of query.
- G: N1/N2.
- T1: S1 accumulated across multiple batches.
FLOAT32 ND (B,N2,S1,G);(N2,T1,G) × softmaxSum(aclTensor*) Input aclTensor on the Device side, the intermediate output of the attention forward computation. - B: Support generalization and keep consistent with the B of query.
- N2: Equal to N1.
- S1: Support generalization and keep consistent with the S1 of query.
- G: N1/N2.
- T1: Accumulated S1 across multiple batches.
FLOAT32 ND (B,N2,S1,G);(N2,T1,G) × softmaxMaxIndex(aclTensor*) Input aclTensor on the Device side. Intermediate output of the forward attention computation. - B: Support generalization and keep consistent with the B of query.
- Nidx2: 1.
- S1: Support generalization and keep consistent with the S1 of query.
- T1: Accumulated S1 across multiple batches.
FLOAT32 ND (B,Nidx2,S1);(Nidx2,T1) × softmaxSumIndex(aclTensor*) Input aclTensor on the Device side. Intermediate output of the attention forward computation. - B: Supports generalization and keeps consistent with the B of query.
- Nidx2: 1.
- S1: Supports generalization and keeps consistent with the S1 of query.
- T1: Accumulated S1 of multiple batches.
FLOAT32 ND (B,Nidx2,S1);(Nidx2,T1) √ queryRope (aclTensor*) Input MLA rope part: Query positional encoding output. - Keep consistent with the layout dimensions of query.
- B: Supports generalization and keeps consistent with the B of query.
- S1: Supports generalization and keeps consistent with the S1 of query.
- N1: 128, 64, 32.
- Dr: 64.
- T1: Accumulated S1 across multiple batches.
FLOAT16, BFLOAT16 ND (B,S1,N1,Dr);(T1,N1,Dr) √ keyRope (aclTensor*) Input MLA rope part: output of Key position encoding. - Keep consistent with the layout dimensions of key.
- B: supports generalization and keeps consistent with the B of query.
- S2: supports generalization and keeps consistent with the S1 of key.
- N2: equals N1.
- Dr: 64.
- T2: accumulated S2 across multiple batches.
FLOAT16, BFLOAT16 ND (B,S2,N2,Dr);(T2,N2,Dr) √ actualSeqLengthsQuery (aclIntArray*) Input Number of valid Query tokens in each batch. - Value dependency.
- The length is consistent with B.
- The accumulated sum is consistent with T1.
INT64 ND (B,) - actualSeqLengthsKey(aclIntArray*) Input Number of valid Key tokens in each Batch. - Value dependency.
- The length is consistent with B.
- The accumulated sum is consistent with T2.
INT64 ND (B,) - scaleValue (double) Input Scaling factor. - Recommended value: the reciprocal of the square root of d in the formula.
- - - - layout (char*) Input Layout format. Only BSND and TND formats are supported. - - - - sparseMode (int64_t) Input Sparse mode - Represents the sparse mode. For details about different sparse modes, see Constraints.
- Only mode 3 is supported.
- - - - preTokens (int64_t) Input Used for sparse computation. Indicates that Attention is computed with the preceding several tokens. Same as the definition of preTokens in Attention. It takes effect when sparseMode = 0 or 4. Defaults to 2147483647. - - - - nextTokens (int64_t) Input Used for sparse computation. Indicates the number of subsequent tokens that Attention needs to compute correlation with. Same as the definition of nextTokens in Attention. It takes effect when sparseMode = 0 or 4. Defaults to 2147483647. - - - - dQueryIndex (aclTensor*) Output Gradient of QueryIndex. - B: Support Generalization. Keep consistent with B of query.
- S1: Support Generalization. Keep consistent with S1 of query.
- Nidx1: 64, 32, 16, 8.
- D: 128.
- T1: Accumulated S1 of multiple batches.
FLOAT16, BFLOAT16 ND (B,S1,Nidx1,D);(T1,Nidx1,D) √ dKeyIndex (aclTensor*) Output Gradient of KeyIndex. - B: Support Generalization. Keep consistent with B of query.
- S2: Support Generalization. Keep consistent with S2 of key.
- Nidx2: 1.
- D: 128.
- T2: Accumulate S2 of multiple batches.
FLOAT16, BFLOAT16 ND (B,S2,Nidx2,D);(T2,Nidx2,D) √ dWeights (aclTensor*) Output Gradient of Weights. - B: Support Generalization.
- S1: Support Generalization. Cannot be the M dimension of Matmul.
- Nidx1: 64, 32, 16, 8.
- T1: Accumulation of S1 across multiple batches.
FLOAT16, BFLOAT16, FLOAT32 ND (B,S1,Nidx1);(T1,Nidx1) √ loss (aclTensor*) Output Loss function value. - FLOAT32 ND (1,) - workspaceSize (uint64_t*) Output Returns the workspace size to be allocated on the Device side. - - - - - executor (aclOpExecutor**) Output Returns the op executor, which contains the operator computation flow. - - - - - 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 required parameter or the output is a null pointer. ACLNN_ERR_PARAM_INVALID 161002 The data types or data formats of input variables such as query, key, queryIndex, keyIndex, weights, and softmaxMax are not within the supported range. ACLNN_ERR_INNER_TILING_ERROR 561002 The shapes of multiple input tensors do not match (see Parameters for details).
aclnnDenseLightningIndexerGradKLLoss
Parameters:
Parameter Input/Output Description workspace Input Workspace memory address allocated on the Device side. workspaceSize Input Workspace size allocated on the Device side. Obtained by the first-phase API aclnnDenseLightningIndexerGradKLLossGetWorkspaceSize. executor Input Op executor that contains the operator computation flow. stream Input Stream for task execution. Return value
Returns an aclnnStatus status code. For details, see aclnnReturnCode.
Constraints
The data types of query, key, queryIndex, and keyIndex must be the same.
If weights is not float32, the data types of query, key, queryIndex, keyIndex, and weights must be the same.
General Constraints
- Deterministic computation: aclnnDenseLightningIndexerGradKLLoss defaults to a non-deterministic implementation, and supports enabling deterministic computation through alcrtCtxSetSysParamOpt.
- Handling of empty input parameters:
- If query, key, query_index, key_index, or weight is an empty tensor: currently not supported, and an error is reported.
sparseMode Meaning Note 0 defaultMask mode. If attenmask is not passed in, no mask operation is performed, and preTokens and nextTokens are ignored. If attenmask is passed in, the complete attenmask matrix must be passed in, indicating that the part between preTokens and nextTokens requires calculation. Not Supported 1 allMask. The complete attenmask matrix must be passed in. Not Supported 2 leftUpCausal mode mask. The optimized attenmask matrix must be passed in. Not Supported 3 Mask in rightDownCausal mode, corresponding to the lower-triangle use case partitioned by the right vertex. The optimized attenmask matrix must be passed in. Supported 4 Mask in band mode. The optimized attenmask matrix must be passed in. Not Supported 5 prefix Not Supported 6 global Not supported 7 dilated Not supported 8 block_local Not supported Specification constraints
Specification Item Specification Specification B 1-256 - S1, S2 1-1M S1 and S2 support unequal lengths. N1 32, 64, 128 - Nidx1 8, 16, 32, 64 - N2 32, 64, 128 - Nidx2 1 - D 128 The D of query and query_index is the same. Drope 64 - layout BSND/TND - Typical values
Item Typical Value query N1=128/64/32; D=128 queryIndex Nidx1 = 64/32/16/8; D = 128 ; S1 = 64k/128k keyIndex D = 128 qRope D = 64
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 <cstdint>
#include <cmath>
#include "acl/acl.h"
#include "aclnnop/aclnn_dense_lightning_indexer_grad_kl_loss.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 shapeSize = 1;
for (auto i : shape) {
shapeSize *= i;
}
return shapeSize;
}
void PrintOutResult(std::vector<int64_t> &shape, void** deviceAddr) {
auto size = GetShapeSize(shape);
std::vector<aclFloat16> resultData(size, 0);
auto ret = aclrtMemcpy(resultData.data(), resultData.size() * sizeof(resultData[0]),
*deviceAddr, size * sizeof(resultData[0]), ACL_MEMCPY_DEVICE_TO_HOST);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("copy result from device to host failed. ERROR: %d\n", ret); return);
for (int64_t i = 0; i < size; i++) {
LOG_PRINT("mean result[%ld] is: %f\n", i, aclFloat16ToFloat(resultData[i]));
}
}
int Init(int32_t deviceId, aclrtContext* context, aclrtStream* stream) {
// Boilerplate: AscendCL 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 = aclrtCreateContext(context, deviceId);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtCreateContext failed. ERROR: %d\n", ret); return ret);
ret = aclrtSetCurrentContext(*context);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtSetCurrentContext failed. ERROR: %d\n", ret); return ret);
ret = aclrtCreateStream(stream);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtCreateStream failed. ERROR: %d\n", ret); return ret);
return 0;
}
template <typename T>
int CreateAclTensor(const std::vector<T>& hostData, const std::vector<int64_t>& shape, void** deviceAddr,
aclDataType dataType, aclTensor** tensor) {
auto size = GetShapeSize(shape) * sizeof(T);
// Call aclrtMalloc to allocate memory on the device side.
auto ret = aclrtMalloc(deviceAddr, size, ACL_MEM_MALLOC_HUGE_FIRST);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtMalloc failed. ERROR: %d\n", ret); return ret);
// Call aclrtMemcpy to copy host-side data to device-side memory.
ret = aclrtMemcpy(*deviceAddr, size, hostData.data(), size, ACL_MEMCPY_HOST_TO_DEVICE);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtMemcpy failed. ERROR: %d\n", ret); return ret);
// Compute the strides of the contiguous tensor.
std::vector<int64_t> strides(shape.size(), 1);
for (int64_t i = shape.size() - 2; i >= 0; i--) {
strides[i] = shape[i + 1] * strides[i + 1];
}
// Call the aclCreateTensor API to create an aclTensor.
*tensor = aclCreateTensor(shape.data(), shape.size(), dataType, strides.data(), 0, aclFormat::ACL_FORMAT_ND,
shape.data(), shape.size(), *deviceAddr);
return 0;
}
int main() {
// 1. (Boilerplate) Initialize the device/context/stream. For details, see the list of AscendCL external APIs.
// Set deviceId based on the actual device.
int32_t deviceId = 0;
aclrtContext context;
aclrtStream stream;
auto ret = Init(deviceId, &context, &stream);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("Init acl failed. ERROR: %d\n", ret); return ret);
// 2. Construct the input and output. Customize the construction according to the API.
int64_t s1 = 1;
int64_t s2 = 1;
int64_t n1 = 32;
int64_t n2 = n1;
int64_t n1Index = 8;
int64_t n2Index = 1;
int64_t dQuery = 128;
int64_t dRope = 64;
int64_t dQueryIndex = 128;
int64_t t1 = s1;
int64_t t2 = s2;
int64_t G = n1 / n2;
std::vector<int64_t> qShape = {t1, n1, dQuery};
std::vector<int64_t> kShape = {t2, n2, dQuery};
std::vector<int64_t> qRopeShape = {t1, n1, dRope};
std::vector<int64_t> kRopeShape = {t2, n2, dRope};
std::vector<int64_t> qIndexShape = {t1, n1Index, dQueryIndex};
std::vector<int64_t> kIndexShape = {t2, n2Index, dQueryIndex};
std::vector<int64_t> weightShape = {t1, n1Index};
std::vector<int64_t> softmaxMaxShape = {n2, t1, G};
std::vector<int64_t> softmaxSumShape = {n2, t1, G};
std::vector<int64_t> softmaxMaxIndexShape = {n2Index, t1};
std::vector<int64_t> softmaxSumIndexShape = {n2Index, t1};
std::vector<int64_t> dQIndexShape = {t1, n1Index, dQueryIndex};
std::vector<int64_t> dKIndexShape = {t2, n2Index, dQueryIndex};
std::vector<int64_t> dWeightShape = {t1, n1Index};
std::vector<int64_t> lossShape = {1};
void* qDeviceAddr = nullptr;
void* kDeviceAddr = nullptr;
void* qRopeDeviceAddr = nullptr;
void* kRopeDeviceAddr = nullptr;
void* qIndexDeviceAddr = nullptr;
void* kIndexDeviceAddr = nullptr;
void* weightDeviceAddr = nullptr;
void* softmaxMaxDeviceAddr = nullptr;
void* softmaxSumDeviceAddr = nullptr;
void* softmaxMaxIndexDeviceAddr = nullptr;
void* softmaxSumIndexDeviceAddr = nullptr;
void* dQIndexDeviceAddr = nullptr;
void* dKIndexDeviceAddr = nullptr;
void* dWeightDeviceAddr = nullptr;
void* lossDeviceAddr = nullptr;
aclTensor* q = nullptr;
aclTensor* k = nullptr;
aclTensor* qRope = nullptr;
aclTensor* kRope = nullptr;
aclTensor* qIndex = nullptr;
aclTensor* kIndex = nullptr;
aclTensor* weight = nullptr;
aclTensor* softmaxMax = nullptr;
aclTensor* softmaxSum = nullptr;
aclTensor* softmaxMaxIndex = nullptr;
aclTensor* softmaxSumIndex = nullptr;
aclTensor* dQIndex = nullptr;
aclTensor* dKIndex = nullptr;
aclTensor* dWeight = nullptr;
aclTensor* loss = nullptr;
std::vector<aclFloat16> qHostData(t1 * n1 * dQuery, aclFloatToFloat16(0.1));
std::vector<aclFloat16> kHostData(t2 * n2 * dQuery, aclFloatToFloat16(0.2));
std::vector<aclFloat16> qRopeHostData(t1 * n1 * dRope, aclFloatToFloat16(0.1));
std::vector<aclFloat16> kRopeHostData(t2 * n2 * dRope, aclFloatToFloat16(0.2));
std::vector<aclFloat16> qIndexHostData(t1 * n1Index * dQueryIndex, aclFloatToFloat16(0.2));
std::vector<aclFloat16> kIndexHostData(t2 * n2Index * dQueryIndex, aclFloatToFloat16(0.1));
std::vector<aclFloat16> weightHostData(t1 * n1Index, aclFloatToFloat16(0.005));
std::vector<float> softmaxMaxHostData(t1 * n2, 25.4483f);
std::vector<float> softmaxSumHostData(t1 * n2, 1.0f);
std::vector<float> softmaxMaxIndexHostData(t1 * n2Index, 25.4483f);
std::vector<float> softmaxSumIndexHostData(t1 * n2Index, 1.0f);
std::vector<aclFloat16> dQIndexHostData(t1 * n1Index * dQueryIndex);
std::vector<aclFloat16> dKIndexHostData(t2 * n2Index * dQueryIndex);
std::vector<aclFloat16> dWeightHostData(t1 * n1Index);
std::vector<float> lossHostData(1, 1.0f);
ret = CreateAclTensor(qHostData, qShape, &qDeviceAddr, aclDataType::ACL_FLOAT16, &q);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(kHostData, kShape, &kDeviceAddr, aclDataType::ACL_FLOAT16, &k);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(qRopeHostData, qRopeShape, &qRopeDeviceAddr, aclDataType::ACL_FLOAT16, &qRope);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(kRopeHostData, kRopeShape, &kRopeDeviceAddr, aclDataType::ACL_FLOAT16, &kRope);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(qIndexHostData, qIndexShape, &qIndexDeviceAddr, aclDataType::ACL_FLOAT16, &qIndex);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(kIndexHostData, kIndexShape, &kIndexDeviceAddr, aclDataType::ACL_FLOAT16, &kIndex);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(weightHostData, weightShape, &weightDeviceAddr, aclDataType::ACL_FLOAT16, &weight);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(softmaxMaxHostData, softmaxMaxShape, &softmaxMaxDeviceAddr, aclDataType::ACL_FLOAT, &softmaxMax);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(softmaxSumHostData, softmaxSumShape, &softmaxSumDeviceAddr, aclDataType::ACL_FLOAT, &softmaxSum);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(softmaxMaxIndexHostData, softmaxMaxIndexShape, &softmaxMaxIndexDeviceAddr, aclDataType::ACL_FLOAT, &softmaxMaxIndex);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(softmaxSumIndexHostData, softmaxSumIndexShape, &softmaxSumIndexDeviceAddr, aclDataType::ACL_FLOAT, &softmaxSumIndex);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(dQIndexHostData, dQIndexShape, &dQIndexDeviceAddr, aclDataType::ACL_FLOAT16, &dQIndex);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(dKIndexHostData, dKIndexShape, &dKIndexDeviceAddr, aclDataType::ACL_FLOAT16, &dKIndex);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(dWeightHostData, dWeightShape, &dWeightDeviceAddr, aclDataType::ACL_FLOAT16, &dWeight);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(lossHostData, lossShape, &lossDeviceAddr, aclDataType::ACL_FLOAT, &loss);
CHECK_RET(ret == ACL_SUCCESS, return ret);
std::vector<int64_t> acSeqQLenOp = {t1};
std::vector<int64_t> acSeqKvLenOp = {t2};
aclIntArray* acSeqQLen = aclCreateIntArray(acSeqQLenOp.data(), acSeqQLenOp.size());
aclIntArray* acSeqKvLen = aclCreateIntArray(acSeqKvLenOp.data(), acSeqKvLenOp.size());
float scaleValue = 1.0 / sqrt(dQuery);
int64_t preTokens = 2147483647;
int64_t nextTokens = 2147483647;
int64_t sparseMode = 3;
bool deterministic = false;
char layout[5] = {'T', 'N', 'D', 0};
// 3. Call the CANN operator library API. Replace it with the specific API name.
uint64_t workspaceSize = 0;
aclOpExecutor* executor;
// Call the first-phase API aclnnDenseLightningIndexerGradKLLossGetWorkspaceSize.
ret = aclnnDenseLightningIndexerGradKLLossGetWorkspaceSize(
q, k, qIndex, kIndex, weight, softmaxMax, softmaxSum, softmaxMaxIndex, softmaxSumIndex, qRope, kRope,
acSeqQLen, acSeqKvLen, scaleValue, layout, sparseMode, preTokens, nextTokens, dQIndex, dKIndex, dWeight, loss,
&workspaceSize, &executor);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnDenseLightningIndexerGradKLLossGetWorkspaceSize 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 aclnnDenseLightningIndexerGradKLLoss
ret = aclnnDenseLightningIndexerGradKLLoss(workspaceAddr, workspaceSize, executor, stream);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnDenseLightningIndexerGradKLLoss failed. ERROR: %d\n", ret); return ret);
// 4. (boilerplate) Synchronize and wait for task execution to finish.
ret = aclrtSynchronizeStream(stream);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtSynchronizeStream failed. ERROR: %d\n", ret); return ret);
// 5. Obtain the output value and copy the result from the Device side to the Host side. Modify the code based on the specific API definition.
PrintOutResult(dQIndexShape, &dQIndexDeviceAddr);
PrintOutResult(dKIndexShape, &dKIndexDeviceAddr);
PrintOutResult(dWeightShape, &dWeightDeviceAddr);
PrintOutResult(lossShape, &lossDeviceAddr);
// 6. Release aclTensor and aclScalar. Modify the code based on the specific API definition.
aclDestroyTensor(q);
aclDestroyTensor(k);
aclDestroyTensor(qIndex);
aclDestroyTensor(kIndex);
aclDestroyTensor(qRope);
aclDestroyTensor(kRope);
aclDestroyTensor(weight);
aclDestroyTensor(softmaxMax);
aclDestroyTensor(softmaxSum);
aclDestroyTensor(softmaxMaxIndex);
aclDestroyTensor(softmaxSumIndex);
aclDestroyTensor(dQIndex);
aclDestroyTensor(dKIndex);
aclDestroyTensor(dWeight);
aclDestroyTensor(loss);
// 7. Release Device resources.
aclrtFree(qDeviceAddr);
aclrtFree(kDeviceAddr);
aclrtFree(qIndexDeviceAddr);
aclrtFree(kIndexDeviceAddr);
aclrtFree(qRopeDeviceAddr);
aclrtFree(kRopeDeviceAddr);
aclrtFree(weightDeviceAddr);
aclrtFree(softmaxMaxDeviceAddr);
aclrtFree(softmaxSumDeviceAddr);
aclrtFree(softmaxMaxIndexDeviceAddr);
aclrtFree(softmaxSumIndexDeviceAddr);
aclrtFree(dQIndexDeviceAddr);
aclrtFree(dKIndexDeviceAddr);
aclrtFree(dWeightDeviceAddr);
aclrtFree(lossDeviceAddr);
if (workspaceSize > 0) {
aclrtFree(workspaceAddr);
}
aclrtDestroyStream(stream);
aclrtDestroyContext(context);
aclrtResetDevice(deviceId);
aclFinalize();
return 0;
}