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.
File size: 17,337 Bytes
1ddf025
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
//! ProseGuard Wasm (`prose_guard_wasm`) — Zero-Dependency Rust + WebAssembly Engine for
//! Client-Side AI-Generated Article Detection & Stylometric Forensics.
//!
//! Combines six orthogonal forensic signals inspired by open-source research:
//! 1. **ZipPy LZ77 Sliding-Window Compression Redundancy** (`lz_entropy`)
//! 2. **Binoculars Conditional Cross-Entropy Curvature Surrogate** (`lz_entropy`)
//! 3. **Sentence Cadence Burstiness & Local Alternation Variance** (`stylometry`)
//! 4. **GLTR 4-Band Lexical Predictability, MATTR-50 & Hapax Richness** (`stylometry`)
//! 5. **Multilingual LLM Discourse Templates & Markdown Structural Symmetry** (`stylometry`)
//! 6. **Invisible Unicode Watermark (`ZWSP`, `NNBSP`, `WJ`) & Sanitizer** (`watermark`)
//!
//! Security & Supply-Chain Invariant: `[dependencies]` in `Cargo.toml` is empty.

#![deny(missing_docs)]

pub mod cooccur_graph;
pub mod diveye;
pub mod gbdt;
pub mod hash_tables;
pub mod json_emit;
pub mod lm_proxy;
pub mod lz_entropy;
pub mod ml_features;
pub mod model;
pub mod stylometry;
pub mod trained_forest;
pub mod watermark;

use std::cell::RefCell;

use crate::json_emit::serialize_report_json;
use crate::model::{DetectError, DetectionConfig, GenrePreset, SensitivityMode, ValidatedArticle};
use crate::stylometry::analyze_article;
use crate::watermark::sanitize_text;

thread_local! {
    static REPORT_JSON_BUF: RefCell<String> = const { RefCell::new(String::new()) };
    static SANITIZED_TEXT_BUF: RefCell<String> = const { RefCell::new(String::new()) };
    static REMOVED_ZW_COUNT: RefCell<u32> = const { RefCell::new(0) };
    static NORMALIZED_SPACE_COUNT: RefCell<u32> = const { RefCell::new(0) };
    static ERROR_MSG_BUF: RefCell<String> = const { RefCell::new(String::new()) };
}

fn record_error(err: &DetectError) -> usize {
    ERROR_MSG_BUF.with(|slot| {
        *slot.borrow_mut() = err.to_string();
    });
    0
}

/// Computes IEEE 802.3 CRC-32 over a byte slice (`CRC32("123456789") == 0xCBF4_3926`).
#[must_use]
pub fn crc32_ieee(bytes: &[u8]) -> u32 {
    let mut crc = 0xFFFF_FFFFu32;
    for &byte in bytes {
        crc ^= u32::from(byte);
        for _ in 0..8 {
            let mask = (crc & 1).wrapping_neg();
            crc = (crc >> 1) ^ (0xEDB8_8320u32 & mask);
        }
    }
    !crc
}

// ============================================================================
// Named WebAssembly FFI Adapter Boundary
// ============================================================================

/// Allocates `size` bytes in WebAssembly linear memory and returns its base pointer.
#[no_mangle]
pub extern "C" fn wasm_alloc(size: usize) -> *mut u8 {
    if size == 0 {
        return core::ptr::null_mut();
    }
    let mut buf = Vec::<u8>::with_capacity(size);
    let ptr = buf.as_mut_ptr();
    core::mem::forget(buf);
    ptr
}

/// Reclaims a buffer previously allocated via `wasm_alloc(size)`.
///
/// # Safety
/// `ptr` must have been allocated by `wasm_alloc(size)` in the same linear memory instance
/// and must not be freed more than once.
#[no_mangle]
pub unsafe extern "C" fn wasm_dealloc(ptr: *mut u8, size: usize) {
    if !ptr.is_null() && size > 0 {
        // SAFETY: Upheld by caller (`withWasmBuffer` RAII wrapper in `wasm-loader.js`).
        let _ = unsafe { Vec::from_raw_parts(ptr, 0, size) };
    }
}

