aclnnMoeTokenPermuteWithRoutingMapGrad

📄 View Source Code

Applicable Products

ProductSupported
Ascend 950PR/Ascend 950DT√
Atlas A3 training products/Atlas A3 inference products√
Atlas A2 training products/Atlas A2 inference products√
Atlas 200I/500 A2 inference products×
Atlas inference products×
Atlas training products×

Function

  • Description: Backward propagation of aclnnMoeTokenPermuteWithRoutingMap.

  • Formula:

    permuteTokenId,outIndex=sortedIndices.sort(dim=−1)permuteTokenId, outIndex= sortedIndices.sort(dim=-1) capacity=permutedTokensOutputGrad.size(0)/numExpertscapacity = permutedTokensOutputGrad.size(0) / numExperts
    • When probs is not None:

      probsGradOutOptional=zeros(tokensnum,numExperts)probsGradOutOptional = zeros(tokens_num, numExperts)
    • When dropPaddedMode is true:

      probsGradOutOptional[sortedIndices[i],i/capacity]=permutedProbsOutputGradOptional[i]probsGradOutOptional [sortedIndices[i], i/capacity] = permutedProbsOutputGradOptional[i]
    • When dropPaddedMode is false:

      probsGradOutOptional=maskedscatter(probsGradOutOptional,routingMapOptional,permutedProbsOutputGradOptional)probsGradOutOptional = maskedscatter(probsGradOutOptional,routingMapOptional, permutedProbsOutputGradOptional)
    • When probs is None:

      tokensGradOut=zeros(restoreShapeOptional,dtype=permutedTokens.dtype,device=permutedTokens.device)tokensGradOut= zeros(restoreShapeOptional, dtype=permutedTokens.dtype, device=permutedTokens.device) tokensGradOut[permuteTokenId[i]]+=permutedTokens[outIndex[i]]tokensGradOut[permuteTokenId[i]] += permutedTokens[outIndex[i]]

Function Prototype

Each operator is divided into a two-phase API. You must first call the "aclnnMoeTokenPermuteWithRoutingMapGradGetWorkspaceSize" API to obtain the workspace size required for computation and the executor that contains the operator computation process, and then call the "aclnnMoeTokenPermuteWithRoutingMapGrad" API to perform the computation.

aclnnStatus aclnnMoeTokenPermuteWithRoutingMapGradGetWorkspaceSize(
    const aclTensor *permutedTokensOutputGrad,
    const aclTensor *permutedProbsOutputGradOptional,
    const aclTensor *sortedIndices,
    const aclTensor *routingMapOptional,
    int64_t          experts_num,
    int64_t          tokens_num,
    bool             dropAndPad,
    aclTensor       *tokenGradOut,
    aclTensor       *probsGradOutOptional,
    uint64_t        *workspaceSize,
    aclOpExecutor   **executor)
aclnnStatus aclnnMoeTokenPermuteWithRoutingMapGrad(
    void                *workspace,
    uint64_t             workspaceSize,
    aclOpExecutor       *executor,
    const aclrtStream    stream)

