aclnnGenericBlockSparseAttentionGradMetadata

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: aclnnGenericBlockSparseAttentionGradMetadata performs partitioning and load balancing for sparse attention based on information such as sparseBlockIdx, sparseBlockCount, and seqlen. It is a preceding AICPU operator of aclnnGenericBlockSparseAttentionGrad. It expands the (b, n2, j, g) task list in the order of B → N2 → J → G and performs greedy load balancing across AIC cores at the [baseM, baseN] = [128, 128] basic block granularity, outputting metadata for the main Grad operator to consume.
  • This operator is not recommended for standalone use. It is recommended to use it with aclnnGenericBlockSparseAttentionGrad to form a complete workflow.
$$ \text{metaSize} = 80 + B \times N1 \times J \times 4 $$

where J = ceilDiv(maxKvSeqlen, blockShapeY).

Function Prototype

Each operator uses a two-phase API. Call the "aclnnGenericBlockSparseAttentionGradMetadataGetWorkspaceSize" API first to obtain the workspace size required for computation and the executor that contains the operator computation process, and then call the "aclnnGenericBlockSparseAttentionGradMetadata" API to execute the computation.

aclnnStatus aclnnGenericBlockSparseAttentionGradMetadataGetWorkspaceSize(
    const aclTensor *sparseBlockIdx,
    const aclTensor *sparseBlockCount,
    const aclTensor *cuSeqLengthsQOptional,
    const aclTensor *cuSeqLengthsKvOptional,
    const aclTensor *sequsedQOptional,
    const aclTensor *sequsedKvOptional,
    int64_t maxQSeqlen,
    int64_t maxKvSeqlen,
    int64_t numQHeads,
    int64_t numKvHeads,
    int64_t headDim,
    const aclIntArray *blockShape,
    char *layoutQ,
    char *layoutKv,
    int64_t layoutSparsePattern,
    int64_t maskType,
    int64_t softmaxPrecision,
    int64_t winLeft,
    int64_t winRight,
    int64_t residualBlockMode,
    bool isConsistentTopk,
    aclTensor *metadata,
    uint64_t *workspaceSize,
    aclOpExecutor **executor)
aclnnStatus aclnnGenericBlockSparseAttentionGradMetadata(
    void *workspace,
    uint64_t workspaceSize,
    aclOpExecutor *executor,
    aclrtStream stream)

aclnnGenericBlockSparseAttentionGradMetadataGetWorkspaceSize

  • Parameters

    Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor
    sparseBlockIdx Input Sparse block index array, specifying the Q block/token indices selected for each KV block. Refer to layout correspondence. Does not support empty tensors. INT32 ND TND: [B, N2, ceilDiv(maxS2, blockShapeY), maxS1]; BNSD/BSND: [B, N2, ceilDiv(S2, blockShapeY), S1] √
    sparseBlockCount Input Specifies the number of Q blocks actually selected for each KV block. Refer to layout correspondence description. Does not support empty tensor. INT32 ND [B, N2, ceilDiv(maxS2, blockShapeY)] or [B, N2, ceilDiv(S2, blockShapeY)] √
    cuSeqLengthsQOptional Optional input Prefix sum of query sequence lengths corresponding to each batch. Must be configured when layoutQ is "TND"; pass nullptr when layoutQ is "BNSD" or "BSND". INT64 ND [B+1] -
    cuSeqLengthsKvOptional Optional input Prefix sum of key/value sequence lengths for each batch. Must be configured when layoutKv is "TND"; pass nullptr when layoutKv is "BNSD" or "BSND". INT64 ND [B+1] -
    sequsedQOptional Optional input Actual sequence length of the query in each batch. Takes effect only when layoutQ is "TND"; nullptr must be passed when layoutQ is "BNSD" or "BSND", and the actual length is consistent with the S dimension of maxQSeqlen/query. The length is B. INT32 ND [B] √
    sequsedKvOptional Optional input Actual sequence lengths of kv in each batch. Takes effect when layoutKv is "TND"; must pass nullptr when layoutKv is "BNSD" or "BSND", in which case the actual length is taken from maxKvSeqlen (must be consistent with the S dimension of key/value). Length: B. INT32 ND [B] √
    maxQSeqlen Input Maximum value of qSeqlen across all batches. Must be ≥0. In BNSD/BSND use cases, must be consistent with the S dimension of query. INT64 - - -
    maxKvSeqlen Input Maximum value of kvSeqlen across all batches. Must be ≥0. Used to compute J = ceilDiv(maxKvSeqlen, blockShapeY). INT64 - - -
    numQHeads Input Number of query heads (N1). Must fall within [1, 128] and be divisible by numKvHeads. INT64 - - -
    numKvHeads Input Number of heads (N2) of key/value. Must fall within [1, 128] and must be consistent with the N2 dimension of sparseBlockIdx. INT64 - - -
    headDim Input Embedding dimension of query/key/value. Currently fixed to 128. INT64 - - -
    blockShape Input Sparse block shape array. Contains two elements [blockShapeX, blockShapeY]. blockShapeX currently only supports 1; blockShapeY must be ≥128 and a multiple of 64. INT64 - - -
    layoutQ Input Data layout format of the input query. Currently supports "TND", "BNSD", and "BSND". STRING - - -
    layoutKv Input Data layout format of the input key and value. Currently supports "TND", "BNSD", "BSND" and must be consistent with layoutQ. STRING - - -
    layoutSparsePattern Input Represents the data layout format of the input sparseBlockIdx and sparseBlockCount. Currently only supports the value "1". For details, refer to layout correspondence description. INT64 - - -
    maskType Input Mask type in the attention computation. Currently only supports 1 (CAUSAL). INT64 - - -
    softmaxPrecision Input Precision level used for the Softmax computation. Currently only supports 0. INT64 - - -
    winLeft Input Number of tokens included in the sliding window in the forward direction. Must be -1 when disabled. INT64 - - -
    winRight Input Number of tokens included backward in the sliding window. Must be -1 when disabled. INT64 - - -
    residualBlockMode Input Indicates the state of the tail incomplete block after the KV sequence is sparsified in units of blockShapeY. Currently only supports the value 0, indicating that whether the tail incomplete block participates in the computation is determined by the value passed in via sparseBlockIdx. The value 1 indicates that the tail incomplete block must participate in the computation but must not be included in sparseBlockIdx, which is currently not supported. INT64 - - -
    isConsistentTopk Input Whether the maximum number of KV blocks selected by each Q block within the same batch and head is consistent when the preceding operator performs sparse block selection. Only 0 or 1 is supported. 0 indicates inconsistency and 1 indicates consistency. Currently, both values use the generic implementation calculated based on the actual sparse indices and quantities. BOOL - - -
    metadata Output Partition information of sparse attention. Does not support empty Tensor. metaSize ≥ 80 + B×N1×J×4. INT32 ND [metaSize] ×
    workspaceSize Output Returns the workspace size that needs to be applied on the Device side. - - - - -
    executor 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_INNER_CREATE_EXECUTOR 561101 Failed to create aclOpExecutor.
    ACLNN_ERR_INNER_NULLPTR 561103 workspaceSize or executor is a null pointer.
    ACLNN_ERR_PARAM_INVALID 161002 sparseBlockIdx/sparseBlockCount/metadata is empty or shape/dtype is invalid.
    cuSeqLengths is not provided when layout is TND; headDim, blockShape, layoutSparsePattern, residualBlockMode, isConsistentTopk, and window are not in the supported range.
    The J dimension of sparseBlockIdx is inconsistent with ceilDiv(maxKvSeqlen, blockShapeY); the metadata length is insufficient; B×N1×J exceeds the upper limit of task count (1M).

aclnnGenericBlockSparseAttentionGradMetadata

  • Parameters

    Parameter Input/Output Description
    workspace Input workspace memory address applied on the Device side.
    workspaceSize Input workspace size applied on the Device side, obtained by the first-phase API aclnnGenericBlockSparseAttentionGradMetadataGetWorkspaceSize.
    executor Input Executor of the op, containing the operator computation flow.
    stream Input Specifies the Stream for executing tasks.
  • Return Value

    aclnnStatus: Return value. For details, see aclnn return codes.

Constraints

  • The layoutSparsePattern, residualBlockMode, and isConsistentTopk settings in Grad and GradMetadata calls must be consistent. Currently only layoutSparsePattern=1 and residualBlockMode=0 are supported.

  • Deterministic computation:

    • The output of this operator is deterministic.
  • Must be used together with aclnnGenericBlockSparseAttentionGrad. This operator must be successfully executed before the main operator is called.

  • HeadDim is fixed to 128; numQHeads/numKvHeads must be in the range [1, 128], and numQHeads % numKvHeads == 0.

  • blockShape currently only supports [1, 128]; layoutSparsePattern currently only supports 1; maskType currently only supports 1.

  • layoutQ and layoutKv must be the same, with the value "TND"/"BNSD"/"BSND"; cuSeqLengthsQOptional/cuSeqLengthsKvOptional are mandatory when the layout is TND.

  • sequsedQOptional/sequsedKvOptional take effect only for TND; nullptr must be passed for BNSD/BSND, and the actual sequence length is taken from maxQSeqlen/maxKvSeqlen (which must be the same as the S dimension of Q/K).

  • winLeft and winRight must be -1 when not enabled.

  • The last dimension maxS1 of sparseBlockIdx must be ≥ maxQSeqlen; J = ceilDiv(maxKvSeqlen, blockShapeY) must be the same as the 3rd dimension of sparseBlockIdx.

  • The length of metadata must satisfy shape[0] ≥ 80 + B × numQHeads × J × 4; the upper bound of the number of tasks is B × numQHeads × J ≤ 1048576.

