aclnnDenseLightningIndexerSoftmaxLse

Applicable Products

  • Ascend 950PR&950DT products: Supported
  • Atlas A3 products: 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: The DenseLightningIndexerSoftmaxLse operator is a branch operator of the DenseLightningIndexerGradKlLoss operator for computing the Softmax input.

  • Formula:

    $$ \text{res}=\text{AttentionMask}\left(\text{ReduceSum}\left(W\odot\text{ReLU}\left(Q_{index}@K_{index}^T\right)\right)\right) $$
    $$ \text{maxIndex}=\text{max}\left(res\right) $$
    $$ \text{sumIndex}=\text{ReduceSum}\left(\text{exp}\left(res-maxIndex\right)\right) $$

    maxIndex and sumIndex are passed as outputs to the DenseLightningIndexerGradKlLoss operator as inputs for Softmax computation.

Function Prototype

The operator execution API is a two-phase API. You must first call the "aclnnDenseLightningIndexerSoftmaxLseGetWorkspaceSize" API to obtain the input parameters and calculate the required workspace size based on the computation process, and then call the "aclnnDenseLightningIndexerSoftmaxLse" API to execute the computation.

aclnnStatus aclnnDenseLightningIndexerSoftmaxLseGetWorkspaceSize(
    const aclTensor   *queryIndex,
    const aclTensor   *keyIndex,
    const aclTensor   *weight,
    const aclIntArray *actualSeqLengthsQueryOptional,
    const aclIntArray *actualSeqLengthsKeyOptional,
    char              *layoutOptional,
    int64_t            sparseMode,
    int64_t            preTokens,
    int64_t            nextTokens,
    const aclTensor   *softmaxMaxOut,
    const aclTensor   *softmaxSumOut,
    uint64_t          *workspaceSize,
    aclOpExecutor    **executor);
aclnnStatus aclnnDenseLightningIndexerSoftmaxLse(
    void          *workspace,
    uint64_t       workspaceSize,
    aclOpExecutor *executor,
    aclrtStream    stream);

