aclnnStemOamPrepPagedKv

📄 View Source Code

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: Stem OAM (Output-Aware Metric) is the pre-scoring module of the dynamic sparse attention mechanism for large model inference. It extracts K/V data from the Paged KV Cache, computes through K Processing (per-token K-scale × group sum + anti-diagonal flip) and V Processing (per-head vScale × L2 Norm → Log → Global Normalize → ReLU → Block Average), and outputs kFlat and vBias for Stem OAM score computation.

  • Formula: Stage 1: De-page + Cast FP32 + kScaleCache Gather

$$ K\_dense[b], V\_dense[b], kscale\_per\_row[b] = Cast\big(gather(kcache[kv\_indices[b]]),\ FP32\big),\ Cast\big(gather(vcache[kv\_indices[b]]),\ FP32\big),\ gather(kScaleCache[kv\_indices[b]]) $$
$$ k\_padded[b] = \lceil kv\_len[b] / B \rceil \times B, \quad num\_Kb[b] = k\_padded[b] / B, \quad R = B / S $$
$$ K\_scaled[b, h] = K\_dense[b, h, :] \times kscale\_per\_row[b, h, :] \quad (\text{per-token per-head, broadcast on dim}) $$

Stage 2: K Processing (Weighted Group Sum + Anti-diagonal Flip)

$$ K\_group\_sum[b,h,kb,g,:] = \sum_{r=0}^{R-1} K\_blocks[b,h,kb,r,g,:] $$
$$ K\_group\_rev[b,h,kb,g',:] = K\_group\_sum[b,h,kb,\ S-1-g',:] \quad (\text{anti-diagonal flip}) $$
$$ kFlat[b,h,kb,:] = reshape(K\_group\_rev[b,h,kb,:,:],\ [kflat\_dim = S \times D]) \xrightarrow{Cast} BF16 $$

Stage 3: V Processing

Step 3a: L2 Norm + Max Pool + Log

$$ norms[b,h,idx,s,:] = \| V\_rows[b,h,idx,s,:] \times vScale[h] \|_2 = \sqrt{\sum_d (V\_rows[idx,s,d] \times vScale[h])^2} $$
$$ v\_norm\_down[b,h,idx] = \max_{s} norms[b,h,idx,s,:] \quad (\text{zero beyond } kv\_len) $$
$$ log\_vals[b,h,idx] = \log(v\_norm\_down[b,h,idx] + \epsilon), \quad \epsilon = 10^{-6} $$

Step 3b: Global Normalize (μ/σ over ALL k_down_len values)

$$ \mu[b,h] = \frac{1}{k\_down\_len} \sum_{idx=0}^{k\_down\_len-1} log\_vals[b,h,idx] $$
$$ \sigma[b,h] = \sqrt{\frac{\sum(log\_vals - \mu)^2}{k\_down\_len - 1}} \quad (k\_down\_len > 1);\quad \sigma = 0 \quad (k\_down\_len = 1) $$

Step 3c: Normalize + ReLU + Block Average

$$ normalized[b,h,idx] = \frac{log\_vals[b,h,idx] - \mu[b,h]}{\sigma[b,h] + \epsilon} $$
$$ v\_final[b,h,idx] = \lambda \times ReLU(normalized[b,h,idx]) $$
$$ vBias[b,h,kb] = \frac{1}{R} \sum_{r=0}^{R-1} v\_final[b,h,\ kb \times R + r] $$

Function Prototype

Each operator uses a two-phase API. You must first call the "aclnnStemOamPrepPagedKvGetWorkspaceSize" API to obtain the workspace size required for the computation and the executor that includes computation of the operator, and then call the "aclnnStemOamPrepPagedKv" API to perform the computation.