Example

The following sample code is for reference only. For details about compilation and execution, refer to Compile and Run Samples.

#include <cmath>
#include <cstdint>
#include <iostream>
#include <vector>
#include "acl/acl.h"
#include "aclnnop/aclnn_generic_block_sparse_attention_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 n = 1;
    for (auto v : shape) {
        n *= v;
    }
    return n;
}

int Init(int32_t deviceId, 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 = 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 = 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 Finalize(int32_t deviceId, aclrtStream stream)
{
    aclrtDestroyStream(stream);
    aclrtResetDevice(deviceId);
    aclFinalize();
}

int main()
{
    int32_t deviceId = 0;
    aclrtStream stream = nullptr;
    auto ret = Init(deviceId, &stream);
    CHECK_RET(ret == ACL_SUCCESS, return ret);

    const int64_t B = 1, N1 = 1, N2 = 1, S1 = 128, S2 = 128, D = 128;
    const int64_t blockY = 128;
    const int64_t J = (S2 + blockY - 1) / blockY;
    const int64_t metaSize = 80 + B * N1 * J * 4;

    std::vector<int64_t> idxShape = {B, N2, J, S1};
    std::vector<int64_t> cntShape = {B, N2, J};
    std::vector<int64_t> metaShape = {metaSize};

    std::vector<int32_t> idxHost(static_cast<size_t>(GetShapeSize(idxShape)), -1);
    std::vector<int32_t> cntHost(static_cast<size_t>(GetShapeSize(cntShape)), 0);
    std::vector<int32_t> metaHost(static_cast<size_t>(metaSize), 0);
    for (int64_t q = 0; q < S1; ++q) {
        idxHost[static_cast<size_t>(q)] = static_cast<int32_t>(q);
    }
    cntHost[0] = static_cast<int32_t>(S1);

    void *idxAddr = nullptr, *cntAddr = nullptr, *metaAddr = nullptr;
    aclTensor *idx = nullptr, *cnt = nullptr, *metadata = nullptr;
    ret = CreateAclTensor(idxHost, idxShape, &idxAddr, aclDataType::ACL_INT32, &idx);
    CHECK_RET(ret == ACL_SUCCESS, Finalize(deviceId, stream); return ret);
    ret = CreateAclTensor(cntHost, cntShape, &cntAddr, aclDataType::ACL_INT32, &cnt);
    CHECK_RET(ret == ACL_SUCCESS, Finalize(deviceId, stream); return ret);
    ret = CreateAclTensor(metaHost, metaShape, &metaAddr, aclDataType::ACL_INT32, &metadata);
    CHECK_RET(ret == ACL_SUCCESS, Finalize(deviceId, stream); return ret);

    const int64_t blockShapeData[] = {1, blockY};
    aclIntArray *blockShape = aclCreateIntArray(blockShapeData, 2);
    char layout[] = "BNSD";

    uint64_t wsSize = 0;
    aclOpExecutor *executor = nullptr;
    ret = aclnnGenericBlockSparseAttentionGradMetadataGetWorkspaceSize(
        idx, cnt, nullptr, nullptr, nullptr, nullptr, S1, S2, N1, N2, D, blockShape, layout, layout, 1, 1, 0, -1, -1, 0, 0,
        metadata, &wsSize, &executor);
    CHECK_RET(ret == ACL_SUCCESS, Finalize(deviceId, stream); return ret);

    void *ws = nullptr;
    if (wsSize > 0) {
        ret = aclrtMalloc(&ws, wsSize, ACL_MEM_MALLOC_HUGE_FIRST);
        CHECK_RET(ret == ACL_SUCCESS, Finalize(deviceId, stream); return ret);
    }
    ret = aclnnGenericBlockSparseAttentionGradMetadata(ws, wsSize, executor, stream);
    CHECK_RET(ret == ACL_SUCCESS, Finalize(deviceId, stream); return ret);
    ret = aclrtSynchronizeStream(stream);
    CHECK_RET(ret == ACL_SUCCESS, Finalize(deviceId, stream); return ret);

    LOG_PRINT("GenericBlockSparseAttentionGradMetadata finished successfully.\n");

    aclDestroyIntArray(blockShape);
    aclDestroyTensor(idx);
    aclDestroyTensor(cnt);
    aclDestroyTensor(metadata);
    aclrtFree(idxAddr);
    aclrtFree(cntAddr);
    aclrtFree(metaAddr);
    if (wsSize > 0) {
        aclrtFree(ws);
    }
    Finalize(deviceId, stream);
    return 0;
}