amsgrad.html 34.6 KB
Newer Older
V
Varuna Jayasiri 已提交
1 2 3 4 5 6 7 8 9 10 11
<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="content-type" content="text/html;charset=utf-8"/>
    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
    <meta name="description" content="A simple PyTorch implementation/tutorial of AMSGrad optimizer."/>

    <meta name="twitter:card" content="summary"/>
    <meta name="twitter:image:src" content="https://avatars1.githubusercontent.com/u/64068543?s=400&amp;v=4"/>
    <meta name="twitter:title" content="AMSGrad Optimizer"/>
    <meta name="twitter:description" content="A simple PyTorch implementation/tutorial of AMSGrad optimizer."/>
V
urls  
Varuna Jayasiri 已提交
12 13
    <meta name="twitter:site" content="@labmlai"/>
    <meta name="twitter:creator" content="@labmlai"/>
V
Varuna Jayasiri 已提交
14

V
urls  
Varuna Jayasiri 已提交
15
    <meta property="og:url" content="https://nn.labml.ai/optimizers/amsgrad.html"/>
V
Varuna Jayasiri 已提交
16 17 18 19 20 21 22 23 24
    <meta property="og:title" content="AMSGrad Optimizer"/>
    <meta property="og:image" content="https://avatars1.githubusercontent.com/u/64068543?s=400&amp;v=4"/>
    <meta property="og:site_name" content="LabML Neural Networks"/>
    <meta property="og:type" content="object"/>
    <meta property="og:title" content="AMSGrad Optimizer"/>
    <meta property="og:description" content="A simple PyTorch implementation/tutorial of AMSGrad optimizer."/>

    <title>AMSGrad Optimizer</title>
    <link rel="stylesheet" href="../pylit.css">
V
urls  
Varuna Jayasiri 已提交
25
    <link rel="canonical" href="https://nn.labml.ai/optimizers/amsgrad.html"/>
V
Varuna Jayasiri 已提交
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
    <!-- Global site tag (gtag.js) - Google Analytics -->
    <script async src="https://www.googletagmanager.com/gtag/js?id=G-4V3HC8HBLH"></script>
    <script>
        window.dataLayer = window.dataLayer || [];

        function gtag() {
            dataLayer.push(arguments);
        }

        gtag('js', new Date());

        gtag('config', 'G-4V3HC8HBLH');
    </script>
</head>
<body>
<div id='container'>
    <div id="background"></div>
    <div class='section'>
        <div class='docs'>
            <p>
V
Varuna Jayasiri 已提交
46
                <a class="parent" href="/">home</a>
V
Varuna Jayasiri 已提交
47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543
                <a class="parent" href="index.html">optimizers</a>
            </p>
            <p>

                <a href="https://github.com/lab-ml/labml_nn/tree/master/optimizers/amsgrad.py">
                    <img alt="Github"
                         src="https://img.shields.io/github/stars/lab-ml/nn?style=social"
                         style="max-width:100%;"/></a>
                <a href="https://join.slack.com/t/labforml/shared_invite/zt-egj9zvq9-Dl3hhZqobexgT7aVKnD14g/"
                   rel="nofollow">
                    <img alt="Join Slact"
                         src="https://img.shields.io/badge/slack-chat-green.svg?logo=slack"
                         style="max-width:100%;"/></a>
                <a href="https://twitter.com/labmlai"
                   rel="nofollow">
                    <img alt="Twitter"
                         src="https://img.shields.io/twitter/follow/labmlai?style=social"
                         style="max-width:100%;"/></a>
            </p>
        </div>
    </div>
    <div class='section' id='section-0'>
        <div class='docs doc-strings'>
                <div class='section-link'>
                    <a href='#section-0'>#</a>
                </div>
                <h1>AMSGrad</h1>
<p>This is an implementation of the paper
<a href="https://arxiv.org/abs/1904.09237">On the Convergence of Adam and Beyond</a>.</p>
<p>We implement this as an extension to our <a href="adam.html">Adam optimizer implementation</a>.
The implementation it self is really small since it&rsquo;s very similar to Adam.</p>
<p>We also have an implementation of the synthetic example described in the paper where Adam fails to converge.</p>
            </div>
            <div class='code'>
                <div class="highlight"><pre><span class="lineno">18</span><span></span><span class="kn">from</span> <span class="nn">typing</span> <span class="kn">import</span> <span class="n">Dict</span>
