aclnnAttentionUpdate

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: Updates the intermediate results lse and localOut output by the PA operator in each SP domain into global results.
  • Formula:
$$ lse_{max} = \text{max}lse_i $$
$$ lse = \sum_i \text{exp}(lse_i - lse_{max}) $$
$$ lse_m = lse_{max} + \text{log}(lse) $$
$$ O = \sum_i O_i \cdot \text{exp}(lse_i - lse_m) $$

Function Prototype

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

aclnnStatus aclnnAttentionUpdateGetWorkspaceSize(
   const aclTensorList  *lse,
   const aclTensorList  *localOut,
   int64_t              updateType,
   aclTensor            *out,
   aclTensor            *lseOut,
   uint64_t             *workspaceSize,
   aclOpExecutor        **executor)
aclnnStatus aclnnAttentionUpdate(
   void          *workspace,
   uint64_t       workspaceSize,
   aclOpExecutor *executor,
   aclrtStream    stream)

aclnnAttentionUpdateGetWorkspaceSize

  • Parameters

    Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor
    lse Input Local lse of each SP domain. The length of tensorList is sp. FLOAT32 ND [batch * seqLen * headNum] x
    localOut Input Local attentionout of each SP domain. The length of tensorList is sp. FLOAT32, FLOAT16, BFLOAT16 ND [batch * seqLen * headNum, headDim] x
    updateType Input Controls whether lseOut is output. 0 and 1 are supported, indicating that lseOut is not output and lseOut is output respectively. INT64 - - -
    out Output Output tensor. - Same as localOut ND [batch * seqLen * headNum, headDim] x
    lseOut Optional output Serves as the optional output of lse_m. If lseOut is not required, pass in nullptr. FLOAT32 ND [batch * seqLen * headNum] x
    workspaceSize Output Returns the workspace size that needs to be requested on the Device. - - - - -
    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 input lse, localOut, or out is a null pointer.
    ACLNN_ERR_PARAM_INVALID 161002 The data type/data format of lse, localOut, or out is not within the supported range.
    updateType or sp is out of the value range.
    The shape of lse, localOut, or out does not meet the constraints.
    When updateType is 0, lseOut is not nullptr.
    When updateType is 1, lseOut is nullptr.

aclnnAttentionUpdate

  • Parameters

    Parameter Input/Output Description
    workspace Input Workspace memory address allocated on the Device side.
    workspaceSize Input Workspace size allocated on the Device side, obtained by the first-phase API aclnnAttentionUpdateGetWorkspaceSize.
    executor Input op executor, including the operator computation flow.
    stream Input Specifies the stream for executing tasks.
  • Return Value

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

Constraints

  • Deterministic computation:

    • aclnnAttentionUpdate defaults to a deterministic implementation.
  • Value range of the sequence parallelism degree sp:

    • Atlas A2 products and Atlas A3 products: [1, 128].
    • Ascend 950PR&950DT products: [1, 16].
  • headDim ranges from 8 to 512 and is a multiple of 8.

  • Empty tensors are supported.

Example

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

#include <iostream>
#include <memory>
#include <vector>
#include "acl/acl.h"
#include "aclnnop/aclnn_attention_update.h"

#define CHECK_RET(cond, return_expr) \
  do {                               \
    if (!(cond)) {                   \
      return_expr;                   \
    }                                \
  } while (0)

