aclnnGluBackward

📄 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: Performs the backward propagation of aclnnGlu.

  • Formula:

    ∂GLU(a,b)∂(a,b)=cat(σ(b),σ(b)⊗a⊗(1−σ(b)))\frac{\partial GLU(a,b)}{\partial(a,b)}=cat(\sigma(b),\sigma(b) \otimes a \otimes (1-\sigma(b)))
  • Mathematical expression:

    Assume that the output GLUGrad consists of two parts: out = [a_grad, b_grad], then: sig_b = sigmoid(b) a_grad = y_grad sig_b b_grad = a_grad (a - a * sig_b) Where: y_grad is gradOut, a represents the first half tensor of the input tensor evenly split along the specified dim, and b represents the second half tensor.

Function Prototype

Each operator is divided into a two-phase API. The "aclnnGluBackwardGetWorkspaceSize" API must be called first to obtain the workspace size required for computation and the executor that encapsulates the operator computation flow. Then, the "aclnnGluBackward" API is called to perform the computation.

aclnnStatus aclnnGluBackwardGetWorkspaceSize(
  const aclTensor *gradOut,
  const aclTensor *self,
  int64_t          dim,
  const aclTensor *out,
  uint64_t        *workspaceSize,
  aclOpExecutor  **executor)
aclnnStatus aclnnGluBackward(
  void           *workspace,
  uint64_t        workspaceSize,
  aclOpExecutor  *executor,
  aclrtStream     stream)

aclnnGluBackwardGetWorkspaceSize

  • Parameters:

    Parameter Input/Output Description Instruction Data Type Data Format Dimension (Shape) Non-contiguous Tensor
    gradOut (aclTensor*) Input Represents the gradient update coefficient, i.e., y_grad in the formula.
    • Supports empty tensors.
    • The data type must be the same as that of self, with the shape $(*_1,M,*_2)$, where $*$ denotes the corresponding dimension in self and $M = N /2$.
    DOUBLE, FLOAT, FLOAT16, BFLOAT16 ND - √
    self (aclTensor*) Input Specifies the input for GluBackward computation. The tensor must have a dimension greater than 0, and the shape must be divisible by 2 on the dimension corresponding to the dim parameter. The shape is expressed as $(*_1,N,*_2)$, where $*$ represents any number of additional dimensions, and $N$ represents the size of the dimension specified by dim. DOUBLE, FLOAT, FLOAT16, BFLOAT16 ND - √
    dim (int64_t) Input Specifies the dimension along which to split the input self. Value range: [-self.dim, self.dim-1]. - - - -
    out (aclTensor*) Output Computes the output. The data type and shape must be consistent with those of self. DOUBLE, FLOAT, FLOAT16, BFLOAT16 ND - √
    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 flow. - - - - -
    • Atlas inference products, Atlas training products: The supported data types are DOUBLE, FLOAT, and FLOAT16.
  • 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 gradOut, self, or out is a null pointer.
    ACLNN_ERR_PARAM_INVALID 161002 The data types of gradOut, self, and out are not within the supported range.
    The input parameter dim exceeds the valid dimension range of self's shape [-self.dim, self.dim-1].
    The dimension corresponding to the specified dim of the input parameter self is not divisible by 2.
    The shape of out is not equal to the shape of self.
    The data types of gradOut and out are inconsistent with that of self.
    The shape of gradOut does not satisfy (*1, M, *2), where M = N / 2 and N is the value of self in the dimension specified by dim.
    The number of dimensions of gradOut, self, or out exceeds 8.
    The number of dimensions of self equals 0.

aclnnGluBackward

  • Parameters:

    Parameter Input/Output Description
    workspace Input Specifies the workspace memory address applied for on the Device side.
    workspaceSize Input Specifies the workspace size applied for on the Device side, which is obtained through the first-phase API aclnnGluBackwardGetWorkspaceSize.
    executor Input Operator executor, which contains the operator computation flow.
    stream Input Specifies the stream that executes the task.
  • Return value

    aclnnStatus: return code. For details, see aclnn Return Code.