aclnnDenseLightningIndexerSoftmaxLseGetWorkspaceSize

  • Parameters:

    Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor
    queryIndex(aclTensor*) Input Input queryIndex of the lightningIndexer structure.
    • B: Supports generalization and keeps consistent with the B of query.
    • Nidx1: 64, 32, 16, 8.
    • D: 128.
    • T1: Accumulated S1 across multiple batches.
    FLOAT16, BFLOAT16 ND (B,S1,Nidx1,D);(T1,Nidx1,D) ×
    keyIndex (aclTensor*) Input Input keyIndex of the lightningIndexer structure.
    • B: Supports generalization and keeps consistent with the B of queryIndex.
    • S2: Supports generalization.
    • Nidx2: 1.
    • D: 128.
    • T2: Accumulation of S2 over multiple batches.
    FLOAT16, BFLOAT16 ND (B,S2,Nidx2,D);(T2,Nidx2,D) ×
    weight (aclTensor*) Input Weight
    • B: Supports generalization and keeps consistent with the B of queryIndex.
    • S1: Supports generalization and keeps consistent with the S1 of queryIndex.
    • Nidx1: 64, 32, 16, 8.
    • T1: Accumulation of S1 over multiple batches.
    FLOAT16, BFLOAT16, FLOAT32 ND (B,S1,Nidx1);(T1,Nidx1) ×
    actualSeqLengthsQueryOptional (aclIntArray*) Input Number of valid Query tokens in each Batch.
    • Value dependency.
    • The length must keep consistent with B.
    • In TND format, the last element is the accumulated sum. The accumulated sum is less than or equal to T1.
    INT64 ND (B,) -
    actualSeqLengthsKeyOptional(aclIntArray*) Input Number of valid tokens of Key in each batch.
    • Value dependency.
    • The length keeps consistent with B.
    • In TND format, the last element is the accumulated sum. The accumulated sum is less than or equal to T2.
    INT64 ND (B,) -
    layoutOptional(char*) Input Layout format. Only BSND and TND formats are supported. STRING - - -
    sparseMode (int64_t) Input Sparse mode.
    • Indicates the sparse mode. For details about different sparse modes, see Constraints.
    • Only mode 3 is supported.
    - - - -
    preTokens (int64_t) Input Used for sparse computation. Indicates the number of previous tokens that Attention needs to compute correlation with. Same as the definition of preTokens in Attention. Takes effect when sparseMode = 0 or 4. Only 2^63-1 is supported. - - - -
    nextTokens (int64_t) Input Used for sparse computation. Indicates that Attention needs to compute correlation with the following tokens. Same as the definition of nextTokens in Attention. Takes effect when sparseMode = 0 or 4. Only 2^63-1 is supported. - - - -
    softmaxMaxOut (aclTensor*) Output The max value used in the softmax compute
    • B: Supports generalization and keeps consistent with the B of queryIndex.
    • Nidx2: Keeps consistent with the Nidx2 of keyIndex.
    • S1: Supports generalization, and keeps consistent with the S1 of queryIndex.
    • T1: The accumulated S1 of multiple batches.
    FLOAT32 ND (B,Nidx2,S1);(Nidx2,T1) ×
    softmaxSumOut (aclTensor*) Output Sum value used for softmax computation.
    • B: Support generalization and keep consistent with the B of query.
    • Nidx2: Keep consistent with the Nidx2 of keyIndex.
    • S1: Support generalization and keep consistent with the S1 of queryIndex.
    • T1: Accumulate the S1 of multiple batches.
    FLOAT32 ND (B,Nidx2,S1);(Nidx2,T1) ×
    workspaceSize (uint64_t*) Output Return the workspace size required for Device side application. - - - - -
    executor (aclOpExecutor**) Output Returns the op executor containing the operator compute 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 A required parameter or output is a null pointer.
    ACLNN_ERR_PARAM_INVALID 161002 The data types and data formats of input variables such as queryIndex, keyIndex, and weight are not supported.
    ACLNN_ERR_INNER_TILING_ERROR 561002 The shape information of multiple input tensors does not match (see Parameters).

aclnnDenseLightningIndexerSoftmaxLse

  • Parameters:

    Parameter Input/Output Description
    workspace Input Workspace memory address of the Device Side Application.
    workspaceSize Input Workspace size of the Device Side Application, obtained by the first-phase API aclnnDenseLightningIndexerSoftmaxLseGetWorkspaceSize.
    executor Input Op executor that contains the operator computation flow.
    stream Input Stream for executing tasks.
  • Return value

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

Constraints

  • The data types of queryIndex and keyIndex must be consistent.

  • If weight is not float32, the data types of queryIndex, keyIndex, and weight should keep consistent.

  • Deterministic computation: aclnnDenseLightningIndexerSoftmaxLse defaults to a deterministic implementation.

  • General Constraints

    • Handling of empty input parameters:
      • queryIndex is an empty tensor: Returns directly.
      • The handling of empty input parameters in SFAG general constraints is consistent with FAG.
    sparseMode Meaning Note
    0 defaultMask mode. If attenmask is not passed in, no mask operation is performed, and preTokens and nextTokens are ignored. If attenmask is passed in, the complete attenmask matrix needs to be passed in, indicating that the part between preTokens and nextTokens needs to be computed. Not Supported
    1 allMask. The complete attenmask matrix must be passed in. Not Supported
    2 leftUpCausal mode. The optimized attenmask matrix needs to be passed in. Not Supported
    3 Mask of the rightDownCausal mode. It corresponds to the lower triangular scenario with the right vertex as the boundary. Need to pass in the optimized attenmask matrix. Supported
    4 Mask of the band mode. Need to pass in the optimized attenmask matrix. Not Supported
    5 prefix Not Supported
    6 global Not Supported
    7 dilated Not Supported
    8 block_local Not Supported
  • Specification constraints

    Specification Item Specification Specification
    B 1-256 -
    S1, S2 0-1M Unequal lengths are supported for S1 and S2. When the layout is BSND, S1<=S2; when the layout is TND, the value of actualSeqLengthsQuery at each index is less than or equal to the value of actualSeqLengthsKey at the same index, and S1<=S2 at the same index.
    Nidx1 8, 16, 32, 64 -
    Nidx2 1 -
    D 128 -
    layout BSND/TND -
  • Typical values

    Specification Item Typical Value
    queryIndex N1 = 64/32; D = 128 ; S1 = 64k/128k
    keyIndex D = 128.

