aclnnSparseFlashMlaSoftmaxL1Norm

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: Computes the Softmax L1Norm result of SparseFlashMla attention, supporting Compressed Attention and Sparse Compressed Attention use cases. This API is the companion API of the aclnnDenseLightningIndexerKLLossGrad backward operator, and its output can be used for backward gradient computation. During the call, call the aclnnSparseFlashMlaSoftmaxL1NormMetadata API first to complete the load balancing computation, and then call the aclnnSparseFlashMlaSoftmaxL1Norm API to complete the operator computation.

    • aclnnSparseFlashMlaSoftmaxL1NormMetadata API: Based on information such as the shape, layout, and mask of the primary operator, evenly partitions tasks across available AIC cores in a strided manner, and outputs metadata for use by the primary operator.
    • aclnnSparseFlashMlaSoftmaxL1Norm API: Computes the Softmax L1Norm of Q and K based on the core partitioning information in metadata.
  • Formula:

    Stage 1: Select the input k based on whether the use case is sparse

    • When sparse:
    $$ selectedKv\text{ }=\text{ }Gather \left( K, sparseIndices \left[ i \left] \left) ,\text{ }0\text{ } < =i < \text{ }selectBlockCount\right. \right. \right. \right. $$
    • else:
    $$ selectedKv\text{ }=\text{ }K $$

    Stage 2: Calculate P (SimpleSoftmax).

    $$ P = SimpleSoftmax(Mask(Q \text{ }@\text{ } selectedKv^{{T}} \cdot \text{ } scale), softmaxLse) $$

    Stage 3: Calculate Softmax L1Norm.

    $$ softmaxL1Norm = \frac{ReduceSum(P, dim=G)}{G} $$

    Where $G$ indicates the number of groups ($G = N1 / N2$), and $ReduceSum$ sums the softmax probability $P$ over the G dimension (q head group dimension) and then takes the average.

Function Prototype

Each operator uses a two-phase API. Call the "aclnnSparseFlashMlaSoftmaxL1NormGetWorkspaceSize" API first to obtain the workspace size required for computation and the executor that contains the operator computation process. Then call the "aclnnSparseFlashMlaSoftmaxL1Norm" API to execute the computation.

aclnnStatus aclnnSparseFlashMlaSoftmaxL1NormGetWorkspaceSize(
    const aclTensor   *q,
    const aclTensor   *k,
    const aclTensor   *softmaxLse,
    const aclTensor   *sparseIndicesOptional,
    const aclTensor   *cuSeqlensQOptional,
    const aclTensor   *cuSeqlensKOptional,
    const aclTensor   *sequsedQOptional,
    const aclTensor   *sequsedKOptional,
    const aclTensor   *cmpResidualKOptional,
    const aclTensor   *topkLengthOptional,
    const aclTensor   *metadataOptional,
    double             softmaxScale,
    int64_t            cmpRatio,
    int64_t            maskMode,
    char              *layoutQOptional,
    char              *layoutKOptional,
    const aclTensor   *softmaxL1Norm,
    uint64_t          *workspaceSize,
    aclOpExecutor    **executor);
aclnnStatus aclnnSparseFlashMlaSoftmaxL1Norm(
    void             *workspace,
    uint64_t          workspaceSize,
    aclOpExecutor    *executor,
    aclrtStream       stream);

