aclnnFusedAdam
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: Implements the Adam optimizer function. Supports multiple parameter lists (TensorList) to complete the Adam optimizer function in a single call.
Formula:
Function Prototype
Each operator uses a two-phase API. You must first call the "aclnnFusedAdamGetWorkspaceSize" API to obtain the workspace size required for computation and the executor that contains the operator computation process, and then call the "aclnnFusedAdam" API to perform the computation.
aclnnStatus aclnnFusedAdamGetWorkspaceSize(
const aclTensorList* paramsRef,
const aclTensorList* gradsRef,
const aclTensorList* expAvgsRef,
const aclTensorList* expAvgSqsRef,
const aclTensorList* maxExpAvgSqsRef,
const aclTensorList* stateSteps,
const aclTensor* gradScaleOptional,
const aclTensor* foundInfOptional,
double lr,
double beta1,
double beta2,
double weightDecay,
double eps,
bool amsgrad,
bool maximize,
uint64_t* workspaceSize,
aclOpExecutor** executor)aclnnStatus aclnnFusedAdam(
void* workspace,
uint64_t workspaceSize,
aclOpExecutor* executor,
aclrtStream stream)aclnnFusedAdamGetWorkspaceSize
Parameters:
Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor paramsRef (aclTensorList*) Input/Output - Does not support empty tensors.
- Weight list to be computed, θ in the formula.
- FLOAT16, BFLOAT16, FLOAT32 ND 1-8 √ gradsRef (aclTensorList*) Input/Output - Does not support empty tensors.
- Gradient data list, gt in the formula. Gradients are updated only when the gradScale input is not empty.
- FLOAT16, BFLOAT16, FLOAT32 ND 1-8 √ expAvgsRef (aclTensorList*) Input/Output - Does not support empty tensor.
- First moment list, m in the formula.
- FLOAT16, BFLOAT16, FLOAT32 ND 1-8 √ expAvgSqsRef (aclTensorList*) Input/Output - Does not support empty tensors.
- List of second moments, corresponding to v in the formula. The value cannot be negative.
- FLOAT16, BFLOAT16, FLOAT32 ND 1-8 √ maxExpAvgSqsRef (aclTensorList*) Input/Output - Does not support empty tensors.
- Stores the maximum second moment list. Compares it with the updated expAvgSqsRef and outputs the maximum value.
This parameter is required when amsgrad is true, and optional when amsgrad is false. FLOAT16, BFLOAT16, FLOAT32 ND 1-8 √ stateSteps (aclTensorList*) Input - Does not support empty tensors.
- List of iteration counts, that is, t in the formula. The value must be greater than 0.
- INT64, FLOAT32 ND - x gradScaleOptional (aclTensor*) Input Optional input, gradient scaling factor s. When gradScaleOptional is not empty, gradients are updated and output accordingly (overwriting the original gradients). FLOAT ND - x foundInfOptional (aclTensor*) Input Optional input indicating whether Inf/NaN occurs. When foundInfOptional is not empty and its value is 1, updating stops. FLOAT ND - x lr (double) Input Learning rate, η in the formula. - DOUBLE - - - beta1 (double) Input β1 parameter. - DOUBLE - - - beta2 (double) Input β2 parameter. - DOUBLE - - - weightDecay (double) Input Weight decay coefficient, λ in the formula. - DOUBLE - - - eps (double) Input Prevents division by zero. - DOUBLE - - - amsgrad (bool) Input Variable indicating whether to enable the AMSGrad update logic. See Function BOOL - - - maximize (bool) Input Whether to maximize the parameters. See Function BOOL - - - workspaceSize (uint64_t*) Output Returns the workspace size that needs to be applied by the Device side. - - - - - 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 The input paramsRef, gradsRef, expAvgsRef, expAvgSqsRef, or stateSteps is a null pointer. ACLNN_ERR_PARAM_INVALID 161002 The data types of paramsRef, gradsRef, expAvgsRef, expAvgSqsRef, or maxExpAvgSqsRef are not within the supported range. The data formats of paramsRef, gradsRef, expAvgsRef, expAvgSqsRef, or maxExpAvgSqsRef are not within the supported range. The shapes of gradsRef, expAvgsRef, expAvgSqsRef, and paramsRef are inconsistent. The number of tensors in stateSteps is inconsistent with that of paramsRef.
aclnnFusedAdam
Parameters:
Parameter Input/Output Description workspace Input Pointer to the workspace memory applied by the Device side. workspaceSize Input Size of the workspace applied by the Device side, obtained by calling the first-phase API aclnnFusedAdamGetWorkspaceSize. executor Input Op executor that contains the operator computation flow. stream Input Specifies the stream for executing the task. Return value
aclnnStatus: return status code. For details, see aclnn Return Codes.
Constraints
Each tensor in the input tensorLists paramsRef, gradsRef, expAvgsRef, and expAvgSqsRef must not be empty. The data types must be consistent, and only FLOAT16, BFLOAT16, and FLOAT32 are supported.
In the input tensorLists paramsRef, gradsRef, expAvgsRef, and expAvgSqsRef, the number of tensors must be consistent, and the tensors at the same index must have consistent shapes.
stateSteps is of the tensorList type and supports INT64 and FLOAT32. The number of tensors in it must be consistent with that of paramsRef, gradsRef, expAvgsRef, expAvgSqsRef, and maxExpAvgSqsRef. Each tensor contains at least one element. If the number of elements is greater than 1, the value of the 0th element is used as the value of stateSteps.
When amsgrad is false, maxExpAvgSqsRef can be empty; when amsgrad is true, maxExpAvgSqsRef is required, and the number of tensors, and the shape and dtype of each tensor, must be consistent with paramsRef, gradsRef, expAvgsRef, and expAvgSqsRef.
Deterministic computation:
- aclnnFusedAdam 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 "acl/acl.h"
#include "aclnnop/aclnn_fused_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("result[%ld] is: %f\n", i, resultData[i]);
}
}
int Init(int32_t deviceId, aclrtStream* stream)
{
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);
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);
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);
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];
}
*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 device/stream, see the acl API manual
// Fill in the deviceId based on your 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 input and output. Customize the construction based on the API.
std::vector<float> paramsRefHostData1 = {1, 2, 3, 4, 5, 6, 7, 8};
std::vector<float> gradsHostData1 = {0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8};
std::vector<float> expavgsHostData1 = {0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8};
std::vector<float> expavgsqsHostData1 = {0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8};
std::vector<float> maxexpavgsqsHostData1 = {1, 2, 3, 4, 5, 6, 7, 8};
std::vector<float> stepsHostData1 = {3};
std::vector<float> paramsRefHostData2 = {9, 10, 11, 12};
std::vector<float> gradsHostData2 = {0.9, 1.0, 1.1, 1.2};
std::vector<float> expavgsHostData2 = {-1, -2, -3, -4};
std::vector<float> expavgsqsHostData2 = {1, 2, 3, 4};
std::vector<float> maxexpavgsqsHostData2 = {-1, -1, -1, -1};
std::vector<float> stepsHostData2 = {4};
std::vector<float> gradScaleOptionalHostData = {2};
std::vector<int64_t> inputShape1 = {2, 2, 2};
std::vector<int64_t> inputShape2 = {2, 2};
std::vector<int64_t> scalarShape = {1};
void* paramsRef1DeviceAddr = nullptr;
void* grads1DeviceAddr = nullptr;
void* expavgs1DeviceAddr = nullptr;
void* expavgsqs1DeviceAddr = nullptr;
void* maxexpavgsqs1DeviceAddr = nullptr;
void* steps1DeviceAddr = nullptr;
void* paramsRef2DeviceAddr = nullptr;
void* grads2DeviceAddr = nullptr;
void* expavgs2DeviceAddr = nullptr;
void* expavgsqs2DeviceAddr = nullptr;
void* maxexpavgsqs2DeviceAddr = nullptr;
void* steps2DeviceAddr = nullptr;
void* gradScaleOptionalDeviceAddr = nullptr;
aclTensor* paramsRef1 = nullptr;
aclTensor* grads1 = nullptr;
aclTensor* expavgs1 = nullptr;
aclTensor* expavgsqs1 = nullptr;
aclTensor* maxexpavgsqs1 = nullptr;
aclTensor* steps1 = nullptr;
aclTensor* paramsRef2 = nullptr;
aclTensor* grads2 = nullptr;
aclTensor* expavgs2 = nullptr;
aclTensor* expavgsqs2 = nullptr;
aclTensor* maxexpavgsqs2 = nullptr;
aclTensor* steps2 = nullptr;
aclTensor* gradScaleOptional = nullptr;
aclTensor* foundInfOptional = nullptr;
ret = CreateAclTensor(paramsRefHostData1, inputShape1, ¶msRef1DeviceAddr, aclDataType::ACL_FLOAT, ¶msRef1);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(gradsHostData1, inputShape1, &grads1DeviceAddr, aclDataType::ACL_FLOAT, &grads1);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(expavgsHostData1, inputShape1, &expavgs1DeviceAddr, aclDataType::ACL_FLOAT, &expavgs1);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(expavgsqsHostData1, inputShape1, &expavgsqs1DeviceAddr, aclDataType::ACL_FLOAT, &expavgsqs1);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(maxexpavgsqsHostData1, inputShape1, &maxexpavgsqs1DeviceAddr, aclDataType::ACL_FLOAT,
&maxexpavgsqs1);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(stepsHostData1, inputShape1, &steps1DeviceAddr, aclDataType::ACL_FLOAT, &steps1);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(paramsRefHostData2, inputShape2, ¶msRef2DeviceAddr, aclDataType::ACL_FLOAT, ¶msRef2);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(gradsHostData2, inputShape2, &grads2DeviceAddr, aclDataType::ACL_FLOAT, &grads2);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(expavgsHostData2, inputShape2, &expavgs2DeviceAddr, aclDataType::ACL_FLOAT, &expavgs2);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(expavgsqsHostData2, inputShape2, &expavgsqs2DeviceAddr, aclDataType::ACL_FLOAT, &expavgsqs2);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(maxexpavgsqsHostData2, inputShape2, &maxexpavgsqs2DeviceAddr, aclDataType::ACL_FLOAT,
&maxexpavgsqs2);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(stepsHostData2, inputShape2, &steps2DeviceAddr, aclDataType::ACL_FLOAT, &steps2);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(gradScaleOptionalHostData, scalarShape, &gradScaleOptionalDeviceAddr, aclDataType::ACL_FLOAT,
&gradScaleOptional);
CHECK_RET(ret == ACL_SUCCESS, return ret);
std::vector<aclTensor*> paramsRefListData = {paramsRef1, paramsRef2};
std::vector<aclTensor*> gradsListData = {grads1, grads2};
std::vector<aclTensor*> expavgsListData = {expavgs1, expavgs2};
std::vector<aclTensor*> expavgsqsListData = {expavgsqs1, expavgsqs2};
std::vector<aclTensor*> maxexpavgsqsData = {maxexpavgsqs1, maxexpavgsqs2};
std::vector<aclTensor*> stepsListData = {steps1, steps2};
aclTensorList* paramsRefList = aclCreateTensorList(paramsRefListData.data(), paramsRefListData.size());
aclTensorList* gradsList = aclCreateTensorList(gradsListData.data(), gradsListData.size());
aclTensorList* expavgsList = aclCreateTensorList(expavgsListData.data(), expavgsListData.size());
aclTensorList* expavgsqsList = aclCreateTensorList(expavgsqsListData.data(), expavgsqsListData.size());
aclTensorList* maxexpavgsqsList = aclCreateTensorList(maxexpavgsqsData.data(), maxexpavgsqsData.size());
aclTensorList* stepsList = aclCreateTensorList(stepsListData.data(), stepsListData.size());
double lr = 0.001f;
double beta1 = 0.9f;
double beta2 = 0.999f;
double weightDecay = 0.0f;
double eps = 1e-8;
bool amsgrad = true;
bool maximize = false;
// 3. Call the API.
uint64_t workspaceSize = 0;
aclOpExecutor* executor;
// Call the first-phase API aclnnFusedAdamGetWorkspaceSize.
ret = aclnnFusedAdamGetWorkspaceSize(paramsRefList, gradsList, expavgsList, expavgsqsList, maxexpavgsqsList,
stepsList, gradScaleOptional, foundInfOptional, lr, beta1, beta2, weightDecay,
eps, amsgrad, maximize, &workspaceSize, &executor);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnFusedAdamGetWorkspaceSize 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 aclnnXxx.
ret = aclnnFusedAdam(workspaceAddr, workspaceSize, executor, stream);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnFusedAdam 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 from the device memory to the host memory.
LOG_PRINT("====== Tensor 1-1 paramsRef1 results ======\n");
PrintOutResult(inputShape1, ¶msRef1DeviceAddr);
LOG_PRINT("====== Tensor 1-2 grads1 results ======\n");
PrintOutResult(inputShape1, &grads1DeviceAddr);
LOG_PRINT("====== Tensor 1-3 expavgs1 results ======\n");
PrintOutResult(inputShape1, &expavgs1DeviceAddr);
LOG_PRINT("====== Tensor 1-4 expavgsqs1 results ======\n");
PrintOutResult(inputShape1, &expavgsqs1DeviceAddr);
LOG_PRINT("====== Tensor 1-5 maxexpavgsqs1 results ======\n");
PrintOutResult(inputShape1, &maxexpavgsqs1DeviceAddr);
LOG_PRINT("====== Tensor 2-1 paramsRef results ======\n");
PrintOutResult(inputShape2, ¶msRef2DeviceAddr);
LOG_PRINT("====== Tensor 2-2 grads2 results ======\n");
PrintOutResult(inputShape2, &grads2DeviceAddr);
LOG_PRINT("====== Tensor 2-3 expavgs2 results ======\n");
PrintOutResult(inputShape2, &expavgs2DeviceAddr);
LOG_PRINT("====== Tensor 2-4 expavgsqs2 results ======\n");
PrintOutResult(inputShape2, &expavgsqs2DeviceAddr);
LOG_PRINT("====== Tensor 2-5 maxexpavgsqs2 results ======\n");
PrintOutResult(inputShape2, &maxexpavgsqs2DeviceAddr);
// 6. Release the aclTensor.
aclDestroyTensorList(paramsRefList);
aclDestroyTensorList(gradsList);
aclDestroyTensorList(expavgsList);
aclDestroyTensorList(expavgsqsList);
aclDestroyTensorList(maxexpavgsqsList);
aclDestroyTensorList(stepsList);
aclDestroyTensor(gradScaleOptional);
aclDestroyTensor(foundInfOptional);
// 7. Release device resources.
aclrtFree(paramsRef1DeviceAddr);
aclrtFree(grads1DeviceAddr);
aclrtFree(expavgs1DeviceAddr);
aclrtFree(expavgsqs1DeviceAddr);
aclrtFree(maxexpavgsqs1DeviceAddr);
aclrtFree(steps1DeviceAddr);
aclrtFree(paramsRef2DeviceAddr);
aclrtFree(grads2DeviceAddr);
aclrtFree(expavgs2DeviceAddr);
aclrtFree(expavgsqs2DeviceAddr);
aclrtFree(maxexpavgsqs2DeviceAddr);
aclrtFree(steps2DeviceAddr);
aclrtFree(gradScaleOptionalDeviceAddr);
if (workspaceSize > 0) {
aclrtFree(workspaceAddr);
}
ret = aclrtDestroyStream(stream);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("destroy stream failed. ERROR: %d\n", ret); return ret);
ret = aclrtResetDevice(deviceId);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("reset device failed. ERROR: %d\n", ret); return ret);
ret = aclFinalize();
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("finalize acl failed. ERROR: %d\n", ret); return ret);
return 0;
}