Skip to content

How to save a model / fit and load it? Issue with JLD2 for "reconstructing" #2309

@DominiqueMakowski

Description

@DominiqueMakowski

(this issue is somewhat related to #2308)

I'm trying to save models on the disk and, in a new session, loading and using them.

Here's an MWE, starting with making and saving a model:

using Turing
using JLD2

@model function mymodel(y)
    μ ~ Normal(0, 2)
    σ ~ truncated(Normal(0, 3), 0.0, Inf)
    for i in 1:length(y)
        y[i] ~ Normal(μ, σ)
    end
end
fit = mymodel([1, 2, 3, 4, 5])

jldsave("model.jld2";  model=mymodel, fit=fit)

Now, in a new session, if I do the following it errors:

using Turing
using JLD2

loaded = jldopen("model.jld2", "r+")
loaded["model"]
┌ Warning: type Main.#mymodel does not exist in workspace; reconstructing
└ @ JLD2 C:\Users\domma\.julia\packages\JLD2\twZ5D\src\data\reconstructing_datatypes.jl:492
loaded["model"]([1, 2, 3, 4, 5])
ERROR: MethodError: objects of type JLD2.ReconstructedSingleton{Symbol("#mymodel")} are not callable
Stacktrace:
 [1] top-level scope
   @ c:\Users\domma\Dropbox\RECHERCHE\Studies\DoggoNogo\study1\analysis\1_models_make.jl:154

How to correctly save/load Turing models?

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions