{
"cells": [
{
"cell_type": "markdown",
"id": "2f8ac037",
"metadata": {},
"source": [
"The following additional libraries are needed to run this\n",
"notebook. Note that running on Colab is experimental, please report a Github\n",
"issue if you have any problem."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "7ddef951",
"metadata": {},
"outputs": [],
"source": [
"!pip install d2l==0.17.6\n"
]
},
{
"cell_type": "markdown",
"id": "b63cc858",
"metadata": {
"origin_pos": 0
},
"source": [
"# Adam\n",
":label:`sec_adam`\n",
"\n",
"In the discussions leading up to this section we encountered a number of techniques for efficient optimization. Let us recap them in detail here:\n",
"\n",
"* We saw that :numref:`sec_sgd` is more effective than Gradient Descent when solving optimization problems, e.g., due to its inherent resilience to redundant data. \n",
"* We saw that :numref:`sec_minibatch_sgd` affords significant additional efficiency arising from vectorization, using larger sets of observations in one minibatch. This is the key to efficient multi-machine, multi-GPU and overall parallel processing. \n",
"* :numref:`sec_momentum` added a mechanism for aggregating a history of past gradients to accelerate convergence.\n",
"* :numref:`sec_adagrad` used per-coordinate scaling to allow for a computationally efficient preconditioner. \n",
"* :numref:`sec_rmsprop` decoupled per-coordinate scaling from a learning rate adjustment. \n",
"\n",
"Adam :cite:`Kingma.Ba.2014` combines all these techniques into one efficient learning algorithm. As expected, this is an algorithm that has become rather popular as one of the more robust and effective optimization algorithms to use in deep learning. It is not without issues, though. In particular, :cite:`Reddi.Kale.Kumar.2019` show that there are situations where Adam can diverge due to poor variance control. In a follow-up work :cite:`Zaheer.Reddi.Sachan.ea.2018` proposed a hotfix to Adam, called Yogi which addresses these issues. More on this later. For now let us review the Adam algorithm. \n",
"\n",
"## The Algorithm\n",
"\n",
"One of the key components of Adam is that it uses exponential weighted moving averages (also known as leaky averaging) to obtain an estimate of both the momentum and also the second moment of the gradient. That is, it uses the state variables\n",
"\n",
"$$\\begin{aligned}\n",
" \\mathbf{v}_t & \\leftarrow \\beta_1 \\mathbf{v}_{t-1} + (1 - \\beta_1) \\mathbf{g}_t, \\\\\n",
" \\mathbf{s}_t & \\leftarrow \\beta_2 \\mathbf{s}_{t-1} + (1 - \\beta_2) \\mathbf{g}_t^2.\n",
"\\end{aligned}$$\n",
"\n",
"Here $\\beta_1$ and $\\beta_2$ are nonnegative weighting parameters. Common choices for them are $\\beta_1 = 0.9$ and $\\beta_2 = 0.999$. That is, the variance estimate moves *much more slowly* than the momentum term. Note that if we initialize $\\mathbf{v}_0 = \\mathbf{s}_0 = 0$ we have a significant amount of bias initially towards smaller values. This can be addressed by using the fact that $\\sum_{i=0}^t \\beta^i = \\frac{1 - \\beta^t}{1 - \\beta}$ to re-normalize terms. Correspondingly the normalized state variables are given by \n",
"\n",
"$$\\hat{\\mathbf{v}}_t = \\frac{\\mathbf{v}_t}{1 - \\beta_1^t} \\text{ and } \\hat{\\mathbf{s}}_t = \\frac{\\mathbf{s}_t}{1 - \\beta_2^t}.$$\n",
"\n",
"Armed with the proper estimates we can now write out the update equations. First, we rescale the gradient in a manner very much akin to that of RMSProp to obtain\n",
"\n",
"$$\\mathbf{g}_t' = \\frac{\\eta \\hat{\\mathbf{v}}_t}{\\sqrt{\\hat{\\mathbf{s}}_t} + \\epsilon}.$$\n",
"\n",
"Unlike RMSProp our update uses the momentum $\\hat{\\mathbf{v}}_t$ rather than the gradient itself. Moreover, there is a slight cosmetic difference as the rescaling happens using $\\frac{1}{\\sqrt{\\hat{\\mathbf{s}}_t} + \\epsilon}$ instead of $\\frac{1}{\\sqrt{\\hat{\\mathbf{s}}_t + \\epsilon}}$. The former works arguably slightly better in practice, hence the deviation from RMSProp. Typically we pick $\\epsilon = 10^{-6}$ for a good trade-off between numerical stability and fidelity. \n",
"\n",
"Now we have all the pieces in place to compute updates. This is slightly anticlimactic and we have a simple update of the form\n",
"\n",
"$$\\mathbf{x}_t \\leftarrow \\mathbf{x}_{t-1} - \\mathbf{g}_t'.$$\n",
"\n",
"Reviewing the design of Adam its inspiration is clear. Momentum and scale are clearly visible in the state variables. Their rather peculiar definition forces us to debias terms (this could be fixed by a slightly different initialization and update condition). Second, the combination of both terms is pretty straightforward, given RMSProp. Last, the explicit learning rate $\\eta$ allows us to control the step length to address issues of convergence. \n",
"\n",
"## Implementation \n",
"\n",
"Implementing Adam from scratch is not very daunting. For convenience we store the time step counter $t$ in the `hyperparams` dictionary. Beyond that all is straightforward.\n"
]
},