aclnnMoeTokenPermute

📄 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: MoE permute computation, which broadcasts and sorts tokens based on the indices.

  • Formula:

    • When paddedMode is false, the formula is as follows. topK refers to the number of experts selected by a token. When Indices is 2-dimensional, topK equals the size of the last dimension of Indices. When Indices is 1-dimensional, topK equals 1:

      $$ sortedIndicesFirst=argSort(\text{flatten}(Indices)) $$
      $$ sortedIndicesOut=argSort(sortedIndicesFirst) $$
      $$ permuteTokensOut[sortedIndicesOut[i]]=tokens[i//topK] $$
    • When paddedMode is true (not supported yet):

      $$ permuteTokensOut[i]=tokens[indices[i]] $$
      $$ sortedIndicesOut=indices $$

Function Prototype

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

aclnnStatus aclnnMoeTokenPermuteGetWorkspaceSize(
    const aclTensor  *tokens,
    const aclTensor  *indices,
    int64_t           numOutTokens,
    bool              paddedMode,
    const aclTensor  *permuteTokensOut,
    const aclTensor  *sortedIndicesOut,
    uint64_t         *workspaceSize,
    aclOpExecutor   **executor)
aclnnStatus aclnnMoeTokenPermute(
    void             *workspace,
    uint64_t          workspaceSize,
    aclOpExecutor    *executor,
    aclrtStream       stream)

aclnnMoeTokenPermuteGetWorkspaceSize

  • Parameters:

    Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor
    tokens Input Input token features.
    • Supports empty tensors.
    • Must be a tensor with at least two dimensions. The size of the first dimension is num_tokens.
    FLOAT16, BFLOAT16, FLOAT32, INT8 ND ≥2 √
    indices Input Input indices.
    • Supports empty tensors.
    • The shape must be 2D or 1D.
    • When paddedMode is false, it indicates the topK expert indices that process each input token. The shape is (num_tokens, topK) or (num_tokens).
    • When paddedMode is true, it indicates the token indices selected by each expert (not supported yet).
    • The number of elements is less than 16777215, and the value is greater than or equal to 0 and less than 16777215.
    INT32, INT64 ND 1 or 2 √
    numOutTokens Input Number of valid output tokens. The value can be any integer; 0 means no token is deleted. If the value is greater than 0, tokens sorted by expert are sliced based on numOutTokens, and the first numOutTokens tokens are retained. If the value is less than 0, it is treated as a negative slice index. - - - -
    paddedMode Input Indicates whether the padded mode is used. The value can be false or true.
    • false: indicates the non-padded mode. indices are sorted.
    • true: indicates the padded mode. indices are padded to represent the token indexes selected by each expert. In this case, indices are not sorted (not supported yet).
    - - - -
    permuteTokensOut Output Tokens broadcast and sorted based on indices.
    • Supports empty tensors.
    • Must be a tensor with two or more dimensions. The first dimension size is min(num_tokens * topK, numOutTokens).
    • The product of sizes of dimensions other than the first is the same as that of tokens.
    • The data type is the same as that of tokens.
    FLOAT16, BFLOAT16, FLOAT32, INT8 ND ≥2 ×
    sortedIndicesOut Output Mapping between permuteTokensOut and tokens.
    • Supports empty tensors.
    • Must be a 1D tensor with shape (num_tokens*topK).
    INT32 ND 1 ×
    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 Input and output tensors are null pointers.
    ACLNN_ERR_PARAM_INVALID 161002 Input and output data types are not within the supported range.
    ACLNN_ERR_INNER_TILING_ERROR 561002 The dimension of the shape of tokens is less than 2.
    The shape of indices is not 1D or 2D, or when paddedMode is false, the first dimension of the shape of indices is not equal to the first dimension of tokens.
    paddedMode is true.

aclnnMoeTokenPermute

  • Parameters:

    Parameter Input/Output Description
    workspace Input The workspace memory address allocated on the Device.
    workspaceSize Input The workspace size allocated on the Device, obtained by the first-phase API aclnnMoeTokenPermuteGetWorkspaceSize.
    executor Input Op executor that contains the computation flow of the operator.
    stream Input Stream used to execute tasks.
  • Return value

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

Constraints

  • When this API is called, indices must be 1D or 2D. Otherwise, the API directly returns a parameter error.
  • Deterministic computation:
    • aclnnMoeTokenPermute defaults to a deterministic implementation.
  • Ascend 950PR&950DT products: Only this product supports INT8 tokens and permuteTokensOut. They are processed in a non-quantized manner, and their data types must be the same. When tokens is INT8, its dimension must be 2; three or more dimensions are not supported.
  • Ascend 950PR&950DT products: When the data type of tokens is INT8, indices indicates the expert ID. The value range is [0, 10240). The maximum value is 10239, and 10240 is not supported.

Example

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

#include "acl/acl.h"
#include "aclnnop/aclnn_moe_token_permute.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 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 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: initialize the device/stream. For details, see the list of ACL APIs.
    // Set deviceId based on the actual device.
    int32_t deviceId = 0;
    aclrtStream stream;
    auto ret = Init(deviceId, &stream);
    // Handle the check as required.
    CHECK_RET(ret == 0, LOG_PRINT("Init acl failed. ERROR: %d\n", ret); return ret);
    // 2. Construct the inputs and outputs according to the API definition.
    std::vector<int64_t> xShape = {3, 4};
    std::vector<int64_t> idxShape = {3, 2};
    std::vector<int64_t> expandedXOutShape = {6, 4};
    std::vector<int64_t> idxOutShape = {6};
    void* xDeviceAddr = nullptr;
    void* indicesDeviceAddr = nullptr;
    void* expandedXOutDeviceAddr = nullptr;
    void* sortedIndicesOutDeviceAddr = nullptr;
    aclTensor* x = nullptr;
    aclTensor* indices = nullptr;
    int64_t numTokenOut = 0;
    bool padMode = false;

    aclTensor* expandedXOut = nullptr;
    aclTensor* sortedIndicesOut = nullptr;
    std::vector<float> xHostData = {0.1, 0.1, 0.1, 0.1, 0.2, 0.2, 0.2, 0.2, 0.3, 0.3, 0.3, 0.3};
    std::vector<int> indicesHostData = {1, 2, 0, 1, 0, 2};
    std::vector<float> expandedXOutHostData = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
    std::vector<int> sortedIndicesOutHostData = {0, 0, 0, 0, 0, 0};
    // Create self aclTensor.
    ret = CreateAclTensor(xHostData, xShape, &xDeviceAddr, aclDataType::ACL_FLOAT, &x);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    ret = CreateAclTensor(indicesHostData, idxShape, &indicesDeviceAddr, aclDataType::ACL_INT32, &indices);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    // Create out aclTensor.
    ret = CreateAclTensor(expandedXOutHostData, expandedXOutShape, &expandedXOutDeviceAddr, aclDataType::ACL_FLOAT, &expandedXOut);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    ret = CreateAclTensor(sortedIndicesOutHostData, idxOutShape, &sortedIndicesOutDeviceAddr, aclDataType::ACL_INT32, &sortedIndicesOut);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    // 3. Call the CANN operator library API. Change it to the specific API.
    uint64_t workspaceSize = 0;
    aclOpExecutor* executor;
    // Call the first-phase API of aclnnMoeTokenPermute.
    ret = aclnnMoeTokenPermuteGetWorkspaceSize(x, indices, numTokenOut, padMode, expandedXOut,
                                               sortedIndicesOut, &workspaceSize, &executor);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnMoeTokenPermuteGetWorkspaceSize 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 aclnnMoeTokenPermute.
    ret = aclnnMoeTokenPermute(workspaceAddr, workspaceSize, executor, stream);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnMoeTokenPermute failed. ERROR: %d\n", ret); return ret);
    // 4. Boilerplate. Synchronously 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 and copy the results from the device-side memory to the host side. Modify it based on the definition of the specific API.
    auto expandedXSize = GetShapeSize(expandedXOutShape);
    std::vector<float> expandedXData(expandedXSize, 0);
    ret = aclrtMemcpy(expandedXData.data(), expandedXData.size() * sizeof(expandedXData[0]), expandedXOutDeviceAddr, expandedXSize * 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 < expandedXSize; i++) {
        LOG_PRINT("expandedXData[%ld] is: %f\n", i, expandedXData[i]);
    }
    auto sortedIndicesSize = GetShapeSize(idxOutShape);
    std::vector<int> sortedIndicesData(sortedIndicesSize, 0);
    ret = aclrtMemcpy(sortedIndicesData.data(), sortedIndicesData.size() * sizeof(sortedIndicesData[0]), sortedIndicesOutDeviceAddr, sortedIndicesSize * sizeof(int32_t),
                      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 < sortedIndicesSize; i++) {
        LOG_PRINT("sortedIndicesData[%ld] is: %d\n", i, sortedIndicesData[i]);
    }
    // 6. Release aclTensor and aclScalar. Modify it based on the definition of the specific API.
    aclDestroyTensor(x);
    aclDestroyTensor(indices);
    aclDestroyTensor(expandedXOut);
    aclDestroyTensor(sortedIndicesOut);

    // 7. Release device resources. Modify it based on the definition of the specific API.
    aclrtFree(xDeviceAddr);
    aclrtFree(indicesDeviceAddr);
    aclrtFree(expandedXOutDeviceAddr);
    aclrtFree(sortedIndicesOutDeviceAddr);
    if (workspaceSize > 0) {
      aclrtFree(workspaceAddr);
    }
    aclrtDestroyStream(stream);
    aclrtResetDevice(deviceId);
    aclFinalize();
    return 0;
}