//! Native training, proposal-only inference and isolated task evaluation. #![deny(missing_docs)] use clap::{Parser, Subcommand, ValueEnum}; use lispm_llm::{ biencoder, catalog::ActionCatalog, composition, engine::ModelEngine, evaluation, inference, task_benchmark, training, }; use std::{fs::OpenOptions, io::Write, path::PathBuf, process::ExitCode}; use thiserror::Error; /// Explicit side-effect entry point; only task-benchmark executes isolated fixture actions. #[derive(Parser)] #[command( name = "lispm-llm", about = "Train and run the bounded Emacs command model in Rust" )] struct Cli { /// Native CPU worker count; the measured reference uses two threads. #[arg(long, global = true, default_value_t = 2)] threads: i32, /// One explicitly requested operation. #[command(subcommand)] operation: Operation, } /// Operations expose model training separately from inference and held-out evaluation. #[derive(Subcommand)] enum Operation { /// Print a validated action proposal or an explicit refusal. Infer { /// Directory containing config.json and model.safetensors. #[arg(long, default_value = ".")] model: PathBuf, /// Optional open ActionCatalog JSON overriding a bi-encoder's default catalog. #[arg(long)] catalog: Option, /// Optional active major-mode names (repeatable) for mode-scoped open actions. #[arg(long = "mode")] modes: Vec, /// English request with JSON-quoted strings where needed. command: String, /// Proposal representation. #[arg(long, value_enum, default_value = "lisp")] format: OutputFormat, }, /// Train an open-vocabulary dual-tower bi-encoder from scratch. TrainBiencoder { /// Portable training/calibration JSON path. #[arg(long, default_value = "data/refined-semantic-training.json")] data: PathBuf, /// Optional open ActionCatalog JSON; defaults to the 48 core actions. #[arg(long)] catalog: Option, /// New output directory; existing artifacts are never overwritten. #[arg(long)] output: PathBuf, /// Number of parameter updates. #[arg(long, default_value_t = 2400)] steps: u32, /// Seed for native tensor and Rust sampling random generators. #[arg(long, default_value_t = 42)] seed: u64, }, /// Train from scratch or explicit initial weights; save an eligible checkpoint. Train { /// Portable training/calibration data; no evaluation file is read. #[arg(long, default_value = "data/training.json")] data: PathBuf, /// New output directory; existing artifacts are never overwritten. #[arg(long)] output: PathBuf, /// Number of parameter updates. #[arg(long, default_value_t = 3200)] steps: u32, /// Seed for native tensor and Rust sampling random generators. #[arg(long, default_value_t = 42)] seed: u64, /// Immutable model directory for optional fixed-vocabulary fine-tuning. #[arg(long, requires = "learning_rate")] init_model: Option, /// Initial fine-tuning rate; finite, positive and strictly below 0.002. #[arg(long, requires = "init_model", value_parser = parse_warm_learning_rate)] learning_rate: Option, }, /// Evaluate frozen cohorts without changing weights or confidence thresholds. Evaluate { /// Directory containing the model to evaluate. #[arg(long, default_value = ".")] model: PathBuf, /// Previously frozen, overlap-filtered evaluation commands. #[arg(long, default_value = "data/benchmark.json")] data: PathBuf, /// New JSON report; an existing report is not overwritten. #[arg(long)] output: PathBuf, }, /// Extend frozen single-action cohorts with deterministic two-action regressions. PrepareBenchmark { /// Existing materialized single-action benchmark, kept unchanged. #[arg(long, default_value = "data/evaluation.json")] data: PathBuf, /// New expanded benchmark file, never overwriting an existing dataset. #[arg(long)] output: PathBuf, }, /// Measure real Emacs goal states in disposable buffers and temporary files. TaskBenchmark { /// Artifact under test; predictions cannot execute outside reviewed fixtures. #[arg(long, default_value = ".")] model: PathBuf, /// Reviewed task instructions, typed oracle actions and fixture identities. #[arg(long, default_value = "data/emacs-tasks.json")] data: PathBuf, /// Emacs executable used in a clean batch subprocess. #[arg(long, default_value = "emacs")] emacs: PathBuf, /// Self-contained task execution and state-oracle implementation. #[arg(long, default_value = "emacs/lispm-llm-benchmark.el")] runner: PathBuf, /// Maximum time per batch execution before the child is terminated. #[arg(long, default_value_t = 60)] timeout_seconds: u64, /// New artifact-bound execution report. #[arg(long)] output: PathBuf, }, } /// Supported proposal serializations; both encode the same validated program. #[derive(Clone, Copy, ValueEnum)] enum OutputFormat { /// Fixed Emacs Lisp rendering. Lisp, /// Typed action objects. Json, } /// Errors are converted to text only at this terminal-facing boundary. #[derive(Debug, Error)] enum CliError { /// Thread counts must be positive before crossing the native API boundary. #[error("--threads must be positive")] InvalidThreads, /// Artifact loading or model computation failed. #[error(transparent)] Model(#[from] lispm_llm::model::ModelError), /// Input was refused or inference infrastructure failed. #[error(transparent)] Inference(#[from] inference::InferenceError), /// Training inputs or checkpoint selection failed. #[error(transparent)] Training(#[from] training::TrainingError), /// Frozen-corpus evaluation failed. #[error(transparent)] Evaluation(#[from] evaluation::EvaluationError), /// Composition inputs do not satisfy the complete action-pair contract. #[error(transparent)] Composition(#[from] composition::CompositionError), /// Open action catalog validation failed. #[error(transparent)] Catalog(#[from] lispm_llm::catalog::CatalogError), /// Isolated Emacs execution or task evidence failed validation. #[error(transparent)] TaskBenchmark(#[from] task_benchmark::TaskBenchmarkError), /// Output could not be serialized. #[error(transparent)] Json(#[from] serde_json::Error), /// Report creation or terminal output failed. #[error(transparent)] Io(#[from] std::io::Error), } /// Execute one parsed operation with explicit CPU configuration and output effects. fn run(cli: Cli) -> Result<(), CliError> { if cli.threads <= 0 { return Err(CliError::InvalidThreads); } tch::set_num_threads(cli.threads); let text = match cli.operation { Operation::Infer { model, catalog, modes, command, format, } => { let mut engine = ModelEngine::load(model)?; if let Some(cat_path) = catalog { let loaded = ActionCatalog::from_bytes(&std::fs::read(cat_path)?)?; engine.set_catalog(&loaded)?; } let active_modes = (!modes.is_empty()).then_some(modes.as_slice()); let program = engine.predict(&command, None, active_modes)?; match format { OutputFormat::Lisp => program.to_lisp(), OutputFormat::Json => serde_json::to_string(&program.to_json())?, } } Operation::TrainBiencoder { data, catalog, output, steps, seed, } => { let action_catalog = match catalog { Some(path) => ActionCatalog::from_bytes(&std::fs::read(path)?)?, None => ActionCatalog::builtin(), }; let report = biencoder::train_biencoder(&biencoder::BiEncoderTrainOptions { data_path: data, output_dir: output, catalog: action_catalog, steps, seed, threads: cli.threads, })?; serde_json::to_string_pretty(&report)? } Operation::Train { data, output, steps, seed, init_model, learning_rate, } => { let warm_start = match (init_model, learning_rate) { (Some(model_dir), Some(learning_rate)) => Some(training::WarmStartOptions { model_dir, learning_rate, }), (None, None) => None, _ => { return Err(training::TrainingError::InvalidData( "warm-start source and learning rate must be supplied together", ) .into()); } }; let report = training::train(&training::TrainOptions { data_path: data, output_dir: output, steps, seed, threads: cli.threads, warm_start, })?; serde_json::to_string_pretty(&report)? } Operation::Evaluate { model, data, output, } => { let report = evaluation::evaluate(&model, &data)?; let encoded = serde_json::to_vec_pretty(&report)?; let mut file = OpenOptions::new() .create_new(true) .write(true) .open(&output)?; file.write_all(&encoded)?; file.write_all(b"\n")?; format!("Evaluation written to {}", output.display()) } Operation::PrepareBenchmark { data, output } => { let encoded = composition::extend(&std::fs::read(data)?)?; write_report(&output, &encoded)?; format!("Expanded benchmark written to {}", output.display()) } Operation::TaskBenchmark { model, data, emacs, runner, timeout_seconds, output, } => { let options = task_benchmark::RunnerOptions { emacs, runner, timeout_seconds, }; let report = task_benchmark::evaluate( &model, &data, &options, &std::sync::atomic::AtomicBool::new(false), &mut |_| {}, )?; write_report(&output, &serde_json::to_vec_pretty(&report)?)?; format!("Emacs task benchmark written to {}", output.display()) } }; writeln!(std::io::stdout().lock(), "{text}")?; Ok(()) } /// Validate warm-start CLI rates before any model, data or runtime side effect. fn parse_warm_learning_rate(value: &str) -> Result { let rate = value.parse::().map_err(|error| error.to_string())?; if !rate.is_finite() || rate <= 0.0 || rate >= 0.002 || rate / 20.0 == 0.0 { return Err( "learning rate must be finite, positive and below 0.002 with a positive final rate" .into(), ); } Ok(rate) } /// Publish a complete JSON artifact only to a caller-selected fresh output path. fn write_report(path: &std::path::Path, bytes: &[u8]) -> Result<(), CliError> { let mut file = OpenOptions::new().create_new(true).write(true).open(path)?; file.write_all(bytes)?; file.write_all(b"\n")?; Ok(()) } /// Report recoverable failures without a panic or an executable fallback action. fn main() -> ExitCode { match run(Cli::parse()) { Ok(()) => ExitCode::SUCCESS, Err(error) => { let _ = writeln!(std::io::stderr().lock(), "error: {error}"); ExitCode::FAILURE } } } #[cfg(test)] mod tests { use super::*; /// Explicit warm-start arguments form one pair; scratch defaults stay absent. #[test] fn warm_start_arguments_require_each_other() { let base = ["lispm-llm", "train", "--output", "unused"]; assert!(Cli::try_parse_from(base).is_ok()); assert!(Cli::try_parse_from(base.into_iter().chain(["--init-model", "source"])).is_err()); assert!( Cli::try_parse_from(base.into_iter().chain(["--learning-rate", "0.0002"])).is_err() ); assert!( Cli::try_parse_from(base.into_iter().chain([ "--init-model", "source", "--learning-rate", "0.0002", ])) .is_ok() ); } /// Invalid or non-conservative rates fail parsing before training starts. #[test] fn warm_start_rate_rejects_nonfinite_nonpositive_and_scratch_rates() { for rate in [ "NaN", "inf", "-inf", "0", "-0.0001", "0.002", "0.01", "5e-324", ] { assert!(parse_warm_learning_rate(rate).is_err()); } assert_eq!(parse_warm_learning_rate("0.0002"), Ok(0.0002)); } }