oa/ml/training/callback/
phase.rs1use crate::{Error, Result};
6
7use super::super::{
8 Optimizer, TrainingCallback, TrainingCallbackContext, TrainingConfig, TrainingControl,
9};
10use super::write_stdout;
11
12#[derive(Clone, Debug, PartialEq, Eq)]
14pub struct TrainingPhase {
15 id: String,
16 epochs: u64,
17 steps: u64,
18}
19
20impl TrainingPhase {
21 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 pub fn id(&self) -> &str {
49 &self.id
50 }
51
52 pub const fn epochs(&self) -> u64 {
54 self.epochs
55 }
56
57 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
66pub 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 pub const fn new() -> Self {
80 Self {
81 phases: Vec::new(),
82 on_phase_begin: None,
83 current_phase: None,
84 }
85 }
86
87 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 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 pub fn phases(&self) -> &[TrainingPhase] {
116 &self.phases
117 }
118
119 pub const fn current_phase(&self) -> Option<usize> {
121 self.current_phase
122 }
123
124 pub fn total_epochs(&self) -> u64 {
126 self.phases.iter().map(TrainingPhase::epochs).sum()
127 }
128
129 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 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}