aclnnSparseFlashMlaSoftmaxL1NormMetadata

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 serves as the preceding operator of aclnnSparseFlashMlaSoftmaxL1Norm. It calculates and outputs core-partitioned metadata based on the input shape, layout, mask, and compression ratio of aclnnSparseFlashMlaSoftmaxL1Norm. The output can be used as the metadataOptional input of aclnnSparseFlashMlaSoftmaxL1Norm, reducing host array access in the tiling phase of the main operator.

    This operator is not recommended for standalone use. Use it with aclnnSparseFlashMlaSoftmaxL1Norm to form a complete workflow.

    1. Receives the shape information of the main operator, including batchSize, maxSeqLenQ, maxSeqLenK, numHeadsQ, numHeadsK, headDim, topk, layout, and mask.
    2. 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.
    3. Outputs metadata, which is then used as the metadataOptional input of the aclnnSparseFlashMlaSoftmaxL1Norm operator.

Function Prototype

Each operator uses a two-phase API. You must first call the first-phase API "aclnnSparseFlashMlaSoftmaxL1NormMetadataGetWorkspaceSize" to obtain the workspace size required for computation and the executor containing the operator computation process, and then call the second-phase API "aclnnSparseFlashMlaSoftmaxL1NormMetadata" to execute the computation.

aclnnStatus aclnnSparseFlashMlaSoftmaxL1NormMetadataGetWorkspaceSize(
    const aclTensor *cuSeqLensQOptional,
    const aclTensor *cuSeqLensKOptional,
    const aclTensor *seqUsedQOptional,
    const aclTensor *seqUsedKOptional,
    const aclTensor *cmpResidualKOptional,
    const aclTensor *topkLengthOptional,
    int64_t batchSize,
    int64_t maxSeqLenQ,
    int64_t maxSeqLenK,
    int64_t numHeadsQ,
    int64_t numHeadsK,
    int64_t headDim,
    int64_t topk,
    int64_t cmpRatio,
    int64_t maskMode,
    char *layoutQ,
    char *layoutK,
    const aclTensor *metadata,
    uint64_t *workspaceSize,
    aclOpExecutor **executor);
aclnnStatus aclnnSparseFlashMlaSoftmaxL1NormMetadata(
    void *workspace,
    uint64_t workspaceSize,
    aclOpExecutor *executor,
    aclrtStream stream);

aclnnSparseFlashMlaSoftmaxL1NormMetadataGetWorkspaceSize

  • Parameters

    Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor
    cuSeqLensQOptional Input Indicates the cumulative sequence length of query in different batches.
    Required in the TND use case. The batch count can be derived from the shape of this parameter.
    The first value is fixed to 0.
    Supports empty tensors. INT32 ND 1D, shape (B+1,) x
    cuSeqLensKOptional Input Indicates the cumulative sequence length of key in different batches.
    Required in the TND use case.
    The first value is fixed to 0.
    Supports empty tensors. INT32 ND 1D, shape (B+1,) x
    seqUsedQOptional Input Indicates the sequence length of queries actually used in computation for each batch. Supports empty tensors. When this input parameter is present, the total seq count is calculated by accumulating the seqs actually used in each batch. INT32 ND 1D, shape (B,) x
    seqUsedKOptional Input Indicates the sequence length of the key that actually participates in the computation in each batch. Empty tensors are supported. INT32 ND 1D, shape (B,) x
    cmpResidualKOptional Input Indicates the residual related to cmpRatio for the key sequence length in different batches. Supports empty tensors. Mandatory when maskMode=3 and cmpRatio!=1. INT32 ND 1 dimension, shape (B,) x
    topkLengthOptional Input Indicates the actual selectable topk length of keys corresponding to each row of query. Support empty tensors. Required when maskMode=0 and sparse indices exist. Must be an exact value. INT32 ND 2D or 3D, shape (B,S1,N2) or (T1,N2) x
    batchSize Input Indicates the batch count. Supports non-negative values. In the TND use case, this parameter can be set to 0 and derived through cuSeqLensQOptional. INT64 - - -
    maxSeqLenQ Input Indicates the maximum sequence length of the query. Supports non-negative values. In the BSND use case, this parameter must be a positive number. INT64 - - -
    maxSeqLenK Input Indicates the maximum sequence length of key. Supports non-negative values. Must be a positive value in BSND use cases. INT64 - - -
    numHeadsQ Input Indicates the count of query heads. Value range: [1, 128]. The value must be divisible by numHeadsK. INT64 - - -
    numHeadsK Input Indicates the head count of key. Currently only supports 1. INT64 - - -
    headDim Input Indicates the head dimension of q/k. Currently only supports 512. INT64 - - -
    topk Input Indicates the count of key tokens filtered from key. Supports non-negative values. 0 indicates no sparsity. INT64 - - -
    cmpRatio Input Indicates the compression ratio of key. Value range: [1, 128]. INT64 - - -
    maskMode Input Indicates the sparse mask mode. 0: No mask
    3: Causal
    INT64 - - -
    layoutQ Input Indicates the layout format of query. Supports BSND/TND. The default value is BSND. STRING - - -
    layoutK Input Indicates the layout format of key. Supports BSND/TND. The default value is BSND. STRING - - -
    metadata Output Indicates the load balancing result output. The output is used as the metadataOptional input of aclnnSparseFlashMlaSoftmaxL1Norm. INT32 ND 1 dimension, shape fixed to (64,) x
    workspaceSize Output Returns the workspace size to be allocated on the Device side. The current implementation returns 0. - - - -
    executor Output Returns the op executor containing the operator computation flow. - - - - -
  • Return Value

    aclnnStatus: Return status code. For details, see aclnn return code.

    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 output is a null pointer.
    ACLNN_ERR_PARAM_INVALID 161002 The data type or value of an input parameter is not within the supported value range.

