aclnnLogitGrad

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

    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 < 0 \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 divided into a two-phase API. You must first call the "aclnnLogitGradGetWorkspaceSize" API to obtain the input parameters and calculate the required workspace size based on the calculation 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 Dimension (Shape) Non-contiguous Tensor
    x (aclTensor*) Input Input tensor, i.e., x in the formula. Supports empty tensors. BFLOAT16, FLOAT16, FLOAT ND 0-8 √
    dy (aclTensor*) Input. Gradient of the forward output result, i.e., dy in the formula.
    • Supports empty tensors.
    • The data type, data format, and shape are consistent with the input x.
    BFLOAT16, FLOAT16, FLOAT ND 0-8 √
    eps (double) Input Specifies the epsilon boundary that limits the input to prevent division-by-zero errors. Corresponds to eps in the formula. Suggested value: -1. - - - -
    out (aclTensor*) Output Output tensor, which is dx in the formula. The data type, data format, and shape of the output are consistent with the input x. BFLOAT16, FLOAT16, FLOAT ND 0-8 √
    workspaceSize (uint64_t*) Output Returns the workspace size to be requested on the Device side. - - - - -
    executor (aclOpExecutor**) 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 Code Error Code Description
    ACLNN_ERR_PARAM_NULLPTR 161001 The input x, dy, or out is a null pointer.
    ACLNN_ERR_PARAM_INVALID 161002 The data type of x, dy, or out is not within the supported range.

aclnnLogitGrad

  • Parameters:

    Parameter Input/Output Description
    workspace Input Specifies the workspace memory address applied on the Device side.
    workspaceSize Input Specifies the workspace size applied on the Device side, which is obtained by the first-phase API aclnnLogitGradGetWorkspaceSize.
    executor Input Operator 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:

    • 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 provides example code for reference only. For details about compilation and running, 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 apply for 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);
  // Copy data from the host side to the device side by calling aclrtMemcpy.
  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 a 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];
  }

  // Create an aclTensor by calling the aclCreateTensor API.
  *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. See 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 the input and output. Customize the construction 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 with the specific API name.
  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);

  // Apply for 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 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 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. Modify this based on the specific API definition.
  PrintOutResult(dxShape, &dxDeviceAddr);

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

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

  return 0;
}