Cion-lab commited on
Commit
20e54a8
·
verified ·
1 Parent(s): fc350c9

Phase 2: build_mix -- resumable, cross-source shards, seeded intra-shuffle, mandatory en filter

Browse files
Files changed (1) hide show
  1. build/build_mix.py +340 -0
build/build_mix.py ADDED
@@ -0,0 +1,340 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Phase 2 builder: turn the selected sources into tokenised, deduplicated, resumable shards.
2
+ #
3
+ # Constraints this is written against (all measured, docs/00-platform-notes.md):
4
+ # * Kaggle **CPU** session: 4 vCPU, 30 GiB cgroup, **no swap**, 19.5 GB /kaggle/working. Dedup
5
+ # structures are sized by *document count* (~2.1M docs), never by tokens.
6
+ # * Hub download is 35-89 MB/s and tokenisation ~661k tok/s on 4 cores. Neither is the bottleneck;
7
+ # `datasets` streaming at ~3.3 MB/s per process is. So sources go one at a time, streamed, never
8
+ # materialised.
9
+ # * The session can be killed at any time (§3.1). Every completed shard is written and recorded before
10
+ # the next begins, and the exact-duplicate hash set is persisted alongside it -- otherwise "resume"
11
+ # silently means "start forgetting what you already emitted", which would let duplicates back in
12
+ # across the resume boundary. State is saved only *after* a shard lands on disk.
13
+ #
14
+ # Dedup policy, with its limits stated:
15
+ # * exact, global: 64-bit hash of the normalised document.
16
+ # * cross-source, on the upstream url/id/file_path field -- this is what actually catches FinePhrase's
17
+ # configs being rewrites of the same FineWeb-Edu documents (§02-mix-plan §2).
18
+ # * near-dup MinHash is NOT run here. It needs every signature resident at once (~1.1 GB) and the
19
+ # within-source benefit is already largely captured by the exact hash. It is a v2 candidate, decided
20
+ # by the measured exact-dedup loss this script reports, not by convention.
21
+ #
22
+ # Language: §3.4 is English-only and the inventory measured 8.5% of finepdfs `eng_Latn` and 7.5% of
23
+ # open-web-math failing a crude English test, so the filter below is mandatory, not decorative.
24
+ #
25
+ # No credentials in this file. Publish is a separate script.
26
+
27
+ import argparse
28
+ import array
29
+ import hashlib
30
+ import json
31
+ import os
32
+ import random
33
+ import struct
34
+ import time
35
+
36
+ TOKENS_PER_SHARD = 8_000_000 # 16 MB as uint16 -> ~140 shards for 1.1B tokens, ~2.3 GB total
37
+ ROW_TOKEN_CAP = 16_384 # one document must never dominate a shard
38
+ SHUFFLE_SEED = 20260919 # recorded in the manifest so a rebuild is reproducible
39
+ HASHES_FILE = "seen_hashes.bin"
40
+ STATE_NAME = "build_state.json"
41
+
42
+ # Corrected config and column names, from the Phase 2 inventory (docs/02-mix-plan.md §9). The §2 names
43
+ # came from dataset cards and five of them did not exist.
44
+ SOURCES = [
45
+ dict(repo="HuggingFaceFW/fineweb-edu", config="sample-10BT", col="text", tokens=300_000_000,
46
+ min_score=4, why="quality-scored general English"),
47
+ dict(repo="HuggingFaceFW/finepdfs-edu", config="eng_Latn", col="text", tokens=150_000_000,
48
+ en_filter=True, why="long-form educational PDFs; needs own en filter"),
49
+ dict(repo="HuggingFaceTB/cosmopedia", config="stanford", col="text", tokens=60_000_000,
50
+ why="textbook expository"),
51
+ dict(repo="HuggingFaceTB/cosmopedia", config="openstax", col="text", tokens=30_000_000,
52
+ why="textbook science"),
53
+ dict(repo="HuggingFaceTB/cosmopedia", config="khanacademy", col="text", tokens=10_000_000,
54
+ why="worked steps"),
55
+ dict(repo="HuggingFaceTB/cosmopedia", config="auto_math_text", col="text", tokens=30_000_000,
56
+ why="synthetic math exposition"),
57
+ dict(repo="HuggingFaceTB/cosmopedia", config="wikihow", col="text", tokens=30_000_000,
58
+ why="procedural / physical-world steps"),
59
+ dict(repo="HuggingFaceFW/finewiki", config="en", col="rewritten", tokens=80_000_000,
60
+ why="rewritten encyclopedic prose"),
61
+ dict(repo="omarkamali/wikipedia-monthly", config="20260101.en", col="text", tokens=60_000_000,
62
+ why="current encyclopedic breadth"),
63
+ dict(repo="HuggingFaceTB/finemath", config="finemath-4plus", col="text", tokens=130_000_000,
64
+ why="math; upstream-decontaminated against GSM8K/MMLU/ARC"),
65
+ dict(repo="open-web-math/open-web-math", config="default", col="text", tokens=70_000_000,
66
+ en_filter=True, why="forum/webbook math prose"),
67
+ dict(repo="HuggingFaceFW/finephrase", config="tutorial", col="text", tokens=60_000_000,
68
+ why="stepwise tutorial register"),
69
+ dict(repo="HuggingFaceFW/finephrase", config="faq", col="text", tokens=30_000_000,
70
+ why="FAQ register"),
71
+ dict(repo="HuggingFaceFW/finephrase", config="table", col="text", tokens=30_000_000,
72
+ why="tabular->prose"),
73
+ dict(repo="SimpleStories/SimpleStories", config="default", col="story", tokens=40_000_000,
74
+ why="long-range simple narrative coherence"),
75
+ dict(repo="common-pile/arxiv_abstracts", config="default", col="text", tokens=20_000_000,
76
+ why="CC0 scientific abstracts"),
77
+ # No code source yet: stack-v3-train has only a `default` config, and its rows are whole repos with a
78
+ # nested `files` struct, so it needs its own probe first (docs/02-mix-plan.md §9.3).
79
+ # libretexts dropped outright: its `text` column holds URLs and 93% of sampled rows failed en.
80
+ ]
81
+
82
+ STOP = (" the ", " and ", " of ", " to ", " that ", " is ", " in ", " for ", " with ", " as ")
83
+ KEY_COLS = ("url", "id", "file_path", "doc_id", "generation_id", "repo_name")
84
+
85
+
86
+ def normalize(s):
87
+ # Whitespace-collapse only. Aggressive folding would collide genuinely different documents (tables,
88
+ # code) and a false merge is worse than a missed near-duplicate.
89
+ return " ".join(s.split())
90
+
91
+
92
+ def looks_english(s):
93
+ low = s[:600].lower()
94
+ return sum(w in low for w in STOP) >= 3
95
+
96
+
97
+ def doc_hash(s):
98
+ return struct.unpack("<Q", hashlib.sha256(s.encode("utf-8")).hexdigest()[:16].encode())[0]
99
+
100
+
101
+ def key_of(row, cols):
102
+ for c in KEY_COLS:
103
+ if c in cols:
104
+ v = row.get(c)
105
+ if isinstance(v, str) and v:
106
+ return v
107
+ return None
108
+
109
+
110
+ class State:
111
+ def __init__(self, out_dir):
112
+ self.dir = out_dir
113
+ self.path = os.path.join(out_dir, STATE_NAME)
114
+ self.hashes_path = os.path.join(out_dir, HASHES_FILE)
115
+ self.d = {"shards": [], "per_source": {}, "started": time.time(), "version": 2}
116
+ self.seen_exact = set()
117
+ self.seen_url = set()
118
+ if os.path.exists(self.path):
119
+ self.d = json.load(open(self.path))
120
+ if os.path.exists(self.hashes_path):
121
+ a = array.array("Q")
122
+ with open(self.hashes_path, "rb") as f:
123
+ a.fromfile(f, os.path.getsize(self.hashes_path) // 8)
124
+ self.seen_exact = set(a)
125
+ print(f"resuming: {len(self.d['shards'])} shards, "
126
+ f"{len(self.seen_exact):,} exact hashes, {self.tokens_done():,} tokens", flush=True)
127
+ for s in self.d["per_source"].values():
128
+ self.seen_url.update(s.get("keys", []))
129
+
130
+ def tokens_done(self):
131
+ return sum(s["tokens"] for s in self.d["shards"])
132
+
133
+ def save(self, new_hashes, new_keys):
134
+ with open(self.hashes_path, "ab") as f:
135
+ array.array("Q", new_hashes).tofile(f)
136
+ d = dict(self.d)
137
+ d["per_source"] = {k: {kk: vv for kk, vv in v.items() if kk != "keys"}
138
+ for k, v in self.d["per_source"].items()}
139
+ tmp = self.path + ".tmp"
140
+ with open(tmp, "w") as f:
141
+ json.dump(d, f, indent=1)
142
+ os.replace(tmp, self.path)
143
+
144
+ def record_source(self, key, done, tokens, docs_seen, drops, seconds, keys):
145
+ self.d["per_source"][key] = {"complete": bool(done), "tokens": tokens,
146
+ "docs_seen": docs_seen, "dropped": drops,
147
+ "seconds": round(seconds, 1), "keys_sample": keys[:2000]}
148
+ self.seen_url.update(keys[:2000])
149
+
150
+
151
+ def build(args):
152
+ t_start = time.monotonic()
153
+ from tokenizers import Tokenizer
154
+ from huggingface_hub import hf_hub_download
155
+
156
+ os.makedirs(args.out, exist_ok=True)
157
+ tok_path = hf_hub_download("HuggingFaceTB/SmolLM2-135M", "tokenizer.json")
158
+ tk = Tokenizer.from_file(tok_path)
159
+ tk.no_truncation()
160
+ vocab = tk.get_vocab_size()
161
+ assert vocab <= 65536, f"uint16 shard layout breaks above 65,536 (vocab={vocab})"
162
+ tok_sha = hashlib.sha256(open(tok_path, "rb").read()).hexdigest()
163
+ print(f"tokenizer vocab={vocab} sha256={tok_sha[:12]} budget={args.budget_tokens:,}", flush=True)
164
+
165
+ st = State(args.out)
166
+ buf, buf_src = [], []
167
+ buf_tokens = 0
168
+ pending_hashes, pending_keys = [], []
169
+
170
+ def flush_shard():
171
+ nonlocal buf, buf_src, buf_tokens, pending_hashes, pending_keys
172
+ if not buf:
173
+ pending_hashes, pending_keys = [], []
174
+ return
175
+ ids = array.array("H")
176
+ # The buffer deliberately spans source boundaries (nothing flushes at end-of-source), so a shard
177
+ # already mixes domains; shuffling the documents first removes the residual "all fineweb-edu, then
178
+ # all cosmopedia" ordering inside a pass. Seeded and recorded so a rebuild is reproducible.
179
+ random.Random(SHUFFLE_SEED + len(st.d["shards"])).shuffle(buf)
180
+ docs = 0
181
+ for doc in buf:
182
+ ids.extend(doc)
183
+ docs += 1
184
+ idx = len(st.d["shards"])
185
+ path = os.path.join(args.out, f"shard-{idx:04d}.bin")
186
+ tmp = path + ".tmp"
187
+ with open(tmp, "wb") as f:
188
+ f.write(struct.pack("<II", vocab, len(ids)))
189
+ ids.tofile(f)
190
+ os.replace(tmp, path)
191
+ digest = hashlib.sha256(open(path, "rb").read()).hexdigest()
192
+ st.d["shards"].append({"file": os.path.basename(path), "tokens": len(ids), "docs": docs,
193
+ "sha256": digest, "bytes": os.path.getsize(path),
194
+ "sources": sorted(set(buf_src))})
195
+ st.save(pending_hashes, pending_keys)
196
+ print(f" shard {idx:04d}: {len(ids):,} tok / {docs:,} docs sha256={digest[:12]} "
197
+ f"[{time.monotonic() - t_start:.0f}s]", flush=True)
198
+ buf, buf_src, buf_tokens, pending_hashes, pending_keys = [], [], 0, [], []
199
+
200
+ if args.max_shards and len(st.d["shards"]) >= args.max_shards:
201
+ print(f"max_shards={args.max_shards} reached; exiting without work", flush=True)
202
+ return {"total_tokens": st.tokens_done(), "shards": len(st.d["shards"])}
203
+
204
+ stats = []
205
+ for src in SOURCES:
206
+ key = f"{src['repo']}::{src['config']}"
207
+ if st.d["per_source"].get(key, {}).get("complete"):
208
+ print(f"skip {key} (already complete)", flush=True)
209
+ continue
210
+ if st.tokens_done() >= args.budget_tokens:
211
+ print("budget reached", flush=True)
212
+ break
213
+ if args.max_shards and len(st.d["shards"]) >= args.max_shards:
214
+ print(f"max_shards={args.max_shards} reached", flush=True)
215
+ break
216
+ import datasets
217
+
218
+ try:
219
+ ds = datasets.load_dataset(src["repo"], src["config"], split="train", streaming=True)
220
+ except Exception as e:
221
+ # A wrong config name must be loud, must be recorded, and must not abort later sources.
222
+ print(f"!! {key} could not load: {type(e).__name__}: {str(e)[:200]}", flush=True)
223
+ stats.append({"source": key, "error": f"{type(e).__name__}: {str(e)[:200]}"})
224
+ continue
225
+
226
+ want = min(src["tokens"], args.budget_tokens - st.tokens_done())
227
+ got = docs_seen = 0
228
+ drops = {"short_or_low_score": 0, "non_english": 0, "exact_dup": 0, "url_dup": 0, "too_few_tokens": 0}
229
+ cols = None
230
+ t0 = time.monotonic()
231
+ src_keys = []
232
+ for row in ds:
233
+ if got >= want:
234
+ break
235
+ if args.sec_per_source and time.monotonic() - t0 > args.sec_per_source:
236
+ break
237
+ if cols is None:
238
+ cols = set(row.keys())
239
+ if src["col"] not in cols:
240
+ print(f"!! {key} has no column {src['col']!r}; seen {sorted(cols)[:10]}", flush=True)
241
+ drops["short_or_low_score"] = -1
242
+ break
243
+ raw = row.get(src["col"])
244
+ if not isinstance(raw, str):
245
+ continue
246
+ docs_seen += 1
247
+ s = normalize(raw)
248
+ if len(s) < args.min_chars:
249
+ drops["short_or_low_score"] += 1
250
+ continue
251
+ if src.get("min_score") is not None:
252
+ sc = row.get("int_score", row.get("score"))
253
+ try:
254
+ if sc is not None and float(sc) < src["min_score"]:
255
+ drops["short_or_low_score"] += 1
256
+ continue
257
+ except (TypeError, ValueError):
258
+ pass
259
+ if src.get("en_filter") and not looks_english(s):
260
+ drops["non_english"] += 1
261
+ continue
262
+ h = doc_hash(s)
263
+ if h in st.seen_exact:
264
+ drops["exact_dup"] += 1
265
+ continue
266
+ u = key_of(row, cols)
267
+ if u and u in st.seen_url:
268
+ drops["url_dup"] += 1
269
+ continue
270
+ ids = tk.encode(s[:args.max_chars], add_special_tokens=False).ids[:ROW_TOKEN_CAP]
271
+ if len(ids) < 16:
272
+ drops["too_few_tokens"] += 1
273
+ continue
274
+ st.seen_exact.add(h)
275
+ pending_hashes.append(h)
276
+ if u:
277
+ st.seen_url.add(u)
278
+ src_keys.append(u)
279
+ pending_keys.append(u)
280
+ buf.append(ids)
281
+ buf_src.append(key)
282
+ buf_tokens += len(ids)
283
+ got += len(ids)
284
+ if buf_tokens >= TOKENS_PER_SHARD:
285
+ flush_shard()
286
+
287
+ elapsed = time.monotonic() - t0
288
+ complete = got >= want
289
+ st.record_source(key, complete, got, docs_seen, drops, elapsed, src_keys)
290
+ stats.append({"source": key, "tokens": got, "docs_seen": docs_seen, "dropped": dict(drops),
291
+ "seconds": round(elapsed, 1), "tok_per_s": round(got / max(1e-9, elapsed)),
292
+ "complete": bool(complete)})
293
+ print(f" {key}: {got:,} tok of {want:,} target from {docs_seen:,} docs; dup={drops['exact_dup']}"
294
+ f"/{drops['url_dup']} lang={drops['non_english']} short={drops['short_or_low_score']} "
295
+ f"[{stats[-1]['tok_per_s']:,} tok/s, {elapsed:.0f}s]", flush=True)
296
+
297
+ flush_shard()
298
+ total_docs = sum(s.get("docs_seen", 0) for s in stats) or 1
299
+ total_dupes = sum(d["exact_dup"] + d["url_dup"]
300
+ for s in stats for d in [s.get("dropped") or {}] if d)
301
+ manifest = {
302
+ "tokenizer": {"id": "HuggingFaceTB/SmolLM2-135M:tokenizer.json", "vocab_size": vocab,
303
+ "sha256": tok_sha},
304
+ "layout": {"dtype": "uint16", "header": "<II (vocab, n_tokens)",
305
+ "resume_cursor": "(shard_index, token_offset) into the concatenated id stream",
306
+ "tokens_per_shard_target": TOKENS_PER_SHARD, "row_token_cap": ROW_TOKEN_CAP,
307
+ "shuffle_seed_base": SHUFFLE_SEED,
308
+ "shuffle_note": "documents within shard idx are shuffled with seed base+idx; "
309
+ "shard order is the training order"},
310
+ "total_tokens": st.tokens_done(), "shards": st.d["shards"], "sources": stats,
311
+ "budget_tokens": args.budget_tokens,
312
+ "exact_dedup_drop_rate": round(total_dupes / total_docs, 4),
313
+ "seconds": round(time.monotonic() - t_start, 1),
314
+ }
315
+ with open(os.path.join(args.out, "manifest.json"), "w") as f:
316
+ json.dump(manifest, f, indent=1)
317
+ return manifest
318
+
319
+
320
+ def main():
321
+ ap = argparse.ArgumentParser()
322
+ ap.add_argument("--out", default="/kaggle/working/mix")
323
+ ap.add_argument("--budget-tokens", type=int, default=1_310_000_000)
324
+ ap.add_argument("--min-chars", type=int, default=300)
325
+ ap.add_argument("--max-chars", type=int, default=100_000)
326
+ ap.add_argument("--sec-per-source", type=int, default=0)
327
+ ap.add_argument("--max-shards", type=int, default=0, help="0 = unlimited")
328
+ a = ap.parse_args()
329
+ if a.max_shards == 0:
330
+ a.max_shards = None
331
+ m = build(a)
332
+ print("BUILD_JSON_BEGIN")
333
+ print(json.dumps({"total_tokens": m["total_tokens"], "shards": len(m["shards"]),
334
+ "exact_dedup_drop_rate": m.get("exact_dedup_drop_rate"),
335
+ "seconds": m["seconds"]}))
336
+ print("BUILD_JSON_END")
337
+
338
+
339
+ if __name__ == "__main__":
340
+ main()