Download build_script.py from sandysanta/stem-text-corpus: direct link, hf CLI and curl.
- Browser
- Download file 18.1 kB
-
https://huggingface.co/datasets/sandysanta/stem-text-corpus/resolve/main/build_script.py
- Command line
-
hf download hf://datasets/sandysanta/stem-text-corpus/build_script.py
-
curl -L -o build_script.py https://huggingface.co/datasets/sandysanta/stem-text-corpus/resolve/main/build_script.py
18.1 kB
| """Text dataset compilations -> private HF repos under sandysanta. | |
| python dsb.py {calib|stem|wiki|cot|plan} [limit] (limit>0: tiny dry run, writes locally, no upload) | |
| Pipeline per source: stream -> adapt/filter -> 13-gram decontamination vs GSM8K/MATH/MMLU/ARC test -> exact dedupe -> parquet shards by license config.""" | |
| import os, sys, re, json, hashlib, itertools, collections, shutil | |
| from multiprocessing import Pool | |
| import pyarrow as pa, pyarrow.parquet as pq | |
| from datasets import load_dataset | |
| from huggingface_hub import HfApi | |
| WHICH = sys.argv[1] if len(sys.argv) > 1 else "calib" | |
| LIMIT = int(sys.argv[2]) if len(sys.argv) > 2 else 0 | |
| USER, WORKERS = "sandysanta", 4 | |
| WRE = re.compile(r"[a-z0-9]+") | |
| words = lambda t: WRE.findall(t.lower()) | |
| # ---------------- STEM vocabulary scoring (heuristic, not a trained classifier) ---------------- | |
| VOCAB = { | |
| "math": "theorem lemma proof corollary polynomial integral derivative matrix eigenvalue eigenvector calculus algebra geometry topology probability combinatorics prime modulo equation inequality logarithm trigonometric sine cosine tangent hypotenuse axiom conjecture manifold homomorphism isomorphic isomorphism convergence converges differentiable continuous bijection subgroup commutative abelian cardinality supremum infimum permutation determinant coefficient quadratic", | |
| "physics": "quantum photon electron proton neutron momentum velocity acceleration thermodynamics entropy relativity gravitational electromagnetic wavelength frequency hamiltonian lagrangian boson fermion nuclear particle newton joule voltage magnetic oscillator spectrum kinetic torque friction inertia refraction diffraction superconductor plasma", | |
| "chemistry": "molecule atom ion bond reaction catalyst organic compound solvent acid oxidation reduction polymer titration molar stoichiometry isomer covalent ionic equilibrium synthesis spectroscopy electronegativity alkane alkene benzene reagent precipitate", | |
| "biology": "protein gene dna rna genome mutation evolution species organism enzyme metabolism membrane chromosome ecosystem photosynthesis mitochondria bacteria virus neuron hormone tissue taxonomy phylogenetic allele genotype phenotype ribosome cytoplasm", | |
| "cs": "algorithm complexity compiler runtime recursion sorting hashing database cryptography encryption neural bitwise polynomial-time automaton turing heap pointer asymptotic complexity-class pseudocode", | |
| "eng": "circuit transistor resistor capacitor inductor amplifier impedance semiconductor stress strain thermal turbulence controller sensor voltage resistance bandwidth modulation", | |
| "earth": "geology tectonic seismic climate atmosphere glacier mineral sediment volcano orbit planet galaxy telescope astronomy cosmology exoplanet stellar supernova", | |
| } | |
| ALL = {} | |
| for _s, _v in VOCAB.items(): | |
| for _w in _v.split(): | |
| ALL.setdefault(_w, _s) | |
| def stem_score(text, nw=3000): | |
| """(STEM-term density per 1000 words, best subject).""" | |
| w = words(text[:30000])[:nw] | |
| if len(w) < 50: return 0.0, "none" | |
| c = collections.Counter() | |
| for x in w: | |
| s = ALL.get(x) or (ALL.get(x[:-1]) if x.endswith("s") else None) | |
| if s: c[s] += 1 | |
| n = sum(c.values()) | |
| return 1000.0 * n / len(w), (c.most_common(1)[0][0] if c else "none") | |
| # ---------------- benchmark decontamination (13-gram overlap) ---------------- | |
| NG, H = 13, set() | |
| def build_H(): | |
| def add(t): | |
| w = words(t) | |
| for i in range(max(1, len(w) - NG + 1)): H.add(hash(" ".join(w[i:i + NG]))) | |
| for r in load_dataset("openai/gsm8k", "main", split="test"): add(r["question"]); add(r["answer"]) | |
| for c in ("algebra", "counting_and_probability", "geometry", "intermediate_algebra", "number_theory", "prealgebra", "precalculus"): | |
| for r in load_dataset("EleutherAI/hendrycks_math", c, split="test"): add(r["problem"]); add(r["solution"]) | |
| for r in load_dataset("cais/mmlu", "all", split="test"): add(r["question"] + " " + " ".join(r["choices"])) | |
| for c in ("ARC-Challenge", "ARC-Easy"): | |
| for r in load_dataset("allenai/ai2_arc", c, split="test"): add(r["question"] + " " + " ".join(r["choices"]["text"])) | |
| print("decontamination 13-gram set:", len(H), flush=True) | |
| def contaminated(text, stride): | |
| w = words(text[:200000]) | |
| return any(hash(" ".join(w[i:i + NG])) in H for i in range(0, len(w) - NG + 1, stride)) | |
| # ---------------- adapters: raw row -> unified dict (or None to drop) ---------------- | |
| L_ODC, L_OWM = "odc-by-1.0", "odc-by-1.0 (per the OpenWebMath paper; the dataset card has no license field)" | |
| STEM_SITES = {f"{s}.stackexchange.com": s for s in ("math", "physics", "chemistry", "biology", "stats", "cs", "cstheory", "datascience", "electronics", "engineering", | |
| "astronomy", "earthscience", "quantumcomputing", "scicomp", "matheducators", "bioinformatics", "materials", "robotics", "space", "crypto", "dsp", "mathematica")} | |
| STEM_SITES["mathoverflow.net"] = "mathoverflow" | |
| SITE_SUBJ = {"math": "math", "mathoverflow": "math", "matheducators": "math", "stats": "math", "crypto": "math", "physics": "physics", "chemistry": "chemistry", "biology": "biology", | |
| "bioinformatics": "biology", "cs": "cs", "cstheory": "cs", "datascience": "cs", "quantumcomputing": "physics", "scicomp": "cs", "mathematica": "cs", | |
| "electronics": "eng", "engineering": "eng", "robotics": "eng", "dsp": "eng", "materials": "eng", "astronomy": "earth", "earthscience": "earth", "space": "earth"} | |
| T_COSMO, T_WEB, T_WIKI = 20.0, 20.0, 18.0 # STEM density thresholds (tuned with `calib`) | |
| def row(text, source, lic, subject, url): | |
| return dict(text=text, source=source, license=lic, subject=subject, url=url, n_chars=len(text), _chk=text) | |
| def a_owm(r): | |
| t = r["text"] | |
| if len(t) < 300: return None | |
| s, sub = stem_score(t); return row(t, "open-web-math", L_OWM, sub if s > 0 else "math", r.get("url")) | |
| def a_finemath(r): | |
| t = r["text"] | |
| if len(t) < 300: return None | |
| s, sub = stem_score(t); return row(t, "finemath-4plus", L_ODC, sub if s > 0 else "math", r.get("url")) | |
| def a_cosmo(r): | |
| t = r["text"]; s, sub = stem_score(t) | |
| return row(t, "cosmopedia-v2", L_ODC + " (synthetic, generated with Mixtral)", sub, None) if len(t) >= 300 and s >= T_COSMO else None | |
| def a_fweb(r): | |
| t = r["text"] | |
| if r.get("int_score", 0) < 3 or len(t) < 500: return None | |
| s, sub = stem_score(t) | |
| return row(t, "fineweb-edu", L_ODC, sub, r.get("url")) if s >= T_WEB else None | |
| def a_se(r): | |
| m = r["metadata"]; site = m.get("site", "") | |
| if site not in STEM_SITES or len(r["text"]) < 300: return None | |
| short = STEM_SITES[site] | |
| return row(r["text"], f"stackexchange/{site}", "CC BY-SA (version varies per post; see url)", SITE_SUBJ[short], m.get("url")) | |
| def a_wiki(r): | |
| t, ti = r["text"], r["title"] | |
| if len(t) < 1500 or ti.startswith("List of") or "(disambiguation)" in ti: return None | |
| s, sub = stem_score(t) | |
| if s < T_WIKI: return None | |
| return dict(id=r["id"], title=ti, url=r["url"], text=t, subject=sub, stem_score=round(s, 2), n_chars=len(t), license="CC BY-SA 3.0 + GFDL", _chk=t) | |
| def conv(q, a, source, lic, gen, subject, code=False): | |
| return dict(messages=[{"role": "user", "content": q}, {"role": "assistant", "content": a}], source=source, license=lic, generated_by=gen, | |
| subject=subject, has_code=code, n_chars=len(q) + len(a), _chk=q) | |
| def a_numina(r): | |
| m = r["messages"] | |
| return conv(m[0]["content"], m[1]["content"], f"numina-cot/{r['source']}", "apache-2.0", "GPT-4o", "math") if len(m) == 2 and len(m[1]["content"]) > 20 else None | |
| def a_metamath(r): return conv(r["query"], r["response"], f"metamathqa/{r['type']}", "mit", "GPT-3.5-turbo", "math") | |
| def a_orca(r): return conv(r["question"], r["answer"], "orca-math-200k", "mit", "GPT-4-Turbo", "math") | |
| def a_omi2(r): return conv(r["problem"], r["generated_solution"], f"openmathinstruct-2/{r['problem_source']}", "cc-by-4.0 (generated with Llama-3.1-405B; Llama license terms apply)", "Llama-3.1-405B-Instruct", "math") | |
| def a_mathinstruct(r): | |
| o = r["output"] | |
| if "PoT" in r["source"] or "```" in o or "def " in o: return None # drop program-of-thought / code | |
| return conv(r["instruction"], o, "mathinstruct-cot", "mit", "mixed (see MathInstruct card)", "math") | |
| def a_camel(dom): | |
| def f(r): return conv(r["message_1"], r["message_2"], f"camel-ai/{dom}", "cc-by-nc-4.0", "GPT-4", dom) | |
| return f | |
| def a_sqa(r): | |
| if r.get("image") is not None or not (r.get("solution") or "").strip(): return None | |
| ch = "\n".join(f"{chr(65 + i)}. {c}" for i, c in enumerate(r["choices"])) | |
| q = (r["hint"] + "\n" if r.get("hint") else "") + r["question"] + "\n" + ch | |
| return conv(q, r["solution"].strip() + f"\nAnswer: {chr(65 + r['answer'])}", "scienceqa-text", "cc-by-sa-4.0", "human (ScienceQA)", r.get("subject", "science")) | |
| WANT = {"Planning", "Advice seeking", "Brainstorming", "Reasoning"} | |
| def a_plan(r): | |
| if r["primary_tag"] not in WANT or r["quality"] not in ("good", "excellent") or r.get("safe") is False: return None | |
| c = r["conversation"] | |
| if len(c) < 2: return None | |
| msgs = [{"role": ("user" if m["role"] in ("user", "human") else "assistant"), "content": m["content"]} for m in c] | |
| return dict(messages=msgs, tag=r["primary_tag"], difficulty=r["difficulty"], quality=r["quality"], source="magpie-ultra-v1.0", | |
| license="Llama 3.1 Community License (generated with Llama-3.1-405B-Instruct; 'Built with Llama')", generated_by="Llama-3.1-405B-Instruct", | |
| n_chars=sum(len(m["content"]) for m in msgs), _chk=msgs[0]["content"], _cap=r["primary_tag"]) | |
| ADAPT = {"owm": a_owm, "finemath": a_finemath, "cosmo": a_cosmo, "fweb": a_fweb, "se": a_se, "wiki": a_wiki, "numina": a_numina, "metamath": a_metamath, "orca": a_orca, | |
| "omi2": a_omi2, "mathinstruct": a_mathinstruct, "camel-physics": a_camel("physics"), "camel-chemistry": a_camel("chemistry"), | |
| "camel-biology": a_camel("biology"), "sqa": a_sqa, "plan": a_plan} | |
| STRIDE = {k: (1 if k in ("numina", "metamath", "orca", "omi2", "mathinstruct", "camel-physics", "camel-chemistry", "camel-biology", "sqa", "plan") else 4) for k in ADAPT} | |
| def work(arg): | |
| name, rows = arg; out, ncon = [], 0 | |
| for r in rows: | |
| try: x = ADAPT[name](r) | |
| except Exception: x = None | |
| if x is None: continue | |
| chk = x.pop("_chk") | |
| if contaminated(chk, STRIDE[name]): ncon += 1; continue | |
| x["_dig"] = hashlib.md5(" ".join(words(chk)).encode()).digest() | |
| out.append(x) | |
| return out, len(rows), ncon | |
| # ---------------- sources ---------------- | |
| def robust(fn): | |
| """Yield rows of a streaming dataset; on a network error reopen and resume after the rows already yielded.""" | |
| import time | |
| n, tries = 0, 0 | |
| while True: | |
| try: | |
| ds = fn() | |
| if n: ds = ds.skip(n) | |
| for r in ds: | |
| n += 1; tries = 0; yield r | |
| return | |
| except Exception as e: | |
| tries += 1 | |
| print(f"stream error after {n} rows ({type(e).__name__}: {str(e)[:80]}); retry {tries}", flush=True) | |
| if tries > 8: raise | |
| time.sleep(10 * tries) | |
| S = lambda *a, **k: (lambda: robust(lambda: load_dataset(*a, streaming=True, **k))) | |
| SRC = { | |
| "owm": S("open-web-math/open-web-math", split="train"), "finemath": S("HuggingFaceTB/finemath", "finemath-4plus", split="train"), | |
| "cosmo": S("HuggingFaceTB/smollm-corpus", "cosmopedia-v2", split="train"), "fweb": S("HuggingFaceFW/fineweb-edu", "sample-10BT", split="train"), | |
| "se": S("common-pile/stackexchange", split="train"), "wiki": S("wikimedia/wikipedia", "20231101.en", split="train"), | |
| "numina": S("AI-MO/NuminaMath-CoT", split="train"), "metamath": S("meta-math/MetaMathQA", split="train"), | |
| "orca": S("microsoft/orca-math-word-problems-200k", split="train"), "omi2": S("nvidia/OpenMathInstruct-2", split="train_1M"), | |
| "mathinstruct": S("TIGER-Lab/MathInstruct", split="train"), "camel-physics": S("camel-ai/physics", split="train"), | |
| "camel-chemistry": S("camel-ai/chemistry", split="train"), "camel-biology": S("camel-ai/biology", split="train"), | |
| "sqa": S("derek-thomas/ScienceQA", split="train"), "plan": S("argilla/magpie-ultra-v1.0", split="train"), | |
| } | |
| # per dataset: name -> list of (source key, config, kept-row cap, scanned-row cap, per-key cap) | |
| PLANS = { | |
| "stem": ("stem-text-corpus", [("owm", "core", 300_000, 450_000, None), ("finemath", "core", 300_000, 450_000, None), ("cosmo", "core", 150_000, 1_500_000, None), | |
| ("fweb", "core", 200_000, 3_000_000, None), ("se", "sharealike", 300_000, 12_000_000, 25_000)]), | |
| "wiki": ("wikipedia-stem", [("wiki", "default", 10**9, 7_000_000, None)]), | |
| "cot": ("stem-cot-sft", [("numina", "permissive", 900_000, 900_000, None), ("metamath", "permissive", 400_000, 400_000, None), ("orca", "permissive", 200_000, 200_000, None), | |
| ("omi2", "permissive", 300_000, 300_000, None), ("mathinstruct", "permissive", 270_000, 270_000, None), ("sqa", "sharealike", 10_000, 40_000, None)]), | |
| "plan": ("planning-instruct", [("plan", "default", 10**9, 1_000_000, {"Planning": 100_000, "Advice seeking": 60_000, "Brainstorming": 50_000, "Reasoning": 50_000})]), | |
| } | |
| T = pa.string() | |
| SCHEMAS = { | |
| "stem": pa.schema([("text", T), ("source", T), ("license", T), ("subject", T), ("url", T), ("n_chars", pa.int64())]), | |
| "wiki": pa.schema([("id", T), ("title", T), ("url", T), ("text", T), ("subject", T), ("stem_score", pa.float32()), ("n_chars", pa.int64()), ("license", T)]), | |
| "cot": pa.schema([("messages", pa.list_(pa.struct([("role", T), ("content", T)]))), ("source", T), ("license", T), ("generated_by", T), ("subject", T), ("has_code", pa.bool_()), ("n_chars", pa.int64())]), | |
| "plan": pa.schema([("messages", pa.list_(pa.struct([("role", T), ("content", T)]))), ("tag", T), ("difficulty", T), ("quality", T), ("source", T), ("license", T), ("generated_by", T), ("n_chars", pa.int64())]), | |
| } | |
| class Shards: | |
| def __init__(s, out, cfg, schema): s.d, s.schema, s.buf, s.nb, s.k, s.n = f"{out}/data/{cfg}", schema, [], 0, 0, 0; os.makedirs(s.d, exist_ok=True) | |
| def add(s, r): s.buf.append(r); s.nb += r["n_chars"]; s.n += 1; (s.flush() if s.nb > 250_000_000 else None) | |
| def flush(s): | |
| if not s.buf: return | |
| pq.write_table(pa.Table.from_pylist(s.buf, schema=s.schema), f"{s.d}/train-{s.k:05d}.parquet", compression="zstd"); s.buf, s.nb, s.k = [], 0, s.k + 1 | |
| def pump(pool, name, batches, handle, window=20): | |
| pend = collections.deque() | |
| for b in batches: | |
| pend.append(pool.apply_async(work, ((name, b),))) | |
| while len(pend) >= window: | |
| if handle(*pend.popleft().get()): return | |
| while pend: | |
| if handle(*pend.popleft().get()): return | |
| def build(which): | |
| repo, plan = PLANS[which]; out = f"out_{repo}" + ("_dry" if LIMIT else "") | |
| shutil.rmtree(out, ignore_errors=True); schema = SCHEMAS[which]; cols = set(schema.names) | |
| build_H(); seen, shards, stats = set(), {}, {} | |
| for key, cfg, cap, scan, percap in plan: | |
| if LIMIT: cap, scan = min(cap, LIMIT), LIMIT * 40 | |
| sh = shards.setdefault(cfg, Shards(out, cfg, schema)); st = stats[key] = collections.Counter(); st["cfg"] = cfg; capn = collections.Counter(); n = [0] | |
| def handle(kept, nin, ncon): | |
| st["scanned"] += nin; st["decontaminated"] += ncon | |
| for x in kept: | |
| d = x.pop("_dig") | |
| if d in seen: st["duplicates"] += 1; continue | |
| ck = x.pop("_cap", None) or (x["source"] if percap and isinstance(percap, int) else None) | |
| lim = percap if isinstance(percap, int) else (percap or {}).get(ck) | |
| if ck is not None and lim is not None and capn[ck] >= lim: continue | |
| seen.add(d); capn[ck] += 1; sh.add({k: x.get(k) for k in schema.names}); st["kept"] += 1; st["chars"] += x["n_chars"]; n[0] += 1 | |
| if n[0] >= cap: return True | |
| if st["scanned"] % 50_000 < 200: print(key, dict(st), flush=True) | |
| return False | |
| it = itertools.islice(SRC[key](), scan) | |
| batches = iter(lambda it=it: list(itertools.islice(it, 200)), []) | |
| with Pool(WORKERS) as pool: pump(pool, key, batches, handle) | |
| print("DONE", key, dict(st), flush=True) | |
| for sh in shards.values(): sh.flush() | |
| stats = {k: dict(v) for k, v in stats.items()} | |
| json.dump(stats, open(f"{out}/build_stats.json", "w"), indent=1) | |
| shutil.copy(__file__, f"{out}/build_script.py") | |
| shutil.copy("cards.py", f"{out}/cards.py") | |
| write_card(which, repo, out, stats, {c: s.n for c, s in shards.items()}) | |
| if LIMIT: print("DRY RUN OK", stats); return | |
| api = HfApi(); rid = f"{USER}/{repo}"; api.create_repo(rid, repo_type="dataset", private=True, exist_ok=True) | |
| api.upload_folder(folder_path=out, repo_id=rid, repo_type="dataset", commit_message="Initial release (private)") | |
| print("BUILD_DONE", rid, flush=True) | |
| # ---------------- dataset cards ---------------- | |
| def write_card(which, repo, out, stats, counts): | |
| from cards import card | |
| open(f"{out}/README.md", "w", encoding="utf8").write(card(which, repo, stats, counts)) | |
| def calib(): | |
| """Print STEM-score distributions so thresholds are chosen on evidence.""" | |
| for name, n in (("wiki", 8000), ("fweb", 4000), ("cosmo", 3000)): | |
| sc = [] | |
| for r in itertools.islice(SRC[name](), n): | |
| s, sub = stem_score(r["text"]); sc.append((s, sub, r.get("title") or r["text"][:60].replace("\n", " "))) | |
| v = sorted(x[0] for x in sc); q = lambda p: round(v[int(p * (len(v) - 1))], 1) | |
| print(f"== {name}: quantiles 50/75/90/95/99% = {q(.5)} {q(.75)} {q(.9)} {q(.95)} {q(.99)}") | |
| for lo, hi in ((6, 10), (10, 14), (14, 18), (18, 24), (24, 40)): | |
| ex = [f"{x[2][:38]} ({x[0]:.0f},{x[1]})" for x in sc if lo <= x[0] < hi][:6] | |
| print(f" [{lo},{hi}) n={sum(lo <= x[0] < hi for x in sc)}: {ex}") | |
| if __name__ == "__main__": | |
| os.environ.setdefault("PYTHONHASHSEED", "0") | |
| calib() if WHICH == "calib" else build(WHICH) | |