File size: 16,697 Bytes
362b32d | 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 | """SHADOW Assistant text data: download, route, tokenise (Gemma 4 vocabulary of EmbeddingGemma 2), pack 3 bytes per token,
upload shards as they finish (local disk only holds the shards in flight). Each shard also saves its unigram counts
(.counts.npz), so the frozen table's log-unigram prior is a sum over these files, with no second pass over the data.
python prep_text.py --source fineweb_edu --workers 30
python prep_text.py --source legal --test # tiny local check: 2 files, 2M tokens per bucket, no upload
Layout, one folder per source: <area>/<source>/<source>_w<worker>_<shard>.bin (+ .json, .counts.npz)
fineweb_edu HuggingFaceFW/fineweb-edu: .au pages -> knowledge/fineweb_edu_au (all), others -> knowledge/fineweb_edu (75B)
dclm mlfoundations/dclm-baseline-1.0: .au pages -> knowledge/dclm_au (6B, skipping URLs already in FineWeb-Edu .au),
others -> knowledge/dclm (35B)
legal, spaceai, joeyllm whole dataset -> knowledge/<source>
opencoder_fineweb, opencoder_annealing whole dataset -> code/<source>
nemotron_math nvidia/Nemotron-CC-Math-v1 4plus -> math/nemotron_cc_math_4plus, private repo (training only, rebuilt not posted)
wikipedia_au Australian articles of English Wikipedia -> knowledge/wikipedia_au, private repo (CC BY-SA, rebuilt not posted)
anneal_* maths for the anneal (SK 2026-10-23) -> math/anneal/<source>: Dolmino-mix-1124 maths subsets (MathCoder2,
TuluMath, DolminoSynthMath, GSM8K train, CodeSearchNet-owmfilter), MegaMath Q&A, and MegaMath Q&A
Shard file: raw tokens, 3 bytes each little-endian, every document = <bos> text <eos>. The .json lists tokens, documents
and source files.
"""
import argparse, hashlib, json, multiprocessing as mp, os, pathlib, re, time
from urllib.parse import urlparse
import numpy as np
BOS, EOS, VOCAB = 2, 1, 262144
SRC = {
"fineweb_edu": {"repo": "HuggingFaceFW/fineweb-edu", "glob": r"^data/.*\.parquet$", "route": "au_or_global",
"au": "knowledge/fineweb_edu_au", "glb": "knowledge/fineweb_edu", "glb_quota": 75e9, "au_quota": 1e12, "save_au_urls": True},
"dclm": {"repo": "mlfoundations/dclm-baseline-1.0", "glob": r"\.jsonl\.zst$", "route": "au_or_global",
"au": "knowledge/dclm_au", "glb": "knowledge/dclm", "glb_quota": 35e9, "au_quota": 6e9, "skip_au_urls": True},
"dclm_global": {"repo": "mlfoundations/dclm-baseline-1.0", "glob": r"\.jsonl\.zst$", "route": "au_or_global", # global half only
"au": "knowledge/dclm_au", "glb": "knowledge/dclm", "glb_quota": 35e9, "au_quota": 0},
"dclm_au": {"repo": "mlfoundations/dclm-baseline-1.0", "glob": r"\.jsonl\.zst$", "route": "au_or_global", # .au half only
"au": "knowledge/dclm_au", "glb": "knowledge/dclm", "glb_quota": 0, "au_quota": 6e9, "skip_au_urls": True},
"legal": {"repo": "isaacus/open-australian-legal-corpus", "glob": r"\.(parquet|jsonl|jsonl\.gz)$", "route": "all", "all": "knowledge/legal", "quota": 1e12},
"spaceai": {"repo": "MrSpaceCommander/spaceai-australian-corpus", "glob": r"^data/(train|validation)/(?!oalc).*[.]jsonl[.]gz$", # its oalc files repeat the legal corpus
"route": "all", "all": "knowledge/spaceai", "quota": 1e12},
"joeyllm": {"repo": "JoeyLLM/australian-dataset-1b", "glob": r"\.parquet$", "route": "all", "all": "knowledge/joeyllm", "quota": 1e12, "skip_au_urls": True},
"opencoder_fineweb": {"repo": "OpenCoder-LLM/opc-fineweb-code-corpus", "glob": r"^data/.*\.parquet$", "route": "all", "all": "code/opencoder_fineweb", "quota": 1e12},
"opencoder_annealing": {"repo": "OpenCoder-LLM/opc-annealing-corpus", "glob": r"\.jsonl$", "route": "all", "all": "code/opencoder_annealing", "quota": 1e12},
"gutenberg": {"repo": "juniot/qualc-gutenberg-en", "glob": r"^data/.*\.parquet$", "route": "all", "all": "creative/gutenberg", "quota": 1e12},
"poetry_lines": {"repo": "biglam/gutenberg-poetry-corpus", "glob": r"^data/.*\.parquet$", "route": "all", "all": "creative/gutenberg_poetry",
"quota": 1e12, "text": "poetry_lines"},
"poems": {"repo": "DanFosing/public-domain-poetry", "glob": r"^poems\.json$", "route": "all", "all": "creative/public_domain_poetry", "quota": 1e12, "text": "poem"},
"cosmopedia_stories": {"repo": "HuggingFaceTB/cosmopedia", "glob": r"^data/stories/.*\.parquet$", "route": "all", "all": "creative/cosmopedia_stories", "quota": 1e12},
"nemotron_math": {"repo": "nvidia/Nemotron-CC-Math-v1", "glob": r"^4plus/.*\.parquet$", "route": "all", "all": "math/nemotron_cc_math_4plus",
"quota": 1e12, "private": True}, # NVIDIA's terms: training only, rebuilt not posted
"wikipedia_au": {"repo": "wikimedia/wikipedia", "glob": r"^20231101\.en/.*\.parquet$", "route": "all", "all": "knowledge/wikipedia_au",
"quota": 1e12, "filter": "australia", "private": True},
"anneal_mathcoder2": {"repo": "allenai/dolmino-mix-1124", "glob": r"^data/math/mathcoder2-synthmath/.*\.jsonl(\.gz|\.zst)?$", "route": "all", "all": "math/anneal/mathcoder2", "quota": 1e12},
"anneal_tulu_math": {"repo": "allenai/dolmino-mix-1124", "glob": r"^data/math/tulu_math/.*\.jsonl(\.gz|\.zst)?$", "route": "all", "all": "math/anneal/tulu_math", "quota": 1e12},
"anneal_dolmino_synth": {"repo": "allenai/dolmino-mix-1124", "glob": r"^data/math/dolmino_math_synth/.*\.jsonl(\.gz|\.zst)?$", "route": "all", "all": "math/anneal/dolmino_math_synth", "quota": 1e12},
"anneal_gsm8k": {"repo": "allenai/dolmino-mix-1124", "glob": r"^data/math/gsm8k/main/train/.*\.jsonl(\.gz|\.zst)?$", "route": "all", "all": "math/anneal/gsm8k", "quota": 1e12},
"anneal_codesearchnet": {"repo": "allenai/dolmino-mix-1124", "glob": r"^data/math/codesearchnet-owmfilter/.*\.jsonl(\.gz|\.zst)?$", "route": "all", "all": "math/anneal/codesearchnet_owmfilter", "quota": 1e12},
"anneal_megamath_qa": {"repo": "LLM360/MegaMath", "glob": r"^megamath-qa/.*\.parquet$", "route": "all", "all": "math/anneal/megamath_qa", "quota": 1e12},
}
AU_WORDS = re.compile(r"\b(Australia|Australian|New South Wales|Victoria, Australia|Queensland|Tasmania|Western Australia|South Australia|Northern Territory|Canberra|Sydney|Melbourne|Brisbane|Perth|Adelaide|Hobart|Darwin)\b")
def is_au(url):
try: return urlparse(url).netloc.lower().split(":")[0].endswith(".au")
except Exception: return False
def rows_jsonl_zst(repo, f):
"""read a .jsonl.zst file line by line, keeping only text and url (DCLM files disagree on the types of other fields)"""
import io, zstandard
from huggingface_hub import HfFileSystem
with HfFileSystem().open(f"datasets/{repo}/{f}", "rb", block_size=16 << 20) as fh:
for line in io.TextIOWrapper(zstandard.ZstdDecompressor().stream_reader(fh), encoding="utf-8", errors="replace"):
try: o = json.loads(line)
except Exception: continue
yield {"text": o.get("text") or "", "url": o.get("url") or ""}
def poems_from_lines(rows, max_chars=20000):
"""the Gutenberg Poetry Corpus has one row per line; join consecutive lines of the same book into documents"""
cur, lines, n = None, [], 0
for r in rows:
if (r["gutenberg_id"] != cur or n > max_chars) and lines: yield {"text": "\n".join(lines)}; lines, n = [], 0
cur = r["gutenberg_id"]; lines.append(r["line"]); n += len(r["line"]) + 1
if lines: yield {"text": "\n".join(lines)}
def uhash(url): return hashlib.blake2b(url.encode("utf-8", "ignore"), digest_size=8).digest()
class Shards:
"""collects tokens for one bucket and writes 3-byte shards; finished shard names go to the upload queue"""
def __init__(self, out, bucket, wid, shard_tokens, upq):
self.out, self.bucket, self.wid, self.shard_tokens, self.upq = out, bucket, wid, shard_tokens, upq
self.buf, self.n, self.docs, self.k, self.files = [], 0, 0, 0, set()
def add(self, ids_list, src_file):
for ids in ids_list:
self.buf.append(np.asarray([BOS] + ids + [EOS], np.uint32)); self.n += len(ids) + 2; self.docs += 1
self.files.add(src_file)
if self.n >= self.shard_tokens: self.flush()
def flush(self):
if not self.n: return
a = np.concatenate(self.buf); b = np.empty((len(a), 3), np.uint8); b[:, 0] = a & 255; b[:, 1] = (a >> 8) & 255; b[:, 2] = (a >> 16) & 255
name = f"{self.bucket}/{self.bucket.split('/')[-1]}_w{self.wid:02d}_{self.k:05d}"
p = pathlib.Path(self.out) / (name + ".bin"); p.parent.mkdir(parents=True, exist_ok=True); p.write_bytes(b.tobytes())
np.savez_compressed(pathlib.Path(self.out) / (name + ".counts.npz"), counts=np.bincount(a, minlength=VOCAB).astype(np.uint32))
meta = {"tokens": int(len(a)), "documents": self.docs, "bytes_per_token": 3, "bos": BOS, "eos": EOS, "source_files": sorted(self.files)}
pathlib.Path(self.out, name + ".json").write_text(json.dumps(meta))
self.upq.put(name); self.buf, self.n, self.docs, self.files = [], 0, 0, set(); self.k += 1
def worker(wid, files, args, cfg, counters, upq, ret):
from datasets import load_dataset
from transformers import AutoTokenizer
tk = AutoTokenizer.from_pretrained("google/embeddinggemma-2")
skip = set()
if cfg.get("skip_au_urls") and os.path.exists(args.au_urls):
raw = pathlib.Path(args.au_urls).read_bytes(); skip = {raw[i:i + 8] for i in range(0, len(raw), 8)}
if cfg.get("skip_urls_file"): # pages already in another source (by URL)
raw = pathlib.Path(cfg["skip_urls_file"]).read_bytes(); skip = {raw[i:i + 8] for i in range(0, len(raw), 8)}
au_seen = [] if cfg.get("save_au_urls") else None
sh = {}
def S(b):
if b not in sh: sh[b] = Shards(args.out, b, wid, args.shard_tokens, upq); sh[b].k = args.shard_start
return sh[b]
def room(key, quota):
with counters[key].get_lock(): return counters[key].value < quota
quotas = [("glb", cfg["glb_quota"]), ("au", cfg["au_quota"])] if cfg["route"] == "au_or_global" else [("all", cfg["quota"])]
def put(batch, f):
for (bb, kk, qq), texts in batch.items():
if not texts or not room(kk, qq): continue
ids = tk(texts, add_special_tokens=False)["input_ids"]; S(bb).add(ids, f)
with counters[kk].get_lock(): counters[kk].value += sum(len(i) + 2 for i in ids)
for fi, f in enumerate(files):
if all(not room(k, q) for k, q in quotas): break
ds = rows_jsonl_zst(cfg["repo"], f) if f.endswith(".jsonl.zst") else load_dataset(cfg["repo"], data_files=[f], split="train", streaming=True)
if cfg.get("text") == "poetry_lines": ds = poems_from_lines(ds)
batch = {}
for row in ds:
t = row.get("text") or ""
if cfg.get("text") == "poem": t = f"{row.get('Title') or ''}\nby {row.get('Author') or 'Anonymous'}\n\n{t}".strip()
if len(t) < 50: continue
if cfg.get("filter") == "australia" and not AU_WORDS.search(t[:3000]): continue
if cfg["route"] == "au_or_global":
url = row.get("url") or ""
if is_au(url):
h = uhash(url)
if h in skip: continue
if au_seen is not None: au_seen.append(h)
key = (cfg["au"], "au", cfg["au_quota"])
else: key = (cfg["glb"], "glb", cfg["glb_quota"])
else:
if (cfg.get("skip_au_urls") or cfg.get("skip_urls_file")) and uhash(row.get("url") or "") in skip: continue
key = (cfg["all"], "all", cfg["quota"])
batch.setdefault(key, []).append(t)
if sum(len(v) for v in batch.values()) >= 512:
put(batch, f); batch = {}
if all(not room(k, q) for k, q in quotas): break # every bucket of this source is full: stop reading
put(batch, f)
print(f"w{wid:02d} file {fi + 1}/{len(files)} done {f} | totals " + " ".join(f"{k}={v.value / 1e9:.3f}B" for k, v in counters.items()), flush=True)
for s in sh.values(): s.flush()
if au_seen: ret.put(b"".join(au_seen))
def upload(names, out, repo):
"""one commit per source folder for a batch of finished shards, then delete the local files"""
from huggingface_hub import HfApi, CommitOperationAdd
api = HfApi(); groups = {}
for n in names: groups.setdefault(n.rsplit("/", 1)[0], []).append(n)
for folder, ns in groups.items():
ops = [CommitOperationAdd(path_in_repo=n + ext, path_or_fileobj=str(pathlib.Path(out) / (n + ext))) for n in ns for ext in (".bin", ".json", ".counts.npz")]
for attempt in range(8):
try: api.create_commit(repo, repo_type="dataset", operations=ops, commit_message=f"Add {folder} ({len(ns)} shards)"); break
except Exception as e: print(f"upload retry {attempt + 1} {folder}: {str(e)[:150]}", flush=True); time.sleep(30 * (attempt + 1))
else: print(f"UPLOAD FAILED {folder}: kept on disk", flush=True); continue
for n in ns:
for ext in (".bin", ".json", ".counts.npz"): (pathlib.Path(out) / (n + ext)).unlink(missing_ok=True)
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--source", required=True, choices=list(SRC)); ap.add_argument("--workers", type=int, default=max(1, os.cpu_count() - 4))
ap.add_argument("--out", default="out"); ap.add_argument("--repo", default="QLNI/shadow-assistant-data")
ap.add_argument("--private-repo", default="QLNI/shadow-assistant-private"); ap.add_argument("--shard-tokens", type=int, default=250_000_000)
ap.add_argument("--batch", type=int, default=8, help="shards per commit"); ap.add_argument("--au-urls", default="fineweb_edu_au_urls.bin")
ap.add_argument("--test", action="store_true"); ap.add_argument("--skip-files", default="", help="file listing source files already done")
ap.add_argument("--glb-quota", type=float, default=0); ap.add_argument("--shard-start", type=int, default=0, help="first shard number (resume)")
args = ap.parse_args(); cfg = dict(SRC[args.source]); repo = args.private_repo if cfg.get("private") else args.repo
if args.glb_quota: cfg["glb_quota"] = args.glb_quota
from huggingface_hub import HfApi
files = sorted(f for f in HfApi().list_repo_files(cfg["repo"], repo_type="dataset") if re.search(cfg["glob"], f))
if args.skip_files:
done = set(open(args.skip_files).read().split()); files = [f for f in files if f not in done]
if args.test:
files = files[:2]; args.workers = min(2, len(files)); args.shard_tokens = 1_000_000; repo = ""
for k in ("glb_quota", "au_quota", "quota"):
if k in cfg: cfg[k] = 2e6
print(f"{args.source}: {len(files)} files, {args.workers} workers, repo {repo or '(none, local only)'}", flush=True)
counters = {k: mp.Value("d", 0.0) for k in (["glb", "au"] if cfg["route"] == "au_or_global" else ["all"])}
upq, ret = mp.Queue(), mp.Queue(); chunks = [files[i::args.workers] for i in range(args.workers)]
t0 = time.time(); ps = [mp.Process(target=worker, args=(i, chunks[i], args, cfg, counters, upq, ret)) for i in range(args.workers)]
for p in ps: p.start()
pending, urls, last = [], [], time.time()
def drain():
while True:
try: pending.append(upq.get_nowait())
except Exception: break
while True:
try: urls.append(ret.get_nowait())
except Exception: break
while any(p.is_alive() for p in ps): # the main process does all uploads, in batches
time.sleep(5); drain()
if repo and (len(pending) >= args.batch or (pending and time.time() - last > 900)):
upload(pending, args.out, repo); pending, last = [], time.time()
for p in ps: p.join()
drain()
if repo and pending: upload(pending, args.out, repo)
if cfg.get("save_au_urls") and urls: pathlib.Path(args.au_urls).write_bytes(b"".join(urls))
summary = {"source": args.source, "files": len(files), "hours": round((time.time() - t0) / 3600, 3), **{k: v.value for k, v in counters.items()}}
print("SUMMARY", json.dumps(summary), flush=True)
pathlib.Path(args.out).mkdir(exist_ok=True); pathlib.Path(args.out, f"summary_{args.source}.json").write_text(json.dumps(summary, indent=1))
if __name__ == "__main__":
main()
|