/// Runs IEEE 802.3 CRC-32 self-test across an FFI byte slice.
///
/// # Safety
/// If `len > 0`, `ptr` must point to `len` readable initialized bytes in Wasm linear memory.
#[no_mangle]
pub unsafe extern "C" fn wasm_crc32(ptr: *const u8, len: usize) -> u32 {
    if ptr.is_null() || len == 0 {
        return crc32_ieee(&[]);
    }
    // SAFETY: Caller guarantees `ptr..ptr+len` is valid in Wasm linear memory.
    let bytes = unsafe { core::slice::from_raw_parts(ptr, len) };
    crc32_ieee(bytes)
}

/// Pointer to the latest UTF-8 JSON forensic report written by `wasm_analyze_article`.
#[no_mangle]
pub extern "C" fn wasm_report_ptr() -> *const u8 {
    REPORT_JSON_BUF.with(|buf| buf.borrow().as_ptr())
}

/// Byte length of the latest UTF-8 JSON forensic report.
#[no_mangle]
pub extern "C" fn wasm_report_len() -> usize {
    REPORT_JSON_BUF.with(|buf| buf.borrow().len())
}

/// Pointer to the latest sanitized UTF-8 string produced by `wasm_sanitize_text`.
#[no_mangle]
pub extern "C" fn wasm_sanitized_ptr() -> *const u8 {
    SANITIZED_TEXT_BUF.with(|buf| buf.borrow().as_ptr())
}

/// Byte length of the latest sanitized UTF-8 string.
#[no_mangle]
pub extern "C" fn wasm_sanitized_len() -> usize {
    SANITIZED_TEXT_BUF.with(|buf| buf.borrow().len())
}

/// Count of zero-width watermark characters stripped in the last `wasm_sanitize_text` call.
#[no_mangle]
pub extern "C" fn wasm_removed_zw_count() -> u32 {
    REMOVED_ZW_COUNT.with(|c| *c.borrow())
}

/// Count of atypical spaces normalized in the last `wasm_sanitize_text` call.
#[no_mangle]
pub extern "C" fn wasm_normalized_space_count() -> u32 {
    NORMALIZED_SPACE_COUNT.with(|c| *c.borrow())
}

/// Pointer to the last UTF-8 error message if `wasm_analyze_article` returned `0`.
#[no_mangle]
pub extern "C" fn wasm_error_ptr() -> *const u8 {
    ERROR_MSG_BUF.with(|e| e.borrow().as_ptr())
}

/// Byte length of the last UTF-8 error message.
#[no_mangle]
pub extern "C" fn wasm_error_len() -> usize {
    ERROR_MSG_BUF.with(|e| e.borrow().len())
}

/// Analyzes a UTF-8 article in WebAssembly linear memory and writes the JSON forensic report.
/// Returns the report byte length on success, or `0` on domain validation error.
///
/// # Safety
/// If `len > 0`, `ptr` must reference `len` readable bytes in Wasm linear memory.
#[no_mangle]
pub unsafe extern "C" fn wasm_analyze_article(
    ptr: *const u8,
    len: usize,
    genre_code: u8,
    sensitivity_code: u8,
    inspect_watermarks: u8,
    inspect_markdown: u8,
) -> usize {
    if ptr.is_null() || len == 0 {
        return record_error(&DetectError::EmptyDocument);
    }
    // SAFETY: Caller (`withWasmBuffer`) allocated and populated `ptr..ptr+len`.
    let raw_bytes = unsafe { core::slice::from_raw_parts(ptr, len) };
    let Ok(raw_str) = core::str::from_utf8(raw_bytes) else {
        return record_error(&DetectError::InvalidUtf8);
    };

    let genre = match GenrePreset::from_code(genre_code) {
        Ok(g) => g,
        Err(e) => return record_error(&e),
    };
    let sensitivity = match SensitivityMode::from_code(sensitivity_code) {
        Ok(s) => s,
        Err(e) => return record_error(&e),
    };
    let validated = match ValidatedArticle::try_new(raw_str) {
        Ok(v) => v,
        Err(e) => return record_error(&e),
    };

    let cfg = DetectionConfig {
        genre,
        sensitivity,
        inspect_watermarks: inspect_watermarks != 0,
        inspect_markdown_symmetry: inspect_markdown != 0,
    };

    match analyze_article(validated, cfg) {
        Ok(report) => {
            let json = serialize_report_json(&report);
            let json_len = json.len();
            REPORT_JSON_BUF.with(|slot| {
                *slot.borrow_mut() = json;
            });
            json_len
        }
        Err(e) => record_error(&e),
    }
}

