1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
use crate::checkpoint::{
AsyncCheckpointer, Checkpointer, CheckpointingAction, CheckpointingStrategy,
};
use crate::metric::store::EventStoreClient;
use crate::{
CloneEarlyStoppingStrategy, LearnerModel, TrainOutput, TrainStep, TrainingModelInput,
TrainingModelOutput,
};
use burn_core::store::ModuleRecord;
use burn_core::tensor::Device;
use burn_optim::lr_scheduler::LrSchedulerRecord;
use burn_optim::lr_scheduler::module_lr_scheduler::{ModuleLearningRate, ModuleLrScheduler};
use burn_optim::{GradientsParams, ModuleOptimizer, MultiGradientsParams, OptimizerRecord};
use std::marker::PhantomData;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
/// Learner struct encapsulating all components necessary to train a Neural Network model.
pub struct Learner<M: LearnerModel> {
pub(crate) model: M,
optim: ModuleOptimizer,
lr_scheduler: ModuleLrScheduler,
lr_module: ModuleLearningRate,
}
impl<M: LearnerModel> Clone for Learner<M> {
fn clone(&self) -> Self {
Self {
model: self.model.clone(),
optim: self.optim.clone(),
lr_scheduler: self.lr_scheduler.clone(),
lr_module: self.lr_module.clone(),
}
}
}
impl<M: LearnerModel> Learner<M> {
/// Create a learner.
pub fn new(
model: M,
optim: ModuleOptimizer,
lr_scheduler: impl Into<ModuleLrScheduler>,
) -> Self {
Self {
model,
optim,
lr_scheduler: lr_scheduler.into(),
lr_module: 0.0.into(),
}
}
}
impl<M: LearnerModel> Learner<M> {
/// Fork the learner's model to the given device.
pub fn fork(&mut self, device: &Device) {
self.model = self.model().fork(device);
}
/// Returns the current model.
pub fn model(&self) -> M {
self.model.clone()
}
/// Returns the current learning rate.
pub fn lr_current(&self) -> ModuleLearningRate {
self.lr_module.clone()
}
/// Executes a step of the learning rate scheduler.
pub fn lr_step(&mut self) {
self.lr_module = self.lr_scheduler.step();
}
/// Runs a step of the model for training, which executes the forward and backward passes.
///
/// # Arguments
///
/// * `item` - The input for the model.
///
/// # Returns
///
/// The output containing the model output and the gradients.
pub fn train_step(&self, item: TrainingModelInput<M>) -> TrainOutput<TrainingModelOutput<M>> {
TrainStep::step(&self.model, item)
}
/// Optimize the current module with the provided gradients and learning rate.
///
/// # Arguments
///
/// * `optim`: Optimizer used for learning.
/// * `lr`: The learning rate used for this step.
/// * `grads`: The gradients of each parameter in the current model.
pub fn optimizer_step(&mut self, grads: GradientsParams) {
self.model = self
.model()
.optimize(&mut self.optim, self.lr_module.clone(), grads);
}
/// Optimize the current module with the provided gradients and learning rate.
///
/// # Arguments
///
/// * `optim`: Optimizer used for learning.
/// * `lr`: The learning rate used for this step.
/// * `grads`: Multiple gradients associated to each parameter in the current model.
pub fn optimizer_step_multi(&mut self, grads: MultiGradientsParams) {
self.model = self
.model()
.optimize_multi(&mut self.optim, self.lr_module.clone(), grads);
}
/// Load the module state from a [record](ModuleRecord).
pub fn load_model(&mut self, record: ModuleRecord) {
self.model = self.model.clone().load_record(record);
}
/// Load the state of the learner's optimizer from a [record](OptimizerRecord).
///
/// No device is needed: the optimizer state is migrated to each parameter's device on the next
/// step (see [`ModuleOptimizer::load_record`](burn_optim::ModuleOptimizer::load_record)).
pub fn load_optim(&mut self, record: OptimizerRecord) {
self.optim = self.optim.clone().load_record(record);
}
/// Load the state of the learner's scheduler from a [record](LrSchedulerRecord).
pub fn load_scheduler(&mut self, record: LrSchedulerRecord) {
self.lr_scheduler = self.lr_scheduler.clone().load_record(record);
}
}
/// Used to create, delete, or load checkpoints of the training process.
pub struct LearningCheckpointer<M: LearnerModel> {
model: AsyncCheckpointer<ModuleRecord>,
optim: AsyncCheckpointer<OptimizerRecord>,
lr_scheduler: AsyncCheckpointer<LrSchedulerRecord>,
strategy: Box<dyn CheckpointingStrategy>,
_phantom: PhantomData<M>,
}
impl<M: LearnerModel> LearningCheckpointer<M> {
/// Create a new learning checkpointer.
pub fn new(
model: AsyncCheckpointer<ModuleRecord>,
optim: AsyncCheckpointer<OptimizerRecord>,
lr_scheduler: AsyncCheckpointer<LrSchedulerRecord>,
strategy: Box<dyn CheckpointingStrategy>,
) -> Self {
Self {
model,
optim,
lr_scheduler,
strategy,
_phantom: PhantomData,
}
}
/// Create checkpoint for the training process.
pub fn checkpoint(&mut self, learner: &Learner<M>, epoch: usize, store: &EventStoreClient) {
let actions = self.strategy.checkpointing(epoch, store);
for action in actions {
match action {
CheckpointingAction::Delete(epoch) => {
self.model
.delete(epoch)
.expect("Can delete model checkpoint.");
self.optim
.delete(epoch)
.expect("Can delete optimizer checkpoint.");
self.lr_scheduler
.delete(epoch)
.expect("Can delete learning rate scheduler checkpoint.");
}
CheckpointingAction::Save => {
self.model
.save(epoch, learner.model.clone().into_record())
.expect("Can save model checkpoint.");
self.optim
.save(epoch, learner.optim.to_record())
.expect("Can save optimizer checkpoint.");
self.lr_scheduler
.save(epoch, learner.lr_scheduler.to_record())
.expect("Can save learning rate scheduler checkpoint.");
}
}
}
}
/// Load a training checkpoint.
///
/// No device is taken: checkpoints are device-free burnpack records (file-backed bytes). On
/// load, the model keeps the device of the learner's existing parameters, and the optimizer
/// state is migrated to each parameter's device on the next step. The training device is fixed
/// earlier, when the learner's model is created/forked.
pub fn load_checkpoint(&self, mut learner: Learner<M>, epoch: usize) -> Learner<M> {
let record = self
.model
.restore(epoch)
.expect("Can load model checkpoint.");
learner.load_model(record);
let record = self
.optim
.restore(epoch)
.expect("Can load optimizer checkpoint.");
learner.load_optim(record);
let record = self
.lr_scheduler
.restore(epoch)
.expect("Can load learning rate scheduler checkpoint.");
learner.load_scheduler(record);
learner
}
}
/// Cloneable reference to an early stopping strategy
pub(crate) type EarlyStoppingStrategyRef = Box<dyn CloneEarlyStoppingStrategy>;
#[derive(Clone, Default)]
/// A handle that allows aborting the training/evaluation process early.
pub struct Interrupter {
state: Arc<AtomicBool>,
message: Arc<Mutex<Option<String>>>,
}
impl Interrupter {
/// Create a new instance.
pub fn new() -> Self {
Self::default()
}
/// Notify the learner that it should stop.
/// # Arguments
/// * `reason` - A string describing the reason the training was stopped.
pub fn stop(&self, reason: Option<&str>) {
self.state.store(true, Ordering::Relaxed);
reason.inspect(|r| {
let mut message = self.message.lock().unwrap();
*message = Some(String::from(*r));
});
}
/// Reset the interrupter.
pub fn reset(&self) {
self.state.store(false, Ordering::Relaxed);
}
/// True if .stop() has been called.
pub fn should_stop(&self) -> bool {
self.state.load(Ordering::Relaxed)
}
/// Get the message associated with the interrupt.
pub fn get_message(&self) -> Option<String> {
let message = self.message.lock().unwrap();
message.clone()
}
}