aclnnNsaSelectedAttentionGrad

Applicable Products

  • Ascend 950PR&950DT products: Not supported
  • Atlas A3 products: Not supported
  • Atlas A2 products: Supported
  • Atlas 200I/500 A2 inference products: Not supported
  • Atlas inference products: Not supported
  • Atlas training products: Not supported

Function

  • Description: Rearranges data of a selected size (selectedBlockSize) from key and value based on topkIndices, and then computes the backward output of attention in training scenarios.

  • Formula:

    Rearranges data of selectedBlockCount blocks, each of size selectedBlockSize, from key and value based on the input topkIndices. The formula is as follows:

    $$ selectedKey = Gather(key, topkIndices[i]),0<=i<selectedBlockCount \\ selectedValue = Gather(value, topkIndices[i]),0<=i<selectedBlockCount $$

    Then, the backward computation of the attention mechanism is performed. The formula is:

    $$ dV=P^TdY $$
    $$ dQ=\frac{((dS)*K)}{\sqrt{d}} $$
    $$ dK=\frac{((dS)^T*Q)}{\sqrt{d}} $$

Function Prototype

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

aclnnStatus aclnnNsaSelectedAttentionGradGetWorkspaceSize(
  const aclTensor   *query,
  const aclTensor   *key,
  const aclTensor   *value,
  const aclTensor   *attentionOut,
  const aclTensor   *attentionOutGrad,
  const aclTensor   *softmaxMax,
  const aclTensor   *softmaxSum,
  const aclTensor   *topkIndices,
  const aclIntArray *actualSeqQLenOptional,
  const aclIntArray *actualSeqKvLenOptional,
  const aclTensor   *attenMaskOptional,
  double             scaleValue,
  int64_t            selectedBlockSize,
  int64_t            selectedBlockCount,
  int64_t            headNum,
  char              *inputLayout,
  int64_t            sparseMode,
  const aclTensor         *dqOut,
  const aclTensor         *dkOut,
  const aclTensor         *dvOut,
  uint64_t          *workspaceSize,
  aclOpExecutor    **executor)
aclnnStatus aclnnNsaSelectedAttentionGrad(
  void          *workspace,
  uint64_t       workspaceSize,
  aclOpExecutor *executor,
  aclrtStream    stream);

aclnnNsaSelectedAttentionGradGetWorkspaceSize

  • Parameters

    Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor
    query Input query in the formula. - BFLOAT16, FLOAT16 ND 3 √
    key Input key in the formula. - BFLOAT16, FLOAT16 ND 3-4 √
    value Input Value in the formula. - BFLOAT16, FLOAT16 ND 3 √
    attentionOut Input Final output of the forward attention computation. - BFLOAT16, FLOAT16 ND 3 √
    attentionOutGrad Input dY in the formula. - BFLOAT16, FLOAT16 ND 3 √
    softmaxMax Input Max intermediate result of the Softmax computation. Used for backward computation. FLOAT ND 3 √
    softmaxSum Input Sum intermediate result of the Softmax computation. Used for backward computation. FLOAT ND 3 √
    topkIndices Input topk_indices in the formula. - INT32 ND 3 √
    attenMaskOptional Input atten_mask in the formula. - BOOL, UINT8 ND 2 √
    actualSeqQLenOptional Input Cumulative S length of each batch in query. - INT64 ND 1 -
    actualSeqKvLenOptional Input Cumulative length of S for each batch in key/value. - INT64 ND 1 -
    scaleValue Input Scaling factor scale. Generally D^-0.5. DOUBLE - - -
    headNum Input Number of heads. - INT64 - - -
    inputLayout Input Data layout format of query/key/value. Currently, only TND is supported. String - - -
    selectedBlockSize Input Length of each block. - INT64 - - -
    selectedBlockCount Input Number of select blocks. - INT64 - - -
    sparseMode Input Sparse mode. Supports 0 or 2. INT64 - - -
    dqOut Output dQ in the formula, indicating the gradient of query. - FLOAT16, BFLOAT16, FLOAT32 ND [BNSD], [BSND], [BSH], [SBH] √
    dkOut Output dK in the formula, indicating the gradient of keyIn. - FLOAT16, BFLOAT16, FLOAT32 ND [BNSD], [BSND], [BSH], [SBH] √
    dvOut Output dV in the formula, indicating the gradient of value. - FLOAT16, BFLOAT16, FLOAT32 ND [BNSD], [BSND], [BSH], [SBH] √
    workspaceSize Output Returns the workspace size to be applied by the Device side. - - - - -
    executor Output Returns the op executor, which contains 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_PARAM_NULLPTR 161001 The parameter is a required input, output, or attribute and is a null pointer.
    ACLNN_ERR_PARAM_INVALID 161002 The data types of query, key, value, attentionOut, attentionOutGrad, softmaxMax, softmaxSum, topkIndices, attenMaskOptional, actualSeqQLenOptional, actualSeqKvLenOptional, dqOut, dkOut, and dvOut are not in the supported range.
    The data formats of query, key, value, attentionOut, attentionOutGrad, softmaxMax, softmaxSum, topkIndices, attenMaskOptional, actualSeqQLenOptional, actualSeqKvLenOptional, dqOut, dkOut, and dvOut are not in the supported range.

