aclnnLightningIndexerKLLoss

Applicable Products

  • Ascend 950PR&950DT products: Not 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: lightning_indexer_kl_loss computes the KL divergence loss between the teacher distribution and the student distribution in the Lightning Indexer.

    • teacher side (target_score): unnormalized raw primary attention scores of the compressed segment (sum ≠ 1). clamp_min is used to prevent NaN caused by log(0) at y=0.
    • student side (index_probs): probability distribution after indexer softmax. +eps is used to preserve the gradient at Y→0.
  • Formula:

    $$ y = \text{target\_score}, \quad Y = \text{index\_probs} $$
    $$ P = \frac{y}{\text{sum}(y, \text{dim}=-1, \text{keepdim=True}) + \varepsilon} $$
    $$ \log\_P = \log(\text{clamp\_min}(\tilde{y}, \varepsilon)) $$
    $$ \log\_Y = \log(Y + \varepsilon) $$
    $$ \text{loss} = \sum((\log\_P - \log\_Y) \cdot \text{weight}) $$

    where $\varepsilon$ is the eps parameter.

    The selection of weight is controlled by weight_type:

    • 'logits': weight = y, i.e., the raw unnormalized score
    • 'probs': weight = P, i.e., the normalized probability

Function Prototype

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

aclnnStatus aclnnLightningIndexerKLLossGetWorkspaceSize(
  const aclTensor   *targetScore,
  const aclTensor   *indexProbs,
  double             eps,
  const char        *weightType,
  const aclTensor   *loss,
  uint64_t          *workspaceSize,
  aclOpExecutor    **executor)
aclnnStatus aclnnLightningIndexerKLLoss(
  void             *workspace,
  uint64_t          workspaceSize,
  aclOpExecutor    *executor,
  aclrtStream       stream)

aclnnLightningIndexerKLLossGetWorkspaceSize

  • Parameters

    Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor
    targetScore Input Unnormalized raw main attention scores of the teacher. Supported shapes: (T, K) or (B, S, K). FLOAT16, BFLOAT16, FLOAT ND 2-3 √
    indexProbs Input Probability distribution of the student after softmax. Same shape as targetScore. FLOAT16, BFLOAT16, FLOAT ND 2-3 √
    eps Attribute Numerical stability constant. Prevents NaN caused by log(0). double - - -
    weightType Attribute Outer weight selection, 'logits' or 'probs'. 'logits' uses the raw target_score as the outer weight, and 'probs' uses the normalized probability P = target_score / sum(target_score) as the outer weight. string - - -
    loss Output Loss function value, scalar. Same data type as targetScore. Shape is (1). FLOAT16, BFLOAT16, FLOAT ND 1 √
    workspaceSize Output Returns the workspace size to be allocated 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.

aclnnLightningIndexerKLLoss

  • 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 aclnnLightningIndexerKLLossGetWorkspaceSize.
    executor Input Op executor that contains the operator computation process.
    stream Input Stream for executing tasks.
  • Return Value

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

Constraints

  • Deterministic computation:
    • aclnnLightningIndexerKLLoss defaults to a non-deterministic implementation. Deterministic computation can be enabled by calling aclrtCtxSetSysParamOpt.
  • Input shape constraints:
    • Supported shapes are (B, S, K) or (T, K), where B is in the range 1~512, and the last dimension K is in the range 1~8192.
  • eps must be greater than 0.
  • weight_type must be 'logits' or 'probs'.

Example

The following sample code shows the aclnn single-operator call, for reference only. For details about the compilation and execution process, see Compile and Run Samples.

