Skip to main content

oa/ml/training/
training.rs

1//! Donor-backed training lifecycle, metrics, and callbacks.
2//!
3//! Port provenance: `oa/ml/itTraining.h`, `oa/ml/itTraining.cpp`, and
4//! `oa/ml/metric.{h,cpp}`. Rust callbacks return control explicitly and are
5//! borrowed by the loop instead of inheriting from the C++ callback root.
6
7use std::time::{Duration, Instant};
8
9use crate::{DType, Error, Matrix, Result, Runtime, ml::optim::AdamWProgramSignature};
10
11use super::{
12	AdamW, CheckpointOptimizer, Optimizer, TrainingCallback, TrainingMetric, TrainingParameterDesc,
13	TrainingProgram, TrainingSession, TrainingSessionAttachment, TrainingSessionHandlers,
14	TrainingSessionSnapshot, TrainingState, program::TrainingProgramCapture,
15};
16pub use crate::ml::types::TrainingConfig;
17
18#[path = "fit.rs"]
19mod fit;
20pub use fit::{EvaluationReport, TrainingEpoch, TrainingFitOptions, TrainingHistory};
21
22impl Default for TrainingConfig {
23	fn default() -> Self {
24		Self {
25			initial_step: 0,
26			total_steps: 0,
27			steps_per_epoch: 0,
28			epoch_steps: Vec::new(),
29			batch_size: 1,
30			sequence_length: 0,
31			sequence_unit: "token".into(),
32			source_units_per_sample: 0.0,
33			source_unit: "byte".into(),
34			timer_name: "training_step".into(),
35			enable_gpu_timing: false,
36		}
37	}
38}
39
40/// Explicit callback decision at a lifecycle boundary.
41#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
42pub enum TrainingControl {
43	/// Continue the configured lifecycle.
44	#[default]
45	Continue,
46	/// Stop before admitting another step.
47	Stop,
48}
49
50/// User-visible whole-program capture eligibility for a [`Training`] run.
51#[derive(Clone, Debug, PartialEq, Eq)]
52pub enum CaptureEligibility {
53	/// The run may capture a whole-program replay graph on its next automatic step.
54	Eligible,
55	/// Whole-program capture is currently active and replaying a captured program.
56	Active,
57	/// Whole-program capture is unavailable; execution remains eager for the reported reason.
58	Ineligible { reason: String },
59}
60
61impl CaptureEligibility {
62	/// Whether whole-program capture is currently eligible or already active.
63	#[must_use]
64	pub const fn is_eligible(&self) -> bool {
65		matches!(self, Self::Eligible | Self::Active)
66	}
67
68	/// Whether a captured training program is currently active.
69	#[must_use]
70	pub const fn is_active(&self) -> bool {
71		matches!(self, Self::Active)
72	}
73
74	/// Human-readable reason when capture is ineligible, or `None` otherwise.
75	#[must_use]
76	pub fn reason(&self) -> Option<&str> {
77		match self {
78			Self::Ineligible { reason } => Some(reason.as_str()),
79			Self::Eligible | Self::Active => None,
80		}
81	}
82}
83
84/// Immutable state supplied to metrics and callbacks.
85#[derive(Clone, Copy, Debug)]
86pub struct TrainingSnapshot {
87	step_count: u64,
88	total_steps: u64,
89	epoch: u64,
90	total_epochs: u64,
91	step_in_epoch: u64,
92	steps_in_epoch: u64,
93	epoch_boundary: bool,
94	last_step: bool,
95	last_loss: Option<f32>,
96	last_gpu_time: Option<Duration>,
97	gpu_timing: GpuTimingStats,
98	gpu_timed_samples: u64,
99	gpu_timed_units: u64,
100	gpu_timed_source_units: u64,
101	total_samples: u64,
102	total_units: u64,
103	total_source_units: u64,
104	epoch_source_units: u64,
105	elapsed: Duration,
106	epoch_elapsed: Duration,
107	training_mean_loss: f64,
108	epoch_mean_loss: f64,
109	attempted_updates: u64,
110	applied_updates: u64,
111	skipped_updates: u64,
112}
113
114/// One metric value committed to the shared training history.
115///
116/// Entries are append-only and ordered: the lifecycle commits training epoch
117/// metrics before any epoch-end callback fires, so validation, checkpoint
118/// monitors, and early stopping read committed training values in the same
119/// boundary. Sinks never re-derive a number another sink read — they query
120/// the log.
121#[derive(Clone, Debug, PartialEq)]
122pub struct CommittedMetric {
123	/// Epoch at commitment, one-based within the run's epoch schedule.
124	pub epoch: u64,
125	/// Completed step at commitment.
126	pub step: u64,
127	/// `train`, `validation`, `test`, or a caller-named evaluation split.
128	pub split: String,
129	/// Stable snake_case metric identifier.
130	pub name: String,
131	/// Committed value; units belong to the metric definition.
132	pub value: f64,
133}
134
135/// Aggregate device time for completed, timestamped training steps.
136#[derive(Clone, Copy, Debug, Default, PartialEq)]
137pub struct GpuTimingStats {
138	/// Number of device-timed steps.
139	pub count: u64,
140	/// Arithmetic mean device milliseconds per step.
141	pub mean_ms: f64,
142	/// Minimum device milliseconds per step.
143	pub min_ms: f64,
144	/// Maximum device milliseconds per step.
145	pub max_ms: f64,
146	/// Median device milliseconds per step.
147	pub median_ms: f64,
148	/// Nearest-rank 95th-percentile device milliseconds per step.
149	pub p95_ms: f64,
150	/// Most recent device milliseconds per step.
151	pub last_ms: f64,
152}
153
154impl GpuTimingStats {
155	/// Construct an empty timing report.
156	#[inline]
157	#[must_use]
158	pub fn new() -> Self {
159		Self::default()
160	}
161}
162
163impl TrainingSnapshot {
164	pub const fn step_count(self) -> u64 {
165		self.step_count
166	}
167
168	pub const fn total_steps(self) -> u64 {
169		self.total_steps
170	}
171
172	pub const fn epoch(self) -> u64 {
173		self.epoch
174	}
175
176	pub const fn total_epochs(self) -> u64 {
177		self.total_epochs
178	}
179
180	pub const fn step_in_epoch(self) -> u64 {
181		self.step_in_epoch
182	}
183
184	pub const fn steps_in_epoch(self) -> u64 {
185		self.steps_in_epoch
186	}
187
188	pub const fn is_epoch_boundary(self) -> bool {
189		self.epoch_boundary
190	}
191
192	pub const fn is_last_step(self) -> bool {
193		self.last_step
194	}
195
196	pub const fn last_loss(self) -> Option<f32> {
197		self.last_loss
198	}
199
200	pub const fn last_gpu_time(self) -> Option<Duration> {
201		self.last_gpu_time
202	}
203
204	pub const fn gpu_timing_stats(self) -> GpuTimingStats {
205		self.gpu_timing
206	}
207
208	pub const fn total_samples(self) -> u64 {
209		self.total_samples
210	}
211
212	pub const fn total_units(self) -> u64 {
213		self.total_units
214	}
215
216	pub const fn total_source_units(self) -> u64 {
217		self.total_source_units
218	}
219
220	pub const fn elapsed(self) -> Duration {
221		self.elapsed
222	}
223
224	pub const fn epoch_elapsed(self) -> Duration {
225		self.epoch_elapsed
226	}
227
228	pub const fn training_mean_loss(self) -> f64 {
229		self.training_mean_loss
230	}
231
232	pub const fn epoch_mean_loss(self) -> f64 {
233		self.epoch_mean_loss
234	}
235
236	/// Total optimizer updates attempted across completed steps (including skipped AMP updates).
237	pub const fn attempted_updates(self) -> u64 {
238		self.attempted_updates
239	}
240
241	/// Total optimizer updates actually applied (excluding skipped AMP overflow updates).
242	pub const fn applied_updates(self) -> u64 {
243		self.applied_updates
244	}
245
246	/// Total optimizer updates skipped due to non-finite gradients or AMP overflow.
247	pub const fn skipped_updates(self) -> u64 {
248		self.skipped_updates
249	}
250
251	/// Return completed samples per wall-clock second.
252	pub fn wall_samples_per_second(self) -> f64 {
253		let seconds = self.elapsed.as_secs_f64();
254		if seconds > 0.0 {
255			self.total_samples as f64 / seconds
256		} else {
257			0.0
258		}
259	}
260
261	/// Return completed sequence units per wall-clock second.
262	pub fn wall_units_per_second(self) -> f64 {
263		let seconds = self.elapsed.as_secs_f64();
264		if seconds > 0.0 {
265			self.total_units as f64 / seconds
266		} else {
267			0.0
268		}
269	}
270
271	/// Return completed source units per wall-clock second.
272	pub fn wall_source_units_per_second(self) -> f64 {
273		let seconds = self.elapsed.as_secs_f64();
274		if seconds > 0.0 {
275			self.total_source_units as f64 / seconds
276		} else {
277			0.0
278		}
279	}
280
281	/// Return completed epoch source units per wall-clock second.
282	pub fn epoch_source_units_per_second(self) -> f64 {
283		let seconds = self.epoch_elapsed.as_secs_f64();
284		if seconds > 0.0 {
285			self.epoch_source_units as f64 / seconds
286		} else {
287			0.0
288		}
289	}
290
291	/// Return timestamped samples per device second.
292	pub fn gpu_samples_per_second(self) -> f64 {
293		let seconds = self.gpu_timing.mean_ms / 1000.0;
294		if seconds > 0.0 && self.gpu_timing.count > 0 {
295			self.gpu_timed_samples as f64 / self.gpu_timing.count as f64 / seconds
296		} else {
297			0.0
298		}
299	}
300
301	/// Return timestamped sequence units per device second.
302	pub fn gpu_units_per_second(self) -> f64 {
303		let seconds = self.gpu_timing.mean_ms / 1000.0;
304		if seconds > 0.0 && self.gpu_timing.count > 0 {
305			self.gpu_timed_units as f64 / self.gpu_timing.count as f64 / seconds
306		} else {
307			0.0
308		}
309	}
310
311	/// Return timestamped source units per device second.
312	pub fn gpu_source_units_per_second(self) -> f64 {
313		let seconds = self.gpu_timing.mean_ms / 1000.0;
314		if seconds > 0.0 && self.gpu_timing.count > 0 {
315			self.gpu_timed_source_units as f64 / self.gpu_timing.count as f64 / seconds
316		} else {
317			0.0
318		}
319	}
320
321	/// Return mean wall-clock milliseconds per completed step.
322	pub fn wall_ms_per_step(self) -> f64 {
323		if self.step_count > 0 {
324			self.elapsed.as_secs_f64() * 1000.0 / self.step_count as f64
325		} else {
326			0.0
327		}
328	}
329}
330
331enum CallbackOptimizer<'a> {
332	AdamW(&'a mut AdamW),
333	Eager(&'a mut dyn Optimizer),
334	Checkpointable(&'a mut dyn CheckpointOptimizer),
335}
336
337impl CallbackOptimizer<'_> {
338	fn behavior_mut(&mut self) -> &mut dyn Optimizer {
339		match self {
340			Self::AdamW(optimizer) => *optimizer,
341			Self::Eager(optimizer) => *optimizer,
342			Self::Checkpointable(optimizer) => *optimizer,
343		}
344	}
345
346	fn checkpoint_mut(&mut self) -> Option<&mut dyn CheckpointOptimizer> {
347		match self {
348			Self::AdamW(optimizer) => Some(*optimizer),
349			Self::Eager(_) => None,
350			Self::Checkpointable(optimizer) => Some(*optimizer),
351		}
352	}
353}
354
355/// Restricted mutable services available to one callback invocation.
356pub struct TrainingCallbackContext<'a> {
357	snapshot: TrainingSnapshot,
358	optimizer: CallbackOptimizer<'a>,
359	config: &'a TrainingConfig,
360	committed_metrics: &'a mut Vec<CommittedMetric>,
361	excluded_wall_time: Duration,
362}
363
364impl TrainingCallbackContext<'_> {
365	/// Return the immutable state at this lifecycle boundary.
366	pub const fn snapshot(&self) -> TrainingSnapshot {
367		self.snapshot
368	}
369
370	/// Borrow the training optimizer for scheduling or checkpoint policy.
371	pub fn optimizer(&mut self) -> &mut dyn Optimizer {
372		self.optimizer.behavior_mut()
373	}
374
375	/// Borrow native checkpoint persistence when the optimizer admits it.
376	///
377	/// # Errors
378	///
379	/// Returns an error when the iterator was constructed through the open
380	/// eager-only optimizer route.
381	pub fn checkpoint_optimizer(&mut self) -> Result<&mut dyn CheckpointOptimizer> {
382		self.optimizer.checkpoint_mut().ok_or_else(|| {
383			Error::failed_precondition("training optimizer does not support native checkpoints")
384		})
385	}
386
387	/// Commit one metric value to the shared training history.
388	///
389	/// Entries order by commit time at this lifecycle boundary: training
390	/// metrics the lifecycle itself commits come first, then values committed
391	/// by callbacks in registration order. Later callbacks and every sink read
392	/// the committed value rather than re-deriving it.
393	pub fn commit_metric(&mut self, split: &str, name: &str, value: f64) {
394		self.committed_metrics.push(CommittedMetric {
395			epoch: self.snapshot.epoch(),
396			step: self.snapshot.step_count(),
397			split: split.to_owned(),
398			name: name.to_owned(),
399			value,
400		});
401	}
402
403	/// Return every metric committed so far, in commit order.
404	pub fn committed_metrics(&self) -> &[CommittedMetric] {
405		self.committed_metrics
406	}
407
408	/// Return the most recent committed value for `split`/`name`, when present.
409	pub fn latest_committed(&self, split: &str, name: &str) -> Option<f64> {
410		self
411			.committed_metrics
412			.iter()
413			.rev()
414			.find(|entry| entry.split == split && entry.name == name)
415			.map(|entry| entry.value)
416	}
417
418	/// Return the immutable iterator configuration.
419	pub const fn config(&self) -> &TrainingConfig {
420		self.config
421	}
422
423	/// Exclude callback-owned work such as validation from throughput timing.
424	pub fn exclude_wall_time(&mut self, duration: Duration) {
425		self.excluded_wall_time = self.excluded_wall_time.saturating_add(duration);
426	}
427}
428
429#[derive(Clone, Copy)]
430enum CallbackPhase {
431	TrainBegin,
432	EpochBegin,
433	StepEnd,
434	EpochEnd,
435	TrainEnd,
436}
437
438#[derive(Clone, Copy, PartialEq, Eq)]
439enum ExecutionMode {
440	Eager,
441	Captured,
442	Automatic,
443}
444
445enum TrainingOptimizer<'optimizer> {
446	AdamW(&'optimizer mut AdamW),
447	Eager(&'optimizer mut dyn Optimizer),
448	Checkpointable(&'optimizer mut dyn CheckpointOptimizer),
449}
450
451impl TrainingOptimizer<'_> {
452	fn behavior(&self) -> &dyn Optimizer {
453		match self {
454			Self::AdamW(optimizer) => *optimizer,
455			Self::Eager(optimizer) => *optimizer,
456			Self::Checkpointable(optimizer) => *optimizer,
457		}
458	}
459
460	fn behavior_mut(&mut self) -> &mut dyn Optimizer {
461		match self {
462			Self::AdamW(optimizer) => *optimizer,
463			Self::Eager(optimizer) => *optimizer,
464			Self::Checkpointable(optimizer) => *optimizer,
465		}
466	}
467
468	const fn supports_capture(&self) -> bool {
469		matches!(self, Self::AdamW(_))
470	}
471
472	fn adamw_mut(&mut self) -> Result<&mut AdamW> {
473		match self {
474			Self::AdamW(optimizer) => Ok(*optimizer),
475			Self::Eager(_) | Self::Checkpointable(_) => Err(Error::failed_precondition(
476				"captured training currently requires AdamW",
477			)),
478		}
479	}
480
481	fn callback(&mut self) -> CallbackOptimizer<'_> {
482		match self {
483			Self::AdamW(optimizer) => CallbackOptimizer::AdamW(optimizer),
484			Self::Eager(optimizer) => CallbackOptimizer::Eager(*optimizer),
485			Self::Checkpointable(optimizer) => CallbackOptimizer::Checkpointable(*optimizer),
486		}
487	}
488}
489
490/// Exact eager or captured training-step lifecycle.
491///
492/// The loop borrows the runtime, optimizer, metrics, and callbacks. Call
493/// [`Training::begin_step`] before authoring each body, then finish it with
494/// [`Training::complete_step`] or [`Training::complete_program_step`].
495/// [`Training::finish`] is the explicit fallible terminal boundary.
496#[must_use]
497pub struct Training<'runtime, 'hooks> {
498	runtime: &'runtime Runtime,
499	optimizer: TrainingOptimizer<'runtime>,
500	config: TrainingConfig,
501	epoch_offsets: Vec<u64>,
502	metrics: Vec<&'hooks mut dyn TrainingMetric>,
503	callbacks: Vec<&'hooks mut dyn TrainingCallback>,
504	session: Option<TrainingSessionAttachment<'hooks>>,
505	started: bool,
506	body_pending: bool,
507	stop_requested: bool,
508	execution_mode: Option<ExecutionMode>,
509	program: Option<TrainingProgram>,
510	program_capture_disabled: bool,
511	program_capture_fallback_count: u64,
512	last_program_capture_fallback: Option<String>,
513	stable_resource_frame_open: bool,
514	retain_eager_resources: bool,
515	sample_weighted_loss: bool,
516	stable_resource_inputs_sealed: bool,
517	step_count: u64,
518	attempted_updates: u64,
519	applied_updates: u64,
520	skipped_updates: u64,
521	last_epoch_started: u64,
522	pending_source_units: Option<u64>,
523	pending_step_samples: Option<u64>,
524	last_loss: Option<f32>,
525	last_gpu_time: Option<Duration>,
526	gpu_timing_samples: Vec<Duration>,
527	gpu_timing_sum: Duration,
528	gpu_timed_samples: u64,
529	gpu_timed_units: u64,
530	gpu_timed_source_units: u64,
531	total_samples: u64,
532	total_units: u64,
533	total_source_units: u64,
534	epoch_source_units: u64,
535	committed_metrics: Vec<CommittedMetric>,
536	epoch_loss_sum: f64,
537	epoch_loss_count: u64,
538	training_loss_sum: f64,
539	training_loss_count: u64,
540	start: Instant,
541	epoch_start: Instant,
542	excluded_wall: Duration,
543	excluded_epoch: Duration,
544}
545
546impl<'runtime, 'hooks> Training<'runtime, 'hooks> {
547	/// Construct a training lifecycle around one runtime and optimizer.
548	///
549	/// # Errors
550	///
551	/// Returns an error when source-unit accounting is non-finite or overflows,
552	/// or the variable epoch schedule overflows.
553	pub fn new(
554		runtime: &'runtime Runtime,
555		optimizer: &'runtime mut AdamW,
556		config: TrainingConfig,
557	) -> Result<Self> {
558		Self::new_with_optimizer(runtime, TrainingOptimizer::AdamW(optimizer), config)
559	}
560
561	/// Construct an eager-only training lifecycle around any optimizer.
562	///
563	/// This route provides the ordinary step, metric, and callback lifecycle.
564	/// Whole-program capture remains optimizer-specific and currently admits
565	/// [`AdamW`] through [`Training::new`].
566	///
567	/// # Errors
568	///
569	/// Returns an error when the optimizer does not belong to `runtime`, source-unit
570	/// accounting is non-finite or overflows, or the epoch schedule overflows.
571	pub fn new_eager(
572		runtime: &'runtime Runtime,
573		optimizer: &'runtime mut dyn Optimizer,
574		config: TrainingConfig,
575	) -> Result<Self> {
576		Self::new_with_optimizer(runtime, TrainingOptimizer::Eager(optimizer), config)
577	}
578
579	/// Construct an eager lifecycle with native checkpoint capability.
580	///
581	/// Built-in checkpoint callbacks can borrow this optimizer through their
582	/// restricted callback context. Whole-program capture remains exclusive to
583	/// the AdamW [`Training::new`] route.
584	///
585	/// # Errors
586	///
587	/// Returns the same configuration or ownership errors as [`Training::new_eager`].
588	pub fn new_eager_checkpointable(
589		runtime: &'runtime Runtime,
590		optimizer: &'runtime mut dyn CheckpointOptimizer,
591		config: TrainingConfig,
592	) -> Result<Self> {
593		Self::new_with_optimizer(
594			runtime,
595			TrainingOptimizer::Checkpointable(optimizer),
596			config,
597		)
598	}
599
600	fn new_with_optimizer(
601		runtime: &'runtime Runtime,
602		optimizer: TrainingOptimizer<'runtime>,
603		mut config: TrainingConfig,
604	) -> Result<Self> {
605		if !optimizer.behavior().belongs_to(runtime) {
606			return Err(Error::invalid_argument(
607				"training optimizer must belong to the selected runtime",
608			));
609		}
610		if !config.source_units_per_sample.is_finite() || config.source_units_per_sample < 0.0 {
611			return Err(Error::invalid_argument(
612				"source units per sample must be finite and non-negative",
613			));
614		}
615		config.batch_size = config.batch_size.max(1);
616		let epoch_offsets = normalize_epoch_schedule(&mut config)?;
617		if config.total_steps > 0 && config.initial_step > config.total_steps {
618			return Err(Error::invalid_argument(
619				"training initial step exceeds the absolute step budget",
620			));
621		}
622		let initial_step = config.initial_step;
623		let now = Instant::now();
624		Ok(Self {
625			runtime,
626			optimizer,
627			config,
628			epoch_offsets,
629			metrics: Vec::new(),
630			callbacks: Vec::new(),
631			session: None,
632			started: false,
633			body_pending: false,
634			stop_requested: false,
635			execution_mode: None,
636			program: None,
637			program_capture_disabled: false,
638			program_capture_fallback_count: 0,
639			last_program_capture_fallback: None,
640			stable_resource_frame_open: false,
641			retain_eager_resources: true,
642			sample_weighted_loss: false,
643			stable_resource_inputs_sealed: false,
644			step_count: initial_step,
645			attempted_updates: initial_step,
646			applied_updates: initial_step,
647			skipped_updates: 0,
648			last_epoch_started: 0,
649			pending_source_units: None,
650			pending_step_samples: None,
651			last_loss: None,
652			last_gpu_time: None,
653			gpu_timing_samples: Vec::new(),
654			gpu_timing_sum: Duration::ZERO,
655			gpu_timed_samples: 0,
656			gpu_timed_units: 0,
657			gpu_timed_source_units: 0,
658			total_samples: 0,
659			total_units: 0,
660			total_source_units: 0,
661			epoch_source_units: 0,
662			committed_metrics: Vec::new(),
663			epoch_loss_sum: 0.0,
664			epoch_loss_count: 0,
665			training_loss_sum: 0.0,
666			training_loss_count: 0,
667			start: now,
668			epoch_start: now,
669			excluded_wall: Duration::ZERO,
670			excluded_epoch: Duration::ZERO,
671		})
672	}
673
674	pub fn add_metric(&mut self, metric: &'hooks mut dyn TrainingMetric) {
675		self.metrics.push(metric);
676	}
677
678	pub fn add_callback(&mut self, callback: &'hooks mut dyn TrainingCallback) {
679		self.callbacks.push(callback);
680	}
681
682	/// Attach one thread-safe live-control session before training starts.
683	///
684	/// Handler closures remain on this iterator's runtime thread. Clones of
685	/// `session` contain only bounded commands and immutable observation data.
686	///
687	/// # Errors
688	///
689	/// Returns an error after training has started, while a step is pending, or
690	/// when the session is already attached.
691	pub fn attach_session(
692		&mut self,
693		session: &TrainingSession,
694		handlers: TrainingSessionHandlers<'hooks>,
695	) -> Result<()> {
696		if self.started || self.body_pending || self.session.is_some() {
697			return Err(Error::failed_precondition(
698				"training session attachment must occur once before training starts",
699			));
700		}
701		let snapshot = self.snapshot();
702		let learning_rate = self.optimizer.behavior().learning_rate();
703		session.attach(TrainingSessionSnapshot {
704			revision: 0,
705			state: TrainingState::Running,
706			step: snapshot.step_count(),
707			epoch: snapshot.epoch(),
708			learning_rate,
709			loss: snapshot.last_loss().unwrap_or(0.0),
710			gpu_ms: snapshot
711				.last_gpu_time()
712				.unwrap_or(Duration::ZERO)
713				.as_secs_f64()
714				* 1000.0,
715			wall_ms: snapshot.wall_ms_per_step(),
716			metrics: Vec::new(),
717		})?;
718		session.cache_parameter(
719			"learning_rate".into(),
720			super::TrainingValue::Float(f64::from(learning_rate)),
721		)?;
722		self.session = Some(TrainingSessionAttachment::new(session.clone(), handlers));
723		Ok(())
724	}
725
726	/// Register an application-owned parameter on the attached control session.
727	///
728	/// # Errors
729	///
730	/// Returns an error without an attached session, during a pending step, or
731	/// for an invalid or duplicate descriptor.
732	pub fn register_session_parameter(&mut self, desc: TrainingParameterDesc<'hooks>) -> Result<()> {
733		if self.body_pending {
734			return Err(Error::failed_precondition(
735				"training parameters may only be registered at a safe point",
736			));
737		}
738		self
739			.session
740			.as_mut()
741			.ok_or_else(|| Error::failed_precondition("no training session is attached"))?
742			.register_parameter(desc)
743	}
744
745	pub fn zero_grad(&self) {
746		self.optimizer.behavior().zero_grad();
747	}
748
749	pub fn request_stop(&mut self) {
750		self.stop_requested = true;
751	}
752
753	pub const fn stop_requested(&self) -> bool {
754		self.stop_requested
755	}
756
757	/// Begin the next step, firing lazy train/epoch begin hooks.
758	///
759	/// Returns `false` after the configured budget or a callback stop decision.
760	///
761	/// # Errors
762	///
763	/// Returns a callback failure or counter exhaustion.
764	pub fn begin_step(&mut self) -> Result<bool> {
765		if self.body_pending {
766			return Ok(true);
767		}
768		self.poll_session_commands();
769		if self.stop_requested
770			|| self
771				.session
772				.as_ref()
773				.is_some_and(|session| session.session.state() != TrainingState::Running)
774		{
775			return Ok(false);
776		}
777		if !self.started {
778			self.started = true;
779			let now = Instant::now();
780			self.start = now;
781			self.epoch_start = now;
782			for metric in &mut self.metrics {
783				metric.reset();
784			}
785			if self.fire_checked(CallbackPhase::TrainBegin)? == TrainingControl::Stop {
786				return Ok(false);
787			}
788		}
789		if self.config.total_steps > 0 && self.step_count >= self.config.total_steps {
790			return Ok(false);
791		}
792		self.step_count = self
793			.step_count
794			.checked_add(1)
795			.ok_or_else(|| Error::resource_exhausted("training step counter exhausted"))?;
796		self.body_pending = true;
797		let epoch = self.epoch();
798		if self.has_epochs() && epoch != self.last_epoch_started {
799			self.last_epoch_started = epoch;
800			self.epoch_loss_sum = 0.0;
801			self.epoch_loss_count = 0;
802			self.epoch_source_units = 0;
803			self.epoch_start = Instant::now();
804			self.excluded_epoch = Duration::ZERO;
805			for metric in &mut self.metrics {
806				metric.reset();
807			}
808			if self.fire_checked(CallbackPhase::EpochBegin)? == TrainingControl::Stop {
809				self.body_pending = false;
810				return Ok(false);
811			}
812		}
813		// A restored absolute step does not replace this process's eager warm-up.
814		// Stable-resource allocation ordinals are learned locally, so the first
815		// post-restore step must establish them before reuse begins.
816		if self.retain_eager_resources
817			&& self.training_loss_count > 0
818			&& matches!(
819				self.execution_mode,
820				Some(ExecutionMode::Eager | ExecutionMode::Automatic)
821			) {
822			if let Err(error) = self.runtime.begin_stable_resource_frame() {
823				return self.fail(error);
824			}
825			self.stable_resource_frame_open = true;
826		}
827		Ok(true)
828	}
829
830	/// Block at the next safe point while an attached session is paused.
831	///
832	/// A session clone may enqueue resume or stop from another thread. Without an
833	/// attached session this is equivalent to [`Training::begin_step`].
834	///
835	/// # Errors
836	///
837	/// Returns the same lifecycle or callback errors as [`Training::begin_step`].
838	pub fn wait_begin_step(&mut self) -> Result<bool> {
839		loop {
840			if self.begin_step()? {
841				return Ok(true);
842			}
843			if self.stop_requested
844				|| (self.config.total_steps > 0 && self.step_count >= self.config.total_steps)
845			{
846				return Ok(false);
847			}
848			let Some(session) = self.session.as_ref() else {
849				return Ok(false);
850			};
851			match session.session.state() {
852				TrainingState::Paused => session.session.wait_while_paused(),
853				TrainingState::Running => continue,
854				TrainingState::Stopping | TrainingState::Completed | TrainingState::Failed => {
855					return Ok(false);
856				}
857			}
858		}
859	}
860
861	// Split PPO epochs submit and release several tapes within one optimizer
862	// step. Allocation-ordinal retention across that entire step defeats the
863	// minibatch memory bound; other eager/captured consumers keep their policy.
864	pub(super) fn disable_eager_resource_reuse(&mut self) {
865		self.retain_eager_resources = false;
866	}
867
868	/// Complete one eagerly authored forward/backward step.
869	///
870	/// This records AdamW, submits the complete eager batch, waits for its exact
871	/// event, reads the scalar loss, updates metrics, and fires end hooks.
872	///
873	/// # Errors
874	///
875	/// Returns an error for an unmatched begin, invalid loss, optimizer/runtime
876	/// failure, timestamp failure, metric accounting overflow, or callback failure.
877	pub fn complete_step(&mut self, loss: &Matrix) -> Result<()> {
878		self.complete_step_with_device_prefix(loss, Duration::ZERO)
879	}
880
881	/// Internal composition of disjoint, already-completed device submissions
882	/// with this step's final optimizer submission. Never a host wall duration.
883	pub(super) fn complete_step_with_device_prefix(
884		&mut self,
885		loss: &Matrix,
886		device_prefix: Duration,
887	) -> Result<()> {
888		self.require_pending()?;
889		if let Err(error) = self.select_execution_mode(ExecutionMode::Eager) {
890			return self.fail(error);
891		}
892		self.complete_eager_step(loss, device_prefix)
893	}
894
895	/// Complete one eagerly authored scaled-loss step under a `GradScaler`.
896	///
897	/// The caller runs forward and backward against `scaler.scale_loss(&loss)`
898	/// and unscales parameter gradients through
899	/// `GradScaler::unscale_gradients`, then hands the unscaled loss and the
900	/// scaler's finite check to this method. The optimizer step applies only
901	/// when every unscaled gradient is finite; `scaler.update()` adjusts the
902	/// scale either way. Returns whether the optimizer step ran.
903	///
904	/// This is the eager AMP contract: the finite gate reads one scalar back
905	/// at the step boundary, where torch performs the equivalent CPU-side
906	/// check. The automatically captured `step` path instead replays the
907	/// device-resident gate produced by `GradScaler::record_finite_gate`
908	/// through `Optimizer::set_finite_gate`, freezing the update inside the
909	/// program when gradients are not finite.
910	///
911	/// # Errors
912	///
913	/// Returns an error for an unmatched begin, invalid loss, scaler or
914	/// optimizer failure, timestamp failure, metric accounting overflow, or
915	/// callback failure.
916	pub fn complete_step_scaled(
917		&mut self,
918		loss: &Matrix,
919		check: &Matrix,
920		scaler: &mut crate::ml::optim::GradScaler,
921	) -> Result<bool> {
922		self.require_pending()?;
923		if let Err(error) = self.select_execution_mode(ExecutionMode::Eager) {
924			return self.fail(error);
925		}
926		if let Err(error) = self.seal_stable_resources() {
927			return self.fail(error);
928		}
929		if !loss.shape().is_empty() || loss.dtype() != DType::F32 {
930			return self.fail(Error::invalid_argument(
931				"training loss must be an FP32 scalar",
932			));
933		}
934		if !self.runtime.owns_matrix(loss) {
935			return self.fail(Error::invalid_argument(
936				"training loss must belong to the selected runtime",
937			));
938		}
939		let stepped = match scaler.step_optimizer(self.optimizer.behavior_mut(), check) {
940			Ok(stepped) => stepped,
941			Err(error) => return self.fail(error),
942		};
943		scaler.update();
944		let event = if self.config.enable_gpu_timing {
945			self.runtime.checkpoint_timed()
946		} else {
947			self.runtime.checkpoint()
948		};
949		let event = match event {
950			Ok(event) => event,
951			Err(error) => return self.fail(error),
952		};
953		let gpu_time = if self.config.enable_gpu_timing {
954			match event.device_duration() {
955				Ok(value) => Some(value),
956				Err(error) => return self.fail(error),
957			}
958		} else {
959			if let Err(error) = event.wait() {
960				return self.fail(error);
961			}
962			None
963		};
964		let values = match loss.read_f32() {
965			Ok(values) => values,
966			Err(error) => return self.fail(error),
967		};
968		self.complete_with_update(values[0], gpu_time, stepped)?;
969		Ok(stepped)
970	}
971
972	fn complete_eager_step(&mut self, loss: &Matrix, device_prefix: Duration) -> Result<()> {
973		if let Err(error) = self.seal_stable_resources() {
974			return self.fail(error);
975		}
976		if !loss.shape().is_empty() || loss.dtype() != DType::F32 {
977			return self.fail(Error::invalid_argument(
978				"training loss must be an FP32 scalar",
979			));
980		}
981		if !self.runtime.owns_matrix(loss) {
982			return self.fail(Error::invalid_argument(
983				"training loss must belong to the selected runtime",
984			));
985		}
986		if let Err(error) = self.optimizer.behavior_mut().step() {
987			return self.fail(error);
988		}
989		let event = if self.config.enable_gpu_timing {
990			self.runtime.checkpoint_timed()
991		} else {
992			self.runtime.checkpoint()
993		};
994		let event = match event {
995			Ok(event) => event,
996			Err(error) => return self.fail(error),
997		};
998		let gpu_time = if self.config.enable_gpu_timing {
999			match event.device_duration() {
1000				Ok(value) => match value.checked_add(device_prefix) {
1001					Some(total) => Some(total),
1002					None => return self.fail(Error::resource_exhausted("training device time overflow")),
1003				},
1004				Err(error) => return self.fail(error),
1005			}
1006		} else {
1007			if let Err(error) = event.wait() {
1008				return self.fail(error);
1009			}
1010			None
1011		};
1012		let values = match loss.read_f32() {
1013			Ok(values) => values,
1014			Err(error) => return self.fail(error),
1015		};
1016		self.complete(values[0], gpu_time)
1017	}
1018
1019	/// Execute one automatically captured fixed-shape training step.
1020	///
1021	/// `prepare` runs on every admitted step and should allocate or refresh the
1022	/// fixed-shape input batch. `record` runs for the eager warm-up and once more
1023	/// to capture forward, backward, and AdamW work; later steps replay the owned
1024	/// program without rebuilding that graph. The returned boolean is `false`
1025	/// after the configured budget or a cooperative stop decision.
1026	///
1027	/// # Errors
1028	///
1029	/// Returns lifecycle, preparation, recording, capture, replay, completion,
1030	/// metric-accounting, timestamp, or callback errors. A whole-program compile
1031	/// rejection is an observable optimization fallback: the recorded source step
1032	/// runs eagerly and later steps remain eager until recapture is requested.
1033	pub fn step<P>(
1034		&mut self,
1035		prepare: impl FnOnce() -> Result<P>,
1036		record: impl FnOnce(P) -> Result<Matrix>,
1037	) -> Result<bool> {
1038		if let Err(error) = self.select_execution_mode(ExecutionMode::Automatic) {
1039			return self.fail(error);
1040		}
1041		if !self.begin_step()? {
1042			return Ok(false);
1043		}
1044		if self.runtime.has_pending_work() {
1045			return self.fail(Error::failed_precondition(
1046				"automatic training step requires an empty execution session",
1047			));
1048		}
1049		let prepared = match prepare() {
1050			Ok(prepared) => prepared,
1051			Err(error) => return self.fail(error),
1052		};
1053		if self.runtime.has_pending_work() {
1054			self.runtime.abort_pending_work();
1055			return self.fail(Error::failed_precondition(
1056				"automatic training preparation may only allocate or refresh inputs",
1057			));
1058		}
1059
1060		if self.step_count == 1 {
1061			self.optimizer.behavior().zero_grad();
1062			let loss = match record(prepared) {
1063				Ok(loss) => loss,
1064				Err(error) => return self.fail(error),
1065			};
1066			self.complete_eager_step(&loss, Duration::ZERO)?;
1067			return Ok(true);
1068		}
1069
1070		self.seal_replay_inputs()?;
1071		if self.program_capture_disabled {
1072			self.optimizer.behavior().zero_grad();
1073			let loss = match record(prepared) {
1074				Ok(loss) => loss,
1075				Err(error) => return self.fail(error),
1076			};
1077			self.complete_eager_step(&loss, Duration::ZERO)?;
1078			return Ok(true);
1079		}
1080		if self.program.is_none() {
1081			let optimizer = self.optimizer.adamw_mut();
1082			let optimizer = match optimizer {
1083				Ok(optimizer) => optimizer,
1084				Err(error) => return self.fail(error),
1085			};
1086			let capture =
1087				TrainingProgram::capture_preserving_recording(self.runtime, optimizer, || record(prepared));
1088			match capture {
1089				Ok(TrainingProgramCapture::Captured(program)) => self.program = Some(*program),
1090				Ok(TrainingProgramCapture::Rejected {
1091					error,
1092					loss,
1093					optimizer,
1094				}) => {
1095					self.complete_capture_fallback(error, loss, &optimizer)?;
1096					return Ok(true);
1097				}
1098				Err(error) => return self.fail(error),
1099			}
1100		} else {
1101			drop(prepared);
1102		}
1103		self.complete_automatic_program_step()?;
1104		Ok(true)
1105	}
1106
1107	fn complete_capture_fallback(
1108		&mut self,
1109		error: Error,
1110		loss: Matrix,
1111		optimizer: &AdamWProgramSignature,
1112	) -> Result<()> {
1113		self.program_capture_disabled = true;
1114		self.program_capture_fallback_count = self.program_capture_fallback_count.saturating_add(1);
1115		self.last_program_capture_fallback = Some(error.to_string());
1116		crate::log_warn!(
1117			crate::LogComponent::ML,
1118			"training program capture unavailable at step {} ({}); continuing eagerly",
1119			self.step_count,
1120			error
1121		);
1122		let event = if self.config.enable_gpu_timing {
1123			self.runtime.checkpoint_timed()
1124		} else {
1125			self.runtime.checkpoint()
1126		};
1127		let event = match event {
1128			Ok(event) => event,
1129			Err(error) => return self.fail(error),
1130		};
1131		let gpu_time = if self.config.enable_gpu_timing {
1132			match event.device_duration() {
1133				Ok(duration) => Some(duration),
1134				Err(error) => return self.fail(error),
1135			}
1136		} else {
1137			if let Err(error) = event.wait() {
1138				return self.fail(error);
1139			}
1140			None
1141		};
1142		let adamw = self.optimizer.adamw_mut();
1143		let adamw = match adamw {
1144			Ok(adamw) => adamw,
1145			Err(error) => return self.fail(error),
1146		};
1147		if let Err(error) = adamw.complete_capture_fallback(optimizer) {
1148			return self.fail(error);
1149		}
1150		let values = match loss.read_f32() {
1151			Ok(values) => values,
1152			Err(error) => return self.fail(error),
1153		};
1154		self.complete(values[0], gpu_time)
1155	}
1156
1157	fn complete_automatic_program_step(&mut self) -> Result<()> {
1158		let program = self
1159			.program
1160			.as_mut()
1161			.ok_or_else(|| Error::internal("automatic training program is missing"));
1162		let program = match program {
1163			Ok(program) => program,
1164			Err(error) => return self.fail(error),
1165		};
1166		let optimizer = self.optimizer.adamw_mut();
1167		let optimizer = match optimizer {
1168			Ok(optimizer) => optimizer,
1169			Err(error) => return self.fail(error),
1170		};
1171		let completed = if self.config.enable_gpu_timing {
1172			program
1173				.replay_timed_and_wait(self.runtime, optimizer)
1174				.map(|(loss, time)| (loss, Some(time)))
1175		} else {
1176			program
1177				.replay_and_wait(self.runtime, optimizer)
1178				.map(|loss| (loss, None))
1179		};
1180		match completed {
1181			Ok((loss, time)) => self.complete(loss, time),
1182			Err(error) => self.fail(error),
1183		}
1184	}
1185
1186	/// Return the automatically owned program after its capture step.
1187	pub const fn training_program(&self) -> Option<&TrainingProgram> {
1188		self.program.as_ref()
1189	}
1190
1191	/// Return how many whole-program capture rejections continued eagerly.
1192	pub const fn program_capture_fallback_count(&self) -> u64 {
1193		self.program_capture_fallback_count
1194	}
1195
1196	/// Return the most recent whole-program capture rejection message.
1197	pub fn last_program_capture_fallback(&self) -> Option<&str> {
1198		self.last_program_capture_fallback.as_deref()
1199	}
1200
1201	/// Report whether whole-program capture is eligible, active, or ineligible
1202	/// for this training run, together with the restriction or fallback reason.
1203	#[must_use]
1204	pub fn capture_eligibility(&self) -> CaptureEligibility {
1205		if self.program.is_some() || self.execution_mode == Some(ExecutionMode::Captured) {
1206			return CaptureEligibility::Active;
1207		}
1208		if self.program_capture_disabled {
1209			let reason = self
1210				.last_program_capture_fallback
1211				.clone()
1212				.unwrap_or_else(|| {
1213					"whole-program capture rejected and fell back to eager execution".to_owned()
1214				});
1215			return CaptureEligibility::Ineligible { reason };
1216		}
1217		if !self.optimizer.supports_capture() {
1218			return CaptureEligibility::Ineligible {
1219				reason: "captured training currently requires AdamW".to_owned(),
1220			};
1221		}
1222		if self.execution_mode == Some(ExecutionMode::Eager) {
1223			return CaptureEligibility::Ineligible {
1224				reason: "training loop is bound to eager execution".to_owned(),
1225			};
1226		}
1227		CaptureEligibility::Eligible
1228	}
1229
1230	/// Discard the automatically captured program, or re-enable capture after a
1231	/// prior rejection, so the next step records a new fixed-shape program after
1232	/// preparation.
1233	///
1234	/// # Errors
1235	///
1236	/// Returns an error while a step body is pending or when this loop does not use
1237	/// [`Training::step`].
1238	pub fn request_program_recapture(&mut self) -> Result<()> {
1239		if self.body_pending {
1240			return Err(Error::failed_precondition(
1241				"training program recapture requires a completed step",
1242			));
1243		}
1244		if self.execution_mode != Some(ExecutionMode::Automatic) {
1245			return Err(Error::failed_precondition(
1246				"training program recapture requires automatic capture",
1247			));
1248		}
1249		self.program = None;
1250		self.program_capture_disabled = false;
1251		Ok(())
1252	}
1253
1254	/// Seal allocations authored during preparation as stable replay inputs.
1255	///
1256	/// On eager steps after the first warm-up, Matrix storage allocated after
1257	/// `begin_step` and before this call forms the externally retained input
1258	/// prefix. Later allocations in the same step are classified as stable
1259	/// capture-local temporaries with exact executable-graph lifetimes. Calling
1260	/// this on the warm-up step is a no-op so one loop body can be used unchanged.
1261	/// If this boundary is omitted, `complete_step` conservatively classifies every
1262	/// allocation in the frame as external.
1263	///
1264	/// # Errors
1265	///
1266	/// Returns an error without a pending step or when the boundary is repeated.
1267	pub fn seal_replay_inputs(&mut self) -> Result<()> {
1268		self.require_pending()?;
1269		if self.stable_resource_inputs_sealed {
1270			return self.fail(Error::failed_precondition(
1271				"training replay inputs may only be sealed once per step",
1272			));
1273		}
1274		if self.stable_resource_frame_open
1275			&& let Err(error) = self.runtime.seal_stable_resource_inputs()
1276		{
1277			return self.fail(error);
1278		}
1279		self.stable_resource_inputs_sealed = true;
1280		Ok(())
1281	}
1282
1283	/// Complete one replay of an already captured fixed-shape training program.
1284	///
1285	/// # Errors
1286	///
1287	/// Returns an unmatched-begin, replay, completion, accounting, or callback error.
1288	pub fn complete_program_step(&mut self, program: &mut TrainingProgram) -> Result<()> {
1289		self.complete_program_step_with_device_prefix(program, Duration::ZERO)
1290	}
1291
1292	pub(super) fn adamw_mut(&mut self) -> Result<&mut AdamW> {
1293		self.optimizer.adamw_mut()
1294	}
1295
1296	pub(super) fn complete_program_step_with_device_prefix(
1297		&mut self,
1298		program: &mut TrainingProgram,
1299		prefix: Duration,
1300	) -> Result<()> {
1301		self.require_pending()?;
1302		if let Err(error) = self.select_execution_mode(ExecutionMode::Captured) {
1303			return self.fail(error);
1304		}
1305		if let Err(error) = self.seal_stable_resources() {
1306			return self.fail(error);
1307		}
1308		let optimizer = self.optimizer.adamw_mut();
1309		let optimizer = match optimizer {
1310			Ok(optimizer) => optimizer,
1311			Err(error) => return self.fail(error),
1312		};
1313		let completed = if self.config.enable_gpu_timing {
1314			program
1315				.replay_timed_and_wait(self.runtime, optimizer)
1316				.map(|(loss, time)| (loss, Some(time)))
1317		} else {
1318			program
1319				.replay_and_wait(self.runtime, optimizer)
1320				.map(|loss| (loss, None))
1321		};
1322		match completed {
1323			Ok((loss, time)) => {
1324				let time = time
1325					.map(|t| {
1326						t.checked_add(prefix)
1327							.ok_or_else(|| Error::resource_exhausted("compiled update timing overflow"))
1328					})
1329					.transpose()?;
1330				self.complete(loss, time)
1331			}
1332			Err(error) => self.fail(error),
1333		}
1334	}
1335
1336	pub fn record_source_units(&mut self, units: u64) {
1337		self.pending_source_units = Some(units);
1338	}
1339
1340	/// Exclude application work such as validation from wall-rate denominators.
1341	pub fn exclude_wall_time(&mut self, duration: Duration) {
1342		self.excluded_wall = self.excluded_wall.saturating_add(duration);
1343		self.excluded_epoch = self.excluded_epoch.saturating_add(duration);
1344	}
1345
1346	pub fn snapshot(&self) -> TrainingSnapshot {
1347		let epoch_loss = if self.epoch_loss_count == 0 {
1348			0.0
1349		} else {
1350			self.epoch_loss_sum / self.epoch_loss_count as f64
1351		};
1352		let training_loss = if self.training_loss_count == 0 {
1353			0.0
1354		} else {
1355			self.training_loss_sum / self.training_loss_count as f64
1356		};
1357		TrainingSnapshot {
1358			step_count: self.step_count,
1359			total_steps: self.config.total_steps,
1360			epoch: self.epoch(),
1361			total_epochs: self.total_epochs(),
1362			step_in_epoch: self.step_in_epoch(),
1363			steps_in_epoch: self.steps_in_current_epoch(),
1364			epoch_boundary: self.is_epoch_boundary(),
1365			last_step: self.is_last_step(),
1366			last_loss: self.last_loss,
1367			last_gpu_time: self.last_gpu_time,
1368			gpu_timing: self.gpu_timing_stats(),
1369			gpu_timed_samples: self.gpu_timed_samples,
1370			gpu_timed_units: self.gpu_timed_units,
1371			gpu_timed_source_units: self.gpu_timed_source_units,
1372			total_samples: self.total_samples,
1373			total_units: self.total_units,
1374			total_source_units: self.total_source_units,
1375			epoch_source_units: self.epoch_source_units,
1376			elapsed: self.start.elapsed().saturating_sub(self.excluded_wall),
1377			epoch_elapsed: self
1378				.epoch_start
1379				.elapsed()
1380				.saturating_sub(self.excluded_epoch),
1381			training_mean_loss: training_loss,
1382			epoch_mean_loss: epoch_loss,
1383			attempted_updates: self.attempted_updates,
1384			applied_updates: self.applied_updates,
1385			skipped_updates: self.skipped_updates,
1386		}
1387	}
1388
1389	/// Return aggregate device timing without submitting or synchronizing work.
1390	pub fn gpu_timing_stats(&self) -> GpuTimingStats {
1391		let Some(last) = self.gpu_timing_samples.last().copied() else {
1392			return GpuTimingStats::default();
1393		};
1394		let mut milliseconds = self
1395			.gpu_timing_samples
1396			.iter()
1397			.map(|duration| duration.as_secs_f64() * 1000.0)
1398			.collect::<Vec<_>>();
1399		milliseconds.sort_by(f64::total_cmp);
1400		let count = milliseconds.len();
1401		let percentile = |probability: f64| {
1402			let position = probability * (count - 1) as f64;
1403			let lower = position.floor() as usize;
1404			let upper = (lower + 1).min(count - 1);
1405			let fraction = position - lower as f64;
1406			milliseconds[lower] * (1.0 - fraction) + milliseconds[upper] * fraction
1407		};
1408		GpuTimingStats {
1409			count: count as u64,
1410			mean_ms: self.gpu_timing_sum.as_secs_f64() * 1000.0 / count as f64,
1411			min_ms: milliseconds[0],
1412			max_ms: milliseconds[count - 1],
1413			median_ms: percentile(0.50),
1414			p95_ms: percentile(0.95),
1415			last_ms: last.as_secs_f64() * 1000.0,
1416		}
1417	}
1418
1419	/// Close the lifecycle and fire `on_train_end` exactly once.
1420	///
1421	/// # Errors
1422	///
1423	/// Returns an error when a begun body was not completed or a callback fails.
1424	/// Return every metric committed to the shared history, in commit order.
1425	///
1426	/// Training epoch metrics are committed by the lifecycle itself before
1427	/// epoch-end callbacks; validation, caller metrics, and callback-committed
1428	/// values follow in registration order at each boundary.
1429	pub fn committed_metrics(&self) -> &[CommittedMetric] {
1430		&self.committed_metrics
1431	}
1432
1433	pub fn finish(mut self) -> Result<TrainingSnapshot> {
1434		if self.body_pending {
1435			return self.fail(Error::failed_precondition(
1436				"cannot finish with an incomplete training step",
1437			));
1438		}
1439		if let Err(error) = self.fire(CallbackPhase::TrainEnd) {
1440			return self.fail(error);
1441		}
1442		let snapshot = self.snapshot();
1443		self.publish_session_snapshot(Some(TrainingState::Completed));
1444		Ok(snapshot)
1445	}
1446
1447	fn complete(&mut self, loss: f32, gpu_time: Option<Duration>) -> Result<()> {
1448		self.complete_with_update(loss, gpu_time, true)
1449	}
1450
1451	fn complete_with_update(
1452		&mut self,
1453		loss: f32,
1454		gpu_time: Option<Duration>,
1455		applied: bool,
1456	) -> Result<()> {
1457		let batch_size = self
1458			.pending_step_samples
1459			.take()
1460			.unwrap_or(self.config.batch_size);
1461		let counts = (|| {
1462			let total_samples = checked_add(self.total_samples, batch_size, "training sample")?;
1463			let units = batch_size
1464				.checked_mul(self.config.sequence_length)
1465				.ok_or_else(|| Error::resource_exhausted("training sequence-unit count overflows u64"))?;
1466			let total_units = checked_add(self.total_units, units, "training sequence-unit")?;
1467			let source = match self.pending_source_units {
1468				Some(value) => value,
1469				None => fixed_source_units(batch_size, self.config.source_units_per_sample)?,
1470			};
1471			let total_source_units =
1472				checked_add(self.total_source_units, source, "training source-unit")?;
1473			let epoch_source_units = checked_add(self.epoch_source_units, source, "epoch source unit")?;
1474			let (gpu_timed_samples, gpu_timed_units, gpu_timed_source_units) = if gpu_time.is_some() {
1475				(
1476					checked_add(self.gpu_timed_samples, batch_size, "GPU-timed sample")?,
1477					checked_add(self.gpu_timed_units, units, "GPU-timed unit")?,
1478					checked_add(self.gpu_timed_source_units, source, "GPU-timed source unit")?,
1479				)
1480			} else {
1481				(
1482					self.gpu_timed_samples,
1483					self.gpu_timed_units,
1484					self.gpu_timed_source_units,
1485				)
1486			};
1487			Ok((
1488				total_samples,
1489				total_units,
1490				total_source_units,
1491				epoch_source_units,
1492				gpu_timed_samples,
1493				gpu_timed_units,
1494				gpu_timed_source_units,
1495			))
1496		})();
1497		let (
1498			total_samples,
1499			total_units,
1500			total_source_units,
1501			epoch_source_units,
1502			gpu_timed_samples,
1503			gpu_timed_units,
1504			gpu_timed_source_units,
1505		) = match counts {
1506			Ok(counts) => counts,
1507			Err(error) => return self.fail(error),
1508		};
1509		self.pending_source_units = None;
1510		self.last_loss = Some(loss);
1511		self.last_gpu_time = gpu_time;
1512		if let Some(duration) = gpu_time {
1513			self.gpu_timing_samples.push(duration);
1514			self.gpu_timing_sum = self.gpu_timing_sum.saturating_add(duration);
1515		}
1516		self.gpu_timed_samples = gpu_timed_samples;
1517		self.gpu_timed_units = gpu_timed_units;
1518		self.gpu_timed_source_units = gpu_timed_source_units;
1519		let loss_weight = if self.sample_weighted_loss {
1520			batch_size
1521		} else {
1522			1
1523		};
1524		let weighted_loss = f64::from(loss) * loss_weight as f64;
1525		self.epoch_loss_sum += weighted_loss;
1526		self.epoch_loss_count = self.epoch_loss_count.saturating_add(loss_weight);
1527		self.training_loss_sum += weighted_loss;
1528		self.training_loss_count = self.training_loss_count.saturating_add(loss_weight);
1529		self.total_samples = total_samples;
1530		self.total_units = total_units;
1531		self.total_source_units = total_source_units;
1532		self.epoch_source_units = epoch_source_units;
1533		self.attempted_updates = self.attempted_updates.saturating_add(1);
1534		if applied {
1535			self.applied_updates = self.applied_updates.saturating_add(1);
1536		} else {
1537			self.skipped_updates = self.skipped_updates.saturating_add(1);
1538		}
1539		self.close_stable_resource_frame();
1540		let snapshot = self.snapshot();
1541		for metric in &mut self.metrics {
1542			metric.update_step(snapshot);
1543		}
1544		if self.fire_checked(CallbackPhase::StepEnd)? == TrainingControl::Stop {
1545			self.stop_requested = true;
1546		}
1547		if self.is_epoch_boundary() {
1548			// The lifecycle commits the training epoch metrics before any
1549			// epoch-end callback fires, so validation, checkpoint monitors,
1550			// and early stopping read them in commit order at this boundary.
1551			let epoch_mean_loss = if self.epoch_loss_count == 0 {
1552				f64::NAN
1553			} else {
1554				self.epoch_loss_sum / self.epoch_loss_count as f64
1555			};
1556			self.committed_metrics.push(CommittedMetric {
1557				epoch: self.epoch(),
1558				step: self.step_count,
1559				split: "train".to_owned(),
1560				name: "loss".to_owned(),
1561				value: epoch_mean_loss,
1562			});
1563			// Metric commits follow the lifecycle's own training-loss commit
1564			// and precede every epoch-end callback, so validation results and
1565			// monitor decisions read them in commit order at this boundary.
1566			let snapshot = self.snapshot();
1567			let committed_metrics = &mut self.committed_metrics;
1568			let optimizer = &mut self.optimizer;
1569			let config = &self.config;
1570			for metric in &mut self.metrics {
1571				let mut context = TrainingCallbackContext {
1572					snapshot,
1573					optimizer: optimizer.callback(),
1574					config,
1575					committed_metrics,
1576					excluded_wall_time: Duration::ZERO,
1577				};
1578				if let Err(error) = metric.commit_epoch(&mut context) {
1579					self.stop_requested = true;
1580					self.body_pending = false;
1581					return Err(error);
1582				}
1583			}
1584			// Training diagnostics record at epoch cadence on the same bus:
1585			// the learning rate the completed epoch's updates actually applied
1586			// and the cumulative whole-program capture fallback count.
1587			let learning_rate = f64::from(self.optimizer.behavior().learning_rate());
1588			let fallbacks = self.program_capture_fallback_count;
1589			let epoch = self.epoch();
1590			let step = self.step_count;
1591			self.committed_metrics.push(CommittedMetric {
1592				epoch,
1593				step,
1594				split: "train".to_owned(),
1595				name: "learning_rate".to_owned(),
1596				value: learning_rate,
1597			});
1598			self.committed_metrics.push(CommittedMetric {
1599				epoch,
1600				step,
1601				split: "train".to_owned(),
1602				name: "capture_fallbacks".to_owned(),
1603				value: fallbacks as f64,
1604			});
1605			if self.skipped_updates > 0 {
1606				self.committed_metrics.push(CommittedMetric {
1607					epoch,
1608					step,
1609					split: "train".to_owned(),
1610					name: "skipped_updates".to_owned(),
1611					value: self.skipped_updates as f64,
1612				});
1613			}
1614			if self.fire_checked(CallbackPhase::EpochEnd)? == TrainingControl::Stop {
1615				self.stop_requested = true;
1616			}
1617		}
1618		self.body_pending = false;
1619		self.publish_session_snapshot(None);
1620		Ok(())
1621	}
1622
1623	fn poll_session_commands(&mut self) {
1624		let Some(mut session) = self.session.take() else {
1625			return;
1626		};
1627		let can_recapture = self.execution_mode == Some(ExecutionMode::Automatic);
1628		let actions = session.poll(self.optimizer.behavior_mut(), can_recapture);
1629		if actions.stop {
1630			self.stop_requested = true;
1631		}
1632		if actions.recapture {
1633			self.program = None;
1634			self.program_capture_disabled = false;
1635		}
1636		self.session = Some(session);
1637	}
1638
1639	fn publish_session_snapshot(&self, terminal: Option<TrainingState>) {
1640		if let Some(session) = self.session.as_ref() {
1641			session.session.publish(
1642				self.snapshot(),
1643				self.optimizer.behavior().learning_rate(),
1644				terminal,
1645			);
1646		}
1647	}
1648
1649	fn fire_checked(&mut self, phase: CallbackPhase) -> Result<TrainingControl> {
1650		match self.fire(phase) {
1651			Ok(control) => Ok(control),
1652			Err(error) => self.fail(error),
1653		}
1654	}
1655
1656	fn fire(&mut self, phase: CallbackPhase) -> Result<TrainingControl> {
1657		let snapshot = self.snapshot();
1658		let mut requested = TrainingControl::Continue;
1659		let committed_metrics = &mut self.committed_metrics;
1660		let optimizer = &mut self.optimizer;
1661		let config = &self.config;
1662		let mut excluded = Duration::ZERO;
1663		for callback in &mut self.callbacks {
1664			let mut context = TrainingCallbackContext {
1665				snapshot,
1666				optimizer: optimizer.callback(),
1667				config,
1668				committed_metrics,
1669				excluded_wall_time: Duration::ZERO,
1670			};
1671			let result = match phase {
1672				CallbackPhase::TrainBegin => callback.on_train_begin(&mut context),
1673				CallbackPhase::EpochBegin => callback.on_epoch_begin(&mut context),
1674				CallbackPhase::StepEnd => callback.on_step_end(&mut context),
1675				CallbackPhase::EpochEnd => callback.on_epoch_end(&mut context),
1676				CallbackPhase::TrainEnd => callback.on_train_end(&mut context),
1677			};
1678			excluded = excluded.saturating_add(context.excluded_wall_time);
1679			let control = match result {
1680				Ok(control) => control,
1681				Err(error) => {
1682					self.stop_requested = true;
1683					self.body_pending = false;
1684					return Err(error);
1685				}
1686			};
1687			if control == TrainingControl::Stop {
1688				self.stop_requested = true;
1689				requested = TrainingControl::Stop;
1690			}
1691		}
1692		self.excluded_wall = self.excluded_wall.saturating_add(excluded);
1693		self.excluded_epoch = self.excluded_epoch.saturating_add(excluded);
1694		Ok(requested)
1695	}
1696
1697	fn require_pending(&mut self) -> Result<()> {
1698		if self.body_pending {
1699			Ok(())
1700		} else {
1701			self.fail(Error::failed_precondition(
1702				"training step completion requires begin_step",
1703			))
1704		}
1705	}
1706
1707	fn fail<T>(&mut self, error: Error) -> Result<T> {
1708		self.close_stable_resource_frame();
1709		self.stop_requested = true;
1710		self.body_pending = false;
1711		self.publish_session_snapshot(Some(TrainingState::Failed));
1712		Err(error)
1713	}
1714
1715	pub(super) fn fail_composed_step<T>(&mut self, error: Error) -> Result<T> {
1716		self.fail(error)
1717	}
1718
1719	fn seal_stable_resources(&self) -> Result<()> {
1720		if self.stable_resource_frame_open && !self.stable_resource_inputs_sealed {
1721			self.runtime.seal_all_stable_resources_external()?;
1722		}
1723		Ok(())
1724	}
1725
1726	fn select_execution_mode(&mut self, mode: ExecutionMode) -> Result<()> {
1727		match self.execution_mode {
1728			Some(existing) if existing != mode => Err(Error::failed_precondition(
1729				"training loop cannot mix eager and captured step completion",
1730			)),
1731			Some(_) => Ok(()),
1732			None => {
1733				self.execution_mode = Some(mode);
1734				Ok(())
1735			}
1736		}
1737	}
1738
1739	fn close_stable_resource_frame(&mut self) {
1740		if self.stable_resource_frame_open {
1741			self.runtime.end_stable_resource_frame();
1742			self.stable_resource_frame_open = false;
1743		}
1744		self.stable_resource_inputs_sealed = false;
1745	}
1746
1747	fn has_epochs(&self) -> bool {
1748		self.config.steps_per_epoch > 0 || !self.epoch_offsets.is_empty()
1749	}
1750
1751	fn epoch(&self) -> u64 {
1752		if self.step_count == 0 || !self.has_epochs() {
1753			return 0;
1754		}
1755		if !self.epoch_offsets.is_empty() {
1756			return self
1757				.epoch_offsets
1758				.partition_point(|end| *end < self.step_count) as u64
1759				+ 1;
1760		}
1761		(self.step_count - 1) / self.config.steps_per_epoch + 1
1762	}
1763
1764	fn total_epochs(&self) -> u64 {
1765		if !self.epoch_offsets.is_empty() {
1766			return self.epoch_offsets.len() as u64;
1767		}
1768		if self.config.steps_per_epoch == 0 || self.config.total_steps == 0 {
1769			return 0;
1770		}
1771		self
1772			.config
1773			.total_steps
1774			.div_ceil(self.config.steps_per_epoch)
1775	}
1776
1777	fn step_in_epoch(&self) -> u64 {
1778		if self.step_count == 0 {
1779			return 0;
1780		}
1781		if !self.epoch_offsets.is_empty() {
1782			let index = self
1783				.epoch_offsets
1784				.partition_point(|end| *end < self.step_count);
1785			let begin = if index == 0 {
1786				0
1787			} else {
1788				self.epoch_offsets[index - 1]
1789			};
1790			return self.step_count - begin;
1791		}
1792		if self.config.steps_per_epoch == 0 {
1793			return self.step_count;
1794		}
1795		(self.step_count - 1) % self.config.steps_per_epoch + 1
1796	}
1797
1798	fn steps_in_current_epoch(&self) -> u64 {
1799		if !self.config.epoch_steps.is_empty() {
1800			let index = self
1801				.epoch_offsets
1802				.partition_point(|end| *end < self.step_count.max(1));
1803			return self.config.epoch_steps[index.min(self.config.epoch_steps.len() - 1)];
1804		}
1805		if self.config.steps_per_epoch == 0 {
1806			return self.config.total_steps;
1807		}
1808		if self.config.total_steps > 0 && self.epoch() == self.total_epochs() {
1809			return self.config.total_steps - (self.epoch() - 1) * self.config.steps_per_epoch;
1810		}
1811		self.config.steps_per_epoch
1812	}
1813
1814	fn is_last_step(&self) -> bool {
1815		self.config.total_steps > 0 && self.step_count == self.config.total_steps
1816	}
1817
1818	fn is_epoch_boundary(&self) -> bool {
1819		if self.step_count == 0 || !self.has_epochs() {
1820			return false;
1821		}
1822		if self.is_last_step() {
1823			return true;
1824		}
1825		if !self.epoch_offsets.is_empty() {
1826			return self.epoch_offsets.binary_search(&self.step_count).is_ok();
1827		}
1828		self.step_count.is_multiple_of(self.config.steps_per_epoch)
1829	}
1830}
1831
1832impl Drop for Training<'_, '_> {
1833	fn drop(&mut self) {
1834		self.close_stable_resource_frame();
1835	}
1836}
1837
1838fn checked_add(left: u64, right: u64, name: &'static str) -> Result<u64> {
1839	left
1840		.checked_add(right)
1841		.ok_or_else(|| Error::resource_exhausted(format!("{name} count overflows u64")))
1842}
1843
1844fn fixed_source_units(batch_size: u64, source_units_per_sample: f64) -> Result<u64> {
1845	let value = batch_size as f64 * source_units_per_sample;
1846	if !value.is_finite() || value > u64::MAX as f64 {
1847		return Err(Error::resource_exhausted(
1848			"training source-unit count overflows u64",
1849		));
1850	}
1851	Ok(value.round() as u64)
1852}
1853
1854fn normalize_epoch_schedule(config: &mut TrainingConfig) -> Result<Vec<u64>> {
1855	let mut offsets = Vec::with_capacity(config.epoch_steps.len());
1856	if config.epoch_steps.is_empty() {
1857		return Ok(offsets);
1858	}
1859	let mut sum = 0_u64;
1860	for steps in &mut config.epoch_steps {
1861		*steps = (*steps).max(1);
1862		sum = sum
1863			.checked_add(*steps)
1864			.ok_or_else(|| Error::resource_exhausted("training epoch schedule overflows u64"))?;
1865		offsets.push(sum);
1866	}
1867	config.total_steps = sum;
1868	Ok(offsets)
1869}
1870
1871#[cfg(test)]
1872#[path = "../../../../../test/rs/ml/training_timing_unit.rs"]
1873mod timing_tests;