File size: 24,173 Bytes
fc0f7bd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
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
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "qEIr4kn4W6Zs"
      },
      "source": [
        "# Sharpness-Aware Minimization (SAM)\n",
        "\n",
        "[![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.sandbox.google.com/github/google-deepmind/optax/blob/main/examples/sam.ipynb)\n",
        "\n",
        "\n",
        "This serves a testing ground for a simple SAM type optimizer implementation in JAX with existing apis."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "AxR7ryYMXHcr"
      },
      "outputs": [],
      "source": [
        "import jax\n",
        "import jax.numpy as np\n",
        "import matplotlib.pyplot as plt\n",
        "import optax\n",
        "import chex\n",
        "from optax import contrib"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "ImgJJV9_iq-v"
      },
      "source": [
        "## Transparent Mode\n",
        "\n",
        "This implementation of SAM can be used in two different modes: transparent and opaque.\n",
        " - Transparent mode exposes all gradient updates (described below) to the training loop, but it is easier to set up.\n",
        " - Opaque mode hides the adversarial updates from the training loop, which is necessary when other state depends on the updates, such as BatchNorm parameters.\n",
        "\n",
        "Opaque mode is slightly more work to set up, so we will start with transparent mode."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "TocZvhcDJoyY"
      },
      "source": [
        "One way to describe what SAM does is that it does some number of steps (usually 1) of adversarial updates, followed by an outer gradient update.\n",
        "\n",
        "What this means is that we have to do a bunch of steps:\n",
        "\n",
        "\n",
        "    # adversarial step\n",
        "    params = params + sam_rho * normalize(gradient)\n",
        "\n",
        "    # outer update step\n",
        "    params = cache - learning_rate * gradient\n",
        "    cache = params\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "7-p_W8vkhnO1"
      },
      "source": [
        "To actually use SAM then, you create your adversarial optimizer, here SGD with normalized gradients, an outer optimzer, and then wrap them with SAM.\n",
        "\n",
        "The drop-in SAM optimizer described in the paper uses SGD for both optimizers."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "ueMKkNw7jLNJ"
      },
      "outputs": [],
      "source": [
        "lr = 0.01\n",
        "rho = 0.1\n",
        "opt = optax.sgd(lr)\n",
        "adv_opt = optax.chain(contrib.normalize(), optax.sgd(rho))\n",
        "sam_opt = contrib.sam(opt, adv_opt, sync_period=2)  # This is the drop-in SAM optimizer.\n",
        "\n",
        "sgd_opt = optax.sgd(lr)  # Baseline SGD optimizer"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "jgFuHGHPAIfU"
      },
      "source": [
        "However, it is possible to use SGD for the adversarial optimizer, and, for example, SGD with momentum for the outer optimizer."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "TsLVwjHywg55"
      },
      "outputs": [],
      "source": [
        "def sam_mom(lr=1e-3, momentum=0.1, rho=0.1, sync_period=2):\n",
        "  opt = optax.sgd(lr, momentum=momentum)\n",
        "  adv_opt = optax.chain(contrib.normalize(), optax.sgd(rho))\n",
        "  return contrib.sam(opt, adv_opt, sync_period=sync_period)\n",
        "\n",
        "mom = 0.9\n",
        "sam_mom_opt = sam_mom(lr, momentum=mom)\n",
        "mom_opt = optax.sgd(lr, momentum=mom)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "K6CCwKIIASsN"
      },
      "source": [
        "It's even possible to use Adam for **both** optimizers. In this case, we'll need to increase the number of adversarial steps between syncs, but the resulting optimization will still be much faster than using SGD by itself with SAM."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "0FesjRbUsT80"
      },
      "outputs": [],
      "source": [
        "def sam_adam(lr=1e-3, b1=0.9, b2=0.999, rho=0.03, sync_period=5):\n",
        "  \"\"\"A SAM optimizer using Adam for the outer optimizer.\"\"\"\n",
        "  opt = optax.adam(lr, b1=b1, b2=b2)\n",
        "  adv_opt = optax.chain(contrib.normalize(), optax.adam(rho))\n",
        "  return contrib.sam(opt, adv_opt, sync_period=sync_period)\n",
        "\n",
        "sam_adam_opt = sam_adam(lr)\n",
        "adam_opt = optax.adam(lr)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "DyTChHZr2Yw6"
      },
      "source": [
        "We'll set up a simple test problem below, we're going to try to optimize a sum of two exponentials that has two minima, one at (0,0) and another at (2,0) and compare the performance of both SAM and ordinary SGD."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "PSE3mM2FZGio"
      },
      "outputs": [],
      "source": [
        "# An example 2D loss function. It has two minima at (0,0) and (2,0).\n",
        "# Both points attain almost zero loss value, but the first one is much sharper.\n",
        "\n",
        "def loss(params):\n",
        "  x, y = params\n",
        "  return -np.exp(-(x - 2)**2 - y**2) - 1.0*np.exp(-((x)**2 + (y)**2*100))\n",
        "\n",
        "x, y = np.meshgrid(np.linspace(0, 2, 100), np.linspace(0, 2, 100))\n",
        "l = loss((x, y))\n",
        "plt.matshow(l)\n",
        "plt.xticks([0, 50, 100], [0, 1, 2])\n",
        "plt.yticks([0, 50, 100], [0, 1, 2])\n",
        "plt.title('Loss Surface')\n",
        "plt.show();"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "Zi3tzM1AZbN_"
      },
      "outputs": [],
      "source": [
        "params = np.array([-0.4, -0.4])\n",
        "\n",
        "@chex.dataclass\n",
        "class Store:\n",
        "  params: chex.Array\n",
        "  state: optax.OptState\n",
        "  step: int = 0\n",
        "\n",
        "sam_store = Store(params=params, state=sam_opt.init(params))\n",
        "sgd_store = Store(params=params, state=sgd_opt.init(params))\n",
        "sam_mom_store = Store(params=params, state=sam_mom_opt.init(params))\n",
        "mom_store = Store(params=params, state=mom_opt.init(params))\n",
        "sam_adam_store = Store(params=params, state=sam_adam_opt.init(params))\n",
        "adam_store = Store(params=params, state=adam_opt.init(params))"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "UhFr0AwqZjRk"
      },
      "outputs": [],
      "source": [
        "def make_step(opt):\n",
        "  @jax.jit\n",
        "  def step(store):\n",
        "    value, grads = jax.value_and_grad(loss)(store.params)\n",
        "    updates, state = opt.update(grads, store.state, store.params)\n",
        "    params = optax.apply_updates(store.params, updates)\n",
        "    return store.replace(\n",
        "        params=params,\n",
        "        state=state,\n",
        "        step=store.step+1), value\n",
        "  return step"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "bTkjju6IinJx"
      },
      "outputs": [],
      "source": [
        "sam_step = make_step(sam_opt)\n",
        "sgd_step = make_step(sgd_opt)\n",
        "\n",
        "sam_mom_step = make_step(sam_mom_opt)\n",
        "mom_step = make_step(mom_opt)\n",
        "\n",
        "sam_adam_step = make_step(sam_adam_opt)\n",
        "adam_step = make_step(adam_opt)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "MEF-PriWcLSa"
      },
      "outputs": [],
      "source": [
        "sam_vals = []\n",
        "sam_params = []\n",
        "sgd_vals = []\n",
        "sgd_params = []\n",
        "\n",
        "sam_mom_vals = []\n",
        "sam_mom_params = []\n",
        "mom_vals = []\n",
        "mom_params = []\n",
        "\n",
        "sam_adam_vals = []\n",
        "sam_adam_params = []\n",
        "adam_vals = []\n",
        "adam_params = []"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "8Em3xy9PaEbH"
      },
      "outputs": [],
      "source": [
        "T = 8000\n",
        "for i in range(T):\n",
        "  sam_store, sam_val = sam_step(sam_store)\n",
        "  sgd_store, sgd_val = sgd_step(sgd_store)\n",
        "  sam_mom_store, sam_mom_val = sam_mom_step(sam_mom_store)\n",
        "  mom_store, mom_val = mom_step(mom_store)\n",
        "  sam_adam_store, sam_adam_val = sam_adam_step(sam_adam_store)\n",
        "  adam_store, adam_val = adam_step(adam_store)\n",
        "\n",
        "  sam_vals.append(sam_val)\n",
        "  sgd_vals.append(sgd_val)\n",
        "  sam_mom_vals.append(sam_mom_val)\n",
        "  mom_vals.append(mom_val)\n",
        "  sam_adam_vals.append(sam_adam_val)\n",
        "  adam_vals.append(adam_val)\n",
        "\n",
        "  sam_params.append(sam_store.params)\n",
        "  sgd_params.append(sgd_store.params)\n",
        "  sam_mom_params.append(sam_mom_store.params)\n",
        "  mom_params.append(mom_store.params)\n",
        "  sam_adam_params.append(sam_adam_store.params)\n",
        "  adam_params.append(adam_store.params)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "sCrf_qJzdDmk"
      },
      "outputs": [],
      "source": [
        "ts = np.arange(T)\n",
        "fig, axs = plt.subplots(6, figsize=(10, 12))\n",
        "axs[0].plot(ts, sgd_vals, label='SGD')\n",
        "axs[0].plot(ts[::2], sam_vals[0::2], label='SAM Outer Loss', lw=3, zorder=100)\n",
        "axs[0].plot(ts[1::2], sam_vals[1::2], label='SAM Adv Loss', alpha=0.5)\n",
        "axs[0].legend();\n",
        "\n",
        "axs[1].plot(ts, sgd_vals, label='SGD')\n",
        "axs[1].plot(ts[::2] / 2, sam_vals[::2], label='1/2 SAM', lw=3)\n",
        "axs[1].legend();\n",
        "\n",
        "axs[2].plot(ts, mom_vals, label='Mom')\n",
        "axs[2].plot(ts[::2], sam_mom_vals[::2], label='SAM Mom Outer Loss', lw=3, zorder=100)\n",
        "axs[2].plot(ts[1::2], sam_mom_vals[1::2], label='SAM Mom Adv Loss', alpha=0.5)\n",
        "axs[2].legend();\n",
        "\n",
        "axs[3].plot(ts, mom_vals, label='Mom')\n",
        "axs[3].plot(ts[::2] / 2, sam_mom_vals[::2], label='1/2 SAM Mom', lw=3)\n",
        "axs[3].legend();\n",
        "\n",
        "axs[4].plot(ts, adam_vals, label='Adam')\n",
        "axs[4].plot(ts[::5], sam_adam_vals[::5], label='SAM Adam Outer Loss', lw=3, zorder=100)\n",
        "axs[4].plot(ts[4::5], sam_adam_vals[4::5], label='SAM Adam Adv Loss', alpha=0.5)\n",
        "axs[4].legend();\n",
        "\n",
        "axs[5].plot(ts, adam_vals, label='Adam')\n",
        "axs[5].plot(ts[::5] / 5, sam_adam_vals[::5], label='1/5 SAM Adam', lw=3)\n",
        "axs[5].legend();"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "kEmX6vdp_n50"
      },
      "source": [
        "On this problem, SAM Mom is the fastest of the three SAM optimizers in terms of real steps, but in terms of outer gradient steps, SAM Adam is slightly faster, since it has 4 inner gradient steps for every outer gradient step, compared with 1 inner per outer for SAM and SAM Mom."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "o1kIeonUeA0x"
      },
      "outputs": [],
      "source": [
        "fig, axs = plt.subplots(ncols=3, figsize=(8 * 3, 6))\n",
        "axs[0].plot(*np.array(sgd_params).T, label='SGD')\n",
        "axs[0].plot(*np.array(sam_params)[1::2].T, label='SAM Outer Steps', zorder=100)\n",
        "axs[0].plot(*np.array(sam_params)[::2].T, label='SAM Adv Steps', alpha=0.5)\n",
        "axs[0].legend(loc=4);\n",
        "\n",
        "axs[1].plot(*np.array(mom_params).T, label='Mom')\n",
        "axs[1].plot(*np.array(sam_mom_params)[1::2].T, label='SAM Mom Outer Steps', zorder=100)\n",
        "axs[1].plot(*np.array(sam_mom_params)[::2].T, label='SAM Mom Adv Steps', alpha=0.5)\n",
        "axs[1].legend(loc=4);\n",
        "\n",
        "axs[2].plot(*np.array(adam_params).T, label='Adam')\n",
        "axs[2].plot(*np.array(sam_adam_params)[4::5].T, label='SAM Adam Outer Steps', zorder=100)\n",
        "axs[2].plot(*np.array(sam_adam_params)[3::5].T, label='SAM Adam Adv Steps', alpha=0.5)\n",
        "axs[2].legend(loc=4);"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "8nVNiUsweApJ"
      },
      "source": [
        "As you can see, all three SAM optimizers find the smooth optimum, while all three standard optimizers get stuck in the sharp optimum.\n",
        "\n",
        "SAM and SAM Mom follow fairly similar paths (although SAM Mom is much faster), but Sam Adam actually passes through the sharp optimum on the way to the smooth optimum.\n",
        "\n",
        "The adversarial steps are quite different between the three SAM optimizers, demonstrating that the choice of both outer and inner optimizer have strong impacts on how the loss landscape gets explored."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "0s8UWJB-joV-"
      },
      "source": [
        "## Opaque Mode\n",
        "\n",
        "Here, we'll demonstrate how to use opaque mode on the same setting.\n",
        "\n",
        "The main difference is that we need to pass a gradient function to the update call. The gradient function needs to take as arguments params and an integer (indicating the current adversarial step). It's generally safe to ignore the second argument:\n",
        "```python\n",
        "grad_fn = jax.grad(\n",
        "    lambda params, _: loss(params, batch, and_other_args, to_loss))\n",
        "updates, sam_state = sam_opt.update(updates, sam_state, params, grad_fn=grad_fn)\n",
        "params = optax.apply_updates(params, updates)\n",
        "```"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "EwXxXOFVkjou"
      },
      "source": [
        "Here's the opaque drop-in SAM optimizer again.\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "UMvJqqxRjmIF"
      },
      "outputs": [],
      "source": [
        "lr = 0.01\n",
        "rho = 0.1\n",
        "opt = optax.sgd(lr)\n",
        "adv_opt = optax.chain(contrib.normalize(), optax.sgd(rho))\n",
        "sam_opt = contrib.sam(opt, adv_opt, sync_period=2, opaque_mode=True)\n",
        "\n",
        "sgd_opt = optax.sgd(lr)  # Baseline SGD optimizer"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "woThldyjjmIH"
      },
      "source": [
        "Here's an opaque momentum SAM optimizer."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "YcaxX4-4jmIH"
      },
      "outputs": [],
      "source": [
        "def sam_mom(lr=1e-3, momentum=0.1, rho=0.1, sync_period=2):\n",
        "  opt = optax.sgd(lr, momentum=momentum)\n",
        "  adv_opt = optax.chain(contrib.normalize(), optax.sgd(rho))\n",
        "  return contrib.sam(opt, adv_opt, sync_period=sync_period, opaque_mode=True)\n",
        "\n",
        "mom = 0.9\n",
        "sam_mom_opt = sam_mom(lr, momentum=mom)\n",
        "mom_opt = optax.sgd(lr, momentum=mom)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "0MXyU4WrjmIH"
      },
      "source": [
        "Here's an opaque Adam-based SAM optimizer."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "Fb8Cy5xgjmIJ"
      },
      "outputs": [],
      "source": [
        "def sam_adam(lr=1e-3, b1=0.9, b2=0.999, rho=0.03, sync_period=5):\n",
        "  \"\"\"A SAM optimizer using Adam for the outer optimizer.\"\"\"\n",
        "  opt = optax.adam(lr, b1=b1, b2=b2)\n",
        "  adv_opt = optax.chain(contrib.normalize(), optax.adam(rho))\n",
        "  return contrib.sam(opt, adv_opt, sync_period=sync_period, opaque_mode=True)\n",
        "\n",
        "sam_adam_opt = sam_adam(lr)\n",
        "adam_opt = optax.adam(lr)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "-z4NxcZujmIJ"
      },
      "outputs": [],
      "source": [
        "params = np.array([-0.4, -0.4])\n",
        "\n",
        "@chex.dataclass\n",
        "class Store:\n",
        "  params: chex.Array\n",
        "  state: optax.OptState\n",
        "  step: int = 0\n",
        "\n",
        "sam_store = Store(params=params, state=sam_opt.init(params))\n",
        "sgd_store = Store(params=params, state=sgd_opt.init(params))\n",
        "sam_mom_store = Store(params=params, state=sam_mom_opt.init(params))\n",
        "mom_store = Store(params=params, state=mom_opt.init(params))\n",
        "sam_adam_store = Store(params=params, state=sam_adam_opt.init(params))\n",
        "adam_store = Store(params=params, state=adam_opt.init(params))"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "bwLv3UTCjmIK"
      },
      "outputs": [],
      "source": [
        "def make_step(opt):\n",
        "  @jax.jit\n",
        "  def step(store):\n",
        "    value, grads = jax.value_and_grad(loss)(store.params)\n",
        "    if isinstance(store.state, contrib.SAMState):\n",
        "      updates, state = opt.update(\n",
        "          grads, store.state, store.params,\n",
        "          grad_fn=jax.grad(lambda p, _: loss(p)))  # NOTICE THE ADDITIONAL grad_fn ARGUMENT!\n",
        "    else:\n",
        "      updates, state = opt.update(grads, store.state, store.params)\n",
        "    params = optax.apply_updates(store.params, updates)\n",
        "    return store.replace(\n",
        "        params=params,\n",
        "        state=state,\n",
        "        step=store.step+1), value\n",
        "  return step"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "VRJiF7TWjmIK"
      },
      "outputs": [],
      "source": [
        "sam_step = make_step(sam_opt)\n",
        "sgd_step = make_step(sgd_opt)\n",
        "\n",
        "sam_mom_step = make_step(sam_mom_opt)\n",
        "mom_step = make_step(mom_opt)\n",
        "\n",
        "sam_adam_step = make_step(sam_adam_opt)\n",
        "adam_step = make_step(adam_opt)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "cwSnRxfQjmIK"
      },
      "outputs": [],
      "source": [
        "sam_vals = []\n",
        "sam_params = []\n",
        "sgd_vals = []\n",
        "sgd_params = []\n",
        "\n",
        "sam_mom_vals = []\n",
        "sam_mom_params = []\n",
        "mom_vals = []\n",
        "mom_params = []\n",
        "\n",
        "sam_adam_vals = []\n",
        "sam_adam_params = []\n",
        "adam_vals = []\n",
        "adam_params = []"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "m20mYyBHjmIK"
      },
      "outputs": [],
      "source": [
        "T = 4000\n",
        "for i in range(T):\n",
        "  sam_store, sam_val = sam_step(sam_store)\n",
        "  sgd_store, sgd_val = sgd_step(sgd_store)\n",
        "  sam_mom_store, sam_mom_val = sam_mom_step(sam_mom_store)\n",
        "  mom_store, mom_val = mom_step(mom_store)\n",
        "  sam_adam_store, sam_adam_val = sam_adam_step(sam_adam_store)\n",
        "  adam_store, adam_val = adam_step(adam_store)\n",
        "\n",
        "  sam_vals.append(sam_val)\n",
        "  sgd_vals.append(sgd_val)\n",
        "  sam_mom_vals.append(sam_mom_val)\n",
        "  mom_vals.append(mom_val)\n",
        "  sam_adam_vals.append(sam_adam_val)\n",
        "  adam_vals.append(adam_val)\n",
        "\n",
        "  sam_params.append(sam_store.params)\n",
        "  sgd_params.append(sgd_store.params)\n",
        "  sam_mom_params.append(sam_mom_store.params)\n",
        "  mom_params.append(mom_store.params)\n",
        "  sam_adam_params.append(sam_adam_store.params)\n",
        "  adam_params.append(adam_store.params)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "zlDP-42ajmIK"
      },
      "outputs": [],
      "source": [
        "ts = np.arange(T)\n",
        "fig, axs = plt.subplots(6, figsize=(10, 12))\n",
        "axs[0].plot(ts, sgd_vals, label='SGD')\n",
        "axs[0].plot(ts, sam_vals, label='SAM', lw=3, zorder=100)\n",
        "axs[0].legend();\n",
        "\n",
        "axs[1].plot(ts, sgd_vals, label='SGD')\n",
        "axs[1].plot(ts * 2, sam_vals, label='2 * SAM', lw=3)\n",
        "axs[1].legend();\n",
        "\n",
        "axs[2].plot(ts, mom_vals, label='Mom')\n",
        "axs[2].plot(ts, sam_mom_vals, label='SAM Mom', lw=3, zorder=100)\n",
        "axs[2].legend();\n",
        "\n",
        "axs[3].plot(ts, mom_vals, label='Mom')\n",
        "axs[3].plot(ts * 2, sam_mom_vals, label='2 * SAM Mom', lw=3)\n",
        "axs[3].legend();\n",
        "\n",
        "axs[4].plot(ts, adam_vals, label='Adam')\n",
        "axs[4].plot(ts, sam_adam_vals, label='SAM Adam', lw=3, zorder=100)\n",
        "axs[4].legend();\n",
        "\n",
        "axs[5].plot(ts, adam_vals, label='Adam')\n",
        "axs[5].plot(ts * 5, sam_adam_vals, label='5 * SAM Adam', lw=3)\n",
        "axs[5].legend();"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "NLAJFJ-SjmIK"
      },
      "source": [
        "The behavior is identical to transparent mode, but the percieved number of gradient steps is half as many as in transparent mode (or 1/5 as many for SAM Adam)."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "mY5FzqMLjmIK"
      },
      "outputs": [],
      "source": [
        "fig, axs = plt.subplots(ncols=3, figsize=(8 * 3, 6))\n",
        "axs[0].plot(*np.array(sgd_params).T, label='SGD')\n",
        "axs[0].plot(*np.array(sam_params).T, label='SAM', zorder=100)\n",
        "axs[0].legend(loc=4);\n",
        "\n",
        "axs[1].plot(*np.array(mom_params).T, label='Mom')\n",
        "axs[1].plot(*np.array(sam_mom_params).T, label='SAM Mom')\n",
        "axs[1].legend(loc=4);\n",
        "\n",
        "axs[2].plot(*np.array(adam_params).T, label='Adam')\n",
        "axs[2].plot(*np.array(sam_adam_params).T, label='SAM Adam')\n",
        "axs[2].legend(loc=4);"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "P_MjRgofjmIK"
      },
      "source": [
        "The behavior is identical to transparent mode here as well, but we don't get to see the adversarial updates."
      ]
    }
  ],
  "metadata": {
    "colab": {
      "last_runtime": {
        "build_target": "//learning/grp/tools/ml_python:ml_notebook",
        "kind": "private"
      },
      "private_outputs": true,
      "provenance": [
        {
          "file_id": "1ap7lwdf3vgoQdyNogmSVfncYZcH1ijch",
          "timestamp": 1697129954516
        }
      ],
      "toc_visible": true
    },
    "kernelspec": {
      "display_name": "Python 3",
      "name": "python3"
    },
    "language_info": {
      "name": "python"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}