aclnnInplacePartialRotaryMul

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

Function

  • Description: Performs the Inplace computation of single-path rotary position encoding, directly modifying the input tensor xRef without generating a new output tensor.

  • Formula:

    (1) interleave mode (rotary_mode = 1):

    $$ x1 = x[..., ::2].view(-1, 1) $$
    $$ x2 = x[..., 1::2].view(-1, 1) $$
    $$ x\_rotate = torch.cat((-x2, x1), dim=-1).view(x.shape[0], x.shape[1], x.shape[2], x.shape[3]) $$
    $$ x = x * cos + x\_rotate * sin $$
  • partial_slice parameter description: Supports partial rotary position encoding on the last dimension of the input tensor. The partial_slice parameter specifies the [start, end) range. Rotary position encoding is performed only on the data in this range.

Function Prototype

Each operator uses a two-phase API. Call "aclnnInplacePartialRotaryMulGetWorkspaceSize" first to obtain the input parameters and calculate the required workspace size based on the procedure, and then call "aclnnInplacePartialRotaryMul" to perform the computation.

aclnnStatus aclnnInplacePartialRotaryMulGetWorkspaceSize(
  const aclTensor   *xRef,
  const aclTensor   *cos,
  const aclTensor   *sin,
  int64_t           rotary_mode,
  const aclIntArray *partialSlice,
  uint64_t          *workspaceSize,
  aclOpExecutor     **executor)
aclnnStatus aclnnInplacePartialRotaryMul(
  void          *workspace,
  uint64_t      workspaceSize,
  aclOpExecutor *executor,
  aclrtStream   stream)

aclnnInplacePartialRotaryMulGetWorkspaceSize

  • Parameters

    Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor
    xRef Input Tensor to which rotary position encoding is applied, corresponding to x in the formula. In inplace mode, xRef also serves as the output where the result is written. - BFLOAT16, FLOAT16, FLOAT32 ND 4 ×
    cos Input Position encoding tensor, corresponding to cos in the formula. Same as the data type of xRef, or FLOAT32. BFLOAT16, FLOAT16, FLOAT32 ND 4 ×
    sin Input Position encoding tensor, which is sin in the formula. Same as the data type of xRef, or FLOAT32 BFLOAT16, FLOAT16, FLOAT32 ND 4 ×
    rotary_mode Input Rotation mode 0 indicates the half mode, and 1 indicates the interleave mode. Currently, only the interleave mode is supported. INT64 - - -
    partialSlice Input Slice range [start, end) for partial rotation, acting on the last dimension. Defaults to [0, 0] if not specified. No rotation encoding is performed when start and end are equal. INT64 array - - -
    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.

    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 xRef, cos, or sin is a null pointer.
    ACLNN_ERR_PARAM_INVALID 161002 The data type of the passed-in xRef, cos, or sin is out of the supported range, or the data types of cos and sin are inconsistent, or the precision combination does not meet requirements.
    ACLNN_ERR_INNER_TILING_ERROR 561002 Tiling-stage check failed: the passed-in rotary_mode, partialSlice, or input tensor shape does not meet constraints. For details, see "Constraints".

aclnnInplacePartialRotaryMul

  • 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 calling the first-phase API aclnnInplacePartialRotaryMulGetWorkspaceSize.
    executor Input Op executor that contains the operator computation process.
    stream Input Stream for task execution.
  • Return value

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

