Skip to content

Commit a87ffd5

Browse files
add trainables (#171)
* trainables * trainables * cl/trainables * trainables * test second order derivatives * add doc section * fix test * Update src/trainables.jl
1 parent b4920f7 commit a87ffd5

File tree

8 files changed

+214
-5
lines changed

8 files changed

+214
-5
lines changed

docs/src/api.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,7 @@ Such restrictions are also obeyed by this function for flattening a model:
5959
```@docs
6060
Optimisers.destructure
6161
Optimisers.Restructure
62+
Optimisers.trainables
6263
```
6364

6465
## Rule Definition

docs/src/index.md

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -290,3 +290,29 @@ flat, re = destructure(params)
290290
end
291291
```
292292

293+
## Collecting all trainable parameters
294+
295+
Sometimes it is useful to collect all trainable parameters in a model,
296+
similarly to what [`destructure`](@ref Optimisers.destructure) does but without
297+
concatenating the arrays into a flat vector.
298+
This is done by [`trainables`](@ref Optimisers.trainables), which returns a list of arrays:
299+
300+
```julia
301+
julia> using Flux, Optimisers
302+
303+
julia> model = Chain(Dense(2 => 3, tanh), BatchNorm(3), Dense(3 => 2));
304+
305+
julia> trainables(model)
306+
6-element Vector{AbstractArray}:
307+
Float32[0.5756773 -0.1975264; 0.4723181 -0.7546912; -0.91631395 0.07392061]
308+
Float32[0.0, 0.0, 0.0]
309+
Float32[0.0, 0.0, 0.0]
310+
Float32[1.0, 1.0, 1.0]
311+
Float32[-0.8764882 0.40812716 0.1919528; -0.9123545 -0.4462516 0.6751252]
312+
Float32[0.0, 0.0]
313+
314+
julia> l2reg(model) = sum([sum(abs2,p) for p in trainables(model)]);
315+
316+
julia> g = gradient(l2reg, model)[1];
317+
```
318+
Notice that the `BatchNorm` layer has two trainable parameters, `γ` and `β`, which are included in the list, while the `μ ` and `σ²` buffers are not.

src/Optimisers.jl

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,9 @@ include("adjust.jl")
1111
include("destructure.jl")
1212
export destructure
1313

14+
include("trainables.jl")
15+
export trainables
16+
1417
include("rules.jl")
1518
export Descent, Adam, Momentum, Nesterov, Rprop, RMSProp,
1619
AdaGrad, AdaMax, AdaDelta, AMSGrad, NAdam, AdamW, RAdam, OAdam, AdaBelief,

src/destructure.jl

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -66,19 +66,19 @@ function _flatten(x)
6666
isnumeric(x) && return vcat(_vec(x)), 0, length(x) # trivial case
6767
arrays = AbstractVector[]
6868
len = Ref(0)
69-
off = fmap(x; exclude = isnumeric, walk = _TrainableStructWalk()) do y
69+
off = fmap(x; exclude = isnumeric, walk = TrainableStructWalk()) do y
7070
push!(arrays, _vec(y))
7171
o = len[]
7272
len[] = o + length(y)
7373
o
7474
end
7575
isempty(arrays) && return Bool[], off, 0
76-
reduce(vcat, arrays), off, len[]
76+
return reduce(vcat, arrays), off, len[]
7777
end
7878

79-
struct _TrainableStructWalk <: AbstractWalk end
79+
struct TrainableStructWalk <: AbstractWalk end
8080

81-
(::_TrainableStructWalk)(recurse, x) = map(recurse, _trainable(x))
81+
(::TrainableStructWalk)(recurse, x) = map(recurse, _trainable(x))
8282

8383
_vec(x::Number) = LinRange(x,x,1)
8484
_vec(x::AbstractArray) = vec(x)
@@ -174,3 +174,4 @@ function ChainRulesCore.rrule(::typeof(_maybewarn))
174174
@warn "second derivatives of destructure may not work yet, sorry!" maxlog=3
175175
nothing, _ -> (NoT,)
176176
end
177+

src/interface.jl

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -167,6 +167,7 @@ and `trainable(x)` must contain a subset of these.
167167
"""
168168
trainable(x) = functor(x)[1]
169169

170+
# like trainable(x), but also tries to output non-trainable children giving value nothing
170171
_trainable(x) = _trainable(functor(x)[1], trainable(x))
171172
_trainable(ch::NamedTuple, tr::NamedTuple) = merge(map(_ -> nothing, ch), tr)
172173
_trainable(ch::Tuple{Vararg{Any,N}}, tr::Tuple{Vararg{Any,N}}) where N = tr

src/trainables.jl

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
2+
"""
3+
trainables(x)
4+
5+
Return a list over all the trainable parameters in `x`, that is all the numerical
6+
arrays (see [`isnumeric`](@ref Optimisers.isnumeric)) which are reachable through [`trainable`](@ref Optimisers.trainable).
7+
8+
Parameters appearing multiple times in the model (tied weights) will be present only once in the output.
9+
10+
See also [`destructure`](@ref) for a similar operation that returns a single flat vector instead.
11+
12+
# Examples
13+
14+
```jldoctest
15+
julia> struct MyLayer
16+
w
17+
b
18+
end
19+
20+
julia> Functors.@functor MyLayer
21+
22+
julia> Optimisers.trainable(x::MyLayer) = (; w = x.w,) # only w is trainable in this example
23+
24+
julia> x = MyLayer([1.0,2.0,3.0], [4.0,5.0,6.0]);
25+
26+
julia> trainables(x)
27+
1-element Vector{AbstractArray}:
28+
[1.0, 2.0, 3.0]
29+
30+
julia> x = MyLayer((a=[1.0,2.0], b=[3.0]), [4.0,5.0,6.0]);
31+
32+
julia> trainables(x) # collects nested parameters
33+
2-element Vector{AbstractArray}:
34+
[1.0, 2.0]
35+
[3.0]
36+
"""
37+
function trainables(x)
38+
arrays = AbstractArray[]
39+
exclude(x) = Optimisers.isnumeric(x)
40+
fmap(x; exclude, walk = Optimisers.TrainableStructWalk()) do y
41+
push!(arrays, y)
42+
return y
43+
end
44+
return arrays
45+
end
46+
47+
function ∇trainables(x, Δ)
48+
exclude(x) = Optimisers.isnumeric(x)
49+
i = 0
50+
return fmapstructure(x; exclude, walk = TrainableStructWalk()) do _
51+
return Δ[i+=1]
52+
end
53+
end
54+
55+
function ChainRulesCore.rrule(::typeof(trainables), x)
56+
y = trainables(x)
57+
trainables_back(Δ) = (NoTangent(), ∇trainables(x, unthunk(Δ)))
58+
return y, trainables_back
59+
end

test/runtests.jl

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ Random.seed!(1)
1010

1111
struct Foo; x; y; end
1212
Functors.@functor Foo
13-
Optimisers.trainable(x::Foo) = (x.y, x.x)
13+
Optimisers.trainable(x::Foo) = (; x.y, x.x)
1414

1515
struct TwoThirds a; b; c; end
1616
Functors.@functor TwoThirds (a, c)
@@ -539,6 +539,9 @@ end
539539
@testset verbose=true "Destructure" begin
540540
include("destructure.jl")
541541
end
542+
@testset verbose=true "Trainables" begin
543+
include("trainables.jl")
544+
end
542545
@testset verbose=true "Optimisation Rules" begin
543546
include("rules.jl")
544547
end

test/trainables.jl

Lines changed: 115 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,115 @@
1+
2+
m1 = collect(1:3.0)
3+
m2 = (collect(1:3.0), collect(4:6.0))
4+
m3 = (x = m1, y = sin, z = collect(4:6.0))
5+
6+
m4 = (x = m1, y = m1, z = collect(4:6.0)) # tied
7+
m5 = (a = (m3, true), b = (m1, false), c = (m4, true))
8+
m6 = (a = m1, b = [4.0 + im], c = m1)
9+
10+
m7 = TwoThirds((sin, collect(1:3.0)), (cos, collect(4:6.0)), (tan, collect(7:9.0)))
11+
m8 = [Foo(m1, m1), (a = true, b = Foo([4.0], false), c = ()), [[5.0]]]
12+
13+
mat = Float32[4 6; 5 7]
14+
m9 = (a = m1, b = mat, c = [mat, m1])
15+
16+
@testset "trainables" begin
17+
ps = trainables(m1)
18+
@test ps isa Vector
19+
@test length(ps) == 1
20+
@test ps[1] == m1
21+
22+
ps = trainables(m2)
23+
@test ps isa Vector
24+
@test length(ps) == 2
25+
@test ps[1] == m2[1]
26+
@test ps[2] == m2[2]
27+
28+
ps = trainables(m3)
29+
@test length(ps) == 2
30+
@test ps[1] == 1:3
31+
@test ps[2] == 4:6
32+
33+
ps = trainables(m4)
34+
@test length(ps) == 2
35+
@test ps[1] == 1:3
36+
@test ps[2] == 4:6
37+
38+
ps = trainables(m5)
39+
@test length(ps) == 3
40+
@test ps[1] == 1:3
41+
@test ps[2] == 4:6
42+
@test ps[3] == 4:6
43+
44+
ps = trainables(m6)
45+
@test length(ps) == 2
46+
@test ps[1] == 1:3
47+
@test ps[2] == ComplexF64[4.0 + 1.0im]
48+
49+
ps = trainables(m7)
50+
@test length(ps) == 1
51+
@test ps[1] == [1.0, 2.0, 3.0]
52+
53+
ps = trainables(m8)
54+
@test length(ps) == 3
55+
@test ps[1] == 1:3
56+
@test ps[2] == [4.0]
57+
@test ps[3] == [5.0]
58+
59+
ps = trainables(m9)
60+
@test length(ps) == 2
61+
@test ps[1] == 1:3
62+
@test ps[2] == mat
63+
end
64+
65+
@testset "gradient" begin
66+
loss(m) = sum([sum(abs2, p) for p in trainables(m)])
67+
g = gradient(loss, m1)[1]
68+
@test g == [2.0, 4.0, 6.0]
69+
70+
g = gradient(loss, m2)[1]
71+
@test g == ([2.0, 4.0, 6.0], [8.0, 10.0, 12.0])
72+
73+
g = gradient(loss, m3)[1]
74+
@test g.x == [2.0, 4.0, 6.0]
75+
@test g.y === nothing
76+
@test g.z == [8.0, 10.0, 12.0]
77+
78+
g = gradient(loss, m4)[1]
79+
@test g == (x = [2.0, 4.0, 6.0], y = [2.0, 4.0, 6.0], z = [8.0, 10.0, 12.0])
80+
g.x === g.y # shared gradient for shared weights
81+
82+
g = gradient(loss, m5)[1]
83+
@test g == (a = ((x = [2.0, 4.0, 6.0], y = nothing, z = [8.0, 10.0, 12.0]), nothing), b = ([2.0, 4.0, 6.0], nothing), c = ((x = [2.0, 4.0, 6.0], y = [2.0, 4.0, 6.0], z = [8.0, 10.0, 12.0]), nothing))
84+
85+
g = gradient(loss, m6)[1]
86+
@test g == (a = [2.0, 4.0, 6.0], b = ComplexF64[8.0 + 2.0im], c = [2.0, 4.0, 6.0])
87+
88+
g = gradient(loss, m7)[1]
89+
@test g == (a = (nothing, [2.0, 4.0, 6.0]), b = nothing, c = nothing)
90+
91+
g = gradient(loss, m8)[1]
92+
@test g[1] == (x = [2.0, 4.0, 6.0], y = [2.0, 4.0, 6.0])
93+
@test g[2] == (a = nothing, b = (x = [8.0], y = nothing), c = nothing)
94+
@test g[3] == [[10.0]]
95+
96+
g = gradient(loss, m9)[1]
97+
@test g == (a = [2.0, 4.0, 6.0], b = Float32[8.0 12.0; 10.0 14.0], c = Array[Float32[8.0 12.0; 10.0 14.0], [2.0, 4.0, 6.0]])
98+
end
99+
100+
@testset "second order derivatives" begin
101+
struct DenseLayer
102+
w
103+
b
104+
end
105+
106+
Functors.@functor DenseLayer
107+
108+
loss(m) = sum([sum(abs2, p) for p in trainables(m)])
109+
110+
model = DenseLayer([1. 2.; 3. 4.], [0., 0.])
111+
112+
g = gradient(m -> loss(gradient(loss, m)), model)[1]
113+
@test g.w == [8.0 16.0; 24.0 32.0]
114+
@test g.b == [0.0, 0.0]
115+
end

0 commit comments

Comments
 (0)