-
Notifications
You must be signed in to change notification settings - Fork 0
/
notebook.jl
1830 lines (1509 loc) · 58.2 KB
/
notebook.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.11
using Markdown
using InteractiveUtils
# ╔═╡ d5559dba-9fe4-11ec-3744-ebd1408e7dc4
using AbstractTrees, PlutoUI, HypertextLiteral, PlutoTest, LinearAlgebra, Plots
# ╔═╡ 4da7a594-aec5-4c8d-ab20-6913ed6ff8ac
TableOfContents(title="📚 Table of Contents", indent=true, depth=4, aside=true)
# ╔═╡ 1b768306-0e0e-414d-a501-5c62a2db720f
md"## Computations as Trees"
# ╔═╡ 6733267e-1251-49a7-86a0-ff45ba408205
md"### Tracking variables"
# ╔═╡ 17f9e2c0-aa70-4d4e-ba42-51782df43785
md"### Computational Tree (Forward Pass)"
# ╔═╡ 7299bfea-e23e-4993-bebd-9d8762427294
md"### Pretty Viz: Forward Pass + Reverse Mode Diff"
# ╔═╡ be693f92-de60-4b43-82b3-ee6cceea310a
md"""
$\frac{\partial}{\partial x} (2xy + (x-1)^2) = 2y + 2(x-1)$
$\frac{\partial}{\partial y} (2xy + (x-1)^2) = 2x$
If x = 3 and y = 5, then these evaluate to 14 and 6.
"""
# ╔═╡ 20571e1a-9687-4d42-98b3-b3bc0b207b3b
md"## Implementation in Code"
# ╔═╡ 5e02b2c0-10cf-4746-840d-7017648f89f8
md"""
Besides the mathematics of reverse mode differentiation, there are many interesting computer science issues regarding the implementation of reverse diff. Probably the jury is still out which is best.
The implementation below is based on Julia's dispatch system.
This means we create a type `Tracked` for keeping track of our input variables and everything we'll need to calculate later.
The other main approach (not illustrated here) is source to source translation of code. In Julia the zygote package translates at the high level, while the increasingly popular Enzyme package translates at the lower level.
"""
# ╔═╡ d1312080-272c-4bd5-bcfe-bf47f8320961
md"### The Tracked Data Structure"
# ╔═╡ 99b6ab91-a022-449c-988c-0e5c5719c910
begin
struct Tracked{T} <: Number
val::T
name::Symbol
df
deps::Vector{Tracked}
end
# the two argument version as in Tracked{Int}(3,:x)
Tracked{T}(x, name=gensym()) where {T} = Tracked{T}(x, name, nothing, Tracked[])
## The above is typical Julia, the below shows up often when you
## define a new number type and you want ordinary numbers to work together
## with your newly defined numbers.
## This is similar to when in mathematics, strictly speaking integers
## are separate from the reals, but we all treat integers as embedded
## in the reals.
# Converting a Tracked variable, converts like the number
Base.convert(T::Type{Tracked{S}}, x::Tracked) where {S} = T(convert(S, x.val), x.name, x.df, x.deps)
# This tells Julia to convert any number added to a `Tracked` to a `Tracked` first
Base.promote_rule(::Type{Tracked{S}}, ::Type{T}) where {S<:Number, T<:Number} = Tracked{promote_type(S, T)}
# All this is just for nicer printing
function Base.show(io::IO, x::Tracked)
if x.df === nothing
print(io, Base.isgensym(x.name) ? x.val : "$(x.val)=$(x.name)")
else
#print(io, "⋅Tracked(")
print(io,"[")
print(io, x.name)
print(io,"]")
#print(io, ", ")
print(io," → ")
show(io, x.val)
#print(io, ")")
end
end
function Base.show(io::IO, x::Tracked{<:AbstractArray})
io = IOContext(io, :compact=>true)
print(io, Base.isgensym(x.name) ? x.val : string(x.name))
end
Base.show(io::IO, ::MIME"text/plain", x::Tracked) = print_tree(io, x)
Base.:(==)(x::Tracked, y::Tracked) = x === y
end
# ╔═╡ 0b5e6560-81fd-4182-bba5-aca702fb3048
begin
# The second argument of Tracked is a symbol only used for printing
x = Tracked{Int}(3, :x)
y = Tracked{Int}(5, :y)
u = Tracked{Int}(2, :u)
end
# ╔═╡ 0d006e4d-72e3-42ab-beb3-e5304a4d9ba9
x
# ╔═╡ 8919faec-753d-41d0-b0a8-c84c025b2919
xfloat = convert( Tracked{Float64}, x)
# ╔═╡ be28f764-a415-46ed-a503-68e8d831f8a8
(aa,bb) = (promote(x,2.5)) # promotes x to be a float and also y to be a Tracked
# ╔═╡ a0c0f48d-e0b0-4f45-8e0e-d9ab5743958b
Dump(aa)
# ╔═╡ 814786be-a760-4023-a614-83e727681075
Dump(bb)
# ╔═╡ 2ba83769-89b4-4ba0-8726-9210f394b4e7
md"### Operations on Tracked"
# ╔═╡ 885cd51d-895f-4996-a23b-780498b5b810
md"""
All overloads will do the operation (e.g. sum `x` and `y`), but also remember the pullback map and input variables for the reverse pass.
"""
# ╔═╡ 4813e57f-557a-4179-afd2-7925687b3d35
## Simeon write your way too
# These operations are
# d(x/y)= (y dx - x dy)/y^2
# ∇(x/y) = [1/y; -x/y^2] # Notice that the Δ -> (?,?) is just the gradient
# ╔═╡ ea94bdf9-b0b1-42ad-ba44-aaba73ed1192
md"""
Let's look at our example from above, $z = x^2+y$.
We'll introduce an intermediate variable $u = x^2$ so we can write $z$ as $u + y$.
We will first start with $1 \cdot dz$. The one here represents the fact that $\frac{\partial z}{\partial z} = 1$.
We then want to *pull* that *back* until we get something in terms of $dx$ and $dy$, so we then get the derivatives wrt $x$ and $y$
The pullback map for $+$ will first map $dz$ to $d(u + y) = du + dy$ and then we can use the pullback map for ^ to expand $du$ to $2x \cdot dx$.
Using that recursive method we end up with $dz = 2x \cdot dx + dy$, which is exactly what we'd get if we did this by hand. This tells us that $\frac{\partial z}{\partial x} = 2x$ and $\frac{\partial z}{\partial y} = y$.
"""
# ╔═╡ 13487e65-5e48-4a37-9bea-f262dd7b6d56
function Base.:+(x::Tracked, y::Tracked)
Tracked(x.val + y.val, :+, Δ -> (Δ, Δ), Tracked[x, y])
end
# ╔═╡ c9d70049-4793-41db-9075-e9e73e926c1a
x+y
# ╔═╡ b0cc4665-eb45-48ea-9a33-5acf56d2a283
function Base.:-(x::Tracked, y::Tracked)
Tracked(x.val - y.val, :-, Δ -> (Δ, -Δ), Tracked[x, y])
end
# ╔═╡ 73d638bf-30c1-4694-b3a8-4b29c5e3fa65
function Base.:*(x::Tracked, y::Tracked)
Tracked(x.val * y.val, :*, Δ -> (Δ * y.val', x.val' * Δ), Tracked[x, y])
end
# ╔═╡ 95ab6c83-0757-40b3-a116-6d872a074f69
x*y
# ╔═╡ db4f871a-3ca1-4bd3-a2c5-da7d6f599281
(x*y).val
# ╔═╡ 29360c2a-c47b-48a3-b225-248eb3ec8a42
(x*y).name
# ╔═╡ b47754ac-cb17-4ea3-a97d-20371fd341a5
((x*y).df)(1) # For reference
# ╔═╡ bb75e790-a628-4821-b7b1-11cd34a73d38
(x*y).deps
# ╔═╡ ac097299-0a31-474c-ab26-a4fb24bb9046
function Base.:^(x::Tracked, n::Int)
Tracked(x.val^n, Symbol("^$n"), Δ -> (Δ * n * x.val^(n-1),), Tracked[x,])
end
# ╔═╡ aa99b123-7164-4ed7-833f-b99b19118a0d
x^2+y
# ╔═╡ 0d2a3187-46f1-4705-bb3e-ecf74e34840d
z = (2x*y + (x-1)^2)
# ╔═╡ 61513f88-c126-43ab-9515-85a2c8a472bf
(x^2+y).deps
# ╔═╡ 2c3f3103-9ccb-446e-a289-87bbd0a1b97b
(x^2+y).deps[2]
# ╔═╡ 795c510e-6280-42d9-8820-290ca07be88d
((x^2+y).deps[2]).deps
# ╔═╡ e450329b-46ee-4f53-b6f0-891d6596938c
x^2+y
# ╔═╡ d48b9f23-b1b8-43f8-a05d-2234b69bf1f0
(2x*y + (x-1)^2)
# ╔═╡ 2141849b-675e-406c-8df4-34b2706507af
function Base.:/(x::Tracked, y::Tracked)
Tracked(x.val / y.val, :/, Δ -> (Δ / y.val, -Δ * x.val / y.val^2), Tracked[x, y])
end
# ╔═╡ 8ab0f55d-a393-4a8a-a48c-9ced26033f57
function Base.sin(x::Tracked)
Tracked(sin(x.val), :sin, Δ -> (Δ * cos(x.val),), Tracked[x,])
end
# ╔═╡ 4bfc2f7d-a5b0-44c7-8bb6-f1b834c1cc51
md"""
`Tracked` is a tree -- We just need to tell *AbstractTrees.jl* how to get the children for each node and we get tree printing and iteration over all nodes for free.
"""
# ╔═╡ 2188a663-5a85-4ce4-bc8d-20383481e59b
AbstractTrees.children(x::Tracked) = x.deps
# ╔═╡ ccafd0b9-95aa-4e58-8afc-26cd3ee61cc9
md"""
Straight away we get the primal result of our calculation:
"""
# ╔═╡ 81eb8a2d-a3a9-45af-a5a5-b96aefd48712
(2x*y + (x-1)^2).val # The result of `2x*y + (x-1)^2`
# ╔═╡ 01eacbd4-ef37-4524-aecc-2ef9a1044cf8
md"""
To also get the gradient, we'll use `PreOrderDFS` to traverse the tree we just created from the top down.
"""
# ╔═╡ e52aa672-69a9-419b-a992-e7a3d1364fb6
# `PreOrderDFS` traverses this tree from the top down
Text.(collect(PreOrderDFS(z)))
# ╔═╡ d5565717-239b-41ab-b311-d59b383130ed
md"""
Ok, let's create our function `grad` which will accumulate all intermediate gradients into a dictionary:
"""
# ╔═╡ 99a3507b-ca03-429f-acde-e2d1ebb32054
function grad(f::Tracked)
d = Dict{Any, Any}(f => 1)
for x in PreOrderDFS(f) # recursively traverse all dependents
x.df === nothing && continue # ignore untracked variables like constants
dy = x.df(d[x]) # evaluate pullback
for (yᵢ, dyᵢ) in zip(x.deps, dy)
# store the gradient in d
# if we have already stored a gradient for this variable, we need to add them
d[yᵢ] = get(d, yᵢ, 0) .+ dyᵢ
end
end
return d
end
# ╔═╡ d4e9b202-242e-4420-986b-12d2ab57af93
grad(f::Tracked, x::Tracked) = grad(f)[x]
# ╔═╡ 7fcccb65-4a7b-4527-97be-d25f481f6eaf
md"""
We can verify that it does the right thing:
"""
# ╔═╡ 18b1c55d-a6b5-44f6-b0b3-50bdb0aa9d96
w = x*y + x
# ╔═╡ 506d408e-dc2b-4e12-b917-286e3f4079a2
grad(w)
# ╔═╡ a7c8cb6a-6e17-4d8f-8958-fe3527c5b8e7
grad(w, x), grad(w, y)
# ╔═╡ e55dfad2-db50-459f-ab54-fa7637fc3638
md"""
## How can we visualize both the forward and the reverse pass?
We can further visualize each steps we just took. First we do the forwards calculation, where we also build up our tree, then we go down the tree in the opposite direction to accumulate our gradient.
"""
# ╔═╡ d9304d8d-9a34-46f2-908d-42d5cc5f5c5f
👽 = Tracked{Int}(12, :👽)
# ╔═╡ a6c2d3a2-326a-41dd-864d-aa3662466222
x,y
# ╔═╡ bcff2aa8-2387-44c7-a28f-39cd505a7adf
md"""
We can also visualize what Julia does in the forward pass on the code itself:
"""
# ╔═╡ 53ae4070-8818-4d21-8648-19df9319918a
md"""
## Let's write our own neural network!
"""
# ╔═╡ 8a70e835-dae6-4727-8204-95c87d5c23da
md"""
We need some more overloads
"""
# ╔═╡ 520f280d-c78e-433b-a0a2-8ef05b04f7cc
function Base.broadcasted(::typeof(tanh), x::Tracked)
res = tanh.(x.val)
Tracked(res, :tanh, Δ -> (Δ .* (1 .- res.^2),), Tracked[x,])
end
# ╔═╡ a5671f2f-48ca-4896-9428-147dc671d2b9
function Base.broadcasted(::typeof(+), x::Tracked{<:VecOrMat}, y::Tracked{<:Vector})
Tracked(x.val .+ y.val, :.+, Δ -> (Δ, sum(Δ; dims=2)), Tracked[x, y])
end
# ╔═╡ e01114fa-a847-424a-931f-8f42e623109f
function LinearAlgebra.norm(x::Tracked)
res = norm(x.val)
Tracked(res, :norm, Δ -> (Δ/res .* x.val,), Tracked[x,])
end
# ╔═╡ e6ee1921-57aa-4194-b2eb-8e32fa4a6c44
macro t(s)
:(Tracked{typeof($(esc(s)))}($(esc(s)), $(QuoteNode(s))))
end
# ╔═╡ 266bf2ed-d625-47be-8a87-21e12052b27f
md"""
Let's use three dense layers, all of the form
$x \mapsto \tanh.(W \cdot x + b)$
"""
# ╔═╡ 788903f0-a372-4265-bbf3-5b507a705100
NN(x, (W1, W2, W3, b1, b2, b3)) = W3 * tanh.(W2 * tanh.(W1 * @t(x) .+ b1) .+ b2) .+ b3
# ╔═╡ 337bc837-174f-4ed6-bee1-c9e80dc03b52
input = collect(range(0, 2π; length=100))'
# ╔═╡ 8f1ec8d7-89ab-4bc5-9eef-2b0a69019854
md"""
We'll try to approximate a sine curve:
"""
# ╔═╡ d2d21d41-9a4e-428b-b696-6878901849ba
ŷ = sin.(input) #.+ .2input .^ 2 .- cos.(5input)
# ╔═╡ 98807f0d-f8a5-4fe0-9983-2b95290347d9
md"""
### Tada! 🎉
(It's even reasonably fast for neural nets)
"""
# ╔═╡ 85098c31-04a1-421c-b3f6-25fec9360588
md"### What if we use a (leaky) rectified linear unit (ReLU) as activation?"
# ╔═╡ 7dca2c78-6faf-450a-8096-1c5b9f7f1295
leaky_relu(x) = x > 0 ? x : .1x
# ╔═╡ b2622dc4-2fd3-4d80-8efd-a6a985a6b2e9
function Base.broadcasted(::typeof(leaky_relu), x::Tracked)
Tracked(leaky_relu.(x.val), :tanh, Δ -> (map((x, Δ) -> x > 0 ? Δ : .1Δ, x.val, Δ),), Tracked[x,])
end
# ╔═╡ 0911a08a-4290-455b-9b26-0bf2862296da
plot(leaky_relu; label="leaky relu")
# ╔═╡ 0b094198-cf44-41d7-a8dc-fd8fd0716bb4
md"""
---
### Helper Functions
"""
# ╔═╡ d82adc20-4c8c-4f2c-9839-d03ad7e7f581
begin
struct EX
x::Any
function EX(ex)
if Meta.isexpr(ex, :call) && ex.args[1] === :+ && length(ex.args) > 3
new(Expr(:call, :+, Expr(:call, :+, ex.args[2:end-1]...), ex.args[end]))
else
new(ex)
end
end
end
show_tree(ex::Expr) = show_tree(EX(ex))
function Base.show(io::IO, ex::EX)
Base.show_unquoted(io, Meta.isexpr(ex.x, :call) ? ex.x.args[1] : ex.x)
if Meta.isexpr(ex.x, :call) && ex.x.args[1] === :^
print(io, ex.x.args[3])
end
end
function AbstractTrees.children(ex::EX)
if Meta.isexpr(ex.x, :call)
ex.x.args[1] === :^ ? [EX(ex.x.args[2])] : EX.(ex.x.args[2:end])
else
EX[]
end
end
Base.:(==)(ex1::EX, ex2::EX) = ex1.x == ex2.x
Base.hash(ex::EX, i::UInt) = hash(ex.x, i)
end
# ╔═╡ 96286b65-1a22-4458-a399-46579248cce4
begin
_rand(s...) = randn(s...) / √prod(s)
W1, W2, W3 = _rand(32, 1), _rand(32, 32), _rand(1, 32)
b1, b2, b3 = _rand(32), _rand(32), _rand(1)
params = [@t(W1), @t(W2), @t(W3), @t(b1), @t(b2), @t(b3)]
p = @animate for i in 1:10000
loss = norm(NN(input, params) - @t(ŷ))
∇ = grad(loss)
for p in params
p.val .-= 1e-3 .* ∇[p]
end
plot(input', [NN(input, params).val; ŷ]'; label=["prediction" "training data"])
end every 200
gif(p; fps=5)
end
# ╔═╡ 49333dc7-b809-4bb1-b285-20a12d8b9209
let ŷ_t = @t(ŷ)
loss = norm(NN(input, params) - ŷ_t)
∇ = grad(loss)
params′ = deepcopy(params)
for (p, p′) in zip(params, params′)
p′.val .-= 1e-3 .* ∇[p]
end
plot(input', [NN(input, params).val; ŷ]'; label=["prediction" "training data"])
quiver!(input[1:4:end], NN(input, params).val[1:4:end]; quiver=(zero(input[1:4:end]), 3(NN(input, params′).val .- NN(input, params).val)[1:4:end]))
end
# ╔═╡ 86fa378b-815d-4c3d-9121-1338ee54f30f
let
NN(x, (W1, W2, W3, b1, b2, b3)) = W3 * leaky_relu.(W2 * leaky_relu.(W1 * @t(x) .+ b1) .+ b2) .+ b3
_rand(s...) = randn(s...) / √prod(s)
W1, W2, W3 = _rand(32, 1), _rand(32, 32), _rand(1, 32)
b1, b2, b3 = _rand(32), _rand(32), _rand(1)
params = [@t(W1), @t(W2), @t(W3), @t(b1), @t(b2), @t(b3)]
p = @animate for i in 1:10000
loss = norm(NN(input, params) - @t(ŷ))
∇ = grad(loss)
for p in params
p.val .-= 1e-3 .* ∇[p]
end
plot(input', [NN(input, params).val; ŷ]'; label=["prediction" "training data"])
end every 200
gif(p; fps=5)
end
# ╔═╡ 8110f306-a7bb-43a2-bb36-6182c59b4b2e
begin
struct TTREE
x
d::Dict{Any, Any}
end
function Base.show(io::IO, x::TTREE)
show(io, x.x)
print(io, " ")
show(io, MIME("text/html"), get(x.d, x.x, @htl("")))
end
AbstractTrees.children(x::TTREE) = (TTREE(i, x.d) for i in children(x.x))
end
# ╔═╡ 1f1b384a-6588-45a5-9dd3-6de3face8bfb
function ad_steps(x::Expr; color_fwd="red", color_bwd="green", font_size=".8em")
x = EX(x)
repr(x) = sprint(show, x; context=:compact=>true)
span_fwd = @htl "<span style='color: $color_fwd; font-size: $font_size'>"
span_bwd = @htl "<span style='color: $color_bwd; font-size: $font_size'>"
d1 = Dict(
let e = eval(i.x)
i => @htl " $(span_fwd)$(repr(e isa Tracked ? e.val : e))</span>"
end
for i in PostOrderDFS(x) if isempty(children(i))
)
res = accumulate(Iterators.filter(x -> !isempty(children(x)), PostOrderDFS(x)); init=d1) do d,i
d = copy(d)
e = eval(i.x)
d[i] = @htl " $(span_fwd)$(repr(e isa Tracked ? e.val : e))</span>"
d
end
pushfirst!(res, d1)
f = eval(x.x)
d = Dict{Any, Any}(f => 1)
let d1 = copy(res[end])
d1[x] = @htl "$(d1[x]) $(span_bwd)1</span>"
push!(res, d1)
end
for (x, e) in zip(PreOrderDFS.((f, x))...)
x.df === nothing && continue
dy = x.df(d[x])
for (yᵢ, dyᵢ, e) in zip(x.deps, dy, children(e))
d1 = copy(res[end])
if haskey(d, yᵢ)
d1[e] = @htl "$(get(d1, e, ""))$(span_bwd) + $(repr(dyᵢ))</span>"
else
d1[e] = @htl "$(get(d1, e, "")) $(span_bwd)$(repr(dyᵢ))</span>"
end
push!(res, d1)
d[yᵢ] = get(d, yᵢ, 0) + dyᵢ
end
end
res
end
# ╔═╡ 1a154bb7-93a3-4973-8908-788db77ac294
s2 = @htl """
<link rel="stylesheet" href="https://fperucic.github.io/treant-js/Treant.css"/>
<style>
.Treant > .node {
padding: 5px; border: 2px solid #484848; border-radius: 8px;
box-sizing: unset;
min-width: fit-content;
font-size: 1.6em;
}
.Treant > .node > span {
vertical-align: middle;
}
.Treant .collapse-switch { width: 100%; height: 100%; border: none; }
.Treant .node.collapsed { background-color: var(--main-bg-color); }
.Treant .node.collapsed .collapse-switch { background: none;}
</style>
<script src="https://fperucic.github.io/treant-js/vendor/jquery.min.js"></script>
<script src="https://fperucic.github.io/treant-js/vendor/jquery.easing.js"></script>
<script src="https://fperucic.github.io/treant-js/vendor/raphael.js"></script>
<script src="https://fperucic.github.io/treant-js/Treant.js"></script>
"""
# ╔═╡ 6b1fb808-e993-4c2b-b81b-6710f8206de7
function to_json(x)
d = Dict{Symbol, Any}(
:innerHTML => sprint(AbstractTrees.printnode, x),
:children => Any[to_json(c) for c in children(x)],
#:collapsed => !isempty(children(x)),
)
end
# ╔═╡ 437285d4-ec53-4bb7-9966-fcfb5352e205
function show_tree(x; height=400)
id = gensym()
@htl """
$s2
<div id="$id" style="width:100%; height: $(height)px"> </div>
<script>
var simple_chart_config = {
chart: {
container: "#$id",
//animateOnInit: true,
node: {
collapsable: true,
},
nodeAlign: "BOTTOM",
connectors: {
type: "straight",
style: {
stroke: getComputedStyle(document.documentElement).getPropertyValue('--cm-editor-text-color')
}
},
animation: {
nodeAnimation: "easeOutBounce",
nodeSpeed: 500,
connectorsAnimation: "bounce",
connectorsSpeed: 500
},
},
nodeStructure: $(to_json(x))
};
var my_chart = new Treant(simple_chart_config);
</script>
"""
end
# ╔═╡ 86aa821b-a373-4814-953e-535f3a33c002
show_tree(norm(NN(input, params) - @t(ŷ)); height = 1000)
# ╔═╡ 094bf7ee-7c9b-458c-98dc-521768831654
function show_steps(steps; height=400)
id1, id2 = gensym(), gensym()
@htl """
$s2
<div id="$id1" style="width:100%; height: $(height)px"> </div>
<span style="color: red; font-size: 1.5em; margin-bottom: 1em">Move me!</span>
<input id="$id2" type="range" min="0" max="$(length(steps)-1)" value="0" style="width: 100%">
<script>
var steps = $(to_json.(steps));
var simple_chart_config = {
chart: {
container: "#$id1",
//animateOnInit: true,
node: {
collapsable: true,
},
nodeAlign: "BOTTOM",
connectors: {
type: "straight",
style: {
stroke: getComputedStyle(document.documentElement).getPropertyValue('--cm-editor-text-color')
}
},
animation: {
nodeAnimation: "easeOutBounce",
nodeSpeed: 500,
connectorsAnimation: "bounce",
connectorsSpeed: 500
},
},
nodeStructure: steps[0]
};
var my_chart = new Treant(simple_chart_config, null, \$);
var slider = document.getElementById("$id2");
slider.addEventListener('input', function(){
simple_chart_config.nodeStructure = steps[this.value];
document.getElementById("$id1").innerHTML = "";
my_chart = new Treant(simple_chart_config, null, \$);
});
</script>
"""
end
# ╔═╡ faf69c6f-b179-4ca2-aa22-641e9560e17b
macro ad_steps(ex)
quote
ex = $(QuoteNode(ex))
steps = ad_steps(ex)
show_steps([TTREE(EX(ex), step) for step in steps])
end
end
# ╔═╡ 27b39d7d-fc08-4ccc-aea4-b64f8a4f5726
#@ad_steps 3y*x + 2(x-1)*x
@ad_steps (2x*y + (x-1)^2) # type the steps for the macro
# ╔═╡ ec723b90-1c8b-4a87-8a86-fe17d6e85f22
@ad_steps (x+y)
# ╔═╡ 0d186a1b-eb89-4be8-a237-e5a9608f4a30
@ad_steps (x*y)
# ╔═╡ db3389c0-cb00-404c-81a8-8c4ccdab22f4
@ad_steps ((x*y)*u)
# ╔═╡ 8b486bd8-25a1-4895-99c8-0541c9e3c8b0
@ad_steps (x/y)
# ╔═╡ 2eb6af9c-9ac7-4b64-93fb-c5a2f037d303
@ad_steps y^2
# ╔═╡ f6ce8448-d9ce-4453-9e47-dc6443d50f55
s1 = html"""
<style>
p-frame-viewer {
display: inline-flex;
flex-direction: column;
}
p-frames,
p-frame-controls {
display: inline-flex;
}
p-frame-controls {
margin-top: 20px;
}
line-like {
font-size: 30px;
}
"""
# ╔═╡ 9a141034-17cb-4d85-a5a2-4724a38dd269
macro visual_debug(expr)
s1
quote
$(esc(:(PlutoTest.@eval_step_by_step($expr)))) .|> PlutoTest.SlottedDisplay |> PlutoTest.frames |> PlutoTest.with_slotted_css
end
end
# ╔═╡ 79f71f9d-b491-4a2c-85a4-29ae8da4f312
@visual_debug 3y + 2(x-1)
# ╔═╡ 00000000-0000-0000-0000-000000000001
PLUTO_PROJECT_TOML_CONTENTS = """
[deps]
AbstractTrees = "1520ce14-60c1-5f80-bbc7-55ef81b5835c"
HypertextLiteral = "ac1192a8-f4b3-4bfe-ba22-af5b92cd3ab2"
LinearAlgebra = "37e2e46d-f89d-539d-b4ee-838fcccc9c8e"
Plots = "91a5bcdd-55d7-5caf-9e0b-520d859cae80"
PlutoTest = "cb4044da-4d16-4ffa-a6a3-8cad7f73ebdc"
PlutoUI = "7f904dfe-b85e-4ff6-b463-dae2292396a8"
[compat]
AbstractTrees = "~0.4.2"
HypertextLiteral = "~0.9.4"
Plots = "~1.31.7"
PlutoTest = "~0.2.2"
PlutoUI = "~0.7.39"
"""
# ╔═╡ 00000000-0000-0000-0000-000000000002
PLUTO_MANIFEST_TOML_CONTENTS = """
# This file is machine-generated - editing it directly is not advised
julia_version = "1.8.0"
manifest_format = "2.0"
project_hash = "eceb496e896aa6e7e79fc43936b5726532da0604"
[[deps.AbstractPlutoDingetjes]]
deps = ["Pkg"]
git-tree-sha1 = "8eaf9f1b4921132a4cff3f36a1d9ba923b14a481"
uuid = "6e696c72-6542-2067-7265-42206c756150"
version = "1.1.4"
[[deps.AbstractTrees]]
git-tree-sha1 = "5c0b629df8a5566a06f5fef5100b53ea56e465a0"
uuid = "1520ce14-60c1-5f80-bbc7-55ef81b5835c"
version = "0.4.2"
[[deps.Adapt]]
deps = ["LinearAlgebra"]
git-tree-sha1 = "195c5505521008abea5aee4f96930717958eac6f"
uuid = "79e6a3ab-5dfb-504d-930d-738a2a938a0e"
version = "3.4.0"
[[deps.ArgTools]]
uuid = "0dad84c5-d112-42e6-8d28-ef12dabb789f"
version = "1.1.1"
[[deps.Artifacts]]
uuid = "56f22d72-fd6d-98f1-02f0-08ddc0907c33"
[[deps.Base64]]
uuid = "2a0f44e3-6c83-55bd-87e4-b1978d98bd5f"
[[deps.Bzip2_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "19a35467a82e236ff51bc17a3a44b69ef35185a2"
uuid = "6e34b625-4abd-537c-b88f-471c36dfa7a0"
version = "1.0.8+0"
[[deps.Cairo_jll]]
deps = ["Artifacts", "Bzip2_jll", "Fontconfig_jll", "FreeType2_jll", "Glib_jll", "JLLWrappers", "LZO_jll", "Libdl", "Pixman_jll", "Pkg", "Xorg_libXext_jll", "Xorg_libXrender_jll", "Zlib_jll", "libpng_jll"]
git-tree-sha1 = "4b859a208b2397a7a623a03449e4636bdb17bcf2"
uuid = "83423d85-b0ee-5818-9007-b63ccbeb887a"
version = "1.16.1+1"
[[deps.ChainRulesCore]]
deps = ["Compat", "LinearAlgebra", "SparseArrays"]
git-tree-sha1 = "80ca332f6dcb2508adba68f22f551adb2d00a624"
uuid = "d360d2e6-b24c-11e9-a2a3-2a2ae2dbcce4"
version = "1.15.3"
[[deps.ChangesOfVariables]]
deps = ["ChainRulesCore", "LinearAlgebra", "Test"]
git-tree-sha1 = "38f7a08f19d8810338d4f5085211c7dfa5d5bdd8"
uuid = "9e997f8a-9a97-42d5-a9f1-ce6bfc15e2c0"
version = "0.1.4"
[[deps.CodecZlib]]
deps = ["TranscodingStreams", "Zlib_jll"]
git-tree-sha1 = "ded953804d019afa9a3f98981d99b33e3db7b6da"
uuid = "944b1d66-785c-5afd-91f1-9de20f533193"
version = "0.7.0"
[[deps.ColorSchemes]]
deps = ["ColorTypes", "ColorVectorSpace", "Colors", "FixedPointNumbers", "Random"]
git-tree-sha1 = "1fd869cc3875b57347f7027521f561cf46d1fcd8"
uuid = "35d6a980-a343-548e-a6ea-1d62b119f2f4"
version = "3.19.0"
[[deps.ColorTypes]]
deps = ["FixedPointNumbers", "Random"]
git-tree-sha1 = "eb7f0f8307f71fac7c606984ea5fb2817275d6e4"
uuid = "3da002f7-5984-5a60-b8a6-cbb66c0b333f"
version = "0.11.4"
[[deps.ColorVectorSpace]]
deps = ["ColorTypes", "FixedPointNumbers", "LinearAlgebra", "SpecialFunctions", "Statistics", "TensorCore"]
git-tree-sha1 = "d08c20eef1f2cbc6e60fd3612ac4340b89fea322"
uuid = "c3611d14-8923-5661-9e6a-0046d554d3a4"
version = "0.9.9"
[[deps.Colors]]
deps = ["ColorTypes", "FixedPointNumbers", "Reexport"]
git-tree-sha1 = "417b0ed7b8b838aa6ca0a87aadf1bb9eb111ce40"
uuid = "5ae59095-9a9b-59fe-a467-6f913c188581"
version = "0.12.8"
[[deps.Compat]]
deps = ["Dates", "LinearAlgebra", "UUIDs"]
git-tree-sha1 = "5856d3031cdb1f3b2b6340dfdc66b6d9a149a374"
uuid = "34da2185-b29b-5c13-b0c7-acf172513d20"
version = "4.2.0"
[[deps.CompilerSupportLibraries_jll]]
deps = ["Artifacts", "Libdl"]
uuid = "e66e0078-7015-5450-92f7-15fbd957f2ae"
version = "0.5.2+0"
[[deps.Contour]]
git-tree-sha1 = "d05d9e7b7aedff4e5b51a029dced05cfb6125781"
uuid = "d38c429a-6771-53c6-b99e-75d170b6e991"
version = "0.6.2"
[[deps.DataAPI]]
git-tree-sha1 = "fb5f5316dd3fd4c5e7c30a24d50643b73e37cd40"
uuid = "9a962f9c-6df0-11e9-0e5d-c546b8b5ee8a"
version = "1.10.0"
[[deps.DataStructures]]
deps = ["Compat", "InteractiveUtils", "OrderedCollections"]
git-tree-sha1 = "d1fff3a548102f48987a52a2e0d114fa97d730f0"
uuid = "864edb3b-99cc-5e75-8d2d-829cb0a9cfe8"
version = "0.18.13"
[[deps.DataValueInterfaces]]
git-tree-sha1 = "bfc1187b79289637fa0ef6d4436ebdfe6905cbd6"
uuid = "e2d170a0-9d28-54be-80f0-106bbe20a464"
version = "1.0.0"
[[deps.Dates]]
deps = ["Printf"]
uuid = "ade2ca70-3891-5945-98fb-dc099432e06a"
[[deps.DelimitedFiles]]
deps = ["Mmap"]
uuid = "8bb1440f-4735-579b-a4ab-409b98df4dab"
[[deps.DocStringExtensions]]
deps = ["LibGit2"]
git-tree-sha1 = "5158c2b41018c5f7eb1470d558127ac274eca0c9"
uuid = "ffbed154-4ef7-542d-bbb7-c09d3a79fcae"
version = "0.9.1"
[[deps.Downloads]]
deps = ["ArgTools", "FileWatching", "LibCURL", "NetworkOptions"]
uuid = "f43a241f-c20a-4ad4-852c-f6b1247861c6"
version = "1.6.0"
[[deps.EarCut_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "3f3a2501fa7236e9b911e0f7a588c657e822bb6d"
uuid = "5ae413db-bbd1-5e63-b57d-d24a61df00f5"
version = "2.2.3+0"
[[deps.Expat_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "bad72f730e9e91c08d9427d5e8db95478a3c323d"
uuid = "2e619515-83b5-522b-bb60-26c02a35a201"
version = "2.4.8+0"
[[deps.Extents]]
git-tree-sha1 = "5e1e4c53fa39afe63a7d356e30452249365fba99"
uuid = "411431e0-e8b7-467b-b5e0-f676ba4f2910"
version = "0.1.1"
[[deps.FFMPEG]]
deps = ["FFMPEG_jll"]
git-tree-sha1 = "b57e3acbe22f8484b4b5ff66a7499717fe1a9cc8"
uuid = "c87230d0-a227-11e9-1b43-d7ebe4e7570a"
version = "0.4.1"
[[deps.FFMPEG_jll]]
deps = ["Artifacts", "Bzip2_jll", "FreeType2_jll", "FriBidi_jll", "JLLWrappers", "LAME_jll", "Libdl", "Ogg_jll", "OpenSSL_jll", "Opus_jll", "Pkg", "Zlib_jll", "libaom_jll", "libass_jll", "libfdk_aac_jll", "libvorbis_jll", "x264_jll", "x265_jll"]
git-tree-sha1 = "ccd479984c7838684b3ac204b716c89955c76623"
uuid = "b22a6f82-2f65-5046-a5b2-351ab43fb4e5"
version = "4.4.2+0"
[[deps.FileWatching]]
uuid = "7b1f6079-737a-58dc-b8bc-7a2ca5c1b5ee"
[[deps.FixedPointNumbers]]
deps = ["Statistics"]
git-tree-sha1 = "335bfdceacc84c5cdf16aadc768aa5ddfc5383cc"
uuid = "53c48c17-4a7d-5ca2-90c5-79b7896eea93"
version = "0.8.4"
[[deps.Fontconfig_jll]]
deps = ["Artifacts", "Bzip2_jll", "Expat_jll", "FreeType2_jll", "JLLWrappers", "Libdl", "Libuuid_jll", "Pkg", "Zlib_jll"]
git-tree-sha1 = "21efd19106a55620a188615da6d3d06cd7f6ee03"
uuid = "a3f928ae-7b40-5064-980b-68af3947d34b"
version = "2.13.93+0"
[[deps.Formatting]]
deps = ["Printf"]
git-tree-sha1 = "8339d61043228fdd3eb658d86c926cb282ae72a8"
uuid = "59287772-0a20-5a39-b81b-1366585eb4c0"
version = "0.4.2"
[[deps.FreeType2_jll]]
deps = ["Artifacts", "Bzip2_jll", "JLLWrappers", "Libdl", "Pkg", "Zlib_jll"]
git-tree-sha1 = "87eb71354d8ec1a96d4a7636bd57a7347dde3ef9"
uuid = "d7e528f0-a631-5988-bf34-fe36492bcfd7"
version = "2.10.4+0"
[[deps.FriBidi_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "aa31987c2ba8704e23c6c8ba8a4f769d5d7e4f91"
uuid = "559328eb-81f9-559d-9380-de523a88c83c"
version = "1.0.10+0"
[[deps.GLFW_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Libglvnd_jll", "Pkg", "Xorg_libXcursor_jll", "Xorg_libXi_jll", "Xorg_libXinerama_jll", "Xorg_libXrandr_jll"]
git-tree-sha1 = "d972031d28c8c8d9d7b41a536ad7bb0c2579caca"
uuid = "0656b61e-2033-5cc2-a64a-77c0f6c09b89"
version = "3.3.8+0"
[[deps.GR]]
deps = ["Base64", "DelimitedFiles", "GR_jll", "HTTP", "JSON", "Libdl", "LinearAlgebra", "Pkg", "Printf", "Random", "RelocatableFolders", "Serialization", "Sockets", "Test", "UUIDs"]
git-tree-sha1 = "cf0a9940f250dc3cb6cc6c6821b4bf8a4286cf9c"
uuid = "28b8d3ca-fb5f-59d9-8090-bfdbd6d07a71"
version = "0.66.2"
[[deps.GR_jll]]
deps = ["Artifacts", "Bzip2_jll", "Cairo_jll", "FFMPEG_jll", "Fontconfig_jll", "GLFW_jll", "JLLWrappers", "JpegTurbo_jll", "Libdl", "Libtiff_jll", "Pixman_jll", "Pkg", "Qt5Base_jll", "Zlib_jll", "libpng_jll"]
git-tree-sha1 = "2d908286d120c584abbe7621756c341707096ba4"
uuid = "d2c73de3-f751-5644-a686-071e5b155ba9"
version = "0.66.2+0"
[[deps.GeoInterface]]
deps = ["Extents"]
git-tree-sha1 = "fb28b5dc239d0174d7297310ef7b84a11804dfab"
uuid = "cf35fbd7-0cd7-5166-be24-54bfbe79505f"
version = "1.0.1"
[[deps.GeometryBasics]]
deps = ["EarCut_jll", "GeoInterface", "IterTools", "LinearAlgebra", "StaticArrays", "StructArrays", "Tables"]
git-tree-sha1 = "a7a97895780dab1085a97769316aa348830dc991"
uuid = "5c1252a2-5f33-56bf-86c9-59e7332b4326"
version = "0.4.3"
[[deps.Gettext_jll]]
deps = ["Artifacts", "CompilerSupportLibraries_jll", "JLLWrappers", "Libdl", "Libiconv_jll", "Pkg", "XML2_jll"]
git-tree-sha1 = "9b02998aba7bf074d14de89f9d37ca24a1a0b046"
uuid = "78b55507-aeef-58d4-861c-77aaff3498b1"
version = "0.21.0+0"
[[deps.Glib_jll]]
deps = ["Artifacts", "Gettext_jll", "JLLWrappers", "Libdl", "Libffi_jll", "Libiconv_jll", "Libmount_jll", "PCRE_jll", "Pkg", "Zlib_jll"]
git-tree-sha1 = "a32d672ac2c967f3deb8a81d828afc739c838a06"
uuid = "7746bdde-850d-59dc-9ae8-88ece973131d"
version = "2.68.3+2"
[[deps.Graphite2_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "344bf40dcab1073aca04aa0df4fb092f920e4011"
uuid = "3b182d85-2403-5c21-9c21-1e1f0cc25472"
version = "1.3.14+0"
[[deps.Grisu]]
git-tree-sha1 = "53bb909d1151e57e2484c3d1b53e19552b887fb2"
uuid = "42e2da0e-8278-4e71-bc24-59509adca0fe"
version = "1.0.2"
[[deps.HTTP]]
deps = ["Base64", "CodecZlib", "Dates", "IniFile", "Logging", "LoggingExtras", "MbedTLS", "NetworkOptions", "Random", "SimpleBufferStream", "Sockets", "URIs", "UUIDs"]
git-tree-sha1 = "bf7fcabde6565fd8226d8a4c31bc8bb25fdd7f1d"
uuid = "cd3eb016-35fb-5094-929b-558a96fad6f3"
version = "1.3.0"
[[deps.HarfBuzz_jll]]
deps = ["Artifacts", "Cairo_jll", "Fontconfig_jll", "FreeType2_jll", "Glib_jll", "Graphite2_jll", "JLLWrappers", "Libdl", "Libffi_jll", "Pkg"]
git-tree-sha1 = "129acf094d168394e80ee1dc4bc06ec835e510a3"
uuid = "2e76f6c2-a576-52d4-95c1-20adfe4de566"
version = "2.8.1+1"
[[deps.Hyperscript]]
deps = ["Test"]
git-tree-sha1 = "8d511d5b81240fc8e6802386302675bdf47737b9"
uuid = "47d2ed2b-36de-50cf-bf87-49c2cf4b8b91"
version = "0.0.4"
[[deps.HypertextLiteral]]
deps = ["Tricks"]
git-tree-sha1 = "c47c5fa4c5308f27ccaac35504858d8914e102f9"
uuid = "ac1192a8-f4b3-4bfe-ba22-af5b92cd3ab2"
version = "0.9.4"