jvonrad commited on
Commit
694072a
·
verified ·
1 Parent(s): dcf5865

Upload src/xscript/data/fineweb.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. src/xscript/data/fineweb.py +326 -0
src/xscript/data/fineweb.py ADDED
@@ -0,0 +1,326 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Model-training text pools from FineWeb-HQ (EN) / FineWeb2-HQ (DE/FR/AR/ZH).
2
+
3
+ Both datasets come from the same lab and the same XLM-R-embedding quality
4
+ classifier (top-10%% selection), keeping filtering methodology constant across
5
+ all five languages -- with two documented exceptions: FineWeb2-HQ's arb_Arab
6
+ split is only ~29GB total (85 parquet files, confirmed exhausted 2026-07-13),
7
+ and fra_Latn -HQ fully exhausted at 124.1GB (2026-07-14), both far short of
8
+ what our token budgets need. `FALLBACK_SOURCES` lets a language keep pulling
9
+ from a second, less-strict source (FineWeb2's own dedup+quality-filtered
10
+ "train" split, one filter step short of the top-decile HQ cut -- still same
11
+ lab/pipeline) once its primary source is exhausted, rather than epoch heavily
12
+ over a small pool. This is a real, deliberate deviation from strict
13
+ filter-parity for these two languages; note it in the thesis.
14
+
15
+ We stream parquet with column pruning (only `text`), so the large `embeddings`
16
+ column in FineWeb2-HQ is never downloaded. Output pools are zstd jsonl shards
17
+ of ~1GB uncompressed text. The first parquet file of the primary source is
18
+ reserved exclusively for the in-domain eval holdout (never enters the pool).
19
+ """
20
+ import json
21
+ from pathlib import Path
22
+
23
+ from ..langs import LANGS
24
+ from ..paths import MANIFEST_CACHE, POOLS, HOLDOUT, pool_dir, ensure
25
+
26
+ POOL_SHARD_BYTES = 1 << 30 # uncompressed text per pool shard
27
+ HOLDOUT_BYTES = 30 * (1 << 20) # 30MB per language
28
+
29
+ FALLBACK_SOURCES: dict[str, tuple[str, str]] = {
30
+ "ar": ("HuggingFaceFW/fineweb-2", "data/arb_Arab/train"),
31
+ # fra_Latn -HQ (epfml/FineWeb2-HQ) fully exhausted 2026-07-14 at 124.1GB,
32
+ # short of the 152.2GB budget -- same fallback pattern as ar.
33
+ "fr": ("HuggingFaceFW/fineweb-2", "data/fra_Latn/train"),
34
+ }
35
+
36
+
37
+ def _sources_for(lang: str) -> list[tuple[str, str]]:
38
+ """[(repo, subdir), ...] in priority order: primary (quality-filtered -HQ)
39
+ first, then any FALLBACK_SOURCES entry once the primary is exhausted."""
40
+ L = LANGS[lang]
41
+ srcs = [(L.fineweb_repo, L.fineweb_subdir)]
42
+ if lang in FALLBACK_SOURCES:
43
+ srcs.append(FALLBACK_SOURCES[lang])
44
+ return srcs
45
+
46
+
47
+ def _list_parquets(repo: str, subdir: str) -> list[str]:
48
+ """Manifest of parquet files under repo/subdir, round-robin across CC dumps
49
+ for raw FineWeb-HQ (EN)."""
50
+ from huggingface_hub import HfApi
51
+ cache = ensure(MANIFEST_CACHE / "fineweb_hq_pools") / \
52
+ f"{repo.replace('/', '__')}__{subdir.replace('/', '_')}.json"
53
+ if cache.exists():
54
+ return json.loads(cache.read_text())
55
+ api = HfApi()
56
+ files = [e.path for e in api.list_repo_tree(repo, subdir,
57
+ repo_type="dataset", recursive=True)
58
+ if e.__class__.__name__ == "RepoFile" and e.path.endswith(".parquet")]
59
+ if repo == "epfml/FineWeb-HQ":
60
+ # data/CC-MAIN-YYYY-WW/000_xxxxx.parquet: interleave dumps so the pool
61
+ # spans the full 2013-2024 crawl range like FineWeb2-HQ does.
62
+ by_dump: dict[str, list[str]] = {}
63
+ for f in sorted(files):
64
+ by_dump.setdefault(f.split("/")[1], []).append(f)
65
+ out = []
66
+ for i in range(max(len(v) for v in by_dump.values())):
67
+ for d in sorted(by_dump):
68
+ if i < len(by_dump[d]):
69
+ out.append(by_dump[d][i])
70
+ files = out
71
+ else:
72
+ files = sorted(files)
73
+ cache.write_text(json.dumps(files))
74
+ return files
75
+
76
+
77
+ def _iter_texts(repo: str, path_in_repo: str):
78
+ import pyarrow.parquet as pq
79
+ from huggingface_hub import HfFileSystem
80
+ fs = HfFileSystem()
81
+ with fs.open(f"datasets/{repo}/{path_in_repo}", "rb") as f:
82
+ pf = pq.ParquetFile(f)
83
+ for rg in range(pf.num_row_groups):
84
+ tbl = pf.read_row_group(rg, columns=["text"])
85
+ for t in tbl.column("text").to_pylist():
86
+ if t:
87
+ yield t
88
+
89
+
90
+ class _PoolWriter:
91
+ def __init__(self, out_dir: Path, prefix: str = "pool", start_idx: int = -1,
92
+ total_bytes: int = 0, total_docs: int = 0):
93
+ import zstandard
94
+ self.dir = ensure(out_dir)
95
+ self.prefix = prefix
96
+ self.zstd = zstandard
97
+ self.idx = start_idx
98
+ self.cur = None
99
+ self.cur_bytes = 0
100
+ self.total_bytes = total_bytes
101
+ self.total_docs = total_docs
102
+ self._roll()
103
+
104
+ def _roll(self):
105
+ if self.cur:
106
+ self.cur.close()
107
+ self.idx += 1
108
+ self.cur_bytes = 0
109
+ raw = open(self.dir / f"{self.prefix}_{self.idx:05d}.jsonl.zst", "wb")
110
+ self.cur = self.zstd.ZstdCompressor(level=3).stream_writer(raw, closefd=True)
111
+
112
+ def write(self, text: str):
113
+ line = json.dumps({"text": text}, ensure_ascii=False) + "\n"
114
+ b = line.encode("utf-8")
115
+ self.cur.write(b)
116
+ n = len(text.encode("utf-8"))
117
+ self.cur_bytes += n
118
+ self.total_bytes += n
119
+ self.total_docs += 1
120
+ if self.cur_bytes >= POOL_SHARD_BYTES:
121
+ self._roll()
122
+
123
+ def close(self):
124
+ if self.cur:
125
+ self.cur.close()
126
+ self.cur = None
127
+
128
+
129
+ CHECKPOINT_EVERY_N_FILES = 3 # bound on re-downloaded work if the process dies
130
+
131
+
132
+ def _next_shard_idx(out_dir: Path, prefix: str = "pool") -> int:
133
+ existing = sorted(out_dir.glob(f"{prefix}_*.jsonl.zst"))
134
+ if not existing:
135
+ return -1
136
+ stem = existing[-1].name[len(prefix) + 1:] # "NNNNN.jsonl.zst"
137
+ return int(stem.split(".", 1)[0])
138
+
139
+
140
+ def build_pool(lang: str, budget_bytes: float, holdout_bytes: int = HOLDOUT_BYTES) -> dict:
141
+ """Build (or resume) a language's text pool.
142
+
143
+ Crash-resumable: every CHECKPOINT_EVERY_N_FILES source files, the current
144
+ shard is closed (a truncated zstd frame from a mid-write kill can't be
145
+ decoded, so a checkpoint never leaves a shard half-written) and
146
+ `stats.json` records which manifest files are already consumed plus the
147
+ index of that last cleanly-closed shard (`shard_idx`). A crash *between*
148
+ checkpoints (e.g. mid-way through one large parquet file) can still leave
149
+ a higher-numbered shard on disk with an unterminated zstd frame -- since
150
+ none of its bytes were counted into `text_bytes`/`docs` at the last
151
+ checkpoint, resuming deletes any shard past `shard_idx` before writing
152
+ starts again, so a stray corrupt shard never lingers for `pack()` to trip
153
+ on. Re-running `xscript pool` after an interruption (SSH drop, node
154
+ hiccup, ^C, session teardown) picks up from there instead of
155
+ re-downloading from scratch. `files_consumed` entries are tagged
156
+ "repo::path" so a language with a FALLBACK_SOURCES entry can track
157
+ consumption across sources without collision; old untagged checkpoints
158
+ (single-source) are migrated on load by assuming the primary repo.
159
+ """
160
+ sources = _sources_for(lang)
161
+ primary_repo, primary_subdir = sources[0]
162
+ first_files = _list_parquets(primary_repo, primary_subdir)
163
+ if not first_files:
164
+ raise RuntimeError(f"no parquet files found for {lang}")
165
+ out = pool_dir(lang)
166
+ stats_path = out / "stats.json"
167
+ resume = None
168
+ if stats_path.exists():
169
+ st = json.loads(stats_path.read_text())
170
+ if st["text_bytes"] >= budget_bytes * 0.99:
171
+ print(f"[pool] {lang}: cached ({st['text_bytes']/1e9:.1f}GB)")
172
+ return st
173
+ if st.get("files_consumed"):
174
+ resume = st
175
+ print(f"[pool] {lang}: resuming from checkpoint "
176
+ f"({st['text_bytes']/1e9:.1f}/{budget_bytes/1e9:.1f}GB, "
177
+ f"{len(st['files_consumed'])} files already consumed)")
178
+
179
+ if resume is None:
180
+ # holdout from the primary source's first file only; pool starts at the second
181
+ hw = _PoolWriter(HOLDOUT, prefix=lang)
182
+ got = 0
183
+ for t in _iter_texts(primary_repo, first_files[0]):
184
+ hw.write(t)
185
+ got += len(t.encode("utf-8"))
186
+ if got >= holdout_bytes:
187
+ break
188
+ hw.close()
189
+ used: list[str] = []
190
+ pw = _PoolWriter(out)
191
+ else:
192
+ got = resume["holdout_bytes"]
193
+ used = [u if "::" in u else f"{primary_repo}::{u}" for u in resume["files_consumed"]]
194
+ # shard_idx is missing on checkpoints written before this field existed;
195
+ # best-effort fall back to whatever's on disk (pre-existing behaviour).
196
+ last_good_idx = resume.get("shard_idx")
197
+ if last_good_idx is None:
198
+ last_good_idx = _next_shard_idx(out)
199
+ else:
200
+ for stray in out.glob("pool_*.jsonl.zst"):
201
+ idx = int(stray.name[len("pool_"):].split(".", 1)[0])
202
+ if idx > last_good_idx:
203
+ stray.unlink() # never checkpointed -- may be a truncated zstd frame
204
+ # The file *at* shard_idx is the one _checkpoint()'s _roll() had just
205
+ # opened (empty) when that checkpoint was written -- everything written
206
+ # into it since then, up to a crash, was never counted in text_bytes/
207
+ # docs. It's fine (already fully closed) if the run reached this point
208
+ # via the final `pw.close()` on graceful completion, but indistinguishable
209
+ # from a crash-mid-write from stats.json alone -- so verify by decoding.
210
+ at_idx = out / f"pool_{last_good_idx:05d}.jsonl.zst"
211
+ if at_idx.exists():
212
+ import io
213
+ import zstandard
214
+ try:
215
+ with open(at_idx, "rb") as raw:
216
+ reader = zstandard.ZstdDecompressor().stream_reader(raw)
217
+ for jline in io.TextIOWrapper(reader, encoding="utf-8"):
218
+ if jline.strip():
219
+ json.loads(jline)
220
+ except Exception as exc:
221
+ print(f"[pool] {lang}: {at_idx.name} failed validation ({exc}) "
222
+ f"-- discarding (never counted in checkpointed totals)")
223
+ at_idx.unlink()
224
+ pw = _PoolWriter(out, start_idx=last_good_idx,
225
+ total_bytes=resume["text_bytes"], total_docs=resume["docs"])
226
+
227
+ def _checkpoint():
228
+ pw._roll() # close the current shard so it's a complete, valid zstd frame
229
+ st = {"lang": lang, "budget_bytes": budget_bytes, "text_bytes": pw.total_bytes,
230
+ "docs": pw.total_docs, "holdout_bytes": got, "holdout_file": first_files[0],
231
+ "files_consumed": used, "shard_idx": pw.idx, "exhausted": False}
232
+ stats_path.write_text(json.dumps(st, indent=2))
233
+
234
+ done = False
235
+ for i, (repo, subdir) in enumerate(sources):
236
+ files = first_files if i == 0 else _list_parquets(repo, subdir)
237
+ pool_files = files[1:] if i == 0 else files # only the primary source reserves a holdout file
238
+ for f in pool_files:
239
+ tag = f"{repo}::{f}"
240
+ if tag in used:
241
+ continue
242
+ used.append(tag)
243
+ try:
244
+ for t in _iter_texts(repo, f):
245
+ pw.write(t)
246
+ if pw.total_bytes >= budget_bytes:
247
+ break
248
+ except Exception as exc:
249
+ print(f"[pool] WARN {tag}: {exc}")
250
+ used.pop() # not actually consumed -- retry it on the next run
251
+ if pw.total_bytes >= budget_bytes:
252
+ done = True
253
+ _checkpoint()
254
+ break
255
+ if len(used) % CHECKPOINT_EVERY_N_FILES == 0:
256
+ _checkpoint()
257
+ if len(used) % 20 == 0:
258
+ print(f"[pool] {lang}: {pw.total_bytes/1e9:.1f}/{budget_bytes/1e9:.1f}GB "
259
+ f"({len(used)} files, source {i+1}/{len(sources)}: {repo})")
260
+ if done:
261
+ break
262
+ if i + 1 < len(sources):
263
+ print(f"[pool] {lang}: source {i+1}/{len(sources)} ({repo}) exhausted at "
264
+ f"{pw.total_bytes/1e9:.1f}GB -> falling back to {sources[i+1][0]}")
265
+ pw.close()
266
+ st = {"lang": lang, "budget_bytes": budget_bytes, "text_bytes": pw.total_bytes,
267
+ "docs": pw.total_docs, "holdout_bytes": got, "holdout_file": first_files[0],
268
+ "files_consumed": used, "shard_idx": pw.idx,
269
+ "exhausted": pw.total_bytes < budget_bytes * 0.99}
270
+ stats_path.write_text(json.dumps(st, indent=2))
271
+ if st["exhausted"]:
272
+ print(f"[pool] WARNING {lang}: corpus exhausted at {pw.total_bytes/1e9:.1f}GB "
273
+ f"< budget {budget_bytes/1e9:.1f}GB -> training will epoch over this pool")
274
+ print(f"[pool] {lang}: {pw.total_bytes/1e9:.2f}GB text, {pw.total_docs} docs")
275
+ return st
276
+
277
+
278
+ def _measured_bytes_per_token(flavor: str = "unigram", condition: str = "destarved") -> dict[str, float]:
279
+ """Real bytes/token per study language, measured on FLORES+ dev with the
280
+ tokenizer that will actually pack the pool text. Destarved is the more
281
+ byte-hungry of the two conditions (better fertility -> more input bytes
282
+ needed per token), so it's the binding case for sizing. Scripts vary a
283
+ lot (Arabic ~6.8 bytes/token vs Chinese ~4.0) -- returns {} (caller falls
284
+ back to a flat estimate) if the tokenizer or FLORES+ aren't ready yet.
285
+ """
286
+ from .. import flores
287
+ from ..langs import tok_name
288
+ from ..paths import tokenizer_dir
289
+ from ..tok.wrapper import Tok
290
+
291
+ tdir = tokenizer_dir(tok_name(flavor, condition))
292
+ if not (tdir / "meta.json").exists():
293
+ return {}
294
+ try:
295
+ tok = Tok(tdir)
296
+ par = flores.load_parallel(list(LANGS), "dev")
297
+ except Exception as exc:
298
+ print(f"[pool] WARN: couldn't measure real bytes/token ({exc}); "
299
+ f"falling back to the flat estimate")
300
+ return {}
301
+ out = {}
302
+ for l, sents in par.items():
303
+ b = sum(len(s.encode("utf-8")) for s in sents)
304
+ t = sum(len(tok.encode(s)) for s in sents)
305
+ out[l] = b / t
306
+ return out
307
+
308
+
309
+ def plan_budgets(tokens_per_run: float = 30e9, est_bytes_per_token: float = 4.5,
310
+ safety: float = 1.15) -> dict[str, float]:
311
+ """Per-language pool byte budgets.
312
+
313
+ Monolingual runs need the full token budget in one language; bilingual
314
+ runs need half. The pool must cover the *max* need across planned runs
315
+ under the worst-case (most byte-hungry, i.e. destarved) tokenizer.
316
+
317
+ Sized from each language's REAL measured bytes/token (destarved
318
+ tokenizer on FLORES+), not a flat guess -- a single constant badly
319
+ under/over-shoots per language given how much bytes/token varies by
320
+ script. `est_bytes_per_token` is only a fallback for languages the
321
+ measurement can't cover yet (e.g. before the tokenizer gate).
322
+ """
323
+ need_tokens = {l: tokens_per_run for l in LANGS} # monolingual dominates
324
+ measured = _measured_bytes_per_token()
325
+ return {l: need_tokens[l] * measured.get(l, est_bytes_per_token) * safety
326
+ for l in LANGS}