Skip to main content

oa/viewer/
training_source.rs

1//! `TrainingViewerSource` — non-owning `TrainingSession` dashboard adapter.
2//!
3//! Donor: `oa/ui/trainingViewer.h`, `oa/ui/trainingViewer.cpp`.
4//!
5//! Training owns the model, optimizer, graph, and worker thread. The viewer
6//! only reads immutable snapshots and enqueues typed commands at the shared
7//! safe point, so it can attach to supervised, PPO, DQN, or SAC training
8//! without another trainer abstraction.
9//!
10//! The donor registers its key actions into the `Viewer`-owned `InputSystem`
11//! during `init`. The Rust `ViewerLiveSource` seam delivers raw UI events
12//! instead, so this source owns one [`InputSystem`] and dispatches the same
13//! four actions — Space pause/resume, C checkpoint, E evaluate, S stop.
14
15use std::sync::Mutex;
16
17use crate::input::{InputContext, InputEvent, InputSystem, Key, KeyAction, KeyBinding};
18use crate::ml::training::{TrainingSession, TrainingSessionSnapshot, TrainingState};
19use crate::ui::{
20	PixelRect, Ui, UiDirection, UiDropdownConfig, UiEdge, UiLayout, UiPlotConfig, UiScrollConfig,
21	UiSplitConfig, UiTabItem, UiTooltipConfig, UiTreeRowConfig,
22};
23pub use crate::viewer::types::TrainingViewerConfig;
24use crate::{Color, Engine, Error, Event, Result, Texture};
25
26use super::{ViewerLiveCapabilities, ViewerLiveSource};
27
28impl Default for TrainingViewerConfig {
29	fn default() -> Self {
30		Self {
31			title: String::from("OA training"),
32			history_capacity: 512,
33			max_metric_plots: 6,
34			show_gpu_timing: true,
35			show_wall_timing: true,
36			show_preview: true,
37		}
38	}
39}
40
41/// Immutable generated artifact handed from a training/evaluation producer to
42/// the viewer. The texture allocation is shared; the timeline event prevents
43/// presentation until the producing GPU batch has completed. Replacing a
44/// pending frame drops it without ever blocking the training owner.
45///
46/// Donor: `oa::TrainingPreviewFrame`.
47#[derive(Clone)]
48pub struct TrainingPreviewFrame {
49	/// Produced preview texture, required for publication.
50	pub texture: Option<Texture>,
51	/// Producer completion event; the frame is promoted only when complete.
52	pub completion: Event,
53	/// Optional frame label.
54	pub label: String,
55	/// Training step that produced the frame.
56	pub step: i64,
57}
58
59/// Non-owning `TrainingSession` dashboard source for `Viewer` live mode.
60///
61/// Donor: `oa::TrainingViewerSource`.
62pub struct TrainingViewerSource {
63	session: TrainingSession,
64	config: TrainingViewerConfig,
65	input: InputSystem,
66	snapshot: Option<TrainingSessionSnapshot>,
67	series: Vec<Series>,
68	last_result_sequence: u64,
69	viewer_frame_ms: f32,
70	/// 0=responsive, 1/2=explicit metric-card column count.
71	metric_columns: i32,
72	selected_metric: i32,
73	compact_tabs: crate::ui::UiTabBarState,
74	preview_split_ratio: f32,
75	preview: Mutex<PreviewState>,
76}
77
78struct Series {
79	name: String,
80	values: Vec<f32>,
81	color: Color,
82	expanded: bool,
83}
84
85#[derive(Default)]
86struct PreviewState {
87	pending: Option<TrainingPreviewFrame>,
88	current: Option<TrainingPreviewFrame>,
89}
90
91impl TrainingViewerSource {
92	/// Attach to `session`. The handle is shared, not owned: enqueueing and
93	/// snapshot reads never block the training thread.
94	pub fn new(session: &TrainingSession, mut config: TrainingViewerConfig) -> Self {
95		config.history_capacity = config.history_capacity.max(2);
96		config.max_metric_plots = config.max_metric_plots.clamp(1, 12);
97		let mut input = InputSystem::new();
98		let binding = |key| KeyBinding {
99			key,
100			modifiers: crate::input::INPUT_MOD_NONE,
101		};
102		let pause_session = session.clone();
103		input.register_action(KeyAction {
104			name: "training-pause-resume".into(),
105			binding: binding(Key::Space),
106			context: InputContext::Global,
107			allow_repeat: false,
108			callback: Some(Box::new(move || match pause_session.state() {
109				TrainingState::Running => {
110					log_enqueue(pause_session.pause(0), "pause");
111				}
112				TrainingState::Paused => {
113					log_enqueue(pause_session.resume(0), "resume");
114				}
115				_ => {}
116			})),
117		});
118		let stop_session = session.clone();
119		input.register_action(KeyAction {
120			name: "training-stop".into(),
121			binding: binding(Key::S),
122			context: InputContext::Global,
123			allow_repeat: false,
124			callback: Some(Box::new(move || {
125				log_enqueue(stop_session.stop(0), "stop");
126			})),
127		});
128		let checkpoint_session = session.clone();
129		input.register_action(KeyAction {
130			name: "training-checkpoint".into(),
131			binding: binding(Key::C),
132			context: InputContext::Global,
133			allow_repeat: false,
134			callback: Some(Box::new(move || {
135				log_enqueue(checkpoint_session.checkpoint(0), "checkpoint");
136			})),
137		});
138		let evaluate_session = session.clone();
139		input.register_action(KeyAction {
140			name: "training-evaluate".into(),
141			binding: binding(Key::E),
142			context: InputContext::Global,
143			allow_repeat: false,
144			callback: Some(Box::new(move || {
145				log_enqueue(evaluate_session.evaluate(0), "evaluate");
146			})),
147		});
148		crate::log_info!(
149			crate::LogComponent::UI,
150			"OaTrainingViewer: Space=pause/resume · C=checkpoint · E=evaluate · S=stop"
151		);
152		Self {
153			session: session.clone(),
154			config,
155			input,
156			snapshot: None,
157			series: Vec::new(),
158			last_result_sequence: 0,
159			viewer_frame_ms: 0.0,
160			metric_columns: 0,
161			selected_metric: 0,
162			compact_tabs: crate::ui::UiTabBarState::default(),
163			preview_split_ratio: 0.60,
164			preview: Mutex::new(PreviewState::default()),
165		}
166	}
167
168	/// Publish one preview frame; an incomplete producer event defers
169	/// promotion until the next `update` observes completion.
170	///
171	/// # Errors
172	///
173	/// Returns [`ErrorKind::InvalidArgument`] when the frame has no texture.
174	///
175	/// [`ErrorKind::InvalidArgument`]: crate::ErrorKind::InvalidArgument
176	pub fn publish_preview(&self, frame: TrainingPreviewFrame) -> Result<()> {
177		if frame.texture.is_none() {
178			return Err(Error::invalid_argument(
179				"OaTrainingViewer preview requires a valid texture",
180			));
181		}
182		self
183			.preview
184			.lock()
185			.unwrap_or_else(std::sync::PoisonError::into_inner)
186			.pending = Some(frame);
187		Ok(())
188	}
189
190	/// Return the normalized dashboard configuration.
191	#[must_use]
192	pub const fn config(&self) -> &TrainingViewerConfig {
193		&self.config
194	}
195
196	/// Return the latest session snapshot observed by the dashboard.
197	#[must_use]
198	pub fn latest_snapshot(&self) -> Option<TrainingSessionSnapshot> {
199		self.snapshot.clone()
200	}
201
202	/// Return the latest promoted preview frame, if any.
203	#[must_use]
204	pub fn latest_preview(&self) -> Option<TrainingPreviewFrame> {
205		self
206			.preview
207			.lock()
208			.unwrap_or_else(std::sync::PoisonError::into_inner)
209			.current
210			.clone()
211	}
212
213	/// Return the number of retained metric series.
214	#[must_use]
215	pub fn metric_series_count(&self) -> u32 {
216		self.series.len() as u32
217	}
218
219	/// Return the retained sample count for the series named `name`.
220	#[must_use]
221	pub fn metric_sample_count(&self, name: &str) -> u32 {
222		self
223			.series
224			.iter()
225			.find(|series| series.name == name)
226			.map_or(0, |series| series.values.len() as u32)
227	}
228
229	fn find_series(&mut self, name: &str) -> Option<&mut Series> {
230		self.series.iter_mut().find(|series| series.name == name)
231	}
232
233	fn append_series(&mut self, name: &str, value: f64, color: Color) {
234		if !value.is_finite() {
235			return;
236		}
237		if self.find_series(name).is_none() {
238			if self.series.len() >= self.config.max_metric_plots as usize {
239				return;
240			}
241			self.series.push(Series {
242				name: name.to_owned(),
243				values: Vec::new(),
244				color,
245				expanded: true,
246			});
247		}
248		let capacity = self.config.history_capacity.max(2) as usize;
249		if let Some(series) = self.find_series(name) {
250			series.values.push(value as f32);
251			if series.values.len() > capacity {
252				let excess = series.values.len() - capacity;
253				series.values.drain(..excess);
254			}
255		}
256	}
257
258	fn append_snapshot(&mut self, snapshot: &TrainingSessionSnapshot) {
259		let new_step = self
260			.snapshot
261			.as_ref()
262			.is_none_or(|previous| snapshot.step != previous.step);
263		if new_step && snapshot.step > 0 {
264			self.append_series("loss", f64::from(snapshot.loss), Color::accent());
265			if self.config.show_gpu_timing {
266				self.append_series("gpu_ms", snapshot.gpu_ms, Color::new(0.70, 0.46, 0.96, 1.0));
267			}
268			if self.config.show_wall_timing {
269				self.append_series("wall_ms", snapshot.wall_ms, Color::warning());
270			}
271			let colors = [
272				Color::success(),
273				Color::new(0.30, 0.72, 0.94, 1.0),
274				Color::new(0.95, 0.43, 0.36, 1.0),
275				Color::new(0.85, 0.67, 0.24, 1.0),
276				Color::new(0.55, 0.78, 0.42, 1.0),
277			];
278			for (index, metric) in snapshot.metrics.iter().enumerate() {
279				self.append_series(&metric.name, metric.value, colors[index % colors.len()]);
280			}
281		}
282		self.snapshot = Some(snapshot.clone());
283	}
284
285	fn poll_results(&mut self) {
286		for result in self.session.results_after(self.last_result_sequence) {
287			self.last_result_sequence = self.last_result_sequence.max(result.sequence);
288		}
289	}
290}
291
292fn state_name(state: TrainingState) -> &'static str {
293	match state {
294		TrainingState::Running => "RUNNING",
295		TrainingState::Paused => "PAUSED",
296		TrainingState::Stopping => "STOPPING",
297		TrainingState::Completed => "COMPLETED",
298		TrainingState::Failed => "FAILED",
299	}
300}
301
302fn state_color(state: TrainingState) -> Color {
303	match state {
304		TrainingState::Running | TrainingState::Completed => Color::success(),
305		TrainingState::Paused | TrainingState::Stopping => Color::warning(),
306		TrainingState::Failed => Color::error(),
307	}
308}
309
310fn log_enqueue(result: Result<u64>, name: &str) {
311	if let Err(error) = result {
312		crate::log_warn!(
313			crate::LogComponent::UI,
314			"OaTrainingViewer {name} rejected: {error}"
315		);
316	}
317}
318
319#[allow(clippy::too_many_arguments)]
320fn draw_label(
321	ui: &mut Ui<'_>,
322	content_scale: f32,
323	id: &str,
324	rect: PixelRect,
325	text: &str,
326	size: f32,
327	color: Color,
328) {
329	let mut style = ui.current_style();
330	style.font_size = size * content_scale;
331	style.text = color;
332	let layout = UiLayout {
333		padding: UiEdge::default(),
334		..UiLayout::default()
335	};
336	ui.push_style(style);
337	ui.begin_panel_with_layout(id, rect, layout);
338	ui.label(text);
339	ui.end_panel();
340	ui.pop_style();
341}
342
343impl ViewerLiveSource for TrainingViewerSource {
344	fn capabilities(&self) -> ViewerLiveCapabilities {
345		ViewerLiveCapabilities {
346			receives_events: true,
347			..ViewerLiveCapabilities::default()
348		}
349	}
350
351	fn open(&mut self, _engine: &Engine) -> Result<()> {
352		if let Some(snapshot) = self.session.latest_snapshot() {
353			self.append_snapshot(&snapshot);
354		}
355		Ok(())
356	}
357
358	fn on_event(&mut self, event: &InputEvent) -> Result<()> {
359		self.input.dispatch(event);
360		Ok(())
361	}
362
363	fn update(&mut self, delta_ms: f32) -> Result<()> {
364		if !delta_ms.is_finite() || delta_ms < 0.0 {
365			return Err(Error::invalid_argument(
366				"TrainingViewerSource::update requires a finite non-negative delta",
367			));
368		}
369		if delta_ms > 0.0 {
370			self.viewer_frame_ms = if self.viewer_frame_ms <= 0.0 {
371				delta_ms
372			} else {
373				self.viewer_frame_ms * 0.90 + delta_ms * 0.10
374			};
375		}
376		if let Some(snapshot) = self.session.latest_snapshot() {
377			let changed = self.snapshot.as_ref().is_none_or(|previous| {
378				snapshot.step != previous.step
379					|| snapshot.revision != previous.revision
380					|| snapshot.state != previous.state
381			});
382			if changed {
383				self.append_snapshot(&snapshot);
384			}
385		}
386		{
387			let mut preview = self
388				.preview
389				.lock()
390				.unwrap_or_else(std::sync::PoisonError::into_inner);
391			if preview
392				.pending
393				.as_ref()
394				.is_some_and(|frame| frame.completion.is_complete().unwrap_or(false))
395			{
396				preview.current = preview.pending.take();
397			}
398		}
399		self.poll_results();
400		Ok(())
401	}
402
403	#[allow(clippy::too_many_lines)]
404	fn render(&mut self, ui: &mut Ui<'_>, width: u32, height: u32) -> Result<()> {
405		if width > i32::MAX as u32 || height > i32::MAX as u32 {
406			return Err(Error::invalid_argument(
407				"TrainingViewerSource::render extent exceeds signed UI coordinates",
408			));
409		}
410		let (width, height) = (width as i32, height as i32);
411		let content_scale = ui.content_scale();
412		let px = |logical: i32| ((logical as f32 * content_scale).round() as i32).max(1);
413		if width < px(320) || height < px(240) {
414			return Ok(());
415		}
416		let margin = px(20);
417		let gap = px(14);
418		let header_height = px(108);
419		let header = PixelRect::new(
420			margin,
421			margin,
422			(width - margin * 2) as u32,
423			header_height as u32,
424		);
425		ui.rect(header, Color::new(0.045, 0.045, 0.045, 1.0), 0.0)?;
426		ui.rect_outline(header, Color::new(1.0, 1.0, 1.0, 0.10), 1, 0.0)?;
427
428		let default_snapshot = TrainingSessionSnapshot {
429			revision: 0,
430			state: TrainingState::Running,
431			step: 0,
432			epoch: 0,
433			learning_rate: 0.0,
434			loss: 0.0,
435			gpu_ms: 0.0,
436			wall_ms: 0.0,
437			metrics: Vec::new(),
438		};
439		let snapshot = self.snapshot.clone().unwrap_or(default_snapshot);
440		let status_color = state_color(snapshot.state);
441		ui.rect(
442			PixelRect::new(header.x, header.y, px(6) as u32, header.h),
443			status_color,
444			0.0,
445		)?;
446		draw_label(
447			ui,
448			content_scale,
449			"training-title",
450			PixelRect::new(
451				header.x + px(22),
452				header.y + px(10),
453				(header.w as i32 - px(240)).max(1) as u32,
454				px(24) as u32,
455			),
456			&self.config.title,
457			18.0,
458			Color::new(0.96, 0.96, 0.96, 1.0),
459		);
460		ui.begin_panel_with_layout(
461			"training-metric-layout",
462			PixelRect::new(
463				header.x + (header.w as i32 - px(194)).max(0),
464				header.y + px(8),
465				px(174) as u32,
466				px(30) as u32,
467			),
468			UiLayout {
469				padding: UiEdge::default(),
470				gap: 0.0,
471				..UiLayout::default()
472			},
473		);
474		ui.dropdown(
475			"metrics",
476			&["Auto", "1 column", "2 columns"],
477			&mut self.metric_columns,
478			UiDropdownConfig {
479				max_visible_items: 3,
480				..UiDropdownConfig::default()
481			},
482		);
483		ui.tooltip(
484			"Choose responsive, one-column, or two-column metric cards.",
485			UiTooltipConfig::default(),
486		);
487		ui.end_panel();
488		let summary = format!(
489			"{}   step {}   epoch {}   loss {:.6}   lr {:.6}",
490			state_name(snapshot.state),
491			snapshot.step,
492			snapshot.epoch,
493			f64::from(snapshot.loss),
494			f64::from(snapshot.learning_rate),
495		);
496		draw_label(
497			ui,
498			content_scale,
499			"training-summary",
500			PixelRect::new(
501				header.x + px(22),
502				header.y + px(40),
503				(header.w as i32 - px(44)).max(1) as u32,
504				px(20) as u32,
505			),
506			&summary,
507			13.0,
508			status_color,
509		);
510		let fps = if self.viewer_frame_ms > 0.0 {
511			1000.0 / self.viewer_frame_ms
512		} else {
513			0.0
514		};
515		let timing = format!(
516			"GPU {:.3} ms   wall {:.3} ms   viewer {:.1} FPS   Space pause/resume   C checkpoint   E evaluate   S stop",
517			snapshot.gpu_ms,
518			snapshot.wall_ms,
519			f64::from(fps),
520		);
521		draw_label(
522			ui,
523			content_scale,
524			"training-timing",
525			PixelRect::new(
526				header.x + px(22),
527				header.y + px(70),
528				(header.w as i32 - px(44)).max(1) as u32,
529				px(18) as u32,
530			),
531			&timing,
532			11.0,
533			Color::new(0.68, 0.68, 0.68, 1.0),
534		);
535
536		let preview = self
537			.preview
538			.lock()
539			.unwrap_or_else(std::sync::PoisonError::into_inner)
540			.current
541			.clone();
542		let preview_available = self.config.show_preview
543			&& preview
544				.as_ref()
545				.is_some_and(|frame| frame.texture.is_some());
546		let show_split_preview = width >= px(720) && preview_available;
547		let plot_count = self.series.len().min(self.config.max_metric_plots as usize) as u32;
548		let mut plot_top = header.y + header.h as i32 + gap;
549		let compact_tabs = width < px(720) && preview_available;
550		if compact_tabs {
551			let tabs = [
552				UiTabItem {
553					id: "metrics".into(),
554					label: "metrics".into(),
555					closable: false,
556					..UiTabItem::default()
557				},
558				UiTabItem {
559					id: "preview".into(),
560					label: "preview".into(),
561					closable: false,
562					..UiTabItem::default()
563				},
564			];
565			let mut tab_state = std::mem::take(&mut self.compact_tabs);
566			ui.tab_bar(
567				"training-compact-tabs",
568				PixelRect::new(margin, plot_top, (width - margin * 2) as u32, px(28) as u32),
569				&tabs,
570				&mut tab_state,
571			);
572			self.compact_tabs = tab_state;
573			plot_top += px(28) + gap;
574		}
575		let available_height = (height - plot_top - margin).max(px(80));
576		let mut plot_viewport = PixelRect::new(
577			margin,
578			plot_top,
579			(width - margin * 2) as u32,
580			available_height as u32,
581		);
582		let mut preview_panel = PixelRect::default();
583		if compact_tabs && self.compact_tabs.selected == 1 {
584			ui.rect(plot_viewport, Color::new(0.025, 0.025, 0.025, 1.0), 0.0)?;
585			ui.begin_panel("training-preview", plot_viewport);
586			if let Some(frame) = &preview
587				&& let Some(texture) = &frame.texture
588			{
589				ui.image_at(texture, plot_viewport)?;
590			}
591			ui.end_panel();
592			ui.rect_outline(plot_viewport, Color::new(1.0, 1.0, 1.0, 0.10), 1, 0.0)?;
593			return Ok(());
594		}
595		if show_split_preview {
596			let content = ui.split_pane(
597				"training-content-split",
598				plot_viewport,
599				&mut self.preview_split_ratio,
600				UiSplitConfig {
601					direction: UiDirection::Row,
602					handle_size: px(10) as f32,
603					minimum_first: px(300) as f32,
604					minimum_second: px(280) as f32,
605					..UiSplitConfig::default()
606				},
607			);
608			plot_viewport = content.first;
609			preview_panel = content.second;
610			ui.tooltip(
611				"Drag to resize metrics and preview. Use Left/Right for precise adjustment.",
612				UiTooltipConfig::default(),
613			);
614		}
615		let plot_area_width = plot_viewport.w as i32;
616		let columns = if self.metric_columns == 0 {
617			if plot_area_width >= px(760) { 2 } else { 1 }
618		} else {
619			self.metric_columns
620		};
621		let rows = ((plot_count as i32 + columns - 1) / columns).max(1);
622		let plot_height = if rows <= 1 {
623			available_height
624		} else {
625			(available_height * 3 / 7).clamp(px(128), px(240))
626		};
627		let content_height = if plot_count == 0 {
628			available_height
629		} else {
630			rows * plot_height + gap * (rows - 1)
631		};
632		let plots = ui.begin_scroll_panel(
633			"training-metrics",
634			plot_viewport,
635			content_height,
636			UiScrollConfig::default(),
637		);
638		let plot_width = ((plots.content.w as i32 - gap * (columns - 1)) / columns).max(1);
639		let visible_rows = ui.virtual_rows(rows, plot_height, gap, 0);
640		for row in visible_rows.first..visible_rows.one_past_last {
641			for column in 0..columns {
642				let index = (row * columns + column) as u32;
643				if index >= plot_count {
644					break;
645				}
646				let rect = PixelRect::new(
647					plots.content.x + column * (plot_width + gap),
648					plots.content.y + row * (plot_height + gap),
649					plot_width.max(1) as u32,
650					plot_height as u32,
651				);
652				let (color, latest, samples, name, expanded) = {
653					let series = &self.series[index as usize];
654					(
655						series.color,
656						series.values.last().copied().unwrap_or(0.0),
657						series.values.len(),
658						series.name.clone(),
659						series.expanded,
660					)
661				};
662				ui.rect(rect, Color::new(0.045, 0.045, 0.045, 1.0), 0.0)?;
663				let tree = ui.tree_row(
664					&name,
665					PixelRect::new(
666						rect.x + px(8),
667						rect.y + px(6),
668						(rect.w as i32 - px(16)).max(1) as u32,
669						px(26) as u32,
670					),
671					&name,
672					UiTreeRowConfig {
673						has_children: true,
674						open: expanded,
675						selected: self.selected_metric == index as i32,
676						..UiTreeRowConfig::new()
677					},
678				);
679				if tree.activated {
680					self.selected_metric = index as i32;
681				}
682				if tree.open_changed {
683					self.series[index as usize].expanded = tree.open;
684				}
685				ui.property_row(
686					&name,
687					PixelRect::new(
688						rect.x + px(8),
689						rect.y + px(34),
690						(rect.w as i32 - px(16)).max(1) as u32,
691						px(22) as u32,
692					),
693					"latest",
694					&format!("{latest:.6} · {samples} samples"),
695					crate::ui::UiPropertyRowConfig {
696						alternate: index & 1 != 0,
697						..Default::default()
698					},
699				);
700				let graph = PixelRect::new(
701					rect.x + px(8),
702					rect.y + px(62),
703					(rect.w as i32 - px(16)).max(1) as u32,
704					(rect.h as i32 - px(70)).max(1) as u32,
705				);
706				if expanded && samples > 0 {
707					ui.begin_panel(&name, graph);
708					ui.plot_line(
709						&self.series[index as usize].values,
710						graph,
711						&UiPlotConfig {
712							color,
713							auto_scale: true,
714							show_grid: true,
715							fill: index == 0,
716							..UiPlotConfig::default()
717						},
718					)?;
719					ui.end_panel();
720				}
721			}
722		}
723		ui.end_scroll_panel();
724		if show_split_preview {
725			ui.rect(preview_panel, Color::new(0.025, 0.025, 0.025, 1.0), 0.0)?;
726			ui.begin_panel("training-preview", preview_panel);
727			if let Some(frame) = &preview
728				&& let Some(texture) = &frame.texture
729			{
730				ui.image_at(texture, preview_panel)?;
731			}
732			ui.end_panel();
733			ui.rect_outline(preview_panel, Color::new(1.0, 1.0, 1.0, 0.10), 1, 0.0)?;
734		}
735		Ok(())
736	}
737
738	fn close(&mut self) -> Result<()> {
739		Ok(())
740	}
741}