Download scripts/train_tokenizer.py from Infinity08/KAWK50M-Project: direct link, hf CLI and curl.
- Browser
- Download file 8.41 kB
-
https://huggingface.co/datasets/Infinity08/KAWK50M-Project/resolve/main/scripts/train_tokenizer.py
- Command line
-
hf download hf://datasets/Infinity08/KAWK50M-Project/scripts/train_tokenizer.py
-
curl -L -o train_tokenizer.py https://huggingface.co/datasets/Infinity08/KAWK50M-Project/resolve/main/scripts/train_tokenizer.py
8.41 kB
| 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() | |