aclnnStatus aclnnStemOamPrepPagedKvGetWorkspaceSize(
  const aclTensor  *kCache,
  const aclTensor  *vCache,
  const aclTensor  *kvIndices,
  const aclIntArray  *kvSeqLens,
  const aclTensor  *kScaleCache,
  const aclTensor  *vScale,
  double            lambdaMag,
  char              *kvLayout,
  int64_t           stemBlockSize,
  int64_t           stemStride,
  const aclTensor  *kFlat,
  const aclTensor  *vBias,
  uint64_t         *workspaceSize,
  aclOpExecutor    **executor)
aclnnStatus aclnnStemOamPrepPagedKv(
  void          *workspace,
  uint64_t       workspaceSize,
  aclOpExecutor *executor,
  aclrtStream    stream)

aclnnStemOamPrepPagedKvGetWorkspaceSize

  • Parameters

    Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor
    kCache (aclTensor*) Input Paged K cache. Does not support null Tensor.
    Two layouts, specified by kvLayout. Currently only supports "BNBD":
    "BBND" is [total_blocks, kvBlockSize, H_kv, D=128],
    "BNBD" is [total_blocks, H_kv, kvBlockSize, D=128].
    The first three dimensions support non-contiguous layouts, the last dimension must be contiguous, and the maximum value of H_kv is 8.
    FLOAT8_E4M3FN ND 4 √
    vCache (aclTensor*) Input Paged V cache. Does not support null Tensor.
    The layout is the same as kCache.
    Same as kCache ND 4 √
    kvIndices (aclTensor*) Input Array of KV Block indices per batch Does not support null Tensor.
    shape: [batch, max_kv_blocks], where the maximum value of batch is 16 and the maximum value of max_kv_blocks is 2048.
    INT32 ND 2 x
    kvSeqLens (aclIntArray*) Input KV sequence length for each batch. Does not support null list.
    shape:[batch], maximum KV sequence length 262144
    INT32 ND 1 x
    kScaleCacheOptional (aclTensor*) Input Per-token per-head K scale. Required when the data type of kCache is FP8; can be omitted (pass nullptr) for other data types.
    Two layouts, specified by kvLayout. Currently only supports "BNBD":
    "BBND" is [total_blocks, kvBlockSize, H_kv, 1],
    "BNBD" is [total_blocks, H_kv, kvBlockSize, 1].
    The first three dimensions can be non-contiguous, and the last dimension must be contiguous.
    FLOAT ND 4 √
    vScaleOptional (aclTensor*) Input Per-head V scale. Required when the data type of kCache is FP8; optional for other types (pass nullptr).
    shape:[H_kv]
    FLOAT ND 1 x
    lambdaMag ATTR V bias multiplier. Value range: [0,1]. double - - -
    kvLayout ATTR KV Cache layout. Value range: "BBND", "BNBD". Currently only supports "BNBD". char* - - -
    stemBlockSize ATTR Stem block size. Value range: %32==0, ≤256, and stemBlockSize must be a multiple of stemStride. 128 is recommended. int64_t - - -
    stemStride ATTR Stride size. Value range: %16==0, ≤64, ≤stemBlockSize, 16 recommended. int64_t - - -
    kFlat (aclTensor*) Output K group sum + anti-diag flip result. Does not support empty tensors.
    The shape is [batch, H_kv, max_Kb, kflat_dim], where kflat_dim=stemStride*D,
    max_Kb is computed based on the kvSeqLens input.
    BFLOAT16 ND 4 ×
    vBias (aclTensor*) Output V block bias result. Does not support null Tensor.
    The shape is [batch, H_kv, max_Kb], where max_Kb is calculated based on the kvSeqLens input.
    FLOAT ND 3 ×
    workspaceSize (uint64_t*) Output Returns the size of the workspace to be requested by the Device side. - - - - -
    executor (aclOpExecutor**) Output Returns the op executor, which includes computation flow of the operator. - - - - -
  • Return value

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

    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 kCache, vCache, kFlat, or vBias is a null pointer.
    kScaleCache or vScale is a null pointer when the kCache data type is FP8.
    ACLNN_ERR_PARAM_INVALID 161002 kCache dtype is not FLOAT8_E4M3FN.
    kScaleCache dtype is not FLOAT.
    vScale shape is not 1D [H_kv].
    kvLayout/stemBlockSize/stemStride do not meet the constraints.
    ACLNN_ERR_INNER 361001 Internal error, such as Tiling computation failure or Kernel lookup failure.

