aclnnGroupedBiasAddGradV2

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: Performs backward computation of groupBiasAdd. This API extends the functionality of the aclnnGroupedBiasAddGrad API by adding the groupIdxType attribute, which specifies the type of groupIdx.
  • Formula:
    (1) When the optional input groupIdxOptional is provided and groupIdxType is 0:
out(G,H)={∑i=groupIdxOptional(j−1)groupIdxOptional(j)gradY(i,H),1≤j≤G−1∑i=0groupIdxOptional(j)gradY(i,H),j=0out(G,H) = \begin{cases} \sum_{i=groupIdxOptional(j-1)}^{groupIdxOptional(j)} gradY(i, H), & 1 \leq j \leq G-1 \\ \sum_{i=0}^{groupIdxOptional(j)} gradY(i, H), & j = 0 \end{cases}

  (2) When the optional input groupIdxOptional is provided and groupIdxType is 1:

groupIdx(j)=∑i=0jgroupIdxOptional(i),j=0,...,G−1groupIdx(j) = \sum_{i=0}^{j} groupIdxOptional(i), j=0,...,G-1 out(G,H)={∑i=groupIdx(j−1)groupIdx(j)gradY(i,H),1≤j≤G−1∑i=0groupIdx(j)gradY(i,H),j=0out(G,H) = \begin {cases} \sum_{i=groupIdx(j-1)}^{groupIdx(j)} gradY(i,H), & 1 \leq j \leq G-1 \\ \sum_{i=0}^{groupIdx(j)} gradY(i, H), & j=0 \end {cases}

  Here, gradY has 2 dimensions, H indicates the dimension size of the last dimension of gradY, G indicates the dimension size of dimension 0 of groupIdxOptional, that is, groupIdxOptional has G numbers, groupIdxOptional(j) indicates the size of the j-th number, and after computation, out has 2 dimensions with shape (G, H).
  (3) When no optional input groupIdxOptional is provided:

out(G,H)=∑i=0CgradY(G,i,H)out(G, H) = \sum_{i=0}^{C} gradY(G, i, H)

  Here, gradY has 3 dimensions, with G, C, and H representing the sizes of the 0th to 2nd dimensions of gradY respectively. After computation, out is 2-dimensional with shape (G, H).

  • Example:
    (1) When the optional input groupIdxOptional is provided and groupIdxType is 0:
    The shape of gradY is (1000, 30), and groupIdxOptional is (400, 600, 1000). gradY is divided into 3 groups, and the number of rows for per-group accumulation is 400, 200, and 400 in turn. After computation, the shape of out is (3, 30).
    (2) When the optional input groupIdxOptional is provided and groupIdxType is 1:
    The shape of gradY is (1000, 30), and groupIdxOptional is (400, 210, 390). gradY is divided into 3 groups, and the number of rows for per-group accumulation is 400, 210, and 390 in turn. After computation, the shape of out is (3, 30).
    (3) When no optional input groupIdxOptional is provided:
    The shape of gradY is (10, 100, 30). gradY is divided into 10 groups, and the number of rows for per-group accumulation is 100 in each group. After computation, the shape of out is (10, 30).

Function Prototype

Each operator uses a two-phase API. You must first call the "aclnnGroupedBiasAddGradV2GetWorkspaceSize" API to obtain the workspace size required for computation and the executor that includes computation of the operator process. Then call the "aclnnGroupedBiasAddGradV2" API to perform the computation.

aclnnStatus aclnnGroupedBiasAddGradV2GetWorkspaceSize(
  const aclTensor *gradY,
  const aclTensor *groupIdxOptional,
  int64_t          groupIdxType,
  aclTensor       *out,
  uint64_t        *workspaceSize,
  aclOpExecutor   **executor)
aclnnStatus aclnnGroupedBiasAddGradV2(
  void          *workspace,
  uint64_t       workspaceSize,
  aclOpExecutor *executor,
  aclrtStream    stream)

aclnnGroupedBiasAddGradV2GetWorkspaceSize

  • Parameters

    Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor
    gradY Input Backward propagation gradient, gradY in the formula. If the optional input groupIdxOptional is present, the shape supports only 2 dimensions. If there is no optional input groupIdxOptional, the shape supports only 3 dimensions. FLOAT, FLOAT16, BFLOAT16 ND 2-3 √
    groupIdxOptional Input End position of each group, groupIdxOptional in the formula. - INT32, INT64 ND 1 √
    groupIdxType groupIdxType Indicates the type of groupIdx. 0: indicates that the value in groupIdxOptional is the end index of each group.
    1: indicates that the value in groupIdxOptional is the size of each group.
    - - - -
    out Output Gradient of bias, which is out in the formula. - Same as gradY. ND 2 ×
    workspaceSize Output Returns the size of the workspace that needs to be side-applied on the Device. - - - - -
    executor Output Returns the op executor, which includes computation of the operator. - - - - -
  • Return value

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

    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 gradY or out is a null pointer.
    ACLNN_ERR_PARAM_INVALID 161002 The data type or dimension of gradY, groupIdxOptional, or out is not supported.
    The dimension relationships of gradY, groupIdxOptional, and out do not match.
    The number of groups exceeds 2048.
    The value of groupIdxType is not supported.

aclnnGroupedBiasAddGradV2

  • Parameters:

    Parameter Input/Output Description
    workspace Input Device-side-applied workspace memory address.
    workspaceSize Input Device-side-applied workspace size, obtained by the first-phase API aclnnGroupedBiasAddGradV2GetWorkspaceSize.
    executor Input op executor, includes computation flow of the operator.
    stream Input Specifies the Stream for task execution.
  • Return value

    aclnnStatus: Returned status code. For details, see aclnn return code.

Constraints

  • Deterministic computation:
    • aclnnGroupedBiasAddGradV2 defaults to a deterministic implementation.
  • groupIdxOptional supports a maximum of 2048 elements.
  • When the optional input groupIdxOptional is present, the tensor values must not exceed the INT32 maximum value and must be non-negative.
  • When the optional input groupIdxOptional is present and groupIdxType is 0, the tensor data must be in ascending order, and the last value must equal the size of the 0th dimension of gradY.
  • With optional input groupIdxOptional and groupIdxType set to 1, the sum of tensor values must equal the dimension size of the 0th dimension of gradY.

Example

The following sample code is for reference only. For details about the compilation and execution process, see Compile and Run Samples.

#include <iostream>
#include <vector>
#include "acl/acl.h"
#include "aclnnop/aclnn_grouped_bias_add_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 shape_size = 1;
  for (auto i : shape) {
    shape_size *= i;
  }
  return shape_size;
}

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 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);

  // Call aclrtMemcpy to copy host-side data to device-side 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) Device/stream initialization. For details, see the acl API manual.
  // Fill in 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 == 0, LOG_PRINT("Init acl failed. ERROR: %d\n", ret); return ret);
  // 2. Construct the input and output. Custom construction is required based on the API.
  std::vector<int64_t> gradYShape = {40, 10};
  std::vector<int64_t> groupIdxShape = {4};
  std::vector<int64_t> outShape = {4, 10};
  void* gradYDeviceAddr = nullptr;
  void* groupIdxDeviceAddr = nullptr;
  void* outDeviceAddr = nullptr;
  aclTensor* gradY = nullptr;
  aclTensor* groupIdx = nullptr;
  aclTensor* out = nullptr;

  std::vector<float> gradYHostData(400, 1.0);
  std::vector<int32_t> groupIdxHostData = {5, 15, 10, 10};
  std::vector<float> outHostData(40, 0.0);
  int64_t groupIdxType = 1;

  // Create the gradY aclTensor.
  ret = CreateAclTensor(gradYHostData, gradYShape, &gradYDeviceAddr, aclDataType::ACL_FLOAT, &gradY);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  // Create the groupIdxOptional aclTensor.
  ret = CreateAclTensor(groupIdxHostData, groupIdxShape, &groupIdxDeviceAddr, aclDataType::ACL_INT32, &groupIdx);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  // Create out aclTensor.
  ret = CreateAclTensor(outHostData, outShape, &outDeviceAddr, aclDataType::ACL_FLOAT, &out);
  CHECK_RET(ret == ACL_SUCCESS, return ret);

  // 3. Call the CANN operator library API. Replace it with the specific API.
  uint64_t workspaceSize = 0;
  aclOpExecutor* executor;
  // Call the first-phase API of aclnnGroupedBiasAddGradV2.
  ret = aclnnGroupedBiasAddGradV2GetWorkspaceSize(gradY, groupIdx, groupIdxType, out, &workspaceSize, &executor);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnGroupedBiasAddGradV2GetWorkspaceSize 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 aclnnGroupedBiasAddGradV2.
  ret = aclnnGroupedBiasAddGradV2(workspaceAddr, workspaceSize, executor, stream);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnGroupedBiasAddGradV2 failed. ERROR: %d\n", ret); return ret);
  // 4. (Boilerplate) Wait synchronously 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 value, and copy the result on the device-side memory to the host. Modify it 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 it based on the specific API definition.
  aclDestroyTensor(gradY);
  aclDestroyTensor(groupIdx);
  aclDestroyTensor(out);

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