Download rust_src/src/gbdt.rs from ElderRyan/ProseGuard-ML: direct link, hf CLI and curl.
- Browser
- Download file 11.6 kB
-
https://huggingface.co/ElderRyan/ProseGuard-ML/resolve/main/rust_src/src/gbdt.rs
- Command line
-
hf download hf://ElderRyan/ProseGuard-ML/rust_src/src/gbdt.rs
-
curl -L -o gbdt.rs https://huggingface.co/ElderRyan/ProseGuard-ML/resolve/main/rust_src/src/gbdt.rs
11.6 kB
| //! Corpus-Trained Gradient Boosted Decision Tree Evaluator, Monotone Isotonic Calibrator, | |
| //! and Exact Stack-Allocated Path-Dependent TreeSHAP (`gbdt`). | |
| //! | |
| //! Law (Shapley Local Accuracy): For any feature vector $x \in \mathbb{R}^F$ and tree ensemble $T$, | |
| //! `expected_margin(T) + sum_j shap[j] == raw_margin(T, x)` within IEEE-754 rounding (`< 1e-9`), | |
| //! provided every internal node satisfies `cover == left.cover + right.cover`. | |
| /// Number of orthogonal ML features consumed by the GBDT classifier. | |
| pub const NUM_GBDT_FEATURES: usize = 28; | |
| /// Maximum root-to-leaf path buffer capacity (`max_depth <= 8` -> `path_len <= 9`). | |
| const MAX_PATH_CAP: usize = 12; | |
| /// Single immutable node in a binary decision tree (`Copy`, 32 bytes). | |
| pub struct TreeNode { | |
| /// Split feature index in `0..NUM_GBDT_FEATURES`, or `-1` if this node is a leaf. | |
| pub feature: i16, | |
| /// Left child index (`x[feature] <= threshold`). | |
| pub left: u16, | |
| /// Right child index (`x[feature] > threshold`). | |
| pub right: u16, | |
| /// Split threshold for internal nodes (`0.0` for leaves). | |
| pub threshold: f64, | |
| /// Leaf log-odds weight (`0.0` for internal nodes). | |
| pub leaf_value: f64, | |
| /// Training sample cover reaching this node (`cover == left.cover + right.cover`). | |
| pub cover: f64, | |
| } | |
| impl TreeNode { | |
| /// Semantic predicate: returns `true` when this node is a terminal leaf. | |
| pub const fn is_leaf(self) -> bool { | |
| self.feature < 0 | |
| } | |
| } | |
| struct PathElem { | |
| feature: i32, | |
| zero_frac: f64, | |
| one_frac: f64, | |
| pweight: f64, | |
| } | |
| impl Default for PathElem { | |
| fn default() -> Self { | |
| Self { | |
| feature: -1, | |
| zero_frac: 1.0, | |
| one_frac: 1.0, | |
| pweight: 0.0, | |
| } | |
| } | |
| } | |
| /// Complete trained GBDT + Isotonic calibration model specification. | |
| pub struct TrainedGbdtModel<'a> { | |
| /// Base prior log-odds offset. | |
| pub base_margin: f64, | |
| /// Slice of decision trees, each stored in contiguous node order starting at root `0`. | |
| pub trees: &'a [&'a [TreeNode]], | |
| /// Monotone piecewise-linear calibration knots `(margin, calibrated_prob)`. | |
| pub isotonic_knots: &'a [(f64, f64)], | |
| /// Platt logistic fallback `(slope, intercept)` for smooth tail extrapolation. | |
| pub platt_tail: (f64, f64), | |
| } | |
| /// Result of running GBDT inference + Exact TreeSHAP on a single document. | |
| pub struct GbdtPrediction { | |
| /// Raw uncalibrated log-odds margin $f(x) = \text{base} + \sum_t T_t(x)$. | |
| pub raw_margin: f64, | |
| /// Expected baseline margin $\phi_0 = \text{base} + \sum_t \mathbb{E}[T_t]$. | |
| pub expected_margin: f64, | |
| /// Calibrated probability $p(y = \text{AI} \mid x) \in [0, 1]$. | |
| pub calibrated_prob: f64, | |
| /// Exact per-feature Shapley log-odds attributions $\phi_j(x)$ summing to `raw_margin - expected_margin`. | |
| pub shap_values: [f64; NUM_GBDT_FEATURES], | |
| } | |
| /// Evaluates a single tree's deterministic leaf prediction for `x`. | |
| pub fn eval_single_tree(nodes: &[TreeNode], x: &[f64; NUM_GBDT_FEATURES]) -> f64 { | |
| let mut idx = 0usize; | |
| for _ in 0..MAX_PATH_CAP { | |
| let Some(&node) = nodes.get(idx) else { | |
| return 0.0; | |
| }; | |
| if node.is_leaf() { | |
| return node.leaf_value; | |
| } | |
| let f_idx = usize::try_from(node.feature).unwrap_or(0); | |
| let f_val = x.get(f_idx).copied().unwrap_or(0.0); | |
| idx = if f_val <= node.threshold { | |
| usize::from(node.left) | |
| } else { | |
| usize::from(node.right) | |
| }; | |
| } | |
| 0.0 | |
| } | |
| /// Computes exact expected value $\mathbb{E}[T]$ of a tree weighted by empirical node cover. | |
| pub fn tree_expected_value(nodes: &[TreeNode]) -> f64 { | |
| let Some(&root) = nodes.first() else { | |
| return 0.0; | |
| }; | |
| if root.cover <= 0.0 { | |
| return 0.0; | |
| } | |
| expected_rec(nodes, 0, root.cover, 0) | |
| } | |
| fn expected_rec(nodes: &[TreeNode], idx: usize, root_cover: f64, depth: usize) -> f64 { | |
| if depth >= MAX_PATH_CAP { | |
| return 0.0; | |
| } | |
| let Some(&node) = nodes.get(idx) else { | |
| return 0.0; | |
| }; | |
| if node.is_leaf() { | |
| return (node.cover / root_cover) * node.leaf_value; | |
| } | |
| expected_rec(nodes, usize::from(node.left), root_cover, depth + 1) | |
| + expected_rec(nodes, usize::from(node.right), root_cover, depth + 1) | |
| } | |
| fn extend_path( | |
| path: &mut [PathElem; MAX_PATH_CAP], | |
| plen: usize, | |
| p_z: f64, | |
| p_o: f64, | |
| p_i: i32, | |
| ) -> usize { | |
| if plen + 1 >= MAX_PATH_CAP { | |
| return plen; | |
| } | |
| if let Some(slot) = path.get_mut(plen) { | |
| *slot = PathElem { | |
| feature: p_i, | |
| zero_frac: p_z, | |
| one_frac: p_o, | |
| pweight: if plen == 0 { 1.0 } else { 0.0 }, | |
| }; | |
| } | |
| let denom = (plen + 1) as f64; | |
| for i in (0..plen).rev() { | |
| let wi = path.get(i).map(|e| e.pweight).unwrap_or(0.0); | |
| if let Some(next_slot) = path.get_mut(i + 1) { | |
| next_slot.pweight += p_o * wi * ((i + 1) as f64) / denom; | |
| } | |
| if let Some(cur_slot) = path.get_mut(i) { | |
| cur_slot.pweight = p_z * wi * ((plen - i) as f64) / denom; | |
| } | |
| } | |
| plen + 1 | |
| } | |
| fn unwind_path(path: &mut [PathElem; MAX_PATH_CAP], plen: usize, remove_idx: usize) -> usize { | |
| if plen == 0 || remove_idx >= plen { | |
| return plen; | |
| } | |
| let n = plen - 1; | |
| let one_f = path.get(remove_idx).map(|e| e.one_frac).unwrap_or(0.0); | |
| let zero_f = path.get(remove_idx).map(|e| e.zero_frac).unwrap_or(1.0); | |
| let mut next_w = path.get(n).map(|e| e.pweight).unwrap_or(0.0); | |
| if one_f != 0.0 { | |
| for j in (0..n).rev() { | |
| let tmp = path.get(j).map(|e| e.pweight).unwrap_or(0.0); | |
| let updated = next_w * ((n + 1) as f64) / (((j + 1) as f64) * one_f); | |
| if let Some(slot) = path.get_mut(j) { | |
| slot.pweight = updated; | |
| } | |
| next_w = tmp - updated * zero_f * ((n - j) as f64) / ((n + 1) as f64); | |
| } | |
| } else if zero_f > 0.0 { | |
| for j in 0..n { | |
| if let Some(slot) = path.get_mut(j) { | |
| slot.pweight = (slot.pweight * ((n + 1) as f64)) / (zero_f * ((n - j) as f64)); | |
| } | |
| } | |
| } | |
| for j in remove_idx..n { | |
| let next_elem = path.get(j + 1).copied().unwrap_or_default(); | |
| if let Some(slot) = path.get_mut(j) { | |
| slot.feature = next_elem.feature; | |
| slot.zero_frac = next_elem.zero_frac; | |
| slot.one_frac = next_elem.one_frac; | |
| } | |
| } | |
| n | |
| } | |
| fn treeshap_recurse( | |
| nodes: &[TreeNode], | |
| node_idx: usize, | |
| x: &[f64; NUM_GBDT_FEATURES], | |
| phi: &mut [f64; NUM_GBDT_FEATURES], | |
| mut path: [PathElem; MAX_PATH_CAP], | |
| mut plen: usize, | |
| p_z: f64, | |
| p_o: f64, | |
| p_i: i32, | |
| ) { | |
| plen = extend_path(&mut path, plen, p_z, p_o, p_i); | |
| let Some(&node) = nodes.get(node_idx) else { | |
| return; | |
| }; | |
| if node.is_leaf() { | |
| for i in 1..plen { | |
| let mut copy = path; | |
| let ulen = unwind_path(&mut copy, plen, i); | |
| let mut w_sum = 0.0f64; | |
| for k in 0..ulen { | |
| w_sum += copy.get(k).map(|e| e.pweight).unwrap_or(0.0); | |
| } | |
| if let Some(elem) = path.get(i) { | |
| if let Ok(f_idx) = usize::try_from(elem.feature) { | |
| if let Some(slot) = phi.get_mut(f_idx) { | |
| *slot += w_sum * (elem.one_frac - elem.zero_frac) * node.leaf_value; | |
| } | |
| } | |
| } | |
| } | |
| return; | |
| } | |
| let f_idx = usize::try_from(node.feature).unwrap_or(0); | |
| let f_val = x.get(f_idx).copied().unwrap_or(0.0); | |
| let hot_idx = if f_val <= node.threshold { | |
| usize::from(node.left) | |
| } else { | |
| usize::from(node.right) | |
| }; | |
| let cold_idx = if f_val <= node.threshold { | |
| usize::from(node.right) | |
| } else { | |
| usize::from(node.left) | |
| }; | |
| let mut incoming_z = 1.0f64; | |
| let mut incoming_o = 1.0f64; | |
| let split_feat_i32 = i32::from(node.feature); | |
| if let Some(dup_pos) = (1..plen).find(|&k| { | |
| path.get(k) | |
| .map(|e| e.feature == split_feat_i32) | |
| .unwrap_or(false) | |
| }) { | |
| incoming_z = path.get(dup_pos).map(|e| e.zero_frac).unwrap_or(1.0); | |
| incoming_o = path.get(dup_pos).map(|e| e.one_frac).unwrap_or(1.0); | |
| plen = unwind_path(&mut path, plen, dup_pos); | |
| } | |
| let parent_cover = node.cover.max(1e-9); | |
| let hot_cover = nodes.get(hot_idx).map(|n| n.cover).unwrap_or(0.0); | |
| let cold_cover = nodes.get(cold_idx).map(|n| n.cover).unwrap_or(0.0); | |
| if hot_cover > 0.0 { | |
| treeshap_recurse( | |
| nodes, | |
| hot_idx, | |
| x, | |
| phi, | |
| path, | |
| plen, | |
| incoming_z * (hot_cover / parent_cover), | |
| incoming_o, | |
| split_feat_i32, | |
| ); | |
| } | |
| if cold_cover > 0.0 { | |
| treeshap_recurse( | |
| nodes, | |
| cold_idx, | |
| x, | |
| phi, | |
| path, | |
| plen, | |
| incoming_z * (cold_cover / parent_cover), | |
| 0.0, | |
| split_feat_i32, | |
| ); | |
| } | |
| } | |
| /// Maps raw GBDT margin + additive shift into a calibrated probability in `[0.002, 0.998]`. | |
| pub fn calibrate_margin(margin: f64, knots: &[(f64, f64)], platt_tail: (f64, f64)) -> f64 { | |
| let platt_p = 1.0 / (1.0 + (-(platt_tail.0 * margin + platt_tail.1)).exp()); | |
| let (Some(&first), Some(&last)) = (knots.first(), knots.last()) else { | |
| return platt_p.clamp(0.002, 0.998); | |
| }; | |
| if margin <= first.0 { | |
| return (0.5 * first.1 + 0.5 * platt_p).clamp(0.002, 0.998); | |
| } | |
| if margin >= last.0 { | |
| return (0.5 * last.1 + 0.5 * platt_p).clamp(0.002, 0.998); | |
| } | |
| let mut iso_p = platt_p; | |
| for pair in knots.windows(2) { | |
| if let (Some(&(x0, y0)), Some(&(x1, y1))) = (pair.first(), pair.get(1)) { | |
| if margin >= x0 && margin <= x1 { | |
| let span = (x1 - x0).max(1e-9); | |
| let t = ((margin - x0) / span).clamp(0.0, 1.0); | |
| iso_p = y0 + t * (y1 - y0); | |
| break; | |
| } | |
| } | |
| } | |
| // Blend 75% empirical isotonic + 25% smooth Platt sigmoid so rank ordering is strictly monotone | |
| (0.75 * iso_p + 0.25 * platt_p).clamp(0.002, 0.998) | |
| } | |
| /// Evaluates the full GBDT ensemble + Exact Path-Dependent TreeSHAP + Calibration. | |
| pub fn predict_with_treeshap( | |
| model: TrainedGbdtModel<'_>, | |
| features: &[f64; NUM_GBDT_FEATURES], | |
| additive_logit_shift: f64, | |
| ) -> GbdtPrediction { | |
| let mut raw_margin = model.base_margin; | |
| let mut expected_margin = model.base_margin; | |
| let mut shap_values = [0.0f64; NUM_GBDT_FEATURES]; | |
| for &tree_nodes in model.trees { | |
| raw_margin += eval_single_tree(tree_nodes, features); | |
| expected_margin += tree_expected_value(tree_nodes); | |
| let init_path = [PathElem::default(); MAX_PATH_CAP]; | |
| treeshap_recurse( | |
| tree_nodes, | |
| 0, | |
| features, | |
| &mut shap_values, | |
| init_path, | |
| 0, | |
| 1.0, | |
| 1.0, | |
| -1, | |
| ); | |
| } | |
| let shifted_margin = raw_margin + additive_logit_shift; | |
| let calibrated_prob = calibrate_margin(shifted_margin, model.isotonic_knots, model.platt_tail); | |
| GbdtPrediction { | |
| raw_margin: shifted_margin, | |
| expected_margin, | |
| calibrated_prob, | |
| shap_values, | |
| } | |
| } | |