"""AI-text detector as one Transformers model: text encoder (LoRA already merged in) + token head + window head + scoring. from transformers import AutoModel, AutoTokenizer tok = AutoTokenizer.from_pretrained(REPO, trust_remote_code=True) model = AutoModel.from_pretrained(REPO, trust_remote_code=True).to('cuda').eval() r = model.analyze("some text ...", tok) # r['verdict'] is 'Human', 'Mixed' or 'AI' """ import numpy as np import torch import torch.nn as nn from transformers import AutoConfig, AutoModel, PreTrainedModel from transformers.utils import ModelOutput from .configuration_detector import AiTextDetectorConfig from .scoring import decode_prepared, norm_text, prepare LABELS = {'human': 'human', 'assisted': 'ai_assisted', 'generated': 'ai_generated'} class AiTextDetectorModel(PreTrainedModel): config_class = AiTextDetectorConfig base_model_prefix = 'encoder' _keep_in_fp32_modules_strict = ['token_head', 'window_head'] _keep_in_fp32_modules = ['token_head', 'window_head'] # the encoder runs in bfloat16; the two small heads stay in float32 def __init__(self, config): super().__init__(config) tc = dict(config.text_config); mt = tc.pop('model_type') self.encoder = AutoModel.from_config(AutoConfig.for_model(mt, **tc)) H = self.encoder.config.hidden_size self.token_head = nn.Linear(H, config.num_token_classes) # per token: human / AI-assisted / AI-generated self.window_head = nn.Linear(H, config.num_share_buckets) # per window: AI share of the window, in 15 steps from 0 to 1 self.post_init() def forward(self, input_ids, attention_mask=None, **kwargs): """Raw outputs for one batch of windows. For texts, use analyze(); it does the windowing and the scoring. The window head is read at the last real token of each row.""" if attention_mask is None: attention_mask = torch.ones_like(input_ids) h = self.encoder(input_ids=input_ids, attention_mask=attention_mask).last_hidden_state if self.token_head.weight.dtype != torch.float32: self.token_head.float(); self.window_head.float() hf = h.float(); last = hf[torch.arange(h.shape[0], device=h.device), attention_mask.sum(1) - 1] return ModelOutput(token_logits=self.token_head(hf), window_logits=self.window_head(last), last_hidden_state=h) @torch.no_grad() def _token_probs(self, text, tok, batch_size): cfg, dev = self.config, self.device W, S = cfg.window_tokens, cfg.window_step enc = tok(text, return_offsets_mapping=True); ids = enc['input_ids'][:cfg.max_tokens + 1]; off = enc['offset_mapping'][1:len(ids)] body = ids[1:]; n = len(body); step = W - 1 if n == 0: return np.zeros((0, 3)), np.zeros((0, 3)), [] starts = [0] if n <= step else list(range(0, n - step, S)) + [n - step] # the last window ends at the end of the text units = [(st, ids[:1] + body[st:st + step]) for st in starts] fb = torch.linspace(0, 1, cfg.num_share_buckets, device=dev) phi = torch.stack([torch.clamp(1 - 2 * fb, min=0), torch.clamp(1 - 2 * (fb - 0.5).abs(), min=0), torch.clamp(2 * fb - 1, min=0)], 1) # AI share -> human / assisted / generated tot = np.zeros((n, 3)); pri_tot = np.zeros((n, 3)); cnt = np.zeros((n, 1)) for b0 in range(0, len(units), batch_size): xs = [u[1] for u in units[b0:b0 + batch_size]] seqs = [x + x[1:] for x in xs]; m = max(map(len, seqs)) # the window is given two times; labels are read on copy 2 I = torch.full((len(seqs), m), tok.pad_token_id, dtype=torch.long); A = torch.zeros(len(seqs), m, dtype=torch.long) for k, q in enumerate(seqs): I[k, :len(q)] = torch.tensor(q); A[k, :len(q)] = 1 out = self(input_ids=I.to(dev), attention_mask=A.to(dev)) pr = torch.softmax(out.token_logits.float(), -1).cpu().numpy(); sp = torch.softmax(out.window_logits.float(), -1) pri = sp @ phi; pri = (pri / pri.sum(1, keepdim=True)).cpu().numpy() for k, x in enumerate(xs): st = units[b0 + k][0]; p = pr[k, len(x):2 * len(x) - 1] tot[st:st + len(p)] += p; pri_tot[st:st + len(p)] += pri[k]; cnt[st:st + len(p)] += 1 c = np.maximum(cnt, 1) return tot / c, pri_tot / c, off def analyze(self, text, tokenizer, batch_size=8): """Verdict for one text. Returns dict(verdict, share, segments, words, tokens, short, truncated, text_scored). segments are character ranges of text_scored (the text after the same clean-up as in training).""" text = norm_text(text) P, SP, off = self._token_probs(text, tokenizer, batch_size) if len(P) == 0: return dict(error='empty text') d = decode_prepared([prepare(dict(probs=P, segp=SP, offsets=off), text)], self.config.scoring_params, with_marginals=True)[0] segs = [dict(start=max(0, g['char_start']), end=min(len(text), g['char_end']), label=LABELS[g['label']], confidence=round(g['confidence'], 3)) for g in d['segments']] segs = [s for s in segs if s['end'] > s['start']] if segs: segs[0]['start'] = 0; segs[-1]['end'] = len(text) words = len(text.split()) return dict(verdict=d['verdict'], share=dict(human=round(d['f_human'], 4), ai_assisted=round(d['f_assisted'], 4), ai_generated=round(d['f_generated'], 4)), segments=segs, words=words, tokens=len(P), short=words < 50, truncated=len(P) >= self.config.max_tokens, text_scored=text) def detect(self, texts, tokenizer, batch_size=8): """Verdicts for a list of texts: ['Human' | 'Mixed' | 'AI', ...].""" return [self.analyze(t, tokenizer, batch_size).get('verdict') for t in texts]