aclnnApplyFusedEmaAdam
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 FusedEmaAdam fused optimizer function.
- Formula:
Function Prototype
Each operator uses a two-phase API. First, call the "aclnnApplyFusedEmaAdamGetWorkspaceSize" API to obtain the input parameters, calculate the required workspace size based on the computation process, and obtain the executor containing the computation process of the operator. 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 Dimension (shape) Non-contiguous Tensor grad(aclTensor*) Input Gradient of the parameters to be updated, corresponding to grad in the formula. FLOAT16, BFLOAT16, FLOAT32 ND 1-8 - varRef (aclTensor*) Input/Output Parameters to be updated, corresponding to var in the formula. Shape must remain consistent with the input grad. Remain consistent with grad. ND 1-8 - mRef (aclTensor*) Input/Output First moment of the parameters to be updated, corresponding to m in the formula. The shape must remain consistent with input grad. Remain consistent with grad. ND 1-8 - vRef (aclTensor*) Input/Output Second-order momentum of the parameters to be updated, corresponding to v in the corresponding formula. The shape must remain consistent with the input grad. Remain consistent with grad ND 1-8 - sRef (aclTensor*) Input/Output EMA weight corresponding to the parameters to be updated, which is s in the formula. The shape must remain consistent with the input grad. Consistent with grad ND 1-8 - step (aclTensor*) Input Current number of optimizer updates, corresponding to step in the formula. Shape requirement: [1,]. INT64 ND 1 - lr (double) Input Learning rate, η in the formula. Recommended values: 1e-3, 1e-5, 1e-8. Range: 0-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 moment. Corresponds to the beta1 parameter in the formula. Recommended value: 0.9. Range: 0-1. - DOUBLE - - - beta2 (double) Input Coefficient for calculating the second-order momentum, corresponding to the beta2 parameter in the formula. The recommended value is 0.9, and the value range is 0-1. - DOUBLE - - - eps (double) Input A term added to the denominator for numerical stability, which is eps in the corresponding formula. - DOUBLE - - - mode (int64_t) Input Controls whether to apply L2 regularization or weight decay, which is mode in the corresponding 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. - - - - - executor (aclOpExecutor**) Output Returns the op executor, which contains the operator computation process. - - - - - Return value
aclnnStatus: return status code. For details, see aclnn Error 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 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 Address of the workspace memory allocated on the Device. workspaceSize Input Size of the workspace memory allocated on the Device, obtained by the first-phase API aclnnApplyFusedEmaAdamGetWorkspaceSize. executor Input Op executor, containing the computation flow of the operator. stream Input Stream for task execution. Return value
aclnnStatus: return status code. For details, see aclnn Error Codes.
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 sample code is for reference only. For details, 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, 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 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 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.
// Set deviceId to the 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 as required by 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. Replace it with the actual 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);
// 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 aclnnApplyFusedEmaAdam.
ret = aclnnApplyFusedEmaAdam(workspaceAddr, workspaceSize, executor, stream);
CHECK_RET(ret == ACL_SUCCESS,
LOG_PRINT("aclnnApplyFusedEmaAdam 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 value of the output and copy the result from the device memory to the host memory. Modify the code based on the specific API definition.
PrintOutResult(outShape, &varDeviceAddr);
PrintOutResult(outShape, &mDeviceAddr);
PrintOutResult(outShape, &vDeviceAddr);
PrintOutResult(outShape, &sDeviceAddr);
// 6. Release the aclTensor and aclScalar. Modify the code based on the specific API definition.
aclDestroyTensor(grad);
aclDestroyTensor(var);
aclDestroyTensor(m);
aclDestroyTensor(v);
aclDestroyTensor(s);
aclDestroyTensor(step);
// 7. Release the 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;
}