aclnnCrossEntropyLossGrad

📄 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: Backward propagation of aclnnCrossEntropyLoss.
  • Formula:ignoreMasktarget(t)={1,target(t)≠ignoreIndex0,target(t)=ignoreIndexignoreMask_{target(t)}=\begin{cases} 1, &target(t) ≠ ignoreIndex \\ 0, &target(t) = ignoreIndex \end{cases} smoothLossGrad={grad/sum(weighttarget∗ignoreMask)∗labelSmoothing/C,reduction=meangrad∗labelSmoothing/C,reduction=sumgrad∗labelSmoothing/C,reduction=nonesmoothLossGrad=\begin{cases} grad / sum(weight_{target}* ignoreMask) * labelSmoothing / C, &reduction = mean \\ grad * labelSmoothing / C, &reduction = sum \\ grad * labelSmoothing / C, &reduction = none \end{cases} lossOutGrad={grad∗(1−labelSmoothing)/sum(weighttarget∗ignoreMask)∗ignoreMask,reduction=meangrad∗(1−labelSmoothing)∗ignoreMask,reduction=sumgrad∗(1−labelSmoothing)∗ignoreMask,reduction=nonelossOutGrad=\begin{cases} grad * (1-labelSmoothing) / sum(weight_{target}* ignoreMask) * ignoreMask, &reduction = mean \\ grad * (1-labelSmoothing) * ignoreMask, &reduction = sum \\ grad * (1-labelSmoothing) * ignoreMask, &reduction = none \end{cases} nllLossGrad=lossOutGrad∗weighttargetnllLossGrad = lossOutGrad * weight_{target} logSoftmaxGradLossOutSubPart=exp(logProb)∗nllLossGradlogSoftmaxGradLossOutSubPart = exp(logProb) * nllLossGrad predictionsGradLossOutij={nllLossGradi,j=target(i)0,j≠target(i)predictionsGradLossOut_{ij}=\begin{cases} nllLossGrad_i, & j=target(i) \\ 0, & j ≠ target(i) \end{cases} predictionsGradLossOut=logSoftmaxGradLossOutSubPart−predictionsGradLossOutpredictionsGradLossOut = logSoftmaxGradLossOutSubPart - predictionsGradLossOut smoothLossGrad=smoothLossGrad∗ignoreMasksmoothLossGrad = smoothLossGrad * ignoreMask logSoftmaxGradSmoothLoss=smoothLossGrad∗weightlogSoftmaxGradSmoothLoss = smoothLossGrad * weight predictionsGradSmoothLoss=exp(logProb)∗sum(logSoftmaxGradSmoothLoss)−logSoftmaxGradSmoothLosspredictionsGradSmoothLoss = exp(logProb) * sum(logSoftmaxGradSmoothLoss) - logSoftmaxGradSmoothLoss Output when the zloss scenario is not involved:xGradout=predictionsGradLossOut+predictionsGradSmoothLossxGrad_{out} = predictionsGradLossOut + predictionsGradSmoothLoss zloss scenario:gradZ={grad+gradZloss,gradZloss is passedgrad,gradZloss is not passedgradZ=\begin{cases} grad + gradZloss, & \text{gradZloss is passed} \\ grad, & \text{gradZloss is not passed} \end{cases} zlossGrad={gradZ/sum(ignoreMask),reduction=meangradZ,reduction=sumgradZ,reduction=nonezlossGrad=\begin{cases} gradZ / sum(ignoreMask), & &reduction = mean \\ gradZ, & &reduction = sum \\ gradZ, & &reduction = none \end{cases} lseGrad=2∗lseSquareScaleForZloss∗lseForZloss∗ignoreMask∗zlossGradlseGrad = 2 * lseSquareScaleForZloss * lseForZloss * ignoreMask * zlossGrad zlossOutputGrad=exp(logProb)∗lseGradzlossOutputGrad = exp(logProb) * lseGrad Output in the zloss scenario:xGradout=xGradout+zlossOutputGradxGrad_{out} = xGrad_{out} + zlossOutputGrad

Function Prototype

Each operator uses a two-phase API. Call the "aclnnCrossEntropyLossGradGetWorkspaceSize" API first to obtain the workspace size required for the computation and the executor containing the computation process of the operator, and then call the "aclnnCrossEntropyLossGrad" API to perform the computation.

aclnnStatus aclnnCrossEntropyLossGradGetWorkspaceSize(
    const aclTensor *gradLoss,
    const aclTensor *logProb,
    const aclTensor *target,
    const aclTensor *weightOptional,
    const aclTensor *gradZlossOptional,
    const aclTensor *lseForZlossOptional,
    char            *reductionOptional,
    int64_t          ignoreIndex,
    double           labelSmoothing,
    double           lseSquareScaleForZloss,
    const aclTensor *out,
    uint64_t        *workspaceSize,
    aclOpExecutor  **executor)
aclnnStatus aclnnCrossEntropyLossGrad(
    void          *workspace,
    uint64_t       workspaceSize,
    aclOpExecutor *executor,
    aclrtStream    stream)

aclnnCrossEntropyLossGradGetWorkspaceSize

  • Parameters

    Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor
    gradLoss (aclTensor*) Input Gradient of the forward output loss. This parameter corresponds to grad in the formula.
    • If reductionOptional is none, the tensor must be 1D.
    • If reductionOptional is mean/sum, the tensor must be 0D.
    FLOAT16, FLOAT, BFLOAT16 ND (N,)
    N is the batch size
    -
    logProb (aclTensor*) Input logSoftmax result of the forward input. The tensor must be 2D. - FLOAT16, FLOAT, BFLOAT16 ND (N, C)
    C is the number of labels and must be greater than 0
    -
    target (aclTensor*) Input Class indices. Must be a 1D tensor. N is equal to the 0th dimension of input. The value range is [0, C). When ignoreIndex is specified, the value of target can also be ignoreIndex. INT64 ND (N,) -
    weightOptional (aclTensor*) Optional input Requires the shape to be a 1D tensor. - FLOAT - (C,) -
    gradZlossOptional (aclTensor*) Optional input Corresponds to gradZloss in the formula. zloss-related input. If the forward pass outputs zloss, the backward pass takes a grad_zloss input.
    • When reductionOptional is none, a 1D tensor is required.
    • When reductionOptional is mean/sum, a 0D tensor is required.
    • Currently not supported.
    FLOAT16, FLOAT, BFLOAT16 ND (N,) -
    lseForZlossOptional (aclTensor*) Optional input zloss-related input. If lse_square_scale_for_zloss is not 0, the lse_for_zloss intermediate result additionally output by forward propagation is passed to backward propagation to compute lse.
    • Required to be a 1D tensor.
    • Currently not supported.
    FLOAT16, FLOAT, BFLOAT16 ND (N,) -
    reductionOptional (char*) Input Specifies the reduction to be applied to the output.
    • none: no reduction is applied.
    • mean: the weighted average of the output is computed.
    • sum: the output is summed.
    - - - -
    ignoreIndex (int64_t) Input Specifies the label value to be ignored. - INT64 - - -
    labelSmoothing (double) Input Indicates the smoothing amount when computing the loss. A floating-point number in the range [0.0, 1.0], where 0.0 indicates no smoothing. Currently, only 0.0 is supported. DOUBLE - - -
    lseSquareScaleForZloss (double) Input zloss-related attribute. 0.0 indicates the PyTorch native branch; a non-0.0 value indicates the new zloss branch. Currently not supported. DOUBLE - - -
    out (aclTensor*) Output Gradient computation result. Must be a 2D tensor. - Same as gradLoss ND (N,C) -
    workspaceSize (uint64_t*) Output Returns the size of the workspace to be allocated on the Device. - - - - -
    executor (aclOpExecutor**) Output Returns the op executor containing the operator computation flow. - - - - -
  • Return Value

    aclnnStatus: return value of the status 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 gradLoss, logProb, target, or out passed in is a null pointer.
    ACLNN_ERR_PARAM_INVALID 161002 The data types of gradLoss, logProb, target, weightOptional, gradZlossOptional, and lseForZlossOptional are not in the supported range.
    ACLNN_ERR_INNER_TILING_ERROR 561002 The shapes of the input logProb, target, and weightOptional are not in the supported range.

aclnnCrossEntropyLossGrad

  • Parameters

    Parameter Input/Output Description
    workspace Input Workspace memory address allocated on the Device.
    workspaceSize Input Workspace size allocated on the Device, obtained by calling the first-phase API aclnnCrossEntropyLossGradGetWorkspaceSize.
    executor Input Executor of the op, containing the operator computation flow.
    stream Input Stream for executing the task.
  • Return Value

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

Constraints

  • target supports only class label indices, not probability inputs.

  • gradLoss, logProb, gradZlossOptional, lseForZlossOptional, and xGradOut must have the same data type.

  • The zloss function is currently not supported. Passing related inputs, i.e., gradZlossOptional, lseForZlossOptional, and lseSquareScaleForZloss, will not take effect.

  • Deterministic computation:

    • aclnnCrossEntropyLossGrad 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_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>
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 Host data 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 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 documentation.
  // Set deviceId based on the actual device.
  int32_t deviceId = 0;
  aclrtStream stream;
  auto ret = Init(deviceId, &stream);
  // Handle the check as needed.
  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.
  std::vector<int64_t> gradLossShape = {};
  std::vector<int64_t> logProbShape = {2, 3};
  std::vector<int64_t> targetShape = {2,};
  std::vector<int64_t> weightShape = {3,};
  std::vector<int64_t> xGradShape = {2, 3};
  void* gradLossDeviceAddr = nullptr;
  void* logProbDeviceAddr = nullptr;
  void* targetDeviceAddr = nullptr;
  void* weightDeviceAddr = nullptr;
  void* xGradOutDeviceAddr = nullptr;
  aclTensor* gradLoss = nullptr;
  aclTensor* logProb = nullptr;
  aclTensor* target = nullptr;
  aclTensor* weight = nullptr;
  aclTensor* gradZloss = nullptr;
  aclTensor* lseForZloss = nullptr;
  aclTensor* xGradOut = nullptr;
  std::vector<float> gradLossHostData = {0.1};
  std::vector<float> logProbHostData = {-0.2, -0.2, -0.2, -0.2, -0.2, -0.2};
  std::vector<int64_t> targetHostData = {0, 0};
  std::vector<float> weightHostData = {1.0, 1.0, 1.0};
  std::vector<float> xGradOutHostData = {-0.0091, 0.0409, 0.0409, -0.0091, 0.0409, 0.0409};
  int64_t ignoreIndex = -100;
  double labelSmoothing = 0.0;
  double lseSquareScaleForZloss = 0.0;

  // Create the gradLoss aclTensor.
  ret = CreateAclTensor(gradLossHostData, gradLossShape, &gradLossDeviceAddr, aclDataType::ACL_FLOAT, &gradLoss);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  // Create the logProb aclTensor.
  ret = CreateAclTensor(logProbHostData, logProbShape, &logProbDeviceAddr, aclDataType::ACL_FLOAT, &logProb);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  // Create the target aclTensor.
  ret = CreateAclTensor(targetHostData, targetShape, &targetDeviceAddr, aclDataType::ACL_INT64, &target);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  // Create the weight aclTensor.
  ret = CreateAclTensor(weightHostData, weightShape, &weightDeviceAddr, aclDataType::ACL_FLOAT, &weight);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  // Create the xGradOut aclTensor.
  ret = CreateAclTensor(xGradOutHostData, xGradShape, &xGradOutDeviceAddr, aclDataType::ACL_FLOAT, &xGradOut);
  CHECK_RET(ret == ACL_SUCCESS, return ret);

  uint64_t workspaceSize = 0;
  aclOpExecutor* executor;

  // 3. Call the CANN operator library API. Replace with the specific API name.
  // Call the first-phase API of aclnnCrossEntropyLossGrad.
  ret = aclnnCrossEntropyLossGradGetWorkspaceSize(gradLoss, logProb, target, weight, gradZloss, lseForZloss, "mean", ignoreIndex, labelSmoothing, lseSquareScaleForZloss, xGradOut, &workspaceSize, &executor);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnCrossEntropyLossGradGetWorkspaceSize 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 aclnnCrossEntropyLossGrad.
  ret = aclnnCrossEntropyLossGrad(workspaceAddr, workspaceSize, executor, stream);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnCrossEntropyLossGrad failed. ERROR: %d\n", ret); return ret);

  // 4. (boilerplate) Synchronize and wait for the task execution to finish.
  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 based on the specific API definition.
  auto size = GetShapeSize(xGradShape);
  std::vector<float> resultData(size, 0);
  ret = aclrtMemcpy(resultData.data(), resultData.size() * sizeof(resultData[0]), xGradOutDeviceAddr,
                    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 < size; i++) {
    LOG_PRINT("result[%ld] is: %f\n", i, resultData[i]);
  }

  // 6. Release the aclTensor and aclScalar objects. Modify based on the specific API definition.
  aclDestroyTensor(gradLoss);
  aclDestroyTensor(logProb);
  aclDestroyTensor(target);
  aclDestroyTensor(weight);
  aclDestroyTensor(xGradOut);

  // 7. Release device resources. Modify according to the specific API definition.
  aclrtFree(gradLossDeviceAddr);
  aclrtFree(logProbDeviceAddr);
  aclrtFree(targetDeviceAddr);
  aclrtFree(weightDeviceAddr);
  aclrtFree(xGradOutDeviceAddr);
  if (workspaceSize > 0) {
    aclrtFree(workspaceAddr);
  }
  aclrtDestroyStream(stream);
  aclrtResetDevice(deviceId);
  aclFinalize();
  return 0;
}