From 01bc2bbcb1d09fde7ea35c1b281c323fc2bd3eef Mon Sep 17 00:00:00 2001 From: ichen27 Date: Sun, 15 Nov 2026 17:34:01 -0500 Subject: [PATCH] Add a private-writing test that keeps texts and per-document scores out of the repository private_eval scores documents listed in RAW_DATA_DIR/private with Clef, Binoculars and both classifiers, then reports how many each detector flags using the bar and combination weights already set on the long set's calibration half. The detectors' entry points now accept any list of texts. --- AGENTS.md | 3 + README.md | 17 ++++ src/detecteval/binoculars.py | 10 ++- src/detecteval/classify.py | 20 +++-- src/detecteval/items.py | 28 +++++- src/detecteval/private_eval.py | 152 +++++++++++++++++++++++++++++++++ src/detecteval/score_long.py | 7 +- tests/test_long_set.py | 14 +++ 8 files changed, 237 insertions(+), 14 deletions(-) create mode 100644 src/detecteval/private_eval.py diff --git a/AGENTS.md b/AGENTS.md index 9be5c38..7e64c4e 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -20,6 +20,7 @@ classifier fine-tuned on examples. It is an evaluation harness, not a detector p `build_long_set`, `generate_long`, `score_long`. - Local detectors: `binoculars`; `generate_mirrors`, `train_data`, `train_classifier`, `classify`. - Comparison of everything on held-out halves: `compare`, `compare_report`. + - Private writing: `private_eval` scores documents listed in `RAW_DATA_DIR/private/manifest.jsonl`. - `data/` — both evaluation sets, the texts generated for them, and the training mirrors (committed). - `results/` — scores per detector, summaries, reports and figures (committed deliverables). - Raw third-party downloads and trained model weights live outside Git in `RAW_DATA_DIR` (default @@ -40,6 +41,8 @@ classifier fine-tuned on examples. It is an evaluation harness, not a detector p writes one row per key, so `compare` can join them. - `generate_long` plans humanized rewrites from the fresh texts that exist when it runs. To retry failed fresh texts later, rerun only the fresh jobs, or the rewrite sample changes. +- Private documents, their titles, ids and per-document scores never enter the repository. Only the + aggregate report from `private_eval report` is committed. - Long-set texts carry a `split`. Set thresholds and fit combinations on `calib`; report on `test`. - Training data must never overlap evaluation data. `train_data` excludes every evaluation source document, uses separate Stack Exchange sites, and leaves four current generators and all student diff --git a/README.md b/README.md index a00aa9d..936aa47 100644 --- a/README.md +++ b/README.md @@ -225,6 +225,23 @@ Verified here: the pipeline ran through a private MCP gateway in front of Cloudf Pointing `MCP_URL` directly at `https://mcp.cloudflare.com/mcp` uses the same tool and should behave the same, but that path was not run. +## Testing your own writing + +Private documents written before language models were common are the cleanest test of false accusations: +they cannot be in any model's training data and cannot be AI-assisted. + +1. Create `RAW_DATA_DIR/private/manifest.jsonl` with one JSON object per line: + `{"id": "doc-001", "group": "own_pre_ai", "text": "..."}`. `group` is free text; use one group for + writing you are sure is unassisted and another for anything else. +2. `uv run python -m detecteval.private_eval clef` (paid; sends each text to Clef on your Workers AI + account), then `uv run python -m detecteval.private_eval local` (needs `uv sync --group ml` and the + trained classifiers). +3. `uv run python -m detecteval.private_eval report` writes `results/private_writing.md`. + +The flagging bar and combination weights are the ones set on the long set's calibration half, so your +documents play no part in choosing them. Texts and per-document scores stay under `RAW_DATA_DIR/private`; +the report contains counts and rates only. + ### Cost Paid calls go to Workers AI. The first study's committed scores account for about 4 million input tokens diff --git a/src/detecteval/binoculars.py b/src/detecteval/binoculars.py index 0fe7db1..3c3d9f1 100644 --- a/src/detecteval/binoculars.py +++ b/src/detecteval/binoculars.py @@ -76,7 +76,8 @@ def statistics_torch(observer_logits, performer_logits, tokens) -> dict: "log_ppl": -log_likelihood / count, "tokens": count} -def main() -> None: +def run(items: list[dict], path) -> None: + """Score ``items`` and append to ``path``; keys already in the file are skipped.""" config.cap_gpu_memory("0.45") import torch from transformers import AutoModelForCausalLM, AutoTokenizer @@ -90,10 +91,9 @@ def main() -> None: models = [AutoModelForCausalLM.from_pretrained(name, dtype=dtype).to(device).eval() for name in (OBSERVER, PERFORMER)] - path = config.RESULTS_DIR / "detectors" / "binoculars.jsonl" path.parent.mkdir(parents=True, exist_ok=True) finished = done_keys(path) - todo = sorted((item for item in all_items() if item["key"] not in finished), key=lambda item: len(item["text"])) + todo = sorted((item for item in items if item["key"] not in finished), key=lambda item: len(item["text"])) with open(path, "a") as handle, torch.no_grad(): for start in range(0, len(todo), BATCH): chunk = todo[start:start + BATCH] @@ -116,5 +116,9 @@ def main() -> None: print("done ->", path) +def main() -> None: + run(all_items(), config.RESULTS_DIR / "detectors" / "binoculars.jsonl") + + if __name__ == "__main__": main() diff --git a/src/detecteval/classify.py b/src/detecteval/classify.py index 9ef37b8..e254143 100644 --- a/src/detecteval/classify.py +++ b/src/detecteval/classify.py @@ -17,20 +17,19 @@ BATCH = 8 -def main() -> None: +def run(recipes: list[str], items: list[dict], directory) -> None: + """Score ``items`` with each trained recipe and write ``directory``/classifier-.jsonl.""" config.cap_gpu_memory() import torch from transformers import AutoModelForSequenceClassification, AutoTokenizer - parser = argparse.ArgumentParser(description=__doc__.split("\n")[0]) - parser.add_argument("recipes", nargs="+", choices=["raid", "mirrors"]) - args = parser.parse_args() device = config.torch_device() - items = sorted(all_items(), key=lambda item: len(item["text"])) - for recipe in args.recipes: + directory.mkdir(parents=True, exist_ok=True) + items = sorted(items, key=lambda item: len(item["text"])) + for recipe in recipes: tokenizer = AutoTokenizer.from_pretrained(model_dir(recipe)) model = AutoModelForSequenceClassification.from_pretrained(model_dir(recipe)).to(device).eval() - path = config.RESULTS_DIR / "detectors" / f"classifier-{recipe}.jsonl" + path = directory / f"classifier-{recipe}.jsonl" rows = [] with torch.no_grad(): for start in range(0, len(items), BATCH): @@ -49,5 +48,12 @@ def main() -> None: print(recipe, len(rows), "->", path) +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__.split("\n")[0]) + parser.add_argument("recipes", nargs="+", choices=["raid", "mirrors"]) + args = parser.parse_args() + run(args.recipes, all_items(), config.RESULTS_DIR / "detectors") + + if __name__ == "__main__": main() diff --git a/src/detecteval/items.py b/src/detecteval/items.py index dbe3d27..ab235d2 100644 --- a/src/detecteval/items.py +++ b/src/detecteval/items.py @@ -8,7 +8,7 @@ import json from . import config -from .textprep import rung_text +from .textprep import rung_text, strip_markdown def short_items() -> list[dict]: @@ -30,6 +30,32 @@ def long_items(rungs: list[int] | None = None) -> list[dict]: return out +def private_dir(): + """Private texts and their scores live with the raw downloads, never in the repository.""" + return config.raw_dir() / "private" + + +def private_documents() -> list[dict]: + """Rows of the private manifest: ``id``, ``group``, ``text`` and any dates.""" + path = private_dir() / "manifest.jsonl" + if not path.exists(): + raise SystemExit(f"no private manifest at {path}; see the README section on testing your own writing") + with open(path) as handle: + return [json.loads(line) for line in handle] + + +def private_items(rungs: list[int] | None = None) -> list[dict]: + """One item per private document and length rung it can fill, cleaned like every other text.""" + out = [] + for row in private_documents(): + for rung in rungs or config.RUNGS: + text = rung_text(strip_markdown(row["text"]), rung, config.RUNG_FILL) + if text is not None: + out.append({"key": f"{row['id']}@{rung}", "id": row["id"], "set": "private", "rung": rung, + "text": text}) + return out + + def all_items() -> list[dict]: return short_items() + long_items() diff --git a/src/detecteval/private_eval.py b/src/detecteval/private_eval.py new file mode 100644 index 0000000..1466869 --- /dev/null +++ b/src/detecteval/private_eval.py @@ -0,0 +1,152 @@ +"""Test the detectors on private writing, such as your own unpublished documents. + +Public human text may be in a model's training data, and recent public text may be AI-assisted. +Documents that were never online and were written before language models were common are the clean +test of how often a detector accuses a real person. + + python -m detecteval.private_eval clef # paid: sends each text to Clef 27B on Workers AI + python -m detecteval.private_eval local # Binoculars and both classifiers; needs the "ml" group + python -m detecteval.private_eval report # writes results/private_writing.md and .json + +Put the documents in RAW_DATA_DIR/private/manifest.jsonl, one JSON object per line: + + {"id": "doc-001", "group": "own_pre_ai", "text": "...", "modified": "2021-04-02"} + +``group`` is free text; every group is reported separately. The texts and the per-document scores stay +under RAW_DATA_DIR/private, outside the repository. The report holds counts and rates only: no text, +no titles and no document ids. The flagging bar and the combination weights are the ones set on the +calibration half of the long set, so the private documents play no part in choosing them. +""" +from __future__ import annotations + +import argparse +import collections +import json + +import numpy as np + +from . import compare, config, metrics +from .items import private_dir, private_documents, private_items + +DETECTORS = ["clef", "binoculars", "classifier-raid", "classifier-mirrors"] +COMBINATIONS = {"clef+binoculars": ["clef", "binoculars"], + "all-three": ["clef", "binoculars", "classifier-mirrors"]} +NAMES = {"clef": "Clef 27B, asked", "binoculars": "Binoculars (0.5B pair)", + "classifier-raid": "Classifier, RAID only", "classifier-mirrors": "Classifier, RAID + mirrors", + "clef+binoculars": "Clef + Binoculars", "all-three": "All three combined"} +GROUP_NAMES = {"own_pre_ai": "Written before ChatGPT (30 Nov 2022)", + "own_recent": "Written since, AI use unknown"} + + +def scores_dir(): + return private_dir() / "scores" + + +def load_private_scores() -> dict[str, dict[str, float]]: + """Scores per detector and key, oriented like ``compare.load_scores`` (higher = more likely AI).""" + directory = scores_dir() + local = compare.read_jsonl(directory / "binoculars.jsonl") + scores = { + "clef": {row["key"]: row["score"] for row in compare.read_jsonl(directory / "clef.pct_ai.jsonl")}, + "binoculars": {row["key"]: -row["binoculars"] for row in local}, + "classifier-raid": {row["key"]: row["logit"] for row in + compare.read_jsonl(directory / "classifier-raid.jsonl")}, + "classifier-mirrors": {row["key"]: row["logit"] for row in + compare.read_jsonl(directory / "classifier-mirrors.jsonl")}, + } + return {name: values for name, values in scores.items() if values} + + +def rate(values: np.ndarray, threshold: float) -> dict: + count = int((values > threshold).sum()) + return {"n": int(values.size), "flagged": count, "share": count / values.size if values.size else None, + "ci95": metrics.wilson_interval(count, int(values.size))} + + +def analyse(target_fpr: float = 0.05) -> dict: + texts, public = compare.load_texts(), compare.load_scores() + private = load_private_scores() + groups = {row["id"]: row["group"] for row in private_documents()} + out: dict = {"target_fpr": target_fpr, "documents": dict(collections.Counter(groups.values())), "rungs": {}} + for rung in config.RUNGS: + keys = compare.keys_of(texts, "long", rung, public) + calib = [key for key in keys if texts[key]["split"] == "calib" and texts[key]["label"] in ("human", "ai")] + calib_human = [key for key in calib if texts[key]["label"] == "human"] + test_human = [key for key in keys if texts[key]["split"] == "test" and texts[key]["label"] == "human"] + mine = collections.defaultdict(list) + for document, group in groups.items(): + key = f"{document}@{rung}" + if all(key in private.get(name, {}) for name in DETECTORS): + mine[group].append(key) + if len(calib_human) < 20 or not mine: + continue + entry: dict = {} + plans = {name: [name] for name in DETECTORS} | COMBINATIONS + for name, parts in plans.items(): + if not all(part in public and part in private for part in parts): + continue + if len(parts) == 1: + def score(rows, source, part=parts[0]): + return np.array([source[part][key] for key in rows]) + else: + # Weights come from the public calibration half only. + def matrix(rows, source, parts=parts): + return np.array([[source[part][key] for part in parts] for key in rows]) + model = metrics.fit_logistic(matrix(calib, public), + np.array([texts[key]["label"] == "ai" for key in calib], float)) + + def score(rows, source, model=model, matrix=matrix): + return metrics.predict_logistic(model, matrix(rows, source)) + threshold = metrics.threshold_for_fpr(score(calib_human, public), target_fpr) + entry[name] = {"public_test_humans": rate(score(test_human, public), threshold), + "groups": {group: rate(score(rows, private), threshold) for group, rows in mine.items()}} + out["rungs"][str(rung)] = entry + return out + + +def markdown(summary: dict) -> str: + lines = ["# Private writing", "", + "How often each detector flags documents that were never published. The flagging bar is the one " + f"set to flag {summary['target_fpr']:.0%} of human texts on the calibration half of the long set; " + "these documents had no part in setting it. A detector that treats this writing like other human " + f"writing should flag about {summary['target_fpr']:.0%} of it.", "", + "Documents: " + ", ".join(f"{GROUP_NAMES.get(group, group)}: {count}" + for group, count in sorted(summary["documents"].items())) + ".", + "The texts, titles and per-document scores are not in this repository."] + for rung, entry in summary["rungs"].items(): + groups = sorted({group for detector in entry.values() for group in detector["groups"]}) + lines += ["", f"## At {rung} words", "", + "| Detector | Public human texts (test half) | " + + " | ".join(GROUP_NAMES.get(group, group) for group in groups) + " |", + "|---|---|" + "---|" * len(groups)] + for name, detector in entry.items(): + cells = [] + for cell in [detector["public_test_humans"]] + [detector["groups"].get(group) for group in groups]: + cells.append("" if not cell or not cell["n"] else + f"{cell['flagged']} of {cell['n']} ({cell['share']:.0%}; " + f"{cell['ci95'][0]:.0%}-{cell['ci95'][1]:.0%})") + lines.append(f"| {NAMES[name]} | " + " | ".join(cells) + " |") + return "\n".join(lines) + "\n" + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__.split("\n")[0]) + parser.add_argument("step", choices=["clef", "local", "report"]) + args = parser.parse_args() + config.load_env() + if args.step == "clef": + from .score_long import score + score("clef", "pct_ai", config.RUNGS, private_items(), scores_dir() / "clef.pct_ai.jsonl") + elif args.step == "local": + from . import binoculars, classify + binoculars.run(private_items(), scores_dir() / "binoculars.jsonl") + classify.run(["raid", "mirrors"], private_items(), scores_dir()) + else: + summary = analyse() + (config.RESULTS_DIR / "private_writing.json").write_text(json.dumps(summary, indent=1) + "\n") + (config.RESULTS_DIR / "private_writing.md").write_text(markdown(summary)) + print(markdown(summary)) + + +if __name__ == "__main__": + main() diff --git a/src/detecteval/score_long.py b/src/detecteval/score_long.py index b4c5620..8c60be4 100644 --- a/src/detecteval/score_long.py +++ b/src/detecteval/score_long.py @@ -17,11 +17,12 @@ BATCH = 12 -def score(model: str, question: str, rungs: list[int]) -> None: - path = config.RESULTS_DIR / "scores_long" / f"{model}.{question}.jsonl" +def score(model: str, question: str, rungs: list[int], items: list[dict] | None = None, path=None) -> None: + """Score the long set, or ``items`` when given, appending to ``path``; finished keys are skipped.""" + path = path or config.RESULTS_DIR / "scores_long" / f"{model}.{question}.jsonl" path.parent.mkdir(parents=True, exist_ok=True) finished = done_keys(path) - todo = [item for item in long_items(rungs) if item["key"] not in finished] + todo = [item for item in (long_items(rungs) if items is None else items) if item["key"] not in finished] workers, failures = WorkersAI(), 0 with open(path, "a") as handle: for start in range(0, len(todo), BATCH): diff --git a/tests/test_long_set.py b/tests/test_long_set.py index 0d8f78c..c300927 100644 --- a/tests/test_long_set.py +++ b/tests/test_long_set.py @@ -38,3 +38,17 @@ def test_score_of_maps_each_question_to_zero_one(): assert score_of("ai_yes", {"noul": 0.25}) == 0.25 assert score_of("author", {"probabilities": {"human": 0.3, "ai": 0.7}}) == 0.7 assert score_of("pct_ai", {"score": 3.0}) == 0.75 + + +def test_private_items_cut_documents_to_the_rungs_they_fill(tmp_path, monkeypatch): + from detecteval import items + + monkeypatch.setenv("RAW_DATA_DIR", str(tmp_path)) + (tmp_path / "private").mkdir() + text = " ".join(f"word{n}." for n in range(200)) + (tmp_path / "private" / "manifest.jsonl").write_text( + '{"id": "doc-1", "group": "own_pre_ai", "text": "' + text + '"}\n') + found = {item["key"]: item for item in items.private_items()} + assert set(found) == {"doc-1@75", "doc-1@150"} # 200 words cannot stand for 300 or 500 + assert len(found["doc-1@150"]["text"].split()) == 150 + assert found["doc-1@75"]["set"] == "private"