tinymix / code /build.py
jncarlo's picture
tinymix: 100M, 10M, 1M
f0c12b0 verified
Raw History Blame Contribute Delete
16 kB
"""Build one size of the dataset: python build.py 10M [source ...]
Per source: stream -> clean -> filter -> dedup until the word quota is met.
Output: work/<size>/<source>.jsonl, then assemble.py slices train/valid.
"""
import hashlib
import itertools
import json
import os
import re
import sys
import time
import unicodedata
from collections import Counter
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
# HF_TOKEN lives in ../.env (never printed); must be set before importing datasets
_env = ROOT / ".env"
if _env.exists():
for _l in _env.read_text(encoding="utf-8").splitlines():
if "=" in _l and not _l.lstrip().startswith("#"):
_k, _v = _l.split("=", 1)
os.environ.setdefault(_k.strip(), _v.strip().strip("'\""))
import fasttext
import ftfy
from datasketch import MinHash, MinHashLSH
from wordfreq import top_n_list
import mix
import sources
QUOTES = str.maketrans({"‘": "'", "’": "'", "“": '"', "”": '"',
"–": "-", "—": " - ", "…": "...", " ": " "})
RE_URL = re.compile(r"https?://\S+|www\.\S+")
RE_EMAIL = re.compile(r"\S+@\S+\.\S+")
RE_PHONE = re.compile(r"\+?\d[\d\s().-]{8,}\d")
RE_HTML = re.compile(r"<[^>]{1,100}>")
RE_CODE = re.compile(r"```.*?```", re.S)
RE_HEAD = re.compile(r"^#{1,6}\s*", re.M)
RE_LATEX = re.compile(r"\$\$.*?\$\$|\\\(.*?\\\)|\\\[.*?\\\]", re.S)
LLM_TICS = re.compile(r"\bas an ai\b|\bdelve\b|\btapestry\b|\bcertainly!|\bin conclusion,|"
r"\bit'?s important to note\b|\bbustling\b|\bas a language model\b", re.I)
# deliberately small: only terms that are unambiguous in any context
BAD = re.compile(r"\b(fuck\w*|shit\w*|bitch\w*|cunt|porn\w*|nigg\w+|rape[sd]?|raping|"
r"cock|dick|pussy|slut|whore|orgasm\w*|erotic\w*|blowjob|masturbat\w*)\b", re.I)
# characters allowed in a document: ASCII, Latin-1 and Latin Extended-A/B, curly quotes, dashes,
# ellipsis, and a few math signs common in textbooks. Anything else (emoji, CJK, Greek, Cyrillic,
# Arabic, private-use) rejects the whole document, so rare scripts never reach the tokenizer
RE_CHARSET = re.compile(r"[^\x00-\x7f\u00a0-\u024f\u2013\u2014\u2018-\u201d\u2026"
r"\u00b1\u00d7\u00f7\u2212\u221a\u221e\u2248\u2260\u2264\u2265]")
STOP = {"the", "and", "to", "of", "a", "in", "that", "is", "it", "for"}
END_OK = ('.', '!', '?', '"', "'", ")")
lid = fasttext.load_model(str(ROOT / "work" / "lid.176.ftz"))
def normalize(t):
t = ftfy.fix_text(t).translate(QUOTES)
t = unicodedata.normalize("NFKC", t)
for rx in (RE_CODE, RE_LATEX, RE_URL, RE_EMAIL, RE_HTML):
t = rx.sub(" ", t)
t = RE_PHONE.sub(" ", t)
t = RE_HEAD.sub("", t)
t = re.sub(r"[ \t]+", " ", t)
t = re.sub(r" ?\n ?", "\n", t)
t = re.sub(r"\n{3,}", "\n\n", t)
return t.strip()
def syllables(w):
n = len(re.findall(r"[aeiouy]+", w))
if w.endswith("e") and n > 1 and not w.endswith("le"):
n -= 1
return max(n, 1)
def fk_grade(text):
words = re.findall(r"[A-Za-z']+", text)
sents = max(len(re.findall(r"[.!?]+(?:\s|$)", text)), 1)
if not words:
return 99
syl = sum(syllables(w.lower()) for w in words)
return 0.39 * len(words) / sents + 11.8 * syl / len(words) - 15.59
def vocab_coverage(text, vocab):
# capitalised words (names, sentence starts) never match, so they are ignored
toks = re.findall(r"\b[a-z']+\b", text)
return sum(t in vocab for t in toks) / len(toks) if toks else 0
def gopher_ok(text):
words = text.split()
if not words:
return False
if not 3 <= sum(map(len, words)) / len(words) <= 10:
return False
if sum(not c.isalnum() and not c.isspace() and c not in ".,;:!?'\"()-" for c in text) / len(text) > 0.1:
return False
if sum(c.isdigit() for c in text) / len(text) > 0.1:
return False
lines = [l for l in text.split("\n") if l.strip()]
if len(lines) > 3 and 1 - len(set(lines)) / len(lines) > 0.3:
return False
if sum(w.lower().strip(".,!?\"'") in STOP for w in words) < 2:
return False
bi = Counter(zip(words, words[1:]))
return not bi or bi.most_common(1)[0][1] / max(len(words) - 1, 1) <= 0.2
def is_english(text):
# lid.f.predict avoids fasttext's numpy-1 only wrapper; returns [(prob, label)]
pred = lid.f.predict(text[:1000].replace("\n", " ") + "\n", 1, 0.0, "strict")
return bool(pred) and pred[0][1] == "__label__en" and pred[0][0] >= 0.9
def split_long(text, title, doc_max):
"""Split at paragraph borders; the title is repeated so each chunk stays self-contained."""
paras, chunks, cur, n = text.split("\n"), [], [], 0
for p in paras:
w = len(p.split())
if cur and n + w > doc_max:
chunks.append("\n".join(cur))
cur, n = [], 0
cur.append(p)
n += w
if cur:
chunks.append("\n".join(cur))
return [(f"{title}\n{c}" if title else c) for c in chunks if len(c.split()) >= mix.DOC_MIN]
class Dedup:
def __init__(self):
self.exact, self.lsh, self.n = set(), MinHashLSH(threshold=0.8, num_perm=64), 0
def seen(self, text):
h = hashlib.md5(re.sub(r"\W+", "", text.lower()).encode()).hexdigest()
if h in self.exact:
return True
self.exact.add(h)
w = text.lower().split()
mh = MinHash(num_perm=64)
mh.update_batch([" ".join(w[i:i + 5]).encode() for i in range(max(len(w) - 4, 1))])
if self.lsh.query(mh):
return True
self.lsh.insert(str(self.n), mh)
self.n += 1
return False
def trim_tail(text):
"""Drop trailing headings and list stubs ("Other websites", "References") so a complete
article is not rejected as truncated; real truncation leaves a long unfinished last line."""
lines = text.split("\n")
while len(lines) > 1 and (not lines[-1].strip() or
(len(lines[-1].split()) < 12 and not lines[-1].rstrip().endswith(END_OK))):
lines.pop()
return "\n".join(lines).strip()
def process(doc, genre, tier, vocab, src_name, cov):
"""Return (clean documents, None) or ([], rejection reason)."""
if "turns" in doc:
turns = [(s.strip(), normalize(t)) for s, t in doc["turns"]]
turns = [(s, t.replace("\n", " ")) for s, t in turns if t]
# assistant chats (User/Assistant) include 2-turn tasks (summarise, rewrite) and long answers,
# so they get a lower turn minimum and a looser per-turn cap than named dialogues
chat = all(s in ("User", "Assistant") for s, _ in turns)
if len(turns) < (2 if chat else 4) or any(len(s) > 20 for s, _ in turns):
return [], "dialogue_shape"
if sum(len(t.split()) for _, t in turns) / len(turns) > tier["turn"] * (mix.CHAT_TURN_MULT if chat else 1):
return [], "turn_length"
text = "\n".join(f"{s}: {t}" for s, t in turns)
title = None
else:
text, title = normalize(doc["text"]), doc.get("title")
if "�" in text:
return [], "mojibake"
if genre != "poetry":
text = trim_tail(text)
nw = len(text.split())
if RE_CHARSET.search(text):
return [], "charset"
if genre == "poetry":
if nw < 20:
return [], "short"
return ([text], None) if is_english(text) else ([], "lang")
if nw < mix.DOC_MIN:
return [], "short"
if len(LLM_TICS.findall(text)) > 2:
return [], "llm_tics"
if BAD.search(text):
return [], "explicit"
if src_name not in mix.LID_SKIP and not is_english(text):
return [], "lang"
if not text.rstrip().endswith(END_OK):
return [], "truncated"
if not gopher_ok(text):
return [], "gopher"
if genre != "dialogue":
cap = tier["fk_exp"] if genre == "expository" else tier["fk"]
if fk_grade(text) > cap and src_name not in ("simplewiki",):
return [], "fk"
if vocab_coverage(text, vocab) < cov:
return [], "vocab"
docs = split_long(text, title, tier["doc_max"]) if nw > tier["doc_max"] else [f"{title}\n{text}" if title else text]
return docs, (None if docs else "short")
def doc_words(doc):
return len(doc["text"].split()) if "text" in doc else sum(len(t.split()) for _, t in doc["turns"])
def at_step(tier, step):
"""Tier and vocabulary-coverage threshold at a relaxation-ladder step."""
dfk, dcov = mix.LADDER[step]
return dict(tier, fk=tier["fk"] + dfk, fk_exp=tier["fk_exp"] + dfk), mix.VOCAB_COVERAGE + dcov
def probe(name, size, genre, tier, vocab, quota):
"""Mechanism 1: sample the first docs and pick the first ladder step whose projected
scan fits comfortably in the budget (yield >= 2/MAX_SCAN). Returns (step, report)."""
docs = list(itertools.islice(sources.REGISTRY[name](size), mix.PROBE_DOCS))
scanned = sum(doc_words(d) for d in docs) or 1
report = []
for step in range(len(mix.LADDER)):
t, cov = at_step(tier, step)
rej, kept = Counter(), 0
for d in docs:
out, why = process(d, genre, t, vocab, name, cov)
kept += sum(len(x.split()) for x in out)
if why:
rej[why] += 1
yield_ = kept / scanned
report.append(dict(step=step, yield_pct=round(100 * yield_, 1), top_rejections=rej.most_common(3)))
if yield_ >= 2 / mix.MAX_SCAN:
return step, report
return len(mix.LADDER) - 1, report
def build_source(name, size, dedup, quota=None, tag=""):
"""Fill one source's quota. `tag=".topup"` writes an extra file for fallback top-ups."""
genre, quotas = mix.MIX[name]
if quota is None:
quota = quotas[mix.SIZES[size]] * 1_000_000
if quota <= 0:
return None
out = ROOT / "work" / size / f"{name}{tag}.jsonl"
done = out.with_suffix(".done")
if done.exists():
stats = json.loads(done.read_text())
if abs(stats["target_M"] - quota / 1e6) < 1e-6:
for l in out.open(encoding="utf-8"): # reload so global dedup stays consistent
dedup.seen(json.loads(l)["text"])
return stats
base = mix.TIERS[size]
vocab = set(top_n_list("en", base["vocab"]))
t0 = time.time()
step, probe_report = probe(name, size, genre, base, vocab, quota)
print(f" probe {name}{tag}: start at ladder step {step}; {probe_report[-1]}", flush=True)
tier, cov = at_step(base, step)
got = scanned = kept = seen_docs = 0
openers, rej = Counter(), Counter()
win_scanned = win_kept = win_docs = 0
relaxed, abort = [dict(step=step, at_words=0)], None
with out.open("w", encoding="utf-8") as f:
for doc in sources.REGISTRY[name](size):
seen_docs += 1
win_docs += 1
w = doc_words(doc)
scanned += w
win_scanned += w
if scanned > quota * mix.MAX_SCAN:
abort = "scan_cap"
break
docs, why = process(doc, genre, tier, vocab, name, cov)
if why:
rej[why] += 1
for text in docs:
# anti-template: no 4-word opening may exceed 0.5% of the accepted docs
op = " ".join(text.lower().split()[:4])
if genre != "poetry" and openers[op] >= max(5, 0.005 * kept):
rej["opener_cap"] += 1
continue
if dedup.seen(text):
rej["duplicate"] += 1
continue
openers[op] += 1
kept += 1
n = len(text.split())
got += n
win_kept += n
f.write(json.dumps({"text": text, "genre": genre, "src": name}) + "\n")
if got >= quota:
break
if seen_docs % 2000 == 0:
print(f" {name}{tag}: {seen_docs} docs, kept {kept}, {got/1e6:.2f}M/{quota/1e6:.2f}M words, "
f"{time.time()-t0:.0f}s, top rejections {rej.most_common(3)}", flush=True)
if win_docs >= mix.WINDOW:
# mechanisms 2+4: if the recent yield cannot finish within the scan budget,
# climb one ladder step; at the top of the ladder give up on this source
recent = win_kept / win_scanned if win_scanned else 0
need = (quota - got) / recent if recent else float("inf")
if need > quota * mix.MAX_SCAN - scanned:
if step + 1 < len(mix.LADDER):
step += 1
tier, cov = at_step(base, step)
relaxed.append(dict(step=step, at_words=got))
print(f" {name}{tag}: yield {100*recent:.1f}% too low, relaxing to step {step}", flush=True)
else:
abort = "projected_shortfall"
break
win_scanned = win_kept = win_docs = 0
stats = dict(source=name + tag, genre=genre, target_M=quota / 1e6, words_M=round(got / 1e6, 3),
docs=kept, scanned_docs=seen_docs, scanned_words_M=round(scanned / 1e6, 1),
seconds=round(time.time() - t0), stopped="quota" if got >= quota else (abort or "source_exhausted"),
relaxation=relaxed, probe=probe_report, rejections=dict(rej.most_common()))
done.write_text(json.dumps(stats))
return stats
def plan_fallbacks(size, results):
"""Mechanism 3: spread each source's shortfall over same-genre substitutes, capped."""
idx = mix.SIZES[size]
quota = {n: q[idx] * 1e6 for n, (_, q) in mix.MIX.items()}
target = sum(quota.values())
got = {r["source"]: r["words_M"] * 1e6 for r in results if "words_M" in r}
extra, plan, log = Counter(), Counter(), []
for src, q in quota.items():
gap = q - got.get(src, 0) if q > 0 else 0
if gap < 0.01 * q:
continue
for sub in mix.FALLBACKS.get(src, []):
if gap <= 0:
break
room = max(mix.EXTRA_FRAC * quota[sub], mix.EXTRA_FLOOR * target) - extra[sub]
room = min(room, mix.SHARE_CAP * target - got.get(sub, 0) - extra[sub])
amt = min(gap, room)
if amt < 0.005 * target:
continue
extra[sub] += amt
plan[sub] += amt
gap -= amt
log.append(dict(missing_from=src, filled_by=sub, words_M=round(amt / 1e6, 3)))
if gap > 0:
log.append(dict(missing_from=src, unfilled_M=round(gap / 1e6, 3)))
return plan, log
def main():
size = sys.argv[1]
only = sys.argv[2:]
(ROOT / "work" / size).mkdir(parents=True, exist_ok=True)
dedup, results = Dedup(), []
def run(name, **kw):
print(f"== {name}{kw.get('tag', '')}", flush=True)
try:
r = build_source(name, size, dedup, **kw)
except Exception as e: # keep going; a failed source is reported, not hidden
print(f" FAILED {name}: {e!r}", flush=True)
r = dict(source=name + kw.get("tag", ""), error=repr(e))
if r:
print(" ", {k: v for k, v in r.items() if k not in ("probe", "relaxation")}, flush=True)
results.append(r)
for name in mix.MIX:
if not only or name in only:
run(name)
fallback_log = []
if not only:
plan, fallback_log = plan_fallbacks(size, [r for r in results if "tag" not in r])
print("== fallback plan", fallback_log, flush=True)
for sub, words in plan.items():
run(sub, quota=words, tag=".topup")
total = sum(r.get("words_M", 0) for r in results)
print(f"== total {total:.2f}M words", flush=True)
(ROOT / "work" / size / "stats.json").write_text(
json.dumps(dict(total_M=round(total, 3), fallbacks=fallback_log, sources=results), indent=1))
if __name__ == "__main__":
main()