File size: 8,413 Bytes
91ac3cc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from __future__ import annotations

import argparse
import json
import os
import random
from collections.abc import Iterator
from pathlib import Path

import sentencepiece as spm
from tqdm import tqdm
from transformers import LlamaTokenizer

from kawk50m.cli import configure_utf8_stdio
from kawk50m.io import discover_paths, iter_documents


def parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser(
        description="Train a Korean SentencePiece Unigram tokenizer."
    )
    parser.add_argument(
        "--input",
        nargs="+",
        default=["data/clean/train-*.jsonl"],
        help="Clean training shards or glob patterns.",
    )
    parser.add_argument("--output-dir", default="artifacts/tokenizer-20k")
    parser.add_argument("--vocab-size", type=int, default=20_000)
    parser.add_argument("--max-sentences", type=int, default=2_000_000)
    parser.add_argument(
        "--min-sentences",
        type=int,
        default=1_000,
        help="Safety floor; lower only for a synthetic smoke test.",
    )
    parser.add_argument("--max-line-chars", type=int, default=4096)
    parser.add_argument("--seed", type=int, default=42)
    parser.add_argument("--model-max-length", type=int, default=1024)
    parser.add_argument("--text-field", default="text")
    parser.add_argument("--num-threads", type=int, default=os.cpu_count() or 1)
    parser.add_argument(
        "--reuse-model",
        action="store_true",
        help=(
            "Reuse an existing tokenizer.model/tokenizer.vocab in --output-dir "
            "and rebuild only the Hugging Face wrapper files."
        ),
    )
    parser.add_argument(
        "--training-lines",
        type=int,
        default=None,
        help="Original SentencePiece line count recorded with --reuse-model.",
    )
    return parser.parse_args()


def chunks(text: str, max_chars: int) -> Iterator[str]:
    for paragraph in text.splitlines():
        paragraph = paragraph.strip()
        if not paragraph:
            continue
        for start in range(0, len(paragraph), max_chars):
            piece = paragraph[start : start + max_chars].strip()
            if piece:
                yield piece


