Skip to main content

oa/ml/training/callback/
phase.rs

1//! Multi-phase training callback.
2//!
3//! Port provenance: `oa/ml/callbacks.h` (`CbPhase`).
4
5use crate::{Error, Result};
6
7use super::super::{
8	Optimizer, TrainingCallback, TrainingCallbackContext, TrainingConfig, TrainingControl,
9};
10use super::write_stdout;
11
12/// One consecutive epoch range in a [`PhaseCallback`].
13#[derive(Clone, Debug, PartialEq, Eq)]
14pub struct TrainingPhase {
15	id: String,
16	epochs: u64,
17	steps: u64,
18}
19
20impl TrainingPhase {
21	/// Construct a named phase with aggregate epoch and step counts.
22	///
23	/// # Errors
24	///
25	/// Returns an error for an empty name, zero epochs, or fewer than one step
26	/// per epoch.
27	pub fn new(id: impl Into<String>, epochs: u64, steps: u64) -> Result<Self> {
28		let id = id.into();
29		if id.is_empty() {
30			return Err(Error::invalid_argument(
31				"training phase name must not be empty",
32			));
33		}
34		if epochs == 0 {
35			return Err(Error::invalid_argument(
36				"training phase must contain at least one epoch",
37			));
38		}
39		if steps < epochs {
40			return Err(Error::invalid_argument(
41				"training phase must contain at least one step per epoch",
42			));
43		}
44		Ok(Self { id, epochs, steps })
45	}
46
47	/// Return the stable phase identifier.
48	pub fn id(&self) -> &str {
49		&self.id
50	}
51
52	/// Return the number of epochs in this phase.
53	pub const fn epochs(&self) -> u64 {
54		self.epochs
55	}
56
57	/// Return the aggregate step count across this phase.
58	pub const fn steps(&self) -> u64 {
59		self.steps
60	}
61}
62
63type PhaseBeginHook<'hook> =
64	Box<dyn FnMut(usize, &TrainingPhase, &mut dyn Optimizer) -> Result<()> + 'hook>;
65
66/// Consecutive phase policy over one [`super::super::Training`] lifecycle.
67///
68/// The phase schedule does not own another iterator. Its epoch/step totals must
69/// exactly match the iterator configuration, and its optional transition hook
70/// receives restricted mutable access to the iterator's existing optimizer.
71pub struct PhaseCallback<'hook> {
72	phases: Vec<TrainingPhase>,
73	on_phase_begin: Option<PhaseBeginHook<'hook>>,
74	current_phase: Option<usize>,
75}
76
77impl<'hook> PhaseCallback<'hook> {
78	/// Construct an empty phase schedule.
79	pub const fn new() -> Self {
80		Self {
81			phases: Vec::new(),
82			on_phase_begin: None,
83			current_phase: None,
84		}
85	}
86
87	/// Append a consecutive phase.
88	///
89	/// # Errors
90	///
91	/// Returns an error for invalid phase fields or aggregate count overflow.
92	pub fn add_phase(&mut self, id: impl Into<String>, epochs: u64, steps: u64) -> Result<()> {
93		let phase = TrainingPhase::new(id, epochs, steps)?;
94		let _ = self
95			.total_epochs()
96			.checked_add(epochs)
97			.ok_or_else(|| Error::resource_exhausted("training phase epoch count overflows u64"))?;
98		let _ = self
99			.total_steps()
100			.checked_add(steps)
101			.ok_or_else(|| Error::resource_exhausted("training phase step count overflows u64"))?;
102		self.phases.push(phase);
103		Ok(())
104	}
105
106	/// Install the hook invoked exactly once when each phase begins.
107	pub fn set_on_phase_begin(
108		&mut self,
109		hook: impl FnMut(usize, &TrainingPhase, &mut dyn Optimizer) -> Result<()> + 'hook,
110	) {
111		self.on_phase_begin = Some(Box::new(hook));
112	}
113
114	/// Return all configured phases in execution order.
115	pub fn phases(&self) -> &[TrainingPhase] {
116		&self.phases
117	}
118
119	/// Return the currently entered phase index.
120	pub const fn current_phase(&self) -> Option<usize> {
121		self.current_phase
122	}
123
124	/// Return the aggregate epoch count.
125	pub fn total_epochs(&self) -> u64 {
126		self.phases.iter().map(TrainingPhase::epochs).sum()
127	}
128
129	/// Return the aggregate step count.
130	pub fn total_steps(&self) -> u64 {
131		self.phases.iter().map(TrainingPhase::steps).sum()
132	}
133
134	fn validate_config(&self, config: &TrainingConfig) -> Result<()> {
135		if self.phases.is_empty() {
136			return Ok(());
137		}
138		let actual = configured_epoch_steps(config)?;
139		let expected_epochs = usize::try_from(self.total_epochs())
140			.map_err(|_| Error::resource_exhausted("training phase epoch count exceeds usize"))?;
141		if actual.len() != expected_epochs {
142			return Err(Error::invalid_argument(format!(
143				"training phase schedule defines {expected_epochs} epochs but iterator defines {}",
144				actual.len()
145			)));
146		}
147
148		let mut epoch = 0_usize;
149		for phase in &self.phases {
150			let phase_epochs = usize::try_from(phase.epochs)
151				.map_err(|_| Error::resource_exhausted("training phase epoch count exceeds usize"))?;
152			let end = epoch
153				.checked_add(phase_epochs)
154				.ok_or_else(|| Error::resource_exhausted("training phase epoch range overflows usize"))?;
155			let actual_steps = actual[epoch..end].iter().try_fold(0_u64, |sum, steps| {
156				sum
157					.checked_add(*steps)
158					.ok_or_else(|| Error::resource_exhausted("iterator phase step count overflows u64"))
159			})?;
160			if actual_steps != phase.steps {
161				return Err(Error::invalid_argument(format!(
162					"training phase {} defines {} steps but its iterator epochs contain {actual_steps}",
163					phase.id, phase.steps
164				)));
165			}
166			epoch = end;
167		}
168		Ok(())
169	}
170
171	/// Resolve a one-based global epoch to its phase index and one-based local epoch.
172	///
173	/// This query does not enter a phase or invoke its hook. Workloads that retain
174	/// their own checkpoint boundaries can resolve restored progress without
175	/// restarting callback accounting.
176	///
177	/// # Errors
178	///
179	/// Returns an error for zero or an epoch outside the configured schedule.
180	pub fn phase_for_epoch(&self, epoch: u64) -> Result<(usize, u64)> {
181		if epoch == 0 {
182			return Err(Error::failed_precondition(
183				"training phase callback requires a one-based epoch",
184			));
185		}
186		let mut epochs_before = 0_u64;
187		for (index, phase) in self.phases.iter().enumerate() {
188			let end = epochs_before
189				.checked_add(phase.epochs)
190				.ok_or_else(|| Error::resource_exhausted("training phase epoch range overflows u64"))?;
191			if epoch <= end {
192				return Ok((index, epoch - epochs_before));
193			}
194			epochs_before = end;
195		}
196		Err(Error::failed_precondition(format!(
197			"training epoch {epoch} is outside the configured phase schedule"
198		)))
199	}
200
201	fn render_schedule(&self) -> String {
202		let mut output = String::from("phase schedule:\n");
203		for (index, phase) in self.phases.iter().enumerate() {
204			let suffix = if phase.epochs == 1 { "" } else { "s" };
205			output.push_str(&format!(
206				"  {}. {:<8} — {} epoch{} ({} steps)\n",
207				index + 1,
208				phase.id,
209				phase.epochs,
210				suffix,
211				phase.steps,
212			));
213		}
214		output
215	}
216}
217
218impl Default for PhaseCallback<'_> {
219	fn default() -> Self {
220		Self::new()
221	}
222}
223
224impl TrainingCallback for PhaseCallback<'_> {
225	fn on_train_begin(
226		&mut self,
227		context: &mut TrainingCallbackContext<'_>,
228	) -> Result<TrainingControl> {
229		self.current_phase = None;
230		self.validate_config(context.config())?;
231		if !self.phases.is_empty() {
232			write_stdout(&self.render_schedule())?;
233		}
234		Ok(TrainingControl::Continue)
235	}
236
237	fn on_epoch_begin(
238		&mut self,
239		context: &mut TrainingCallbackContext<'_>,
240	) -> Result<TrainingControl> {
241		if self.phases.is_empty() {
242			return Ok(TrainingControl::Continue);
243		}
244		let (index, epoch_in_phase) = self.phase_for_epoch(context.snapshot().epoch())?;
245		let phase = &self.phases[index];
246		if self.current_phase != Some(index) {
247			self.current_phase = Some(index);
248			let suffix = if phase.epochs == 1 { "" } else { "s" };
249			let steps_per_epoch = phase.steps / phase.epochs;
250			write_stdout(&format!(
251				"\nPhase {}/{} — {} · {} epoch{} × {} steps\n",
252				index + 1,
253				self.phases.len(),
254				phase.id,
255				phase.epochs,
256				suffix,
257				steps_per_epoch,
258			))?;
259			if let Some(hook) = &mut self.on_phase_begin {
260				hook(index, phase, context.optimizer())?;
261			}
262		}
263		write_stdout(&format!("epoch {epoch_in_phase}/{}\n", phase.epochs))?;
264		Ok(TrainingControl::Continue)
265	}
266}
267
268fn configured_epoch_steps(config: &TrainingConfig) -> Result<Vec<u64>> {
269	if !config.epoch_steps.is_empty() {
270		return Ok(config.epoch_steps.clone());
271	}
272	if config.steps_per_epoch == 0 || config.total_steps == 0 {
273		return Ok(Vec::new());
274	}
275	let epoch_count = config.total_steps.div_ceil(config.steps_per_epoch);
276	let capacity = usize::try_from(epoch_count)
277		.map_err(|_| Error::resource_exhausted("iterator epoch count exceeds usize"))?;
278	let mut epochs = Vec::new();
279	epochs
280		.try_reserve_exact(capacity)
281		.map_err(|_| Error::resource_exhausted("iterator epoch schedule allocation failed"))?;
282	let mut remaining = config.total_steps;
283	while remaining > 0 {
284		let steps = remaining.min(config.steps_per_epoch);
285		epochs.push(steps);
286		remaining -= steps;
287	}
288	Ok(epochs)
289}