aclnnEmbeddingDenseBackward

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

Function

Implements the backward computation of aclnnEmbedding. Accumulates the rows of grad that correspond to the same index in indices into out.

Function Prototype

Each operator uses a two-phase API. You must first call the "aclnnEmbeddingDenseBackwardGetWorkspaceSize" API to obtain the workspace size required for the computation and the executor that contains the operator computation process, and then call the "aclnnEmbeddingDenseBackward" API to perform the computation.

aclnnStatus aclnnEmbeddingDenseBackwardGetWorkspaceSize(
 const aclTensor *grad,
 const aclTensor *indices,
 uint64_t         numWeights,
 uint64_t         paddingIdx,
 bool             scaleGradByFreq,
 const aclTensor *out,
 uint64_t        *workspaceSize,
 aclOpExecutor  **executor)
aclnnStatus aclnnEmbeddingDenseBackward(
 void             *workspace,
 uint64_t          workspaceSize,
 aclOpExecutor    *executor,
 const aclrtStream stream)

aclnnEmbeddingDenseBackwardGetWorkspaceSize

  • Parameters

    Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor
    grad Input Original gradient of the data. - BFLOAT16, FLOAT16, FLOAT ND 2-8 √
    indices Input Index values corresponding to the grad input. Negative indices are not supported. The value range is [0,numWeights-1]. FLOAT, FLOAT16, DOUBLE, INT32, INT64, INT16, INT8, UINT8, BOOL ND 1-8 √
    numWeights Input Size of the first axis of the output tensor. - - - - -
    paddingIdx Input Fills the paddingIdx-th row of the output tensor with 0. If paddingIdx is negative, no processing is performed. - - - -
    scaleGradByFreq Input Specifies whether to scale gradients by word frequency. If true, the result is scaled by word frequency. If false, no scaling is performed. - - - -
    out Output Output of the gradient summation result. - Same type as grad ND 2
    The first dimension is numWeights, and the last dimension is the same as that of grad.
    -
    workspaceSize Output Returns the size of the workspace to be allocated on the Device. - - - - -
    executor Output Returns the op executor, which contains the operator computation flow. - - - - -
    • Atlas training products: The BFLOAT16 data type is not supported.
  • 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 grad, indices, and out are null pointers.
    ACLNN_ERR_PARAM_INVALID 161002 The data types and data formats of grad, indices, and out are not within the supported range.
    The dimensions of grad and indices exceed 8.
    The shapes of grad and indices do not meet the constraints.
    The shape of out does not match the deduction result.

aclnnEmbeddingDenseBackward

  • Parameters

    Parameter Input/Output Description
    workspace Input Workspace memory address requested on the Device.
    workspaceSize Input Workspace size requested on the Device, obtained by the first-phase API aclnnEmbeddingDenseBackwardGetWorkspaceSize.
    executor Input Op executor, containing the operator computation flow.
    stream Input Specifies the stream for executing the task.
  • Return Value

    aclnnStatus: return value, which is a status code. For details, see aclnn Return Codes.

Constraints

  • Deterministic computation:
    • aclnnEmbeddingDenseBackward defaults to a non-deterministic implementation. Deterministic computation can be enabled via aclrtCtxSetSysParamOpt.
  • Atlas training products:
    • For scenarios where scale is true, if the last dimension of grad is embeddingDim and its size exceeds the specified range, an error is reported. The valid range is as follows:
      • When indices is int32, the following must be satisfied:
      embeddingDim<180192−countsSize∗436embeddingDim < \frac{180192 - countsSize * 4}{36}
      • When indices is int64, the following must be satisfied:
      embeddingDim<180192−countsSize∗820embeddingDim < \frac{180192 - countsSize * 8}{20}
      • The formula for countsSize is as follows, where coreNum represents the number of AI processor cores:
      countsSize=numWeights/coreNum+numWeights%coreNumcountsSize = numWeights / coreNum + numWeights \% coreNum
  • Atlas A2 products and Atlas A3 products:
    • When the parameter shape exceeds the following limits, the output cannot guarantee high precision. If deterministic computation is enabled, high performance also cannot be guaranteed.
      • After grad is coalesced into a two-dimensional shape, the first dimension exceeds INT32_MAX (2147483647).
      • numWeights exceeds INT32_MAX (2147483647).
    • When the dimension of indices after concatenation exceeds INT32_INF (2139095040), high performance cannot be guaranteed.

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

int Init(int32_t deviceId, aclrtStream* stream) {
  // Boilerplate code 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 allocate device 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 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);

  // Compute 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 aclCreateTensor 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 manual.
  // Fill in deviceId based on your 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.
  uint64_t numWeights = 4;
  uint64_t paddingIdx = 0;
  bool scaleGradByFreq = false;
  std::vector<int64_t> gradOutputShape = {2, 3};
  std::vector<int64_t> indicesShape = {2};
  std::vector<int64_t> outShape = {4, 3};
  void* gradOutputDeviceAddr = nullptr;
  void* indicesDeviceAddr = nullptr;
  void* outDeviceAddr = nullptr;
  aclTensor* gradOutput = nullptr;
  aclTensor* indices = nullptr;
  aclTensor* out = nullptr;

  std::vector<float> gradOutputHostData = {1, 2, 3, 4, 5, 6};
  std::vector<int64_t> indicesHostData = {1, 2};
  std::vector<float> outHostData = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};

  // Create the gradOutput aclTensor.
  ret = CreateAclTensor(gradOutputHostData, gradOutputShape, &gradOutputDeviceAddr, aclDataType::ACL_FLOAT, &gradOutput);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  // Create the indices aclTensor.
  ret = CreateAclTensor(indicesHostData, indicesShape, &indicesDeviceAddr, aclDataType::ACL_INT64, &indices);
  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);

  // 3. Call the CANN operator library API. Change the name to the specific API name.
  uint64_t workspaceSize = 0;
  aclOpExecutor* executor;
  // Call the first-phase API of aclnnEmbeddingDenseBackward.
  ret = aclnnEmbeddingDenseBackwardGetWorkspaceSize(gradOutput, indices, numWeights, paddingIdx, scaleGradByFreq, out,
                                                    &workspaceSize, &executor);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnEmbeddingDenseBackwardGetWorkspaceSize 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 aclnnEmbeddingDenseBackward.
  ret = aclnnEmbeddingDenseBackward(workspaceAddr, workspaceSize, executor, stream);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnEmbeddingDenseBackward failed. ERROR: %d\n", ret); return ret);

  // 4. (Boilerplate) Wait synchronously for the task 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 device memory to host. Modify the code according to 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(resultData[0]), ACL_MEMCPY_DEVICE_TO_HOST);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("copy resultData from device to host failed. ERROR: %d\n", ret);
            return ret);
  for (int64_t i = 0; i < size; i++) {
    LOG_PRINT("resultData[%ld] is: %f\n", i, resultData[i]);
  }

  // 6. Release the aclTensor. Modify the code according to the specific API definition.
  aclDestroyTensor(gradOutput);
  aclDestroyTensor(indices);
  aclDestroyTensor(out);

  // 7. Release device resources. Modify the code according to the specific API definition.
  aclrtFree(gradOutputDeviceAddr);
  aclrtFree(indicesDeviceAddr);
  aclrtFree(outDeviceAddr);
  if (workspaceSize > 0) {
    aclrtFree(workspaceAddr);
  }
  aclrtDestroyStream(stream);
  aclrtResetDevice(deviceId);
  aclFinalize();
  return 0;
}