st-taro amannagarkar commited on
Commit
81d0d00
·
1 Parent(s): 176b47c

Super-squash branch 'main' using huggingface_hub

Browse files

Co-authored-by: amannagarkar <amannagarkar@users.noreply.huggingface.co>

README.md ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ A mixture of datasets focused on Source/Intermediate Representation training for multilingual code generation.
3
+ For SCU CSEN346.
4
+
5
+
6
+ Sources:
7
+ UKPLab/SLTrans
8
+ bigcode/the-stack
9
+ allenai/peS2o
10
+ open-web-math/open-web-math
build_mixed_dataset.py ADDED
@@ -0,0 +1,504 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ build_mixed_dataset.py — Four-source mixed pre-training corpus builder.
4
+
5
+ Sources
6
+ -------
7
+ SLTrans local parquet (balanced language x IR-type) --sltrans-tokens
8
+ peS2o allenai/peS2o (open scientific papers) --pes2o-tokens
9
+ TheStack bigcode/the-stack (permissively licensed code) --stack-tokens
10
+ OpenWebMath open-web-math/open-web-math (math web text) --owm-tokens
11
+
12
+ Set any cap to 0 to skip that source.
13
+
14
+ Output
15
+ ------
16
+ JSONL shards under --output-dir, one filename prefix per source:
17
+ sltrans-00000.jsonl, pes2o-00000.jsonl, the_stack-00000.jsonl, ...
18
+ Each record:
19
+ {"text": "...", "source": "...", "meta": {...}, "est_tokens": N}
20
+ Plus manifest.json summarising the run.
21
+
22
+ Usage
23
+ -----
24
+ pip install "datasets>=2.18" pyarrow pandas tqdm
25
+ huggingface-cli login # peS2o and the-stack are gated
26
+
27
+ python build_mixed_dataset.py
28
+ python build_mixed_dataset.py --sltrans-tokens 500e6 --owm-tokens 200e6
29
+ python build_mixed_dataset.py --stack-tokens 0 # skip TheStack
30
+ python build_mixed_dataset.py --stack-langs python,rust,go
31
+ """
32
+
33
+ from __future__ import annotations
34
+
35
+ import argparse
36
+ import json
37
+ import random
38
+ import re
39
+ import socket
40
+ import sys
41
+ import time
42
+ from concurrent.futures import ThreadPoolExecutor
43
+ from pathlib import Path
44
+
45
+ import pandas as pd
46
+ import pyarrow.parquet as pq
47
+ from tqdm import tqdm
48
+
49
+ socket.setdefaulttimeout(90)
50
+
51
+ # ── constants ──────────────────────────────────────────────────────────────────
52
+ SLTRANS_PROBE_ROWS = 200
53
+ SLTRANS_SKIP_DIRS = {".venv", "__pycache__", ".git"}
54
+
55
+ THE_STACK_LANGS = [
56
+ "python", "c", "cpp", "rust", "go",
57
+ "java", "javascript", "typescript",
58
+ ]
59
+
60
+ _TRANSIENT_ERRORS = ("ssl", "timeout", "handshake", "connection", "timed out")
61
+
62
+
63
+ # ── token estimation ───────────────────────────────────────────────────────────
64
+
65
+ def estimate_tokens(text: str) -> int:
66
+ return int(len(text.split()) * 1.5)
67
+
68
+
69
+ # ── JSONL shard writer ─────────────────────────────────────────────────────────
70
+
71
+ class ShardWriter:
72
+ def __init__(self, out_dir: Path, prefix: str, records_per_shard: int):
73
+ out_dir.mkdir(parents=True, exist_ok=True)
74
+ self._dir, self._pfx, self._rps = out_dir, prefix, records_per_shard
75
+ self._idx = self._n = 0
76
+ self._fh = None
77
+ self._roll()
78
+
79
+ def _roll(self):
80
+ if self._fh:
81
+ self._fh.close()
82
+ self._fh = (self._dir / f"{self._pfx}-{self._idx:05d}.jsonl").open("w", encoding="utf-8")
83
+ self._n = 0
84
+ self._idx += 1
85
+
86
+ def write(self, record: dict):
87
+ self._fh.write(json.dumps(record, ensure_ascii=False) + "\n")
88
+ self._n += 1
89
+ if self._n >= self._rps:
90
+ self._roll()
91
+
92
+ def close(self):
93
+ if self._fh:
94
+ self._fh.close()
95
+ self._fh = None
96
+
97
+
98
+ # ── SLTrans (local parquet) ────────────────────────────────────────────────────
99
+
100
+ def _sltrans_find_groups(root: Path) -> dict[tuple[str, str], list[Path]]:
101
+ """Return {(language, ir_type): [sorted shard paths]}."""
102
+ groups: dict[tuple[str, str], list[Path]] = {}
103
+ for d in sorted(root.iterdir()):
104
+ if not d.is_dir() or d.name in SLTRANS_SKIP_DIRS:
105
+ continue
106
+ for f in sorted(d.glob("*.parquet")):
107
+ m = re.match(r"^(Perf_Optimized|Size_Optimized)", f.name)
108
+ if m:
109
+ groups.setdefault((d.name, m.group(1)), []).append(f)
110
+ return groups
111
+
112
+
113
+ def _pq_nrows(files: list[Path]) -> int:
114
+ return sum(pq.ParquetFile(f).metadata.num_rows for f in files)
115
+
116
+
117
+ def _est_tok_df(src: pd.Series, ir: pd.Series) -> pd.Series:
118
+ src_w = src.fillna("").str.split().str.len().fillna(0)
119
+ ir_w = ir.fillna("").str.split().str.len().fillna(0)
120
+ return ((src_w + ir_w + 5) * 1.5).astype(int)
121
+
122
+
123
+ def _probe_avg_tokens(files: list[Path], n: int, rng: random.Random) -> float:
124
+ frames = []
125
+ seed = rng.randint(0, 2**31)
126
+ for f in files:
127
+ df = pq.ParquetFile(f).read_row_group(0).to_pandas()
128
+ if not df.empty:
129
+ frames.append(df.sample(min(n, len(df)), random_state=seed))
130
+ if sum(len(x) for x in frames) >= n:
131
+ break
132
+ if not frames:
133
+ return 0.0
134
+ p = pd.concat(frames, ignore_index=True).head(n)
135
+ p = p.dropna(subset=["Source_Code", "IR_Original"])
136
+ p = p[(p["Source_Code"] != "") & (p["IR_Original"] != "")]
137
+ return float(_est_tok_df(p["Source_Code"], p["IR_Original"]).mean()) if len(p) else 0.0
138
+
139
+
140
+ def _sltrans_allocate(
141
+ groups: dict[tuple[str, str], list[Path]],
142
+ total: int,
143
+ rng: random.Random,
144
+ ) -> dict[tuple[str, str], int]:
145
+ """Equal-share budget with deficit redistribution for small groups."""
146
+ keys = sorted(groups)
147
+ avail: dict[tuple[str, str], int] = {}
148
+ for k in tqdm(keys, desc=" probe", unit="grp", leave=False):
149
+ rows = _pq_nrows(groups[k])
150
+ avg = _probe_avg_tokens(groups[k], SLTRANS_PROBE_ROWS, rng)
151
+ avail[k] = int(rows * avg)
152
+ tqdm.write(
153
+ f" {k[0]:>15}/{k[1]:<16} ~{avail[k]:>14,} tok"
154
+ f" ({rows:,} rows, avg {avg:.0f})"
155
+ )
156
+ budgets = {k: total // len(keys) for k in keys}
157
+ for _ in range(len(keys)):
158
+ capped = {k: min(budgets[k], avail[k]) for k in keys}
159
+ deficit = sum(budgets[k] - capped[k] for k in keys)
160
+ if not deficit:
161
+ break
162
+ room = [k for k in keys if capped[k] < avail[k]]
163
+ if not room:
164
+ break
165
+ bonus = deficit // len(room)
166
+ for k in room:
167
+ capped[k] = min(capped[k] + bonus, avail[k])
168
+ budgets = capped
169
+ return budgets
170
+
171
+
172
+ def write_sltrans(
173
+ root: Path,
174
+ budget: int,
175
+ writer: ShardWriter,
176
+ rng: random.Random,
177
+ min_tokens: int,
178
+ ) -> int:
179
+ groups = _sltrans_find_groups(root)
180
+ if not groups:
181
+ print(f" WARNING: no SLTrans parquet files found in {root}", file=sys.stderr)
182
+ return 0
183
+
184
+ budgets = _sltrans_allocate(groups, budget, rng)
185
+ total_written = 0
186
+ bar = tqdm(total=budget, unit="tok", unit_scale=True,
187
+ desc=" write", dynamic_ncols=True)
188
+
189
+ for (lang, ir_type) in sorted(groups):
190
+ g_budget = budgets[(lang, ir_type)]
191
+ g_written = 0
192
+ files = list(groups[(lang, ir_type)])
193
+ rng.shuffle(files)
194
+
195
+ for f in files:
196
+ if g_written >= g_budget:
197
+ break
198
+ pf = pq.ParquetFile(f)
199
+ for gi in range(pf.num_row_groups):
200
+ if g_written >= g_budget:
201
+ break
202
+ df = pf.read_row_group(gi).to_pandas()
203
+ df = df.dropna(subset=["Source_Code", "IR_Original"])
204
+ df = df[(df["Source_Code"] != "") & (df["IR_Original"] != "")]
205
+ if df.empty:
206
+ continue
207
+ df = df.sample(frac=1, random_state=rng.randint(0, 2**31)).reset_index(drop=True)
208
+ df["_t"] = _est_tok_df(df["Source_Code"], df["IR_Original"])
209
+
210
+ remaining = g_budget - g_written
211
+ cutoff = max(int((df["_t"].cumsum() <= remaining).sum()), 1)
212
+ for row in df.iloc[:cutoff].to_dict("records"):
213
+ toks = int(row["_t"])
214
+ if toks < min_tokens:
215
+ continue
216
+ text = (
217
+ f"<source>\n{row['Source_Code']}\n</source>\n"
218
+ f"<llvm_ir>\n{row['IR_Original']}\n</llvm_ir>"
219
+ )
220
+ writer.write({
221
+ "text": text,
222
+ "source": "sltrans",
223
+ "meta": {"language": lang, "ir_type": ir_type},
224
+ "est_tokens": toks,
225
+ })
226
+ g_written += toks
227
+ total_written += toks
228
+ bar.update(min(toks, budget - bar.n))
229
+ bar.close()
230
+ return total_written
231
+
232
+
233
+ # ── HuggingFace streaming ──────────────────────────────────────────────────────
234
+
235
+ def _hf_open(
236
+ hf_path: str,
237
+ split: str = "train",
238
+ hf_config: str | None = None,
239
+ data_dir: str | None = None,
240
+ ):
241
+ """Open one HF streaming dataset with exponential-backoff retry."""
242
+ from datasets import load_dataset
243
+
244
+ kw: dict = {"split": split, "streaming": True}
245
+ if hf_config:
246
+ kw["name"] = hf_config
247
+ if data_dir:
248
+ kw["data_dir"] = data_dir
249
+
250
+ for attempt in range(5):
251
+ try:
252
+ return load_dataset(hf_path, **kw)
253
+ except ValueError as e:
254
+ if "Bad split" in str(e):
255
+ return None
256
+ raise
257
+ except Exception as e:
258
+ if attempt < 4 and any(k in str(e).lower() for k in _TRANSIENT_ERRORS):
259
+ time.sleep(2 ** attempt)
260
+ continue
261
+ raise
262
+ return None
263
+
264
+
265
+ def _hf_iter(
266
+ hf_path: str,
267
+ split: str = "train",
268
+ hf_config: str | None = None,
269
+ subsets: list[str] | None = None,
270
+ ):
271
+ """
272
+ Yield rows from a HuggingFace streaming dataset.
273
+ For TheStack, pass subsets; streams are resolved in parallel and interleaved.
274
+ """
275
+ if not subsets:
276
+ ds = _hf_open(hf_path, split=split, hf_config=hf_config)
277
+ if ds is not None:
278
+ yield from ds
279
+ return
280
+
281
+ # Resolve subset streams in parallel (each resolution is an HTTP round-trip).
282
+ def _open_sub(sub: str):
283
+ return _hf_open(hf_path, split=split, data_dir=f"data/{sub}")
284
+
285
+ with ThreadPoolExecutor(max_workers=min(4, len(subsets))) as pool:
286
+ streams = [s for s in pool.map(_open_sub, subsets) if s is not None]
287
+
288
+ if streams:
289
+ from datasets import interleave_datasets
290
+ yield from interleave_datasets(streams, stopping_strategy="all_exhausted")
291
+
292
+
293
+ def write_hf_source(
294
+ source_name: str,
295
+ budget: int,
296
+ writer: ShardWriter,
297
+ rng: random.Random,
298
+ min_tokens: int,
299
+ hf_path: str,
300
+ text_fn,
301
+ meta_fn,
302
+ hf_config: str | None = None,
303
+ split: str = "train",
304
+ subsets: list[str] | None = None,
305
+ ) -> int:
306
+ written = skipped = 0
307
+ bar = tqdm(total=budget, unit="tok", unit_scale=True,
308
+ desc=f" {source_name:<12}", dynamic_ncols=True, smoothing=0.05)
309
+ try:
310
+ for row in _hf_iter(hf_path, split=split, hf_config=hf_config, subsets=subsets):
311
+ text = text_fn(row)
312
+ if not text:
313
+ skipped += 1
314
+ continue
315
+ toks = estimate_tokens(text)
316
+ if toks < min_tokens:
317
+ skipped += 1
318
+ continue
319
+ writer.write({
320
+ "text": text,
321
+ "source": source_name,
322
+ "meta": meta_fn(row),
323
+ "est_tokens": toks,
324
+ })
325
+ written += toks
326
+ bar.update(min(toks, budget - bar.n))
327
+ if written >= budget:
328
+ break
329
+ finally:
330
+ bar.close()
331
+ print(f" done: {written:,} tokens written, {skipped:,} rows skipped")
332
+ return written
333
+
334
+
335
+ # ── text / meta extractors ─────────────────────────────────────────────────────
336
+
337
+ def _get(row: dict, *keys: str, default: str = "") -> str:
338
+ for k in keys:
339
+ v = row.get(k)
340
+ if v:
341
+ return str(v)
342
+ return default
343
+
344
+
345
+ def pes2o_text(row): return _get(row, "text", "content")
346
+ def pes2o_meta(row): return {"id": _get(row, "id", "doc_id"), "source": _get(row, "source", "venue")}
347
+
348
+ def stack_text(row): return _get(row, "content", "text", "code")
349
+ def stack_meta(row): return {
350
+ "lang": _get(row, "lang", "language"),
351
+ "repo": _get(row, "max_stars_repo_name", "repo_name"),
352
+ "license": _get(row, "license"),
353
+ }
354
+
355
+ def owm_text(row): return _get(row, "text")
356
+ def owm_meta(row): return {"url": _get(row, "url")}
357
+
358
+
359
+ # ── main ───────────────────────────────────────────────────────────────────────
360
+
361
+ def main() -> None:
362
+ ap = argparse.ArgumentParser(
363
+ description=__doc__,
364
+ formatter_class=argparse.RawDescriptionHelpFormatter,
365
+ )
366
+ ap.add_argument("--sltrans-root", default=".",
367
+ help="Root dir of downloaded SLTrans parquet files (default: .)")
368
+ ap.add_argument("--sltrans-tokens", type=float, default=700_000_000,
369
+ help="Token cap for SLTrans (default: 700M, 0=skip)")
370
+ ap.add_argument("--pes2o-tokens", type=float, default=150_000_000,
371
+ help="Token cap for peS2o (default: 150M, 0=skip)")
372
+ ap.add_argument("--stack-tokens", type=float, default=100_000_000,
373
+ help="Token cap for TheStack (default: 100M, 0=skip)")
374
+ ap.add_argument("--owm-tokens", type=float, default=50_000_000,
375
+ help="Token cap for OpenWebMath (default: 50M, 0=skip)")
376
+ ap.add_argument("--stack-langs", default=",".join(THE_STACK_LANGS),
377
+ help="Comma-separated TheStack language subsets")
378
+ ap.add_argument("--output-dir", default="./mixed_pretrain",
379
+ help="Output directory for JSONL shards (default: ./mixed_pretrain)")
380
+ ap.add_argument("--shard-size", type=int, default=50_000,
381
+ help="Records per JSONL shard (default: 50000)")
382
+ ap.add_argument("--min-tokens", type=int, default=32,
383
+ help="Drop records shorter than this (est. tokens, default: 32)")
384
+ ap.add_argument("--seed", type=int, default=42)
385
+ args = ap.parse_args()
386
+
387
+ rng = random.Random(args.seed)
388
+ out_dir = Path(args.output_dir)
389
+ stack_langs = [s.strip() for s in args.stack_langs.split(",") if s.strip()]
390
+
391
+ budgets = {
392
+ "sltrans": int(args.sltrans_tokens),
393
+ "pes2o": int(args.pes2o_tokens),
394
+ "the_stack": int(args.stack_tokens),
395
+ "openwebmath": int(args.owm_tokens),
396
+ }
397
+ active_sources = [name for name, tok in budgets.items() if tok > 0]
398
+ total_budget = sum(budgets.values())
399
+
400
+ print("=" * 64)
401
+ print("Mixed pre-training dataset builder")
402
+ print(f" Output : {out_dir.resolve()}")
403
+ print(f" Seed : {args.seed}")
404
+ print()
405
+ for name, toks in budgets.items():
406
+ if toks > 0:
407
+ print(f" {name:<14} {toks:>15,} tokens")
408
+ else:
409
+ print(f" {name:<14} (skipped)")
410
+ print(f" {'TOTAL':<14} {total_budget:>15,} tokens")
411
+ print("=" * 64)
412
+
413
+ summary: dict[str, int] = {}
414
+ n_active = len(active_sources)
415
+ step = 1
416
+
417
+ # ── SLTrans ────────────────────────────────────────────────────────────────
418
+ if budgets["sltrans"] > 0:
419
+ print(f"\n[{step}/{n_active}] SLTrans (local parquet, balanced language x IR-type)")
420
+ step += 1
421
+ w = ShardWriter(out_dir, "sltrans", args.shard_size)
422
+ try:
423
+ summary["sltrans"] = write_sltrans(
424
+ Path(args.sltrans_root), budgets["sltrans"], w, rng, args.min_tokens,
425
+ )
426
+ finally:
427
+ w.close()
428
+
429
+ # ── peS2o ──────────────────────────────────────────────────────────────────
430
+ if budgets["pes2o"] > 0:
431
+ print(f"\n[{step}/{n_active}] peS2o (allenai/peS2o, config=v2)")
432
+ step += 1
433
+ w = ShardWriter(out_dir, "pes2o", args.shard_size)
434
+ try:
435
+ summary["pes2o"] = write_hf_source(
436
+ "pes2o", budgets["pes2o"], w, rng, args.min_tokens,
437
+ hf_path="allenai/peS2o",
438
+ text_fn=pes2o_text, meta_fn=pes2o_meta,
439
+ hf_config="v2",
440
+ )
441
+ finally:
442
+ w.close()
443
+
444
+ # ── TheStack ───────────────────────────────────────────────────────────────
445
+ if budgets["the_stack"] > 0:
446
+ print(f"\n[{step}/{n_active}] TheStack (bigcode/the-stack, {len(stack_langs)} language subsets)")
447
+ print(f" langs: {', '.join(stack_langs)}")
448
+ step += 1
449
+ w = ShardWriter(out_dir, "the_stack", args.shard_size)
450
+ try:
451
+ summary["the_stack"] = write_hf_source(
452
+ "the_stack", budgets["the_stack"], w, rng, args.min_tokens,
453
+ hf_path="bigcode/the-stack",
454
+ text_fn=stack_text, meta_fn=stack_meta,
455
+ subsets=stack_langs,
456
+ )
457
+ finally:
458
+ w.close()
459
+
460
+ # ── OpenWebMath ────────────────────────────────────────────────────────────
461
+ if budgets["openwebmath"] > 0:
462
+ print(f"\n[{step}/{n_active}] OpenWebMath (open-web-math/open-web-math)")
463
+ w = ShardWriter(out_dir, "openwebmath", args.shard_size)
464
+ try:
465
+ summary["openwebmath"] = write_hf_source(
466
+ "openwebmath", budgets["openwebmath"], w, rng, args.min_tokens,
467
+ hf_path="open-web-math/open-web-math",
468
+ text_fn=owm_text, meta_fn=owm_meta,
469
+ )
470
+ finally:
471
+ w.close()
472
+
473
+ # ── manifest ───────────────────────────────────────────────────────────────
474
+ manifest = {
475
+ "seed": args.seed,
476
+ "min_tokens_per_record": args.min_tokens,
477
+ "sources": {
478
+ "sltrans": {"root": args.sltrans_root, "target_tokens": budgets["sltrans"]},
479
+ "pes2o": {"hf_path": "allenai/peS2o", "target_tokens": budgets["pes2o"]},
480
+ "the_stack": {"hf_path": "bigcode/the-stack", "target_tokens": budgets["the_stack"], "langs": stack_langs},
481
+ "openwebmath": {"hf_path": "open-web-math/open-web-math", "target_tokens": budgets["openwebmath"]},
482
+ },
483
+ "tokens_written": summary,
484
+ }
485
+ (out_dir / "manifest.json").write_text(json.dumps(manifest, indent=2))
486
+
487
+ # ── summary ────────────────────────────────────────────────────────────────
488
+ grand = sum(summary.values())
489
+ print("\n" + "=" * 62)
490
+ print(f"{'Source':<14} {'Target':>15} {'Written':>15} {'Share':>6}")
491
+ print("-" * 58)
492
+ for name in ["sltrans", "pes2o", "the_stack", "openwebmath"]:
493
+ if budgets[name] == 0:
494
+ continue
495
+ written = summary.get(name, 0)
496
+ pct = 100 * written / grand if grand else 0
497
+ print(f"{name:<14} {budgets[name]:>15,} {written:>15,} {pct:>5.1f}%")
498
+ print("-" * 58)
499
+ print(f"{'TOTAL':<14} {total_budget:>15,} {grand:>15,} 100.0%")
500
+ print(f"\nOutput: {out_dir.resolve()}")
501
+
502
+
503
+ if __name__ == "__main__":
504
+ main()
build_pretrain_dataset.py ADDED
@@ -0,0 +1,456 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Build a mixed continued-pretraining dataset for a code LM.
3
+
4
+ Sources (streamed from the Hub — no full download):
5
+ - UKPLab/SLTrans (LLVM IR <-> source pairs; primary IRCoder signal)
6
+ - allenai/peS2o (open scientific text)
7
+ - bigcode/the-stack (permissively licensed source code)
8
+
9
+ Mixing target (token-weighted): 70 / 15 / 15.
10
+
11
+ Output: JSONL shards under OUT_DIR. Each line:
12
+ {"text": "...", "source": "sltrans" | "pes2o" | "the_stack", "meta": {...}}
13
+
14
+ The token budget is approximate — we use a fast whitespace token estimate by default
15
+ to avoid pulling a heavy tokenizer into the streaming loop. Swap in a real tokenizer
16
+ (see TOKENIZER section) if you want exact counts against your model's vocab.
17
+
18
+ Usage:
19
+ pip install "datasets>=2.18" huggingface_hub tqdm
20
+ huggingface-cli login # SLTrans + the-stack are gated; you must accept their terms
21
+ python build_pretrain_dataset.py
22
+ """
23
+
24
+ from __future__ import annotations
25
+
26
+ import json
27
+ import os
28
+ import random
29
+ import sys
30
+ import time
31
+ from concurrent.futures import ThreadPoolExecutor
32
+ from dataclasses import dataclass
33
+ from pathlib import Path
34
+ from typing import Callable, Iterator
35
+
36
+ import socket
37
+
38
+ from datasets import interleave_datasets, load_dataset
39
+ from tqdm import tqdm
40
+
41
+ # Install hf-transfer and set this env var for significantly faster shard downloads.
42
+ # pip install hf-transfer
43
+ os.environ.setdefault("HF_HUB_ENABLE_HF_TRANSFER", "1")
44
+ # Raise the per-shard download timeout (default 10s is too short for HF CDN under load).
45
+ os.environ.setdefault("HF_HUB_DOWNLOAD_TIMEOUT", "120")
46
+
47
+ # Apply a 90s socket-level timeout to every connection in this process.
48
+ # This covers HF Hub file-listing API calls (which have no timeout by default)
49
+ # and prevents indefinite hangs at 'resolving data files'.
50
+ socket.setdefaulttimeout(90)
51
+
52
+ # ============================================================================
53
+ # CONFIG
54
+ # ============================================================================
55
+
56
+ @dataclass
57
+ class SourceSpec:
58
+ name: str # short id used in output records
59
+ hf_path: str # HF dataset path
60
+ hf_config: str | None # config name, if any
61
+ split: str # split to stream
62
+ target_fraction: float # share of the total token budget
63
+ text_fn: Callable[[dict], str] # extracts the training text from a row
64
+ meta_fn: Callable[[dict], dict] # extracts a small metadata dict
65
+ # the-stack is organized by language subset; SLTrans by source language.
66
+ # If `subsets` is set, we round-robin over them, each loaded as a separate stream.
67
+ subsets: list[str] | None = None
68
+
69
+
70
+ # Total tokens in the final dataset (approximate).
71
+ TOTAL_TOKEN_BUDGET = 1_500_000_000
72
+
73
+ # Per-record length filters (in estimated tokens).
74
+ MIN_TOKENS_PER_RECORD = 32
75
+ MAX_TOKENS_PER_RECORD = 8192
76
+
77
+ # Output.
78
+ OUT_DIR = Path("./pretrain_mix")
79
+ SHARD_RECORDS = 50_000 # records per .jsonl shard
80
+ SEED = 17
81
+
82
+ # Reservoir / sampling. We don't reservoir-sample (would require knowing N);
83
+ # instead we accept records with probability `keep_prob` per source, tuned so
84
+ # the stream yields roughly the target token count before exhaustion. Set to
85
+ # 1.0 to take everything until budget is hit.
86
+ KEEP_PROB = {
87
+ "sltrans": 1.0,
88
+ "pes2o": 1.0,
89
+ "the_stack": 0.5, # the-stack is huge; subsample to diversify languages
90
+ }
91
+
92
+ # For the-stack, list languages you want represented. Keep this short for a
93
+ # focused replication; expand for broader code coverage.
94
+ THE_STACK_LANGS = [
95
+ "python", "c", "cpp", "rust", "go", "java", "javascript", "typescript",
96
+ ]
97
+
98
+ # SLTrans subsets (source languages whose IR we want). None => use default split.
99
+ SLTRANS_SUBSETS = [
100
+ f"{lang}/{split}"
101
+ for lang in ["C", "C++", "D", "Fortran", "Go", "Haskell", "Nim", "Objective-C", "Python", "Rust", "Swift"]
102
+ for split in ["Perf_Optimized", "Size_Optimized"]
103
+ ]
104
+
105
+ # ============================================================================
106
+ # TEXT / META EXTRACTORS
107
+ # ============================================================================
108
+ # These are intentionally defensive — different dataset versions name fields
109
+ # differently. Adjust if a `KeyError` shows up in your run.
110
+
111
+ def _first_present(row: dict, keys: list[str], default: str = "") -> str:
112
+ for k in keys:
113
+ if k in row and row[k]:
114
+ return row[k]
115
+ return default
116
+
117
+
118
+ def sltrans_text(row: dict) -> str:
119
+ """SLTrans pairs source code with its LLVM IR. Concatenate with a marker so
120
+ the model learns to associate them — IRCoder-style."""
121
+ src = _first_present(row, ["source", "code", "src", "input"])
122
+ ir = _first_present(row, ["ir", "llvm_ir", "llvm", "target", "output"])
123
+ if not src or not ir:
124
+ return ""
125
+ return f"<source>\n{src}\n</source>\n<llvm_ir>\n{ir}\n</llvm_ir>"
126
+
127
+
128
+ def sltrans_meta(row: dict) -> dict:
129
+ return {
130
+ "lang": _first_present(row, ["language", "lang", "source_lang"]),
131
+ }
132
+
133
+
134
+ def pes2o_text(row: dict) -> str:
135
+ return _first_present(row, ["text", "content"])
136
+
137
+
138
+ def pes2o_meta(row: dict) -> dict:
139
+ return {
140
+ "id": _first_present(row, ["id", "doc_id"]),
141
+ "source": _first_present(row, ["source", "venue"]),
142
+ }
143
+
144
+
145
+ def the_stack_text(row: dict) -> str:
146
+ return _first_present(row, ["content", "text", "code"])
147
+
148
+
149
+ def the_stack_meta(row: dict) -> dict:
150
+ return {
151
+ "lang": _first_present(row, ["lang", "language"]),
152
+ "repo": _first_present(row, ["max_stars_repo_name", "repo_name"]),
153
+ "license": _first_present(row, ["license"]),
154
+ }
155
+
156
+
157
+ # ============================================================================
158
+ # SOURCES
159
+ # ============================================================================
160
+
161
+ SOURCES: list[SourceSpec] = [
162
+ SourceSpec(
163
+ name="sltrans",
164
+ hf_path="UKPLab/SLTrans",
165
+ hf_config=None,
166
+ split="train",
167
+ target_fraction=0.70,
168
+ text_fn=sltrans_text,
169
+ meta_fn=sltrans_meta,
170
+ subsets=SLTRANS_SUBSETS,
171
+ ),
172
+ SourceSpec(
173
+ name="pes2o",
174
+ hf_path="allenai/peS2o",
175
+ hf_config="v2",
176
+ split="train",
177
+ target_fraction=0.15,
178
+ text_fn=pes2o_text,
179
+ meta_fn=pes2o_meta,
180
+ ),
181
+ SourceSpec(
182
+ name="the_stack",
183
+ hf_path="bigcode/the-stack",
184
+ hf_config=None,
185
+ # the-stack uses `data_dir` per language rather than HF configs.
186
+ split="train",
187
+ target_fraction=0.15,
188
+ text_fn=the_stack_text,
189
+ meta_fn=the_stack_meta,
190
+ subsets=THE_STACK_LANGS,
191
+ ),
192
+ ]
193
+
194
+
195
+ # ============================================================================
196
+ # TOKEN ESTIMATOR
197
+ # ============================================================================
198
+ # Whitespace-based estimate. For BPE tokenizers, real tokens ~= 1.3x words for
199
+ # natural language and ~1.5–2x for code. We bake a 1.5x correction in here so
200
+ # the budget is honest enough for planning. If you want exact counts:
201
+ #
202
+ # from transformers import AutoTokenizer
203
+ # tok = AutoTokenizer.from_pretrained("Qwen/Qwen2.5-Coder-3B")
204
+ # def estimate_tokens(text: str) -> int:
205
+ # return len(tok.encode(text, add_special_tokens=False))
206
+
207
+ def estimate_tokens(text: str) -> int:
208
+ return int(len(text.split()) * 1.5)
209
+
210
+
211
+ # ============================================================================
212
+ # STREAMING
213
+ # ============================================================================
214
+
215
+ def open_stream(spec: SourceSpec, subset: str | None):
216
+ """Return an IterableDataset for a (source, subset) pair, or None if unavailable."""
217
+ kwargs = {"split": spec.split, "streaming": True}
218
+ if spec.hf_config is not None:
219
+ kwargs["name"] = spec.hf_config
220
+
221
+ # the-stack uses data_dir to select a language.
222
+ if spec.hf_path == "bigcode/the-stack" and subset is not None:
223
+ kwargs["data_dir"] = f"data/{subset}"
224
+
225
+ # SLTrans subsets are encoded as "Lang/Split" (e.g. "Python/Perf_Optimized").
226
+ if spec.hf_path == "UKPLab/SLTrans" and subset is not None:
227
+ lang, slt_split = subset.rsplit("/", 1)
228
+ kwargs["name"] = lang
229
+ kwargs["split"] = slt_split
230
+
231
+ _TRANSIENT = ("ssl", "timeout", "handshake", "connection", "timed out")
232
+ for attempt in range(5):
233
+ try:
234
+ return load_dataset(spec.hf_path, **kwargs)
235
+ except ValueError as e:
236
+ if "Bad split" in str(e):
237
+ return None
238
+ raise
239
+ except Exception as e:
240
+ if attempt < 4 and any(k in str(e).lower() for k in _TRANSIENT):
241
+ time.sleep(2 ** attempt) # 1s, 2s, 4s, 8s
242
+ continue
243
+ raise
244
+ return None
245
+
246
+
247
+ def round_robin(spec: SourceSpec) -> Iterator[dict]:
248
+ """Yield rows from the source, interleaving across subsets if any.
249
+
250
+ Data-file resolution (the HF Hub HTTP round-trips that show as
251
+ 'resolving data files') is parallelised across subsets so all
252
+ metadata fetches happen concurrently instead of one-by-one.
253
+ """
254
+ if not spec.subsets:
255
+ ds = open_stream(spec, None)
256
+ if ds is not None:
257
+ yield from ds
258
+ return
259
+
260
+ # Resolve all subset streams in parallel — resolution is I/O-bound so
261
+ # threads eliminate most of the serial 'resolving data files' wait.
262
+ with ThreadPoolExecutor(max_workers=min(4, len(spec.subsets))) as pool:
263
+ results = list(pool.map(open_stream, [spec] * len(spec.subsets), spec.subsets))
264
+
265
+ datasets = [ds for ds in results if ds is not None]
266
+ if not datasets:
267
+ return
268
+
269
+ yield from interleave_datasets(datasets, stopping_strategy="all_exhausted")
270
+
271
+
272
+ # ============================================================================
273
+ # WRITER
274
+ # ============================================================================
275
+
276
+ class ShardWriter:
277
+ def __init__(self, out_dir: Path, prefix: str, records_per_shard: int):
278
+ self.out_dir = out_dir
279
+ self.prefix = prefix
280
+ self.records_per_shard = records_per_shard
281
+ self.out_dir.mkdir(parents=True, exist_ok=True)
282
+ self._shard_idx = 0
283
+ self._records_in_shard = 0
284
+ self._fh = None
285
+ self._open_new_shard()
286
+
287
+ def _open_new_shard(self) -> None:
288
+ if self._fh is not None:
289
+ self._fh.close()
290
+ path = self.out_dir / f"{self.prefix}-{self._shard_idx:05d}.jsonl"
291
+ self._fh = path.open("w", encoding="utf-8")
292
+ self._records_in_shard = 0
293
+ self._shard_idx += 1
294
+
295
+ def write(self, record: dict) -> None:
296
+ self._fh.write(json.dumps(record, ensure_ascii=False) + "\n")
297
+ self._records_in_shard += 1
298
+ if self._records_in_shard >= self.records_per_shard:
299
+ self._open_new_shard()
300
+
301
+ def close(self) -> None:
302
+ if self._fh is not None:
303
+ self._fh.close()
304
+ self._fh = None
305
+
306
+
307
+ # ============================================================================
308
+ # MAIN
309
+ # ============================================================================
310
+
311
+ def sample_source(spec: SourceSpec, target_tokens: int, writer: ShardWriter,
312
+ rng: random.Random) -> int:
313
+ """Stream `spec` until ~target_tokens have been written. Returns tokens written."""
314
+ keep_prob = KEEP_PROB.get(spec.name, 1.0)
315
+ tokens_written = 0
316
+ records_written = 0
317
+ rows_seen = 0
318
+ rows_skipped_filter = 0
319
+ rows_skipped_subsample = 0
320
+ rows_skipped_empty = 0
321
+ started = time.time()
322
+
323
+ # tqdm bar measured in tokens — the unit that actually matters for the budget.
324
+ # `unit_scale=True` formats large counts as 1.23M / 1.23B automatically.
325
+ bar = tqdm(
326
+ total=target_tokens,
327
+ unit="tok",
328
+ unit_scale=True,
329
+ desc=f"{spec.name:>10}",
330
+ dynamic_ncols=True,
331
+ smoothing=0.05,
332
+ )
333
+
334
+ def _refresh_postfix() -> None:
335
+ elapsed = max(time.time() - started, 1e-6)
336
+ bar.set_postfix({
337
+ "records": f"{records_written:,}",
338
+ "rows": f"{rows_seen:,}",
339
+ "tok/s": f"{tokens_written/elapsed:,.0f}",
340
+ "skip": f"{rows_skipped_filter+rows_skipped_subsample+rows_skipped_empty:,}",
341
+ }, refresh=False)
342
+
343
+ try:
344
+ for row in round_robin(spec):
345
+ rows_seen += 1
346
+
347
+ if keep_prob < 1.0 and rng.random() > keep_prob:
348
+ rows_skipped_subsample += 1
349
+ continue
350
+
351
+ try:
352
+ text = spec.text_fn(row)
353
+ except Exception as e:
354
+ if rows_seen <= 3:
355
+ bar.write(f"[{spec.name}] text_fn error on row {rows_seen}: {e!r}")
356
+ rows_skipped_empty += 1
357
+ continue
358
+
359
+ if not text:
360
+ rows_skipped_empty += 1
361
+ continue
362
+
363
+ n_tok = estimate_tokens(text)
364
+ if n_tok < MIN_TOKENS_PER_RECORD or n_tok > MAX_TOKENS_PER_RECORD:
365
+ rows_skipped_filter += 1
366
+ continue
367
+
368
+ record = {
369
+ "text": text,
370
+ "source": spec.name,
371
+ "meta": spec.meta_fn(row),
372
+ "est_tokens": n_tok,
373
+ }
374
+ writer.write(record)
375
+ tokens_written += n_tok
376
+ records_written += 1
377
+
378
+ # Don't overshoot the bar (tqdm clamps, but `min` keeps the math clean).
379
+ bar.update(min(n_tok, target_tokens - bar.n))
380
+
381
+ # Refresh the postfix every ~1k records — cheaper than every step.
382
+ if records_written % 1_000 == 0:
383
+ _refresh_postfix()
384
+
385
+ if tokens_written >= target_tokens:
386
+ break
387
+
388
+ _refresh_postfix()
389
+ finally:
390
+ bar.close()
391
+
392
+ elapsed = time.time() - started
393
+ print(f"[{spec.name}] DONE: {records_written:,} records, "
394
+ f"{tokens_written:,} tokens, {rows_seen:,} rows seen, "
395
+ f"skipped(filter={rows_skipped_filter:,} subsample={rows_skipped_subsample:,} "
396
+ f"empty={rows_skipped_empty:,}), {elapsed:.0f}s")
397
+ return tokens_written
398
+
399
+
400
+ def main() -> None:
401
+ rng = random.Random(SEED)
402
+ OUT_DIR.mkdir(parents=True, exist_ok=True)
403
+
404
+ # Sanity-check fractions sum to ~1.
405
+ total_frac = sum(s.target_fraction for s in SOURCES)
406
+ if abs(total_frac - 1.0) > 1e-3:
407
+ print(f"WARN: source fractions sum to {total_frac}, not 1.0", file=sys.stderr)
408
+
409
+ # Banner — reassures the user something is happening before HF streams open.
410
+ print("=" * 64)
411
+ print(f"Building mixed pretrain corpus → {OUT_DIR.resolve()}")
412
+ print(f"Total token budget: {TOTAL_TOKEN_BUDGET:,}")
413
+ print(f"Per-record range: {MIN_TOKENS_PER_RECORD}–{MAX_TOKENS_PER_RECORD} tokens")
414
+ for s in SOURCES:
415
+ target = int(TOTAL_TOKEN_BUDGET * s.target_fraction)
416
+ kp = KEEP_PROB.get(s.name, 1.0)
417
+ subs = f", subsets={s.subsets}" if s.subsets else ""
418
+ print(f" - {s.name:>10}: {s.target_fraction:>5.0%} → {target:>15,} tok "
419
+ f"[keep_prob={kp}{subs}]")
420
+ print("=" * 64)
421
+
422
+ summary = {}
423
+ for spec in SOURCES:
424
+ target = int(TOTAL_TOKEN_BUDGET * spec.target_fraction)
425
+ writer = ShardWriter(OUT_DIR, prefix=spec.name,
426
+ records_per_shard=SHARD_RECORDS)
427
+ try:
428
+ written = sample_source(spec, target, writer, rng)
429
+ finally:
430
+ writer.close()
431
+ summary[spec.name] = {"target": target, "written": written}
432
+
433
+ # Manifest.
434
+ manifest = {
435
+ "total_token_budget": TOTAL_TOKEN_BUDGET,
436
+ "seed": SEED,
437
+ "sources": [
438
+ {"name": s.name, "hf_path": s.hf_path,
439
+ "fraction": s.target_fraction, "subsets": s.subsets}
440
+ for s in SOURCES
441
+ ],
442
+ "tokens_written": summary,
443
+ }
444
+ (OUT_DIR / "manifest.json").write_text(json.dumps(manifest, indent=2))
445
+
446
+ print("\n=== SUMMARY ===")
447
+ grand_total = sum(v["written"] for v in summary.values())
448
+ for name, v in summary.items():
449
+ pct = 100 * v["written"] / grand_total if grand_total else 0
450
+ print(f" {name:>10}: {v['written']:>15,} tokens ({pct:5.1f}%)")
451
+ print(f" {'TOTAL':>10}: {grand_total:>15,} tokens")
452
+ print(f"\nOutput: {OUT_DIR.resolve()}")
453
+
454
+
455
+ if __name__ == "__main__":
456
+ main()
sltrans_subset_1500M.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d896c84650b6dd23943264c919d898f215eb147c264df4c9ad2d1e28f715817d
3
+ size 2230258908
sltrans_subset_500M.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:dfac595fae04a9f8faf34f66d4ac1c555203259aab3e2717a7d3e5f49f47c368
3
+ size 737917857
sltrans_subset_700M.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b44b696df0b58b07f6b88192da9aa022d16edaf21aefa45eaaabddb88e269a77
3
+ size 1021734608