aclnnSparseFlashMlaSoftmaxL1NormGetWorkspaceSize

  • Parameters:

    Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor
    q (aclTensor*) Input Input Q of the attention structure. The N-axis correspondence between q and k must satisfy the GQA constraint (N1 = N2 × G). BFLOAT16, FLOAT16 ND (B,S1,N1,D), (T1,N1,D)
    B: support generalization; S1: support generalization; N1: support 1-128; D: 512; T1: B × S1
    √
    k (aclTensor*) Input Input K(V) of the attention structure. Empty tensors are currently not supported. BFLOAT16, FLOAT16 ND (B,S2,N2,D), (T2,N2,D)
    B: keep consistent with the B of q; S2: supports generalization; N2: 1; D: 512; T2: B × S2
    √
    softmaxLse (aclTensor*) Input softmaxLse output from the forward attention computation. For the formula, see the sparse_flash_mla document. - FLOAT32 ND (B,N2,S1,G), (N2,T1,G)
    B: Keep consistent with B of q; N2: 1; S1: Keep consistent with S1 of q; G: N1/N2; T1: B × S1
    √
    sparseIndicesOptional(aclTensor*) Input Attention indices with higher weights selected from k in sparse use cases.
    • Supports empty tensors.
    INT32 ND (B,S1,N2,K), (T1,N2,K) √
    cuSeqlensQOptional (aclTensor*) Input Number of valid query tokens in each batch.
    • Optional: exists when layout is TND.
    • The length is consistent with B+1.
    • The cumulative sum is consistent with T1.
    INT32 ND (B+1,) √
    cuSeqlensKOptional (aclTensor*) Input Number of valid Key tokens in each batch.
    • Optional: This variable exists when layout is TND.
    • The length is consistent with B+1.
    • The cumulative sum is consistent with T2.
    INT32 ND (B+1,) √
    sequsedQOptional (aclTensor*) Input Indicates the number of tokens of q that actually participate in the computation in different batches. Length is B. INT32 ND (B,)
    √
    sequsedKOptional (aclTensor*) Input Indicates the number of tokens of k that actually participate in computation in each batch. Length is B. INT32 ND (B,)
    √
    cmpResidualKOptional (aclTensor*) Input Indicates the remainder of S2 // cmpRatio for each batch. Must be passed in when maskMode=3 and cmpRatio!=1. INT32 ND (B,)
    √
    topkLengthOptional (aclTensor*) Input Indicates the actual available topk length of k corresponding to each row of q. Required when maskMode=0 and a sparse index exists, and must be an exact value. INT32 ND (B,S1,N2), (T1,N2)
    √
    metadataOptional (aclTensor*) Input Indicates the output of the aicpu operator with tiling offloaded. Required. Generated by the aclnnSparseFlashMlaSoftmaxL1NormMetadata operator. INT32 ND (x)
    √
    softmaxScale (double) Input Scale factor. Suggested value: reciprocal of the square root of d in the formula FLOAT32 - - -
    cmpRatio (int64_t) Input Indicates the compression ratio of k. Value range: 1-128 INT64 - - -
    maskMode (int64_t) Input Indicates the mask mode for the computation of q and k.
    • Indicates the sparse mode. For details about different sparse modes, see Constraints.
    INT64 - - -
    layoutQOptional (char*) Input Indicates the data layout format of input q. Supports "BSND" and "TND". Must be consistent with layoutKOptional. STRING - - -
    layoutKOptional (char*) Input Indicates the data layout format of input k. Supports "BSND" and "TND". Must be consistent with layoutQOptional. STRING - - -
    softmaxL1Norm (aclTensor*) Output Indicates the softmax L1Norm result computed from q and k. Formula: reduceG(softmax)/G. If sparse indices exist, this output is not empty; in other use cases, the parameter output is empty. FLOAT32 ND (B,S1,N2,S2), (T1,N2,T2)
    B: keep consistent with B of q; S1: keep consistent with S1 of q; N2: 1; S2: keep consistent with S2 of k; T1: B × S1; T2: B × S2
    √
  • 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 An invalid nullptr exists in the parameters.
    ACLNN_ERR_PARAM_INVALID 161002 The input data type is not a supported type.
    Required inputs/outputs q, k, softmaxLse, or softmaxL1Norm are not passed in.

aclnnSparseFlashMlaSoftmaxL1Norm

  • Parameters:

    Parameter Input/Output Description
    workspace Input Workspace memory address allocated on the device.
    workspaceSize Input Workspace size allocated on the device, obtained by the first-phase API aclnnSparseFlashMlaSoftmaxL1NormGetWorkspaceSize.
    executor Input Operator executor that contains the operator computation flow.
    stream Input Specifies the stream for task execution.
  • Return Value

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

Constraints

  • Deterministic computation: aclnnSparseFlashMlaSoftmaxL1Norm defaults to a deterministic implementation.

  • Common constraints:

    • Empty input handling: If q is an empty tensor, the API returns directly.
  • Mask

    maskMode Meaning Note
    0 No mask operation. Supported
    3 Mask in rightDownCausal mode, corresponding to the lower triangular use case with the right vertex as the division point. Supported
  • Specification constraints

    Item Specification Description
    B Support Generalization -
    S1, S2 Support Generalization Supports S1 and S2 with unequal lengths.
    N1 1-128 -
    N2 1 -
    D 512 -
    layout BSND/TND -

