SkootrMechanic commited on
Commit
5fbb148
Β·
verified Β·
1 Parent(s): 874c5da

Initial release of PostBERT

Browse files
.gitattributes CHANGED
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ assets/postbert-teaser.webp filter=lfs diff=lfs merge=lfs -text
README.md ADDED
@@ -0,0 +1,164 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: apache-2.0
3
+ language:
4
+ - en
5
+ base_model: answerdotai/ModernBERT-base
6
+ pipeline_tag: text-classification
7
+ library_name: transformers
8
+ inference: false
9
+ tags:
10
+ - ai-text-detection
11
+ - email
12
+ - modernbert
13
+ - onnx
14
+ ---
15
+
16
+ # PostBERT
17
+
18
+ ![PostBERT: spot AI-written email without sending it anywhere](assets/postbert-teaser.webp)
19
+
20
+ **PostBERT** is a fast, compact open-weight classifier built specifically for email. It scores an English email body from `0` (human) to `100` (AI) in a single pass up to **1,024 tokens** (~750 words), running locally on a laptop CPU, GPU, or directly inside a web browser. Your email never leaves the device.
21
+
22
+ Built by **Skootr** on [ModernBERT-base](https://huggingface.co/answerdotai/ModernBERT-base) (149.6M parameters, Apache-2.0).
23
+
24
+ ## Why PostBERT
25
+
26
+ - **Built for real email, not essays.** General AI detectors often trip on normal email formatting, short replies, and signatures. PostBERT is trained and normalized specifically for email bodies from 25 words up to 1,024 tokens.
27
+ - **Private by design.** At 300 MB in half-precision ONNX, PostBERT runs natively in Chrome WebGPU, WebAssembly, or local CPU with zero API calls.
28
+ - **Tunable 3-bracket scoring.** Outputs a continuous `0-100` score (`ai_score`) so you can sort messages into **Likely human**, **Potentially AI**, and **Likely AI** using brackets that fit your workflow.
29
+ - **Strong on unseen models.** Tested against three AI model families held completely out of training, holding **94.8%** detection on unseen families at 1 false alarm per 500 human emails.
30
+
31
+ ## Recommended Score Brackets
32
+
33
+ PostBERT outputs a continuous `0-100` score. You can set your own thresholds for your tolerance, or use our recommended 3-bracket setup:
34
+
35
+ | Bracket | Score range | Meaning |
36
+ |---|---|---|
37
+ | **Likely human** | `0` to `10` | Reads as human-written |
38
+ | **Potentially AI** | `10` to `51` | Mixed, AI-assisted, or uncertain |
39
+ | **Likely AI** | `51` to `100` | Reads as AI-written (1-in-500 human false-alarm rate) |
40
+
41
+ ### Benchmark Results (Recommended Brackets)
42
+
43
+ Measured on our held-out November 2026 test set (16,080 pre-Nov-2022 human emails, 1,690 mixed-AI emails, and 1,209 full-AI emails; none used in training):
44
+
45
+ | Email group | Count | Likely human (`0-10`) | Potentially AI (`10-51`) | Likely AI (`51-100`) | AUROC |
46
+ |---|---:|---:|---:|---:|---:|
47
+ | **Human** | 16,080 | **98.0%** | 1.8% | **0.2%** | - |
48
+ | **Full AI (>100 words)** | 386 | 0.3% | 1.0% | **98.7%** | **0.9998** |
49
+ | **Full AI (25-100 words)** | 823 | 2.8% | 1.8% | **95.4%** | **0.996** |
50
+ | **Full AI (unseen model families)** | 343 | 2.6% | 2.6% | **94.8%** | **0.994** |
51
+ | **Mixed AI (all)** | 1,690 | 7.2% | 18.3% | **74.5%** | **0.988** |
52
+ | Mixed: AI-written from summary | 938 | 3.4% | 5.8% | **90.8%** | 0.995 |
53
+ | Mixed: AI rewrite of human email | 752 | 12.0% | 33.9% | **54.1%** | 0.980 |
54
+
55
+ - **Long emails (401 to 3,500 words):** On an additional held-out set of longer emails (674 human, 123 AI rewrites, 142 AI-from-summary, 121 full AI) scored in one pass up to 1,024 tokens, **0 of 674** human emails landed in Likely AI (`>=51`) and **100%** of full-AI and AI-from-summary emails were detected (AUROC `1.000`; AI rewrites AUROC `0.996`).
56
+
57
+ ## Quick Start
58
+
59
+ ```python
60
+ import importlib.util
61
+ import torch
62
+ from huggingface_hub import hf_hub_download
63
+ from transformers import AutoTokenizer, AutoModelForSequenceClassification
64
+
65
+ repo = "SkootrAI/PostBERT"
66
+
67
+ # Load the required text normalizer from this repository
68
+ spec = importlib.util.spec_from_file_location(
69
+ "normalize", hf_hub_download(repo, "normalize.py"))
70
+ mod = importlib.util.module_from_spec(spec)
71
+ spec.loader.exec_module(mod)
72
+ normalize = mod.normalize
73
+
74
+ tok = AutoTokenizer.from_pretrained(repo)
75
+ model = AutoModelForSequenceClassification.from_pretrained(repo).eval()
76
+
77
+ def score_email(email_body: str) -> tuple[float, str]:
78
+ enc = tok(normalize(email_body), truncation=True, max_length=1024,
79
+ return_tensors="pt")
80
+ with torch.inference_mode():
81
+ score = 100 * torch.sigmoid(model(**enc).logits[0, 0]).item()
82
+ bracket = "likely_human" if score < 10 else "potentially_ai" if score < 51 else "likely_ai"
83
+ return round(score, 1), bracket
84
+
85
+ print(score_email("Paste an email body of 25 words or more here ..."))
86
+ ```
87
+
88
+ ### Best Practices
89
+ 1. **Always run `normalize()` first.** It standardizes typography, spacing, and hard line wraps and replaces URLs, email addresses, and phone numbers with fixed placeholders so the model focuses on authorship rather than formatting.
90
+ 2. **Score only the new message.** Strip quoted replies, forwarded threads, and automatic footers beforehand.
91
+ 3. **Use 25+ words.** Messages under 25 words do not carry enough signal to score reliably.
92
+
93
+ ### Emails Over 1,024 Tokens
94
+
95
+ Single-pass scoring covers up to 1,024 tokens (~750 words). For longer emails, you can score overlapping 1,024-token windows (1,022 content tokens plus start and end tokens) and combine the scores however fits your app:
96
+
97
+ ```python
98
+ def part_scores(email_body: str, size: int = 1022) -> list[float]:
99
+ ids = tok(normalize(email_body), add_special_tokens=False)["input_ids"]
100
+ starts = [0]
101
+ if len(ids) > size:
102
+ starts = list(range(0, len(ids) - size, size)) + [len(ids) - size]
103
+ scores = []
104
+ for s in starts:
105
+ part = [tok.cls_token_id] + ids[s:s + size] + [tok.sep_token_id]
106
+ with torch.inference_mode():
107
+ logit = model(input_ids=torch.tensor([part])).logits[0, 0]
108
+ scores.append(100 * torch.sigmoid(logit).item())
109
+ return scores
110
+ ```
111
+
112
+ ## Speed Benchmarks
113
+
114
+ Median single-email latency measured on an Apple M1 Ultra (`model_fp16.onnx` for ONNX / browser, `model.safetensors` for PyTorch MPS):
115
+
116
+ | Runtime | 64 tokens (~25-50 words) | 128 tokens (~50-100 words) | 256 tokens (~100-200 words) | 512 tokens (~200-400 words) | 1,024 tokens (~400-750 words) |
117
+ |---|---:|---:|---:|---:|---:|
118
+ | **PyTorch (MPS GPU)** | 14 ms | 16 ms | 18 ms | 30 ms | 63 ms |
119
+ | **Chrome (WebGPU)** | 78 ms | 78 ms | 96 ms | 159 ms | 402 ms |
120
+ | **ONNX Runtime (4 CPU threads)** | 59 ms | 113 ms | 224 ms | 496 ms | 1,199 ms |
121
+ | **Chrome (WASM, 8 threads)** | 72 ms | 132 ms | 258 ms | 588 ms | 1,394 ms |
122
+ | **ONNX Runtime (1 CPU thread)** | 176 ms | 352 ms | 774 ms | 1,719 ms | 3,889 ms |
123
+
124
+ ## Repository Files
125
+
126
+ | File | Purpose |
127
+ |---|---|
128
+ | `model.safetensors` | PyTorch / Transformers weights (fp32, ~600 MB) |
129
+ | `onnx/model.onnx` | ONNX Runtime weights (fp32, ~600 MB) |
130
+ | `onnx/model_fp16.onnx` | ONNX Runtime & ONNX Runtime Web weights (fp16, ~300 MB) |
131
+ | `normalize.py` | Standalone text normalizer (Python standard library only) |
132
+
133
+ ## Training Overview
134
+
135
+ PostBERT was trained on ~45,000 English emails:
136
+ - **~27,000 human emails:** publicly available pre-November-2022 email from public-record archives and open mailing lists.
137
+ - **~18,000 AI emails:** generated across 10 language models from 5 model families, covering full drafts, summary-to-email drafts, and rewrites of human messages.
138
+
139
+ No private or customer email was used.
140
+
141
+ ## Scope & Practical Notes
142
+
143
+ - **Signal, not proof:** Treat PostBERT as a triage and awareness signal rather than standalone proof of authorship.
144
+ - **English email (25+ words):** Built and benchmarked for English email bodies of 25 words or more.
145
+ - **Tune for your inbox:** Benchmark brackets on a small sample of your own known-human mail if your domain has unusual templates or boilerplate.
146
+
147
+ ## Questions & Comments
148
+
149
+ If you have questions or comments, please open a thread in the [Community tab](https://huggingface.co/SkootrAI/PostBERT/discussions) or contact us at [models@skootr.ai](mailto:models@skootr.ai).
150
+
151
+ ## License
152
+
153
+ Apache License 2.0 (same as [ModernBERT-base](https://huggingface.co/answerdotai/ModernBERT-base)). Copyright 2026 Skootr.
154
+
155
+ ## Citation
156
+
157
+ ```bibtex
158
+ @misc{postbert2026,
159
+ title = {PostBERT: an on-device detector for AI-written email},
160
+ author = {Skootr},
161
+ year = {2026},
162
+ url = {https://huggingface.co/SkootrAI/PostBERT}
163
+ }
164
+ ```
assets/postbert-teaser.webp ADDED

Git LFS Details

  • SHA256: 17fd496c2f9c939b5046b55b3f2e60d2d9e10a26202369e117223f5fe6d0aaed
  • Pointer size: 131 Bytes
  • Size of remote file: 114 kB
config.json ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "ModernBertForSequenceClassification"
4
+ ],
5
+ "attention_bias": false,
6
+ "attention_dropout": 0.0,
7
+ "bos_token_id": 50281,
8
+ "classifier_activation": "gelu",
9
+ "classifier_bias": false,
10
+ "classifier_dropout": 0.0,
11
+ "classifier_pooling": "mean",
12
+ "cls_token_id": 50281,
13
+ "decoder_bias": true,
14
+ "deterministic_flash_attn": false,
15
+ "dtype": "float32",
16
+ "embedding_dropout": 0.0,
17
+ "eos_token_id": 50282,
18
+ "global_attn_every_n_layers": 3,
19
+ "gradient_checkpointing": false,
20
+ "hidden_activation": "gelu",
21
+ "hidden_size": 768,
22
+ "id2label": {
23
+ "0": "ai_score"
24
+ },
25
+ "initializer_cutoff_factor": 2.0,
26
+ "initializer_range": 0.02,
27
+ "intermediate_size": 1152,
28
+ "label2id": {
29
+ "ai_score": 0
30
+ },
31
+ "layer_norm_eps": 1e-05,
32
+ "layer_types": [
33
+ "full_attention",
34
+ "sliding_attention",
35
+ "sliding_attention",
36
+ "full_attention",
37
+ "sliding_attention",
38
+ "sliding_attention",
39
+ "full_attention",
40
+ "sliding_attention",
41
+ "sliding_attention",
42
+ "full_attention",
43
+ "sliding_attention",
44
+ "sliding_attention",
45
+ "full_attention",
46
+ "sliding_attention",
47
+ "sliding_attention",
48
+ "full_attention",
49
+ "sliding_attention",
50
+ "sliding_attention",
51
+ "full_attention",
52
+ "sliding_attention",
53
+ "sliding_attention",
54
+ "full_attention"
55
+ ],
56
+ "local_attention": 128,
57
+ "max_position_embeddings": 8192,
58
+ "mlp_bias": false,
59
+ "mlp_dropout": 0.0,
60
+ "model_type": "modernbert",
61
+ "norm_bias": false,
62
+ "norm_eps": 1e-05,
63
+ "num_attention_heads": 12,
64
+ "num_hidden_layers": 22,
65
+ "pad_token_id": 50283,
66
+ "position_embedding_type": "absolute",
67
+ "rope_parameters": {
68
+ "full_attention": {
69
+ "rope_theta": 160000.0,
70
+ "rope_type": "default"
71
+ },
72
+ "sliding_attention": {
73
+ "rope_theta": 10000.0,
74
+ "rope_type": "default"
75
+ }
76
+ },
77
+ "sep_token_id": 50282,
78
+ "sparse_pred_ignore_index": -100,
79
+ "sparse_prediction": false,
80
+ "tie_word_embeddings": true,
81
+ "transformers_version": "5.15.0",
82
+ "vocab_size": 50368
83
+ }
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0daa938c457389e5291fc2dffa1fe1020902d30c3fb088739f2e046549c7d806
3
+ size 598436708
normalize.py ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Text clean-up for PostBERT. Call normalize() on every email body before scoring.
2
+
3
+ The model was trained on text cleaned by exactly this function. It removes
4
+ surface features that say nothing about who wrote an email: typography
5
+ (curly quotes, long dashes, odd spaces), spacing, hard line wraps, and
6
+ contact details. Skipping it changes scores.
7
+
8
+ Standard library only. Licence: Apache-2.0, Copyright 2026 Skootr.
9
+ """
10
+ from __future__ import annotations
11
+
12
+ import re
13
+ import unicodedata
14
+
15
+ __all__ = ["normalize"]
16
+
17
+ # Typography mapped to plain ASCII; zero-width characters and CR removed.
18
+ _TRANSLATE = str.maketrans({
19
+ "β€˜": "'", "’": "'", "β€š": "'", "β€›": "'", "β€²": "'",
20
+ "β€œ": '"', "”": '"', "β€ž": '"', "β€Ÿ": '"', "β€³": '"',
21
+ "Β«": '"', "Β»": '"',
22
+ "‐": "-", "‑": "-", "β€’": "-", "–": "-", "β€”": "-",
23
+ "―": "-", "βˆ’": "-",
24
+ "…": "...",
25
+ "Β ": " ", " ": " ", " ": " ", " ": " ", " ": " ",
26
+ "β€―": " ", "γ€€": " ",
27
+ "β€’": "-", "Β·": "-", "●": "-", "β–ͺ": "-",
28
+ "​": None, "β€Œ": None, "‍": None, "⁠": None, "ο»Ώ": None,
29
+ "\r": None,
30
+ })
31
+
32
+ _SPACES = re.compile(r"[ \t\f\v]+")
33
+ _BLANKS = re.compile(r"\n{3,}")
34
+ _NO_END = re.compile(r"[^.!?:;,)\]\"'>]$") # line does not end a sentence
35
+ _CONT = re.compile(r"^[a-z(]") # next line continues in lower case
36
+ _LIST_ITEM = re.compile(r"^\s*([-*+]|\d+[.)]|[a-zA-Z][.)])\s")
37
+
38
+ # Every email address, link and North American phone number becomes one constant.
39
+ _OCR_AT = re.compile(r"(?<=\w)\u00a9(?=\w)") # "@" misread as a copyright sign
40
+ _EMAIL = re.compile(r"[\w.+'-]+@[\w-]+(?:\.[\w-]+)+")
41
+ _URL = re.compile(r"(?:https?://|www\.)[^\s<>()\[\]]+[^\s<>()\[\].,;:!?'\"]")
42
+ _PHONE = re.compile(r"(?<!\d)(?:\+?1[-. ]?)?\(?\d{3}\)?[-. ]?\d{3}[-. ]\d{4}(?!\d)")
43
+
44
+
45
+ def _unwrap(lines: list[str], min_len: int = 55) -> list[str]:
46
+ """Undo hard wraps: join a line to the next only when it is long, does not
47
+ end a sentence, and the next line continues in lower case and is not a
48
+ list item. Short lines (sign-offs, addresses) are never joined."""
49
+ out: list[str] = []
50
+ for ln in lines:
51
+ if (out and out[-1] and ln and len(out[-1]) >= min_len
52
+ and _NO_END.search(out[-1]) and _CONT.match(ln)
53
+ and not _LIST_ITEM.match(ln)):
54
+ out[-1] = out[-1] + " " + ln
55
+ else:
56
+ out.append(ln)
57
+ return out
58
+
59
+
60
+ def normalize(text: str) -> str:
61
+ """Return the cleaned form of one email body.
62
+
63
+ - email addresses, links and phone numbers -> fixed placeholders
64
+ - Unicode NFKC; curly quotes, dashes, ellipsis and odd spaces -> ASCII
65
+ - zero-width characters and CR removed
66
+ - runs of spaces and tabs -> one space; spaces trimmed at line ends
67
+ - hard-wrapped lines joined back together
68
+ - at most one blank line between paragraphs; outer whitespace removed
69
+
70
+ Call it once, on the raw email body.
71
+ """
72
+ if not text:
73
+ return ""
74
+ t = _OCR_AT.sub("@", text).replace("β– ", "-")
75
+ t = _URL.sub("https://example.com", t)
76
+ t = _EMAIL.sub("name@example.com", t)
77
+ t = _PHONE.sub("555-0100", t)
78
+ t = unicodedata.normalize("NFKC", t).translate(_TRANSLATE)
79
+ lines = [_SPACES.sub(" ", ln).strip() for ln in t.split("\n")]
80
+ t = "\n".join(_unwrap(lines))
81
+ t = _BLANKS.sub("\n\n", t)
82
+ return t.strip()
onnx/model.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2a2d041e112815a69ebfb25825c792c48f68c8236495c503cba80adbedf8012e
3
+ size 599049346
onnx/model_fp16.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ec10c2290de86b445b68933d376d8a2a187832d4b7c80c79ac8cc3a7656f4142
3
+ size 299996571
tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
tokenizer_config.json ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "backend": "tokenizers",
3
+ "clean_up_tokenization_spaces": true,
4
+ "cls_token": "[CLS]",
5
+ "mask_token": "[MASK]",
6
+ "max_length": 1024,
7
+ "model_input_names": [
8
+ "input_ids",
9
+ "attention_mask"
10
+ ],
11
+ "model_max_length": 8192,
12
+ "pad_to_multiple_of": null,
13
+ "pad_token": "[PAD]",
14
+ "pad_token_type_id": 0,
15
+ "padding_side": "right",
16
+ "sep_token": "[SEP]",
17
+ "stride": 0,
18
+ "tokenizer_class": "TokenizersBackend",
19
+ "truncation_side": "right",
20
+ "truncation_strategy": "longest_first",
21
+ "unk_token": "[UNK]"
22
+ }