CoderBak commited on
Commit
7be30d3
·
verified ·
1 Parent(s): 19ae7f7

Make main a release index and serve weights from dated tags

Browse files
.gitattributes DELETED
@@ -1 +0,0 @@
1
- *.safetensors filter=lfs diff=lfs merge=lfs -text
 
 
README.md CHANGED
@@ -6,7 +6,7 @@ tags:
6
 
7
  # Monthly authorship detectors
8
 
9
- These checkpoints label English prose as human-written, AI-assisted, or AI-generated. Select a [release tag](https://huggingface.co/api/models/CoderBak/ai-detector-dev-11-14/refs) by date and size. Each tag has a model card at `cards/<tag>.md` on `main`.
10
 
11
  | Checkpoint date | Model | Status | Model card |
12
  |---|---|---|---|
 
6
 
7
  # Monthly authorship detectors
8
 
9
+ These checkpoints label English prose as human-written, AI-assisted, or AI-generated. Download the model from a [release tag](https://huggingface.co/api/models/CoderBak/ai-detector-dev-11-14/refs) by date and size. The `main` branch indexes model cards at `cards/<tag>.md`.
10
 
11
  | Checkpoint date | Model | Status | Model card |
12
  |---|---|---|---|
backbone/config.json DELETED
@@ -1,85 +0,0 @@
1
- {
2
- "architectures": [
3
- "ModernBertModel"
4
- ],
5
- "attention_bias": false,
6
- "attention_dropout": 0.0,
7
- "bos_token_id": 50281,
8
- "causal_mask": false,
9
- "classifier_activation": "gelu",
10
- "classifier_bias": false,
11
- "classifier_dropout": 0.0,
12
- "classifier_pooling": "mean",
13
- "cls_token_id": 50281,
14
- "decoder_bias": true,
15
- "deterministic_flash_attn": false,
16
- "dtype": "float32",
17
- "embedding_dropout": 0.0,
18
- "eos_token_id": 50282,
19
- "global_attn_every_n_layers": 3,
20
- "gradient_checkpointing": false,
21
- "hidden_activation": "gelu",
22
- "hidden_size": 1024,
23
- "initializer_cutoff_factor": 2.0,
24
- "initializer_range": 0.02,
25
- "intermediate_size": 2624,
26
- "is_causal": false,
27
- "layer_norm_eps": 1e-05,
28
- "layer_types": [
29
- "full_attention",
30
- "sliding_attention",
31
- "sliding_attention",
32
- "full_attention",
33
- "sliding_attention",
34
- "sliding_attention",
35
- "full_attention",
36
- "sliding_attention",
37
- "sliding_attention",
38
- "full_attention",
39
- "sliding_attention",
40
- "sliding_attention",
41
- "full_attention",
42
- "sliding_attention",
43
- "sliding_attention",
44
- "full_attention",
45
- "sliding_attention",
46
- "sliding_attention",
47
- "full_attention",
48
- "sliding_attention",
49
- "sliding_attention",
50
- "full_attention",
51
- "sliding_attention",
52
- "sliding_attention",
53
- "full_attention",
54
- "sliding_attention",
55
- "sliding_attention",
56
- "full_attention"
57
- ],
58
- "local_attention": 128,
59
- "max_position_embeddings": 7999,
60
- "mlp_bias": false,
61
- "mlp_dropout": 0.0,
62
- "model_type": "modernbert",
63
- "norm_bias": false,
64
- "norm_eps": 1e-05,
65
- "num_attention_heads": 16,
66
- "num_hidden_layers": 28,
67
- "pad_token_id": 50283,
68
- "position_embedding_type": "sans_pos",
69
- "rope_parameters": {
70
- "full_attention": {
71
- "rope_theta": 160000.0,
72
- "rope_type": "default"
73
- },
74
- "sliding_attention": {
75
- "rope_theta": 160000.0,
76
- "rope_type": "default"
77
- }
78
- },
79
- "sep_token_id": 50282,
80
- "sparse_pred_ignore_index": -100,
81
- "sparse_prediction": false,
82
- "tie_word_embeddings": true,
83
- "transformers_version": "5.20.2",
84
- "vocab_size": 50368
85
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
backbone/model.safetensors DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:aa252abcfaa50224707019a0149855a7944717eb7a4660d4070a1b346e5cc10e
3
- size 1579143688
 
 
 
 
crf.json DELETED
@@ -1,41 +0,0 @@
1
- {
2
- "W": [
3
- [
4
- 0.4718745624986739,
5
- -0.4123477040991616,
6
- -0.2773522963614583,
7
- -0.03416339782948477,
8
- 0.03866048957222454,
9
- -0.144998947726002
10
- ],
11
- [
12
- -0.2461554802390373,
13
- 0.6545299264957797,
14
- -0.28286622677293427,
15
- -0.08189829301847114,
16
- 0.06542677560291564,
17
- -0.059113237757466935
18
- ],
19
- [
20
- -0.22552176619249883,
21
- -0.24198490632945613,
22
- 0.5604158392015485,
23
- 0.1160616908479318,
24
- -0.10408726517514506,
25
- 0.20411218548347226
26
- ]
27
- ],
28
- "alpha": [
29
- -1.0222998986718383,
30
- -0.5387720161717896,
31
- 1.5610719148436307
32
- ],
33
- "delta": [
34
- 0.5,
35
- -0.5,
36
- 0.0
37
- ],
38
- "lambda": 0.5,
39
- "gamma": 4.0,
40
- "l_min": 1
41
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
head.safetensors DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:d97a2e92ab59e4a3038564b54ae48f9b792d130761cfd6c71c55c95ee59bde9e
3
- size 82388
 
 
 
 
inference.py DELETED
@@ -1,447 +0,0 @@
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
7
- import sys
8
- import unicodedata
9
-
10
- import numpy as np
11
- import torch
12
-
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
20
- (re.compile("[\u201c\u201d\u201e\u2033]"), '"'), # curly double quotes
21
- (re.compile("\\s*\u2014\\s*"), " -- "), # em dash
22
- (re.compile("(?<=\\w)\u2013(?=\\w)"), "-"), # en dash in ranges: 1990-1995
23
- (re.compile("\\s*\u2013\\s*"), " - "),
24
- (re.compile("\u2026"), "..."), # ellipsis character
25
- (re.compile("[\u00a0\u2009\u202f]"), " "), # non-breaking and thin spaces
26
- (re.compile("[\u200b\u200c\u200d\ufeff]"), ""), # zero-width characters
27
- (re.compile(r"^```[^\n]*\n?", re.M), ""), # Markdown: code fences
28
- (re.compile(r"^#{1,6}\s+", re.M), ""), # headings
29
- (re.compile(r"^\s{0,3}>\s?", re.M), ""), # block quotes
30
- (re.compile("^(\\s*)[-*+\u2022]\\s+", re.M), r"\1"), # bullets
31
- (re.compile(r"(\*\*|__)(?=\S)(.+?)(?<=\S)\1"), r"\2"), # bold
32
- (re.compile(r"(?<![\w*])\*(?=\S)([^*\n]+?)(?<=\S)\*(?![\w*])"), r"\1"), # italic *x*
33
- (re.compile(r"(?<![\w_])_(?=\S)([^_\n]+?)(?<=\S)_(?![\w_])"), r"\1"), # italic _x_
34
- (re.compile(r"\[([^\]]+)\]\((?:https?://|/)[^)]*\)"), r"\1"), # links
35
- (re.compile(r"^\s*([-*_]\s*){3,}$", re.M), ""), # horizontal rules
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)),
103
- np.maximum(0, 2 * _BUCKETS - 1)]) # each bucket's weight on human / AI-assisted / AI-generated
104
- _SENTENCE_END = re.compile("[.!?\u2026]+[\\\"'\u201d\u2019)\\]]*(?=\\s|$)|\\n\\s*\\n")
105
-
106
-
107
- def _windows(n, window, stride):
108
- if n <= 0:
109
- return []
110
- if n <= window:
111
- return [(0, n)]
112
- starts = list(range(0, n - window + 1, stride))
113
- if starts[-1] != n - window:
114
- starts.append(n - window)
115
- return [(s, s + window) for s in starts]
116
-
117
-
118
- def _unary(x, crf):
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):
169
- """Index of the sentence each token belongs to (by the token's middle character)."""
170
- ends = np.asarray([m.end() for m in _SENTENCE_END.finditer(text)], np.int64)
171
- middle = (offsets[:, 0] + np.maximum(offsets[:, 1] - 1, offsets[:, 0])) // 2
172
- return np.searchsorted(ends, middle, side="right")
173
-
174
-
175
- def _sentence_vote(labels, sentence):
176
- labels = labels.copy()
177
- cut = np.flatnonzero(np.diff(sentence)) + 1
178
- for a, b in zip(np.r_[0, cut], np.r_[cut, len(labels)]):
179
- labels[a:b] = np.bincount(labels[a:b], minlength=3).argmax()
180
- return labels
181
-
182
-
183
- def _merge_short(labels, l_min):
184
- """Merge runs shorter than l_min tokens into a neighbour (the longer one when the two neighbours differ)."""
185
- if l_min <= 1 or not len(labels):
186
- return labels
187
- cut = np.flatnonzero(np.diff(labels)) + 1
188
- runs = [[int(labels[a]), int(b - a)] for a, b in zip(np.r_[0, cut], np.r_[cut, len(labels)])]
189
- while len(runs) > 1:
190
- i = next((k for k, (_, n) in enumerate(runs) if n < l_min), None)
191
- if i is None:
192
- break
193
- if i == 0 or i == len(runs) - 1:
194
- j = 1 if i == 0 else i - 1
195
- elif runs[i - 1][0] == runs[i + 1][0]:
196
- j = i - 1
197
- else:
198
- j = i - 1 if runs[i - 1][1] >= runs[i + 1][1] else i + 1
199
- runs[j][1] += runs[i][1]
200
- del runs[i]
201
- k = 0
202
- while k < len(runs) - 1:
203
- if runs[k][0] == runs[k + 1][0]:
204
- runs[k][1] += runs[k + 1][1]
205
- del runs[k + 1]
206
- else:
207
- k += 1
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
237
- self.backbone = AutoModel.from_pretrained(path / "backbone", attn_implementation="sdpa")
238
- self.backbone = self.backbone.float().to(self.device).eval()
239
- self.heads = {k: v.float().to(self.device) for k, v in load_file(path / "head.safetensors").items()}
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)
247
- tok, seg = np.zeros((n, 3), np.float32), np.zeros((n, 3), np.float32)
248
- count, mix, mix_weight = np.zeros(n, np.float32), np.zeros(n, np.float32), np.zeros(n, np.float32)
249
- windows = _windows(n, self.meta["window"], self.meta["stride"])
250
- cls, sep, pad = self.tokenizer.cls_token_id, self.tokenizer.sep_token_id, self.tokenizer.pad_token_id
251
- linear = torch.nn.functional.linear
252
- for k in range(0, len(windows), self.batch_size):
253
- batch = windows[k:k + self.batch_size]
254
- width = max(b - a for a, b in batch) + 2
255
- input_ids = np.full((len(batch), width), pad, np.int64)
256
- mask = np.zeros((len(batch), width), np.int64)
257
- for r, (a, b) in enumerate(batch):
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):
278
- size = b - a
279
- tok[a:b] += token_logits[r, 1:size + 1]
280
- seg[a:b] += log_prior[r]
281
- count[a:b] += 1
282
- centre = 1 - np.abs(np.arange(size) - (size - 1) / 2) / ((size + 1) / 2)
283
- mix[a:b] += centre * log_odds[r]
284
- mix_weight[a:b] += centre
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__":
447
- main()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
model.json DELETED
@@ -1,29 +0,0 @@
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 DELETED
@@ -1,2 +0,0 @@
1
- torch>=2.6
2
- transformers==5.20.2
 
 
 
tokenizer/tokenizer.json DELETED
The diff for this file is too large to render. See raw diff
 
tokenizer/tokenizer_config.json DELETED
@@ -1,17 +0,0 @@
1
- {
2
- "backend": "tokenizers",
3
- "clean_up_tokenization_spaces": true,
4
- "cls_token": "[CLS]",
5
- "is_local": true,
6
- "local_files_only": false,
7
- "mask_token": "[MASK]",
8
- "model_input_names": [
9
- "input_ids",
10
- "attention_mask"
11
- ],
12
- "model_max_length": 1000000000,
13
- "pad_token": "[PAD]",
14
- "sep_token": "[SEP]",
15
- "tokenizer_class": "TokenizersBackend",
16
- "unk_token": "[UNK]"
17
- }