aclnnMoeTokenPermuteWithRoutingMapGradGetWorkspaceSize

  • Parameters:

    Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor
    permutedTokensOutputGrad Input Represents the gradient of the forward output permutedTokens. The shape supports 2D dimensions. Empty tensors are not supported. topK_num indicates the number of experts selected for each token, and capacity indicates the number of tokens selected for each expert. BFLOAT16, FLOAT16, FLOAT32 ND
    • Non-dropAndPad mode: (tokens_num * topK_num, hidden_size).
    • dropAndPad mode: (experts_num * capacity, hidden_size).
    √
    permutedProbsOutputGradOptional Optional input. Gradient of the forward output permutedProbs.
    • If not passed, probsGradOutOptional does not need to be computed.
    • The shape is a 1D dimension, where topK_num indicates the number of experts selected per token, and capacity indicates the number of tokens selected per expert.
    • The data type is the same as permutedTokensOutputGrad, or FLOAT is supported when permutedTokensOutputGrad is BFLOAT16.
    BFLOAT16, FLOAT16, FLOAT32 ND
    • Non-dropAndPad mode: (tokens_num * topK_num).
    • dropAndPad mode: (experts_num * capacity).
    √
    sortedIndices Input Sorted index values. In non-dropAndPad mode, the index value range is [0, tokens_num * topK_num - 1]; in dropAndPad mode, the index value range is [0, experts_num * capacity - 1], where topK_num indicates the number of experts selected for each token, and capacity indicates the number of tokens selected for each expert. INT32 ND
    • Non-dropAndPad mode: (tokens_num * topK_num, );
    • DropAndPad mode: (experts_num * capacity).
    √
    routingMapOptional Optional Input Represents the mapping relationship from tokens to experts. Requires the shape to be a 2D tensor. In non-dropAndPad mode, each row must contain topK true or 1 values. INT8, bool (when the data type is INT8, the supported values are 0 and 1; when the data type is bool, the supported values are true and false). ND (tokens_num, experts_num) √
    experts_num Input Indicates the number of experts involved in the computation. - - - - -
    tokens_num Input Indicates the number of tokens involved in the computation. - - - - -
    dropAndPad Input. - true indicates that dropPaddedMode is enabled, and false indicates that dropPaddedMode is disabled. bool - - -
    tokensGradOut Output Gradient of the input permutedTokens. Must be a 2D tensor. BFLOAT16, FLOAT16, FLOAT32 ND (tokens_num, hidden_size) ×
    probsGradOutOptional Optional output. Gradient of the forward operator input probs. Shape supports 2D dimensions. Same as permutedProbsOutputGradOptional. ND (tokens_num, experts_num) ×
    workspaceSize Output Returns the workspace size to be applied for on the Device side. - - - - -
    executor Output Returns the operator executor, which contains the operator computation process. - - - - -
  • Return value

    aclnnStatus: return code. For details, see aclnn Return Code.

    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 A required input, required output, or required attribute is a null pointer.
    ACLNN_ERR_PARAM_INVALID 161002 1. The data types and data formats of the inputs and outputs are not within the supported range.
    2. The shapes of the inputs and outputs are not within the supported range.

aclnnMoeTokenPermuteWithRoutingMapGrad

  • Parameters:

    Parameter Input/Output Description
    workspace Input Workspace memory address applied for on the Device side.
    workspaceSize Input Workspace size applied for on the Device side, obtained through the first-phase API aclnnMoeTokenPermuteWithRoutingMapGradGetWorkspaceSize.
    executor InputOperator executor, which contains the operator computation flow.
    stream Input Specifies the stream for task execution.
  • Return value

    aclnnStatus: return code. For details, see aclnn Return Code.

Constraints

  • Deterministic computation:

    • aclnnMoeTokenPermuteWithRoutingMapGrad defaults to a deterministic implementation.
  • In non-dropPaddedMode scenarios, topK_num <= 512

Example

The following provides example code for reference only. For details about compilation and running, see Compile and Run Samples.

#include "aclnnop/aclnn_moe_token_permute_with_routing_map_grad.h"
#include <iostream>
#include <vector>
#include <sys/stat.h>
#include <fstream>
#include <fcntl.h>
#include <unistd.h>
#include <cstdio>
#include <cassert>
#include <iomanip>
#include <unistd.h>
#include "acl/acl.h"
#include "aclnn/acl_meta.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;
}

