File size: 4,427 Bytes
4ffdd01
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# SPDX-License-Identifier: Apache-2.0
"""Raon tokenizer (Qwen2 byte-level BPE, ``tokenizers`` library only) with the official special-token patch.

The shipped tokenizer files are outdated: the official code (``update_tokenizer`` / ``patch_tokenizer_files``,
modeling_raon.py 190-302) rewrites them at load so that the 12 Raon special tokens (``config.SPECIAL_TEXT``) encode
to their ids and are ``special``. We apply the same patch to the JSON *data* of ``tokenizer.json`` in memory (model
vocab entries + added-token entries, sorted by id) and load it with ``tokenizers.Tokenizer.from_str``; the patched
JSON is also saved to the cache (``RAON_CACHE_DIR/tokenizer/``) and is what the bundle ships.

``encode(text)`` = HF ``tokenizer.encode(text)`` (no BOS for Qwen2, added tokens atomic); ``decode(ids,
skip_special_tokens=True)`` = HF decode (``clean_up_tokenization_spaces`` is False in the shipped config).
"""

from __future__ import annotations

import json
import os
from typing import Iterable, List, Optional, Sequence

from ..config import SPECIAL_TEXT, resolve_weights


def patch_tokenizer_json(tj: dict) -> dict:
    """The official ``patch_tokenizer_files`` applied to a parsed ``tokenizer.json`` (returns a new dict)."""
    tj = json.loads(json.dumps(tj))
    vocab = tj.get("model", {}).get("vocab")
    if isinstance(vocab, dict):
        for text, tid in SPECIAL_TEXT.items():
            vocab[text] = tid
    by_id = {int(e["id"]): e for e in tj.get("added_tokens", [])}
    for text, tid in SPECIAL_TEXT.items():
        e = by_id.get(tid)
        if e is None:
            by_id[tid] = {"id": tid, "content": text, "single_word": False, "lstrip": False, "rstrip": False,
                          "normalized": False, "special": True}
        else:
            e.update(content=text, single_word=False, lstrip=False, rstrip=False, normalized=False, special=True)
    tj["added_tokens"] = [by_id[i] for i in sorted(by_id)]
    return tj


class RaonTokenizer:
    def __init__(self, model_dir: Optional[str] = None, tokenizer_json: Optional[str] = None):
        from tokenizers import Tokenizer

        if tokenizer_json is None:
            d = model_dir or resolve_weights("raon")
            with open(os.path.join(d, "tokenizer.json"), encoding="utf-8") as f:
                tj = patch_tokenizer_json(json.load(f))
            self.json = json.dumps(tj, ensure_ascii=False)
        else:
            with open(tokenizer_json, encoding="utf-8") as f:
                self.json = f.read()
        self.tok = Tokenizer.from_str(self.json)
        self.special_ids = frozenset(int(e["id"]) for e in json.loads(self.json)["added_tokens"] if e["special"])
        for text, tid in SPECIAL_TEXT.items():
            got = self.tok.encode(text, add_special_tokens=False).ids
            if got != [tid]:
                raise RuntimeError(f"tokenizer patch failed: {text!r} -> {got}, expected [{tid}]")

    def save(self, path: str) -> str:
        os.makedirs(os.path.dirname(path), exist_ok=True)
        tmp = path + f".tmp{os.getpid()}"
        with open(tmp, "w", encoding="utf-8") as f:
            f.write(self.json)
        os.replace(tmp, path)
        return path

    def encode(self, text: str) -> List[int]:
        return list(self.tok.encode(text, add_special_tokens=True).ids)

    def decode(self, ids: Iterable[int], skip_special_tokens: bool = True) -> str:
        return self.tok.decode([int(i) for i in ids], skip_special_tokens=skip_special_tokens)

    def id_to_token(self, i: int) -> Optional[str]:
        return self.tok.id_to_token(int(i))


class TextStreamer:
    """Incremental detokenizer for streaming text: ``push(ids) -> new text`` (holds back an incomplete UTF-8 tail,
    as HF ``TextStreamer`` does with the replacement character)."""

    def __init__(self, tok: RaonTokenizer, skip_special_tokens: bool = True):
        self.tok, self.skip = tok, skip_special_tokens
        self.ids: List[int] = []
        self.sent = 0

    def push(self, ids: Sequence[int]) -> str:
        self.ids.extend(int(i) for i in ids)
        text = self.tok.decode(self.ids, self.skip)
        if text.endswith("�"):
            return ""
        new = text[self.sent:]
        self.sent = len(text)
        return new

    def flush(self) -> str:
        text = self.tok.decode(self.ids, self.skip)
        new = text[self.sent:]
        self.sent = len(text)
        return new