aclnnQkvRmsNormRopeCache

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: Inputs a fused QKV tensor, splits it into Q, K, and V tensors via SplitVD, performs RmsNorm, ApplyRotaryPosEmb, Quant, and Scatter fusion operations, and outputs qOut, kCache, vCache, qBeforeQuant (optional), kBeforeQuant (optional), and vBeforeQuant (optional).

  • The scenarios currently supported by this API are as follows:

    Scenario TypeOverview
    • cacheMode is PA_NZ
    • Q is non-quantized
    • K and V support non-quantized, symmetric quantization, and asymmetric quantization
    • qBeforeQuant/kBeforeQuant/vBeforeQuant are not output
    The qkv shape is [$B_{qkv}$ $S_{qkv}$, $N_{qkv}$ $D_{qkv}$]. q, k, and v have exactly the same D dimension. Main computation process and corresponding outputs:
    • qkv through SplitVD->q, k, v
    • q through RmsNorm, RoPE->qOut
    • k through RmsNorm, RoPE, Quant(optional), Scatter->kCache
    • v through Quant(optional), Scatter->vCache
  • Formula:

    (1) SplitVD:

    In the following formula, $N_q$, $N_k$, and $N_v$ denote the numbers of attention heads of the q, k, and v components, respectively. The following conditions must be met:

    $$ \begin{cases} N_k = N_v \\ N_{qkv} = N_k + N_v + N_q \\ D_{qkv} = D_q = D_k = D_v \end{cases} $$
    $$ \begin{aligned} q &= qkv[..., [:N_q] * D_{qkv}] \\ k &= qkv[..., [N_q:-N_v] * D_{qkv}] \\ v &= qkv[..., [-N_v:] * D_{qkv}] \end{aligned} $$

    (2) RmsNorm:

    Here, x and y represent the input tensor and output tensor of RmsNorm, respectively. The normalization is performed along the last dimension (feature dimension). This computation rule applies to both q and k components.

    $$ squareX = x * x $$
    $$ meanSquareX = squareX.mean(dim = -1, keepdim = True) $$
    $$ rms = \sqrt{meanSquareX + epsilon} $$
    $$ y = (x / rms) * gamma $$

    (3) RoPE (Half-and-Half):

    Here, y refers to the output result after completing the RmsNorm computation.

    $$ y1 = y[\ldots, :d/2] $$
    $$ y2 = y[\ldots, d/2:] $$
    $$ y\_RoPE = torch.cat((-y2, y1), dim = -1) $$
    $$ y\_embed = (y * cos) + y\_RoPE * sin $$

    (4) Quant:

    Non-quantized:

    $$ kQuant = kRoPE \\ vQuant = v $$

    Symmetric quantization:

    $$ kQuant = kRoPE / kScale \\ vQuant = v / vScale $$

    Asymmetric quantization part:

    $$ kQuant = kRoPE / kScale + kOffset \\ vQuant = v / vScale + vOffset $$

Function Prototype

Each operator uses a two-phase API. You must first call the "aclnnQkvRmsNormRopeCacheGetWorkspaceSize" API to obtain the input parameters and calculate the required workspace size according to the process, and then call the "aclnnQkvRmsNormRopeCache" API to perform the computation.

aclnnStatus aclnnQkvRmsNormRopeCacheGetWorkspaceSize(
  const aclTensor   *qkv,
  const aclTensor   *qGamma,
  const aclTensor   *kGamma,
  const aclTensor   *cos,
  const aclTensor   *sin,
  const aclTensor   *index,
  aclTensor         *qOut,
  aclTensor         *kCache,
  aclTensor         *vCache,
  const aclTensor   *kScaleOptional,
  const aclTensor   *vScaleOptional,
  const aclTensor   *kOffsetOptional,
  const aclTensor   *vOffsetOptional,
  const aclIntArray *qkvSize,
  const aclIntArray *headNums,
  double             epsilon,
  char              *cacheModeOptional,
  const aclTensor   *qOutBeforeQuant,
  const aclTensor   *kOutBeforeQuant,
  const aclTensor   *vOutBeforeQuant,
  uint64_t          *workspaceSize,
  aclOpExecutor     **executor)
aclnnStatus aclnnQkvRmsNormRopeCache(
  void            *workspace,
  uint64_t         workspaceSize,
  aclOpExecutor   *executor,
  aclrtStream      stream)

aclnnQkvRmsNormRopeCacheGetWorkspaceSize

  • Parameters:

    Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor
    qkv Input Input data used for splitting q, k, v, corresponding to qkv in the formula.
    • Does not support null Tensor.
    • shape is [Bqkv * Sqkv, Nqkv * Dqkv].
    FLOAT16, BFLOAT16 ND 2 √
    qGamma Input Input data used for q rms_norm computation, corresponding to gamma in the formula.
    • Does not support null Tensor.
    • Same data type as input qkv.
    • The shape is [Dqkv].
    FLOAT16, BFLOAT16 ND 1 √
    kGamma Input Input data used for the rms_norm computation of k, corresponding to gamma in the formula.
    • Does not support null Tensor.
    • Same data type as input qkv.
    • The shape is [Dqkv].
    FLOAT16, BFLOAT16 ND 1 √
    cos Input Input data used for the rope computation. Performs cosine transformation on the input tensor, corresponding to cos in the formula.
    • Does not support null Tensor.
    • The data type is the same as the input qkv.
    • The shape is [Bqkv * Sqkv, 1 * D_rope], D_rope = Dqkv, and (Dqkv * number of bytes occupied by the qkv data type) must be divisible by 32.
    FLOAT16, BFLOAT16 ND 2 √
    sin Input Input data used for rope computation. Applies sine transformation to the input tensor, corresponding to sin in the formula.
    • Null tensors are not supported.
    • The data type and format must remain consistent with the input cos.
    FLOAT16, BFLOAT16 ND 2 √
    index Input Used for specifying the specific index position to write to the cache, corresponding to index in the formula.
    • Does not support null Tensor.
    • The data type is the same as the input qkv.
    • The shape is [Bqkv * Sqkv]. The value of index must not be repeated, and the value range is [-1, BlockNum * BlockSize].
    INT64 ND 1 √
    qOut Input \ Output The cache applied for. The input/output reuses the same address (in-place operation).
    • Does not support null tensors.
    • Data type is the same as the input qkv.
    • shape is [Bqkv * Sqkv, Nq * Dqkv].
    FLOAT16, BFLOAT16 ND 2 √
    kCache Input \ Output The cache applied for; input and output are reused at the same address (in-place operation).
    • Does not support null tensors.
    • Data type is the same as the input qkv (k non-quantization), or INT8 (k quantization).
    • shape is [BlockNum, Nk * Dqkv // 16, BlockSize, 16] (k non-quantization), or [BlockNum, Nk * Dqkv // 32, BlockSize, 32] (k quantization).
    FLOAT16, BFLOAT16, INT8 ND 4 √
    vCache Input \ Output The cache applied for, with input/output as an in-place operation.
    • Does not support null Tensor.
    • The same data type as the input qkv (non-quantization), or INT8 (quantization).
    • The shape is [BlockNum, Nk * Dqkv // 16, BlockSize, 16] (non-quantization), or [BlockNum, Nk * Dqkv // 32, BlockSize, 32] (quantization).
    FLOAT16, BFLOAT16, INT8 ND 4 √
    kScaleOptional Optional input Required when kCache is of the INT8 data type. Corresponds to kScale in the formula. The shape is [Nk, Dqkv]. FLOAT32 ND 2 √
    vScaleOptional Optional input Required when the data type of vCache is INT8. Corresponds to vScale in the formula. The shape is [Nv, Dqkv]. FLOAT32 ND 2 √
    kOffsetOptional Optional input Corresponds to kOffset in the formula.
    • This parameter is required when the data type of kCache is INT8, the corresponding kScaleOptional input exists, and the quantization scenario is asymmetric quantization.
    • Shape is [Nk, Dqkv].
    FLOAT32 ND 2 √
    vOffsetOptional Optional input Corresponds to vOffset in the formula.
    • This parameter is required when the data type of vCache is INT8, the corresponding vScaleOptional input exists, and the quantization scenario is asymmetric quantization.
    • Shape is [Nv, Dqkv].
    FLOAT32 ND 2 √
    qkvSize Input Passed in the order of [Bqkv, Sqkv, Nqkv, Dqkv], providing the specific sizes of the B, S, N, and D dimensions of the qkv matrix of input parameter qkvSize.
    • Requirement: Nqkv = Nq + Nk + Nv.
    • The number of elements must be exactly 4, and each element must be a non-zero valid positive integer.
    INT64 - - -
    headNums Input Passed in the order of [Nq, Nk, Nv]. Specifies the sizes of the N dimension of each qkv component split from the input qkv tensor. [Nq, Nk, Nv] must be the actual original values and cannot be reduced. INT64 - - -
    epsilon Input Prevents division by 0 in RmsNorm computation. Corresponding computation: epsilon in the formula. Recommended value: 1e-6 FLOAT32 - - -
    cacheModeOptional Input Indicates the cache format. The recommended value is "PA_NZ". CHAR* - - -
    qOutBeforeQuant Output Indicates that data is to be written to qOut.
    • Type classification and data type must remain consistent with the input parameter qkv.
    • The shape is [Bqkv * Sqkv, Nq * Dqkv].
    FLOAT16, BFLOAT16 ND 2 √
    kOutBeforeQuant Output Indicates the data to be written to vCache, that is, the intermediate computation result before quantization and Scatter.
    • The type classification and data type must remain consistent with those of the input parameter qkv.
    • The shape is [Bqkv * Sqkv, Nq * Dqkv].
    FLOAT16, BFLOAT16 ND 2 √
    vOutBeforeQuant Output Indicates that the data to be written to vCache is the intermediate computation result before quantization and Scatter.
    • The type classification and data type must remain consistent with the input parameter qkv.
    • The shape is [Bqkv * Sqkv, Nq * Dqkv].
    FLOAT16, BFLOAT16 ND 2 √
    workspaceSize Output Returns the workspace size to be applied for on the Device. - - - - -
    executor Output Returns the op executor containing the operator computation 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 The input qkv, qGamma, kGamma, cos, sin, etc. are null pointers.
    ACLNN_ERR_PARAM_INVALID 161002 The data type of the input or output is not within the supported range.
    The dimensions of the input or output parameters are not within the supported range.
    dim is not within the specified value range.

aclnnQkvRmsNormRopeCache

  • Parameters:

    Parameter Input/Output Description
    workspace Input Memory address of the workspace applied by the device side.
    workspaceSize Input Size of the workspace applied by the device side, obtained by the first-phase API aclnnQkvRmsNormRopeCacheGetWorkspaceSize.
    executor Input op executor, which contains the operator computation flow.
    stream Input Stream for task execution.
  • Return value

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

Constraints

  • Deterministic computation:

    • aclnnQkvRmsNormRopeCache defaults to a deterministic implementation.
  • Input shape constraints:

    • Bqkv is the batch_size of the input qkv, and Sqkv is the sequence length of the input qkv, whose size is determined by qkvSize.
    • Nqkv is the head number of the input qkv. Dqkv is the head dim of the input qkv, which currently supports only 128. Dq, Dk, and Dv are the head dims of q, k, and v respectively, requiring Dqkv = Dq = Dk = Dv. Dqkv must satisfy that (Dqkv * byte size of the qkv data type) is divisible by 32.
    • According to the rope rules, Dk and Dq must be even numbers. If cacheMode is PA_NZ, Dk and Dq must be 32-byte aligned; BlockSize must be 32-byte aligned.
    • For the 32B alignment cases described above, the alignment value is determined by the data type of the cache. Taking BlockSize as an example: if the cache data type is int8, BlockSize % 32 = 0 must be satisfied; if the cache data type is float16, BlockSize % 16 = 0 must be satisfied; if the dtypes of the kCache and vCache parameters are inconsistent, BlockSize must satisfy both BlockSize % 32 = 0 and BlockSize % 16 = 0.
    • BlockNum is the number of memory blocks written to the cache, and its size is determined by the user input scenario. It must satisfy BlockNum >= Ceil(Sqkv / BlockSize) * Bqkv.
    • requireMemory indicates the size of the space required to store data. The following requirement must be met: requireMemory >= (Bqkv Sqkv Nqkv Dqkv + 2 Dqkv + 2 Bqkv Sqkv Dqkv + Bqkv Sqkv Nq Dqkv + BlockNum BlockSize Nv Dqkv + BlockNum BlockSize Nk Dqkv) sizeof(FLOAT16) + Bqkv Sqkv sizeof(INT64) + (2 Nk Dqkv + 2 Nv) * sizeof(FLOAT). If the calculated requireMemory size exceeds the total GM space of the current AI processor, this API is not supported.
  • Other constraints:

    • For index, the value range of index values must be [-1, BlockNum * BlockSize). Values must not be duplicated. When index is -1, it indicates skipping the update.
    • kScaleOptional and vScaleOptional represent scaling factors for symmetric quantization, so their values cannot be 0 if passed.

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 "acl/acl.h"
#include "aclnnop/aclnn_qkv_rms_norm_rope_cache.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<int8_t> 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: %d\n", i, resultData[i]);
    }
}

