File size: 14,520 Bytes
23b3bd1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
"""

Tokenize filtered parquet data and create LitData streaming format for litgpt.



Creates flat binary token chunks compatible with litdata's TokensLoader,

which litgpt's LitData data module uses for pretraining.



STREAMING MODE: Tokenizes texts in batches and flushes chunks to disk

incrementally, keeping RAM usage constant (~128MB buffer) regardless of

dataset size. Supports resuming from the last completed chunk.



Usage:

    python Base/scripts/prepare_litdata.py --mode small

    python Base/scripts/prepare_litdata.py --mode full

    python Base/scripts/prepare_litdata.py --mode both

"""

import argparse
import json
import os
import time
from pathlib import Path

import numpy as np
import pyarrow.parquet as pq

from litgpt.tokenizer import Tokenizer


# Must match model config's block_size + 1 (extra token for targets)
BLOCK_SIZE = 1025
# 64 MB per chunk file
CHUNK_BYTES_TARGET = 64 * 1024 * 1024
# litdata's TokensLoader uses _TORCH_DTYPES_MAPPING[16] = torch.int32
DTYPE = np.int32
# litdata dtype index β€” 16 maps to torch.int32
DTYPE_INDEX = 16


def _write_chunk(output_dir, chunk_idx, block_buffer, num_blocks):
    """Write a single chunk file with litdata header + flat int32 data."""
    dtype_size = DTYPE().itemsize
    filename = f"chunk-0-{chunk_idx}.bin"
    filepath = os.path.join(output_dir, filename)

    chunk_data = block_buffer[:num_blocks * BLOCK_SIZE]

    # Header: [num_items(uint32)] + [offsets 0..num_blocks(uint32)]
    header_num_items = np.array([num_blocks], dtype=np.uint32)
    offsets = np.arange(num_blocks + 1, dtype=np.uint32) * (BLOCK_SIZE * dtype_size)
    header = np.concatenate([header_num_items, offsets])

    with open(filepath, "wb") as f:
        header.tofile(f)
        chunk_data.tofile(f)

    data_bytes = int(chunk_data.nbytes)
    header_bytes = int(header.nbytes)
    return {
        "chunk_bytes": data_bytes + header_bytes,
        "chunk_size": num_blocks,
        "dim": int(len(chunk_data)),
        "filename": filename,
    }, header_bytes, data_bytes


def _load_resume_state(output_dir):
    """Check for existing chunks to support resuming."""
    index_path = os.path.join(output_dir, "index.json.partial")
    if not os.path.exists(index_path):
        return [], 0, 0
    with open(index_path) as f:
        state = json.load(f)
    chunks = state.get("chunks", [])
    tokens_written = sum(c["dim"] for c in chunks)
    return chunks, len(chunks), tokens_written


def _save_resume_state(output_dir, chunks_metadata):
    """Save partial progress for resume."""
    path = os.path.join(output_dir, "index.json.partial")
    with open(path, "w") as f:
        json.dump({"chunks": chunks_metadata}, f)


