aclnnBroadcastGradientArgs

📄 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: BroadcastGradientArgs is a TensorFlow operator used to compute the broadcast dimension indices required for gradient propagation. During backward propagation, based on the original shapes of the two tensors in forward propagation, it automatically identifies the dimensions extended by the broadcasting mechanism and outputs the dimensions along which gradients need to be reduced, so that the gradients can be restored from the broadcast shape to the shape of each original tensor.

  • Computation rules:

    1. If the two inputs have the same shape length and all dimension values are equal one by one (that is, the two inputs are fully elementwise consistent), both y1 and y2 are empty, indicating that no reduction is required.
    2. If the two inputs have different shape lengths, pad the shorter one with 1s on the left until its length is consistent with the longer one. After padding, the extra leading dimensions of the shorter one are regarded as dimensions with value 1 for that tensor and must be added to the corresponding reduction list.
    3. Except for use case 1, compare x1[i] with x2[i] dimension by dimension after alignment. If the value of either side is 1, the dimension is added to the reduction list corresponding to the side whose value is 1 (when x1[i]==1, index i is added to y1; when x2[i]==1, index i is added to y2).
  • Example:

    Example 1 (the two inputs are of equal length, and some dimensions are 1):
      The shape of tensor a is [2, 1, 4, 1, 6]
      The shape of tensor b is [2, 3, 1, 5, 1]
      x1_data: [2, 1, 4, 1, 6]   # x1_shape=[5]
      x2_data: [2, 3, 1, 5, 1]   # x2_shape=[5]
    
      Dimension-by-dimension comparison:
        dim0: x1=2, x2=2   → equal, no output
        dim1: x1=1, x2=3   → x1[i]==1, y1 collects index 1
        dim2: x1=4, x2=1   → x2[i]==1, y2 collects index 2
        dim3: x1=1, x2=5   → x1[i]==1, y1 collects index 3
        dim4: x1=6, x2=1   → x2[i]==1, y2 collects index 4
    
      y1_data: [1, 3]            # y1_shape=[2]
      y2_data: [2, 4]            # y2_shape=[2]
    
    Example 2 (input lengths differ, pad 1 on the left for alignment):
      The shape of original tensor a is [4, 1, 6]
      The shape of original tensor b is [2, 3, 1, 5, 1]
      x1_data: [4, 1, 6]         # x1_shape=[3], shorter
      x2_data: [2, 3, 1, 5, 1]   # x2_shape=[5], longer
    
      Alignment: left-pad x1 with 1s to length 5, obtaining [1, 1, 4, 1, 6]
            x1(after padding): [1, 1, 4, 1, 6]
            x2:         [2, 3, 1, 5, 1]
    
      Dimension-wise comparison (using the padded x1):
        dim0: x1=1(padded), x2=2 → x1[i]==1, y1 collects index 0
        dim1: x1=1(padded), x2=3 → x1[i]==1, y1 collects index 1
        dim2: x1=4,     x2=1 → x2[i]==1, y2 collects index 2
        dim3: x1=1,     x2=5 → x1[i]==1, y1 collects index 3
        dim4: x1=6,     x2=1 → x2[i]==1, y2 collects index 4
    
      y1_data: [0, 1, 3]         # y1_shape=[3]
      y2_data: [2, 4]            # y2_shape=[2]
    
    Example 3 (the two inputs are identical, no reduction required):
      The shape of the original tensor a is [2, 1, 4, 1, 6].
      The shape of the original tensor b is [2, 1, 4, 1, 6].
      x1_data: [2, 1, 4, 1, 6]   # x1_shape=[5]
      x2_data: [2, 1, 4, 1, 6]   # x2_shape=[5]
    
      The two inputs have the same length and the dimension values are equal one by one. This falls into use case 1, and no reduction is required.
    
      y1_data: []                # y1_shape=[0]
      y2_data: []                # y2_shape=[0]

Function Prototype

Each operator corresponds to a two-phase API. You must first call the "aclnnBroadcastGradientArgsGetWorkspaceSize" API to obtain the workspace size required for the computation and the executor that contains the operator computation process, and then call the "aclnnBroadcastGradientArgs" API to execute the computation.

aclnnStatus aclnnBroadcastGradientArgsGetWorkspaceSize(
  const aclTensor *x1,
  const aclTensor *x2,
  aclTensor       *y1,
  aclTensor       *y2,
  uint64_t        *workspaceSize,
  aclOpExecutor  **executor)