<span class="lineno">19</span>
<span class="lineno">20</span><span class="kn">import</span> <span class="nn">torch</span>
<span class="lineno">21</span><span class="kn">from</span> <span class="nn">torch</span> <span class="kn">import</span> <span class="n">nn</span>
<span class="lineno">22</span>
<span class="lineno">23</span><span class="kn">from</span> <span class="nn">labml_nn.optimizers</span> <span class="kn">import</span> <span class="n">WeightDecay</span>
<span class="lineno">24</span><span class="kn">from</span> <span class="nn">labml_nn.optimizers.adam</span> <span class="kn">import</span> <span class="n">Adam</span></pre></div>
            </div>
        </div>
    <div class='section' id='section-1'>
        <div class='docs doc-strings'>
                <div class='section-link'>
                    <a href='#section-1'>#</a>
                </div>
                <h2>AMSGrad Optimizer</h2>
<p>This class extends from Adam optimizer defined in <a href="adam.html"><code>adam.py</code></a>.
Adam optimizer is extending the class <code>GenericAdaptiveOptimizer</code>
defined in <a href="index.html"><code>__init__.py</code></a>.</p>
            </div>
            <div class='code'>
                <div class="highlight"><pre><span class="lineno">27</span><span class="k">class</span> <span class="nc">AMSGrad</span><span class="p">(</span><span class="n">Adam</span><span class="p">):</span></pre></div>
            </div>
        </div>
    <div class='section' id='section-2'>
        <div class='docs doc-strings'>
                <div class='section-link'>
                    <a href='#section-2'>#</a>
                </div>
                <h3>Initialize the optimizer</h3>
<ul>
<li><code>params</code> is the list of parameters</li>
<li><code>lr</code> is the learning rate $\alpha$</li>
<li><code>betas</code> is a tuple of ($\beta_1$, $\beta_2$)</li>
<li><code>eps</code> is $\hat{\epsilon}$ or $\epsilon$ based on <code>optimized_update</code></li>
<li><code>weight_decay</code> is an instance of class <code>WeightDecay</code> defined in <a href="index.html"><code>__init__.py</code></a></li>
<li>&lsquo;optimized_update&rsquo; is a flag whether to optimize the bias correction of the second moment
  by doing it after adding $\epsilon$</li>
<li><code>amsgrad</code> is a flag indicating whether to use AMSGrad or fallback to plain Adam</li>
<li><code>defaults</code> is a dictionary of default for group values.
 This is useful when you want to extend the class <code>Adam</code>.</li>
</ul>
            </div>
            <div class='code'>
                <div class="highlight"><pre><span class="lineno">35</span>    <span class="k">def</span> <span class="fm">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">params</span><span class="p">,</span> <span class="n">lr</span><span class="o">=</span><span class="mf">1e-3</span><span class="p">,</span> <span class="n">betas</span><span class="o">=</span><span class="p">(</span><span class="mf">0.9</span><span class="p">,</span> <span class="mf">0.999</span><span class="p">),</span> <span class="n">eps</span><span class="o">=</span><span class="mf">1e-16</span><span class="p">,</span>
<span class="lineno">36</span>                 <span class="n">weight_decay</span><span class="p">:</span> <span class="n">WeightDecay</span> <span class="o">=</span> <span class="n">WeightDecay</span><span class="p">(),</span>
<span class="lineno">37</span>                 <span class="n">optimized_update</span><span class="p">:</span> <span class="nb">bool</span> <span class="o">=</span> <span class="kc">True</span><span class="p">,</span>
<span class="lineno">38</span>                 <span class="n">amsgrad</span><span class="o">=</span><span class="kc">True</span><span class="p">,</span> <span class="n">defaults</span><span class="o">=</span><span class="kc">None</span><span class="p">):</span></pre></div>
            </div>
        </div>
    <div class='section' id='section-3'>
            <div class='docs'>
                <div class='section-link'>
                    <a href='#section-3'>#</a>
                </div>
                
            </div>
            <div class='code'>
                <div class="highlight"><pre><span class="lineno">53</span>        <span class="n">defaults</span> <span class="o">=</span> <span class="p">{}</span> <span class="k">if</span> <span class="n">defaults</span> <span class="ow">is</span> <span class="kc">None</span> <span class="k">else</span> <span class="n">defaults</span>
