File size: 10,667 Bytes
b3d361d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
"""
Prepare raw text files (or a HuggingFace dataset) for LLM training.

Tokenizes all input text, concatenates all token IDs into a single flat
sequence, splits into train / validation sets, and saves each as a uint16
numpy binary file (.bin) ready for TextDataset / PackedDataset.

Usage — glob of local text files:
    python data/prepare.py \
        --input  "data/raw/*.txt" \
        --output  data/train.bin \
        --val_output data/val.bin \
        --tokenizer tokenizer/tokenizer.json \
        --val_split 0.005 \
        --seed 42

Usage — HuggingFace dataset (streaming):
    python data/prepare.py \
        --hf_dataset  allenai/c4 \
        --hf_subset   en \
        --hf_split    train \
        --hf_text_col text \
        --output      data/train.bin \
        --val_output  data/val.bin \
        --tokenizer   tokenizer/tokenizer.json \
        --val_split   0.005
"""

from __future__ import annotations

import argparse
import glob
import os
import random
import sys
from pathlib import Path

import numpy as np
from tokenizers import Tokenizer
from tqdm import tqdm


# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------

def load_tokenizer(tokenizer_path: str) -> Tokenizer:
    path = Path(tokenizer_path)
    if not path.exists():
        raise FileNotFoundError(f"Tokenizer not found: {path}")
    return Tokenizer.from_file(str(path))


def find_input_files(pattern: str) -> list[str]:
    """Resolve a glob pattern or a plain file path to a list of files."""
    if any(c in pattern for c in ("*", "?", "[")):
        files = sorted(glob.glob(pattern, recursive=True))
    else:
        files = [pattern] if Path(pattern).exists() else []
    if not files:
        raise FileNotFoundError(f"No files matched pattern: {pattern!r}")
    return files


def tokenize_file(path: str, tokenizer: Tokenizer) -> list[int]:
    """Read a single text file and return its token IDs."""
    with open(path, "r", encoding="utf-8", errors="replace") as fh:
        text = fh.read()
    return tokenizer.encode(text).ids


def derive_val_path(output_path: Path, val_output_arg: str | None) -> Path:
    """Return the val .bin path, either explicitly provided or auto-derived."""
    if val_output_arg:
        return Path(val_output_arg)
    # If the stem contains "train", swap it for "val".
    if "train" in output_path.name:
        candidate = output_path.parent / output_path.name.replace("train", "val")
        if candidate != output_path:
            return candidate
    # Generic fallback: append _val before the suffix.
    return output_path.with_name(output_path.stem + "_val" + output_path.suffix)


def save_bin(tokens: list[int], path: Path) -> None:
    path.parent.mkdir(parents=True, exist_ok=True)
    np.array(tokens, dtype=np.uint16).tofile(str(path))


def _fmt_bytes(n_tokens: int) -> str:
    """Return a human-readable size string for a uint16 token array."""
    nbytes = n_tokens * 2  # uint16 = 2 bytes per token
    for unit in ("B", "KB", "MB", "GB", "TB"):
        if nbytes < 1024:
            return f"{nbytes:.1f} {unit}"
        nbytes /= 1024
    return f"{nbytes:.1f} PB"


# ---------------------------------------------------------------------------
# Source iterators
# ---------------------------------------------------------------------------

def iter_tokens_from_files(
    input_files: list[str],
    tokenizer: Tokenizer,
    seed: int,
) -> tuple[list[int], int]:
    """
    Tokenize every file, shuffle at file level, flatten, and return
    (all_tokens_shuffled, file_count).
    """
    per_file_tokens: list[list[int]] = []
    for fpath in tqdm(input_files, desc="Tokenizing", unit="file"):
        per_file_tokens.append(tokenize_file(fpath, tokenizer))

    rng = random.Random(seed)
    rng.shuffle(per_file_tokens)

    all_tokens: list[int] = []
    for toks in per_file_tokens:
        all_tokens.extend(toks)

    return all_tokens, len(input_files)


def iter_tokens_from_hf(
    hf_dataset: str,
    hf_subset: str | None,
    hf_split: str,
    hf_text_col: str,
    tokenizer: Tokenizer,
) -> tuple[list[int], int]:
    """
    Stream a HuggingFace dataset row-by-row, tokenize each row's text column,
    and return (all_tokens, row_count).

    Rows are appended in streaming order; no shuffle is performed here because
    the stream may be very large.  A seed-based split by position is used later.
    """
    try:
        from datasets import load_dataset
    except ImportError:
        raise ImportError(
            "The 'datasets' package is required for --hf_dataset. "
            "Install it with: pip install datasets"
        )

    print(f"Streaming HuggingFace dataset: {hf_dataset}"
          + (f" / {hf_subset}" if hf_subset else "")
          + f"  split={hf_split}")

    ds = load_dataset(
        hf_dataset,
        hf_subset,
        split=hf_split,
        streaming=True,
        trust_remote_code=True,
    )

    all_tokens: list[int] = []
    row_count = 0
    pbar = tqdm(desc="Tokenizing rows", unit="row")
    for row in ds:
        text = row.get(hf_text_col, "")
        if text:
            all_tokens.extend(tokenizer.encode(text).ids)
        row_count += 1
        pbar.update(1)
    pbar.close()

    return all_tokens, row_count


