File size: 2,110 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
from __future__ import annotations

import argparse
import json
from pathlib import Path

import numpy as np
from transformers import AutoTokenizer

from kawk50m.cli import configure_utf8_stdio
from scripts.tokenize_corpus import tokenize_split


def parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser(
        description="Tokenize one clean JSONL shard into a uint16 token part."
    )
    parser.add_argument("--input", required=True)
    parser.add_argument("--tokenizer-dir", required=True)
    parser.add_argument("--output", required=True)
    parser.add_argument("--batch-size", type=int, default=64)
    return parser.parse_args()


def main() -> None:
    configure_utf8_stdio()
    args = parse_args()
    input_path = Path(args.input)
    output_path = Path(args.output)
    metadata_path = output_path.with_suffix(".json")
    if not input_path.is_file():
        raise FileNotFoundError(input_path)
    if output_path.exists() or metadata_path.exists():
        raise FileExistsError(f"Refusing to overwrite token part: {output_path}")
    if args.batch_size <= 0:
        raise ValueError("--batch-size must be positive")

    output_path.parent.mkdir(parents=True, exist_ok=True)
    tokenizer = AutoTokenizer.from_pretrained(
        args.tokenizer_dir, use_fast=False, legacy=True
    )
    tokenizer.model_max_length = int(1e30)
    if len(tokenizer) > np.iinfo(np.uint16).max:
        raise ValueError("uint16 output requires a vocabulary no larger than 65,535")
    if tokenizer.eos_token_id is None:
        raise ValueError("Tokenizer must define eos_token_id")

    summary = tokenize_split(
        split=input_path.stem,
        paths=[input_path],
        tokenizer=tokenizer,
        output_path=output_path,
        batch_size=args.batch_size,
        max_tokens=None,
    )
    summary["input"] = str(input_path)
    with metadata_path.open("w", encoding="utf-8") as handle:
        json.dump(summary, handle, ensure_ascii=False, indent=2)
        handle.write("\n")
    print(json.dumps(summary, ensure_ascii=False))


if __name__ == "__main__":
    main()