tokenization_led.py 19 KB

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