template <typename T>
bool WriteFile(const std::string &filePath, int64_t size, std::vector<T>& hostData)
{
    int fd = open(filePath.c_str(), O_RDWR | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR);
    if (fd < 0) {
        LOG_PRINT("Open file failed. path = %s", filePath.c_str());
        return false;
    }

    size_t writeSize = write(fd, reinterpret_cast<char*>(hostData.data()), size * sizeof(T));
    (void)close(fd);
    if (writeSize != size * sizeof(T)) {
        LOG_PRINT("Write file Failed.");
        return false;
    }

    return true;
}
void PrintOutResult(std::vector<int64_t>& shape, void** deviceAddr)
{
    auto size = GetShapeSize(shape);
    std::vector<float> 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 < 10; i++) {
        LOG_PRINT("result[%ld] is: %f\n", i, resultData[i]);
    }
}

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 apply for 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 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 acl API manual.
    // Enter the actual device ID.
    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 inputs and outputs. Customize the construction based on the API interface.

    int64_t num_token = 4096;
    int64_t hidden_size = 7168;
    int64_t num_expert = 256;
    int64_t num_capacity = 16;
    std::vector<float> permuted_output_grad_Data(num_expert * num_capacity * hidden_size, 0);
    std::vector<int64_t> permuted_output_grad_Shape = {num_expert * num_capacity, hidden_size};
    void* permuted_output_grad_Addr = nullptr;
    aclTensor* permuted_output_grad = nullptr;

    ret = CreateAclTensor(permuted_output_grad_Data, permuted_output_grad_Shape, &permuted_output_grad_Addr,
                          aclDataType::ACL_FLOAT, &permuted_output_grad);
    CHECK_RET(ret == ACL_SUCCESS, return ret);

    std::vector<float> permutedProbsOutputGradOptional(num_expert * num_capacity, 0.1);
    std::vector<int64_t> permutedProbsOutputGradOptionalShape = {num_expert * num_capacity};
    void* permutedProbsOutputGrad_Addr = nullptr;
    aclTensor* ppermutedProbsOutputGrad = nullptr;
    ret = CreateAclTensor(permutedProbsOutputGradOptional, permutedProbsOutputGradOptionalShape,
                          &permutedProbsOutputGrad_Addr, aclDataType::ACL_FLOAT, &ppermutedProbsOutputGrad);
    CHECK_RET(ret == ACL_SUCCESS, return ret);

    std::vector<int> sortedIndicesData(num_expert * num_capacity, 0);
    std::vector<int64_t> sortedIndicesShape = {num_expert * num_capacity};
    void* sortedIndicesAddr = nullptr;
    aclTensor* sortedIndices = nullptr;
    ret = CreateAclTensor(sortedIndicesData, sortedIndicesShape, &sortedIndicesAddr, aclDataType::ACL_INT32,
                          &sortedIndices);
    CHECK_RET(ret == ACL_SUCCESS, return ret);

    std::vector<char> routingMapOptionalData(num_token * num_expert, 1);
    std::vector<int64_t> routingMapOptionalShape = {num_token , num_expert};
    void* routingMapOptionalAddr = nullptr;
    aclTensor* proutingMapOptional = nullptr;

    ret = CreateAclTensor(routingMapOptionalData, routingMapOptionalShape, &routingMapOptionalAddr,
                          aclDataType::ACL_INT8, &proutingMapOptional);
    CHECK_RET(ret == ACL_SUCCESS, return ret);

    std::vector<float> outData(num_token * hidden_size, 0.0f);
    std::vector<int64_t> outShape = {num_token, hidden_size};
    // std::vector<int64_t> outShape = {num_token};
    void* outAddr = nullptr;
    aclTensor* out = nullptr;

    ret = CreateAclTensor(outData, outShape, &outAddr, aclDataType::ACL_FLOAT, &out);
    CHECK_RET(ret == ACL_SUCCESS, return ret);

    std::vector<float> outData2(num_token * num_expert, 0.0f);
    std::vector<int64_t> outShape2 = {num_token, num_expert};
    void* outAddr2 = nullptr;
    aclTensor* out2 = nullptr;

    ret = CreateAclTensor(outData2, outShape2, &outAddr2, aclDataType::ACL_FLOAT, &out2);
    CHECK_RET(ret == ACL_SUCCESS, return ret);

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

    // Call the first-phase API of aclnnMoeTokenPermuteWithRoutingMapGrad.
    ret = aclnnMoeTokenPermuteWithRoutingMapGradGetWorkspaceSize(permuted_output_grad, ppermutedProbsOutputGrad, sortedIndices, proutingMapOptional, num_expert, num_token, true,
                                                                 out, out2, &workspaceSize, &executor);
    CHECK_RET(ret == ACL_SUCCESS,
              LOG_PRINT("aclnnMoeTokenPermuteWithRoutingMapGradGetWorkspaceSize 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 aclnnMoeTokenPermuteWithRoutingMapGrad.
    ret = aclnnMoeTokenPermuteWithRoutingMapGrad(workspaceAddr, workspaceSize, executor, stream);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnMoeTokenPermuteWithRoutingMapGrad failed. ERROR: %d\n", ret);
              return ret);

    // 4. (Boilerplate) Synchronously wait for 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 value and copy the result from the device memory to the host side. Modify based on the specific API definition.
    PrintOutResult(outShape, &outAddr);
    PrintOutResult(outShape2, &outAddr2);

    // 6. Release aclTensor and aclScalar. Modify based on the specific API definition.
    aclDestroyTensor(permuted_output_grad);
    aclDestroyTensor(sortedIndices);
    aclDestroyTensor(out);

    // 7. Release device resources.
    aclrtFree(permuted_output_grad_Addr);
    aclrtFree(sortedIndicesAddr);
    aclrtFree(outAddr);

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

    return 0;
}