aclnnApplyFusedEmaAdam

📄 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: Implements the FusedEmaAdam fused optimizer function.

  • Formula:

    (correctionβ1,correctionβ2)={(1,1),biasCorrection=False(1−β1step,1−β2step),biasCorrection=True(correction_{\beta_1},correction_{\beta_2})=\begin{cases} (1,1),&biasCorrection=False\\ (1-\beta_1^{step},1-\beta_2^{step}),&biasCorrection=True \end{cases} grad={grad+weightDecay∗var,mode=0grad,mode=1grad=\begin{cases} grad+weightDecay*var,&mode=0\\ grad,&mode=1 \end{cases} mout=β1∗m+(1−β1)∗gradm_{out}=\beta_1*m+(1-\beta_1)*grad vout=β2∗v+(1−β2)∗grad2v_{out}=\beta_2*v+(1-\beta_2)*grad^2 mnext=mout/correctionβ1m_{next}=m_{out}/correction_{\beta_1} vnext=vout/correctionβ2v_{next}=v_{out}/correction_{\beta_2} denom=vnext+epsdenom=\sqrt{v_{next}}+eps update={mnext/denom,mode=0mnext/denom+weightDecay∗var,mode=1update=\begin{cases} m_{next}/denom,&mode=0\\ m_{next}/denom+weightDecay*var,&mode=1 \end{cases} varout=var−lr∗updatevar_{out}=var-lr*update sout=emaDecay∗s+(1−emaDecay)∗varouts_{out}=emaDecay*s+(1-emaDecay)*var_{out}

Function Prototype

Each operator is divided into a two-phase API. You must first call the "aclnnApplyFusedEmaAdamGetWorkspaceSize" API to obtain the input parameters and calculate the required workspace size and the executor that contains the operator computation process based on the computation flow, and then call the "aclnnApplyFusedEmaAdam" API to perform the computation.

aclnnStatus aclnnApplyFusedEmaAdamGetWorkspaceSize(
    const aclTensor *grad,
    aclTensor       *varRef,
    aclTensor       *mRef,
    aclTensor       *vRef,
    aclTensor       *sRef,
    const aclTensor *step,
    double           lr,
    double           emaDecay,
    double           beta1,
    double           beta2,
    double           eps,
    int64_t          mode,
    bool             biasCorrection,
    double           weightDecay,
    uint64_t        *workspaceSize,
    aclOpExecutor  **executor)
aclnnStatus aclnnApplyFusedEmaAdam(
    void          *workspace,
    uint64_t       workspaceSize,
    aclOpExecutor *executor,
    aclrtStream    stream)

aclnnApplyFusedEmaAdamGetWorkspaceSize

  • Parameters:

    Parameter Input/Output Description Instruction Data Type Data Format Shape Non-contiguous Tensor
    grad (aclTensor*) Input Gradient corresponding to the parameter to be updated, corresponding to grad in the formula. FLOAT16, BFLOAT16, FLOAT32 ND 1-8 √
    varRef (aclTensor*) Input/Output Parameter to be updated, corresponding to var in the formula. The shape must be consistent with the input grad. Consistent with grad. ND 1-8 √
    mRef (aclTensor*) Input/Output First-order momentum corresponding to the parameter to be updated, corresponding to m in the formula. The shape must be consistent with the input grad. Consistent with grad. ND 1-8 √
    vRef (aclTensor*) Input/Output Second-order momentum of the parameter to be updated, corresponding to v in the formula. The shape must be consistent with the input grad. Consistent with grad. ND 1-8 √
    sRef (aclTensor*) Input/Output EMA weight corresponding to the parameter to be updated, which corresponds to s in the corresponding formula. The shape must be consistent with the input grad. Consistent with grad. ND 1-8 √
    step (aclTensor*) Input Current update count of the optimizer, corresponding to step in the formula. The shape must be [1,]. INT64 ND 1 √
    lr (double) Input Learning rate, η in the formula. Recommended values: 1e-3, 1e-5, 1e-8. Range: 0 to 1. - DOUBLE - - -
    emaDecay (double) Input Decay rate of the exponential moving average (EMA), corresponding to emaDecay in the formula. - DOUBLE - - -
    beta1 (double) Input Coefficient for computing the first-order momentum, corresponding to the beta1 parameter in the formula. Recommended value: 0.9, range: 0 to 1. - DOUBLE - - -
    beta2 (double) Input Specifies the coefficient for computing the second-order momentum, corresponding to the beta2 parameter in the formula. The recommended value is 0.9, with a range of 0 to 1. - DOUBLE - - -
    eps (double) Input A term added to the denominator for numerical stability, corresponding to eps in the formula. - DOUBLE - - -
    mode (int64_t) Input Controls whether to apply L2 regularization or weight decay, corresponding to mode in the formula. 1 indicates adamw, and 0 indicates L2. - INT64 - - -
    biasCorrection (bool) Input Controls whether to perform bias correction, corresponding to biasCorrection in the corresponding formula. true indicates that correction is performed, and false indicates that no correction is performed. - BOOL - - -
    weightDecay (double) Input Weight decay, corresponding to weightDecay in the formula. - DOUBLE - - -
    workspaceSize (uint64_t*) Output Returns the workspace size to be allocated on the Device side. - - - - -
    executor (aclOpExecutor**) Output Returns the operator executor, which contains the operator computation flow. - - - - -
  • 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 or output tensor is a null pointer.
    ACLNN_ERR_PARAM_INVALID 161002 The data type or data format of the input or output is not within the supported range.

aclnnApplyFusedEmaAdam

  • Parameters:

    Parameter Input/Output Description
    workspace Input Memory address of the workspace applied for on the device side.
    workspaceSize Input Size of the workspace applied for on the device side, obtained through the first-phase API aclnnApplyFusedEmaAdamGetWorkspaceSize.
    executor Input Operator executor that contains the operator computation flow.
    stream Input Specifies the stream for executing the task.
  • Return value

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

Constraints

The data types and shapes of the input parameters grad, var, m, v, and s must be consistent.

  • Deterministic computation:

    • aclnnApplyFusedEmaAdam 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 "acl/acl.h"
#include "aclnnop/aclnn_apply_fused_ema_adam.h"
#include <iostream>
#include <vector>

#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;
}

void PrintOutResult(std::vector<int64_t> &shape, void **deviceAddr) {
  auto size = GetShapeSize(shape);
  std::vector<float> resultData(size, 0);
  auto ret = aclrtMemcpy(
      resultData.data(), resultData.size() * sizeof(resultData[0]), *deviceAddr,
      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 );
  for (int64_t i = 0; i < size; i++) {
    LOG_PRINT("mean result[%ld] is: %f\n", i, resultData[i]);
  }
}

int Init(int32_t deviceId, aclrtStream *stream) {
  // Boilerplate 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 apply for memory on the device side.
  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 side 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 the device/stream. Refer to the acl API manual.
  // Fill in the 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. You need to customize the construction based on the API.
  // input
  std::vector<float> gradHostData = {1, 2, 3, 4, 5, 6, 7, 8};
  std::vector<float> varHostData = {1, 2, 3, 4, 5, 6, 7, 8};
  std::vector<float> mHostData = {1, 2, 3, 4, 5, 6, 7, 8};
  std::vector<float> vHostData = {1, 2, 3, 4, 5, 6, 7, 8};
  std::vector<float> sHostData = {1, 2, 3, 4, 5, 6, 7, 8};
  std::vector<int64_t> stepHostData = {10};
  std::vector<int64_t> inputShape = {2, 2, 2};
  std::vector<int64_t> stepShape = {1,};
  void *gradDeviceAddr = nullptr;
  void *varDeviceAddr = nullptr;
  void *mDeviceAddr = nullptr;
  void *vDeviceAddr = nullptr;
  void *sDeviceAddr = nullptr;
  void *stepDeviceAddr = nullptr;
  aclTensor *grad = nullptr;
  aclTensor *var = nullptr;
  aclTensor *m = nullptr;
  aclTensor *v = nullptr;
  aclTensor *s = nullptr;
  aclTensor *step = nullptr;
  ret = CreateAclTensor(gradHostData, inputShape, &gradDeviceAddr, aclDataType::ACL_FLOAT, &grad);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  ret = CreateAclTensor(varHostData, inputShape, &varDeviceAddr, aclDataType::ACL_FLOAT, &var);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  ret = CreateAclTensor(mHostData, inputShape, &mDeviceAddr, aclDataType::ACL_FLOAT, &m);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  ret = CreateAclTensor(vHostData, inputShape, &vDeviceAddr, aclDataType::ACL_FLOAT, &v);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  ret = CreateAclTensor(sHostData, inputShape, &sDeviceAddr, aclDataType::ACL_FLOAT, &s);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  ret = CreateAclTensor(stepHostData, stepShape, &stepDeviceAddr, aclDataType::ACL_INT64, &step);
  CHECK_RET(ret == ACL_SUCCESS, return ret);

  // out, inplace
  std::vector<int64_t> outShape = {2, 2, 2};

  // attr
  float lr = 0.001f;
  float emaDecay = 0.5f;
  float beta1 = 0.9f;
  float beta2 = 0.999f;
  float eps = 1e-8f;
  int64_t mode = 1;
  bool bias = true;
  float weightDecay = 0.5f;

  uint64_t workspaceSize = 0;
  aclOpExecutor *executor;

  // 3. Call the CANN operator library API. Modify it to the specific API name.
  // Call the first-phase API of aclnnApplyFusedEmaAdam.
  ret = aclnnApplyFusedEmaAdamGetWorkspaceSize(grad, var, m, v, s, step, lr, emaDecay, beta1, beta2, eps,
                                               mode, bias, weightDecay, &workspaceSize, &executor);
  CHECK_RET(
      ret == ACL_SUCCESS,
      LOG_PRINT("aclnnApplyFusedEmaAdamGetWorkspaceSize 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 aclnnApplyFusedEmaAdam.
  ret = aclnnApplyFusedEmaAdam(workspaceAddr, workspaceSize, executor, stream);
  CHECK_RET(ret == ACL_SUCCESS,
            LOG_PRINT("aclnnApplyFusedEmaAdam failed. ERROR: %d\n", ret);
            return ret);

  // 4. (Boilerplate) Wait for the task execution to complete synchronously.
  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-side memory to the host side. Modify this based on the specific API definition.
  PrintOutResult(outShape, &varDeviceAddr);
  PrintOutResult(outShape, &mDeviceAddr);
  PrintOutResult(outShape, &vDeviceAddr);
  PrintOutResult(outShape, &sDeviceAddr);

  // 6. Release aclTensor and aclScalar. Modify this based on the specific API definition.
  aclDestroyTensor(grad);
  aclDestroyTensor(var);
  aclDestroyTensor(m);
  aclDestroyTensor(v);
  aclDestroyTensor(s);
  aclDestroyTensor(step);

  // 7. Release device resources.
  aclrtFree(gradDeviceAddr);
  aclrtFree(varDeviceAddr);
  aclrtFree(mDeviceAddr);
  aclrtFree(vDeviceAddr);
  aclrtFree(sDeviceAddr);
  aclrtFree(stepDeviceAddr);
  if (workspaceSize > 0) {
    aclrtFree(workspaceAddr);
  }
  aclrtDestroyStream(stream);
  aclrtResetDevice(deviceId);
  aclFinalize();

  return 0;
}