"""Parallel, resource-bounded build for big sizes: python build_pool.py 1000M [options] Same filters and safety nets as build.py (process, probe and the relaxation ladder come from there). What is different: - Jobs. A source whose estimated time (from work/100M/stats.json) exceeds --job-hours is split into shards (whole dataset files, or every k-th row). Jobs run longest first in at most --workers processes, at below-normal priority and with one thread each, so the machine stays usable. - Memory. Dedup keeps 8-byte keys per document (the md5 key and the LSH band keys build.Dedup uses) instead of datasketch's index, and each job only holds its own. A global pass over the key files with numpy then drops documents that repeat across jobs; the first occurrence in MIX order wins, and a document that matches any earlier one is dropped (build.Dedup only compares against kept ones, so this is marginally stricter). Jobs collect --overshoot extra words so that pass rarely leaves a source short, and the excess is trimmed. The scheduler waits to start jobs while free RAM is below --min-free-gb and stops the youngest job when it falls below --kill-free-gb; a stopped job resumes later. - Robustness. Each job checkpoints every --ckpt-seconds, after flushing its data, so a hard kill loses at most that interval. On a network error it reopens the stream and skips the documents already seen (the streams are deterministic: fixed seed and shard). A job that crashes restarts from its checkpoint up to --retries times. Rerunning the same command resumes everything and skips finished jobs. Output: work//.jsonl and .topup.jsonl plus stats.json, which assemble.py reads as before. Per-job files (data, keys, checkpoints, logs) live in work//jobs/. Testing: --scale 0.002 multiplies every quota (output in work/_x0.002/); a small --job-hours forces shards. """ import argparse import hashlib import itertools import json import math import multiprocessing as mp import os import re import shutil import statistics import sys import time import traceback from collections import Counter from pathlib import Path # one thread per process for numpy, BLAS and Arrow; spawned workers inherit these for _v in ("OMP_NUM_THREADS", "OPENBLAS_NUM_THREADS", "MKL_NUM_THREADS"): os.environ.setdefault(_v, "1") import numpy as np import psutil from datasketch import MinHash, MinHashLSH from wordfreq import top_n_list import build import mix import sources ROOT = build.ROOT _LSH = MinHashLSH(threshold=0.8, num_perm=64) # build.Dedup's parameters; only b and r are used BANDS, ROWS = _LSH.b, _LSH.r _MH = MinHash(num_perm=64) # reused permutations; building them per document is most of MinHash's cost PERMS, SCHEME = _MH.permutations, _MH.scheme # odd 64-bit multipliers that fold the ROWS values of a band into one key MIXER = np.random.RandomState(7).randint(1, 2**62, size=ROWS, dtype=np.int64).astype(np.uint64) | np.uint64(1) REC = np.dtype([("x", " tries: raise wait = min(600, 15 * 2 ** fails) print(f"stream error at doc {pos} ({e!r}); retry {fails}/{tries} in {wait}s", flush=True) time.sleep(wait) def consumed_docs(job, jobs_dir): """Where a top-up starts: after what its source's primary job read, when both read the same stream.""" if not job["tag"] or list(job["shard"]) != [0, 1]: return 0 d = read_json(jobs_dir / f"{job['name']}.s0of1.done") return d["scanned_docs"] if d else 0 def run_job(job, size, jobs_dir, ckpt_seconds): """build.build_source for one job, with checkpoints and resume.""" p = paths(jobs_dir, job) if is_done(jobs_dir, job): return name, quota = job["name"], job["quota"] genre = mix.MIX[name][0] base = mix.TIERS[size] vocab = set(top_n_list("en", base["vocab"])) dedup = Keys() for seed in job["seeds"]: # a top-up must not repeat its own source's primary files dedup.load(Path(seed)) st = read_json(p["ckpt"]) # resuming skips documents by position, so it is only valid on the very same stream stream = [list(job["shard"]), INPUT_SHARDS.get(name)] if st and (abs(st["quota"] - quota) > 1 or st.get("stream") != stream): st = None # options changed since the checkpoint: start over openers = Counter() if st: # drop whatever was written after the last checkpoint, then rebuild state from the rest with p["jsonl"].open("r+b") as f: f.truncate(st["bytes"]) with p["keys"].open("r+b") as f: f.truncate(st["kept"] * REC.itemsize) dedup.load(p["keys"]) for line in p["jsonl"].open(encoding="utf-8"): openers[" ".join(json.loads(line)["text"].lower().split()[:4])] += 1 print(f"resume at doc {st['seen_docs']}, {st['got'] / 1e6:.2f}M/{quota / 1e6:.2f}M words", flush=True) else: step, probe_report = build.probe(name, size, genre, base, vocab, quota) print(f"probe: start at ladder step {step}; {probe_report[-1]}", flush=True) st = dict(quota=quota, stream=stream, step=step, probe=probe_report, relaxed=[dict(step=step, at_words=0)], got=0, scanned=0, kept=0, seen_docs=consumed_docs(job, jobs_dir), rej={}, seconds=0, retries=0, bytes=0) p["jsonl"].write_bytes(b"") p["keys"].write_bytes(b"") step = st["step"] tier, cov = build.at_step(base, step) got, scanned, kept, seen = st["got"], st["scanned"], st["kept"], st["seen_docs"] rej = Counter(st["rej"]) win_scanned = win_kept = win_docs = 0 abort, t0, last, elapsed0 = None, time.time(), time.time(), st["seconds"] with p["jsonl"].open("ab") as f, p["keys"].open("ab") as kf: def save(): for h in (f, kf): h.flush() os.fsync(h.fileno()) st.update(step=step, got=got, scanned=scanned, kept=kept, seen_docs=seen, rej=dict(rej), seconds=round(elapsed0 + time.time() - t0), bytes=f.tell()) write_json(p["ckpt"], st) stream = robust_stream(name, size, seen, st) if got < quota else () for doc in stream: seen += 1 win_docs += 1 w = build.doc_words(doc) scanned += w win_scanned += w if scanned > quota * mix.MAX_SCAN: abort = "scan_cap" break docs, why = build.process(doc, genre, tier, vocab, name, cov) if why: rej[why] += 1 for text in docs: op = " ".join(text.lower().split()[:4]) if genre != "poetry" and openers[op] >= max(5, 0.005 * kept): rej["opener_cap"] += 1 continue x, bands = doc_keys(text) if dedup.seen(x, bands): rej["duplicate"] += 1 win_scanned -= len(text.split()) # says nothing about the yield of what is left 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").encode("utf-8")) rec = np.zeros(1, REC) rec["x"], rec["b"], rec["w"] = x, bands, n kf.write(rec.tobytes()) if got >= quota: break if time.time() - last >= ckpt_seconds: save() last = time.time() print(f"{seen} docs, kept {kept}, {got / 1e6:.2f}M/{quota / 1e6:.2f}M words, " f"step {step}, top rejections {rej.most_common(3)}", flush=True) if win_docs >= mix.WINDOW: # same rule as build.py: climb a ladder step when the recent yield cannot finish # within the scan budget, give up at the top of the ladder recent = win_kept / win_scanned if win_scanned > 0 else 0 need = (quota - got) / recent if recent else float("inf") if win_scanned > 0 and need > quota * mix.MAX_SCAN - scanned: if step + 1 < len(mix.LADDER): step += 1 tier, cov = build.at_step(base, step) st["relaxed"].append(dict(step=step, at_words=got)) print(f"yield {100 * recent:.1f}% too low, relaxing to step {step}", flush=True) else: abort = "projected_shortfall" break win_scanned = win_kept = win_docs = 0 save() stats = dict(job=job["id"], source=name + job["tag"], genre=genre, target_M=job["target"] / 1e6, quota_M=quota / 1e6, words_M=round(got / 1e6, 3), docs=kept, scanned_docs=seen, scanned_words_M=round(scanned / 1e6, 1), seconds=st["seconds"], stopped="quota" if got >= quota else (abort or "source_exhausted"), relaxation=st["relaxed"], probe=st["probe"], rejections=dict(rej.most_common()), stream_retries=st.get("retries", 0)) write_json(p["done"], stats) p["ckpt"].unlink(missing_ok=True) print(f"done: {stats['words_M']}M words, stopped by {stats['stopped']}", flush=True) def worker(job, size, scale, ckpt_seconds, jobs_dir): jobs_dir = Path(jobs_dir) sys.stdout = sys.stderr = paths(jobs_dir, job)["log"].open("a", encoding="utf-8", buffering=1) print(f"== {job['id']} pid {os.getpid()} {time.strftime('%Y-%m-%d %H:%M:%S')}", flush=True) psutil.Process().nice(psutil.BELOW_NORMAL_PRIORITY_CLASS if os.name == "nt" else 10) try: import pyarrow pyarrow.set_cpu_count(1) pyarrow.set_io_thread_count(2) except Exception: pass apply_scale(scale, size) sources.SHARD = tuple(job["shard"]) sources.INPUT_SHARDS.update(INPUT_SHARDS) try: run_job(job, size, jobs_dir, ckpt_seconds) except Exception: traceback.print_exc() sys.exit(1) # ---------------------------------------------------------------- parent side class Log: def __init__(self, path): self.f = path.open("a", encoding="utf-8", buffering=1) def __call__(self, msg): line = f"{time.strftime('%H:%M:%S')} {msg}" print(line, flush=True) self.f.write(line + "\n") def seconds_per_word(): """Build seconds per target word for each source, measured on the 100M build.""" s = read_json(ROOT / "work" / "100M" / "stats.json") or {} rates = {r["source"]: r["seconds"] / (r["target_M"] * 1e6) for r in s.get("sources", []) if r.get("target_M") and "seconds" in r} default = statistics.median(rates.values()) if rates else 1e-4 return lambda name: rates.get(name, default) def plan_jobs(targets, tag, args, seeds_for): """Split each (source, words) into shards of at most --job-hours estimated time.""" rate, jobs = seconds_per_word(), [] for name, target in targets: if target <= 0: continue est = rate(name) * target k = 1 if name in NO_SHARD else max(1, min(args.max_shards, math.ceil(est / (args.job_hours * 3600)))) for i in range(k): jobs.append(dict(id=f"{name}{tag}.s{i}of{k}", name=name, tag=tag, shard=(i, k), target=target / k, quota=target / k * (1 + args.overshoot), est=est / k, seeds=seeds_for(name))) return jobs def run_pool(jobs, args, size, jobs_dir, log): """Run jobs in at most --workers processes, longest first, within the RAM and disk limits. Returns the jobs that failed more than --retries times.""" pending = sorted((j for j in jobs if not is_done(jobs_dir, j)), key=lambda j: -j["est"]) if not pending: return [] total_est = sum(j["est"] for j in pending) log(f"{len(pending)} jobs to run ({len(jobs) - len(pending)} already done), about " f"{total_est / 3600:.1f} CPU hours by the 100M rates, {args.workers} workers") ctx = mp.get_context("spawn") running, attempts, failed = {}, Counter(), [] # a job stopped twice for memory runs alone from then on, otherwise it could be stopped forever mem_stops, alone = Counter(), set() peak = Counter() # observed peak RSS per source, GB hold = kill_hold = last_status = 0.0 def need(job): return max(MEM_GB.get(job["name"], MEM_DEFAULT_GB), peak[job["name"]]) def rss(proc): try: return psutil.Process(proc.pid).memory_info().rss / 1e9 except psutil.Error: return 0.0 def stop(jid, why): proc, job, _ = running.pop(jid) proc.terminate() proc.join() pending.insert(0, job) log(f"stopped {jid} ({why}); it resumes from its checkpoint") def pick(free, reserved): """First pending job whose expected peak leaves the stop threshold clear, so a big job that does not fit yet does not hold back smaller ones; a job marked to run alone waits for the rest.""" if alone & set(running): return None for j in pending: if j["id"] in alone: return j if not running else None if not running or free - reserved - need(j) >= args.kill_free_gb + 0.5: return j return None try: while pending or running: now = time.time() for jid, (proc, job, _) in list(running.items()): if proc.is_alive(): continue proc.join() del running[jid] d = read_json(paths(jobs_dir, job)["done"]) if d: log(f"done {jid}: {d['words_M']}M words in {d['seconds'] / 60:.0f} min, stopped by {d['stopped']}") continue attempts[jid] += 1 if attempts[jid] > args.retries: failed.append(job) log(f"FAILED {jid} after {attempts[jid]} attempts, see {paths(jobs_dir, job)['log']}") else: pending.insert(0, job) hold = max(hold, now + 30) log(f"{jid} exited with code {proc.exitcode}; restart {attempts[jid]}/{args.retries}") free = psutil.virtual_memory().available / 1e9 # memory a running job is still expected to take (it grows while its buffers fill) reserved = 0.0 for proc, job, _ in running.values(): r = rss(proc) peak[job["name"]] = max(peak[job["name"]], r) reserved += max(0.0, need(job) - r) disk = shutil.disk_usage(jobs_dir).free / 1e9 if disk < args.min_disk_gb: for jid in list(running): stop(jid, f"only {disk:.1f} GB free on disk") raise SystemExit(f"stopped: {disk:.1f} GB free on disk, below --min-disk-gb {args.min_disk_gb}. " "Free space and rerun the same command to resume.") # the last running job is never stopped: that would only trade progress for nothing if free < args.kill_free_gb and len(running) > 1 and now >= kill_hold: # one job at a time, then give the OS time to reclaim its memory before judging again jid = max(running, key=lambda j: running[j][2]) stop(jid, f"free RAM {free:.1f} GB < {args.kill_free_gb}") mem_stops[jid] += 1 if mem_stops[jid] >= 2 and jid not in alone: alone.add(jid) log(f"{jid} will run alone: it was stopped {mem_stops[jid]} times for memory") hold, kill_hold = now + 120, now + 30 elif (len(running) < args.workers and pending and now >= hold and free >= args.min_free_gb and (job := pick(free, reserved))): pending.remove(job) proc = ctx.Process(target=worker, args=(job, size, args.scale, args.ckpt_seconds, str(jobs_dir))) proc.start() running[job["id"]] = (proc, job, now) hold = now + args.stagger log(f"start {job['id']} (est {job['est'] / 60:.0f} min, ~{need(job):.1f} GB)") if now - last_status >= args.status_seconds: last_status = now parts = [] for jid, (proc, job, _) in running.items(): ck = read_json(paths(jobs_dir, job)["ckpt"]) prog = f"{100 * ck['got'] / job['quota']:.0f}%" if ck else "probe" parts.append(f"{jid} {prog} {rss(proc):.1f}GB") log(f"status: {len(pending)} pending, free RAM {free:.1f} GB | " + " | ".join(parts)) time.sleep(2) except KeyboardInterrupt: for proc, _, _ in running.values(): proc.terminate() log("interrupted; rerun the same command to resume") raise SystemExit(130) return failed def global_pass(groups, jobs_dir, out_dir, log, write): """groups: [(output file, [job, ...])] in priority order. Drops documents whose md5 key or any band key appeared in an earlier document, then keeps each job's documents in order until its target. With `write`, writes the output files. Returns {job id: report}.""" jobs = [j for _, js in groups for j in js if is_done(jobs_dir, j)] recs = [np.fromfile(paths(jobs_dir, j)["keys"], dtype=REC) for j in jobs] allr = np.concatenate(recs) if recs else np.zeros(0, REC) order = np.arange(len(allr)) dup = np.zeros(len(allr), bool) for col in [allr["x"]] + [allr["b"][:, i] for i in range(BANDS)]: _, first, inv = np.unique(col, return_index=True, return_inverse=True) dup |= first[inv.ravel()] != order avail, off = {}, 0 for j, r in zip(jobs, recs): avail[j["id"]] = int(r["w"][~dup[off:off + len(r)]].sum(dtype=np.int64)) off += len(r) # the shards of a source share its target: what one lost to duplicates, another with spare words fills budget = {} for _, js in groups: short = sum(max(0, j["target"] - avail[j["id"]]) for j in js if j["id"] in avail) for j in js: if j["id"] in avail: add = min(max(0, avail[j["id"]] - j["target"]), short) budget[j["id"]] = j["target"] + add short -= add report, masks, off = {}, {}, 0 for j, r in zip(jobs, recs): d, w = dup[off:off + len(r)], r["w"].astype(np.int64) off += len(r) keep = ~d kw = np.where(keep, w, 0) before = np.cumsum(kw) - kw trimmed = keep & (before >= budget[j["id"]]) keep &= ~trimmed masks[j["id"]] = keep report[j["id"]] = dict(docs=int(keep.sum()), words=int(w[keep].sum()), dup_docs=int(d.sum()), dup_words=int(w[d].sum()), trimmed_words=int(w[trimmed].sum())) log(f"global dedup over {len(allr)} docs: {int(dup.sum())} duplicates across jobs, " f"{sum(r['trimmed_words'] for r in report.values()) / 1e6:.2f}M words trimmed to quota") if write: wanted = {fname for fname, _ in groups} for fname, js in groups: tmp = out_dir / (fname + ".tmp") with tmp.open("wb") as dst: for j in js: if j["id"] not in masks: continue mask, n = masks[j["id"]], 0 with paths(jobs_dir, j)["jsonl"].open("rb") as src: for line in src: if n >= len(mask): break if mask[n]: dst.write(line) n += 1 if n != len(mask): raise RuntimeError(f"{j['id']}: {n} lines but {len(mask)} keys; delete its files and rerun") os.replace(tmp, out_dir / fname) # a top-up file from an earlier run that this plan no longer has would still be read by assemble.py for stale in out_dir.glob("*.jsonl"): if stale.name not in wanted: stale.replace(stale.with_suffix(".jsonl.stale")) log(f"renamed stale {stale.name} to .stale") return report def summarize(groups, jobs_dir, report): out = [] for fname, js in groups: ds = [read_json(paths(jobs_dir, j)["done"]) for j in js] ds = [d for d in ds if d] rs = [report[j["id"]] for j in js if j["id"] in report] rej = Counter() for d in ds: rej.update(d["rejections"]) out.append(dict( source=fname[:-len(".jsonl")], genre=mix.MIX[js[0]["name"]][0], target_M=round(sum(j["target"] for j in js) / 1e6, 3), words_M=round(sum(r["words"] for r in rs) / 1e6, 3), docs=sum(r["docs"] for r in rs), collected_M=round(sum(d["words_M"] for d in ds), 3), cross_job_duplicates_M=round(sum(r["dup_words"] for r in rs) / 1e6, 3), trimmed_M=round(sum(r["trimmed_words"] for r in rs) / 1e6, 3), scanned_words_M=round(sum(d["scanned_words_M"] for d in ds), 1), seconds=sum(d["seconds"] for d in ds), shards=len(js), jobs_done=len(ds), stopped=sorted({d["stopped"] for d in ds}), stream_retries=sum(d["stream_retries"] for d in ds), rejections=dict(rej.most_common()), jobs=[{k: d[k] for k in ("job", "words_M", "stopped", "relaxation", "probe")} for d in ds])) return out def main(): phys = psutil.cpu_count(logical=False) or 2 ap = argparse.ArgumentParser(description=__doc__.split("\n")[0]) ap.add_argument("size", choices=list(mix.SIZES)) ap.add_argument("--workers", type=int, default=max(1, phys // 2), help=f"parallel jobs (default half the physical cores: {max(1, phys // 2)})") ap.add_argument("--min-free-gb", type=float, default=2.0, help="start a job only above this free RAM") ap.add_argument("--kill-free-gb", type=float, default=1.0, help="stop the youngest job below this free RAM") ap.add_argument("--min-disk-gb", type=float, default=10.0, help="stop everything below this free disk") ap.add_argument("--job-hours", type=float, default=1.5, help="split sources estimated above this") ap.add_argument("--max-shards", type=int, default=6) ap.add_argument("--overshoot", type=float, default=0.03, help="extra share collected before global dedup") ap.add_argument("--ckpt-seconds", type=int, default=120) ap.add_argument("--retries", type=int, default=3, help="restarts per job after a crash") ap.add_argument("--stagger", type=int, default=20, help="seconds between job starts") ap.add_argument("--status-seconds", type=int, default=300) ap.add_argument("--scale", type=float, default=1.0, help="multiply quotas, for test runs") ap.add_argument("--only", nargs="*", default=[], help="build only these sources (no fallbacks)") ap.add_argument("--allow-failed", action="store_true", help="go on to fallbacks even if a job failed") args = ap.parse_args() size = args.size apply_scale(args.scale, size) out_dir = ROOT / "work" / (size if args.scale == 1 else f"{size}_x{args.scale:g}") jobs_dir = out_dir / "jobs" jobs_dir.mkdir(parents=True, exist_ok=True) log = Log(out_dir / "pool.log") psutil.Process().nice(psutil.BELOW_NORMAL_PRIORITY_CLASS if os.name == "nt" else 10) t0, idx = time.time(), mix.SIZES[size] names = [n for n in mix.MIX if not args.only or n in args.only] log(f"== build {size} into {out_dir} ({' '.join(sys.argv[1:])})") prim = plan_jobs([(n, mix.MIX[n][1][idx] * 1e6) for n in names], "", args, lambda n: []) shards = Counter(j["name"] for j in prim) log("plan: " + ", ".join(f"{n} x{k}" for n, k in shards.items())) failed = run_pool(prim, args, size, jobs_dir, log) if failed and not args.allow_failed: raise SystemExit(f"{len(failed)} jobs failed: {[j['id'] for j in failed]}. Rerun the same command to " "retry them, or add --allow-failed to fill their share from fallbacks.") groups = [(f"{n}.jsonl", [j for j in prim if j["name"] == n]) for n in names if shards[n]] fallback_log = [] if not args.only: report = global_pass(groups, jobs_dir, out_dir, log, write=False) got = Counter() for j in prim: got[j["name"]] += report.get(j["id"], {}).get("words", 0) plan, fallback_log = build.plan_fallbacks(size, [dict(source=n, words_M=got[n] / 1e6) for n in names]) log(f"fallback plan: {fallback_log}") topups = plan_jobs(list(plan.items()), ".topup", args, lambda n: [str(paths(jobs_dir, j)["keys"]) for j in prim if j["name"] == n]) failed = run_pool(topups, args, size, jobs_dir, log) if failed and not args.allow_failed: raise SystemExit(f"{len(failed)} top-up jobs failed: {[j['id'] for j in failed]}. Rerun to retry.") groups += [(f"{n}.topup.jsonl", [j for j in topups if j["name"] == n]) for n in plan] report = global_pass(groups, jobs_dir, out_dir, log, write=True) srcs = summarize(groups, jobs_dir, report) total = sum(s["words_M"] for s in srcs) stats = dict(total_M=round(total, 3), fallbacks=fallback_log, sources=srcs, wall_seconds=round(time.time() - t0), options=vars(args)) (out_dir / "stats.json").write_text(json.dumps(stats, indent=1)) log(f"== total {total:.2f}M words in {(time.time() - t0) / 60:.0f} min wall") if __name__ == "__main__": main()