def main() -> None:
    configure_utf8_stdio()
    args = parse_args()
    if args.vocab_size <= 300:
        raise ValueError("--vocab-size must exceed 300 when byte fallback is enabled")
    if args.max_sentences <= 0:
        raise ValueError("--max-sentences must be positive")

    paths = discover_paths(args.input)
    if not paths:
        raise FileNotFoundError("No tokenizer training inputs were found")
    random.Random(args.seed).shuffle(paths)

    output_dir = Path(args.output_dir)
    output_dir.mkdir(parents=True, exist_ok=True)
    model_path = output_dir / "tokenizer.model"
    generated_paths = [
        output_dir / "tokenizer.model",
        output_dir / "tokenizer.vocab",
        output_dir / "tokenizer_config.json",
        output_dir / "training_metadata.json",
    ]
    existing_generated = [path for path in generated_paths if path.exists()]
    if existing_generated and not args.reuse_model:
        raise FileExistsError(
            f"{existing_generated[0]} already exists. "
            "Choose a new output directory to avoid overwriting tokenizer artifacts."
        )
    if args.reuse_model:
        if not model_path.is_file() or not (output_dir / "tokenizer.vocab").is_file():
            raise FileNotFoundError(
                "--reuse-model requires tokenizer.model and tokenizer.vocab"
            )
        for stale_wrapper in (
            output_dir / "tokenizer.json",
            output_dir / "tokenizer_config.json",
            output_dir / "special_tokens_map.json",
            output_dir / "training_metadata.json",
        ):
            stale_wrapper.unlink(missing_ok=True)
    temporary_corpus = output_dir / ".sentencepiece_input.tmp"

    sentence_count = args.training_lines if args.reuse_model else 0
    if not args.reuse_model:
        try:
            with temporary_corpus.open("w", encoding="utf-8", newline="\n") as handle:
                documents = iter_documents(paths, text_field=args.text_field)
                progress = tqdm(total=args.max_sentences, unit="lines")
                for document in documents:
                    for line in chunks(document["text"], args.max_line_chars):
                        handle.write(line.replace("\n", " "))
                        handle.write("\n")
                        sentence_count += 1
                        progress.update(1)
                        if sentence_count >= args.max_sentences:
                            break
                    if sentence_count >= args.max_sentences:
                        break
                progress.close()

            if sentence_count < args.min_sentences:
                raise ValueError(
                    f"Only {sentence_count} lines were found; "
                    f"at least {args.min_sentences} are required"
                )

            spm.SentencePieceTrainer.train(
                input=str(temporary_corpus),
                model_prefix=str(output_dir / "tokenizer"),
                model_type="unigram",
                vocab_size=args.vocab_size,
                character_coverage=1.0,
                normalization_rule_name="identity",
                byte_fallback=True,
                split_digits=True,
                unk_id=0,
                bos_id=1,
                eos_id=2,
                pad_id=3,
                unk_piece="<unk>",
                bos_piece="<s>",
                eos_piece="</s>",
                pad_piece="<pad>",
                user_defined_symbols=["<EMAIL>", "<PHONE>", "<RRN>"],
                input_sentence_size=0,
                shuffle_input_sentence=False,
                max_sentence_length=max(args.max_line_chars * 2, 8192),
                num_threads=args.num_threads,
                train_extremely_large_corpus=True,
                hard_vocab_limit=True,
            )
        finally:
            temporary_corpus.unlink(missing_ok=True)

    tokenizer = LlamaTokenizer(
        vocab_file=str(model_path),
        unk_token="<unk>",
        bos_token="<s>",
        eos_token="</s>",
        pad_token="<pad>",
        add_bos_token=True,
        add_eos_token=False,
        model_max_length=args.model_max_length,
        clean_up_tokenization_spaces=False,
        legacy=True,
    )
    tokenizer.padding_side = "right"
    tokenizer.save_pretrained(output_dir)
    if len(tokenizer) != args.vocab_size:
        raise RuntimeError(
            f"Expected {args.vocab_size} tokens, tokenizer has {len(tokenizer)}"
        )

    probes = [
        "안녕하세요. 오늘 날씨가 좋습니다.",
        "이거 진짜 되는 거 맞아? ㅋㅋㅋㅋ",
        "갤럭시 S26을 2026년에 구매했습니다.",
        "KTX를 타고 부산에 내려갔다. 🚄",
    ]
    round_trip = []
    for text in probes:
        token_ids = tokenizer.encode(text, add_special_tokens=False)
        decoded = tokenizer.decode(
            token_ids, skip_special_tokens=False, clean_up_tokenization_spaces=False
        )
        round_trip.append(
            {
                "text": text,
                "tokens": len(token_ids),
                "unknown_tokens": token_ids.count(tokenizer.unk_token_id),
                "decoded": decoded,
                "exact_round_trip": decoded == text,
            }
        )

    metadata = {
        "type": "SentencePiece Unigram",
        "vocab_size": len(tokenizer),
        "normalization": "external NFC + SentencePiece identity",
        "byte_fallback": True,
        "split_digits": True,
        "training_lines": sentence_count,
        "reused_sentencepiece_model": args.reuse_model,
        "model_max_length": args.model_max_length,
        "special_token_ids": {
            "unk": tokenizer.unk_token_id,
            "bos": tokenizer.bos_token_id,
            "eos": tokenizer.eos_token_id,
            "pad": tokenizer.pad_token_id,
        },
        "probes": round_trip,
    }
    with (output_dir / "training_metadata.json").open(
        "w", encoding="utf-8"
    ) as handle:
        json.dump(metadata, handle, ensure_ascii=False, indent=2)
        handle.write("\n")
    print(json.dumps(metadata, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()