#include <iostream>
#include <vector>
#include <cstdint>
#include <cmath>
#include "acl/acl.h"
#include "aclnnop/aclnn_lightning_indexer_kl_loss.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<float> 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("result[%ld] is: %f\n", i, resultData[i]);
  }
}

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() {
  // 1. Initialize the device/context/stream.
  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 inputs and outputs.
  // target_score: (B, S, K) = (2, 4, 128), float32, unnormalized raw attention scores
  // index_probs:  (B, S, K) = (2, 4, 128), float32, probability distribution after softmax
  // loss:         scalar (1,), float32
  int64_t b = 2;
  int64_t s = 4;
  int64_t k = 128;
  std::vector<int64_t> inputShape = {b, s, k};
  std::vector<int64_t> lossShape = {1};

  std::vector<float> targetScoreHostData(b * s * k, 0);
  for (int64_t i = 0; i < b * s * k; i++) {
    targetScoreHostData[i] = static_cast<float>(rand()) / static_cast<float>(RAND_MAX) * 2.0f;
  }

  std::vector<float> indexProbsHostData(b * s * k, 0);
  for (int64_t bs = 0; bs < b * s; bs++) {
    float sum = 0.0f;
    for (int64_t j = 0; j < k; j++) {
      indexProbsHostData[bs * k + j] = static_cast<float>(rand()) / static_cast<float>(RAND_MAX);
      sum += indexProbsHostData[bs * k + j];
    }
    for (int64_t j = 0; j < k; j++) {
      indexProbsHostData[bs * k + j] /= sum;
    }
  }

  std::vector<float> lossHostData(1, 0.0f);

  void* targetScoreDeviceAddr = nullptr;
  void* indexProbsDeviceAddr = nullptr;
  void* lossDeviceAddr = nullptr;

  aclTensor* targetScore = nullptr;
  aclTensor* indexProbs = nullptr;
  aclTensor* loss = nullptr;

  ret = CreateAclTensor(targetScoreHostData, inputShape, &targetScoreDeviceAddr,
                        aclDataType::ACL_FLOAT, &targetScore);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  ret = CreateAclTensor(indexProbsHostData, inputShape, &indexProbsDeviceAddr,
                        aclDataType::ACL_FLOAT, &indexProbs);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  ret = CreateAclTensor(lossHostData, lossShape, &lossDeviceAddr,
                        aclDataType::ACL_FLOAT, &loss);
  CHECK_RET(ret == ACL_SUCCESS, return ret);

  // eps parameter
  double eps = 1e-9;

  // 3. Call the C(A)NN operator library API.
  uint64_t workspaceSize = 0;
  aclOpExecutor* executor;

  // Call the first-phase API aclnnLightningIndexerKLLossGetWorkspaceSize.
  ret = aclnnLightningIndexerKLLossGetWorkspaceSize(
      targetScore, indexProbs, eps, "logits", loss, &workspaceSize, &executor);
  CHECK_RET(ret == ACL_SUCCESS,
            LOG_PRINT("aclnnLightningIndexerKLLossGetWorkspaceSize failed. ERROR: %d\n", ret);
            return ret);

  // Allocate device memory based on workspaceSize.
  void* workspaceAddr = nullptr;
  if (workspaceSize > static_cast<uint64_t>(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 aclnnLightningIndexerKLLoss.
  ret = aclnnLightningIndexerKLLoss(workspaceAddr, workspaceSize, executor, stream);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnLightningIndexerKLLoss failed. ERROR: %d\n", ret); return ret);

  // 4. 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 values.
  PrintOutResult(lossShape, &lossDeviceAddr);

  // 6. Destroy the aclTensor.
  aclDestroyTensor(targetScore);
  aclDestroyTensor(indexProbs);
  aclDestroyTensor(loss);

  // 7. Release device resources.
  aclrtFree(targetScoreDeviceAddr);
  aclrtFree(indexProbsDeviceAddr);
  aclrtFree(lossDeviceAddr);
  if (workspaceSize > static_cast<uint64_t>(0)) {
    aclrtFree(workspaceAddr);
  }
  aclrtDestroyStream(stream);
  aclrtDestroyContext(context);
  aclrtResetDevice(deviceId);
  aclFinalize();

  return 0;
}