File size: 4,057 Bytes
2109241
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
//! Cooperative training checkpoints and typed progress at adapter boundaries.

use std::io::Write;
use std::path::PathBuf;

use serde::Serialize;

use super::TrainingError;
use crate::metrics::DecisionMetrics;

/// Serializable progress snapshots; terminal failures use `TrainingError`.
#[derive(Debug, Serialize)]
#[serde(tag = "phase", rename_all = "snake_case")]
pub enum TrainingProgress {
    /// Input validation begins before any model is allocated.
    Validating {
        /// Requested number of optimizer updates.
        steps: u32,
    },
    /// The corpus and runtime capability are ready for model initialization.
    Started {
        /// Total requested optimizer updates.
        steps: u32,
        /// Number of unique training examples.
        train_unique: usize,
        /// Number of unique calibration examples.
        calibration_unique: usize,
    },
    /// A completed optimizer update; emitted first, every 25 steps, and last.
    Step {
        /// Most recently completed update.
        step: u32,
        /// Total requested updates.
        steps: u32,
        /// Finite smoothed training objective for this batch.
        train_loss: f64,
    },
    /// Calibration-only checkpoint evidence, preserving CLI progress fields.
    Calibration {
        /// Checkpoint's completed optimizer update.
        step: u32,
        /// Total requested updates.
        steps: u32,
        /// Finite training objective immediately before calibration.
        train_loss: f64,
        /// Unsmoothed calibration objective.
        calibration_loss: f64,
        /// Raw class accuracy before runtime admission.
        calibration_accuracy: f64,
        /// Correct decisions minus weighted errors and refusals.
        decision_utility: i64,
        /// Whether all frozen incumbent bounds hold.
        eligible: bool,
        /// Immutable evidence for the original calibration prefix.
        original: Option<DecisionMetrics>,
        /// Immutable evidence for the added calibration suffix.
        added: Option<DecisionMetrics>,
    },
    /// Selection succeeded; stored weights will be restored and recalibrated.
    Selecting {
        /// Selected eligible update.
        selected_step: u32,
    },
    /// Final cancellation checkpoint immediately before artifact publication.
    Publishing {
        /// Selected eligible update.
        selected_step: u32,
    },
    /// Publication completed; the immutable destination is ready for evaluation.
    Completed {
        /// Selected eligible update.
        selected_step: u32,
        /// New artifact directory containing the trained checkpoint and report.
        output_dir: PathBuf,
    },
}

/// Caller-owned cancellation and reporting boundary for synchronous training.
///
/// Native workers may hold an atomic cancellation flag and a channel sender.
/// Progress must return promptly; it is invoked on the training worker, never
/// on the Emacs thread. Implementations must not access Lisp runtime values.
pub trait TrainingControl {
    /// Return whether cancellation has been requested; checked between kernels.
    fn is_cancelled(&self) -> bool;

    /// Receive one typed snapshot without retaining any model or corpus borrow.
    fn progress(&mut self, event: &TrainingProgress) -> Result<(), TrainingError>;
}

/// Observe cooperative cancellation without attempting to interrupt LibTorch.
pub(super) fn checkpoint(control: &(impl TrainingControl + ?Sized)) -> Result<(), TrainingError> {
    if control.is_cancelled() {
        Err(TrainingError::Cancelled)
    } else {
        Ok(())
    }
}

/// Existing CLI behavior emits progress as newline-delimited JSON on stderr.
pub(super) struct StderrControl;

impl TrainingControl for StderrControl {
    fn is_cancelled(&self) -> bool {
        false
    }

    fn progress(&mut self, event: &TrainingProgress) -> Result<(), TrainingError> {
        writeln!(
            std::io::stderr().lock(),
            "{}",
            serde_json::to_string(event)?
        )?;
        Ok(())
    }
}