argmin/core/checkpointing/mod.rs
1// Copyright 2018-2024 argmin developers
2//
3// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
4// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
5// http://opensource.org/licenses/MIT>, at your option. This file may not be
6// copied, modified, or distributed except according to those terms.
7
8//! # Checkpointing
9//!
10//! Checkpointing is a useful mechanism for mitigating the effects of crashes when software is run
11//! in an unstable environment, particularly for long run times. Checkpoints are saved regularly
12//! with a user-chosen frequency. Optimizations can then be resumed from a given checkpoint after a
13//! crash.
14//!
15//! For saving checkpoints to disk, `FileCheckpoint` is provided in the `argmin-checkpointing-file`
16//! crate.
17//! Via the `Checkpoint` trait other checkpointing approaches can be implemented.
18//!
19//! The `CheckpointingFrequency` defines how often checkpoints are saved and can be chosen to be
20//! either `Always` (every iteration), `Every(u64)` (every Nth iteration) or `Never`.
21//!
22//! The following example shows how the `checkpointing` method is used to activate checkpointing.
23//! If no checkpoint is available on disk, an optimization will be started from scratch. If the run
24//! crashes and a checkpoint is found on disk, then it will resume from the checkpoint.
25//!
26//! ## Example
27//!
28//! ```rust
29//! # extern crate argmin;
30//! # extern crate argmin_testfunctions;
31//! # use argmin::core::{CostFunction, Error, Executor, Gradient, observers::ObserverMode};
32//! # #[cfg(feature = "serde1")]
33//! use argmin::core::checkpointing::CheckpointingFrequency;
34//! # #[cfg(feature = "serde1")]
35//! use argmin_checkpointing_file::FileCheckpoint;
36//! # use argmin_observer_slog::SlogLogger;
37//! # use argmin::solver::landweber::Landweber;
38//! # use argmin_testfunctions::{rosenbrock, rosenbrock_derivative};
39//! #
40//! # #[derive(Default)]
41//! # struct Rosenbrock {}
42//! #
43//! # /// Implement `CostFunction` for `Rosenbrock`
44//! # impl CostFunction for Rosenbrock {
45//! # /// Type of the parameter vector
46//! # type Param = Vec<f64>;
47//! # /// Type of the return value computed by the cost function
48//! # type Output = f64;
49//! #
50//! # /// Apply the cost function to a parameter `p`
51//! # fn cost(&self, p: &Self::Param) -> Result<Self::Output, Error> {
52//! # Ok(rosenbrock(p))
53//! # }
54//! # }
55//! #
56//! # /// Implement `Gradient` for `Rosenbrock`
57//! # impl Gradient for Rosenbrock {
58//! # /// Type of the parameter vector
59//! # type Param = Vec<f64>;
60//! # /// Type of the return value computed by the cost function
61//! # type Gradient = Vec<f64>;
62//! #
63//! # /// Compute the gradient at parameter `p`.
64//! # fn gradient(&self, p: &Self::Param) -> Result<Self::Gradient, Error> {
65//! # Ok(rosenbrock_derivative(p))
66//! # }
67//! # }
68//! #
69//! # fn run() -> Result<(), Error> {
70//! # // define initial parameter vector
71//! # let init_param: Vec<f64> = vec![1.2, 1.2];
72//! # let my_optimization_problem = Rosenbrock {};
73//! #
74//! # let iters = 35;
75//! # let solver = Landweber::new(0.001);
76//!
77//! // [...]
78//!
79//! # #[cfg(feature = "serde1")]
80//! let checkpoint = FileCheckpoint::new(
81//! ".checkpoints",
82//! "optim",
83//! CheckpointingFrequency::Every(20)
84//! );
85//!
86//! #
87//! # #[cfg(feature = "serde1")]
88//! let res = Executor::new(my_optimization_problem, solver)
89//! .configure(|config| config.param(init_param).max_iters(iters))
90//! .checkpointing(checkpoint)
91//! .run()?;
92//!
93//! // [...]
94//! #
95//! # Ok(())
96//! # }
97//! #
98//! # fn main() {
99//! # if let Err(ref e) = run() {
100//! # println!("{}", e);
101//! # }
102//! # }
103//! ```
104
105use crate::core::Error;
106use std::default::Default;
107use std::fmt::Display;
108
109/// An interface for checkpointing methods
110///
111/// Handles saving of a checkpoint. The methods [`save`](`Checkpoint::save`) (saving the
112/// checkpoint), [`load`](`Checkpoint::load`) (loading a checkpoint) are mandatory to implement.
113/// The method [`save_cond`](`Checkpoint::save_cond`) determines if the conditions for calling
114/// `save` are met, and if yes, calls `save`. [`frequency`](`Checkpoint::frequency`) returns the
115/// conditions in form of a [`CheckpointingFrequency`].
116///
117/// # Example
118///
119/// ```
120/// use argmin::core::Error;
121/// use argmin::core::checkpointing::{Checkpoint, CheckpointingFrequency};
122/// # #[cfg(feature = "serde1")]
123/// use serde::{Serialize, de::DeserializeOwned};
124///
125/// struct MyCheckpoint {
126/// frequency: CheckpointingFrequency,
127/// // ..
128/// }
129///
130/// # #[cfg(feature = "serde1")]
131/// impl<S, I> Checkpoint<S, I> for MyCheckpoint
132/// where
133/// // Both `solver` (`S`) and `state` (`I`) (probably) need to be (de)serializable
134/// S: Serialize + DeserializeOwned,
135/// I: Serialize + DeserializeOwned,
136/// # S: Default,
137/// # I: Default,
138/// {
139/// fn save(&self, solver: &S, state: &I) -> Result<(), Error> {
140/// // Save `solver` and `state`
141/// Ok(())
142/// }
143///
144/// fn load(&self) -> Result<Option<(S, I)>, Error> {
145/// // Load `solver` and `state` from checkpoint
146/// // Return `Ok(None)` in case checkpoint is not found.
147/// # let solver = S::default();
148/// # let state = I::default();
149/// Ok(Some((solver, state)))
150/// }
151///
152/// fn frequency(&self) -> CheckpointingFrequency {
153/// self.frequency
154/// }
155/// }
156/// # fn main() {}
157/// ```
158pub trait Checkpoint<S, I> {
159 /// Save a checkpoint
160 ///
161 /// Gets a reference to the current `solver` of type `S` and to the current `state` of type
162 /// `I`. Both solver and state can maintain state. Optimization problems itself are not allowed
163 /// to have state which changes during an optimization (at least not in the context of
164 /// checkpointing).
165 fn save(&self, solver: &S, state: &I) -> Result<(), Error>;
166
167 /// Saves a checkpoint when the checkpointing condition is met.
168 ///
169 /// Calls [`save`](`Checkpoint::save`) in each iteration (`CheckpointingFrequency::Always`),
170 /// every X iterations (`CheckpointingFrequency::Every(X)`) or never
171 /// (`CheckpointingFrequency::Never`).
172 fn save_cond(&self, solver: &S, state: &I, iter: u64) -> Result<(), Error> {
173 match self.frequency() {
174 CheckpointingFrequency::Always => self.save(solver, state)?,
175 CheckpointingFrequency::Every(it) if iter.is_multiple_of(it) => {
176 self.save(solver, state)?
177 }
178 CheckpointingFrequency::Never | CheckpointingFrequency::Every(_) => {}
179 };
180 Ok(())
181 }
182
183 /// Loads a saved checkpoint
184 ///
185 /// Returns the solver of type `S` and the `state` of type `I`.
186 fn load(&self) -> Result<Option<(S, I)>, Error>;
187
188 /// Indicates how often checkpoints should be saved
189 ///
190 /// Returns enum `CheckpointingFrequency`.
191 fn frequency(&self) -> CheckpointingFrequency;
192}
193
194/// Defines at which intervals a checkpoint is saved.
195///
196/// # Example
197///
198/// ```
199/// use argmin::core::checkpointing::CheckpointingFrequency;
200///
201/// // A checkpoint every 10 iterations
202/// let every_10 = CheckpointingFrequency::Every(10);
203///
204/// // A checkpoint in each iteration
205/// let always = CheckpointingFrequency::Always;
206///
207/// // The default is `CheckpointingFrequency::Always`
208/// assert_eq!(CheckpointingFrequency::default(), CheckpointingFrequency::Always);
209/// ```
210#[derive(Clone, Eq, PartialEq, Debug, Hash, Copy, Default)]
211pub enum CheckpointingFrequency {
212 /// Never create checkpoint
213 Never,
214 /// Create checkpoint every N iterations
215 Every(u64),
216 /// Create checkpoint in every iteration
217 #[default]
218 Always,
219}
220
221impl Display for CheckpointingFrequency {
222 fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
223 match *self {
224 CheckpointingFrequency::Never => write!(f, "Never"),
225 CheckpointingFrequency::Every(i) => write!(f, "Every({i})"),
226 CheckpointingFrequency::Always => write!(f, "Always"),
227 }
228 }
229}