aclnnDenseLightningIndexerKLLossGradMetadata

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 aclnnDenseLightningIndexerKLLossGrad. Based on the input shape, layout, mask, and compression ratio information of the aclnnDenseLightningIndexerKLLossGrad operator, this operator computes and outputs the core-splitting metadata. The output can be used as the metadataOptional input of the aclnnDenseLightningIndexerKLLossGrad operator, reducing host array access in the tiling phase of the main operator.

    This operator is not recommended for standalone use. It is recommended to use it together with the aclnnDenseLightningIndexerKLLossGrad operator to form a complete workflow.

    1. Receive the shape information of the main operator, including batchSize, maxSeqLenQ, maxSeqLenK, numHeadsQ, numHeadsK, headDim, layout, and mask information.
    2. Estimate the load based on the valid sequence length of each query, and evenly split the tasks with merged B/S1 axes across the available AIC cores.
    3. After the metadata is output, it is used later as the metadataOptional input of the aclnnDenseLightningIndexerKLLossGrad operator.

Function Prototype

Each operator uses a two-phase API. First call "aclnnDenseLightningIndexerKLLossGradMetadataGetWorkspaceSize" to obtain the workspace size, and then call "aclnnDenseLightningIndexerKLLossGradMetadata" to execute the computation.

aclnnStatus aclnnDenseLightningIndexerKLLossGradMetadataGetWorkspaceSize(
    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 aclnnDenseLightningIndexerKLLossGradMetadata(
    void           *workspace,
    uint64_t        workspaceSize,
    aclOpExecutor  *executor,
    aclrtStream     stream)

aclnnDenseLightningIndexerKLLossGradMetadataGetWorkspaceSize

  • 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.
    • Supports empty tensor.
    • Mandatory in the TND use case. The batch can be derived from the shape of this input.
    • The first value is fixed to 0.
    • The shape is fixed to (B+1, ).
    INT32 ND 1-D, shape (B+1,) ×
    cuSeqLensKOptional (const aclTensor*) Input Indicates the cumulative sequence length of key in different batches.
    • Supports empty tensor
    • Required in the TND use case.
    • The first value is fixed to 0.
    • The shape is fixed to (B+1, ).
    INT32 ND 1D with shape (B+1,) ×
    seqUsedQOptional(const aclTensor*) Input Indicates the actual sequence length of the query participating in computation in different batches.
    • Supports empty tensor.
    • The shape is fixed to (B, ).
    INT32 ND 1D, shape (B,) ×
    seqUsedKOptional (const aclTensor*) Input Indicates the sequence length of keys that actually participate in computation in different batches.
    • Empty tensors are supported.
    • The shape is fixed to (B, ).
    INT32 ND 1D, shape (B,) ×
    cmpResidualKOptional (const aclTensor*) Input Indicates the residual related to the sequence length of keys in different batches and cmpRatio.
    • Supports empty tensors.
    • Shape is fixed to (B, ).
    INT32 ND 1-D, shape (B,) ×
    batchSize (int64_t) Input Indicates the batch quantity.
    • Supports non-negative values. In TND use cases, it can be set to 0 and derived through cuSeqLensQOptional.
    • The recommended value is 0.
    - - - -
    maxSeqLenQ (int64_t) Input Indicates the maximum sequence length of query.
    • Supports non-negative values. The value must be positive in the BSND use case.
    • The recommended value is 0.
    - - - -
    maxSeqLenK (int64_t) Input Indicates the maximum sequence length of key.
    • Supports non-negative values. The value must be positive in the BSND use case.
    • The recommended value is 0.
    - - - -
    numHeadsQ (int64_t) Input Indicates the number of query heads. Must be positive and divisible by numHeadsK. Currently supports [1, 128]. - - - -
    numHeadsK (int64_t) Input Indicates the number of heads of the 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 format of the query side.
    • Supports BSND and TND.
    • The recommended value is BSND.
    - - - -
    layoutK (char*) Input Indicates the layout format on the key side.
    • Supports BSND and TND.
    • The recommended value is BSND.
    - - - -
    maskMode (int64_t) Input Indicates the mask mode.
    • 0: No mask.
    • 3: mask of the rightDownCausal mode, corresponding to the lower triangular scenario divided by the right vertex.
    • The recommended value is 0.
    - - - -
    cmpRatio (int64_t) Input Indicates the compression ratio of key.
    • Value range: [1, 128]
    • The recommended value is 1, indicating no compression.
    - - - -
    metadata (const aclTensor*) Output Indicates the load balancing result output. The output result is used as the metadataOptional input of aclnnDenseLightningIndexerKLLossGrad. INT32 ND 1D, shape fixed to (64,) ×
    workspaceSize (uint64_t*) Output Returns the workspace size required for Device side application. - - - - -
    executor (aclOpExecutor**) Output Returns the op executor containing 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 Code Description
    ACLNN_ERR_INNER_NULLPTR 561103 workspaceSize or executor is a null pointer.
    ACLNN_ERR_PARAM_INVALID 161002 The data type or dimensions of cuSeqLensQOptional, cuSeqLensKOptional, seqUsedQOptional, seqUsedKOptional, or cmpResidualKOptional are not within the supported range.
    metadata is a null pointer, or its data type, dimensions, or shape is not within the supported range.
    numHeadsQ, numHeadsK, or headDim is not within the supported range.
    layoutQ or layoutK is a null pointer, or is not within the supported range.
    batchSize, maxSeqLenQ, maxSeqLenK, maskMode, or cmpRatio does not satisfy the value constraints.
    In the TND use case, the corresponding cuSeqLensQOptional or cuSeqLensKOptional is not passed in, or cmpResidualKOptional is not passed in when maskMode=3 and cmpRatio is not 1.
    The batch quantities derived from query, key, or cmpResidualKOptional are inconsistent.

aclnnDenseLightningIndexerKLLossGradMetadata

  • Parameters

    Parameter Input/Output Description
    workspace Input Workspace memory address allocated on the Device side.
    workspaceSize Input Size of the workspace allocated on the Device side, obtained by calling the first-phase API aclnnDenseLightningIndexerKLLossGradMetadataGetWorkspaceSize.
    executor Input op executor, which contains the operator computation flow.
    stream Input Stream used to execute tasks.
  • Return Value

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

Constraints

  • Deterministic computation: aclnnDenseLightningIndexerKLLossGradMetadata defaults to a deterministic implementation.
  • BSND scenario
    • batchSize, maxSeqLenQ, and maxSeqLenK must be passed to obtain shape information.
  • TND scenario
    • Pass the 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, numHeadsK, and headDim must be positive.
    • numHeadsQ must be divisible by numHeadsK.
  • dense constraints
    • 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
totalSize 0 Total number of task rows after combining the B/S1 axes.
formerCoreSize 1 Core-splitting granularity in the up-alignment use case.
remainCoreSize 2 Core-splitting granularity in the down-alignment use case.
remainCoreNum 3 Quantity of cube cores processing remainCoreSize.
usedCoreNum 4 Quantity of cube cores actually used by the main kernel.
maxSeqK 5 Maximum sequence length of key.
reserved 6-63 Reserved field, currently set to 0.

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_dense_lightning_indexer_kl_loss_grad_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_MAX_CORE_NUM = 25;
constexpr uint32_t DLI_METADATA_HEADER_SIZE = 8;
constexpr uint32_t DLI_METADATA_SIZE = 64;

struct DliGradKLLossMetaData {
    int32_t coreNum;
    int32_t totalSize;
    int32_t splitFactorSize;
    int32_t reserved[DLI_METADATA_HEADER_SIZE - 3];
    int32_t bS1Index[DLI_METADATA_MAX_CORE_NUM];
};

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 { 0 };
    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;
    }

    argsGuard.Dismiss();
    return ACL_SUCCESS;
}

void PrintMetadata(const DliGradKLLossMetaData &metadata)
{
    printf("coreNum          : %d\n", metadata.coreNum);
    printf("totalSize        : %d\n", metadata.totalSize);
    printf("splitFactorSize  : %d\n", metadata.splitFactorSize);
    for (uint32_t i = 0; i < std::min<uint32_t>(metadata.coreNum, DLI_METADATA_MAX_CORE_NUM); ++i) {
        printf("bS1Index[%u]      : %d\n", i, metadata.bS1Index[i]);
    }
}

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 = aclnnDenseLightningIndexerKLLossGradMetadataGetWorkspaceSize(
        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,
        "aclnnDenseLightningIndexerKLLossGradMetadataGetWorkspaceSize 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 = aclnnDenseLightningIndexerKLLossGradMetadata(workspaceAddr, workspaceSize, executor, stream);
    CHECK_LOG_RET(ret == ACL_SUCCESS, ret,
        "aclnnDenseLightningIndexerKLLossGradMetadata failed. ERROR: %d", ret);

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

    DliGradKLLossMetaData 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