1pub use crate::ml::types::ValidationResult;
4use std::{
5 io::{self, Write},
6 time::{Duration, Instant},
7};
8
9use crate::{Error, Result};
10
11use super::{
12 CommittedMetric, TrainingCallbackContext, TrainingConfig, TrainingControl, TrainingSnapshot,
13};
14
15mod checkpoint;
16mod csv;
17mod phase;
18mod policy;
19mod validation;
20
21pub use checkpoint::CheckpointCallback;
22pub use csv::CsvLoggerCallback;
23pub use phase::{PhaseCallback, TrainingPhase};
24pub use policy::{EarlyStopMode, EarlyStoppingCallback, LearningRateCallback};
25pub use validation::{ValidationCallback, ValidationMetric};
26
27pub trait TrainingCallback {
29 fn on_train_begin(
30 &mut self,
31 _context: &mut TrainingCallbackContext<'_>,
32 ) -> Result<TrainingControl> {
33 Ok(TrainingControl::Continue)
34 }
35
36 fn on_epoch_begin(
37 &mut self,
38 _context: &mut TrainingCallbackContext<'_>,
39 ) -> Result<TrainingControl> {
40 Ok(TrainingControl::Continue)
41 }
42
43 fn on_step_end(&mut self, _context: &mut TrainingCallbackContext<'_>) -> Result<TrainingControl> {
44 Ok(TrainingControl::Continue)
45 }
46
47 fn on_epoch_end(
48 &mut self,
49 _context: &mut TrainingCallbackContext<'_>,
50 ) -> Result<TrainingControl> {
51 Ok(TrainingControl::Continue)
52 }
53
54 fn on_train_end(
55 &mut self,
56 _context: &mut TrainingCallbackContext<'_>,
57 ) -> Result<TrainingControl> {
58 Ok(TrainingControl::Continue)
59 }
60}
61
62pub struct ProgressBarCallback {
64 width: usize,
65 show_epoch_header: bool,
66 last_print: Option<Instant>,
67 last_finalized_step: u64,
68}
69
70impl ProgressBarCallback {
71 pub fn new(width: usize) -> Self {
73 Self {
74 width: width.max(1),
75 show_epoch_header: true,
76 last_print: None,
77 last_finalized_step: 0,
78 }
79 }
80
81 pub fn set_show_epoch_header(&mut self, show: bool) {
83 self.show_epoch_header = show;
84 }
85
86 pub fn render_line(&self, state: TrainingSnapshot, config: &TrainingConfig) -> String {
88 let has_epochs = state.total_epochs() > 0;
89 let step = if has_epochs {
90 state.step_in_epoch()
91 } else {
92 state.step_count()
93 };
94 let total = if has_epochs {
95 state.steps_in_epoch()
96 } else {
97 state.total_steps()
98 };
99 let elapsed = if has_epochs {
100 state.epoch_elapsed()
101 } else {
102 state.elapsed()
103 };
104 let mut line = String::from("\r ");
105 if total > 0 {
106 let eighths = ((step as u128 * self.width as u128 * 8 + u128::from(total / 2))
107 / u128::from(total)) as usize;
108 let full = (eighths / 8).min(self.width);
109 let partial = eighths % 8;
110 line.push_str(&format!("{step}/{total} |"));
111 line.push_str(&"█".repeat(full));
112 if full < self.width && partial > 0 {
113 line.push_str(["", "▏", "▎", "▍", "▌", "▋", "▊", "▉"][partial]);
114 line.push_str(&"░".repeat(self.width - full - 1));
115 } else {
116 line.push_str(&"░".repeat(self.width - full));
117 }
118 line.push_str("| ");
119 } else {
120 line.push_str(&format!("step {step} "));
121 }
122 let seconds = elapsed.as_secs_f64();
123 let milliseconds = if step > 0 {
124 seconds * 1000.0 / step as f64
125 } else {
126 0.0
127 };
128 let samples_per_second = if seconds > 0.0 {
129 step as f64 * config.batch_size as f64 / seconds
130 } else {
131 0.0
132 };
133 line.push_str(&format!(
134 "{seconds:.2}s · {milliseconds:.2} ms/step · {} sample/s",
135 format_rate(samples_per_second)
136 ));
137 if config.sequence_length > 0 {
138 line.push_str(&format!(
139 " · {} {}/s",
140 format_rate(samples_per_second * config.sequence_length as f64),
141 config.sequence_unit
142 ));
143 }
144 if state.total_source_units() > 0 {
145 let rate = if has_epochs {
146 state.epoch_source_units_per_second()
147 } else {
148 state.wall_source_units_per_second()
149 };
150 line.push_str(&format!(
151 " · {} {}/s",
152 format_rate(rate),
153 config.source_unit
154 ));
155 }
156 if let Some(loss) = state.last_loss() {
157 line.push_str(&format!(" · loss: {loss:.4}"));
158 }
159 line.push_str(" ");
160 line
161 }
162
163 fn render(&self, context: &TrainingCallbackContext<'_>, newline: bool) -> Result<()> {
164 let mut output = self.render_line(context.snapshot(), context.config());
165 if newline {
166 output.push('\n');
167 }
168 write_stdout(&output)
169 }
170}
171
172impl Default for ProgressBarCallback {
173 fn default() -> Self {
174 Self::new(10)
175 }
176}
177
178impl TrainingCallback for ProgressBarCallback {
179 fn on_train_begin(
180 &mut self,
181 _context: &mut TrainingCallbackContext<'_>,
182 ) -> Result<TrainingControl> {
183 self.last_print = Some(Instant::now());
184 Ok(TrainingControl::Continue)
185 }
186
187 fn on_epoch_begin(
188 &mut self,
189 context: &mut TrainingCallbackContext<'_>,
190 ) -> Result<TrainingControl> {
191 let state = context.snapshot();
192 if self.show_epoch_header && state.total_epochs() > 0 {
193 write_stdout(&format!(
194 "epoch {}/{}\n",
195 state.epoch(),
196 state.total_epochs()
197 ))?;
198 }
199 Ok(TrainingControl::Continue)
200 }
201
202 fn on_step_end(&mut self, context: &mut TrainingCallbackContext<'_>) -> Result<TrainingControl> {
203 let state = context.snapshot();
204 if state.is_epoch_boundary() {
205 return Ok(TrainingControl::Continue);
206 }
207 let now = Instant::now();
208 let boundary = state.is_last_step();
209 if !boundary
210 && self
211 .last_print
212 .is_some_and(|last| now.duration_since(last) < Duration::from_millis(33))
213 {
214 return Ok(TrainingControl::Continue);
215 }
216 self.last_print = Some(now);
217 self.render(context, boundary)?;
218 if boundary {
219 self.last_finalized_step = state.step_count();
220 }
221 Ok(TrainingControl::Continue)
222 }
223
224 fn on_epoch_end(&mut self, context: &mut TrainingCallbackContext<'_>) -> Result<TrainingControl> {
225 self.render(context, true)?;
226 self.last_finalized_step = context.snapshot().step_count();
227 Ok(TrainingControl::Continue)
228 }
229
230 fn on_train_end(&mut self, context: &mut TrainingCallbackContext<'_>) -> Result<TrainingControl> {
231 let state = context.snapshot();
232 if self.last_finalized_step != state.step_count() {
233 self.render(context, true)?;
234 }
235 Ok(TrainingControl::Continue)
236 }
237}
238
239pub struct SummaryCallback {
241 track_initial_loss: bool,
242 initial_loss: Option<f32>,
243 validation_metric: Option<ValidationMetric>,
244 committed_metrics: Vec<CommittedMetric>,
245}
246
247impl SummaryCallback {
248 #[inline]
250 #[must_use]
251 pub fn new() -> Self {
252 Self::default()
253 }
254
255 pub const fn new_with_initial_loss(track_initial_loss: bool) -> Self {
257 Self {
258 track_initial_loss,
259 initial_loss: None,
260 validation_metric: None,
261 committed_metrics: Vec::new(),
262 }
263 }
264
265 pub fn set_validation_metric(&mut self, metric: ValidationMetric) {
267 self.validation_metric = Some(metric);
268 }
269
270 #[must_use]
273 pub fn committed_metrics(&self) -> &[CommittedMetric] {
274 &self.committed_metrics
275 }
276
277 fn record_committed(&mut self, entries: &[CommittedMetric]) {
278 for entry in entries {
279 if let Some(existing) = self
280 .committed_metrics
281 .iter_mut()
282 .find(|item| item.split == entry.split && item.name == entry.name)
283 {
284 *existing = entry.clone();
285 } else {
286 self.committed_metrics.push(entry.clone());
287 }
288 }
289 }
290
291 pub fn render_report(&self, state: TrainingSnapshot, config: &TrainingConfig) -> String {
293 let mut report = String::from("\nSummary:\n");
294 match (self.initial_loss, state.last_loss()) {
295 (_, None) => report.push_str(" loss: n/a (no loss recorded)\n"),
296 (Some(initial), Some(final_loss)) if self.track_initial_loss => report.push_str(&format!(
297 " loss: initial {initial:.6} · final {final_loss:.6} · mean {:.6}\n",
298 state.training_mean_loss()
299 )),
300 (_, Some(final_loss)) => report.push_str(&format!(
301 " loss: final {final_loss:.6} · mean {:.6}\n",
302 state.training_mean_loss()
303 )),
304 }
305 if let Some(metric) = &self.validation_metric
306 && let Some(value) = metric.value()
307 {
308 report.push_str(&format!(" Validation: {} {value:.6}\n", metric.name()));
309 }
310 if !self.committed_metrics.is_empty() {
311 report.push_str(" Metrics:\n");
312 for entry in &self.committed_metrics {
313 report.push_str(&format!(
314 " {}/{}: {:.6}\n",
315 entry.split, entry.name, entry.value
316 ));
317 }
318 }
319 report.push_str(&format!(
320 " Wall: {:.2} ms/step · {} sample/s",
321 state.wall_ms_per_step(),
322 format_rate(state.wall_samples_per_second())
323 ));
324 if config.sequence_length > 0 {
325 report.push_str(&format!(
326 " · {} {}/s",
327 format_rate(state.wall_units_per_second()),
328 config.sequence_unit
329 ));
330 }
331 if state.total_source_units() > 0 {
332 report.push_str(&format!(
333 " · {} {}/s",
334 format_rate(state.wall_source_units_per_second()),
335 config.source_unit
336 ));
337 }
338 report.push('\n');
339
340 let gpu = state.gpu_timing_stats();
341 if gpu.count == 0 {
342 report.push_str(&format!(
343 " GPU ({}): n/a (timer unavailable)\n",
344 config.timer_name
345 ));
346 } else {
347 report.push_str(&format!(
348 " GPU ({}): mean {:.3} ms/step · p50 {:.3} · p95 {:.3} · min {:.3} · max {:.3} · {} sample/s",
349 config.timer_name,
350 gpu.mean_ms,
351 gpu.median_ms,
352 gpu.p95_ms,
353 gpu.min_ms,
354 gpu.max_ms,
355 format_rate(state.gpu_samples_per_second())
356 ));
357 if config.sequence_length > 0 {
358 report.push_str(&format!(
359 " · {} {}/s",
360 format_rate(state.gpu_units_per_second()),
361 config.sequence_unit
362 ));
363 }
364 if state.total_source_units() > 0 {
365 report.push_str(&format!(
366 " · {} {}/s",
367 format_rate(state.gpu_source_units_per_second()),
368 config.source_unit
369 ));
370 }
371 let gap = if state.gpu_samples_per_second() > 0.0 {
372 (100.0 * (1.0 - state.wall_samples_per_second() / state.gpu_samples_per_second()))
373 .clamp(0.0, 100.0)
374 } else {
375 0.0
376 };
377 report.push_str(&format!(" · wall-GPU gap {gap:.0}%\n"));
378 }
379 report.push_str(&format!(
380 " run: {:.2}s · {} steps · batch {}",
381 state.elapsed().as_secs_f64(),
382 state.step_count(),
383 config.batch_size
384 ));
385 if state.skipped_updates() > 0 {
386 report.push_str(&format!(
387 " · {} applied / {} skipped updates",
388 state.applied_updates(),
389 state.skipped_updates()
390 ));
391 }
392 if config.sequence_length > 0 {
393 report.push_str(&format!(
394 " · sequence {} {}/sample",
395 config.sequence_length, config.sequence_unit
396 ));
397 }
398 report.push('\n');
399 report
400 }
401}
402
403impl Default for SummaryCallback {
404 fn default() -> Self {
405 Self::new_with_initial_loss(true)
406 }
407}
408
409impl TrainingCallback for SummaryCallback {
410 fn on_step_end(&mut self, context: &mut TrainingCallbackContext<'_>) -> Result<TrainingControl> {
411 if self.track_initial_loss
412 && self.initial_loss.is_none()
413 && context.snapshot().step_count() == 1
414 {
415 self.initial_loss = context.snapshot().last_loss();
416 }
417 Ok(TrainingControl::Continue)
418 }
419
420 fn on_epoch_end(&mut self, context: &mut TrainingCallbackContext<'_>) -> Result<TrainingControl> {
421 self.record_committed(context.committed_metrics());
422 Ok(TrainingControl::Continue)
423 }
424
425 fn on_train_end(&mut self, context: &mut TrainingCallbackContext<'_>) -> Result<TrainingControl> {
426 self.record_committed(context.committed_metrics());
427 write_stdout(&self.render_report(context.snapshot(), context.config()))?;
428 Ok(TrainingControl::Continue)
429 }
430}
431
432fn format_rate(rate: f64) -> String {
433 if rate >= 1.0e6 {
434 format!("{:.2}M", rate / 1.0e6)
435 } else if rate >= 1.0e3 {
436 format!("{:.2}K", rate / 1.0e3)
437 } else {
438 format!("{rate:.0}")
439 }
440}
441
442fn write_stdout(text: &str) -> Result<()> {
443 let mut stdout = io::stdout().lock();
444 stdout
445 .write_all(text.as_bytes())
446 .map_err(|error| Error::io("write training progress", error))?;
447 stdout
448 .flush()
449 .map_err(|error| Error::io("flush training progress", error))
450}