tokenization_luke.py 80 KB

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