aclnnDenseLightningIndexerKLLossGrad
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 DenseLightningIndexerKLLossGrad operator is the backward computation operator of the LightningIndexer KL Loss (Dense mode). This API takes q, k, and w from the Lightning Indexer branch, as well as attnSoftmaxL1Norm and softmaxLse precomputed by the main Attention branch, and computes and outputs dq, dk, dw, and softmaxOut. This API performs dense attention computation over all keys and no longer relies on sparseIndices for top-k filtering; it does not need to recompute the
Q @ K -> softmax -> reduce/l1 normof the main Attention inside the kernel, and no longer outputs loss. The target distribution of the main Attention is provided by the attnSoftmaxL1Norm input, and softmaxOut can be used for subsequent loss computation.Formula: Indexer logits can be expressed as:
$$ S_{t,:}=q_{t,:}@K^{T} $$$$ I_{t,:}=W_{t,:}@\mathrm{ReLU}(S_{t,:}) $$Here, $q$ and $K$ correspond to q and k of this API respectively, and $W$ corresponds to w of this API. The softmax output of the Indexer branch is:
$$ y_{t,:}=\operatorname{Softmax}(I_{t,:}) $$This API writes $y$ to softmaxOut. The target distribution $p$ is provided by the attnSoftmaxL1Norm input. It is equivalent to the result obtained internally in the legacy kernel by performing head sum and L1 normalization on the main attention score. If KL Loss is computed subsequently, its form is the same as in the legacy version:
$$ L(I){=}\sum_tD_{KL}(p_{t,:}||\operatorname{Softmax}(I_{t,:})) $$$$ 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_{t,:}=\operatorname{Softmax}(I_{t,:})-p_{t,:} $$The gradients of the w, q, and k matrices can be computed using the chain rule:
$$ dW_{t,:}=dI_{t,:}\text{@}\left(\mathrm{ReLU}(S_{t,:})\right)^{T} $$$$ dq_{t,:}=dS_{t,:}@K $$$$ dK=\sum_t\left(dS_{t,:}\right)^{T}@q_{t,:} $$dK is accumulated directly to the corresponding key positions. No scatter-add is required.
Function Prototype
Each operator uses a two-phase API. You must first call the "aclnnDenseLightningIndexerKLLossGradGetWorkspaceSize" API to obtain the input parameters and calculate the required workspace size based on the computation process, and then call the "aclnnDenseLightningIndexerKLLossGrad" API to perform the computation.
aclnnStatus aclnnDenseLightningIndexerKLLossGradGetWorkspaceSize(
const aclTensor *q,
const aclTensor *k,
const aclTensor *w,
const aclTensor *attnSoftmaxL1Norm,
const aclTensor *softmaxLse,
const aclTensor *cuSeqLensQOptional,
const aclTensor *cuSeqLensKOptional,
const aclTensor *seqUsedQOptional,
const aclTensor *seqUsedKOptional,
const aclTensor *cmpResidualKOptional,
const aclTensor *metadataOptional,
char *layoutQ,
char *layoutK,
int64_t maskMode,
int64_t cmpRatio,
const aclTensor *dq,
const aclTensor *dk,
const aclTensor *dw,
const aclTensor *softmaxOut,
uint64_t *workspaceSize,
aclOpExecutor **executor)aclnnStatus aclnnDenseLightningIndexerKLLossGrad(
void *workspace,
uint64_t workspaceSize,
aclOpExecutor *executor,
aclrtStream stream)aclnnDenseLightningIndexerKLLossGradGetWorkspaceSize
Parameters:
Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor q Input Query input of the Lightning Indexer branch. - The data type must be the same as that of k, dq, and dk.
- Does not support null Tensor.
FLOAT16, BFLOAT16 ND (B,S1,N1,D), (T1,N1,D) √ k Input Key input of the Lightning Indexer branch. - The data type must be the same as q, dq, and dk.
- Currently, only N2=1 is supported.
- Does not support null tensors.
FLOAT16, BFLOAT16 ND (B,S2,N2,D), (T2,N2,D) √ w Input Head weight of Indexer logits. Does not support null tensors. FLOAT32 ND (B,S1,N1), (T1,N1) √ attnSoftmaxL1Norm Input Target distribution precomputed by the main Attention branch. - Replaces the main Attention recomputation result inside the legacy kernel.
- Dimensions: (B,S1,N2,S2) or (T1,N2,maxSeqLenK), covering all keys.
- Does not support null tensors.
FLOAT32 ND (B,S1,N2,S2), (T1,N2,maxSeqLenK) √ softmaxLse Input softmax log-sum-exp value, precomputed by DenseLightningIndexerSoftmaxLse. - Used for numerically stable computation.
- Dimensions: (B,N2,S1) or (N2,T1).
- Does not support null tensors.
FLOAT32 ND (B,N2,S1), (N2,T1) √ cuSeqLensQOptional Optional Input Cumulative sequence length of q under the TND layout. Required when layoutQ is TND. The length is B+1, and the first element is 0. INT32 ND (B+1,) √ cuSeqLensKOptional Optional Input Cumulative sequence length of k under the TND layout. Required when layoutK is TND. Length: B+1. First element: 0. INT32 ND (B+1,) √ seqUsedQOptional Optional Input Represents the actual q length used in each batch. Length: B. INT32 ND (B,) √ seqUsedKOptional Optional Input Indicates the actual k length used by each batch. The length is B. INT32 ND (B,) √ cmpResidualKOptional Optional Input Required when maskMode=3 and cmpRatio!=1. The length is B. INT32 ND (B,) √ metadataOptional Input Core splitting information generated by aclnnDenseLightningIndexerKLLossGradMetadata. Must be passed in. Once passed in, the kernel uses the core splitting from the metadata. INT32 ND (x,) √ layoutQ Input Layout of q, w, attnSoftmaxL1Norm, softmaxLse, dq, dw, and softmaxOut. Only BSND and TND are supported. STRING - - - layoutK Input Layout of k and dk. Only BSND and TND are supported. STRING - - - maskMode Input Mask mode. For details about the supported mask modes, see Constraints. INT64 - - - cmpRatio Input Compression ratio. Value range: 1-128. INT64 - - - dq Output Gradient of q. Data type and shape are the same as q. FLOAT16, BFLOAT16 ND (B,S1,N1,D), (T1,N1,D) x dk Output Gradient of k. Same data type and shape as k. FLOAT16, BFLOAT16 ND (B,S2,N2,D), (T2,N2,D) x dw Output Gradient of w. Same data type and shape as w. FLOAT32 ND (B,S1,N1), (T1,N1) x softmaxOut Output Indexer branch softmax output. Same shape as attnSoftmaxL1Norm. FLOAT32 ND (B,S1,N2,S2), (T1,N2,S2) x workspaceSize Output Returns the workspace size that the user needs to allocate on the device. - - - - - executor Output Executor of the op, including 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 Illegal nullptr exists in the parameters. ACLNN_ERR_PARAM_INVALID 161002 The input data type is not among the supported types. Required inputs q, k, w, attnSoftmaxL1Norm, and softmaxLse are not passed. Required outputs dq, dk, dw, and softmaxOut are not passed.
aclnnDenseLightningIndexerKLLossGrad
Parameters:
Parameter Input/Output Description workspace Input Workspace memory address allocated on the device. workspaceSize Input Workspace size allocated on the device, obtained by calling the first-phase API aclnnDenseLightningIndexerKLLossGradGetWorkspaceSize. executor Input Op executor, which contains the operator computation process. stream Input Specifies the Stream for executing tasks. Return value
aclnnStatus: return status code. For details, see aclnn Return Codes.
Constraints
Deterministic computation:
Ascend 950PR&950DT products : aclnnDenseLightningIndexerKLLossGrad defaults to a non-deterministic implementation. Deterministic computation can be enabled through aclrtCtxSetSysParamOpt.
Common constraints:
The data types of q, k, dq, and dk must be consistent. FLOAT16 and BFLOAT16 are supported.
The data types of w, dw, attnSoftmaxL1Norm, softmaxLse, and softmaxOut must be FLOAT32.
The data types of cuSeqLensQOptional, cuSeqLensKOptional, seqUsedQOptional, seqUsedKOptional, cmpResidualKOptional, and metadataOptional must be INT32.
Currently, layoutQ and layoutK support BSND and TND.
If layoutQ is TND, cuSeqLensQOptional is required. If layoutK is TND, cuSeqLensKOptional is required.
The dimensions of attnSoftmaxL1Norm are (B,S1,N2,S2) or (T1,N2,maxSeqLenK), covering the target distribution over all keys.
softmaxLse is precomputed and provided by the DenseLightningIndexerSoftmaxLse operator, with dimensions of (B,N2,S1) or (N2,T1), for numerically stable computation.
The metadata input must be passed in to compute core splitting information.
maskMode Meaning Remarks 0 defaultMask mode; causal mask is not applied. Supported 1 allMask; the complete attenmask matrix must be passed in. Not supported 2 Mask for the leftUpCausal mode. Not supported 3 Mask of the rightDownCausal mode, corresponding to the lower triangle scenario with the top-right vertex as the dividing point. Supported 4 Mask of the band mode. Not supported 5 Prefix mode. Not supported 6 global mode. Not supported 7 dilated mode. Not supported 8 block_local mode. Not supported
Specification constraints:
Specification Item Specification Specification Description B - - S1 and S2 - S1 and S2 support different lengths N1 1-128 MQA use case N2 1 Currently, only N2=1 is supported. D 128 - cmpRatio 1-128 -
Example
The sample code is as follows, for reference only. For details about compilation and execution, see Compile and Run Samples.
#include <algorithm>
#include <cstdint>
#include <cstdio>
#include <iostream>
#include <vector>
#include "acl/acl.h"
#include "aclnnop/aclnn_dense_lightning_indexer_kl_loss_grad.h"
#include "aclnnop/aclnn_dense_lightning_indexer_kl_loss_grad_metadata.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;
}
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);
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);
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);
std::vector<int64_t> strides(shape.size(), 1);
for (int64_t i = static_cast<int64_t>(shape.size()) - 2; i >= 0; i--) {
strides[i] = shape[i + 1] * strides[i + 1];
}
*tensor = aclCreateTensor(shape.data(), shape.size(), dataType, strides.data(), 0, aclFormat::ACL_FORMAT_ND,
shape.data(), shape.size(), *deviceAddr);
return 0;
}
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 < std::min<int64_t>(size, 5); i++) {
LOG_PRINT("softmaxOut[%ld] is: %f\n", i, resultData[i]);
}
}
int Init(int32_t deviceId, aclrtContext* context, aclrtStream* stream) {
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;
}
int main() {
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);
const int64_t batchSize = 1;
const int64_t t1 = 16;
const int64_t t2 = 4;
const int64_t numHeadsQ = 8;
const int64_t numHeadsK = 1;
const int64_t headDim = 128;
const int64_t maskMode = 3;
const int64_t cmpRatio = 1;
std::vector<int64_t> qShape = {t1, numHeadsQ, headDim};
std::vector<int64_t> kShape = {t2, numHeadsK, headDim};
std::vector<int64_t> wShape = {t1, numHeadsQ};
std::vector<int64_t> l1NormShape = {t1, numHeadsK, t2};
std::vector<int64_t> softmaxLseShape = {numHeadsK, t1};
std::vector<int64_t> softmaxShape = {t1, numHeadsK, t2};
std::vector<int64_t> cuSeqLensShape = {batchSize + 1};
std::vector<int64_t> metadataShape = {64};
std::vector<uint16_t> qHostData(GetShapeSize(qShape), 0x3C00);
std::vector<uint16_t> kHostData(GetShapeSize(kShape), 0x3C00);
std::vector<float> wHostData(GetShapeSize(wShape), 1.0f);
std::vector<float> attnSoftmaxL1NormHostData(GetShapeSize(l1NormShape), 0.0f);
for (int64_t t = 0; t < t1; ++t) {
auto validK = std::min<int64_t>(std::max<int64_t>(1, (t + 1) / cmpRatio), t2);
for (int64_t kIdx = 0; kIdx < validK; ++kIdx) {
attnSoftmaxL1NormHostData[t * numHeadsK * t2 + kIdx] = 1.0f / static_cast<float>(validK);
}
}
std::vector<float> softmaxLseHostData(GetShapeSize(softmaxLseShape), 0.0f);
std::vector<int32_t> cuSeqLensQHostData = {0, static_cast<int32_t>(t1)};
std::vector<int32_t> cuSeqLensKHostData = {0, static_cast<int32_t>(t2)};
std::vector<int32_t> metadataHostData(GetShapeSize(metadataShape), 0);
std::vector<uint16_t> dqHostData(GetShapeSize(qShape), 0);
std::vector<uint16_t> dkHostData(GetShapeSize(kShape), 0);
std::vector<float> dwHostData(GetShapeSize(wShape), 0.0f);
std::vector<float> softmaxOutHostData(GetShapeSize(softmaxShape), 0.0f);
void* qDeviceAddr = nullptr;
void* kDeviceAddr = nullptr;
void* wDeviceAddr = nullptr;
void* attnSoftmaxL1NormDeviceAddr = nullptr;
void* softmaxLseDeviceAddr = nullptr;
void* cuSeqLensQDeviceAddr = nullptr;
void* cuSeqLensKDeviceAddr = nullptr;
void* metadataDeviceAddr = nullptr;
void* dqDeviceAddr = nullptr;
void* dkDeviceAddr = nullptr;
void* dwDeviceAddr = nullptr;
void* softmaxOutDeviceAddr = nullptr;
aclTensor* q = nullptr;
aclTensor* k = nullptr;
aclTensor* w = nullptr;
aclTensor* attnSoftmaxL1Norm = nullptr;
aclTensor* softmaxLse = nullptr;
aclTensor* cuSeqLensQ = nullptr;
aclTensor* cuSeqLensK = nullptr;
aclTensor* metadata = nullptr;
aclTensor* dq = nullptr;
aclTensor* dk = nullptr;
aclTensor* dw = nullptr;
aclTensor* softmaxOut = nullptr;
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(wHostData, wShape, &wDeviceAddr, aclDataType::ACL_FLOAT, &w);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(attnSoftmaxL1NormHostData, l1NormShape, &attnSoftmaxL1NormDeviceAddr,
aclDataType::ACL_FLOAT, &attnSoftmaxL1Norm);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(softmaxLseHostData, softmaxLseShape, &softmaxLseDeviceAddr,
aclDataType::ACL_FLOAT, &softmaxLse);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(cuSeqLensQHostData, cuSeqLensShape, &cuSeqLensQDeviceAddr, aclDataType::ACL_INT32, &cuSeqLensQ);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(cuSeqLensKHostData, cuSeqLensShape, &cuSeqLensKDeviceAddr, aclDataType::ACL_INT32, &cuSeqLensK);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(metadataHostData, metadataShape, &metadataDeviceAddr, aclDataType::ACL_INT32, &metadata);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(dqHostData, qShape, &dqDeviceAddr, aclDataType::ACL_FLOAT16, &dq);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(dkHostData, kShape, &dkDeviceAddr, aclDataType::ACL_FLOAT16, &dk);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(dwHostData, wShape, &dwDeviceAddr, aclDataType::ACL_FLOAT, &dw);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(softmaxOutHostData, softmaxShape, &softmaxOutDeviceAddr, aclDataType::ACL_FLOAT, &softmaxOut);
CHECK_RET(ret == ACL_SUCCESS, return ret);
char layoutQ[4] = {'T', 'N', 'D', 0};
char layoutK[4] = {'T', 'N', 'D', 0};
uint64_t metadataWorkspaceSize = 0;
aclOpExecutor* metadataExecutor = nullptr;
ret = aclnnDenseLightningIndexerKLLossGradMetadataGetWorkspaceSize(
cuSeqLensQ, cuSeqLensK, nullptr, nullptr, nullptr, batchSize, t1, t2, numHeadsQ, numHeadsK, headDim,
layoutQ, layoutK, maskMode, cmpRatio, metadata, &metadataWorkspaceSize, &metadataExecutor);
CHECK_RET(ret == ACL_SUCCESS,
LOG_PRINT("aclnnDenseLightningIndexerKLLossGradMetadataGetWorkspaceSize failed. ERROR: %d\n", ret);
return ret);
void* metadataWorkspaceAddr = nullptr;
if (metadataWorkspaceSize > 0) {
ret = aclrtMalloc(&metadataWorkspaceAddr, metadataWorkspaceSize, ACL_MEM_MALLOC_HUGE_FIRST);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("allocate metadata workspace failed. ERROR: %d\n", ret); return ret);
}
ret = aclnnDenseLightningIndexerKLLossGradMetadata(metadataWorkspaceAddr, metadataWorkspaceSize,
metadataExecutor, stream);
CHECK_RET(ret == ACL_SUCCESS,
LOG_PRINT("aclnnDenseLightningIndexerKLLossGradMetadata failed. ERROR: %d\n", ret); return ret);
uint64_t workspaceSize = 0;
aclOpExecutor* executor = nullptr;
ret = aclnnDenseLightningIndexerKLLossGradGetWorkspaceSize(
q, k, w, attnSoftmaxL1Norm, softmaxLse, cuSeqLensQ, cuSeqLensK, nullptr, nullptr, nullptr, metadata,
layoutQ, layoutK, maskMode, cmpRatio, dq, dk, dw, softmaxOut, &workspaceSize, &executor);
CHECK_RET(ret == ACL_SUCCESS,
LOG_PRINT("aclnnDenseLightningIndexerKLLossGradGetWorkspaceSize failed. ERROR: %d\n", ret);
return ret);
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);
}
ret = aclnnDenseLightningIndexerKLLossGrad(workspaceAddr, workspaceSize, executor, stream);
CHECK_RET(ret == ACL_SUCCESS,
LOG_PRINT("aclnnDenseLightningIndexerKLLossGrad failed. ERROR: %d\n", ret); return ret);
ret = aclrtSynchronizeStream(stream);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtSynchronizeStream failed. ERROR: %d\n", ret); return ret);
PrintOutResult(softmaxShape, &softmaxOutDeviceAddr);
aclDestroyTensor(q);
aclDestroyTensor(k);
aclDestroyTensor(w);
aclDestroyTensor(attnSoftmaxL1Norm);
aclDestroyTensor(softmaxLse);
aclDestroyTensor(cuSeqLensQ);
aclDestroyTensor(cuSeqLensK);
aclDestroyTensor(metadata);
aclDestroyTensor(dq);
aclDestroyTensor(dk);
aclDestroyTensor(dw);
aclDestroyTensor(softmaxOut);
aclrtFree(qDeviceAddr);
aclrtFree(kDeviceAddr);
aclrtFree(wDeviceAddr);
aclrtFree(attnSoftmaxL1NormDeviceAddr);
aclrtFree(softmaxLseDeviceAddr);
aclrtFree(cuSeqLensQDeviceAddr);
aclrtFree(cuSeqLensKDeviceAddr);
aclrtFree(metadataDeviceAddr);
aclrtFree(dqDeviceAddr);
aclrtFree(dkDeviceAddr);
aclrtFree(dwDeviceAddr);
aclrtFree(softmaxOutDeviceAddr);
if (metadataWorkspaceSize > 0) {
aclrtFree(metadataWorkspaceAddr);
}
if (workspaceSize > 0) {
aclrtFree(workspaceAddr);
}
aclrtDestroyStream(stream);
aclrtDestroyContext(context);
aclrtResetDevice(deviceId);
aclFinalize();
return 0;
}