""" Qwen2.5-0.5B perplexity scorer. This module wraps the Qwen2.5-0.5B causal language model for fast, CPU-based perplexity scoring of individual sentences. Design decisions: - Model is loaded once at application startup (PerplexityScorer.__init__) and shared across all requests. - All inference is wrapped in @torch.no_grad() to reduce memory pressure. - torch_dtype=torch.float32 and device_map="cpu" for reliable CPU deployment. - Sentence-level scoring is used (not token-level) to produce a single mean perplexity value per sentence. """ from __future__ import annotations import logging import math from dataclasses import dataclass, field from typing import Optional import torch # type: ignore from transformers import AutoModelForCausalLM, AutoTokenizer # type: ignore logger = logging.getLogger(__name__) # --------------------------------------------------------------------------- # Result dataclasses # --------------------------------------------------------------------------- @dataclass class TokenPerplexitySpan: """A contiguous span of tokens with an associated perplexity score.""" tokens: str perplexity: float @dataclass class SentencePerplexityResult: """Perplexity analysis result for a single sentence.""" sentence_index: int sentence_text: str mean_perplexity: float classification: str # "high_risk" | "medium_risk" | "low_risk" low_perplexity_spans: list[TokenPerplexitySpan] = field(default_factory=list) @dataclass class PerplexityResult: """Aggregate perplexity result for an entire piece of text.""" mean_perplexity: float sentence_results: list[SentencePerplexityResult] # --------------------------------------------------------------------------- # PerplexityScorer # --------------------------------------------------------------------------- class PerplexityScorer: """Wrapper around Qwen2.5-0.5B for fast, CPU-based perplexity scoring. Usage:: scorer = PerplexityScorer() # load once at startup result = scorer.score_sentence("Some text.") # per-sentence scoring results = scorer.score_sentences(["S1.", "S2."]) Thresholds (configurable via constructor): high_risk : mean_perplexity < 30 medium_risk: 30 ≤ mean_perplexity < 60 low_risk : mean_perplexity ≥ 60 """ def __init__( self, model_id: str = "Qwen/Qwen2.5-0.5B", high_risk_threshold: float = 30.0, medium_risk_threshold: float = 60.0, ) -> None: """Load the Qwen2.5-0.5B model and tokeniser. Args: model_id: HuggingFace model identifier. high_risk_threshold: Sentences below this perplexity are 'high_risk'. medium_risk_threshold: Sentences below this (and above high) are 'medium_risk'. """ self.model_id = model_id self.high_risk_threshold = high_risk_threshold self.medium_risk_threshold = medium_risk_threshold logger.info("Loading tokeniser for '%s' …", model_id) self.tokenizer = AutoTokenizer.from_pretrained(model_id) logger.info("Loading model '%s' (float32, CPU) …", model_id) self.model = AutoModelForCausalLM.from_pretrained( model_id, dtype=torch.float32, device_map="cpu", ) self.model.eval() logger.info("PerplexityScorer ready.") # ------------------------------------------------------------------ # Public API # ------------------------------------------------------------------ def score_sentence( self, sentence: str, sentence_index: int = 0, compute_spans: bool = False, ) -> SentencePerplexityResult: """Score a single sentence. Args: sentence: Text of the sentence to score. sentence_index: Index of the sentence in the parent document (used for downstream instruction generation). compute_spans: If True, run sliding-window span detection to find low-perplexity token subsequences. Disabled by default because it adds ~900ms per sentence (16 extra forward passes). Enable only for debugging or the /analyze debug endpoint. Returns: SentencePerplexityResult with mean_perplexity and classification. """ mean_ppl = self._compute_mean_perplexity(sentence) classification = self._classify(mean_ppl) low_spans = ( self._find_low_perplexity_spans(sentence) if compute_spans else [] ) return SentencePerplexityResult( sentence_index=sentence_index, sentence_text=sentence, mean_perplexity=round(mean_ppl, 2), classification=classification, low_perplexity_spans=low_spans, ) def score_sentences( self, sentences: list[str] ) -> list[SentencePerplexityResult]: """Score multiple sentences. Args: sentences: List of sentence strings. Returns: List of SentencePerplexityResult in the same order. """ results: list[SentencePerplexityResult] = [] for idx, sent in enumerate(sentences): if not sent.strip(): # Skip empty sentences — assign low risk results.append( SentencePerplexityResult( sentence_index=idx, sentence_text=sent, mean_perplexity=100.0, classification="low_risk", ) ) continue results.append(self.score_sentence(sent, sentence_index=idx)) return results def score_text(self, text: str) -> PerplexityResult: """Score an entire text by splitting on newlines and spaces. Convenience method when sentence splitting is not needed. Args: text: Any string. Returns: PerplexityResult with per-sentence breakdown and overall mean. """ # Basic sentence split for standalone usage import re raw_sentences = re.split(r"(?<=[.!?])\s+", text.strip()) sentences = [s.strip() for s in raw_sentences if s.strip()] sentence_results = self.score_sentences(sentences) all_ppls = [r.mean_perplexity for r in sentence_results] overall_mean = sum(all_ppls) / len(all_ppls) if all_ppls else 0.0 return PerplexityResult( mean_perplexity=round(overall_mean, 2), sentence_results=sentence_results, ) # ------------------------------------------------------------------ # Private helpers # ------------------------------------------------------------------ @torch.no_grad() def _compute_mean_perplexity(self, text: str) -> float: """Compute mean token-level perplexity for *text* using Qwen2.5-0.5B. Args: text: Any string (typically one sentence). Returns: Float perplexity value. Returns 100.0 on error. """ try: encodings = self.tokenizer( text, return_tensors="pt", truncation=True, max_length=512, ) input_ids: torch.Tensor = encodings["input_ids"] if input_ids.shape[1] < 2: # Single-token text — cannot compute meaningful perplexity return 100.0 labels = input_ids.clone() outputs = self.model(input_ids=input_ids, labels=labels) # outputs.loss is the mean negative log-likelihood over tokens loss: torch.Tensor = outputs.loss return float(math.exp(loss.item())) except Exception as exc: logger.warning("Perplexity computation failed for text '%s…': %s", text[:40], exc) return 100.0 def _classify(self, mean_perplexity: float) -> str: """Map a perplexity value to a risk classification string. Args: mean_perplexity: The computed perplexity score. Returns: 'high_risk', 'medium_risk', or 'low_risk'. """ if mean_perplexity < self.high_risk_threshold: return "high_risk" if mean_perplexity < self.medium_risk_threshold: return "medium_risk" return "low_risk" @torch.no_grad() def _find_low_perplexity_spans( self, sentence: str, window_size: int = 4, threshold: float = 15.0, ) -> list[TokenPerplexitySpan]: """Identify low-perplexity token spans within a sentence. Uses a sliding window over tokens to find subsequences that are particularly predictable (i.e. likely AI-generated). Args: sentence: The sentence to scan. window_size: Number of tokens per window. threshold: Perplexity below this is considered a 'low' span. Returns: List of TokenPerplexitySpan objects (may be empty). """ spans: list[TokenPerplexitySpan] = [] try: encodings = self.tokenizer( sentence, return_tensors="pt", truncation=True, max_length=512, ) input_ids: torch.Tensor = encodings["input_ids"] n_tokens = input_ids.shape[1] if n_tokens < window_size + 1: return spans for start in range(1, n_tokens - window_size): window_ids = input_ids[:, start : start + window_size] context_ids = input_ids[:, :start] # Score the window given the full context full_ids = torch.cat([context_ids, window_ids], dim=1) labels = full_ids.clone() # Mask context labels so only window tokens contribute to loss labels[:, : context_ids.shape[1]] = -100 outputs = self.model(input_ids=full_ids, labels=labels) window_ppl = float(math.exp(outputs.loss.item())) if window_ppl < threshold: token_str = self.tokenizer.decode( window_ids[0], skip_special_tokens=True ).strip() if token_str: spans.append( TokenPerplexitySpan( tokens=token_str, perplexity=round(window_ppl, 2), ) ) except Exception as exc: logger.debug("Low-perplexity span detection failed: %s", exc) return spans