aclnnSparseFlashMlaSoftmaxL1NormMetadata

  • 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 aclnnSparseFlashMlaSoftmaxL1NormMetadataGetWorkspaceSize.
    executor Input op executor that contains the operator computation flow.
    stream Input Stream for task execution.
  • Return Value

    aclnnStatus: Return status code. For details, see aclnn Return Codes.

Constraints

  • Deterministic computation: aclnnSparseFlashMlaSoftmaxL1NormMetadata defaults to a deterministic implementation.

    • 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. Consistency with layoutQ is recommended.
  • head constraints
    • numHeadsQ: range [1, 128].
    • Currently, only numHeadsK = 1 is supported.
    • Currently, only headDim = 512 is supported.
    • numHeadsQ must be divisible by numHeadsK.
  • Load balancing constraint
    • topk supports non-negative values. 0 indicates no sparsity.
    • cmpRatio: range [1, 128].
    • maskMode currently only supports 0 and 3.
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
totalNum 0 Total count of seqs participating in load balancing. For the TND use case, the value is the sum of seqQ across batches. For the BSND use case, the value is B*S. If seqUsedQOptional is present, the value is accumulated based on the seqs actually used by each batch.
formerCoreProcessNum 1 Count of seqs processed by regular cores, that is, ceil(totalNum / totalCoreNum).
remainCoreProcessNum 2 Count of seqs processed by tail cores, that is, floor(totalNum / totalCoreNum).
remainCoreNum 3 Number of tail cores. 0 when totalNum is divisible by totalCoreNum; otherwise totalCoreNum - (totalNum % totalCoreNum).
totalCoreNum 4 Number of AIC cores actually used, min(totalNum, aicCoreNum, 36).

Strided partitioning is used. The seq indexes processed by a core step by totalCoreNum across cores. For example, if totalNum=72 and totalCoreNum=36, core 0 processes seq[0] and seq[36], core 1 processes seq[1] and seq[37], and so on.

Example

The following sample code is for reference only. For details about compilation and execution, 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_sparse_flash_mla_softmax_l1_norm_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 SMLA_METADATA_SIZE = 64;

struct SmlaSoftmaxL1NormMetaData {
    int32_t totalNum;
    int32_t formerCoreProcessNum;
    int32_t remainCoreProcessNum;
    int32_t remainCoreNum;
    int32_t totalCoreNum;
};

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 topkLengthOptional {};
    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 { 512 };
    int64_t topk { 64 };
    char *layoutQ { nullptr };
    char *layoutK { nullptr };
    int64_t maskMode { 3 };
    int64_t cmpRatio { 1 };
};

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);
    DestroyTensor(context.topkLengthOptional);

    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, { SMLA_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;
    }

    argsGuard.Dismiss();
    return ACL_SUCCESS;
}

void PrintMetadata(const SmlaSoftmaxL1NormMetaData &metadata)
{
    printf("totalNum             : %d\n", metadata.totalNum);
    printf("formerCoreProcessNum: %d\n", metadata.formerCoreProcessNum);
    printf("remainCoreProcessNum: %d\n", metadata.remainCoreProcessNum);
    printf("remainCoreNum       : %d\n", metadata.remainCoreNum);
    printf("totalCoreNum        : %d\n", metadata.totalCoreNum);
}

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 = aclnnSparseFlashMlaSoftmaxL1NormMetadataGetWorkspaceSize(
        context.cuSeqLensQOptional.data, context.cuSeqLensKOptional.data, context.seqUsedQOptional.data,
        context.seqUsedKOptional.data, context.cmpResidualKOptional.data, context.topkLengthOptional.data,
        context.batchSize, context.maxSeqLenQ, context.maxSeqLenK, context.numHeadsQ, context.numHeadsK,
        context.headDim, context.topk, context.cmpRatio, context.maskMode, context.layoutQ, context.layoutK,
        context.metadata.data, &workspaceSize, &executor);
    CHECK_LOG_RET(ret == ACL_SUCCESS, ret,
        "aclnnSparseFlashMlaSoftmaxL1NormMetadataGetWorkspaceSize 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 = aclnnSparseFlashMlaSoftmaxL1NormMetadata(workspaceAddr, workspaceSize, executor, stream);
    CHECK_LOG_RET(ret == ACL_SUCCESS, ret,
        "aclnnSparseFlashMlaSoftmaxL1NormMetadata failed. ERROR: %d", ret);

    ret = aclrtSynchronizeStream(stream);
    CHECK_LOG_RET(ret == ACL_SUCCESS, ret, "aclrtSynchronizeStream failed. ERROR: %d", ret);

    SmlaSoftmaxL1NormMetaData 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);

    return 0;
}

Troubleshooting