//! Dual-Proxy Corpus Language Model & Modern RLHF Syntactic Log-Odds Scorer (`lm_proxy`). //! //! Inspired by Ghostbuster (NAACL) and GPTZero's multi-indicator architecture: //! 1. Scores token/character transitions against embedded RLHF-vs-Human log-odds lexicons across //! English, Simplified/Traditional Chinese, and Japanese (covering GPT-4o, Claude, DeepSeek, Qwen). //! 2. Evaluates structural negative parallelisms ("not just X, but Y", "不是…而是…", "単なる…ではなく"), //! participial clause tails (", ensuring...", ", making it..."), conceptual scare-quotes ("“XX”"), //! and nominalization/glue smoothness. //! 3. Computes per-sentence proxy surprisal & cross-sentence surprisal burstiness, catching clean, //! cliché-free LLM articles via flat predictability pacing. use crate::model::{ScriptFamily, UnitScore}; /// High-log-odds English RLHF vocabulary stems (GPT-4o / Claude / Llama / DeepSeek). const EN_RLHF_WORDS: &[(&str, f64)] = &[ ("delve", 2.4), ("delves", 2.4), ("delving", 2.4), ("tapestry", 2.5), ("testament", 2.0), ("pivotal", 2.1), ("crucial", 1.1), ("vital", 0.9), ("multifaceted", 2.3), ("nuanced", 1.7), ("nuances", 1.6), ("underscore", 2.0), ("underscores", 2.2), ("underscoring", 2.2), ("foster", 1.7), ("fostering", 2.0), ("fosters", 1.8), ("realm", 1.7), ("beacon", 1.9), ("interplay", 2.1), ("synergy", 1.8), ("holistic", 1.9), ("seamless", 1.6), ("seamlessly", 1.9), ("leverage", 1.3), ("leveraging", 1.7), ("harness", 1.6), ("harnessing", 1.9), ("empower", 1.6), ("empowering", 1.8), ("empowers", 1.7), ("elevate", 1.5), ("elevating", 1.7), ("streamline", 1.6), ("streamlining", 1.8), ("transformative", 1.9), ("paradigm", 1.9), ("ecosystem", 1.2), ("stakeholders", 1.6), ("actionable", 1.7), ("overarching", 0.9), ("intricate", 1.7), ("intricacies", 2.0), ("meticulous", 1.8), ("meticulously", 2.0), ("commendable", 1.9), ("indispensable", 1.6), ("catalyst", 1.6), ("cornerstone", 1.7), ("navigating", 1.8), ("embark", 1.8), ("poised", 1.6), ("unprecedented", 1.3), ("burgeoning", 2.0), ("resonate", 1.5), ("resonates", 1.7), ("alignment", 1.3), ("reimagine", 1.9), ("demystify", 2.0), ("illuminate", 1.6), ("illuminates", 1.8), ("spearhead", 1.8), ("bolster", 1.5), ("cultivate", 1.5), ("cultivating", 1.7), ("landscape", 1.4), ("moreover", 1.6), ("furthermore", 1.7), ("additionally", 1.2), ("consequently", 1.1), ("ultimately", 1.0), ("notably", 1.1), ("undeniably", 1.6), ]; /// Modern English syntactic & rhetorical frames favored by GPT-4o, Claude, and DeepSeek. const EN_RLHF_FRAMES: &[(&str, f64)] = &[ ("not just ", 1.5), ("not merely ", 1.8), ("more than just ", 1.7), ("isn't just ", 1.6), ("aren't just ", 1.6), ("it's not about ", 1.8), ("it is not about ", 1.8), ("isn't about ", 1.8), ("not because ", 1.3), ("more often than not", 1.7), ("at its core", 1.9), ("in essence,", 1.7), ("the reality is", 1.4), ("here's why", 1.4), ("here's what", 1.5), ("here's the ", 1.3), ("that's why ", 1.2), ("think about what happens", 1.6), ("moves the needle", 1.7), ("nice-to-have", 1.5), ("first-class", 1.2), ("narrative coherence", 2.0), ("peculiar comfort", 1.8), ("this is where ", 1.3), ("that's where ", 1.3), ("whether you're ", 1.5), ("whether it's ", 1.5), ("it is important to note", 2.4), ("it's important to note", 2.4), ("it is worth noting", 2.1), ("it's worth noting", 2.0), ("in conclusion,", 2.0), ("in summary,", 1.9), ("on one hand", 1.4), ("on the other hand", 1.3), ("at the same time,", 1.1), ("by doing so,", 1.6), ("in other words,", 1.1), ("with that in mind", 1.7), ("moving forward", 1.4), ("looking ahead", 1.4), ("plays a pivotal role", 2.5), ("plays a crucial role", 2.2), ("plays a vital role", 2.1), ("rapidly evolving", 2.2), ("ever-evolving", 2.3), ("rich tapestry", 2.6), ("a testament to", 2.1), (", making it ", 1.3), (", allowing ", 1.2), (", enabling ", 1.4), (", ensuring ", 1.5), (", creating ", 1.2), (", fostering ", 2.0), (", highlighting ", 1.6), (", underscoring ", 2.1), (", reflecting ", 1.3), (", offering ", 1.3), (", paving the way", 2.0), ]; /// Chinese RLHF vocabulary, abstract nominalizations & syntactic markers (GPT-4o / Claude / DeepSeek / Qwen). const ZH_RLHF_MARKERS: &[(&str, f64)] = &[ ("值得注意的是", 2.3), ("值得一提的是", 1.9), ("需要指出的是", 2.1), ("不可否认", 1.7), ("毫无疑问", 1.5), ("显而易见", 1.5), ("不难发现", 1.8), ("不难看出", 1.7), ("这意味着", 1.5), ("这也意味着", 1.7), ("换句话说", 1.4), ("换言之", 1.4), ("某种程度上", 1.5), ("从某种意义上", 1.7), ("从本质上讲", 1.9), ("本质上", 1.2), ("归根结底", 1.6), ("事实上,", 1.2), ("在此背景下", 1.9), ("正因如此", 1.5), ("由此可见", 1.6), ("更重要的是", 1.2), ("尤为重要的是", 1.8), ("与此同时", 1.4), ("不仅如此", 1.5), ("除此之外", 1.2), ("总而言之", 2.2), ("综上所述", 2.2), ("总的来看", 1.7), ("展望未来", 1.8), ("赋能", 2.1), ("闭环", 2.0), ("抓手", 2.0), ("底座", 1.7), ("范式", 1.8), ("颗粒度", 1.9), ("心智", 1.6), ("势能", 1.8), ("场域", 1.9), ("底层逻辑", 1.9), ("顶层设计", 1.8), ("全链路", 1.9), ("护城河", 1.5), ("方法论", 1.5), ("差异化", 1.4), ("规模化", 1.3), ("精细化", 1.4), ("常态化", 1.4), ("多元化", 1.3), ("系统性", 1.2), ("结构性", 1.3), ("确定性", 1.4), ("可持续", 1.3), ("多维度", 1.9), ("全方位", 1.7), ("深层次", 1.5), ("核心竞争力", 1.7), ("不可或缺", 1.6), ("至关重要", 1.8), ("息息相关", 1.5), ("相辅相成", 1.6), ("潜移默化", 1.4), ("双刃剑", 1.8), ("重塑", 1.5), ("重构", 1.3), ("洞察", 1.4), ("锚定", 1.8), ("拆解", 1.3), ("沉淀", 1.5), ("演进", 1.3), ("深耕", 1.6), ("注入了", 1.6), ("展现出", 1.3), ("呈现出", 1.3), ("折射出", 1.6), ("扮演着", 1.8), ("发挥着", 1.6), ("在当今", 2.0), ("随着科技", 1.9), ("悄然", 1.6), ("支离破碎", 1.6), ("延迟满足", 1.7), ("情绪内耗", 1.8), ("课题分离", 1.8), ("生活质感", 1.9), ("庸常瞬间", 2.0), ("或许所谓的", 2.1), ("温和抵抗", 1.9), ("精神锚点", 2.0), ("说到底,", 1.3), ("很多人以为", 1.5), ("總而言之", 2.2), ("綜上所述", 2.2), ("扮演著", 1.8), ("發揮著", 1.6), ("至關重要", 1.8), ("不可或缺", 1.6), ("多維度", 1.9), ("生態閉環", 2.2), ("底層邏輯", 1.9), ("這意味著", 1.5), ("換句話說", 1.4), ("在此背景下", 1.9), ("與此同時", 1.4), ]; /// Japanese RLHF markers (GPT-4o / Claude / DeepSeek Japanese prose). const JA_RLHF_MARKERS: &[(&str, f64)] = &[ ("重要な点として", 2.2), ("特筆すべき", 2.0), ("結論として", 2.0), ("総じて言えば", 2.1), ("言い換えれば", 1.5), ("すなわち、", 1.3), ("このように、", 1.3), ("その一方で", 1.3), ("にとどまらず", 1.7), ("重要な役割を果たし", 2.1), ("不可欠な要素", 1.9), ("多面的な視点", 2.1), ("包括的な", 1.7), ("持続可能な", 1.5), ("急速に進化", 2.0), ("パラダイム", 1.8), ("浮き彫りに", 1.6), ("再定義", 1.6), ("枠組み", 1.3), ]; /// Output of the proxy language model & RLHF syntactic scorer. #[derive(Debug, Clone)] pub struct ProxyLmAnalysis { /// Document-level RLHF lexical & syntactic log-odds AI score (`[0.0, 1.0]`). pub rlhf_discourse_score: UnitScore, /// Proxy language model predictability & cross-sentence surprisal flatness (`[0.0, 1.0]`). pub perplexity_flatness_score: UnitScore, /// Per-sentence proxy AI likelihood (`len == all_sentences.len()`). pub sentence_lm_scores: Vec, /// Per-sentence hit counts of RLHF frames/stems. pub sentence_hit_counts: Vec, /// Mean sentence proxy surprisal (`bits/token` equivalent). pub mean_surprisal_bits: f64, /// Cross-sentence surprisal coefficient of variation (low = flat AI perplexity). pub surprisal_cv: f64, /// Top matched RLHF phrases / syntactic frames for explainability UI. pub matched_signals: Vec, } fn push_unique_signal(out: &mut Vec, label: &str) { if out.len() < 12 && !out.iter().any(|s| s == label) { out.push(label.to_string()); } } /// Detects paired contrastive / negative-parallelism constructions inside a sentence. #[must_use] pub fn count_paired_contrast_frames(sent_lower: &str) -> (usize, Option<&'static str>) { const PAIRS: &[(&str, &str, &str)] = &[ ("不是", "而是", "不是…而是…"), ("并非", "而是", "并非…而是…"), ("不再是", "而", "不再是…而…"), ("从来不", "而", "从来不…而…"), ("从来不在", "藏在", "从来不在…就藏在…"), ("不在于", "而在于", "不在于…而在于…"), ("不只是", "更是", "不只是…更是…"), ("不仅仅是", "更是", "不仅仅是…更是…"), ("不仅是", "更是", "不仅是…更是…"), ("不仅", "而且", "不仅…而且…"), ("与其说", "不如说", "与其说…不如说…"), ("一方面", "另一方面", "一方面…另一方面…"), ("无论是", "还是", "无论是…还是…"), ("既要", "又要", "既要…又要…"), ("not only ", " but also ", "not only ... but also"), ("not just ", " but ", "not just ... but"), ("not merely ", " but ", "not merely ... but"), ( "not because ", " but because ", "not because ... but because", ), ("isn't ", "; it's ", "isn't X; it's Y"), ("isn't ", "—it's ", "isn't X—it's Y"), ("rather than ", ", ", "rather than ... contrast"), ("until ", ", they remain ", "until X, they remain Y"), ("単なる", "ではなく", "単なる…ではなく"), ("だけでなく", "もまた", "だけでなく…もまた"), ]; let mut hits = 0usize; let mut first_label = None; for &(left, right, label) in PAIRS { if let Some(pos) = sent_lower.find(left) { let after = pos.saturating_add(left.len()); if let Some(rest) = sent_lower.get(after..) { if rest.contains(right) { hits = hits.saturating_add(1); if first_label.is_none() { first_label = Some(label); } } } } } (hits, first_label) } /// Counts short conceptual scare-quotes (`“XX”` or `「XX」` wrapping 2–6 chars). #[must_use] fn count_conceptual_scare_quotes(text: &str) -> usize { let mut count = 0usize; for (open_q, close_q) in [('“', '”'), ('「', '」')] { let mut rest = text; while let Some(start) = rest.find(open_q) { let after_open = start.saturating_add(open_q.len_utf8()); let Some(tail) = rest.get(after_open..) else { break; }; let Some(end) = tail.find(close_q) else { break; }; if let Some(inner) = tail.get(..end) { let char_len = inner.chars().count(); let has_punct = inner .chars() .any(|c| matches!(c, ',' | '。' | '!' | '?' | ',' | '.' | ':')); if (2..=6).contains(&char_len) && !has_punct { count = count.saturating_add(1); } } let next_start = end.saturating_add(close_q.len_utf8()); rest = tail.get(next_start..).unwrap_or(""); } } count } fn cjk_clause_surprisal(sentence: &str) -> f64 { const CJK_ABSTRACT: &[char] = &[ '化', '性', '度', '体', '系', '机', '制', '模', '式', '赋', '维', '环', '态', '域', '层', '构', '筑', '塑', ]; const CJK_SPOKEN_STANCE: &[&str] = &[ "我觉得", "我覺得", "我喜欢", "我喜歡", "我不在乎", "我是", "我们做", "我們做", "咱们", "咱們", "说不定", "說不定", "实话说", "實話說", "可惜", "私", "僕", "思います", "信じています", "可愛い", "んです", "わけです", ]; let chars: Vec = sentence.chars().filter(|c| !c.is_whitespace()).collect(); let total = chars.len().max(1); let abs_cnt = chars.iter().filter(|c| CJK_ABSTRACT.contains(c)).count(); let abs_ratio = (abs_cnt as f64) / (total as f64); let mut delta = 0.0f64; if abs_ratio >= 0.07 { delta -= (abs_ratio * 5.0).min(0.68); } if CJK_SPOKEN_STANCE.iter().any(|&s| sentence.contains(s)) { delta += 0.54; } else if sentence.contains('我') || sentence.contains('你') { delta += 0.28; } let clauses: Vec = sentence .split([',', ',', '、', ';']) .map(|cl| cl.chars().filter(|c| !c.is_whitespace()).count()) .filter(|&len| len > 0) .collect(); if clauses.len() >= 3 { let mean_cl = (clauses.iter().sum::() as f64) / (clauses.len() as f64); if clauses.iter().all(|&c| (8..=22).contains(&c)) && (10.5..=18.5).contains(&mean_cl) { delta -= 0.42; } } delta } fn alpha_clause_surprisal(sentence: &str) -> f64 { const FIRST_PERSON: &[&str] = &[ "i", "i'm", "i've", "i'd", "i'll", "my", "me", "we", "we're", "we've", "our", "us", "you", "you're", "your", ]; const RLHF_GERUNDS: &[&str] = &[ "fostering", "navigating", "leveraging", "streamlining", "reshaping", "embracing", "cultivating", "empowering", "underscoring", "prioritizing", "optimizing", "unlocking", "bridging", "harnessing", ]; let raw_words: Vec<&str> = sentence .split(|c: char| !c.is_alphabetic() && c != '\'') .filter(|w| !w.is_empty()) .collect(); let total = raw_words.len().max(1); let words: Vec = raw_words.iter().map(|w| w.to_lowercase()).collect(); let nom_cnt = words .iter() .filter(|w| { RLHF_GERUNDS.contains(&w.as_str()) || (w.len() >= 8 && (w.ends_with("tion") || w.ends_with("tions") || w.ends_with("ment") || w.ends_with("ments") || w.ends_with("ity") || w.ends_with("ities") || w.ends_with("ness"))) }) .count(); let has_stance = words.iter().any(|w| FIRST_PERSON.contains(&w.as_str())); let proper_nouns = raw_words .iter() .skip(1) .filter(|w| w.len() >= 3 && w.chars().next().map(char::is_uppercase).unwrap_or(false)) .count(); let nom_ratio = (nom_cnt as f64) / (total as f64); let mut delta = 0.0f64; if nom_ratio >= 0.10 { delta -= (nom_ratio * 3.4).min(0.68); } if total >= 13 && !has_stance && proper_nouns == 0 { delta -= 0.34; } if has_stance { delta += 0.36; } if proper_nouns >= 1 { delta += (proper_nouns as f64 * 0.18).min(0.42); } if sentence.contains('(') || sentence.contains("...") || sentence.contains(';') { delta += 0.24; } delta } /// Estimates proxy surprisal (in bits per token equivalent) for a single prose sentence. #[must_use] pub fn estimate_sentence_surprisal_bits(sentence: &str, script: ScriptFamily) -> f64 { const HUMAN_COLLOQUIAL: &[&str] = &[ "wait", "honestly", "literally", "weird", "crazy", "damn", "ugh", "btw", "imo", "tbh", "gonna", "wanna", "kinda", "sorta", "heck", "nope", "yep", "folks", "居然", "简直", "离谱", "吐槽", "折腾", "压根", "说白了", "算了", "哈哈", "偏偏", "硬是", "真绝", "干脆", "莫名其妙", "说实话", "毛病", "狂刷", "搞明白", "抽风", "老头儿", "泥巴", "嘎嘣", "老婆", "笑话", "哪有", "钟头", "鐘頭", "離譜", "古怪", "遣散", "訴苦", "发呆", "發呆", "没边儿", "愣半天", "turns out", "sure—", "barely", "declined to", "pretend", "fool ", "まさか", "ぶっちゃけ", "なんか", "やばい", "しかめ面", "タクシードライバー", ]; let mut surprisal = 4.60f64; surprisal += if script.uses_ideographic_cadence() { cjk_clause_surprisal(sentence) } else { alpha_clause_surprisal(sentence) }; let digit_groups = sentence .split(|c: char| !c.is_ascii_digit()) .filter(|s| !s.is_empty()) .count(); if digit_groups >= 2 { surprisal += 0.46; } else if digit_groups == 1 { surprisal += 0.18; } if sentence .chars() .any(|c| matches!(c, '?' | '!' | '?' | '!' | '`' | '/')) { surprisal += 0.44; } let lower = sentence.to_lowercase(); if HUMAN_COLLOQUIAL.iter().any(|&kw| lower.contains(kw)) { surprisal += 0.88; } surprisal.clamp(2.4, 8.2) } fn accumulate_english_odds(lower_full: &str, signals: &mut Vec) -> f64 { let mut odds = 0.0f64; for word in lower_full.split(|c: char| !c.is_alphabetic()) { if word.is_empty() { continue; } for &(stem, w) in EN_RLHF_WORDS { if word == stem { odds += w; push_unique_signal(signals, stem); break; } } } for &(frame, w) in EN_RLHF_FRAMES { let cnt = lower_full.matches(frame).count(); if cnt > 0 { odds += w * (cnt as f64).min(4.0); push_unique_signal(signals, frame.trim_matches(|c: char| c == ',' || c == ' ')); } } odds } fn accumulate_cjk_odds(full_text: &str, signals: &mut Vec) -> f64 { let mut odds = 0.0f64; for &(marker, w) in ZH_RLHF_MARKERS.iter().chain(JA_RLHF_MARKERS.iter()) { let cnt = full_text.matches(marker).count(); if cnt > 0 { odds += w * (cnt as f64).min(4.0); push_unique_signal(signals, marker); } } let scare_quotes = count_conceptual_scare_quotes(full_text); let char_k = (full_text.chars().count().max(120) as f64) / 1000.0; let sq_per_k = (scare_quotes as f64) / char_k; if scare_quotes >= 3 && sq_per_k >= 4.0 { odds += ((sq_per_k - 3.0) * 0.45).min(4.5); push_unique_signal(signals, "“概念双引号”高频修饰"); } odds } fn accumulate_markdown_odds(full_text: &str, signals: &mut Vec) -> f64 { let mut headings = 0usize; let mut bold_bullets = 0usize; let mut plain_bullets = 0usize; for line in full_text.lines() { let t = line.trim_start(); if t.starts_with("# ") || t.starts_with("## ") || t.starts_with("### ") { headings = headings.saturating_add(1); } else if t.starts_with("- ") || t.starts_with("* ") || t.starts_with("1. ") || t.starts_with("2. ") || t.starts_with("3. ") || t.starts_with("4. ") { plain_bullets = plain_bullets.saturating_add(1); if t.contains("**:") || t.contains("**:") || t.contains("** —") || t.contains("** -") { bold_bullets = bold_bullets.saturating_add(1); } } } if bold_bullets >= 2 { push_unique_signal(signals, "Markdown **Bold**: List"); 2.6 + ((bold_bullets as f64) * 0.75).min(3.6) } else if headings >= 2 && plain_bullets >= 3 { 1.9 } else if headings >= 3 { 1.1 } else { 0.0 } } fn score_single_sentence(sent: &str, script: ScriptFamily) -> (f64, usize) { let s_low = sent.to_lowercase(); let (mut s_hits, _) = count_paired_contrast_frames(&s_low); if !matches!(script, ScriptFamily::Cjk) { s_hits = s_hits.saturating_add( EN_RLHF_FRAMES .iter() .filter(|&&(f, _)| s_low.contains(f)) .count(), ); s_hits = s_hits.saturating_add( s_low .split(|c: char| !c.is_alphabetic()) .filter(|w| EN_RLHF_WORDS.iter().any(|&(st, _)| &st == w)) .count(), ); } if script.uses_ideographic_cadence() { s_hits = s_hits.saturating_add( ZH_RLHF_MARKERS .iter() .chain(JA_RLHF_MARKERS.iter()) .filter(|&&(m, _)| sent.contains(m)) .count(), ); } let s_bits = estimate_sentence_surprisal_bits(sent, script); let prob = (0.54 + (4.58 - s_bits) * 0.42 + (s_hits as f64) * 0.17).clamp(0.03, 0.98); (prob, s_hits) } fn accumulate_rhetorical_cadence_odds( lower_full: &str, prose_sentences: &[String], script: ScriptFamily, signals: &mut Vec, ) -> f64 { let mut odds = 0.0f64; let mut consec_short_decl = 0usize; let mut max_consec_short = 0usize; let mut consec_questions = 0usize; let mut max_consec_q = 0usize; for s in prose_sentences { let trimmed = s.trim(); let wc = trimmed .split(|c: char| !c.is_alphanumeric()) .filter(|w| !w.is_empty()) .count(); if trimmed.ends_with('.') && (2..=4).contains(&wc) && !script.uses_ideographic_cadence() { consec_short_decl = consec_short_decl.saturating_add(1); max_consec_short = max_consec_short.max(consec_short_decl); } else { consec_short_decl = 0; } if trimmed.ends_with('?') || trimmed.ends_with('?') { consec_questions = consec_questions.saturating_add(1); max_consec_q = max_consec_q.max(consec_questions); } else { consec_questions = 0; } } if max_consec_short >= 2 { odds += 2.9; push_unique_signal(signals, "Staccato Triplet Rhythm"); } if max_consec_q >= 2 { odds += 2.2; push_unique_signal(signals, "Rhetorical Question Series"); } if lower_full.contains("everyone talks about") && lower_full.contains("nobody talks about") { odds += 2.6; push_unique_signal(signals, "everyone talks / nobody talks"); } odds } /// Evaluates full document and sentence-level proxy LM & RLHF stylometric signals. #[must_use] pub fn evaluate_proxy_lm( full_text: &str, prose_sentences: &[String], all_sentences: &[String], script: ScriptFamily, inspect_markdown: bool, ) -> ProxyLmAnalysis { let lower_full = full_text.to_lowercase(); let mut matched_signals: Vec = Vec::new(); let mut total_log_odds = 0.0f64; if !matches!(script, ScriptFamily::Cjk) { total_log_odds += accumulate_english_odds(&lower_full, &mut matched_signals); } if script.uses_ideographic_cadence() { total_log_odds += accumulate_cjk_odds(full_text, &mut matched_signals); } for sent in all_sentences { let (cnt, lbl) = count_paired_contrast_frames(&sent.to_lowercase()); if cnt > 0 { total_log_odds += (cnt as f64) * 1.95; if let Some(label_str) = lbl { push_unique_signal(&mut matched_signals, label_str); } } } total_log_odds += accumulate_rhetorical_cadence_odds( &lower_full, prose_sentences, script, &mut matched_signals, ); if inspect_markdown { total_log_odds += accumulate_markdown_odds(full_text, &mut matched_signals); } let eff_sents = ((prose_sentences.len().max(2)) as f64).powf(0.76); let odds_density = total_log_odds / eff_sents; let rlhf_discourse_score = UnitScore::clamped(1.0 / (1.0 + (-1.45 * (odds_density - 0.78)).exp())); let eval_pool = if prose_sentences.is_empty() { all_sentences } else { prose_sentences }; let surprisals: Vec = eval_pool .iter() .map(|s| estimate_sentence_surprisal_bits(s, script)) .collect(); let mean_surprisal_bits = if surprisals.is_empty() { 4.5 } else { surprisals.iter().sum::() / (surprisals.len() as f64) }; let surprisal_cv = if surprisals.len() >= 2 { let var = surprisals .iter() .map(|&x| (x - mean_surprisal_bits).powi(2)) .sum::() / (surprisals.len() as f64); var.sqrt() / mean_surprisal_bits.max(1.0) } else { 0.10 }; let low_ppl_signal = (4.58 - mean_surprisal_bits).clamp(-1.2, 1.2) * 0.46; let flat_cv_signal = (0.12 - surprisal_cv).clamp(-0.12, 0.10) * 2.8; let perplexity_flatness_score = UnitScore::clamped(0.52 + low_ppl_signal + flat_cv_signal); let mut sentence_lm_scores = Vec::with_capacity(all_sentences.len()); let mut sentence_hit_counts = Vec::with_capacity(all_sentences.len()); for sent in all_sentences { let (p, h) = score_single_sentence(sent, script); sentence_lm_scores.push(p); sentence_hit_counts.push(h); } ProxyLmAnalysis { rlhf_discourse_score, perplexity_flatness_score, sentence_lm_scores, sentence_hit_counts, mean_surprisal_bits, surprisal_cv, matched_signals, } }