1use 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#[derive(Clone, Copy, Debug, PartialEq, Eq)]
15pub enum TrainingCompilationStage {
16 SemanticValidation,
18 ReplaySafety,
20 Decomposition,
22 Fusion,
24 Placement,
26 Precision,
28 KernelSelection,
30 LoweringValidation,
32 MemoryPlanning,
34 SynchronizationPlanning,
36 CommandRecording,
38}
39
40impl TrainingCompilationStage {
41 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#[derive(Clone, Copy, Debug, PartialEq, Eq)]
61pub enum TrainingCompilationState {
62 NotRun,
64 Inherited,
66 Analyzed,
68 Applied,
70 Failed,
72}
73
74impl TrainingCompilationState {
75 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#[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 pub const fn stage(self) -> TrainingCompilationStage {
99 self.stage
100 }
101
102 pub const fn state(self) -> TrainingCompilationState {
104 self.state
105 }
106
107 pub const fn input_count(self) -> usize {
109 self.input_count
110 }
111
112 pub const fn output_count(self) -> usize {
114 self.output_count
115 }
116}
117
118#[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 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 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(¶meters)?;
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 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 pub fn bind_input(&mut self, captured: &Matrix, replacement: &Matrix) -> Result<()> {
321 self.plan.bind_matrix_input(captured, replacement)
322 }
323
324 pub fn replay(&mut self, runtime: &Runtime, optimizer: &mut AdamW) -> Result<Event> {
335 self.replay_impl(runtime, optimizer, false)
336 }
337
338 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 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 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 pub const fn loss(&self) -> &Matrix {
403 &self.loss
404 }
405
406 pub fn diagnostics(&self) -> ExecutionPlanDiagnostics {
408 self.plan.diagnostics()
409 }
410
411 pub const fn semantic_graph(&self) -> &SemanticGraph {
413 self.plan.semantic_graph()
414 }
415
416 pub fn semantic_debug_report_json(&self, name: &str) -> String {
418 self.plan.semantic_graph().debug_report_json(name)
419 }
420
421 pub fn debug_report_json(&self, name: &str) -> String {
423 self.plan.debug_report_json(name)
424 }
425
426 pub const fn replay_count(&self) -> u32 {
428 self.replays
429 }
430
431 pub fn is_complete(&self) -> Result<bool> {
439 self.plan.is_complete()
440 }
441
442 pub fn wait(&self) -> Result<()> {
448 self.plan.wait()
449 }
450
451 pub fn reset(self) -> Result<()> {
461 self.plan.reset()
462 }
463
464 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 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}