aclnnFusedLinearCrossEntropyLossGrad

📄 View Source Code

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: This operator is part of the cross-entropy loss computation module in vocabulary parallelism scenarios, addressing memory and computational efficiency issues for extremely large vocabularies. The current part implements gradient computation, used to compute the gradients of the leaf nodes input and weight. The relevant outputs of aclnnFusedLinearOnlineMaxSum and aclnnFusedCrossEntropyLossWithMaxSum, as well as the global communication results related to logits, are required as inputs of this API.
  • Formula:

  High-performance mode, softmaxOptional is not nullptr:

softmax∈RBT×V\text{softmax} \in \mathbb{R}^{BT \times V} arange_1d=[0,1,…,BT−1]∈NBT\text{arange\_1d} = [0, 1, \dots, BT-1] \in \mathbb{N}^{BT} softmax_update=1−target_mask.view(−1)∈RBT\text{softmax\_update} = \mathbf{1} - \text{target\_mask}.view(-1) \in \mathbb{R}^{BT} softmax[arange_1d,masked_target]←softmax[arange_1d,masked_target]−softmax_update\text{softmax}[\text{arange\_1d}, \text{masked\_target}] \leftarrow \text{softmax}[\text{arange\_1d}, \text{masked\_target}] - \text{softmax\_update} softmax←softmax⊙grad.unsqueeze(−1)∈RBT×V\text{softmax} \leftarrow \text{softmax} \odot \text{grad}.unsqueeze(-1) \in \mathbb{R}^{BT \times V} grad_input=softmax⋅weightT∈RBT×H\text{grad\_input} = \text{softmax} \cdot \text{weight}^T \in \mathbb{R}^{BT \times H} grad_weight=softmaxT⋅input∈RV×H\text{grad\_weight} = \text{softmax}^T \cdot \text{input} \in \mathbb{R}^{V \times H}
  Memory-saving mode, where softmaxOptional is nullptr: vocab_parallel_logits=input⋅weightT∈RBT×V\text{vocab\_parallel\_logits} = \text{input} \cdot \text{weight}^T \quad \in \mathbb{R}^{BT \times V} logits_sub=vocab_parallel_logits−logits_max.unsqueeze(−1)∈RBT×V\text{logits\_sub} = \text{vocab\_parallel\_logits} - \text{logits\_max}.unsqueeze(-1) \quad \in \mathbb{R}^{BT \times V} exp_logits=exp⁡(logits_sub)∈RBT×V\text{exp\_logits} = \exp(\text{logits\_sub}) \quad \in \mathbb{R}^{BT \times V} exp_logits←exp_logitssum_exp_logits.unsqueeze(−1)∈RBT×V\text{exp\_logits} \gets \frac{\text{exp\_logits}}{\text{sum\_exp\_logits}.unsqueeze(-1)} \quad \in \mathbb{R}^{BT \times V} grad_logits=exp_logits∈RBT×V\text{grad\_logits} = \text{exp\_logits} \quad \in \mathbb{R}^{BT \times V} grad_2d=grad_logits.view(−1,partition_vocab_size)∈RBT×V\text{grad\_2d} = \text{grad\_logits}.view(-1, \text{partition\_vocab\_size}) \quad \in \mathbb{R}^{BT \times V} arange_1d=[0,1,…,BT−1]∈NBT\text{arange\_1d} = [0, 1, \dots, BT-1] \quad \in \mathbb{N}^{BT} softmax_update=1−target_mask.view(−1)∈RBT\text{softmax\_update} = 1 - \text{target\_mask}.view(-1) \quad \in \mathbb{R}^{BT} grad_2d[arange_1d,masked_target_1d]←grad_2d[arange_1d,masked_target_1d]−softmax_update\text{grad\_2d}[\text{arange\_1d}, \text{masked\_target\_1d}] \gets \text{grad\_2d}[\text{arange\_1d}, \text{masked\_target\_1d}] - \text{softmax\_update} grad_logits←grad_logits⊙grad.unsqueeze(−1)∈RBT×V\text{grad\_logits} \gets \text{grad\_logits} \odot \text{grad}.unsqueeze(-1) \quad \in \mathbb{R}^{BT \times V} grad_input=grad_logits⋅weight∈RBT×H\text{grad\_input} = \text{grad\_logits} \cdot \text{weight} \quad \in \mathbb{R}^{BT \times H} grad_weight=grad_logitsT⋅input∈RV×H\text{grad\_weight} = \text{grad\_logits}^T \cdot \text{input} \quad \in \mathbb{R}^{V \times H}

