aclnnApplyAdamWV2
Applicable Products
| Product | Supported |
|---|---|
| √ | |
| √ | |
| √ | |
| × | |
| × | |
| × |
Function
Description: Implements the AdamW optimizer function.
Formula:
Function Prototype
Each operator is divided into a two-phase API. The "aclnnApplyAdamWV2GetWorkspaceSize" API must be called first to obtain the workspace size required for computation and the executor that encapsulates the operator computation flow. Then, the "aclnnApplyAdamWV2" API is called 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 The weight input to be computed, which is also the output, i.e., θ in the formula. - FLOAT16, BFLOAT16, FLOAT32 ND 1-8 √ mRef (aclTensor*) Input/Output The m parameter in the AdamW optimizer, i.e., m in the formula. - Same as the "varRef" parameter. ND Same as the "varRef" parameter. √ vRef (aclTensor*) Input/Output The v parameter in the AdamW optimizer, corresponding to v in the formula. It cannot be negative. - Same as the "varRef" parameter. ND Same as the "varRef" parameter. √ maxGradNormOptionalRef (aclTensor*) Input/Output Compares the input maxGradNormOptionalRef with the updated vRef, and outputs the maximum value to maxGradNormOptionalRef. This parameter is mandatory when the amsgrad parameter is true, and optional when the amsgrad parameter is false. Same as the "varRef" parameter. ND Same as the "varRef" parameter. √ grad (aclTensor*) Input Gradient data, corresponding to gt in the formula. - Same as the 'varRef' parameter. ND Same as the 'varRef' parameter. √ step (aclTensor*) Input Number of iterations, denoted as t in the formula. Must be greater than 0. The number of elements is 1. 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 Specifies whether to use the AMSGrad variant of the algorithm. - BOOL - - - maximize (bool) Input Whether to maximize the parameters. - BOOL - - - workspaceSize (uint64_t*) Output Returns the workspace size to be applied on the Device side. - - - - - executor (aclOpExecutor**) Output Returns the op executor, which includes 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 Value Error Code Description ACLNN_ERR_PARAM_NULLPTR 161001 When the passed varRef, mRef, vRef, maxGradNormOptionalRef, grad, or step is a null pointer. ACLNN_ERR_PARAM_INVALID 161002 The data types of varRef, mRef, vRef, maxGradNormOptionalRef, grad, and step are not within the supported range. The data formats of varRef, mRef, vRef, maxGradNormOptionalRef, grad, and step are not within the supported range. 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 Specifies the workspace memory address applied on the Device side. workspaceSize Input Specifies the workspace size applied on the Device side, which is obtained from the first-phase API aclnnApplyAdamWV2GetWorkspaceSize. executor Input Operator executor, which includes the operator computation flow. stream Input Specifies the stream for task execution. Return value
aclnnStatus: return code. For details, see aclnn Return Code.
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 provides example code for reference only. For details about compilation and running, 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: 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 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 a 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 device/stream. See the ACL API manual.
// Set deviceId based on the actual device.
int32_t deviceId = 0;
aclrtStream stream;
auto ret = Init(deviceId, &stream);
// Handle check based on actual requirements.
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("Init acl failed. ERROR: %d\n", ret); return ret);
// 2. Construct inputs and outputs. Customize the construction based on 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 m aclTensor.
ret = CreateAclTensor(mHostData, mShape, &mDeviceAddr, aclDataType::ACL_FLOAT, &m);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// Create v aclTensor.
ret = CreateAclTensor(vHostData, vShape, &vDeviceAddr, aclDataType::ACL_FLOAT, &v);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// Create grad aclTensor.
ret = CreateAclTensor(gradHostData, gradShape, &gradDeviceAddr, aclDataType::ACL_FLOAT, &grad);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// Create maxgrad aclTensor.
ret = CreateAclTensor(maxgradHostData, maxgradShape, &maxgradDeviceAddr, aclDataType::ACL_FLOAT, &maxgrad);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// Create 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. Replace with 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);
// 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 aclnnApplyAdamWV2.
ret = aclnnApplyAdamWV2(workspaceAddr, workspaceSize, executor, stream);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnApplyAdamWV2 failed. ERROR: %d\n", ret); return ret);
// 4. (Boilerplate) Synchronize and wait for 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 side memory to the host side. Modify based on the specific API definition.
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 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;
}