File size: 3,333 Bytes
6d5c79f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Tokenize cleaned corpora and emit binary shards for pretraining."""

from __future__ import annotations

import argparse
import json
import logging
from pathlib import Path

import numpy as np
import sentencepiece as spm

LOGGER = logging.getLogger(__name__)


def stream_records(path: Path):
    """Yield text records from JSONL."""

    with path.open("r", encoding="utf-8") as f:
        for line in f:
            if line.strip():
                record = json.loads(line)
                yield record.get("text", ""), record.get("kind", "general")


def shard_tokens(token_ids: list[int], shard_size: int, out_dir: Path, prefix: str) -> int:
    """Write token ids into uint32 binary shard files."""

    out_dir.mkdir(parents=True, exist_ok=True)
    count = 0
    for i in range(0, len(token_ids), shard_size):
        shard = np.array(token_ids[i : i + shard_size], dtype=np.uint32)
        out_file = out_dir / f"{prefix}_{count:06d}.bin"
        shard.tofile(out_file)
        count += 1
    return count


def tokenize_corpus(
    input_jsonl: Path,
    tokenizer_model: Path,
    out_dir: Path,
    shard_size: int,
    general_ratio: float,
    code_ratio: float,
) -> dict[str, int]:
    """Tokenize and split according to configured data mix."""

    sp = spm.SentencePieceProcessor(model_file=str(tokenizer_model))

    general_tokens: list[int] = []
    code_tokens: list[int] = []

    for text, kind in stream_records(input_jsonl):
        ids = sp.encode(text, out_type=int)
        if kind == "code":
            code_tokens.extend(ids)
        else:
            general_tokens.extend(ids)

    total = len(general_tokens) + len(code_tokens)
    if total == 0:
        raise ValueError("No tokens produced from dataset")

    target_general = int(total * general_ratio)
    target_code = int(total * code_ratio)

    mixed = general_tokens[:target_general] + code_tokens[:target_code]
    mixed_shards = shard_tokens(mixed, shard_size, out_dir / "pretrain", "mix")

    return {
        "total_tokens": len(mixed),
        "general_tokens_used": min(target_general, len(general_tokens)),
        "code_tokens_used": min(target_code, len(code_tokens)),
        "shards": mixed_shards,
    }


def parse_args() -> argparse.Namespace:
    """Parse CLI arguments."""

    parser = argparse.ArgumentParser(description="Tokenize cleaned data to binary shards")
    parser.add_argument("--input", type=Path, required=True)
    parser.add_argument("--tokenizer-model", type=Path, required=True)
    parser.add_argument("--out-dir", type=Path, required=True)
    parser.add_argument("--shard-size", type=int, default=4_000_000)
    parser.add_argument("--general-ratio", type=float, default=0.87)
    parser.add_argument("--code-ratio", type=float, default=0.13)
    return parser.parse_args()


def main() -> None:
    """CLI entrypoint."""

    logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s: %(message)s")
    args = parse_args()
    stats = tokenize_corpus(
        input_jsonl=args.input,
        tokenizer_model=args.tokenizer_model,
        out_dir=args.out_dir,
        shard_size=args.shard_size,
        general_ratio=args.general_ratio,
        code_ratio=args.code_ratio,
    )
    LOGGER.info("Tokenization complete: %s", stats)


if __name__ == "__main__":
    main()