Example

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

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

void PrintOutResult(std::vector<int64_t> &shape, void** deviceAddr) {
  auto size = GetShapeSize(shape);
  std::vector<aclFloat16> resultData(size, 0);
  auto ret = aclrtMemcpy(resultData.data(), resultData.size() * sizeof(resultData[0]),
                         *deviceAddr, size * sizeof(resultData[0]), ACL_MEMCPY_DEVICE_TO_HOST);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("copy result from device to host failed. ERROR: %d\n", ret); return);
  for (int64_t i = 0; i < size; i++) {
    LOG_PRINT("mean result[%ld] is: %f\n", i, aclFloat16ToFloat(resultData[i]));
  }
}

int Init(int32_t deviceId, aclrtContext* context, aclrtStream* stream) {
  // Boilerplate: initialize AscendCL.
  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 = aclrtCreateContext(context, deviceId);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtCreateContext failed. ERROR: %d\n", ret); return ret);
  ret = aclrtSetCurrentContext(*context);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtSetCurrentContext 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.
  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 data to device 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);

  // Compute 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 aclTensor
  *tensor = aclCreateTensor(shape.data(), shape.size(), dataType, strides.data(), 0, aclFormat::ACL_FORMAT_ND,
                            shape.data(), shape.size(), *deviceAddr);
  return 0;
}