Example

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

#include <iostream>
#include <vector>
#include "acl/acl.h"
#include "aclnnop/aclnn_sparse_flash_mla_softmax_l1_norm.h"
#include "aclnnop/aclnn_sparse_flash_mla_softmax_l1_norm_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 shapeSize = 1;
  for (auto i : shape) {
    shapeSize *= i;
  }
  return shapeSize;
}

int Init(int32_t deviceId, aclrtContext* context, 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 = 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);
  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 = 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;
}

int main() {
  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);

  // TND layout: qShape=(T1,N1,D), kShape=(T2,N2,D), softmaxLseShape=(N2,T1,G)
  std::vector<int64_t> qShape = {16, 128, 512};
  std::vector<int64_t> kShape = {2048, 1, 512};
  std::vector<int64_t> softmaxLseShape = {1, 16, 128};
  std::vector<int64_t> cuSeqQLenshape = {2};
  std::vector<int64_t> cuSeqKLenshape = {2};
  std::vector<int64_t> cmpResidualKShape = {1};
  std::vector<int64_t> softmaxL1NormShape = {16, 1, 2048};
  std::vector<int64_t> metadataShape = {64};

  void* qDeviceAddr = nullptr;
  void* kDeviceAddr = nullptr;
  void* softmaxLseDeviceAddr = nullptr;
  void* cuSeqQLenDeviceAddr = nullptr;
  void* cuSeqKLenDeviceAddr = nullptr;
  void* cmpResidualKDeviceAddr = nullptr;
  void* softmaxL1NormDeviceAddr = nullptr;
  void* metadataDeviceAddr = nullptr;

  aclTensor* q = nullptr;
  aclTensor* k = nullptr;
  aclTensor* softmaxLse = nullptr;
  aclTensor* cuSeqQLen = nullptr;
  aclTensor* cuSeqKLen = nullptr;
  aclTensor* cmpResidualK = nullptr;
  aclTensor* softmaxL1Norm = nullptr;
  aclTensor* metadata = nullptr;

  std::vector<short> qHostData(16 * 128 * 512, 1.0);
  std::vector<short> kHostData(2048 * 1 * 512, 1.0);
  std::vector<float> softmaxLseHostData(1 * 16 * 128, 3.0);
  std::vector<int32_t> cuSeqQLenHostData = {0, 16};
  std::vector<int32_t> cuSeqKLenHostData = {0, 2048};
  std::vector<int32_t> cmpResidualKHostData = {0};
  std::vector<float> softmaxL1NormHostData(16 * 1 * 2048, 0);
  std::vector<int32_t> metadataHostData(64, 0);

  ret = CreateAclTensor(qHostData, qShape, &qDeviceAddr, aclDataType::ACL_FLOAT16, &q);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  ret = CreateAclTensor(kHostData, kShape, &kDeviceAddr, aclDataType::ACL_FLOAT16, &k);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  ret = CreateAclTensor(softmaxLseHostData, softmaxLseShape, &softmaxLseDeviceAddr, aclDataType::ACL_FLOAT, &softmaxLse);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  ret = CreateAclTensor(cuSeqQLenHostData, cuSeqQLenshape, &cuSeqQLenDeviceAddr, aclDataType::ACL_INT32, &cuSeqQLen);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  ret = CreateAclTensor(cuSeqKLenHostData, cuSeqKLenshape, &cuSeqKLenDeviceAddr, aclDataType::ACL_INT32, &cuSeqKLen);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  ret = CreateAclTensor(cmpResidualKHostData, cmpResidualKShape, &cmpResidualKDeviceAddr, aclDataType::ACL_INT32,
                        &cmpResidualK);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  ret = CreateAclTensor(softmaxL1NormHostData, softmaxL1NormShape, &softmaxL1NormDeviceAddr, aclDataType::ACL_FLOAT,
                        &softmaxL1Norm);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  ret = CreateAclTensor(metadataHostData, metadataShape, &metadataDeviceAddr, aclDataType::ACL_INT32, &metadata);
  CHECK_RET(ret == ACL_SUCCESS, return ret);

  double softmaxScale = 0.088388;
  int64_t maxSeqlenK = 2048;
  int64_t cmpRatio = 128;
  int64_t maskMode = 3;
  char layoutQ[4] = {'T', 'N', 'D', 0};
  char layoutK[4] = {'T', 'N', 'D', 0};

  // 1. Call the preceding metadata operator.
  uint64_t metadataWorkspaceSize = 0;
  aclOpExecutor* metadataExecutor = nullptr;
  ret = aclnnSparseFlashMlaSoftmaxL1NormMetadataGetWorkspaceSize(
      cuSeqQLen, cuSeqKLen, nullptr, nullptr, cmpResidualK, nullptr,
      0, 16, 2048, 128, 1, 512, 0, cmpRatio, maskMode, layoutQ, layoutK,
      metadata, &metadataWorkspaceSize, &metadataExecutor);
  CHECK_RET(ret == ACL_SUCCESS,
            LOG_PRINT("aclnnSparseFlashMlaSoftmaxL1NormMetadataGetWorkspaceSize failed. ERROR: %d\n", ret);
            return ret);
  void* metadataWorkspaceAddr = nullptr;
  if (metadataWorkspaceSize > 0) {
    ret = aclrtMalloc(&metadataWorkspaceAddr, metadataWorkspaceSize, ACL_MEM_MALLOC_HUGE_FIRST);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("allocate metadata workspace failed. ERROR: %d\n", ret); return ret);
  }
  ret = aclnnSparseFlashMlaSoftmaxL1NormMetadata(metadataWorkspaceAddr, metadataWorkspaceSize, metadataExecutor, stream);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnSparseFlashMlaSoftmaxL1NormMetadata failed. ERROR: %d\n", ret); return ret);
  ret = aclrtSynchronizeStream(stream);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtSynchronizeStream failed. ERROR: %d\n", ret); return ret);

  // 2. Call the main operator.
  uint64_t workspaceSize = 0;
  aclOpExecutor* executor = nullptr;
  ret = aclnnSparseFlashMlaSoftmaxL1NormGetWorkspaceSize(
      q, k, softmaxLse, nullptr, cuSeqQLen, cuSeqKLen, nullptr, nullptr, cmpResidualK, nullptr, metadata,
      softmaxScale, maxSeqlenK, cmpRatio, maskMode, layoutQ, layoutK, softmaxL1Norm, &workspaceSize, &executor);
  CHECK_RET(ret == ACL_SUCCESS,
            LOG_PRINT("aclnnSparseFlashMlaSoftmaxL1NormGetWorkspaceSize failed. ERROR: %d\n", ret); return ret);

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

  try {
    ret = aclnnSparseFlashMlaSoftmaxL1Norm(workspaceAddr, workspaceSize, executor, stream);
    if (ret != ACL_SUCCESS) {
      LOG_PRINT("Expected kernel failure (skeleton stage): ERROR: %d\n", ret);
    } else {
      ret = aclrtSynchronizeStream(stream);
      CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtSynchronizeStream failed. ERROR: %d\n", ret); return ret);
    }
  } catch (const std::exception& e) {
    LOG_PRINT("Expected kernel failure (skeleton stage): %s\n", e.what());
  }

  aclDestroyTensor(q);
  aclDestroyTensor(k);
  aclDestroyTensor(softmaxLse);
  aclDestroyTensor(cuSeqQLen);
  aclDestroyTensor(cuSeqKLen);
  aclDestroyTensor(cmpResidualK);
  aclDestroyTensor(softmaxL1Norm);
  aclDestroyTensor(metadata);
  aclrtFree(qDeviceAddr);
  aclrtFree(kDeviceAddr);
  aclrtFree(softmaxLseDeviceAddr);
  aclrtFree(cuSeqQLenDeviceAddr);
  aclrtFree(cuSeqKLenDeviceAddr);
  aclrtFree(cmpResidualKDeviceAddr);
  aclrtFree(softmaxL1NormDeviceAddr);
  aclrtFree(metadataDeviceAddr);
  if (workspaceSize > 0) {
    aclrtFree(workspaceAddr);
  }
  if (metadataWorkspaceSize > 0) {
    aclrtFree(metadataWorkspaceAddr);
  }
  aclrtDestroyStream(stream);
  aclrtDestroyContext(context);
  aclrtResetDevice(deviceId);
  aclFinalize();
  return 0;
}