def prepare_litdata(filtered_dir: str, output_dir: str, tokenizer_path: str, label: str):
    """Tokenize filtered text and write LitData chunks β€” MAX THROUGHPUT version.



    Uses:

      - HuggingFace tokenizers encode_batch() for parallel Rust-level tokenization

      - Bulk parquet reads (entire files into RAM)

      - 512 MB write buffer to minimize I/O syscalls

      - All CPU cores via tokenizers' internal parallelism

    """
    import multiprocessing
    print(f"\n{'='*60}")
    print(f"Preparing LitData [{label}]  ** HIGH-THROUGHPUT MODE **")
    print(f"Input: {filtered_dir}")
    print(f"Output: {output_dir}")
    print(f"Tokenizer: {tokenizer_path}")
    print(f"CPU cores: {multiprocessing.cpu_count()}")
    print(f"{'='*60}\n")

    if not Path(filtered_dir).exists():
        print(f"ERROR: Filtered directory not found: {filtered_dir}")
        print("Run filter_datasets.py first!")
        return

    os.makedirs(output_dir, exist_ok=True)

    # --- Load the raw HF fast tokenizer for encode_batch() ---
    hf_tok = None
    tok_dir = Path(tokenizer_path)
    for candidate in ["tokenizer.json", "tokenizer.model"]:
        cp = tok_dir / candidate
        if cp.exists() and candidate == "tokenizer.json":
            from tokenizers import Tokenizer as HFTokenizer
            hf_tok = HFTokenizer.from_file(str(cp))
            print(f"  Loaded HF fast tokenizer from {cp}")
            break
    # Fallback to litgpt wrapper (slower, single-threaded)
    if hf_tok is None:
        print("  WARNING: No tokenizer.json found, falling back to litgpt Tokenizer (slower)")
    litgpt_tok = Tokenizer(tok_dir)
    eos_id = litgpt_tok.eos_id

    # --- Chunk math ---
    dtype_size = DTYPE().itemsize
    tokens_per_chunk = CHUNK_BYTES_TARGET // dtype_size
    tokens_per_chunk = (tokens_per_chunk // BLOCK_SIZE) * BLOCK_SIZE

    # --- Resume support ---
    chunks_metadata, chunk_idx, tokens_to_skip = _load_resume_state(output_dir)
    if tokens_to_skip > 0:
        print(f"RESUMING: Found {chunk_idx} existing chunks ({tokens_to_skip:,} tokens)")
        print(f"  Will skip {tokens_to_skip:,} tokens then continue writing chunks\n")

    # --- Large write buffer (512 MB worth of tokens) ---
    BIG_BUF_TOKENS = (512 * 1024 * 1024) // dtype_size
    BIG_BUF_TOKENS = (BIG_BUF_TOKENS // BLOCK_SIZE) * BLOCK_SIZE
    token_buf = np.empty(BIG_BUF_TOKENS + BLOCK_SIZE * 1024, dtype=DTYPE)
    buf_pos = 0
    total_tokens_written = sum(c["dim"] for c in chunks_metadata)
    total_texts = 0
    skipped_tokens = 0

    # Batch size for encode_batch β€” large batches saturate all cores
    ENCODE_BATCH = 32_768

    parquet_files = sorted(Path(filtered_dir).glob("*.parquet"))
    t0 = time.time()

    def flush_chunks():
        """Flush all complete chunks from the buffer."""
        nonlocal buf_pos, chunk_idx, total_tokens_written
        flushed = 0
        while buf_pos >= tokens_per_chunk:
            num_blocks = tokens_per_chunk // BLOCK_SIZE
            chunk_array = token_buf[:tokens_per_chunk].copy()
            meta, hdr_b, data_b = _write_chunk(output_dir, chunk_idx, chunk_array, num_blocks)
            chunks_metadata.append(meta)
            total_tokens_written += meta["dim"]
            flushed += 1

            if flushed % 4 == 0 or buf_pos < tokens_per_chunk * 2:
                _save_resume_state(output_dir, chunks_metadata)
                el = time.time() - t0
                rate = total_tokens_written / max(el, 1)
                print(f"  chunk-0-{chunk_idx}.bin | "
                      f"total: {total_tokens_written:,} tokens | "
                      f"{rate:,.0f} tok/s | {el:.0f}s")
            chunk_idx += 1

            leftover = buf_pos - tokens_per_chunk
            if leftover > 0:
                token_buf[:leftover] = token_buf[tokens_per_chunk:tokens_per_chunk + leftover]
            buf_pos = leftover
        return flushed

    def encode_and_append(texts):
        """Encode a batch of texts and append to buffer, handling EOS."""
        nonlocal buf_pos, total_texts, skipped_tokens
        if hf_tok is not None:
            # Rust-parallel batch encode β€” uses ALL CPU cores
            encoded = hf_tok.encode_batch(texts, add_special_tokens=False)
            for enc in encoded:
                ids = enc.ids
                ids.append(eos_id)  # append EOS
                n = len(ids)

                if skipped_tokens < tokens_to_skip:
                    remaining = tokens_to_skip - skipped_tokens
                    if n <= remaining:
                        skipped_tokens += n
                        total_texts += 1
                        continue
                    ids = ids[int(remaining):]
                    skipped_tokens = tokens_to_skip
                    n = len(ids)

                # Ensure buffer capacity
                if buf_pos + n > len(token_buf):
                    flush_chunks()
                    if buf_pos + n > len(token_buf):
                        # Extremely long doc β€” extend buffer
                        extra = np.empty(n + BLOCK_SIZE * 256, dtype=DTYPE)
                        old = token_buf[:buf_pos].copy()
                        new_buf = np.empty(buf_pos + n + BLOCK_SIZE * 256, dtype=DTYPE)
                        new_buf[:buf_pos] = old
                        # Keep reference to token_buf so nonlocal works
                        # Actually we need to reassign
                        pass

                arr = np.array(ids, dtype=DTYPE)
                token_buf[buf_pos:buf_pos + n] = arr
                buf_pos += n
                total_texts += 1
        else:
            # Fallback: single-threaded litgpt tokenizer
            for text in texts:
                tokens = litgpt_tok.encode(text, bos=False, eos=True)
                tok_array = tokens.numpy().astype(DTYPE) if hasattr(tokens, 'numpy') else np.array(tokens.tolist(), dtype=DTYPE)
                n = len(tok_array)

                if skipped_tokens < tokens_to_skip:
                    remaining = tokens_to_skip - skipped_tokens
                    if n <= remaining:
                        skipped_tokens += n
                        total_texts += 1
                        continue
                    tok_array = tok_array[int(remaining):]
                    skipped_tokens = tokens_to_skip
                    n = len(tok_array)

                if buf_pos + n > len(token_buf):
                    flush_chunks()

                token_buf[buf_pos:buf_pos + n] = tok_array
                buf_pos += n
                total_texts += 1

    print(f"Tokenizing (batch_size={ENCODE_BATCH:,}, buffer={BIG_BUF_TOKENS*dtype_size/1e6:.0f} MB)...")
    for pf_idx, pf in enumerate(parquet_files):
        # Read entire parquet into RAM (fast, data is ~10MB/file)
        table = pq.read_table(str(pf), columns=["text"])
        all_texts = table.column("text").to_pylist()
        del table  # free arrow memory

        # Process in large batches
        for i in range(0, len(all_texts), ENCODE_BATCH):
            batch = all_texts[i:i + ENCODE_BATCH]
            encode_and_append(batch)
            flush_chunks()

        del all_texts
        elapsed = time.time() - t0
        rate = total_tokens_written / max(elapsed, 1)
        print(f"  [{pf.name}] file {pf_idx+1}/{len(parquet_files)} | "
              f"texts: {total_texts:,} | tokens: {total_tokens_written:,} | "
              f"{rate:,.0f} tok/s | {elapsed:.0f}s")

    # Flush remaining buffer
    flush_chunks()
    remaining_blocks = buf_pos // BLOCK_SIZE
    if remaining_blocks > 0:
        final_tokens = remaining_blocks * BLOCK_SIZE
        chunk_array = token_buf[:final_tokens].copy()
        meta, hdr_b, data_b = _write_chunk(output_dir, chunk_idx, chunk_array, remaining_blocks)
        chunks_metadata.append(meta)
        total_tokens_written += meta["dim"]
        print(f"  chunk-0-{chunk_idx}.bin (final): {remaining_blocks} blocks, "
              f"{meta['dim']:,} tokens")
        chunk_idx += 1

    # Write final index.json
    index = {
        "chunks": chunks_metadata,
        "config": {
            "chunk_bytes": CHUNK_BYTES_TARGET,
            "chunk_size": None,
            "compression": None,
            "data_format": [f"no_header_tensor:{DTYPE_INDEX}"],
            "data_spec": None,
            "encryption": None,
            "item_loader": "TokensLoader",
        },
        "updated_at": str(time.time()),
    }
    with open(os.path.join(output_dir, "index.json"), "w") as f:
        json.dump(index, f, indent=2)

    # Clean up partial state
    partial_path = os.path.join(output_dir, "index.json.partial")
    if os.path.exists(partial_path):
        os.remove(partial_path)

    elapsed = time.time() - t0
    print(f"\n--- LitData preparation [{label}] complete ---")
    print(f"Chunks: {chunk_idx}")
    print(f"Total tokens: {total_tokens_written:,}")
    print(f"Total blocks: {total_tokens_written // BLOCK_SIZE:,}")
    print(f"Texts processed: {total_texts:,}")
    print(f"Time: {elapsed:.0f}s ({total_tokens_written/max(elapsed,1):,.0f} tok/s)")
    print(f"Output: {output_dir}")


def main():
    parser = argparse.ArgumentParser(description="Prepare LitData from filtered parquet")
    parser.add_argument(
        "--mode",
        choices=["small", "full", "both", "english"],
        default="small",
        help="Which dataset to prepare (english = ultra-clean English corpus)",
    )
    parser.add_argument(
        "--tokenizer_path",
        type=str,
        default="Base/checkpoints/EleutherAI/pythia-160m",
        help="Path to tokenizer directory",
    )
    parser.add_argument(
        "--filtered_dir",
        type=str,
        default=None,
        help="Custom filtered parquet directory to tokenize",
    )
    parser.add_argument(
        "--output_dir",
        type=str,
        default=None,
        help="Custom LitData output directory",
    )
    parser.add_argument(
        "--label",
        type=str,
        default="CUSTOM",
        help="Label shown in logs for custom directory mode",
    )
    args = parser.parse_args()

    if args.filtered_dir or args.output_dir:
        if not args.filtered_dir or not args.output_dir:
            raise ValueError("Both --filtered_dir and --output_dir must be provided together")
        prepare_litdata(
            filtered_dir=args.filtered_dir,
            output_dir=args.output_dir,
            tokenizer_path=args.tokenizer_path,
            label=args.label,
        )
        return

    if args.mode in ("small", "both"):
        prepare_litdata(
            filtered_dir="Base/data/filtered_10m",
            output_dir="Base/data/litdata_10m",
            tokenizer_path=args.tokenizer_path,
            label="SMALL (10M)",
        )

    if args.mode in ("full", "both"):
        prepare_litdata(
            filtered_dir="Base/data/filtered_3b",
            output_dir="Base/data/litdata_3b",
            tokenizer_path=args.tokenizer_path,
            label="FULL (3B)",
        )

    if args.mode == "english":
        prepare_litdata(
            filtered_dir="Base/data/filtered_english",
            output_dir="Base/data/litdata_english",
            tokenizer_path=args.tokenizer_path,
            label="ENGLISH (ultra-clean)",
        )

    print("\nDone! Next step: run litgpt pretrain with the appropriate config.")


if __name__ == "__main__":
    main()