1pub use crate::ml::types::{TrainingCommandResult, TrainingSessionConfig};
8use std::{
9 collections::VecDeque,
10 sync::{Arc, Condvar, Mutex, MutexGuard},
11 time::Duration,
12};
13
14use crate::{Error, ErrorKind, Result};
15
16use super::{Optimizer, TrainingSnapshot};
17
18type CommandHandler<'a> = Box<dyn FnMut() -> Result<()> + 'a>;
19type RebuildHandler<'a> = Box<dyn FnMut(&TrainingCommand) -> Result<()> + 'a>;
20type ValueGetter<'a> = Box<dyn Fn() -> TrainingValue + 'a>;
21type ValueSetter<'a> = Box<dyn FnMut(&TrainingValue) -> Result<()> + 'a>;
22
23#[derive(Clone, Copy, Debug, PartialEq, Eq)]
25pub enum TrainingState {
26 Running,
28 Paused,
30 Stopping,
32 Completed,
34 Failed,
36}
37
38impl TrainingState {
39 pub(crate) const fn is_terminal(self) -> bool {
40 matches!(self, Self::Completed | Self::Failed)
41 }
42}
43
44#[derive(Clone, Copy, Debug, PartialEq, Eq)]
46pub enum TrainingCommandKind {
47 Pause,
49 Resume,
51 Stop,
53 Checkpoint,
55 Evaluate,
57 SetParameter,
59 RequestRecapture,
61 RequestRebuild,
63}
64
65#[derive(Clone, Copy, Debug, PartialEq, Eq)]
67pub enum TrainingCommandDisposition {
68 Applied,
70 Rejected,
72}
73
74#[derive(Clone, Copy, Debug, PartialEq, Eq)]
76pub enum TrainingParameterClass {
77 Hot,
79 Recapture,
81 Rebuild,
83 Immutable,
85}
86
87#[derive(Clone, Copy, Debug, PartialEq, Eq)]
89pub enum TrainingValueKind {
90 Empty,
92 Boolean,
94 Integer,
96 Float,
98 String,
100}
101
102#[derive(Clone, Debug, Default, PartialEq)]
104pub enum TrainingValue {
105 #[default]
107 Empty,
108 Boolean(bool),
110 Integer(i64),
112 Float(f64),
114 String(String),
116}
117
118impl TrainingValue {
119 pub const fn kind(&self) -> TrainingValueKind {
121 match self {
122 Self::Empty => TrainingValueKind::Empty,
123 Self::Boolean(_) => TrainingValueKind::Boolean,
124 Self::Integer(_) => TrainingValueKind::Integer,
125 Self::Float(_) => TrainingValueKind::Float,
126 Self::String(_) => TrainingValueKind::String,
127 }
128 }
129
130 pub fn as_number(&self) -> Option<f64> {
132 match self {
133 Self::Integer(value) => Some(*value as f64),
134 Self::Float(value) => Some(*value),
135 Self::Empty | Self::Boolean(_) | Self::String(_) => None,
136 }
137 }
138}
139
140#[derive(Clone, Debug, PartialEq)]
142pub struct TrainingCommand {
143 pub sequence: u64,
145 pub expected_revision: u64,
147 pub kind: TrainingCommandKind,
149 pub parameter: String,
151 pub value: TrainingValue,
153}
154
155impl TrainingCommand {
156 fn new(kind: TrainingCommandKind, expected_revision: u64) -> Self {
157 Self {
158 sequence: 0,
159 expected_revision,
160 kind,
161 parameter: String::new(),
162 value: TrainingValue::Empty,
163 }
164 }
165}
166
167#[derive(Clone, Debug, PartialEq, Eq)]
169pub struct TrainingCommandError {
170 kind: ErrorKind,
171 message: String,
172}
173
174impl TrainingCommandError {
175 pub const fn kind(&self) -> ErrorKind {
177 self.kind
178 }
179
180 pub fn message(&self) -> &str {
182 &self.message
183 }
184
185 fn new(kind: ErrorKind, message: impl Into<String>) -> Self {
186 Self {
187 kind,
188 message: message.into(),
189 }
190 }
191
192 fn from_error(error: &Error) -> Self {
193 Self::new(error.kind(), error.message())
194 }
195}
196
197#[derive(Clone, Debug, PartialEq)]
199pub struct TrainingMetricSample {
200 pub name: String,
202 pub value: f64,
204 pub step: u64,
206}
207
208#[derive(Clone, Debug, PartialEq)]
210pub struct TrainingSessionSnapshot {
211 pub revision: u64,
213 pub state: TrainingState,
215 pub step: u64,
217 pub epoch: u64,
219 pub learning_rate: f32,
221 pub loss: f32,
223 pub gpu_ms: f64,
225 pub wall_ms: f64,
227 pub metrics: Vec<TrainingMetricSample>,
229}
230
231impl Default for TrainingSessionConfig {
232 fn default() -> Self {
233 Self {
234 command_capacity: 64,
235 result_capacity: 128,
236 snapshot_capacity: 256,
237 }
238 }
239}
240
241#[derive(Default)]
243pub struct TrainingSessionHandlers<'a> {
244 checkpoint: Option<CommandHandler<'a>>,
245 evaluate: Option<CommandHandler<'a>>,
246 rebuild: Option<RebuildHandler<'a>>,
247}
248
249impl<'a> TrainingSessionHandlers<'a> {
250 #[inline]
252 #[must_use]
253 pub fn new() -> Self {
254 Self::default()
255 }
256
257 pub fn checkpoint(mut self, handler: impl FnMut() -> Result<()> + 'a) -> Self {
259 self.checkpoint = Some(Box::new(handler));
260 self
261 }
262
263 pub fn evaluate(mut self, handler: impl FnMut() -> Result<()> + 'a) -> Self {
265 self.evaluate = Some(Box::new(handler));
266 self
267 }
268
269 pub fn rebuild(mut self, handler: impl FnMut(&TrainingCommand) -> Result<()> + 'a) -> Self {
271 self.rebuild = Some(Box::new(handler));
272 self
273 }
274}
275
276pub struct TrainingParameterDesc<'a> {
278 name: String,
279 parameter_class: TrainingParameterClass,
280 kind: TrainingValueKind,
281 minimum: Option<f64>,
282 maximum: Option<f64>,
283 get: ValueGetter<'a>,
284 set: Option<ValueSetter<'a>>,
285}
286
287impl<'a> TrainingParameterDesc<'a> {
288 pub fn mutable(
290 name: impl Into<String>,
291 parameter_class: TrainingParameterClass,
292 kind: TrainingValueKind,
293 get: impl Fn() -> TrainingValue + 'a,
294 set: impl FnMut(&TrainingValue) -> Result<()> + 'a,
295 ) -> Self {
296 Self {
297 name: name.into(),
298 parameter_class,
299 kind,
300 minimum: None,
301 maximum: None,
302 get: Box::new(get),
303 set: Some(Box::new(set)),
304 }
305 }
306
307 pub fn immutable(
309 name: impl Into<String>,
310 kind: TrainingValueKind,
311 get: impl Fn() -> TrainingValue + 'a,
312 ) -> Self {
313 Self {
314 name: name.into(),
315 parameter_class: TrainingParameterClass::Immutable,
316 kind,
317 minimum: None,
318 maximum: None,
319 get: Box::new(get),
320 set: None,
321 }
322 }
323
324 pub fn numeric_range(mut self, minimum: f64, maximum: f64) -> Self {
326 self.minimum = Some(minimum);
327 self.maximum = Some(maximum);
328 self
329 }
330}
331
332struct Shared {
333 state: Mutex<SessionState>,
334 wake: Condvar,
335}
336
337struct SessionState {
338 config: TrainingSessionConfig,
339 state: TrainingState,
340 revision: u64,
341 next_sequence: u64,
342 take_sequence: u64,
343 attached: bool,
344 commands: VecDeque<TrainingCommand>,
345 results: VecDeque<TrainingCommandResult>,
346 snapshots: VecDeque<TrainingSessionSnapshot>,
347 parameters: Vec<(String, TrainingValue)>,
348 pending_metrics: Vec<TrainingMetricSample>,
349}
350
351#[derive(Clone)]
356pub struct TrainingSession {
357 shared: Arc<Shared>,
358}
359
360impl TrainingSession {
361 pub fn new(mut config: TrainingSessionConfig) -> Self {
363 config.command_capacity = config.command_capacity.max(1);
364 config.result_capacity = config.result_capacity.max(1);
365 config.snapshot_capacity = config.snapshot_capacity.max(1);
366 Self {
367 shared: Arc::new(Shared {
368 state: Mutex::new(SessionState {
369 config,
370 state: TrainingState::Running,
371 revision: 0,
372 next_sequence: 1,
373 take_sequence: 0,
374 attached: false,
375 commands: VecDeque::new(),
376 results: VecDeque::new(),
377 snapshots: VecDeque::new(),
378 parameters: Vec::new(),
379 pending_metrics: Vec::new(),
380 }),
381 wake: Condvar::new(),
382 }),
383 }
384 }
385
386 pub fn enqueue(&self, mut command: TrainingCommand) -> Result<u64> {
392 let mut state = self.lock();
393 if state.commands.len() >= state.config.command_capacity {
394 return Err(Error::resource_exhausted(
395 "training session command queue is full",
396 ));
397 }
398 let sequence = state.next_sequence;
399 state.next_sequence = state
400 .next_sequence
401 .checked_add(1)
402 .ok_or_else(|| Error::resource_exhausted("training command sequence exhausted"))?;
403 command.sequence = sequence;
404 state.commands.push_back(command);
405 drop(state);
406 self.shared.wake.notify_all();
407 Ok(sequence)
408 }
409
410 pub fn pause(&self, expected_revision: u64) -> Result<u64> {
412 self.enqueue(TrainingCommand::new(
413 TrainingCommandKind::Pause,
414 expected_revision,
415 ))
416 }
417
418 pub fn resume(&self, expected_revision: u64) -> Result<u64> {
420 self.enqueue(TrainingCommand::new(
421 TrainingCommandKind::Resume,
422 expected_revision,
423 ))
424 }
425
426 pub fn stop(&self, expected_revision: u64) -> Result<u64> {
428 self.enqueue(TrainingCommand::new(
429 TrainingCommandKind::Stop,
430 expected_revision,
431 ))
432 }
433
434 pub fn checkpoint(&self, expected_revision: u64) -> Result<u64> {
436 self.enqueue(TrainingCommand::new(
437 TrainingCommandKind::Checkpoint,
438 expected_revision,
439 ))
440 }
441
442 pub fn evaluate(&self, expected_revision: u64) -> Result<u64> {
444 self.enqueue(TrainingCommand::new(
445 TrainingCommandKind::Evaluate,
446 expected_revision,
447 ))
448 }
449
450 pub fn set_parameter(
452 &self,
453 name: impl Into<String>,
454 value: TrainingValue,
455 expected_revision: u64,
456 ) -> Result<u64> {
457 let mut command = TrainingCommand::new(TrainingCommandKind::SetParameter, expected_revision);
458 command.parameter = name.into();
459 command.value = value;
460 self.enqueue(command)
461 }
462
463 pub fn request_recapture(&self, expected_revision: u64) -> Result<u64> {
465 self.enqueue(TrainingCommand::new(
466 TrainingCommandKind::RequestRecapture,
467 expected_revision,
468 ))
469 }
470
471 pub fn request_rebuild(&self, value: TrainingValue, expected_revision: u64) -> Result<u64> {
473 let mut command = TrainingCommand::new(TrainingCommandKind::RequestRebuild, expected_revision);
474 command.value = value;
475 self.enqueue(command)
476 }
477
478 pub fn publish_metric(&self, name: impl Into<String>, value: f64) {
480 let name = name.into();
481 if name.is_empty() || !value.is_finite() {
482 return;
483 }
484 let mut state = self.lock();
485 if let Some(metric) = state
486 .pending_metrics
487 .iter_mut()
488 .find(|metric| metric.name == name)
489 {
490 metric.value = value;
491 } else {
492 state.pending_metrics.push(TrainingMetricSample {
493 name,
494 value,
495 step: 0,
496 });
497 }
498 }
499
500 pub fn parameter(&self, name: &str) -> Option<TrainingValue> {
502 self
503 .lock()
504 .parameters
505 .iter()
506 .find_map(|(candidate, value)| (candidate == name).then(|| value.clone()))
507 }
508
509 pub fn state(&self) -> TrainingState {
511 self.lock().state
512 }
513
514 pub fn revision(&self) -> u64 {
516 self.lock().revision
517 }
518
519 pub fn current_snapshot(&self) -> TrainingSessionSnapshot {
521 let state = self.lock();
522 let mut snapshot = state
523 .snapshots
524 .back()
525 .cloned()
526 .unwrap_or_else(|| TrainingSessionSnapshot {
527 revision: state.revision,
528 state: state.state,
529 step: 0,
530 epoch: 0,
531 learning_rate: 0.0,
532 loss: 0.0,
533 gpu_ms: 0.0,
534 wall_ms: 0.0,
535 metrics: Vec::new(),
536 });
537 snapshot.revision = state.revision;
538 snapshot.state = state.state;
539 snapshot
540 }
541
542 pub fn latest_snapshot(&self) -> Option<TrainingSessionSnapshot> {
544 self.lock().snapshots.back().cloned()
545 }
546
547 pub fn results_after(&self, sequence: u64) -> Vec<TrainingCommandResult> {
549 self
550 .lock()
551 .results
552 .iter()
553 .filter(|result| result.sequence > sequence)
554 .cloned()
555 .collect()
556 }
557
558 pub fn take_results(&self) -> Vec<TrainingCommandResult> {
563 let mut state = self.lock();
564 let results = state
565 .results
566 .iter()
567 .filter(|result| result.sequence > state.take_sequence)
568 .cloned()
569 .collect::<Vec<_>>();
570 if let Some(result) = results.last() {
571 state.take_sequence = result.sequence;
572 }
573 results
574 }
575
576 fn lock(&self) -> MutexGuard<'_, SessionState> {
577 self
578 .shared
579 .state
580 .lock()
581 .unwrap_or_else(std::sync::PoisonError::into_inner)
582 }
583
584 pub(crate) fn attach(&self, snapshot: TrainingSessionSnapshot) -> Result<()> {
585 let mut state = self.lock();
586 if state.attached {
587 return Err(Error::already_exists(
588 "training session is already attached to an iterator",
589 ));
590 }
591 state.attached = true;
592 state.state = TrainingState::Running;
593 state.revision = state
594 .revision
595 .checked_add(1)
596 .ok_or_else(|| Error::resource_exhausted("training session revision exhausted"))?;
597 let mut snapshot = snapshot;
598 snapshot.revision = state.revision;
599 snapshot.state = state.state;
600 let capacity = state.config.snapshot_capacity;
601 push_bounded(&mut state.snapshots, snapshot, capacity);
602 drop(state);
603 self.shared.wake.notify_all();
604 Ok(())
605 }
606
607 pub(crate) fn drain_commands(&self) -> Vec<TrainingCommand> {
608 self.lock().commands.drain(..).collect()
609 }
610
611 pub(crate) fn command_context(&self) -> (TrainingState, u64) {
612 let state = self.lock();
613 (state.state, state.revision)
614 }
615
616 pub(crate) fn record_result(
617 &self,
618 command: &TrainingCommand,
619 transition: Option<TrainingState>,
620 error: Option<TrainingCommandError>,
621 ) {
622 let mut state = self.lock();
623 if error.is_none() {
624 if let Some(next) = transition {
625 state.state = next;
626 }
627 state.revision = state.revision.saturating_add(1);
628 }
629 let result = TrainingCommandResult {
630 sequence: command.sequence,
631 revision: state.revision,
632 disposition: if error.is_none() {
633 TrainingCommandDisposition::Applied
634 } else {
635 TrainingCommandDisposition::Rejected
636 },
637 state: state.state,
638 error,
639 };
640 let capacity = state.config.result_capacity;
641 push_bounded(&mut state.results, result, capacity);
642 drop(state);
643 self.shared.wake.notify_all();
644 }
645
646 pub(crate) fn cache_parameter(&self, name: String, value: TrainingValue) -> Result<()> {
647 let mut state = self.lock();
648 if state
649 .parameters
650 .iter()
651 .any(|(candidate, _)| candidate == &name)
652 {
653 return Err(Error::already_exists(format!(
654 "training session parameter already exists: {name}"
655 )));
656 }
657 state.parameters.push((name, value));
658 Ok(())
659 }
660
661 pub(crate) fn update_parameter(&self, name: &str, value: TrainingValue) {
662 if let Some((_, cached)) = self
663 .lock()
664 .parameters
665 .iter_mut()
666 .find(|(candidate, _)| candidate == name)
667 {
668 *cached = value;
669 }
670 }
671
672 pub(crate) fn publish(
673 &self,
674 snapshot: TrainingSnapshot,
675 learning_rate: f32,
676 terminal: Option<TrainingState>,
677 ) {
678 let mut state = self.lock();
679 if let Some(terminal) = terminal {
680 state.state = terminal;
681 state.revision = state.revision.saturating_add(1);
682 }
683 let metrics = state
684 .pending_metrics
685 .iter()
686 .cloned()
687 .map(|mut metric| {
688 metric.step = snapshot.step_count();
689 metric
690 })
691 .collect();
692 let live = TrainingSessionSnapshot {
693 revision: state.revision,
694 state: state.state,
695 step: snapshot.step_count(),
696 epoch: snapshot.epoch(),
697 learning_rate,
698 loss: snapshot.last_loss().unwrap_or(0.0),
699 gpu_ms: snapshot
700 .last_gpu_time()
701 .unwrap_or(Duration::ZERO)
702 .as_secs_f64()
703 * 1000.0,
704 wall_ms: snapshot.wall_ms_per_step(),
705 metrics,
706 };
707 let capacity = state.config.snapshot_capacity;
708 push_bounded(&mut state.snapshots, live, capacity);
709 drop(state);
710 self.shared.wake.notify_all();
711 }
712
713 pub(crate) fn wait_while_paused(&self) {
714 let mut state = self.lock();
715 while state.state == TrainingState::Paused && state.commands.is_empty() {
716 state = self
717 .shared
718 .wake
719 .wait(state)
720 .unwrap_or_else(std::sync::PoisonError::into_inner);
721 }
722 }
723}
724
725impl Default for TrainingSession {
726 fn default() -> Self {
727 Self::new(TrainingSessionConfig::default())
728 }
729}
730
731pub(crate) struct TrainingSessionAttachment<'a> {
732 pub(crate) session: TrainingSession,
733 handlers: TrainingSessionHandlers<'a>,
734 parameters: Vec<TrainingParameterDesc<'a>>,
735}
736
737#[derive(Default)]
738pub(crate) struct SessionActions {
739 pub(crate) stop: bool,
740 pub(crate) recapture: bool,
741}
742
743impl<'a> TrainingSessionAttachment<'a> {
744 pub(crate) fn new(session: TrainingSession, handlers: TrainingSessionHandlers<'a>) -> Self {
745 Self {
746 session,
747 handlers,
748 parameters: Vec::new(),
749 }
750 }
751
752 pub(crate) fn register_parameter(&mut self, desc: TrainingParameterDesc<'a>) -> Result<()> {
753 if desc.name.is_empty() || desc.minimum.zip(desc.maximum).is_some_and(|(a, b)| a > b) {
754 return Err(Error::invalid_argument(
755 "training parameter requires a name and an ordered numeric range",
756 ));
757 }
758 if desc.parameter_class != TrainingParameterClass::Immutable && desc.set.is_none() {
759 return Err(Error::invalid_argument(
760 "mutable training parameter requires a setter",
761 ));
762 }
763 let value = (desc.get)();
764 if value.kind() != desc.kind {
765 return Err(Error::invalid_argument(
766 "training parameter getter kind does not match its declaration",
767 ));
768 }
769 self.session.cache_parameter(desc.name.clone(), value)?;
770 self.parameters.push(desc);
771 Ok(())
772 }
773
774 pub(crate) fn poll(
775 &mut self,
776 optimizer: &mut dyn Optimizer,
777 can_recapture: bool,
778 ) -> SessionActions {
779 let mut actions = SessionActions::default();
780 for command in self.session.drain_commands() {
781 let (state, revision) = self.session.command_context();
782 let mut transition = None;
783 let error = if command.expected_revision != 0 && command.expected_revision != revision {
784 Some(TrainingCommandError::new(
785 ErrorKind::Aborted,
786 "training session command revision is stale",
787 ))
788 } else {
789 match command.kind {
790 TrainingCommandKind::Pause if state != TrainingState::Running => {
791 Some(TrainingCommandError::new(
792 ErrorKind::FailedPrecondition,
793 "pause requires a running training session",
794 ))
795 }
796 TrainingCommandKind::Pause => {
797 transition = Some(TrainingState::Paused);
798 None
799 }
800 TrainingCommandKind::Resume if state != TrainingState::Paused => {
801 Some(TrainingCommandError::new(
802 ErrorKind::FailedPrecondition,
803 "resume requires a paused training session",
804 ))
805 }
806 TrainingCommandKind::Resume => {
807 transition = Some(TrainingState::Running);
808 None
809 }
810 TrainingCommandKind::Stop if state.is_terminal() => Some(TrainingCommandError::new(
811 ErrorKind::FailedPrecondition,
812 "stop requires an active training session",
813 )),
814 TrainingCommandKind::Stop => {
815 actions.stop = true;
816 transition = Some(TrainingState::Stopping);
817 None
818 }
819 TrainingCommandKind::Checkpoint => {
820 invoke_handler(self.handlers.checkpoint.as_mut(), "checkpoint")
821 }
822 TrainingCommandKind::Evaluate => {
823 invoke_handler(self.handlers.evaluate.as_mut(), "evaluation")
824 }
825 TrainingCommandKind::SetParameter => self.set_parameter(&command, state, optimizer),
826 TrainingCommandKind::RequestRecapture if state != TrainingState::Paused => {
827 Some(TrainingCommandError::new(
828 ErrorKind::FailedPrecondition,
829 "program recapture requires a paused session",
830 ))
831 }
832 TrainingCommandKind::RequestRecapture if !can_recapture => {
833 Some(TrainingCommandError::new(
834 ErrorKind::FailedPrecondition,
835 "training program recapture requires automatic capture",
836 ))
837 }
838 TrainingCommandKind::RequestRecapture => {
839 actions.recapture = true;
840 None
841 }
842 TrainingCommandKind::RequestRebuild if state != TrainingState::Paused => {
843 Some(TrainingCommandError::new(
844 ErrorKind::FailedPrecondition,
845 "training rebuild requires a paused session",
846 ))
847 }
848 TrainingCommandKind::RequestRebuild => match self.handlers.rebuild.as_mut() {
849 Some(handler) => handler(&command)
850 .err()
851 .as_ref()
852 .map(TrainingCommandError::from_error),
853 None => Some(missing_handler("rebuild")),
854 },
855 }
856 };
857 self.session.record_result(&command, transition, error);
858 }
859 actions
860 }
861
862 fn set_parameter(
863 &mut self,
864 command: &TrainingCommand,
865 state: TrainingState,
866 optimizer: &mut dyn Optimizer,
867 ) -> Option<TrainingCommandError> {
868 if command.parameter == "learning_rate" {
869 let Some(value) = command.value.as_number() else {
870 return Some(kind_mismatch());
871 };
872 let result = if !value.is_finite() || value.abs() > f64::from(f32::MAX) {
873 Err(Error::out_of_range("learning rate is outside f32 range"))
874 } else {
875 optimizer.set_learning_rate(value as f32)
876 };
877 return match result {
878 Ok(()) => {
879 self.session.update_parameter(
880 "learning_rate",
881 TrainingValue::Float(f64::from(optimizer.learning_rate())),
882 );
883 None
884 }
885 Err(error) => Some(TrainingCommandError::from_error(&error)),
886 };
887 }
888 let Some(parameter) = self
889 .parameters
890 .iter_mut()
891 .find(|parameter| parameter.name == command.parameter)
892 else {
893 return Some(TrainingCommandError::new(
894 ErrorKind::NotFound,
895 format!("unknown training parameter: {}", command.parameter),
896 ));
897 };
898 if parameter.parameter_class == TrainingParameterClass::Immutable {
899 return Some(TrainingCommandError::new(
900 ErrorKind::FailedPrecondition,
901 format!("training parameter is immutable: {}", command.parameter),
902 ));
903 }
904 if parameter.parameter_class != TrainingParameterClass::Hot && state != TrainingState::Paused {
905 return Some(TrainingCommandError::new(
906 ErrorKind::FailedPrecondition,
907 "recapture/rebuild parameters require a paused session",
908 ));
909 }
910 if command.value.kind() != parameter.kind
911 && !(parameter.kind == TrainingValueKind::Float
912 && command.value.kind() == TrainingValueKind::Integer)
913 {
914 return Some(kind_mismatch());
915 }
916 if let Some(number) = command.value.as_number()
917 && (parameter.minimum.is_some_and(|minimum| number < minimum)
918 || parameter.maximum.is_some_and(|maximum| number > maximum))
919 {
920 return Some(TrainingCommandError::new(
921 ErrorKind::OutOfRange,
922 "training parameter value is outside its declared range",
923 ));
924 }
925 let Some(set) = parameter.set.as_mut() else {
926 return Some(TrainingCommandError::new(
927 ErrorKind::FailedPrecondition,
928 "training parameter does not admit mutation",
929 ));
930 };
931 if let Err(error) = set(&command.value) {
932 return Some(TrainingCommandError::from_error(&error));
933 }
934 self
935 .session
936 .update_parameter(¶meter.name, (parameter.get)());
937 None
938 }
939}
940
941fn invoke_handler(
942 handler: Option<&mut CommandHandler<'_>>,
943 name: &'static str,
944) -> Option<TrainingCommandError> {
945 match handler {
946 Some(handler) => handler()
947 .err()
948 .as_ref()
949 .map(TrainingCommandError::from_error),
950 None => Some(missing_handler(name)),
951 }
952}
953
954fn missing_handler(name: &'static str) -> TrainingCommandError {
955 TrainingCommandError::new(
956 ErrorKind::FailedPrecondition,
957 format!("training session has no {name} handler"),
958 )
959}
960
961fn kind_mismatch() -> TrainingCommandError {
962 TrainingCommandError::new(
963 ErrorKind::InvalidArgument,
964 "training parameter value kind does not match its declaration",
965 )
966}
967
968fn push_bounded<T>(queue: &mut VecDeque<T>, value: T, capacity: usize) {
969 while queue.len() >= capacity {
970 queue.pop_front();
971 }
972 queue.push_back(value);
973}