Skip to main content

oa/ml/training/
program.rs

1//! Captured, replayable training program.
2
3use std::time::Duration;
4
5use crate::{
6	DType, Event, ExecutionPlan, ExecutionPlanDiagnostics, Matrix, Result, Runtime, SemanticGraph,
7	runtime::CaptureAttempt,
8};
9
10use super::AdamW;
11use crate::ml::optim::AdamWProgramSignature;
12
13/// Ordered compilation stage for a captured training program.
14#[derive(Clone, Copy, Debug, PartialEq, Eq)]
15pub enum TrainingCompilationStage {
16	/// Validate the backend-independent semantic graph.
17	SemanticValidation,
18	/// Reject kernels whose mutable state cannot advance safely during replay.
19	ReplaySafety,
20	/// Analyze decomposition of semantic operations into executable work.
21	Decomposition,
22	/// Analyze candidate DNN partitions and fusion regions.
23	Fusion,
24	/// Resolve execution placement inherited from the originating runtime.
25	Placement,
26	/// Resolve precision policy inherited from recorded operations.
27	Precision,
28	/// Resolve concrete kernels inherited from recorded dispatches.
29	KernelSelection,
30	/// Validate semantic-to-executable lowering provenance.
31	LoweringValidation,
32	/// Analyze and, when profitable, materialize transient aliases.
33	MemoryPlanning,
34	/// Plan executable resource hazards and synchronization.
35	SynchronizationPlanning,
36	/// Record the reusable backend command.
37	CommandRecording,
38}
39
40impl TrainingCompilationStage {
41	/// Return the stable report token for this stage.
42	pub const fn token(self) -> &'static str {
43		match self {
44			Self::SemanticValidation => "semantic_validation",
45			Self::ReplaySafety => "replay_safety",
46			Self::Decomposition => "decomposition",
47			Self::Fusion => "fusion",
48			Self::Placement => "placement",
49			Self::Precision => "precision",
50			Self::KernelSelection => "kernel_selection",
51			Self::LoweringValidation => "lowering_validation",
52			Self::MemoryPlanning => "memory_planning",
53			Self::SynchronizationPlanning => "synchronization_planning",
54			Self::CommandRecording => "command_recording",
55		}
56	}
57}
58
59/// Outcome of one training-program compilation stage.
60#[derive(Clone, Copy, Debug, PartialEq, Eq)]
61pub enum TrainingCompilationState {
62	/// The stage did not run during this capture transaction.
63	NotRun,
64	/// The stage consumed an already-resolved decision from recording.
65	Inherited,
66	/// The stage analyzed its input without changing the executable plan.
67	Analyzed,
68	/// The stage validated or changed the executable plan successfully.
69	Applied,
70	/// The stage failed and prevented capture commit.
71	Failed,
72}
73
74impl TrainingCompilationState {
75	/// Return the stable report token for this state.
76	pub const fn token(self) -> &'static str {
77		match self {
78			Self::NotRun => "not_run",
79			Self::Inherited => "inherited",
80			Self::Analyzed => "analyzed",
81			Self::Applied => "applied",
82			Self::Failed => "failed",
83		}
84	}
85}
86
87/// Immutable evidence for one training-program compilation stage.
88#[derive(Clone, Copy, Debug, PartialEq, Eq)]
89pub struct TrainingCompilationStageRecord {
90	stage: TrainingCompilationStage,
91	state: TrainingCompilationState,
92	input_count: usize,
93	output_count: usize,
94}
95
96impl TrainingCompilationStageRecord {
97	/// Return the compilation stage.
98	pub const fn stage(self) -> TrainingCompilationStage {
99		self.stage
100	}
101
102	/// Return how the stage completed during capture.
103	pub const fn state(self) -> TrainingCompilationState {
104		self.state
105	}
106
107	/// Return the number of stage-specific input work items.
108	pub const fn input_count(self) -> usize {
109		self.input_count
110	}
111
112	/// Return the number of stage-specific output work items.
113	pub const fn output_count(self) -> usize {
114		self.output_count
115	}
116}
117
118/// Fixed-shape forward, backward, and AdamW program captured for Vulkan replay.
119///
120/// The first capture records semantic work without executing it. Replays use one
121/// cached command buffer and graph-resident optimizer state; no forward,
122/// autograd, or optimizer graph is rebuilt on the host.
123#[must_use]
124pub struct TrainingProgram {
125	plan: ExecutionPlan,
126	loss: Matrix,
127	optimizer: AdamWProgramSignature,
128	compilation_stages: [TrainingCompilationStageRecord; 11],
129	replays: u32,
130}
131
132pub(super) enum TrainingProgramCapture {
133	Captured(Box<TrainingProgram>),
134	Rejected {
135		error: crate::Error,
136		loss: Matrix,
137		optimizer: AdamWProgramSignature,
138	},
139}
140
141impl TrainingProgram {
142	/// Capture one complete fixed-shape forward/backward/AdamW step.
143	///
144	/// `step` must construct and return a scalar F32 loss and record its backward
145	/// pass. This method clears existing gradients and records the optimizer update
146	/// after `step` returns. Capture performs no submission or waiting.
147	///
148	/// # Errors
149	///
150	/// Returns an error from execution capture, `step`, backward/optimizer
151	/// recording, or when the returned value is not a scalar F32 loss or every
152	/// optimizer parameter did not receive a stable gradient.
153	pub fn capture(
154		runtime: &Runtime,
155		optimizer: &mut AdamW,
156		step: impl FnOnce() -> Result<Matrix>,
157	) -> Result<Self> {
158		let (plan, loss) = runtime.capture_observed_matrix(|| {
159			optimizer.zero_grad();
160			let loss = step()?;
161			if !loss.shape().is_empty() || loss.dtype() != DType::F32 {
162				return Err(crate::Error::invalid_argument(
163					"training program requires a scalar F32 loss",
164				));
165			}
166			optimizer.step()?;
167			Ok(loss)
168		})?;
169		plan.validate_training_replay_safety()?;
170		let optimizer = optimizer.program_signature()?;
171		let compilation_stages = compilation_stage_records(plan.diagnostics());
172		Ok(Self {
173			plan,
174			loss,
175			optimizer,
176			compilation_stages,
177			replays: 0,
178		})
179	}
180
181	/// Capture one complete fixed-shape scaled forward/backward/AdamW step
182	/// under a [`GradScaler`](crate::ml::optim::GradScaler).
183	///
184	/// The `step` closure owns forward and backward exactly as in
185	/// [`Self::capture`], with one contract change: it must scale the loss
186	/// with `scale_loss` on the scaler it receives before `tape.backward`
187	/// and return the *unscaled* scalar F32 loss for observability. The
188	/// closure receives the prepared scaler rather than capturing it so the
189	/// same value can be mutably prepared and immutably consulted in one
190	/// call. This method then records
191	/// the remainder of the scaler contract inside the same program —
192	/// gradient unscaling, the finite check, device-side scale bookkeeping,
193	/// and the gated optimizer update — so replaying needs no per-step host
194	/// readback: overflow skips the update on-device exactly as a host-gated
195	/// `step_optimizer` false return does, and scale growth/backoff advance
196	/// in device state per replay.
197	///
198	/// This method prepares the scaler on the first capture and retains its
199	/// device state for recapture on the same Runtime. Recapture reads the
200	/// applied optimizer step at a completed boundary for bias correction.
201	/// Complete prior replay work before recapturing.
202	///
203	/// # Errors
204	///
205	/// Returns the scaler preparation, gate binding, execution capture,
206	/// `step`, unscale, or optimizer recording errors, or the scalar-loss
207	/// validation error of [`Self::capture`].
208	pub fn capture_scaled(
209		runtime: &Runtime,
210		optimizer: &mut AdamW,
211		scaler: &mut crate::ml::optim::GradScaler,
212		step: impl FnOnce(&crate::ml::optim::GradScaler) -> Result<Matrix>,
213	) -> Result<Self> {
214		if !optimizer.belongs_to(runtime) {
215			return Err(crate::Error::invalid_argument(
216				"training optimizer must belong to the capture Runtime",
217			));
218		}
219		let applied_step = optimizer.applied_step_at_boundary()?;
220		scaler.ensure_captured(runtime)?;
221		optimizer.set_finite_gate(&scaler.finite_flag()?)?;
222		let parameters = optimizer.parameters();
223		let (plan, loss) = runtime.capture_observed_matrix(|| {
224			optimizer.zero_grad();
225			let loss = step(scaler)?;
226			if !loss.shape().is_empty() || loss.dtype() != DType::F32 {
227				return Err(crate::Error::invalid_argument(
228					"training program requires a scalar F32 loss",
229				));
230			}
231			let check = scaler.unscale_gradients(&parameters)?;
232			scaler.record_finite_gate(&check)?;
233			optimizer.record_captured_step(applied_step)?;
234			Ok(loss)
235		})?;
236		plan.validate_training_replay_safety()?;
237		let optimizer = optimizer.program_signature()?;
238		let compilation_stages = compilation_stage_records(plan.diagnostics());
239		Ok(Self {
240			plan,
241			loss,
242			optimizer,
243			compilation_stages,
244			replays: 0,
245		})
246	}
247
248	pub(super) fn capture_preserving_recording(
249		runtime: &Runtime,
250		optimizer: &mut AdamW,
251		step: impl FnOnce() -> Result<Matrix>,
252	) -> Result<TrainingProgramCapture> {
253		let attempt = runtime.capture_observed_training_matrix_preserving(|| {
254			optimizer.zero_grad();
255			let loss = step()?;
256			if !loss.shape().is_empty() || loss.dtype() != DType::F32 {
257				return Err(crate::Error::invalid_argument(
258					"training program requires a scalar F32 loss",
259				));
260			}
261			optimizer.step()?;
262			Ok(loss)
263		})?;
264		let optimizer_signature = optimizer.program_signature()?;
265		Ok(match attempt {
266			CaptureAttempt::Captured { plan, output: loss } => {
267				let compilation_stages = compilation_stage_records(plan.diagnostics());
268				TrainingProgramCapture::Captured(Box::new(Self {
269					plan: *plan,
270					loss,
271					optimizer: optimizer_signature,
272					compilation_stages,
273					replays: 0,
274				}))
275			}
276			CaptureAttempt::Rejected {
277				error,
278				output: loss,
279			} => TrainingProgramCapture::Rejected {
280				error,
281				loss,
282				optimizer: optimizer_signature,
283			},
284		})
285	}
286
287	/// Upload a new fixed-shape host batch into a captured input slot.
288	///
289	/// The slot rotates through a bounded triple-buffered staging ring: each
290	/// upload writes the next ring buffer and rebinds it, so a pending prior
291	/// replay stalls only while its submission still consumes the target ring
292	/// buffer. Each distinct ring binding records one command on first use and
293	/// reuses the cached command afterwards. The captured Matrix's own buffer
294	/// mirrors each upload, so the stable value remains coherent for host
295	/// reads.
296	///
297	/// # Errors
298	///
299	/// Returns the input-slot validation, completion, or upload error.
300	pub fn upload_input<T: crate::core::Element>(
301		&mut self,
302		captured: &Matrix,
303		values: &[T],
304	) -> Result<()> {
305		self.plan.upload_matrix_input(captured, values)
306	}
307
308	/// Rebind a captured input slot to a different same-shape Matrix without
309	/// waiting for in-flight replays.
310	///
311	/// Unlike [`TrainingProgram::upload_input`], rebinding does not wait for the
312	/// pending replay because it never overwrites the buffer the GPU still reads.
313	/// Rotating through a bounded set of input Matrices therefore pipelines
314	/// uploads with replays; each distinct binding set pays one command record on
315	/// its first submission and reuses the cached command afterwards.
316	///
317	/// # Errors
318	///
319	/// Returns the input-slot validation error.
320	pub fn bind_input(&mut self, captured: &Matrix, replacement: &Matrix) -> Result<()> {
321		self.plan.bind_matrix_input(captured, replacement)
322	}
323
324	/// Submit one replay without waiting.
325	///
326	/// Same-queue timeline ordering serializes repeated updates. Call
327	/// [`TrainingProgram::upload_input`] before changing a reused input slot; it
328	/// owns the required completion wait.
329	///
330	/// # Errors
331	///
332	/// Returns an error when the runtime or optimizer differs, stable captured state
333	/// was replaced, a counter is exhausted, or submission fails.
334	pub fn replay(&mut self, runtime: &Runtime, optimizer: &mut AdamW) -> Result<Event> {
335		self.replay_impl(runtime, optimizer, false)
336	}
337
338	/// Submit one replay with device timestamps around the complete program.
339	///
340	/// # Errors
341	///
342	/// Returns the errors from [`TrainingProgram::replay`], or
343	/// `MissingCapability` when the selected queue cannot provide timestamps.
344	pub fn replay_timed(&mut self, runtime: &Runtime, optimizer: &mut AdamW) -> Result<Event> {
345		self.replay_impl(runtime, optimizer, true)
346	}
347
348	fn replay_impl(
349		&mut self,
350		runtime: &Runtime,
351		optimizer: &mut AdamW,
352		timed: bool,
353	) -> Result<Event> {
354		let expected_step = self
355			.optimizer
356			.base_step
357			.checked_add(self.replays)
358			.ok_or_else(|| crate::Error::resource_exhausted("training step counter exhausted"))?;
359		let logical_step = expected_step
360			.checked_add(1)
361			.ok_or_else(|| crate::Error::resource_exhausted("training step counter exhausted"))?;
362		optimizer.validate_program_replay(&self.optimizer, expected_step, logical_step)?;
363		let event = if timed {
364			runtime.submit_timed(&self.plan)?
365		} else {
366			runtime.submit(&self.plan)?
367		};
368		optimizer.complete_program_replay(&self.optimizer, logical_step)?;
369		self.replays = self
370			.replays
371			.checked_add(1)
372			.ok_or_else(|| crate::Error::resource_exhausted("training replay counter exhausted"))?;
373		Ok(event)
374	}
375
376	/// Submit one replay, wait for its exact completion, and read its scalar loss.
377	///
378	/// # Errors
379	///
380	/// Returns the replay, completion, or loss-read error.
381	pub fn replay_and_wait(&mut self, runtime: &Runtime, optimizer: &mut AdamW) -> Result<f32> {
382		self.replay(runtime, optimizer)?.wait()?;
383		Ok(self.loss.read_f32()?[0])
384	}
385
386	/// Submit one timed replay, wait, and return its scalar loss and device time.
387	///
388	/// # Errors
389	///
390	/// Returns the timed replay, completion, timestamp, or loss-read error.
391	pub fn replay_timed_and_wait(
392		&mut self,
393		runtime: &Runtime,
394		optimizer: &mut AdamW,
395	) -> Result<(f32, Duration)> {
396		let event = self.replay_timed(runtime, optimizer)?;
397		let duration = event.device_duration()?;
398		Ok((self.loss.read_f32()?[0], duration))
399	}
400
401	/// Return the captured scalar loss value.
402	pub const fn loss(&self) -> &Matrix {
403		&self.loss
404	}
405
406	/// Return graph, command-cache, submission, and input-upload diagnostics.
407	pub fn diagnostics(&self) -> ExecutionPlanDiagnostics {
408		self.plan.diagnostics()
409	}
410
411	/// Return the captured backend-independent training graph.
412	pub const fn semantic_graph(&self) -> &SemanticGraph {
413		self.plan.semantic_graph()
414	}
415
416	/// Return the backend-independent captured semantic graph as deterministic JSON.
417	pub fn semantic_debug_report_json(&self, name: &str) -> String {
418		self.plan.semantic_graph().debug_report_json(name)
419	}
420
421	/// Return the normalized captured executable graph as deterministic JSON.
422	pub fn debug_report_json(&self, name: &str) -> String {
423		self.plan.debug_report_json(name)
424	}
425
426	/// Return how many training steps this program submitted.
427	pub const fn replay_count(&self) -> u32 {
428		self.replays
429	}
430
431	/// Return whether the most recently submitted training replay has completed.
432	///
433	/// A captured program that has not replayed is complete.
434	///
435	/// # Errors
436	///
437	/// Returns an error when Vulkan cannot query the originating timeline.
438	pub fn is_complete(&self) -> Result<bool> {
439		self.plan.is_complete()
440	}
441
442	/// Wait for the most recently submitted replay and host retirement.
443	///
444	/// # Errors
445	///
446	/// Returns an error when Vulkan completion or host retirement waiting fails.
447	pub fn wait(&self) -> Result<()> {
448		self.plan.wait()
449	}
450
451	/// Wait for pending replay and consume the program, releasing captured state.
452	///
453	/// Capture constructs a new Rust value, so consuming reset replaces the C++
454	/// donor's reusable empty shell. Ordinary drop remains non-blocking.
455	///
456	/// # Errors
457	///
458	/// Returns an error from [`TrainingProgram::wait`]. Submitted resources remain
459	/// protected by runtime retirement if the wait fails.
460	pub fn reset(self) -> Result<()> {
461		self.plan.reset()
462	}
463
464	/// Return the donor-compatible deterministic compilation report as JSON.
465	///
466	/// The report contains no Vulkan handles, addresses, descriptors, or mutable
467	/// routing controls. It records capture-time stages, private DNN analysis,
468	/// semantic lowering provenance, and logical memory-planning evidence.
469	pub fn compilation_debug_report_json(&self, name: &str) -> String {
470		let diagnostics = self.plan.diagnostics();
471		let lowering = self.plan.semantic_lowering();
472		let resources = self.plan.captured_resources();
473		let mut output = String::new();
474		output.push_str("{\n  \"schema\": \"oa.training_compilation.v2\",\n  \"name\": ");
475		crate::core::push_json_string(&mut output, name);
476		output.push_str(",\n  \"captured\": true,\n  \"stages\": [");
477		for (index, stage) in self.compilation_stages.iter().enumerate() {
478			output.push_str(if index == 0 { "\n" } else { ",\n" });
479			crate::core::push_format(
480				&mut output,
481				format_args!(
482					"    {{\"stage\": \"{}\", \"state\": \"{}\", \"input_count\": {}, \"output_count\": {}}}",
483					stage.stage.token(),
484					stage.state.token(),
485					stage.input_count,
486					stage.output_count
487				),
488			);
489		}
490		output.push_str("\n  ],\n  \"dnn_plan\": {\n");
491		crate::core::push_format(
492			&mut output,
493			format_args!(
494				"    \"graph_hash\": {},\n    \"source_operation_count\": {},\n    \"captured_operation_count\": {},\n    \"partition_count\": {},\n    \"recognized_partition_count\": {},\n    \"applied_partition_count\": {},\n    \"inherited_partition_count\": {},\n    \"fallback_partition_count\": {},\n    \"unexpected_fallback_count\": {},\n    \"fallback_reasons\": [",
495				diagnostics.dnn_graph_hash(),
496				diagnostics.semantic_operation_count(),
497				diagnostics.dnn_captured_operation_count(),
498				diagnostics.dnn_partition_count(),
499				diagnostics.dnn_recognized_partition_count(),
500				diagnostics.dnn_applied_partition_count(),
501				diagnostics.dnn_inherited_partition_count(),
502				diagnostics.dnn_fallback_partition_count(),
503				diagnostics.dnn_unexpected_fallback_count(),
504			),
505		);
506		for (index, reason) in self.plan.dnn_fallback_reasons().enumerate() {
507			if index != 0 {
508				output.push_str(", ");
509			}
510			crate::core::push_json_string(&mut output, reason);
511		}
512		output.push_str("]\n");
513		output.push_str("  },\n  \"lowering_analysis\": {\n");
514		crate::core::push_format(
515			&mut output,
516			format_args!(
517				"    \"operation_count\": {},\n    \"schema_owned_node_count\": {},\n    \"compatibility_node_count\": {},\n    \"direct_operation_count\": {},\n    \"decomposed_operation_count\": {},\n    \"fused_operation_count\": {},\n    \"fused_node_count\": {},\n    \"maximum_nodes_per_operation\": {},\n    \"maximum_operations_per_node\": {},\n    \"operations\": [",
518				diagnostics.semantic_operation_count(),
519				lowering.schema_owned_node_count(),
520				lowering.compatibility_node_count(),
521				lowering.direct_op_count(),
522				lowering.decomposed_op_count(),
523				lowering.fused_op_count(),
524				lowering.fused_node_count(),
525				lowering.maximum_nodes_per_op(),
526				lowering.maximum_ops_per_node(),
527			),
528		);
529		for (index, operation) in self.plan.semantic_graph().operations().iter().enumerate() {
530			output.push_str(if index == 0 { "\n" } else { ",\n" });
531			crate::core::push_format(
532				&mut output,
533				format_args!(
534					"      {{\"operation\": {}, \"executable_node_count\": {}}}",
535					operation.id().index(),
536					lowering.executable_node_count(operation.id())
537				),
538			);
539		}
540		if !self.plan.semantic_graph().operations().is_empty() {
541			output.push('\n');
542		}
543		output.push_str("    ]\n  },\n  \"memory_analysis\": {\n");
544		crate::core::push_format(
545			&mut output,
546			format_args!(
547				"    \"resource_count\": {},\n    \"candidate_count\": {},\n    \"materialization_eligible_count\": {},\n    \"alias_group_count\": {},\n    \"potential_savings_bytes\": {},\n    \"materialized_savings_bytes\": {},\n    \"materialized\": {},\n    \"fallback_reason\": ",
548				diagnostics.captured_resource_count(),
549				diagnostics.alias_candidate_count(),
550				diagnostics.alias_candidate_count(),
551				diagnostics.planned_alias_group_count(),
552				diagnostics.potential_alias_savings(),
553				diagnostics.materialized_alias_savings(),
554				if diagnostics.materialized_alias_savings() == 0 {
555					"false"
556				} else {
557					"true"
558				},
559			),
560		);
561		crate::core::push_json_string(
562			&mut output,
563			self
564				.plan
565				.alias_materialization_fallback_reason()
566				.unwrap_or(""),
567		);
568		output.push_str(",\n    \"resources\": [");
569		for (index, resource) in resources.iter().enumerate() {
570			output.push_str(if index == 0 { "\n" } else { ",\n" });
571			crate::core::push_format(
572				&mut output,
573				format_args!(
574					"      {{\"resource\": {}, \"bytes\": {}, \"placement\": \"host_upload\", \"has_lifetime\": true, \"first_access\": {}, \"last_access\": {}, \"semantic_external\": {}, \"stable_replay_input\": {}, \"stable_transient\": {}, \"observed_output\": {}, \"alias_candidate\": {}, \"alias_materialized\": {}}}",
575					resource.resource(),
576					resource.byte_len(),
577					resource.first_access(),
578					resource.last_access(),
579					resource.semantic_external(),
580					resource.stable_replay_input(),
581					resource.stable_transient(),
582					resource.observed_output(),
583					resource.alias_candidate(),
584					resource.alias_materialized(),
585				),
586			);
587		}
588		if !resources.is_empty() {
589			output.push('\n');
590		}
591		output.push_str("    ]\n  }\n}\n");
592		output
593	}
594
595	/// Return immutable stage-by-stage evidence from the capture transaction.
596	///
597	/// Explicit capture records commands lazily, so its command-recording stage is
598	/// `NotRun`. Automatic [`crate::ml::Training`] capture precompiles the
599	/// reusable command before committing its preserved source recording.
600	pub const fn compilation_stages(&self) -> &[TrainingCompilationStageRecord] {
601		&self.compilation_stages
602	}
603}
604
605fn compilation_stage_records(
606	diagnostics: ExecutionPlanDiagnostics,
607) -> [TrainingCompilationStageRecord; 11] {
608	use TrainingCompilationStage as Stage;
609	use TrainingCompilationState as State;
610
611	let semantic = diagnostics.semantic_operation_count();
612	let nodes = diagnostics.node_count();
613	let memory_state = if diagnostics.materialized_alias_savings() == 0 {
614		State::Analyzed
615	} else {
616		State::Applied
617	};
618	let memory_output = if diagnostics.materialized_alias_savings() == 0 {
619		diagnostics.alias_candidate_count()
620	} else {
621		diagnostics.alias_materialized_count()
622	};
623	let command_state = if diagnostics.command_recording_count() == 0 {
624		State::NotRun
625	} else {
626		State::Applied
627	};
628	[
629		record(
630			Stage::SemanticValidation,
631			State::Applied,
632			semantic,
633			semantic,
634		),
635		record(Stage::ReplaySafety, State::Applied, nodes, nodes),
636		record(
637			Stage::Decomposition,
638			State::Analyzed,
639			semantic,
640			diagnostics.schema_owned_node_count(),
641		),
642		record(
643			Stage::Fusion,
644			State::Analyzed,
645			semantic,
646			diagnostics.dnn_partition_count(),
647		),
648		record(Stage::Placement, State::Inherited, semantic, nodes),
649		record(Stage::Precision, State::Inherited, semantic, nodes),
650		record(Stage::KernelSelection, State::Inherited, semantic, nodes),
651		record(Stage::LoweringValidation, State::Applied, semantic, nodes),
652		record(
653			Stage::MemoryPlanning,
654			memory_state,
655			diagnostics.captured_resource_count(),
656			memory_output,
657		),
658		record(
659			Stage::SynchronizationPlanning,
660			State::Applied,
661			nodes,
662			diagnostics.barrier_count(),
663		),
664		record(Stage::CommandRecording, command_state, nodes, nodes),
665	]
666}
667
668const fn record(
669	stage: TrainingCompilationStage,
670	state: TrainingCompilationState,
671	input_count: usize,
672	output_count: usize,
673) -> TrainingCompilationStageRecord {
674	TrainingCompilationStageRecord {
675		stage,
676		state,
677		input_count,
678		output_count,
679	}
680}