Encodes a string into a list of token IDs. Args: s (str): The input string to be encoded. bos (bool): Whether to prepend the beginning-of-sequence token. eos (bool): Whether to append the end-of-sequence token. allowed_special ("all"|
(
self,
s: str,
*,
bos: bool,
eos: bool,
allowed_special: Optional[Union[Literal["all"], AbstractSet[str]]] = None,
disallowed_special: Union[Literal["all"], Collection[str]] = (),
)
| 117 | ] |
| 118 | |
| 119 | def encode( |
| 120 | self, |
| 121 | s: str, |
| 122 | *, |
| 123 | bos: bool, |
| 124 | eos: bool, |
| 125 | allowed_special: Optional[Union[Literal["all"], AbstractSet[str]]] = None, |
| 126 | disallowed_special: Union[Literal["all"], Collection[str]] = (), |
| 127 | ) -> List[int]: |
| 128 | """ |
| 129 | Encodes a string into a list of token IDs. |
| 130 | |
| 131 | Args: |
| 132 | s (str): The input string to be encoded. |
| 133 | bos (bool): Whether to prepend the beginning-of-sequence token. |
| 134 | eos (bool): Whether to append the end-of-sequence token. |
| 135 | allowed_special ("all"|set[str]): allowed special tokens in string |
| 136 | disallowed_special ("all"|set[str]): special tokens that raise an error when in string |
| 137 | |
| 138 | Returns: |
| 139 | list[int]: A list of token IDs. |
| 140 | |
| 141 | By default, setting disallowed_special=() encodes a string by ignoring |
| 142 | special tokens. Specifically: |
| 143 | - Setting `disallowed_special` to () will cause all text corresponding |
| 144 | to special tokens to be encoded as natural text (insteading of raising |
| 145 | an error). |
| 146 | - Setting `allowed_special` to "all" will treat all text corresponding |
| 147 | to special tokens to be encoded as special tokens. |
| 148 | """ |
| 149 | if allowed_special is None: |
| 150 | allowed_special = set() |
| 151 | assert type(s) is str |
| 152 | |
| 153 | substrs = ( |
| 154 | substr |
| 155 | for i in range(0, len(s), TIKTOKEN_MAX_ENCODE_CHARS) |
| 156 | for substr in self._split_whitespaces_or_nonwhitespaces( |
| 157 | s[i : i + TIKTOKEN_MAX_ENCODE_CHARS], MAX_NO_WHITESPACES_CHARS |
| 158 | ) |
| 159 | ) |
| 160 | t: List[int] = [] |
| 161 | for substr in substrs: |
| 162 | t.extend( |
| 163 | self.model.encode( |
| 164 | substr, |
| 165 | allowed_special=allowed_special, |
| 166 | disallowed_special=disallowed_special, |
| 167 | ) |
| 168 | ) |
| 169 | if bos: |
| 170 | t.insert(0, self.bos_id) |
| 171 | if eos: |
| 172 | t.append(self.eos_id) |
| 173 | return t |
| 174 | |
| 175 | def decode(self, t: Sequence[int]) -> str: |
| 176 | """ |