aclnnStemOamPrepPagedKv

  • Parameters

    Parameter Input/Output Description
    workspace Input Workspace memory address requested by the Device side.
    workspaceSize Input Size of the workspace requested by the Device side, obtained by the first-phase API aclnnStemOamPrepPagedKvGetWorkspaceSize.
    executor Input The op executor, which includes computation flow of the operator.
    stream Input Stream for executing tasks.
  • Return Value

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

Constraints

  • kvBlockSize must be 64 or 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 <cstring>
#include "acl/acl.h"
#include "aclnnop/aclnn_stem_oam_prep_paged_kv.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) {
  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, aclFormat format) {
  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, format,
                            shape.data(), shape.size(), *deviceAddr);
  return 0;
}

int main() {
  int32_t deviceId = 0;
  aclrtStream stream;
  auto ret = Init(deviceId, &stream);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("Init acl failed. ERROR: %d\n", ret); return ret);

  int64_t batch = 1;
  int64_t totalBlocks = 8;
  int64_t numKvHeads = 4;
  int64_t dimQk = 128;
  int64_t maxKvBlocks = 2;
  int64_t stemBlockSize = 128;
  int64_t stemStride = 16;
  int64_t maxKb = 2;
  int64_t kflatDim = stemStride * dimQk;
  char *kvLayout = "BNBD";

  std::vector<int64_t> kCacheShape = {totalBlocks, numKvHeads, 64, dimQk};
  std::vector<int64_t> kvIndicesShape = {batch, maxKvBlocks};
  std::vector<int64_t> kScaleCacheShape = {totalBlocks, numKvHeads, 64, 1};
  std::vector<int64_t> vScaleShape = {numKvHeads};
  std::vector<int64_t> kFlatShape = {batch, numKvHeads, maxKb, kflatDim};
  std::vector<int64_t> vBiasShape = {batch, numKvHeads, maxKb};

  void* kCacheDeviceAddr = nullptr;
  void* vCacheDeviceAddr = nullptr;
  void* kvIndicesDeviceAddr = nullptr;
  void* kScaleCacheDeviceAddr = nullptr;
  void* vScaleDeviceAddr = nullptr;
  void* kFlatDeviceAddr = nullptr;
  void* vBiasDeviceAddr = nullptr;

  aclTensor* kCache = nullptr;
  aclTensor* vCache = nullptr;
  aclTensor* kvIndices = nullptr;
  aclIntArray* kvSeqLens = nullptr;
  aclTensor* kScaleCache = nullptr;
  aclTensor* vScale = nullptr;
  aclTensor* kFlat = nullptr;
  aclTensor* vBias = nullptr;

  std::vector<uint8_t> hostKCache(GetShapeSize(kCacheShape), 1);
  std::vector<uint8_t> hostVCache(GetShapeSize(kCacheShape), 1);
  std::vector<int32_t> hostKvIndices({0, 1, 2, 3, 4, 5, 6, 7});
  std::vector<int64_t> hostKvSeqLens({128});
  std::vector<float> hostKScaleCache(GetShapeSize(kScaleCacheShape), 1.0f);
  std::vector<float> hostVScale(numKvHeads, 1.0f);
  std::vector<uint16_t> hostKFlat(GetShapeSize(kFlatShape), 0);
  std::vector<float> hostVBias(GetShapeSize(vBiasShape), 0.0f);

  ret = CreateAclTensor(hostKCache, kCacheShape, &kCacheDeviceAddr, aclDataType::ACL_FLOAT8_E4M3FN, &kCache, aclFormat::ACL_FORMAT_ND);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  ret = CreateAclTensor(hostVCache, kCacheShape, &vCacheDeviceAddr, aclDataType::ACL_FLOAT8_E4M3FN, &vCache, aclFormat::ACL_FORMAT_ND);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  ret = CreateAclTensor(hostKvIndices, kvIndicesShape, &kvIndicesDeviceAddr, aclDataType::ACL_INT32, &kvIndices, aclFormat::ACL_FORMAT_ND);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  kvSeqLens = aclCreateIntArray(hostKvSeqLens.data(), hostKvSeqLens.size());
  ret = CreateAclTensor(hostKScaleCache, kScaleCacheShape, &kScaleCacheDeviceAddr, aclDataType::ACL_FLOAT, &kScaleCache, aclFormat::ACL_FORMAT_ND);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  ret = CreateAclTensor(hostVScale, vScaleShape, &vScaleDeviceAddr, aclDataType::ACL_FLOAT, &vScale, aclFormat::ACL_FORMAT_ND);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  ret = CreateAclTensor(hostKFlat, kFlatShape, &kFlatDeviceAddr, aclDataType::ACL_BF16, &kFlat, aclFormat::ACL_FORMAT_ND);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  ret = CreateAclTensor(hostVBias, vBiasShape, &vBiasDeviceAddr, aclDataType::ACL_FLOAT, &vBias, aclFormat::ACL_FORMAT_ND);
  CHECK_RET(ret == ACL_SUCCESS, return ret);

  uint64_t workspaceSize = 0;
  aclOpExecutor* executor;
  ret = aclnnStemOamPrepPagedKvGetWorkspaceSize(
      kCache, vCache, kvIndices, kvSeqLens, kScaleCache, vScale,
      0.3, kvLayout, stemBlockSize, stemStride,
      kFlat, vBias, &workspaceSize, &executor);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("GetWorkspaceSize 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);
  }
  ret = aclnnStemOamPrepPagedKv(workspaceAddr, workspaceSize, executor, stream);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnStemOamPrepPagedKv 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);

  auto size = GetShapeSize(kFlatShape);
  std::vector<uint16_t> resultData(size, 0);
  ret = aclrtMemcpy(resultData.data(), resultData.size() * sizeof(resultData[0]), kFlatDeviceAddr,
                    size * sizeof(resultData[0]), ACL_MEMCPY_DEVICE_TO_HOST);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("copy result failed. ERROR: %d\n", ret); return ret);
  for (int64_t i = 0; i < size && i < 10; i++) {
    float val;
    uint16_t bf16 = resultData[i];
    uint32_t bits = static_cast<uint32_t>(bf16) << 16;
    std::memcpy(&val, &bits, sizeof(val));
    LOG_PRINT("result[%ld] is: %f\n", i, val);
  }

  aclDestroyTensor(kCache);
  aclDestroyTensor(vCache);
  aclDestroyTensor(kvIndices);
  aclDestroyIntArray(kvSeqLens);
  aclDestroyTensor(kScaleCache);
  aclDestroyTensor(vScale);
  aclDestroyTensor(kFlat);
  aclDestroyTensor(vBias);

  aclrtFree(kCacheDeviceAddr);
  aclrtFree(vCacheDeviceAddr);
  aclrtFree(kvIndicesDeviceAddr);
  aclrtFree(kScaleCacheDeviceAddr);
  aclrtFree(vScaleDeviceAddr);
  aclrtFree(kFlatDeviceAddr);
  aclrtFree(vBiasDeviceAddr);
  if (workspaceSize > 0) {
    aclrtFree(workspaceAddr);
  }
  aclrtDestroyStream(stream);
  aclrtResetDevice(deviceId);
  aclFinalize();
  return 0;
}