|
1 | 1 | # Saving and Loading Models |
2 | 2 |
|
3 | 3 | You may wish to save models so that they can be loaded and run in a later |
4 | | -session. The easiest way to do this is via |
| 4 | +session. Flux provides a number of ways to do this. |
| 5 | +The recommended way, which is the most robust one for long term storage, |
| 6 | +is to use [`Flux.state`](@ref) in combination with a serialization format like |
| 7 | +[JLD2.jl](https://juliaio.github.io/JLD2.jl/dev/) or |
5 | 8 | [BSON.jl](https://github.com/JuliaIO/BSON.jl). |
6 | 9 |
|
7 | 10 | Save a model: |
8 | 11 |
|
9 | 12 | ```jldoctest saving |
10 | 13 | julia> using Flux |
11 | 14 |
|
12 | | -julia> model = Chain(Dense(10, 5, NNlib.relu), Dense(5, 2), NNlib.softmax) |
13 | | -Chain( |
14 | | - Dense(10 => 5, relu), # 55 parameters |
15 | | - Dense(5 => 2), # 12 parameters |
16 | | - NNlib.softmax, |
17 | | -) # Total: 4 arrays, 67 parameters, 524 bytes. |
| 15 | +julia> struct MyModel |
| 16 | + net |
| 17 | + end |
18 | 18 |
|
19 | | -julia> using BSON: @save |
| 19 | +julia> Flux.@functor MyModel |
20 | 20 |
|
21 | | -julia> @save "mymodel.bson" model |
| 21 | +julia> MyModel() = MyModel(Chain(Dense(10, 5, relu), Dense(5, 2))); |
| 22 | +
|
| 23 | +julia> model = MyModel() |
| 24 | +MyModel(Chain(Dense(10 => 5, relu), Dense(5 => 2))) |
| 25 | +
|
| 26 | +julia> model_state = Flux.state(model); |
| 27 | +
|
| 28 | +julia> using JLD2 |
| 29 | +
|
| 30 | +julia> jldsave("mymodel.jld2"; model_state) |
22 | 31 | ``` |
23 | 32 |
|
24 | | -Load it again: |
| 33 | +Load it again in a new session using [`Flux.loadmodel!`](@ref): |
25 | 34 |
|
26 | 35 | ```jldoctest saving |
27 | | -julia> using Flux # Flux must be loaded before calling @load |
| 36 | +julia> using Flux, JLD2 |
28 | 37 |
|
29 | | -julia> using BSON: @load |
| 38 | +julia> model_state = JLD2.load("mymodel.jld2", "model_state"); |
30 | 39 |
|
31 | | -julia> @load "mymodel.bson" model |
| 40 | +julia> model = MyModel(); # MyModel definition must be available |
32 | 41 |
|
33 | | -julia> model |
34 | | -Chain( |
35 | | - Dense(10 => 5, relu), # 55 parameters |
36 | | - Dense(5 => 2), # 12 parameters |
37 | | - NNlib.softmax, |
38 | | -) # Total: 4 arrays, 67 parameters, 524 bytes. |
| 42 | +julia> Flux.loadmodel!(model, model_state); |
39 | 43 | ``` |
40 | 44 |
|
41 | | -Models are just normal Julia structs, so it's fine to use any Julia storage |
42 | | -format for this purpose. BSON.jl is particularly well supported and most likely |
43 | | -to be forwards compatible (that is, models saved now will load in future |
44 | | -versions of Flux). |
45 | | - |
46 | 45 | !!! note |
47 | 46 |
|
48 | 47 | If a saved model's parameters are stored on the GPU, the model will not load |
49 | 48 | later on if there is no GPU support available. It's best to [move your model |
50 | 49 | to the CPU](gpu.md) with `cpu(model)` before saving it. |
51 | 50 |
|
52 | | -!!! warning |
53 | | - |
54 | | - Previous versions of Flux suggested saving only the model weights using |
55 | | - `@save "mymodel.bson" params(model)`. |
56 | | - This is no longer recommended and even strongly discouraged. |
57 | | - Saving models this way will only store the trainable parameters which |
58 | | - will result in incorrect behavior for layers like `BatchNorm`. |
59 | | - |
60 | | -```julia |
61 | | -julia> using Flux |
62 | | - |
63 | | -julia> model = Chain(Dense(10 => 5,relu),Dense(5 => 2),softmax) |
64 | | -Chain( |
65 | | - Dense(10 => 5, relu), # 55 parameters |
66 | | - Dense(5 => 2), # 12 parameters |
67 | | - NNlib.softmax, |
68 | | -) # Total: 4 arrays, 67 parameters, 524 bytes. |
69 | | - |
70 | | -julia> weights = Flux.params(model); |
71 | | -``` |
72 | | - |
73 | | -Loading the model as shown above will return a new model with the stored parameters. |
74 | | -But sometimes you already have a model, and you want to load stored parameters into it. |
75 | | -This can be done as |
76 | | - |
77 | | -```julia |
78 | | -using Flux: loadmodel! |
79 | | -using BSON |
80 | | - |
81 | | -# some predefined model |
82 | | -model = Chain(Dense(10 => 5, relu), Dense(5 => 2), softmax) |
83 | | - |
84 | | -# load one model into another |
85 | | -model = loadmodel!(model, BSON.load("mymodel.bson")[:model]) |
86 | | -``` |
87 | | - |
88 | | -This ensures that the model loaded from `"mymodel.bson"` matches the structure of `model`. [`Flux.loadmodel!`](@ref) is also convenient for copying parameters between models in memory. |
89 | | - |
90 | | -```@docs |
91 | | -Flux.loadmodel! |
92 | | -``` |
93 | 51 |
|
94 | 52 | ## Checkpointing |
95 | 53 |
|
96 | | -In longer training runs it's a good idea to periodically save your model, so that you can resume if training is interrupted (for example, if there's a power cut). You can do this by saving the model in the [callback provided to `train!`](training/training.md). |
| 54 | +In longer training runs it's a good idea to periodically save your model, so that you can resume if training is interrupted (for example, if there's a power cut). |
97 | 55 |
|
98 | 56 | ```jldoctest saving |
99 | 57 | julia> using Flux: throttle |
100 | 58 |
|
101 | | -julia> using BSON: @save |
| 59 | +julia> using JLD2 |
102 | 60 |
|
103 | | -julia> m = Chain(Dense(10 => 5, relu), Dense(5 => 2), softmax) |
| 61 | +julia> m = Chain(Dense(10 => 5, relu), Dense(5 => 2)) |
104 | 62 | Chain( |
105 | 63 | Dense(10 => 5, relu), # 55 parameters |
106 | 64 | Dense(5 => 2), # 12 parameters |
107 | | - NNlib.softmax, |
108 | 65 | ) # Total: 4 arrays, 67 parameters, 524 bytes. |
109 | 66 |
|
110 | | -julia> evalcb = throttle(30) do |
111 | | - # Show loss |
112 | | - @save "model-checkpoint.bson" model |
| 67 | +julia> for epoch in 1:10 |
| 68 | + # ... train model ... |
| 69 | + jldsave("model-checkpoint.jld2", model_state = Flux.state(m)) |
113 | 70 | end; |
114 | 71 | ``` |
115 | 72 |
|
116 | | -This will update the `"model-checkpoint.bson"` file every thirty seconds. |
| 73 | +This will update the `"model-checkpoint.jld2"` every epoch. |
117 | 74 |
|
118 | 75 | You can get more advanced by saving a series of models throughout training, for example |
119 | 76 |
|
120 | 77 | ```julia |
121 | | -@save "model-$(now()).bson" model |
| 78 | +jldsave("model-$(now()).jld2", model_state = Flux.state(m)) |
122 | 79 | ``` |
123 | 80 |
|
124 | | -will produce a series of models like `"model-2018-03-06T02:57:10.41.bson"`. You |
| 81 | +will produce a series of models like `"model-2018-03-06T02:57:10.41.jld2"`. You |
125 | 82 | could also store the current test set loss, so that it's easy to (for example) |
126 | 83 | revert to an older copy of the model if it starts to overfit. |
127 | 84 |
|
128 | 85 | ```julia |
129 | | -@save "model-$(now()).bson" model loss = testloss() |
| 86 | +jldsave("model-$(now()).jld2", model_state = Flux.state(m), loss = testloss()) |
130 | 87 | ``` |
131 | 88 |
|
132 | | -Note that to resume a model's training, you might need to restore other stateful parts of your training loop. Possible examples are stateful optimisers (which usually utilize an `IdDict` to store their state), and the randomness used to partition the original data into the training and validation sets. |
| 89 | +Note that to resume a model's training, you might need to restore other stateful parts of your training loop. Possible examples are the optimiser state and the randomness used to partition the original data into the training and validation sets. |
133 | 90 |
|
134 | 91 | You can store the optimiser state alongside the model, to resume training |
135 | | -exactly where you left off. BSON is smart enough to [cache values](https://github.com/JuliaIO/BSON.jl/blob/v0.3.4/src/write.jl#L71) and insert links when saving, but only if it knows everything to be saved up front. Thus models and optimisers must be saved together to have the latter work after restoring. |
| 92 | +exactly where you left off: |
136 | 93 |
|
137 | 94 | ```julia |
138 | | -opt = Adam() |
139 | | -@save "model-$(now()).bson" model opt |
| 95 | +model = MyModel() |
| 96 | +opt_state = Flux.setup(AdamW(), model) |
| 97 | + |
| 98 | +# ... train model ... |
| 99 | + |
| 100 | +model_state = Flux.state(model) |
| 101 | +jldsave("checkpoint_epoch=42.jld2"; model_state, opt_state) |
| 102 | +``` |
| 103 | + |
| 104 | +# Saving Models as Julia Structs |
| 105 | + |
| 106 | +Models are just normal Julia structs, so it's fine to use any Julia storage |
| 107 | +format to save the struct as it is instead of saving the state returned by [`Flux.state`](@ref). |
| 108 | +[BSON.jl](https://github.com/JuliaIO/BSON.jl) is particularly convenient for this, |
| 109 | +since it can also save anynomous functions, which are sometimes part of a model definition. |
| 110 | + |
| 111 | +Save a model: |
| 112 | + |
| 113 | +```jldoctest saving |
| 114 | +julia> using Flux |
| 115 | +
|
| 116 | +julia> model = Chain(Dense(10, 5, NNlib.relu), Dense(5, 2)); |
| 117 | +
|
| 118 | +julia> using BSON: @save |
| 119 | +
|
| 120 | +julia> @save "mymodel.bson" model |
140 | 121 | ``` |
| 122 | + |
| 123 | +Load it again in a new session: |
| 124 | + |
| 125 | +```jldoctest saving |
| 126 | +julia> using Flux, BSON |
| 127 | +
|
| 128 | +julia> BSON.@load "mymodel.bson" model |
| 129 | +
|
| 130 | +julia> model |
| 131 | +Chain( |
| 132 | + Dense(10 => 5, relu), # 55 parameters |
| 133 | + Dense(5 => 2), # 12 parameters |
| 134 | +) # Total: 4 arrays, 67 parameters, 524 bytes. |
| 135 | +``` |
| 136 | +!!! warning |
| 137 | + Saving models this way could lead to compatibility issues across julia versions |
| 138 | + and across Flux versions if some of the Flux layers' internals are changed. |
| 139 | + It is therefore not recommended for long term storage, use [`Flux.state`](@ref) instead. |
| 140 | + |
| 141 | +!!! warning |
| 142 | + |
| 143 | + Previous versions of Flux suggested saving only the model weights using |
| 144 | + `@save "mymodel.bson" params(model)`. |
| 145 | + This is no longer recommended and even strongly discouraged. |
| 146 | + Saving models this way will only store the trainable parameters which |
| 147 | + will result in incorrect behavior for layers like `BatchNorm`. |
0 commit comments