int Init(int32_t deviceId, aclrtStream *stream)
{
    // Boilerplate for resource 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 device memory.
    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 an 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 for device/stream initialization. For details, see the acl API.
    // Set deviceId based on the actual device.
    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);

    // 2. Construct the input and output according to the API definition.
    std::vector<int64_t> qkvShape = {48, 2304};
    std::vector<int64_t> qGammaShape = {128};
    std::vector<int64_t> kGammaShape = {128};
    std::vector<int64_t> cosShape = {48, 128};
    std::vector<int64_t> sinShape = {48, 128};
    std::vector<int64_t> indexShape = {48};
    std::vector<int64_t> qOutShape = {48, 2048};
    std::vector<int64_t> kCacheShape = {16, 4, 128, 32};
    std::vector<int64_t> vCacheShape = {16, 4, 128, 32};
    std::vector<int64_t> kScaleShape = {1, 128};
    std::vector<int64_t> vScaleShape = {1, 128};
    std::vector<int64_t> qkv_size_list = {16, 3, 18, 128};
    std::vector<int64_t> head_nums_list = {16, 1, 1};

    std::vector<int16_t> qkvHostData(48 * 2304, 0);
    std::vector<int16_t> qGammaHostData(128, 0);
    std::vector<int16_t> kGammaHostData(128, 0);
    std::vector<int16_t> cosHostData(48 * 128, 0);
    std::vector<int16_t> sinHostData(48 * 128, 0);
    std::vector<int64_t> indexHostData(48, 0);
    std::vector<int16_t> qOutHostData(48 * 2048, 0);
    std::vector<int16_t> kCacheHostData(16 * 4 * 128 * 32, 0);
    std::vector<int16_t> vCacheHostData(16 * 4 * 128 * 32, 0);
    std::vector<float> kScaleHostData(1 * 128, 0.0f);
    std::vector<float> vScaleHostData(1 * 128, 0.0f);

    void *qkvDeviceAddr = nullptr;
    void *qGammaDeviceAddr = nullptr;
    void *kGammaDeviceAddr = nullptr;
    void *cosDeviceAddr = nullptr;
    void *sinDeviceAddr = nullptr;
    void *indexDeviceAddr = nullptr;
    void *qOutDeviceAddr = nullptr;
    void *kCacheDeviceAddr = nullptr;
    void *vCacheDeviceAddr = nullptr;
    void *kScaleDeviceAddr = nullptr;
    void *vScaleDeviceAddr = nullptr;

    aclTensor *qkv = nullptr;
    aclTensor *qGamma = nullptr;
    aclTensor *kGamma = nullptr;
    aclTensor *cos = nullptr;
    aclTensor *sin = nullptr;
    aclTensor *index = nullptr;
    aclTensor *qOut = nullptr;
    aclTensor *kCache = nullptr;
    aclTensor *vCache = nullptr;
    aclTensor *kScale = nullptr;
    aclTensor *vScale = nullptr;

    aclIntArray *qkv_size = aclCreateIntArray(qkv_size_list.data(), qkv_size_list.size());
    aclIntArray *head_nums = aclCreateIntArray(head_nums_list.data(), head_nums_list.size());

    double epsilon = 1e-6;
    char *cacheMode = "PA_NZ";

    ret = CreateAclTensor(qkvHostData, qkvShape, &qkvDeviceAddr, aclDataType::ACL_FLOAT16, &qkv);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    ret = CreateAclTensor(qGammaHostData, qGammaShape, &qGammaDeviceAddr, aclDataType::ACL_FLOAT16, &qGamma);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    ret = CreateAclTensor(kGammaHostData, kGammaShape, &kGammaDeviceAddr, aclDataType::ACL_FLOAT16, &kGamma);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    ret = CreateAclTensor(cosHostData, cosShape, &cosDeviceAddr, aclDataType::ACL_FLOAT16, &cos);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    ret = CreateAclTensor(sinHostData, sinShape, &sinDeviceAddr, aclDataType::ACL_FLOAT16, &sin);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    ret = CreateAclTensor(indexHostData, indexShape, &indexDeviceAddr, aclDataType::ACL_INT64, &index);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    ret = CreateAclTensor(qOutHostData, qOutShape, &qOutDeviceAddr, aclDataType::ACL_FLOAT16, &qOut);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    ret = CreateAclTensor(kCacheHostData, kCacheShape, &kCacheDeviceAddr, aclDataType::ACL_INT8, &kCache);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    ret = CreateAclTensor(vCacheHostData, vCacheShape, &vCacheDeviceAddr, aclDataType::ACL_INT8, &vCache);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    ret = CreateAclTensor(kScaleHostData, kScaleShape, &kScaleDeviceAddr, aclDataType::ACL_FLOAT, &kScale);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    ret = CreateAclTensor(vScaleHostData, vScaleShape, &vScaleDeviceAddr, aclDataType::ACL_FLOAT, &vScale);
    CHECK_RET(ret == ACL_SUCCESS, return ret);

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

    // Call the first-phase API of aclnnQkvRmsNormRopeCache.
    ret = aclnnQkvRmsNormRopeCacheGetWorkspaceSize(qkv, qGamma, kGamma, cos, sin, index, qOut, kCache, vCache, kScale,
                                                   vScale, nullptr, nullptr, qkv_size, head_nums, epsilon, cacheMode,
                                                   nullptr, nullptr, nullptr, &workspaceSize, &executor);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnQkvRmsNormRopeCacheGetWorkspaceSize failed. ERROR: %d\n", ret);
              return ret);

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

    // 4. Boilerplate: synchronously wait for the task 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 and copy the result from the device memory to the host memory. Modify it based on the API definition.
    PrintOutResult(kCacheShape, &kCacheDeviceAddr);
    PrintOutResult(vCacheShape, &vCacheDeviceAddr);

    // 6. Release aclTensor. Modify it based on the API definition.
    aclDestroyTensor(qkv);
    aclDestroyTensor(qGamma);
    aclDestroyTensor(kGamma);
    aclDestroyTensor(cos);
    aclDestroyTensor(sin);
    aclDestroyTensor(index);
    aclDestroyTensor(qOut);
    aclDestroyTensor(kCache);
    aclDestroyTensor(vCache);
    aclDestroyTensor(kScale);
    aclDestroyTensor(vScale);

    // 7. Release device resources.
    aclrtFree(qkvDeviceAddr);
    aclrtFree(qGammaDeviceAddr);
    aclrtFree(kGammaDeviceAddr);
    aclrtFree(cosDeviceAddr);
    aclrtFree(sinDeviceAddr);
    aclrtFree(indexDeviceAddr);
    aclrtFree(qOutDeviceAddr);
    aclrtFree(kCacheDeviceAddr);
    aclrtFree(vCacheDeviceAddr);
    aclrtFree(kScaleDeviceAddr);
    aclrtFree(vScaleDeviceAddr);

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

    return 0;
}