tokenization_mluke.py 80 KB

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