1use crate::{Error, Result, ml::EarlyStoppingState};
6
7use super::super::{
8 LrScheduler, TrainingCallback, TrainingCallbackContext, TrainingControl, TrainingSnapshot,
9};
10use super::validation::ValidationMetric;
11
12#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
14pub enum EarlyStopMode {
15 #[default]
17 Min,
18 Max,
20}
21
22enum MonitorSource {
25 Closure(Box<dyn Fn(TrainingSnapshot) -> f64>),
27 Committed { split: String, name: String },
29}
30
31pub struct EarlyStoppingCallback {
32 patience: u64,
33 min_delta: f64,
34 mode: EarlyStopMode,
35 metric_name: String,
36 monitor: MonitorSource,
37 best: f64,
38 bad_epochs: u64,
39 stop: bool,
40}
41
42impl EarlyStoppingCallback {
43 pub fn new(patience: u64, min_delta: f64, mode: EarlyStopMode) -> Result<Self> {
49 Self::new_with_monitor(patience, min_delta, mode, "loss", |snapshot| {
50 snapshot.epoch_mean_loss()
51 })
52 }
53
54 pub fn new_with_monitor(
64 patience: u64,
65 min_delta: f64,
66 mode: EarlyStopMode,
67 metric_name: impl Into<String>,
68 monitor: impl Fn(TrainingSnapshot) -> f64 + 'static,
69 ) -> Result<Self> {
70 if !min_delta.is_finite() || min_delta < 0.0 {
71 return Err(Error::invalid_argument(
72 "early-stop minimum delta must be finite and non-negative",
73 ));
74 }
75 let metric_name = metric_name.into();
76 if metric_name.is_empty() {
77 return Err(Error::invalid_argument(
78 "early-stop metric name must not be empty",
79 ));
80 }
81 Ok(Self {
82 patience,
83 min_delta,
84 mode,
85 metric_name,
86 monitor: MonitorSource::Closure(Box::new(monitor)),
87 best: match mode {
88 EarlyStopMode::Min => f64::INFINITY,
89 EarlyStopMode::Max => f64::NEG_INFINITY,
90 },
91 bad_epochs: 0,
92 stop: false,
93 })
94 }
95
96 pub fn new_with_validation_metric(
107 patience: u64,
108 min_delta: f64,
109 mode: EarlyStopMode,
110 metric: ValidationMetric,
111 ) -> Result<Self> {
112 let name = metric.name().to_owned();
113 Self::new_with_monitor(patience, min_delta, mode, name, move |_| metric.result())
114 }
115
116 pub const fn should_stop(&self) -> bool {
118 self.stop
119 }
120
121 pub const fn best(&self) -> f64 {
123 self.best
124 }
125
126 pub const fn bad_epochs(&self) -> u64 {
128 self.bad_epochs
129 }
130
131 pub const fn capture_state(&self) -> EarlyStoppingState {
134 EarlyStoppingState {
135 best: self.best,
136 bad_epochs: self.bad_epochs,
137 }
138 }
139
140 pub fn restore_state(&mut self, state: EarlyStoppingState) -> Result<()> {
150 if state.best.is_nan()
151 || (self.mode == EarlyStopMode::Min && state.best == f64::NEG_INFINITY)
152 || (self.mode == EarlyStopMode::Max && state.best == f64::INFINITY)
153 {
154 return Err(Error::invalid_argument(
155 "restored early-stopping best metric is invalid for improvement mode",
156 ));
157 }
158 if !state.best.is_finite() && state.bad_epochs > 0 {
159 return Err(Error::invalid_argument(
160 "restored early-stopping bad_epochs requires a finite best metric",
161 ));
162 }
163 self.best = state.best;
164 self.bad_epochs = state.bad_epochs;
165 self.stop = state.bad_epochs > 0 && state.bad_epochs >= self.patience;
166 Ok(())
167 }
168}
169
170impl EarlyStoppingCallback {
171 pub fn new_with_committed(
183 patience: u64,
184 min_delta: f64,
185 mode: EarlyStopMode,
186 split: impl Into<String>,
187 name: impl Into<String>,
188 ) -> Result<Self> {
189 let split = split.into();
190 let name = name.into();
191 if name.is_empty() {
192 return Err(Error::invalid_argument(
193 "early-stop metric name must not be empty",
194 ));
195 }
196 if !min_delta.is_finite() || min_delta < 0.0 {
197 return Err(Error::invalid_argument(
198 "early-stop minimum delta must be finite and non-negative",
199 ));
200 }
201 Ok(Self {
202 patience,
203 min_delta,
204 mode,
205 metric_name: format!("{split}/{name}"),
206 monitor: MonitorSource::Committed { split, name },
207 best: match mode {
208 EarlyStopMode::Min => f64::INFINITY,
209 EarlyStopMode::Max => f64::NEG_INFINITY,
210 },
211 bad_epochs: 0,
212 stop: false,
213 })
214 }
215}
216
217impl Default for EarlyStoppingCallback {
218 fn default() -> Self {
219 Self::new(5, 1.0e-4, EarlyStopMode::Min).expect("the constant OA early-stop defaults are valid")
220 }
221}
222
223impl TrainingCallback for EarlyStoppingCallback {
224 fn on_epoch_end(&mut self, context: &mut TrainingCallbackContext<'_>) -> Result<TrainingControl> {
225 let snapshot = context.snapshot();
226 let metric = match &self.monitor {
227 MonitorSource::Closure(monitor) => monitor(snapshot),
228 MonitorSource::Committed { split, name } => {
229 context.latest_committed(split, name).unwrap_or(f64::NAN)
230 }
231 };
232 if !metric.is_finite() {
233 return Err(Error::callback(format!(
234 "early-stop metric {} is not finite",
235 self.metric_name
236 )));
237 }
238 let improved = match self.mode {
239 EarlyStopMode::Min => metric < self.best - self.min_delta,
240 EarlyStopMode::Max => metric > self.best + self.min_delta,
241 };
242 if improved {
243 self.best = metric;
244 self.bad_epochs = 0;
245 return Ok(TrainingControl::Continue);
246 }
247 self.bad_epochs = self.bad_epochs.saturating_add(1);
248 if self.bad_epochs >= self.patience {
249 self.stop = true;
250 crate::log_info!(
251 crate::LogComponent::ML,
252 "epoch {}: early stopping; {} did not improve for {} epochs (best {:.6})",
253 snapshot.epoch(),
254 self.metric_name,
255 self.bad_epochs,
256 self.best
257 );
258 Ok(TrainingControl::Stop)
259 } else {
260 Ok(TrainingControl::Continue)
261 }
262 }
263}
264
265pub struct LearningRateCallback<'schedule> {
267 schedule: &'schedule dyn LrScheduler,
268}
269
270impl<'schedule> LearningRateCallback<'schedule> {
271 pub const fn new(schedule: &'schedule dyn LrScheduler) -> Self {
273 Self { schedule }
274 }
275}
276
277impl TrainingCallback for LearningRateCallback<'_> {
278 fn on_step_end(&mut self, context: &mut TrainingCallbackContext<'_>) -> Result<TrainingControl> {
279 let next_step = context.snapshot().step_count().saturating_add(1);
280 let learning_rate = self.schedule.learning_rate(next_step);
281 context.optimizer().set_learning_rate(learning_rate)?;
282 Ok(TrainingControl::Continue)
283 }
284}