File size: 8,713 Bytes
dc9424f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
"""
prepare.py - build the training data.

Streams text from the four sources straight from Hugging Face (nothing raw is
kept on disk), tokenizes it with the GPT-2 byte-pair tokenizer, and writes two
flat files of 16-bit token ids:

    <out>/train.bin   the training tokens
    <out>/val.bin     a held-out slice for measuring validation loss
    <out>/meta.json   how many tokens came from each source

Sources are mixed document by document according to --mix, so the stream is
already shuffled across sources when it hits the disk. Every document ends with
the GPT-2 end-of-text token so the model learns where documents stop.

Examples:
    # thin slice for testing the code on the Mac (about 1 minute)
    python prepare.py --out data_small --tokens 5e6 --val-tokens 2e5

    # the real first run (10 billion tokens, run this on the GPU server)
    python prepare.py --out data --tokens 10e9 --val-tokens 2e7 --workers 48
"""

import argparse
import json
import os
import random
import time
from multiprocessing import Pool

import numpy as np
import tiktoken

EOT = 50256  # GPT-2 end-of-text token id

PILE_OF_LAW_FILES = [
    # primary sources: law, regulation, government record. Edit this list to taste.
    "uscode",
    "cfr",
    "federal_register",
    "us_bills",
    "founding_docs",
    "constitutions",
    "congressional_hearings",
    "eurlex",
    "undebates",
    "courtlisteneropinions.0",
    "courtlisteneropinions.1",
]


# ---------------------------------------------------------------- sources ---
# Each source is a function that returns an iterator of plain text strings.

def source_fineweb_edu():
    from datasets import load_dataset
    ds = load_dataset("HuggingFaceFW/fineweb-edu", name="sample-10BT",
                      split="train", streaming=True)
    for row in ds:
        yield row["text"]


def source_wikipedia():
    from datasets import load_dataset
    ds = load_dataset("wikimedia/wikipedia", name="20231101.en",
                      split="train", streaming=True)
    for row in ds:
        yield row["title"] + "\n\n" + row["text"]


def source_science():
    from datasets import load_dataset
    ds = load_dataset("json",
                      data_files="hf://datasets/allenai/peS2o/data/v2/train-*.json.gz",
                      split="train", streaming=True)
    for row in ds:
        yield row["text"]


def source_primary():
    from datasets import load_dataset
    base = "https://huggingface.co/datasets/pile-of-law/pile-of-law/resolve/main/data/train."
    files = [base + name + ".jsonl.xz" for name in PILE_OF_LAW_FILES]
    ds = load_dataset("json", data_files=files, split="train", streaming=True)
    for row in ds:
        yield row["text"]


SOURCES = {
    "fineweb_edu": source_fineweb_edu,
    "wikipedia": source_wikipedia,
    "science": source_science,
    "primary": source_primary,
}


# ------------------------------------------------------------- tokenizing ---

_enc = None


def _encode_batch(texts):
    global _enc
    if _enc is None:
        _enc = tiktoken.get_encoding("gpt2")
    out = []
    for toks in _enc.encode_ordinary_batch(texts):
        toks.append(EOT)
        out.append(np.array(toks, dtype=np.uint16))
    return out


