aclnnDenseLightningIndexerSoftmaxLseV2Metadata
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: This operator is an AICPU operator and the preceding operator of aclnnDenseLightningIndexerSoftmaxLseV2. Based on the input shape, layout, mask, and compression ratio information of the aclnnDenseLightningIndexerSoftmaxLseV2 operator, it computes and outputs the core-partitioned metadata. The output can be used as the metadataOptional input of the aclnnDenseLightningIndexerSoftmaxLseV2 operator, reducing host array access in the tiling phase of the main operator.
This operator is not recommended for standalone use. Use it with the aclnnDenseLightningIndexerSoftmaxLseV2 operator to form a complete workflow.
- Receive the shape information of the main operator, including batchSize, maxSeqLenQ, maxSeqLenK, numHeadsQ, numHeadsK, headDim, layout, and mask information.
- Calculates the total number of seqs involved in load balancing based on layout and the optional input seqUsedQOptional, and evenly partitions tasks across available AIC cores in a strided manner.
- After the metadata is output, it is subsequently used as the metadataOptional input of the aclnnDenseLightningIndexerSoftmaxLseV2 operator.
Function Prototype
Each operator uses a two-phase API. Call "aclnnDenseLightningIndexerSoftmaxLseV2MetadataGetWorkspaceSize" first to obtain the workspace size, and then call "aclnnDenseLightningIndexerSoftmaxLseV2Metadata" to perform the computation.
aclnnStatus aclnnDenseLightningIndexerSoftmaxLseV2MetadataGetWorkspaceSize(
const aclTensor *cuSeqLensQOptional,
const aclTensor *cuSeqLensKOptional,
const aclTensor *seqUsedQOptional,
const aclTensor *seqUsedKOptional,
const aclTensor *cmpResidualKOptional,
int64_t batchSize,
int64_t maxSeqLenQ,
int64_t maxSeqLenK,
int64_t numHeadsQ,
int64_t numHeadsK,
int64_t headDim,
char *layoutQ,
char *layoutK,
int64_t maskMode,
int64_t cmpRatio,
const aclTensor *metadata,
uint64_t *workspaceSize,
aclOpExecutor **executor);aclnnStatus aclnnDenseLightningIndexerSoftmaxLseV2Metadata(
void *workspace,
uint64_t workspaceSize,
aclOpExecutor *executor,
aclrtStream stream);aclnnDenseLightningIndexerSoftmaxLseV2MetadataGetWorkspaceSize
Parameters
Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor cuSeqLensQOptional (const aclTensor*) Input Indicates the cumulative sequence length of query in different batches.
Mandatory in the TND use case. The batch can be derived from the shape of this parameter.
The first value is fixed to 0.Supports empty tensors. INT32 ND 1-D, shape (B+1,) × cuSeqLensKOptional (const aclTensor*) Input Indicates the cumulative sequence length of key in different batches.
Mandatory in the TND use case.
The first value is fixed to 0.Supports empty tensors. INT32 ND 1D, shape (B+1,) × seqUsedQOptional (const aclTensor*) Input Indicates the actual sequence length of queries involved in computation in each batch. Supports empty tensors. If this parameter exists, the total number of seqs is calculated by accumulating the seqs actually used in each batch. INT32 ND 1 dimension, shape (B,) × seqUsedKOptional (const aclTensor*) Input Indicates the actual sequence length of keys involved in the computation in different batches. Supports empty tensors. When this input parameter exists, the value of seqused_k does not exceed the actual seqlen_k of each batch. INT32 ND 1 dimension, shape (B,) × cmpResidualKOptional (const aclTensor*) Input Indicates the residual related to cmpRatio for the sequence length of keys in different batches. Supports empty tensors. Mandatory when maskMode=3 and cmpRatio>1, and each value must be less than cmpRatio. INT32 ND 1D, shape (B,) × batchSize (int64_t) Input Indicates the number of batches. Supports non-negative values. In the TND use case, it can be set to 0 and derived through cuSeqLensQOptional. - - - - maxSeqLenQ (int64_t) Input Indicates the maximum sequence length of the query. Supports non-negative values. In BSND use cases, the value must be positive. - - - - maxSeqLenK (int64_t) Input Indicates the maximum sequence length of key. Supports non-negative values. In BSND use cases, the value must be positive. - - - - numHeadsQ (int64_t) Input Indicates the number of query heads. Must be positive, value range [1, 128], and can be divided by numHeadsK. - - - - numHeadsK (int64_t) Input Indicates the number of heads of key. Must be positive. Currently only supports 1. - - - - headDim (int64_t) Input Indicates the head dimension of q/k. Must be positive. Currently only supports 128. - - - - layoutQ (char*) Input Indicates the layout of the query. Supports BSND/TND. BSND is used when a null pointer is passed. STRING - - - layoutK (char*) Input Indicates the layout format on the key side. Supports BSND/TND. BSND is used when a null pointer is passed. Must be consistent with layoutQ. STRING - - - maskMode (int64_t) Input Indicates the sparse mask mode. 0: No mask
3: Causal- - - - cmpRatio (int64_t) Input Indicates the compression ratio of key. Value range [1, 128]. - - - - metadata (const aclTensor*) Output Indicates the load balancing result output. The output is used as the metadataOptional input of aclnnDenseLightningIndexerSoftmaxLseV2. INT32 ND 1D, shape fixed to (64,) × workspaceSize (uint64_t*) Output Returns the workspace size requested by the device side. The current implementation returns 0. - - - - executor (aclOpExecutor**) Output Returns the op executor that 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 Null pointers exist in metadata, workspaceSize, or executor. ACLNN_ERR_PARAM_INVALID 161002 The data type of metadata is not supported. numHeadsQ, numHeadsK, and headDim are not supported. layoutQ and layoutK indicate different layouts, or are not supported. batchSize, maxSeqLenQ, and maxSeqLenK do not meet the value constraints. maskMode is not supported. cmpRatio is not supported.
aclnnDenseLightningIndexerSoftmaxLseV2Metadata
Parameters:
Parameter Input/Output Description workspace Input Workspace memory address requested on the device side. workspaceSize Input Workspace size requested on the device side, obtained through the first-phase API aclnnDenseLightningIndexerSoftmaxLseV2MetadataGetWorkspaceSize. executor Input Op executor that contains the operator computation process. stream Input Stream for executing tasks. Return Value
aclnnStatus: return status code. For details, see aclnn return codes.
Constraints
aclnnDenseLightningIndexerSoftmaxLseV2Metadata defaults to a deterministic implementation. The deterministic computation configuration does not change its output rules.
BSND scenario
- batchSize, maxSeqLenQ, and maxSeqLenK must be passed to obtain shape information.
TND scenario
- Mandatory to pass cuSeqLensQOptional and cuSeqLensKOptional parameters to obtain correct shape information.
- When batchSize is 0, derive the batch from the shape of cuSeqLensQOptional.
Mask
| mask_mode | Meaning | Remarks |
|---|---|---|
| 0 | No mask. | Supported |
| 3 | Mask in rightDownCausal mode, corresponding to the lower triangular scenario partitioned by the right vertex. | Supported |
Special Constraints
- Batch value rules
- If batchSize is greater than 0, prefer to use batchSize.
- If batchSize is less than or equal to 0 and layoutQ is TND, derive the batch from the shape of cuSeqLensQOptional.
- If batchSize is less than or equal to 0 and layoutQ is BSND, an error is reported.
- Seqlen value rules
- In TND scenarios, calculate the actual q/k length of each batch via cuSeqLensQOptional and cuSeqLensKOptional.
- In the BSND use case, the q/k length is obtained through maxSeqLenQ and maxSeqLenK.
- layout constraints
- layoutQ must be BSND or TND.
- layoutK supports BSND and TND, and must be consistent with layoutQ.
- head constraints
- numHeadsQ: range [1, 128], and must be divisible by numHeadsK.
- Currently, only numHeadsK = 1 is supported.
- headDim currently supports only 128.
- Load balancing constraint
- cmpRatio: range [1, 128].
- maskMode currently only supports 0 and 3.
- cmp_residual_k constraints
- If maskMode=3 and cmpRatio>1, cmpResidualKOptional must be passed in.
- Each value of cmpResidualKOptional must be less than cmpRatio.
- seqused constraints
- Each value of seqUsedQOptional must not exceed the actual seqlen_q of each batch.
- Each value of seqUsedKOptional must not exceed the actual seqlen_k of each batch.
Metadata Output Layout
The metadata output is an INT32 tensor. The shape is currently fixed to (64,). The field layout is as follows.
| Field | index | Description |
|---|---|---|
| forecore_num | 0 | Number of fore cores, that is, the number of cores processing more tasks. If totalNum cannot be exactly divided by aicCoreNum, forecore_num = totalNum % aicCoreNum, and each fore core processes ceil(totalNum / aicCoreNum) tasks. If totalNum can be exactly divided by aicCoreNum, forecore_num = aicCoreNum. |
| tail_core_num | 1 | Number of tail cores, that is, the number of cores processing fewer tasks. tail_core_num = aicCoreNum - forecore_num, and each tail core processes floor(totalNum / aicCoreNum) tasks. The value is 0 when totalNum can be exactly divided by aicCoreNum. |
| b_s1_per_core | 2 | Number of B*S1 tasks processed by each fore core, that is, ceil(totalNum / aicCoreNum). |
| b_s1_per_tail_core | 3 | Number of B*S1 tasks processed by each tail core, which is floor(totalNum / aicCoreNum). Set to 0 if totalNum can be evenly divided by aicCoreNum. |
Differentiated block partitioning is used for preceding cores and tail cores. Let totalNum be the total number of seqs involved in load balancing and N be aicCoreNum. When totalNum can be evenly divided by N, forecore_num=N, tail_core_num=0, and each core processes totalNum/N tasks. When it cannot be evenly divided, let base=floor(totalNum/N) and rem=totalNum%N. Then forecore_num=rem, each preceding core processes base+1 tasks, tail_core_num=N-rem, and each tail core processes base tasks. For example, when totalNum=16 and N=36, 16<36, forecore_num=16, tail_core_num=0, and b_s1_per_core=1. The first 16 cores each process 1 task, and the remaining cores are idle.
Example
The following sample code is for reference only. For details about the compilation and execution process, see Compile and Run Samples.
#include <algorithm>
#include <cstdint>
#include <cstdio>
#include <cstring>
#include <functional>
#include <iostream>
#include <utility>
#include <vector>
#include "acl/acl.h"
#include "aclnnop/aclnn_dense_lightning_indexer_softmax_lse_v2_metadata.h"
#define CHECK_LOG_RET(cond, ret_val, fmt, ...) \
do { \
if (!(cond)) { \
printf(fmt "\n", ##__VA_ARGS__); \
return (ret_val); \
} \
} while (0)
constexpr uint32_t DLI_METADATA_SIZE = 64;
struct DenseLISoftmaxLseV2MetaData {
int32_t forecore_num;
int32_t tail_core_num;
int32_t b_s1_per_core;
int32_t b_s1_per_tail_core;
};
struct ScopeGuard
{
explicit ScopeGuard(std::function<void()> onExitScope) : m_exitFunc(std::move(onExitScope)),
m_isDismissed(false) {}
ScopeGuard(const ScopeGuard&) = delete;
ScopeGuard& operator=(const ScopeGuard&) = delete;
~ScopeGuard()
{
if (!m_isDismissed) {
m_exitFunc();
}
}
void Dismiss()
{
m_isDismissed = true;
}
std::function<void()> m_exitFunc;
bool m_isDismissed;
};
struct Tensor {
void *hostAddr { nullptr };
void *deviceAddr { nullptr };
aclTensor *data { nullptr };
};
struct ArgScenario {
bool hasCuSeq { true };
};
struct ArgContext {
Tensor cuSeqLensQOptional {};
Tensor cuSeqLensKOptional {};
Tensor seqUsedQOptional {};
Tensor seqUsedKOptional {};
Tensor cmpResidualKOptional {};
Tensor metadata {};
int64_t batchSize { 0 };
int64_t maxSeqLenQ { 0 };
int64_t maxSeqLenK { 0 };
int64_t numHeadsQ { 8 };
int64_t numHeadsK { 1 };
int64_t headDim { 128 };
char *layoutQ { nullptr };
char *layoutK { nullptr };
int64_t maskMode { 3 };
int64_t cmpRatio { 4 };
};
int64_t GetShapeSize(const std::vector<int64_t>& shape)
{
int64_t shapeSize = 1;
for (auto i : shape) {
shapeSize *= i;
}
return shapeSize;
}
aclnnStatus Init(int32_t deviceId, aclrtStream* stream)
{
auto ret = aclInit(nullptr);
CHECK_LOG_RET(ret == ACL_SUCCESS, ret, "aclInit failed. ERROR: %d", ret);
ret = aclrtSetDevice(deviceId);
CHECK_LOG_RET(ret == ACL_SUCCESS, ret, "aclrtSetDevice failed. ERROR: %d", ret);
ret = aclrtCreateStream(stream);
CHECK_LOG_RET(ret == ACL_SUCCESS, ret, "aclrtCreateStream failed. ERROR: %d", ret);
return ACL_SUCCESS;
}
void Finalize(int32_t deviceId, aclrtStream stream)
{
aclrtDestroyStream(stream);
aclrtResetDevice(deviceId);
aclFinalize();
}
aclnnStatus CreateTensor(aclDataType dataType, const std::vector<int64_t> &shape, Tensor &tensor)
{
auto size = GetShapeSize(shape) * aclDataTypeSize(dataType);
auto ret = aclrtMallocHost(&(tensor.hostAddr), size);
CHECK_LOG_RET(ret == ACL_SUCCESS, ret, "aclrtMallocHost failed. ERROR: %d", ret);
memset(tensor.hostAddr, 0, size);
ret = aclrtMalloc(&(tensor.deviceAddr), size, ACL_MEM_MALLOC_HUGE_FIRST);
CHECK_LOG_RET(ret == ACL_SUCCESS, ret, "aclrtMalloc failed. ERROR: %d", ret);
tensor.data = aclCreateTensor(shape.data(), shape.size(), dataType, nullptr, 0, aclFormat::ACL_FORMAT_ND,
shape.data(), shape.size(), tensor.deviceAddr);
ret = aclrtMemcpy(tensor.deviceAddr, size, tensor.hostAddr, size, ACL_MEMCPY_HOST_TO_DEVICE);
CHECK_LOG_RET(ret == ACL_SUCCESS, ret, "aclrtMemcpy failed. ERROR: %d", ret);
return ACL_SUCCESS;
}
void SetInt32TensorData(Tensor &tensor, const std::vector<int32_t> &hostData)
{
auto size = hostData.size() * sizeof(int32_t);
memcpy(tensor.hostAddr, hostData.data(), size);
aclrtMemcpy(tensor.deviceAddr, size, tensor.hostAddr, size, ACL_MEMCPY_HOST_TO_DEVICE);
}
void DestroyTensor(Tensor &tensor)
{
if (tensor.data != nullptr) {
aclDestroyTensor(tensor.data);
tensor.data = nullptr;
}
if (tensor.deviceAddr != nullptr) {
aclrtFree(tensor.deviceAddr);
tensor.deviceAddr = nullptr;
}
if (tensor.hostAddr != nullptr) {
aclrtFreeHost(tensor.hostAddr);
tensor.hostAddr = nullptr;
}
}
void DestroyArgs(ArgContext &context)
{
DestroyTensor(context.metadata);
DestroyTensor(context.cuSeqLensQOptional);
DestroyTensor(context.cuSeqLensKOptional);
DestroyTensor(context.seqUsedQOptional);
DestroyTensor(context.seqUsedKOptional);
DestroyTensor(context.cmpResidualKOptional);
if (context.layoutQ != nullptr) {
free(context.layoutQ);
context.layoutQ = nullptr;
}
if (context.layoutK != nullptr) {
free(context.layoutK);
context.layoutK = nullptr;
}
}
aclnnStatus CreateArgs(const ArgScenario &scenario, ArgContext &context)
{
ScopeGuard argsGuard([&] { DestroyArgs(context); });
aclnnStatus ret;
int64_t batchSize = 1;
context.maxSeqLenQ = 16;
context.maxSeqLenK = 4;
context.layoutQ = (char *)malloc(sizeof(char) * 16);
context.layoutK = (char *)malloc(sizeof(char) * 16);
strcpy(context.layoutQ, scenario.hasCuSeq ? "TND" : "BSND");
strcpy(context.layoutK, scenario.hasCuSeq ? "TND" : "BSND");
ret = CreateTensor(aclDataType::ACL_INT32, { DLI_METADATA_SIZE }, context.metadata);
CHECK_LOG_RET(ret == ACL_SUCCESS, ret, "Create metadata failed. Error: %d", ret);
if (scenario.hasCuSeq) {
ret = CreateTensor(aclDataType::ACL_INT32, { batchSize + 1 }, context.cuSeqLensQOptional);
CHECK_LOG_RET(ret == ACL_SUCCESS, ret, "Create cuSeqLensQOptional failed. Error: %d", ret);
ret = CreateTensor(aclDataType::ACL_INT32, { batchSize + 1 }, context.cuSeqLensKOptional);
CHECK_LOG_RET(ret == ACL_SUCCESS, ret, "Create cuSeqLensKOptional failed. Error: %d", ret);
SetInt32TensorData(context.cuSeqLensQOptional, { 0, static_cast<int32_t>(context.maxSeqLenQ) });
SetInt32TensorData(context.cuSeqLensKOptional, { 0, static_cast<int32_t>(context.maxSeqLenK) });
context.batchSize = 0;
} else {
context.batchSize = batchSize;
}
// cmp_residual_k is required when maskMode=3 and cmpRatio>1
if (context.maskMode == 3 && context.cmpRatio > 1) {
ret = CreateTensor(aclDataType::ACL_INT32, { batchSize }, context.cmpResidualKOptional);
CHECK_LOG_RET(ret == ACL_SUCCESS, ret, "Create cmpResidualKOptional failed. Error: %d", ret);
SetInt32TensorData(context.cmpResidualKOptional, std::vector<int32_t>(batchSize, 0));
}
argsGuard.Dismiss();
return ACL_SUCCESS;
}
void PrintMetadata(const DenseLISoftmaxLseV2MetaData &metadata)
{
printf("forecore_num : %d\n", metadata.forecore_num);
printf("tail_core_num : %d\n", metadata.tail_core_num);
printf("b_s1_per_core : %d\n", metadata.b_s1_per_core);
printf("b_s1_per_tail_core: %d\n", metadata.b_s1_per_tail_core);
}
int main() {
int32_t deviceId = 0;
aclrtStream stream;
auto ret = Init(deviceId, &stream);
CHECK_LOG_RET(ret == ACL_SUCCESS, ret, "Init acl failed. ERROR: %d", ret);
ScopeGuard sysGuard([&] { Finalize(deviceId, stream); });
ArgScenario scenario {};
scenario.hasCuSeq = true;
ArgContext context {};
ret = CreateArgs(scenario, context);
CHECK_LOG_RET(ret == ACL_SUCCESS, ret, "Create input arguments failed. ERROR: %d", ret);
ScopeGuard argsGuard([&] { DestroyArgs(context); });
uint64_t workspaceSize = 0;
aclOpExecutor *executor = nullptr;
void *workspaceAddr = nullptr;
ret = aclnnDenseLightningIndexerSoftmaxLseV2MetadataGetWorkspaceSize(
context.cuSeqLensQOptional.data, context.cuSeqLensKOptional.data, context.seqUsedQOptional.data,
context.seqUsedKOptional.data, context.cmpResidualKOptional.data, context.batchSize, context.maxSeqLenQ,
context.maxSeqLenK, context.numHeadsQ, context.numHeadsK, context.headDim, context.layoutQ,
context.layoutK, context.maskMode, context.cmpRatio, context.metadata.data, &workspaceSize, &executor);
CHECK_LOG_RET(ret == ACL_SUCCESS, ret,
"aclnnDenseLightningIndexerSoftmaxLseV2MetadataGetWorkspaceSize failed. ERROR: %d", ret);
if (workspaceSize > static_cast<uint64_t>(0)) {
ret = aclrtMalloc(&workspaceAddr, workspaceSize, ACL_MEM_MALLOC_HUGE_FIRST);
CHECK_LOG_RET(ret == ACL_SUCCESS, ret, "allocate workspace failed. ERROR: %d", ret);
}
ScopeGuard workspaceGuard([&] {
if (workspaceAddr != nullptr) {
aclrtFree(workspaceAddr);
workspaceAddr = nullptr;
}
});
ret = aclnnDenseLightningIndexerSoftmaxLseV2Metadata(workspaceAddr, workspaceSize, executor, stream);
CHECK_LOG_RET(ret == ACL_SUCCESS, ret,
"aclnnDenseLightningIndexerSoftmaxLseV2Metadata failed. ERROR: %d", ret);
ret = aclrtSynchronizeStream(stream);
CHECK_LOG_RET(ret == ACL_SUCCESS, ret, "aclrtSynchronizeStream failed. ERROR: %d", ret);
DenseLISoftmaxLseV2MetaData result {};
ret = aclrtMemcpy(&result, sizeof(result), context.metadata.deviceAddr, sizeof(result), ACL_MEMCPY_DEVICE_TO_HOST);
CHECK_LOG_RET(ret == ACL_SUCCESS, ret, "aclrtMemcpy failed. ERROR: %d", ret);
PrintMetadata(result);
printf("pass\n");
return 0;
}Troubleshooting
- For common execution problems or exceptions of the AI CPU operator Kernel, see "Fault Cases > Operator Execution Issues > AI CPU Operator Kernel Execution Error" in Troubleshooting for the troubleshooting method.