tokenization_markuplm.py 68 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468
  1. # coding=utf-8
  2. # Copyright Microsoft Research and The HuggingFace Inc. team. All rights reserved.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. """Tokenization class for MarkupLM."""
  16. import json
  17. import os
  18. from functools import lru_cache
  19. from typing import Dict, List, Optional, Tuple, Union
  20. import regex as re
  21. from ...file_utils import PaddingStrategy, TensorType, add_end_docstrings
  22. from ...tokenization_utils import AddedToken, PreTrainedTokenizer
  23. from ...tokenization_utils_base import (
  24. ENCODE_KWARGS_DOCSTRING,
  25. BatchEncoding,
  26. EncodedInput,
  27. PreTokenizedInput,
  28. TextInput,
  29. TextInputPair,
  30. TruncationStrategy,
  31. )
  32. from ...utils import logging
  33. logger = logging.get_logger(__name__)
  34. VOCAB_FILES_NAMES = {"vocab_file": "vocab.json", "merges_file": "merges.txt", "tokenizer_file": "tokenizer.json"}
  35. MARKUPLM_ENCODE_PLUS_ADDITIONAL_KWARGS_DOCSTRING = r"""
  36. add_special_tokens (`bool`, *optional*, defaults to `True`):
  37. Whether or not to encode the sequences with the special tokens relative to their model.
  38. padding (`bool`, `str` or [`~file_utils.PaddingStrategy`], *optional*, defaults to `False`):
  39. Activates and controls padding. Accepts the following values:
  40. - `True` or `'longest'`: Pad to the longest sequence in the batch (or no padding if only a single
  41. sequence if provided).
  42. - `'max_length'`: Pad to a maximum length specified with the argument `max_length` or to the maximum
  43. acceptable input length for the model if that argument is not provided.
  44. - `False` or `'do_not_pad'` (default): No padding (i.e., can output a batch with sequences of different
  45. lengths).
  46. truncation (`bool`, `str` or [`~tokenization_utils_base.TruncationStrategy`], *optional*, defaults to `False`):
  47. Activates and controls truncation. Accepts the following values:
  48. - `True` or `'longest_first'`: Truncate to a maximum length specified with the argument `max_length` or
  49. to the maximum acceptable input length for the model if that argument is not provided. This will
  50. truncate token by token, removing a token from the longest sequence in the pair if a pair of
  51. sequences (or a batch of pairs) is provided.
  52. - `'only_first'`: Truncate to a maximum length specified with the argument `max_length` or to the
  53. maximum acceptable input length for the model if that argument is not provided. This will only
  54. truncate the first sequence of a pair if a pair of sequences (or a batch of pairs) is provided.
  55. - `'only_second'`: Truncate to a maximum length specified with the argument `max_length` or to the
  56. maximum acceptable input length for the model if that argument is not provided. This will only
  57. truncate the second sequence of a pair if a pair of sequences (or a batch of pairs) is provided.
  58. - `False` or `'do_not_truncate'` (default): No truncation (i.e., can output batch with sequence lengths
  59. greater than the model maximum admissible input size).
  60. max_length (`int`, *optional*):
  61. Controls the maximum length to use by one of the truncation/padding parameters. If left unset or set to
  62. `None`, this will use the predefined model maximum length if a maximum length is required by one of the
  63. truncation/padding parameters. If the model has no specific maximum input length (like XLNet)
  64. truncation/padding to a maximum length will be deactivated.
  65. stride (`int`, *optional*, defaults to 0):
  66. If set to a number along with `max_length`, the overflowing tokens returned when
  67. `return_overflowing_tokens=True` will contain some tokens from the end of the truncated sequence
  68. returned to provide some overlap between truncated and overflowing sequences. The value of this
  69. argument defines the number of overlapping tokens.
  70. pad_to_multiple_of (`int`, *optional*):
  71. If set will pad the sequence to a multiple of the provided value. This is especially useful to enable
  72. the use of Tensor Cores on NVIDIA hardware with compute capability `>= 7.5` (Volta).
  73. return_tensors (`str` or [`~file_utils.TensorType`], *optional*):
  74. If set, will return tensors instead of list of python integers. Acceptable values are:
  75. - `'tf'`: Return TensorFlow `tf.constant` objects.
  76. - `'pt'`: Return PyTorch `torch.Tensor` objects.
  77. - `'np'`: Return Numpy `np.ndarray` objects.
  78. """
  79. @lru_cache()
  80. def bytes_to_unicode():
  81. """
  82. Returns list of utf-8 byte and a mapping to unicode strings. We specifically avoids mapping to whitespace/control
  83. characters the bpe code barfs on. The reversible bpe codes work on unicode strings. This means you need a large #
  84. of unicode characters in your vocab if you want to avoid UNKs. When you're at something like a 10B token dataset
  85. you end up needing around 5K for decent coverage. This is a significant percentage of your normal, say, 32K bpe
  86. vocab. To avoid that, we want lookup tables between utf-8 bytes and unicode strings.
  87. """
  88. bs = (
  89. list(range(ord("!"), ord("~") + 1)) + list(range(ord("¡"), ord("¬") + 1)) + list(range(ord("®"), ord("ÿ") + 1))
  90. )
  91. cs = bs[:]
  92. n = 0
  93. for b in range(2**8):
  94. if b not in bs:
  95. bs.append(b)
  96. cs.append(2**8 + n)
  97. n += 1
  98. cs = [chr(n) for n in cs]
  99. return dict(zip(bs, cs))
  100. def get_pairs(word):
  101. """
  102. Return set of symbol pairs in a word. Word is represented as tuple of symbols (symbols being variable-length
  103. strings).
  104. """
  105. pairs = set()
  106. prev_char = word[0]
  107. for char in word[1:]:
  108. pairs.add((prev_char, char))
  109. prev_char = char
  110. return pairs
  111. class MarkupLMTokenizer(PreTrainedTokenizer):
  112. r"""
  113. Construct a MarkupLM tokenizer. Based on byte-level Byte-Pair-Encoding (BPE). [`MarkupLMTokenizer`] can be used to
  114. turn HTML strings into to token-level `input_ids`, `attention_mask`, `token_type_ids`, `xpath_tags_seq` and
  115. `xpath_tags_seq`. This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods.
  116. Users should refer to this superclass for more information regarding those methods.
  117. Args:
  118. vocab_file (`str`):
  119. Path to the vocabulary file.
  120. merges_file (`str`):
  121. Path to the merges file.
  122. errors (`str`, *optional*, defaults to `"replace"`):
  123. Paradigm to follow when decoding bytes to UTF-8. See
  124. [bytes.decode](https://docs.python.org/3/library/stdtypes.html#bytes.decode) for more information.
  125. bos_token (`str`, *optional*, defaults to `"<s>"`):
  126. The beginning of sequence token that was used during pretraining. Can be used a sequence classifier token.
  127. <Tip>
  128. When building a sequence using special tokens, this is not the token that is used for the beginning of
  129. sequence. The token used is the `cls_token`.
  130. </Tip>
  131. eos_token (`str`, *optional*, defaults to `"</s>"`):
  132. The end of sequence token.
  133. <Tip>
  134. When building a sequence using special tokens, this is not the token that is used for the end of sequence.
  135. The token used is the `sep_token`.
  136. </Tip>
  137. sep_token (`str`, *optional*, defaults to `"</s>"`):
  138. The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
  139. sequence classification or for a text and a question for question answering. It is also used as the last
  140. token of a sequence built with special tokens.
  141. cls_token (`str`, *optional*, defaults to `"<s>"`):
  142. The classifier token which is used when doing sequence classification (classification of the whole sequence
  143. instead of per-token classification). It is the first token of the sequence when built with special tokens.
  144. unk_token (`str`, *optional*, defaults to `"<unk>"`):
  145. The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
  146. token instead.
  147. pad_token (`str`, *optional*, defaults to `"<pad>"`):
  148. The token used for padding, for example when batching sequences of different lengths.
  149. mask_token (`str`, *optional*, defaults to `"<mask>"`):
  150. The token used for masking values. This is the token used when training this model with masked language
  151. modeling. This is the token which the model will try to predict.
  152. add_prefix_space (`bool`, *optional*, defaults to `False`):
  153. Whether or not to add an initial space to the input. This allows to treat the leading word just as any
  154. other word. (RoBERTa tokenizer detect beginning of words by the preceding space).
  155. """
  156. vocab_files_names = VOCAB_FILES_NAMES
  157. def __init__(
  158. self,
  159. vocab_file,
  160. merges_file,
  161. tags_dict,
  162. errors="replace",
  163. bos_token="<s>",
  164. eos_token="</s>",
  165. sep_token="</s>",
  166. cls_token="<s>",
  167. unk_token="<unk>",
  168. pad_token="<pad>",
  169. mask_token="<mask>",
  170. add_prefix_space=False,
  171. max_depth=50,
  172. max_width=1000,
  173. pad_width=1001,
  174. pad_token_label=-100,
  175. only_label_first_subword=True,
  176. **kwargs,
  177. ):
  178. bos_token = AddedToken(bos_token, lstrip=False, rstrip=False) if isinstance(bos_token, str) else bos_token
  179. eos_token = AddedToken(eos_token, lstrip=False, rstrip=False) if isinstance(eos_token, str) else eos_token
  180. sep_token = AddedToken(sep_token, lstrip=False, rstrip=False) if isinstance(sep_token, str) else sep_token
  181. cls_token = AddedToken(cls_token, lstrip=False, rstrip=False) if isinstance(cls_token, str) else cls_token
  182. unk_token = AddedToken(unk_token, lstrip=False, rstrip=False) if isinstance(unk_token, str) else unk_token
  183. pad_token = AddedToken(pad_token, lstrip=False, rstrip=False) if isinstance(pad_token, str) else pad_token
  184. # Mask token behave like a normal word, i.e. include the space before it
  185. mask_token = AddedToken(mask_token, lstrip=True, rstrip=False) if isinstance(mask_token, str) else mask_token
  186. with open(vocab_file, encoding="utf-8") as vocab_handle:
  187. self.encoder = json.load(vocab_handle)
  188. self.tags_dict = tags_dict
  189. self.decoder = {v: k for k, v in self.encoder.items()}
  190. self.errors = errors # how to handle errors in decoding
  191. self.byte_encoder = bytes_to_unicode()
  192. self.byte_decoder = {v: k for k, v in self.byte_encoder.items()}
  193. with open(merges_file, encoding="utf-8") as merges_handle:
  194. bpe_merges = merges_handle.read().split("\n")[1:-1]
  195. bpe_merges = [tuple(merge.split()) for merge in bpe_merges]
  196. self.bpe_ranks = dict(zip(bpe_merges, range(len(bpe_merges))))
  197. self.cache = {}
  198. self.add_prefix_space = add_prefix_space
  199. # Should have added re.IGNORECASE so BPE merges can happen for capitalized versions of contractions
  200. self.pat = re.compile(r"""'s|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+""")
  201. # additional properties
  202. self.max_depth = max_depth
  203. self.max_width = max_width
  204. self.pad_width = pad_width
  205. self.unk_tag_id = len(self.tags_dict)
  206. self.pad_tag_id = self.unk_tag_id + 1
  207. self.pad_xpath_tags_seq = [self.pad_tag_id] * self.max_depth
  208. self.pad_xpath_subs_seq = [self.pad_width] * self.max_depth
  209. super().__init__(
  210. vocab_file=vocab_file,
  211. merges_file=merges_file,
  212. tags_dict=tags_dict,
  213. errors=errors,
  214. bos_token=bos_token,
  215. eos_token=eos_token,
  216. unk_token=unk_token,
  217. sep_token=sep_token,
  218. cls_token=cls_token,
  219. pad_token=pad_token,
  220. mask_token=mask_token,
  221. add_prefix_space=add_prefix_space,
  222. max_depth=max_depth,
  223. max_width=max_width,
  224. pad_width=pad_width,
  225. pad_token_label=pad_token_label,
  226. only_label_first_subword=only_label_first_subword,
  227. **kwargs,
  228. )
  229. self.pad_token_label = pad_token_label
  230. self.only_label_first_subword = only_label_first_subword
  231. def get_xpath_seq(self, xpath):
  232. """
  233. Given the xpath expression of one particular node (like "/html/body/div/li[1]/div/span[2]"), return a list of
  234. tag IDs and corresponding subscripts, taking into account max depth.
  235. """
  236. xpath_tags_list = []
  237. xpath_subs_list = []
  238. xpath_units = xpath.split("/")
  239. for unit in xpath_units:
  240. if not unit.strip():
  241. continue
  242. name_subs = unit.strip().split("[")
  243. tag_name = name_subs[0]
  244. sub = 0 if len(name_subs) == 1 else int(name_subs[1][:-1])
  245. xpath_tags_list.append(self.tags_dict.get(tag_name, self.unk_tag_id))
  246. xpath_subs_list.append(min(self.max_width, sub))
  247. xpath_tags_list = xpath_tags_list[: self.max_depth]
  248. xpath_subs_list = xpath_subs_list[: self.max_depth]
  249. xpath_tags_list += [self.pad_tag_id] * (self.max_depth - len(xpath_tags_list))
  250. xpath_subs_list += [self.pad_width] * (self.max_depth - len(xpath_subs_list))
  251. return xpath_tags_list, xpath_subs_list
  252. @property
  253. def vocab_size(self):
  254. return len(self.encoder)
  255. def get_vocab(self):
  256. vocab = self.encoder.copy()
  257. vocab.update(self.added_tokens_encoder)
  258. return vocab
  259. def bpe(self, token):
  260. if token in self.cache:
  261. return self.cache[token]
  262. word = tuple(token)
  263. pairs = get_pairs(word)
  264. if not pairs:
  265. return token
  266. while True:
  267. bigram = min(pairs, key=lambda pair: self.bpe_ranks.get(pair, float("inf")))
  268. if bigram not in self.bpe_ranks:
  269. break
  270. first, second = bigram
  271. new_word = []
  272. i = 0
  273. while i < len(word):
  274. try:
  275. j = word.index(first, i)
  276. except ValueError:
  277. new_word.extend(word[i:])
  278. break
  279. else:
  280. new_word.extend(word[i:j])
  281. i = j
  282. if word[i] == first and i < len(word) - 1 and word[i + 1] == second:
  283. new_word.append(first + second)
  284. i += 2
  285. else:
  286. new_word.append(word[i])
  287. i += 1
  288. new_word = tuple(new_word)
  289. word = new_word
  290. if len(word) == 1:
  291. break
  292. else:
  293. pairs = get_pairs(word)
  294. word = " ".join(word)
  295. self.cache[token] = word
  296. return word
  297. def _tokenize(self, text):
  298. """Tokenize a string."""
  299. bpe_tokens = []
  300. for token in re.findall(self.pat, text):
  301. token = "".join(
  302. self.byte_encoder[b] for b in token.encode("utf-8")
  303. ) # Maps all our bytes to unicode strings, avoiding control tokens of the BPE (spaces in our case)
  304. bpe_tokens.extend(bpe_token for bpe_token in self.bpe(token).split(" "))
  305. return bpe_tokens
  306. def _convert_token_to_id(self, token):
  307. """Converts a token (str) in an id using the vocab."""
  308. return self.encoder.get(token, self.encoder.get(self.unk_token))
  309. def _convert_id_to_token(self, index):
  310. """Converts an index (integer) in a token (str) using the vocab."""
  311. return self.decoder.get(index)
  312. def convert_tokens_to_string(self, tokens):
  313. """Converts a sequence of tokens (string) in a single string."""
  314. logger.warning(
  315. "MarkupLM now does not support generative tasks, decoding is experimental and subject to change."
  316. )
  317. text = "".join(tokens)
  318. text = bytearray([self.byte_decoder[c] for c in text]).decode("utf-8", errors=self.errors)
  319. return text
  320. def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
  321. if not os.path.isdir(save_directory):
  322. logger.error(f"Vocabulary path ({save_directory}) should be a directory")
  323. return
  324. vocab_file = os.path.join(
  325. save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
  326. )
  327. merge_file = os.path.join(
  328. save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["merges_file"]
  329. )
  330. # save vocab_file
  331. with open(vocab_file, "w", encoding="utf-8") as f:
  332. f.write(json.dumps(self.encoder, indent=2, sort_keys=True, ensure_ascii=False) + "\n")
  333. # save merge_file
  334. index = 0
  335. with open(merge_file, "w", encoding="utf-8") as writer:
  336. writer.write("#version: 0.2\n")
  337. for bpe_tokens, token_index in sorted(self.bpe_ranks.items(), key=lambda kv: kv[1]):
  338. if index != token_index:
  339. logger.warning(
  340. f"Saving vocabulary to {merge_file}: BPE merge indices are not consecutive."
  341. " Please check that the tokenizer is not corrupted!"
  342. )
  343. index = token_index
  344. writer.write(" ".join(bpe_tokens) + "\n")
  345. index += 1
  346. return vocab_file, merge_file
  347. def prepare_for_tokenization(self, text, is_split_into_words=False, **kwargs):
  348. add_prefix_space = kwargs.pop("add_prefix_space", self.add_prefix_space)
  349. if (is_split_into_words or add_prefix_space) and (len(text) > 0 and not text[0].isspace()):
  350. text = " " + text
  351. return (text, kwargs)
  352. def build_inputs_with_special_tokens(
  353. self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
  354. ) -> List[int]:
  355. """
  356. Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
  357. adding special tokens. A RoBERTa sequence has the following format:
  358. - single sequence: `<s> X </s>`
  359. - pair of sequences: `<s> A </s></s> B </s>`
  360. Args:
  361. token_ids_0 (`List[int]`):
  362. List of IDs to which the special tokens will be added.
  363. token_ids_1 (`List[int]`, *optional*):
  364. Optional second list of IDs for sequence pairs.
  365. Returns:
  366. `List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
  367. """
  368. if token_ids_1 is None:
  369. return [self.cls_token_id] + token_ids_0 + [self.sep_token_id]
  370. cls = [self.cls_token_id]
  371. sep = [self.sep_token_id]
  372. return cls + token_ids_0 + sep + token_ids_1 + sep
  373. def build_xpath_tags_with_special_tokens(
  374. self, xpath_tags_0: List[int], xpath_tags_1: Optional[List[int]] = None
  375. ) -> List[int]:
  376. pad = [self.pad_xpath_tags_seq]
  377. if len(xpath_tags_1) == 0:
  378. return pad + xpath_tags_0 + pad
  379. return pad + xpath_tags_0 + pad + xpath_tags_1 + pad
  380. def build_xpath_subs_with_special_tokens(
  381. self, xpath_subs_0: List[int], xpath_subs_1: Optional[List[int]] = None
  382. ) -> List[int]:
  383. pad = [self.pad_xpath_subs_seq]
  384. if len(xpath_subs_1) == 0:
  385. return pad + xpath_subs_0 + pad
  386. return pad + xpath_subs_0 + pad + xpath_subs_1 + pad
  387. def get_special_tokens_mask(
  388. self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None, already_has_special_tokens: bool = False
  389. ) -> List[int]:
  390. """
  391. Args:
  392. Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
  393. special tokens using the tokenizer `prepare_for_model` method.
  394. token_ids_0 (`List[int]`):
  395. List of IDs.
  396. token_ids_1 (`List[int]`, *optional*):
  397. Optional second list of IDs for sequence pairs.
  398. already_has_special_tokens (`bool`, *optional*, defaults to `False`):
  399. Whether or not the token list is already formatted with special tokens for the model.
  400. Returns:
  401. `List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
  402. """
  403. if already_has_special_tokens:
  404. return super().get_special_tokens_mask(
  405. token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
  406. )
  407. if token_ids_1 is None:
  408. return [1] + ([0] * len(token_ids_0)) + [1]
  409. return [1] + ([0] * len(token_ids_0)) + [1, 1] + ([0] * len(token_ids_1)) + [1]
  410. def create_token_type_ids_from_sequences(
  411. self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
  412. ) -> List[int]:
  413. """
  414. Create a mask from the two sequences passed to be used in a sequence-pair classification task. RoBERTa does not
  415. make use of token type ids, therefore a list of zeros is returned.
  416. Args:
  417. token_ids_0 (`List[int]`):
  418. List of IDs.
  419. token_ids_1 (`List[int]`, *optional*):
  420. Optional second list of IDs for sequence pairs.
  421. Returns:
  422. `List[int]`: List of zeros.
  423. """
  424. sep = [self.sep_token_id]
  425. cls = [self.cls_token_id]
  426. if token_ids_1 is None:
  427. return len(cls + token_ids_0 + sep) * [0]
  428. return len(cls + token_ids_0 + sep + token_ids_1 + sep) * [0]
  429. @add_end_docstrings(ENCODE_KWARGS_DOCSTRING, MARKUPLM_ENCODE_PLUS_ADDITIONAL_KWARGS_DOCSTRING)
  430. def __call__(
  431. self,
  432. text: Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]],
  433. text_pair: Optional[Union[PreTokenizedInput, List[PreTokenizedInput]]] = None,
  434. xpaths: Union[List[List[int]], List[List[List[int]]]] = None,
  435. node_labels: Optional[Union[List[int], List[List[int]]]] = None,
  436. add_special_tokens: bool = True,
  437. padding: Union[bool, str, PaddingStrategy] = False,
  438. truncation: Union[bool, str, TruncationStrategy] = None,
  439. max_length: Optional[int] = None,
  440. stride: int = 0,
  441. pad_to_multiple_of: Optional[int] = None,
  442. padding_side: Optional[bool] = None,
  443. return_tensors: Optional[Union[str, TensorType]] = None,
  444. return_token_type_ids: Optional[bool] = None,
  445. return_attention_mask: Optional[bool] = None,
  446. return_overflowing_tokens: bool = False,
  447. return_special_tokens_mask: bool = False,
  448. return_offsets_mapping: bool = False,
  449. return_length: bool = False,
  450. verbose: bool = True,
  451. **kwargs,
  452. ) -> BatchEncoding:
  453. """
  454. Main method to tokenize and prepare for the model one or several sequence(s) or one or several pair(s) of
  455. sequences with node-level xpaths and optional labels.
  456. Args:
  457. text (`str`, `List[str]`, `List[List[str]]`):
  458. The sequence or batch of sequences to be encoded. Each sequence can be a string, a list of strings
  459. (nodes of a single example or questions of a batch of examples) or a list of list of strings (batch of
  460. nodes).
  461. text_pair (`List[str]`, `List[List[str]]`):
  462. The sequence or batch of sequences to be encoded. Each sequence should be a list of strings
  463. (pretokenized string).
  464. xpaths (`List[List[int]]`, `List[List[List[int]]]`):
  465. Node-level xpaths.
  466. node_labels (`List[int]`, `List[List[int]]`, *optional*):
  467. Node-level integer labels (for token classification tasks).
  468. """
  469. # Input type checking for clearer error
  470. def _is_valid_text_input(t):
  471. if isinstance(t, str):
  472. # Strings are fine
  473. return True
  474. elif isinstance(t, (list, tuple)):
  475. # List are fine as long as they are...
  476. if len(t) == 0:
  477. # ... empty
  478. return True
  479. elif isinstance(t[0], str):
  480. # ... list of strings
  481. return True
  482. elif isinstance(t[0], (list, tuple)):
  483. # ... list with an empty list or with a list of strings
  484. return len(t[0]) == 0 or isinstance(t[0][0], str)
  485. else:
  486. return False
  487. else:
  488. return False
  489. if text_pair is not None:
  490. # in case text + text_pair are provided, text = questions, text_pair = nodes
  491. if not _is_valid_text_input(text):
  492. raise ValueError("text input must of type `str` (single example) or `List[str]` (batch of examples). ")
  493. if not isinstance(text_pair, (list, tuple)):
  494. raise ValueError(
  495. "Nodes must be of type `List[str]` (single pretokenized example), "
  496. "or `List[List[str]]` (batch of pretokenized examples)."
  497. )
  498. else:
  499. # in case only text is provided => must be nodes
  500. if not isinstance(text, (list, tuple)):
  501. raise ValueError(
  502. "Nodes must be of type `List[str]` (single pretokenized example), "
  503. "or `List[List[str]]` (batch of pretokenized examples)."
  504. )
  505. if text_pair is not None:
  506. is_batched = isinstance(text, (list, tuple))
  507. else:
  508. is_batched = isinstance(text, (list, tuple)) and text and isinstance(text[0], (list, tuple))
  509. nodes = text if text_pair is None else text_pair
  510. assert xpaths is not None, "You must provide corresponding xpaths"
  511. if is_batched:
  512. assert len(nodes) == len(xpaths), "You must provide nodes and xpaths for an equal amount of examples"
  513. for nodes_example, xpaths_example in zip(nodes, xpaths):
  514. assert len(nodes_example) == len(xpaths_example), "You must provide as many nodes as there are xpaths"
  515. else:
  516. assert len(nodes) == len(xpaths), "You must provide as many nodes as there are xpaths"
  517. if is_batched:
  518. if text_pair is not None and len(text) != len(text_pair):
  519. raise ValueError(
  520. f"batch length of `text`: {len(text)} does not match batch length of `text_pair`:"
  521. f" {len(text_pair)}."
  522. )
  523. batch_text_or_text_pairs = list(zip(text, text_pair)) if text_pair is not None else text
  524. is_pair = bool(text_pair is not None)
  525. return self.batch_encode_plus(
  526. batch_text_or_text_pairs=batch_text_or_text_pairs,
  527. is_pair=is_pair,
  528. xpaths=xpaths,
  529. node_labels=node_labels,
  530. add_special_tokens=add_special_tokens,
  531. padding=padding,
  532. truncation=truncation,
  533. max_length=max_length,
  534. stride=stride,
  535. pad_to_multiple_of=pad_to_multiple_of,
  536. padding_side=padding_side,
  537. return_tensors=return_tensors,
  538. return_token_type_ids=return_token_type_ids,
  539. return_attention_mask=return_attention_mask,
  540. return_overflowing_tokens=return_overflowing_tokens,
  541. return_special_tokens_mask=return_special_tokens_mask,
  542. return_offsets_mapping=return_offsets_mapping,
  543. return_length=return_length,
  544. verbose=verbose,
  545. **kwargs,
  546. )
  547. else:
  548. return self.encode_plus(
  549. text=text,
  550. text_pair=text_pair,
  551. xpaths=xpaths,
  552. node_labels=node_labels,
  553. add_special_tokens=add_special_tokens,
  554. padding=padding,
  555. truncation=truncation,
  556. max_length=max_length,
  557. stride=stride,
  558. pad_to_multiple_of=pad_to_multiple_of,
  559. padding_side=padding_side,
  560. return_tensors=return_tensors,
  561. return_token_type_ids=return_token_type_ids,
  562. return_attention_mask=return_attention_mask,
  563. return_overflowing_tokens=return_overflowing_tokens,
  564. return_special_tokens_mask=return_special_tokens_mask,
  565. return_offsets_mapping=return_offsets_mapping,
  566. return_length=return_length,
  567. verbose=verbose,
  568. **kwargs,
  569. )
  570. @add_end_docstrings(ENCODE_KWARGS_DOCSTRING, MARKUPLM_ENCODE_PLUS_ADDITIONAL_KWARGS_DOCSTRING)
  571. def batch_encode_plus(
  572. self,
  573. batch_text_or_text_pairs: Union[
  574. List[TextInput],
  575. List[TextInputPair],
  576. List[PreTokenizedInput],
  577. ],
  578. is_pair: bool = None,
  579. xpaths: Optional[List[List[List[int]]]] = None,
  580. node_labels: Optional[Union[List[int], List[List[int]]]] = None,
  581. add_special_tokens: bool = True,
  582. padding: Union[bool, str, PaddingStrategy] = False,
  583. truncation: Union[bool, str, TruncationStrategy] = None,
  584. max_length: Optional[int] = None,
  585. stride: int = 0,
  586. pad_to_multiple_of: Optional[int] = None,
  587. padding_side: Optional[bool] = None,
  588. return_tensors: Optional[Union[str, TensorType]] = None,
  589. return_token_type_ids: Optional[bool] = None,
  590. return_attention_mask: Optional[bool] = None,
  591. return_overflowing_tokens: bool = False,
  592. return_special_tokens_mask: bool = False,
  593. return_offsets_mapping: bool = False,
  594. return_length: bool = False,
  595. verbose: bool = True,
  596. **kwargs,
  597. ) -> BatchEncoding:
  598. # Backward compatibility for 'truncation_strategy', 'pad_to_max_length'
  599. padding_strategy, truncation_strategy, max_length, kwargs = self._get_padding_truncation_strategies(
  600. padding=padding,
  601. truncation=truncation,
  602. max_length=max_length,
  603. pad_to_multiple_of=pad_to_multiple_of,
  604. verbose=verbose,
  605. **kwargs,
  606. )
  607. return self._batch_encode_plus(
  608. batch_text_or_text_pairs=batch_text_or_text_pairs,
  609. is_pair=is_pair,
  610. xpaths=xpaths,
  611. node_labels=node_labels,
  612. add_special_tokens=add_special_tokens,
  613. padding_strategy=padding_strategy,
  614. truncation_strategy=truncation_strategy,
  615. max_length=max_length,
  616. stride=stride,
  617. pad_to_multiple_of=pad_to_multiple_of,
  618. padding_side=padding_side,
  619. return_tensors=return_tensors,
  620. return_token_type_ids=return_token_type_ids,
  621. return_attention_mask=return_attention_mask,
  622. return_overflowing_tokens=return_overflowing_tokens,
  623. return_special_tokens_mask=return_special_tokens_mask,
  624. return_offsets_mapping=return_offsets_mapping,
  625. return_length=return_length,
  626. verbose=verbose,
  627. **kwargs,
  628. )
  629. def _batch_encode_plus(
  630. self,
  631. batch_text_or_text_pairs: Union[
  632. List[TextInput],
  633. List[TextInputPair],
  634. List[PreTokenizedInput],
  635. ],
  636. is_pair: bool = None,
  637. xpaths: Optional[List[List[List[int]]]] = None,
  638. node_labels: Optional[List[List[int]]] = None,
  639. add_special_tokens: bool = True,
  640. padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD,
  641. truncation_strategy: TruncationStrategy = TruncationStrategy.DO_NOT_TRUNCATE,
  642. max_length: Optional[int] = None,
  643. stride: int = 0,
  644. pad_to_multiple_of: Optional[int] = None,
  645. padding_side: Optional[bool] = None,
  646. return_tensors: Optional[Union[str, TensorType]] = None,
  647. return_token_type_ids: Optional[bool] = None,
  648. return_attention_mask: Optional[bool] = None,
  649. return_overflowing_tokens: bool = False,
  650. return_special_tokens_mask: bool = False,
  651. return_offsets_mapping: bool = False,
  652. return_length: bool = False,
  653. verbose: bool = True,
  654. **kwargs,
  655. ) -> BatchEncoding:
  656. if return_offsets_mapping:
  657. raise NotImplementedError(
  658. "return_offset_mapping is not available when using Python tokenizers. "
  659. "To use this feature, change your tokenizer to one deriving from "
  660. "transformers.PreTrainedTokenizerFast."
  661. )
  662. batch_outputs = self._batch_prepare_for_model(
  663. batch_text_or_text_pairs=batch_text_or_text_pairs,
  664. is_pair=is_pair,
  665. xpaths=xpaths,
  666. node_labels=node_labels,
  667. add_special_tokens=add_special_tokens,
  668. padding_strategy=padding_strategy,
  669. truncation_strategy=truncation_strategy,
  670. max_length=max_length,
  671. stride=stride,
  672. pad_to_multiple_of=pad_to_multiple_of,
  673. padding_side=padding_side,
  674. return_attention_mask=return_attention_mask,
  675. return_token_type_ids=return_token_type_ids,
  676. return_overflowing_tokens=return_overflowing_tokens,
  677. return_special_tokens_mask=return_special_tokens_mask,
  678. return_length=return_length,
  679. return_tensors=return_tensors,
  680. verbose=verbose,
  681. )
  682. return BatchEncoding(batch_outputs)
  683. @add_end_docstrings(ENCODE_KWARGS_DOCSTRING, MARKUPLM_ENCODE_PLUS_ADDITIONAL_KWARGS_DOCSTRING)
  684. def _batch_prepare_for_model(
  685. self,
  686. batch_text_or_text_pairs,
  687. is_pair: bool = None,
  688. xpaths: Optional[List[List[int]]] = None,
  689. node_labels: Optional[List[List[int]]] = None,
  690. add_special_tokens: bool = True,
  691. padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD,
  692. truncation_strategy: TruncationStrategy = TruncationStrategy.DO_NOT_TRUNCATE,
  693. max_length: Optional[int] = None,
  694. stride: int = 0,
  695. pad_to_multiple_of: Optional[int] = None,
  696. padding_side: Optional[bool] = None,
  697. return_tensors: Optional[str] = None,
  698. return_token_type_ids: Optional[bool] = None,
  699. return_attention_mask: Optional[bool] = None,
  700. return_overflowing_tokens: bool = False,
  701. return_special_tokens_mask: bool = False,
  702. return_length: bool = False,
  703. verbose: bool = True,
  704. ) -> BatchEncoding:
  705. """
  706. Prepares a sequence of input id, or a pair of sequences of inputs ids so that it can be used by the model. It
  707. adds special tokens, truncates sequences if overflowing while taking into account the special tokens and
  708. manages a moving window (with user defined stride) for overflowing tokens.
  709. Args:
  710. batch_ids_pairs: list of tokenized input ids or input ids pairs
  711. """
  712. batch_outputs = {}
  713. for idx, example in enumerate(zip(batch_text_or_text_pairs, xpaths)):
  714. batch_text_or_text_pair, xpaths_example = example
  715. outputs = self.prepare_for_model(
  716. batch_text_or_text_pair[0] if is_pair else batch_text_or_text_pair,
  717. batch_text_or_text_pair[1] if is_pair else None,
  718. xpaths_example,
  719. node_labels=node_labels[idx] if node_labels is not None else None,
  720. add_special_tokens=add_special_tokens,
  721. padding=PaddingStrategy.DO_NOT_PAD.value, # we pad in batch afterward
  722. truncation=truncation_strategy.value,
  723. max_length=max_length,
  724. stride=stride,
  725. pad_to_multiple_of=None, # we pad in batch afterward
  726. padding_side=None, # we pad in batch afterward
  727. return_attention_mask=False, # we pad in batch afterward
  728. return_token_type_ids=return_token_type_ids,
  729. return_overflowing_tokens=return_overflowing_tokens,
  730. return_special_tokens_mask=return_special_tokens_mask,
  731. return_length=return_length,
  732. return_tensors=None, # We convert the whole batch to tensors at the end
  733. prepend_batch_axis=False,
  734. verbose=verbose,
  735. )
  736. for key, value in outputs.items():
  737. if key not in batch_outputs:
  738. batch_outputs[key] = []
  739. batch_outputs[key].append(value)
  740. batch_outputs = self.pad(
  741. batch_outputs,
  742. padding=padding_strategy.value,
  743. max_length=max_length,
  744. pad_to_multiple_of=pad_to_multiple_of,
  745. padding_side=padding_side,
  746. return_attention_mask=return_attention_mask,
  747. )
  748. batch_outputs = BatchEncoding(batch_outputs, tensor_type=return_tensors)
  749. return batch_outputs
  750. @add_end_docstrings(ENCODE_KWARGS_DOCSTRING)
  751. def encode(
  752. self,
  753. text: Union[TextInput, PreTokenizedInput],
  754. text_pair: Optional[PreTokenizedInput] = None,
  755. xpaths: Optional[List[List[int]]] = None,
  756. node_labels: Optional[List[int]] = None,
  757. add_special_tokens: bool = True,
  758. padding: Union[bool, str, PaddingStrategy] = False,
  759. truncation: Union[bool, str, TruncationStrategy] = None,
  760. max_length: Optional[int] = None,
  761. stride: int = 0,
  762. pad_to_multiple_of: Optional[int] = None,
  763. padding_side: Optional[bool] = None,
  764. return_tensors: Optional[Union[str, TensorType]] = None,
  765. return_token_type_ids: Optional[bool] = None,
  766. return_attention_mask: Optional[bool] = None,
  767. return_overflowing_tokens: bool = False,
  768. return_special_tokens_mask: bool = False,
  769. return_offsets_mapping: bool = False,
  770. return_length: bool = False,
  771. verbose: bool = True,
  772. **kwargs,
  773. ) -> List[int]:
  774. encoded_inputs = self.encode_plus(
  775. text=text,
  776. text_pair=text_pair,
  777. xpaths=xpaths,
  778. node_labels=node_labels,
  779. add_special_tokens=add_special_tokens,
  780. padding=padding,
  781. truncation=truncation,
  782. max_length=max_length,
  783. stride=stride,
  784. pad_to_multiple_of=pad_to_multiple_of,
  785. padding_side=padding_side,
  786. return_tensors=return_tensors,
  787. return_token_type_ids=return_token_type_ids,
  788. return_attention_mask=return_attention_mask,
  789. return_overflowing_tokens=return_overflowing_tokens,
  790. return_special_tokens_mask=return_special_tokens_mask,
  791. return_offsets_mapping=return_offsets_mapping,
  792. return_length=return_length,
  793. verbose=verbose,
  794. **kwargs,
  795. )
  796. return encoded_inputs["input_ids"]
  797. @add_end_docstrings(ENCODE_KWARGS_DOCSTRING, MARKUPLM_ENCODE_PLUS_ADDITIONAL_KWARGS_DOCSTRING)
  798. def encode_plus(
  799. self,
  800. text: Union[TextInput, PreTokenizedInput],
  801. text_pair: Optional[PreTokenizedInput] = None,
  802. xpaths: Optional[List[List[int]]] = None,
  803. node_labels: Optional[List[int]] = None,
  804. add_special_tokens: bool = True,
  805. padding: Union[bool, str, PaddingStrategy] = False,
  806. truncation: Union[bool, str, TruncationStrategy] = None,
  807. max_length: Optional[int] = None,
  808. stride: int = 0,
  809. pad_to_multiple_of: Optional[int] = None,
  810. padding_side: Optional[bool] = None,
  811. return_tensors: Optional[Union[str, TensorType]] = None,
  812. return_token_type_ids: Optional[bool] = None,
  813. return_attention_mask: Optional[bool] = None,
  814. return_overflowing_tokens: bool = False,
  815. return_special_tokens_mask: bool = False,
  816. return_offsets_mapping: bool = False,
  817. return_length: bool = False,
  818. verbose: bool = True,
  819. **kwargs,
  820. ) -> BatchEncoding:
  821. """
  822. Tokenize and prepare for the model a sequence or a pair of sequences. .. warning:: This method is deprecated,
  823. `__call__` should be used instead.
  824. Args:
  825. text (`str`, `List[str]`, `List[List[str]]`):
  826. The first sequence to be encoded. This can be a string, a list of strings or a list of list of strings.
  827. text_pair (`List[str]` or `List[int]`, *optional*):
  828. Optional second sequence to be encoded. This can be a list of strings (nodes of a single example) or a
  829. list of list of strings (nodes of a batch of examples).
  830. """
  831. # Backward compatibility for 'truncation_strategy', 'pad_to_max_length'
  832. padding_strategy, truncation_strategy, max_length, kwargs = self._get_padding_truncation_strategies(
  833. padding=padding,
  834. truncation=truncation,
  835. max_length=max_length,
  836. pad_to_multiple_of=pad_to_multiple_of,
  837. verbose=verbose,
  838. **kwargs,
  839. )
  840. return self._encode_plus(
  841. text=text,
  842. xpaths=xpaths,
  843. text_pair=text_pair,
  844. node_labels=node_labels,
  845. add_special_tokens=add_special_tokens,
  846. padding_strategy=padding_strategy,
  847. truncation_strategy=truncation_strategy,
  848. max_length=max_length,
  849. stride=stride,
  850. pad_to_multiple_of=pad_to_multiple_of,
  851. padding_side=padding_side,
  852. return_tensors=return_tensors,
  853. return_token_type_ids=return_token_type_ids,
  854. return_attention_mask=return_attention_mask,
  855. return_overflowing_tokens=return_overflowing_tokens,
  856. return_special_tokens_mask=return_special_tokens_mask,
  857. return_offsets_mapping=return_offsets_mapping,
  858. return_length=return_length,
  859. verbose=verbose,
  860. **kwargs,
  861. )
  862. def _encode_plus(
  863. self,
  864. text: Union[TextInput, PreTokenizedInput],
  865. text_pair: Optional[PreTokenizedInput] = None,
  866. xpaths: Optional[List[List[int]]] = None,
  867. node_labels: Optional[List[int]] = None,
  868. add_special_tokens: bool = True,
  869. padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD,
  870. truncation_strategy: TruncationStrategy = TruncationStrategy.DO_NOT_TRUNCATE,
  871. max_length: Optional[int] = None,
  872. stride: int = 0,
  873. pad_to_multiple_of: Optional[int] = None,
  874. padding_side: Optional[bool] = None,
  875. return_tensors: Optional[Union[str, TensorType]] = None,
  876. return_token_type_ids: Optional[bool] = None,
  877. return_attention_mask: Optional[bool] = None,
  878. return_overflowing_tokens: bool = False,
  879. return_special_tokens_mask: bool = False,
  880. return_offsets_mapping: bool = False,
  881. return_length: bool = False,
  882. verbose: bool = True,
  883. **kwargs,
  884. ) -> BatchEncoding:
  885. if return_offsets_mapping:
  886. raise NotImplementedError(
  887. "return_offset_mapping is not available when using Python tokenizers. "
  888. "To use this feature, change your tokenizer to one deriving from "
  889. "transformers.PreTrainedTokenizerFast. "
  890. "More information on available tokenizers at "
  891. "https://github.com/huggingface/transformers/pull/2674"
  892. )
  893. return self.prepare_for_model(
  894. text=text,
  895. text_pair=text_pair,
  896. xpaths=xpaths,
  897. node_labels=node_labels,
  898. add_special_tokens=add_special_tokens,
  899. padding=padding_strategy.value,
  900. truncation=truncation_strategy.value,
  901. max_length=max_length,
  902. stride=stride,
  903. pad_to_multiple_of=pad_to_multiple_of,
  904. padding_side=padding_side,
  905. return_tensors=return_tensors,
  906. prepend_batch_axis=True,
  907. return_attention_mask=return_attention_mask,
  908. return_token_type_ids=return_token_type_ids,
  909. return_overflowing_tokens=return_overflowing_tokens,
  910. return_special_tokens_mask=return_special_tokens_mask,
  911. return_length=return_length,
  912. verbose=verbose,
  913. )
  914. @add_end_docstrings(ENCODE_KWARGS_DOCSTRING, MARKUPLM_ENCODE_PLUS_ADDITIONAL_KWARGS_DOCSTRING)
  915. def prepare_for_model(
  916. self,
  917. text: Union[TextInput, PreTokenizedInput],
  918. text_pair: Optional[PreTokenizedInput] = None,
  919. xpaths: Optional[List[List[int]]] = None,
  920. node_labels: Optional[List[int]] = None,
  921. add_special_tokens: bool = True,
  922. padding: Union[bool, str, PaddingStrategy] = False,
  923. truncation: Union[bool, str, TruncationStrategy] = None,
  924. max_length: Optional[int] = None,
  925. stride: int = 0,
  926. pad_to_multiple_of: Optional[int] = None,
  927. padding_side: Optional[bool] = None,
  928. return_tensors: Optional[Union[str, TensorType]] = None,
  929. return_token_type_ids: Optional[bool] = None,
  930. return_attention_mask: Optional[bool] = None,
  931. return_overflowing_tokens: bool = False,
  932. return_special_tokens_mask: bool = False,
  933. return_offsets_mapping: bool = False,
  934. return_length: bool = False,
  935. verbose: bool = True,
  936. prepend_batch_axis: bool = False,
  937. **kwargs,
  938. ) -> BatchEncoding:
  939. """
  940. Prepares a sequence or a pair of sequences so that it can be used by the model. It adds special tokens,
  941. truncates sequences if overflowing while taking into account the special tokens and manages a moving window
  942. (with user defined stride) for overflowing tokens. Please Note, for *text_pair* different than `None` and
  943. *truncation_strategy = longest_first* or `True`, it is not possible to return overflowing tokens. Such a
  944. combination of arguments will raise an error.
  945. Node-level `xpaths` are turned into token-level `xpath_tags_seq` and `xpath_subs_seq`. If provided, node-level
  946. `node_labels` are turned into token-level `labels`. The node label is used for the first token of the node,
  947. while remaining tokens are labeled with -100, such that they will be ignored by the loss function.
  948. Args:
  949. text (`str`, `List[str]`, `List[List[str]]`):
  950. The first sequence to be encoded. This can be a string, a list of strings or a list of list of strings.
  951. text_pair (`List[str]` or `List[int]`, *optional*):
  952. Optional second sequence to be encoded. This can be a list of strings (nodes of a single example) or a
  953. list of list of strings (nodes of a batch of examples).
  954. """
  955. # Backward compatibility for 'truncation_strategy', 'pad_to_max_length'
  956. padding_strategy, truncation_strategy, max_length, kwargs = self._get_padding_truncation_strategies(
  957. padding=padding,
  958. truncation=truncation,
  959. max_length=max_length,
  960. pad_to_multiple_of=pad_to_multiple_of,
  961. verbose=verbose,
  962. **kwargs,
  963. )
  964. tokens = []
  965. pair_tokens = []
  966. xpath_tags_seq = []
  967. xpath_subs_seq = []
  968. pair_xpath_tags_seq = []
  969. pair_xpath_subs_seq = []
  970. labels = []
  971. if text_pair is None:
  972. if node_labels is None:
  973. # CASE 1: web page classification (training + inference) + CASE 2: token classification (inference)
  974. for word, xpath in zip(text, xpaths):
  975. if len(word) < 1: # skip empty nodes
  976. continue
  977. word_tokens = self.tokenize(word)
  978. tokens.extend(word_tokens)
  979. xpath_tags_list, xpath_subs_list = self.get_xpath_seq(xpath)
  980. xpath_tags_seq.extend([xpath_tags_list] * len(word_tokens))
  981. xpath_subs_seq.extend([xpath_subs_list] * len(word_tokens))
  982. else:
  983. # CASE 2: token classification (training)
  984. for word, xpath, label in zip(text, xpaths, node_labels):
  985. if len(word) < 1: # skip empty nodes
  986. continue
  987. word_tokens = self.tokenize(word)
  988. tokens.extend(word_tokens)
  989. xpath_tags_list, xpath_subs_list = self.get_xpath_seq(xpath)
  990. xpath_tags_seq.extend([xpath_tags_list] * len(word_tokens))
  991. xpath_subs_seq.extend([xpath_subs_list] * len(word_tokens))
  992. if self.only_label_first_subword:
  993. # Use the real label id for the first token of the word, and padding ids for the remaining tokens
  994. labels.extend([label] + [self.pad_token_label] * (len(word_tokens) - 1))
  995. else:
  996. labels.extend([label] * len(word_tokens))
  997. else:
  998. # CASE 3: web page question answering (inference)
  999. # text = question
  1000. # text_pair = nodes
  1001. tokens = self.tokenize(text)
  1002. xpath_tags_seq = [self.pad_xpath_tags_seq for _ in range(len(tokens))]
  1003. xpath_subs_seq = [self.pad_xpath_subs_seq for _ in range(len(tokens))]
  1004. for word, xpath in zip(text_pair, xpaths):
  1005. if len(word) < 1: # skip empty nodes
  1006. continue
  1007. word_tokens = self.tokenize(word)
  1008. pair_tokens.extend(word_tokens)
  1009. xpath_tags_list, xpath_subs_list = self.get_xpath_seq(xpath)
  1010. pair_xpath_tags_seq.extend([xpath_tags_list] * len(word_tokens))
  1011. pair_xpath_subs_seq.extend([xpath_subs_list] * len(word_tokens))
  1012. # Create ids + pair_ids
  1013. ids = self.convert_tokens_to_ids(tokens)
  1014. pair_ids = self.convert_tokens_to_ids(pair_tokens) if pair_tokens else None
  1015. if (
  1016. return_overflowing_tokens
  1017. and truncation_strategy == TruncationStrategy.LONGEST_FIRST
  1018. and pair_ids is not None
  1019. ):
  1020. raise ValueError(
  1021. "Not possible to return overflowing tokens for pair of sequences with the "
  1022. "`longest_first`. Please select another truncation strategy than `longest_first`, "
  1023. "for instance `only_second` or `only_first`."
  1024. )
  1025. # Compute the total size of the returned encodings
  1026. pair = bool(pair_ids is not None)
  1027. len_ids = len(ids)
  1028. len_pair_ids = len(pair_ids) if pair else 0
  1029. total_len = len_ids + len_pair_ids + (self.num_special_tokens_to_add(pair=pair) if add_special_tokens else 0)
  1030. # Truncation: Handle max sequence length
  1031. overflowing_tokens = []
  1032. overflowing_xpath_tags_seq = []
  1033. overflowing_xpath_subs_seq = []
  1034. overflowing_labels = []
  1035. if truncation_strategy != TruncationStrategy.DO_NOT_TRUNCATE and max_length and total_len > max_length:
  1036. (
  1037. ids,
  1038. xpath_tags_seq,
  1039. xpath_subs_seq,
  1040. pair_ids,
  1041. pair_xpath_tags_seq,
  1042. pair_xpath_subs_seq,
  1043. labels,
  1044. overflowing_tokens,
  1045. overflowing_xpath_tags_seq,
  1046. overflowing_xpath_subs_seq,
  1047. overflowing_labels,
  1048. ) = self.truncate_sequences(
  1049. ids,
  1050. xpath_tags_seq=xpath_tags_seq,
  1051. xpath_subs_seq=xpath_subs_seq,
  1052. pair_ids=pair_ids,
  1053. pair_xpath_tags_seq=pair_xpath_tags_seq,
  1054. pair_xpath_subs_seq=pair_xpath_subs_seq,
  1055. labels=labels,
  1056. num_tokens_to_remove=total_len - max_length,
  1057. truncation_strategy=truncation_strategy,
  1058. stride=stride,
  1059. )
  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. # Load from model defaults
  1067. if return_token_type_ids is None:
  1068. return_token_type_ids = "token_type_ids" in self.model_input_names
  1069. if return_attention_mask is None:
  1070. return_attention_mask = "attention_mask" in self.model_input_names
  1071. encoded_inputs = {}
  1072. if return_overflowing_tokens:
  1073. encoded_inputs["overflowing_tokens"] = overflowing_tokens
  1074. encoded_inputs["overflowing_xpath_tags_seq"] = overflowing_xpath_tags_seq
  1075. encoded_inputs["overflowing_xpath_subs_seq"] = overflowing_xpath_subs_seq
  1076. encoded_inputs["overflowing_labels"] = overflowing_labels
  1077. encoded_inputs["num_truncated_tokens"] = total_len - max_length
  1078. # Add special tokens
  1079. if add_special_tokens:
  1080. sequence = self.build_inputs_with_special_tokens(ids, pair_ids)
  1081. token_type_ids = self.create_token_type_ids_from_sequences(ids, pair_ids)
  1082. xpath_tags_ids = self.build_xpath_tags_with_special_tokens(xpath_tags_seq, pair_xpath_tags_seq)
  1083. xpath_subs_ids = self.build_xpath_subs_with_special_tokens(xpath_subs_seq, pair_xpath_subs_seq)
  1084. if labels:
  1085. labels = [self.pad_token_label] + labels + [self.pad_token_label]
  1086. else:
  1087. sequence = ids + pair_ids if pair else ids
  1088. token_type_ids = [0] * len(ids) + ([0] * len(pair_ids) if pair else [])
  1089. xpath_tags_ids = xpath_tags_seq + pair_xpath_tags_seq if pair else xpath_tags_seq
  1090. xpath_subs_ids = xpath_subs_seq + pair_xpath_subs_seq if pair else xpath_subs_seq
  1091. # Build output dictionary
  1092. encoded_inputs["input_ids"] = sequence
  1093. encoded_inputs["xpath_tags_seq"] = xpath_tags_ids
  1094. encoded_inputs["xpath_subs_seq"] = xpath_subs_ids
  1095. if return_token_type_ids:
  1096. encoded_inputs["token_type_ids"] = token_type_ids
  1097. if return_special_tokens_mask:
  1098. if add_special_tokens:
  1099. encoded_inputs["special_tokens_mask"] = self.get_special_tokens_mask(ids, pair_ids)
  1100. else:
  1101. encoded_inputs["special_tokens_mask"] = [0] * len(sequence)
  1102. if labels:
  1103. encoded_inputs["labels"] = labels
  1104. # Check lengths
  1105. self._eventual_warn_about_too_long_sequence(encoded_inputs["input_ids"], max_length, verbose)
  1106. # Padding
  1107. if padding_strategy != PaddingStrategy.DO_NOT_PAD or return_attention_mask:
  1108. encoded_inputs = self.pad(
  1109. encoded_inputs,
  1110. max_length=max_length,
  1111. padding=padding_strategy.value,
  1112. pad_to_multiple_of=pad_to_multiple_of,
  1113. padding_side=padding_side,
  1114. return_attention_mask=return_attention_mask,
  1115. )
  1116. if return_length:
  1117. encoded_inputs["length"] = len(encoded_inputs["input_ids"])
  1118. batch_outputs = BatchEncoding(
  1119. encoded_inputs, tensor_type=return_tensors, prepend_batch_axis=prepend_batch_axis
  1120. )
  1121. return batch_outputs
  1122. def truncate_sequences(
  1123. self,
  1124. ids: List[int],
  1125. xpath_tags_seq: List[List[int]],
  1126. xpath_subs_seq: List[List[int]],
  1127. pair_ids: Optional[List[int]] = None,
  1128. pair_xpath_tags_seq: Optional[List[List[int]]] = None,
  1129. pair_xpath_subs_seq: Optional[List[List[int]]] = None,
  1130. labels: Optional[List[int]] = None,
  1131. num_tokens_to_remove: int = 0,
  1132. truncation_strategy: Union[str, TruncationStrategy] = "longest_first",
  1133. stride: int = 0,
  1134. ) -> Tuple[List[int], List[int], List[int]]:
  1135. """
  1136. Args:
  1137. Truncates a sequence pair in-place following the strategy.
  1138. ids (`List[int]`):
  1139. Tokenized input ids of the first sequence. Can be obtained from a string by chaining the `tokenize` and
  1140. `convert_tokens_to_ids` methods.
  1141. xpath_tags_seq (`List[List[int]]`):
  1142. XPath tag IDs of the first sequence.
  1143. xpath_subs_seq (`List[List[int]]`):
  1144. XPath sub IDs of the first sequence.
  1145. pair_ids (`List[int]`, *optional*):
  1146. Tokenized input ids of the second sequence. Can be obtained from a string by chaining the `tokenize`
  1147. and `convert_tokens_to_ids` methods.
  1148. pair_xpath_tags_seq (`List[List[int]]`, *optional*):
  1149. XPath tag IDs of the second sequence.
  1150. pair_xpath_subs_seq (`List[List[int]]`, *optional*):
  1151. XPath sub IDs of the second sequence.
  1152. num_tokens_to_remove (`int`, *optional*, defaults to 0):
  1153. Number of tokens to remove using the truncation strategy.
  1154. truncation_strategy (`str` or [`~tokenization_utils_base.TruncationStrategy`], *optional*, defaults to
  1155. `False`):
  1156. The strategy to follow for truncation. Can be:
  1157. - `'longest_first'`: Truncate to a maximum length specified with the argument `max_length` or to the
  1158. maximum acceptable input length for the model if that argument is not provided. This will truncate
  1159. token by token, removing a token from the longest sequence in the pair if a pair of sequences (or a
  1160. batch of pairs) is provided.
  1161. - `'only_first'`: Truncate to a maximum length specified with the argument `max_length` or to the
  1162. maximum acceptable input length for the model if that argument is not provided. This will only
  1163. truncate the first sequence of a pair if a pair of sequences (or a batch of pairs) is provided.
  1164. - `'only_second'`: Truncate to a maximum length specified with the argument `max_length` or to the
  1165. maximum acceptable input length for the model if that argument is not provided. This will only
  1166. truncate the second sequence of a pair if a pair of sequences (or a batch of pairs) is provided.
  1167. - `'do_not_truncate'` (default): No truncation (i.e., can output batch with sequence lengths greater
  1168. than the model maximum admissible input size).
  1169. stride (`int`, *optional*, defaults to 0):
  1170. If set to a positive number, the overflowing tokens returned will contain some tokens from the main
  1171. sequence returned. The value of this argument defines the number of additional tokens.
  1172. Returns:
  1173. `Tuple[List[int], List[int], List[int]]`: The truncated `ids`, the truncated `pair_ids` and the list of
  1174. overflowing tokens. Note: The *longest_first* strategy returns empty list of overflowing tokens if a pair
  1175. of sequences (or a batch of pairs) is provided.
  1176. """
  1177. if num_tokens_to_remove <= 0:
  1178. return ids, xpath_tags_seq, xpath_subs_seq, pair_ids, pair_xpath_tags_seq, pair_xpath_subs_seq, [], [], []
  1179. if not isinstance(truncation_strategy, TruncationStrategy):
  1180. truncation_strategy = TruncationStrategy(truncation_strategy)
  1181. overflowing_tokens = []
  1182. overflowing_xpath_tags_seq = []
  1183. overflowing_xpath_subs_seq = []
  1184. overflowing_labels = []
  1185. if truncation_strategy == TruncationStrategy.ONLY_FIRST or (
  1186. truncation_strategy == TruncationStrategy.LONGEST_FIRST and pair_ids is None
  1187. ):
  1188. if len(ids) > num_tokens_to_remove:
  1189. window_len = min(len(ids), stride + num_tokens_to_remove)
  1190. overflowing_tokens = ids[-window_len:]
  1191. overflowing_xpath_tags_seq = xpath_tags_seq[-window_len:]
  1192. overflowing_xpath_subs_seq = xpath_subs_seq[-window_len:]
  1193. ids = ids[:-num_tokens_to_remove]
  1194. xpath_tags_seq = xpath_tags_seq[:-num_tokens_to_remove]
  1195. xpath_subs_seq = xpath_subs_seq[:-num_tokens_to_remove]
  1196. labels = labels[:-num_tokens_to_remove]
  1197. else:
  1198. error_msg = (
  1199. f"We need to remove {num_tokens_to_remove} to truncate the input "
  1200. f"but the first sequence has a length {len(ids)}. "
  1201. )
  1202. if truncation_strategy == TruncationStrategy.ONLY_FIRST:
  1203. error_msg = (
  1204. error_msg + "Please select another truncation strategy than "
  1205. f"{truncation_strategy}, for instance 'longest_first' or 'only_second'."
  1206. )
  1207. logger.error(error_msg)
  1208. elif truncation_strategy == TruncationStrategy.LONGEST_FIRST:
  1209. logger.warning(
  1210. "Be aware, overflowing tokens are not returned for the setting you have chosen,"
  1211. f" i.e. sequence pairs with the '{TruncationStrategy.LONGEST_FIRST.value}' "
  1212. "truncation strategy. So the returned list will always be empty even if some "
  1213. "tokens have been removed."
  1214. )
  1215. for _ in range(num_tokens_to_remove):
  1216. if pair_ids is None or len(ids) > len(pair_ids):
  1217. ids = ids[:-1]
  1218. xpath_tags_seq = xpath_tags_seq[:-1]
  1219. xpath_subs_seq = xpath_subs_seq[:-1]
  1220. labels = labels[:-1]
  1221. else:
  1222. pair_ids = pair_ids[:-1]
  1223. pair_xpath_tags_seq = pair_xpath_tags_seq[:-1]
  1224. pair_xpath_subs_seq = pair_xpath_subs_seq[:-1]
  1225. elif truncation_strategy == TruncationStrategy.ONLY_SECOND and pair_ids is not None:
  1226. if len(pair_ids) > num_tokens_to_remove:
  1227. window_len = min(len(pair_ids), stride + num_tokens_to_remove)
  1228. overflowing_tokens = pair_ids[-window_len:]
  1229. overflowing_xpath_tags_seq = pair_xpath_tags_seq[-window_len:]
  1230. overflowing_xpath_subs_seq = pair_xpath_subs_seq[-window_len:]
  1231. pair_ids = pair_ids[:-num_tokens_to_remove]
  1232. pair_xpath_tags_seq = pair_xpath_tags_seq[:-num_tokens_to_remove]
  1233. pair_xpath_subs_seq = pair_xpath_subs_seq[:-num_tokens_to_remove]
  1234. else:
  1235. logger.error(
  1236. f"We need to remove {num_tokens_to_remove} to truncate the input "
  1237. f"but the second sequence has a length {len(pair_ids)}. "
  1238. f"Please select another truncation strategy than {truncation_strategy}, "
  1239. "for instance 'longest_first' or 'only_first'."
  1240. )
  1241. return (
  1242. ids,
  1243. xpath_tags_seq,
  1244. xpath_subs_seq,
  1245. pair_ids,
  1246. pair_xpath_tags_seq,
  1247. pair_xpath_subs_seq,
  1248. labels,
  1249. overflowing_tokens,
  1250. overflowing_xpath_tags_seq,
  1251. overflowing_xpath_subs_seq,
  1252. overflowing_labels,
  1253. )
  1254. def _pad(
  1255. self,
  1256. encoded_inputs: Union[Dict[str, EncodedInput], BatchEncoding],
  1257. max_length: Optional[int] = None,
  1258. padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD,
  1259. pad_to_multiple_of: Optional[int] = None,
  1260. padding_side: Optional[bool] = None,
  1261. return_attention_mask: Optional[bool] = None,
  1262. ) -> dict:
  1263. """
  1264. Args:
  1265. Pad encoded inputs (on left/right and up to predefined length or max length in the batch)
  1266. encoded_inputs:
  1267. Dictionary of tokenized inputs (`List[int]`) or batch of tokenized inputs (`List[List[int]]`).
  1268. max_length: maximum length of the returned list and optionally padding length (see below).
  1269. Will truncate by taking into account the special tokens.
  1270. padding_strategy: PaddingStrategy to use for padding.
  1271. - PaddingStrategy.LONGEST Pad to the longest sequence in the batch
  1272. - PaddingStrategy.MAX_LENGTH: Pad to the max length (default)
  1273. - PaddingStrategy.DO_NOT_PAD: Do not pad
  1274. The tokenizer padding sides are defined in self.padding_side:
  1275. - 'left': pads on the left of the sequences
  1276. - 'right': pads on the right of the sequences
  1277. pad_to_multiple_of: (optional) Integer if set will pad the sequence to a multiple of the provided value.
  1278. This is especially useful to enable the use of Tensor Core on NVIDIA hardware with compute capability
  1279. `>= 7.5` (Volta).
  1280. padding_side:
  1281. The side on which the model should have padding applied. Should be selected between ['right', 'left'].
  1282. Default value is picked from the class attribute of the same name.
  1283. return_attention_mask:
  1284. (optional) Set to False to avoid returning attention mask (default: set to model specifics)
  1285. """
  1286. # Load from model defaults
  1287. if return_attention_mask is None:
  1288. return_attention_mask = "attention_mask" in self.model_input_names
  1289. required_input = encoded_inputs[self.model_input_names[0]]
  1290. if padding_strategy == PaddingStrategy.LONGEST:
  1291. max_length = len(required_input)
  1292. if max_length is not None and pad_to_multiple_of is not None and (max_length % pad_to_multiple_of != 0):
  1293. max_length = ((max_length // pad_to_multiple_of) + 1) * pad_to_multiple_of
  1294. needs_to_be_padded = padding_strategy != PaddingStrategy.DO_NOT_PAD and len(required_input) != max_length
  1295. # Initialize attention mask if not present.
  1296. if return_attention_mask and "attention_mask" not in encoded_inputs:
  1297. encoded_inputs["attention_mask"] = [1] * len(required_input)
  1298. if needs_to_be_padded:
  1299. difference = max_length - len(required_input)
  1300. padding_side = padding_side if padding_side is not None else self.padding_side
  1301. if padding_side == "right":
  1302. if return_attention_mask:
  1303. encoded_inputs["attention_mask"] = encoded_inputs["attention_mask"] + [0] * difference
  1304. if "token_type_ids" in encoded_inputs:
  1305. encoded_inputs["token_type_ids"] = (
  1306. encoded_inputs["token_type_ids"] + [self.pad_token_type_id] * difference
  1307. )
  1308. if "xpath_tags_seq" in encoded_inputs:
  1309. encoded_inputs["xpath_tags_seq"] = (
  1310. encoded_inputs["xpath_tags_seq"] + [self.pad_xpath_tags_seq] * difference
  1311. )
  1312. if "xpath_subs_seq" in encoded_inputs:
  1313. encoded_inputs["xpath_subs_seq"] = (
  1314. encoded_inputs["xpath_subs_seq"] + [self.pad_xpath_subs_seq] * difference
  1315. )
  1316. if "labels" in encoded_inputs:
  1317. encoded_inputs["labels"] = encoded_inputs["labels"] + [self.pad_token_label] * difference
  1318. if "special_tokens_mask" in encoded_inputs:
  1319. encoded_inputs["special_tokens_mask"] = encoded_inputs["special_tokens_mask"] + [1] * difference
  1320. encoded_inputs[self.model_input_names[0]] = required_input + [self.pad_token_id] * difference
  1321. elif padding_side == "left":
  1322. if return_attention_mask:
  1323. encoded_inputs["attention_mask"] = [0] * difference + encoded_inputs["attention_mask"]
  1324. if "token_type_ids" in encoded_inputs:
  1325. encoded_inputs["token_type_ids"] = [self.pad_token_type_id] * difference + encoded_inputs[
  1326. "token_type_ids"
  1327. ]
  1328. if "xpath_tags_seq" in encoded_inputs:
  1329. encoded_inputs["xpath_tags_seq"] = [self.pad_xpath_tags_seq] * difference + encoded_inputs[
  1330. "xpath_tags_seq"
  1331. ]
  1332. if "xpath_subs_seq" in encoded_inputs:
  1333. encoded_inputs["xpath_subs_seq"] = [self.pad_xpath_subs_seq] * difference + encoded_inputs[
  1334. "xpath_subs_seq"
  1335. ]
  1336. if "labels" in encoded_inputs:
  1337. encoded_inputs["labels"] = [self.pad_token_label] * difference + encoded_inputs["labels"]
  1338. if "special_tokens_mask" in encoded_inputs:
  1339. encoded_inputs["special_tokens_mask"] = [1] * difference + encoded_inputs["special_tokens_mask"]
  1340. encoded_inputs[self.model_input_names[0]] = [self.pad_token_id] * difference + required_input
  1341. else:
  1342. raise ValueError("Invalid padding strategy:" + str(padding_side))
  1343. return encoded_inputs