-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathhw2.jl
2315 lines (1913 loc) · 80.4 KB
/
hw2.jl
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
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
### A Pluto.jl notebook ###
# v0.19.12
#> [frontmatter]
#> title = "HW2 - Automatic differentiation"
#> date = "2022-09-23"
using Markdown
using InteractiveUtils
# ╔═╡ ddbf8ae6-39b6-11ed-226e-0d38991ed784
begin
using BenchmarkTools
using ChainRulesCore
using ForwardDiff
using LinearAlgebra
using Plots # may take a long time to load
using PlutoTeachingTools
using PlutoUI
using ProgressLogging
using Zygote # may take a long time to load
end
# ╔═╡ ddbba011-f413-4804-b29b-fdc4efe2b3b3
md"""
Homework 2 of the MIT Course [_Julia: solving real-world problems with computation_](https://github.com/mitmath/JuliaComputation)
Release date: Friday, Sep 24, 2022 (version 2)
**Due date: Friday, Oct 1, 2022 at 11:59pm EST**
Submission by: Jazzy Doe (jazz@mit.edu)
"""
# ╔═╡ 9a1453a3-bfad-4212-ac19-a4b6c7df5b16
student = (name = "Jazzy Doe", kerberos_id = "jazz")
# ╔═╡ 9f6254b5-bc06-469c-a0ef-5ee31ac75233
md"""
The following cell is quite slow, so go grab a coffee while it runs!
Package loading times are one of the main pain points of Julia, and people are actively working to make them shorter.
"""
# ╔═╡ f447c167-2bcb-4bf3-86cd-0f40f4e54c97
TableOfContents()
# ╔═╡ a405d214-4348-4692-999e-0e890bd91e5d
md"""
# HW2 - Automatic differentiation
"""
# ╔═╡ d19834fc-edd1-433b-8bfc-6022fd7e3239
md"""
Throughout this homework, whenever a new function (or macro) is introduced, it is a good idea to check out its documentation using Pluto.
Just create a new cell and type in `?` followed by the function name, then the "Live docs" tab will open automatically.
Once the "Live docs" tab is open, clicking on a function name also displays its documentation.
We also try to include the link to the GitHub repository of every external package we use.
Once you're on the repository, look for a badge like [](https://youtu.be/dQw4w9WgXcQ) or [](https://youtu.be/dQw4w9WgXcQ), it will take you to the appropriate documentation page.
"""
# ╔═╡ 7493915c-53b4-4284-bb7f-33cac680f759
md"""
# 0. Calculus refresher
"""
# ╔═╡ 1cfba628-aa7b-4851-89f1-84b1a45802b3
md"""
## Scalar functions
"""
# ╔═╡ 3829f016-a7cd-4ce6-b2d4-1c84da8fdb97
md"""
Let $f : \mathbb{R} \longrightarrow \mathbb{R}$ be a function with scalar input and output.
When we say that $f$ is differentiable at $x \in \mathbb{R}$, we mean that there is a _number_ $f'(x) \in \mathbb{R}$ such that for any perturbation $h \in \mathbb{R}$,
$$f(x+h) = f(x) + f'(x)h + o(h)$$
In other words, $f$ can be approximated with a straight tangent line around $x$.
Furthermore, the error is negligible compared with the distance $\lvert h \rvert$ to $x$, at least for small enough values of $\lvert h \rvert$ (that is what the $o(h)$ means).
The number $f'(x)$ is called the _derivative_ of $f$ at $x$, and it gives the slope of the tangent.
"""
# ╔═╡ 755ff203-43d8-488f-a075-14a858b0a096
md"""
To generalize derivatives in higher dimensions, we will need to shift our focus from lines to functions.
Indeed, a straight line with slope $f'(x)$ is nothing but a linear function $h \longmapsto f'(x)h$.
So computing a derivative boils down to the following question:
_What is the best linear approximation of my function around a given point?_
"""
# ╔═╡ fd6dd009-2a52-46d1-b1a8-5f094e8c1d98
md"""
## Vector functions
"""
# ╔═╡ 4d9d2f52-c406-4a7c-8b0e-ba5af7ebc3d8
md"""
Let $f: \mathcal{A} \longrightarrow \mathcal{B}$ be a function between two normed vector spaces.
When we say that $f$ is differentiable at $x \in \mathcal{A}$, we mean that there is a _linear function_ $f'(x): \mathcal{A} \longrightarrow \mathcal{B}$ such that for any perturbation $h \in \mathcal{A}$,
$$f(x + h) = f(x) + f'(x)(h) + o(\lVert h \rVert)$$
The linear function $f'(x)$ is called the _derivative_ of $f$ at $x$.
"""
# ╔═╡ de4df88a-2a55-4a02-aeaf-f02242b6c52f
md"""
When $\mathcal{A} = \mathbb{R}^n$ and $\mathcal{B} = \mathbb{R}^m$ are both Euclidean spaces, we can always find a matrix $J_f(x) \in \mathbb{R}^{m \times n}$ that satisfies
$$f'(x)(h) = J_f(x) h$$
In the previous equation, the left hand side is the application of the function $f'(x)$ to the vector $h$, while the right hand side is a product between the matrix $J_f(x)$ and the same vector $h$.
The matrix $J_f(x)$ is called the _Jacobian_ of $f$ at $x$.
"""
# ╔═╡ e22cec4a-03d3-4821-945b-9283e16207a8
md"""
It can be expressed with partial derivatives: if $x = (x_1, ..., x_n)$ and $f(x) = (f_1(x), ..., f_m(x))$, then
$$J_f(x) = \begin{pmatrix}
\frac{\partial f_1(x)}{\partial x_1} & \frac{\partial f_1(x)}{\partial x_2} & \cdots & \frac{\partial f_1(x)}{\partial x_n} \\
\frac{\partial f_2(x)}{\partial x_1} & \frac{\partial f_2(x)}{\partial x_2} & \cdots & \frac{\partial f_2(x)}{\partial x_n} \\
\vdots & \vdots & \ddots & \vdots \\
\frac{\partial f_m(x)}{\partial x_1} & \frac{\partial f_m(x)}{\partial x_2} & \cdots & \frac{\partial f_m(x)}{\partial x_n} \\
\end{pmatrix}$$
However, it is good practice to learn how to manipulate Jacobians in matrix form, without needing to compute individual coefficients.
"""
# ╔═╡ 19fd4ce6-fc2e-4047-b265-7b54e9bbdad4
md"""
# 1. Memory & performance
"""
# ╔═╡ 38a6618a-00e9-4565-aaef-4893afcb3181
md"""
Many people use Julia for high performance scientific computations.
But it takes some knowledge and practice to get to that level.
So buckle up, because your journey to lightning fast code starts... now!
In this section, we discuss two topics:
- How to measure code performance
- How to improve it with a clever use of memory
There are other tricks you can learn, mostly related to types and dispatch, but we will get to them later in the class.
"""
# ╔═╡ 9ba8d153-e2c9-4387-a487-fb5a25f5808b
md"""
## Benchmarking
"""
# ╔═╡ 25d27d5a-dcaa-464c-ba44-9aea9ea8be38
md"""
To start with, let us note that Julia already has a useful built-in macro called `@time`.
When you put it before a function call, it measures the CPU time, memory use and number of allocations required.
"""
# ╔═╡ d0263b55-0f11-4a37-9837-bb4f9e322aa8
@time rand(1000, 1000);
# ╔═╡ d1079990-5d9a-495c-9dbf-d9ea07c5c8f7
md"""
But `@time` has a few drawbacks:
- it only runs the function one time, which means estimates are noisy
- it includes compilation time if the function has never been run before
- it can be biased by [global variables](https://docs.julialang.org/en/v1/manual/performance-tips/#Avoid-untyped-global-variables)
Here are some examples.
"""
# ╔═╡ 751234f4-6957-4273-84e9-9d048c756fa7
@time cos.(rand(1000, 1000));
# ╔═╡ 2e4ac856-fe22-426d-b58b-f3adbacdee8a
md"""
The first time you run the previous cell, most of the time will actually be spent compiling the function.
If you run it a second time, the benchmarking result will be completely different.
"""
# ╔═╡ e75e2ea0-bf1a-4519-87a2-efb61736ab44
let
x = rand(1000, 1000)
sum(abs2, x) # run once to compile
@time sum(abs2, x)
end;
# ╔═╡ 6ebe2c16-400b-40a0-bec6-e52d2858e83a
md"""
In the previous cell, there is no reason for the sum to allocate anything: this is just an artefact due to the global variable `x`.
"""
# ╔═╡ 9aa600b1-9c39-430a-88d4-169c5d84e145
md"""
For all of these reasons, [`BenchmarkTools.jl`](https://github.com/JuliaCI/BenchmarkTools.jl) is a much better option.
Its `@btime` macro does basically the same job as `@time`, but runs the function several times and circumvents global variables, as long as they are "interpolated" with a `$` sign.
"""
# ╔═╡ 43cfe774-4ed1-4f4f-985a-c261c4d569bf
@btime rand(1000, 1000);
# ╔═╡ 88103471-6f2c-4604-83cc-0d76645776d7
md"""
This benchmark is pretty comparable to the one given by `@time`.
"""
# ╔═╡ 5d9c5359-d0a9-4a0a-853e-3fd0028f23df
@btime sin.(rand(1000, 1000));
# ╔═╡ 6bacff8b-ac8c-46b0-adeb-7d8b1aab85f2
md"""
This benchmark does not include compilation time, because the first run of the function is just one of many.
"""
# ╔═╡ 86399001-e7c4-4733-b476-503650c11e0c
let; x = randn(1000, 1000); @btime sum(abs2, $x); end;
# ╔═╡ 0817247f-f9ae-48cc-9966-dd451c136d43
md"""
This benchmark shows zero allocation, which is what we actually expect.
"""
# ╔═╡ 1d1d83b0-8669-452c-90ca-26c1396c822a
md"""
!!! danger "Task"
Write a function that compares matrix addition and multiplication based on the time per operation.
"""
# ╔═╡ 2ded206d-e563-4752-a0b1-19402e1e4f52
hint(md"
Unlike `@btime`, which prints a bunch of information but returns the result of the function, `@belapsed` actually returns the elapsed CPU time.
Don't forget to interpolate the arguments.
Remember that for a given size $n$, addition requires $n^2$ operations while multiplication requires $2n^3$ operations.
You should divide the output of `@belapsed` by these factors.
")
# ╔═╡ 5b47082b-d080-4243-90a2-5d98b82451d4
function compare_add_mul(n)
# write your code here
end
# ╔═╡ 89b1f353-523a-4a4c-aee4-9b6e36b944fb
compare_add_mul(10)
# ╔═╡ 4b1a6ce2-b57d-466a-97cd-35036689fe43
compare_add_mul(100)
# ╔═╡ fe1f4c0e-becb-4058-a069-be213622aa92
md"""
!!! danger "Task"
Plot the normalized time per operation for matrix addition and multiplication, using sizes $n \in \{3, 10, 30, 100, 300\}$. Comment on what you observe.
"""
# ╔═╡ eb0d58fc-3348-47f9-966c-e7f9f316ddb7
hint(md"
The loop over $n$ may take a little time, don't be scared.
You can put the `@progress` macro from [`ProgressLogging`](https://github.com/JuliaLogging/ProgressLogging.jl) in front of the `for` keyword if you want to track its progress.
Use the [`Plots.jl`](https://github.com/JuliaPlots/Plots.jl) package for visualization.
The function `plot` will let you create an empty plot with the properties you need (like `xscale=:log10` or `xlabel=\"size\"`).
The function `scatter!` will allow you to modify it by adding series of dots.
")
# ╔═╡ 11f3c0d4-0609-4446-aa84-4db3d93e93b0
# write your code here
# ╔═╡ c22a890c-a308-4d1b-be4b-d78f93693a9c
md"""
## Memory management
"""
# ╔═╡ 48511240-20d1-41b6-bc7b-a8ecfc3aa06d
md"""
Since Julia is a high-level language, you don't need to care about memory to write correct code.
New objects are allocated transparently, and once you no longer need them, the Garbage Collector (GC) automatically frees their memory slots.
However, in many cases, memory management is a performance bottleneck.
If you want to write fast code, you might need to work "in place" (mutating existing arrays), as opposed to "out of place" (creating many temporary arrays).
This is emphasized [several](https://docs.julialang.org/en/v1/manual/performance-tips/#Measure-performance-with-[@time](@ref)-and-pay-attention-to-memory-allocation) [times](https://docs.julialang.org/en/v1/manual/performance-tips/#Pre-allocating-outputs) in the Julia performance tips.
"""
# ╔═╡ ffb8851d-c7e8-47ae-ac9d-96baf0774ca3
md"""
A common pattern is broadcasted operations, which can look like `x .+ y` (the `.` goes in front for short operators) or `exp.(x)` (the `.` goes behind for functions).
They allow you to work directly with array components, instead of allocating new arrays.
This leads to performance gains, as explained [here](https://docs.julialang.org/en/v1/manual/performance-tips/#More-dots:-Fuse-vectorized-operations).
"""
# ╔═╡ a6eb6028-acca-447a-9e55-e60ecd3c6f84
md"""
!!! danger "Task"
Try to explain the difference in speed and memory use between the following code snippets.
"""
# ╔═╡ f2bedf2b-2dfe-4392-ba2a-add10882af07
let
x = rand(100, 100)
y = rand(100, 100)
@btime $x += 2 * $y
end;
# ╔═╡ f504954b-ac63-4843-8891-b1ca0e5ae58b
let
x = rand(100, 100)
y = rand(100, 100)
@btime $x .+= 2 .* $y
end;
# ╔═╡ 1da14b09-5d62-42cc-b9b4-a5a6ddc34181
hint(md"`x += y` is syntactically equivalent to `x = x + y`.")
# ╔═╡ a9472534-e32b-4323-8dfc-e00b9f31f8e0
md"""
> Write your answer here
"""
# ╔═╡ ecfe4d79-b1c6-4a6d-a9d7-a563a26e32cd
md"""
Whenever possible, you may also want to use or write mutating versions of critical functions.
By convention, such functions get a `!` suffix to warn about their side effects.
"""
# ╔═╡ 83423082-2d3a-42a1-b1db-ed267399cb31
md"""
!!! danger "Task"
Write a function that compares mutating and non-mutating matrix multiplication.
"""
# ╔═╡ fb416cfd-f9ee-4d7d-9e83-056e81c422e0
hint(md"
Take a look at the documentation for the three-argument function `mul!(C, A, B)`, and compare it with `A * B`.
Don't forget to interpolate the arguments
")
# ╔═╡ d0020df6-62a1-4000-b8cf-ceacb8014a0b
# write your code here
# ╔═╡ d8301150-7b08-45b6-a986-d21574eee91b
md"""
# 2. Autodiff works... almost always
"""
# ╔═╡ 1f40437c-0419-4fc0-96ae-a8130efaa36a
md"""
## Differentiable programming
"""
# ╔═╡ 8419603a-3c5c-45a0-9a70-4a74347a7ad7
md"""
In scientific computing, differentiation plays a central role.
Gradients, Jacobians and Hessians are used everywhere, from optimization algorithms to differential equations or sensitivity analysis.
Unfortunately, the functions involved may be very complicated, sometimes without an explicit formula.
That is where _differentiable programming_ comes into play: the idea that you can use computer programs to represent complex functions, and then differentiate through these programs with automatic differentiation.
"""
# ╔═╡ 4f9d3c2e-1ec8-4337-b49b-e0dc1d63bc62
md"""
The Julia ecosystem is very interesting in this regard, because its autodiff packages are compatible with a large fraction of the language itself.
Conversely, major Python autodiff packages like `PyTorch` or `TensorFlow` expect the user to only manipulate custom tensors, which restricts their generality.
An extensive list of packages is available on the JuliaDiff [web page](https://juliadiff.org/).
Right now, the most widely used are probably:
- [`ForwardDiff.jl`](https://github.com/JuliaDiff/ForwardDiff.jl) for forward mode autodiff
- [`Zygote.jl`](https://github.com/FluxML/Zygote.jl) for reverse mode autodiff
Here is an example showing how to use them for Jacobian computation.
"""
# ╔═╡ 7476a638-5eca-47cc-9a01-41f30b9dbf9d
function powersum(x; p=5)
return sum(x .^ i for i in 0:p)
end
# ╔═╡ d0d580d4-8e92-4d46-8177-67f52fbb3934
powersum(1:3)
# ╔═╡ c5784ec1-17cf-4897-8cd3-ff81998b9d9c
let
x = rand(3)
J1 = ForwardDiff.jacobian(powersum, x)
J2 = Zygote.jacobian(powersum, x)[1]
J1, J2
end
# ╔═╡ 387d145f-e77c-4e13-89b7-fc8733215694
md"""
## The limitations of autodiff packages
"""
# ╔═╡ 3790f106-9895-4425-a16f-5c5e0857e99e
md"""
Alas, every autodiff package comes with its own limitations.
Here are the main ones you should be aware of:
- `ForwardDiff.jl` requires functions that work with generic number types, not just `Float64` for example. The reason is that forward mode relies on numbers of type `Dual` (which store both a quantity and its derivative)
- `Zygote.jl` requires functions that avoid mutating arrays. The reason is that array mutation gives rise to several nodes in the computational graph for a single variable in the code, which is complicated to handle from an implementation perspective.
"""
# ╔═╡ 945a16d3-805c-40c9-9166-5120743bd3d7
md"""
!!! danger "Task"
Write a function that does the same computation as `powersum`, but for which `ForwardDiff.jl` will throw an error.
"""
# ╔═╡ 728c8956-9911-47d5-a021-df224e3f5b90
hint(md"
Modify the type annotation of `x` to avoid accepting generic numbers.
")
# ╔═╡ 3716d3cc-8706-41bf-873d-193543cb0514
function powersum_breakforwarddiff(x; p=5)
# write your code here
end
# ╔═╡ 87c72b22-8c81-4062-8a9c-40902f83a623
powersum(1:3), powersum_breakforwarddiff(1:3)
# ╔═╡ 1362cd95-6a87-44e3-980d-014496afce85
let
x = rand(3)
# this should throw "No method matching powersum_breakforwarddiff(Vector{Dual})"
ForwardDiff.jacobian(powersum_breakforwarddiff, x)
end
# ╔═╡ 46075912-60b7-46d2-88c9-a13a8b015e0b
md"""
!!! danger "Task"
Write a function that does the same computation as `powersum`, but for which `Zygote.jl` will throw an error.
"""
# ╔═╡ f8ba8857-ece1-4cec-b7f2-2a8bc8bfb1d9
hint(md"
Set up an answer vector `y` initialized to `ones(eltype(x), length(x))`, and write a loop that updates it with successive powers of `x`.
")
# ╔═╡ cf13543a-9dd4-40ef-9523-5953e9db2c78
function powersum_breakzygote(x; p=5)
# write your code here
end
# ╔═╡ 0736648c-a181-4352-8b4e-bacf745fda64
powersum(1:3), powersum_breakzygote(1:3)
# ╔═╡ 95dd7822-ef43-4629-bb42-ddb15bd1f965
let
x = rand(3)
# this should throw "Mutating arrays is not supported..."
Zygote.jacobian(powersum_breakzygote, x)[1]
end
# ╔═╡ 786b7ea2-7827-4cab-abbb-786abe935cc3
md"""
Usually, it is quite easy to write type-generic code that works with `ForwardDiff.jl`.
On the other hand, sometimes mutation is inevitable for performance reasons, which means `Zygote.jl` will be mad at us.
So how do we get the best of both worlds, _performance AND differentiability_?
The answer is: by teaching `Zygote.jl` a custom differentiation rule.
"""
# ╔═╡ 4440f39c-51e5-4ffd-8031-96d4a760270c
md"""
## The role of custom differentiation rules
"""
# ╔═╡ bfb3280e-638f-4e8f-8e37-d5f8fd75541d
md"""
Autodiff packages have two main ingredients:
- a set of differentiation rules for built-in functions (`+`, `-`, `*`, `/`, `exp`, ...)
- a way to compose these basic functions and their derivatives (using the chain rule)
"""
# ╔═╡ 7f6e72fd-aacc-47a8-a496-25794c60343c
md"""
The [`ChainRules.jl`](https://github.com/JuliaDiff/ChainRules.jl) package is an attempt to provide unified differentiation rules for Julia's whole autodiff ecosystem.
It contains rules for most of the functions in the Julia standard library, but also allows users to define custom rules.
Since `Zygote.jl` cannot handle mutation out of the box, we must define a custom reverse rule for any function involving mutation.
This will allow `Zygote.jl` to differentiate it "blindly", without looking inside.
"""
# ╔═╡ 55160454-2738-4911-be15-29f484f610db
md"""
Without further ado, we show the definition of a custom reverse rule for the following function.
It probably similar to the one that you used to break `Zygote.jl` earlier, so of course it will behave in the same way until we give it a differentiation rule.
"""
# ╔═╡ e90098ec-a9c3-4204-95f7-88adeb74ee50
function powersum_okayzygote(x; p=5)
y = zeros(eltype(x), length(x))
for i in 0:p
y .+= x .^ i
end
return y
end
# ╔═╡ 7b92051d-4015-4e22-b6b9-41462e2cc54f
powersum(1:3), powersum_okayzygote(1:3)
# ╔═╡ 4eef090f-29b1-44e1-929a-98162719ae93
md"""
If we want to teach a derivative to `Zygote.jl`, we have to know how to compute it.
"""
# ╔═╡ 32f6a219-f69b-4085-ba4b-5c7dc3ca2155
function powersum_okayzygote_jacobian(x; p=5)
J = zeros(eltype(x), length(x), length(x))
for i in 1:p
J .+= Diagonal(i .* (x .^ (i-1)))
end
return J
end
# ╔═╡ ffffadbb-5fcd-443d-97fb-b6d372029814
md"""
Custom reverse rules are created by writing a new method for the `ChainRulesCore.rrule` function.
For technical reasons, the reverse rule does not work with the Jacobian directly, but instead computes _vector-Jacobian products_ (VJPs) of the form $v^\top J_f(x)$ (see section 4).
"""
# ╔═╡ 19198826-15a0-432d-abe2-ae5ead6869f5
function ChainRulesCore.rrule(fun::typeof(powersum_okayzygote), x; p=5)
y = powersum_okayzygote(x; p=p)
J = powersum_okayzygote_jacobian(x; p=p)
function vector_jacobian_product(v)
return (NoTangent(), J' * v)
end
return y, vector_jacobian_product
end
# ╔═╡ 0d762ed4-dfb9-433f-8ded-1ae653ad87c2
begin
rrule_syntax = md"""
The arguments given to `rrule` are all the arguments of the function we want to differentiate (in this case `powersum_okayzygote`), plus an additional first argument `fun` which is a function.
We define our method to only accept the type of `powersum_okayzygote` itself, so that autodiff packages can recognize it and dispatch on the appropriate rule for each function.
So we actually do not need `fun` in the body of the `rrule`, and we could also have used an empty argument:
```
function ChainRulesCore.rrule(::typeof(powersum_okayzygote), x; p=5)
...
end
```
The output of `rrule` is a couple that contains 1) the return value of the function `powersum_okayzygote` and 2) a nested function called `vector_jacobian_product`, which is used during reverse mode autodiff.
This nested function computes a VJP for each positional argument of `rrule`, in this case `fun` and `x`.
By convention, we do not compute VJPs for keyword arguments, since one does not usually differentiate with respect to those.
Most of the time, the VJP with respect to `fun` is `NoTangent()`, since the function `fun` rarely has internal parameters.
On the other hand, the VJP with respect to `x` is the interesting part.
It is given as `J' * v` instead of `v' * J` because we want a column vector instead of a row vector.
We precompute the Jacobian matrix `J` outside of the `vector_jacobian_product` because it can be reused with several vectors `v`.
"""
Foldable("Unfold to understand the syntax of the reverse rule", rrule_syntax)
end
# ╔═╡ ef28a71e-74f4-40dd-a72d-1a51628fd01b
md"""
Thanks to this new rule, `Zygote.jl` is now able to differentiate through our mutating power sum.
"""
# ╔═╡ f9ca3e33-243c-45c8-b646-587aa7d2d902
md"""
By now, you may have a question on your mind.
What is the point of autodiff if I need to work out derivatives by hand anyway?
Indeed, when `Zygote.jl` is unable to handle your function, you may need to provide derivatives manually.
But then, you can insert your function within a larger computational graph (like a neural network), and the rest of the derivatives will be computed without your help.
In other words, your efforts are only required for a few performance-critical functions, and the rest is taken care of automatically.
"""
# ╔═╡ c7a0dbbe-89e6-4759-a57f-b367fbeba62e
md"""
Let us see what that looks like by composing several functions.
"""
# ╔═╡ 9a8f7f42-2677-43ff-a280-3b75df6258e1
function big_composition(x)
y = vcat(x, -x)
z = powersum_okayzygote(x)
return sum(abs, z)
end
# ╔═╡ 7b3551c2-22f7-47dd-82dc-b817d7e0f1fb
md"""
Isn't that wonderful?
"""
# ╔═╡ f6330892-3379-4e0d-a007-c451a465bd06
md"""
# 3. Application to linear regression
"""
# ╔═╡ 6d848043-e5bc-4beb-a18a-004d4cac5c23
md"""
Linear regression is perhaps the most basic form of machine learning.
Given a matrix of features $M \in \mathbb{R}^{m \times n}$ and a vector of targets $y \in \mathbb{R}^m$, we approximate $y$ by $M x$, where $x \in \mathbb{R}^n$ is a vector of parameters (feature weights).
"""
# ╔═╡ fc84dce4-779c-4377-af2a-cda7e453f382
md"""
## Computing the squared errors
"""
# ╔═╡ d76d5ddc-fe59-47f4-8b56-6f704b486ebc
md"""
One way to measure the quality of the approximation for a given $x$ is to compute the squared error on all components of $y$.
Let us denote by $\odot$ the componentwise product between vectors (which is the same as `.*` in Julia).
We define the function
$$f: x \in \mathbb{R}^n \longmapsto (Mx - y) \odot (Mx - y) = \begin{pmatrix} (Mx - y)_1^2 \\ \vdots \\ (Mx - y)_m^2 \end{pmatrix} \in \mathbb{R}^m$$
"""
# ╔═╡ 9ef1e014-5a7d-4b17-98de-0cf51d788bfa
md"""
!!! danger "Task"
Implement the function $f$ in a way that does not mutate arrays.
"""
# ╔═╡ f8cd5dce-6a4c-4c6c-b2d5-7ec56132e95e
function f(x; M, y)
# write your code here
end
# ╔═╡ c7ee9795-2c7a-480a-9269-440a9227c591
let
n, m = 3, 5
M = rand(m, n)
y = rand(m)
x = rand(n)
f(x; M=M, y=y)
end
# ╔═╡ 28f31ef9-27ea-4e94-8f03-89b0f6cfa0d1
md"""
!!! danger "Task"
Implement the function $f$ in the most efficient way you can, by pre-allocating and mutating the output vector `e`.
Compare the performance of both implementations.
"""
# ╔═╡ 1676ec54-bd96-4892-aa08-3ae831b537bb
hint(md"Modify `e` step-by-step: start with $Mx$, then $Mx-y$, and finally $(Mx-y) \odot (Mx-y)$.")
# ╔═╡ ea16d4c6-d6e4-46fa-a721-fa5a0f2ff021
function f!(e, x; M, y)
# write your code here
end
# ╔═╡ bd37c58d-8544-40b1-a0b5-ea03ec5692a8
let
n, m = 3, 5
M = rand(m, n)
y = rand(m)
x = rand(n)
e = rand(m)
f(x; M=M, y=y), f!(e, x; M=M, y=y)
end
# ╔═╡ 5bbd690b-6a98-4dbf-a8c4-581ac77a4da5
let
n, m = 3, 5
M = rand(m, n)
y = rand(m)
x = rand(n)
e = rand(m)
@btime f($x; M=$M, y=$y)
@btime f!($e, $x; M=$M, y=$y)
end;
# ╔═╡ cc224a30-81bf-4a2c-b636-40ff5c941bb6
md"""
## Differentiating the squared errors
"""
# ╔═╡ 3d20c24c-469b-4f0d-9936-705e42033ded
md"""
If we want to find the best possible $x$, we can do it by minimizing the sum of the components of $f(x)$ (_e.g._ with gradient descent).
We may also wish to use the function $f$ within a neural network.
In both cases, it is essential to differentiate $f$ with respect to its input $x$ (assuming $M$ and $y$ are fixed).
"""
# ╔═╡ bf6c5fc8-8283-46d4-aa67-416d53f7d315
md"""
!!! danger "Task"
Try to compute the Jacobian of `f` and `f!` with `Zygote.jl`.
"""
# ╔═╡ d00bf3fd-9bd8-4b11-b755-a85f0f8644cb
let
n, m = 3, 5
M = rand(m, n)
y = rand(m)
x = rand(n)
Zygote.jacobian(x -> f(x; M=M, y=y), x)[1]
end
# ╔═╡ a80b3a0f-53d1-473e-9bea-2494a85ac511
let
n, m = 3, 5
M = rand(m, n)
y = rand(m)
x = rand(n)
e = rand(m)
# this should throw "Mutating arrays is not supported..."
Zygote.jacobian(x -> f!(e, x; M=M, y=y), x)[1]
end
# ╔═╡ ab398337-adb5-48fa-ae1b-4c9499438097
md"""
Once you are done with this section, you will be able to do this without encountering an error. Yay!
"""
# ╔═╡ ae7b2114-de91-4f1b-8765-af5e02cc1b63
md"""
!!! danger "Task"
Work out the derivative of the function $f$ at a point $x$.
"""
# ╔═╡ e4aedbd4-a609-4eaf-812b-d2f3d6f4df3d
hint(md"
Write $f(x+h)$ as a componentwise product, and then expand it as you would do with a regular product.
You are allowed to do that since the componentwise product is bilinear.
Then identify three parts in the resulting expression: $f(x)$, a linear function of $h$, and a term that is of order $\lVert h \rVert^2$ (in other words, negligible).
")
# ╔═╡ b8974b20-d8dc-4109-a64e-585c7afdb484
md"""
> Write your answer here
"""
# ╔═╡ bd10d753-eea6-4798-939c-8e5551d40c5c
md"""
!!! danger "Task"
Deduce the Jacobian matrix of the function $f$ at a point $x$. Check that its size is coherent.
"""
# ╔═╡ 2f95afd6-1418-44bb-9868-970dbe888500
hint(md"
A componentwise product between two vectors $a \odot b$ can also be interpreted as the multiplication by a diagonal matrix $D(a) b$.
Using this with $a = 2(Mx - y)$ and $b = Mh$ should help you recognize the Jacobian matrix.
For checking, remember that $M$ has size $m \times n$.
")
# ╔═╡ 06e91432-935f-4d7c-899f-d7968a10a78e
md"""
> Write your answer here
"""
# ╔═╡ c7efc656-ae9b-4eef-b0cd-3afe3852d396
md"""
!!! danger "Task"
Implement a function computing the Jacobian matrix $J_f(x)$ at a point $x$.
Check your result using finite differences.
"""
# ╔═╡ ca4b41dd-353e-498d-a461-648c582cb999
hint(md"You may want to use the `Diagonal` constructor from [`LinearAlgebra`](https://docs.julialang.org/en/v1/stdlib/LinearAlgebra/).")
# ╔═╡ c5fc8f3a-ed90-41ec-b4b9-1172a41e3adc
function Jf(x; M, y)
# write your code here
end
# ╔═╡ 40e13883-dd9a-43b9-9ef7-1069ef036846
let
n, m = 3, 5
M = rand(m, n)
y = rand(m)
x = rand(n)
h = 0.001 .* rand(n)
diff1 = f(x + h; M=M, y=y) .- f(x; M=M, y=y)
diff2 = Jf(x; M=M, y=y) * h
diff1, diff2
end
# ╔═╡ 7c7bdbd9-edd5-4142-a765-4c498761f7e7
md"""
## Custom rule, from slow to fast
"""
# ╔═╡ 8569cd7b-890f-4b04-a6d5-c92a70a226ab
md"""
!!! danger "Task"
Define a custom reverse rule for `f2!` (because of a Pluto bug we couldn't use `f!` directly). Check that `Zygote.jl` is now able to compute its Jacobian.
"""
# ╔═╡ cf250e37-ed37-47cd-b689-8e2596f9fdc5
f2!(e, x; M, y) = f!(e, x; M, y)
# ╔═╡ 8f46db4a-cc94-4497-aad8-0fc4b0cfa1e3
hint(md"Beware: you will need to give a VJP with respect to `rrule` arguments `fun`, `e` and `x`. Use `NoTangent()` for `fun` and `ZeroTangent()` for `e`.")
# ╔═╡ dccf9f6d-82a6-423c-bbe5-22c5a8c2f5e4
function ChainRulesCore.rrule(::typeof(f2!), e, x; M, y)
# write some code here
function vector_jacobian_product(v)
# and some code there
end
return e, vector_jacobian_product
end
# ╔═╡ ffd6df27-c0e5-44be-aee9-2c7a9d4fb5c0
let
x = rand(3)
ChainRulesCore.rrule(powersum_okayzygote, x) # trick Pluto's dependency handler
J = powersum_okayzygote_jacobian(x)
J_zygote = Zygote.jacobian(powersum_okayzygote, x)[1]
J, J_zygote
end
# ╔═╡ 0cee5c93-266c-4be3-9997-20728cf11921
let
x = rand(3)
ChainRulesCore.rrule(powersum_okayzygote, x) # trick Pluto's dependency handler
Zygote.gradient(big_composition, x)[1]
end
# ╔═╡ bbe25d4e-952b-4ed5-b20e-24b3dcd30495
md"""
!!! danger "Task"
Uncomment and run the following cell once the `rrule` above is complete.
"""
# ╔═╡ 77eac64f-eac5-4d12-8acf-5b5070e60858
# let
# n, m = 3, 5
# M = rand(m, n)
# y = rand(m)
# x = rand(n)
# e = rand(m)
# ChainRulesCore.rrule(f2!, e, x; M=M, y=y) # trick Pluto's dependency handler
# J1 = Zygote.jacobian(x -> f(x; M=M, y=y), x)[1]
# J2 = Zygote.jacobian(x -> f2!(e, x; M=M, y=y), x)[1]
# J1, J2
# end
# ╔═╡ aa4194d6-2f8c-4367-850e-22ebcf1b72e4
md"""
Although we managed to get reverse mode autodiff working, the end result is still not very satisfactory.
On the one hand, the function `f2!` is fast and requires zero allocation.
On the other hand, the custom reverse rule still involves computing and storing a full Jacobian matrix, which is pretty expensive.
Luckily, we can do better.
"""
# ╔═╡ f66a0ea7-70fd-4340-8b02-6fbaab847dfc
md"""
!!! danger "Task"
Explain why a VJP can be computed for the function $f$ without ever storing the full Jacobian.
"""
# ╔═╡ 8cca11ed-a61c-4cc8-af4b-350137073756
hint(md"Try to think in terms of computer program instead of mathematics. Describe the sequence of intermediate operations that you would perform for each of these computations.")
# ╔═╡ 7144c6c8-79dd-437d-a201-bac143f6a261
md"""
> Write your answer here
"""
# ╔═╡ 45765f4a-536d-4e9d-be9d-144b7ccd4dcf
md"""
!!! danger "Task"
Implement a VJP function for $f$, following the efficient method you just suggested.
"""
# ╔═╡ df89f509-cfd7-46b3-9dd1-cdcfcea68053
hint(md"
Now you should revert to `.*` for componentwise products instead of using diagonal matrices.
Remember that you must return a column vector, so technically $J_f(x)^\top v$ instead of $v^\top J_f(x)$.
")
# ╔═╡ 0b51e23e-a015-4e86-ba48-6475a9ee9779
function f_vjp(v, x; M, y)
# write your code here
end
# ╔═╡ 14dcad57-23ae-4905-aac4-d29066f2a085
md"""
!!! danger "Task"
Check the correctness of your VJP function against the naive version provided below.
"""
# ╔═╡ 06a59777-b6ec-4808-9105-7a2542a629ea
function f_vjp_naive(v, x; M, y)
J = Jf(x; M=M, y=y)
return v' * J
end
# ╔═╡ 9222d644-5d20-474a-83db-4b2e3bed45e2
# write your code here
# ╔═╡ c511e1c4-0306-46c7-800f-8257266c0091
md"""
!!! danger "Task"
Compare the performance of both VJP implementations.
"""
# ╔═╡ c79e7017-4acc-4562-817a-50245ce654dc
# write your code here
# ╔═╡ ac115404-0115-4c94-9b51-9a8674ac4b05
md"""
Now, if you wanted to, you could implement an `rrule` for `f2!` that uses `f_vjp`, and observe that Jacobian computations are accelerated.
And as it turns out, you could even go one step further.
"""
# ╔═╡ dd01d4b4-b05a-43a3-9b76-65e13076535f
md"""
!!! danger "Task"
Explain how yet another speed up can be achieved within the `rrule` by mutualizing computations between $f$ and its VJP.
"""
# ╔═╡ 766e1909-5063-4ce2-821d-1f93be4db789
hint(md"Try to identify a quantity that appears in both. Do we really need to compute it twice?")
# ╔═╡ 2b83cccd-bdaf-4481-a7f5-391434220bd5
md"""
> Write your answer here
"""
# ╔═╡ 69a9ec45-d2ff-4362-9c3c-5c004e46ceb3
md"""
# 4. Going further
"""
# ╔═╡ cc167cfd-b776-4280-a308-d5908ceaec4b
md"""
## Why VJPs?
"""
# ╔═╡ 8923a5ad-ddba-4ae2-886e-84526a3521ba
md"""
In concrete applications, the dimensions $n$ and $m$ often make it impossible to store a full Jacobian (of size $m \times n$) in memory.
As a result, autodiff systems only manipulate Jacobians "lazily" by computing their products with vectors.
In machine learning, we are mostly interested in loss functions with many inputs ($n \gg 1$) and a single scalar output ($m = 1$).
This means the Jacobian matrix only has one row, and it can be seen as the transpose of the gradient: $J_f(x) = \nabla f(x)^\top$.
Thus we only need one VJP (with $v = 1$) to retrieve the gradient.
"""
# ╔═╡ e1b9f114-58e7-4546-a3c0-5e07fb1665e7
md"""
!!! danger "Task"
How many VJPs would it take to compute the full Jacobian for a function $f : \mathbb{R}^n \longrightarrow \mathbb{R}^m$, and which vectors $v$ should you choose?
"""
# ╔═╡ ba07ccda-ae66-4fce-837e-00b2b039b404
md"""
> Write your answer here
"""
# ╔═╡ d0ae8c14-b341-4220-8a1c-79fed9758f64
md"""
## Why reverse mode?
"""
# ╔═╡ f843b77d-8160-4d87-8641-eeb04549af8f
md"""
Let us now consider a composite function $f = f_3 \circ f_2 \circ f_1$ with $3$ layers.
The _chain rule_ yields the following derivative:
$$f'(x) = f_3'((f_2 \circ f_1)(x)) \circ f_2'(f_1(x)) \circ f_1'(x)$$
In the Euclidean case, we can re-interpret this function composition as a matrix product:
$$\underbrace{J_f(x)}_J = \underbrace{J_{f_3}((f^2 \circ f^1) (x))}_{J_3} ~ \underbrace{J_{f_2}(f^1(x))}_{J_2} ~ \underbrace{J_{f_1}(x)}_{J_1}$$
"""
# ╔═╡ 9b34a8f9-6afa-4712-bde8-a94f4d5e7a33
md"""
But again, storing and multiplying full Jacobian matrices is expensive in high dimension.
Assuming we know how to manipulate the $J_k$ lazily, can we do the same for $J$?
In other words, can we deduce a VJP for $f$ based on a VJP for the $f_k$?
The answer is yes, but only if we do it in the right direction.
Indeed, we can accumulate the product from last to first layer:
$$v^\top J = v^\top J^3 J^2 J^1 \quad \implies \quad \begin{cases} v^3 = v^\top J^3 \\ v^2 = (v^3)^\top J^2 \\ v^1 = (v^2)^\top J^1 \end{cases}$$
This is why reverse mode autodiff uses VJPs, as shown in the `ChainRulesCore.rrule` syntax.
They allow efficient propagation of derivative information from the last layer to the first, which is particularly appropriate to compute gradients of high-dimensional loss functions.
Congrats, you now know how neural networks are trained!
"""
# ╔═╡ 00000000-0000-0000-0000-000000000001
PLUTO_PROJECT_TOML_CONTENTS = """
[deps]
BenchmarkTools = "6e4b80f9-dd63-53aa-95a3-0cdb28fa8baf"
ChainRulesCore = "d360d2e6-b24c-11e9-a2a3-2a2ae2dbcce4"
ForwardDiff = "f6369f11-7733-5829-9624-2563aa707210"
LinearAlgebra = "37e2e46d-f89d-539d-b4ee-838fcccc9c8e"
Plots = "91a5bcdd-55d7-5caf-9e0b-520d859cae80"
PlutoTeachingTools = "661c6b06-c737-4d37-b85c-46df65de6f69"
PlutoUI = "7f904dfe-b85e-4ff6-b463-dae2292396a8"
ProgressLogging = "33c8b6b6-d38a-422a-b730-caa89a2f386c"
Zygote = "e88e6eb3-aa80-5325-afca-941959d7151f"
[compat]
BenchmarkTools = "~1.3.1"