aclnnStatus aclnnBroadcastGradientArgs(
  void          *workspace,
  uint64_t       workspaceSize,
  aclOpExecutor *executor,
  aclrtStream    stream)

aclnnBroadcastGradientArgsGetWorkspaceSize

  • Parameters:

    Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor
    x1 Input Represents the shape of the original tensor a. Must be 1-dimensional.
    Data type must be consistent with x2.
    INT32, INT64 ND 1 √
    x2 Input Represents the shape of the original tensor b. Must be 1D.
    The data type must be consistent with x1.
    INT32, INT64 ND 1 √
    y1 Output Indicates the indices to be broadcast in the tensor shape of x1. The data type must be consistent with x1.
    The output size must be allocated based on max(x1_len, x2_len). The actual output may be less than this value. After execution completion, obtain the actual shape through aclGetViewShape.
    INT32, INT64 ND 1 ×
    y2 Output Represents the indices that need to be broadcast in the tensor shape of x2. The data type must be the same as that of x1.
    The output size must be allocated based on max(x1_len, x2_len). The actual output may be smaller than this value. After execution completion, obtain the actual shape by calling aclGetViewShape.
    INT32, INT64 ND 1
    workspaceSize Output Returns the workspace size to be requested on the Device side. - - - - -
    executor Output Returns the op executor, which contains the computation process 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:

    Error Code Error code description
    ACLNN_ERR_PARAM_NULLPTR 161001 Thrown when x1, x2, y1, or y2 is a null pointer.
    ACLNN_ERR_PARAM_INVALID 161002 The data type of x1 or x2 is not supported. Only INT32 and INT64 are supported.
    The data type of x1 is different from that of x2, or the data type of y1/y2 is different from that of x1/x2.
    The shape of x1, x2, y1, or y2 is not 1D.
    The capacity of y1 or y2 is smaller than max(x1 length, x2 length). Out-of-bounds writes by the kernel may occur.
    The current device is not Ascend 950PR&950DT products. The operator is not supported on this architecture.

aclnnBroadcastGradientArgs

  • Parameters:

    Parameter Input/Output Description
    workspace Input Workspace memory address allocated on the Device.
    workspaceSize Input Workspace size allocated on the Device, obtained by the first-phase API aclnnBroadcastGradientArgsGetWorkspaceSize.
    executor Input Op executor containing the operator computation flow.
    stream Input Stream for task execution.
  • Return value

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

Constraints

  • Deterministic computation:

    • aclnnBroadcastGradientArgs defaults to a deterministic implementation.
  • Only Ascend 950PR&950DT products are supported. Other architectures are not supported.

  • Inputs x1 and x2 must satisfy the broadcast rule: the corresponding dimensions must be equal, or at least one of them must be 1.

  • y1 and y2 are dynamic shape outputs. The output memory must be pre-allocated based on max(x1 length, x2 length). The number of actual output elements may be less than this value. After execution is complete, call aclGetViewShape to obtain the actual output shape.

  • Non-contiguous tensors are not supported for y1 and y2.

Example

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