Constraints

  • Deterministic computation:

    • aclnnGluBackward defaults to a deterministic implementation.

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_glu_backward.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 shape_size = 1;
  for (auto i : shape) {
    shape_size *= i;
  }
  return shape_size;
}

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 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 host-side data to device memory using 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);

  // Calculate 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];
  }

  // 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. See the ACL API manual.
  // Set deviceId based on the actual device.
  int32_t deviceId = 0;
  aclrtStream stream;
  auto ret = Init(deviceId, &stream);
  // Handle based on your own needs.
  CHECK_RET(ret == 0, LOG_PRINT("Init acl failed. ERROR: %d\n", ret); return ret);
  // Construct the input and output. Customize the construction based on the API interface.
  std::vector<int64_t> gradOutShape = {2,4,3};
  std::vector<int64_t> selfShape = {2,4,6};
  std::vector<int64_t> outShape = {2,4,6};
  void* gradOutDeviceAddr = nullptr;
  void* selfDeviceAddr = nullptr;
  void* outDeviceAddr = nullptr;
  aclTensor* gradOut = nullptr;
  aclTensor* self = nullptr;
  aclTensor* out = nullptr;

  std::vector<float> gradOutHostData = {
    1,  1,  1,
    1,  1,  1,
    1,  1,  1,
    1,  1,  1,
    1,  1,  1,
    1,  1,  1,
    1,  1,  1,
    1,  1,  1
  };

  std::vector<float> selfHostData = {
    0.2948,  1.6331,  2.3158, -0.6872,  0.3036,  0.1575,
    0.2992,  1.0893, -0.1126,  0.1910, -1.3675,  0.5587,
    0.4928,  1.4385,  0.6834, -0.6529,  1.0361, -0.6160,
    1.2554, -2.0038,  0.5361, -1.4009, -0.7497, -0.8814,
    0.4113,  0.7549, -1.2869, -1.4354,  0.6939,  0.2192,
    0.3932,  1.8506, -0.7737,  3.6379, -0.9404, -1.1261,
    -1.6927,  0.8456,  0.6500,  0.2738,  0.5115,  0.3356,
    0.5763,  0.2667, -0.6570, -0.4159,  1.5258,  0.0843
  };
  std::vector<float> outHostData = {
    0, 0, 0, 0, 0, 0,
    0, 0, 0, 0, 0, 0,
    0, 0, 0, 0, 0, 0,
    0, 0, 0, 0, 0, 0,
    0, 0, 0, 0, 0, 0,
    0, 0, 0, 0, 0, 0,
    0, 0, 0, 0, 0, 0,
    0, 0, 0, 0, 0, 0
  };

  // Create the gradOut aclTensor.
  ret = CreateAclTensor(gradOutHostData, gradOutShape, &gradOutDeviceAddr, aclDataType::ACL_FLOAT, &gradOut);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  // Create the self aclTensor.
  ret = CreateAclTensor(selfHostData, selfShape, &selfDeviceAddr, aclDataType::ACL_FLOAT, &self);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  // Create the out aclTensor.
  ret = CreateAclTensor(outHostData, outShape, &outDeviceAddr, aclDataType::ACL_FLOAT, &out);
  CHECK_RET(ret == ACL_SUCCESS, return ret);

  int64_t dim = -1;

  // 3. Call the CANN operator library API. Replace with the specific API.
  uint64_t workspaceSize = 0;
  aclOpExecutor* executor;
  // Call the first-phase API of aclnnGluBackward.
  ret = aclnnGluBackwardGetWorkspaceSize(gradOut, self, dim, out, &workspaceSize, &executor);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnGluBackwardGetWorkspaceSize 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 aclnnGluBackward.
  ret = aclnnGluBackward(workspaceAddr, workspaceSize, executor, stream);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnGluBackward failed. ERROR: %d\n", ret); return ret);
  // 4. (Boilerplate) Synchronize and 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 based on the specific API definition.
  auto size = GetShapeSize(outShape);
  std::vector<float> resultData(size, 0);
  ret = aclrtMemcpy(resultData.data(), resultData.size() * sizeof(resultData[0]), outDeviceAddr, size * sizeof(float),
                    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 aclTensor. Modify based on the specific API definition.
  aclDestroyTensor(gradOut);
  aclDestroyTensor(self);
  aclDestroyTensor(out);

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