# ---------------------------------------------------------------------------
# Argument parsing
# ---------------------------------------------------------------------------

def parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser(
        description=(
            "Tokenize text sources and save as uint16 binary files for LLM training. "
            "Accepts either a glob of local text files (--input) or a HuggingFace "
            "dataset (--hf_dataset)."
        )
    )

    # --- Input source (mutually exclusive) ---
    source = parser.add_mutually_exclusive_group()
    source.add_argument(
        "--input",
        default=None,
        help='Glob pattern or path to a single text file, e.g. "data/raw/*.txt"',
    )
    source.add_argument(
        "--hf_dataset",
        default=None,
        metavar="DATASET",
        help="HuggingFace dataset name, e.g. allenai/c4 (alternative to --input)",
    )

    # --- HuggingFace-specific options ---
    parser.add_argument(
        "--hf_subset",
        default=None,
        metavar="SUBSET",
        help="Dataset subset / config name, e.g. 'en' for allenai/c4",
    )
    parser.add_argument(
        "--hf_split",
        default="train",
        metavar="SPLIT",
        help="Dataset split to use (default: train)",
    )
    parser.add_argument(
        "--hf_text_col",
        default="text",
        metavar="COLUMN",
        help="Name of the text column in the dataset (default: text)",
    )

    # --- Output paths ---
    parser.add_argument(
        "--output",
        required=True,
        help="Output path for the training binary, e.g. data/train.bin",
    )
    parser.add_argument(
        "--val_output",
        default=None,
        metavar="PATH",
        help=(
            "Explicit output path for the validation binary "
            "(default: auto-derived from --output, e.g. train.bin → val.bin)"
        ),
    )

    # --- Tokenizer ---
    parser.add_argument(
        "--tokenizer",
        default="tokenizer/tokenizer.json",
        help="Path to a trained tokenizer JSON file (default: tokenizer/tokenizer.json)",
    )

    # --- Split / reproducibility ---
    parser.add_argument(
        "--val_split",
        type=float,
        default=0.005,
        help="Fraction of tokens reserved for validation (default: 0.005)",
    )
    parser.add_argument(
        "--seed",
        type=int,
        default=42,
        help="Random seed for reproducible train/val split (default: 42)",
    )

    args = parser.parse_args()

    # Require at least one input source.
    if args.input is None and args.hf_dataset is None:
        parser.error("One of --input or --hf_dataset is required.")

    return args


# ---------------------------------------------------------------------------
# Main
# ---------------------------------------------------------------------------

def main() -> None:
    args = parse_args()

    # ---- Load tokenizer ----
    tokenizer = load_tokenizer(args.tokenizer)
    vocab_size = tokenizer.get_vocab_size()

    # Warn early if IDs could overflow uint16.
    if vocab_size > 65535:
        print(
            "WARNING: vocab_size > 65535; token IDs above 65535 will be "
            "truncated when cast to uint16.",
            file=sys.stderr,
        )

    # ---- Collect tokens from the chosen source ----
    if args.hf_dataset:
        all_tokens, source_count = iter_tokens_from_hf(
            hf_dataset=args.hf_dataset,
            hf_subset=args.hf_subset,
            hf_split=args.hf_split,
            hf_text_col=args.hf_text_col,
            tokenizer=tokenizer,
        )
        source_label = f"{source_count:,} rows"
    else:
        input_files = find_input_files(args.input)
        print(f"Found {len(input_files)} input file(s).")
        all_tokens, source_count = iter_tokens_from_files(
            input_files=input_files,
            tokenizer=tokenizer,
            seed=args.seed,
        )
        source_label = f"{source_count:,} files"

    total_tokens = len(all_tokens)

    # ---- Split into train / val ----
    val_size   = max(1, int(total_tokens * args.val_split))
    train_size = total_tokens - val_size

    train_tokens = all_tokens[:train_size]
    val_tokens   = all_tokens[train_size:]

    # ---- Resolve output paths ----
    train_path = Path(args.output)
    val_path   = derive_val_path(train_path, args.val_output)

    # ---- Save ----
    print(f"\nSaving train data -> {train_path}")
    save_bin(train_tokens, train_path)

    print(f"Saving val data   -> {val_path}")
    save_bin(val_tokens, val_path)

    # ---- Final stats ----
    tokens_per_step = 8 * 2048 * 4 * 8  # bs=8, seq=2048, accum=4, 8 GPUs
    estimated_steps = train_size // tokens_per_step

    print()
    print(f"Tokenizer: {args.tokenizer} (vocab_size={vocab_size:,})")
    print(f"Total tokens: {total_tokens:,}")
    print(
        f"Train tokens: {train_size:,}"
        f" (stored in {train_path}, {_fmt_bytes(train_size)})"
    )
    print(
        f"Val tokens:   {val_size:,}"
        f"     (stored in {val_path}, {_fmt_bytes(val_size)})"
    )
    print(
        f"Estimated steps (bs=8, seq=2048, 8 GPUs, accum=4): {estimated_steps:,}"
    )


if __name__ == "__main__":
    main()