This repository has been archived by the owner on Nov 17, 2023. It is now read-only.
/
optimizer.jl
312 lines (241 loc) · 7.54 KB
/
optimizer.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
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
###############################################################################
# Types
###############################################################################
"""
AbstractOptimizer
Base type for all optimizers.
"""
abstract type AbstractOptimizer end
"""
AbstractLearningRateScheduler
Base type for all learning rate scheduler.
"""
abstract type AbstractLearningRateScheduler end
"""
AbstractMomentumScheduler
Base type for all momentum scheduler.
"""
abstract type AbstractMomentumScheduler end
"""
OptimizationState
### Attributes
* `batch_size`: The size of the mini-batch used in stochastic training.
* `curr_epoch`:
The current epoch count. Epoch 0 means no training yet, during the first
pass through the data, the epoch will be 1; during the second pass, the
epoch count will be 1, and so on.
* `curr_batch`:
The current mini-batch count. The batch count is reset during every epoch.
The batch count 0 means the beginning of each epoch, with no mini-batch
seen yet. During the first mini-batch, the mini-batch count will be 1.
* `curr_iter`:
The current iteration count. One iteration corresponds to one mini-batch,
but unlike the mini-batch count, the iteration count does **not** reset
in each epoch. So it track the *total* number of mini-batches seen so far.
"""
mutable struct OptimizationState
batch_size :: Int
curr_epoch :: Int
curr_batch :: Int
curr_iter :: Int
end
OptimizationState(batch_size::Int) = OptimizationState(batch_size, 0, 0, 0)
###############################################################################
# LearningRate module
###############################################################################
module LearningRate
using Markdown
import Base: get
import ..mx: AbstractLearningRateScheduler, OptimizationState, update!
export initlrsched
initlrsched(η::Real) = LearningRate.Fixed(η)
update!(a::AbstractLearningRateScheduler) = (isdefined(a, :t) && (a.t += 1))
"""
get(sched::AbstractLearningRateScheduler)
Returns the current learning rate.
"""
get(::AbstractLearningRateScheduler) = nothing
"""
LearningRate.Fixed(η)
Fixed learning rate scheduler always return the same learning rate.
"""
struct Fixed <: AbstractLearningRateScheduler
η::Float64
end
get(f::Fixed) = f.η
@doc doc"""
LearningRate.Exp(η₀; γ = 0.9)
```math
\eta_t = \eta_0\gamma^t
```
Where `t` is the epoch count, or the iteration count.
"""
mutable struct Exp <: AbstractLearningRateScheduler
η₀::Float64
γ ::Float64
t ::Int
end
function Exp(η₀; γ = 0.9, t = 0)
@assert 0 < γ < 1
Exp(η₀, γ, t)
end
get(a::Exp) = a.η₀ * a.γ^a.t
@doc doc"""
LearningRate.Inv(η₀; γ = 0.9, p = 0.5)
```math
\eta_t = \eta_0 (1 + \gamma t)^{-p}
```
Where `t` is the epoch count, or the iteration count.
"""
mutable struct Inv <: AbstractLearningRateScheduler
η₀::Float64
γ ::Float64
p ::Float64
t ::Int
end
function Inv(η₀; γ = 0.9, p = 0.5, t = 0)
@assert 0 < γ < 1
@assert 0 <= p
Inv(η₀, γ, p, t)
end
get(i::Inv) = i.η₀ * (1 + i.γ*i.t)^(-i.p)
end # module LearningRate
using .LearningRate
###############################################################################
# Momentum module
###############################################################################
module Momentum
using Markdown
import Base: get
import ..mx: AbstractMomentumScheduler, OptimizationState
export initmomsched
"""
get(sched)
* `sched::AbstractMomentumScheduler`: the momentum scheduler.
Returns the current momentum.
"""
get
initmomsched(μ::Real) = iszero(μ) ? Momentum.Null() : Momentum.Fixed(μ)
"""
Momentum.Null
The null momentum scheduler always returns 0 for momentum. It is also used to
explicitly indicate momentum should not be used.
"""
struct Null <: AbstractMomentumScheduler
end
get(::Null) = 0.0
"""
Momentum.Fixed
Fixed momentum scheduler always returns the same value.
"""
mutable struct Fixed <: AbstractMomentumScheduler
μ::Float64
end
get(f::Fixed) = f.μ
@doc doc"""
NadamScheduler(; μ = 0.99, δ = 0.004, γ = 0.5, α = 0.96)
Nesterov-accelerated adaptive momentum scheduler.
Description in [Incorporating Nesterov Momentum into Adam]
(http://cs229.stanford.edu/proj2015/054_report.pdf).
```math
\mu_t = \mu_0 * (1 - \gamma * \alpha^{t * \delta})
```
Where
* `t`: iteration count
* `μ`: default `0.99`, μ₀
* `δ`: default `0.004` is scheduler decay.
* `γ`: default `0.5`
* `α`: default `0.96`
"""
struct NadamScheduler <: AbstractMomentumScheduler
μ::Float64
δ::Float64
γ::Float64
α::Float64
end
function NadamScheduler(; μ = 0.99, δ = 0.004, γ = 0.5, α = 0.96)
@assert 0.0 <= μ < 1.0
@assert 0.0 <= δ
@assert 0.0 <= γ <= 1.0
@assert 0.0 <= α <= 1.0
NadamScheduler(μ, δ, γ, α)
end
"""
get(n::NadamScheduler, t)
Where `t` is the iteration count.
"""
get(n::NadamScheduler, t) =
n.μ * (1.0 - n.γ * n.α^( t * n.δ)),
n.μ * (1.0 - n.γ * n.α^((t + 1) * n.δ))
end # module Momentum
using .Momentum
###############################################################################
# Public APIs
###############################################################################
"""
getupdater(optimizer)
A utility function to create an updater function of `KVStore`,
that uses its closure to store all the states needed for each weights.
Ther returned function has following signature:
```julia
decend!(index::Int, ∇::NDArray, x::NDArray)
```
If the optimizer is stateful and need access/store states during updating,
`index` will be the key to access/store states.
"""
function getupdater(optimizer::AbstractOptimizer)
states = Dict{Int,Any}()
function updater(index::Int, ∇::NDArray, x::NDArray)
if !haskey(states, index)
states[index] = create_state(optimizer, index, x)
end
update!(optimizer, index, x, ∇, states[index])
end
updater
end
"""
normgrad(optimizer, W, ∇)
Get the properly normalized gradient (re-scaled and clipped if necessary).
* `optimizer`: the optimizer,
should contain the field `scale`, `clip` and `λ`.
* `W::NDArray`: the trainable weights.
* `∇::NDArray`: the original gradient of the weights.
"""
function normgrad!(opt::AbstractOptimizer, W::NDArray, ∇::NDArray)
# rescaling
s = opt.scale
!iszero(s) && @inplace ∇ .*= s
# gradient clipping
c = opt.clip
c > 0 && clamp!(∇, -c, c)
# weight decay
λ = opt.λ
λ > 0 && @inplace ∇ += λ .* W
∇
end
###############################################################################
# Builtin Optimizers
###############################################################################
include("optimizers/sgd.jl")
include("optimizers/adam.jl")
include("optimizers/adagrad.jl")
include("optimizers/adadelta.jl")
include("optimizers/adamax.jl")
include("optimizers/rmsprop.jl")
include("optimizers/nadam.jl")