aclnnDropoutV3Grad

📄 View Source Code

Applicable Products

  • Ascend 950PR&950DT products: Supported
  • Atlas A3 products: Not supported
  • Atlas A2 products: Not supported
  • Atlas 200I/500 A2 inference products: Not supported
  • Atlas inference products: Not supported
  • Atlas training products: Not supported

Function

  • Description: During training, elements in the input are randomly set to zero based on the probability mask, and the output is scaled up by scale. The computation uses a pure multiplication chain gradX = gradY * mask * scale (mask, a value of 0 or 1, participates in the multiplication).
  • Formula:gradXi=gradYi∗maski∗scalegradX_i = gradY_i * mask_i * scale where maski∈{0,1}mask_i \in \{0, 1\} is a scalar value (converted from the input bitmask).

Function Prototype

Each operator uses a two-phase API. You must first call the "aclnnDropoutV3GradGetWorkspaceSize" API to obtain the workspace size required for computation and the executor containing the operator computation flow, and then call the "aclnnDropoutV3Grad" API to execute the computation.

aclnnStatus aclnnDropoutV3GradGetWorkspaceSize(
  const aclTensor* gradY,
  const aclTensor* mask,
  double           scale,
  aclTensor*       gradX,
  uint64_t*        workspaceSize,
  aclOpExecutor**  executor)
aclnnStatus aclnnDropoutV3Grad(
  void          *workspace,
  uint64_t       workspaceSize,
  aclOpExecutor *executor,
  aclrtStream    stream)

aclnnDropoutV3GradGetWorkspaceSize

  • Parameters:

    Parameter Input/Output Description Instruction Data Type Data Format Shape Non-contiguous Tensor
    gradY (aclTensor*) Input The input gradY_i in the corresponding formula. Supports empty tensor. FLOAT, FLOAT16, BFLOAT16 ND 0-8 √
    mask (aclTensor*) Input Bitmask data. Supports the bit type and is stored using the UINT8 type.
    • Supports empty tensors.
    • The number of elements must be (align(number of elements in gradY,128)/8), indicating that the number of bits must be aligned to 128, where align means rounding the number of elements in gradY up to a multiple of 128. For example, align(1111, 128) returns 1152.
    UINT8 ND 0-8 √
    scale (double) Input Corresponds to the input scale in the corresponding formula, used to compute the scaling factor of the output data. scale comes from 1/(1-p) in the forward pass, where p is the dropout probability with a value range of [0,1); therefore, scale is 0 or greater than or equal to 1. - - - -
    gradX (aclTensor*) Output The output gradX_i in the corresponding formula.
    • Supports empty tensors.
    • The data type must be a data type that gradY can be converted to.
    • The shape must be the same as that of gradY.
    FLOAT, FLOAT16, BFLOAT16 ND 0-8 √
    workspaceSize (uint64_t*) Output Returns the size of the workspace to be requested on the device. - - - - -
    executor (aclOpExecutor**) Output Returns the op executor, which contains the operator computation flow. - - - - -
  • Return value

    aclnnStatus: Returns the status code. For details, see 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 Input gradY, mask, or gradX is a null pointer.
    ACLNN_ERR_PARAM_INVALID 161002 The data type of gradY, mask, or gradX is not within the supported range.
    The shapes of gradY and gradX are inconsistent.
    The shape of mask does not meet the requirements.

aclnnDropoutV3Grad

  • Parameters:

    Parameter Input/Output Description
    workspace Input Workspace memory address allocated on the Device.
    workspaceSize Input Size of the workspace allocated on the Device, obtained by the first-phase API aclnnDropoutV3GradGetWorkspaceSize.
    executor Input op executor, which contains the operator computation flow.
    stream Input Stream for executing the task.
  • Return value

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

Constraints

  • deterministic computation:
    • aclnnDropoutV3Grad 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_dropout_v3_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, 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 memory on the device.
  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 data from the host 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 device/stream. For details, see the ACL API list.
  // 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 inputs and outputs as required by the API.
  // gradY: backward gradient, shape {4, 2}, 8 elements in total.
  // mask : bit mask, the number of elements is align(8, 128)/8 = 16 (uint8).
  std::vector<int64_t> gradYShape = {4, 2};
  std::vector<int64_t> maskShape = {16};
  std::vector<int64_t> gradXShape = {4, 2};
  void* gradYDeviceAddr = nullptr;
  void* maskDeviceAddr = nullptr;
  void* gradXDeviceAddr = nullptr;
  aclTensor* gradY = nullptr;
  aclTensor* mask = nullptr;
  aclTensor* gradX = nullptr;
  std::vector<float> gradYHostData = {0, 1, 2, 3, 4, 5, 6, 7};
  std::vector<uint8_t> maskHostData(16, 0);
  // The first byte of mask is 42 = 0b00101010, and the bit order after LSB-first expansion is 0,1,0,1,0,1,0,0.
  // With scale=2, the result is gradY_i * mask_i * scale, i.e., result = {0, 2, 0, 6, 0, 10, 0, 0}.
  maskHostData[0] = 42;
  std::vector<float> gradXHostData(8, 0);
  // scale = 1 / (1 - p), where p = 0.5 -> scale = 2
  double scale = 2;

  // Create the gradY aclTensor.
  ret = CreateAclTensor(gradYHostData, gradYShape, &gradYDeviceAddr, aclDataType::ACL_FLOAT, &gradY);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  // Create the mask aclTensor.
  ret = CreateAclTensor(maskHostData, maskShape, &maskDeviceAddr, aclDataType::ACL_UINT8, &mask);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  // Create the gradX aclTensor.
  ret = CreateAclTensor(gradXHostData, gradXShape, &gradXDeviceAddr, aclDataType::ACL_FLOAT, &gradX);
  CHECK_RET(ret == ACL_SUCCESS, return ret);

  // 3. Call aclnnDropoutV3Grad to execute dropout.
  uint64_t workspaceSize = 0;
  aclOpExecutor* executor;
  // Call the first-phase API of aclnnDropoutV3Grad.
  ret = aclnnDropoutV3GradGetWorkspaceSize(gradY, mask, scale, gradX, &workspaceSize, &executor);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnDropoutV3GradGetWorkspaceSize 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 aclnnDropoutV3Grad.
  ret = aclnnDropoutV3Grad(workspaceAddr, workspaceSize, executor, stream);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnDropoutV3Grad 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, and copy the results from the device memory to the host memory. Modify the code based on the specific API definition.
  auto size = GetShapeSize(gradXShape);
  std::vector<float> resultData(size, 0);
  ret = aclrtMemcpy(resultData.data(), resultData.size() * sizeof(resultData[0]), gradXDeviceAddr,
                    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. Modify the code based on the specific API definition.
  aclDestroyTensor(gradY);
  aclDestroyTensor(gradX);
  aclDestroyTensor(mask);

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