# coding=utf-8
# Copyright 2021 T5 Authors and HuggingFace Inc. team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tokenization class for model ByT5."""
import warnings
from typing import List, Optional, Tuple
from transformers.tokenization_utils import AddedToken, PreTrainedTokenizer
from transformers.utils import logging
logger = logging.get_logger(__name__)
class UTF8LikeByteTokenizer(PreTrainedTokenizer):
"""
Construct a ByT5 tokenizer. ByT5 simply uses raw bytes utf-8 encoding.
This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to
this superclass for more information regarding those methods.
Args:
eos_token (`str`, *optional*, defaults to `""`):
The end of sequence token.
When building a sequence using special tokens, this is not the token that is used for the end of sequence.
The token used is the `sep_token`.
unk_token (`str`, *optional*, defaults to `""`):
The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
token instead.
pad_token (`str`, *optional*, defaults to `""`):
The token used for padding, for example when batching sequences of different lengths.
extra_ids (`int`, *optional*, defaults to 125):
Add a number of extra ids added to the end of the vocabulary for use as sentinels. These tokens are
accessible as "" where "{%d}" is a number between 0 and extra_ids-1. Extra tokens are
indexed from the end of the vocabulary up to beginning ("" is the last token in the vocabulary
like in ByT5 preprocessing see
[here](https://github.com/google-research/text-to-text-transfer-transformer/blob/9fd7b14a769417be33bc6c850f9598764913c833/t5/data/preprocessors.py#L2117)).
additional_special_tokens (`List[str]`, *optional*):
Additional special tokens used by the tokenizer.
"""
model_input_names = ["input_ids", "attention_mask"]
def __init__(
self,
bos_token="",
eos_token="",
pad_token="",
cls_token="",
sep_token="",
mask_token="",
extra_ids=26,
additional_special_tokens=None,
**kwargs,
) -> None:
# Add extra_ids to the special token list
if extra_ids > 0 and additional_special_tokens is None:
additional_special_tokens = [f"" for i in range(extra_ids)]
elif extra_ids > 0 and additional_special_tokens is not None and len(additional_special_tokens) > 0:
# Check that we have the right number of extra_id special tokens
extra_tokens = len(set(filter(lambda x: bool("extra_id" in str(x)), additional_special_tokens)))
if extra_tokens != extra_ids:
raise ValueError(
f"Both extra_ids ({extra_ids}) and additional_special_tokens ({additional_special_tokens}) are"
" provided to ByteTokenizer. In this case the additional_special_tokens must include the"
" extra_ids tokens"
)
bos_token = AddedToken(bos_token, lstrip=False, rstrip=False) if isinstance(bos_token, str) else bos_token
eos_token = AddedToken(eos_token, lstrip=False, rstrip=False) if isinstance(eos_token, str) else eos_token
pad_token = AddedToken(pad_token, lstrip=False, rstrip=False) if isinstance(pad_token, str) else pad_token
cls_token = AddedToken(cls_token, lstrip=False, rstrip=False) if isinstance(cls_token, str) else cls_token
sep_token = AddedToken(sep_token, lstrip=False, rstrip=False) if isinstance(sep_token, str) else sep_token
mask_token = AddedToken(mask_token, lstrip=False, rstrip=False) if isinstance(mask_token, str) else mask_token
# unk token needs to be in the vocab with correct index
self._added_tokens_decoder = {0: pad_token, 1: eos_token, 2: bos_token, 3: cls_token, 4: sep_token, 5: mask_token}
self.offset = len(self._added_tokens_decoder)
self._utf_vocab_size = 2**8 # utf is 8 bits
super().__init__(
bos_token=bos_token,
eos_token=eos_token,
pad_token=pad_token,
cls_token=cls_token,
sep_token=sep_token,
mask_token=mask_token,
extra_ids=0,
additional_special_tokens=additional_special_tokens, # TODO extra ids are not used :sweatywmile:
**kwargs,
)
@property
def vocab_size(self):
return self._utf_vocab_size
def get_vocab(self):
vocab = {
self.convert_ids_to_tokens(i): i for i in range(self.vocab_size + self.offset)
}
vocab.update(self.added_tokens_encoder)
return vocab
def _add_bos_if_not_present(self, token_ids: List[int]) -> List[int]:
"""Do not add bos again if user already added it."""
if len(token_ids) > 0 and token_ids[0] == self.bos_token_id:
warnings.warn(
f"This sequence already has {self.bos_token}. In future versions this behavior may lead to duplicated"
" bos tokens being added."
)
return token_ids
else:
return [self.bos_token_id] + token_ids
def _add_eos_if_not_present(self, token_ids: List[int]) -> List[int]:
"""Do not add eos again if user already added it."""
if len(token_ids) > 0 and token_ids[-1] == self.eos_token_id:
warnings.warn(
f"This sequence already has {self.eos_token}. In future versions this behavior may lead to duplicated"
" eos tokens being added."
)
return token_ids
else:
return token_ids + [self.eos_token_id]
def build_inputs_with_special_tokens(
self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
) -> List[int]:
"""
Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
adding special tokens. A sequence has the following format:
- single sequence: `X `
- pair of sequences: `A B `
Args:
token_ids_0 (`List[int]`):
List of IDs to which the special tokens will be added.
token_ids_1 (`List[int]`, *optional*):
Optional second list of IDs for sequence pairs.
Returns:
`List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
"""
token_ids_0 = self._add_bos_if_not_present(token_ids_0)
token_ids_0 = self._add_eos_if_not_present(token_ids_0)
if token_ids_1 is None:
return token_ids_0
else:
token_ids_1 = self._add_bos_if_not_present(token_ids_1)
token_ids_1 = self._add_eos_if_not_present(token_ids_1)
return token_ids_0 + token_ids_1
def _tokenize(self, text: str) -> List[str]:
"""Take as input a string and return a list of strings (tokens) for words/sub-words"""
token_ids = []
for c in text:
token_ids.extend(self.unicode_to_bytes(ord(c)))
# Convert to string
token_ids = [str(i) for i in token_ids]
return token_ids
def _convert_token_to_id(self, token):
"""Converts a token (str) in an id using the vocab."""
token_id = int(token) + self.offset
return token_id
def _convert_id_to_token(self, index):
"""Converts an index (integer) in a token (str) using the vocab."""
return str(index - self.offset)
def convert_tokens_to_string(self, tokens):
token_id_with_special_tokens = []
for token in tokens:
try:
token_id = int(token)
token_id_with_special_tokens.append(token_id)
except ValueError:
token_id_with_special_tokens.append(token)
return self.decode_ids(token_id_with_special_tokens)
def decode_ids(self, tokens: List[int]) -> str:
decoded = ""
i = 0
try:
while i < len(tokens):
if type(tokens[i]) == str:
decoded += tokens[i]
i += 1
continue
if tokens[i] < 0b10000000:
decoded += chr(tokens[i])
i += 1
elif tokens[i] < 0b11000000:
decoded += chr(((tokens[i] & 0b00111111) << 7) + (tokens[i + 1] & 0b01111111))
i += 2
elif tokens[i] < 0b11100000:
decoded += chr(((tokens[i] & 0b00011111) << 13) + ((tokens[i + 1] & 0b00111111) << 7) + (tokens[i + 2] & 0b01111111))
i += 3
elif tokens[i] < 0b11110000:
decoded += chr(
((tokens[i] & 0b00001111) << 18) + ((tokens[i + 1] & 0b00111111) << 13) + ((tokens[i + 2] & 0b00111111) << 7) + (tokens[i + 3] & 0b01111111)
)
i += 4
else:
raise ValueError("invalid token")
except IndexError:
pass
return decoded
def unicode_to_bytes(self, codepoint: int) -> list[int]:
codepoint_bin = f"{codepoint:b}"
if len(codepoint_bin) <= 7: # 1byte char
codepoint_bin = f"{codepoint:07b}"
bytes_bin = [
"0" + codepoint_bin,
]
elif len(codepoint_bin) <= 13: # 2byte char
codepoint_bin = f"{codepoint:013b}"
bytes_bin = [
"10" + codepoint_bin[:6],
"0" + codepoint_bin[6:],
]
elif len(codepoint_bin) <= 18: # 3byte char
codepoint_bin = f"{codepoint:018b}"
bytes_bin = [
"110" + codepoint_bin[:5],
"10" + codepoint_bin[5:11],
"0" + codepoint_bin[11:],
]
elif len(codepoint_bin) <= 22: # 4byte char
codepoint_bin = f"{codepoint:022b}"
bytes_bin = [
"1110" + codepoint_bin[:4],
"110" + codepoint_bin[4:9],
"10" + codepoint_bin[9:15],
"0" + codepoint_bin[15:],
]
else:
raise ValueError("codepoint is too large")
return [int(byte, 2) for byte in bytes_bin]
# ByteTokenizer has no vocab file
def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
return ()