Run this model with HF Jobs

Run ElderRyan/proseguard on Hugging Face's managed compute, monitor its progress, and retrieve the results when it's done.

Paste one of these prompts into your coding agent:

Fine-tune on my dataset

Use HF Jobs to fine-tune https://huggingface.co/ElderRyan/proseguard. Ask me which dataset to train on, then push the fine-tuned model to a new model repo. Run `hf jobs --help` first to learn the CLI.

Run batch inference

Use HF Jobs to run batch inference with https://huggingface.co/ElderRyan/proseguard on the inputs in a mounted HF Bucket. Ask me which Bucket to use, then write the outputs back to it and keep each input ID. Run `hf jobs --help` first to learn the CLI.
proseguard / ml /rust_src /src /hash_tables.rs
ElderRyan's picture
Release unified ProseGuard model suite (ml + mmbert-small + mmbert-base)
1ddf025 verified
Raw History Blame Contribute Delete
19.4 kB
//! Quantized Dual-Distribution PPM Context Model, Liang et al. (ICML 2024) Mixture MLE Solver,
//! and Feature-Hashed Multilingual N-gram NBSVM (`hash_tables`).
//!
//! Basis:
//! - `DualPpmTable`: Covers local sequential predictability $\Delta H(x_t \mid x_{<t})$ and emits
//! empirical human conditional surprisal stream $s_t = -\log_2 P_{\text{Human}}(x_t \mid x_{<t})$.
//! - `MixtureMleTable`: Covers global/local vocabulary shift $(1-\alpha)P(v) + \alpha Q(v)$ via
//! strictly concave Newton-Raphson MLE on $[0, 1]$.
//! - `NbSvmTable`: Covers sparse multilingual character (3-5 gram) and word (1-2 gram) linear margins.
//!
//! Tightness: `MlTablesView::from_bytes` validates exact magic header and byte length (`327,696` bytes)
//! at construction; all bucket lookups mask by `BUCKET_MASK = 0xFFFF` with checked `.get()`.
use std::collections::BTreeMap;
use crate::model::{DetectError, ScriptFamily};
use crate::stylometry::is_cjk_or_kana;
/// Number of feature-hash buckets per statistical table (`2^16 = 65,536`).
pub const BUCKET_COUNT: usize = 65_536;
/// Bitmask for `BUCKET_COUNT`.
pub const BUCKET_MASK: usize = BUCKET_COUNT - 1;
/// Exact binary byte length of `weights/ml_tables.bin`.
pub const ML_TABLES_BYTE_LEN: usize = 16 + BUCKET_COUNT * 2 + BUCKET_COUNT * 2 + BUCKET_COUNT;
/// Magic 8-byte header identifying `ml_tables.bin` format v2.
pub const ML_TABLES_MAGIC: &[u8; 8] = b"AIDML02\0";
/// Domain-separation seeds for SplitMix64 feature hashing.
pub const SEED_PPM_ORD1: u64 = 0x9E37_79B9_7F4A_7C15;
/// Second-order context seed for Dual PPM.
pub const SEED_PPM_ORD2: u64 = 0xBF58_476D_1CE4_E5B9;
/// Third-order context seed for Dual PPM.
pub const SEED_PPM_ORD3: u64 = 0x94D0_49BB_1331_11EB;
/// Unigram vocabulary seed for Mixture MLE.
pub const SEED_MLE_UNI: u64 = 0xD6E8_FEB8_6659_FD93;
/// Bigram vocabulary seed for Mixture MLE.
pub const SEED_MLE_BI: u64 = 0xA5A3_5625_AA0F_3B2D;
/// Character 3-gram seed for NBSVM.
pub const SEED_NBSVM_C3: u64 = 0x517C_C1B7_2722_0A95;
/// Character 4-gram seed for NBSVM.
pub const SEED_NBSVM_C4: u64 = 0x2545_F491_4F6C_DD1D;
/// Word unigram seed for NBSVM.
pub const SEED_NBSVM_W1: u64 = 0xC6BC_2796_92B5_C323;
/// Word bigram seed for NBSVM.
pub const SEED_NBSVM_W2: u64 = 0x8CB9_2BA7_2F3D_8DD7;
/// Validated zero-copy view over the `327,696`-byte quantized ML statistical tables.
#[derive(Debug, Clone, Copy)]
pub struct MlTablesView<'a> {
ppm_bytes: &'a [u8],
mle_bytes: &'a [u8],
nbsvm_bytes: &'a [u8],
nbsvm_bias: f64,
nbsvm_scale: f64,
}
impl<'a> MlTablesView<'a> {
/// Validates magic bytes and slice offsets to construct a panic-free `MlTablesView`.
///
/// Post: `Ok(view)` guarantees `ppm_bytes.len() == 131072`, `mle_bytes.len() == 131072`,
/// and `nbsvm_bytes.len() == 65536`.
pub fn from_bytes(raw: &'a [u8]) -> Result<Self, DetectError> {
if raw.len() != ML_TABLES_BYTE_LEN {
return Err(DetectError::NullOrInvalidBuffer);
}
let Some(magic) = raw.get(0..8) else {
return Err(DetectError::NullOrInvalidBuffer);
};
if magic != ML_TABLES_MAGIC {
return Err(DetectError::NullOrInvalidBuffer);
}
let bias = read_f32_le(raw, 8).unwrap_or(0.0);
let scale = read_f32_le(raw, 12).unwrap_or(1.0 / 32.0);
let ppm_end = 16 + BUCKET_COUNT * 2;
let mle_end = ppm_end + BUCKET_COUNT * 2;
let nbsvm_end = mle_end + BUCKET_COUNT;
let (Some(ppm_bytes), Some(mle_bytes), Some(nbsvm_bytes)) = (
raw.get(16..ppm_end),
raw.get(ppm_end..mle_end),
raw.get(mle_end..nbsvm_end),
) else {
return Err(DetectError::NullOrInvalidBuffer);
};
Ok(Self {
ppm_bytes,
mle_bytes,
nbsvm_bytes,
nbsvm_bias: f64::from(bias),
nbsvm_scale: if scale.abs() < 1e-7 {
1.0 / 32.0
} else {
f64::from(scale)
},
})
}
/// Looks up `(llr_bits, human_surprisal_bits)` for a Dual-PPM context bucket.
#[inline]
#[must_use]
pub fn lookup_ppm(self, bucket: u16) -> (f64, f64) {
let base = (usize::from(bucket) & BUCKET_MASK) * 2;
let llr_q = self.ppm_bytes.get(base).copied().unwrap_or(0) as i8;
let surp_q = self.ppm_bytes.get(base + 1).copied().unwrap_or(90);
((f64::from(llr_q)) / 24.0, (f64::from(surp_q)) / 18.0)
}
/// Looks up `(p_human, q_ai)` unnormalized probabilities for Mixture MLE.
#[inline]
#[must_use]
pub fn lookup_mle_probs(self, bucket: u16) -> (f64, f64) {
let base = (usize::from(bucket) & BUCKET_MASK) * 2;
let nll_h = 2.0 + f64::from(self.mle_bytes.get(base).copied().unwrap_or(160)) / 20.0;
let nll_a = 2.0 + f64::from(self.mle_bytes.get(base + 1).copied().unwrap_or(160)) / 20.0;
((-nll_h).exp(), (-nll_a).exp())
}
/// Looks up signed NBSVM weight for a hashed n-gram bucket, with sign-hash collision cancellation.
#[inline]
#[must_use]
pub fn lookup_nbsvm_weight(self, hash64: u64) -> f64 {
let bucket = (hash64 as usize) & BUCKET_MASK;
let sign = if ((hash64 >> 32) & 1) == 0 { 1.0 } else { -1.0 };
let w_q = self.nbsvm_bytes.get(bucket).copied().unwrap_or(0) as i8;
sign * f64::from(w_q) * self.nbsvm_scale
}
/// Returns the learned NBSVM intercept bias.
#[inline]
#[must_use]
pub const fn nbsvm_bias(self) -> f64 {
self.nbsvm_bias
}
}
fn read_f32_le(buf: &[u8], offset: usize) -> Option<f32> {
let b0 = *buf.get(offset)?;
let b1 = *buf.get(offset + 1)?;
let b2 = *buf.get(offset + 2)?;
let b3 = *buf.get(offset + 3)?;
Some(f32::from_le_bytes([b0, b1, b2, b3]))
}
/// Pure SplitMix64-avalanched FNV-style byte mixer.
#[inline]
#[must_use]
pub const fn mix64(mut z: u64) -> u64 {
z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
z ^ (z >> 31)
}
/// Hashes a sequence of `u32` codepoints or token hashes under a domain seed.
#[inline]
#[must_use]
pub fn hash_u32_seq(seed: u64, items: &[u32]) -> u64 {
let mut h = seed;
for &x in items {
h = mix64(h ^ u64::from(x).wrapping_mul(0x9E37_79B9_7F4A_7C15));
}
h
}
/// Hashes a lowercase UTF-8 token under a domain seed.
#[inline]
#[must_use]
pub fn hash_token_str(seed: u64, s: &str) -> u32 {
let mut h = seed;
for b in s.bytes() {
h = h.wrapping_mul(0x0100_0000_01B3) ^ u64::from(b);
}
let mixed = mix64(h);
(mixed as u32) ^ ((mixed >> 32) as u32)
}
/// Canonicalizes high-frequency Traditional Chinese ideographs to Simplified equivalents
/// so `zh-Hant` and `zh-Hans` share unified CJK statistical density without loss.
#[must_use]
pub const fn canonical_cjk(ch: char) -> char {
match ch {
'體' => '体',
'學' => '学',
'讀' => '读',
'實' => '实',
'這' => '这',
'說' => '说',
'們' => '们',
'會' => '会',
'對' => '对',
'個' => '个',
'時' => '时',
'過' => '过',
'為' => '为',
'來' => '来',
'發' => '发',
'動' => '动',
'機' => '机',
'經' => '经',
'現' => '现',
'點' => '点',
'開' => '开',
'關' => '关',
'問' => '问',
'題' => '题',
'進' => '进',
'還' => '还',
'讓' => '让',
'從' => '从',
'當' => '当',
'應' => '应',
'長' => '长',
'間' => '间',
'樣' => '样',
'種' => '种',
'與' => '与',
'無' => '无',
'數' => '数',
'變' => '变',
'結' => '结',
'構' => '构',
'論' => '论',
'語' => '语',
'電' => '电',
'腦' => '脑',
'網' => '网',
'絡' => '络',
'軟' => '软',
'資' => '资',
'訊' => '讯',
'處' => '处',
'際' => '际',
'態' => '态',
'層' => '层',
'維' => '维',
'環' => '环',
'閉' => '闭',
'輯' => '辑',
'顯' => '显',
'著' => '着',
'轉' => '转',
'傳' => '传',
'統' => '统',
'設' => '设',
'計' => '计',
'驗' => '验',
'證' => '证',
'據' => '据',
'優' => '优',
'質' => '质',
'書' => '书',
'寫' => '写',
'認' => '认',
'識' => '识',
'覺' => '觉',
'頭' => '头',
'見' => '见',
'聽' => '听',
'觀' => '观',
'業' => '业',
'務' => '务',
'產' => '产',
'品' => '品',
'術' => '术',
'連' => '连',
'接' => '接',
'選' => '选',
'擇' => '择',
'境' => '境',
'複' => '复',
'雜' => '杂',
'簡' => '简',
'單' => '单',
'獨' => '独',
'創' => '创',
'義' => '义',
'價' => '价',
'值' => '值',
'報' => '报',
'導' => '导',
'標' => '标',
'準' => '准',
'確' => '确',
'決' => '决',
'議' => '议',
'專' => '专',
'門' => '门',
'區' => '区',
'塊' => '块',
'鏈' => '链',
'節' => '节',
'約' => '约',
'規' => '规',
'則' => '则',
'範' => '范',
'圍' => '围',
'廣' => '广',
'東' => '东',
'車' => '车',
'馬' => '马',
'風' => '风',
'雲' => '云',
'飛' => '飞',
'氣' => '气',
'力' => '力',
other => other,
}
}
/// Summary outputs produced by scanning text through `DualPpmTable`, `MixtureMleTable`, and `NbSvmTable`.
#[derive(Debug, Clone)]
pub struct HashModelScan {
/// Interpolated mean PPM log-likelihood ratio (`bits`, positive = AI-like).
pub ppm_mean_llr: f64,
/// Order-1 (bigram) mean PPM log-likelihood ratio.
pub ppm_ord1_llr: f64,
/// Order-3 (trigram/4-gram) mean PPM log-likelihood ratio.
pub ppm_ord3_llr: f64,
/// Token/unit-level conditional human surprisal sequence $s_1, \dots, s_T$ for DivEye.
pub surprisal_stream: Vec<f64>,
/// Global document Mixture MLE $\hat{\alpha} \in [0, 1]$ (Liang et al., ICML 2024).
pub mle_alpha_hat: f64,
/// Fisher curvature information $I(\hat{\alpha})$ of the MLE estimate.
pub mle_fisher_info: f64,
/// Mean lexical excess log-likelihood ratio $\frac{1}{N} \sum \ln(Q(v)/P(v))$.
pub mle_mean_llr: f64,
/// Global document Feature-Hashed NBSVM log-odds margin.
pub nbsvm_margin: f64,
}
/// Semantic predicate: returns `true` if `text` contains Japanese Hiragana or Katakana.
#[must_use]
pub fn contains_japanese_kana(text: &str) -> bool {
text.chars().any(|c| ('\u{3040}'..='\u{30FF}').contains(&c))
}
/// Extracts normalized word/CJK-unit sequence (`u32` token hashes) for PPM & MLE models.
/// Applies a disjoint domain salt for Japanese (Kana-bearing) prose so shared Kanji never
/// collide with Chinese corpus buckets.
#[must_use]
pub fn tokenize_units_u32(text: &str, script: ScriptFamily) -> Vec<u32> {
let is_ja = contains_japanese_kana(text);
let ja_mask: u32 = if is_ja { 0x4A41_0000 } else { 0 };
let word_seed: u64 = if is_ja { 0x4A41_1234_5678 } else { 0x1234_5678 };
let mut units = Vec::new();
let mut word_buf = String::new();
for raw_ch in text.chars() {
let ch = if is_ja { raw_ch } else { canonical_cjk(raw_ch) };
if is_cjk_or_kana(ch) {
if !word_buf.is_empty() {
units.push(hash_token_str(word_seed, &word_buf));
word_buf.clear();
}
units.push((ch as u32) ^ ja_mask);
} else if ch.is_alphanumeric() || ch == '\'' {
for lc in ch.to_lowercase() {
word_buf.push(lc);
}
} else {
if !word_buf.is_empty() {
units.push(hash_token_str(word_seed, &word_buf));
word_buf.clear();
}
let keep_punct = (!script.uses_ideographic_cadence()
&& matches!(ch, ',' | '.' | ';' | ':' | '?' | '!' | '-'))
|| (script.uses_ideographic_cadence()
&& matches!(ch, ',' | '。' | '、' | ';' | ':' | '?' | '!'));
if keep_punct {
units.push(0x8000_0000 | ((ch as u32) ^ ja_mask));
}
}
}
if !word_buf.is_empty() {
units.push(hash_token_str(word_seed, &word_buf));
}
units
}
/// Emits formatting-invariant hashed n-gram counts (word/CJK 1-3 grams + intra-word stems,
/// completely invariant to `\n\n` paragraph breaks and scraping whitespace) for NBSVM.
#[must_use]
pub fn extract_nbsvm_features(text: &str) -> BTreeMap<u64, u32> {
let mut counts: BTreeMap<u64, u32> = BTreeMap::new();
let units = tokenize_units_u32(text, ScriptFamily::Hybrid);
for &u in units.iter().take(16_000) {
let h = hash_u32_seq(SEED_NBSVM_W1, &[u]);
let entry = counts.entry(h).or_insert(0);
*entry = entry.saturating_add(1);
}
for w2 in units.windows(2).take(16_000) {
let h = hash_u32_seq(SEED_NBSVM_W2, w2);
let entry = counts.entry(h).or_insert(0);
*entry = entry.saturating_add(1);
}
for w3 in units.windows(3).take(16_000) {
let h = hash_u32_seq(SEED_NBSVM_C3, w3);
let entry = counts.entry(h).or_insert(0);
*entry = entry.saturating_add(1);
}
for w4 in units.windows(4).take(12_000) {
let h = hash_u32_seq(SEED_NBSVM_C4, w4);
let entry = counts.entry(h).or_insert(0);
*entry = entry.saturating_add(1);
}
counts
}
/// Solves Liang et al. (ICML 2024) strictly concave mixture log-likelihood
/// $\max_{\alpha \in [0, 1]} \sum_b c_b \ln((1-\alpha) P_b + \alpha Q_b)$ via safeguarded Newton-Raphson.
///
/// Law: Concavity ($\mathcal{L}''(\alpha) \le 0$) guarantees unique global maximum on $[0, 1]$.
#[must_use]
pub fn solve_mixture_mle(
bucket_counts: &BTreeMap<u16, u32>,
tables: MlTablesView<'_>,
) -> (f64, f64, f64) {
if bucket_counts.is_empty() {
return (0.5, 0.0, 0.0);
}
let mut items: Vec<(f64, f64, f64)> = Vec::with_capacity(bucket_counts.len());
let mut total_cnt = 0.0f64;
let mut sum_llr = 0.0f64;
for (&b, &cnt) in bucket_counts {
let (p, q) = tables.lookup_mle_probs(b);
let c = f64::from(cnt);
total_cnt += c;
sum_llr += c * (q.max(1e-12) / p.max(1e-12)).ln();
items.push((c, p, q));
}
let mean_llr = sum_llr / total_cnt.max(1.0);
// Evaluate gradient at boundaries first (exact KKT check on [0, 1]!)
let grad_at = |a: f64| -> (f64, f64) {
let mut g1 = 0.0f64;
let mut g2 = 0.0f64;
for &(c, p, q) in &items {
let diff = q - p;
let denom = ((1.0 - a) * p + a * q).max(1e-15);
let ratio = diff / denom;
g1 += c * ratio;
g2 -= c * ratio * ratio;
}
(g1, g2)
};
let (g0, g2_0) = grad_at(0.0);
if g0 <= 0.0 {
return (0.0, (-g2_0).max(0.0), mean_llr);
}
let (g1_end, g2_1) = grad_at(1.0);
if g1_end >= 0.0 {
return (1.0, (-g2_1).max(0.0), mean_llr);
}
let mut lo = 0.0f64;
let mut hi = 1.0f64;
let mut alpha = 0.5f64;
let mut last_fisher = 0.0f64;
for _ in 0..14 {
let (g, h) = grad_at(alpha);
last_fisher = (-h).max(0.0);
if g.abs() < 1e-7 {
break;
}
if g > 0.0 {
lo = alpha;
} else {
hi = alpha;
}
let newton = if h < -1e-12 {
alpha - g / h
} else {
0.5 * (lo + hi)
};
alpha = if newton > lo && newton < hi {
newton
} else {
0.5 * (lo + hi)
};
}
(alpha.clamp(0.0, 1.0), last_fisher, mean_llr)
}
/// Evaluates `DualPpmTable`, `MixtureMleTable`, and `NbSvmTable` over a text slice in a single pass.
#[must_use]
pub fn evaluate_hash_models(
text: &str,
script: ScriptFamily,
tables: MlTablesView<'_>,
) -> HashModelScan {
let units = tokenize_units_u32(text, script);
let mut surprisal_stream = Vec::with_capacity(units.len());
let mut sum_llr = 0.0f64;
let mut sum_ord1 = 0.0f64;
let mut sum_ord3 = 0.0f64;
let mut steps = 0usize;
let mut mle_counts: BTreeMap<u16, u32> = BTreeMap::new();
for (idx, &u) in units.iter().enumerate() {
let ub = (hash_u32_seq(SEED_MLE_UNI, &[u]) as u16) & (BUCKET_MASK as u16);
let e1 = mle_counts.entry(ub).or_insert(0);
*e1 = e1.saturating_add(1);
if idx >= 1 {
let prev1 = units.get(idx - 1).copied().unwrap_or(0);
let bb = (hash_u32_seq(SEED_MLE_BI, &[prev1, u]) as u16) & (BUCKET_MASK as u16);
let e2 = mle_counts.entry(bb).or_insert(0);
*e2 = e2.saturating_add(1);
let b1 = (hash_u32_seq(SEED_PPM_ORD1, &[prev1, u]) as u16) & (BUCKET_MASK as u16);
let (llr1, surp1) = tables.lookup_ppm(b1);
let (llr2, surp2) = if idx >= 2 {
let prev2 = units.get(idx - 2).copied().unwrap_or(0);
let b2 =
(hash_u32_seq(SEED_PPM_ORD2, &[prev2, prev1, u]) as u16) & (BUCKET_MASK as u16);
tables.lookup_ppm(b2)
} else {
(llr1, surp1)
};
let (llr3, surp3) = if idx >= 3 {
let prev3 = units.get(idx - 3).copied().unwrap_or(0);
let prev2 = units.get(idx - 2).copied().unwrap_or(0);
let b3 = (hash_u32_seq(SEED_PPM_ORD3, &[prev3, prev2, prev1, u]) as u16)
& (BUCKET_MASK as u16);
tables.lookup_ppm(b3)
} else {
(llr2, surp2)
};
let interp_llr = 0.30 * llr1 + 0.40 * llr2 + 0.30 * llr3;
let interp_surp = 0.30 * surp1 + 0.40 * surp2 + 0.30 * surp3;
sum_llr += interp_llr;
sum_ord1 += llr1;
sum_ord3 += llr3;
surprisal_stream.push(interp_surp);
steps = steps.saturating_add(1);
}
}
let denom = (steps.max(1)) as f64;
let (mle_alpha_hat, mle_fisher_info, mle_mean_llr) = solve_mixture_mle(&mle_counts, tables);
let nbsvm_feats = extract_nbsvm_features(text);
let mut raw_dot = tables.nbsvm_bias();
let norm = ((nbsvm_feats.len().max(1)) as f64).sqrt();
let mut sum_w = 0.0f64;
for (&h, &cnt) in &nbsvm_feats {
let tf = 1.0 + (f64::from(cnt)).ln();
sum_w += tf * tables.lookup_nbsvm_weight(h);
}
raw_dot += sum_w / norm;
HashModelScan {
ppm_mean_llr: sum_llr / denom,
ppm_ord1_llr: sum_ord1 / denom,
ppm_ord3_llr: sum_ord3 / denom,
surprisal_stream,
mle_alpha_hat,
mle_fisher_info,
mle_mean_llr,
nbsvm_margin: raw_dot,
}
}