#include <iostream>
#include <vector>
#include "acl/acl.h"
#include "aclnnop/aclnn_broadcast_gradient_args.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); aclFinalize(); return ret);
  ret = aclrtCreateStream(stream);
  CHECK_RET(ret == ACL_SUCCESS,
            LOG_PRINT("aclrtCreateStream failed. ERROR: %d\n", ret);
            aclrtResetDevice(deviceId); aclFinalize(); 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 tensors.
  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. For details, see the acl API documentation.
  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.
  //    x1 = {2, 1, 4, 1, 6}  (shape of the original tensor a)
  //    x2 = {2, 3, 1, 5, 1}  (shape of the original tensor b)
  //    The output is allocated with the maximum possible size, max(5, 5) = 5.
  std::vector<int32_t> x1HostData = {2, 1, 4, 1, 6};
  std::vector<int32_t> x2HostData = {2, 3, 1, 5, 1};
  std::vector<int64_t> y1Shape = {5};
  std::vector<int64_t> y2Shape = {5};
  void* x1DeviceAddr = nullptr;
  void* x2DeviceAddr = nullptr;
  void* y1DeviceAddr = nullptr;
  void* y2DeviceAddr = nullptr;
  aclTensor* x1 = nullptr;
  aclTensor* x2 = nullptr;
  aclTensor* y1 = nullptr;
  aclTensor* y2 = nullptr;
  std::vector<int32_t> y1HostData(5, 0);
  std::vector<int32_t> y2HostData(5, 0);
  ret = CreateAclTensor(x1HostData, {5}, &x1DeviceAddr, aclDataType::ACL_INT32, &x1);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  ret = CreateAclTensor(x2HostData, {5}, &x2DeviceAddr, aclDataType::ACL_INT32, &x2);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  ret = CreateAclTensor(y1HostData, y1Shape, &y1DeviceAddr, aclDataType::ACL_INT32, &y1);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  ret = CreateAclTensor(y2HostData, y2Shape, &y2DeviceAddr, aclDataType::ACL_INT32, &y2);
  CHECK_RET(ret == ACL_SUCCESS, return ret);

  // 3. Call the CANN operator library API.
  uint64_t workspaceSize = 0;
  aclOpExecutor* executor;
  // Call the first-phase API of aclnnBroadcastGradientArgs.
  ret = aclnnBroadcastGradientArgsGetWorkspaceSize(x1, x2, y1, y2, &workspaceSize, &executor);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnBroadcastGradientArgsGetWorkspaceSize 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 aclnnBroadcastGradientArgs.
  ret = aclnnBroadcastGradientArgs(workspaceAddr, workspaceSize, executor, stream);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnBroadcastGradientArgs failed. ERROR: %d\n", ret); return ret);

  // 4. (boilerplate) 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 actual output shape (a key step for dynamic shapes) and copy the result from the device side to the host side.
  int64_t* y1ViewDims = nullptr;
  uint64_t y1ViewDimsNum = 0;
  ret = aclGetViewShape(y1, &y1ViewDims, &y1ViewDimsNum);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclGetViewShape y1 failed. ERROR: %d\n", ret); return ret);
  int64_t y1Size = 1;
  for (uint64_t i = 0; i < y1ViewDimsNum; i++) {
    y1Size *= y1ViewDims[i];
  }
  if (y1Size > 0) {
    std::vector<int32_t> y1ResultData(y1Size, 0);
    ret = aclrtMemcpy(y1ResultData.data(), y1ResultData.size() * sizeof(int32_t), y1DeviceAddr,
                      y1Size * sizeof(int32_t), ACL_MEMCPY_DEVICE_TO_HOST);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("copy y1 result failed. ERROR: %d\n", ret); return ret);
    for (int64_t i = 0; i < y1Size; i++) {
      LOG_PRINT("y1[%ld] is: %d\n", i, y1ResultData[i]);
    }
  } else {
    LOG_PRINT("y1 is empty (no broadcast axis)\n");
  }
  delete[] y1ViewDims;

  int64_t* y2ViewDims = nullptr;
  uint64_t y2ViewDimsNum = 0;
  ret = aclGetViewShape(y2, &y2ViewDims, &y2ViewDimsNum);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclGetViewShape y2 failed. ERROR: %d\n", ret); return ret);
  int64_t y2Size = 1;
  for (uint64_t i = 0; i < y2ViewDimsNum; i++) {
    y2Size *= y2ViewDims[i];
  }
  if (y2Size > 0) {
    std::vector<int32_t> y2ResultData(y2Size, 0);
    ret = aclrtMemcpy(y2ResultData.data(), y2ResultData.size() * sizeof(int32_t), y2DeviceAddr,
                      y2Size * sizeof(int32_t), ACL_MEMCPY_DEVICE_TO_HOST);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("copy y2 result failed. ERROR: %d\n", ret); return ret);
    for (int64_t i = 0; i < y2Size; i++) {
      LOG_PRINT("y2[%ld] is: %d\n", i, y2ResultData[i]);
    }
  } else {
    LOG_PRINT("y2 is empty (no broadcast axis)\n");
  }
  delete[] y2ViewDims;

  // 6. Release the aclTensor.
  aclDestroyTensor(x1);
  aclDestroyTensor(x2);
  aclDestroyTensor(y1);
  aclDestroyTensor(y2);

  // 7. Release device resources.
  aclrtFree(x1DeviceAddr);
  aclrtFree(x2DeviceAddr);
  aclrtFree(y1DeviceAddr);
  aclrtFree(y2DeviceAddr);
  if (workspaceSize > 0) {
    aclrtFree(workspaceAddr);
  }
  aclrtDestroyStream(stream);
  aclrtResetDevice(deviceId);
  aclFinalize();
  return 0;
}