Function Prototype

Each operator uses a two-phase API. First call aclnnFusedLinearCrossEntropyLossGradGetWorkspaceSize to obtain the workspace size required for computation and the executor that contains the computation process. Then call aclnnFusedLinearCrossEntropyLossGrad to execute the computation.

aclnnStatus aclnnFusedLinearCrossEntropyLossGradGetWorkspaceSize(
  const aclTensor   *grad,
  const aclTensor   *input,
  const aclTensor   *weight,
  const aclTensor   *targetMask,
  const aclTensor   *maskedTarget,
  float              labelSmoothing,
  const aclTensor   *logitsMaxOptional,
  const aclTensor   *sumExpLogitsOptional,
  const aclTensor   *softmaxOptional,
  aclTensor         *inputGradOut,
  aclTensor         *weightGradOut,
  uint64_t          *workspaceSize,
  aclOpExecutor    **executor)
aclnnStatus aclnnFusedLinearCrossEntropyLossGrad(
  void             *workspace,
  uint64_t          workspaceSize,
  aclOpExecutor    *executor,
  aclrtStream       stream)

aclnnFusedLinearCrossEntropyLossGradGetWorkspaceSize

  • Parameters

    Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor
    grad Input Gradient of the current node. It is the input grad in the formula. Empty tensors are supported. FLOAT32 ND 1 √
    Input Input Input matrix of the matrix multiplication. It is the input input in the formula. The dimension length of dim 1 is the same as the length of input grad. Empty tensors are supported. FLOAT16, BFLOAT16 ND 2 √
    weight Input Weight matrix in matrix multiplication, that is, weight in the formula. The data type is the same as that of input input. The dimension length of dim 1 cannot be less than 128. The dimension length of dim 2 is the same as that of input input. FLOAT16, BFLOAT16 ND 2 √
    targetMask Input Intermediate variable, indicating whether the corresponding token ID is in the target range. It is target_mask in the formula.
    • Every 1 bit of data represents a Boolean value. 0 indicates false, and 1 indicates true.
    • The shape length multiplied by 8 must not be less than the length of input grad.
    UINT8 ND 1 √
    maskedTarget Input Intermediate variable. Represents the local index mapped from the corresponding word ID to the vocabulary shard on the current device. Invalid targets are masked by targetMask. This is masked_target in the formula. The shape length is the same as that of input grad. INT64, INT32 ND 1 √
    labelSmoothing Input Label smoothing coefficient, used to mitigate overfitting. Currently, only the value 0 is supported. FLOAT32 - - -
    logitsMaxOptional Optional input Intermediate variable. The maximum value of global logits, that is, logits_max in the formula.
    • Supports nullptr input. If nullptr is input, a valid softmaxOptional input must be provided.
    • Has the same shape length as the input grad.
    FLOAT32 ND 1 √
    sumExpLogitsOptional Optional input Intermediate variable. Processed logits, corresponding to sum_exp_logits in the formula.
    • Supports nullptr input. If nullptr is input, a valid softmaxOptional input must be provided.
    • Has the same shape length as the input grad.
    FLOAT32 ND 1 √
    softmaxOptional Optional input Intermediate variable. Result of matrix multiplication. The softmax in the formula.
    • Supports nullptr. If nullptr is input, valid logitsMaxOptional and sumExpLogitsOptional inputs must be provided. If the input is not nullptr, logitsMaxOptional and sumExpLogitsOptional are invalid.
    • The dimension length of the first shape dimension is the same as the length of input grad. The dimension length of the second dimension is the same as the first dimension length of input weight.
    FLOAT32 ND 2 √
    inputGradOut Output Gradient of the leaf node input, that is, grad_input in the formula.
    • The data type is the same as that of input input.
    • The first dimension length of shape is the same as the length of input grad, and the second dimension length is the same as the second dimension length of input weight.
    FLOAT16, BFLOAT16 ND 2 √
    weightGradOut Output Gradient of the leaf node weight, that is, grad_weight in the formula.
    • Same data type as input input.
    • The first dimension length of the shape is the same as the first dimension length of input weight, and the second dimension length is the same as that of input grad.
    FLOAT16, BFLOAT16 ND 2 √
    workspaceSize Output Returns the size of the workspace to be allocated on the Device. - - - - -
    executor Output Returns the op executor. It 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:

    Error Code Error code Description
    ACLNN_ERR_PARAM_NULLPTR 161001 The non-optional input is a null pointer.
    In the use case where the input softmaxOptional is a null pointer, logitsMaxOptional or sumExpLogitsOptional is a null pointer.
    ACLNN_ERR_PARAM_INVALID 161002 The value of the input labelSmoothing is not supported.
    The data type of the input is out of the supported range.
    The data format of the input is out of the supported range.
    The shape of the input is out of the supported range. The length requirement is not met.
    ACLNN_ERR_RUNTIME_ERROR 361001 The current platform is out of the supported platform range.

