aclnnApplyRotaryPosEmbV2

📄 View Source Code

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: Supported
  • Atlas training products: Not supported

Function

  • Description: To improve performance, the inference network fuses the query and key operators into a single operator. It performs rotary position embedding computation, and the computation result is updated in-place. This API has the following functional changes compared to aclnnApplyRotaryPosEmb. Choose an appropriate API as required:

    • A new parameter rotaryMode is added to control different rotary encoding modes.
  • Formula:

    (1) When rotaryMode is "half":

    $$ query\_q1 = query[..., : query.shape[-1] // 2] $$
    $$ query\_q2 = query[..., query.shape[-1] // 2 :] $$
    $$ query\_rotate = torch.cat((-query\_q2, query\_q1), dim=-1) $$
    $$ key\_k1 = key[..., : key.shape[-1] // 2] $$
    $$ key\_k2 = key[..., key.shape[-1] // 2 :] $$
    $$ key\_rotate = torch.cat((-key\_k2, key\_k1), dim=-1) $$
    $$ q\_embed = (query * cos) + query\_rotate * sin $$
    $$ k\_embed = (key * cos) + key\_rotate * sin $$

    (2) When rotaryMode is "quarter":

    $$ query\_q1 = query[..., : query.shape[-1] // 4] $$
    $$ query\_q2 = query[..., query.shape[-1] // 4 : query.shape[-1] // 2] $$
    $$ query\_q3 = query[..., query.shape[-1] // 2 : query.shape[-1] // 4 * 3] $$
    $$ query\_q4 = query[..., query.shape[-1] // 4 * 3 :] $$
    $$ query\_rotate = torch.cat((-query\_q2, query\_q1, -query\_q4, query\_q3), dim=-1) $$
    $$ key\_q1 = key[..., : key.shape[-1] // 4] $$
    $$ key\_q2 = key[..., key.shape[-1] // 4 : key.shape[-1] // 2] $$
    $$ key\_q3 = key[..., key.shape[-1] // 2 : key.shape[-1] // 4 * 3] $$
    $$ key\_q4 = key[..., key.shape[-1] // 4 * 3 :] $$
    $$ key\_rotate = torch.cat((-key\_q2, key\_q1, -key\_q4, key\_q3), dim=-1) $$
    $$ q\_embed = (query * cos) + query\_rotate * sin $$
    $$ k\_embed = (key * cos) + key\_rotate * sin $$

    (3) rotaryMode is "interleave":

    $$ query\_q1 = query[..., ::2].view(-1, 1) $$
    $$ query\_q2 = query[..., 1::2].view(-1, 1) $$
    $$ query\_rotate = torch.cat((-query\_q2, query\_q1), dim=-1).view(query.shape[0], query.shape[1], query.shape[2], query.shape[3]) $$
    $$ key\_q1 = key[..., ::2].view(-1, 1) $$
    $$ key\_q2 = key[..., 1::2].view(-1, 1) $$
    $$ key\_rotate = torch.cat((-key\_q2, key\_q1), dim=-1).view(key.shape[0], key.shape[1], key.shape[2], key.shape[3]) $$
    $$ q\_embed = (query * cos) + query\_rotate * sin $$
    $$ k\_embed = (key * cos) + key\_rotate * sin $$

Function Prototype

Each operator uses a two-phase API. Call "aclnnApplyRotaryPosEmbV2GetWorkspaceSize" first to obtain the input parameters and calculate the required workspace size based on the process, and then call "aclnnApplyRotaryPosEmbV2" to perform the calculation.

aclnnStatus aclnnApplyRotaryPosEmbV2GetWorkspaceSize(
  aclTensor       *queryRef,
  aclTensor       *keyRef,
  const aclTensor *cos,
  const aclTensor *sin,
  int64_t         layout,
  char            *rotaryMode,
  uint64_t        *workspaceSize,
  aclOpExecutor   **executor)
aclnnStatus aclnnApplyRotaryPosEmbV2(
  void          *workspace,
  uint64_t      workspaceSize,
  aclOpExecutor *executor,
  aclrtStream   stream)

aclnnApplyRotaryPosEmbV2GetWorkspaceSize

  • Parameters

    Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor
    queryRef (aclTensor) Input/Output Indicates the first tensor for rotary position embedding, which is query in the formula. The calculation result is updated in-place.
    • Atlas inference products, Atlas A2 products, Atlas A3 products:
      • Does not support empty tensor.
      • The last dimension (D) of shape must be equal to 128 or 64.
    • Ascend 950PR&950DT products:
      • Supports empty tensor.
      • The last dimension (D) of shape is less than or equal to 1024.
    BFLOAT16, FLOAT16, FLOAT ND The dimension is 3 when layout is 4, and the dimension in other layout scenarios is 4 √
    keyRef (aclTensor) Input/Output Indicates the second tensor for rotary position embedding, which is key in the formula. The calculation result is updated in-place.
    • Atlas inference products, Atlas A2 products, Atlas A3 products:
      • Does not support empty tensors.
      • The last dimension (D) of shape must be equal to 128 or 64.
    • Ascend 950PR&950DT products:
      • Supports empty tensors.
      • The last dimension (D) of shape is less than or equal to 1024.
    BFLOAT16, FLOAT16, FLOAT ND The dimension is 3 when layout=4, and the dimension in other layout scenarios is 4. √
    cos (aclTensor) Input Indicates the position encoding tensor participating in the calculation, that is, cos in the formula.
    • Atlas inference products, Atlas A2 products, Atlas A3 products:
      • Does not support empty tensors.
      • The B dimension in shape is consistent with the B dimensions of queryRef and keyRef.
      • The third dimension (N) of shape must be equal to 1.
      • The last dimension (D) of shape must be equal to 128 or 64.
    • Ascend 950PR&950DT products:
      • Supports empty tensors.
      • The B dimension in shape is consistent with the B dimensions of queryRef and keyRef, or is equal to 1.
      • The N dimension in shape must be equal to 1.
      • The last dimension (D) of shape is less than or equal to 1024.
    BFLOAT16, FLOAT16, FLOAT ND When layout=4, the dimension is 3, and in other layout scenarios it is 4. √
    sin (aclTensor) Input Indicates the position embedding tensor involved in the calculation, which is sin in the formula.
    • Atlas inference products, Atlas A2 products, Atlas A3 products:
      • Does not support empty Tensor.
      • The B dimension in shape is consistent with the B dimensions of queryRef and keyRef.
      • The third dimension (N) in shape must be equal to 1.
      • The last dimension (D) in shape must be equal to 128 or 64.
    • Ascend 950PR&950DT products:
      • Supports empty Tensor.
      • The B dimension in shape is consistent with the B dimensions of queryRef and keyRef, or is equal to 1.
      • The N dimension in shape must be equal to 1.
      • The last dimension (D) in shape is less than or equal to 1024.
    BFLOAT16, FLOAT16, FLOAT ND When layout=4, the dimension is 3, and in other layout scenarios it is 4. √
    layout (int64_t) Input Indicates the layout format of the input tensor.
    • Value range: 1-BSND, 2-SBND, 3-BNSD, 4-TND.
    • Atlas inference products, Atlas A2 products, and Atlas A3 products: support 4D tensors in 1-BSND format and 3D tensors in 4-TND format.
    • Ascend 950PR&950DT products: support 4D tensors in 1-BSND, 2-SBND, and 3-BNSD formats, and 3D tensors in 4-TND format.
    int64 - - -
    rotaryMode (char) Input Indicates the rotary mode in the formula.
    • Value range: "half", "interleave", and "quarter".
    • Atlas inference products, Atlas A2 products, and Atlas A3 products: support the "half" mode.
    • Ascend 950PR&950DT products: support the "half", "interleave", and "quarter" modes.
    char - - -
    workspaceSize (uint64_t) Output Returns the workspace size to be applied by Device. - - - - executor (aclOpExecutor)
    Output Returns the op executor, which contains the operator calculation flow. - - - - - -
    • Atlas inference products: Not supported BFLOAT16
  • 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 passed-in queryRef, keyRef, cos, or sin is a null pointer.
    ACLNN_ERR_PARAM_INVALID 161002 The data type or data format of the passed-in queryRef, keyRef, cos, or sin is not within the supported range, or the shapes do not match.
    The passed-in layout parameter is not within the supported range.
    The passed-in rotaryMode parameter is not within the supported range.

aclnnApplyRotaryPosEmbV2

  • Parameters

    Parameter Input/Output Description
    workspace Input Workspace memory address applied by on the Device side.
    workspaceSize Input Size of the workspace applied by on the Device side, obtained by calling the first-phase API aclnnApplyRotaryPosEmbV2GetWorkspaceSize.
    executor Input op executor, which contains the operator calculation flow.
    stream Input Stream on which tasks are executed.
  • Return Value

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

Constraints

  • Deterministic computation:
    • aclnnApplyRotaryPosEmbV2 defaults to a deterministic implementation.
  • Atlas inference products, Atlas A2 products, Atlas A3 products:
    • When layout is 1, the first two dimensions (B, S) of the input shapes of queryRef, keyRef, cos, and sin must be equal; when layout is 4, the first dimension (T) must be equal.

    • The last dimension (D) of the input shapes of queryRef and keyRef must be equal, and the last dimension (D) of the input shapes of cos and sin must be equal.

    • The input tensors queryRef, keyRef, cos, and sin must have the same dtype.

    • When layout is 1, the shape of input queryRef is represented as (q_b, q_s, q_n, q_d), the shape of keyRef is represented as (q_b, q_s, k_n, q_d), and the shapes of cos and sin are represented as (q_b, q_s, 1, cos_d). Here, b indicates batch_size, s indicates seq_length, n indicates head_num, and d indicates head_dim. When layout is 4, the shape of input queryRef is represented as (q_t, q_n, q_d), the shape of keyRef is represented as (q_t, k_n, q_d), and the shapes of cos and sin are represented as (q_t, 1, cos_d). Here, t indicates the merged axis of b and s, n indicates head_num, and d indicates head_dim.

      • When the input is BFLOAT16, cast is 1, castSize is 4, and DtypeSize is 2.
      • When the input is FLOAT16 or FLOAT32, cast is 0, and castSize = DtypeSize (2 for FLOAT16, 4 for FLOAT32).

      Use lastDim to indicate the dimension of the input shape that requires rotary position embedding. The required UB space size is calculated as follows: ub_required = (q_n + k_n) * lastDim * castSize * 2 + lastDim * DtypeSize * 4 + (q_n + k_n) * lastDim * castSize + (q_n + k_n) * lastDim * castSize * 2 + cast * (lastDim * 4 * 2). When the calculated ub_required size exceeds the total UB space size of the current AI processor, this fused operator is not supported.

  • Ascend 950PR&950DT products:
    • For any layout, queryRef and keyRef must have the same dimensions except the N dimension; the last dimension (D) of the queryRef and keyRef input shapes must be equal, and the last dimension (D) of the cos and sin input shapes must be equal and less than or equal to the last dimension (D) of the queryRef and keyRef input shapes.
    • The input tensors queryRef, keyRef, cos, and sin must have the same dtype.
    • When rotaryMode is "half" or "interleave", the last dimension of the input shape must be divisible by 2; when rotaryMode is "quarter", the last dimension of the input shape must be divisible by 4.

Example

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

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

#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 shape_size = 1;
    for (auto i : shape) {
        shape_size *= i;
    }
    return shape_size;
}

int Init(int32_t deviceId, aclrtStream* stream) {
    // Boilerplate. 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 data from the host 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);

    // Calculate 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 aclCreateTensor 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. Device/stream initialization. For details, see the acl API reference.
    // Set deviceId based on the actual device in use.
    int32_t deviceId = 0;
    aclrtStream stream;
    auto ret = Init(deviceId, &stream);
    // Handle the check as needed.
    CHECK_RET(ret == 0, LOG_PRINT("Init acl failed. ERROR: %d\n", ret); return ret);
    // 2. Construct inputs and outputs according to the API definition.
    std::vector<int64_t> queryShape = {1, 1, 1, 128};
    std::vector<int64_t> keyShape = {1, 1, 1, 128};
    std::vector<int64_t> cosShape = {1, 1, 1, 128};
    std::vector<int64_t> sinShape = {1, 1, 1, 128};
    int64_t layout = 1;
    char *rotaryMode = "half";

    void* queryDeviceAddr = nullptr;
    void* keyDeviceAddr = nullptr;
    void* cosDeviceAddr = nullptr;
    void* sinDeviceAddr = nullptr;
    aclTensor* query = nullptr;
    aclTensor* key = nullptr;
    aclTensor* cos = nullptr;
    aclTensor* sin = nullptr;

    std::vector<float> queryHostData = {74, 54, 84, 125, 23, 78, 37, 72, 27, 98, 34, 107, 29, 23, 54, 60, 70, 49,
                                        119, 54, 29, 54, 41, 99, 27, 62, 5, 46, 108, 39, 24, 123, 33, 82, 6, 40, 88,
                                        24, 6, 116, 38, 119, 110, 5, 30, 79, 87, 18, 29, 100, 90, 24, 21, 93, 63, 68,
                                        34, 112, 119, 48, 74, 43, 85, 64, 14, 49, 128, 59, 18, 37, 123, 76, 14, 63, 10,
                                        39, 107, 124, 79, 16, 17, 76, 80, 47, 90, 41, 58, 82, 75, 80, 69, 37, 74, 36, 54,
                                        26, 32, 54, 13, 100, 105, 15, 13, 69, 122, 26, 94, 59, 29, 14, 60, 8, 24, 17, 45,
                                        33, 107, 122, 63, 111, 75, 128, 68, 31, 105, 6, 82, 99};
    std::vector<float> keyHostData = {112, 32, 66, 114, 69, 31, 117, 122, 77, 57, 78, 119, 115, 25, 54, 27, 122, 65, 15, 85,
                                      33, 16, 36, 6, 95, 15, 43, 6, 66, 91, 14, 101, 78, 51, 110, 74, 56, 30, 127, 61, 53, 29,
                                      32, 65, 114, 77, 26, 116, 89, 38, 75, 14, 96, 91, 87, 34, 25, 42, 57, 26, 51, 43, 23, 42,
                                      40, 17, 98, 117, 53, 75, 68, 75, 38, 41, 115, 76, 67, 22, 76, 10, 24, 46, 85, 54, 61, 114,
                                      10, 59, 6, 123, 58, 10, 115, 9, 13, 58, 66, 120, 23, 30, 83, 13, 11, 76, 18, 82, 57, 4,
                                      117, 105, 8, 73, 127, 5, 91, 56, 12, 125, 20, 3, 104, 40, 46, 18, 89, 63, 99, 104};
    std::vector<float> cosHostData = {41, 37, 17, 25, 49, 25, 22, 24, 110, 120, 107, 3, 82, 66, 75, 86, 85, 115, 110, 56, 52,
                                      39, 86, 23, 36, 71, 20, 73, 113, 25, 114, 56, 125, 80, 95, 82, 31, 63, 99, 62, 23, 55, 30,
                                      99, 42, 121, 15, 24, 97, 87, 81, 67, 43, 21, 13, 9, 33, 29, 117, 10, 114, 61, 98, 15, 78,
                                      108, 48, 97, 1, 3, 78, 109, 57, 46, 47, 56, 50, 66, 81, 77, 17, 128, 68, 121, 47, 91, 114,
                                      125, 51, 108, 31, 15, 47, 78, 109, 115, 113, 26, 53, 97, 1, 111, 103, 58, 106, 68, 11,
                                      104, 22, 79, 61, 127, 86, 39, 33, 123, 102, 39, 64, 41, 119, 120, 61, 29, 94, 68, 36, 12};
    std::vector<float> sinHostData = {46, 56, 56, 101, 66, 10, 96, 16, 86, 57, 102, 66, 12, 105, 76, 58, 90, 6, 79, 128, 126,
                                      82, 41, 3, 45, 7, 66, 4, 46, 22, 31, 26, 37, 63, 97, 84, 91, 90, 47, 77, 90, 34, 41, 83,
                                      91, 108, 120, 13, 90, 32, 85, 37, 119, 31, 51, 82, 122, 125, 7, 116, 121, 108, 38, 56,
                                      100, 20, 97, 119, 10, 4, 53, 13, 46, 82, 103, 119, 124, 80, 23, 67, 78, 56, 119, 122, 40,
                                      58, 128, 27, 30, 52, 71, 42, 123, 69, 4, 5, 116, 97, 38, 107, 8, 4, 65, 120, 40, 22, 60,
                                      44, 48, 66, 68, 125, 4, 93, 112, 112, 113, 90, 94, 23, 104, 39, 85, 84, 64, 128, 96, 119};

    // Create the query aclTensor.
    ret = CreateAclTensor(queryHostData, queryShape, &queryDeviceAddr, aclDataType::ACL_FLOAT, &query);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    // Create the key aclTensor.
    ret = CreateAclTensor(keyHostData, keyShape, &keyDeviceAddr, aclDataType::ACL_FLOAT, &key);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    // Create the cos aclTensor.
    ret = CreateAclTensor(cosHostData, cosShape, &cosDeviceAddr, aclDataType::ACL_FLOAT, &cos);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    // Create the sin aclTensor.
    ret = CreateAclTensor(sinHostData, sinShape, &sinDeviceAddr, aclDataType::ACL_FLOAT, &sin);
    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 aclnnApplyRotaryPosEmbV2.
    ret = aclnnApplyRotaryPosEmbV2GetWorkspaceSize(query, key, cos, sin, layout, rotaryMode, &workspaceSize, &executor);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnApplyRotaryPosEmbV2GetWorkspaceSize 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 aclnnApplyRotaryPosEmbV2.
    ret = aclnnApplyRotaryPosEmbV2(workspaceAddr, workspaceSize, executor, stream);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnApplyRotaryPosEmbV2 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 device memory to host memory. Modify it according to the definition of the specific API.
    auto size = GetShapeSize(queryShape);
    std::vector<float> resultData(size, 0);
    ret = aclrtMemcpy(resultData.data(), resultData.size() * sizeof(resultData[0]), queryDeviceAddr, size * sizeof(float),
                      ACL_MEMCPY_DEVICE_TO_HOST);
    CHECK_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("result[%ld] is: %f\n", i, resultData[i]);
    }

    auto size1 = GetShapeSize(keyShape);
    std::vector<float> resultData1(size1, 0);
    ret = aclrtMemcpy(resultData1.data(), resultData1.size() * sizeof(resultData1[0]), keyDeviceAddr, size1 * sizeof(float),
                      ACL_MEMCPY_DEVICE_TO_HOST);
    CHECK_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 < size1; i++) {
        LOG_PRINT("result[%ld] is: %f\n", i, resultData1[i]);
    }

    // 6. Release aclTensor and aclScalar. Modify the code based on the specific API definition.
    aclDestroyTensor(query);
    aclDestroyTensor(key);
    aclDestroyTensor(cos);
    aclDestroyTensor(sin);

    // 7. Release device resources.
    aclrtFree(queryDeviceAddr);
    aclrtFree(keyDeviceAddr);
    aclrtFree(cosDeviceAddr);
    aclrtFree(sinDeviceAddr);
    if (workspaceSize > 0) {
      aclrtFree(workspaceAddr);
    }
    aclrtDestroyStream(stream);
    aclrtResetDevice(deviceId);
    aclFinalize();

    return 0;
}