File size: 5,598 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
//! Validated Binary Loader & Thread-Local Cache for the Corpus-Trained LightGBM Ensemble (`trained_forest`).
//!
//! Binary format `AIDGB02\0` (`src/weights/gbdt_forest.bin`):
//! - `[0..8]`: Magic `"AIDGB02\0"`
//! - `[8..16]`: `base_margin: f64` (LE)
//! - `[16..24]`: `platt_slope: f64` (LE)
//! - `[24..32]`: `platt_intercept: f64` (LE)
//! - `[32..36]`: `num_trees: u32` (LE)
//! - `[36..40]`: `num_knots: u32` (LE)
//! - Knots: `num_knots * 16` bytes of `(margin: f64, prob: f64)` (LE)
//! - Trees: `num_trees` blocks of `num_nodes: u16` followed by `num_nodes * 30` bytes
//!   `(feature: i16, left: u16, right: u16, threshold: f64, leaf_value: f64, cover: f64)`.

use std::cell::OnceCell;

use crate::gbdt::{TrainedGbdtModel, TreeNode};
use crate::model::DetectError;

/// Raw embedded LightGBM + Isotonic Calibration binary (`src/weights/gbdt_forest.bin`).
pub static EMBEDDED_GBDT_BYTES: &[u8] = include_bytes!("weights/gbdt_forest.bin");

/// Decoded owned forest cached once per Wasm/native thread.
pub struct DecodedForest {
    base_margin: f64,
    platt_tail: (f64, f64),
    knots: Vec<(f64, f64)>,
    trees: Vec<Vec<TreeNode>>,
}

thread_local! {
    static CACHED_FOREST: OnceCell<DecodedForest> = const { OnceCell::new() };
}

fn read_u16_le(buf: &[u8], off: &mut usize) -> Option<u16> {
    let s = buf.get(*off..*off + 2)?;
    *off += 2;
    Some(u16::from_le_bytes([*s.first()?, *s.get(1)?]))
}

fn read_i16_le(buf: &[u8], off: &mut usize) -> Option<i16> {
    let s = buf.get(*off..*off + 2)?;
    *off += 2;
    Some(i16::from_le_bytes([*s.first()?, *s.get(1)?]))
}

fn read_u32_le(buf: &[u8], off: &mut usize) -> Option<u32> {
    let s = buf.get(*off..*off + 4)?;
    *off += 4;
    Some(u32::from_le_bytes([
        *s.first()?,
        *s.get(1)?,
        *s.get(2)?,
        *s.get(3)?,
    ]))
}

fn read_f64_le(buf: &[u8], off: &mut usize) -> Option<f64> {
    let s = buf.get(*off..*off + 8)?;
    *off += 8;
    Some(f64::from_le_bytes([
        *s.first()?,
        *s.get(1)?,
        *s.get(2)?,
        *s.get(3)?,
        *s.get(4)?,
        *s.get(5)?,
        *s.get(6)?,
        *s.get(7)?,
    ]))
}

/// Parses and validates an `AIDGB02\0` binary forest buffer without panicking.
pub fn decode_gbdt_bytes(raw: &[u8]) -> Result<DecodedForest, DetectError> {
    if raw.get(0..8) != Some(b"AIDGB02\0".as_slice()) {
        return Err(DetectError::NullOrInvalidBuffer);
    }
    let mut off = 8usize;
    let base_margin = read_f64_le(raw, &mut off).ok_or(DetectError::NullOrInvalidBuffer)?;
    let platt_slope = read_f64_le(raw, &mut off).ok_or(DetectError::NullOrInvalidBuffer)?;
    let platt_intercept = read_f64_le(raw, &mut off).ok_or(DetectError::NullOrInvalidBuffer)?;
    let num_trees =
        usize::try_from(read_u32_le(raw, &mut off).ok_or(DetectError::NullOrInvalidBuffer)?)
            .unwrap_or(0);
    let num_knots =
        usize::try_from(read_u32_le(raw, &mut off).ok_or(DetectError::NullOrInvalidBuffer)?)
            .unwrap_or(0);

    if num_trees == 0 || num_trees > 1024 || num_knots > 512 {
        return Err(DetectError::NullOrInvalidBuffer);
    }

    let mut knots = Vec::with_capacity(num_knots);
    for _ in 0..num_knots {
        let kx = read_f64_le(raw, &mut off).ok_or(DetectError::NullOrInvalidBuffer)?;
        let ky = read_f64_le(raw, &mut off).ok_or(DetectError::NullOrInvalidBuffer)?;
        knots.push((kx, ky));
    }

    let mut trees = Vec::with_capacity(num_trees);
    for _ in 0..num_trees {
        let n_nodes =
            usize::from(read_u16_le(raw, &mut off).ok_or(DetectError::NullOrInvalidBuffer)?);
        if n_nodes == 0 || n_nodes > 512 {
            return Err(DetectError::NullOrInvalidBuffer);
        }
        let mut nodes = Vec::with_capacity(n_nodes);
        for _ in 0..n_nodes {
            let feature = read_i16_le(raw, &mut off).ok_or(DetectError::NullOrInvalidBuffer)?;
            let left = read_u16_le(raw, &mut off).ok_or(DetectError::NullOrInvalidBuffer)?;
            let right = read_u16_le(raw, &mut off).ok_or(DetectError::NullOrInvalidBuffer)?;
            let threshold = read_f64_le(raw, &mut off).ok_or(DetectError::NullOrInvalidBuffer)?;
            let leaf_value = read_f64_le(raw, &mut off).ok_or(DetectError::NullOrInvalidBuffer)?;
            let cover = read_f64_le(raw, &mut off).ok_or(DetectError::NullOrInvalidBuffer)?;
            nodes.push(TreeNode {
                feature,
                left,
                right,
                threshold,
                leaf_value,
                cover,
            });
        }
        trees.push(nodes);
    }

    Ok(DecodedForest {
        base_margin,
        platt_tail: (platt_slope, platt_intercept),
        knots,
        trees,
    })
}

/// Evaluates `f` with a zero-copy `TrainedGbdtModel` view backed by the thread-local decoded forest.
pub fn with_trained_gbdt<R, F>(f: F) -> Result<R, DetectError>
where
    F: FnOnce(TrainedGbdtModel<'_>) -> R,
{
    CACHED_FOREST.with(|cell| {
        if cell.get().is_none() {
            let decoded = decode_gbdt_bytes(EMBEDDED_GBDT_BYTES)?;
            let _ = cell.set(decoded);
        }
        let Some(forest) = cell.get() else {
            return Err(DetectError::NullOrInvalidBuffer);
        };
        let tree_slices: Vec<&[TreeNode]> = forest.trees.iter().map(Vec::as_slice).collect();
        let view = TrainedGbdtModel {
            base_margin: forest.base_margin,
            trees: &tree_slices,
            isotonic_knots: &forest.knots,
            platt_tail: forest.platt_tail,
        };
        Ok(f(view))
    })
}