aclnnNsaSelectedAttentionGrad

  • Parameters

    Parameter Input/Output Description
    workspace Input Workspace memory address applied by the Device side.
    workspaceSize Input Workspace size applied by the Device side, obtained by the first-phase API aclnnNsaSelectedAttentionGradGetWorkspaceSize.
    executor Input Op executor, which contains the computation process of the operator.
    stream Input Specifies the Stream for task execution.
  • Return Value

    Returns the aclnnStatus status code. For details, see aclnn Return Code.

Constraints

  • Deterministic computation:
    • aclnnNsaSelectedAttentionGrad defaults to a non-deterministic implementation. Deterministic computation can be enabled by calling aclrtCtxSetSysParamOpt.
  • When using this API with PyTorch, ensure that the versions of CANN-related packages and PyTorch-related packages are compatible.
  • The B (batchsize) of the input query, key, value, attentionOut, and attentionOutGrad must be equal.
  • The N (numHead) of the input key and value must be consistent.
  • The N (numHead) of the input query, attentionOut, and attentionOutGrad must be consistent.
  • The D (HeadDim) of the input value, attentionOut, and attentionOutGrad must be consistent.
  • The inputLayout of the input query, key, value, attentionOut, and attentionOutGrad must be consistent.
  • For constraints on data shape, take TND of inputLayout as an example, where:
    • T1: Value range: 1 to 2M. T1 represents the sum of S across all batches of query.
    • T2: Value range: 1 to 2M. T2 represents the sum of S across all batches of key and value.
    • B: Value range: 1 to 2M.
    • N1: Value range: 1 to 128. Represents the headNum of query. N1 must be an integer multiple of N2.
    • N2: Value range: 1 to 128. Represents the headNum of key and value.
    • G: value range is 1 to 32. G = N1 / N2
    • S: value range is 1~128K. For key, value, S must be greater than or equal to selectedBlockSize * selectedBlockCount, and must be an integer multiple of selectedBlockSize.
    • D: value range is 192 or 128. Supports unequal D (HeadDim) for K and V.
    • selectedBlockSize supports ≤ 128 and must be an integer multiple of 16.
    • selectedBlockCount: Supported range is [1-128]. The total selected size selectedBlockCount * selectedBlockSize < 128 * 64(8K)
    • When Layout is TND, S2 of each batch must be greater than the total selected size selectedBlockCount * selectedBlockSize.
  • Constraints on the shape of the softmaxMax and softmaxSum parameters: [T1, N1, 8].
  • Constraints on the shape of the topkIndices parameter: [T1, N2, selectedBlockCount].

Example

The sample code is as follows, for reference only. For details about compilation and execution, see Compile and Run Samples.

#include <iostream>
#include <vector>
#include "acl/acl.h"
#include "aclnnop/aclnn_nsa_selected_attention_grad.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;
}

