File size: 11,637 Bytes
99fb72f | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 | //! 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).
#[derive(Debug, Clone, Copy)]
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.
#[inline]
#[must_use]
pub const fn is_leaf(self) -> bool {
self.feature < 0
}
}
#[derive(Debug, Clone, Copy)]
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.
#[derive(Debug, Clone, Copy)]
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.
#[derive(Debug, Clone, Copy)]
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`.
#[must_use]
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.
#[must_use]
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
}
#[allow(clippy::too_many_arguments)]
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]`.
#[must_use]
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.
#[must_use]
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,
}
}
|