Skip to main content

oa/ml/training/callback/
policy.rs

1//! Donor-backed training-control and optimizer-policy callbacks.
2//!
3//! Port provenance: `oa/ml/callbacks.h`.
4
5use crate::{Error, Result, ml::EarlyStoppingState};
6
7use super::super::{
8	LrScheduler, TrainingCallback, TrainingCallbackContext, TrainingControl, TrainingSnapshot,
9};
10use super::validation::ValidationMetric;
11
12/// Improvement direction for [`EarlyStoppingCallback`].
13#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
14pub enum EarlyStopMode {
15	/// A lower monitored value is better.
16	#[default]
17	Min,
18	/// A higher monitored value is better.
19	Max,
20}
21
22/// Cooperative epoch-boundary early stopping.
23/// Where the early-stopping callback reads its monitored value.
24enum MonitorSource {
25	/// Application-owned closure sampled from the completed snapshot.
26	Closure(Box<dyn Fn(TrainingSnapshot) -> f64>),
27	/// Latest value committed to the shared history bus under split/name.
28	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	/// Monitor the completed epoch's mean training loss.
44	///
45	/// # Errors
46	///
47	/// Returns an error when `min_delta` is not finite and non-negative.
48	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	/// Monitor an application-owned metric sampled from the completed snapshot.
55	///
56	/// The closure can capture shared validation state; it is invoked only at an
57	/// epoch boundary and never owns or re-enters the training loop.
58	///
59	/// # Errors
60	///
61	/// Returns an error when the metric name is empty or `min_delta` is not finite
62	/// and non-negative.
63	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	/// Monitor the result produced by a preceding [`ValidationCallback`](super::super::ValidationCallback)
97	/// callback.
98	///
99	/// Register validation before this callback. A missing or non-finite
100	/// validation result fails the lifecycle instead of silently acting as a
101	/// non-improving epoch.
102	///
103	/// # Errors
104	///
105	/// Returns an error when `min_delta` is not finite and non-negative.
106	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	/// Return whether this callback has requested termination.
117	pub const fn should_stop(&self) -> bool {
118		self.stop
119	}
120
121	/// Return the best monitored value observed so far.
122	pub const fn best(&self) -> f64 {
123		self.best
124	}
125
126	/// Return consecutive non-improving epochs since the last improvement.
127	pub const fn bad_epochs(&self) -> u64 {
128		self.bad_epochs
129	}
130
131	/// Capture the best monitored value and consecutive non-improving epoch
132	/// counter for `.runstate` persistence.
133	pub const fn capture_state(&self) -> EarlyStoppingState {
134		EarlyStoppingState {
135			best: self.best,
136			bad_epochs: self.bad_epochs,
137		}
138	}
139
140	/// Restore early-stopping selection criteria from a `.runstate` companion.
141	///
142	/// Rejects NaN and an infinite sentinel whose sign disagrees with this
143	/// callback's improvement mode.
144	///
145	/// # Errors
146	///
147	/// Returns an error when `state.best` is NaN or carries the opposite
148	/// infinity sentinel for this callback's improvement mode.
149	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	/// Monitor the latest value committed to the shared history bus under
172	/// `split`/`name`.
173	///
174	/// The committing callback — validation, or a caller-defined commit — must
175	/// register before early stopping so the value exists at the boundary.
176	/// A missing or non-finite committed value is a configuration error.
177	///
178	/// # Errors
179	///
180	/// Returns an error when the metric name is empty or `min_delta` is not
181	/// finite and non-negative.
182	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
265/// Applies a learning-rate schedule after every completed optimizer step.
266pub struct LearningRateCallback<'schedule> {
267	schedule: &'schedule dyn LrScheduler,
268}
269
270impl<'schedule> LearningRateCallback<'schedule> {
271	/// Borrow a schedule for the callback's lifetime.
272	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}