aclnnApplyAdamWV2

📄 View Source Code

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: Implements the AdamW optimizer function.

  • Formula:

    mt=β1mt−1+(1−β1)gtm_{t}=\beta_{1} m_{t-1}+\left(1-\beta_{1}\right) g_{t} \\ vt=β2vt−1+(1−β2)gt2v_{t}=\beta_{2} v_{t-1}+\left(1-\beta_{2}\right) g_{t}^{2} m^t=mt1−β1t\hat{m}_{t}=\frac{m_{t}}{1-\beta_{1}^{t}} \\ v^t=vt1−β2t\hat{v}_{t}=\frac{v_{t}}{1-\beta_{2}^{t}} \\ θt+1=θt−ηv^t+ϵm^t−η⋅λ⋅θt−1\theta_{t+1}=\theta_{t}-\frac{\eta}{\sqrt{\hat{v}_{t}}+\epsilon} \hat{m}_{t}-\eta \cdot \lambda \cdot \theta_{t-1}

Function Prototype

Each operator corresponds to a two-phase API. Call the "aclnnApplyAdamWV2GetWorkspaceSize" API to obtain the workspace size required for the computation and the executor that contains the operator computation process. Then call the "aclnnApplyAdamWV2" API to perform the computation.

aclnnStatus aclnnApplyAdamWV2GetWorkspaceSize(
    aclTensor       *varRef,
    aclTensor       *mRef,
    aclTensor       *vRef,
    aclTensor       *maxGradNormOptionalRef,
    const aclTensor *grad,
    const aclTensor *step,
    float            lr,
    float            beta1,
    float            beta2,
    float            weightDecay,
    float            eps,
    bool             amsgrad,
    bool             maximize,
    uint64_t        *workspaceSize,
    aclOpExecutor  **executor)
aclnnStatus aclnnApplyAdamWV2(
    void          *workspace,
    uint64_t       workspaceSize,
    aclOpExecutor *executor,
    aclrtStream    stream)

aclnnApplyAdamWV2GetWorkspaceSize

  • Parameters:

    Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor
    varRef (aclTensor*) Input/Output Weight to be computed, serving as both input and output, θ in the formula. - FLOAT16, BFLOAT16, FLOAT32 ND 1-8 √
    mRef (aclTensor*) Input/Output The m parameter in the AdamW optimizer, m in the formula. - Consistent with the "varRef" parameter. ND Consistent with the "varRef" parameter. √
    vRef (aclTensor*) Input/Output v parameter of the AdamW optimizer, corresponding to v in the formula. It cannot be negative. - Consistent with the "varRef" parameter. ND Consistent with the "varRef" parameter. √
    maxGradNormOptionalRef (aclTensor*) Input/Output The input maxGradNormOptionalRef is compared with the updated vRef, and the maximum value is output to maxGradNormOptionalRef. This parameter is mandatory when the amsgrad parameter is true, and optional when the amsgrad parameter is false. Consistent with the "varRef" parameter. ND Consistent with the "varRef" parameter. √
    grad (aclTensor*) Input Gradient data, gt in the formula. - Consistent with the "varRef" parameter. ND Consistent with the "varRef" parameter. √
    step (aclTensor*) Input Number of iterations, t in the formula, must be greater than 0. Contains 1 element. INT64, FLOAT32 ND - x
    lr (float) Input Learning rate, η in the formula. - FLOAT - - -
    beta1 (float) Input β1 parameter. - FLOAT - - -
    beta2 (float) Input β2 parameter. - FLOAT - - -
    weightDecay(float) Input Weight decay coefficient, λ in the formula. - FLOAT - - -
    eps(float) Input Prevents division by zero. - FLOAT - - -
    amsgrad (bool) Input Whether to use the AMSGrad variant of the algorithm. - BOOL - - -
    maximize (bool) Input Whether to maximize parameters. - BOOL - - -
    workspaceSize (uint64_t*) Output Returns the Device-allocated workspace size. - - - - -
    executor (aclOpExecutor**) Output Returns the op executor, which contains the operator computation flow. - - - - -
  • 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 When varRef, mRef, vRef, maxGradNormOptionalRef, grad, and step are null pointers.
    ACLNN_ERR_PARAM_INVALID 161002 When the data types of varRef, mRef, vRef, maxGradNormOptionalRef, grad, and step are not within the supported range.
    When the data formats of varRef, mRef, vRef, maxGradNormOptionalRef, grad, and step are not within the supported range.
    When the shapes of mRef, vRef, grad, and varRef are inconsistent.
    When amsgrad is true and the shapes of maxGradNormOptionalRef and varRef are inconsistent.
    When the shape size of step is not 1.

