File size: 13,933 Bytes
28f22d2
a03b48c
cff7711
 
 
a03b48c
bdd2818
 
cff7711
 
a03b48c
28f22d2
4e32a51
 
cff7711
a03b48c
cff7711
28f22d2
cff7711
 
 
a03b48c
cff7711
 
 
 
a03b48c
cff7711
 
a03b48c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cff7711
a03b48c
28f22d2
4e32a51
 
 
 
 
 
28f22d2
 
 
 
 
 
4e32a51
28f22d2
a03b48c
 
 
 
 
cff7711
 
a03b48c
 
 
 
 
 
 
 
 
 
 
 
 
 
cff7711
 
a03b48c
 
 
 
 
 
 
bdd2818
 
 
 
 
 
 
 
a03b48c
cff7711
a03b48c
 
 
 
cff7711
a03b48c
 
 
 
bdd2818
a03b48c
 
 
 
 
28f22d2
 
 
a03b48c
 
 
 
cff7711
 
a03b48c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
28f22d2
a03b48c
 
 
 
 
 
cff7711
 
 
a03b48c
 
 
 
 
 
cff7711
 
a03b48c
 
 
 
9de24cf
cff7711
 
 
9de24cf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cff7711
 
 
9de24cf
 
 
 
 
 
 
 
 
 
 
 
a03b48c
 
cff7711
 
a03b48c
 
 
 
9de24cf
a03b48c
 
9de24cf
a03b48c
9de24cf
 
 
a03b48c
 
 
 
 
 
28f22d2
 
a03b48c
28f22d2
a03b48c
 
 
cff7711
 
 
a03b48c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bdd2818
a03b48c
 
cff7711
a03b48c
 
 
 
cff7711
a03b48c
 
 
 
 
 
 
 
 
 
cff7711
a03b48c
 
 
 
 
 
9de24cf
a03b48c
9de24cf
 
a03b48c
 
 
 
 
 
 
 
 
 
 
 
28f22d2
a03b48c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
"""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()