aclnnLogitGrad

📄 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:

    Completes the backward propagation of aclnnLogit.

  • Formula:

dxi={NaN,if x<0 or x>1,eps<00,if x<eps or x>1−eps,eps≥0dyixi⋅(1−xi),if eps≤xi≤1−epsdx_i= \begin{cases} NaN, & \text{if } x < \text0 \text{ or } x > 1 ,eps <0 \\ 0, & \text{if } x < \text{eps} \text{ or } x > 1 - \text{eps},eps \geq 0 \\ \frac{dy_i}{x_i \cdot (1 - x_i)}, & \text{if } \text{eps} \leq x_i \leq 1 - \text{eps} \\ \end{cases}

Function Prototype

Each operator is split into a two-phase API. You must call the "aclnnLogitGradGetWorkspaceSize" API first to obtain the input parameters and calculate the required workspace size based on the computation process, and then call the "aclnnLogitGrad" API to perform the computation.

aclnnStatus aclnnLogitGradGetWorkspaceSize(
  const aclTensor *x,
  const aclTensor *dy,
  double           eps,
  const aclTensor *out,
  uint64_t        *workspaceSize,
  aclOpExecutor  **executor)
aclnnStatus aclnnLogitGrad(
  void            *workspace,
  uint64_t         workspaceSize,
  aclOpExecutor   *executor,
  aclrtStream      stream)

aclnnLogitGradGetWorkspaceSize

  • Parameters:

    Parameter Input/Output Description Instruction Data Type Data Format Shape Non-contiguous Tensor
    x (aclTensor*) Input Input tensor, x in the formula. Supports empty tensors. BFLOAT16, FLOAT16, FLOAT ND 0-8 √
    dy (aclTensor*) Input Gradient of the forward output, dy in the formula.
    • Empty tensors are supported.
    • The data type, data format, and shape are the same as those of input x.
    BFLOAT16, FLOAT16, FLOAT ND 0-8 √
    eps (double) Input Epsilon boundary of input to prevent division by zero. It is eps in the formula. Recommended value: -1. - - - -
    out (aclTensor*) Output Output tensor, the output dx in the formula. The data type, data format, and shape of the output are the same as those of input x. BFLOAT16, FLOAT16, FLOAT ND 0-8 ×
    workspaceSize (uint64_t*) Output Returns the workspace size to be allocated on the Device. - - - - -
    executor (aclOpExecutor**) Output Returns the op executor, which contains the operator computation flow. - - - - -
  • Return value

    aclnnStatus: return status code. For details, see aclnn Error 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 x, dy, or out is a null pointer.
    ACLNN_ERR_PARAM_INVALID 161002 The data type of x, dy, or out is not supported.

aclnnLogitGrad

  • Parameters:

    Parameter Input/Output Description
    workspace Input The workspace memory address on the Device.
    workspaceSize Input The workspace size on the Device, obtained by the first-phase API aclnnLogitGradGetWorkspaceSize.
    executor Input Executor of the op, which contains the operator computation flow.
    stream Input Specifies the stream for executing tasks.
  • Return value

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

Constraints

  • Deterministic computation:

    • aclnnLogitGrad defaults to a deterministic implementation.
  • Impact of eps on x and the output:

    • When eps is less than 0 and x is outside the range [0, 1], the output is NaN.
    • When eps is greater than or equal to 0, if x is outside the range [eps, 1 - eps], the output is 0.
    • When eps is greater than 1, the output is NaN; when the value is 1, the output is Inf.
    • When eps is Inf, the output is 0.
    • When eps is NaN, the output is NaN.
  • Impact of x values on the output:

    • When x is 0 or 1, the output is Inf.
    • When x is Inf or NaN, the output is NaN.
  • When dy is Inf or NaN, the output is Inf or NaN.

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_logit_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;
}

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 < size; i++) {
    LOG_PRINT("mean result[%ld] is: %f\n", i, resultData[i]);
  }
}

int Init(int32_t deviceId, aclrtStream* stream) {
  // Boilerplate for 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 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);

  // Compute 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) Device/stream initialization. Refer to the acl API.
  // Set deviceId based on the 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 inputs and outputs. The construction must be customized based on the API.
  std::vector<int64_t> xShape = {1, 4};

  std::vector<int64_t> dyShape = {1, 4};

  std::vector<float> xHostData = {0.1, 0.2, 0.3, 0.4};

  std::vector<float> dyHostData = {1.0, 2.0, 3.0, 4.0};

  void* xDeviceAddr = nullptr;

  void* dyDeviceAddr = nullptr;

  aclTensor* x = nullptr;

  aclTensor* dy = nullptr;

  // Create the x aclTensor.
  ret = CreateAclTensor(xHostData, xShape, &xDeviceAddr, aclDataType::ACL_FLOAT, &x);
  CHECK_RET(ret == ACL_SUCCESS, return ret);

  // Create the dy aclTensor.
  ret = CreateAclTensor(dyHostData, dyShape, &dyDeviceAddr, aclDataType::ACL_FLOAT, &dy);
  CHECK_RET(ret == ACL_SUCCESS, return ret);

  double eps = -1.0;
  std::vector<int64_t> dxShape = {1, 4};
  std::vector<float> dxHostData(4, 1);
  aclTensor* dx = nullptr;
  void* dxDeviceAddr = nullptr;
  // Create the dx aclTensor.
  ret = CreateAclTensor(dxHostData, dxShape, &dxDeviceAddr, aclDataType::ACL_FLOAT, &dx);
  CHECK_RET(ret == ACL_SUCCESS, return ret);

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

  // Call the first-phase API of aclnnLogitGrad.
  ret = aclnnLogitGradGetWorkspaceSize(x, dy, eps, dx, &workspaceSize, &executor);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnLogitGradGetWorkspaceSize 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 aclnnLogitGrad.
  ret = aclnnLogitGrad(workspaceAddr, workspaceSize, executor, stream);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnLogitGrad 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, copy the results from device memory to host memory, and modify the code based on the specific API definition.
  PrintOutResult(dxShape, &dxDeviceAddr);

  // 6. Release aclTensor. Modify the code based on the specific API definition.
  aclDestroyTensor(x);
  aclDestroyTensor(dy);
  aclDestroyTensor(dx);

  // 7. Release device resources. Modify the code based on the specific API definition.
  aclrtFree(xDeviceAddr);
  aclrtFree(dyDeviceAddr);
  aclrtFree(dxDeviceAddr);
  if (workspaceSize > 0) {
    aclrtFree(workspaceAddr);
  }
  aclrtDestroyStream(stream);
  aclrtResetDevice(deviceId);
  aclFinalize();

  return 0;
}