Constraints

  • Deterministic computation:
    • aclnnInplacePartialRotaryMul defaults to a deterministic implementation.
  • Non-contiguous tensors are not supported.
  • Only the interleave mode (rotary_mode = 1) is supported.
  • Inplace execution: the input xRef and the output share the same tensor, and the computation result is written back to the input xRef directly.
  • The shape of the input tensor xRef is in BSND layout. The shape constraints of each parameter are as follows:
    • The size of the last dimension (D) of the input tensor xRef does not exceed 1024.

    • In interleave mode (rotary_mode = 1), the size of the last dimension (D) of xRef must be a multiple of 2. The partialSlice slice length (that is, partialSlice[1] - partialSlice[0]) must be a multiple of 2.

    • The size of the last dimension of the input tensors cos and sin must be the same and must equal the partialSlice slice length (that is, partialSlice[1] - partialSlice[0]).

    • The shapes of cos/sin must satisfy the broadcast relationship with xRef, subject to the following constraints:

      • Ascend 950PR&950DT products: The shapes of cos/sin currently support only the BSND, B1ND, B11D, and 111D layouts.
      • Atlas A3 products, Atlas A2 products: The shapes of cos/sin currently support only the BS1D and B11D layouts, which requires the B dimension to remain the same.
    • partialSlice constraints: sliceStart ≥ 0, sliceEnd ≥ 0, sliceEnd ≤ the size of the last dimension (D) of xRef, and sliceLength = sliceEnd - sliceStart >= 0. When sliceEnd is equal to sliceStart, no rotary position encoding is performed and the function returns directly.

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

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) {
    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. Boilerplate: device/stream initialization. For details, see the acl API manual.
    int32_t deviceId = 0;
    aclrtStream stream;
    auto ret = Init(deviceId, &stream);
    CHECK_RET(ret == 0, LOG_PRINT("Init acl failed. ERROR: %d\n", ret); return ret);

    // 2. Construct the input according to the API definition.
    std::vector<int64_t> xShape = {96, 1, 1, 512};
    std::vector<int64_t> cosShape = {96, 1, 1, 64};
    std::vector<int64_t> sinShape = {96, 1, 1, 64};
    int64_t rotary_mode = 1;
    std::vector<int64_t> partialSlice = {448, 512};

    void* xDeviceAddr = nullptr;
    void* cosDeviceAddr = nullptr;
    void* sinDeviceAddr = nullptr;
    aclTensor* x = nullptr;
    aclTensor* cos = nullptr;
    aclTensor* sin = nullptr;

    // Create host data (example data)
    std::vector<float> xHostData = { /* fill with your data */ };
    std::vector<float> cosHostData = { /* fill with your data */ };
    std::vector<float> sinHostData = { /* fill with your data */ };

    ret = CreateAclTensor(xHostData, xShape, &xDeviceAddr, aclDataType::ACL_FLOAT, &x);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    ret = CreateAclTensor(cosHostData, cosShape, &cosDeviceAddr, aclDataType::ACL_FLOAT, &cos);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    ret = CreateAclTensor(sinHostData, sinShape, &sinDeviceAddr, aclDataType::ACL_FLOAT, &sin);
    CHECK_RET(ret == ACL_SUCCESS, return ret);

    aclIntArray* partialSliceArray = aclCreateIntArray(partialSlice.data(), partialSlice.size());

    // 3. Call the CANN operator library API.
    uint64_t workspaceSize = 0;
    aclOpExecutor* executor;
    // Call the first-phase API of aclnnInplacePartialRotaryMul.
    ret = aclnnInplacePartialRotaryMulGetWorkspaceSize(x, cos, sin, rotary_mode, partialSliceArray,
                                                        &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;);
    }

    // Call the second-phase API of aclnnInplacePartialRotaryMul.
    ret = aclnnInplacePartialRotaryMul(workspaceAddr, workspaceSize, executor, stream);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("InplacePartialRotaryMul failed. ERROR: %d\n", ret); return ret);

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

    // Cleanup
    aclDestroyIntArray(partialSliceArray);
    aclDestroyTensor(x);
    aclDestroyTensor(cos);
    aclDestroyTensor(sin);
    aclrtFree(xDeviceAddr);
    aclrtFree(cosDeviceAddr);
    aclrtFree(sinDeviceAddr);
    if (workspaceSize > 0) {
        aclrtFree(workspaceAddr);
    }
    aclrtDestroyStream(stream);
    aclrtResetDevice(deviceId);
    aclFinalize();

    return 0;
}