Download src/training/tests.rs from ElderRyan/lispm-llm: direct link, hf CLI and curl.
- Browser
- Download file 20.6 kB
-
https://huggingface.co/ElderRyan/lispm-llm/resolve/main/src/training/tests.rs
- Command line
-
hf download hf://ElderRyan/lispm-llm/src/training/tests.rs
-
curl -L -o tests.rs https://huggingface.co/ElderRyan/lispm-llm/resolve/main/src/training/tests.rs
20.6 kB
| //! Regression witnesses for training invariants and lifecycle control. | |
| use super::data::sha256; | |
| use super::*; | |
| /// Observer that can cancel at a named lifecycle phase without any stderr IO. | |
| struct RecordingControl { | |
| /// Phase whose delivery requests cancellation, or none to keep running. | |
| cancel_on: Option<&'static str>, | |
| /// Current cooperative cancellation request. | |
| cancelled: bool, | |
| /// Ordered public JSON progress snapshots. | |
| events: Vec<Value>, | |
| } | |
| impl TrainingControl for RecordingControl { | |
| fn is_cancelled(&self) -> bool { | |
| self.cancelled | |
| } | |
| fn progress(&mut self, event: &TrainingProgress) -> Result<(), TrainingError> { | |
| let value = serde_json::to_value(event)?; | |
| if value.get("phase").and_then(Value::as_str) == self.cancel_on { | |
| self.cancelled = true; | |
| } | |
| self.events.push(value); | |
| Ok(()) | |
| } | |
| } | |
| /// Resolve the checked-in training fixture independently of the test directory. | |
| fn training_fixture() -> PathBuf { | |
| PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("data/training.json") | |
| } | |
| fn row_digest_matches_python_default_spacing() -> Result<(), TrainingError> { | |
| let rows = vec![ | |
| ("save buffer".into(), "save-buffer".into()), | |
| ("café NAME".into(), "reject".into()), | |
| ]; | |
| let serialized = "[[\"save buffer\", \"save-buffer\"], [\"café NAME\", \"reject\"]]"; | |
| assert_eq!(rows_sha256(&rows)?, sha256(serialized.as_bytes())); | |
| assert_ne!(rows_sha256(&rows)?, sha256(&serde_json::to_vec(&rows)?)); | |
| Ok(()) | |
| } | |
| fn scheduler_preserves_endpoints_and_descends() -> Result<(), TrainingError> { | |
| let rates = LearningRates::for_options(&TrainOptions::default())?; | |
| assert!((learning_rate(0, 3200, rates)? - 0.002).abs() < 1e-15); | |
| assert!((learning_rate(3200, 3200, rates)? - 0.0001).abs() < 1e-15); | |
| let mut previous = learning_rate(0, 3200, rates)?; | |
| for step in 1..=3200 { | |
| let current = learning_rate(step, 3200, rates)?; | |
| assert!(current <= previous); | |
| previous = current; | |
| } | |
| assert!(learning_rate(1, 0, rates).is_err()); | |
| Ok(()) | |
| } | |
| fn sampling_balances_classes_short_rows_and_hard_examples() -> Result<(), TrainingError> { | |
| let pools = SamplingPools { | |
| general: vec![vec![0], vec![2], vec![3]], | |
| short: vec![vec![1], vec![], vec![]], | |
| hard_supported: vec![4], | |
| hard_rejected: vec![5], | |
| reject_index: 2, | |
| }; | |
| let rows = pools.sample(&mut ChaCha8Rng::seed_from_u64(42))?; | |
| let counts: Vec<usize> = (0..6) | |
| .map(|value| rows.iter().filter(|&&row| row == value).count()) | |
| .collect(); | |
| assert_eq!(counts, vec![4, 2, 6, 64, 32, 32]); | |
| let mut output = Vec::new(); | |
| assert!(sample_rows(&[], 1, &mut ChaCha8Rng::seed_from_u64(42), &mut output).is_err()); | |
| Ok(()) | |
| } | |
| fn calibration_admission_enforces_argument_type_and_single_clause() { | |
| assert!(admissible("save this buffer", "save-buffer")); | |
| assert!(!admissible("save \"other\"", "save-buffer")); | |
| assert!(!admissible("save this buffer then undo", "save-buffer")); | |
| assert!(!admissible( | |
| "open \"javascript:alert(1)\" in browser", | |
| "lispm-browser-open-url" | |
| )); | |
| assert!(admissible( | |
| "open \"https://example.org/reference\" in browser", | |
| "lispm-browser-open-url" | |
| )); | |
| assert!(!admissible("save this buffer", "reject")); | |
| } | |
| fn preexisting_destination_is_never_modified() -> Result<(), TrainingError> { | |
| let temporary = tempfile::tempdir()?; | |
| let marker = temporary.path().join("marker"); | |
| fs::write(&marker, b"retained")?; | |
| let options = TrainOptions { | |
| output_dir: temporary.path().to_owned(), | |
| ..TrainOptions::default() | |
| }; | |
| assert!(matches!( | |
| train(&options), | |
| Err(TrainingError::OutputExists(_)) | |
| )); | |
| assert_eq!(fs::read(marker)?, b"retained"); | |
| Ok(()) | |
| } | |
| fn cancellation_before_or_during_validation_leaves_no_output() -> Result<(), TrainingError> { | |
| let temporary = tempfile::tempdir()?; | |
| let options = TrainOptions { | |
| data_path: temporary.path().join("does-not-exist.json"), | |
| output_dir: temporary.path().join("model"), | |
| ..TrainOptions::default() | |
| }; | |
| let mut control = RecordingControl { | |
| cancel_on: None, | |
| cancelled: true, | |
| events: Vec::new(), | |
| }; | |
| assert!(matches!( | |
| train_with_control(&options, &mut control), | |
| Err(TrainingError::Cancelled) | |
| )); | |
| assert!(control.events.is_empty()); | |
| control.cancel_on = Some("validating"); | |
| control.cancelled = false; | |
| assert!(matches!( | |
| train_with_control(&options, &mut control), | |
| Err(TrainingError::Cancelled) | |
| )); | |
| assert_eq!(control.events.len(), 1); | |
| assert!(!options.output_dir.try_exists()?); | |
| Ok(()) | |
| } | |
| fn portable_validation_matches_bytes_and_rejects_corrupt_sampling_and_hashes() | |
| -> Result<(), TrainingError> { | |
| let path = training_fixture(); | |
| let bytes = fs::read(&path)?; | |
| let summary = validate_training_data(&path)?; | |
| assert_eq!(summary, validate_training_data_bytes(&bytes)?); | |
| assert_eq!(summary.source_sha256, sha256(&bytes)); | |
| assert!( | |
| summary.train_unique > 0 && summary.hard_supported_rows > 0 && summary.hard_reject_rows > 0 | |
| ); | |
| let mut document: Value = serde_json::from_slice(&bytes)?; | |
| let fields = document | |
| .as_object_mut() | |
| .ok_or(TrainingError::InvalidData("fixture object"))?; | |
| fields.insert("hard_training_indices".into(), json!([usize::MAX])); | |
| assert!(matches!( | |
| validate_training_data_bytes(&serde_json::to_vec(&document)?), | |
| Err(TrainingError::InvalidData( | |
| "hard example is not in training" | |
| )) | |
| )); | |
| let mut document: Value = serde_json::from_slice(&bytes)?; | |
| let fields = document | |
| .as_object_mut() | |
| .ok_or(TrainingError::InvalidData("fixture object"))?; | |
| fields.insert("training_sha256".into(), json!("0".repeat(64))); | |
| assert!(matches!( | |
| validate_training_data_bytes(&serde_json::to_vec(&document)?), | |
| Err(TrainingError::InvalidData( | |
| "ordered training/calibration hashes do not match" | |
| )) | |
| )); | |
| Ok(()) | |
| } | |
| fn cancellation_after_first_optimizer_update_stops_before_calibration_and_publication() | |
| -> Result<(), TrainingError> { | |
| let _test = runtime::test_serial_guard(); | |
| let temporary = tempfile::tempdir()?; | |
| let options = TrainOptions { | |
| data_path: training_fixture(), | |
| output_dir: temporary.path().join("model"), | |
| steps: 2, | |
| ..TrainOptions::default() | |
| }; | |
| let mut control = RecordingControl { | |
| cancel_on: Some("step"), | |
| cancelled: false, | |
| events: Vec::new(), | |
| }; | |
| assert!(matches!( | |
| train_with_control(&options, &mut control), | |
| Err(TrainingError::Cancelled) | |
| )); | |
| let phases: Vec<_> = control | |
| .events | |
| .iter() | |
| .filter_map(|event| event.get("phase").and_then(Value::as_str)) | |
| .collect(); | |
| assert_eq!(phases, vec!["validating", "started", "step"]); | |
| let update = control | |
| .events | |
| .last() | |
| .ok_or(TrainingError::InvalidData("missing progress"))?; | |
| assert_eq!(update.get("step").and_then(Value::as_u64), Some(1)); | |
| assert!( | |
| update | |
| .get("train_loss") | |
| .and_then(Value::as_f64) | |
| .is_some_and(f64::is_finite) | |
| ); | |
| assert!(!options.output_dir.try_exists()?); | |
| let _released = runtime::try_acquire()?; | |
| Ok(()) | |
| } | |
| /// Write a tiny real model with every output action and a deliberately fixed vocab. | |
| fn warm_start_fixture(directory: &Path) -> Result<WarmStartOptions, TrainingError> { | |
| let architecture = ModelConfig { | |
| width: 8, | |
| heads: 2, | |
| layers: 1, | |
| feedforward: 16, | |
| char_buckets: 16, | |
| max_ngrams: 8, | |
| ..ModelConfig::default() | |
| }; | |
| let metadata = ArtifactConfig { | |
| architecture, | |
| labels: expected_labels(), | |
| vocab: [ | |
| ("<pad>".into(), 0), | |
| ("<unk>".into(), 1), | |
| ("<cls>".into(), 2), | |
| ("save".into(), 3), | |
| ("buffer".into(), 4), | |
| ("NAME".into(), 5), | |
| ] | |
| .into_iter() | |
| .collect(), | |
| thresholds: Thresholds { | |
| probability: 0.8, | |
| margin: 0.1, | |
| }, | |
| extra: BTreeMap::new(), | |
| }; | |
| let mut bundle = ModelBundle::new(metadata, 17)?; | |
| bundle.save(directory)?; | |
| Ok(WarmStartOptions { | |
| model_dir: directory.to_path_buf(), | |
| learning_rate: 0.0002, | |
| }) | |
| } | |
| /// Source vocabulary identifiers and architecture stay fixed, including OOV features. | |
| fn warm_start_preserves_weights_vocabulary_and_unknown_character_features() | |
| -> Result<(), TrainingError> { | |
| let _test = runtime::test_serial_guard(); | |
| let _runtime = runtime::try_acquire()?; | |
| let temporary = tempfile::tempdir()?; | |
| let options = warm_start_fixture(temporary.path())?; | |
| let source = InitialModelSnapshot::capture(&options)?; | |
| let original = ModelBundle::load(temporary.path())?; | |
| let loaded = source.load(42)?; | |
| assert_eq!(original.metadata.vocab, loaded.metadata.vocab); | |
| assert_eq!(original.metadata.labels, loaded.metadata.labels); | |
| assert_eq!( | |
| serde_json::to_value(&original.metadata.architecture)?, | |
| serde_json::to_value(&loaded.metadata.architecture)? | |
| ); | |
| let original_parameters = original.vs.variables(); | |
| for (name, tensor) in loaded.vs.variables() { | |
| let expected = original_parameters | |
| .get(&name) | |
| .ok_or(TrainingError::InvalidData("fixture parameter missing"))?; | |
| assert!(tensor.f_equal(expected)?); | |
| } | |
| let encoded = encode( | |
| "save novelword", | |
| &loaded.metadata.vocab, | |
| &loaded.metadata.architecture, | |
| )?; | |
| assert_eq!(encoded.word_ids, vec![2, 3, 1]); | |
| assert!( | |
| encoded | |
| .char_ids | |
| .get(2) | |
| .is_some_and(|row| row.iter().any(|&id| id != 0)) | |
| ); | |
| assert!(!loaded.metadata.vocab.contains_key("novelword")); | |
| source.ensure_unchanged()?; | |
| Ok(()) | |
| } | |
| /// Source replacement cannot affect copied bytes, and cannot pass publication checks. | |
| fn warm_start_snapshot_binds_bytes_and_detects_source_mutation() -> Result<(), TrainingError> { | |
| let _test = runtime::test_serial_guard(); | |
| let _runtime = runtime::try_acquire()?; | |
| let temporary = tempfile::tempdir()?; | |
| let options = warm_start_fixture(temporary.path())?; | |
| let config_path = temporary.path().join("config.json"); | |
| let weights_path = temporary.path().join("model.safetensors"); | |
| let config = fs::read(&config_path)?; | |
| let weights = fs::read(&weights_path)?; | |
| let source = InitialModelSnapshot::capture(&options)?; | |
| let identity = source.provenance(); | |
| assert_eq!(identity.get("config_sha256"), Some(&json!(sha256(&config)))); | |
| assert_eq!( | |
| identity.get("weights_sha256"), | |
| Some(&json!(sha256(&weights))) | |
| ); | |
| fs::write(&config_path, b"changed config")?; | |
| assert!(source.load(42).is_ok()); | |
| assert!(matches!( | |
| source.ensure_unchanged(), | |
| Err(TrainingError::InitialModelChanged) | |
| )); | |
| fs::write(&config_path, &config)?; | |
| fs::write(&weights_path, b"changed weights")?; | |
| assert!(matches!( | |
| source.ensure_unchanged(), | |
| Err(TrainingError::InitialModelChanged) | |
| )); | |
| assert!(source.load(42).is_ok()); | |
| Ok(()) | |
| } | |
| /// A fresh optimizer update is repeatable after loading despite prior RNG use. | |
| fn warm_start_first_update_is_seeded_after_loading() -> Result<(), TrainingError> { | |
| let _test = runtime::test_serial_guard(); | |
| let _runtime = runtime::try_acquire()?; | |
| let temporary = tempfile::tempdir()?; | |
| let options = warm_start_fixture(temporary.path())?; | |
| let source = InitialModelSnapshot::capture(&options)?; | |
| let update = |prior_seed| -> Result<ModelBundle, TrainingError> { | |
| tch::manual_seed(prior_seed); | |
| let bundle = source.load(42)?; | |
| let rows = vec![encode( | |
| "save buffer", | |
| &bundle.metadata.vocab, | |
| &bundle.metadata.architecture, | |
| )?]; | |
| let parameters = bundle.vs.trainable_variables(); | |
| let mut optimizer = | |
| COptimizer::adamw(options.learning_rate, 0.9, 0.999, 0.01, 1e-8, false)?; | |
| for parameter in ¶meters { | |
| optimizer.add_parameters(parameter, 0)?; | |
| } | |
| optimize_batch(&bundle, &rows, &[0], &[0], ¶meters, &optimizer)?; | |
| Ok(bundle) | |
| }; | |
| let first = update(11)?.vs.variables(); | |
| let second = update(987)?.vs.variables(); | |
| for (name, tensor) in second { | |
| let expected = first | |
| .get(&name) | |
| .ok_or(TrainingError::InvalidData("fixture parameter missing"))?; | |
| assert!(tensor.f_equal(expected)?); | |
| } | |
| source.ensure_unchanged()?; | |
| Ok(()) | |
| } | |
| /// Warm-start rate validation and cosine endpoints remain independent of scratch defaults. | |
| fn warm_start_schedule_requires_explicit_conservative_finite_rates() -> Result<(), TrainingError> { | |
| for rate in [ | |
| f64::NAN, | |
| f64::INFINITY, | |
| f64::NEG_INFINITY, | |
| 0.0, | |
| -0.0001, | |
| 0.002, | |
| 0.01, | |
| f64::from_bits(1), | |
| ] { | |
| let options = WarmStartOptions { | |
| model_dir: PathBuf::new(), | |
| learning_rate: rate, | |
| }; | |
| assert!(matches!( | |
| options.validate(), | |
| Err(TrainingError::InvalidWarmStartRate) | |
| )); | |
| } | |
| let options = TrainOptions { | |
| warm_start: Some(WarmStartOptions { | |
| model_dir: PathBuf::new(), | |
| learning_rate: 0.0002, | |
| }), | |
| ..TrainOptions::default() | |
| }; | |
| let rates = LearningRates::for_options(&options)?; | |
| assert!((learning_rate(0, 3200, rates)? - 0.0002).abs() < 1e-15); | |
| assert!((learning_rate(3200, 3200, rates)? - 0.00001).abs() < 1e-15); | |
| assert!(TrainOptions::default().warm_start.is_none()); | |
| Ok(()) | |
| } | |
| /// A step-zero fallback keeps eligibility ordering and acquires native provenance on save. | |
| fn warm_start_step_zero_survives_worse_checkpoints_and_serializes_native_hash() | |
| -> Result<(), TrainingError> { | |
| let _test = runtime::test_serial_guard(); | |
| let _runtime = runtime::try_acquire()?; | |
| let temporary = tempfile::tempdir()?; | |
| let options = warm_start_fixture(&temporary.path().join("source"))?; | |
| let config_path = options.model_dir.join("config.json"); | |
| let mut metadata = ArtifactConfig::load(&config_path).map_err(ModelError::from)?; | |
| metadata | |
| .extra | |
| .insert("source_checkpoint_format".into(), json!("pytorch")); | |
| metadata | |
| .extra | |
| .insert("source_checkpoint_sha256".into(), json!("a".repeat(64))); | |
| metadata.save(&config_path).map_err(ModelError::from)?; | |
| let source = InitialModelSnapshot::capture(&options)?; | |
| let mut bundle = source.load(42)?; | |
| let probabilities = [vec![0.9, 0.1]]; | |
| let labels = [0]; | |
| let admissible = [true]; | |
| let batch = CalibrationBatch::new(&probabilities, &labels, &admissible, 1)?; | |
| let selection = select_thresholds(&batch, None, &bundle.metadata.thresholds)?; | |
| let mut result = CalibrationResult { | |
| selection, | |
| loss: 0.1, | |
| accuracy: 1.0, | |
| }; | |
| let mut best = None; | |
| consider_checkpoint(&bundle, 0, &result, &mut best)?; | |
| result.loss = 0.2; | |
| consider_checkpoint(&bundle, 1, &result, &mut best)?; | |
| result.selection.report.eligible = false; | |
| result.loss = 0.0; | |
| consider_checkpoint(&bundle, 2, &result, &mut best)?; | |
| assert!(best.as_ref().is_some_and(|checkpoint| checkpoint.step == 0)); | |
| let output = temporary.path().join("fallback"); | |
| bundle.save(&output)?; | |
| let saved = ModelBundle::load(&output)?; | |
| assert_eq!( | |
| saved.metadata.extra.get("source_checkpoint_format"), | |
| Some(&json!("safetensors")) | |
| ); | |
| assert_eq!( | |
| saved.metadata.extra.get("source_checkpoint_sha256"), | |
| Some(&json!(sha256(&fs::read(output.join("model.safetensors"))?))) | |
| ); | |
| source.ensure_unchanged()?; | |
| let data = ValidatedData::load(&training_fixture())?; | |
| let pools = SamplingPools::build(&data)?; | |
| let training = TrainOptions { | |
| warm_start: Some(options), | |
| ..TrainOptions::default() | |
| }; | |
| let context = RunContext { | |
| options: &training, | |
| data: &data, | |
| pools: &pools, | |
| initial_model: Some(&source), | |
| started: Instant::now(), | |
| }; | |
| result.selection.report.eligible = true; | |
| let report = build_report(&context, &saved, 0, result.selection)?; | |
| assert_eq!(report.selected_step, 0); | |
| assert_eq!( | |
| report.runtime.get("selected_checkpoint_has_updates"), | |
| Some(&json!(false)) | |
| ); | |
| assert_eq!( | |
| report.runtime.get("initialization"), | |
| Some(&source.provenance()) | |
| ); | |
| Ok(()) | |
| } | |
| /// Simulate a caller replacing initialization bytes after an update was selected. | |
| struct SourceMutationControl<'a> { | |
| /// Original model directory whose config is changed at the selection boundary. | |
| source: &'a Path, | |
| } | |
| impl TrainingControl for SourceMutationControl<'_> { | |
| /// Mutation is an input-integrity failure, independently of cancellation. | |
| fn is_cancelled(&self) -> bool { | |
| false | |
| } | |
| /// Replace only the temporary test source when selection is announced. | |
| fn progress(&mut self, event: &TrainingProgress) -> Result<(), TrainingError> { | |
| if matches!(event, TrainingProgress::Selecting { .. }) { | |
| fs::write(self.source.join("config.json"), b"changed during training")?; | |
| } | |
| Ok(()) | |
| } | |
| } | |
| /// Rechecking the source is a publication gate, not merely provenance metadata. | |
| fn warm_start_source_changes_abort_publication() -> Result<(), TrainingError> { | |
| let _test = runtime::test_serial_guard(); | |
| let _runtime = runtime::try_acquire()?; | |
| let temporary = tempfile::tempdir()?; | |
| let warm = warm_start_fixture(&temporary.path().join("source"))?; | |
| let source = InitialModelSnapshot::capture(&warm)?; | |
| let mut bundle = source.load(42)?; | |
| let data = ValidatedData::load(&training_fixture())?; | |
| let pools = SamplingPools::build(&data)?; | |
| let options = TrainOptions { | |
| data_path: training_fixture(), | |
| output_dir: temporary.path().join("never-published"), | |
| warm_start: Some(warm), | |
| ..TrainOptions::default() | |
| }; | |
| let probabilities = [vec![0.9, 0.1]]; | |
| let batch = CalibrationBatch::new(&probabilities, &[0], &[true], 1)?; | |
| let selection = select_thresholds(&batch, None, &bundle.metadata.thresholds)?; | |
| let mut weights = Vec::new(); | |
| bundle.vs.save_to_stream(&mut weights)?; | |
| let selected = SelectedCheckpoint { | |
| rank: selection.rank(0.1)?, | |
| weights, | |
| step: 0, | |
| }; | |
| let context = RunContext { | |
| options: &options, | |
| data: &data, | |
| pools: &pools, | |
| initial_model: Some(&source), | |
| started: Instant::now(), | |
| }; | |
| let result = complete_training( | |
| &context, | |
| &mut bundle, | |
| selected, | |
| &[], | |
| &mut SourceMutationControl { | |
| source: &temporary.path().join("source"), | |
| }, | |
| ); | |
| assert!(matches!(result, Err(TrainingError::InitialModelChanged))); | |
| assert!(!options.output_dir.try_exists()?); | |
| Ok(()) | |
| } | |
| /// Warm-start initialization preserves cancellation before any optimizer work. | |
| fn warm_start_cancellation_keeps_source_and_destination_unchanged() -> Result<(), TrainingError> { | |
| let _test = runtime::test_serial_guard(); | |
| let temporary = tempfile::tempdir()?; | |
| let warm = warm_start_fixture(&temporary.path().join("source"))?; | |
| let config = fs::read(warm.model_dir.join("config.json"))?; | |
| let weights = fs::read(warm.model_dir.join("model.safetensors"))?; | |
| let source_dir = warm.model_dir.to_path_buf(); | |
| let options = TrainOptions { | |
| data_path: training_fixture(), | |
| output_dir: temporary.path().join("cancelled"), | |
| warm_start: Some(warm), | |
| ..TrainOptions::default() | |
| }; | |
| let mut control = RecordingControl { | |
| cancel_on: Some("started"), | |
| cancelled: false, | |
| events: Vec::new(), | |
| }; | |
| assert!(matches!( | |
| train_with_control(&options, &mut control), | |
| Err(TrainingError::Cancelled) | |
| )); | |
| assert!(!options.output_dir.try_exists()?); | |
| assert_eq!(fs::read(source_dir.join("config.json"))?, config); | |
| assert_eq!(fs::read(source_dir.join("model.safetensors"))?, weights); | |
| Ok(()) | |
| } | |