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 pub fn checkpoint(mut self, handler: impl FnMut() -> Result<()> + 'a) -> Self {
252 self.checkpoint = Some(Box::new(handler));
253 self
254 }
255
256 pub fn evaluate(mut self, handler: impl FnMut() -> Result<()> + 'a) -> Self {
258 self.evaluate = Some(Box::new(handler));
259 self
260 }
261
262 pub fn rebuild(mut self, handler: impl FnMut(&TrainingCommand) -> Result<()> + 'a) -> Self {
264 self.rebuild = Some(Box::new(handler));
265 self
266 }
267}
268
269pub struct TrainingParameterDesc<'a> {
271 name: String,
272 parameter_class: TrainingParameterClass,
273 kind: TrainingValueKind,
274 minimum: Option<f64>,
275 maximum: Option<f64>,
276 get: ValueGetter<'a>,
277 set: Option<ValueSetter<'a>>,
278}
279
280impl<'a> TrainingParameterDesc<'a> {
281 pub fn mutable(
283 name: impl Into<String>,
284 parameter_class: TrainingParameterClass,
285 kind: TrainingValueKind,
286 get: impl Fn() -> TrainingValue + 'a,
287 set: impl FnMut(&TrainingValue) -> Result<()> + 'a,
288 ) -> Self {
289 Self {
290 name: name.into(),
291 parameter_class,
292 kind,
293 minimum: None,
294 maximum: None,
295 get: Box::new(get),
296 set: Some(Box::new(set)),
297 }
298 }
299
300 pub fn immutable(
302 name: impl Into<String>,
303 kind: TrainingValueKind,
304 get: impl Fn() -> TrainingValue + 'a,
305 ) -> Self {
306 Self {
307 name: name.into(),
308 parameter_class: TrainingParameterClass::Immutable,
309 kind,
310 minimum: None,
311 maximum: None,
312 get: Box::new(get),
313 set: None,
314 }
315 }
316
317 pub fn numeric_range(mut self, minimum: f64, maximum: f64) -> Self {
319 self.minimum = Some(minimum);
320 self.maximum = Some(maximum);
321 self
322 }
323}
324
325struct Shared {
326 state: Mutex<SessionState>,
327 wake: Condvar,
328}
329
330struct SessionState {
331 config: TrainingSessionConfig,
332 state: TrainingState,
333 revision: u64,
334 next_sequence: u64,
335 take_sequence: u64,
336 attached: bool,
337 commands: VecDeque<TrainingCommand>,
338 results: VecDeque<TrainingCommandResult>,
339 snapshots: VecDeque<TrainingSessionSnapshot>,
340 parameters: Vec<(String, TrainingValue)>,
341 pending_metrics: Vec<TrainingMetricSample>,
342}
343
344#[derive(Clone)]
349pub struct TrainingSession {
350 shared: Arc<Shared>,
351}
352
353impl TrainingSession {
354 pub fn new(mut config: TrainingSessionConfig) -> Self {
356 config.command_capacity = config.command_capacity.max(1);
357 config.result_capacity = config.result_capacity.max(1);
358 config.snapshot_capacity = config.snapshot_capacity.max(1);
359 Self {
360 shared: Arc::new(Shared {
361 state: Mutex::new(SessionState {
362 config,
363 state: TrainingState::Running,
364 revision: 0,
365 next_sequence: 1,
366 take_sequence: 0,
367 attached: false,
368 commands: VecDeque::new(),
369 results: VecDeque::new(),
370 snapshots: VecDeque::new(),
371 parameters: Vec::new(),
372 pending_metrics: Vec::new(),
373 }),
374 wake: Condvar::new(),
375 }),
376 }
377 }
378
379 pub fn enqueue(&self, mut command: TrainingCommand) -> Result<u64> {
385 let mut state = self.lock();
386 if state.commands.len() >= state.config.command_capacity {
387 return Err(Error::resource_exhausted(
388 "training session command queue is full",
389 ));
390 }
391 let sequence = state.next_sequence;
392 state.next_sequence = state
393 .next_sequence
394 .checked_add(1)
395 .ok_or_else(|| Error::resource_exhausted("training command sequence exhausted"))?;
396 command.sequence = sequence;
397 state.commands.push_back(command);
398 drop(state);
399 self.shared.wake.notify_all();
400 Ok(sequence)
401 }
402
403 pub fn pause(&self, expected_revision: u64) -> Result<u64> {
405 self.enqueue(TrainingCommand::new(
406 TrainingCommandKind::Pause,
407 expected_revision,
408 ))
409 }
410
411 pub fn resume(&self, expected_revision: u64) -> Result<u64> {
413 self.enqueue(TrainingCommand::new(
414 TrainingCommandKind::Resume,
415 expected_revision,
416 ))
417 }
418
419 pub fn stop(&self, expected_revision: u64) -> Result<u64> {
421 self.enqueue(TrainingCommand::new(
422 TrainingCommandKind::Stop,
423 expected_revision,
424 ))
425 }
426
427 pub fn checkpoint(&self, expected_revision: u64) -> Result<u64> {
429 self.enqueue(TrainingCommand::new(
430 TrainingCommandKind::Checkpoint,
431 expected_revision,
432 ))
433 }
434
435 pub fn evaluate(&self, expected_revision: u64) -> Result<u64> {
437 self.enqueue(TrainingCommand::new(
438 TrainingCommandKind::Evaluate,
439 expected_revision,
440 ))
441 }
442
443 pub fn set_parameter(
445 &self,
446 name: impl Into<String>,
447 value: TrainingValue,
448 expected_revision: u64,
449 ) -> Result<u64> {
450 let mut command = TrainingCommand::new(TrainingCommandKind::SetParameter, expected_revision);
451 command.parameter = name.into();
452 command.value = value;
453 self.enqueue(command)
454 }
455
456 pub fn request_recapture(&self, expected_revision: u64) -> Result<u64> {
458 self.enqueue(TrainingCommand::new(
459 TrainingCommandKind::RequestRecapture,
460 expected_revision,
461 ))
462 }
463
464 pub fn request_rebuild(&self, value: TrainingValue, expected_revision: u64) -> Result<u64> {
466 let mut command = TrainingCommand::new(TrainingCommandKind::RequestRebuild, expected_revision);
467 command.value = value;
468 self.enqueue(command)
469 }
470
471 pub fn publish_metric(&self, name: impl Into<String>, value: f64) {
473 let name = name.into();
474 if name.is_empty() || !value.is_finite() {
475 return;
476 }
477 let mut state = self.lock();
478 if let Some(metric) = state
479 .pending_metrics
480 .iter_mut()
481 .find(|metric| metric.name == name)
482 {
483 metric.value = value;
484 } else {
485 state.pending_metrics.push(TrainingMetricSample {
486 name,
487 value,
488 step: 0,
489 });
490 }
491 }
492
493 pub fn parameter(&self, name: &str) -> Option<TrainingValue> {
495 self
496 .lock()
497 .parameters
498 .iter()
499 .find_map(|(candidate, value)| (candidate == name).then(|| value.clone()))
500 }
501
502 pub fn state(&self) -> TrainingState {
504 self.lock().state
505 }
506
507 pub fn revision(&self) -> u64 {
509 self.lock().revision
510 }
511
512 pub fn current_snapshot(&self) -> TrainingSessionSnapshot {
514 let state = self.lock();
515 let mut snapshot = state
516 .snapshots
517 .back()
518 .cloned()
519 .unwrap_or_else(|| TrainingSessionSnapshot {
520 revision: state.revision,
521 state: state.state,
522 step: 0,
523 epoch: 0,
524 learning_rate: 0.0,
525 loss: 0.0,
526 gpu_ms: 0.0,
527 wall_ms: 0.0,
528 metrics: Vec::new(),
529 });
530 snapshot.revision = state.revision;
531 snapshot.state = state.state;
532 snapshot
533 }
534
535 pub fn latest_snapshot(&self) -> Option<TrainingSessionSnapshot> {
537 self.lock().snapshots.back().cloned()
538 }
539
540 pub fn results_after(&self, sequence: u64) -> Vec<TrainingCommandResult> {
542 self
543 .lock()
544 .results
545 .iter()
546 .filter(|result| result.sequence > sequence)
547 .cloned()
548 .collect()
549 }
550
551 pub fn take_results(&self) -> Vec<TrainingCommandResult> {
556 let mut state = self.lock();
557 let results = state
558 .results
559 .iter()
560 .filter(|result| result.sequence > state.take_sequence)
561 .cloned()
562 .collect::<Vec<_>>();
563 if let Some(result) = results.last() {
564 state.take_sequence = result.sequence;
565 }
566 results
567 }
568
569 fn lock(&self) -> MutexGuard<'_, SessionState> {
570 self
571 .shared
572 .state
573 .lock()
574 .unwrap_or_else(std::sync::PoisonError::into_inner)
575 }
576
577 pub(crate) fn attach(&self, snapshot: TrainingSessionSnapshot) -> Result<()> {
578 let mut state = self.lock();
579 if state.attached {
580 return Err(Error::already_exists(
581 "training session is already attached to an iterator",
582 ));
583 }
584 state.attached = true;
585 state.state = TrainingState::Running;
586 state.revision = state
587 .revision
588 .checked_add(1)
589 .ok_or_else(|| Error::resource_exhausted("training session revision exhausted"))?;
590 let mut snapshot = snapshot;
591 snapshot.revision = state.revision;
592 snapshot.state = state.state;
593 let capacity = state.config.snapshot_capacity;
594 push_bounded(&mut state.snapshots, snapshot, capacity);
595 drop(state);
596 self.shared.wake.notify_all();
597 Ok(())
598 }
599
600 pub(crate) fn drain_commands(&self) -> Vec<TrainingCommand> {
601 self.lock().commands.drain(..).collect()
602 }
603
604 pub(crate) fn command_context(&self) -> (TrainingState, u64) {
605 let state = self.lock();
606 (state.state, state.revision)
607 }
608
609 pub(crate) fn record_result(
610 &self,
611 command: &TrainingCommand,
612 transition: Option<TrainingState>,
613 error: Option<TrainingCommandError>,
614 ) {
615 let mut state = self.lock();
616 if error.is_none() {
617 if let Some(next) = transition {
618 state.state = next;
619 }
620 state.revision = state.revision.saturating_add(1);
621 }
622 let result = TrainingCommandResult {
623 sequence: command.sequence,
624 revision: state.revision,
625 disposition: if error.is_none() {
626 TrainingCommandDisposition::Applied
627 } else {
628 TrainingCommandDisposition::Rejected
629 },
630 state: state.state,
631 error,
632 };
633 let capacity = state.config.result_capacity;
634 push_bounded(&mut state.results, result, capacity);
635 drop(state);
636 self.shared.wake.notify_all();
637 }
638
639 pub(crate) fn cache_parameter(&self, name: String, value: TrainingValue) -> Result<()> {
640 let mut state = self.lock();
641 if state
642 .parameters
643 .iter()
644 .any(|(candidate, _)| candidate == &name)
645 {
646 return Err(Error::already_exists(format!(
647 "training session parameter already exists: {name}"
648 )));
649 }
650 state.parameters.push((name, value));
651 Ok(())
652 }
653
654 pub(crate) fn update_parameter(&self, name: &str, value: TrainingValue) {
655 if let Some((_, cached)) = self
656 .lock()
657 .parameters
658 .iter_mut()
659 .find(|(candidate, _)| candidate == name)
660 {
661 *cached = value;
662 }
663 }
664
665 pub(crate) fn publish(
666 &self,
667 snapshot: TrainingSnapshot,
668 learning_rate: f32,
669 terminal: Option<TrainingState>,
670 ) {
671 let mut state = self.lock();
672 if let Some(terminal) = terminal {
673 state.state = terminal;
674 state.revision = state.revision.saturating_add(1);
675 }
676 let metrics = state
677 .pending_metrics
678 .iter()
679 .cloned()
680 .map(|mut metric| {
681 metric.step = snapshot.step_count();
682 metric
683 })
684 .collect();
685 let live = TrainingSessionSnapshot {
686 revision: state.revision,
687 state: state.state,
688 step: snapshot.step_count(),
689 epoch: snapshot.epoch(),
690 learning_rate,
691 loss: snapshot.last_loss().unwrap_or(0.0),
692 gpu_ms: snapshot
693 .last_gpu_time()
694 .unwrap_or(Duration::ZERO)
695 .as_secs_f64()
696 * 1000.0,
697 wall_ms: snapshot.wall_ms_per_step(),
698 metrics,
699 };
700 let capacity = state.config.snapshot_capacity;
701 push_bounded(&mut state.snapshots, live, capacity);
702 drop(state);
703 self.shared.wake.notify_all();
704 }
705
706 pub(crate) fn wait_while_paused(&self) {
707 let mut state = self.lock();
708 while state.state == TrainingState::Paused && state.commands.is_empty() {
709 state = self
710 .shared
711 .wake
712 .wait(state)
713 .unwrap_or_else(std::sync::PoisonError::into_inner);
714 }
715 }
716}
717
718impl Default for TrainingSession {
719 fn default() -> Self {
720 Self::new(TrainingSessionConfig::default())
721 }
722}
723
724pub(crate) struct TrainingSessionAttachment<'a> {
725 pub(crate) session: TrainingSession,
726 handlers: TrainingSessionHandlers<'a>,
727 parameters: Vec<TrainingParameterDesc<'a>>,
728}
729
730#[derive(Default)]
731pub(crate) struct SessionActions {
732 pub(crate) stop: bool,
733 pub(crate) recapture: bool,
734}
735
736impl<'a> TrainingSessionAttachment<'a> {
737 pub(crate) fn new(session: TrainingSession, handlers: TrainingSessionHandlers<'a>) -> Self {
738 Self {
739 session,
740 handlers,
741 parameters: Vec::new(),
742 }
743 }
744
745 pub(crate) fn register_parameter(&mut self, desc: TrainingParameterDesc<'a>) -> Result<()> {
746 if desc.name.is_empty() || desc.minimum.zip(desc.maximum).is_some_and(|(a, b)| a > b) {
747 return Err(Error::invalid_argument(
748 "training parameter requires a name and an ordered numeric range",
749 ));
750 }
751 if desc.parameter_class != TrainingParameterClass::Immutable && desc.set.is_none() {
752 return Err(Error::invalid_argument(
753 "mutable training parameter requires a setter",
754 ));
755 }
756 let value = (desc.get)();
757 if value.kind() != desc.kind {
758 return Err(Error::invalid_argument(
759 "training parameter getter kind does not match its declaration",
760 ));
761 }
762 self.session.cache_parameter(desc.name.clone(), value)?;
763 self.parameters.push(desc);
764 Ok(())
765 }
766
767 pub(crate) fn poll(
768 &mut self,
769 optimizer: &mut dyn Optimizer,
770 can_recapture: bool,
771 ) -> SessionActions {
772 let mut actions = SessionActions::default();
773 for command in self.session.drain_commands() {
774 let (state, revision) = self.session.command_context();
775 let mut transition = None;
776 let error = if command.expected_revision != 0 && command.expected_revision != revision {
777 Some(TrainingCommandError::new(
778 ErrorKind::Aborted,
779 "training session command revision is stale",
780 ))
781 } else {
782 match command.kind {
783 TrainingCommandKind::Pause if state != TrainingState::Running => {
784 Some(TrainingCommandError::new(
785 ErrorKind::FailedPrecondition,
786 "pause requires a running training session",
787 ))
788 }
789 TrainingCommandKind::Pause => {
790 transition = Some(TrainingState::Paused);
791 None
792 }
793 TrainingCommandKind::Resume if state != TrainingState::Paused => {
794 Some(TrainingCommandError::new(
795 ErrorKind::FailedPrecondition,
796 "resume requires a paused training session",
797 ))
798 }
799 TrainingCommandKind::Resume => {
800 transition = Some(TrainingState::Running);
801 None
802 }
803 TrainingCommandKind::Stop if state.is_terminal() => Some(TrainingCommandError::new(
804 ErrorKind::FailedPrecondition,
805 "stop requires an active training session",
806 )),
807 TrainingCommandKind::Stop => {
808 actions.stop = true;
809 transition = Some(TrainingState::Stopping);
810 None
811 }
812 TrainingCommandKind::Checkpoint => {
813 invoke_handler(self.handlers.checkpoint.as_mut(), "checkpoint")
814 }
815 TrainingCommandKind::Evaluate => {
816 invoke_handler(self.handlers.evaluate.as_mut(), "evaluation")
817 }
818 TrainingCommandKind::SetParameter => self.set_parameter(&command, state, optimizer),
819 TrainingCommandKind::RequestRecapture if state != TrainingState::Paused => {
820 Some(TrainingCommandError::new(
821 ErrorKind::FailedPrecondition,
822 "program recapture requires a paused session",
823 ))
824 }
825 TrainingCommandKind::RequestRecapture if !can_recapture => {
826 Some(TrainingCommandError::new(
827 ErrorKind::FailedPrecondition,
828 "training program recapture requires automatic capture",
829 ))
830 }
831 TrainingCommandKind::RequestRecapture => {
832 actions.recapture = true;
833 None
834 }
835 TrainingCommandKind::RequestRebuild if state != TrainingState::Paused => {
836 Some(TrainingCommandError::new(
837 ErrorKind::FailedPrecondition,
838 "training rebuild requires a paused session",
839 ))
840 }
841 TrainingCommandKind::RequestRebuild => match self.handlers.rebuild.as_mut() {
842 Some(handler) => handler(&command)
843 .err()
844 .as_ref()
845 .map(TrainingCommandError::from_error),
846 None => Some(missing_handler("rebuild")),
847 },
848 }
849 };
850 self.session.record_result(&command, transition, error);
851 }
852 actions
853 }
854
855 fn set_parameter(
856 &mut self,
857 command: &TrainingCommand,
858 state: TrainingState,
859 optimizer: &mut dyn Optimizer,
860 ) -> Option<TrainingCommandError> {
861 if command.parameter == "learning_rate" {
862 let Some(value) = command.value.as_number() else {
863 return Some(kind_mismatch());
864 };
865 let result = if !value.is_finite() || value.abs() > f64::from(f32::MAX) {
866 Err(Error::out_of_range("learning rate is outside f32 range"))
867 } else {
868 optimizer.set_learning_rate(value as f32)
869 };
870 return match result {
871 Ok(()) => {
872 self.session.update_parameter(
873 "learning_rate",
874 TrainingValue::Float(f64::from(optimizer.learning_rate())),
875 );
876 None
877 }
878 Err(error) => Some(TrainingCommandError::from_error(&error)),
879 };
880 }
881 let Some(parameter) = self
882 .parameters
883 .iter_mut()
884 .find(|parameter| parameter.name == command.parameter)
885 else {
886 return Some(TrainingCommandError::new(
887 ErrorKind::NotFound,
888 format!("unknown training parameter: {}", command.parameter),
889 ));
890 };
891 if parameter.parameter_class == TrainingParameterClass::Immutable {
892 return Some(TrainingCommandError::new(
893 ErrorKind::FailedPrecondition,
894 format!("training parameter is immutable: {}", command.parameter),
895 ));
896 }
897 if parameter.parameter_class != TrainingParameterClass::Hot && state != TrainingState::Paused {
898 return Some(TrainingCommandError::new(
899 ErrorKind::FailedPrecondition,
900 "recapture/rebuild parameters require a paused session",
901 ));
902 }
903 if command.value.kind() != parameter.kind
904 && !(parameter.kind == TrainingValueKind::Float
905 && command.value.kind() == TrainingValueKind::Integer)
906 {
907 return Some(kind_mismatch());
908 }
909 if let Some(number) = command.value.as_number()
910 && (parameter.minimum.is_some_and(|minimum| number < minimum)
911 || parameter.maximum.is_some_and(|maximum| number > maximum))
912 {
913 return Some(TrainingCommandError::new(
914 ErrorKind::OutOfRange,
915 "training parameter value is outside its declared range",
916 ));
917 }
918 let Some(set) = parameter.set.as_mut() else {
919 return Some(TrainingCommandError::new(
920 ErrorKind::FailedPrecondition,
921 "training parameter does not admit mutation",
922 ));
923 };
924 if let Err(error) = set(&command.value) {
925 return Some(TrainingCommandError::from_error(&error));
926 }
927 self
928 .session
929 .update_parameter(¶meter.name, (parameter.get)());
930 None
931 }
932}
933
934fn invoke_handler(
935 handler: Option<&mut CommandHandler<'_>>,
936 name: &'static str,
937) -> Option<TrainingCommandError> {
938 match handler {
939 Some(handler) => handler()
940 .err()
941 .as_ref()
942 .map(TrainingCommandError::from_error),
943 None => Some(missing_handler(name)),
944 }
945}
946
947fn missing_handler(name: &'static str) -> TrainingCommandError {
948 TrainingCommandError::new(
949 ErrorKind::FailedPrecondition,
950 format!("training session has no {name} handler"),
951 )
952}
953
954fn kind_mismatch() -> TrainingCommandError {
955 TrainingCommandError::new(
956 ErrorKind::InvalidArgument,
957 "training parameter value kind does not match its declaration",
958 )
959}
960
961fn push_bounded<T>(queue: &mut VecDeque<T>, value: T, capacity: usize) {
962 while queue.len() >= capacity {
963 queue.pop_front();
964 }
965 queue.push_back(value);
966}