Ryan.K
Publish open-vocabulary bi-encoder, continual learning, and technical paper
4a54697 unverified Download src/main.rs from ElderRyan/lispm-llm: direct link, hf CLI and curl.
- Browser
- Download file 13.6 kB
-
https://huggingface.co/ElderRyan/lispm-llm/resolve/main/src/main.rs
- Command line
-
hf download hf://ElderRyan/lispm-llm/src/main.rs
-
curl -L -o main.rs https://huggingface.co/ElderRyan/lispm-llm/resolve/main/src/main.rs
13.6 kB
| //! Native training, proposal-only inference and isolated task evaluation. | |
| 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. | |
| struct Cli { | |
| /// Native CPU worker count; the measured reference uses two threads. | |
| threads: i32, | |
| /// One explicitly requested operation. | |
| operation: Operation, | |
| } | |
| /// Operations expose model training separately from inference and held-out evaluation. | |
| enum Operation { | |
| /// Print a validated action proposal or an explicit refusal. | |
| Infer { | |
| /// Directory containing config.json and model.safetensors. | |
| model: PathBuf, | |
| /// Optional open ActionCatalog JSON overriding a bi-encoder's default catalog. | |
| catalog: Option<PathBuf>, | |
| /// Optional active major-mode names (repeatable) for mode-scoped open actions. | |
| modes: Vec<String>, | |
| /// English request with JSON-quoted strings where needed. | |
| command: String, | |
| /// Proposal representation. | |
| format: OutputFormat, | |
| }, | |
| /// Train an open-vocabulary dual-tower bi-encoder from scratch. | |
| TrainBiencoder { | |
| /// Portable training/calibration JSON path. | |
| data: PathBuf, | |
| /// Optional open ActionCatalog JSON; defaults to the 48 core actions. | |
| catalog: Option<PathBuf>, | |
| /// New output directory; existing artifacts are never overwritten. | |
| output: PathBuf, | |
| /// Number of parameter updates. | |
| steps: u32, | |
| /// Seed for native tensor and Rust sampling random generators. | |
| seed: u64, | |
| }, | |
| /// Train from scratch or explicit initial weights; save an eligible checkpoint. | |
| Train { | |
| /// Portable training/calibration data; no evaluation file is read. | |
| data: PathBuf, | |
| /// New output directory; existing artifacts are never overwritten. | |
| output: PathBuf, | |
| /// Number of parameter updates. | |
| steps: u32, | |
| /// Seed for native tensor and Rust sampling random generators. | |
| seed: u64, | |
| /// Immutable model directory for optional fixed-vocabulary fine-tuning. | |
| init_model: Option<PathBuf>, | |
| /// Initial fine-tuning rate; finite, positive and strictly below 0.002. | |
| learning_rate: Option<f64>, | |
| }, | |
| /// Evaluate frozen cohorts without changing weights or confidence thresholds. | |
| Evaluate { | |
| /// Directory containing the model to evaluate. | |
| model: PathBuf, | |
| /// Previously frozen, overlap-filtered evaluation commands. | |
| data: PathBuf, | |
| /// New JSON report; an existing report is not overwritten. | |
| output: PathBuf, | |
| }, | |
| /// Extend frozen single-action cohorts with deterministic two-action regressions. | |
| PrepareBenchmark { | |
| /// Existing materialized single-action benchmark, kept unchanged. | |
| data: PathBuf, | |
| /// New expanded benchmark file, never overwriting an existing dataset. | |
| output: PathBuf, | |
| }, | |
| /// Measure real Emacs goal states in disposable buffers and temporary files. | |
| TaskBenchmark { | |
| /// Artifact under test; predictions cannot execute outside reviewed fixtures. | |
| model: PathBuf, | |
| /// Reviewed task instructions, typed oracle actions and fixture identities. | |
| data: PathBuf, | |
| /// Emacs executable used in a clean batch subprocess. | |
| emacs: PathBuf, | |
| /// Self-contained task execution and state-oracle implementation. | |
| runner: PathBuf, | |
| /// Maximum time per batch execution before the child is terminated. | |
| timeout_seconds: u64, | |
| /// New artifact-bound execution report. | |
| output: PathBuf, | |
| }, | |
| } | |
| /// Supported proposal serializations; both encode the same validated program. | |
| enum OutputFormat { | |
| /// Fixed Emacs Lisp rendering. | |
| Lisp, | |
| /// Typed action objects. | |
| Json, | |
| } | |
| /// Errors are converted to text only at this terminal-facing boundary. | |
| enum CliError { | |
| /// Thread counts must be positive before crossing the native API boundary. | |
| InvalidThreads, | |
| /// Artifact loading or model computation failed. | |
| Model( lispm_llm::model::ModelError), | |
| /// Input was refused or inference infrastructure failed. | |
| Inference( inference::InferenceError), | |
| /// Training inputs or checkpoint selection failed. | |
| Training( training::TrainingError), | |
| /// Frozen-corpus evaluation failed. | |
| Evaluation( evaluation::EvaluationError), | |
| /// Composition inputs do not satisfy the complete action-pair contract. | |
| Composition( composition::CompositionError), | |
| /// Open action catalog validation failed. | |
| Catalog( lispm_llm::catalog::CatalogError), | |
| /// Isolated Emacs execution or task evidence failed validation. | |
| TaskBenchmark( task_benchmark::TaskBenchmarkError), | |
| /// Output could not be serialized. | |
| Json( serde_json::Error), | |
| /// Report creation or terminal output failed. | |
| Io( 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<f64, String> { | |
| let rate = value.parse::<f64>().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 | |
| } | |
| } | |
| } | |
| mod tests { | |
| use super::*; | |
| /// Explicit warm-start arguments form one pair; scratch defaults stay absent. | |
| 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. | |
| 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)); | |
| } | |
| } | |