<span class="lineno">54</span>        <span class="n">defaults</span><span class="o">.</span><span class="n">update</span><span class="p">(</span><span class="nb">dict</span><span class="p">(</span><span class="n">amsgrad</span><span class="o">=</span><span class="n">amsgrad</span><span class="p">))</span>
<span class="lineno">55</span>
<span class="lineno">56</span>        <span class="nb">super</span><span class="p">()</span><span class="o">.</span><span class="fm">__init__</span><span class="p">(</span><span class="n">params</span><span class="p">,</span> <span class="n">lr</span><span class="p">,</span> <span class="n">betas</span><span class="p">,</span> <span class="n">eps</span><span class="p">,</span> <span class="n">weight_decay</span><span class="p">,</span> <span class="n">optimized_update</span><span class="p">,</span> <span class="n">defaults</span><span class="p">)</span></pre></div>
            </div>
        </div>
    <div class='section' id='section-4'>
        <div class='docs doc-strings'>
                <div class='section-link'>
                    <a href='#section-4'>#</a>
                </div>
                <h3>Initialize a parameter state</h3>
<ul>
<li><code>state</code> is the optimizer state of the parameter (tensor)</li>
<li><code>group</code> stores optimizer attributes of the parameter group</li>
<li><code>param</code> is the parameter tensor $\theta_{t-1}$</li>
</ul>
            </div>
            <div class='code'>
                <div class="highlight"><pre><span class="lineno">58</span>    <span class="k">def</span> <span class="nf">init_state</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">state</span><span class="p">:</span> <span class="n">Dict</span><span class="p">[</span><span class="nb">str</span><span class="p">,</span> <span class="nb">any</span><span class="p">],</span> <span class="n">group</span><span class="p">:</span> <span class="n">Dict</span><span class="p">[</span><span class="nb">str</span><span class="p">,</span> <span class="nb">any</span><span class="p">],</span> <span class="n">param</span><span class="p">:</span> <span class="n">nn</span><span class="o">.</span><span class="n">Parameter</span><span class="p">):</span></pre></div>
            </div>
        </div>
    <div class='section' id='section-5'>
            <div class='docs'>
                <div class='section-link'>
                    <a href='#section-5'>#</a>
                </div>
                <p>Call <code>init_state</code> of Adam optimizer which we are extending</p>
            </div>
            <div class='code'>
                <div class="highlight"><pre><span class="lineno">68</span>        <span class="nb">super</span><span class="p">()</span><span class="o">.</span><span class="n">init_state</span><span class="p">(</span><span class="n">state</span><span class="p">,</span> <span class="n">group</span><span class="p">,</span> <span class="n">param</span><span class="p">)</span></pre></div>
            </div>
        </div>
    <div class='section' id='section-6'>
            <div class='docs'>
                <div class='section-link'>
                    <a href='#section-6'>#</a>
                </div>
                <p>If <code>amsgrad</code> flag is <code>True</code> for this parameter group, we maintain the maximum of
