SOL-PV-003 // aprender-contracts
Softmax Probability Simplex Invariant
Verify numerical stability and probability conservation |sum_k p_k - 1.0| <= 1e-6 for extreme FP32 logit ranges.
Measured delta: 0 NaN overflows across full FP32 logit range (simplex tol <= 1e-6)
Before (Failing Anti-Pattern)
pub fn naive_softmax(z: &[f32]) -> Vec<f32> {
let exps: Vec<f32> = z.iter().map(|&x| x.exp()).collect(); // NaN on x > 89!
let s: f32 = exps.iter().sum(); exps.into_iter().map(|e| e / s).collect()
}
After (Verified Code)
pub fn softmax(logits: &[f32]) -> Vec<f32> {
let max = logits.iter().copied().fold(f32::NEG_INFINITY, f32::max);
let exps: Vec<f32> = logits.iter().map(|&z| (z - max).exp()).collect();
let sum: f32 = exps.iter().sum();
exps.into_iter().map(|e| e / sum).collect()
}
Verification Contract
metadata:
version: "1.0.0"
kind: pattern
description: "Softmax probability simplex conservation contract"
references:
- "Bridle (1990) Probabilistic Interpretation of Feedforward Classification Outputs"
equations:
softmax:
formula: "sum(p_i) = 1.0"
proof_obligations:
- id: PO-SM-001
type: invariant
property: "Probability simplex sums to 1.0 within 1e-6"
falsification_tests:
- id: FALSIFY-SM-001
rule: "simplex_conservation"
prediction: "abs(sum(p) - 1.0) <= 1e-6"
if_fails: "Missing max-logit stabilization shift"
Verified CLI Command & Output
$ pv validate contracts/softmax.yaml 0 error(s), 0 warning(s) — Contract is valid.