|
| 1 | +using Random, Distributions |
| 2 | +using LinearAlgebra |
| 3 | +using LogDensityProblems, LogDensityProblemsAD |
| 4 | +using JLD2 |
| 5 | + |
| 6 | +using MixFlow |
| 7 | +const MF = MixFlow |
| 8 | + |
| 9 | + |
| 10 | +include(joinpath(@__DIR__, "../../Model.jl")) |
| 11 | +include(joinpath(@__DIR__, "../../julia_env/flowlayer.jl")) |
| 12 | + |
| 13 | +function run_baseline( |
| 14 | + seed, name::String, lr; |
| 15 | + batchsize::Int = 64, niters::Int= 50_000, show_progress=true, |
| 16 | + nsample_eval::Int=1024, save_jld::Bool=true, |
| 17 | +) |
| 18 | + Random.seed!(seed) |
| 19 | + |
| 20 | + @info "load model $(name)" |
| 21 | + target, dims, ad = load_model(name) |
| 22 | + |
| 23 | + @info "learning mfvi for $(name), dims = $(dims)" |
| 24 | + dim = LogDensityProblems.dimension(target) |
| 25 | + logp = Base.Fix1(LogDensityProblems.logdensity, target) |
| 26 | + |
| 27 | + q₀ = MvNormal(zeros(dim), I) |
| 28 | + flow = |
| 29 | + Bijectors.transformed(q₀, Bijectors.Shift(zeros(dim)) ∘ Bijectors.Scale(ones(dim))) |
| 30 | + |
| 31 | + cb(iter, opt_stats, re, θ) = (sample_per_iter = sample_per_iter, ad = ad) |
| 32 | + checkconv(iter, stat, re, θ, st) = _is_nan_or_inf(stat.loss) || (stat.gradient_norm < 1e-3) |
| 33 | + |
| 34 | + time = @elapsed begin |
| 35 | + flow_trained, stats, _ = train_flow( |
| 36 | + NormalizingFlows.elbo, |
| 37 | + flow, |
| 38 | + logp, |
| 39 | + batchsize; |
| 40 | + max_iters=niters, |
| 41 | + optimiser=Optimisers.Adam(lr), |
| 42 | + ADbackend=ad, |
| 43 | + show_progress=show_progress, |
| 44 | + hasconverged=checkconv, |
| 45 | + callback=cb, |
| 46 | + ) |
| 47 | + end |
| 48 | + @info "Training finished" |
| 49 | + |
| 50 | + # if early stop due to NaN or Inf, return NaN for all |
| 51 | + if _is_nan_or_inf(stats[end].loss) |
| 52 | + println("Training failed: loss is NaN or Inf") |
| 53 | + return DataFrame( |
| 54 | + time = NaN, |
| 55 | + elbo = NaN, |
| 56 | + logZ = NaN, |
| 57 | + ess = NaN, |
| 58 | + ) |
| 59 | + end |
| 60 | + |
| 61 | + # losses = map(x -> x.loss, stats) |
| 62 | + # try and if error happens, return NaN |
| 63 | + el, logz, es = flow_sample_eval(logp, flow_trained; nsample = nsample_eval) |
| 64 | + |
| 65 | + # save the trained flow |
| 66 | + if save_jld |
| 67 | + res_dir = joinpath(@__DIR__, "result/") |
| 68 | + |
| 69 | + if !isdir(res_dir) |
| 70 | + mkdir(res_dir) |
| 71 | + end |
| 72 | + |
| 73 | + JLD2.save( |
| 74 | + joinpath(res_dir, "$(name)_mfvi_$(lr)_$(seed).jld2"), |
| 75 | + "flow", flow_trained, |
| 76 | + "batchsize", batchsize, |
| 77 | + "seed", seed, |
| 78 | + ) |
| 79 | + end |
| 80 | + |
| 81 | + df = DataFrame( |
| 82 | + time = time, |
| 83 | + elbo=el, |
| 84 | + logZ=logz, |
| 85 | + ess=es, |
| 86 | + ) |
| 87 | + |
| 88 | + return df |
| 89 | +end |
0 commit comments