fractus-cte-atom / scripts /convert_lmsys_atom.py
thefinalboss's picture
lmsys corpus: reintegrate redacted conversations (NAME_n placeholders removed); script --drop-redacted option
b47ce82 verified
Raw History Blame Contribute Delete
6.8 kB
#!/usr/bin/env python
"""lmsys/lmsys-chat-1m -> Fractus CTE-Atom .i16 id stream (vocab 266).
Format = same as atom_corpus (scripts/convert_atom.py): each conversation is
"\n".join(turn contents) in order user, assistant, user, ... encoded with
AtomFractusTokenizer.encode -> [BOS] payload+boundaries [EOS]; docs concatenated.
Filters: language in {English, French}; redacted conversations kept with NAME_<n>
/[REDACTED] placeholders removed and spacing/punctuation collapsed (--drop-redacted to drop them); no turn flagged by
openai_moderation; non-empty turns; strict user/assistant alternation starting
with user, ending with assistant.
Usage: python convert_lmsys_atom.py --raw DIR --out PREFIX [--limit N] [--workers 6]
"""
import argparse, re, glob, json, os, sys, collections
from multiprocessing import Pool
import numpy as np
import pyarrow.parquet as pq
sys.path.insert(0, os.environ.get("ATOM_REPO", "/workspace/repo"))
from fractus.atom_tokenizer import AtomFractusTokenizer, VOCAB_SIZE
LANGS = {"English", "French"}
DROP_REDACTED = False
# lmsys PII redaction only uses NAME_<n> (3.66M hits; EMAIL_/PHONE_/ADDRESS_ absent;
# ORG_/PERSON_/URL_ <60 hits, legitimate code identifiers -> untouched).
_ONE = r"(?:NAME_\d+(?:'s)?|\[(?:REDACTED|Redacted|redacted)\])"
_PH = re.compile(r"(?<![A-Za-z0-9_])" + _ONE + r"(?:(?:[ \t]*,[ \t]*|[ \t]+(?:and|et|&)[ \t]+|[ \t]*/[ \t]*|[ \t]+)" + _ONE + r")*(?![A-Za-z0-9_])")
def clean_placeholders(text):
"""Remove NAME_<n>/[REDACTED] placeholders, collapse leftover spaces/punctuation."""
out, pos = [], 0
for m in _PH.finditer(text):
a, b = m.start(), m.end()
while a > pos and text[a - 1] in " \t": a -= 1
while b < len(text) and text[b] in " \t": b += 1
prev = text[a - 1] if a > 0 else "\n"
nxt = text[b] if b < len(text) else "\n"
rep = ""
if prev in "([" and nxt in ")]":
a -= 1; b += 1
while b < len(text) and text[b] in " \t": b += 1
while a > pos and text[a - 1] in " \t": a -= 1
prev = text[a - 1] if a > 0 else "\n"
nxt = text[b] if b < len(text) else "\n"
rep = "" if (prev == "\n" or nxt in ",.;:!?\n") else " "
elif prev in "\n([\"'":
if prev == "\n": rep = text[a:m.start()] # keep indentation
if nxt in ",;:":
b += 1
while b < len(text) and text[b] in " \t": b += 1
elif nxt in ",.;:!?)]\"'\n":
rep = ""
else:
rep = " "
out.append(text[pos:a]); out.append(rep); pos = b
out.append(text[pos:])
return "".join(out)
_tok = None
def keep(r, stats):
stats["lang:" + str(r["language"])] += 1
if r["language"] not in LANGS: return None, "lang"
if r["redacted"] and DROP_REDACTED: return None, "redacted"
if any(m.get("flagged") for m in (r["openai_moderation"] or [])): return None, "flagged"
conv = r["conversation"] or []
if not conv or len(conv) % 2: return None, "malformed"
for i, m in enumerate(conv):
if m["role"] != ("user" if i % 2 == 0 else "assistant"): return None, "malformed"
if not (m["content"] or "").strip(): return None, "empty"
if r["redacted"]:
stats["redacted_cleaned"] += 1
conv = [{"role": m["role"], "content": clean_placeholders(m["content"])} for m in conv]
if any(not m["content"].strip() for m in conv): return None, "empty"
return "\n".join(m["content"].strip() for m in conv), "kept"
def work(job):
global _tok
if _tok is None: _tok = AtomFractusTokenizer()
path, start, n, outp = job
pf = pq.ParquetFile(path); off = 0; rgs = []
for g in range(pf.num_row_groups):
m = pf.metadata.row_group(g).num_rows
if off + m > start and off < start + n: rgs.append(g); first = first if len(rgs) > 1 else off
off += m
t = pf.read_row_groups(rgs, columns=["language", "redacted", "openai_moderation", "conversation"]).slice(start - first, n).to_pylist()
stats = collections.Counter(); ids = []
for r in t:
text, why = keep(r, stats); stats[why] += 1
if text is None: continue
if why == "kept" and r["language"] == "French": stats["kept_fr"] += 1
ids.extend(_tok.encode(text))
a = np.asarray(ids, dtype=np.int16); a.tofile(outp)
stats["ids"] = int(a.size)
return dict(stats)
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--raw", required=True); ap.add_argument("--out", required=True)
ap.add_argument("--limit", type=int, default=0); ap.add_argument("--workers", type=int, default=6)
ap.add_argument("--chunk", type=int, default=5000)
ap.add_argument("--drop-redacted", action="store_true", help="drop redacted conversations instead of cleaning NAME_n placeholders")
a = ap.parse_args()
global DROP_REDACTED; DROP_REDACTED = a.drop_redacted
parts_dir = a.out + "_parts"; os.makedirs(parts_dir, exist_ok=True)
jobs = []
for p in sorted(glob.glob(os.path.join(a.raw, "*.parquet"))):
rows = pq.ParquetFile(p).metadata.num_rows
for s in range(0, rows, a.chunk):
n = min(a.chunk, rows - s)
if a.limit:
left = a.limit - sum(j[2] for j in jobs)
if left <= 0: break
n = min(n, left)
jobs.append((p, s, n, os.path.join(parts_dir, f"{os.path.basename(p)[:11]}_{s:07d}.i16")))
tot = collections.Counter()
with Pool(a.workers) as pool:
for i, st in enumerate(pool.imap(work, jobs)):
tot.update(st); print(f"{i+1}/{len(jobs)} kept={tot['kept']} ids={tot['ids']:,}", flush=True)
with open(a.out + ".i16", "wb") as f:
for j in jobs:
with open(j[3], "rb") as g: f.write(g.read())
arr = np.memmap(a.out + ".i16", dtype=np.int16, mode="r")
meta = {"source": "lmsys/lmsys-chat-1m", "tokenizer": AtomFractusTokenizer.VERSION, "vocab_size": VOCAB_SIZE,
"max_span_bytes": 32, "pack_mode": "linguistic", "dtype": "int16",
"format": "BOS + '\\n'.join(user,assistant,...) + EOS per conversation (same as atom_corpus)",
"filters": "language in {English,French}; " + ("not redacted;" if a.drop_redacted else "redacted kept, NAME_n/[REDACTED] placeholders removed;") + " no openai_moderation flag; non-empty, strictly alternating user/assistant",
"docs": tot["kept"], "docs_fr": tot["kept_fr"], "tokens": int(arr.size),
"min_id": int(arr.min()), "max_id": int(arr.max()), "bos": int((arr == 257).sum()),
"stats": {k: v for k, v in tot.items()}}
with open(a.out + ".json", "w") as f: json.dump(meta, f, indent=2)
print(json.dumps({k: v for k, v in meta.items() if k != "stats"}))
if __name__ == "__main__":
main()