plslokeshreddy's picture
Initial release
758867f
Raw History Blame Contribute Delete
13 kB
"""Scoring chain of the detector (CPU, numpy only).
Per token: 6 features (log-probabilities of the token head and of the window-head prior) -> calibrated class scores with a
fitted lean toward "human" -> word labels -> each sentence takes its majority label -> short pieces are merged ->
share of the text per label -> verdict: Human if the human share is at least 90%, AI if the AI-generated share is at
least 80%, otherwise Mixed. All fitted values are in scoring_params.json.
"""
import glob, hashlib, json, math, os, pickle, re, sys, time, unicodedata
from multiprocessing import Pool
import numpy as np
HUMAN, ASSISTED, GENERATED = 0, 1, 2
CLASS_NAMES = ['human', 'assisted', 'generated']
LOG_CLIP = 1e-4 # probabilities are clipped to [LOG_CLIP, 1] before the log (logits are not stored)
HUMAN_MIN_FRACTION = 0.90 # document rule of section 5.1
AI_MIN_FRACTION = 0.80
# ---------------------------------------------------------------- text clean-up (copy of _h100/bench/serve.py, used by the dump)
BYLINE = re.compile(r'^(By \. [^.]{3,60} \. )?((PUBLISHED|UPDATED|Last updated at)[^.]{0,80}\. (\| )?)*')
ZW = dict.fromkeys(map(ord, '​‌‍‎‏⁠­'))
CONF = str.maketrans('АВЕКМНОРСТХаеорсухіјѕԁԛԝΑΒΕΖΗΙΚΜΝΟΡΤΥΧο', 'ABEKMHOPCTXaeopcyxijsdqwABEZHIKMNOPTYXo')
def clean_chars(t):
t = unicodedata.normalize('NFKC', t.translate(ZW))
lat = sum('a' <= c.lower() <= 'z' for c in t); oth = sum(c.isalpha() for c in t) - lat
return t.translate(CONF) if lat > 2 * oth else t
def norm_text(t):
"""The dump tokenised norm(text) for rows without spans and the raw text for rows with spans."""
t = clean_chars(t)
for x, y in (('’', "'"), ('‘', "'"), ('“', '"'), ('”', '"'), ('—', ' - '), ('–', '-'), ('…', '...')):
t = t.replace(x, y)
return BYLINE.sub('', ' '.join(t.split()))
# ---------------------------------------------------------------- token and sentence geometry
PIECE_RE = re.compile(r'\s*(?:\w+|[^\w\s])')
SENT_END_RE = re.compile(r'[.!?]+["\')\]”’]*(?=\s|$)|\n[ \t]*\n')
def token_bounds(n, text, offsets=None):
"""Character boundaries of n tokens: array of n + 1 increasing positions, a complete partition of the text.
With stored offsets the boundaries are the token starts. Without them (no tokenizer on this machine) the tokens are
spread over word and punctuation pieces of the text in proportion: an approximation."""
n_char = len(text)
if offsets is not None and len(offsets) == n:
b = np.empty(n + 1); b[:n] = [o[0] for o in offsets]; b[0] = 0; b[n] = max(n_char, offsets[-1][1])
return np.maximum.accumulate(b)
ends = np.array([0] + [m.end() for m in PIECE_RE.finditer(text)], dtype=float)
if len(ends) < 2:
return np.linspace(0, max(n_char, 1), n + 1)
ends[-1] = n_char
return np.interp(np.arange(n + 1) * (len(ends) - 1) / n, np.arange(len(ends)), ends)
def sentence_ids(text, bounds):
"""Sentence index of every token, by the character midpoint of the token."""
ends = [m.end() for m in SENT_END_RE.finditer(text)]
mid = (bounds[:-1] + bounds[1:]) / 2
return np.searchsorted(np.array(ends, dtype=float), mid, side='right')
def char_labels_from_spans(spans, n_char):
"""True label of every character; characters between two spans take the label of the span before them."""
lab = np.zeros(n_char, dtype=np.int8); prev_end = 0; prev_lab = spans[0][2]
for s, e, l in spans:
lab[prev_end:s] = prev_lab; lab[s:e] = l; prev_end, prev_lab = e, l
lab[prev_end:] = prev_lab
return lab
# ---------------------------------------------------------------- features and unaries
def features(row):
p = np.clip(row['probs'].astype(np.float64), LOG_CLIP, 1.0); s = np.clip(row['segp'].astype(np.float64), LOG_CLIP, 1.0)
return np.concatenate([np.log(p), np.log(s)], 1)
def unaries(x, params, delta=None):
"""u_i(c) = alpha_c + w_c . x_i + delta_c"""
d = np.asarray(params['delta'] if delta is None else delta, dtype=np.float64)
return x @ np.asarray(params['w'], dtype=np.float64).T + np.asarray(params['alpha'], dtype=np.float64) + d
def mixed_log_odds(row, n):
"""m_i at the n - 1 boundaries from an optional 'mixp' field (scalar per document, or per token). None when absent."""
q = row.get('mixp')
if q is None:
return None
q = np.clip(np.atleast_1d(np.asarray(q, dtype=np.float64)).ravel(), 1e-6, 1 - 1e-6); m = np.log(q) - np.log1p(-q)
if len(m) == n:
return (m[:-1] + m[1:]) / 2
return np.full(max(n - 1, 0), m.mean())
def transition(n, lam, gamma=0.0, m=None):
"""Potts off-diagonal score at each boundary: min(0, -lambda + gamma * m_i). gamma = 0 when there is no mixed head."""
if m is None or gamma == 0.0:
return np.full(max(n - 1, 0), -float(lam))
return np.minimum(0.0, -float(lam) + gamma * m)
# ---------------------------------------------------------------- CRF: batched Viterbi and forward-backward
OFF_DIAG = 1.0 - np.eye(3)
def _pad(us, taus):
lens = np.array([len(u) for u in us]); t_max = lens.max(); u = np.zeros((len(us), t_max, 3)); tau = np.zeros((len(us), max(t_max - 1, 1)))
for k, (a, b) in enumerate(zip(us, taus)):
u[k, :len(a)] = a; tau[k, :len(b)] = b
return u, tau, lens
def viterbi_batch(us, taus):
"""MAP label sequence of each document. us: list of [n,3] unaries, taus: list of [n-1] off-diagonal scores (<= 0)."""
u, tau, lens = _pad(us, taus); n_doc, t_max, _ = u.shape
back = np.zeros((t_max, n_doc, 3), dtype=np.int8); d = u[:, 0].copy()
for t in range(1, t_max):
sc = d[:, :, None] + tau[:, t - 1, None, None] * OFF_DIAG # [doc, from, to]; padding has tau = 0 and u = 0
back[t] = sc.argmax(1); d = sc.max(1) + u[:, t]
path = np.zeros((n_doc, t_max), dtype=np.int8); cur = d.argmax(1); rng = np.arange(n_doc)
for t in range(t_max - 1, -1, -1):
path[:, t] = cur
if t:
cur = back[t, rng, cur]
return [path[k, :lens[k]] for k in range(n_doc)]
def _lse(a, axis):
m = a.max(axis, keepdims=True)
return (m + np.log(np.exp(a - m).sum(axis, keepdims=True))).squeeze(axis)
def marginals_batch(us, taus):
"""P(T_i = c | all observations) for each document, by a log-space forward-backward pass."""
u, tau, lens = _pad(us, taus); n_doc, t_max, _ = u.shape
fw = np.zeros((n_doc, t_max, 3)); bw = np.zeros((n_doc, t_max, 3)); fw[:, 0] = u[:, 0]
for t in range(1, t_max):
fw[:, t] = _lse(fw[:, t - 1, :, None] + tau[:, t - 1, None, None] * OFF_DIAG, 1) + u[:, t]
for k in range(n_doc): # beta is 0 at the true last token of each document
bw[k, lens[k]:] = np.nan
for t in range(t_max - 2, -1, -1):
nxt = _lse(tau[:, t, None, None] * OFF_DIAG + (u[:, t + 1] + np.nan_to_num(bw[:, t + 1]))[:, None, :], 2)
live = (t + 1 < lens)[:, None]
bw[:, t] = np.where(live, nxt, 0.0)
out = []
for k in range(n_doc):
g = fw[k, :lens[k]] + np.nan_to_num(bw[k, :lens[k]]); g -= g.max(1, keepdims=True); g = np.exp(g)
out.append(g / g.sum(1, keepdims=True))
return out
def crf_decode(us, taus, with_marginals=False, batch=256):
"""Viterbi (and optionally marginals) for many documents; documents are batched by length."""
order = np.argsort([len(u) for u in us]); paths = [None] * len(us); margs = [None] * len(us)
for b0 in range(0, len(order), batch):
idx = order[b0:b0 + batch]; bu = [us[i] for i in idx]; bt = [taus[i] for i in idx]
for i, p in zip(idx, viterbi_batch(bu, bt)):
paths[i] = p
if with_marginals:
for i, g in zip(idx, marginals_batch(bu, bt)):
margs[i] = g
return paths, margs
# ---------------------------------------------------------------- sentence voting, minimum run length, document rule
def sentence_vote(labels, sent):
"""Every token takes the majority Viterbi label of its sentence. Tie-break: the lowest class index (human first)."""
n_sent = int(sent[-1]) + 1; cnt = np.zeros((n_sent, 3), dtype=np.int64)
np.add.at(cnt, (sent, labels), 1)
return cnt.argmax(1).astype(np.int8)[sent]
def merge_short_runs(labels, l_min):
"""Repeatedly merge the first run shorter than l_min tokens into a neighbour (report 4.3.3).
One neighbour: its label. Same label on both sides: that label. Else the longer neighbour; equal lengths: the left one."""
if l_min <= 1 or len(labels) == 0:
return labels
cut = np.flatnonzero(np.diff(labels)) + 1
if len(cut) == 0:
return labels
starts = np.concatenate([[0], cut]); lens = list(np.diff(np.concatenate([starts, [len(labels)]]))); labs = [int(labels[s]) for s in starts]
while len(labs) > 1:
k = next((j for j, n in enumerate(lens) if n < l_min), None)
if k is None:
break
if k == 0:
new = labs[1]
elif k == len(labs) - 1:
new = labs[k - 1]
elif labs[k - 1] == labs[k + 1]:
new = labs[k - 1]
else:
new = labs[k - 1] if lens[k - 1] >= lens[k + 1] else labs[k + 1]
labs[k] = new; nl, nn = [labs[0]], [lens[0]]
for a, b in zip(labs[1:], lens[1:]):
if a == nl[-1]:
nn[-1] += b
else:
nl.append(a); nn.append(b)
labs, lens = nl, nn
return np.repeat(np.array(labs, dtype=np.int8), lens)
def fractions(labels, bounds):
w = np.diff(bounds); tot = max(w.sum(), 1e-9)
return np.array([w[labels == c].sum() / tot for c in range(3)])
def verdict(f):
"""Document rule of section 5.1. f = (human, assisted, generated) character fractions; f_AI is the generated fraction."""
if f[HUMAN] >= HUMAN_MIN_FRACTION:
return 'Human'
if f[GENERATED] >= AI_MIN_FRACTION:
return 'AI'
return 'Mixed'
def constrain(path, sent, l_min):
if path[0] == path[-1] and (path == path[0]).all():
return path
return merge_short_runs(sentence_vote(path, sent), l_min)
# ---------------------------------------------------------------- public API
def load_params(path):
return json.load(open(path))
def prepare(row, text=None):
"""Features and geometry of one dump row. text must be the string that was tokenised (see norm_text); when it is None
the tokens get equal character lengths and each token is its own sentence group of ~25 tokens."""
n = len(row['probs'])
if text is None:
bounds = np.arange(n + 1, dtype=float); sent = np.arange(n) // 25
else:
bounds = token_bounds(n, text, row.get('offsets')); sent = sentence_ids(text, bounds)
return dict(x=features(row), bounds=bounds, sent=sent, m=mixed_log_odds(row, n))
def decode_prepared(preps, params, with_marginals=True):
us = [unaries(p['x'], params) for p in preps]
taus = [transition(len(u), params['lambda'], params.get('gamma', 0.0), p['m']) for u, p in zip(us, preps)]
paths, margs = crf_decode(us, taus, with_marginals)
out = []
for p, path, g in zip(preps, paths, margs):
final = constrain(path, p['sent'], params['l_min']); f = fractions(final, p['bounds'])
d = dict(verdict=verdict(f), f_human=float(f[0]), f_assisted=float(f[1]), f_generated=float(f[2]),
f_ai_weighted=float(0.5 * f[1] + f[2]), labels=final, viterbi=path)
if g is not None:
conf = g.max(1); cut = np.concatenate([[0], np.flatnonzero(np.diff(final)) + 1, [len(final)]]); b = p['bounds']
d['marginals'] = g.astype(np.float32)
d['segments'] = [dict(char_start=int(round(b[s])), char_end=int(round(b[e])), label=CLASS_NAMES[final[s]],
confidence=float(conf[s:e].mean())) for s, e in zip(cut[:-1], cut[1:])]
out.append(d)
return out
def decode_documents(rows, params, texts=None, with_marginals=True):
"""rows: dump rows (id, probs [n,3], segp [n,3]; optional offsets, spans, mixp, text). texts: optional {id: raw text}.
Returns one dict per row: id, verdict (Human / Mixed / AI), f_human, f_assisted, f_generated, f_ai_weighted,
labels (final per-token labels), viterbi (per-token labels before the sentence and length constraints),
marginals (CRF token posteriors), segments (character ranges with label and confidence)."""
preps = []
for r in rows:
t = r.get('text') if r.get('text') is not None else (texts or {}).get(r['id'])
if t is not None and not r.get('spans') and r.get('text') is None:
t = norm_text(t) # the dump tokenised the cleaned text for rows without spans
preps.append(prepare(r, t))
out = decode_prepared(preps, params, with_marginals)
for r, d in zip(rows, out):
d['id'] = r['id']
return out