aclnnSparseLightningIndexerGradKLLossV2
Applicable Products
Ascend 950PR&950DT products : Supported
Atlas A3 products : Not supported
Atlas A2 products : Not supported
Atlas 200I/500 A2 inference products : Not supported
Atlas inference products : Not supported
Atlas training products : Not supported
Function
Description: The SparselightningIndexerGradKlLoss operator is the backward operator of LightningIndexer, with an additional fused loss computation function. The LightningIndexer operator selects the TopK highest intrinsic connections between QueryToken and KeyToken and stores them in SparseIndices, thereby reducing the computation workload of Attention in long-sequence scenarios and accelerating the inference and training performance of long-sequence networks.
aclnnSparseLightningIndexerGradKLLossV2 adds the sinks parameter on top of aclnnSparseLightningIndexerGradKLLoss. sinks is used to correct the normalization factor of the target distribution (p). This API is supported only on Ascend 950PR&950DT products.
Formula: The formula for computing the value used to obtain Top-k can be expressed as:
$$ I_{t,:}=W_{t,:}@ReLU(q_{t,:}@(K_{:t,:})^T) $$Where $W$ is the weights corresponding to the $t$-th token, $q$ is the matrix formed by concatenating the $G$ query heads corresponding to the $t$-th token, and $K$ is a matrix with $t$ rows.
LightningIndexer is trained separately, and its corresponding loss function is:
$$ L(I){=}\sum_tD_{KL}(p_{t,:}||Softmax(I_{t,:})) $$where $p$ is the target distribution, which is obtained by summing the main attention score over all heads and then performing L1 normalization on the sum along the context dimension. $D_{KL}$ is 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^{{T}}\right. \right. \right. \right. $$$$ d\mathop{{q}}\nolimits_{{t,:}}=dS\mathop{{}}\nolimits_{{t,:}}@K\mathop{{}}\nolimits_{{:t,:}} $$$$ dK\mathop{{}}\nolimits_{{:t,:}}= \left( dS\mathop{{}}\nolimits_{{t,:}} \left) \mathop{{}}\nolimits^{{T}}@q\mathop{{}}\nolimits_{{:t,:}}\right. \right. $$Where S is the result of softmax on the QK matrix.
Function Prototype
Each operator uses a two-phase API. First, call the "aclnnSparseLightningIndexerGradKLLossV2GetWorkspaceSize" API to obtain the input parameters and calculate the required workspace size based on the computation flow. Then, call the "aclnnSparseLightningIndexerGradKLLossV2" API to perform the computation.
aclnnStatus aclnnSparseLightningIndexerGradKLLossV2GetWorkspaceSize(
const aclTensor *query,
const aclTensor *key,
const aclTensor *queryIndex,
const aclTensor *keyIndex,
const aclTensor *weights,
const aclTensor *sparseIndices,
const aclTensor *softmaxMax,
const aclTensor *softmaxSum,
const aclTensor *queryRope,
const aclTensor *keyRope,
const aclIntArray *actualSeqLengthsQuery,
const aclIntArray *actualSeqLengthsKey,
const aclTensor *sinks,
double scaleValue,
char *layout,
int64_t sparseMode,
int64_t preTokens,
int64_t nextTokens,
bool deterministic,
const aclTensor *dQueryIndex,
const aclTensor *dKeyIndex,
const aclTensor *dWeights,
const aclTensor *loss,
uint64_t *workspaceSize,
aclOpExecutor **executor)aclnnStatus aclnnSparseLightningIndexerGradKLLoss(
void *workspace,
uint64_t workspaceSize,
aclOpExecutor *executor,
aclrtStream stream)aclnnSparseLightningIndexerGradKLLossV2GetWorkspaceSize
Parameters:
Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor query Input Input Q of the attention structure. - The data type must be kept consistent with that of key/queryIndex/keyIndex.
- Does not support empty tensors.
FLOAT16, BFLOAT16 ND (B,S1,N1,DQuery), (T1,N1,DQuery) √ key Input Input K of the attention structure. - The data type is kept consistent with query/queryIndex/keyIndex.
- Does not support empty tensors.
FLOAT16, BFLOAT16 ND (B,S2,N2,DQuery), (T2,N2,DQuery) √ queryIndex Input Input queryIndex of the lightningIndexer structure. - The data type is kept consistent with query/key/keyIndex.
- Does not support empty tensors.
FLOAT16, BFLOAT16 ND (B,S1,Nidx1,DQueryIndex),(T1,Nidx1,DQueryIndex) √ keyIndex Input Input keyIndex of the lightningIndexer structure. - The data type must keep consistent with query/key/queryIndex.
- Does not support empty Tensor.
FLOAT16, BFLOAT16 ND (B,S2,Nidx2,DQueryIndex),(T2,Nidx2,DQueryIndex) √ weights Input Weight. Does not support empty tensors. FLOAT16, BFLOAT16, FLOAT32 ND (B,S1,Nidx1), (T1,Nidx1) √ sparseIndices Input topk_index, used to select the key and value corresponding to each query. Does Not Support Empty Tensor. INT32 ND (B,S1,Nidx2,K), (T1,Nidx2,K) √ softmaxMax Input Intermediate output of forward attention computation. Does not support empty tensors. FLOAT32 ND (B,N2,S1,G), (N2,T1,G) √ softmaxSum Input Intermediate output of the attention forward computation. Does not support empty tensors. FLOAT32 ND (B,N2,S1,G), (N2,T1,G) √ queryRope Input MLA rope part: output of Query positional encoding. - Keep consistent with the layout dimension of query.
- Does not support empty tensor.
FLOAT16, BFLOAT16 ND (B,S1,N1,DRope), (T1,N1,DRope) √ keyRope Input MLA rope part: output of Key position encoding. - Keep consistent with the layout dimension of key.
- Does not support empty tensor.
FLOAT16, BFLOAT16 ND (B,S2,N2,DRope), (T2,N2,DRope) √ actualSeqLengthsQuery Input Number of valid Query tokens in each Batch. - Value dependency.
- The length keeps consistent with B.
- The cumulative sum keeps consistent with T1.
- Does not support empty tensor.
INT64 ND (B,) √ actualSeqLengthsKey Input Number of valid Key tokens in each Batch. - Value-dependent.
- The length keeps consistent with B.
- The cumulative sum keeps consistent with T2.
- Does not support empty tensors.
INT64 ND (B,) √ scaleValue Input Scaling factor. Recommended value: the reciprocal of the square root of d in the formula. - - - - layout Input Layout format. Only BSND and TND formats are supported. STRING - - - sparseMode Input Sparse mode. - Indicates the sparse mode. For details about the different sparse modes, see Constraints.
- Only mode 3 is supported.
INT64 - - - preTokens Input Number of tokens retained by the left-side mask. - INT64 - - - nextTokens Input Number of tokens retained by the right-side mask. - INT64 - - - sinks Input Additional softmax term used to correct the normalization factor of the target distribution (p). - Must be 1-dimensional, and its length must equal the N dimension of query.
- This parameter is optional. If it is not passed in, the behavior is the same as that of the aclnnSparseLightningIndexerGradKLLoss API.
- Supported only by Ascend 950PR&950DT products.
FLOAT32 ND (N1,) √ deterministic Input Deterministic computation. Prioritizes the whole-network deterministic configuration. This parameter has no effect. BOOL - - - dQueryIndex Output Gradient of QueryIndex. - FLOAT16, BFLOAT16 ND (B,S1,Nidx1,DQueryIndex), (T1,Nidx1,DQueryIndex) x dKeyIndex Output Gradient of KeyIndex. - FLOAT16, BFLOAT16 ND (B,S2,Nidx2,DQueryIndex), (T2,Nidx2,DQueryIndex) x dWeights Output Gradient of Weights. - FLOAT16, BFLOAT16, FLOAT32 ND (B,S1,Nidx1), (T1,Nidx1) x loss Output Loss function value. - FLOAT32 ND (1,) x workspaceSize Output Returns the workspace size to be requested on the Device side. - - - - - executor Output Returns the op executor, which contains the operator computation process. - - - - - 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 Codes Description ACLNN_ERR_PARAM_NULLPTR 161001 A required parameter or output is a null pointer. ACLNN_ERR_PARAM_INVALID 161002 The data types and data formats of input variables such as query, key, queryIndex, keyIndex, weights, sparseIndices, and softmaxMax are out of the supported range. ACLNN_ERR_RUNTIME_ERROR 361001 An exception occurs when the API calls the NPU runtime memory interface.
aclnnSparseLightningIndexerGradKLLossV2
Parameters:
Parameter Input/Output Description workspace Input Workspace memory address allocated on the device. workspaceSize Input Size of the workspace allocated on the device, obtained by the first-phase API aclnnSparseLightningIndexerGradKLLossV2GetWorkspaceSize. executor Input Op executor that contains the operator computation flow. stream Input Specifies the Stream for task execution. Return value
aclnnStatus: return status code. For details, see aclnn Return Codes.
Constraints
Deterministic computation:
- aclnnSparseLightningIndexerGradKLLossV2 defaults to a non-deterministic implementation. Deterministic computation can be enabled through aclrtCtxSetSysParamOpt.
General 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.
- Handling of empty input parameters:
- query is an empty tensor: return directly.
- The scenario where the input is empty in the common constraints is consistent with FAG.
- sparseMode description:
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 needs to be computed. Not supported 1 allMask. The complete attenmask matrix must be passed in. Not supported 2 Mask of the leftUpCausal mode. The optimized attenmask matrix must be passed in. Not supported 3 Mask of rightDownCausal mode, corresponding to the lower triangle scenario divided by the right vertex. The optimized attenmask matrix must be passed in. Supported 4 Mask of 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
Item Specification Specifications B Supported: 1-256 - S1, S2 S1 supported: 1~32K, S2 supported: 1~1M S1 and S2 support different lengths; S1 must be less than or equal to S2 N1 32, 64, 128 SparseFA is MQA. Nidx1 8, 16, 32, 64 SparseFA is MQA. N2 1 SparseFA is MQA, Nidx2=1. Nidx2 1 SparseFA is MQA, N2=1. DQuery 512 - DQueryIndex 128 - DRope 64 - K 1024, 2048, 3072, 4096, 5120, 6144, 7168, 8192 -
<term>Ascend 950PR&950DT products</term>: N1 additionally supports 48, and Nidx1 additionally supports 24. Only the (48,24) combination is allowed between the two, and other pairings are prohibited; B, S1, and S2 support generalization.
Example
The sample code is as follows, for reference only. For details about the compilation and execution procedure, see Compile and Run Samples.
#include <iostream>
#include <vector>
#include "acl/acl.h"
#include "aclnnop/aclnn_sparse_lightning_indexer_grad_kl_loss_v2.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<float> 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, resultData[i]);
}
}
void PrintOutResultFp16(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 request 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 aclrtMemcpy to copy host-side data to the 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);
// Calculate the strides of contiguous tensors.
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 AscendCL public API list.
// Set deviceId based on the actual device.
int32_t deviceId = 3;
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. Custom construction is required based on the API definition.
std::vector<int64_t> qShape = {1,64,512};
std::vector<int64_t> kShape = {1,1,512};
std::vector<int64_t> qRopeShape = {1,64,64};
std::vector<int64_t> kRopeShape = {1,1,64};
std::vector<int64_t> qIndexShape = {1,32,128};
std::vector<int64_t> kIndexShape = {1,1,128};
std::vector<int64_t> weightShape = {1,32};
std::vector<int64_t> sparseIndicesShape = {1, 1,2048};
std::vector<int64_t> softmaxMaxShape = {1, 1, 64};
std::vector<int64_t> softmaxSumShape = {1, 1, 64};
std::vector<int64_t> dQIndexShape = {1,32,128};
std::vector<int64_t> dKIndexShape = {1,1,128};
std::vector<int64_t> dWeightShape = {1,32};
std::vector<int64_t> lossShape = {1};
// sinks is a 1D float tensor. The length must keep consistent with the N dimension of query. Only Ascend 950PR&950DT products support it.
std::vector<int64_t> sinksShape = {64};
void* qDeviceAddr = nullptr;
void* kDeviceAddr = nullptr;
void* qRopeDeviceAddr = nullptr;
void* kRopeDeviceAddr = nullptr;
void* qIndexDeviceAddr = nullptr;
void* kIndexDeviceAddr = nullptr;
void* weightDeviceAddr = nullptr;
void* sparseIndicesDeviceAddr = nullptr;
void* softmaxMaxDeviceAddr = nullptr;
void* softmaxSumDeviceAddr = nullptr;
void* sinksDeviceAddr = 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* sparseIndices = nullptr;
aclTensor* softmaxMax = nullptr;
aclTensor* softmaxSum = nullptr;
aclTensor* sinks = nullptr;
aclTensor* dQIndex = nullptr;
aclTensor* dKIndex = nullptr;
aclTensor* dWeight = nullptr;
aclTensor* loss = nullptr;
std::vector<float> qHostData(1 * 64 * 512, 1);
std::vector<float> kHostData(1 * 1 * 512, 1);
std::vector<float> qRopeHostData(1 * 64 * 64, 1);
std::vector<float> kRopeHostData(1 * 1 * 64, 1);
std::vector<float> qIndexHostData(1 * 32 * 128, 1);
std::vector<float> kIndexHostData(1 * 1 * 128, 1);
std::vector<float> weightHostData(1 * 32, 1);
std::vector<int32_t> sparseIndicesHostData(2048, 1);
std::vector<float> softmaxMaxHostData(1 * 64, 1);
std::vector<float> softmaxSumHostData(1 * 64, 1);
std::vector<float> sinksHostData(64, 1);
std::vector<float> dQIndexHostData(1 * 32 * 128, 1);
std::vector<float> dKIndexHostData(1 * 1 * 128, 1);
std::vector<float> dWeightHostData(1 * 32, 1);
std::vector<float> lossHostData(1, 1);
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(sparseIndicesHostData, sparseIndicesShape, &sparseIndicesDeviceAddr, aclDataType::ACL_INT32, &sparseIndices);
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(sinksHostData, sinksShape, &sinksDeviceAddr, aclDataType::ACL_FLOAT, &sinks);
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 = {1};
std::vector<int64_t> acSeqKvLenOp = {1};
aclIntArray* acSeqQLen = aclCreateIntArray(acSeqQLenOp.data(), acSeqQLenOp.size());
aclIntArray* acSeqKvLen = aclCreateIntArray(acSeqKvLenOp.data(), acSeqKvLenOp.size());
double scaleValue = 0.044194173824159216;
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. Change it to the specific API name.
uint64_t workspaceSize = 0;
aclOpExecutor* executor;
// Call the first-phase API aclnnSparseLightningIndexerGradKLLossV2GetWorkspaceSize.
ret = aclnnSparseLightningIndexerGradKLLossV2GetWorkspaceSize(
q, k, qIndex, kIndex, weight, sparseIndices, softmaxMax, softmaxSum, qRope, kRope, acSeqQLen, acSeqKvLen,
sinks, scaleValue, layOut, sparseMode, preTokens, nextTokens, deterministic, dQIndex, dKIndex, dWeight, loss,
&workspaceSize, &executor);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnSparseLightningIndexerGradKLLossV2GetWorkspaceSize 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 second-phase API aclnnSparseLightningIndexerGradKLLossV2.
ret = aclnnSparseLightningIndexerGradKLLossV2(workspaceAddr, workspaceSize, executor, stream);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnSparseLightningIndexerGradKLLossV2 failed. ERROR: %d\n", ret); return ret);
// 4. (boilerplate) Synchronize and wait for the task execution to complete.
ret = aclrtSynchronizeStream(stream);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtSynchronizeStream failed. ERROR: %d\n", ret); return ret);
// 5. Obtain the output values. Copy the result from device memory to the host. Modify it based on the specific API definition.
PrintOutResultFp16(dQIndexShape, &dQIndexDeviceAddr);
PrintOutResultFp16(dKIndexShape, &dKIndexDeviceAddr);
PrintOutResultFp16(dWeightShape, &dWeightDeviceAddr);
PrintOutResult(lossShape, &lossDeviceAddr);
// 6. Release aclTensor and aclScalar. Modify it based on the specific API definition.
aclDestroyTensor(q);
aclDestroyTensor(k);
aclDestroyTensor(qIndex);
aclDestroyTensor(kIndex);
aclDestroyTensor(qRope);
aclDestroyTensor(kRope);
aclDestroyTensor(weight);
aclDestroyTensor(sparseIndices);
aclDestroyTensor(softmaxMax);
aclDestroyTensor(softmaxSum);
aclDestroyTensor(sinks);
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(sparseIndicesDeviceAddr);
aclrtFree(softmaxMaxDeviceAddr);
aclrtFree(softmaxSumDeviceAddr);
aclrtFree(sinksDeviceAddr);
aclrtFree(dQIndexDeviceAddr);
aclrtFree(dKIndexDeviceAddr);
aclrtFree(dWeightDeviceAddr);
aclrtFree(lossDeviceAddr);
if (workspaceSize > 0) {
aclrtFree(workspaceAddr);
}
aclrtDestroyStream(stream);
aclrtDestroyContext(context);
aclrtResetDevice(deviceId);
aclFinalize();
return 0;
}