Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

WIP: Make optimize work on structs #1073

Closed
wants to merge 8 commits into from
Closed
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 22 additions & 3 deletions src/optimise/train.jl
Original file line number Diff line number Diff line change
Expand Up @@ -17,17 +17,36 @@ Update the array `x` according to `x .-= x̄`.
"""
function update!(x::AbstractArray, x̄)
x .-= x̄
return
end

function update!(opt, x, x̄)
x .-= apply!(opt, x, x̄)
# skip, if gradient is nothing
update!(x::AbstractArray, x̄::Nothing) = nothing
update!(opt, x::AbstractArray, x̄::Nothing) = nothing
update!(opt, m::M, ∇m::Nothing) where M = nothing

function update!(opt, x::AbstractArray, x̄)
x .-= apply!(opt, x::AbstractArray, x̄)
Roger-luo marked this conversation as resolved.
Show resolved Hide resolved
return
end

# NOTE: since there won't be real loop in a struct
# we could always flatten it, which is a bit
# faster.
@generated function update!(opt, m::M, ∇m) where M
body = Expr(:block)
for each in fieldnames(M)
each = QuoteNode(each)
push!(body.args, :(update!(opt, getfield(m, $each), getfield(∇m, $each))))
end
return body
end

function update!(opt, xs::Params, gs)
for x in xs
gs[x] == nothing && continue
update!(opt, x, gs[x])
end
return
end

# Callback niceties
Expand Down