Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/aien-protocols-mv/blob/main/crates/aien-probe/src/math.rs # aien-protocols-mv Canonical specifications, wire protocols, and schemas for the AIEN sovereign ecosystem Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `aien-protocols-mv / crates / aien-probe / src / math.rs` 127 lines ยท 3751 bytes Raw Blame History 1 //! Calibration primitives for the probe engine. 2 //! 3 //! Temperature scaling, entropy and projection in plain Rust, so the engine stays 4 //! deterministic and testable without a device. 5 6 /// Scales a logit by a temperature. 7 /// 8 /// A non positive or non finite temperature leaves the logit unchanged. A non finite logit 9 /// collapses to zero. 10 pub fn temperature_scale(logit: f64, temperature: f64) -> f64 { 11 if !logit.is_finite() { 12 return 0.0; 13 } 14 if !temperature.is_finite() || temperature <= 1.0e-4 { 15 return logit; 16 } 17 let scaled = logit / temperature; 18 if scaled.is_finite() { 19 scaled 20 } else { 21 logit 22 } 23 } 24 25 /// Numerically stable logistic function. 26 pub fn sigmoid(z: f64) -> f64 { 27 if z.is_nan() { 28 return 0.0; 29 } 30 if z >= 0.0 { 31 1.0 / (1.0 + (-z).exp()) 32 } else { 33 let e = z.exp(); 34 e / (1.0 + e) 35 } 36 } 37 38 /// Numerically stable softmax over a slice of logits. 39 /// 40 /// An empty slice yields an empty vector. A degenerate sum yields a uniform distribution. 41 pub fn softmax(logits: &[f64]) -> Vec { 42 if logits.is_empty() { 43 return Vec::new(); 44 } 45 let max = logits.iter().cloned().fold(f64::NEG_INFINITY, f64::max); 46 let exps: Vec = logits.iter().map(|l| (l - max).exp()).collect(); 47 let sum: f64 = exps.iter().sum(); 48 if !sum.is_finite() || sum <= 0.0 { 49 let uniform = 1.0 / logits.len() as f64; 50 return vec![uniform; logits.len()]; 51 } 52 exps.iter().map(|e| e / sum).collect() 53 } 54 55 /// Probability weighted mean of the level indices, a position on the ordered scale. 56 pub fn expected_value(probabilities: &[f64]) -> f64 { 57 probabilities 58 .iter() 59 .enumerate() 60 .map(|(level, p)| level as f64 * p) 61 .sum() 62 } 63 64 /// Shannon entropy of a probability distribution in nats. 65 pub fn entropy(probabilities: &[f64]) -> f64 { 66 probabilities 67 .iter() 68 .filter(|p| **p > 1.0e-12) 69 .map(|p| -p * p.ln()) 70 .sum() 71 } 72 73 /// Confidence in a distribution: one minus entropy normalized by the uniform maximum. 74 pub fn confidence(probabilities: &[f64]) -> f64 { 75 let n = probabilities.len(); 76 if n <= 1 { 77 return 1.0; 78 } 79 let max_entropy = (n as f64).ln(); 80 if max_entropy <= 0.0 { 81 return 1.0; 82 } 83 (1.0 - entropy(probabilities) / max_entropy).clamp(0.0, 1.0) 84 } 85 86 #[cfg(test)] 87 mod tests { 88 use super::*; 89 90 #[test] 91 fn test_temperature_scale_edges() { 92 assert_eq!(temperature_scale(2.0, 0.5), 4.0); 93 assert_eq!(temperature_scale(5.0, 0.0), 5.0); 94 assert_eq!(temperature_scale(5.0, 0.00005), 5.0); 95 assert_eq!(temperature_scale(f64::NAN, 1.0), 0.0); 96 assert_eq!(temperature_scale(2.0, f64::INFINITY), 2.0); 97 } 98 99 #[test] 100 fn test_sigmoid_symmetry() { 101 assert!((sigmoid(0.0) - 0.5).abs() < 1.0e-12); 102 assert!((sigmoid(1.0) + sigmoid(-1.0) - 1.0).abs() < 1.0e-12); 103 assert!(sigmoid(50.0) > 0.999); 104 assert!(sigmoid(-50.0) < 0.001); 105 } 106 107 #[test] 108 fn test_softmax_sums_to_one() { 109 let probs = softmax(&[1.0, 2.0, 3.0, 4.0]); 110 let sum: f64 = probs.iter().sum(); 111 assert!((sum - 1.0).abs() < 1.0e-12); 112 assert!(softmax(&[]).is_empty()); 113 let uniform = softmax(&[0.0, 0.0, 0.0, 0.0]); 114 for p in uniform { 115 assert!((p - 0.25).abs() < 1.0e-12); 116 } 117 } 118 119 #[test] 120 fn test_expected_value_and_confidence() { 121 let probs = vec![0.0, 0.0, 0.0, 1.0]; 122 assert!((expected_value(&probs) - 3.0).abs() < 1.0e-12); 123 assert!((confidence(&probs) - 1.0).abs() < 1.0e-12); 124 let flat = vec![0.25, 0.25, 0.25, 0.25]; 125 assert!((confidence(&flat)).abs() < 1.0e-12); 126 } 127 }