#define CHECK_FREE_RET(cond, return_expr) \
  do {                                     \
      if (!(cond)) {                       \
          Finalize(deviceId, stream);      \
          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 for 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.
  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 data from the host to the 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);

  // Calculate the stride of a contiguous tensor.
  std::vector<int64_t> stride(shape.size(), 1);
  for (int64_t i = shape.size() - 2; i >= 0; i--) {
    stride[i] = shape[i + 1] * stride[i + 1];
  }

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

void Finalize(int32_t deviceId, aclrtStream stream)
{
  aclrtDestroyStream(stream);
  aclrtResetDevice(deviceId);
  aclFinalize();
}

aclnnStatus aclnnAttentionUpdateTest(int32_t deviceId, aclrtStream& stream) {
  auto ret = Init(deviceId, &stream);
  CHECK_FREE_RET(ret == ACL_SUCCESS, LOG_PRINT("Init acl failed. ERROR: %d\n", ret); return ret);

  // 2. Construct the input and output, which must be custom-built as required by the API.

  std::vector<int64_t> lseShape = {256};
  std::vector<int64_t> localOutShape = {256, 128};
  std::vector<int64_t> outShape = {256, 128};

  int64_t updateType = 0;

  void* lseDeviceAddr[2] = {nullptr, nullptr};
  void* localOutDeviceAddr[2] = {nullptr, nullptr};
  void* outDeviceAddr = nullptr;

  std::vector<aclTensor*> lse = {nullptr, nullptr};
  std::vector<aclTensor*> localOut = {nullptr, nullptr};
  aclTensor* out = nullptr;

  std::vector<float> lse1HostData(GetShapeSize(lseShape), 1);
  std::vector<float> lse2HostData(GetShapeSize(lseShape), 1);
  std::vector<float> localOut1HostData(GetShapeSize(localOutShape), 1);
  std::vector<float> localOut2HostData(GetShapeSize(localOutShape), 1);
  std::vector<float> outHostData(GetShapeSize(outShape), 0);

  // Create the lse aclTensorList.
  ret = CreateAclTensor(lse1HostData, lseShape, &(lseDeviceAddr[0]), aclDataType::ACL_FLOAT, &(lse[0]));
  std::unique_ptr<aclTensor, aclnnStatus (*)(const aclTensor *)> lse1TensorPtr(lse[0], aclDestroyTensor);
  std::unique_ptr<void, aclError (*)(void *)> lse1DeviceAddrPtr(lseDeviceAddr[0], aclrtFree);
  CHECK_FREE_RET(ret == ACL_SUCCESS, return ret);
  ret = CreateAclTensor(lse2HostData, lseShape, &(lseDeviceAddr[1]), aclDataType::ACL_FLOAT, &(lse[1]));
  std::unique_ptr<aclTensor, aclnnStatus (*)(const aclTensor *)> lse2TensorPtr(lse[1], aclDestroyTensor);
  std::unique_ptr<void, aclError (*)(void *)> lse2DeviceAddrPtr(lseDeviceAddr[1], aclrtFree);
  CHECK_FREE_RET(ret == ACL_SUCCESS, return ret);

  aclTensorList *lseList = aclCreateTensorList(lse.data(), lse.size());

  // Create the localOut aclTensorList.
  ret = CreateAclTensor(localOut1HostData, localOutShape, &(localOutDeviceAddr[0]), aclDataType::ACL_FLOAT, &(localOut[0]));
  std::unique_ptr<aclTensor, aclnnStatus (*)(const aclTensor *)> localOut1TensorPtr(localOut[0], aclDestroyTensor);
  std::unique_ptr<void, aclError (*)(void *)> localOut1DeviceAddrPtr(localOutDeviceAddr[0], aclrtFree);
  CHECK_FREE_RET(ret == ACL_SUCCESS, return ret);
  ret = CreateAclTensor(localOut2HostData, localOutShape, &(localOutDeviceAddr[1]), aclDataType::ACL_FLOAT, &(localOut[1]));
  std::unique_ptr<aclTensor, aclnnStatus (*)(const aclTensor *)> localOut2TensorPtr(localOut[1], aclDestroyTensor);
  std::unique_ptr<void, aclError (*)(void *)> localOut2DeviceAddrPtr(localOutDeviceAddr[1], aclrtFree);
  CHECK_FREE_RET(ret == ACL_SUCCESS, return ret);

  aclTensorList *localOutList = aclCreateTensorList(localOut.data(), localOut.size());

  // Create the out aclTensor.
  ret = CreateAclTensor(outHostData, outShape, &outDeviceAddr, aclDataType::ACL_FLOAT, &out);
  std::unique_ptr<aclTensor, aclnnStatus (*)(const aclTensor *)> outTensorPtr(out, aclDestroyTensor);
  std::unique_ptr<void, aclError (*)(void *)> outDeviceAddrPtr(outDeviceAddr, aclrtFree);
  CHECK_FREE_RET(ret == ACL_SUCCESS, return ret);

  // 3. Call the CANN operator library API and change the API name to the specific one.
  uint64_t workspaceSize = 0;
  aclOpExecutor* executor;
  // Call the aclnnAttentionUpdate first-phase API.
  ret = aclnnAttentionUpdateGetWorkspaceSize(lseList,
                                       localOutList,
                                       updateType,
                                       out,
                                       nullptr,
                                       &workspaceSize,
                                       &executor);
  CHECK_FREE_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnAttentionUpdateGetWorkspaceSize failed. ERROR: %d\n", ret); return ret);
  // Allocate device memory based on the workspaceSize calculated by the first-phase API.
  void* workspaceAddr = nullptr;
  std::unique_ptr<void, aclError (*)(void *)> workspaceAddrPtr(nullptr, aclrtFree);
  if (workspaceSize > 0) {
    ret = aclrtMalloc(&workspaceAddr, workspaceSize, ACL_MEM_MALLOC_HUGE_FIRST);
    CHECK_FREE_RET(ret == ACL_SUCCESS, LOG_PRINT("allocate workspace failed. ERROR: %d\n", ret); return ret);
    workspaceAddrPtr.reset(workspaceAddr);
  }
  // Call the aclnnAttentionUpdate second-phase API.
  ret = aclnnAttentionUpdate(workspaceAddr, workspaceSize, executor, stream);
  CHECK_FREE_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnAttentionUpdate failed. ERROR: %d\n", ret); return ret);

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

  // 5. Obtain the output value and copy the result from device memory to the host side. Modify the code according to the definition of the specific API.
  auto size = GetShapeSize(outShape);
  std::vector<float> outData(size, 0);
  ret = aclrtMemcpy(outData.data(), outData.size() * sizeof(outData[0]), outDeviceAddr,
                    size * sizeof(outData[0]), ACL_MEMCPY_DEVICE_TO_HOST);
  CHECK_FREE_RET(ret == ACL_SUCCESS, LOG_PRINT("copy result from device to host failed. ERROR: %d\n", ret); return ret);
  for (int64_t i = 0; i < size; i++) {
    LOG_PRINT("out result[%ld] is: %f\n", i, outData[i]);
  }

  return ACL_SUCCESS;
}

int main() {
  // 1. (boilerplate) Initialize the device/stream. For details, see the list of external APIs.
  // Set deviceId based on your actual device.
  int32_t deviceId = 0;
  aclrtStream stream;
  auto ret = aclnnAttentionUpdateTest(deviceId, stream);
  CHECK_FREE_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnAttentionUpdateTest failed. ERROR: %d\n", ret); return ret);

  Finalize(deviceId, stream);
  return 0;
}