def parse_mix(s):
    mix = {}
    for part in s.split(","):
        name, w = part.split("=")
        name = name.strip()
        if name not in SOURCES:
            raise SystemExit(f"unknown source {name!r}; choose from {list(SOURCES)}")
        mix[name] = float(w)
    total = sum(mix.values())
    return {k: v / total for k, v in mix.items()}


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--out", default="data")
    ap.add_argument("--tokens", type=float, default=10e9, help="training tokens to write")
    ap.add_argument("--val-tokens", type=float, default=2e7, help="validation tokens to write")
    ap.add_argument("--mix", default="fineweb_edu=0.5,wikipedia=0.2,science=0.2,primary=0.1",
                    help="source weights, normalised to sum to 1")
    ap.add_argument("--min-chars", type=int, default=200, help="skip documents shorter than this")
    ap.add_argument("--batch-docs", type=int, default=256, help="documents per tokenizer batch")
    ap.add_argument("--batch-chars", type=int, default=2_000_000,
                    help="close a batch early past this many characters (about 500k tokens), "
                         "so huge documents do not blow past the budgets")
    ap.add_argument("--workers", type=int, default=max(1, os.cpu_count() - 2))
    ap.add_argument("--seed", type=int, default=1337)
    args = ap.parse_args()

    os.makedirs(args.out, exist_ok=True)
    mix = parse_mix(args.mix)
    budget_train = {k: int(args.tokens * w) for k, w in mix.items()}
    budget_val = {k: int(args.val_tokens * w) for k, w in mix.items()}
    rng = random.Random(args.seed)

    iters = {k: SOURCES[k]() for k in mix}
    written = {k: 0 for k in mix}      # tokens written so far per source (train)
    written_val = {k: 0 for k in mix}  # ... (val)
    inflight = {k: 0 for k in mix}     # estimated tokens of batches still in the pool
    exhausted = set()

    val_path = os.path.join(args.out, "val.bin")
    train_path = os.path.join(args.out, "train.bin")
    val_f = open(val_path, "wb")
    train_f = open(train_path, "wb")

    pool = Pool(args.workers)
    t0 = time.time()
    total = 0
    last_report = 0

    def pick_source(phase_written, phase_budget):
        # choose a source at random among those still under budget, weighted by mix
        live = [k for k in mix if k not in exhausted
                and phase_written[k] + inflight[k] < phase_budget[k]]
        if not live:
            return None
        weights = [mix[k] for k in live]
        return rng.choices(live, weights)[0]

    for phase, f, phase_written, phase_budget in (
        ("val", val_f, written_val, budget_val),
        ("train", train_f, written, budget_train),
    ):
        pending = []  # (source, estimated tokens, async result) batches waiting for the pool
        while True:
            # fill a batch of documents from one randomly chosen source
            src = pick_source(phase_written, phase_budget)
            if src is None:
                break
            texts = []
            chars = 0
            it = iters[src]
            while len(texts) < args.batch_docs and chars < args.batch_chars:
                try:
                    text = next(it)
                except StopIteration:
                    exhausted.add(src)
                    print(f"source {src} exhausted after {phase_written[src]:,} {phase} tokens")
                    break
                if text and len(text) >= args.min_chars:
                    texts.append(text)
                    chars += len(text)
            if not texts:
                continue
            est = chars // 4  # about 4 characters per GPT-2 token
            inflight[src] += est
            pending.append((src, est, pool.apply_async(_encode_batch, (texts,))))

            # keep a few batches in flight, then drain the oldest
            if len(pending) >= args.workers * 2:
                src_done, est_done, job = pending.pop(0)
                inflight[src_done] -= est_done
                for arr in job.get():
                    f.write(arr.tobytes())
                    phase_written[src_done] += len(arr)
                    total += len(arr)
            if total - last_report >= 50_000_000:
                last_report = total
                dt = time.time() - t0
                print(f"{phase}: {total/1e6:,.0f}M tokens, {total/dt/1e6:.2f}M tok/s, "
                      + ", ".join(f"{k}={phase_written[k]/1e6:,.0f}M" for k in mix), flush=True)
        for src_done, est_done, job in pending:
            inflight[src_done] -= est_done
            for arr in job.get():
                f.write(arr.tobytes())
                phase_written[src_done] += len(arr)
                total += len(arr)
        f.close()
        print(f"{phase} done: " + ", ".join(f"{k}={phase_written[k]:,}" for k in mix), flush=True)

    pool.close()
    pool.join()

    meta = {
        "tokenizer": "gpt2",
        "vocab_size": 50257,
        "eot": EOT,
        "mix": mix,
        "train_tokens": written,
        "val_tokens": written_val,
        "train_total": sum(written.values()),
        "val_total": sum(written_val.values()),
    }
    with open(os.path.join(args.out, "meta.json"), "w") as mf:
        json.dump(meta, mf, indent=2)
    dt = time.time() - t0
    print(f"wrote {meta['train_total']:,} train and {meta['val_total']:,} val tokens "
          f"to {args.out}/ in {dt/60:.1f} min")


if __name__ == "__main__":
    main()