Skip to main content

lean_ctx/core/
surprise.rs

1//! Predictive Surprise Scoring — conditional entropy relative to LLM knowledge.
2//!
3//! Instead of measuring Shannon entropy in isolation (H(X)), we measure
4//! how surprising each line is to the LLM: H(X | LLM_knowledge).
5//!
6//! Approximation: use BPE token frequency ranks from o200k_base as a proxy
7//! for P(token | LLM). Common tokens (high frequency rank) carry low surprise;
8//! rare tokens (low rank / unknown to the vocab) carry high surprise.
9//!
10//! Scientific basis: Cross-entropy H(P,Q) = -sum(P(x) * log Q(x))
11//! where P is the true distribution and Q is the model's prior.
12
13use std::sync::OnceLock;
14
15use super::tokens::encode_tokens;
16
17static VOCAB_LOG_PROBS: OnceLock<Vec<f64>> = OnceLock::new();
18
19/// Build a log-probability table indexed by token ID.
20/// Uses a Zipfian approximation: P(rank r) ~ 1/(r * H_n) where H_n is the
21/// harmonic number. This closely matches empirical BPE token distributions.
22fn get_vocab_log_probs() -> &'static Vec<f64> {
23    VOCAB_LOG_PROBS.get_or_init(|| {
24        let vocab_size = 200_000usize;
25        let h_n: f64 = (1..=vocab_size).map(|r| 1.0 / r as f64).sum();
26        (0..vocab_size)
27            .map(|rank| {
28                let r = rank + 1; // 1-indexed rank
29                let p = 1.0 / (r as f64 * h_n);
30                -p.log2()
31            })
32            .collect()
33    })
34}
35
36/// Compute the surprise score for a line of text.
37///
38/// Returns the mean negative log-probability (cross-entropy) of the line's
39/// BPE tokens under the Zipfian prior. Higher values = more surprising to
40/// the LLM = more important to keep.
41///
42/// Range: typically 5.0 (very common) to 17.0+ (very rare).
43pub fn line_surprise(text: &str) -> f64 {
44    let tokens = encode_tokens(text);
45    if tokens.is_empty() {
46        return 0.0;
47    }
48    let log_probs = get_vocab_log_probs();
49    let max_id = log_probs.len();
50
51    let total: f64 = tokens
52        .iter()
53        .map(|&t| {
54            let id = t as usize;
55            if id < max_id {
56                log_probs[id]
57            } else {
58                17.6 // max surprise for OOV tokens (~log2(200000))
59            }
60        })
61        .sum();
62
63    total / tokens.len() as f64
64}
65
66/// Classify how surprising a line is relative to the LLM's expected knowledge.
67/// Uses empirically calibrated thresholds for o200k_base.
68#[derive(Debug, Clone, Copy, PartialEq, Eq)]
69pub enum SurpriseLevel {
70    /// Common patterns — safe to compress aggressively
71    Low,
72    /// Mixed content — standard compression
73    Medium,
74    /// Rare/unique tokens — preserve carefully
75    High,
76}
77
78pub fn classify_surprise(text: &str) -> SurpriseLevel {
79    let s = line_surprise(text);
80    if s < 8.0 {
81        SurpriseLevel::Low
82    } else if s < 12.0 {
83        SurpriseLevel::Medium
84    } else {
85        SurpriseLevel::High
86    }
87}
88
89/// Threshold at which the entropy filter starts dropping lines (#1910).
90const DROP_SHARE_ORIGIN: f64 = 0.4;
91/// Extra share of lines dropped per unit of threshold above the origin.
92const DROP_SHARE_SLOPE: f64 = 0.4;
93/// Upper bound: even the most aggressive setting keeps most of a file.
94const MAX_DROP_SHARE: f64 = 0.6;
95
96/// Share of a file's candidate lines the entropy filter drops for a threshold.
97///
98/// Strictly increasing on `(0.4, 1.9)`, which spans every file-adaptive
99/// threshold and the whole aggressiveness range (`0.6 + 1.4a`), so a more
100/// aggressive setting always drops at least as much.
101#[must_use]
102pub fn drop_share(entropy_threshold: f64) -> f64 {
103    ((entropy_threshold - DROP_SHARE_ORIGIN) * DROP_SHARE_SLOPE).clamp(0.0, MAX_DROP_SHARE)
104}
105
106/// Per-file keep floor for [`should_keep_line`] (#1910): the mean per-token
107/// surprise below which a line is among the [`drop_share`] most predictable
108/// lines of `lines`.
109///
110/// The cut is relative to the file on purpose. Absolute cut-offs never fired:
111/// almost every code or prose line has only distinct BPE tokens (normalized
112/// entropy 1.0) and a mean surprise above 11 bits, so a fixed bar either keeps
113/// everything or depends on how the Zipf prior happens to score a language.
114/// Deterministic: the floor is a value from the sorted scores, and ties at it
115/// are kept. Returns `f64::NEG_INFINITY` (keep everything) when nothing is cut.
116#[must_use]
117pub fn surprise_floor<'a>(lines: impl IntoIterator<Item = &'a str>, entropy_threshold: f64) -> f64 {
118    let mut scores: Vec<f64> = lines
119        .into_iter()
120        .map(str::trim)
121        .filter(|t| t.len() >= 3)
122        .map(line_surprise)
123        .collect();
124    #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
125    let cut = (scores.len() as f64 * drop_share(entropy_threshold)).floor() as usize;
126    if cut == 0 {
127        return f64::NEG_INFINITY;
128    }
129    scores.sort_by(f64::total_cmp);
130    scores[cut.min(scores.len() - 1)]
131}
132
133/// Keeps a line unless it is one of the file's most predictable lines, i.e.
134/// its mean per-token surprise is below `surprise_floor` (see
135/// [`surprise_floor`]). Rare identifiers raise the per-token surprise, so a
136/// short line like `CustomDomainType::validate()` survives while boilerplate
137/// built from common tokens is shed first. Lines under 3 bytes always stay.
138pub fn should_keep_line(trimmed: &str, surprise_floor: f64) -> bool {
139    trimmed.len() < 3 || line_surprise(trimmed) >= surprise_floor
140}
141
142// ---------------------------------------------------------------------------
143// Semantic redundancy scoring (#544, EFF-7)
144// ---------------------------------------------------------------------------
145//
146// The Zipf prior measures *lexical* rarity: a rare boilerplate identifier
147// scores high (kept), a frequent but semantically unique line scores low
148// (dropped). The LLMLingua family (survey 2410.12388) climbs this ladder
149// with real likelihood models; the strongest model-assisted step we can take
150// without shipping a token classifier is MMR-style semantic dedup: a line
151// that is near-identical *in embedding space* to something already kept
152// carries almost no marginal information (rate-distortion: spend bits on
153// distinct content only). This is exactly what H2O/SnapKV exploit at the
154// KV level.
155//
156// The embedder is injected as a function so the production path can use the
157// real (feature-gated, lazily loaded) embedding engine while the scoring
158// math stays testable; `None` results fall back to pure Zipf behavior,
159// keeping the no-embeddings build byte-identical.
160
161/// Kept-line embedding window for MMR redundancy checks. Capped so the
162/// incremental cost stays O(n·64) per file.
163const KEPT_WINDOW: usize = 64;
164/// Cosine similarity at or above this means "semantically duplicate".
165const REDUNDANCY_COSINE: f64 = 0.92;
166
167/// Sliding context of already-kept line embeddings.
168#[derive(Default)]
169pub struct ScoringCtx {
170    kept: std::collections::VecDeque<Vec<f32>>,
171}
172
173impl ScoringCtx {
174    pub fn new() -> Self {
175        Self::default()
176    }
177
178    pub fn push_kept(&mut self, embedding: Vec<f32>) {
179        if self.kept.len() >= KEPT_WINDOW {
180            self.kept.pop_front();
181        }
182        self.kept.push_back(embedding);
183    }
184
185    /// Max cosine similarity of `emb` to any kept embedding.
186    pub fn max_cosine(&self, emb: &[f32]) -> f64 {
187        self.kept
188            .iter()
189            .map(|k| cosine(k, emb))
190            .fold(0.0_f64, f64::max)
191    }
192}
193
194fn cosine(a: &[f32], b: &[f32]) -> f64 {
195    if a.is_empty() || a.len() != b.len() {
196        return 0.0;
197    }
198    let mut dot = 0.0_f64;
199    let mut na = 0.0_f64;
200    let mut nb = 0.0_f64;
201    for (x, y) in a.iter().zip(b.iter()) {
202        dot += f64::from(*x) * f64::from(*y);
203        na += f64::from(*x) * f64::from(*x);
204        nb += f64::from(*y) * f64::from(*y);
205    }
206    if na <= 0.0 || nb <= 0.0 {
207        return 0.0;
208    }
209    dot / (na.sqrt() * nb.sqrt())
210}
211
212/// Semantic-redundancy keep decision (#544): the Zipf path nominates keep
213/// candidates exactly as `should_keep_line`; candidates that embed nearly
214/// identically to an already-kept line are dropped (MMR). `embed` returning
215/// `None` (engine not loaded / feature off) preserves today's behavior
216/// byte-for-byte.
217pub fn should_keep_line_semantic(
218    trimmed: &str,
219    surprise_floor: f64,
220    embed: &dyn Fn(&str) -> Option<Vec<f32>>,
221    ctx: &mut ScoringCtx,
222) -> bool {
223    if !should_keep_line(trimmed, surprise_floor) {
224        return false;
225    }
226    let Some(emb) = embed(trimmed) else {
227        return true;
228    };
229    if ctx.max_cosine(&emb) >= REDUNDANCY_COSINE {
230        return false;
231    }
232    ctx.push_kept(emb);
233    true
234}
235
236#[cfg(test)]
237pub mod tests {
238    use super::*;
239
240    #[test]
241    fn common_code_has_low_surprise() {
242        let common = "let x = 1;";
243        let s = line_surprise(common);
244        assert!(s > 0.0, "surprise should be positive");
245    }
246
247    #[test]
248    fn rare_identifiers_have_higher_surprise() {
249        let common = "let x = 1;";
250        let rare = "let zygomorphic_validator = XenolithProcessor::new();";
251        assert!(
252            line_surprise(rare) > line_surprise(common),
253            "rare identifiers should have higher surprise"
254        );
255    }
256
257    #[test]
258    fn empty_returns_zero() {
259        assert_eq!(line_surprise(""), 0.0);
260    }
261
262    #[test]
263    fn classify_surprise_is_consistent() {
264        let simple = "let x = 1;";
265        let complex = "ZygomorphicXenolithValidator::process_quantum_state(&mut ctx)";
266        let s_simple = line_surprise(simple);
267        let s_complex = line_surprise(complex);
268        assert!(
269            s_complex > s_simple,
270            "rare identifiers ({s_complex}) should have higher surprise than common code ({s_simple})"
271        );
272    }
273
274    #[test]
275    fn should_keep_preserves_rare_lines() {
276        let rare = "ZygomorphicValidator::process_xenolith(&mut state)";
277        let common = [
278            "let a = 1;",
279            "let b = 2;",
280            "x += 1;",
281            "return None;",
282            "Ok(())",
283            "let mut v = Vec::new();",
284            "if x { y }",
285            "self.len()",
286            "use std::fmt;",
287        ];
288        let mut file = common.to_vec();
289        file.push(rare);
290        // 1.9 → drop share 0.6: the six most predictable lines fall below it.
291        let floor = surprise_floor(file.iter().copied(), 1.9);
292        assert!(should_keep_line(rare, floor), "rare line must survive");
293        let shed = common
294            .iter()
295            .filter(|l| !should_keep_line(l, floor))
296            .count();
297        assert!(shed >= 1, "boilerplate is shed first (floor {floor})");
298        assert!(should_keep_line("}", floor), "sub-3-byte lines always stay");
299    }
300
301    /// #1910: the threshold must actually steer the filter — the old absolute
302    /// escapes kept every line whatever the threshold or aggressiveness.
303    #[test]
304    fn drop_share_is_monotonic_and_bounded() {
305        assert_eq!(drop_share(0.0), 0.0);
306        assert_eq!(drop_share(DROP_SHARE_ORIGIN), 0.0);
307        let mut prev = drop_share(0.6);
308        for step in 1..=13 {
309            let t = 0.6 + 0.1 * f64::from(step);
310            let share = drop_share(t);
311            assert!(share > prev, "{t}: {share} must exceed {prev}");
312            prev = share;
313        }
314        assert_eq!(drop_share(10.0), MAX_DROP_SHARE);
315    }
316
317    #[test]
318    fn surprise_floor_cuts_the_requested_share() {
319        let lines: Vec<String> = (0..40)
320            .map(|i| format!("let value_{i} = compute_{}(input);", "x".repeat(i % 7)))
321            .collect();
322        let refs = || lines.iter().map(String::as_str);
323        for t in [0.6, 1.0, 1.4, 1.9] {
324            let floor = surprise_floor(refs(), t);
325            let dropped = refs().filter(|l| !should_keep_line(l, floor)).count();
326            #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
327            let cap = (40.0 * drop_share(t)).floor() as usize;
328            assert!(dropped <= cap, "t={t}: dropped {dropped} > cap {cap}");
329            assert_eq!(floor, surprise_floor(refs(), t), "deterministic (#498)");
330        }
331        assert_eq!(surprise_floor(refs(), 0.4), f64::NEG_INFINITY);
332        assert_eq!(surprise_floor(std::iter::empty(), 1.9), f64::NEG_INFINITY);
333    }
334
335    /// Deterministic hashed bag-of-words vectorizer: a real (if simple)
336    /// embedding function for unit-testing the MMR math. Production uses the
337    /// feature-gated neural engine through the same `embed` seam.
338    #[allow(clippy::unnecessary_wraps)] // Option matches the fallible embed seam
339    fn bow_embed(line: &str) -> Option<Vec<f32>> {
340        let mut v = vec![0.0f32; 64];
341        for tok in line.to_lowercase().split(|c: char| !c.is_alphanumeric()) {
342            if tok.len() < 2 {
343                continue;
344            }
345            let mut h = 0u64;
346            for b in tok.bytes() {
347                h = h.wrapping_mul(31).wrapping_add(u64::from(b));
348            }
349            v[(h % 64) as usize] += 1.0;
350        }
351        Some(v)
352    }
353
354    #[test]
355    fn semantic_dedup_drops_near_duplicate_kept_lines() {
356        let mut ctx = ScoringCtx::new();
357        let embed = |s: &str| bow_embed(s);
358        let a = "fn validate_user_payload(payload: &UserPayload) -> Result<(), ValidationError>";
359        // Same bag of words, reordered — semantically duplicate logic.
360        let b = "fn validate_user_payload(payload: &UserPayload) -> Result<(), ValidationError> ";
361        let c = "const MAX_RETRY_BACKOFF_MS: u64 = 30_000;";
362
363        assert!(should_keep_line_semantic(a, 0.5, &embed, &mut ctx));
364        assert!(
365            !should_keep_line_semantic(b, 0.5, &embed, &mut ctx),
366            "near-identical line must be dropped as redundant"
367        );
368        assert!(
369            should_keep_line_semantic(c, 0.5, &embed, &mut ctx),
370            "distinct line stays"
371        );
372    }
373
374    #[test]
375    fn no_embedder_is_identical_to_zipf_path() {
376        let mut ctx = ScoringCtx::new();
377        let none = |_: &str| None;
378        for line in [
379            "fn main() { run(); }",
380            "let x = 1;",
381            "ZygomorphicXenolithValidator::process_quantum_state(&mut ctx)",
382            "// plain comment",
383        ] {
384            assert_eq!(
385                should_keep_line_semantic(line, 1.0, &none, &mut ctx),
386                should_keep_line(line, 1.0),
387                "without embeddings the decision must match the Zipf path: {line}"
388            );
389        }
390    }
391
392    #[test]
393    fn kept_window_is_bounded() {
394        let mut ctx = ScoringCtx::new();
395        for i in 0..200 {
396            ctx.push_kept(vec![i as f32; 8]);
397        }
398        assert!(ctx.kept.len() <= 64);
399    }
400
401    #[test]
402    fn cosine_handles_degenerate_inputs() {
403        assert_eq!(cosine(&[], &[]), 0.0);
404        assert_eq!(cosine(&[1.0], &[1.0, 2.0]), 0.0);
405        assert_eq!(cosine(&[0.0, 0.0], &[0.0, 0.0]), 0.0);
406        assert!((cosine(&[1.0, 0.0], &[1.0, 0.0]) - 1.0).abs() < 1e-9);
407    }
408}