|
| 1 | +import re |
| 2 | + |
| 3 | +from typing import Optional, Callable |
| 4 | + |
| 5 | +import numpy as np |
| 6 | + |
| 7 | +from ..internal import jsonl |
| 8 | +from ..internal.transformers import AutoTokenizer |
| 9 | + |
| 10 | +_IntOrIntList = int | list[int] |
| 11 | +_StrOrStrList = str | list[str] |
| 12 | + |
| 13 | + |
| 14 | +class Oracle: |
| 15 | + def __init__(self, *args, **kwargs): |
| 16 | + self._tok = AutoTokenizer.from_pretrained(*args, **kwargs) |
| 17 | + self._tok.model_max_length = 1 << 31 |
| 18 | + self.cls_token_id = self._tok.cls_token_id |
| 19 | + self.sep_token_id = self._tok.sep_token_id |
| 20 | + self.unk_token_id = self._tok.unk_token_id |
| 21 | + self.max_token_len = max( |
| 22 | + len(token) for token in self._tok.vocab |
| 23 | + ) |
| 24 | + self.max_try_split_len = min(self.max_token_len * 5, 100) |
| 25 | + self._log = jsonl.Writer(basename="oracle", with_timestamp=True) |
| 26 | + |
| 27 | + def close(self): |
| 28 | + self._log.close() |
| 29 | + |
| 30 | + @property |
| 31 | + def normalize_str(self) -> Callable[[str], str]: |
| 32 | + """Normalize the given string. |
| 33 | + """ |
| 34 | + return self._tok.backend_tokenizer.normalizer.normalize_str |
| 35 | + |
| 36 | + def encode(self, *args, **kwargs) -> list[int]: |
| 37 | + """Convert the given string to a list of integer token IDs. |
| 38 | + """ |
| 39 | + token_ids = self._tok.encode(*args, **kwargs) |
| 40 | + assert token_ids[0] == self.cls_token_id |
| 41 | + assert token_ids[-1] == self.sep_token_id |
| 42 | + return token_ids[1:-1] |
| 43 | + |
| 44 | + IDsToTokensType = Callable[[_IntOrIntList], _StrOrStrList] |
| 45 | + |
| 46 | + @property |
| 47 | + def convert_ids_to_tokens(self, *args, **kwargs) -> IDsToTokensType: |
| 48 | + """Convert the given list of token IDs to a list of tokens. |
| 49 | + """ |
| 50 | + return self._tok.convert_ids_to_tokens |
| 51 | + |
| 52 | + def tokenize(self, *args, **kwargs) -> list[str]: |
| 53 | + """Convert the given string into a list of tokens. |
| 54 | + """ |
| 55 | + return self.convert_ids_to_tokens(self.encode(*args, **kwargs)) |
| 56 | + |
| 57 | + @property |
| 58 | + def decode(self) -> Callable[[_IntOrIntList], str]: |
| 59 | + """Convert the given list of token IDs to a string. |
| 60 | + """ |
| 61 | + return self._tok.decode |
| 62 | + |
| 63 | + # For quick checks, see TextSplitter.BASE64_RE for the real deal |
| 64 | + _LOOSE_BASE64_RE = re.compile(r"^[A-Za-z0-9+/]+={0,2}$") |
| 65 | + |
| 66 | + def split_if_trivial( |
| 67 | + self, |
| 68 | + text: str, |
| 69 | + log_unhandled: bool = True, # XXX |
| 70 | + ) -> Optional[list[str]]: |
| 71 | + """Split a string into a list of tokens XXX IF! |
| 72 | +
|
| 73 | + Like `tokenize()` but it only returns if XXX. Otherwise None is |
| 74 | + returned. |
| 75 | + """ |
| 76 | + if len(text) > self.max_try_split_len: |
| 77 | + return None |
| 78 | + |
| 79 | + # Fast path for text that's in the oracle's vocabulary. |
| 80 | + if len(text) <= self.max_token_len and ( |
| 81 | + (text in self._tok.vocab |
| 82 | + or text.lower() in self._tok.vocab) |
| 83 | + and text.isalnum()): |
| 84 | + return [text] |
| 85 | + |
| 86 | + # Limit ourselves to base64-ish input, for now at least. |
| 87 | + if not self._LOOSE_BASE64_RE.match(text): |
| 88 | + raise NotImplementedError(text) |
| 89 | + |
| 90 | + token_ids = self.encode(text) |
| 91 | + if not token_ids or self.unk_token_id in token_ids: |
| 92 | + return None |
| 93 | + |
| 94 | + tokens = self.convert_ids_to_tokens(token_ids) |
| 95 | + word_pieces = [token.lstrip("#") for token in tokens] |
| 96 | + token_lengths = [len(token) for token in word_pieces] |
| 97 | + |
| 98 | + # If the tokens are mostly 2+ characters long and the |
| 99 | + # input text splits on whitespace in the same places as |
| 100 | + # the decoded token ID sequence then call this a match. |
| 101 | + # Subtracting the standard deviation prevents situations |
| 102 | + # where one long token skews the median away from a load |
| 103 | + # of 1-2 character tokens, e.g. "electronically8eb5e30da" |
| 104 | + # tokenizes to ["electronically", "8", "eb", "5", "e", |
| 105 | + # "30", "da"] with bert-base-uncased, so a median token |
| 106 | + # length of 2 characters/token and a mean of 3.3, but |
| 107 | + # the standard deviation of 4.4 indicates at least one |
| 108 | + # token is very far from the mean. |
| 109 | + median_length = np.median(token_lengths) |
| 110 | + length_stddev = np.std(token_lengths) |
| 111 | + if median_length - length_stddev > 1: |
| 112 | + result = text.split() |
| 113 | + want = [token.lower() for token in result] |
| 114 | + if self.decode(token_ids).split() == want: |
| 115 | + return result |
| 116 | + |
| 117 | + print(f"tokens: {tokens}"[:80]) |
| 118 | + |
| 119 | + first_token_id = token_ids[0] |
| 120 | + first_token = self.convert_ids_to_tokens(first_token_id) |
| 121 | + assert "#" not in first_token |
| 122 | + print(f"first_token: {first_token!r} ({first_token_id})") |
| 123 | + |
| 124 | + chars_per_token = len(text) / len(token_ids) |
| 125 | + |
| 126 | + #mean = sum(token_lengths) / len(token_ids) |
| 127 | + print("chars_per_token:", chars_per_token) |
| 128 | + #print("or ------> mean:", mean) |
| 129 | + print(" median:", median_length) |
| 130 | + print(" std.dev:", length_stddev) |
| 131 | + print() |
| 132 | + |
| 133 | + # XXX now what? |
| 134 | + if log_unhandled: |
| 135 | + self._log.write( |
| 136 | + text=text, token_ids=token_ids, |
| 137 | + tokens=tokens, |
| 138 | + decoded=self.decode(token_ids), |
| 139 | + chars_per_token=chars_per_token, |
| 140 | + ) |
| 141 | + return None |
0 commit comments