st-taro commited on
Commit
5b7e9c7
·
0 Parent(s):

Duplicate from st-taro/csen346_temp

Browse files
.gitattributes ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.lz4 filter=lfs diff=lfs merge=lfs -text
12
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
13
+ *.model filter=lfs diff=lfs merge=lfs -text
14
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
15
+ *.npy filter=lfs diff=lfs merge=lfs -text
16
+ *.npz filter=lfs diff=lfs merge=lfs -text
17
+ *.onnx filter=lfs diff=lfs merge=lfs -text
18
+ *.ot filter=lfs diff=lfs merge=lfs -text
19
+ *.parquet filter=lfs diff=lfs merge=lfs -text
20
+ *.pb filter=lfs diff=lfs merge=lfs -text
21
+ *.pickle filter=lfs diff=lfs merge=lfs -text
22
+ *.pkl filter=lfs diff=lfs merge=lfs -text
23
+ *.pt filter=lfs diff=lfs merge=lfs -text
24
+ *.pth filter=lfs diff=lfs merge=lfs -text
25
+ *.rar filter=lfs diff=lfs merge=lfs -text
26
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
27
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
28
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
29
+ *.tar filter=lfs diff=lfs merge=lfs -text
30
+ *.tflite filter=lfs diff=lfs merge=lfs -text
31
+ *.tgz filter=lfs diff=lfs merge=lfs -text
32
+ *.wasm filter=lfs diff=lfs merge=lfs -text
33
+ *.xz filter=lfs diff=lfs merge=lfs -text
34
+ *.zip filter=lfs diff=lfs merge=lfs -text
35
+ *.zst filter=lfs diff=lfs merge=lfs -text
36
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
37
+ # Audio files - uncompressed
38
+ *.pcm filter=lfs diff=lfs merge=lfs -text
39
+ *.sam filter=lfs diff=lfs merge=lfs -text
40
+ *.raw filter=lfs diff=lfs merge=lfs -text
41
+ # Audio files - compressed
42
+ *.aac filter=lfs diff=lfs merge=lfs -text
43
+ *.flac filter=lfs diff=lfs merge=lfs -text
44
+ *.mp3 filter=lfs diff=lfs merge=lfs -text
45
+ *.ogg filter=lfs diff=lfs merge=lfs -text
46
+ *.wav filter=lfs diff=lfs merge=lfs -text
47
+ # Image files - uncompressed
48
+ *.bmp filter=lfs diff=lfs merge=lfs -text
49
+ *.gif filter=lfs diff=lfs merge=lfs -text
50
+ *.png filter=lfs diff=lfs merge=lfs -text
51
+ *.tiff filter=lfs diff=lfs merge=lfs -text
52
+ # Image files - compressed
53
+ *.jpg filter=lfs diff=lfs merge=lfs -text
54
+ *.jpeg filter=lfs diff=lfs merge=lfs -text
55
+ *.webp filter=lfs diff=lfs merge=lfs -text
56
+ mixed_pretrain/* filter=lfs diff=lfs merge=lfs -text
57
+ *.jsonl filter=lfs diff=lfs merge=lfs -text
README.md ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ A mixture of datasets focused on Source/Intermediate Representation training for multilingual code generation.
3
+ For SCU CSEN346.
4
+
5
+
6
+ **Usage**:
7
+ Pass to continued_pretrain.py with
8
+ ```
9
+ --dataset_name './tokenized_dataset'
10
+ ```
11
+
12
+
13
+ Sources:
14
+ UKPLab/SLTrans
15
+ bigcode/the-stack
16
+ allenai/peS2o
17
+ open-web-math/open-web-math
build_ir_dataset.py ADDED
@@ -0,0 +1,202 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Transform the mixed_pretrain JSONL shards into a unified parquet dataset
4
+ where every record has a source_code column and an llvm_ir column.
5
+
6
+ SLTrans records already contain both — the <source> / <llvm_ir> tags are
7
+ parsed out into separate columns. Records from other sources (peS2o,
8
+ TheStack, OpenWebMath) have their text placed in source_code and llvm_ir
9
+ set to null, keeping the schema consistent.
10
+
11
+ Output schema
12
+ -------------
13
+ source_code string source code or prose text
14
+ llvm_ir string LLVM IR (null for non-SLTrans records)
15
+ language string programming language or content category
16
+ ir_type string Perf_Optimized / Size_Optimized (null if not SLTrans)
17
+ source_dataset string sltrans | pes2o | the_stack | openwebmath
18
+ est_tokens int64 whitespace token estimate
19
+
20
+ Usage
21
+ -----
22
+ python build_ir_dataset.py
23
+ python build_ir_dataset.py --input mixed_pretrain --output ir_dataset.parquet
24
+ """
25
+
26
+ from __future__ import annotations
27
+
28
+ import argparse
29
+ import json
30
+ import re
31
+ import sys
32
+ from pathlib import Path
33
+
34
+ import pandas as pd
35
+ import pyarrow as pa
36
+ import pyarrow.parquet as pq
37
+ from tqdm import tqdm
38
+
39
+ # ── SLTrans text parsing ───────────────────────────────────────────────────────
40
+ # Matches the format written by build_mixed_dataset.py:
41
+ # <source>\n{code}\n</source>\n<llvm_ir>\n{ir}\n</llvm_ir>
42
+ _SOURCE_PAT = re.compile(r"<source>\n(.*?)\n</source>", re.DOTALL)
43
+ _IR_PAT = re.compile(r"<llvm_ir>\n(.*?)\n</llvm_ir>", re.DOTALL)
44
+
45
+
46
+ def parse_sltrans(text: str) -> tuple[str, str]:
47
+ src = _SOURCE_PAT.search(text)
48
+ ir = _IR_PAT.search(text)
49
+ return (src.group(1) if src else ""), (ir.group(1) if ir else "")
50
+
51
+
52
+ # ── language normalisation ─────────────────────────────────────────────────────
53
+ # Maps non-SLTrans sources to a human-readable language/category label.
54
+ def _language(source: str, meta: dict) -> str:
55
+ if source == "the_stack":
56
+ return meta.get("lang") or meta.get("language") or "code"
57
+ if source == "pes2o":
58
+ return "scientific"
59
+ if source == "openwebmath":
60
+ return "math"
61
+ return ""
62
+
63
+
64
+ # ── record transformer ─────────────────────────────────────────────────────────
65
+ def transform(rec: dict) -> dict:
66
+ source = rec["source"]
67
+ text = rec.get("text", "")
68
+ meta = rec.get("meta", {})
69
+
70
+ if source == "sltrans":
71
+ source_code, llvm_ir = parse_sltrans(text)
72
+ language = meta.get("language", "")
73
+ ir_type = meta.get("ir_type", None)
74
+ elif source == "stack_llvm":
75
+ # Unpaired IR from TheStack: the text IS the IR, no corresponding source
76
+ source_code = None
77
+ llvm_ir = text
78
+ language = "LLVM"
79
+ ir_type = None
80
+ else:
81
+ source_code = text
82
+ llvm_ir = None
83
+ language = _language(source, meta)
84
+ ir_type = None
85
+
86
+ return {
87
+ "source_code": source_code,
88
+ "llvm_ir": llvm_ir,
89
+ "language": language,
90
+ "ir_type": ir_type,
91
+ "source_dataset": source,
92
+ "est_tokens": rec.get("est_tokens", 0),
93
+ }
94
+
95
+
96
+ # ── parquet schema ─────────────────────────────────────────────────────────────
97
+ SCHEMA = pa.schema([
98
+ pa.field("source_code", pa.large_utf8()),
99
+ pa.field("llvm_ir", pa.large_utf8()),
100
+ pa.field("language", pa.large_utf8()),
101
+ pa.field("ir_type", pa.large_utf8()),
102
+ pa.field("source_dataset", pa.large_utf8()),
103
+ pa.field("est_tokens", pa.int64()),
104
+ ])
105
+
106
+
107
+ def main() -> None:
108
+ ap = argparse.ArgumentParser(
109
+ description=__doc__,
110
+ formatter_class=argparse.RawDescriptionHelpFormatter,
111
+ )
112
+ ap.add_argument("--input", default="mixed_pretrain",
113
+ help="Directory containing JSONL shards (default: mixed_pretrain)")
114
+ ap.add_argument("--output", default="ir_dataset.parquet",
115
+ help="Output parquet path (default: ir_dataset.parquet)")
116
+ ap.add_argument("--batch-size", type=int, default=10_000,
117
+ help="Records per parquet row group (default: 10000)")
118
+ args = ap.parse_args()
119
+
120
+ data_dir = Path(args.input)
121
+ if not data_dir.is_dir():
122
+ print(f"ERROR: input directory not found: {data_dir}", file=sys.stderr)
123
+ sys.exit(1)
124
+
125
+ shards = sorted(data_dir.glob("*.jsonl"))
126
+ if not shards:
127
+ print(f"No JSONL files found in {data_dir}", file=sys.stderr)
128
+ sys.exit(1)
129
+
130
+ out_path = Path(args.output)
131
+ print(f"Input : {data_dir.resolve()} ({len(shards)} shards)")
132
+ print(f"Output : {out_path.resolve()}")
133
+ print(f"Schema : {[f.name for f in SCHEMA]}")
134
+ print()
135
+
136
+ writer = pq.ParquetWriter(out_path, SCHEMA)
137
+ batch: list[dict] = []
138
+ total = sltrans_ok = sltrans_partial = 0
139
+
140
+ def flush(rows: list[dict]) -> None:
141
+ df = pd.DataFrame(rows)
142
+ # Ensure all columns present even if batch is from a single source
143
+ for col in [f.name for f in SCHEMA]:
144
+ if col not in df.columns:
145
+ df[col] = None
146
+ df["est_tokens"] = df["est_tokens"].fillna(0).astype("int64")
147
+ table = pa.Table.from_pandas(df[[ f.name for f in SCHEMA ]], schema=SCHEMA)
148
+ writer.write_table(table)
149
+
150
+ for shard in tqdm(shards, desc="shards", unit="file"):
151
+ with shard.open(encoding="utf-8") as f:
152
+ for line in f:
153
+ line = line.strip()
154
+ if not line:
155
+ continue
156
+ rec = json.loads(line)
157
+ row = transform(rec)
158
+
159
+ if rec["source"] == "sltrans":
160
+ if row["source_code"] and row["llvm_ir"]:
161
+ sltrans_ok += 1
162
+ else:
163
+ sltrans_partial += 1
164
+
165
+ batch.append(row)
166
+ total += 1
167
+
168
+ if len(batch) >= args.batch_size:
169
+ flush(batch)
170
+ batch.clear()
171
+
172
+ if batch:
173
+ flush(batch)
174
+
175
+ writer.close()
176
+
177
+ # ── summary ────────────────────────────────────────────────────────────────
178
+ pf = pq.ParquetFile(out_path)
179
+ print()
180
+ print("=" * 60)
181
+ print("BUILD COMPLETE")
182
+ print("=" * 60)
183
+ print(f"Total records written : {total:,}")
184
+ print(f"SLTrans (both fields) : {sltrans_ok:,}")
185
+ if sltrans_partial:
186
+ print(f"SLTrans (parse miss) : {sltrans_partial:,} <- check text format")
187
+ print()
188
+ print("Output schema:")
189
+ print(pf.schema_arrow)
190
+ print()
191
+
192
+ # Quick per-source count from the written file
193
+ df = pf.read(columns=["source_dataset"]).to_pandas()
194
+ print("Records per source_dataset:")
195
+ for src, cnt in df["source_dataset"].value_counts().items():
196
+ print(f" {src:<14} {cnt:>10,}")
197
+ print()
198
+ print(f"Output: {out_path.resolve()}")
199
+
200
+
201
+ if __name__ == "__main__":
202
+ main()
build_mixed_dataset.py ADDED
@@ -0,0 +1,517 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ build_mixed_dataset.py — Five-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 (code) bigcode/the-stack, non-LLVM languages --stack-tokens
10
+ TheStack (LLVM) bigcode/the-stack, lang=llvm (unpaired IR) --stack-llvm-tokens
11
+ OpenWebMath open-web-math/open-web-math (math web text) --owm-tokens
12
+
13
+ Set any cap to 0 to skip that source.
14
+ TheStack code and LLVM IR are streamed from the same HF dataset but kept
15
+ as separate shards (the_stack-*.jsonl vs stack_llvm-*.jsonl) so downstream
16
+ pipelines can weight them independently.
17
+
18
+ Output
19
+ ------
20
+ JSONL shards under --output-dir, one filename prefix per source:
21
+ sltrans-00000.jsonl, pes2o-00000.jsonl, the_stack-00000.jsonl, ...
22
+ Each record:
23
+ {"text": "...", "source": "...", "meta": {...}, "est_tokens": N}
24
+ Plus manifest.json summarising the run.
25
+
26
+ Usage
27
+ -----
28
+ pip install "datasets>=2.18" pyarrow pandas tqdm
29
+ huggingface-cli login # peS2o and the-stack are gated
30
+
31
+ python build_mixed_dataset.py
32
+ python build_mixed_dataset.py --sltrans-tokens 500e6 --owm-tokens 200e6
33
+ python build_mixed_dataset.py --stack-tokens 0 # skip code
34
+ python build_mixed_dataset.py --stack-langs python,rust,go
35
+ python build_mixed_dataset.py --stack-llvm-tokens 100e6 # 100M unpaired IR
36
+ """
37
+
38
+ from __future__ import annotations
39
+
40
+ import argparse
41
+ import json
42
+ import random
43
+ import re
44
+ import socket
45
+ import sys
46
+ import time
47
+ from pathlib import Path
48
+
49
+ import pandas as pd
50
+ import pyarrow.parquet as pq
51
+ from tqdm import tqdm
52
+
53
+ socket.setdefaulttimeout(90)
54
+
55
+ # ── constants ──────────────────────────────────────────────────────────────────
56
+ SLTRANS_PROBE_ROWS = 200
57
+ SLTRANS_SKIP_DIRS = {".venv", "__pycache__", ".git"}
58
+
59
+ THE_STACK_LANGS = [
60
+ "python", "c", "c++", "rust", "go",
61
+ "java", "javascript", "typescript",
62
+ ]
63
+
64
+ _TRANSIENT_ERRORS = ("ssl", "timeout", "handshake", "connection", "timed out")
65
+
66
+
67
+ # ── token estimation ───────────────────────────────────────────────────────────
68
+
69
+ def estimate_tokens(text: str) -> int:
70
+ return int(len(text.split()) * 1.5)
71
+
72
+
73
+ # ── JSONL shard writer ─────────────────────────────────────────────────────────
74
+
75
+ class ShardWriter:
76
+ def __init__(self, out_dir: Path, prefix: str, records_per_shard: int):
77
+ out_dir.mkdir(parents=True, exist_ok=True)
78
+ self._dir, self._pfx, self._rps = out_dir, prefix, records_per_shard
79
+ self._idx = self._n = 0
80
+ self._fh = None
81
+ self._roll()
82
+
83
+ def _roll(self):
84
+ if self._fh:
85
+ self._fh.close()
86
+ self._fh = (self._dir / f"{self._pfx}-{self._idx:05d}.jsonl").open("w", encoding="utf-8")
87
+ self._n = 0
88
+ self._idx += 1
89
+
90
+ def write(self, record: dict):
91
+ self._fh.write(json.dumps(record, ensure_ascii=False) + "\n")
92
+ self._n += 1
93
+ if self._n >= self._rps:
94
+ self._roll()
95
+
96
+ def close(self):
97
+ if self._fh:
98
+ self._fh.close()
99
+ self._fh = None
100
+
101
+
102
+ # ── SLTrans (local parquet) ────────────────────────────────────────────────────
103
+
104
+ def _sltrans_find_groups(root: Path) -> dict[tuple[str, str], list[Path]]:
105
+ """Return {(language, ir_type): [sorted shard paths]}."""
106
+ groups: dict[tuple[str, str], list[Path]] = {}
107
+ for d in sorted(root.iterdir()):
108
+ if not d.is_dir() or d.name in SLTRANS_SKIP_DIRS:
109
+ continue
110
+ for f in sorted(d.glob("*.parquet")):
111
+ m = re.match(r"^(Perf_Optimized|Size_Optimized)", f.name)
112
+ if m:
113
+ groups.setdefault((d.name, m.group(1)), []).append(f)
114
+ return groups
115
+
116
+
117
+ def _pq_nrows(files: list[Path]) -> int:
118
+ return sum(pq.ParquetFile(f).metadata.num_rows for f in files)
119
+
120
+
121
+ def _est_tok_df(src: pd.Series, ir: pd.Series) -> pd.Series:
122
+ src_w = src.fillna("").str.split().str.len().fillna(0)
123
+ ir_w = ir.fillna("").str.split().str.len().fillna(0)
124
+ return ((src_w + ir_w + 5) * 1.5).astype(int)
125
+
126
+
127
+ def _probe_avg_tokens(files: list[Path], n: int, rng: random.Random) -> float:
128
+ frames = []
129
+ seed = rng.randint(0, 2**31)
130
+ for f in files:
131
+ df = pq.ParquetFile(f).read_row_group(0).to_pandas()
132
+ if not df.empty:
133
+ frames.append(df.sample(min(n, len(df)), random_state=seed))
134
+ if sum(len(x) for x in frames) >= n:
135
+ break
136
+ if not frames:
137
+ return 0.0
138
+ p = pd.concat(frames, ignore_index=True).head(n)
139
+ p = p.dropna(subset=["Source_Code", "IR_Original"])
140
+ p = p[(p["Source_Code"] != "") & (p["IR_Original"] != "")]
141
+ return float(_est_tok_df(p["Source_Code"], p["IR_Original"]).mean()) if len(p) else 0.0
142
+
143
+
144
+ def _sltrans_allocate(
145
+ groups: dict[tuple[str, str], list[Path]],
146
+ total: int,
147
+ rng: random.Random,
148
+ ) -> dict[tuple[str, str], int]:
149
+ """Equal-share budget with deficit redistribution for small groups."""
150
+ keys = sorted(groups)
151
+ avail: dict[tuple[str, str], int] = {}
152
+ for k in tqdm(keys, desc=" probe", unit="grp", leave=False):
153
+ rows = _pq_nrows(groups[k])
154
+ avg = _probe_avg_tokens(groups[k], SLTRANS_PROBE_ROWS, rng)
155
+ avail[k] = int(rows * avg)
156
+ tqdm.write(
157
+ f" {k[0]:>15}/{k[1]:<16} ~{avail[k]:>14,} tok"
158
+ f" ({rows:,} rows, avg {avg:.0f})"
159
+ )
160
+ budgets = {k: total // len(keys) for k in keys}
161
+ for _ in range(len(keys)):
162
+ capped = {k: min(budgets[k], avail[k]) for k in keys}
163
+ deficit = sum(budgets[k] - capped[k] for k in keys)
164
+ if not deficit:
165
+ break
166
+ room = [k for k in keys if capped[k] < avail[k]]
167
+ if not room:
168
+ break
169
+ bonus = deficit // len(room)
170
+ for k in room:
171
+ capped[k] = min(capped[k] + bonus, avail[k])
172
+ budgets = capped
173
+ return budgets
174
+
175
+
176
+ def write_sltrans(
177
+ root: Path,
178
+ budget: int,
179
+ writer: ShardWriter,
180
+ rng: random.Random,
181
+ min_tokens: int,
182
+ ) -> int:
183
+ groups = _sltrans_find_groups(root)
184
+ if not groups:
185
+ print(f" WARNING: no SLTrans parquet files found in {root}", file=sys.stderr)
186
+ return 0
187
+
188
+ budgets = _sltrans_allocate(groups, budget, rng)
189
+ total_written = 0
190
+ bar = tqdm(total=budget, unit="tok", unit_scale=True,
191
+ desc=" write", dynamic_ncols=True)
192
+
193
+ for (lang, ir_type) in sorted(groups):
194
+ g_budget = budgets[(lang, ir_type)]
195
+ g_written = 0
196
+ files = list(groups[(lang, ir_type)])
197
+ rng.shuffle(files)
198
+
199
+ for f in files:
200
+ if g_written >= g_budget:
201
+ break
202
+ pf = pq.ParquetFile(f)
203
+ for gi in range(pf.num_row_groups):
204
+ if g_written >= g_budget:
205
+ break
206
+ df = pf.read_row_group(gi).to_pandas()
207
+ df = df.dropna(subset=["Source_Code", "IR_Original"])
208
+ df = df[(df["Source_Code"] != "") & (df["IR_Original"] != "")]
209
+ if df.empty:
210
+ continue
211
+ df = df.sample(frac=1, random_state=rng.randint(0, 2**31)).reset_index(drop=True)
212
+ df["_t"] = _est_tok_df(df["Source_Code"], df["IR_Original"])
213
+
214
+ remaining = g_budget - g_written
215
+ cutoff = max(int((df["_t"].cumsum() <= remaining).sum()), 1)
216
+ for row in df.iloc[:cutoff].to_dict("records"):
217
+ toks = int(row["_t"])
218
+ if toks < min_tokens:
219
+ continue
220
+ text = (
221
+ f"<source>\n{row['Source_Code']}\n</source>\n"
222
+ f"<llvm_ir>\n{row['IR_Original']}\n</llvm_ir>"
223
+ )
224
+ writer.write({
225
+ "text": text,
226
+ "source": "sltrans",
227
+ "meta": {"language": lang, "ir_type": ir_type},
228
+ "est_tokens": toks,
229
+ })
230
+ g_written += toks
231
+ total_written += toks
232
+ bar.update(min(toks, budget - bar.n))
233
+ bar.close()
234
+ return total_written
235
+
236
+
237
+ # ── HuggingFace streaming ──────────────────────────────────────────────────────
238
+
239
+ def _hf_open(
240
+ hf_path: str,
241
+ split: str = "train",
242
+ hf_config: str | None = None,
243
+ data_dir: str | None = None,
244
+ ):
245
+ """Open one HF streaming dataset with exponential-backoff retry."""
246
+ from datasets import load_dataset
247
+
248
+ kw: dict = {"split": split, "streaming": True, "trust_remote_code": True}
249
+ if hf_config:
250
+ kw["name"] = hf_config
251
+ if data_dir:
252
+ kw["data_dir"] = data_dir
253
+
254
+ for attempt in range(5):
255
+ try:
256
+ return load_dataset(hf_path, **kw)
257
+ except ValueError as e:
258
+ if "Bad split" in str(e):
259
+ return None
260
+ raise
261
+ except Exception as e:
262
+ if attempt < 4 and any(k in str(e).lower() for k in _TRANSIENT_ERRORS):
263
+ time.sleep(2 ** attempt)
264
+ continue
265
+ raise
266
+ return None
267
+
268
+
269
+ def _hf_iter(
270
+ hf_path: str,
271
+ split: str = "train",
272
+ hf_config: str | None = None,
273
+ ):
274
+ """Yield rows from a HuggingFace streaming dataset."""
275
+ ds = _hf_open(hf_path, split=split, hf_config=hf_config)
276
+ if ds is not None:
277
+ yield from ds
278
+
279
+
280
+ def write_hf_source(
281
+ source_name: str,
282
+ budget: int,
283
+ writer: ShardWriter,
284
+ rng: random.Random,
285
+ min_tokens: int,
286
+ hf_path: str,
287
+ text_fn,
288
+ meta_fn,
289
+ hf_config: str | None = None,
290
+ split: str = "train",
291
+ lang_filter: set[str] | None = None,
292
+ ) -> int:
293
+ written = skipped = 0
294
+ bar = tqdm(total=budget, unit="tok", unit_scale=True,
295
+ desc=f" {source_name:<12}", dynamic_ncols=True, smoothing=0.05)
296
+ try:
297
+ for row in _hf_iter(hf_path, split=split, hf_config=hf_config):
298
+ if lang_filter is not None:
299
+ lang = (row.get("lang") or row.get("language") or "").lower()
300
+ if lang not in lang_filter:
301
+ skipped += 1
302
+ continue
303
+ text = text_fn(row)
304
+ if not text:
305
+ skipped += 1
306
+ continue
307
+ toks = estimate_tokens(text)
308
+ if toks < min_tokens:
309
+ skipped += 1
310
+ continue
311
+ writer.write({
312
+ "text": text,
313
+ "source": source_name,
314
+ "meta": meta_fn(row),
315
+ "est_tokens": toks,
316
+ })
317
+ written += toks
318
+ bar.update(min(toks, budget - bar.n))
319
+ if written >= budget:
320
+ break
321
+ finally:
322
+ bar.close()
323
+ print(f" done: {written:,} tokens written, {skipped:,} rows skipped")
324
+ return written
325
+
326
+
327
+ # ── text / meta extractors ─────────────────────────────────────────────────────
328
+
329
+ def _get(row: dict, *keys: str, default: str = "") -> str:
330
+ for k in keys:
331
+ v = row.get(k)
332
+ if v:
333
+ return str(v)
334
+ return default
335
+
336
+
337
+ def pes2o_text(row): return _get(row, "text", "content")
338
+ def pes2o_meta(row): return {"id": _get(row, "id", "doc_id"), "source": _get(row, "source", "venue")}
339
+
340
+ def stack_text(row): return _get(row, "content", "text", "code")
341
+ def stack_meta(row): return {
342
+ "lang": _get(row, "lang", "language"),
343
+ "repo": _get(row, "max_stars_repo_name", "repo_name"),
344
+ "license": _get(row, "license"),
345
+ }
346
+
347
+ def owm_text(row): return _get(row, "text")
348
+ def owm_meta(row): return {"url": _get(row, "url")}
349
+
350
+
351
+ # ── main ───────────────────────────────────────────────────────────────────────
352
+
353
+ def main() -> None:
354
+ ap = argparse.ArgumentParser(
355
+ description=__doc__,
356
+ formatter_class=argparse.RawDescriptionHelpFormatter,
357
+ )
358
+ ap.add_argument("--sltrans-root", default=".",
359
+ help="Root dir of downloaded SLTrans parquet files (default: .)")
360
+ ap.add_argument("--sltrans-tokens", type=float, default=700_000_000,
361
+ help="Token cap for SLTrans (default: 700M, 0=skip)")
362
+ ap.add_argument("--pes2o-tokens", type=float, default=150_000_000,
363
+ help="Token cap for peS2o (default: 150M, 0=skip)")
364
+ ap.add_argument("--stack-tokens", type=float, default=100_000_000,
365
+ help="Token cap for TheStack source code (default: 100M, 0=skip)")
366
+ ap.add_argument("--stack-llvm-tokens", type=float, default=0,
367
+ help="Token cap for TheStack unpaired LLVM IR (default: 0=skip)")
368
+ ap.add_argument("--owm-tokens", type=float, default=50_000_000,
369
+ help="Token cap for OpenWebMath (default: 50M, 0=skip)")
370
+ ap.add_argument("--stack-langs", default=",".join(THE_STACK_LANGS),
371
+ help="Comma-separated TheStack source-code language subsets (never includes llvm)")
372
+ ap.add_argument("--output-dir", default="./mixed_pretrain",
373
+ help="Output directory for JSONL shards (default: ./mixed_pretrain)")
374
+ ap.add_argument("--shard-size", type=int, default=50_000,
375
+ help="Records per JSONL shard (default: 50000)")
376
+ ap.add_argument("--min-tokens", type=int, default=32,
377
+ help="Drop records shorter than this (est. tokens, default: 32)")
378
+ ap.add_argument("--seed", type=int, default=42)
379
+ args = ap.parse_args()
380
+
381
+ rng = random.Random(args.seed)
382
+ out_dir = Path(args.output_dir)
383
+ # Ensure "llvm" never leaks into the source-code filter.
384
+ stack_langs = [s.strip() for s in args.stack_langs.split(",")
385
+ if s.strip() and s.strip().lower() != "llvm"]
386
+
387
+ budgets = {
388
+ "sltrans": int(args.sltrans_tokens),
389
+ "pes2o": int(args.pes2o_tokens),
390
+ "the_stack": int(args.stack_tokens),
391
+ "stack_llvm": int(args.stack_llvm_tokens),
392
+ "openwebmath": int(args.owm_tokens),
393
+ }
394
+ active_sources = [name for name, tok in budgets.items() if tok > 0]
395
+ total_budget = sum(budgets.values())
396
+
397
+ print("=" * 64)
398
+ print("Mixed pre-training dataset builder")
399
+ print(f" Output : {out_dir.resolve()}")
400
+ print(f" Seed : {args.seed}")
401
+ print()
402
+ for name, toks in budgets.items():
403
+ if toks > 0:
404
+ print(f" {name:<14} {toks:>15,} tokens")
405
+ else:
406
+ print(f" {name:<14} (skipped)")
407
+ print(f" {'TOTAL':<14} {total_budget:>15,} tokens")
408
+ print("=" * 64)
409
+
410
+ summary: dict[str, int] = {}
411
+ n_active = len(active_sources)
412
+ step = 1
413
+
414
+ # ── SLTrans ────────────────────────────────────────────────────────────────
415
+ if budgets["sltrans"] > 0:
416
+ print(f"\n[{step}/{n_active}] SLTrans (local parquet, balanced language x IR-type)")
417
+ step += 1
418
+ w = ShardWriter(out_dir, "sltrans", args.shard_size)
419
+ try:
420
+ summary["sltrans"] = write_sltrans(
421
+ Path(args.sltrans_root), budgets["sltrans"], w, rng, args.min_tokens,
422
+ )
423
+ finally:
424
+ w.close()
425
+
426
+ # ── peS2o ──────────────────────────────────────────────────────────────────
427
+ if budgets["pes2o"] > 0:
428
+ print(f"\n[{step}/{n_active}] peS2o (allenai/peS2o, config=v2)")
429
+ step += 1
430
+ w = ShardWriter(out_dir, "pes2o", args.shard_size)
431
+ try:
432
+ summary["pes2o"] = write_hf_source(
433
+ "pes2o", budgets["pes2o"], w, rng, args.min_tokens,
434
+ hf_path="allenai/peS2o",
435
+ text_fn=pes2o_text, meta_fn=pes2o_meta,
436
+ hf_config="v2",
437
+ )
438
+ finally:
439
+ w.close()
440
+
441
+ # ── TheStack ───────────────────────────────────────────────────────────────
442
+ if budgets["the_stack"] > 0:
443
+ print(f"\n[{step}/{n_active}] TheStack (bigcode/the-stack, {len(stack_langs)} language subsets)")
444
+ print(f" langs: {', '.join(stack_langs)}")
445
+ step += 1
446
+ w = ShardWriter(out_dir, "the_stack", args.shard_size)
447
+ try:
448
+ summary["the_stack"] = write_hf_source(
449
+ "the_stack", budgets["the_stack"], w, rng, args.min_tokens,
450
+ hf_path="bigcode/the-stack",
451
+ text_fn=stack_text, meta_fn=stack_meta,
452
+ lang_filter={l.lower() for l in stack_langs},
453
+ )
454
+ finally:
455
+ w.close()
456
+
457
+ # ── TheStack LLVM IR (unpaired) ────────────────────────────────────────────
458
+ if budgets["stack_llvm"] > 0:
459
+ print(f"\n[{step}/{n_active}] TheStack LLVM IR (bigcode/the-stack, lang=llvm, unpaired)")
460
+ step += 1
461
+ w = ShardWriter(out_dir, "stack_llvm", args.shard_size)
462
+ try:
463
+ summary["stack_llvm"] = write_hf_source(
464
+ "stack_llvm", budgets["stack_llvm"], w, rng, args.min_tokens,
465
+ hf_path="bigcode/the-stack",
466
+ text_fn=stack_text, meta_fn=stack_meta,
467
+ lang_filter={"llvm"},
468
+ )
469
+ finally:
470
+ w.close()
471
+
472
+ # ── OpenWebMath ────────────────────────────────────────────────────────────
473
+ if budgets["openwebmath"] > 0:
474
+ print(f"\n[{step}/{n_active}] OpenWebMath (open-web-math/open-web-math)")
475
+ w = ShardWriter(out_dir, "openwebmath", args.shard_size)
476
+ try:
477
+ summary["openwebmath"] = write_hf_source(
478
+ "openwebmath", budgets["openwebmath"], w, rng, args.min_tokens,
479
+ hf_path="open-web-math/open-web-math",
480
+ text_fn=owm_text, meta_fn=owm_meta,
481
+ )
482
+ finally:
483
+ w.close()
484
+
485
+ # ── manifest ───────────────────────────────────────────────────────────────
486
+ manifest = {
487
+ "seed": args.seed,
488
+ "min_tokens_per_record": args.min_tokens,
489
+ "sources": {
490
+ "sltrans": {"root": args.sltrans_root, "target_tokens": budgets["sltrans"]},
491
+ "pes2o": {"hf_path": "allenai/peS2o", "target_tokens": budgets["pes2o"]},
492
+ "the_stack": {"hf_path": "bigcode/the-stack", "target_tokens": budgets["the_stack"], "langs": stack_langs},
493
+ "stack_llvm": {"hf_path": "bigcode/the-stack", "target_tokens": budgets["stack_llvm"], "langs": ["llvm"]},
494
+ "openwebmath": {"hf_path": "open-web-math/open-web-math", "target_tokens": budgets["openwebmath"]},
495
+ },
496
+ "tokens_written": summary,
497
+ }
498
+ (out_dir / "manifest.json").write_text(json.dumps(manifest, indent=2))
499
+
500
+ # ── summary ────────────────────────────────────────────────────────────────
501
+ grand = sum(summary.values())
502
+ print("\n" + "=" * 62)
503
+ print(f"{'Source':<14} {'Target':>15} {'Written':>15} {'Share':>6}")
504
+ print("-" * 58)
505
+ for name in ["sltrans", "pes2o", "the_stack", "stack_llvm", "openwebmath"]:
506
+ if budgets[name] == 0:
507
+ continue
508
+ written = summary.get(name, 0)
509
+ pct = 100 * written / grand if grand else 0
510
+ print(f"{name:<14} {budgets[name]:>15,} {written:>15,} {pct:>5.1f}%")
511
+ print("-" * 58)
512
+ print(f"{'TOTAL':<14} {total_budget:>15,} {grand:>15,} 100.0%")
513
+ print(f"\nOutput: {out_dir.resolve()}")
514
+
515
+
516
+ if __name__ == "__main__":
517
+ 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()
pretraining_mix_raw.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:82c53eafe054a1e7938644fe60e4cdbdf3f321768738294beb8719acaa5db0e3
3
+ size 1442069968
sltrans_subsets/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_subsets/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_subsets/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
tokenize_for_training.py ADDED
@@ -0,0 +1,345 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ tokenize_for_training.py — Tokenize and chunk ir_dataset.parquet into a
4
+ HuggingFace dataset ready for continued_pretrain.py.
5
+
6
+ Pipeline position: AFTER build_ir_dataset.py, BEFORE continued_pretrain.py
7
+
8
+ Input
9
+ -----
10
+ Parquet file produced by build_ir_dataset.py with columns:
11
+ source_code, llvm_ir, language, ir_type, source_dataset, est_tokens
12
+
13
+ Processing
14
+ ----------
15
+ 1. Assemble one text string per record:
16
+ sltrans → <source>\\n{code}\\n</source>\\n<llvm_ir>\\n{ir}\\n</llvm_ir>
17
+ stack_llvm → {llvm_ir} (unpaired IR, no source)
18
+ others → {source_code} (peS2o, TheStack, OpenWebMath)
19
+ 2. Tokenize each string without truncation, append an EOS token as a
20
+ document separator.
21
+ 3. Concatenate all token sequences into one stream, split into
22
+ fixed-length blocks of --block-size tokens.
23
+ 4. Emit records with input_ids / attention_mask / labels columns.
24
+ labels == input_ids (the Trainer shifts internally for causal LM loss).
25
+
26
+ Output
27
+ ------
28
+ Arrow dataset saved with save_to_disk(), optionally pushed to the Hub.
29
+ Load locally: datasets.load_from_disk("./tokenized_dataset")
30
+ Load from Hub: datasets.load_dataset("your-org/your-dataset")
31
+
32
+ NOTE: continued_pretrain.py uses load_dataset(...), so either push to Hub
33
+ or replace that call with load_from_disk() for a purely local workflow.
34
+
35
+ Usage
36
+ -----
37
+ python tokenize_for_training.py \\
38
+ --input ir_dataset.parquet \\
39
+ --model bigcode/starcoderbase-1b \\
40
+ --output ./tokenized_dataset
41
+
42
+ python tokenize_for_training.py \\
43
+ --input ir_dataset.parquet \\
44
+ --model codellama/CodeLlama-7b-hf \\
45
+ --output ./tokenized_dataset \\
46
+ --validation-split 0.05 \\
47
+ --push-to-hub your-org/dataset-name \\
48
+ --token YOUR_HF_TOKEN
49
+ """
50
+
51
+ from __future__ import annotations
52
+
53
+ import argparse
54
+ import sys
55
+ from pathlib import Path
56
+
57
+ from itertools import chain
58
+
59
+ from datasets import Dataset, DatasetDict
60
+ from transformers import AutoTokenizer
61
+
62
+ # Special tokens the IRCoder paper adds to every model's vocabulary.
63
+ _IR_SPECIAL_TOKENS = ["<source_to_llvm>", "<llvm_to_source>"]
64
+ _PAD_TOKEN = "<|pad|>"
65
+
66
+ # Records per batch during the group_texts step. Larger batches waste fewer
67
+ # tokens at chunk boundaries.
68
+ _GROUP_BATCH_SIZE = 5_000
69
+
70
+
71
+ # ── tokenizer setup ────────────────────────────────────────────────────────────
72
+
73
+ def build_tokenizer(model_name: str, block_size: int | None, token: str | None) -> AutoTokenizer:
74
+ """Load tokenizer and register the IRCoder special tokens."""
75
+ tok = AutoTokenizer.from_pretrained(
76
+ model_name,
77
+ padding_side="left",
78
+ truncation_side="right",
79
+ trust_remote_code=True,
80
+ token=token,
81
+ )
82
+
83
+ tokens_to_add: dict = {}
84
+
85
+ if tok.pad_token is None:
86
+ tokens_to_add["pad_token"] = _PAD_TOKEN
87
+
88
+ extra = [t for t in _IR_SPECIAL_TOKENS if t not in tok.get_vocab()]
89
+ existing_extra = list(tok.extra_special_tokens or [])
90
+ new_extra = [t for t in extra if t not in existing_extra]
91
+ if new_extra:
92
+ tokens_to_add["additional_special_tokens"] = existing_extra + new_extra
93
+
94
+ if tokens_to_add:
95
+ tok.add_special_tokens(tokens_to_add)
96
+
97
+ if block_size is not None:
98
+ tok.model_max_length = block_size
99
+ elif tok.model_max_length > 1_000_000:
100
+ # HuggingFace sets model_max_length to a huge sentinel when the tokenizer
101
+ # config doesn't specify a context length. Fall back to the value used by
102
+ # the IRCoder paper for all StarCoder/DeepSeek/CodeLlama models.
103
+ tok.model_max_length = 4096
104
+ print(f" WARNING: tokenizer did not report a context length; defaulting "
105
+ f"to {tok.model_max_length}. Pass --block-size to override.")
106
+
107
+ return tok
108
+
109
+
110
+ # ── text assembly ──────────────────────────────────────────────────────────────
111
+
112
+ def _assemble_text_batch(batch: dict) -> dict:
113
+ """Derive a single 'text' string for each record."""
114
+ texts: list[str | None] = []
115
+ for src, ir, source in zip(
116
+ batch["source_code"], batch["llvm_ir"], batch["source_dataset"]
117
+ ):
118
+ if source == "sltrans":
119
+ if src and ir:
120
+ texts.append(
121
+ f"<source>\n{src}\n</source>\n<llvm_ir>\n{ir}\n</llvm_ir>"
122
+ )
123
+ else:
124
+ texts.append(None)
125
+ elif source == "stack_llvm":
126
+ texts.append(str(ir) if ir else None)
127
+ else:
128
+ texts.append(str(src) if src else None)
129
+ return {"text": texts}
130
+
131
+
132
+ def _is_valid(example: dict) -> bool:
133
+ t = example["text"]
134
+ return t is not None and t != ""
135
+
136
+
137
+ # ── tokenisation ───────────────────────────────────────────────────────────────
138
+
139
+ def _tokenize_batch(batch: dict, tokenizer: AutoTokenizer) -> dict:
140
+ """Tokenize text without truncation; append EOS as a document separator."""
141
+ eos = tokenizer.eos_token_id
142
+ if eos is None:
143
+ raise ValueError(
144
+ f"Tokenizer for {tokenizer.name_or_path!r} has no eos_token_id. "
145
+ "Set one explicitly before running this script."
146
+ )
147
+
148
+ encoded = tokenizer(
149
+ batch["text"],
150
+ add_special_tokens=False,
151
+ truncation=False,
152
+ padding=False,
153
+ )
154
+ return {
155
+ "input_ids": [ids + [eos] for ids in encoded["input_ids"]],
156
+ "attention_mask": [am + [1] for am in encoded["attention_mask"]],
157
+ }
158
+
159
+
160
+ # ── chunking ───────────────────────────────────────────────────────────────────
161
+
162
+ def _group_texts(batch: dict, block_size: int) -> dict:
163
+ """Concatenate token sequences and split into fixed-length blocks."""
164
+ all_ids = list(chain.from_iterable(batch["input_ids"]))
165
+ total = (len(all_ids) // block_size) * block_size
166
+ if total == 0:
167
+ return {"input_ids": [], "attention_mask": [], "labels": []}
168
+
169
+ num_blocks = total // block_size
170
+ ids_list = [all_ids[i : i + block_size] for i in range(0, total, block_size)]
171
+ am_row = [1] * block_size
172
+
173
+ return {
174
+ "input_ids": ids_list,
175
+ "attention_mask": [am_row] * num_blocks,
176
+ "labels": ids_list,
177
+ }
178
+
179
+
180
+ # ── main ───────────────────────────────────────────────────────────────────────
181
+
182
+ def main() -> None:
183
+ ap = argparse.ArgumentParser(
184
+ description=__doc__,
185
+ formatter_class=argparse.RawDescriptionHelpFormatter,
186
+ )
187
+ ap.add_argument(
188
+ "--input", default="ir_dataset.parquet",
189
+ help="Parquet file from build_ir_dataset.py (default: ir_dataset.parquet)",
190
+ )
191
+ ap.add_argument(
192
+ "--model", required=True,
193
+ help="HuggingFace model name — selects the tokenizer "
194
+ "(e.g. bigcode/starcoderbase-1b)",
195
+ )
196
+ ap.add_argument(
197
+ "--output", default="./tokenized_dataset",
198
+ help="Directory for the Arrow dataset (default: ./tokenized_dataset)",
199
+ )
200
+ ap.add_argument(
201
+ "--block-size", type=int, default=None,
202
+ help="Token block length. Defaults to the tokenizer's model_max_length "
203
+ "(4096 for StarCoder/DeepSeek/CodeLlama, 2048 for CodeGen).",
204
+ )
205
+ ap.add_argument(
206
+ "--num-workers", type=int, default=1,
207
+ help="Parallel workers for dataset.map (default: 1). "
208
+ "Increase on Linux; keep at 1 on Windows to avoid spawn issues.",
209
+ )
210
+ ap.add_argument(
211
+ "--validation-split", type=float, default=0.0,
212
+ help="Fraction of blocks to hold out as validation (default: 0 = no split). "
213
+ "The training script can also split at runtime via "
214
+ "--validation_split_percentage.",
215
+ )
216
+ ap.add_argument(
217
+ "--push-to-hub", default=None, metavar="HUB_DATASET_ID",
218
+ help="Push the finished dataset to the Hub (e.g. your-org/dataset-name).",
219
+ )
220
+ ap.add_argument(
221
+ "--token", default=None,
222
+ help="HuggingFace token (required for gated models and Hub push).",
223
+ )
224
+ args = ap.parse_args()
225
+
226
+ in_path = Path(args.input)
227
+ if not in_path.exists():
228
+ print(f"ERROR: input file not found: {in_path}", file=sys.stderr)
229
+ sys.exit(1)
230
+
231
+ # ── tokenizer ─────────────────────────────────────────────────────────────
232
+ print(f"Model / tokenizer : {args.model}")
233
+ tokenizer = build_tokenizer(args.model, args.block_size, args.token)
234
+ block_size = tokenizer.model_max_length
235
+ print(f"Block size : {block_size} tokens")
236
+ print(f"Vocab size (final) : {len(tokenizer)}")
237
+ print(f"EOS token : {tokenizer.eos_token!r} (id={tokenizer.eos_token_id})")
238
+ print()
239
+
240
+ # ── load ──────────────────────────────────────────────────────────────────
241
+ print(f"[1/4] Loading {in_path.resolve()} ...")
242
+ ds: Dataset = Dataset.from_parquet(str(in_path))
243
+ print(f" {len(ds):,} records loaded")
244
+
245
+ # ── assemble text ─────────────────────────────────────────────────────────
246
+ print("\n[2/4] Assembling text column ...")
247
+ ds = ds.map(
248
+ _assemble_text_batch,
249
+ batched=True,
250
+ num_proc=args.num_workers,
251
+ remove_columns=ds.column_names,
252
+ desc="assemble",
253
+ )
254
+ before = len(ds)
255
+ ds = ds.filter(_is_valid, num_proc=args.num_workers, desc="filter-empty")
256
+ dropped = before - len(ds)
257
+ print(f" {len(ds):,} records with text ({dropped:,} dropped — empty/null fields)")
258
+
259
+ # ── tokenize ──────────────────────────────────────────────────────────────
260
+ print("\n[3/4] Tokenizing (no truncation, EOS appended) ...")
261
+ ds = ds.map(
262
+ _tokenize_batch,
263
+ fn_kwargs={"tokenizer": tokenizer},
264
+ batched=True,
265
+ batch_size=1_000,
266
+ writer_batch_size=500,
267
+ num_proc=args.num_workers,
268
+ remove_columns=["text"],
269
+ desc="tokenize",
270
+ )
271
+
272
+ # ── chunk ─────────────────────────────────────────────────────────────────
273
+ print(f"\n[4/4] Chunking into {block_size}-token blocks ...")
274
+ ds = ds.map(
275
+ _group_texts,
276
+ fn_kwargs={"block_size": block_size},
277
+ batched=True,
278
+ batch_size=_GROUP_BATCH_SIZE,
279
+ num_proc=args.num_workers,
280
+ desc="chunk",
281
+ )
282
+ total_tokens = len(ds) * block_size
283
+ print(f" {len(ds):,} blocks ({total_tokens:,} tokens)")
284
+ if len(ds) == 0:
285
+ print("ERROR: chunking produced 0 blocks. Check that --block-size is set "
286
+ "correctly and that the input dataset is non-empty.", file=sys.stderr)
287
+ sys.exit(1)
288
+ if "labels" not in ds.column_names:
289
+ ds = ds.add_column("labels", ds["input_ids"])
290
+
291
+ # ── optional validation split ─────────────────────────────────────────────
292
+ out_ds: Dataset | DatasetDict
293
+ if args.validation_split > 0.0:
294
+ split = ds.train_test_split(
295
+ test_size=args.validation_split, seed=42, shuffle=True
296
+ )
297
+ out_ds = DatasetDict({"train": split["train"], "validation": split["test"]})
298
+ print(
299
+ f"\n train : {len(split['train']):,} blocks"
300
+ f"\n validation : {len(split['test']):,} blocks"
301
+ )
302
+ else:
303
+ out_ds = ds
304
+
305
+ # ── save ──────────────────────────────────────────────────────────────────
306
+ out_dir = Path(args.output)
307
+ out_dir.mkdir(parents=True, exist_ok=True)
308
+ print(f"\nSaving parquet to {out_dir.resolve()} ...")
309
+
310
+ splits: dict[str, Dataset] = (
311
+ dict(out_ds.items()) if isinstance(out_ds, DatasetDict) else {"train": out_ds}
312
+ )
313
+ for split_name, split_ds in splits.items():
314
+ dest = out_dir / f"{split_name}.parquet"
315
+ split_ds.to_parquet(str(dest))
316
+ print(f" Wrote {dest.name} ({len(split_ds):,} blocks)")
317
+
318
+ if args.push_to_hub:
319
+ print(f"\nPushing to Hub: {args.push_to_hub} ...")
320
+ out_ds.push_to_hub(args.push_to_hub, token=args.token)
321
+ print("Pushed.")
322
+
323
+ # ── summary ───────────────────────────────────────────────────────────────
324
+ print()
325
+ print("=" * 60)
326
+ print("TOKENIZATION COMPLETE")
327
+ print("=" * 60)
328
+ for split_name, split_ds in splits.items():
329
+ print(
330
+ f" {split_name:<12} {len(split_ds):>10,} blocks"
331
+ f" ({len(split_ds) * block_size:,} tokens)"
332
+ )
333
+
334
+ schema_ds = next(iter(splits.values()))
335
+ print(f"\nDataset schema : {list(schema_ds.column_names)}")
336
+ print(f"Output : {out_dir.resolve()}")
337
+ if args.push_to_hub:
338
+ print(f"Hub : {args.push_to_hub}")
339
+ print()
340
+ print("Pass to continued_pretrain.py with:")
341
+ print(f" --dataset_name {str(out_dir.resolve())!r}")
342
+
343
+
344
+ if __name__ == "__main__":
345
+ main()
tokenized_dataset/train.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b11b25e97eb3c3b9cfa6feb778898f786a8af4236a19b69a9332688064bf43cb
3
+ size 4598221447
tokenized_dataset/validation.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0906df97b7a78fb6d346f45f2c607778ea0c6f08741030c54e0c1d20c51a98bd
3
+ size 244075062
tokenized_dataset_msoft-bitnet-b1.58-2B-4T-bf16/train.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d22464ab9dbc4ef4400af541e49afbdb2272a101eef57ee162b34bdb1d3da913
3
+ size 4535079215
tokenized_dataset_msoft-bitnet-b1.58-2B-4T-bf16/validation.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3543a4b466780574ca548478e90d2d2f72f9201931242128e74732e7d15ec7d2
3
+ size 239858591
tokenized_dataset_starcoderbase-1b_chunk1k/train.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6e50e3b1b320dee68e539807fa3e74d75e7853523c691ec393e6179f0f986d15
3
+ size 4585957794
tokenized_dataset_starcoderbase-1b_chunk1k/validation.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b9cb0484c75a31235ce8871807c99cdbab0eb23e536a6791560e16df24823dc6
3
+ size 241465412
upload_to_hub.py ADDED
@@ -0,0 +1,102 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Upload the current repo to a fresh HuggingFace dataset via the Hub HTTP API.
3
+ Uploads only git-tracked files — raw SLTrans language folders are ignored.
4
+
5
+ Usage:
6
+ python upload_to_hub.py
7
+ python upload_to_hub.py --repo nlpscu/Multilingual-Code-Generator --private
8
+ """
9
+
10
+ import argparse
11
+ import subprocess
12
+ import sys
13
+ from pathlib import Path
14
+
15
+ from huggingface_hub import HfApi
16
+
17
+
18
+ def git_tracked_files() -> list[str]:
19
+ result = subprocess.run(
20
+ ["git", "ls-files"],
21
+ capture_output=True, text=True, cwd=Path(__file__).parent,
22
+ )
23
+ if result.returncode != 0:
24
+ print("ERROR: not inside a git repo or git not found", file=sys.stderr)
25
+ sys.exit(1)
26
+ return [f for f in result.stdout.strip().splitlines() if f]
27
+
28
+
29
+ def main():
30
+ ap = argparse.ArgumentParser(description=__doc__,
31
+ formatter_class=argparse.RawDescriptionHelpFormatter)
32
+ ap.add_argument("--repo", default="st-taro/csen346_temp",
33
+ help="HuggingFace dataset repo id (default: st-taro/csen346_temp)")
34
+ ap.add_argument("--private", action="store_true", default=False,
35
+ help="Create as private repo (note: private repos have a 10 GB LFS limit)")
36
+ ap.add_argument("--dry-run", action="store_true",
37
+ help="Print files that would be uploaded without uploading")
38
+ args = ap.parse_args()
39
+
40
+ root = Path(__file__).parent
41
+ files = git_tracked_files()
42
+
43
+ print(f"Repo : {args.repo}")
44
+ print(f"Private: {args.private}")
45
+ print(f"Files : {len(files)}")
46
+ for f in files:
47
+ size = (root / f).stat().st_size if (root / f).exists() else 0
48
+ print(f" {f} ({size / 1e6:.1f} MB)")
49
+
50
+ if args.dry_run:
51
+ print("\nDry run — nothing uploaded.")
52
+ return
53
+
54
+ api = HfApi()
55
+
56
+ # Create repo (no-op if already exists)
57
+ try:
58
+ api.create_repo(
59
+ repo_id=args.repo,
60
+ repo_type="dataset",
61
+ private=args.private,
62
+ exist_ok=True,
63
+ )
64
+ print(f"\nRepo ready: https://huggingface.co/datasets/{args.repo}")
65
+ except Exception as e:
66
+ print(f"ERROR creating repo: {e}", file=sys.stderr)
67
+ sys.exit(1)
68
+
69
+ # Upload files one at a time so progress is visible and failures are isolated
70
+ failed = []
71
+ for i, filepath in enumerate(files, 1):
72
+ local = root / filepath
73
+ if not local.exists():
74
+ print(f"[{i}/{len(files)}] SKIP (not on disk): {filepath}")
75
+ continue
76
+ size_mb = local.stat().st_size / 1e6
77
+ print(f"[{i}/{len(files)}] {filepath} ({size_mb:.1f} MB) ... ", end="", flush=True)
78
+ try:
79
+ api.upload_file(
80
+ path_or_fileobj=str(local),
81
+ path_in_repo=filepath,
82
+ repo_id=args.repo,
83
+ repo_type="dataset",
84
+ )
85
+ print("done")
86
+ except Exception as e:
87
+ print(f"FAILED: {e}")
88
+ failed.append((filepath, str(e)))
89
+
90
+ print()
91
+ if failed:
92
+ print(f"Upload finished with {len(failed)} failure(s):")
93
+ for f, err in failed:
94
+ print(f" {f}: {err}")
95
+ sys.exit(1)
96
+ else:
97
+ print(f"All {len(files)} files uploaded.")
98
+ print(f"Dataset: https://huggingface.co/datasets/{args.repo}")
99
+
100
+
101
+ if __name__ == "__main__":
102
+ main()