/// Strips invisible Unicode watermarks (`ZWSP`, `ZWNJ`, `ZWJ`, `WJ`, `BOM`) and normalizes
/// atypical LLM spaces (`U+202F`, `U+00A0`) to standard ASCII spaces.
/// Returns byte length of the sanitized UTF-8 buffer (or `0` if invalid UTF-8).
///
/// # Safety
/// If `len > 0`, `ptr` must reference `len` readable bytes in Wasm linear memory.
#[no_mangle]
pub unsafe extern "C" fn wasm_sanitize_text(ptr: *const u8, len: usize) -> usize {
    if ptr.is_null() || len == 0 {
        SANITIZED_TEXT_BUF.with(|slot| slot.borrow_mut().clear());
        REMOVED_ZW_COUNT.with(|c| *c.borrow_mut() = 0);
        NORMALIZED_SPACE_COUNT.with(|c| *c.borrow_mut() = 0);
        return 0;
    }
    // SAFETY: Caller (`withWasmBuffer`) allocated and populated `ptr..ptr+len`.
    let raw_bytes = unsafe { core::slice::from_raw_parts(ptr, len) };
    let Ok(raw_str) = core::str::from_utf8(raw_bytes) else {
        return record_error(&DetectError::InvalidUtf8);
    };

    let result = sanitize_text(raw_str);
    let out_len = result.cleaned.len();
    REMOVED_ZW_COUNT.with(|c| {
        *c.borrow_mut() = u32::try_from(result.removed_zero_width).unwrap_or(u32::MAX);
    });
    NORMALIZED_SPACE_COUNT.with(|c| {
        *c.borrow_mut() = u32::try_from(result.normalized_spaces).unwrap_or(u32::MAX);
    });
    SANITIZED_TEXT_BUF.with(|slot| {
        *slot.borrow_mut() = result.cleaned;
    });
    out_len
}

#[cfg(test)]
#[allow(clippy::expect_used)]
mod tests {
    use super::*;
    use crate::model::VerdictBand;
    use crate::watermark::{is_atypical_llm_space, is_zero_width_watermark};

    #[test]
    fn crc32_ieee_matches_standard_check_vector() {
        assert_eq!(crc32_ieee(b"123456789"), 0xCBF4_3926);
    }

    #[test]
    fn validation_rejects_empty_and_too_short_inputs_algebraically() {
        assert_eq!(
            ValidatedArticle::try_new("   \n\t "),
            Err(DetectError::EmptyDocument)
        );
        assert_eq!(
            ValidatedArticle::try_new("Too short"),
            Err(DetectError::TooShort {
                observed_chars: 8,
                minimum_chars: 12
            })
        );
    }