aclnnApplyAdamWV2

  • 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 aclnnApplyAdamWV2GetWorkspaceSize.
    executor Input Op executor that contains the operator computation flow.
    stream Input Stream that executes the task.
  • Return value

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

Constraints

  • The data types of the input tensors varRef, mRef, vRef, and grad must be consistent, and the supported data types are FLOAT16, BFLOAT16, and FLOAT32.
  • The shapes of the input tensors varRef, mRef, vRef, and grad must remain consistent.
  • Deterministic computation:
    • aclnnApplyAdamWV2 defaults to a deterministic implementation.

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_apply_adam_w_v2.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 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 request 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) Initialize the device/stream. For details, see the acl API manual.
  // Set 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 == ACL_SUCCESS, LOG_PRINT("Init acl failed. ERROR: %d\n", ret); return ret);

  // 2. Construct the inputs and outputs. Customize the construction according to the API.
  std::vector<int64_t> varShape = {2, 2};
  std::vector<int64_t> mShape = {2, 2};
  std::vector<int64_t> vShape = {2, 2};
  std::vector<int64_t> gradShape = {2, 2};
  std::vector<int64_t> maxgradShape = {2, 2};
  std::vector<int64_t> stepShape = {1};
  void* varDeviceAddr = nullptr;
  void* mDeviceAddr = nullptr;
  void* vDeviceAddr = nullptr;
  void* gradDeviceAddr = nullptr;
  void* maxgradDeviceAddr = nullptr;
  void* stepDeviceAddr = nullptr;
  aclTensor* var = nullptr;
  aclTensor* m = nullptr;
  aclTensor* v = nullptr;
  aclTensor* grad = nullptr;
  aclTensor* maxgrad = nullptr;
  aclTensor* step = nullptr;
  std::vector<float> varHostData = {0, 1, 2, 3};
  std::vector<float> mHostData = {0, 1, 2, 3};
  std::vector<float> vHostData = {0, 1, 2, 3};
  std::vector<float> gradHostData = {0, 1, 2, 3};
  std::vector<float> maxgradHostData = {0, 1, 2, 3};
  std::vector<float> stepHostData = {1};
  bool amsgrad = true;
  bool maximize = true;
  float lr = 1e-3;
  float beta1 = 0.9;
  float beta2 = 0.999;
  float weightDecay = 1e-2;
  float eps = 1e-8;
  // Create the var aclTensor.
  ret = CreateAclTensor(varHostData, varShape, &varDeviceAddr, aclDataType::ACL_FLOAT, &var);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  // Create the m aclTensor.
  ret = CreateAclTensor(mHostData, mShape, &mDeviceAddr, aclDataType::ACL_FLOAT, &m);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  // Create the v aclTensor.
  ret = CreateAclTensor(vHostData, vShape, &vDeviceAddr, aclDataType::ACL_FLOAT, &v);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  // Create the grad aclTensor.
  ret = CreateAclTensor(gradHostData, gradShape, &gradDeviceAddr, aclDataType::ACL_FLOAT, &grad);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  // Create the maxgrad aclTensor.
  ret = CreateAclTensor(maxgradHostData, maxgradShape, &maxgradDeviceAddr, aclDataType::ACL_FLOAT, &maxgrad);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  // Create the step aclTensor.
  ret = CreateAclTensor(stepHostData, stepShape, &stepDeviceAddr, aclDataType::ACL_FLOAT, &step);
  CHECK_RET(ret == ACL_SUCCESS, return ret);

  // 3. Call the CANN operator library API. Change it to the specific API name.
  uint64_t workspaceSize = 0;
  aclOpExecutor* executor;
  // Call the first-phase API of aclnnApplyAdamWV2.
  ret = aclnnApplyAdamWV2GetWorkspaceSize(var, m, v, maxgrad, grad, step, lr, beta1, beta2, weightDecay, eps, amsgrad, maximize, &workspaceSize, &executor);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnApplyAdamWV2GetWorkspaceSize 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 aclnnApplyAdamWV2.
  ret = aclnnApplyAdamWV2(workspaceAddr, workspaceSize, executor, stream);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnApplyAdamWV2 failed. ERROR: %d\n", ret); return ret);

  // 4. (boilerplate) Synchronously 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 output values and copy the result on device memory to the host side. Modify the code according to the API definition of the specific API.
  auto size = GetShapeSize(varShape);
  std::vector<float> resultData(size, 0);
  ret = aclrtMemcpy(resultData.data(), resultData.size() * sizeof(resultData[0]), varDeviceAddr,
                    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 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(var);
  aclDestroyTensor(m);
  aclDestroyTensor(v);
  aclDestroyTensor(grad);
  aclDestroyTensor(maxgrad);
  aclDestroyTensor(step);

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

  return 0;
}