tokenization_deberta.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393
  1. # coding=utf-8
  2. # Copyright 2020 Microsoft and the HuggingFace Inc. team.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. """Tokenization class for model DeBERTa."""
  16. import json
  17. import os
  18. from typing import List, Optional, Tuple
  19. import regex as re
  20. from ...tokenization_utils import AddedToken, PreTrainedTokenizer
  21. from ...utils import logging
  22. logger = logging.get_logger(__name__)
  23. VOCAB_FILES_NAMES = {"vocab_file": "vocab.json", "merges_file": "merges.txt"}
  24. # Copied from transformers.models.gpt2.tokenization_gpt2.bytes_to_unicode
  25. def bytes_to_unicode():
  26. """
  27. Returns list of utf-8 byte and a mapping to unicode strings. We specifically avoids mapping to whitespace/control
  28. characters the bpe code barfs on.
  29. The reversible bpe codes work on unicode strings. This means you need a large # of unicode characters in your vocab
  30. if you want to avoid UNKs. When you're at something like a 10B token dataset you end up needing around 5K for
  31. decent coverage. This is a significant percentage of your normal, say, 32K bpe vocab. To avoid that, we want lookup
  32. tables between utf-8 bytes and unicode strings.
  33. """
  34. bs = (
  35. list(range(ord("!"), ord("~") + 1)) + list(range(ord("¡"), ord("¬") + 1)) + list(range(ord("®"), ord("ÿ") + 1))
  36. )
  37. cs = bs[:]
  38. n = 0
  39. for b in range(2**8):
  40. if b not in bs:
  41. bs.append(b)
  42. cs.append(2**8 + n)
  43. n += 1
  44. cs = [chr(n) for n in cs]
  45. return dict(zip(bs, cs))
  46. # Copied from transformers.models.gpt2.tokenization_gpt2.get_pairs
  47. def get_pairs(word):
  48. """
  49. Return set of symbol pairs in a word.
  50. Word is represented as tuple of symbols (symbols being variable-length strings).
  51. """
  52. pairs = set()
  53. prev_char = word[0]
  54. for char in word[1:]:
  55. pairs.add((prev_char, char))
  56. prev_char = char
  57. return pairs
  58. class DebertaTokenizer(PreTrainedTokenizer):
  59. """
  60. Construct a DeBERTa tokenizer. Based on byte-level Byte-Pair-Encoding.
  61. This tokenizer has been trained to treat spaces like parts of the tokens (a bit like sentencepiece) so a word will
  62. be encoded differently whether it is at the beginning of the sentence (without space) or not:
  63. ```python
  64. >>> from transformers import DebertaTokenizer
  65. >>> tokenizer = DebertaTokenizer.from_pretrained("microsoft/deberta-base")
  66. >>> tokenizer("Hello world")["input_ids"]
  67. [1, 31414, 232, 2]
  68. >>> tokenizer(" Hello world")["input_ids"]
  69. [1, 20920, 232, 2]
  70. ```
  71. You can get around that behavior by passing `add_prefix_space=True` when instantiating this tokenizer or when you
  72. call it on some text, but since the model was not pretrained this way, it might yield a decrease in performance.
  73. <Tip>
  74. When used with `is_split_into_words=True`, this tokenizer will add a space before each word (even the first one).
  75. </Tip>
  76. This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to
  77. this superclass for more information regarding those methods.
  78. Args:
  79. vocab_file (`str`):
  80. Path to the vocabulary file.
  81. merges_file (`str`):
  82. Path to the merges file.
  83. errors (`str`, *optional*, defaults to `"replace"`):
  84. Paradigm to follow when decoding bytes to UTF-8. See
  85. [bytes.decode](https://docs.python.org/3/library/stdtypes.html#bytes.decode) for more information.
  86. bos_token (`str`, *optional*, defaults to `"[CLS]"`):
  87. The beginning of sequence token.
  88. eos_token (`str`, *optional*, defaults to `"[SEP]"`):
  89. The end of sequence token.
  90. sep_token (`str`, *optional*, defaults to `"[SEP]"`):
  91. The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
  92. sequence classification or for a text and a question for question answering. It is also used as the last
  93. token of a sequence built with special tokens.
  94. cls_token (`str`, *optional*, defaults to `"[CLS]"`):
  95. The classifier token which is used when doing sequence classification (classification of the whole sequence
  96. instead of per-token classification). It is the first token of the sequence when built with special tokens.
  97. unk_token (`str`, *optional*, defaults to `"[UNK]"`):
  98. The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
  99. token instead.
  100. pad_token (`str`, *optional*, defaults to `"[PAD]"`):
  101. The token used for padding, for example when batching sequences of different lengths.
  102. mask_token (`str`, *optional*, defaults to `"[MASK]"`):
  103. The token used for masking values. This is the token used when training this model with masked language
  104. modeling. This is the token which the model will try to predict.
  105. add_prefix_space (`bool`, *optional*, defaults to `False`):
  106. Whether or not to add an initial space to the input. This allows to treat the leading word just as any
  107. other word. (Deberta tokenizer detect beginning of words by the preceding space).
  108. add_bos_token (`bool`, *optional*, defaults to `False`):
  109. Whether or not to add an initial <|endoftext|> to the input. This allows to treat the leading word just as
  110. any other word.
  111. """
  112. vocab_files_names = VOCAB_FILES_NAMES
  113. model_input_names = ["input_ids", "attention_mask", "token_type_ids"]
  114. def __init__(
  115. self,
  116. vocab_file,
  117. merges_file,
  118. errors="replace",
  119. bos_token="[CLS]",
  120. eos_token="[SEP]",
  121. sep_token="[SEP]",
  122. cls_token="[CLS]",
  123. unk_token="[UNK]",
  124. pad_token="[PAD]",
  125. mask_token="[MASK]",
  126. add_prefix_space=False,
  127. add_bos_token=False,
  128. **kwargs,
  129. ):
  130. bos_token = AddedToken(bos_token, special=True) if isinstance(bos_token, str) else bos_token
  131. eos_token = AddedToken(eos_token, special=True) if isinstance(eos_token, str) else eos_token
  132. sep_token = AddedToken(sep_token, special=True) if isinstance(sep_token, str) else sep_token
  133. cls_token = AddedToken(cls_token, special=True) if isinstance(cls_token, str) else cls_token
  134. unk_token = AddedToken(unk_token, special=True) if isinstance(unk_token, str) else unk_token
  135. pad_token = AddedToken(pad_token, special=True) if isinstance(pad_token, str) else pad_token
  136. # Mask token behave like a normal word, i.e. include the space before it
  137. mask_token = AddedToken(mask_token, lstrip=True, rstrip=False) if isinstance(mask_token, str) else mask_token
  138. self.add_bos_token = add_bos_token
  139. with open(vocab_file, encoding="utf-8") as vocab_handle:
  140. self.encoder = json.load(vocab_handle)
  141. self.decoder = {v: k for k, v in self.encoder.items()}
  142. self.errors = errors # how to handle errors in decoding
  143. self.byte_encoder = bytes_to_unicode()
  144. self.byte_decoder = {v: k for k, v in self.byte_encoder.items()}
  145. with open(merges_file, encoding="utf-8") as merges_handle:
  146. bpe_merges = merges_handle.read().split("\n")[1:-1]
  147. bpe_merges = [tuple(merge.split()) for merge in bpe_merges]
  148. self.bpe_ranks = dict(zip(bpe_merges, range(len(bpe_merges))))
  149. self.cache = {}
  150. self.add_prefix_space = add_prefix_space
  151. # Should have added re.IGNORECASE so BPE merges can happen for capitalized versions of contractions
  152. self.pat = re.compile(r"""'s|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+""")
  153. super().__init__(
  154. errors=errors,
  155. bos_token=bos_token,
  156. eos_token=eos_token,
  157. unk_token=unk_token,
  158. sep_token=sep_token,
  159. cls_token=cls_token,
  160. pad_token=pad_token,
  161. mask_token=mask_token,
  162. add_prefix_space=add_prefix_space,
  163. add_bos_token=add_bos_token,
  164. **kwargs,
  165. )
  166. @property
  167. # Copied from transformers.models.gpt2.tokenization_gpt2.GPT2Tokenizer.vocab_size
  168. def vocab_size(self):
  169. return len(self.encoder)
  170. # Copied from transformers.models.gpt2.tokenization_gpt2.GPT2Tokenizer.get_vocab
  171. def get_vocab(self):
  172. return dict(self.encoder, **self.added_tokens_encoder)
  173. # Copied from transformers.models.gpt2.tokenization_gpt2.GPT2Tokenizer.bpe
  174. def bpe(self, token):
  175. if token in self.cache:
  176. return self.cache[token]
  177. word = tuple(token)
  178. pairs = get_pairs(word)
  179. if not pairs:
  180. return token
  181. while True:
  182. bigram = min(pairs, key=lambda pair: self.bpe_ranks.get(pair, float("inf")))
  183. if bigram not in self.bpe_ranks:
  184. break
  185. first, second = bigram
  186. new_word = []
  187. i = 0
  188. while i < len(word):
  189. try:
  190. j = word.index(first, i)
  191. except ValueError:
  192. new_word.extend(word[i:])
  193. break
  194. else:
  195. new_word.extend(word[i:j])
  196. i = j
  197. if word[i] == first and i < len(word) - 1 and word[i + 1] == second:
  198. new_word.append(first + second)
  199. i += 2
  200. else:
  201. new_word.append(word[i])
  202. i += 1
  203. new_word = tuple(new_word)
  204. word = new_word
  205. if len(word) == 1:
  206. break
  207. else:
  208. pairs = get_pairs(word)
  209. word = " ".join(word)
  210. self.cache[token] = word
  211. return word
  212. def build_inputs_with_special_tokens(
  213. self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
  214. ) -> List[int]:
  215. """
  216. Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
  217. adding special tokens. A DeBERTa sequence has the following format:
  218. - single sequence: [CLS] X [SEP]
  219. - pair of sequences: [CLS] A [SEP] B [SEP]
  220. Args:
  221. token_ids_0 (`List[int]`):
  222. List of IDs to which the special tokens will be added.
  223. token_ids_1 (`List[int]`, *optional*):
  224. Optional second list of IDs for sequence pairs.
  225. Returns:
  226. `List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
  227. """
  228. if token_ids_1 is None:
  229. return [self.cls_token_id] + token_ids_0 + [self.sep_token_id]
  230. cls = [self.cls_token_id]
  231. sep = [self.sep_token_id]
  232. return cls + token_ids_0 + sep + token_ids_1 + sep
  233. def get_special_tokens_mask(
  234. self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None, already_has_special_tokens: bool = False
  235. ) -> List[int]:
  236. """
  237. Retrieves sequence ids from a token list that has no special tokens added. This method is called when adding
  238. special tokens using the tokenizer `prepare_for_model` or `encode_plus` methods.
  239. Args:
  240. token_ids_0 (`List[int]`):
  241. List of IDs.
  242. token_ids_1 (`List[int]`, *optional*):
  243. Optional second list of IDs for sequence pairs.
  244. already_has_special_tokens (`bool`, *optional*, defaults to `False`):
  245. Whether or not the token list is already formatted with special tokens for the model.
  246. Returns:
  247. `List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
  248. """
  249. if already_has_special_tokens:
  250. return super().get_special_tokens_mask(
  251. token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
  252. )
  253. if token_ids_1 is None:
  254. return [1] + ([0] * len(token_ids_0)) + [1]
  255. return [1] + ([0] * len(token_ids_0)) + [1] + ([0] * len(token_ids_1)) + [1]
  256. def create_token_type_ids_from_sequences(
  257. self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
  258. ) -> List[int]:
  259. """
  260. Create a mask from the two sequences passed to be used in a sequence-pair classification task. A DeBERTa
  261. sequence pair mask has the following format:
  262. ```
  263. 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1
  264. | first sequence | second sequence |
  265. ```
  266. If `token_ids_1` is `None`, this method only returns the first portion of the mask (0s).
  267. Args:
  268. token_ids_0 (`List[int]`):
  269. List of IDs.
  270. token_ids_1 (`List[int]`, *optional*):
  271. Optional second list of IDs for sequence pairs.
  272. Returns:
  273. `List[int]`: List of [token type IDs](../glossary#token-type-ids) according to the given sequence(s).
  274. """
  275. sep = [self.sep_token_id]
  276. cls = [self.cls_token_id]
  277. if token_ids_1 is None:
  278. return len(cls + token_ids_0 + sep) * [0]
  279. return len(cls + token_ids_0 + sep) * [0] + len(token_ids_1 + sep) * [1]
  280. # Copied from transformers.models.gpt2.tokenization_gpt2.GPT2Tokenizer._tokenize
  281. def _tokenize(self, text):
  282. """Tokenize a string."""
  283. bpe_tokens = []
  284. for token in re.findall(self.pat, text):
  285. token = "".join(
  286. self.byte_encoder[b] for b in token.encode("utf-8")
  287. ) # Maps all our bytes to unicode strings, avoiding control tokens of the BPE (spaces in our case)
  288. bpe_tokens.extend(bpe_token for bpe_token in self.bpe(token).split(" "))
  289. return bpe_tokens
  290. # Copied from transformers.models.gpt2.tokenization_gpt2.GPT2Tokenizer._convert_token_to_id
  291. def _convert_token_to_id(self, token):
  292. """Converts a token (str) in an id using the vocab."""
  293. return self.encoder.get(token, self.encoder.get(self.unk_token))
  294. # Copied from transformers.models.gpt2.tokenization_gpt2.GPT2Tokenizer._convert_id_to_token
  295. def _convert_id_to_token(self, index):
  296. """Converts an index (integer) in a token (str) using the vocab."""
  297. return self.decoder.get(index)
  298. # Copied from transformers.models.gpt2.tokenization_gpt2.GPT2Tokenizer.convert_tokens_to_string
  299. def convert_tokens_to_string(self, tokens):
  300. """Converts a sequence of tokens (string) in a single string."""
  301. text = "".join(tokens)
  302. text = bytearray([self.byte_decoder[c] for c in text]).decode("utf-8", errors=self.errors)
  303. return text
  304. # Copied from transformers.models.gpt2.tokenization_gpt2.GPT2Tokenizer.save_vocabulary
  305. def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
  306. if not os.path.isdir(save_directory):
  307. logger.error(f"Vocabulary path ({save_directory}) should be a directory")
  308. return
  309. vocab_file = os.path.join(
  310. save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
  311. )
  312. merge_file = os.path.join(
  313. save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["merges_file"]
  314. )
  315. with open(vocab_file, "w", encoding="utf-8") as f:
  316. f.write(json.dumps(self.encoder, indent=2, sort_keys=True, ensure_ascii=False) + "\n")
  317. index = 0
  318. with open(merge_file, "w", encoding="utf-8") as writer:
  319. writer.write("#version: 0.2\n")
  320. for bpe_tokens, token_index in sorted(self.bpe_ranks.items(), key=lambda kv: kv[1]):
  321. if index != token_index:
  322. logger.warning(
  323. f"Saving vocabulary to {merge_file}: BPE merge indices are not consecutive."
  324. " Please check that the tokenizer is not corrupted!"
  325. )
  326. index = token_index
  327. writer.write(" ".join(bpe_tokens) + "\n")
  328. index += 1
  329. return vocab_file, merge_file
  330. def prepare_for_tokenization(self, text, is_split_into_words=False, **kwargs):
  331. add_prefix_space = kwargs.pop("add_prefix_space", self.add_prefix_space)
  332. if (is_split_into_words or add_prefix_space) and (len(text) > 0 and not text[0].isspace()):
  333. text = " " + text
  334. return (text, kwargs)