    // Law: forall s, sanitize_text(&sanitize_text(s).cleaned).cleaned == sanitize_text(s).cleaned
    #[test]
    fn sanitize_text_is_idempotent_and_erases_all_watermarks() {
        let fixtures = [
            "Hello\u{200B} world\u{202F}from\u{FEFF} LLM\u{2060} output\u{00A0}test!",
            "值得\u{200C}注意\u{200D}的是\u{202F}这是一段测试文本。",
            "Clean human sentence without hidden codepoints.",
        ];
        for sample in fixtures {
            let once = sanitize_text(sample);
            let twice = sanitize_text(&once.cleaned);
            assert_eq!(once.cleaned, twice.cleaned);
            assert_eq!(twice.removed_zero_width, 0);
            assert_eq!(twice.normalized_spaces, 0);
            assert!(!once
                .cleaned
                .chars()
                .any(|c| is_zero_width_watermark(c) || is_atypical_llm_space(c)));
        }
    }

    #[test]
    fn stereotypical_english_llm_essay_scores_substantially_higher_than_spiky_human_note() {
        let ai_essay = "\
In today's rapidly evolving landscape, artificial intelligence plays a pivotal role in transforming modern industries. \
Furthermore, it is important to note that organizations must delve into ethical frameworks to ensure sustainable innovation. \
Moreover, fostering a sense of transparency underscores the importance of responsible governance across global teams.\u{200B}\u{202F}\n\
- **Operational Efficiency**: Streamlining repetitive workflows across departments to maximize productivity.\n\
- **Strategic Alignment**: Navigating the complexities of digital transformation with a multifaceted approach.\n\
- **Scalable Architecture**: Building resilient pipelines that empower stakeholders across the ecosystem.\n\
In conclusion, embracing this paradigm shift is a testament to the enduring power of human-centric technology.";

        let human_note = "\
Clearly, this expenditure pattern is a massive misallocation of resources. \
The last 20% of network hashpower provides vastly less value to the ecosystem than those same resources would \
if they had gone into research and core protocol development. So why not just.... cut the PoW budget by 20% and redirect the funds to those other things instead? \
In early 2020, Justin Sun bought Steem-the-company, which is not the same thing as Steem-the-blockchain but did hold about 20% of the STEEM token supply.";

        let v_ai = ValidatedArticle::try_new(ai_essay).expect("valid ai sample");
        let v_hu = ValidatedArticle::try_new(human_note).expect("valid human sample");

        let rep_ai = analyze_article(v_ai, DetectionConfig::default()).expect("ai report");
        let rep_hu = analyze_article(v_hu, DetectionConfig::default()).expect("human report");

        assert!(
            rep_ai.overall_ai_score.get() > 0.72,
            "Expected high AI score, got {}",
            rep_ai.overall_ai_score.get()
        );
        assert_eq!(rep_ai.verdict, VerdictBand::AiGenerated);
        assert!(
            rep_hu.overall_ai_score.get() < 0.42,
            "Expected low AI score for spiky human prose, got {}",
            rep_hu.overall_ai_score.get()
        );
        assert!(rep_ai.overall_ai_score.get() > rep_hu.overall_ai_score.get() + 0.35);
    }

    #[test]
    fn chinese_llm_template_article_distinguished_from_colloquial_human_writing() {
        let zh_ai = "\
在当今快速发展的数字时代,人工智能正在各个领域扮演着至关重要的角色。值得注意的是,企业不仅需要关注底层算力的提升,\
而且还需要从多维度构建全方位的安全治理体系,从而实现真正的生态闭环。\u{200B}与此同时,如何平衡技术创新与隐私保护也是一把双刃剑。\
总而言之,综上所述,只有持续赋能核心业务场景,才能在激烈的市场竞争中立于不败之地。";

        let zh_human = "\
凌晨两点半被报警电话吵醒,爬起来一看又是上游那个祖传接口超时!明明上周五联调的时候拍胸脯说绝对抗得住三千并发,\
结果才刚切了十分之一流量,数据库连接池就直接打满躺平了。算了,先手动降级把队列消费停掉保命,明天早会必须把锅甩清楚。";

        let r_ai = analyze_article(
            ValidatedArticle::try_new(zh_ai).expect("valid zh ai"),
            DetectionConfig::default(),
        )
        .expect("zh ai report");
        let r_hu = analyze_article(
            ValidatedArticle::try_new(zh_human).expect("valid zh human"),
            DetectionConfig::default(),
        )
        .expect("zh human report");

        assert!(
            r_ai.overall_ai_score.get() > r_hu.overall_ai_score.get() + 0.25,
            "Expected Chinese AI text ({}) > Chinese human text ({})",
            r_ai.overall_ai_score.get(),
            r_hu.overall_ai_score.get()
        );
        assert!(r_ai.removable_watermark_chars >= 1);
    }

