CoderBak commited on
Commit
7d66fef
·
verified ·
1 Parent(s): 3434d4a

Define monthly detector releases and expose span and token evidence

Browse files
Files changed (4) hide show
  1. README.md +40 -33
  2. inference.py +268 -142
  3. model.json +28 -21
  4. requirements.txt +2 -0
README.md CHANGED
@@ -1,50 +1,57 @@
1
  ---
2
  base_model: jhu-clsp/ettin-encoder-400m
3
- language:
4
- - en
 
5
  ---
6
 
7
- # ai-detector-dev-11-14
8
 
9
- A development checkpoint of a token-level AI-text detector. It labels every token of an English text as `human`, `ai_assisted` or `ai_generated`.
10
 
11
- - **Backbone:** [jhu-clsp/ettin-encoder-400m](https://huggingface.co/jhu-clsp/ettin-encoder-400m) (395M parameters), fine-tuned.
12
- - **Heads:** a 3-way token head, a segment head (how much of a window is AI-written) and a mixed-authorship head.
13
- - **Inference:** windows of 512 tokens with stride 256; logits are averaged over overlapping windows. A calibrated linear-chain CRF then gives one label per token.
14
 
15
- ## Files
16
 
17
- | File | Content |
18
- |---|---|
19
- | `backbone/` | Fine-tuned encoder weights and config |
20
- | `head.safetensors` | The three heads |
21
- | `tokenizer/` | Tokenizer |
22
- | `model.json` | Classes, heads, window and stride |
23
- | `crf.json` | Calibration (`W`, `alpha`, `delta`) and CRF parameters (`lambda`, `gamma`, `l_min`) |
24
- | `inference.py` | Standalone inference script |
25
-
26
- ## Usage
27
-
28
- `inference.py` needs `torch`, `transformers`, `safetensors`, `numpy` and `huggingface_hub`.
29
 
30
- ```bash
31
- python inference.py essay.txt # verdict and labelled segments
32
- python inference.py essay.txt --json # full result, with per-sentence probabilities
33
- cat essay.txt | python inference.py -
 
34
  ```
35
 
36
  ```python
37
- from inference import Detector
38
 
39
- detector = Detector() # or Detector("path/to/this/folder", device="cuda:0")
40
- result = detector.detect(text)
41
- result["verdict"] # "Human", "Mixed" or "AI"
42
- result["segments"] # [{"start", "end", "label"}], character positions in result["text"]
43
- result["sentences"] # the same per sentence, with the probability of each label
44
  ```
45
 
46
- The verdict is Human if at least 90% of the text is labelled human, AI if the AI fraction (AI-generated plus half of AI-assisted) is at least 80%, and Mixed otherwise.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
47
 
48
- ## Input
49
 
50
- The detector was trained on normalised text: straight quotes, ` -- ` for em dashes, `...` for the ellipsis character, and plain text without Markdown. `inference.py` applies this normalisation itself, and the positions it returns refer to the normalised text. Feeding raw typographic punctuation without it raises the false-positive rate on human text.
 
1
  ---
2
  base_model: jhu-clsp/ettin-encoder-400m
3
+ language: en
4
+ tags:
5
+ - authorship-detection
6
  ---
7
 
8
+ # Monthly authorship detectors
9
 
10
+ Select a checkpoint by date and size. The November 14, 2026 checkpoint is **Ettin 400M · Internal research test**. It has 394,802,193 parameters and supports English prose.
11
 
12
+ ## Select a release
 
 
13
 
14
+ Each date and size has a permanent Git tag. A monthly release uses `YYYY-MM-DD-SIZE`, such as a date followed by `-400m`. Internal research checkpoints add `-research`. The date identifies the checkpoint release, and the size is its nominal parameter class. Apps can list the repository's tags with the Hub refs API, use the returned commit to cache downloads, and filter out research checkpoints in their picker. The tagged snapshot contains the tokenizer, weights, decoder calibration, metadata, and the inference script for that release. Each new size or release date gets a new tag. `main` is the default snapshot.
15
 
16
+ After obtaining access to this gated repo and signing in with `hf auth login`, download the selected snapshot and run it locally.
 
 
 
 
 
 
 
 
 
 
 
17
 
18
+ ```sh
19
+ hf download CoderBak/ai-detector-dev-11-14 --revision 2026-11-14-400m-research --local-dir detector
20
+ cd detector
21
+ python -m pip install -r requirements.txt
22
+ python inference.py essay.txt --json
23
  ```
24
 
25
  ```python
26
+ from inference import Detector, list_releases
27
 
28
+ choices = list_releases() # date, size, channel, revision and commit
29
+ detector = Detector() # load the downloaded snapshot once
30
+ result = detector.detect(text, tokens=True, windows=True, source_map=True)
31
+ if result["status"] == "assessed":
32
+ print(result["prediction_short"], result["fractions"])
33
  ```
34
 
35
+ For a Hub selection using this runtime, pass `Detector(revision=choice["revision"])`. For cross-version compatibility, load the inference script and weights from the same selected snapshot. Any client can enumerate tags without loading Python or downloading weights. [Hub refs API](https://huggingface.co/api/models/CoderBak/ai-detector-dev-11-14/refs)
36
+
37
+ ## Inference contract
38
+
39
+ All releases use the same three class names, `human`, `ai_assisted`, and `ai_generated`. Results identify the `release`, `channel`, and `schema_version`. Input below 50 whitespace-delimited words after normalization returns `insufficient_text`, empty spans and a null headline. For assessed text, the following fields are available.
40
+
41
+ | Level | Fields and meaning |
42
+ |---|---|
43
+ | Document | `prediction_short` is Human at 90% human characters, AI at 80% AI-generated characters, and Mixed otherwise. `fractions` gives the three displayed class shares across every character of the analyzed text. `weighted_ai_fraction` counts generated characters fully and assisted characters at half weight. `segment_counts`, `word_count`, and `token_length` give totals. |
44
+ | Segments and sentences | `text`, half-open `start` and `end`, displayed `label`, word and token counts, and three mean token probabilities. `ai_assistance_score` is mean P(generated) + ½ P(assisted). `mean_token_confidence` averages the largest probability at each token. `displayed_label_support` averages the probability of the displayed class. Both confidence measures use CRF marginals before sentence voting. |
45
+ | Tokens, opt in | Token ID and offsets, Viterbi label, final displayed label, three CRF marginals, maximum marginal, averaged head features and calibrated unary scores. |
46
+ | Windows, opt in | Token and character bounds, the 15 segment-bucket probabilities from fully human to fully generated, and the mixed-authorship head probability. |
47
+ | Original text, opt in | `source_map` maps analyzed character intervals back to the original string. A `copy` interval maps coordinates position by position, including one-for-one punctuation changes. Every character in a `replacement` interval maps to its entire source interval. Removed Markdown and formatting appear as gaps in source coverage. |
48
+
49
+ All offsets count Unicode code points in `result["text"]`. In JavaScript, `Array.from(text).slice(start, end).join("")` uses the same units. Original positions in `source_map` index the raw input in those units. Byte-level token pieces can share character offsets. Segments form a complete partition of the analyzed text.
50
+
51
+ The research checkpoint also preserves its original fields for benchmark comparisons. `human_fraction` and `ai_fraction` use non-whitespace characters, with half weight for assisted characters in `ai_fraction`. `verdict` uses these two shares. `posterior_ai_share` uses the same character weights with the **probabilities** of the classes. Use `prediction_short` for the monthly headline.
52
+
53
+ ## November checkpoint
54
 
55
+ The bidirectional Ettin encoder runs on overlapping 512-token windows with stride 256. Token logits, projected segment evidence and mixed-authorship scores feed a calibrated three-state CRF. Viterbi supplies the token path and forward–backward supplies marginals. Sentence voting and the checkpoint's minimum-run setting produce the displayed spans. The November calibration uses a one-token minimum, so a single sentence can stand alone. The encoder reads both directions in one pass. Its three trained heads provide token provenance, segment composition and mixed-authorship evidence. Humanizer detection is unavailable. The checkpoint retains its own training-time normalization for Markdown and Unicode punctuation. [Pangram 4 technical report, §§4.3–5.1](https://arxiv.org/html/2607.27183v1#S4.SS3) · [Pangram 4 model card](https://www.pangram.com/research/model-card/pangram-4)
56
 
57
+ `model.json` declares the name, release date, size, channel, exact parameter count, trained heads and inference settings. `crf.json` holds the fitted decoder. Reuse a `Detector` instance for multiple documents. The CPU and CUDA paths share the same output contract. Installing the optional `numba` package accelerates the CRF for long inputs.
inference.py CHANGED
@@ -1,25 +1,6 @@
1
- """Run the detector in this repository on a text.
2
-
3
- python inference.py essay.txt # verdict and labelled segments
4
- python inference.py essay.txt --json # the full result as JSON
5
- cat essay.txt | python inference.py -
6
-
7
- from inference import Detector
8
- result = Detector().detect("some text")
9
-
10
- Needs torch, transformers (with ModernBERT support), safetensors, numpy and huggingface_hub.
11
-
12
- Steps
13
- 1. Normalise the text the way the training data was normalised (straight quotes, " -- ", plain text).
14
- 2. Cut it into windows of 512 tokens with stride 256, the last one anchored to the end. Each window gives token
15
- logits, a 15-bucket estimate of how much of the window is AI-written, and a mixed-authorship score.
16
- 3. Average these over the windows that contain each token, and calibrate them into one score per label.
17
- 4. Decode one label per token with a linear-chain CRF, whose penalty for changing label is relaxed where the
18
- mixed-authorship score is high. Then every sentence takes its majority label.
19
- 5. Verdict: Human if at least 90% of the non-whitespace characters are human; AI if the AI fraction (AI-generated
20
- plus half of AI-assisted) is at least 80%; otherwise Mixed.
21
- """
22
  import argparse
 
23
  import json
24
  import pathlib
25
  import re
@@ -32,7 +13,7 @@ import torch
32
  REPO = "CoderBak/ai-detector-dev-11-14"
33
  LABELS = ("human", "ai_assisted", "ai_generated")
34
 
35
- # ------------------------------------------------------------------------------------------------ normalisation
36
 
37
  _RULES = [
38
  (re.compile("[\u2018\u2019\u201a\u2032]"), "'"), # curly single quotes
@@ -55,17 +36,67 @@ _RULES = [
55
  ]
56
 
57
 
 
 
 
 
58
  def normalize(text):
59
- t = unicodedata.normalize("NFC", text)
60
  for pattern, replacement in _RULES:
61
- t = pattern.sub(replacement, t)
62
- t = re.sub(r"[ \t]+\n", "\n", t)
63
- t = re.sub(r"[ \t]{2,}", " ", t)
64
- t = re.sub(r"\n{3,}", "\n\n", t)
65
- return t.strip()
66
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
67
 
68
- # ----------------------------------------------------------------------------------------------------- decoding
69
 
70
  _BUCKETS = np.arange(15) / 14 # the segment head's buckets, as AI fractions from 0 to 1
71
  _PHI = np.stack([np.maximum(0, 1 - 2 * _BUCKETS), np.maximum(0, 1 - 2 * np.abs(_BUCKETS - 0.5)),
@@ -88,55 +119,50 @@ def _unary(x, crf):
88
  return x @ np.asarray(crf["W"]).T + np.asarray(crf["alpha"]) + np.asarray(crf["delta"])
89
 
90
 
91
- def _viterbi(u, m, lam, gam):
92
- """Most likely label per token. Changing label between two tokens costs min(0, -lam + gam * mixed log-odds)."""
93
- n = len(u)
94
- if n == 0:
95
- return np.zeros(0, np.int8)
96
- between = 0.5 * (m[:-1] + m[1:])
97
- cost = np.minimum(0.0, -lam + gam * between).astype(np.float64)
98
- labels = np.arange(3)
99
- score = u[0].astype(np.float64).copy()
100
- back = np.zeros((n, 3), np.int8)
101
- for t in range(1, n):
102
- first = int(score.argmax())
103
- rest = score.copy()
104
- rest[first] = -np.inf
105
- second = int(rest.argmax())
106
- other = np.where(labels == first, rest[second], score[first]) # best score among the other labels
107
- other_label = np.where(labels == first, second, first)
108
- switch = other + cost[t - 1]
109
- stay = score >= switch
110
- back[t] = np.where(stay, labels, other_label)
111
- score = np.where(stay, score, switch) + u[t]
112
  path = np.empty(n, np.int8)
113
- current = int(score.argmax())
114
- for t in range(n - 1, -1, -1):
115
- path[t] = current
116
- current = back[t, current]
117
- return path
118
-
119
-
120
- def _marginals(u, m, lam, gam):
121
- """Probability of each label for each token (forward-backward on the same chain)."""
122
- n = len(u)
123
- if n == 0:
124
- return np.zeros((0, 3))
125
- cost = np.minimum(0.0, -lam + gam * 0.5 * (m[:-1] + m[1:])) if n > 1 else np.zeros(0)
126
-
127
- def step(previous, c):
128
- others = np.array([np.logaddexp.reduce(np.delete(previous, k)) for k in range(3)])
129
- return np.logaddexp(previous, others + c)
130
  forward = np.zeros((n, 3))
 
131
  backward = np.zeros((n, 3))
132
- forward[0] = u[0]
133
  for i in range(1, n):
134
- forward[i] = u[i] + step(forward[i - 1], cost[i - 1])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
135
  for i in range(n - 2, -1, -1):
136
- backward[i] = step(backward[i + 1] + u[i + 1], cost[i])
137
- log_p = forward + backward
138
- log_p -= np.logaddexp.reduce(log_p, axis=1, keepdims=True)
139
- return np.exp(log_p)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
140
 
141
 
142
  def _sentence_ids(text, offsets):
@@ -182,17 +208,29 @@ def _merge_short(labels, l_min):
182
  return np.repeat([r[0] for r in runs], [r[1] for r in runs]).astype(np.int8)
183
 
184
 
185
- # ----------------------------------------------------------------------------------------------------- detector
186
 
187
  class Detector:
188
- def __init__(self, model=None, device=None, batch_size=32):
189
- """`model`: a folder with this repository's files or a Hub repository id. Default: the folder of this
190
- script if it holds the files, otherwise this repository on the Hub."""
191
  from safetensors.torch import load_file
192
  from transformers import AutoModel, AutoTokenizer
193
- path = _resolve(model)
 
 
194
  self.device = torch.device(device or ("cuda" if torch.cuda.is_available() else "cpu"))
195
  self.meta = json.loads((path / "model.json").read_text())
 
 
 
 
 
 
 
 
 
 
 
196
  self.crf = json.loads((path / "crf.json").read_text())
197
  self.tokenizer = AutoTokenizer.from_pretrained(path / "tokenizer")
198
  self.tokenizer.model_max_length = 10 ** 9 # windows are cut here, not by the tokenizer
@@ -202,7 +240,7 @@ class Detector:
202
  self.batch_size = batch_size
203
 
204
  @torch.inference_mode()
205
- def _features(self, ids):
206
  """Per token: three token logits and three segment log-priors, averaged over the windows that contain the
207
  token [N, 6], and the mixed-authorship log-odds, weighted towards each window's centre [N]."""
208
  n = len(ids)
@@ -220,14 +258,20 @@ class Detector:
220
  input_ids[r, 0], input_ids[r, 1:b - a + 1], input_ids[r, b - a + 1] = cls, ids[a:b], sep
221
  mask[r, :b - a + 2] = 1
222
  input_ids, mask = torch.from_numpy(input_ids).to(self.device), torch.from_numpy(mask).to(self.device)
223
- with torch.autocast(self.device.type, dtype=torch.bfloat16, enabled=self.device.type == "cuda"):
224
  hidden = self.backbone(input_ids=input_ids, attention_mask=mask).last_hidden_state
225
  hidden = hidden.float()
226
  token_logits = linear(hidden, self.heads["token_head.weight"]).cpu().numpy()
227
  first = hidden[:, 0] # the window-level heads read the [CLS] position
228
  segment = linear(first, self.heads["segment_head.weight"], self.heads["segment_head.bias"])
229
  mixed = linear(first, self.heads["mixed_head.weight"], self.heads["mixed_head.bias"])
230
- prior = torch.softmax(segment, -1).cpu().numpy().astype(np.float64) @ _PHI.T
 
 
 
 
 
 
231
  log_prior = np.log(np.maximum(prior / prior.sum(1, keepdims=True), 1e-6)).astype(np.float32)
232
  log_odds = (mixed[:, 1] - mixed[:, 0]).cpu().numpy()
233
  for r, (a, b) in enumerate(batch):
@@ -241,80 +285,162 @@ class Detector:
241
  c = np.maximum(count, 1)[:, None]
242
  return np.concatenate([tok / c, seg / c], 1), mix / np.maximum(mix_weight, 1e-6)
243
 
244
- def detect(self, text, normalise=True):
245
- """Returns {"verdict": "Human" | "Mixed" | "AI", "ai_fraction", "human_fraction", "text", "segments",
246
- "sentences"}. Character positions in `segments` and `sentences` refer to the returned (normalised) text."""
247
- if normalise:
 
 
 
 
248
  text = normalize(text)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
249
  enc = self.tokenizer(text, add_special_tokens=False, return_offsets_mapping=True,
250
  return_attention_mask=False, truncation=False)
251
  ids = np.asarray(enc["input_ids"], np.int32)
252
  offsets = np.asarray(enc["offset_mapping"], np.int64).reshape(-1, 2)
253
  if not len(ids):
254
- return {"verdict": "Human", "ai_fraction": 0.0, "human_fraction": 0.0, "text": text, "segments": [],
255
- "sentences": []}
256
- x, m = self._features(ids)
257
- u = _unary(x, self.crf)
258
  sentence = _sentence_ids(text, offsets)
259
- labels = _viterbi(u, m, self.crf["lambda"], self.crf["gamma"])
260
- labels = _merge_short(_sentence_vote(labels, sentence), self.crf["l_min"])
261
-
262
- # every character takes the label of the token that covers it (or of the token before a gap)
263
- owner = np.searchsorted(offsets[:, 0], np.arange(len(text)), side="right") - 1
264
- chars = labels[np.clip(owner, 0, len(labels) - 1)]
265
- solid = ~np.fromiter((c.isspace() for c in text), bool, len(text))
266
- counts = np.bincount(chars[solid].astype(np.int64), minlength=3)
267
- total = int(counts.sum()) or 1
268
- ai_fraction, human_fraction = float((counts[2] + 0.5 * counts[1]) / total), float(counts[0] / total)
269
- verdict = "Human" if human_fraction >= 0.90 else "AI" if ai_fraction >= 0.80 else "Mixed"
270
-
271
- cut = np.flatnonzero(np.diff(chars)) + 1
272
- segments = [{"start": int(a), "end": int(b), "label": LABELS[int(chars[a])]}
273
- for a, b in zip(np.r_[0, cut], np.r_[cut, len(chars)])]
274
- probabilities = _marginals(u, m, self.crf["lambda"], self.crf["gamma"])
275
- sentences = []
276
- for s in np.unique(sentence):
277
- k = np.flatnonzero(sentence == s)
278
- sentences.append({"start": int(offsets[k[0], 0]), "end": int(offsets[k[-1], 1]),
279
- "label": LABELS[int(np.bincount(labels[k], minlength=3).argmax())],
280
- "probabilities": {name: float(probabilities[k, c].mean())
281
- for c, name in enumerate(LABELS)}})
282
- for a, b in zip(sentences, sentences[1:]): # stretch each sentence to the start of the next one
283
- a["end"] = b["start"]
284
- sentences[0]["start"], sentences[-1]["end"] = 0, len(text)
285
- return {"verdict": verdict, "ai_fraction": ai_fraction, "human_fraction": human_fraction, "text": text,
286
- "segments": segments, "sentences": sentences}
287
-
288
-
289
- def _resolve(model):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
290
  here = pathlib.Path(__file__).resolve().parent
291
- if model is None:
292
- if (here / "model.json").exists():
293
- return here
294
- model = REPO
295
- if pathlib.Path(model).is_dir():
296
  return pathlib.Path(model)
297
  from huggingface_hub import snapshot_download
298
- return pathlib.Path(snapshot_download(model))
 
299
 
300
 
301
  def main():
302
- ap = argparse.ArgumentParser(description="Label a text as human, AI-assisted or AI-generated, token by token.")
303
- ap.add_argument("file", help="a text file, or - for standard input")
304
- ap.add_argument("--model", default=None, help="folder or Hub repository id (default: this repository)")
305
- ap.add_argument("--device", default=None, help="e.g. cuda:0 or cpu (default: cuda if available)")
306
- ap.add_argument("--json", action="store_true", help="print the full result as JSON")
307
- a = ap.parse_args()
308
- text = sys.stdin.read() if a.file == "-" else pathlib.Path(a.file).read_text(encoding="utf-8")
309
- result = Detector(a.model, a.device).detect(text)
310
- if a.json:
311
- print(json.dumps(result, ensure_ascii=False, indent=1))
 
 
 
312
  return
313
- print(f"Verdict: {result['verdict']} (AI fraction {result['ai_fraction']:.2f}, "
314
- f"human fraction {result['human_fraction']:.2f})")
315
- for s in result["segments"]:
316
- snippet = " ".join(result["text"][s["start"]:s["end"]].split())
317
- print(f"[{s['label']:>12} {s['start']:>6}-{s['end']:<6}] {snippet[:90]}{'...' if len(snippet) > 90 else ''}")
 
 
 
 
 
 
 
 
318
 
319
 
320
  if __name__ == "__main__":
 
1
+ """Monthly authorship detector. All character offsets index the returned text."""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2
  import argparse
3
+ from datetime import date
4
  import json
5
  import pathlib
6
  import re
 
13
  REPO = "CoderBak/ai-detector-dev-11-14"
14
  LABELS = ("human", "ai_assisted", "ai_generated")
15
 
16
+
17
 
18
  _RULES = [
19
  (re.compile("[\u2018\u2019\u201a\u2032]"), "'"), # curly single quotes
 
36
  ]
37
 
38
 
39
+ _RULES.extend([(re.compile(r"[ \t]+\n"), "\n"), (re.compile(r"[ \t]{2,}"), " "),
40
+ (re.compile(r"\n{3,}"), "\n\n")])
41
+
42
+
43
  def normalize(text):
44
+ text = unicodedata.normalize("NFC", text)
45
  for pattern, replacement in _RULES:
46
+ text = pattern.sub(replacement, text)
47
+ return text.strip()
48
+
49
+
50
+ def _mapped_text(text):
51
+ """Run the checkpoint's normalization while retaining original code-point intervals."""
52
+ origins = [(i, i + 1) for i in range(len(text))]
53
+ if not unicodedata.is_normalized("NFC", text):
54
+ import regex
55
+ parts, mapped = [], []
56
+ for match in regex.finditer(r"\X", text):
57
+ cluster = unicodedata.normalize("NFC", match.group())
58
+ parts.append(cluster)
59
+ mapped.extend(origins[match.start():match.end()] if cluster == match.group()
60
+ else [match.span()] * len(cluster))
61
+ text, origins = "".join(parts), mapped
62
+ for pattern, replacement in _RULES:
63
+ end, parts, mapped = 0, [], []
64
+ for match in pattern.finditer(text):
65
+ start, stop = match.span()
66
+ parts.extend((text[end:start], match.expand(replacement)))
67
+ mapped.extend(origins[end:start])
68
+ if replacement.startswith("\\"):
69
+ left, right = match.span(int(replacement[1:]))
70
+ mapped.extend(origins[left:right])
71
+ elif replacement:
72
+ mapped.extend([(origins[start][0], origins[stop - 1][1])] * len(replacement))
73
+ end = stop
74
+ if parts:
75
+ parts.append(text[end:])
76
+ mapped.extend(origins[end:])
77
+ text, origins = "".join(parts), mapped
78
+ start = len(text) - len(text.lstrip())
79
+ end = len(text.rstrip())
80
+ return text[start:end], origins[start:end]
81
+
82
+
83
+ def _source_map(origins):
84
+ runs = []
85
+ for i, (start, end) in enumerate(origins):
86
+ if runs:
87
+ prev = runs[-1]
88
+ if (start, end) == (prev["source_start"], prev["source_end"]):
89
+ prev.update(end=i+1, kind="replacement")
90
+ continue
91
+ if prev["kind"] == "copy" and end == start + 1 and prev["source_end"] == start:
92
+ # Keep a repeated origin out of a longer linear run.
93
+ if i+1 == len(origins) or origins[i+1] != (start, end):
94
+ prev.update(end=i+1, source_end=end)
95
+ continue
96
+ kind = "copy" if end == start+1 and (i+1 == len(origins) or origins[i+1] != (start,end)) else "replacement"
97
+ runs.append(dict(start=i, end=i+1, source_start=start, source_end=end, kind=kind))
98
+ return runs
99
 
 
100
 
101
  _BUCKETS = np.arange(15) / 14 # the segment head's buckets, as AI fractions from 0 to 1
102
  _PHI = np.stack([np.maximum(0, 1 - 2 * _BUCKETS), np.maximum(0, 1 - 2 * np.abs(_BUCKETS - 0.5)),
 
119
  return x @ np.asarray(crf["W"]).T + np.asarray(crf["alpha"]) + np.asarray(crf["delta"])
120
 
121
 
122
+ def decode(unary, mixed, lam, gamma):
123
+ """Numerically stable three-state CRF with the deployed decoder's tie rule."""
124
+ n = len(unary)
125
+ score = unary[0].copy()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
126
  path = np.empty(n, np.int8)
127
+ back = np.zeros((n, 3), np.int8)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
128
  forward = np.zeros((n, 3))
129
+ forward[0] = unary[0]
130
  backward = np.zeros((n, 3))
 
131
  for i in range(1, n):
132
+ cost = min(0.0, -lam + gamma * (mixed[i - 1] + mixed[i]) / 2)
133
+ future = np.empty(3)
134
+ for k in range(3):
135
+ first, second = (1, 2) if k == 0 else (0, 2) if k == 1 else (0, 1)
136
+ alternative = first if score[first] >= score[second] else second
137
+ take = k if score[k] >= score[alternative] + cost else alternative
138
+ back[i, k] = take
139
+ future[k] = unary[i, k] + score[take] + (0.0 if take == k else cost)
140
+ alt_log = np.logaddexp(forward[i - 1, first], forward[i - 1, second])
141
+ forward[i, k] = unary[i, k] + np.logaddexp(forward[i - 1, k], alt_log + cost)
142
+ score = future
143
+ current = np.argmax(score)
144
+ for i in range(n - 1, -1, -1):
145
+ path[i] = current
146
+ current = back[i, current]
147
  for i in range(n - 2, -1, -1):
148
+ cost = min(0.0, -lam + gamma * (mixed[i] + mixed[i + 1]) / 2)
149
+ step = unary[i + 1] + backward[i + 1]
150
+ for k in range(3):
151
+ first, second = (1, 2) if k == 0 else (0, 2) if k == 1 else (0, 1)
152
+ alt_log = np.logaddexp(step[first], step[second])
153
+ backward[i, k] = np.logaddexp(step[k], alt_log + cost)
154
+ probabilities = forward + backward
155
+ for i in range(n):
156
+ normalizer = np.logaddexp(np.logaddexp(probabilities[i, 0], probabilities[i, 1]), probabilities[i, 2])
157
+ probabilities[i] = np.exp(probabilities[i] - normalizer)
158
+ return path, probabilities
159
+
160
+ try:
161
+ from numba import njit
162
+ except ImportError:
163
+ pass
164
+ else:
165
+ decode = njit(cache=True)(decode)
166
 
167
 
168
  def _sentence_ids(text, offsets):
 
208
  return np.repeat([r[0] for r in runs], [r[1] for r in runs]).astype(np.int8)
209
 
210
 
211
+
212
 
213
  class Detector:
214
+ def __init__(self, model=None, device=None, batch_size=32, revision=None):
215
+ """Load a local release or a Hub tag such as 2026-11-14-400m."""
 
216
  from safetensors.torch import load_file
217
  from transformers import AutoModel, AutoTokenizer
218
+ if type(batch_size) is not int or batch_size < 1:
219
+ raise ValueError("batch_size must be a positive integer")
220
+ path = _resolve(model, revision)
221
  self.device = torch.device(device or ("cuda" if torch.cuda.is_available() else "cpu"))
222
  self.meta = json.loads((path / "model.json").read_text())
223
+ if self.meta.get("format") != "anagram-detector/1" or tuple(self.meta["classes"]) != LABELS:
224
+ raise ValueError("This runtime needs an anagram-detector/1 release with the standard class order")
225
+ if self.meta["heads"] != ["token", "segment", "mixed"]:
226
+ raise ValueError("This runtime supports the token, segment and mixed heads")
227
+ self.release = f"{self.meta['release_date']}-{self.meta['size']}"
228
+ if self.meta["channel"] == "internal-research-test":
229
+ self.release += "-research"
230
+ elif self.meta["channel"] != "release":
231
+ raise ValueError("Unknown release channel")
232
+ if revision and _TAG.fullmatch(revision) and revision != self.release:
233
+ raise ValueError(f"Release metadata identifies {self.release}, expected {revision}")
234
  self.crf = json.loads((path / "crf.json").read_text())
235
  self.tokenizer = AutoTokenizer.from_pretrained(path / "tokenizer")
236
  self.tokenizer.model_max_length = 10 ** 9 # windows are cut here, not by the tokenizer
 
240
  self.batch_size = batch_size
241
 
242
  @torch.inference_mode()
243
+ def _features(self, ids, observations=None):
244
  """Per token: three token logits and three segment log-priors, averaged over the windows that contain the
245
  token [N, 6], and the mixed-authorship log-odds, weighted towards each window's centre [N]."""
246
  n = len(ids)
 
258
  input_ids[r, 0], input_ids[r, 1:b - a + 1], input_ids[r, b - a + 1] = cls, ids[a:b], sep
259
  mask[r, :b - a + 2] = 1
260
  input_ids, mask = torch.from_numpy(input_ids).to(self.device), torch.from_numpy(mask).to(self.device)
261
+ with torch.autocast(self.device.type, dtype=torch.bfloat16, enabled=self.device.type == "cuda" and torch.cuda.is_bf16_supported()):
262
  hidden = self.backbone(input_ids=input_ids, attention_mask=mask).last_hidden_state
263
  hidden = hidden.float()
264
  token_logits = linear(hidden, self.heads["token_head.weight"]).cpu().numpy()
265
  first = hidden[:, 0] # the window-level heads read the [CLS] position
266
  segment = linear(first, self.heads["segment_head.weight"], self.heads["segment_head.bias"])
267
  mixed = linear(first, self.heads["mixed_head.weight"], self.heads["mixed_head.bias"])
268
+ buckets = torch.softmax(segment, -1).cpu().numpy()
269
+ prior = buckets.astype(np.float64) @ _PHI.T
270
+ if observations is not None:
271
+ mixed_probs = torch.softmax(mixed, -1)[:, 1].cpu().numpy()
272
+ for r, (a, b) in enumerate(batch):
273
+ observations.append(dict(token_start=a, token_end=b, buckets=buckets[r].tolist(),
274
+ mixed_probability=float(mixed_probs[r])))
275
  log_prior = np.log(np.maximum(prior / prior.sum(1, keepdims=True), 1e-6)).astype(np.float32)
276
  log_odds = (mixed[:, 1] - mixed[:, 0]).cpu().numpy()
277
  for r, (a, b) in enumerate(batch):
 
285
  c = np.maximum(count, 1)[:, None]
286
  return np.concatenate([tok / c, seg / c], 1), mix / np.maximum(mix_weight, 1e-6)
287
 
288
+ def detect(self, text, normalise=True, *, tokens=False, windows=False, source_map=False):
289
+ """Score English prose. Optional detail uses the same encoder and decoder pass."""
290
+ if not isinstance(text, str):
291
+ raise TypeError("text must be a string")
292
+ original_length = len(text)
293
+ if source_map and normalise:
294
+ text, origins = _mapped_text(text)
295
+ elif normalise:
296
  text = normalize(text)
297
+ words = len(text.split())
298
+ result = dict(schema_version=1, release=self.release, channel=self.meta["channel"], text=text, source_length=original_length,
299
+ word_count=words, token_length=0, status="insufficient_text", prediction_short=None,
300
+ verdict=None, fractions=None, human_fraction=None, ai_fraction=None,
301
+ weighted_ai_fraction=None, posterior_ai_share=None, segment_counts=None,
302
+ segments=[], sentences=[])
303
+ if source_map:
304
+ result["source_map"] = _source_map(origins) if normalise else (
305
+ [dict(start=0, end=len(text), source_start=0, source_end=len(text), kind="copy")] if text else [])
306
+ if tokens:
307
+ result["tokens"] = []
308
+ if windows:
309
+ result["windows"] = []
310
+ if words < self.meta["min_words"]:
311
+ return result
312
+
313
  enc = self.tokenizer(text, add_special_tokens=False, return_offsets_mapping=True,
314
  return_attention_mask=False, truncation=False)
315
  ids = np.asarray(enc["input_ids"], np.int32)
316
  offsets = np.asarray(enc["offset_mapping"], np.int64).reshape(-1, 2)
317
  if not len(ids):
318
+ return result
319
+ x, mixed = self._features(ids, result.get("windows"))
320
+ unary = _unary(x, self.crf)
321
+ raw, probabilities = decode(unary, mixed, self.crf["lambda"], self.crf["gamma"])
322
  sentence = _sentence_ids(text, offsets)
323
+ labels = _merge_short(_sentence_vote(raw, sentence), self.crf["l_min"])
324
+ # Each character belongs to the last token starting at or before it, including whitespace gaps.
325
+ owner = np.maximum(np.searchsorted(offsets[:, 0], np.arange(len(text)), side="right") - 1, 0)
326
+ chars = labels[owner]
327
+ counts = np.bincount(chars, minlength=3)
328
+ fractions = dict(zip(LABELS, (counts / len(text)).tolist()))
329
+ nonspace = np.fromiter((not c.isspace() for c in text), bool, len(text))
330
+ solid_shares = np.bincount(chars[nonspace], minlength=3) / nonspace.sum()
331
+ human, assisted, generated = solid_shares.tolist()
332
+ legacy_weighted = generated + 0.5 * assisted
333
+ post_ai = probabilities[:, 2] + 0.5 * probabilities[:, 1]
334
+
335
+ def span(a, b, left, right, label):
336
+ marginals = probabilities[left:right]
337
+ mean = marginals.mean(axis=0)
338
+ return dict(start=a, end=b, text=text[a:b], word_count=len(text[a:b].split()),
339
+ token_length=right-left, label=LABELS[label],
340
+ probabilities=dict(zip(LABELS, mean.tolist())),
341
+ ai_assistance_score=float(mean[2] + 0.5 * mean[1]),
342
+ displayed_label_support=float(mean[label]),
343
+ mean_token_confidence=float(marginals.max(axis=1).mean()))
344
+
345
+ # Byte pieces of one Unicode character can share offsets. Token groups
346
+ # follow character midpoints so every token is counted exactly once.
347
+ mids = (offsets[:, 0] + np.maximum(offsets[:, 1] - 1, offsets[:, 0])) // 2
348
+ boundaries = np.r_[0, np.flatnonzero(np.diff(chars)) + 1, len(text)]
349
+ token_cuts = np.searchsorted(mids, boundaries)
350
+ segments = [span(int(a), int(b), int(left), int(right), int(chars[a]))
351
+ for a, b, left, right in zip(boundaries[:-1], boundaries[1:], token_cuts[:-1], token_cuts[1:])]
352
+ cuts = np.r_[0, np.flatnonzero(np.diff(sentence)) + 1, len(ids)]
353
+ starts = [0, *offsets[cuts[1:-1], 0].tolist(), len(text)]
354
+ sentences = [span(a, b, int(left), int(right), int(labels[left]))
355
+ for a, b, left, right in zip(starts[:-1], starts[1:], cuts[:-1], cuts[1:])]
356
+ result.update(status="assessed", token_length=len(ids), fractions=fractions,
357
+ prediction_short=_verdict(fractions["human"], fractions["ai_generated"]),
358
+ weighted_ai_fraction=fractions["ai_generated"] + 0.5 * fractions["ai_assisted"],
359
+ human_fraction=human, ai_fraction=legacy_weighted, verdict=_verdict(human, legacy_weighted),
360
+ posterior_ai_share=float(np.average(post_ai, weights=np.bincount(owner[nonspace], minlength=len(ids)))),
361
+ segment_counts={label: sum(s["label"] == label for s in segments) for label in LABELS},
362
+ segments=segments, sentences=sentences)
363
+ if tokens:
364
+ result["tokens"] = [
365
+ dict(id=int(i), start=int(a), end=int(b), label=LABELS[label], viterbi_label=LABELS[path_label],
366
+ probabilities=dict(zip(LABELS, probs.tolist())), confidence=float(probs.max()),
367
+ token_logits=features[:3].tolist(), segment_log_prior=features[3:].tolist(),
368
+ mixed_log_odds=float(m), unary=u.tolist())
369
+ for i, (a, b), label, path_label, probs, features, m, u in
370
+ zip(ids, offsets, labels, raw, probabilities, x, mixed, unary)
371
+ ]
372
+ if windows:
373
+ for window in result["windows"]:
374
+ window["start"] = int(offsets[window["token_start"], 0])
375
+ window["end"] = int(offsets[window["token_end"] - 1, 1])
376
+ return result
377
+
378
+
379
+ def _verdict(human_share, ai_share):
380
+ return "Human" if human_share >= 0.90 else "AI" if ai_share >= 0.80 else "Mixed"
381
+
382
+
383
+ _TAG = re.compile(r"(\d{4}-\d{2}-\d{2})-([1-9]\d*(?:\.\d+)?[mb])(-research)?")
384
+
385
+
386
+ def list_releases(repo=REPO):
387
+ """Discover available date/size pairs from tags without downloading weights."""
388
+ from huggingface_hub import HfApi
389
+ releases = []
390
+ for tag in HfApi().list_repo_refs(repo).tags:
391
+ match = _TAG.fullmatch(tag.name)
392
+ if match:
393
+ day, size, research = match.groups()
394
+ try:
395
+ date.fromisoformat(day)
396
+ except ValueError:
397
+ continue
398
+ releases.append(dict(date=day, size=size, channel="internal-research-test" if research else "release",
399
+ revision=tag.name, commit=tag.target_commit))
400
+ return sorted(releases, key=lambda r: (r["date"], r["size"]), reverse=True)
401
+
402
+
403
+ def _resolve(model, revision):
404
  here = pathlib.Path(__file__).resolve().parent
405
+ if model is None and revision is None and (here / "model.json").is_file():
406
+ return here
407
+ if model is not None and pathlib.Path(model).is_dir():
408
+ if revision:
409
+ raise ValueError("Pass a checked-out folder or a Hub model with a revision")
410
  return pathlib.Path(model)
411
  from huggingface_hub import snapshot_download
412
+ return pathlib.Path(snapshot_download(model or REPO, revision=revision,
413
+ allow_patterns=["model.json", "crf.json", "head.safetensors", "backbone/*", "tokenizer/*"]))
414
 
415
 
416
  def main():
417
+ ap = argparse.ArgumentParser(description=__doc__)
418
+ ap.add_argument("file", nargs="?", help="UTF-8 text file, or - for stdin")
419
+ ap.add_argument("--model", help="Local release directory or Hub repository ID")
420
+ ap.add_argument("--revision", help="Hub release tag or commit")
421
+ ap.add_argument("--list", action="store_true", help="List released dates and sizes")
422
+ ap.add_argument("--device", help="Torch device, e.g. cpu or cuda:0")
423
+ ap.add_argument("--json", action="store_true")
424
+ ap.add_argument("--tokens", action="store_true")
425
+ ap.add_argument("--windows", action="store_true")
426
+ ap.add_argument("--source-map", action="store_true")
427
+ args = ap.parse_args()
428
+ if args.list:
429
+ print(json.dumps(list_releases(args.model or REPO), indent=2))
430
  return
431
+ if args.file is None:
432
+ ap.error("Specify a text file or --list")
433
+ text = sys.stdin.read() if args.file == "-" else pathlib.Path(args.file).read_text(encoding="utf-8")
434
+ result = Detector(args.model, args.device, revision=args.revision).detect(
435
+ text, tokens=args.tokens, windows=args.windows, source_map=args.source_map)
436
+ if args.json or args.tokens or args.windows or args.source_map:
437
+ print(json.dumps(result, ensure_ascii=False, allow_nan=False))
438
+ elif result["status"] == "assessed":
439
+ print(result["prediction_short"])
440
+ for segment in result["segments"]:
441
+ print(f"[{segment['label']}] {segment['text']}")
442
+ else:
443
+ print("Insufficient text")
444
 
445
 
446
  if __name__ == "__main__":
model.json CHANGED
@@ -1,22 +1,29 @@
1
  {
2
- "attention": "sdpa",
3
- "base_model": "jhu-clsp/ettin-encoder-400m",
4
- "classes": [
5
- "human",
6
- "ai_assisted",
7
- "ai_generated"
8
- ],
9
- "compute": "bf16 autocast, fp32 head",
10
- "decoder": "argmax",
11
- "format": "dp-ettin-token/1",
12
- "heads": [
13
- "token",
14
- "segment",
15
- "mixed"
16
- ],
17
- "hidden_size": 1024,
18
- "revision": "7662476d60abb071a5bd319c9f3074f3072c062d",
19
- "stride": 256,
20
- "template": "[CLS] tokens [SEP]",
21
- "window": 512
22
- }
 
 
 
 
 
 
 
 
1
  {
2
+ "attention": "sdpa",
3
+ "base_model": "jhu-clsp/ettin-encoder-400m",
4
+ "classes": [
5
+ "human",
6
+ "ai_assisted",
7
+ "ai_generated"
8
+ ],
9
+ "compute": "bf16 autocast, fp32 head",
10
+ "decoder": "linear_chain_crf",
11
+ "format": "anagram-detector/1",
12
+ "heads": [
13
+ "token",
14
+ "segment",
15
+ "mixed"
16
+ ],
17
+ "hidden_size": 1024,
18
+ "stride": 256,
19
+ "template": "[CLS] tokens [SEP]",
20
+ "window": 512,
21
+ "release_date": "2026-11-14",
22
+ "size": "400m",
23
+ "parameters": 394802193,
24
+ "language": "en",
25
+ "min_words": 50,
26
+ "channel": "internal-research-test",
27
+ "name": "Ettin 400M · Internal research test",
28
+ "base_revision": "7662476d60abb071a5bd319c9f3074f3072c062d"
29
+ }
requirements.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ torch>=2.6
2
+ transformers==5.20.2