aclnnFusedLinearCrossEntropyLossGrad

  • Parameters

    Parameter Input/Output Description
    workspace Input Workspace memory address requested on the device.
    workspaceSize Input Size of the workspace requested on the device, obtained by calling the first-phase API aclnnFusedLinearCrossEntropyLossGradGetWorkspaceSize.
    executor Input Op executor that contains the operator computation flow.
    stream Input Specifies the stream for task execution.
  • Return Value

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

Constraints

  • Deterministic computation:
    • aclnnFusedLinearCrossEntropyLossGrad defaults to a deterministic implementation.

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_fused_linear_cross_entropy_loss_grad.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;
}

int Init(int32_t deviceId, aclrtStream *stream)
{
    // Boilerplate: initialize resources
    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>
std::vector<T> GenZeroVector(const std::vector<int64_t>& shape) {
    // 1. Calculate the total number of elements.
    size_t total = 1;
    for (auto dim : shape) {
        total *= dim;
    }

    // 2. Fill with 0.
    std::vector<T> vec(total);
    for (auto& elem : vec) {
        elem = 0;
    }
    return vec;
}

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-side 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-side data to device-side 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 the aclCreateTensor API to create aclTensor.
    *tensor = aclCreateTensor(shape.data(), shape.size(), dataType, strides.data(), 0, aclFormat::ACL_FORMAT_ND,
                              shape.data(), shape.size(), *deviceAddr);
    return 0;
}

