aclnnDenseLightningIndexerSoftmaxLseV2
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 DenseLightningIndexerSoftmaxLseV2 operator is a branch operator used to compute the Softmax input for the DenseLightningIndexerGradKlLoss operator. Compared with aclnnDenseLightningIndexerSoftmaxLse, it adds support for Compressed Attention and supports split-core load balancing through the metadata preceding operator.
The main computation process is as follows:
- Computes the attention score of query_index and key_index.
- Performs a weighted sum of attention score based on weight.
- Performs Softmax computation on the weighted result and outputs the log-sum-exp (LSE) result.
Formula:
$$ \text{res}=\text{AttentionMask}\left(\text{ReduceSum}\left(W\odot\text{ReLU}\left(Q_{index}@K_{index}^T\right)\right)\right) $$$$ \text{lse}=\text{ReduceMax}\left(\text{res}\right)+\text{log}\left(\text{ReduceSum}\left(\text{exp}\left(\text{res}-\text{ReduceMax}\left(\text{res}\right)\right)\right)\right) $$The lse is passed as the output to the DenseLightningIndexerGradKlLoss operator as input for Softmax computation.
Function Prototype
The operator execution API is a two-phase API. You must first call "aclnnDenseLightningIndexerSoftmaxLseV2GetWorkspaceSize" to obtain the input parameters and calculate the required workspace size based on the computation process, and then call "aclnnDenseLightningIndexerSoftmaxLseV2" to execute the computation.
aclnnStatus aclnnDenseLightningIndexerSoftmaxLseV2GetWorkspaceSize(
const aclTensor *queryIndex,
const aclTensor *keyIndex,
const aclTensor *weight,
const aclTensor *cuSeqLensQOptional,
const aclTensor *cuSeqLensKOptional,
const aclTensor *seqUsedQOptional,
const aclTensor *seqUsedKOptional,
const aclTensor *cmpResidualKOptional,
const aclTensor *metadataOptional,
const char *layoutQ,
const char *layoutK,
int64_t maskMode,
int64_t cmpRatio,
const aclTensor *softmaxLseOut,
uint64_t *workspaceSize,
aclOpExecutor **executor);aclnnStatus aclnnDenseLightningIndexerSoftmaxLseV2(
void *workspace,
uint64_t workspaceSize,
aclOpExecutor *executor,
aclrtStream stream);aclnnDenseLightningIndexerSoftmaxLseV2GetWorkspaceSize
Parameters:
Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor queryIndex (aclTensor*) Input Input queryIndex of the lightningIndexer structure. - B: supports generalization and must be consistent with B of keyIndex.
- N1: range 1-128, and must be divisible by N2.
- D: 128.
- T1: S1 accumulated across multiple batches.
FLOAT16, BFLOAT16 ND (B,S1,N1,D);(T1,N1,D) × keyIndex (aclTensor*) Input Input keyIndex of the lightningIndexer structure. - B: support generalization and remain consistent with B of queryIndex.
- S2: support generalization.
- N2: 1.
- D: 128 and remain consistent with D of queryIndex.
- T2: S2 accumulated across multiple batches.
FLOAT16, BFLOAT16 ND (B,S2,N2,D);(T2,N2,D) × weight (aclTensor*) Input Weight tensor. - B: support generalization and remain consistent with B of queryIndex.
- S1: support generalization and remain consistent with S1 of queryIndex.
- N1: remain consistent with N1 of queryIndex.
- T1: S1 accumulated across multiple batches.
FLOAT32 ND (B,S1,N1);(T1,N1) × cuSeqLensQOptional(aclTensor*) Optional input Accumulated sum of the number of valid q tokens in the current and preceding batches. - Must be passed in for TND use cases. The first value is fixed to 0.
- Supports empty tensors.
INT32 ND 1D, shape (B+1,) × cuSeqLensKOptional (aclTensor*) Optional input Cumulative sum of the number of valid k tokens in the current batch and preceding batches. - Must be passed in for the TND use case. The first value is fixed to 0.
- Supports empty tensor.
INT32 ND 1-D, shape (B+1,) × seqUsedQOptional (aclTensor*) Optional input Actual used lengths of q in different batches. - Supports empty tensors. When this input is present, each batch participates in the computation based on the actual value of seqused_q.
- The value of seqused_q must not be greater than the actual seqlen_q of each batch.
INT32 ND 1D, shape (B,) × seqUsedKOptional (aclTensor*) Optional input Actual used lengths of k in different batches. - Supports empty tensors. When this parameter is present, each batch participates in the computation based on the actual value of seqused_k.
- The value of seqused_k must not exceed the actual seqlen_k of each batch.
INT32 ND 1-D, shape (B,) × cmpResidualKOptional (aclTensor*) Optional input Represents the residual of the sequence length of k related to cmpRatio. - Supports empty tensors.
- Must be passed in when maskMode=3 and cmpRatio>1.
- Each value of cmp_residual_k must be less than cmpRatio.
INT32 ND 1D, shape (B,) × metadataOptional (aclTensor*) Input Load balancing information across cores output by the preceding AICPU operator. - Must be passed in. Output by the aclnnDenseLightningIndexerSoftmaxLseV2Metadata operator to reduce host array access in the tiling phase.
INT32 ND 1D, shape (64,) × layoutQ (char*) Input Indicates the layout of the query. Supports BSND and TND. Defaults to BSND if a null pointer is passed in. layoutQ must be consistent with layoutK. STRING - - - layoutK (char*) Input Indicates the layout format on the key side. Supports BSND and TND. Defaults to BSND if a null pointer is passed in. layoutK must be consistent with layoutQ. STRING - - - maskMode (int64_t) Input Indicates the mask mode. - 0: No mask.
- 3: Mask in rightDownCausal mode, corresponding to the lower-triangle scenario where the right vertex is the dividing point.
- - - - cmpRatio (int64_t) Input Indicates the compression ratio of key. Value range [1, 128], indicating no compression. - - - - softmaxLseOut (aclTensor*) Output LSE (log-sum-exp) values used for the softmax computation. - B: support generalization; must remain consistent with the B of queryIndex.
- N2: number of heads of key, currently fixed to 1.
- S1: support generalization, and must remain consistent with the S1 of queryIndex.
- T1: accumulation of S1 across multiple batches.
FLOAT32 ND (B,N2,S1);(N2,T1) × 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 An illegal nullptr exists in the parameters. ACLNN_ERR_PARAM_INVALID 161002 The input data type is not supported. Required inputs/outputs queryIndex, keyIndex, weight, and softmaxLseOut are not passed in.
aclnnDenseLightningIndexerSoftmaxLseV2
Parameters:
Parameter Input/Output Description workspace Input Memory address of the workspace allocated on the Device. workspaceSize Input Size of the workspace allocated on the Device, obtained by calling the first-phase API aclnnDenseLightningIndexerSoftmaxLseV2GetWorkspaceSize. executor Input Op executor that contains the operator computation flow. stream Input Specifies the stream for executing tasks. Return value
aclnnStatus: return status code. For details, see aclnn return codes.
Constraints
Deterministic computation: aclnnDenseLightningIndexerSoftmaxLseV2 defaults to a deterministic implementation.
General Constraints
- Handling of empty input parameters:
- If queryIndex is an empty tensor, the API returns directly.
maskMode Meaning Remarks 0 No mask, no mask operation is performed. Supported 3 Mask in rightDownCausal mode, corresponding to the lower-triangular shape divided by the right vertex. Supported - Handling of empty input parameters:
Specification constraints
Specification Item Specification Specification Description B 1-256 - S1, S2 0-128K S1, S2 support different lengths. N1 1-128 Must be divisible by N2. N2 1 - D 128 - layout BSND/TND layoutQ and layoutK must be consistent. cmpRatio 1-128 1 indicates no compression. maskMode 0, 3 0=No mask, 3=rightDownCausal. Special constraints
- In BSND use cases, information about batch_size and max_seqlen_q (indicated by the tensor shape) must be passed in.
- In TND use cases, cuSeqLensQ and cuSeqLensK must be passed in.
- When maskMode=3 and cmpRatio>1, cmpResidualK must be passed in, and each value of cmpResidualK must be less than cmpRatio.
- Each value of seqUsedQ must not be greater than the actual seqlen_q of each batch.
- Each value of seqUsedK must not be greater than the actual seqlen_k of each batch.
- metadataOptional is the output of the preceding operator aclnnDenseLightningIndexerSoftmaxLseV2Metadata and must be passed in to execute the related load balancing policy.
Example
The following sample code is for reference only. For details about the compilation and execution process, see Compile and Run Samples.
#include <iostream>
#include <vector>
#include <cstdint>
#include <cmath>
#include <cstring>
#include "securec.h"
#include "acl/acl.h"
#include "aclnnop/aclnn_dense_lightning_indexer_softmax_lse_v2.h"
#include "aclnnop/aclnn_dense_lightning_indexer_softmax_lse_v2_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;
}
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("result[%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;
}
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 = 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;
}
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);
// BSND layout: q[B,S1,N1,D] k[B,S2,N2,D] w[B,S1,N1] lse[B,N2,S1]
int64_t B = 2;
int64_t S1 = 128;
int64_t S2 = 256;
int64_t N1 = 8;
int64_t N2 = 1;
int64_t D = 128;
std::vector<int64_t> qIndexShape = {B, S1, N1, D};
std::vector<int64_t> kIndexShape = {B, S2, N2, D};
std::vector<int64_t> weightShape = {B, S1, N1};
std::vector<int64_t> softmaxLseShape = {B, N2, S1};
std::vector<int64_t> metadataShape = {64};
void* qIndexDeviceAddr = nullptr;
void* kIndexDeviceAddr = nullptr;
void* weightDeviceAddr = nullptr;
void* softmaxLseDeviceAddr = nullptr;
void* metadataDeviceAddr = nullptr;
aclTensor* qIndex = nullptr;
aclTensor* kIndex = nullptr;
aclTensor* weight = nullptr;
aclTensor* softmaxLse = nullptr;
aclTensor* metadata = nullptr;
std::vector<aclFloat16> qIndexHostData(B * S1 * N1 * D, aclFloatToFloat16(0.2));
std::vector<aclFloat16> kIndexHostData(B * S2 * 1 * D, aclFloatToFloat16(0.1));
std::vector<float> weightHostData(B * S1 * N1, 0.005f);
std::vector<float> softmaxLseHostData(B * N2 * S1, 0.0f);
std::vector<int32_t> metadataHostData(64, 0);
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_FLOAT, &weight);
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(metadataHostData, metadataShape, &metadataDeviceAddr, aclDataType::ACL_INT32, &metadata);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// BSND layout, maskMode=0 (defaultMask), cmpRatio=1
constexpr const char layoutQStr[] = "BSND";
constexpr const char layoutKStr[] = "BSND";
constexpr size_t layoutQLen = sizeof(layoutQStr);
constexpr size_t layoutKLen = sizeof(layoutKStr);
char layoutQ[layoutQLen];
char layoutK[layoutKLen];
errno_t memcpyRet = memcpy_s(layoutQ, sizeof(layoutQ), layoutQStr, layoutQLen);
if (memcpyRet != 0) {
LOG_PRINT("memcpy_s layoutQ failed. ERROR: %d\n", memcpyRet);
return -1;
}
memcpyRet = memcpy_s(layoutK, sizeof(layoutK), layoutKStr, layoutKLen);
if (memcpyRet != 0) {
LOG_PRINT("memcpy_s layoutK failed. ERROR: %d\n", memcpyRet);
return -1;
}
int64_t maskMode = 0;
int64_t cmpRatio = 1;
// 1. Call the preceding metadata operator to generate load balancing information across cores.
uint64_t metadataWorkspaceSize = 0;
aclOpExecutor* metadataExecutor = nullptr;
ret = aclnnDenseLightningIndexerSoftmaxLseV2MetadataGetWorkspaceSize(
nullptr, nullptr, nullptr, nullptr, nullptr, B, S1, S2, N1, N2, D, layoutQ, layoutK, maskMode, cmpRatio,
metadata, &metadataWorkspaceSize, &metadataExecutor);
CHECK_RET(ret == ACL_SUCCESS,
LOG_PRINT("aclnnDenseLightningIndexerSoftmaxLseV2MetadataGetWorkspaceSize 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 = aclnnDenseLightningIndexerSoftmaxLseV2Metadata(metadataWorkspaceAddr, metadataWorkspaceSize,
metadataExecutor, stream);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnDenseLightningIndexerSoftmaxLseV2Metadata 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);
// 2. Call the main operator.
uint64_t workspaceSize = 0;
aclOpExecutor* executor = nullptr;
ret = aclnnDenseLightningIndexerSoftmaxLseV2GetWorkspaceSize(
qIndex, kIndex, weight,
nullptr, nullptr, nullptr, nullptr, nullptr,
metadata,
layoutQ, layoutK, maskMode, cmpRatio,
softmaxLse,
&workspaceSize, &executor);
CHECK_RET(ret == ACL_SUCCESS,
LOG_PRINT("aclnnDenseLightningIndexerSoftmaxLseV2GetWorkspaceSize 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 = aclnnDenseLightningIndexerSoftmaxLseV2(workspaceAddr, workspaceSize, executor, stream);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnDenseLightningIndexerSoftmaxLseV2 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(softmaxLseShape, &softmaxLseDeviceAddr);
LOG_PRINT("pass\n");
aclDestroyTensor(qIndex);
aclDestroyTensor(kIndex);
aclDestroyTensor(weight);
aclDestroyTensor(softmaxLse);
aclDestroyTensor(metadata);
aclrtFree(qIndexDeviceAddr);
aclrtFree(kIndexDeviceAddr);
aclrtFree(weightDeviceAddr);
aclrtFree(softmaxLseDeviceAddr);
aclrtFree(metadataDeviceAddr);
if (workspaceSize > 0) {
aclrtFree(workspaceAddr);
}
if (metadataWorkspaceSize > 0) {
aclrtFree(metadataWorkspaceAddr);
}
aclrtDestroyStream(stream);
aclrtDestroyContext(context);
aclrtResetDevice(deviceId);
aclFinalize();
return 0;
}