int main() {
  // 1. (boilerplate) Initialize device/context/stream. For details, see the AscendCL public API list.
  // Fill in deviceId according to the actual device.
  int32_t deviceId = 0;
  aclrtContext context;
  aclrtStream stream;
  auto ret = Init(deviceId, &context, &stream);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("Init acl failed. ERROR: %d\n", ret); return ret);

  // 2. Construct the input and output. Perform custom construction based on the API.
  int64_t s1 = 4096;
  int64_t s2 = 4096;
  int64_t n1Index = 8;
  int64_t n2Index = 1;
  int64_t dQueryIndex = 128;
  int64_t t1 = s1;
  int64_t t2 = s2;
  int64_t G = n1Index / n2Index;

  std::vector<int64_t> qIndexShape = {t1, n1Index, dQueryIndex};
  std::vector<int64_t> kIndexShape = {t2, n2Index, dQueryIndex};
  std::vector<int64_t> weightShape = {t1, n1Index};
  std::vector<int64_t> softmaxMaxIndexShape = {n2Index, t1};
  std::vector<int64_t> softmaxSumIndexShape = {n2Index, t1};

  void* qIndexDeviceAddr = nullptr;
  void* kIndexDeviceAddr = nullptr;
  void* weightDeviceAddr = nullptr;
  void* softmaxMaxIndexDeviceAddr = nullptr;
  void* softmaxSumIndexDeviceAddr = nullptr;

  aclTensor* qIndex = nullptr;
  aclTensor* kIndex = nullptr;
  aclTensor* weight = nullptr;
  aclTensor* softmaxMaxIndex = nullptr;
  aclTensor* softmaxSumIndex = nullptr;

  std::vector<aclFloat16> qIndexHostData(t1 * n1Index * dQueryIndex, aclFloatToFloat16(0.2));
  std::vector<aclFloat16> kIndexHostData(t2 * n2Index * dQueryIndex, aclFloatToFloat16(0.1));
  std::vector<aclFloat16> weightHostData(t1 * n1Index, aclFloatToFloat16(0.005));

  std::vector<float> softmaxMaxIndexHostData(t1 * n2Index, 25.4483f);
  std::vector<float> softmaxSumIndexHostData(t1 * n2Index, 1.0f);

  ret = CreateAclTensor(qIndexHostData, qIndexShape, &qIndexDeviceAddr, aclDataType::ACL_FLOAT16, &qIndex);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  ret = CreateAclTensor(kIndexHostData, kIndexShape, &kIndexDeviceAddr, aclDataType::ACL_FLOAT16, &kIndex);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  ret = CreateAclTensor(weightHostData, weightShape, &weightDeviceAddr, aclDataType::ACL_FLOAT16, &weight);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  ret = CreateAclTensor(softmaxMaxIndexHostData, softmaxMaxIndexShape, &softmaxMaxIndexDeviceAddr,
      aclDataType::ACL_FLOAT, &softmaxMaxIndex);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  ret = CreateAclTensor(softmaxSumIndexHostData, softmaxSumIndexShape, &softmaxSumIndexDeviceAddr,
      aclDataType::ACL_FLOAT, &softmaxSumIndex);
  CHECK_RET(ret == ACL_SUCCESS, return ret);

  std::vector<int64_t>  acSeqQLenOp = {t1};
  std::vector<int64_t>  acSeqKvLenOp = {t2};
  aclIntArray* acSeqQLen = aclCreateIntArray(acSeqQLenOp.data(), acSeqQLenOp.size());
  aclIntArray* acSeqKvLen = aclCreateIntArray(acSeqKvLenOp.data(), acSeqKvLenOp.size());
  int64_t preTokens = 9223372036854775807;
  int64_t nextTokens = 9223372036854775807;
  int64_t sparseMode = 3;

  char layOut[5] = {'T', 'N', 'D', 0};

  // 3. Call the CANN operator library API. Replace it with the specific API name.
  uint64_t workspaceSize = 0;
  aclOpExecutor* executor;

  // Call the first-phase API aclnnDenseLightningIndexerSoftmaxLseGetWorkspaceSize
  ret = aclnnDenseLightningIndexerSoftmaxLseGetWorkspaceSize(
            qIndex, kIndex, weight, acSeqQLen, acSeqKvLen, layOut,
            sparseMode, preTokens, nextTokens, softmaxMaxIndex, softmaxSumIndex,
            &workspaceSize, &executor);
  CHECK_RET(ret == ACL_SUCCESS,
            LOG_PRINT("aclnnDenseLightningIndexerSoftmaxLseGetWorkspaceSize failed. ERROR: %d\n", ret);
            return ret);

  // Allocate device memory based on the workspaceSize computed 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 aclnnDenseLightningIndexerSoftmaxLse
  ret = aclnnDenseLightningIndexerSoftmaxLse(workspaceAddr, workspaceSize, executor, stream);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnDenseLightningIndexerSoftmaxLse failed. ERROR: %d\n", ret); return ret);

  // 4. (boilerplate) Synchronize and wait for the task execution 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. Copy the result from device memory to host memory. Modify it based on the specific API definition.
  PrintOutResult(softmaxMaxIndexShape, &softmaxMaxIndexDeviceAddr);
  PrintOutResult(softmaxSumIndexShape, &softmaxSumIndexDeviceAddr);

  // 6. Release aclTensor and aclScalar. Modify based on the specific API definition.
  aclDestroyTensor(qIndex);
  aclDestroyTensor(kIndex);
  aclDestroyTensor(weight);
  aclDestroyTensor(softmaxMaxIndex);
  aclDestroyTensor(softmaxSumIndex);

  // 7. Release device resources.
  aclrtFree(qIndexDeviceAddr);
  aclrtFree(kIndexDeviceAddr);
  aclrtFree(weightDeviceAddr);
  aclrtFree(softmaxMaxIndexDeviceAddr);
  aclrtFree(softmaxSumIndexDeviceAddr);

  if (workspaceSize > 0) {
    aclrtFree(workspaceAddr);
  }
  aclrtDestroyStream(stream);
  aclrtDestroyContext(context);
  aclrtResetDevice(deviceId);
  aclFinalize();

  return 0;
}