
{
"cell_type": "code",
"execution_count": 1,
"id": "dd1bfe3b",
"metadata": {
"execution": {
"iopub.execute_input": "2022-11-12T22:03:07.493016Z",
"iopub.status.busy": "2022-11-12T22:03:07.492446Z",
"iopub.status.idle": "2022-11-12T22:03:10.335585Z",
"shell.execute_reply": "2022-11-12T22:03:10.334276Z"
},
"origin_pos": 3,
"tab": [
"tensorflow"
]
},
"outputs": [],
"source": [
"%matplotlib inline\n",
"import tensorflow as tf\n",
"from d2l import tensorflow as d2l\n",
"\n",
"\n",
"def init_adam_states(feature_dim):\n",
" v_w = tf.Variable(tf.zeros((feature_dim, 1)))\n",
" v_b = tf.Variable(tf.zeros(1))\n",
" s_w = tf.Variable(tf.zeros((feature_dim, 1)))\n",
" s_b = tf.Variable(tf.zeros(1))\n",
" return ((v_w, s_w), (v_b, s_b))\n",
"\n",
"def adam(params, grads, states, hyperparams):\n",
" beta1, beta2, eps = 0.9, 0.999, 1e-6\n",
" for p, (v, s), grad in zip(params, states, grads):\n",
" v[:].assign(beta1 * v + (1 - beta1) * grad)\n",
" s[:].assign(beta2 * s + (1 - beta2) * tf.math.square(grad))\n",
" v_bias_corr = v / (1 - beta1 ** hyperparams['t'])\n",
" s_bias_corr = s / (1 - beta2 ** hyperparams['t'])\n",
" p[:].assign(p - hyperparams['lr'] * v_bias_corr\n",
" / tf.math.sqrt(s_bias_corr) + eps)"
]
},
{
"cell_type": "markdown",
"id": "c7ef3745",
"metadata": {
"origin_pos": 4
},
"source": [
"We are ready to use Adam to train the model. We use a learning rate of $\\eta = 0.01$.\n"
]
},
{
"cell_type": "code",
"execution_count": 2,
"id": "07510347",
"metadata": {
"execution": {
"iopub.execute_input": "2022-11-12T22:03:10.341942Z",
"iopub.status.busy": "2022-11-12T22:03:10.341285Z",
"iopub.status.idle": "2022-11-12T22:03:19.268002Z",
"shell.execute_reply": "2022-11-12T22:03:19.267093Z"
},
"origin_pos": 5,
"tab": [
"tensorflow"
]
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"loss: 0.243, 0.153 sec/epoch\n"
]
},
{
"data": {
"image/svg+xml": [
"\n",
"\n",
"\n"
],
"text/plain": [
"