template <typename T>
int CreateEmptyAclTensor(const std::vector<int64_t> &shape, void **deviceAddr,
                         aclDataType dataType, aclTensor **tensor)
{
    auto size = GetShapeSize(shape) * sizeof(T);
    // Call aclrtMalloc to allocate device-side 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);

    // 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 the aclCreateTensor API to create 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 device/stream. For details, see the ACL external API list.
    // Fill in deviceId based on your 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 custom inputs and outputs based on the API definition.
    int64_t BT = 1024;
    int64_t V = 1024;
    int64_t H = 1024;
    std::vector<int64_t> gradShape = {BT};
    std::vector<int64_t> inputShape = {BT, H};
    std::vector<int64_t> weightShape = {V, H};
    std::vector<int64_t> targetMaskShape = {BT};
    std::vector<int64_t> maskedTargetShape = {BT};
    std::vector<int64_t> softmaxOptionalShape = {BT, V};
    std::vector<int64_t> inputGradOutShape = {BT, H};
    std::vector<int64_t> weightGradOutShape = {V, H};
    void *gradDeviceAddr = nullptr;
    void *inputDeviceAddr = nullptr;
    void *weightDeviceAddr = nullptr;
    void *targetMaskDeviceAddr = nullptr;
    void *maskedTargetDeviceAddr = nullptr;
    void *softmaxOptionalDeviceAddr = nullptr;
    void *inputGradOutDeviceAddr = nullptr;
    void *weightGradOutDeviceAddr = nullptr;
    aclTensor *grad = nullptr;
    aclTensor *input = nullptr;
    aclTensor *weight = nullptr;
    aclTensor *targetMask = nullptr;
    aclTensor *maskedTarget = nullptr;
    float labelSmoothing = 0.0;
    aclTensor *logitsMaxOptional = nullptr;
    aclTensor *sumExpLogitsOptional = nullptr;
    aclTensor *softmaxOptional = nullptr;
    aclTensor *inputGradOut = nullptr;
    aclTensor *weightGradOut = nullptr;
    // Create the aclTensor.
    auto gradData = GenZeroVector<int32_t>(gradShape);
    ret = CreateAclTensor<int32_t>(gradData, gradShape, &gradDeviceAddr, aclDataType::ACL_FLOAT, &grad);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    auto inputData = GenZeroVector<int16_t>(inputShape);
    ret = CreateAclTensor<int16_t>(inputData, inputShape, &inputDeviceAddr, aclDataType::ACL_FLOAT16, &input);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    auto weightData = GenZeroVector<int16_t>(weightShape);
    ret = CreateAclTensor<int16_t>(weightData, weightShape, &weightDeviceAddr, aclDataType::ACL_FLOAT16, &weight);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    auto targetMaskData = GenZeroVector<int8_t>(targetMaskShape);
    ret = CreateAclTensor<int8_t>(targetMaskData, targetMaskShape, &targetMaskDeviceAddr, aclDataType::ACL_UINT8, &targetMask);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    auto maskedTargetData = GenZeroVector<int32_t>(maskedTargetShape);
    ret = CreateAclTensor<int32_t>(maskedTargetData, maskedTargetShape, &maskedTargetDeviceAddr, aclDataType::ACL_INT32, &maskedTarget);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    auto softmaxOptionalData = GenZeroVector<int32_t>(softmaxOptionalShape);
    ret = CreateAclTensor<int32_t>(softmaxOptionalData, softmaxOptionalShape, &softmaxOptionalDeviceAddr, aclDataType::ACL_FLOAT, &softmaxOptional);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    auto inputGradOutData = GenZeroVector<int16_t>(inputGradOutShape);
    ret = CreateAclTensor<int16_t>(inputGradOutData, inputGradOutShape, &inputGradOutDeviceAddr, aclDataType::ACL_FLOAT16, &inputGradOut);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    auto weightGradOutData = GenZeroVector<int16_t>(weightGradOutShape);
    ret = CreateAclTensor<int16_t>(weightGradOutData, weightGradOutShape, &weightGradOutDeviceAddr, aclDataType::ACL_FLOAT16, &weightGradOut);
    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 aclnnFusedLinearCrossEntropyLossGrad.
    ret = aclnnFusedLinearCrossEntropyLossGradGetWorkspaceSize(grad, input, weight, targetMask, maskedTarget, labelSmoothing, logitsMaxOptional, sumExpLogitsOptional, softmaxOptional, inputGradOut, weightGradOut, &workspaceSize, &executor);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnFusedLinearCrossEntropyLossGradGetWorkspaceSize failed. ERROR: %d\n", ret); return ret);
    // Allocate device memory based on the workspaceSize computed 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 aclnnFusedLinearCrossEntropyLossGrad.
    ret = aclnnFusedLinearCrossEntropyLossGrad(workspaceAddr, workspaceSize, executor, stream);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnFusedLinearCrossEntropyLossGrad failed. ERROR: %d\n", ret); return ret);

    // 4. (boilerplate) Wait synchronously 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 values. Copy the result from device memory to host memory. Modify this based on the specific API definition.
    // inputGradOut
    auto size = GetShapeSize(inputGradOutShape);
    std::vector<aclFloat16> resultData(size, 0);
    ret = aclrtMemcpy(resultData.data(), resultData.size() * sizeof(resultData[0]), inputGradOutDeviceAddr, 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 ret);
    for (int64_t i = 0; i < 16; i++) {
        LOG_PRINT("result[%ld] is: %f\n", i, aclFloat16ToFloat(resultData[i]));
    }

    // 6. Release the aclTensor. Modify this based on the specific API definition.
    aclDestroyTensor(grad);
    aclDestroyTensor(input);
    aclDestroyTensor(weight);
    aclDestroyTensor(targetMask);
    aclDestroyTensor(maskedTarget);
    aclDestroyTensor(softmaxOptional);
    aclDestroyTensor(inputGradOut);
    aclDestroyTensor(weightGradOut);

    // 7. Release Device resources. Modify based on the specific API definition.
    aclrtFree(gradDeviceAddr);
    aclrtFree(inputDeviceAddr);
    aclrtFree(weightDeviceAddr);
    aclrtFree(targetMaskDeviceAddr);
    aclrtFree(maskedTargetDeviceAddr);
    aclrtFree(softmaxOptionalDeviceAddr);
    aclrtFree(inputGradOutDeviceAddr);
    aclrtFree(weightGradOutDeviceAddr);
    if (workspaceSize > 0) {
        aclrtFree(workspaceAddr);
    }
    aclrtDestroyStream(stream);
    aclrtResetDevice(deviceId);
    aclFinalize();

    return 0;
}