Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
2 changes: 2 additions & 0 deletions Project.toml
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ ChainRulesCore = "d360d2e6-b24c-11e9-a2a3-2a2ae2dbcce4"
Compat = "34da2185-b29b-5c13-b0c7-acf172513d20"
EnzymeCore = "f151be2c-9106-41f4-ab19-57ee4f262869"
Functors = "d9f16b24-f501-4c13-a1f2-28368ffc5196"
GPUArrays = "0c68f7d7-f131-5f86-a1c3-88cf8149b2d7"
LinearAlgebra = "37e2e46d-f89d-539d-b4ee-838fcccc9c8e"
MLCore = "c2834f40-e789-41da-a90e-33b280584a8c"
MLDataDevices = "7e8f7934-dd98-4c1a-8fe8-92b47a384d40"
Expand Down Expand Up @@ -58,6 +59,7 @@ Enzyme = "0.13"
EnzymeCore = "0.7.7, 0.8.4"
FiniteDifferences = "0.12"
Functors = "0.5"
GPUArrays = "11.2"
MLCore = "1.0.0"
MLDataDevices = "1.4.2"
MLUtils = "0.4"
Expand Down
15 changes: 10 additions & 5 deletions src/train.jl
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ using LinearAlgebra
using Optimisers: Optimisers
using Functors: fmap, fmapstructure
using ..Flux: Flux
using GPUArrays: GPUArrays

using ProgressLogging: @progress, @withprogress, @logprogress
using EnzymeCore: Duplicated
Expand Down Expand Up @@ -110,19 +111,23 @@ It adds only a few features to the loop above:
function train!(loss, adtype::AbstractADType, model, data, opt; cb = nothing)
isnothing(cb) || error("""train! does not support callback functions.
For more control use a loop with `gradient` and `update!`.""")
cache = GPUArrays.AllocCache()
@withprogress for (i,d) in enumerate(data)
d_splat = d isa Tuple ? d : (d,)

l, gs = Flux.withgradient(m -> loss(m, d_splat...), adtype, model)
GPUArrays.@cached cache begin
l, gs = Flux.withgradient(m -> loss(m, d_splat...), adtype, model)

if !isfinite(l)
throw(DomainError(lazy"Loss is $l on data item $i, stopping training"))
end
if !isfinite(l)
throw(DomainError(lazy"Loss is $l on data item $i, stopping training"))
end

opt, model = _update!(opt, model, gs[1])
opt, model = _update!(opt, model, gs[1])
end

@logprogress Base.haslength(data) ? i/length(data) : nothing
end
GPUArrays.unsafe_free!(cache)
end

_update!(opt_state, model, grads) = Optimisers.update!(opt_state, model, grads)
Expand Down
Loading