exponential moving average of squared gradient</p>
            </div>
            <div class='code'>
                <div class="highlight"><pre><span class="lineno">72</span>        <span class="k">if</span> <span class="n">group</span><span class="p">[</span><span class="s1">&#39;amsgrad&#39;</span><span class="p">]:</span>
<span class="lineno">73</span>            <span class="n">state</span><span class="p">[</span><span class="s1">&#39;max_exp_avg_sq&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="n">torch</span><span class="o">.</span><span class="n">zeros_like</span><span class="p">(</span><span class="n">param</span><span class="p">,</span> <span class="n">memory_format</span><span class="o">=</span><span class="n">torch</span><span class="o">.</span><span class="n">preserve_format</span><span class="p">)</span></pre></div>
            </div>
        </div>
    <div class='section' id='section-7'>
        <div class='docs doc-strings'>
                <div class='section-link'>
                    <a href='#section-7'>#</a>
                </div>
                <h3>Calculate $m_t$ and and $v_t$ or $\max(v_1, v_2, &hellip;, v_{t-1}, v_t)$</h3>
<ul>
<li><code>state</code> is the optimizer state of the parameter (tensor)</li>
<li><code>group</code> stores optimizer attributes of the parameter group</li>
<li><code>grad</code> is the current gradient tensor $g_t$ for the parameter $\theta_{t-1}$</li>
</ul>
            </div>
            <div class='code'>
                <div class="highlight"><pre><span class="lineno">75</span>    <span class="k">def</span> <span class="nf">get_mv</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">state</span><span class="p">:</span> <span class="n">Dict</span><span class="p">[</span><span class="nb">str</span><span class="p">,</span> <span class="nb">any</span><span class="p">],</span> <span class="n">group</span><span class="p">:</span> <span class="n">Dict</span><span class="p">[</span><span class="nb">str</span><span class="p">,</span> <span class="nb">any</span><span class="p">],</span> <span class="n">grad</span><span class="p">:</span> <span class="n">torch</span><span class="o">.</span><span class="n">Tensor</span><span class="p">):</span></pre></div>
            </div>
        </div>
    <div class='section' id='section-8'>
            <div class='docs'>
                <div class='section-link'>
                    <a href='#section-8'>#</a>
                </div>
                <p>Get $m_t$ and $v_t$ from <em>Adam</em></p>
            </div>
            <div class='code'>
                <div class="highlight"><pre><span class="lineno">85</span>        <span class="n">m</span><span class="p">,</span> <span class="n">v</span> <span class="o">=</span> <span class="nb">super</span><span class="p">()</span><span class="o">.</span><span class="n">get_mv</span><span class="p">(</span><span class="n">state</span><span class="p">,</span> <span class="n">group</span><span class="p">,</span> <span class="n">grad</span><span class="p">)</span></pre></div>
            </div>
        </div>
    <div class='section' id='section-9'>
            <div class='docs'>
                <div class='section-link'>
                    <a href='#section-9'>#</a>
                </div>
                <p>If this parameter group is using <code>amsgrad</code></p>
            </div>
            <div class='code'>
                <div class="highlight"><pre><span class="lineno">88</span>        <span class="k">if</span> <span class="n">group</span><span class="p">[</span><span class="s1">&#39;amsgrad&#39;</span><span class="p">]:</span></pre></div>
            </div>
        </div>
    <div class='section' id='section-10'>
            <div class='docs'>
                <div class='section-link'>
                    <a href='#section-10'>#</a>
                </div>
                <p>Get $\max(v_1, v_2, &hellip;, v_{t-1})$.</p>
<p>🗒 The paper uses the notation $\hat{v}_t$ for this, which we don&rsquo;t use
that here because it confuses with the Adam&rsquo;s usage of the same notation
for bias corrected exponential moving average.</p>
            </div>
            <div class='code'>
                <div class="highlight"><pre><span class="lineno">94</span>            <span class="n">v_max</span> <span class="o">=</span> <span class="n">state</span><span class="p">[</span><span class="s1">&#39;max_exp_avg_sq&#39;</span><span class="p">]</span></pre></div>
            </div>
        </div>
    <div class='section' id='section-11'>
            <div class='docs'>
                <div class='section-link'>
                    <a href='#section-11'>#</a>
                </div>
                <p>Calculate $\max(v_1, v_2, &hellip;, v_{t-1}, v_t)$.</p>
<p>🤔 I feel you should be taking / maintaining the max of the bias corrected
second exponential average of squared gradient.
But this is how it&rsquo;s
<a href="https://github.com/pytorch/pytorch/blob/19f4c5110e8bcad5e7e75375194262fca0a6293a/torch/optim/functional.py#L90">implemented in PyTorch also</a>.
I guess it doesn&rsquo;t really matter since bias correction only increases the value
and it only makes an actual difference during the early few steps of the training.</p>
            </div>
            <div class='code'>
                <div class="highlight"><pre><span class="lineno">103</span>            <span class="n">torch</span><span class="o">.</span><span class="n">maximum</span><span class="p">(</span><span class="n">v_max</span><span class="p">,</span> <span class="n">v</span><span class="p">,</span> <span class="n">out</span><span class="o">=</span><span class="n">v_max</span><span class="p">)</span>
<span class="lineno">104</span>
<span class="lineno">105</span>            <span class="k">return</span> <span class="n">m</span><span class="p">,</span> <span class="n">v_max</span>
<span class="lineno">106</span>        <span class="k">else</span><span class="p">:</span></pre></div>
            </div>
        </div>
    <div class='section' id='section-12'>
            <div class='docs'>
                <div class='section-link'>
                    <a href='#section-12'>#</a>
                </div>
                <p>Fall back to <em>Adam</em> if the parameter group is not using <code>amsgrad</code></p>
            </div>
            <div class='code'>
                <div class="highlight"><pre><span class="lineno">108</span>            <span class="k">return</span> <span class="n">m</span><span class="p">,</span> <span class="n">v</span></pre></div>
            </div>
        </div>
    <div class='section' id='section-13'>
        <div class='docs doc-strings'>
                <div class='section-link'>
                    <a href='#section-13'>#</a>
                </div>
                <h2>Synthetic Experiment</h2>
<p>This is the synthetic experiment described in the paper,
that shows a scenario where <em>Adam</em> fails.</p>
<p>The paper (and Adam) formulates the problem of optimizing as
minimizing the expected value of a function, $\mathbb{E}[f(\theta)]$
with respect to the parameters $\theta$.
In the stochastic training setting we do not get hold of the function $f$
it self; that is,
when you are optimizing a NN $f$ would be the function on  entire
batch of data.
What we actually evaluate is a mini-batch so the actual function is
realization of the stochastic $f$.
This is why we are talking about an expected value.
So let the function realizations be $f_1, f_2, &hellip;, f_T$ for each time step
of training.</p>
<p>We measure the performance of the optimizer as the regret,
<script type="math/tex; mode=display">R(T) = \sum_{t=1}^T \big[ f_t(\theta_t) - f_t(\theta^*) \big]</script>
where $theta_t$ is the parameters at time step $t$, and  $\theta^*$ is the
optimal parameters that minimize $\mathbb{E}[f(\theta)]$.</p>
<p>Now lets define the synthetic problem,
<script type="math/tex; mode=display">\begin{align}
f_t(x) =
\begin{cases}
1010 x,  & \text{for $t \mod 101 = 1$} \\
-10  x, & \text{otherwise}
\end{cases}
\end{align}</script>
where $-1 \le x \le +1$.
The optimal solution is $x = -1$.</p>
<p>This code will try running <em>Adam</em> and <em>AMSGrad</em> on this problem.</p>
            </div>
            <div class='code'>
                <div class="highlight"><pre><span class="lineno">111</span><span class="k">def</span> <span class="nf">_synthetic_experiment</span><span class="p">(</span><span class="n">is_adam</span><span class="p">:</span> <span class="nb">bool</span><span class="p">):</span></pre></div>
            </div>
        </div>
    <div class='section' id='section-14'>
            <div class='docs'>
                <div class='section-link'>
                    <a href='#section-14'>#</a>
                </div>
                <p>Define $x$ parameter</p>
            </div>
            <div class='code'>
                <div class="highlight"><pre><span class="lineno">151</span>    <span class="n">x</span> <span class="o">=</span> <span class="n">nn</span><span class="o">.</span><span class="n">Parameter</span><span class="p">(</span><span class="n">torch</span><span class="o">.</span><span class="n">tensor</span><span class="p">([</span><span class="o">.</span><span class="mi">0</span><span class="p">]))</span></pre></div>
            </div>
        </div>
    <div class='section' id='section-15'>
            <div class='docs'>
                <div class='section-link'>
                    <a href='#section-15'>#</a>
                </div>
                <p>Optimal, $x^* = -1$</p>
            </div>
            <div class='code'>
                <div class="highlight"><pre><span class="lineno">153</span>    <span class="n">x_star</span> <span class="o">=</span> <span class="n">nn</span><span class="o">.</span><span class="n">Parameter</span><span class="p">(</span><span class="n">torch</span><span class="o">.</span><span class="n">tensor</span><span class="p">([</span><span class="o">-</span><span class="mi">1</span><span class="p">]),</span> <span class="n">requires_grad</span><span class="o">=</span><span class="kc">False</span><span class="p">)</span></pre></div>
            </div>
        </div>
    <div class='section' id='section-16'>
        <div class='docs doc-strings'>
                <div class='section-link'>
                    <a href='#section-16'>#</a>
                </div>
                <h3>$f_t(x)$</h3>
            </div>
            <div class='code'>
                <div class="highlight"><pre><span class="lineno">155</span>    <span class="k">def</span> <span class="nf">func</span><span class="p">(</span><span class="n">t</span><span class="p">:</span> <span class="nb">int</span><span class="p">,</span> <span class="n">x_</span><span class="p">:</span> <span class="n">nn</span><span class="o">.</span><span class="n">Parameter</span><span class="p">):</span></pre></div>
            </div>
        </div>
    <div class='section' id='section-17'>
            <div class='docs'>
                <div class='section-link'>
                    <a href='#section-17'>#</a>
                </div>
                
            </div>
            <div class='code'>
                <div class="highlight"><pre><span class="lineno">159</span>        <span class="k">if</span> <span class="n">t</span> <span class="o">%</span> <span class="mi">101</span> <span class="o">==</span> <span class="mi">1</span><span class="p">:</span>
<span class="lineno">160</span>            <span class="k">return</span> <span class="p">(</span><span class="mi">1010</span> <span class="o">*</span> <span class="n">x_</span><span class="p">)</span><span class="o">.</span><span class="n">sum</span><span class="p">()</span>
<span class="lineno">161</span>        <span class="k">else</span><span class="p">:</span>
<span class="lineno">162</span>            <span class="k">return</span> <span class="p">(</span><span class="o">-</span><span class="mi">10</span> <span class="o">*</span> <span class="n">x_</span><span class="p">)</span><span class="o">.</span><span class="n">sum</span><span class="p">()</span></pre></div>
            </div>
        </div>
    <div class='section' id='section-18'>
            <div class='docs'>
                <div class='section-link'>
                    <a href='#section-18'>#</a>
                </div>
                <p>Initialize the relevant optimizer</p>
            </div>
            <div class='code'>
                <div class="highlight"><pre><span class="lineno">165</span>    <span class="k">if</span> <span class="n">is_adam</span><span class="p">:</span>
<span class="lineno">166</span>        <span class="n">optimizer</span> <span class="o">=</span> <span class="n">Adam</span><span class="p">([</span><span class="n">x</span><span class="p">],</span> <span class="n">lr</span><span class="o">=</span><span class="mf">1e-2</span><span class="p">,</span> <span class="n">betas</span><span class="o">=</span><span class="p">(</span><span class="mf">0.9</span><span class="p">,</span> <span class="mf">0.99</span><span class="p">))</span>
<span class="lineno">167</span>    <span class="k">else</span><span class="p">:</span>
<span class="lineno">168</span>        <span class="n">optimizer</span> <span class="o">=</span> <span class="n">AMSGrad</span><span class="p">([</span><span class="n">x</span><span class="p">],</span> <span class="n">lr</span><span class="o">=</span><span class="mf">1e-2</span><span class="p">,</span> <span class="n">betas</span><span class="o">=</span><span class="p">(</span><span class="mf">0.9</span><span class="p">,</span> <span class="mf">0.99</span><span class="p">))</span></pre></div>
            </div>
        </div>
    <div class='section' id='section-19'>
            <div class='docs'>
                <div class='section-link'>
                    <a href='#section-19'>#</a>
                </div>
                <p>$R(T)$</p>
            </div>
            <div class='code'>
                <div class="highlight"><pre><span class="lineno">170</span>    <span class="n">total_regret</span> <span class="o">=</span> <span class="mi">0</span>
<span class="lineno">171</span>
<span class="lineno">172</span>    <span class="kn">from</span> <span class="nn">labml</span> <span class="kn">import</span> <span class="n">monit</span><span class="p">,</span> <span class="n">tracker</span><span class="p">,</span> <span class="n">experiment</span></pre></div>
            </div>
        </div>
    <div class='section' id='section-20'>
            <div class='docs'>
                <div class='section-link'>
                    <a href='#section-20'>#</a>
                </div>
                <p>Create experiment to record results</p>
            </div>
            <div class='code'>
                <div class="highlight"><pre><span class="lineno">175</span>    <span class="k">with</span> <span class="n">experiment</span><span class="o">.</span><span class="n">record</span><span class="p">(</span><span class="n">name</span><span class="o">=</span><span class="s1">&#39;synthetic&#39;</span><span class="p">,</span> <span class="n">comment</span><span class="o">=</span><span class="s1">&#39;Adam&#39;</span> <span class="k">if</span> <span class="n">is_adam</span> <span class="k">else</span> <span class="s1">&#39;AMSGrad&#39;</span><span class="p">):</span></pre></div>
            </div>
        </div>
    <div class='section' id='section-21'>
            <div class='docs'>
                <div class='section-link'>
                    <a href='#section-21'>#</a>
                </div>
                <p>Run for $10^7$ steps</p>
            </div>
            <div class='code'>
                <div class="highlight"><pre><span class="lineno">177</span>        <span class="k">for</span> <span class="n">step</span> <span class="ow">in</span> <span class="n">monit</span><span class="o">.</span><span class="n">loop</span><span class="p">(</span><span class="mi">10_000_000</span><span class="p">):</span></pre></div>
            </div>
        </div>
    <div class='section' id='section-22'>
            <div class='docs'>
                <div class='section-link'>
                    <a href='#section-22'>#</a>
                </div>
                <p>$f_t(\theta_t) - f_t(\theta^*)$</p>
            </div>
            <div class='code'>
                <div class="highlight"><pre><span class="lineno">179</span>            <span class="n">regret</span> <span class="o">=</span> <span class="n">func</span><span class="p">(</span><span class="n">step</span><span class="p">,</span> <span class="n">x</span><span class="p">)</span> <span class="o">-</span> <span class="n">func</span><span class="p">(</span><span class="n">step</span><span class="p">,</span> <span class="n">x_star</span><span class="p">)</span></pre></div>
            </div>
        </div>
    <div class='section' id='section-23'>
            <div class='docs'>
                <div class='section-link'>
                    <a href='#section-23'>#</a>
                </div>
                <p>$R(T) = \sum_{t=1}^T \big[ f_t(\theta_t) - f_t(\theta^*) \big]$</p>
            </div>
            <div class='code'>
                <div class="highlight"><pre><span class="lineno">181</span>            <span class="n">total_regret</span> <span class="o">+=</span> <span class="n">regret</span><span class="o">.</span><span class="n">item</span><span class="p">()</span></pre></div>
            </div>
        </div>
    <div class='section' id='section-24'>
            <div class='docs'>
                <div class='section-link'>
                    <a href='#section-24'>#</a>
                </div>
                <p>Track results every 1,000 steps</p>
            </div>
            <div class='code'>
                <div class="highlight"><pre><span class="lineno">183</span>            <span class="k">if</span> <span class="p">(</span><span class="n">step</span> <span class="o">+</span> <span class="mi">1</span><span class="p">)</span> <span class="o">%</span> <span class="mi">1000</span> <span class="o">==</span> <span class="mi">0</span><span class="p">:</span>
<span class="lineno">184</span>                <span class="n">tracker</span><span class="o">.</span><span class="n">save</span><span class="p">(</span><span class="n">loss</span><span class="o">=</span><span class="n">regret</span><span class="p">,</span> <span class="n">x</span><span class="o">=</span><span class="n">x</span><span class="p">,</span> <span class="n">regret</span><span class="o">=</span><span class="n">total_regret</span> <span class="o">/</span> <span class="p">(</span><span class="n">step</span> <span class="o">+</span> <span class="mi">1</span><span class="p">))</span></pre></div>
            </div>
        </div>
    <div class='section' id='section-25'>
            <div class='docs'>
                <div class='section-link'>
                    <a href='#section-25'>#</a>
                </div>
                <p>Calculate gradients</p>
            </div>
            <div class='code'>
                <div class="highlight"><pre><span class="lineno">186</span>            <span class="n">regret</span><span class="o">.</span><span class="n">backward</span><span class="p">()</span></pre></div>
            </div>
        </div>
    <div class='section' id='section-26'>
            <div class='docs'>
                <div class='section-link'>
                    <a href='#section-26'>#</a>
                </div>
                <p>Optimize</p>
            </div>
            <div class='code'>
                <div class="highlight"><pre><span class="lineno">188</span>            <span class="n">optimizer</span><span class="o">.</span><span class="n">step</span><span class="p">()</span></pre></div>
            </div>
        </div>
    <div class='section' id='section-27'>
            <div class='docs'>
                <div class='section-link'>
                    <a href='#section-27'>#</a>
                </div>
                <p>Clear gradients</p>
            </div>
            <div class='code'>
                <div class="highlight"><pre><span class="lineno">190</span>            <span class="n">optimizer</span><span class="o">.</span><span class="n">zero_grad</span><span class="p">()</span></pre></div>
            </div>
        </div>
    <div class='section' id='section-28'>
            <div class='docs'>
                <div class='section-link'>
                    <a href='#section-28'>#</a>
                </div>
                <p>Make sure $-1 \le x \le +1$</p>
            </div>
            <div class='code'>
                <div class="highlight"><pre><span class="lineno">193</span>            <span class="n">x</span><span class="o">.</span><span class="n">data</span><span class="o">.</span><span class="n">clamp_</span><span class="p">(</span><span class="o">-</span><span class="mf">1.</span><span class="p">,</span> <span class="o">+</span><span class="mf">1.</span><span class="p">)</span>
<span class="lineno">194</span>
<span class="lineno">195</span>
<span class="lineno">196</span><span class="k">if</span> <span class="vm">__name__</span> <span class="o">==</span> <span class="s1">&#39;__main__&#39;</span><span class="p">:</span></pre></div>
            </div>
        </div>
    <div class='section' id='section-29'>
            <div class='docs'>
                <div class='section-link'>
                    <a href='#section-29'>#</a>
                </div>
                <p>Run the synthetic experiment is <em>Adam</em>.
<a href="https://web.lab-ml.com/metrics?uuid=61ebfdaa384411eb94d8acde48001122">Here are the results</a>.
You can see that Adam converges at $x = +1$</p>
            </div>
            <div class='code'>
                <div class="highlight"><pre><span class="lineno">200</span>    <span class="n">_synthetic_experiment</span><span class="p">(</span><span class="kc">True</span><span class="p">)</span></pre></div>
            </div>
        </div>
    <div class='section' id='section-30'>
            <div class='docs'>
                <div class='section-link'>
                    <a href='#section-30'>#</a>
                </div>
                <p>Run the synthetic experiment is <em>AMSGrad</em>
<a href="https://web.lab-ml.com/metrics?uuid=bc06405c384411eb8b82acde48001122">Here are the results</a>.
You can see that AMSGrad converges to true optimal $x = -1$</p>
            </div>
            <div class='code'>
                <div class="highlight"><pre><span class="lineno">204</span>    <span class="n">_synthetic_experiment</span><span class="p">(</span><span class="kc">False</span><span class="p">)</span></pre></div>
            </div>
        </div>
    </div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.4/MathJax.js?config=TeX-AMS_HTML">
</script>
<!-- MathJax configuration -->
<script type="text/x-mathjax-config">
    MathJax.Hub.Config({
        tex2jax: {
            inlineMath: [ ['$','$'] ],
            displayMath: [ ['$$','$$'] ],
            processEscapes: true,
            processEnvironments: true
        },
        // Center justify equations in code and markdown cells. Elsewhere
        // we use CSS to left justify single line equations in code cells.
        displayAlign: 'center',
        "HTML-CSS": { fonts: ["TeX"] }
    });













</script>
</body>
</html>