Download raid/preprocess_raid.py from jed-lee/mirm_style_datasets: direct link, hf CLI and curl.
- Browser
- Download file 13.9 kB
-
https://huggingface.co/datasets/jed-lee/mirm_style_datasets/resolve/main/raid/preprocess_raid.py
- Command line
-
hf download hf://datasets/jed-lee/mirm_style_datasets/raid/preprocess_raid.py
-
curl -L -o preprocess_raid.py https://huggingface.co/datasets/jed-lee/mirm_style_datasets/resolve/main/raid/preprocess_raid.py
13.9 kB
| """prep raid for contrastive style training (which model family wrote it, or human). | |
| src : https://huggingface.co/datasets/liamdugan/raid (train.csv, 11.8gb, mit) | |
| paper : dugan et al. (2024), "raid: a shared benchmark for robust evaluation of | |
| machine-generated text detectors", acl 2024. | |
| text is only edge-stripped (see edge_strip), nothing else changes. | |
| train split only. official test has no labels, and extra is other domains | |
| (code, czech, german). | |
| primary_id_int model family: 0 human, 1 cohere, 2 llama, 3 mistral, | |
| 4 mpt, 5 openai (gpt3, chatgpt, gpt4), 6 gpt2 | |
| (base + chat versions merged) | |
| secondary_category_int human src doc (raid source_id) | |
| source_id links a human text to every gen made from its prompt + every attacked | |
| copy of those. so 1 group = same prompt, diff families, i.e. hard negs. split by | |
| group so attacked copies stay w/ their original. docs that share an identical text | |
| get split together too. model, domain, decoding, rep penalty + attack are kept as | |
| metadata cols, not labels. | |
| file is too big for memory (11.8gb vs 24gb ram), so it's streamed twice: | |
| pass 1 everything except the text, plus a hash per text. decides kept rows, | |
| the split per group and every id | |
| pass 2 streams again, writes kept rows only, in parquet shards | |
| run: python3 code/preprocessing/jed/raid/preprocess_raid.py | |
| writes: code/preprocessing/jed/raid/out/ (git-ignored) | |
| """ | |
| import hashlib | |
| import json | |
| import os | |
| import random | |
| import re | |
| import pandas as pd | |
| import pyarrow as pa | |
| import pyarrow.csv as pacsv | |
| import pyarrow.parquet as pq | |
| from dotenv import load_dotenv | |
| from huggingface_hub import hf_hub_download | |
| HERE = os.path.dirname(os.path.abspath(__file__)) | |
| OUT = os.path.join(HERE, "out") | |
| load_dotenv(os.path.join(HERE, "..", ".env")) | |
| SOURCE_REPO = "liamdugan/raid" | |
| SOURCE_FILE = "train.csv" | |
| SEED = 42 | |
| VAL_FRACTION = 0.10 | |
| ROWS_PER_SHARD = 500_000 # ~200-400mb per parquet file | |
| # model family is the label (peter, 5 oct). human 0, rest alphabetical. binary | |
| # human vs ai is still just primary_id_int == 0. | |
| # gpt2 got its own id (peter ok'd it, 7 oct): it's a 2019 base model, a diff | |
| # generation from gpt3 / chatgpt / gpt4, and writes very diff (40% cut off mid | |
| # sentence, 7.5% looping). base + chat of cohere / mistral / mpt stay together | |
| # since they're the same release. new id is appended so the old ones keep meaning | |
| PRIMARY = {"human": 0, "cohere": 1, "llama": 2, "mistral": 3, "mpt": 4, "openai": 5, "gpt2": 6} | |
| FAMILY = { | |
| "human": "human", | |
| "cohere": "cohere", "cohere-chat": "cohere", | |
| "llama-chat": "llama", | |
| "mistral": "mistral", "mistral-chat": "mistral", | |
| "mpt": "mpt", "mpt-chat": "mpt", | |
| "gpt2": "gpt2", "gpt3": "openai", "chatgpt": "openai", "gpt4": "openai", | |
| } | |
| META = ["model", "domain", "decoding", "repetition_penalty", "attack"] | |
| COLUMNS = ["text", "primary_id_int", "secondary_category_int", "source_record_id"] + META | |
| def stream(path, columns): | |
| """yield batches of the chosen cols. texts have newlines in them, and every col | |
| is read as str so ids + empty cells never get type-guessed""" | |
| reader = pacsv.open_csv( | |
| path, | |
| read_options=pacsv.ReadOptions(block_size=64 << 20), | |
| parse_options=pacsv.ParseOptions(newlines_in_values=True), | |
| convert_options=pacsv.ConvertOptions( | |
| include_columns=columns, | |
| column_types={c: pa.string() for c in columns}, | |
| strings_can_be_null=False, | |
| ), | |
| ) | |
| for batch in reader: | |
| yield batch | |
| # whitespace + zero-width + other invisible chars. python's strip() keeps u+200b, | |
| # and raid has rows that are nothing but zero-width spaces | |
| INVISIBLE = re.compile(r"[\s\u200b-\u200f\u2028-\u202f\u2060-\u206f\ufeff]+") | |
| def visible_len(s): | |
| return len(INVISIBLE.sub("", s)) | |
| def edge_strip(s): | |
| # only the whitespace at the very start + end goes. it's api / file artifacts, not | |
| # style: 99.7% of gpt3 texts start w/ "\n\n" and 99.7% of cohere base texts start | |
| # w/ a space, which no other model does. so it's a free label shortcut. the words, | |
| # and any attack inside the text (zero-width chars, extra spaces), stay as they are | |
| return s.strip() | |
| def text_hash(s): | |
| # 16-byte digest, collisions over ~6m texts are basically impossible | |
| return hashlib.blake2b(s.encode("utf-8"), digest_size=16).digest() | |
| def pass_one(path): | |
| """everything needed to decide the output, w/o holding the texts in memory""" | |
| cols = ["id", "adv_source_id", "source_id", "generation"] + META | |
| parts = [] | |
| for batch in stream(path, cols): | |
| df = batch.to_pandas() | |
| df["generation"] = [edge_strip(t) for t in df["generation"]] | |
| df["h"] = [text_hash(t) for t in df["generation"]] | |
| df["visible"] = [visible_len(t) for t in df["generation"]] | |
| parts.append(df.drop(columns="generation")) | |
| df = pd.concat(parts, ignore_index=True) | |
| df["row"] = range(len(df)) | |
| unknown = set(df["model"]) - set(FAMILY) | |
| assert not unknown, f"models w/ no family: {unknown}" | |
| df["label"] = df["model"].map(FAMILY) | |
| return df | |
| def check_source_structure(df): | |
| """raid's own promise: an attacked row points (adv_source_id) at its unattacked | |
| version, and both share 1 source_id. if this breaks, the grouping is wrong""" | |
| base = df[df["attack"] == "none"].set_index("id")["source_id"] | |
| assert base.index.is_unique, "unattacked ids are not unique" | |
| attacked = df[df["attack"] != "none"] | |
| parent = attacked["adv_source_id"].map(base) | |
| assert parent.notna().all(), "an attacked row points at a missing original" | |
| assert (parent == attacked["source_id"]).all(), "attacked row and original differ in source_id" | |
| human = df[df["model"] == "human"] | |
| assert (human.loc[human["attack"] == "none", "id"] == human.loc[human["attack"] == "none", "source_id"]).all(), \ | |
| "a human original is not its own source" | |
| def clean(df): | |
| stats = {"rows_raw": len(df)} | |
| keep = df["visible"] > 0 | |
| stats["removed_empty_or_invisible"] = int((~keep).sum()) | |
| # same text from 2 families (or human + a model) is ambiguous, so every copy goes | |
| n_labels = df[keep].groupby("h")["label"].nunique() | |
| conflicting = set(n_labels[n_labels > 1].index) | |
| is_conflict = df["h"].isin(conflicting) & keep | |
| stats["removed_conflicting"] = int(is_conflict.sum()) | |
| keep &= ~is_conflict | |
| # exact dups keep 1 copy. an attack that changed nothing leaves a copy of its | |
| # original (e.g. number attack on a text w/ no digits), so prefer the unattacked | |
| # row, then file order | |
| kept = df[keep].assign(attacked=lambda d: d["attack"] != "none") | |
| first = kept.sort_values(["h", "attacked", "row"]).drop_duplicates("h", keep="first")["row"] | |
| is_dup = keep & ~df["row"].isin(set(first)) | |
| stats["removed_duplicates"] = int(is_dup.sum()) | |
| keep &= ~is_dup | |
| # kept on purpose (real model output, spec doesn't remove them), just counted so | |
| # short refusals like "sorry, but i can't assist with that." show up in stats | |
| stats["kept_under_50_visible_chars"] = int((df[keep]["visible"] < 50).sum()) | |
| return df[keep].copy(), stats | |
| def bundles(links): | |
| """src docs that share any identical text (even a removed dup) are linked into 1 | |
| bundle. w/o this, an attacked copy could land in val while the identical text it | |
| came from sits in train under another doc""" | |
| parent = {} | |
| def find(x): | |
| while parent.get(x, x) != x: | |
| parent[x] = parent.get(parent[x], parent[x]) | |
| x = parent[x] | |
| return x | |
| shared = links.groupby("h")["source_id"].unique() | |
| for docs in shared[shared.map(len) > 1]: | |
| for d in docs[1:]: | |
| parent[find(d)] = find(docs[0]) | |
| return {d: find(d) for d in links["source_id"].unique()} | |
| def split_and_ids(df, links): | |
| """no labelled held-out split, so hold out 10% of src docs (seed 42). whole | |
| bundles move together: the human text, its gens, their attacks + any other doc | |
| sharing a text w/ them""" | |
| bundle_of = bundles(links) | |
| members = {} | |
| for d, b in bundle_of.items(): | |
| members.setdefault(b, []).append(d) | |
| order = sorted(members) | |
| random.Random(SEED).shuffle(order) | |
| target = round(len(bundle_of) * VAL_FRACTION) | |
| val_groups = set() | |
| for b in order: | |
| if len(val_groups) >= target: | |
| break | |
| val_groups.update(members[b]) | |
| df["split"] = ["validation" if g in val_groups else "train" for g in df["source_id"]] | |
| # train groups get 0..n-1 w/ no gaps for random access in the trainer, | |
| # val groups continue after them | |
| train_groups = sorted(set(df.loc[df["split"] == "train", "source_id"])) | |
| secondary = {g: i for i, g in enumerate(train_groups + sorted(val_groups & set(df["source_id"])))} | |
| df["primary_id_int"] = df["label"].map(PRIMARY).astype("int64") | |
| df["secondary_category_int"] = df["source_id"].map(secondary).astype("int64") | |
| return df, secondary, len(bundle_of) - len(members) | |
| def check(df, links): | |
| tr, va = df[df["split"] == "train"], df[df["split"] == "validation"] | |
| split_of = dict(zip(df["source_id"], df["split"])) | |
| assert (links["source_id"].map(split_of).groupby(links["h"]).nunique() == 1).all(), \ | |
| "an identical text (kept or removed copy) touches both splits" | |
| assert not set(tr["h"]) & set(va["h"]), "a text appears in both splits" | |
| assert not set(tr["source_id"]) & set(va["source_id"]), "a source document is in both splits" | |
| for col in ("primary_id_int", "secondary_category_int"): | |
| ids = sorted(tr[col].unique()) | |
| assert ids == list(range(len(ids))), f"train {col} is not contiguous from 0" | |
| assert (tr["primary_id_int"].value_counts() >= 2).all(), "a class has <2 train texts" | |
| for part, name in ((tr, "train"), (va, "validation")): | |
| assert set(part["primary_id_int"]) == set(PRIMARY.values()), f"a family is missing from {name}" | |
| assert df["id"].is_unique, "RAID id is not unique, so it cannot be source_record_id" | |
| assert (df["primary_id_int"] == df["model"].map(FAMILY).map(PRIMARY)).all(), "label does not match model" | |
| def pass_two(path, plan, n_raw): | |
| """stream again in the same order + write kept rows, shard by shard. rows are | |
| matched by position in the file, never by raid id, so a removed row can't sneak | |
| back in""" | |
| writers, counts, shard = {}, {"train": 0, "validation": 0}, {"train": 0, "validation": 0} | |
| schema = pa.schema([(c, pa.int64() if c.endswith("_int") else pa.string()) for c in COLUMNS]) | |
| def writer(split): | |
| if split not in writers or counts[split] >= ROWS_PER_SHARD * (shard[split] + 1): | |
| if split in writers: | |
| writers[split].close() | |
| shard[split] += 1 | |
| name = os.path.join(OUT, f"{split}-{shard[split]:05d}.parquet") | |
| writers[split] = pq.ParquetWriter(name, schema, compression="zstd") | |
| return writers[split] | |
| plan = plan.set_index("row") | |
| offset = 0 | |
| for batch in stream(path, ["id", "generation"]): | |
| df = batch.to_pandas() | |
| df["generation"] = [edge_strip(t) for t in df["generation"]] # same as pass 1 | |
| df.index = range(offset, offset + len(df)) | |
| offset += len(df) | |
| df = df.join(plan, how="inner") # rows not in the plan were dropped in pass 1 | |
| assert (df["id"] == df["plan_id"]).all(), "pass 2 rows are out of step with pass 1" | |
| for split, part in df.groupby("split"): | |
| part = part.rename(columns={"generation": "text", "id": "source_record_id"}) | |
| for c in META: | |
| part[c] = part[c].where(part[c] != "", None) # human rows have no decoding / rep penalty | |
| writer(split).write_table(pa.Table.from_pandas(part[COLUMNS], schema=schema, preserve_index=False)) | |
| counts[split] += len(part) | |
| assert offset == n_raw, "pass 2 read a different number of rows than pass 1" | |
| for w in writers.values(): | |
| w.close() | |
| return counts | |
| def main(): | |
| os.makedirs(OUT, exist_ok=True) | |
| for f in os.listdir(OUT): # clear stale shards from an earlier run, else they get uploaded too | |
| os.remove(os.path.join(OUT, f)) | |
| path = hf_hub_download(SOURCE_REPO, SOURCE_FILE, repo_type="dataset", | |
| token=os.environ.get("HF_TOKEN") or None) | |
| df = pass_one(path) | |
| check_source_structure(df) | |
| links = df.loc[df["visible"] > 0, ["h", "source_id"]] | |
| df, stats = clean(df) | |
| df, secondary, stats["source_documents_joined_by_shared_text"] = split_and_ids(df, links) | |
| check(df, links) | |
| plan = df[["row", "id", "split", "primary_id_int", "secondary_category_int"] + META].rename(columns={"id": "plan_id"}) | |
| written = pass_two(path, plan, stats["rows_raw"]) | |
| assert written == df["split"].value_counts().to_dict(), "pass 2 wrote a different number of rows" | |
| counts = {} | |
| for name in ("train", "validation"): | |
| part = df[df["split"] == name] | |
| counts[name] = { | |
| "rows": int(len(part)), | |
| "source_documents": int(part["source_id"].nunique()), | |
| "per_class": {k: int((part["primary_id_int"] == v).sum()) for k, v in PRIMARY.items()}, | |
| "per_model": {k: int(v) for k, v in part["model"].value_counts().sort_index().items()}, | |
| "per_attack": {k: int(v) for k, v in part["attack"].value_counts().sort_index().items()}, | |
| } | |
| with open(os.path.join(OUT, "mappings.json"), "w") as f: | |
| json.dump({ | |
| "primary_id_int": PRIMARY, | |
| "secondary_category_int": {"meaning": "RAID source_id (human source document) -> id", | |
| "map": secondary}, | |
| }, f) | |
| with open(os.path.join(OUT, "stats.json"), "w") as f: | |
| json.dump({"cleaning": stats, "splits": counts}, f, indent=1) | |
| print(json.dumps({"cleaning": stats, "splits": counts}, indent=1)) | |
| if __name__ == "__main__": | |
| main() | |