use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::sync::{Mutex, MutexGuard};
static DETECT_ANOMALY: AtomicBool = AtomicBool::new(false);
static ANOMALY_TRAINING_STEP: AtomicUsize = AtomicUsize::new(0);
static ANOMALY_TEST_LOCK: Mutex<()> = Mutex::new(());
#[doc(hidden)]
pub fn test_lock() -> MutexGuard<'static, ()> {
ANOMALY_TEST_LOCK
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner())
}
pub fn set_detect_anomaly(enabled: bool) {
DETECT_ANOMALY.store(enabled, Ordering::Relaxed);
}
pub fn detect_anomaly_enabled() -> bool {
DETECT_ANOMALY.load(Ordering::Relaxed)
}
pub fn set_anomaly_training_step(step: usize) {
ANOMALY_TRAINING_STEP.store(step, Ordering::Relaxed);
}
pub fn anomaly_training_step() -> usize {
ANOMALY_TRAINING_STEP.load(Ordering::Relaxed)
}
pub fn parse_detect_anomaly(value: &str) -> Result<bool, String> {
match value.trim().to_ascii_lowercase().as_str() {
"0" | "off" | "false" | "no" | "none" => Ok(false),
"1" | "on" | "true" | "yes" => Ok(true),
other => Err(format!(
"unknown detect-anomaly value '{other}'; expected on or off"
)),
}
}
pub fn init_from_env() {
if let Ok(value) = std::env::var("OXIDELM_DETECT_ANOMALY") {
if let Ok(enabled) = parse_detect_anomaly(&value) {
set_detect_anomaly(enabled);
}
}
}
pub fn format_report(operation: &str, shape: &[usize]) -> String {
format!(
"anomaly: non-finite value in operation '{operation}' shape {shape:?} at training step {}",
anomaly_training_step()
)
}
pub fn check_finite(operation: &str, shape: &[usize], values: &[f32]) {
if !detect_anomaly_enabled() {
return;
}
if values.iter().any(|value| !value.is_finite()) {
panic!("{}", format_report(operation, shape));
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parse_accepts_common_booleans() {
assert!(parse_detect_anomaly("1").unwrap());
assert!(parse_detect_anomaly("ON").unwrap());
assert!(!parse_detect_anomaly("off").unwrap());
assert!(parse_detect_anomaly("maybe").is_err());
}
#[test]
fn report_includes_operation_shape_and_step() {
set_anomaly_training_step(12);
let report = format_report("div", &[2, 3]);
assert!(report.contains("operation 'div'"));
assert!(report.contains("shape [2, 3]"));
assert!(report.contains("training step 12"));
set_anomaly_training_step(0);
}
}