tokenization_luke.py 84 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728
  1. # coding=utf-8
  2. # Copyright Studio-Ouisa 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 LUKE."""
  16. import itertools
  17. import json
  18. import os
  19. from collections.abc import Mapping
  20. from functools import lru_cache
  21. from typing import Dict, List, Optional, Tuple, Union
  22. import numpy as np
  23. import regex as re
  24. from ...tokenization_utils import PreTrainedTokenizer
  25. from ...tokenization_utils_base import (
  26. ENCODE_KWARGS_DOCSTRING,
  27. AddedToken,
  28. BatchEncoding,
  29. EncodedInput,
  30. PaddingStrategy,
  31. TensorType,
  32. TextInput,
  33. TextInputPair,
  34. TruncationStrategy,
  35. to_py_obj,
  36. )
  37. from ...utils import add_end_docstrings, is_tf_tensor, is_torch_tensor, logging
  38. logger = logging.get_logger(__name__)
  39. EntitySpan = Tuple[int, int]
  40. EntitySpanInput = List[EntitySpan]
  41. Entity = str
  42. EntityInput = List[Entity]
  43. VOCAB_FILES_NAMES = {
  44. "vocab_file": "vocab.json",
  45. "merges_file": "merges.txt",
  46. "entity_vocab_file": "entity_vocab.json",
  47. }
  48. ENCODE_PLUS_ADDITIONAL_KWARGS_DOCSTRING = r"""
  49. return_token_type_ids (`bool`, *optional*):
  50. Whether to return token type IDs. If left to the default, will return the token type IDs according to
  51. the specific tokenizer's default, defined by the `return_outputs` attribute.
  52. [What are token type IDs?](../glossary#token-type-ids)
  53. return_attention_mask (`bool`, *optional*):
  54. Whether to return the attention mask. If left to the default, will return the attention mask according
  55. to the specific tokenizer's default, defined by the `return_outputs` attribute.
  56. [What are attention masks?](../glossary#attention-mask)
  57. return_overflowing_tokens (`bool`, *optional*, defaults to `False`):
  58. Whether or not to return overflowing token sequences. If a pair of sequences of input ids (or a batch
  59. of pairs) is provided with `truncation_strategy = longest_first` or `True`, an error is raised instead
  60. of returning overflowing tokens.
  61. return_special_tokens_mask (`bool`, *optional*, defaults to `False`):
  62. Whether or not to return special tokens mask information.
  63. return_offsets_mapping (`bool`, *optional*, defaults to `False`):
  64. Whether or not to return `(char_start, char_end)` for each token.
  65. This is only available on fast tokenizers inheriting from [`PreTrainedTokenizerFast`], if using
  66. Python's tokenizer, this method will raise `NotImplementedError`.
  67. return_length (`bool`, *optional*, defaults to `False`):
  68. Whether or not to return the lengths of the encoded inputs.
  69. verbose (`bool`, *optional*, defaults to `True`):
  70. Whether or not to print more information and warnings.
  71. **kwargs: passed to the `self.tokenize()` method
  72. Return:
  73. [`BatchEncoding`]: A [`BatchEncoding`] with the following fields:
  74. - **input_ids** -- List of token ids to be fed to a model.
  75. [What are input IDs?](../glossary#input-ids)
  76. - **token_type_ids** -- List of token type ids to be fed to a model (when `return_token_type_ids=True` or
  77. if *"token_type_ids"* is in `self.model_input_names`).
  78. [What are token type IDs?](../glossary#token-type-ids)
  79. - **attention_mask** -- List of indices specifying which tokens should be attended to by the model (when
  80. `return_attention_mask=True` or if *"attention_mask"* is in `self.model_input_names`).
  81. [What are attention masks?](../glossary#attention-mask)
  82. - **entity_ids** -- List of entity ids to be fed to a model.
  83. [What are input IDs?](../glossary#input-ids)
  84. - **entity_position_ids** -- List of entity positions in the input sequence to be fed to a model.
  85. - **entity_token_type_ids** -- List of entity token type ids to be fed to a model (when
  86. `return_token_type_ids=True` or if *"entity_token_type_ids"* is in `self.model_input_names`).
  87. [What are token type IDs?](../glossary#token-type-ids)
  88. - **entity_attention_mask** -- List of indices specifying which entities should be attended to by the model
  89. (when `return_attention_mask=True` or if *"entity_attention_mask"* is in `self.model_input_names`).
  90. [What are attention masks?](../glossary#attention-mask)
  91. - **entity_start_positions** -- List of the start positions of entities in the word token sequence (when
  92. `task="entity_span_classification"`).
  93. - **entity_end_positions** -- List of the end positions of entities in the word token sequence (when
  94. `task="entity_span_classification"`).
  95. - **overflowing_tokens** -- List of overflowing tokens sequences (when a `max_length` is specified and
  96. `return_overflowing_tokens=True`).
  97. - **num_truncated_tokens** -- Number of tokens truncated (when a `max_length` is specified and
  98. `return_overflowing_tokens=True`).
  99. - **special_tokens_mask** -- List of 0s and 1s, with 1 specifying added special tokens and 0 specifying
  100. regular sequence tokens (when `add_special_tokens=True` and `return_special_tokens_mask=True`).
  101. - **length** -- The length of the inputs (when `return_length=True`)
  102. """
  103. @lru_cache()
  104. # Copied from transformers.models.roberta.tokenization_roberta.bytes_to_unicode
  105. def bytes_to_unicode():
  106. """
  107. Returns list of utf-8 byte and a mapping to unicode strings. We specifically avoids mapping to whitespace/control
  108. characters the bpe code barfs on.
  109. The reversible bpe codes work on unicode strings. This means you need a large # of unicode characters in your vocab
  110. if you want to avoid UNKs. When you're at something like a 10B token dataset you end up needing around 5K for
  111. decent coverage. This is a significant percentage of your normal, say, 32K bpe vocab. To avoid that, we want lookup
  112. tables between utf-8 bytes and unicode strings.
  113. """
  114. bs = (
  115. list(range(ord("!"), ord("~") + 1)) + list(range(ord("¡"), ord("¬") + 1)) + list(range(ord("®"), ord("ÿ") + 1))
  116. )
  117. cs = bs[:]
  118. n = 0
  119. for b in range(2**8):
  120. if b not in bs:
  121. bs.append(b)
  122. cs.append(2**8 + n)
  123. n += 1
  124. cs = [chr(n) for n in cs]
  125. return dict(zip(bs, cs))
  126. # Copied from transformers.models.roberta.tokenization_roberta.get_pairs
  127. def get_pairs(word):
  128. """
  129. Return set of symbol pairs in a word.
  130. Word is represented as tuple of symbols (symbols being variable-length strings).
  131. """
  132. pairs = set()
  133. prev_char = word[0]
  134. for char in word[1:]:
  135. pairs.add((prev_char, char))
  136. prev_char = char
  137. return pairs
  138. class LukeTokenizer(PreTrainedTokenizer):
  139. """
  140. Constructs a LUKE tokenizer, derived from the GPT-2 tokenizer, using byte-level Byte-Pair-Encoding.
  141. This tokenizer has been trained to treat spaces like parts of the tokens (a bit like sentencepiece) so a word will
  142. be encoded differently whether it is at the beginning of the sentence (without space) or not:
  143. ```python
  144. >>> from transformers import LukeTokenizer
  145. >>> tokenizer = LukeTokenizer.from_pretrained("studio-ousia/luke-base")
  146. >>> tokenizer("Hello world")["input_ids"]
  147. [0, 31414, 232, 2]
  148. >>> tokenizer(" Hello world")["input_ids"]
  149. [0, 20920, 232, 2]
  150. ```
  151. You can get around that behavior by passing `add_prefix_space=True` when instantiating this tokenizer or when you
  152. call it on some text, but since the model was not pretrained this way, it might yield a decrease in performance.
  153. <Tip>
  154. When used with `is_split_into_words=True`, this tokenizer will add a space before each word (even the first one).
  155. </Tip>
  156. This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to
  157. this superclass for more information regarding those methods. It also creates entity sequences, namely
  158. `entity_ids`, `entity_attention_mask`, `entity_token_type_ids`, and `entity_position_ids` to be used by the LUKE
  159. model.
  160. Args:
  161. vocab_file (`str`):
  162. Path to the vocabulary file.
  163. merges_file (`str`):
  164. Path to the merges file.
  165. entity_vocab_file (`str`):
  166. Path to the entity vocabulary file.
  167. task (`str`, *optional*):
  168. Task for which you want to prepare sequences. One of `"entity_classification"`,
  169. `"entity_pair_classification"`, or `"entity_span_classification"`. If you specify this argument, the entity
  170. sequence is automatically created based on the given entity span(s).
  171. max_entity_length (`int`, *optional*, defaults to 32):
  172. The maximum length of `entity_ids`.
  173. max_mention_length (`int`, *optional*, defaults to 30):
  174. The maximum number of tokens inside an entity span.
  175. entity_token_1 (`str`, *optional*, defaults to `<ent>`):
  176. The special token used to represent an entity span in a word token sequence. This token is only used when
  177. `task` is set to `"entity_classification"` or `"entity_pair_classification"`.
  178. entity_token_2 (`str`, *optional*, defaults to `<ent2>`):
  179. The special token used to represent an entity span in a word token sequence. This token is only used when
  180. `task` is set to `"entity_pair_classification"`.
  181. errors (`str`, *optional*, defaults to `"replace"`):
  182. Paradigm to follow when decoding bytes to UTF-8. See
  183. [bytes.decode](https://docs.python.org/3/library/stdtypes.html#bytes.decode) for more information.
  184. bos_token (`str`, *optional*, defaults to `"<s>"`):
  185. The beginning of sequence token that was used during pretraining. Can be used a sequence classifier token.
  186. <Tip>
  187. When building a sequence using special tokens, this is not the token that is used for the beginning of
  188. sequence. The token used is the `cls_token`.
  189. </Tip>
  190. eos_token (`str`, *optional*, defaults to `"</s>"`):
  191. The end of sequence token.
  192. <Tip>
  193. When building a sequence using special tokens, this is not the token that is used for the end of sequence.
  194. The token used is the `sep_token`.
  195. </Tip>
  196. sep_token (`str`, *optional*, defaults to `"</s>"`):
  197. The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
  198. sequence classification or for a text and a question for question answering. It is also used as the last
  199. token of a sequence built with special tokens.
  200. cls_token (`str`, *optional*, defaults to `"<s>"`):
  201. The classifier token which is used when doing sequence classification (classification of the whole sequence
  202. instead of per-token classification). It is the first token of the sequence when built with special tokens.
  203. unk_token (`str`, *optional*, defaults to `"<unk>"`):
  204. The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
  205. token instead.
  206. pad_token (`str`, *optional*, defaults to `"<pad>"`):
  207. The token used for padding, for example when batching sequences of different lengths.
  208. mask_token (`str`, *optional*, defaults to `"<mask>"`):
  209. The token used for masking values. This is the token used when training this model with masked language
  210. modeling. This is the token which the model will try to predict.
  211. add_prefix_space (`bool`, *optional*, defaults to `False`):
  212. Whether or not to add an initial space to the input. This allows to treat the leading word just as any
  213. other word. (LUKE tokenizer detect beginning of words by the preceding space).
  214. """
  215. vocab_files_names = VOCAB_FILES_NAMES
  216. model_input_names = ["input_ids", "attention_mask"]
  217. def __init__(
  218. self,
  219. vocab_file,
  220. merges_file,
  221. entity_vocab_file,
  222. task=None,
  223. max_entity_length=32,
  224. max_mention_length=30,
  225. entity_token_1="<ent>",
  226. entity_token_2="<ent2>",
  227. entity_unk_token="[UNK]",
  228. entity_pad_token="[PAD]",
  229. entity_mask_token="[MASK]",
  230. entity_mask2_token="[MASK2]",
  231. errors="replace",
  232. bos_token="<s>",
  233. eos_token="</s>",
  234. sep_token="</s>",
  235. cls_token="<s>",
  236. unk_token="<unk>",
  237. pad_token="<pad>",
  238. mask_token="<mask>",
  239. add_prefix_space=False,
  240. **kwargs,
  241. ):
  242. bos_token = AddedToken(bos_token, lstrip=False, rstrip=False) if isinstance(bos_token, str) else bos_token
  243. eos_token = AddedToken(eos_token, lstrip=False, rstrip=False) if isinstance(eos_token, str) else eos_token
  244. sep_token = AddedToken(sep_token, lstrip=False, rstrip=False) if isinstance(sep_token, str) else sep_token
  245. cls_token = AddedToken(cls_token, lstrip=False, rstrip=False) if isinstance(cls_token, str) else cls_token
  246. unk_token = AddedToken(unk_token, lstrip=False, rstrip=False) if isinstance(unk_token, str) else unk_token
  247. pad_token = AddedToken(pad_token, lstrip=False, rstrip=False) if isinstance(pad_token, str) else pad_token
  248. # Mask token behave like a normal word, i.e. include the space before it
  249. mask_token = AddedToken(mask_token, lstrip=True, rstrip=False) if isinstance(mask_token, str) else mask_token
  250. with open(vocab_file, encoding="utf-8") as vocab_handle:
  251. self.encoder = json.load(vocab_handle)
  252. self.decoder = {v: k for k, v in self.encoder.items()}
  253. self.errors = errors # how to handle errors in decoding
  254. self.byte_encoder = bytes_to_unicode()
  255. self.byte_decoder = {v: k for k, v in self.byte_encoder.items()}
  256. with open(merges_file, encoding="utf-8") as merges_handle:
  257. bpe_merges = merges_handle.read().split("\n")[1:-1]
  258. bpe_merges = [tuple(merge.split()) for merge in bpe_merges]
  259. self.bpe_ranks = dict(zip(bpe_merges, range(len(bpe_merges))))
  260. self.cache = {}
  261. self.add_prefix_space = add_prefix_space
  262. # Should have added re.IGNORECASE so BPE merges can happen for capitalized versions of contractions
  263. self.pat = re.compile(r"""'s|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+""")
  264. # we add 2 special tokens for downstream tasks
  265. # for more information about lstrip and rstrip, see https://github.com/huggingface/transformers/pull/2778
  266. entity_token_1 = (
  267. AddedToken(entity_token_1, lstrip=False, rstrip=False)
  268. if isinstance(entity_token_1, str)
  269. else entity_token_1
  270. )
  271. entity_token_2 = (
  272. AddedToken(entity_token_2, lstrip=False, rstrip=False)
  273. if isinstance(entity_token_2, str)
  274. else entity_token_2
  275. )
  276. kwargs["additional_special_tokens"] = kwargs.get("additional_special_tokens", [])
  277. kwargs["additional_special_tokens"] += [entity_token_1, entity_token_2]
  278. with open(entity_vocab_file, encoding="utf-8") as entity_vocab_handle:
  279. self.entity_vocab = json.load(entity_vocab_handle)
  280. for entity_special_token in [entity_unk_token, entity_pad_token, entity_mask_token, entity_mask2_token]:
  281. if entity_special_token not in self.entity_vocab:
  282. raise ValueError(
  283. f"Specified entity special token ``{entity_special_token}`` is not found in entity_vocab. "
  284. f"Probably an incorrect entity vocab file is loaded: {entity_vocab_file}."
  285. )
  286. self.entity_unk_token_id = self.entity_vocab[entity_unk_token]
  287. self.entity_pad_token_id = self.entity_vocab[entity_pad_token]
  288. self.entity_mask_token_id = self.entity_vocab[entity_mask_token]
  289. self.entity_mask2_token_id = self.entity_vocab[entity_mask2_token]
  290. self.task = task
  291. if task is None or task == "entity_span_classification":
  292. self.max_entity_length = max_entity_length
  293. elif task == "entity_classification":
  294. self.max_entity_length = 1
  295. elif task == "entity_pair_classification":
  296. self.max_entity_length = 2
  297. else:
  298. raise ValueError(
  299. f"Task {task} not supported. Select task from ['entity_classification', 'entity_pair_classification',"
  300. " 'entity_span_classification'] only."
  301. )
  302. self.max_mention_length = max_mention_length
  303. super().__init__(
  304. errors=errors,
  305. bos_token=bos_token,
  306. eos_token=eos_token,
  307. unk_token=unk_token,
  308. sep_token=sep_token,
  309. cls_token=cls_token,
  310. pad_token=pad_token,
  311. mask_token=mask_token,
  312. add_prefix_space=add_prefix_space,
  313. task=task,
  314. max_entity_length=32,
  315. max_mention_length=30,
  316. entity_token_1="<ent>",
  317. entity_token_2="<ent2>",
  318. entity_unk_token=entity_unk_token,
  319. entity_pad_token=entity_pad_token,
  320. entity_mask_token=entity_mask_token,
  321. entity_mask2_token=entity_mask2_token,
  322. **kwargs,
  323. )
  324. @property
  325. # Copied from transformers.models.roberta.tokenization_roberta.RobertaTokenizer.vocab_size with Roberta->Luke, RoBERTa->LUKE
  326. def vocab_size(self):
  327. return len(self.encoder)
  328. # Copied from transformers.models.roberta.tokenization_roberta.RobertaTokenizer.get_vocab with Roberta->Luke, RoBERTa->LUKE
  329. def get_vocab(self):
  330. vocab = dict(self.encoder).copy()
  331. vocab.update(self.added_tokens_encoder)
  332. return vocab
  333. # Copied from transformers.models.roberta.tokenization_roberta.RobertaTokenizer.bpe with Roberta->Luke, RoBERTa->LUKE
  334. def bpe(self, token):
  335. if token in self.cache:
  336. return self.cache[token]
  337. word = tuple(token)
  338. pairs = get_pairs(word)
  339. if not pairs:
  340. return token
  341. while True:
  342. bigram = min(pairs, key=lambda pair: self.bpe_ranks.get(pair, float("inf")))
  343. if bigram not in self.bpe_ranks:
  344. break
  345. first, second = bigram
  346. new_word = []
  347. i = 0
  348. while i < len(word):
  349. try:
  350. j = word.index(first, i)
  351. except ValueError:
  352. new_word.extend(word[i:])
  353. break
  354. else:
  355. new_word.extend(word[i:j])
  356. i = j
  357. if word[i] == first and i < len(word) - 1 and word[i + 1] == second:
  358. new_word.append(first + second)
  359. i += 2
  360. else:
  361. new_word.append(word[i])
  362. i += 1
  363. new_word = tuple(new_word)
  364. word = new_word
  365. if len(word) == 1:
  366. break
  367. else:
  368. pairs = get_pairs(word)
  369. word = " ".join(word)
  370. self.cache[token] = word
  371. return word
  372. # Copied from transformers.models.roberta.tokenization_roberta.RobertaTokenizer._tokenize with Roberta->Luke, RoBERTa->LUKE
  373. def _tokenize(self, text):
  374. """Tokenize a string."""
  375. bpe_tokens = []
  376. for token in re.findall(self.pat, text):
  377. token = "".join(
  378. self.byte_encoder[b] for b in token.encode("utf-8")
  379. ) # Maps all our bytes to unicode strings, avoiding control tokens of the BPE (spaces in our case)
  380. bpe_tokens.extend(bpe_token for bpe_token in self.bpe(token).split(" "))
  381. return bpe_tokens
  382. # Copied from transformers.models.roberta.tokenization_roberta.RobertaTokenizer._convert_token_to_id with Roberta->Luke, RoBERTa->LUKE
  383. def _convert_token_to_id(self, token):
  384. """Converts a token (str) in an id using the vocab."""
  385. return self.encoder.get(token, self.encoder.get(self.unk_token))
  386. # Copied from transformers.models.roberta.tokenization_roberta.RobertaTokenizer._convert_id_to_token with Roberta->Luke, RoBERTa->LUKE
  387. def _convert_id_to_token(self, index):
  388. """Converts an index (integer) in a token (str) using the vocab."""
  389. return self.decoder.get(index)
  390. # Copied from transformers.models.roberta.tokenization_roberta.RobertaTokenizer.convert_tokens_to_string with Roberta->Luke, RoBERTa->LUKE
  391. def convert_tokens_to_string(self, tokens):
  392. """Converts a sequence of tokens (string) in a single string."""
  393. text = "".join(tokens)
  394. text = bytearray([self.byte_decoder[c] for c in text]).decode("utf-8", errors=self.errors)
  395. return text
  396. # Copied from transformers.models.roberta.tokenization_roberta.RobertaTokenizer.build_inputs_with_special_tokens with Roberta->Luke, RoBERTa->LUKE
  397. def build_inputs_with_special_tokens(
  398. self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
  399. ) -> List[int]:
  400. """
  401. Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
  402. adding special tokens. A LUKE sequence has the following format:
  403. - single sequence: `<s> X </s>`
  404. - pair of sequences: `<s> A </s></s> B </s>`
  405. Args:
  406. token_ids_0 (`List[int]`):
  407. List of IDs to which the special tokens will be added.
  408. token_ids_1 (`List[int]`, *optional*):
  409. Optional second list of IDs for sequence pairs.
  410. Returns:
  411. `List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
  412. """
  413. if token_ids_1 is None:
  414. return [self.cls_token_id] + token_ids_0 + [self.sep_token_id]
  415. cls = [self.cls_token_id]
  416. sep = [self.sep_token_id]
  417. return cls + token_ids_0 + sep + sep + token_ids_1 + sep
  418. # Copied from transformers.models.roberta.tokenization_roberta.RobertaTokenizer.get_special_tokens_mask with Roberta->Luke, RoBERTa->LUKE
  419. def get_special_tokens_mask(
  420. self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None, already_has_special_tokens: bool = False
  421. ) -> List[int]:
  422. """
  423. Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
  424. special tokens using the tokenizer `prepare_for_model` method.
  425. Args:
  426. token_ids_0 (`List[int]`):
  427. List of IDs.
  428. token_ids_1 (`List[int]`, *optional*):
  429. Optional second list of IDs for sequence pairs.
  430. already_has_special_tokens (`bool`, *optional*, defaults to `False`):
  431. Whether or not the token list is already formatted with special tokens for the model.
  432. Returns:
  433. `List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
  434. """
  435. if already_has_special_tokens:
  436. return super().get_special_tokens_mask(
  437. token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
  438. )
  439. if token_ids_1 is None:
  440. return [1] + ([0] * len(token_ids_0)) + [1]
  441. return [1] + ([0] * len(token_ids_0)) + [1, 1] + ([0] * len(token_ids_1)) + [1]
  442. # Copied from transformers.models.roberta.tokenization_roberta.RobertaTokenizer.create_token_type_ids_from_sequences with Roberta->Luke, RoBERTa->LUKE
  443. def create_token_type_ids_from_sequences(
  444. self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
  445. ) -> List[int]:
  446. """
  447. Create a mask from the two sequences passed to be used in a sequence-pair classification task. LUKE does not
  448. make use of token type ids, therefore a list of zeros is returned.
  449. Args:
  450. token_ids_0 (`List[int]`):
  451. List of IDs.
  452. token_ids_1 (`List[int]`, *optional*):
  453. Optional second list of IDs for sequence pairs.
  454. Returns:
  455. `List[int]`: List of zeros.
  456. """
  457. sep = [self.sep_token_id]
  458. cls = [self.cls_token_id]
  459. if token_ids_1 is None:
  460. return len(cls + token_ids_0 + sep) * [0]
  461. return len(cls + token_ids_0 + sep + sep + token_ids_1 + sep) * [0]
  462. # Copied from transformers.models.roberta.tokenization_roberta.RobertaTokenizer.prepare_for_tokenization with Roberta->Luke, RoBERTa->LUKE
  463. def prepare_for_tokenization(self, text, is_split_into_words=False, **kwargs):
  464. add_prefix_space = kwargs.pop("add_prefix_space", self.add_prefix_space)
  465. if (is_split_into_words or add_prefix_space) and (len(text) > 0 and not text[0].isspace()):
  466. text = " " + text
  467. return (text, kwargs)
  468. @add_end_docstrings(ENCODE_KWARGS_DOCSTRING, ENCODE_PLUS_ADDITIONAL_KWARGS_DOCSTRING)
  469. def __call__(
  470. self,
  471. text: Union[TextInput, List[TextInput]],
  472. text_pair: Optional[Union[TextInput, List[TextInput]]] = None,
  473. entity_spans: Optional[Union[EntitySpanInput, List[EntitySpanInput]]] = None,
  474. entity_spans_pair: Optional[Union[EntitySpanInput, List[EntitySpanInput]]] = None,
  475. entities: Optional[Union[EntityInput, List[EntityInput]]] = None,
  476. entities_pair: Optional[Union[EntityInput, List[EntityInput]]] = None,
  477. add_special_tokens: bool = True,
  478. padding: Union[bool, str, PaddingStrategy] = False,
  479. truncation: Union[bool, str, TruncationStrategy] = None,
  480. max_length: Optional[int] = None,
  481. max_entity_length: Optional[int] = None,
  482. stride: int = 0,
  483. is_split_into_words: Optional[bool] = False,
  484. pad_to_multiple_of: Optional[int] = None,
  485. padding_side: Optional[bool] = None,
  486. return_tensors: Optional[Union[str, TensorType]] = None,
  487. return_token_type_ids: Optional[bool] = None,
  488. return_attention_mask: Optional[bool] = None,
  489. return_overflowing_tokens: bool = False,
  490. return_special_tokens_mask: bool = False,
  491. return_offsets_mapping: bool = False,
  492. return_length: bool = False,
  493. verbose: bool = True,
  494. **kwargs,
  495. ) -> BatchEncoding:
  496. """
  497. Main method to tokenize and prepare for the model one or several sequence(s) or one or several pair(s) of
  498. sequences, depending on the task you want to prepare them for.
  499. Args:
  500. text (`str`, `List[str]`, `List[List[str]]`):
  501. The sequence or batch of sequences to be encoded. Each sequence must be a string. Note that this
  502. tokenizer does not support tokenization based on pretokenized strings.
  503. text_pair (`str`, `List[str]`, `List[List[str]]`):
  504. The sequence or batch of sequences to be encoded. Each sequence must be a string. Note that this
  505. tokenizer does not support tokenization based on pretokenized strings.
  506. entity_spans (`List[Tuple[int, int]]`, `List[List[Tuple[int, int]]]`, *optional*):
  507. The sequence or batch of sequences of entity spans to be encoded. Each sequence consists of tuples each
  508. with two integers denoting character-based start and end positions of entities. If you specify
  509. `"entity_classification"` or `"entity_pair_classification"` as the `task` argument in the constructor,
  510. the length of each sequence must be 1 or 2, respectively. If you specify `entities`, the length of each
  511. sequence must be equal to the length of each sequence of `entities`.
  512. entity_spans_pair (`List[Tuple[int, int]]`, `List[List[Tuple[int, int]]]`, *optional*):
  513. The sequence or batch of sequences of entity spans to be encoded. Each sequence consists of tuples each
  514. with two integers denoting character-based start and end positions of entities. If you specify the
  515. `task` argument in the constructor, this argument is ignored. If you specify `entities_pair`, the
  516. length of each sequence must be equal to the length of each sequence of `entities_pair`.
  517. entities (`List[str]`, `List[List[str]]`, *optional*):
  518. The sequence or batch of sequences of entities to be encoded. Each sequence consists of strings
  519. representing entities, i.e., special entities (e.g., [MASK]) or entity titles of Wikipedia (e.g., Los
  520. Angeles). This argument is ignored if you specify the `task` argument in the constructor. The length of
  521. each sequence must be equal to the length of each sequence of `entity_spans`. If you specify
  522. `entity_spans` without specifying this argument, the entity sequence or the batch of entity sequences
  523. is automatically constructed by filling it with the [MASK] entity.
  524. entities_pair (`List[str]`, `List[List[str]]`, *optional*):
  525. The sequence or batch of sequences of entities to be encoded. Each sequence consists of strings
  526. representing entities, i.e., special entities (e.g., [MASK]) or entity titles of Wikipedia (e.g., Los
  527. Angeles). This argument is ignored if you specify the `task` argument in the constructor. The length of
  528. each sequence must be equal to the length of each sequence of `entity_spans_pair`. If you specify
  529. `entity_spans_pair` without specifying this argument, the entity sequence or the batch of entity
  530. sequences is automatically constructed by filling it with the [MASK] entity.
  531. max_entity_length (`int`, *optional*):
  532. The maximum length of `entity_ids`.
  533. """
  534. # Input type checking for clearer error
  535. is_valid_single_text = isinstance(text, str)
  536. is_valid_batch_text = isinstance(text, (list, tuple)) and (len(text) == 0 or (isinstance(text[0], str)))
  537. if not (is_valid_single_text or is_valid_batch_text):
  538. raise ValueError("text input must be of type `str` (single example) or `List[str]` (batch).")
  539. is_valid_single_text_pair = isinstance(text_pair, str)
  540. is_valid_batch_text_pair = isinstance(text_pair, (list, tuple)) and (
  541. len(text_pair) == 0 or isinstance(text_pair[0], str)
  542. )
  543. if not (text_pair is None or is_valid_single_text_pair or is_valid_batch_text_pair):
  544. raise ValueError("text_pair input must be of type `str` (single example) or `List[str]` (batch).")
  545. is_batched = bool(isinstance(text, (list, tuple)))
  546. if is_batched:
  547. batch_text_or_text_pairs = list(zip(text, text_pair)) if text_pair is not None else text
  548. if entities is None:
  549. batch_entities_or_entities_pairs = None
  550. else:
  551. batch_entities_or_entities_pairs = (
  552. list(zip(entities, entities_pair)) if entities_pair is not None else entities
  553. )
  554. if entity_spans is None:
  555. batch_entity_spans_or_entity_spans_pairs = None
  556. else:
  557. batch_entity_spans_or_entity_spans_pairs = (
  558. list(zip(entity_spans, entity_spans_pair)) if entity_spans_pair is not None else entity_spans
  559. )
  560. return self.batch_encode_plus(
  561. batch_text_or_text_pairs=batch_text_or_text_pairs,
  562. batch_entity_spans_or_entity_spans_pairs=batch_entity_spans_or_entity_spans_pairs,
  563. batch_entities_or_entities_pairs=batch_entities_or_entities_pairs,
  564. add_special_tokens=add_special_tokens,
  565. padding=padding,
  566. truncation=truncation,
  567. max_length=max_length,
  568. max_entity_length=max_entity_length,
  569. stride=stride,
  570. is_split_into_words=is_split_into_words,
  571. pad_to_multiple_of=pad_to_multiple_of,
  572. padding_side=padding_side,
  573. return_tensors=return_tensors,
  574. return_token_type_ids=return_token_type_ids,
  575. return_attention_mask=return_attention_mask,
  576. return_overflowing_tokens=return_overflowing_tokens,
  577. return_special_tokens_mask=return_special_tokens_mask,
  578. return_offsets_mapping=return_offsets_mapping,
  579. return_length=return_length,
  580. verbose=verbose,
  581. **kwargs,
  582. )
  583. else:
  584. return self.encode_plus(
  585. text=text,
  586. text_pair=text_pair,
  587. entity_spans=entity_spans,
  588. entity_spans_pair=entity_spans_pair,
  589. entities=entities,
  590. entities_pair=entities_pair,
  591. add_special_tokens=add_special_tokens,
  592. padding=padding,
  593. truncation=truncation,
  594. max_length=max_length,
  595. max_entity_length=max_entity_length,
  596. stride=stride,
  597. is_split_into_words=is_split_into_words,
  598. pad_to_multiple_of=pad_to_multiple_of,
  599. padding_side=padding_side,
  600. return_tensors=return_tensors,
  601. return_token_type_ids=return_token_type_ids,
  602. return_attention_mask=return_attention_mask,
  603. return_overflowing_tokens=return_overflowing_tokens,
  604. return_special_tokens_mask=return_special_tokens_mask,
  605. return_offsets_mapping=return_offsets_mapping,
  606. return_length=return_length,
  607. verbose=verbose,
  608. **kwargs,
  609. )
  610. def _encode_plus(
  611. self,
  612. text: Union[TextInput],
  613. text_pair: Optional[Union[TextInput]] = None,
  614. entity_spans: Optional[EntitySpanInput] = None,
  615. entity_spans_pair: Optional[EntitySpanInput] = None,
  616. entities: Optional[EntityInput] = None,
  617. entities_pair: Optional[EntityInput] = None,
  618. add_special_tokens: bool = True,
  619. padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD,
  620. truncation_strategy: TruncationStrategy = TruncationStrategy.DO_NOT_TRUNCATE,
  621. max_length: Optional[int] = None,
  622. max_entity_length: Optional[int] = None,
  623. stride: int = 0,
  624. is_split_into_words: Optional[bool] = False,
  625. pad_to_multiple_of: Optional[int] = None,
  626. padding_side: Optional[bool] = None,
  627. return_tensors: Optional[Union[str, TensorType]] = None,
  628. return_token_type_ids: Optional[bool] = None,
  629. return_attention_mask: Optional[bool] = None,
  630. return_overflowing_tokens: bool = False,
  631. return_special_tokens_mask: bool = False,
  632. return_offsets_mapping: bool = False,
  633. return_length: bool = False,
  634. verbose: bool = True,
  635. **kwargs,
  636. ) -> BatchEncoding:
  637. if return_offsets_mapping:
  638. raise NotImplementedError(
  639. "return_offset_mapping is not available when using Python tokenizers. "
  640. "To use this feature, change your tokenizer to one deriving from "
  641. "transformers.PreTrainedTokenizerFast. "
  642. "More information on available tokenizers at "
  643. "https://github.com/huggingface/transformers/pull/2674"
  644. )
  645. if is_split_into_words:
  646. raise NotImplementedError("is_split_into_words is not supported in this tokenizer.")
  647. (
  648. first_ids,
  649. second_ids,
  650. first_entity_ids,
  651. second_entity_ids,
  652. first_entity_token_spans,
  653. second_entity_token_spans,
  654. ) = self._create_input_sequence(
  655. text=text,
  656. text_pair=text_pair,
  657. entities=entities,
  658. entities_pair=entities_pair,
  659. entity_spans=entity_spans,
  660. entity_spans_pair=entity_spans_pair,
  661. **kwargs,
  662. )
  663. # prepare_for_model will create the attention_mask and token_type_ids
  664. return self.prepare_for_model(
  665. first_ids,
  666. pair_ids=second_ids,
  667. entity_ids=first_entity_ids,
  668. pair_entity_ids=second_entity_ids,
  669. entity_token_spans=first_entity_token_spans,
  670. pair_entity_token_spans=second_entity_token_spans,
  671. add_special_tokens=add_special_tokens,
  672. padding=padding_strategy.value,
  673. truncation=truncation_strategy.value,
  674. max_length=max_length,
  675. max_entity_length=max_entity_length,
  676. stride=stride,
  677. pad_to_multiple_of=pad_to_multiple_of,
  678. padding_side=padding_side,
  679. return_tensors=return_tensors,
  680. prepend_batch_axis=True,
  681. return_attention_mask=return_attention_mask,
  682. return_token_type_ids=return_token_type_ids,
  683. return_overflowing_tokens=return_overflowing_tokens,
  684. return_special_tokens_mask=return_special_tokens_mask,
  685. return_length=return_length,
  686. verbose=verbose,
  687. )
  688. def _batch_encode_plus(
  689. self,
  690. batch_text_or_text_pairs: Union[List[TextInput], List[TextInputPair]],
  691. batch_entity_spans_or_entity_spans_pairs: Optional[
  692. Union[List[EntitySpanInput], List[Tuple[EntitySpanInput, EntitySpanInput]]]
  693. ] = None,
  694. batch_entities_or_entities_pairs: Optional[
  695. Union[List[EntityInput], List[Tuple[EntityInput, EntityInput]]]
  696. ] = None,
  697. add_special_tokens: bool = True,
  698. padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD,
  699. truncation_strategy: TruncationStrategy = TruncationStrategy.DO_NOT_TRUNCATE,
  700. max_length: Optional[int] = None,
  701. max_entity_length: Optional[int] = None,
  702. stride: int = 0,
  703. is_split_into_words: Optional[bool] = False,
  704. pad_to_multiple_of: Optional[int] = None,
  705. padding_side: Optional[bool] = None,
  706. return_tensors: Optional[Union[str, TensorType]] = None,
  707. return_token_type_ids: Optional[bool] = None,
  708. return_attention_mask: Optional[bool] = None,
  709. return_overflowing_tokens: bool = False,
  710. return_special_tokens_mask: bool = False,
  711. return_offsets_mapping: bool = False,
  712. return_length: bool = False,
  713. verbose: bool = True,
  714. **kwargs,
  715. ) -> BatchEncoding:
  716. if return_offsets_mapping:
  717. raise NotImplementedError(
  718. "return_offset_mapping is not available when using Python tokenizers. "
  719. "To use this feature, change your tokenizer to one deriving from "
  720. "transformers.PreTrainedTokenizerFast."
  721. )
  722. if is_split_into_words:
  723. raise NotImplementedError("is_split_into_words is not supported in this tokenizer.")
  724. # input_ids is a list of tuples (one for each example in the batch)
  725. input_ids = []
  726. entity_ids = []
  727. entity_token_spans = []
  728. for index, text_or_text_pair in enumerate(batch_text_or_text_pairs):
  729. if not isinstance(text_or_text_pair, (list, tuple)):
  730. text, text_pair = text_or_text_pair, None
  731. else:
  732. text, text_pair = text_or_text_pair
  733. entities, entities_pair = None, None
  734. if batch_entities_or_entities_pairs is not None:
  735. entities_or_entities_pairs = batch_entities_or_entities_pairs[index]
  736. if entities_or_entities_pairs:
  737. if isinstance(entities_or_entities_pairs[0], str):
  738. entities, entities_pair = entities_or_entities_pairs, None
  739. else:
  740. entities, entities_pair = entities_or_entities_pairs
  741. entity_spans, entity_spans_pair = None, None
  742. if batch_entity_spans_or_entity_spans_pairs is not None:
  743. entity_spans_or_entity_spans_pairs = batch_entity_spans_or_entity_spans_pairs[index]
  744. if len(entity_spans_or_entity_spans_pairs) > 0 and isinstance(
  745. entity_spans_or_entity_spans_pairs[0], list
  746. ):
  747. entity_spans, entity_spans_pair = entity_spans_or_entity_spans_pairs
  748. else:
  749. entity_spans, entity_spans_pair = entity_spans_or_entity_spans_pairs, None
  750. (
  751. first_ids,
  752. second_ids,
  753. first_entity_ids,
  754. second_entity_ids,
  755. first_entity_token_spans,
  756. second_entity_token_spans,
  757. ) = self._create_input_sequence(
  758. text=text,
  759. text_pair=text_pair,
  760. entities=entities,
  761. entities_pair=entities_pair,
  762. entity_spans=entity_spans,
  763. entity_spans_pair=entity_spans_pair,
  764. **kwargs,
  765. )
  766. input_ids.append((first_ids, second_ids))
  767. entity_ids.append((first_entity_ids, second_entity_ids))
  768. entity_token_spans.append((first_entity_token_spans, second_entity_token_spans))
  769. batch_outputs = self._batch_prepare_for_model(
  770. input_ids,
  771. batch_entity_ids_pairs=entity_ids,
  772. batch_entity_token_spans_pairs=entity_token_spans,
  773. add_special_tokens=add_special_tokens,
  774. padding_strategy=padding_strategy,
  775. truncation_strategy=truncation_strategy,
  776. max_length=max_length,
  777. max_entity_length=max_entity_length,
  778. stride=stride,
  779. pad_to_multiple_of=pad_to_multiple_of,
  780. padding_side=padding_side,
  781. return_attention_mask=return_attention_mask,
  782. return_token_type_ids=return_token_type_ids,
  783. return_overflowing_tokens=return_overflowing_tokens,
  784. return_special_tokens_mask=return_special_tokens_mask,
  785. return_length=return_length,
  786. return_tensors=return_tensors,
  787. verbose=verbose,
  788. )
  789. return BatchEncoding(batch_outputs)
  790. def _check_entity_input_format(self, entities: Optional[EntityInput], entity_spans: Optional[EntitySpanInput]):
  791. if not isinstance(entity_spans, list):
  792. raise TypeError("entity_spans should be given as a list")
  793. elif len(entity_spans) > 0 and not isinstance(entity_spans[0], tuple):
  794. raise ValueError(
  795. "entity_spans should be given as a list of tuples containing the start and end character indices"
  796. )
  797. if entities is not None:
  798. if not isinstance(entities, list):
  799. raise ValueError("If you specify entities, they should be given as a list")
  800. if len(entities) > 0 and not isinstance(entities[0], str):
  801. raise ValueError("If you specify entities, they should be given as a list of entity names")
  802. if len(entities) != len(entity_spans):
  803. raise ValueError("If you specify entities, entities and entity_spans must be the same length")
  804. def _create_input_sequence(
  805. self,
  806. text: Union[TextInput],
  807. text_pair: Optional[Union[TextInput]] = None,
  808. entities: Optional[EntityInput] = None,
  809. entities_pair: Optional[EntityInput] = None,
  810. entity_spans: Optional[EntitySpanInput] = None,
  811. entity_spans_pair: Optional[EntitySpanInput] = None,
  812. **kwargs,
  813. ) -> Tuple[list, list, list, list, list, list]:
  814. def get_input_ids(text):
  815. tokens = self.tokenize(text, **kwargs)
  816. return self.convert_tokens_to_ids(tokens)
  817. def get_input_ids_and_entity_token_spans(text, entity_spans):
  818. if entity_spans is None:
  819. return get_input_ids(text), None
  820. cur = 0
  821. input_ids = []
  822. entity_token_spans = [None] * len(entity_spans)
  823. split_char_positions = sorted(frozenset(itertools.chain(*entity_spans)))
  824. char_pos2token_pos = {}
  825. for split_char_position in split_char_positions:
  826. orig_split_char_position = split_char_position
  827. if (
  828. split_char_position > 0 and text[split_char_position - 1] == " "
  829. ): # whitespace should be prepended to the following token
  830. split_char_position -= 1
  831. if cur != split_char_position:
  832. input_ids += get_input_ids(text[cur:split_char_position])
  833. cur = split_char_position
  834. char_pos2token_pos[orig_split_char_position] = len(input_ids)
  835. input_ids += get_input_ids(text[cur:])
  836. entity_token_spans = [
  837. (char_pos2token_pos[char_start], char_pos2token_pos[char_end]) for char_start, char_end in entity_spans
  838. ]
  839. return input_ids, entity_token_spans
  840. first_ids, second_ids = None, None
  841. first_entity_ids, second_entity_ids = None, None
  842. first_entity_token_spans, second_entity_token_spans = None, None
  843. if self.task is None:
  844. if entity_spans is None:
  845. first_ids = get_input_ids(text)
  846. else:
  847. self._check_entity_input_format(entities, entity_spans)
  848. first_ids, first_entity_token_spans = get_input_ids_and_entity_token_spans(text, entity_spans)
  849. if entities is None:
  850. first_entity_ids = [self.entity_mask_token_id] * len(entity_spans)
  851. else:
  852. first_entity_ids = [self.entity_vocab.get(entity, self.entity_unk_token_id) for entity in entities]
  853. if text_pair is not None:
  854. if entity_spans_pair is None:
  855. second_ids = get_input_ids(text_pair)
  856. else:
  857. self._check_entity_input_format(entities_pair, entity_spans_pair)
  858. second_ids, second_entity_token_spans = get_input_ids_and_entity_token_spans(
  859. text_pair, entity_spans_pair
  860. )
  861. if entities_pair is None:
  862. second_entity_ids = [self.entity_mask_token_id] * len(entity_spans_pair)
  863. else:
  864. second_entity_ids = [
  865. self.entity_vocab.get(entity, self.entity_unk_token_id) for entity in entities_pair
  866. ]
  867. elif self.task == "entity_classification":
  868. if not (isinstance(entity_spans, list) and len(entity_spans) == 1 and isinstance(entity_spans[0], tuple)):
  869. raise ValueError(
  870. "Entity spans should be a list containing a single tuple "
  871. "containing the start and end character indices of an entity"
  872. )
  873. first_entity_ids = [self.entity_mask_token_id]
  874. first_ids, first_entity_token_spans = get_input_ids_and_entity_token_spans(text, entity_spans)
  875. # add special tokens to input ids
  876. entity_token_start, entity_token_end = first_entity_token_spans[0]
  877. first_ids = (
  878. first_ids[:entity_token_end] + [self.additional_special_tokens_ids[0]] + first_ids[entity_token_end:]
  879. )
  880. first_ids = (
  881. first_ids[:entity_token_start]
  882. + [self.additional_special_tokens_ids[0]]
  883. + first_ids[entity_token_start:]
  884. )
  885. first_entity_token_spans = [(entity_token_start, entity_token_end + 2)]
  886. elif self.task == "entity_pair_classification":
  887. if not (
  888. isinstance(entity_spans, list)
  889. and len(entity_spans) == 2
  890. and isinstance(entity_spans[0], tuple)
  891. and isinstance(entity_spans[1], tuple)
  892. ):
  893. raise ValueError(
  894. "Entity spans should be provided as a list of two tuples, "
  895. "each tuple containing the start and end character indices of an entity"
  896. )
  897. head_span, tail_span = entity_spans
  898. first_entity_ids = [self.entity_mask_token_id, self.entity_mask2_token_id]
  899. first_ids, first_entity_token_spans = get_input_ids_and_entity_token_spans(text, entity_spans)
  900. head_token_span, tail_token_span = first_entity_token_spans
  901. token_span_with_special_token_ids = [
  902. (head_token_span, self.additional_special_tokens_ids[0]),
  903. (tail_token_span, self.additional_special_tokens_ids[1]),
  904. ]
  905. if head_token_span[0] < tail_token_span[0]:
  906. first_entity_token_spans[0] = (head_token_span[0], head_token_span[1] + 2)
  907. first_entity_token_spans[1] = (tail_token_span[0] + 2, tail_token_span[1] + 4)
  908. token_span_with_special_token_ids = reversed(token_span_with_special_token_ids)
  909. else:
  910. first_entity_token_spans[0] = (head_token_span[0] + 2, head_token_span[1] + 4)
  911. first_entity_token_spans[1] = (tail_token_span[0], tail_token_span[1] + 2)
  912. for (entity_token_start, entity_token_end), special_token_id in token_span_with_special_token_ids:
  913. first_ids = first_ids[:entity_token_end] + [special_token_id] + first_ids[entity_token_end:]
  914. first_ids = first_ids[:entity_token_start] + [special_token_id] + first_ids[entity_token_start:]
  915. elif self.task == "entity_span_classification":
  916. if not (isinstance(entity_spans, list) and len(entity_spans) > 0 and isinstance(entity_spans[0], tuple)):
  917. raise ValueError(
  918. "Entity spans should be provided as a list of tuples, "
  919. "each tuple containing the start and end character indices of an entity"
  920. )
  921. first_ids, first_entity_token_spans = get_input_ids_and_entity_token_spans(text, entity_spans)
  922. first_entity_ids = [self.entity_mask_token_id] * len(entity_spans)
  923. else:
  924. raise ValueError(f"Task {self.task} not supported")
  925. return (
  926. first_ids,
  927. second_ids,
  928. first_entity_ids,
  929. second_entity_ids,
  930. first_entity_token_spans,
  931. second_entity_token_spans,
  932. )
  933. @add_end_docstrings(ENCODE_KWARGS_DOCSTRING, ENCODE_PLUS_ADDITIONAL_KWARGS_DOCSTRING)
  934. def _batch_prepare_for_model(
  935. self,
  936. batch_ids_pairs: List[Tuple[List[int], None]],
  937. batch_entity_ids_pairs: List[Tuple[Optional[List[int]], Optional[List[int]]]],
  938. batch_entity_token_spans_pairs: List[Tuple[Optional[List[Tuple[int, int]]], Optional[List[Tuple[int, int]]]]],
  939. add_special_tokens: bool = True,
  940. padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD,
  941. truncation_strategy: TruncationStrategy = TruncationStrategy.DO_NOT_TRUNCATE,
  942. max_length: Optional[int] = None,
  943. max_entity_length: Optional[int] = None,
  944. stride: int = 0,
  945. pad_to_multiple_of: Optional[int] = None,
  946. padding_side: Optional[bool] = None,
  947. return_tensors: Optional[str] = None,
  948. return_token_type_ids: Optional[bool] = None,
  949. return_attention_mask: Optional[bool] = None,
  950. return_overflowing_tokens: bool = False,
  951. return_special_tokens_mask: bool = False,
  952. return_length: bool = False,
  953. verbose: bool = True,
  954. ) -> BatchEncoding:
  955. """
  956. Prepares a sequence of input id, or a pair of sequences of inputs ids so that it can be used by the model. It
  957. adds special tokens, truncates sequences if overflowing while taking into account the special tokens and
  958. manages a moving window (with user defined stride) for overflowing tokens
  959. Args:
  960. batch_ids_pairs: list of tokenized input ids or input ids pairs
  961. batch_entity_ids_pairs: list of entity ids or entity ids pairs
  962. batch_entity_token_spans_pairs: list of entity spans or entity spans pairs
  963. max_entity_length: The maximum length of the entity sequence.
  964. """
  965. batch_outputs = {}
  966. for input_ids, entity_ids, entity_token_span_pairs in zip(
  967. batch_ids_pairs, batch_entity_ids_pairs, batch_entity_token_spans_pairs
  968. ):
  969. first_ids, second_ids = input_ids
  970. first_entity_ids, second_entity_ids = entity_ids
  971. first_entity_token_spans, second_entity_token_spans = entity_token_span_pairs
  972. outputs = self.prepare_for_model(
  973. first_ids,
  974. second_ids,
  975. entity_ids=first_entity_ids,
  976. pair_entity_ids=second_entity_ids,
  977. entity_token_spans=first_entity_token_spans,
  978. pair_entity_token_spans=second_entity_token_spans,
  979. add_special_tokens=add_special_tokens,
  980. padding=PaddingStrategy.DO_NOT_PAD.value, # we pad in batch afterward
  981. truncation=truncation_strategy.value,
  982. max_length=max_length,
  983. max_entity_length=max_entity_length,
  984. stride=stride,
  985. pad_to_multiple_of=None, # we pad in batch afterward
  986. padding_side=None, # we pad in batch afterward
  987. return_attention_mask=False, # we pad in batch afterward
  988. return_token_type_ids=return_token_type_ids,
  989. return_overflowing_tokens=return_overflowing_tokens,
  990. return_special_tokens_mask=return_special_tokens_mask,
  991. return_length=return_length,
  992. return_tensors=None, # We convert the whole batch to tensors at the end
  993. prepend_batch_axis=False,
  994. verbose=verbose,
  995. )
  996. for key, value in outputs.items():
  997. if key not in batch_outputs:
  998. batch_outputs[key] = []
  999. batch_outputs[key].append(value)
  1000. batch_outputs = self.pad(
  1001. batch_outputs,
  1002. padding=padding_strategy.value,
  1003. max_length=max_length,
  1004. pad_to_multiple_of=pad_to_multiple_of,
  1005. padding_side=padding_side,
  1006. return_attention_mask=return_attention_mask,
  1007. )
  1008. batch_outputs = BatchEncoding(batch_outputs, tensor_type=return_tensors)
  1009. return batch_outputs
  1010. @add_end_docstrings(ENCODE_KWARGS_DOCSTRING, ENCODE_PLUS_ADDITIONAL_KWARGS_DOCSTRING)
  1011. def prepare_for_model(
  1012. self,
  1013. ids: List[int],
  1014. pair_ids: Optional[List[int]] = None,
  1015. entity_ids: Optional[List[int]] = None,
  1016. pair_entity_ids: Optional[List[int]] = None,
  1017. entity_token_spans: Optional[List[Tuple[int, int]]] = None,
  1018. pair_entity_token_spans: Optional[List[Tuple[int, int]]] = None,
  1019. add_special_tokens: bool = True,
  1020. padding: Union[bool, str, PaddingStrategy] = False,
  1021. truncation: Union[bool, str, TruncationStrategy] = None,
  1022. max_length: Optional[int] = None,
  1023. max_entity_length: Optional[int] = None,
  1024. stride: int = 0,
  1025. pad_to_multiple_of: Optional[int] = None,
  1026. padding_side: Optional[bool] = None,
  1027. return_tensors: Optional[Union[str, TensorType]] = None,
  1028. return_token_type_ids: Optional[bool] = None,
  1029. return_attention_mask: Optional[bool] = None,
  1030. return_overflowing_tokens: bool = False,
  1031. return_special_tokens_mask: bool = False,
  1032. return_offsets_mapping: bool = False,
  1033. return_length: bool = False,
  1034. verbose: bool = True,
  1035. prepend_batch_axis: bool = False,
  1036. **kwargs,
  1037. ) -> BatchEncoding:
  1038. """
  1039. Prepares a sequence of input id, entity id and entity span, or a pair of sequences of inputs ids, entity ids,
  1040. entity spans so that it can be used by the model. It adds special tokens, truncates sequences if overflowing
  1041. while taking into account the special tokens and manages a moving window (with user defined stride) for
  1042. overflowing tokens. Please Note, for *pair_ids* different than `None` and *truncation_strategy = longest_first*
  1043. or `True`, it is not possible to return overflowing tokens. Such a combination of arguments will raise an
  1044. error.
  1045. Args:
  1046. ids (`List[int]`):
  1047. Tokenized input ids of the first sequence.
  1048. pair_ids (`List[int]`, *optional*):
  1049. Tokenized input ids of the second sequence.
  1050. entity_ids (`List[int]`, *optional*):
  1051. Entity ids of the first sequence.
  1052. pair_entity_ids (`List[int]`, *optional*):
  1053. Entity ids of the second sequence.
  1054. entity_token_spans (`List[Tuple[int, int]]`, *optional*):
  1055. Entity spans of the first sequence.
  1056. pair_entity_token_spans (`List[Tuple[int, int]]`, *optional*):
  1057. Entity spans of the second sequence.
  1058. max_entity_length (`int`, *optional*):
  1059. The maximum length of the entity sequence.
  1060. """
  1061. # Backward compatibility for 'truncation_strategy', 'pad_to_max_length'
  1062. padding_strategy, truncation_strategy, max_length, kwargs = self._get_padding_truncation_strategies(
  1063. padding=padding,
  1064. truncation=truncation,
  1065. max_length=max_length,
  1066. pad_to_multiple_of=pad_to_multiple_of,
  1067. verbose=verbose,
  1068. **kwargs,
  1069. )
  1070. # Compute lengths
  1071. pair = bool(pair_ids is not None)
  1072. len_ids = len(ids)
  1073. len_pair_ids = len(pair_ids) if pair else 0
  1074. if return_token_type_ids and not add_special_tokens:
  1075. raise ValueError(
  1076. "Asking to return token_type_ids while setting add_special_tokens to False "
  1077. "results in an undefined behavior. Please set add_special_tokens to True or "
  1078. "set return_token_type_ids to None."
  1079. )
  1080. if (
  1081. return_overflowing_tokens
  1082. and truncation_strategy == TruncationStrategy.LONGEST_FIRST
  1083. and pair_ids is not None
  1084. ):
  1085. raise ValueError(
  1086. "Not possible to return overflowing tokens for pair of sequences with the "
  1087. "`longest_first`. Please select another truncation strategy than `longest_first`, "
  1088. "for instance `only_second` or `only_first`."
  1089. )
  1090. # Load from model defaults
  1091. if return_token_type_ids is None:
  1092. return_token_type_ids = "token_type_ids" in self.model_input_names
  1093. if return_attention_mask is None:
  1094. return_attention_mask = "attention_mask" in self.model_input_names
  1095. encoded_inputs = {}
  1096. # Compute the total size of the returned word encodings
  1097. total_len = len_ids + len_pair_ids + (self.num_special_tokens_to_add(pair=pair) if add_special_tokens else 0)
  1098. # Truncation: Handle max sequence length and max_entity_length
  1099. overflowing_tokens = []
  1100. if truncation_strategy != TruncationStrategy.DO_NOT_TRUNCATE and max_length and total_len > max_length:
  1101. # truncate words up to max_length
  1102. ids, pair_ids, overflowing_tokens = self.truncate_sequences(
  1103. ids,
  1104. pair_ids=pair_ids,
  1105. num_tokens_to_remove=total_len - max_length,
  1106. truncation_strategy=truncation_strategy,
  1107. stride=stride,
  1108. )
  1109. if return_overflowing_tokens:
  1110. encoded_inputs["overflowing_tokens"] = overflowing_tokens
  1111. encoded_inputs["num_truncated_tokens"] = total_len - max_length
  1112. # Add special tokens
  1113. if add_special_tokens:
  1114. sequence = self.build_inputs_with_special_tokens(ids, pair_ids)
  1115. token_type_ids = self.create_token_type_ids_from_sequences(ids, pair_ids)
  1116. entity_token_offset = 1 # 1 * <s> token
  1117. pair_entity_token_offset = len(ids) + 3 # 1 * <s> token & 2 * <sep> tokens
  1118. else:
  1119. sequence = ids + pair_ids if pair else ids
  1120. token_type_ids = [0] * len(ids) + ([0] * len(pair_ids) if pair else [])
  1121. entity_token_offset = 0
  1122. pair_entity_token_offset = len(ids)
  1123. # Build output dictionary
  1124. encoded_inputs["input_ids"] = sequence
  1125. if return_token_type_ids:
  1126. encoded_inputs["token_type_ids"] = token_type_ids
  1127. if return_special_tokens_mask:
  1128. if add_special_tokens:
  1129. encoded_inputs["special_tokens_mask"] = self.get_special_tokens_mask(ids, pair_ids)
  1130. else:
  1131. encoded_inputs["special_tokens_mask"] = [0] * len(sequence)
  1132. # Set max entity length
  1133. if not max_entity_length:
  1134. max_entity_length = self.max_entity_length
  1135. if entity_ids is not None:
  1136. total_entity_len = 0
  1137. num_invalid_entities = 0
  1138. valid_entity_ids = [ent_id for ent_id, span in zip(entity_ids, entity_token_spans) if span[1] <= len(ids)]
  1139. valid_entity_token_spans = [span for span in entity_token_spans if span[1] <= len(ids)]
  1140. total_entity_len += len(valid_entity_ids)
  1141. num_invalid_entities += len(entity_ids) - len(valid_entity_ids)
  1142. valid_pair_entity_ids, valid_pair_entity_token_spans = None, None
  1143. if pair_entity_ids is not None:
  1144. valid_pair_entity_ids = [
  1145. ent_id
  1146. for ent_id, span in zip(pair_entity_ids, pair_entity_token_spans)
  1147. if span[1] <= len(pair_ids)
  1148. ]
  1149. valid_pair_entity_token_spans = [span for span in pair_entity_token_spans if span[1] <= len(pair_ids)]
  1150. total_entity_len += len(valid_pair_entity_ids)
  1151. num_invalid_entities += len(pair_entity_ids) - len(valid_pair_entity_ids)
  1152. if num_invalid_entities != 0:
  1153. logger.warning(
  1154. f"{num_invalid_entities} entities are ignored because their entity spans are invalid due to the"
  1155. " truncation of input tokens"
  1156. )
  1157. if truncation_strategy != TruncationStrategy.DO_NOT_TRUNCATE and total_entity_len > max_entity_length:
  1158. # truncate entities up to max_entity_length
  1159. valid_entity_ids, valid_pair_entity_ids, overflowing_entities = self.truncate_sequences(
  1160. valid_entity_ids,
  1161. pair_ids=valid_pair_entity_ids,
  1162. num_tokens_to_remove=total_entity_len - max_entity_length,
  1163. truncation_strategy=truncation_strategy,
  1164. stride=stride,
  1165. )
  1166. valid_entity_token_spans = valid_entity_token_spans[: len(valid_entity_ids)]
  1167. if valid_pair_entity_token_spans is not None:
  1168. valid_pair_entity_token_spans = valid_pair_entity_token_spans[: len(valid_pair_entity_ids)]
  1169. if return_overflowing_tokens:
  1170. encoded_inputs["overflowing_entities"] = overflowing_entities
  1171. encoded_inputs["num_truncated_entities"] = total_entity_len - max_entity_length
  1172. final_entity_ids = valid_entity_ids + valid_pair_entity_ids if valid_pair_entity_ids else valid_entity_ids
  1173. encoded_inputs["entity_ids"] = list(final_entity_ids)
  1174. entity_position_ids = []
  1175. entity_start_positions = []
  1176. entity_end_positions = []
  1177. for token_spans, offset in (
  1178. (valid_entity_token_spans, entity_token_offset),
  1179. (valid_pair_entity_token_spans, pair_entity_token_offset),
  1180. ):
  1181. if token_spans is not None:
  1182. for start, end in token_spans:
  1183. start += offset
  1184. end += offset
  1185. position_ids = list(range(start, end))[: self.max_mention_length]
  1186. position_ids += [-1] * (self.max_mention_length - end + start)
  1187. entity_position_ids.append(position_ids)
  1188. entity_start_positions.append(start)
  1189. entity_end_positions.append(end - 1)
  1190. encoded_inputs["entity_position_ids"] = entity_position_ids
  1191. if self.task == "entity_span_classification":
  1192. encoded_inputs["entity_start_positions"] = entity_start_positions
  1193. encoded_inputs["entity_end_positions"] = entity_end_positions
  1194. if return_token_type_ids:
  1195. encoded_inputs["entity_token_type_ids"] = [0] * len(encoded_inputs["entity_ids"])
  1196. # Check lengths
  1197. self._eventual_warn_about_too_long_sequence(encoded_inputs["input_ids"], max_length, verbose)
  1198. # Padding
  1199. if padding_strategy != PaddingStrategy.DO_NOT_PAD or return_attention_mask:
  1200. encoded_inputs = self.pad(
  1201. encoded_inputs,
  1202. max_length=max_length,
  1203. max_entity_length=max_entity_length,
  1204. padding=padding_strategy.value,
  1205. pad_to_multiple_of=pad_to_multiple_of,
  1206. padding_side=padding_side,
  1207. return_attention_mask=return_attention_mask,
  1208. )
  1209. if return_length:
  1210. encoded_inputs["length"] = len(encoded_inputs["input_ids"])
  1211. batch_outputs = BatchEncoding(
  1212. encoded_inputs, tensor_type=return_tensors, prepend_batch_axis=prepend_batch_axis
  1213. )
  1214. return batch_outputs
  1215. def pad(
  1216. self,
  1217. encoded_inputs: Union[
  1218. BatchEncoding,
  1219. List[BatchEncoding],
  1220. Dict[str, EncodedInput],
  1221. Dict[str, List[EncodedInput]],
  1222. List[Dict[str, EncodedInput]],
  1223. ],
  1224. padding: Union[bool, str, PaddingStrategy] = True,
  1225. max_length: Optional[int] = None,
  1226. max_entity_length: Optional[int] = None,
  1227. pad_to_multiple_of: Optional[int] = None,
  1228. padding_side: Optional[bool] = None,
  1229. return_attention_mask: Optional[bool] = None,
  1230. return_tensors: Optional[Union[str, TensorType]] = None,
  1231. verbose: bool = True,
  1232. ) -> BatchEncoding:
  1233. """
  1234. Pad a single encoded input or a batch of encoded inputs up to predefined length or to the max sequence length
  1235. in the batch. Padding side (left/right) padding token ids are defined at the tokenizer level (with
  1236. `self.padding_side`, `self.pad_token_id` and `self.pad_token_type_id`) .. note:: If the `encoded_inputs` passed
  1237. are dictionary of numpy arrays, PyTorch tensors or TensorFlow tensors, the result will use the same type unless
  1238. you provide a different tensor type with `return_tensors`. In the case of PyTorch tensors, you will lose the
  1239. specific device of your tensors however.
  1240. Args:
  1241. encoded_inputs ([`BatchEncoding`], list of [`BatchEncoding`], `Dict[str, List[int]]`, `Dict[str, List[List[int]]` or `List[Dict[str, List[int]]]`):
  1242. Tokenized inputs. Can represent one input ([`BatchEncoding`] or `Dict[str, List[int]]`) or a batch of
  1243. tokenized inputs (list of [`BatchEncoding`], *Dict[str, List[List[int]]]* or *List[Dict[str,
  1244. List[int]]]*) so you can use this method during preprocessing as well as in a PyTorch Dataloader
  1245. collate function. Instead of `List[int]` you can have tensors (numpy arrays, PyTorch tensors or
  1246. TensorFlow tensors), see the note above for the return type.
  1247. padding (`bool`, `str` or [`~utils.PaddingStrategy`], *optional*, defaults to `True`):
  1248. Select a strategy to pad the returned sequences (according to the model's padding side and padding
  1249. index) among:
  1250. - `True` or `'longest'`: Pad to the longest sequence in the batch (or no padding if only a single
  1251. sequence if provided).
  1252. - `'max_length'`: Pad to a maximum length specified with the argument `max_length` or to the maximum
  1253. acceptable input length for the model if that argument is not provided.
  1254. - `False` or `'do_not_pad'` (default): No padding (i.e., can output a batch with sequences of different
  1255. lengths).
  1256. max_length (`int`, *optional*):
  1257. Maximum length of the returned list and optionally padding length (see above).
  1258. max_entity_length (`int`, *optional*):
  1259. The maximum length of the entity sequence.
  1260. pad_to_multiple_of (`int`, *optional*):
  1261. If set will pad the sequence to a multiple of the provided value. This is especially useful to enable
  1262. the use of Tensor Cores on NVIDIA hardware with compute capability `>= 7.5` (Volta).
  1263. padding_side:
  1264. The side on which the model should have padding applied. Should be selected between ['right', 'left'].
  1265. Default value is picked from the class attribute of the same name.
  1266. return_attention_mask (`bool`, *optional*):
  1267. Whether to return the attention mask. If left to the default, will return the attention mask according
  1268. to the specific tokenizer's default, defined by the `return_outputs` attribute. [What are attention
  1269. masks?](../glossary#attention-mask)
  1270. return_tensors (`str` or [`~utils.TensorType`], *optional*):
  1271. If set, will return tensors instead of list of python integers. Acceptable values are:
  1272. - `'tf'`: Return TensorFlow `tf.constant` objects.
  1273. - `'pt'`: Return PyTorch `torch.Tensor` objects.
  1274. - `'np'`: Return Numpy `np.ndarray` objects.
  1275. verbose (`bool`, *optional*, defaults to `True`):
  1276. Whether or not to print more information and warnings.
  1277. """
  1278. # If we have a list of dicts, let's convert it in a dict of lists
  1279. # We do this to allow using this method as a collate_fn function in PyTorch Dataloader
  1280. if isinstance(encoded_inputs, (list, tuple)) and isinstance(encoded_inputs[0], Mapping):
  1281. encoded_inputs = {key: [example[key] for example in encoded_inputs] for key in encoded_inputs[0].keys()}
  1282. # The model's main input name, usually `input_ids`, has be passed for padding
  1283. if self.model_input_names[0] not in encoded_inputs:
  1284. raise ValueError(
  1285. "You should supply an encoding or a list of encodings to this method "
  1286. f"that includes {self.model_input_names[0]}, but you provided {list(encoded_inputs.keys())}"
  1287. )
  1288. required_input = encoded_inputs[self.model_input_names[0]]
  1289. if not required_input:
  1290. if return_attention_mask:
  1291. encoded_inputs["attention_mask"] = []
  1292. return encoded_inputs
  1293. # If we have PyTorch/TF/NumPy tensors/arrays as inputs, we cast them as python objects
  1294. # and rebuild them afterwards if no return_tensors is specified
  1295. # Note that we lose the specific device the tensor may be on for PyTorch
  1296. first_element = required_input[0]
  1297. if isinstance(first_element, (list, tuple)):
  1298. # first_element might be an empty list/tuple in some edge cases so we grab the first non empty element.
  1299. index = 0
  1300. while len(required_input[index]) == 0:
  1301. index += 1
  1302. if index < len(required_input):
  1303. first_element = required_input[index][0]
  1304. # At this state, if `first_element` is still a list/tuple, it's an empty one so there is nothing to do.
  1305. if not isinstance(first_element, (int, list, tuple)):
  1306. if is_tf_tensor(first_element):
  1307. return_tensors = "tf" if return_tensors is None else return_tensors
  1308. elif is_torch_tensor(first_element):
  1309. return_tensors = "pt" if return_tensors is None else return_tensors
  1310. elif isinstance(first_element, np.ndarray):
  1311. return_tensors = "np" if return_tensors is None else return_tensors
  1312. else:
  1313. raise ValueError(
  1314. f"type of {first_element} unknown: {type(first_element)}. "
  1315. "Should be one of a python, numpy, pytorch or tensorflow object."
  1316. )
  1317. for key, value in encoded_inputs.items():
  1318. encoded_inputs[key] = to_py_obj(value)
  1319. # Convert padding_strategy in PaddingStrategy
  1320. padding_strategy, _, max_length, _ = self._get_padding_truncation_strategies(
  1321. padding=padding, max_length=max_length, verbose=verbose
  1322. )
  1323. if max_entity_length is None:
  1324. max_entity_length = self.max_entity_length
  1325. required_input = encoded_inputs[self.model_input_names[0]]
  1326. if required_input and not isinstance(required_input[0], (list, tuple)):
  1327. encoded_inputs = self._pad(
  1328. encoded_inputs,
  1329. max_length=max_length,
  1330. max_entity_length=max_entity_length,
  1331. padding_strategy=padding_strategy,
  1332. pad_to_multiple_of=pad_to_multiple_of,
  1333. padding_side=padding_side,
  1334. return_attention_mask=return_attention_mask,
  1335. )
  1336. return BatchEncoding(encoded_inputs, tensor_type=return_tensors)
  1337. batch_size = len(required_input)
  1338. if any(len(v) != batch_size for v in encoded_inputs.values()):
  1339. raise ValueError("Some items in the output dictionary have a different batch size than others.")
  1340. if padding_strategy == PaddingStrategy.LONGEST:
  1341. max_length = max(len(inputs) for inputs in required_input)
  1342. max_entity_length = (
  1343. max(len(inputs) for inputs in encoded_inputs["entity_ids"]) if "entity_ids" in encoded_inputs else 0
  1344. )
  1345. padding_strategy = PaddingStrategy.MAX_LENGTH
  1346. batch_outputs = {}
  1347. for i in range(batch_size):
  1348. inputs = {k: v[i] for k, v in encoded_inputs.items()}
  1349. outputs = self._pad(
  1350. inputs,
  1351. max_length=max_length,
  1352. max_entity_length=max_entity_length,
  1353. padding_strategy=padding_strategy,
  1354. pad_to_multiple_of=pad_to_multiple_of,
  1355. padding_side=padding_side,
  1356. return_attention_mask=return_attention_mask,
  1357. )
  1358. for key, value in outputs.items():
  1359. if key not in batch_outputs:
  1360. batch_outputs[key] = []
  1361. batch_outputs[key].append(value)
  1362. return BatchEncoding(batch_outputs, tensor_type=return_tensors)
  1363. def _pad(
  1364. self,
  1365. encoded_inputs: Union[Dict[str, EncodedInput], BatchEncoding],
  1366. max_length: Optional[int] = None,
  1367. max_entity_length: Optional[int] = None,
  1368. padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD,
  1369. pad_to_multiple_of: Optional[int] = None,
  1370. padding_side: Optional[bool] = None,
  1371. return_attention_mask: Optional[bool] = None,
  1372. ) -> dict:
  1373. """
  1374. Pad encoded inputs (on left/right and up to predefined length or max length in the batch)
  1375. Args:
  1376. encoded_inputs:
  1377. Dictionary of tokenized inputs (`List[int]`) or batch of tokenized inputs (`List[List[int]]`).
  1378. max_length: maximum length of the returned list and optionally padding length (see below).
  1379. Will truncate by taking into account the special tokens.
  1380. max_entity_length: The maximum length of the entity sequence.
  1381. padding_strategy: PaddingStrategy to use for padding.
  1382. - PaddingStrategy.LONGEST Pad to the longest sequence in the batch
  1383. - PaddingStrategy.MAX_LENGTH: Pad to the max length (default)
  1384. - PaddingStrategy.DO_NOT_PAD: Do not pad
  1385. The tokenizer padding sides are defined in self.padding_side:
  1386. - 'left': pads on the left of the sequences
  1387. - 'right': pads on the right of the sequences
  1388. pad_to_multiple_of: (optional) Integer if set will pad the sequence to a multiple of the provided value.
  1389. This is especially useful to enable the use of Tensor Core on NVIDIA hardware with compute capability
  1390. `>= 7.5` (Volta).
  1391. padding_side:
  1392. The side on which the model should have padding applied. Should be selected between ['right', 'left'].
  1393. Default value is picked from the class attribute of the same name.
  1394. return_attention_mask:
  1395. (optional) Set to False to avoid returning attention mask (default: set to model specifics)
  1396. """
  1397. entities_provided = bool("entity_ids" in encoded_inputs)
  1398. # Load from model defaults
  1399. if return_attention_mask is None:
  1400. return_attention_mask = "attention_mask" in self.model_input_names
  1401. if padding_strategy == PaddingStrategy.LONGEST:
  1402. max_length = len(encoded_inputs["input_ids"])
  1403. if entities_provided:
  1404. max_entity_length = len(encoded_inputs["entity_ids"])
  1405. if max_length is not None and pad_to_multiple_of is not None and (max_length % pad_to_multiple_of != 0):
  1406. max_length = ((max_length // pad_to_multiple_of) + 1) * pad_to_multiple_of
  1407. if (
  1408. entities_provided
  1409. and max_entity_length is not None
  1410. and pad_to_multiple_of is not None
  1411. and (max_entity_length % pad_to_multiple_of != 0)
  1412. ):
  1413. max_entity_length = ((max_entity_length // pad_to_multiple_of) + 1) * pad_to_multiple_of
  1414. needs_to_be_padded = padding_strategy != PaddingStrategy.DO_NOT_PAD and (
  1415. len(encoded_inputs["input_ids"]) != max_length
  1416. or (entities_provided and len(encoded_inputs["entity_ids"]) != max_entity_length)
  1417. )
  1418. # Initialize attention mask if not present.
  1419. if return_attention_mask and "attention_mask" not in encoded_inputs:
  1420. encoded_inputs["attention_mask"] = [1] * len(encoded_inputs["input_ids"])
  1421. if entities_provided and return_attention_mask and "entity_attention_mask" not in encoded_inputs:
  1422. encoded_inputs["entity_attention_mask"] = [1] * len(encoded_inputs["entity_ids"])
  1423. if needs_to_be_padded:
  1424. difference = max_length - len(encoded_inputs["input_ids"])
  1425. padding_side = padding_side if padding_side is not None else self.padding_side
  1426. if entities_provided:
  1427. entity_difference = max_entity_length - len(encoded_inputs["entity_ids"])
  1428. if padding_side == "right":
  1429. if return_attention_mask:
  1430. encoded_inputs["attention_mask"] = encoded_inputs["attention_mask"] + [0] * difference
  1431. if entities_provided:
  1432. encoded_inputs["entity_attention_mask"] = (
  1433. encoded_inputs["entity_attention_mask"] + [0] * entity_difference
  1434. )
  1435. if "token_type_ids" in encoded_inputs:
  1436. encoded_inputs["token_type_ids"] = encoded_inputs["token_type_ids"] + [0] * difference
  1437. if entities_provided:
  1438. encoded_inputs["entity_token_type_ids"] = (
  1439. encoded_inputs["entity_token_type_ids"] + [0] * entity_difference
  1440. )
  1441. if "special_tokens_mask" in encoded_inputs:
  1442. encoded_inputs["special_tokens_mask"] = encoded_inputs["special_tokens_mask"] + [1] * difference
  1443. encoded_inputs["input_ids"] = encoded_inputs["input_ids"] + [self.pad_token_id] * difference
  1444. if entities_provided:
  1445. encoded_inputs["entity_ids"] = (
  1446. encoded_inputs["entity_ids"] + [self.entity_pad_token_id] * entity_difference
  1447. )
  1448. encoded_inputs["entity_position_ids"] = (
  1449. encoded_inputs["entity_position_ids"] + [[-1] * self.max_mention_length] * entity_difference
  1450. )
  1451. if self.task == "entity_span_classification":
  1452. encoded_inputs["entity_start_positions"] = (
  1453. encoded_inputs["entity_start_positions"] + [0] * entity_difference
  1454. )
  1455. encoded_inputs["entity_end_positions"] = (
  1456. encoded_inputs["entity_end_positions"] + [0] * entity_difference
  1457. )
  1458. elif padding_side == "left":
  1459. if return_attention_mask:
  1460. encoded_inputs["attention_mask"] = [0] * difference + encoded_inputs["attention_mask"]
  1461. if entities_provided:
  1462. encoded_inputs["entity_attention_mask"] = [0] * entity_difference + encoded_inputs[
  1463. "entity_attention_mask"
  1464. ]
  1465. if "token_type_ids" in encoded_inputs:
  1466. encoded_inputs["token_type_ids"] = [0] * difference + encoded_inputs["token_type_ids"]
  1467. if entities_provided:
  1468. encoded_inputs["entity_token_type_ids"] = [0] * entity_difference + encoded_inputs[
  1469. "entity_token_type_ids"
  1470. ]
  1471. if "special_tokens_mask" in encoded_inputs:
  1472. encoded_inputs["special_tokens_mask"] = [1] * difference + encoded_inputs["special_tokens_mask"]
  1473. encoded_inputs["input_ids"] = [self.pad_token_id] * difference + encoded_inputs["input_ids"]
  1474. if entities_provided:
  1475. encoded_inputs["entity_ids"] = [self.entity_pad_token_id] * entity_difference + encoded_inputs[
  1476. "entity_ids"
  1477. ]
  1478. encoded_inputs["entity_position_ids"] = [
  1479. [-1] * self.max_mention_length
  1480. ] * entity_difference + encoded_inputs["entity_position_ids"]
  1481. if self.task == "entity_span_classification":
  1482. encoded_inputs["entity_start_positions"] = [0] * entity_difference + encoded_inputs[
  1483. "entity_start_positions"
  1484. ]
  1485. encoded_inputs["entity_end_positions"] = [0] * entity_difference + encoded_inputs[
  1486. "entity_end_positions"
  1487. ]
  1488. else:
  1489. raise ValueError("Invalid padding strategy:" + str(padding_side))
  1490. return encoded_inputs
  1491. def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
  1492. if not os.path.isdir(save_directory):
  1493. logger.error(f"Vocabulary path ({save_directory}) should be a directory")
  1494. return
  1495. vocab_file = os.path.join(
  1496. save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
  1497. )
  1498. merge_file = os.path.join(
  1499. save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["merges_file"]
  1500. )
  1501. with open(vocab_file, "w", encoding="utf-8") as f:
  1502. f.write(json.dumps(self.encoder, indent=2, sort_keys=True, ensure_ascii=False) + "\n")
  1503. index = 0
  1504. with open(merge_file, "w", encoding="utf-8") as writer:
  1505. writer.write("#version: 0.2\n")
  1506. for bpe_tokens, token_index in sorted(self.bpe_ranks.items(), key=lambda kv: kv[1]):
  1507. if index != token_index:
  1508. logger.warning(
  1509. f"Saving vocabulary to {merge_file}: BPE merge indices are not consecutive."
  1510. " Please check that the tokenizer is not corrupted!"
  1511. )
  1512. index = token_index
  1513. writer.write(" ".join(bpe_tokens) + "\n")
  1514. index += 1
  1515. entity_vocab_file = os.path.join(
  1516. save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["entity_vocab_file"]
  1517. )
  1518. with open(entity_vocab_file, "w", encoding="utf-8") as f:
  1519. f.write(json.dumps(self.entity_vocab, indent=2, sort_keys=True, ensure_ascii=False) + "\n")
  1520. return vocab_file, merge_file, entity_vocab_file