int Init(int32_t deviceId, aclrtStream* stream) {
    // Boilerplate code, resource initialization.
    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);
    // Call aclrtMalloc to allocate memory on the Device side.
    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);

    // Call aclrtMemcpy to copy Host-side data to Device-side memory.
    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);

    // Calculate the strides of the contiguous tensor.
    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];
    }

    // Call the aclCreateTensor API to create an aclTensor.
    *tensor = aclCreateTensor(shape.data(), shape.size(), dataType, strides.data(), 0, aclFormat::ACL_FORMAT_NCHW,
                            shape.data(), shape.size(), *deviceAddr);
    return 0;
}

int main() {
    // 1. (Boilerplate) Initialize the device/stream. For details, see the AscendCL API list.
    // Fill in deviceId based on the actual device.
    int32_t deviceId = 0;
    aclrtStream stream;
    auto ret = Init(deviceId, &stream);
    // Handle the check as needed.
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("Init acl failed. ERROR: %d\n", ret); return ret);

    // 2. Construct the input and output. The construction is custom based on the API.
    int64_t b = 1;
    int64_t s1 = 1;
    int64_t s2 = 1024;
    int64_t t1 = b * s1;
    int64_t t2 = b * s2;
    int64_t n1 = 1;
    int64_t n2 = 1;
    int64_t d = 192;

    int64_t sparseMode = 0;
    char inputLayout[5] = {'T', 'N', 'D', 0};
    double scaleValue = 1.0f;
    int64_t selectedBlockSize = 64;
    int64_t selectedBlockCount = 16;
    int32_t headNum = n1;

    std::vector<int64_t> queryShape = {t1, n1, d};
    std::vector<int64_t> keyShape = {t2, n2, d};
    std::vector<int64_t> valueShape = {t2, n2, d};
    std::vector<int64_t> attentionOutShape = {t1, n1, d};
    std::vector<int64_t> attentionOutGradShape = {t1, n1, d};
    std::vector<int64_t> softmaxMaxShape = {t1, n1, 8};
    std::vector<int64_t> softmaxSumShape = {t1, n1, 8};
    std::vector<int64_t> topkIndicesShape = {t1, n2, selectedBlockCount};
    std::vector<int64_t> actualSeqQLenOptionalShape = {b};
    std::vector<int64_t> actualSeqKvLenOptionalShape = {b};
    std::vector<int64_t> dqOutShape = {t1, n1, d};
    std::vector<int64_t> dkOutShape = {t2, n2, d};
    std::vector<int64_t> dvOutShape = {t2, n2, d};

    void* queryDeviceAddr = nullptr;
    void* keyDeviceAddr = nullptr;
    void* valueDeviceAddr = nullptr;
    void* attentionOutDeviceAddr = nullptr;
    void* attentionOutGradDeviceAddr = nullptr;
    void* softmaxMaxDeviceAddr = nullptr;
    void* softmaxSumDeviceAddr = nullptr;
    void* topkIndicesDeviceAddr = nullptr;
    void* dqOutDeviceAddr = nullptr;
    void* dkOutDeviceAddr = nullptr;
    void* dvOutDeviceAddr = nullptr;

    aclTensor* query = nullptr;
    aclTensor* key = nullptr;
    aclTensor* value = nullptr;
    aclTensor* attentionOut = nullptr;
    aclTensor* attentionOutGrad = nullptr;
    aclTensor* softmaxMax = nullptr;
    aclTensor* softmaxSum = nullptr;
    aclTensor* topkIndices = nullptr;
    aclTensor* dqOut = nullptr;
    aclTensor* dkOut = nullptr;
    aclTensor* dvOut = nullptr;

    std::vector<aclFloat16> queryHostData(GetShapeSize(queryShape), 2);
    std::vector<aclFloat16> keyHostData(GetShapeSize(keyShape), 2);
    std::vector<aclFloat16> valueHostData(GetShapeSize(valueShape), 2);
    std::vector<aclFloat16> attentionOutHostData(GetShapeSize(attentionOutShape), 2);
    std::vector<aclFloat16> attentionOutGradHostData(GetShapeSize(attentionOutGradShape), 2);
    std::vector<float> softmaxMaxHostData(GetShapeSize(softmaxMaxShape), 2);
    std::vector<float> softmaxSumHostData(GetShapeSize(softmaxSumShape), 2);
    std::vector<int32_t> topkIndicesHostData(GetShapeSize(topkIndicesShape), 1);
    std::vector<aclFloat16> dqOutHostData(GetShapeSize(dqOutShape), 2);
    std::vector<aclFloat16> dkOutHostData(GetShapeSize(dkOutShape), 2);
    std::vector<aclFloat16> dvOutHostData(GetShapeSize(dvOutShape), 2);

    for (int32_t i = 0; i < topkIndicesHostData.size(); i++) {
        topkIndicesHostData[i] = i;
    }

    // Create the query aclTensor.
    ret = CreateAclTensor(queryHostData, queryShape, &queryDeviceAddr, aclDataType::ACL_FLOAT16, &query);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    // Create the key aclTensor.
    ret = CreateAclTensor(keyHostData, keyShape, &keyDeviceAddr, aclDataType::ACL_FLOAT16, &key);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    // Create the value aclTensor.
    ret = CreateAclTensor(valueHostData, valueShape, &valueDeviceAddr, aclDataType::ACL_FLOAT16, &value);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    // Create the attentionOut aclTensor.
    ret = CreateAclTensor(attentionOutHostData, attentionOutShape, &attentionOutDeviceAddr, aclDataType::ACL_FLOAT16, &attentionOut);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    // Create the attentionOutGrad aclTensor.
    ret = CreateAclTensor(attentionOutGradHostData, attentionOutGradShape, &attentionOutGradDeviceAddr, aclDataType::ACL_FLOAT16, &attentionOutGrad);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    // Create the softmaxMax aclTensor.
    ret = CreateAclTensor(softmaxMaxHostData, softmaxMaxShape, &softmaxMaxDeviceAddr, aclDataType::ACL_FLOAT, &softmaxMax);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    // Create the softmaxSum aclTensor.
    ret = CreateAclTensor(softmaxSumHostData, softmaxSumShape, &softmaxSumDeviceAddr, aclDataType::ACL_FLOAT, &softmaxSum);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    // Create the topkIndices aclTensor.
    ret = CreateAclTensor(topkIndicesHostData, topkIndicesShape, &topkIndicesDeviceAddr, aclDataType::ACL_INT32, &topkIndices);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    int64_t tempQ[1] = {1};
    int64_t tempK[1] = {1024};
    aclIntArray* actualSeqQLenOptional = aclCreateIntArray(tempQ, static_cast<uint64_t>(1));
    aclIntArray* actualSeqKvLenOptional = aclCreateIntArray(tempK, static_cast<uint64_t>(1));
    // Create the dq aclTensor.
    ret = CreateAclTensor(dqOutHostData, dqOutShape, &dqOutDeviceAddr, aclDataType::ACL_FLOAT16, &dqOut);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    // Create the dk aclTensor.
    ret = CreateAclTensor(dkOutHostData, dkOutShape, &dkOutDeviceAddr, aclDataType::ACL_FLOAT16, &dkOut);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    // Create the dv aclTensor.
    ret = CreateAclTensor(dvOutHostData, dvOutShape, &dvOutDeviceAddr, aclDataType::ACL_FLOAT16, &dvOut);
    CHECK_RET(ret == ACL_SUCCESS, return ret);

    // aclnnNsaSelectedAttentionGrad API call example
    // 3. Call the CANN operator library API. Replace it with the actual API name.
    uint64_t workspaceSize = 0;
    aclOpExecutor* executor;
    // Call the first-phase API of aclnnNsaSelectedAttentionGrad.
    ret = aclnnNsaSelectedAttentionGradGetWorkspaceSize(query, key, value, attentionOut, attentionOutGrad, softmaxMax,
                                                        softmaxSum, topkIndices, actualSeqQLenOptional,
                                                        actualSeqKvLenOptional, nullptr, scaleValue, selectedBlockSize,
                                                        selectedBlockCount, headNum, inputLayout, sparseMode,
                                                        dqOut, dkOut, dvOut, &workspaceSize, &executor);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnNsaSelectedAttentionGradGetWorkspaceSize failed. ERROR: %d\n", ret); return ret);
    // Allocate device memory based on the workspaceSize calculated by the first-phase API.
    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);
    }
    // Call the second-phase API of aclnnNsaSelectedAttentionGrad.
    ret = aclnnNsaSelectedAttentionGrad(workspaceAddr, workspaceSize, executor, stream);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnNsaSelectedAttentionGrad failed. ERROR: %d\n", ret); return ret);

    // 4. (boilerplate) Synchronize and wait for the task to complete.
    ret = aclrtSynchronizeStream(stream);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtSynchronizeStream failed. ERROR: %d\n", ret); return ret);

    // 5. Obtain the output value and copy the result from the Device side to the Host side. Modify it according to the specific API definition.
    auto dqSize = GetShapeSize(dqOutShape);
    std::vector<aclFloat16> dqResultData(dqSize, 0);
    ret = aclrtMemcpy(dqResultData.data(), dqResultData.size() * sizeof(dqResultData[0]), dqOutDeviceAddr,
                      dqSize * sizeof(dqResultData[0]), ACL_MEMCPY_DEVICE_TO_HOST);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("copy out result dq from device to host failed. ERROR: %d\n", ret); return ret);
    for (int64_t i = 0; i < dqSize; i++) {
        LOG_PRINT("result dq[%ld] is: %f\n", i, dqResultData[i]);
    }

    auto dkSize = GetShapeSize(dkOutShape);
    std::vector<aclFloat16> dkResultData(dkSize, 0);
    ret = aclrtMemcpy(dkResultData.data(), dkResultData.size() * sizeof(dkResultData[0]), dkOutDeviceAddr,
                      dkSize * sizeof(dkResultData[0]), ACL_MEMCPY_DEVICE_TO_HOST);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("copy out result dk from device to host failed. ERROR: %d\n", ret); return ret);
    for (int64_t i = 0; i < dkSize; i++) {
        LOG_PRINT("result dk[%ld] is: %f\n", i, dkResultData[i]);
    }

    auto dvSize = GetShapeSize(dvOutShape);
    std::vector<aclFloat16> dvResultData(dvSize, 0);
    ret = aclrtMemcpy(dvResultData.data(), dvResultData.size() * sizeof(dvResultData[0]), dvOutDeviceAddr,
                      dvSize * sizeof(dvResultData[0]), ACL_MEMCPY_DEVICE_TO_HOST);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("copy out result dv from device to host failed. ERROR: %d\n", ret); return ret);
    for (int64_t i = 0; i < dvSize; i++) {
        LOG_PRINT("result dv[%ld] is: %f\n", i, dvResultData[i]);
    }

    // 6. Release aclTensor and aclScalar. Modify it according to the specific API definition.
    aclDestroyTensor(query);
    aclDestroyTensor(key);
    aclDestroyTensor(value);
    aclDestroyTensor(attentionOut);
    aclDestroyTensor(attentionOutGrad);
    aclDestroyTensor(softmaxMax);
    aclDestroyTensor(softmaxSum);
    aclDestroyTensor(topkIndices);
    aclDestroyTensor(dqOut);
    aclDestroyTensor(dkOut);
    aclDestroyTensor(dvOut);
    aclDestroyIntArray(actualSeqQLenOptional);
    aclDestroyIntArray(actualSeqKvLenOptional);
    // 7. Release device resources. Modify it according to the specific API definition.
    aclrtFree(queryDeviceAddr);
    aclrtFree(keyDeviceAddr);
    aclrtFree(valueDeviceAddr);
    aclrtFree(attentionOutDeviceAddr);
    aclrtFree(attentionOutGradDeviceAddr);
    aclrtFree(softmaxMaxDeviceAddr);
    aclrtFree(softmaxSumDeviceAddr);
    aclrtFree(topkIndicesDeviceAddr);
    aclrtFree(dqOutDeviceAddr);
    aclrtFree(dkOutDeviceAddr);
    aclrtFree(dvOutDeviceAddr);
    if (workspaceSize > 0) {
        aclrtFree(workspaceAddr);
    }
    aclrtDestroyStream(stream);
    aclrtResetDevice(deviceId);
    aclFinalize();
    return 0;
}