    // Law (Shapley Local Accuracy): forall x, expected_margin + sum_j shap[j] == unshifted_raw_margin(x)
    #[test]
    fn treeshap_satisfies_exact_local_accuracy_additivity_law() {
        use crate::gbdt::predict_with_treeshap;
        use crate::hash_tables::MlTablesView;
        use crate::ml_features::{extract_ml_features_with_tables, EMBEDDED_ML_TABLES};
        use crate::trained_forest::with_trained_gbdt;

        let tables = MlTablesView::from_bytes(EMBEDDED_ML_TABLES).expect("valid ml_tables.bin");
        let fixtures = [
            "Clearly, this expenditure pattern is a massive misallocation of resources across protocol development.",
            "In today's rapidly evolving landscape, artificial intelligence plays a pivotal role in fostering innovation.",
            "刚刚我在下面看了一下,一些吐槽我觉得特别好。每天都有五亿人在说我们做的不好。",
            "プログラミングは本来楽しいものであり、楽しいからこそ能力が向上するのだと私は思います。",
        ];
        for sample in fixtures {
            let bundle = extract_ml_features_with_tables(sample, true, tables);
            let pred = with_trained_gbdt(|gbdt| predict_with_treeshap(gbdt, &bundle.features, 0.0))
                .expect("valid gbdt");
            let shap_sum: f64 = pred.shap_values.iter().copied().sum();
            let reconstructed = pred.expected_margin + shap_sum;
            let diff = (reconstructed - pred.raw_margin).abs();
            assert!(
                diff < 1e-8,
                "TreeSHAP local accuracy violated: reconstructed={reconstructed}, raw={}, diff={diff}",
                pred.raw_margin
            );
        }
    }

    // Law (Concave Mixture MLE Monotonicity): increasing AI token counts strictly increases/preserves alpha_hat in [0, 1]
    #[test]
    fn mixture_mle_solver_is_bounded_and_monotone() {
        use crate::hash_tables::{solve_mixture_mle, MlTablesView};
        use crate::ml_features::EMBEDDED_ML_TABLES;
        use std::collections::BTreeMap;

        let tables = MlTablesView::from_bytes(EMBEDDED_ML_TABLES).expect("valid ml_tables.bin");
        let mut human_heavy = BTreeMap::new();
        let mut ai_heavy = BTreeMap::new();
        for b in 0..512u16 {
            let (p, q) = tables.lookup_mle_probs(b);
            if p > q * 1.15 {
                human_heavy.insert(b, 10);
                ai_heavy.insert(b, 1);
            } else if q > p * 1.15 {
                human_heavy.insert(b, 1);
                ai_heavy.insert(b, 10);
            }
        }
        if !human_heavy.is_empty() && !ai_heavy.is_empty() {
            let (a_lo, _, _) = solve_mixture_mle(&human_heavy, tables);
            let (a_hi, _, _) = solve_mixture_mle(&ai_heavy, tables);
            assert!((0.0..=1.0).contains(&a_lo));
            assert!((0.0..=1.0).contains(&a_hi));
            assert!(
                a_hi >= a_lo,
                "Expected monotone MLE alpha_hat: {a_hi} >= {a_lo}"
            );
        }
    }
}