tokenization_utils.py 113 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415
  1. # coding=utf-8
  2. # Copyright 2018 The Open AI Team Authors and The HuggingFace Inc. team.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. """Tokenization classes for OpenAI GPT."""
  16. import copy
  17. import functools
  18. import itertools
  19. import json
  20. import logging
  21. import operator
  22. import os
  23. import re
  24. import collections
  25. import unicodedata
  26. from collections import UserDict, defaultdict
  27. from contextlib import contextmanager
  28. from typing import List, Optional, Sequence, Tuple, Union
  29. from tokenizers import AddedToken, Encoding
  30. from tokenizers.implementations import BaseTokenizer
  31. from file_utils import cached_path, hf_bucket_url, is_remote_url, is_tf_available, is_torch_available
  32. if is_tf_available():
  33. import tensorflow as tf
  34. if is_torch_available():
  35. import torch
  36. logger = logging.getLogger(__name__)
  37. SPECIAL_TOKENS_MAP_FILE = "special_tokens_map.json"
  38. ADDED_TOKENS_FILE = "added_tokens.json"
  39. TOKENIZER_CONFIG_FILE = "tokenizer_config.json"
  40. # Define type aliases
  41. TextInput = str
  42. TextPairInput = Tuple[str, str]
  43. PreTokenizedInput = List[str]
  44. PreTokenizedInputPair = Tuple[List[str], List[str]]
  45. def flatten(x: Sequence):
  46. """
  47. Flatten the provided (potentially nested) sequence
  48. Args:
  49. x (Sequence): Potentially nested sequence to flatten
  50. Returns:
  51. list: Flattened sequence
  52. """
  53. return functools.reduce(operator.iconcat, x, [])
  54. @contextmanager
  55. def truncate_and_pad(
  56. tokenizer: BaseTokenizer,
  57. max_length: int,
  58. stride: int,
  59. strategy: str,
  60. pad_to_max_length: bool,
  61. padding_side: str,
  62. pad_token_id: int,
  63. pad_token_type_id: int,
  64. pad_token: str,
  65. ):
  66. """
  67. This contextmanager is in charge of defining the truncation and the padding strategies and then
  68. restore the tokenizer settings afterwards.
  69. This contextmanager assumes the provider tokenizer has no padding / truncation strategy
  70. before the managed section. If your tokenizer set a padding / truncation strategy before,
  71. then it will be reset to no padding/truncation when exiting the managed section.
  72. Args:
  73. tokenizer (BaseTokenizer): The tokenizer which will be used
  74. max_length (int): The maximum size of the sequence
  75. stride (int): The stride to use when handling overflow
  76. strategy (str): Overflowing logic to use
  77. pad_to_max_length (bool): Boolean indicating if the output needs to be padded up to max_length
  78. padding_side (str): "left" or "right" indicating the direction the output sequence will be padded
  79. pad_token_id (int): The integer representation of the padding token to use
  80. pad_token_type_id (int): The integer representation of the padding token type to use
  81. pad_token (str): The string representation of the padding token to use
  82. Returns:
  83. """
  84. # Handle all the truncation and padding stuff
  85. if max_length is not None:
  86. tokenizer.enable_truncation(max_length, stride=stride, strategy=strategy)
  87. if pad_to_max_length and (pad_token and pad_token_id >= 0):
  88. tokenizer.enable_padding(
  89. max_length=max_length,
  90. direction=padding_side,
  91. pad_id=pad_token_id,
  92. pad_type_id=pad_token_type_id,
  93. pad_token=pad_token,
  94. )
  95. elif pad_to_max_length:
  96. logger.warning(
  97. "Disabled padding because no padding token set (pad_token: {}, pad_token_id: {}).\n"
  98. "To remove this error, you can add a new pad token and then resize model embedding:\n"
  99. "\ttokenizer.pad_token = '<PAD>'\n\tmodel.resize_token_embeddings(len(tokenizer))".format(
  100. pad_token, pad_token_id
  101. )
  102. )
  103. yield
  104. if max_length is not None:
  105. tokenizer.no_truncation()
  106. if pad_to_max_length and (pad_token and pad_token_id >= 0):
  107. tokenizer.no_padding()
  108. class BatchEncoding(UserDict):
  109. """
  110. Data structure derived from Dictionary holding all the required information to forward through
  111. a model.
  112. In addition, this structure expose utility methods to map from word/char space to token space.
  113. """
  114. def __init__(self, data: dict, encoding: Optional[Union[Encoding, Sequence[Encoding]]] = None):
  115. super().__init__(data)
  116. if isinstance(encoding, Encoding):
  117. encoding = [encoding]
  118. self._encodings = encoding
  119. def __getitem__(self, item: Union[int, str]) -> Encoding:
  120. if isinstance(item, str):
  121. return self.data[item]
  122. elif self._encodings is not None:
  123. return self._encodings[item]
  124. else:
  125. raise KeyError("int index is supported only on {} from a Rust tokenizer".format(type(self).__name__))
  126. def __getattr__(self, item: str):
  127. return self.data[item]
  128. @property
  129. def encodings(self) -> Optional[List[Encoding]]:
  130. """
  131. Return the list all encoding from the tokenization process
  132. Returns: List[Encoding] or None if input was tokenized through Python tokenizer
  133. """
  134. return self._encodings
  135. def keys(self):
  136. return self.data.keys()
  137. def values(self):
  138. return self.data.values()
  139. def items(self):
  140. return self.data.items()
  141. def char_to_token_offsets(self, sentence: int, char: int) -> Tuple[int, int]:
  142. """
  143. Find the Offsets of the token containing the character at the specified position
  144. Args:
  145. sentence: Index of the sentence relative to the batch provided to the tokenizer
  146. char: Char index to get the relative token offsets
  147. Returns:
  148. tuple: (token start, token end)
  149. """
  150. if not self._encodings:
  151. raise ValueError("char_to_token_offsets() is not available when using Python based tokenizers")
  152. return self[sentence].char_to_token_offsets(char)
  153. def char_to_token(self, sentence: int, char: int) -> int:
  154. """
  155. Return the index of the token at position of the given char.
  156. Args:
  157. sentence (int): Index of the sentence relative to the batch provided to the tokenizer
  158. char (int): Char index to get the relative token offsets
  159. Returns:
  160. int: Integer referring to the position of the token in the returned set of tokens for the sentence
  161. """
  162. if not self._encodings:
  163. raise ValueError("char_to_token() is not available when using Python based tokenizers")
  164. return self[sentence].char_to_token(char)
  165. def char_to_word_offsets(self, sentence: int, char: int) -> Tuple[int, int]:
  166. """
  167. Find the Offsets of the word containing the character at the specified position
  168. Args:
  169. sentence (int): Index of the sentence relative to the batch provided to the tokenizer
  170. char (int): Char index to get the relative token offsets
  171. Returns:
  172. tuple: (word start, word end) representing the first and last characters of the word
  173. """
  174. if not self._encodings:
  175. raise ValueError("char_to_word_offsets() is not available when using Python based tokenizers")
  176. return self[sentence].char_to_word_offsets(char)
  177. def token_to_word_offsets(self, sentence: int, index: int) -> Optional[Tuple[int, int]]:
  178. """
  179. Find the Offsets of the word containing the token at the given index
  180. Args:
  181. sentence (int): Index of the sentence relative to the batch provided to the tokenizer
  182. index (int): Index of the token to map to the original word offsets
  183. Returns:
  184. Optional[tuple]: (word start, word end) or None
  185. """
  186. if not self._encodings:
  187. raise ValueError("token_to_word_offsets() is not available when using Python based tokenizers")
  188. return self[sentence].token_to_word_offsets(index)
  189. class SpecialTokensMixin:
  190. SPECIAL_TOKENS_ATTRIBUTES = [
  191. "bos_token",
  192. "eos_token",
  193. "unk_token",
  194. "sep_token",
  195. "pad_token",
  196. "cls_token",
  197. "mask_token",
  198. "additional_special_tokens",
  199. ]
  200. def __init__(self, **kwargs):
  201. self._bos_token = None
  202. self._eos_token = None
  203. self._unk_token = None
  204. self._sep_token = None
  205. self._pad_token = None
  206. self._cls_token = None
  207. self._mask_token = None
  208. self._pad_token_type_id = 0
  209. self._additional_special_tokens = []
  210. for key, value in kwargs.items():
  211. if key in self.SPECIAL_TOKENS_ATTRIBUTES:
  212. if key == "additional_special_tokens":
  213. assert isinstance(value, (list, tuple)) and all(isinstance(t, str) for t in value)
  214. elif isinstance(value, AddedToken):
  215. setattr(self, key, str(value))
  216. elif isinstance(value, str):
  217. setattr(self, key, value)
  218. else:
  219. raise TypeError(
  220. "special token {} has to be either str or AddedToken but got: {}".format(key, type(value))
  221. )
  222. @property
  223. def bos_token(self):
  224. """ Beginning of sentence token (string). Log an error if used while not having been set. """
  225. if self._bos_token is None:
  226. logger.error("Using bos_token, but it is not set yet.")
  227. return self._bos_token
  228. @property
  229. def eos_token(self):
  230. """ End of sentence token (string). Log an error if used while not having been set. """
  231. if self._eos_token is None:
  232. logger.error("Using eos_token, but it is not set yet.")
  233. return self._eos_token
  234. @property
  235. def unk_token(self):
  236. """ Unknown token (string). Log an error if used while not having been set. """
  237. if self._unk_token is None:
  238. logger.error("Using unk_token, but it is not set yet.")
  239. return self._unk_token
  240. @property
  241. def sep_token(self):
  242. """ Separation token (string). E.g. separate context and query in an input sequence. Log an error if used while not having been set. """
  243. if self._sep_token is None:
  244. logger.error("Using sep_token, but it is not set yet.")
  245. return self._sep_token
  246. @property
  247. def pad_token(self):
  248. """ Padding token (string). Log an error if used while not having been set. """
  249. if self._pad_token is None:
  250. logger.error("Using pad_token, but it is not set yet.")
  251. return self._pad_token
  252. @property
  253. def cls_token(self):
  254. """ Classification token (string). E.g. to extract a summary of an input sequence leveraging self-attention along the full depth of the model. Log an error if used while not having been set. """
  255. if self._cls_token is None:
  256. logger.error("Using cls_token, but it is not set yet.")
  257. return self._cls_token
  258. @property
  259. def mask_token(self):
  260. """ Mask token (string). E.g. when training a model with masked-language modeling. Log an error if used while not having been set. """
  261. if self._mask_token is None:
  262. logger.error("Using mask_token, but it is not set yet.")
  263. return self._mask_token
  264. @property
  265. def additional_special_tokens(self):
  266. """ All the additional special tokens you may want to use (list of strings). Log an error if used while not having been set. """
  267. if self._additional_special_tokens is None:
  268. logger.error("Using additional_special_tokens, but it is not set yet.")
  269. return self._additional_special_tokens
  270. @bos_token.setter
  271. def bos_token(self, value):
  272. self._bos_token = value
  273. @eos_token.setter
  274. def eos_token(self, value):
  275. self._eos_token = value
  276. @unk_token.setter
  277. def unk_token(self, value):
  278. self._unk_token = value
  279. @sep_token.setter
  280. def sep_token(self, value):
  281. self._sep_token = value
  282. @pad_token.setter
  283. def pad_token(self, value):
  284. self._pad_token = value
  285. @cls_token.setter
  286. def cls_token(self, value):
  287. self._cls_token = value
  288. @mask_token.setter
  289. def mask_token(self, value):
  290. self._mask_token = value
  291. @property
  292. def bos_token_id(self):
  293. """ Id of the beginning of sentence token in the vocabulary. Log an error if used while not having been set. """
  294. return self.convert_tokens_to_ids(self.bos_token)
  295. @property
  296. def eos_token_id(self):
  297. """ Id of the end of sentence token in the vocabulary. Log an error if used while not having been set. """
  298. return self.convert_tokens_to_ids(self.eos_token)
  299. @property
  300. def unk_token_id(self):
  301. """ Id of the unknown token in the vocabulary. Log an error if used while not having been set. """
  302. return self.convert_tokens_to_ids(self.unk_token)
  303. @property
  304. def sep_token_id(self):
  305. """ Id of the separation token in the vocabulary. E.g. separate context and query in an input sequence. Log an error if used while not having been set. """
  306. return self.convert_tokens_to_ids(self.sep_token)
  307. @property
  308. def pad_token_id(self):
  309. """ Id of the padding token in the vocabulary. Log an error if used while not having been set. """
  310. return self.convert_tokens_to_ids(self.pad_token)
  311. @property
  312. def pad_token_type_id(self):
  313. """ Id of the padding token type in the vocabulary."""
  314. return self._pad_token_type_id
  315. @property
  316. def cls_token_id(self):
  317. """ Id of the classification token in the vocabulary. E.g. to extract a summary of an input sequence leveraging self-attention along the full depth of the model. Log an error if used while not having been set. """
  318. return self.convert_tokens_to_ids(self.cls_token)
  319. @property
  320. def mask_token_id(self):
  321. """ Id of the mask token in the vocabulary. E.g. when training a model with masked-language modeling. Log an error if used while not having been set. """
  322. return self.convert_tokens_to_ids(self.mask_token)
  323. @property
  324. def additional_special_tokens_ids(self):
  325. """ Ids of all the additional special tokens in the vocabulary (list of integers). Log an error if used while not having been set. """
  326. return self.convert_tokens_to_ids(self.additional_special_tokens)
  327. @property
  328. def special_tokens_map(self):
  329. """ A dictionary mapping special token class attribute (cls_token, unk_token...) to their
  330. values ('<unk>', '<cls>'...)
  331. """
  332. set_attr = {}
  333. for attr in self.SPECIAL_TOKENS_ATTRIBUTES:
  334. attr_value = getattr(self, "_" + attr)
  335. if attr_value:
  336. set_attr[attr] = attr_value
  337. return set_attr
  338. @property
  339. def all_special_tokens(self):
  340. """ List all the special tokens ('<unk>', '<cls>'...) mapped to class attributes
  341. (cls_token, unk_token...).
  342. """
  343. all_toks = []
  344. set_attr = self.special_tokens_map
  345. for attr_value in set_attr.values():
  346. all_toks = all_toks + (list(attr_value) if isinstance(attr_value, (list, tuple)) else [attr_value])
  347. all_toks = list(set(all_toks))
  348. return all_toks
  349. @property
  350. def all_special_ids(self):
  351. """ List the vocabulary indices of the special tokens ('<unk>', '<cls>'...) mapped to
  352. class attributes (cls_token, unk_token...).
  353. """
  354. all_toks = self.all_special_tokens
  355. all_ids = self.convert_tokens_to_ids(all_toks)
  356. return all_ids
  357. @additional_special_tokens.setter
  358. def additional_special_tokens(self, value):
  359. self._additional_special_tokens = value
  360. class PreTrainedTokenizer(SpecialTokensMixin):
  361. """ Base class for all tokenizers.
  362. Handle all the shared methods for tokenization and special tokens as well as methods downloading/caching/loading pretrained tokenizers as well as adding tokens to the vocabulary.
  363. This class also contain the added tokens in a unified way on top of all tokenizers so we don't have to handle the specific vocabulary augmentation methods of the various underlying dictionary structures (BPE, sentencepiece...).
  364. Class attributes (overridden by derived classes):
  365. - ``vocab_files_names``: a python ``dict`` with, as keys, the ``__init__`` keyword name of each vocabulary file required by the model, and as associated values, the filename for saving the associated file (string).
  366. - ``pretrained_vocab_files_map``: a python ``dict of dict`` the high-level keys being the ``__init__`` keyword name of each vocabulary file required by the model, the low-level being the `short-cut-names` (string) of the pretrained models with, as associated values, the `url` (string) to the associated pretrained vocabulary file.
  367. - ``max_model_input_sizes``: a python ``dict`` with, as keys, the `short-cut-names` (string) of the pretrained models, and as associated values, the maximum length of the sequence inputs of this model, or None if the model has no maximum input size.
  368. - ``pretrained_init_configuration``: a python ``dict`` with, as keys, the `short-cut-names` (string) of the pretrained models, and as associated values, a dictionnary of specific arguments to pass to the ``__init__``method of the tokenizer class for this pretrained model when loading the tokenizer with the ``from_pretrained()`` method.
  369. Parameters:
  370. - ``bos_token``: (`Optional`) string: a beginning of sentence token. Will be associated to ``self.bos_token`` and ``self.bos_token_id``
  371. - ``eos_token``: (`Optional`) string: an end of sentence token. Will be associated to ``self.eos_token`` and ``self.eos_token_id``
  372. - ``unk_token``: (`Optional`) string: an unknown token. Will be associated to ``self.unk_token`` and ``self.unk_token_id``
  373. - ``sep_token``: (`Optional`) string: a separation token (e.g. to separate context and query in an input sequence). Will be associated to ``self.sep_token`` and ``self.sep_token_id``
  374. - ``pad_token``: (`Optional`) string: a padding token. Will be associated to ``self.pad_token`` and ``self.pad_token_id``
  375. - ``cls_token``: (`Optional`) string: a classification token (e.g. to extract a summary of an input sequence leveraging self-attention along the full depth of the model). Will be associated to ``self.cls_token`` and ``self.cls_token_id``
  376. - ``mask_token``: (`Optional`) string: a masking token (e.g. when training a model with masked-language modeling). Will be associated to ``self.mask_token`` and ``self.mask_token_id``
  377. - ``additional_special_tokens``: (`Optional`) list: a list of additional special tokens. Adding all special tokens here ensure they won't be split by the tokenization process. Will be associated to ``self.additional_special_tokens`` and ``self.additional_special_tokens_ids``
  378. """
  379. vocab_files_names = {}
  380. pretrained_vocab_files_map = {}
  381. pretrained_init_configuration = {}
  382. max_model_input_sizes = {}
  383. model_input_names = ["token_type_ids", "attention_mask"]
  384. padding_side = "right"
  385. NO_PAD_TOKEN_FOR_BATCH_MSG = (
  386. "No padding token is set for this model, therefore no batch can be made with uneven "
  387. "sequences. Set a padding token or adjust the lengths of the sequences building the "
  388. "batch so that every sequence is of the same length."
  389. )
  390. UNEVEN_SEQUENCES_FOR_BATCH_MSG = (
  391. "The sequences building the batch are not of the same size, no tensor "
  392. "can be built. Set `pad_to_max_length=True` to pad the smaller sequences"
  393. "up to the larger sequence's length."
  394. )
  395. @property
  396. def vocab_size(self) -> int:
  397. """ Size of the base vocabulary (without the added tokens) """
  398. raise NotImplementedError
  399. @property
  400. def is_fast(self):
  401. return False
  402. def get_vocab(self):
  403. """ Returns the vocabulary as a dict of {token: index} pairs. `tokenizer.get_vocab()[token]` is equivalent to `tokenizer.convert_tokens_to_ids(token)` when `token` is in the vocab. """
  404. raise NotImplementedError()
  405. def __init__(self, max_len=None, **kwargs):
  406. super().__init__(**kwargs)
  407. self.max_len = max_len if max_len is not None else int(1e12)
  408. # Padding side is right by default and over-riden in subclasses. If specified in the kwargs, it is changed.
  409. self.padding_side = kwargs.pop("padding_side", self.padding_side)
  410. self.model_input_names = kwargs.pop("model_input_names", self.model_input_names)
  411. # Added tokens
  412. self.added_tokens_encoder = {}
  413. self.unique_added_tokens_encoder = set()
  414. self.added_tokens_decoder = {}
  415. # inputs and kwargs for saving and re-loading (see ``from_pretrained`` and ``save_pretrained``)
  416. self.init_inputs = ()
  417. self.init_kwargs = {}
  418. def __len__(self):
  419. """ Size of the full vocabulary with the added tokens """
  420. return self.vocab_size + len(self.added_tokens_encoder)
  421. @classmethod
  422. def from_pretrained(cls, *inputs, **kwargs):
  423. r"""
  424. Instantiate a :class:`~transformers.PreTrainedTokenizer` (or a derived class) from a predefined tokenizer.
  425. Args:
  426. pretrained_model_name_or_path: either:
  427. - a string with the `shortcut name` of a predefined tokenizer to load from cache or download, e.g.: ``bert-base-uncased``.
  428. - a string with the `identifier name` of a predefined tokenizer that was user-uploaded to our S3, e.g.: ``dbmdz/bert-base-german-cased``.
  429. - a path to a `directory` containing vocabulary files required by the tokenizer, for instance saved using the :func:`~transformers.PreTrainedTokenizer.save_pretrained` method, e.g.: ``./my_model_directory/``.
  430. - (not applicable to all derived classes, deprecated) a path or url to a single saved vocabulary file if and only if the tokenizer only requires a single vocabulary file (e.g. Bert, XLNet), e.g.: ``./my_model_directory/vocab.txt``.
  431. cache_dir: (`optional`) string:
  432. Path to a directory in which a downloaded predefined tokenizer vocabulary files should be cached if the standard cache should not be used.
  433. force_download: (`optional`) boolean, default False:
  434. Force to (re-)download the vocabulary files and override the cached versions if they exists.
  435. resume_download: (`optional`) boolean, default False:
  436. Do not delete incompletely recieved file. Attempt to resume the download if such a file exists.
  437. proxies: (`optional`) dict, default None:
  438. A dictionary of proxy servers to use by protocol or endpoint, e.g.: {'http': 'foo.bar:3128', 'http://hostname': 'foo.bar:4012'}.
  439. The proxies are used on each request.
  440. inputs: (`optional`) positional arguments: will be passed to the Tokenizer ``__init__`` method.
  441. kwargs: (`optional`) keyword arguments: will be passed to the Tokenizer ``__init__`` method. Can be used to set special tokens like ``bos_token``, ``eos_token``, ``unk_token``, ``sep_token``, ``pad_token``, ``cls_token``, ``mask_token``, ``additional_special_tokens``. See parameters in the doc string of :class:`~transformers.PreTrainedTokenizer` for details.
  442. Examples::
  443. # We can't instantiate directly the base class `PreTrainedTokenizer` so let's show our examples on a derived class: BertTokenizer
  444. # Download vocabulary from S3 and cache.
  445. tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')
  446. # Download vocabulary from S3 (user-uploaded) and cache.
  447. tokenizer = BertTokenizer.from_pretrained('dbmdz/bert-base-german-cased')
  448. # If vocabulary files are in a directory (e.g. tokenizer was saved using `save_pretrained('./test/saved_model/')`)
  449. tokenizer = BertTokenizer.from_pretrained('./test/saved_model/')
  450. # If the tokenizer uses a single vocabulary file, you can point directly to this file
  451. tokenizer = BertTokenizer.from_pretrained('./test/saved_model/my_vocab.txt')
  452. # You can link tokens to special vocabulary when instantiating
  453. tokenizer = BertTokenizer.from_pretrained('bert-base-uncased', unk_token='<unk>')
  454. # You should be sure '<unk>' is in the vocabulary when doing that.
  455. # Otherwise use tokenizer.add_special_tokens({'unk_token': '<unk>'}) instead)
  456. assert tokenizer.unk_token == '<unk>'
  457. """
  458. return cls._from_pretrained(*inputs, **kwargs)
  459. @classmethod
  460. def _from_pretrained(cls, pretrained_model_name_or_path, *init_inputs, **kwargs):
  461. cache_dir = kwargs.pop("cache_dir", None)
  462. force_download = kwargs.pop("force_download", False)
  463. resume_download = kwargs.pop("resume_download", False)
  464. proxies = kwargs.pop("proxies", None)
  465. local_files_only = kwargs.pop("local_files_only", False)
  466. s3_models = list(cls.max_model_input_sizes.keys())
  467. vocab_files = {}
  468. init_configuration = {}
  469. if pretrained_model_name_or_path in s3_models:
  470. # Get the vocabulary from AWS S3 bucket
  471. for file_id, map_list in cls.pretrained_vocab_files_map.items():
  472. vocab_files[file_id] = map_list[pretrained_model_name_or_path]
  473. if (
  474. cls.pretrained_init_configuration
  475. and pretrained_model_name_or_path in cls.pretrained_init_configuration
  476. ):
  477. init_configuration = cls.pretrained_init_configuration[pretrained_model_name_or_path].copy()
  478. else:
  479. # Get the vocabulary from local files
  480. logger.info(
  481. "Model name '{}' not found in model shortcut name list ({}). "
  482. "Assuming '{}' is a path, a model identifier, or url to a directory containing tokenizer files.".format(
  483. pretrained_model_name_or_path, ", ".join(s3_models), pretrained_model_name_or_path
  484. )
  485. )
  486. if os.path.isfile(pretrained_model_name_or_path) or is_remote_url(pretrained_model_name_or_path):
  487. if len(cls.vocab_files_names) > 1:
  488. raise ValueError(
  489. "Calling {}.from_pretrained() with the path to a single file or url is not supported."
  490. "Use a model identifier or the path to a directory instead.".format(cls.__name__)
  491. )
  492. logger.warning(
  493. "Calling {}.from_pretrained() with the path to a single file or url is deprecated".format(
  494. cls.__name__
  495. )
  496. )
  497. file_id = list(cls.vocab_files_names.keys())[0]
  498. vocab_files[file_id] = pretrained_model_name_or_path
  499. else:
  500. # At this point pretrained_model_name_or_path is either a directory or a model identifier name
  501. additional_files_names = {
  502. "added_tokens_file": ADDED_TOKENS_FILE,
  503. "special_tokens_map_file": SPECIAL_TOKENS_MAP_FILE,
  504. "tokenizer_config_file": TOKENIZER_CONFIG_FILE,
  505. }
  506. # Look for the tokenizer main vocabulary files + the additional tokens files
  507. for file_id, file_name in {**cls.vocab_files_names, **additional_files_names}.items():
  508. if os.path.isdir(pretrained_model_name_or_path):
  509. full_file_name = os.path.join(pretrained_model_name_or_path, file_name)
  510. if not os.path.exists(full_file_name):
  511. logger.info("Didn't find file {}. We won't load it.".format(full_file_name))
  512. full_file_name = None
  513. else:
  514. full_file_name = hf_bucket_url(pretrained_model_name_or_path, postfix=file_name)
  515. vocab_files[file_id] = full_file_name
  516. # Get files from url, cache, or disk depending on the case
  517. try:
  518. resolved_vocab_files = {}
  519. for file_id, file_path in vocab_files.items():
  520. if file_path is None:
  521. resolved_vocab_files[file_id] = None
  522. else:
  523. resolved_vocab_files[file_id] = cached_path(
  524. file_path,
  525. cache_dir=cache_dir,
  526. force_download=force_download,
  527. proxies=proxies,
  528. resume_download=resume_download,
  529. local_files_only=local_files_only,
  530. )
  531. except EnvironmentError:
  532. if pretrained_model_name_or_path in s3_models:
  533. msg = "Couldn't reach server at '{}' to download vocabulary files."
  534. else:
  535. msg = (
  536. "Model name '{}' was not found in tokenizers model name list ({}). "
  537. "We assumed '{}' was a path or url to a directory containing vocabulary files "
  538. "named {}, but couldn't find such vocabulary files at this path or url.".format(
  539. pretrained_model_name_or_path,
  540. ", ".join(s3_models),
  541. pretrained_model_name_or_path,
  542. list(cls.vocab_files_names.values()),
  543. )
  544. )
  545. raise EnvironmentError(msg)
  546. if all(full_file_name is None for full_file_name in resolved_vocab_files.values()):
  547. raise EnvironmentError(
  548. "Model name '{}' was not found in tokenizers model name list ({}). "
  549. "We assumed '{}' was a path, a model identifier, or url to a directory containing vocabulary files "
  550. "named {} but couldn't find such vocabulary files at this path or url.".format(
  551. pretrained_model_name_or_path,
  552. ", ".join(s3_models),
  553. pretrained_model_name_or_path,
  554. list(cls.vocab_files_names.values()),
  555. )
  556. )
  557. for file_id, file_path in vocab_files.items():
  558. if file_path == resolved_vocab_files[file_id]:
  559. logger.info("loading file {}".format(file_path))
  560. else:
  561. logger.info("loading file {} from cache at {}".format(file_path, resolved_vocab_files[file_id]))
  562. # Prepare tokenizer initialization kwargs
  563. # Did we saved some inputs and kwargs to reload ?
  564. tokenizer_config_file = resolved_vocab_files.pop("tokenizer_config_file", None)
  565. if tokenizer_config_file is not None:
  566. with open(tokenizer_config_file, encoding="utf-8") as tokenizer_config_handle:
  567. init_kwargs = json.load(tokenizer_config_handle)
  568. saved_init_inputs = init_kwargs.pop("init_inputs", ())
  569. if not init_inputs:
  570. init_inputs = saved_init_inputs
  571. else:
  572. init_kwargs = init_configuration
  573. # Update with newly provided kwargs
  574. init_kwargs.update(kwargs)
  575. # Set max length if needed
  576. if pretrained_model_name_or_path in cls.max_model_input_sizes:
  577. # if we're using a pretrained model, ensure the tokenizer
  578. # wont index sequences longer than the number of positional embeddings
  579. max_len = cls.max_model_input_sizes[pretrained_model_name_or_path]
  580. if max_len is not None and isinstance(max_len, (int, float)):
  581. init_kwargs["max_len"] = min(init_kwargs.get("max_len", int(1e12)), max_len)
  582. # Merge resolved_vocab_files arguments in init_kwargs.
  583. added_tokens_file = resolved_vocab_files.pop("added_tokens_file", None)
  584. special_tokens_map_file = resolved_vocab_files.pop("special_tokens_map_file", None)
  585. for args_name, file_path in resolved_vocab_files.items():
  586. if args_name not in init_kwargs:
  587. init_kwargs[args_name] = file_path
  588. if special_tokens_map_file is not None:
  589. with open(special_tokens_map_file, encoding="utf-8") as special_tokens_map_handle:
  590. special_tokens_map = json.load(special_tokens_map_handle)
  591. for key, value in special_tokens_map.items():
  592. if key not in init_kwargs:
  593. init_kwargs[key] = value
  594. # Instantiate tokenizer.
  595. try:
  596. tokenizer = cls(*init_inputs, **init_kwargs)
  597. except OSError:
  598. raise OSError(
  599. "Unable to load vocabulary from file. "
  600. "Please check that the provided vocabulary is accessible and not corrupted."
  601. )
  602. # Save inputs and kwargs for saving and re-loading with ``save_pretrained``
  603. tokenizer.init_inputs = init_inputs
  604. tokenizer.init_kwargs = init_kwargs
  605. # update unique_added_tokens_encoder with special tokens for correct tokenization
  606. tokenizer.unique_added_tokens_encoder.update(set(tokenizer.all_special_tokens))
  607. # Add supplementary tokens.
  608. if added_tokens_file is not None:
  609. with open(added_tokens_file, encoding="utf-8") as added_tokens_handle:
  610. added_tok_encoder = json.load(added_tokens_handle)
  611. added_tok_decoder = {v: k for k, v in added_tok_encoder.items()}
  612. tokenizer.added_tokens_encoder.update(added_tok_encoder)
  613. tokenizer.added_tokens_decoder.update(added_tok_decoder)
  614. tokenizer.unique_added_tokens_encoder.update(set(tokenizer.added_tokens_encoder.keys()))
  615. return tokenizer
  616. def save_pretrained(self, save_directory):
  617. """ Save the tokenizer vocabulary files together with:
  618. - added tokens,
  619. - special-tokens-to-class-attributes-mapping,
  620. - tokenizer instantiation positional and keywords inputs (e.g. do_lower_case for Bert).
  621. This won't save modifications other than (added tokens and special token mapping) you may have
  622. applied to the tokenizer after the instantiation (e.g. modifying tokenizer.do_lower_case after creation).
  623. This method make sure the full tokenizer can then be re-loaded using the :func:`~transformers.PreTrainedTokenizer.from_pretrained` class method.
  624. """
  625. if not os.path.isdir(save_directory):
  626. logger.error("Saving directory ({}) should be a directory".format(save_directory))
  627. return
  628. special_tokens_map_file = os.path.join(save_directory, SPECIAL_TOKENS_MAP_FILE)
  629. added_tokens_file = os.path.join(save_directory, ADDED_TOKENS_FILE)
  630. tokenizer_config_file = os.path.join(save_directory, TOKENIZER_CONFIG_FILE)
  631. tokenizer_config = copy.deepcopy(self.init_kwargs)
  632. if len(self.init_inputs) > 0:
  633. tokenizer_config["init_inputs"] = copy.deepcopy(self.init_inputs)
  634. for file_id in self.vocab_files_names.keys():
  635. tokenizer_config.pop(file_id, None)
  636. with open(tokenizer_config_file, "w", encoding="utf-8") as f:
  637. f.write(json.dumps(tokenizer_config, ensure_ascii=False))
  638. with open(special_tokens_map_file, "w", encoding="utf-8") as f:
  639. f.write(json.dumps(self.special_tokens_map, ensure_ascii=False))
  640. if len(self.added_tokens_encoder) > 0:
  641. with open(added_tokens_file, "w", encoding="utf-8") as f:
  642. out_str = json.dumps(self.added_tokens_encoder, ensure_ascii=False)
  643. f.write(out_str)
  644. vocab_files = self.save_vocabulary(save_directory)
  645. return vocab_files + (special_tokens_map_file, added_tokens_file)
  646. def save_vocabulary(self, save_directory):
  647. """ Save the tokenizer vocabulary to a directory. This method does *NOT* save added tokens
  648. and special token mappings.
  649. Please use :func:`~transformers.PreTrainedTokenizer.save_pretrained` `()` to save the full Tokenizer state if you want to reload it using the :func:`~transformers.PreTrainedTokenizer.from_pretrained` class method.
  650. """
  651. raise NotImplementedError
  652. def add_tokens(self, new_tokens):
  653. """
  654. Add a list of new tokens to the tokenizer class. If the new tokens are not in the
  655. vocabulary, they are added to it with indices starting from length of the current vocabulary.
  656. Args:
  657. new_tokens: string or list of string. Each string is a token to add. Tokens are only added if they are not already in the vocabulary (tested by checking if the tokenizer assign the index of the ``unk_token`` to them).
  658. Returns:
  659. Number of tokens added to the vocabulary.
  660. Examples::
  661. # Let's see how to increase the vocabulary of Bert model and tokenizer
  662. tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')
  663. model = BertModel.from_pretrained('bert-base-uncased')
  664. num_added_toks = tokenizer.add_tokens(['new_tok1', 'my_new-tok2'])
  665. print('We have added', num_added_toks, 'tokens')
  666. model.resize_token_embeddings(len(tokenizer)) # Notice: resize_token_embeddings expect to receive the full size of the new vocabulary, i.e. the length of the tokenizer.
  667. """
  668. if not new_tokens:
  669. return 0
  670. if not isinstance(new_tokens, list):
  671. new_tokens = [new_tokens]
  672. to_add_tokens = []
  673. for token in new_tokens:
  674. assert isinstance(token, str)
  675. if self.init_kwargs.get("do_lower_case", False) and token not in self.all_special_tokens:
  676. token = token.lower()
  677. if (
  678. token != self.unk_token
  679. and self.convert_tokens_to_ids(token) == self.convert_tokens_to_ids(self.unk_token)
  680. and token not in to_add_tokens
  681. ):
  682. to_add_tokens.append(token)
  683. logger.info("Adding %s to the vocabulary", token)
  684. added_tok_encoder = dict((tok, len(self) + i) for i, tok in enumerate(to_add_tokens))
  685. added_tok_decoder = {v: k for k, v in added_tok_encoder.items()}
  686. self.added_tokens_encoder.update(added_tok_encoder)
  687. self.unique_added_tokens_encoder = set(self.added_tokens_encoder.keys()).union(set(self.all_special_tokens))
  688. self.added_tokens_decoder.update(added_tok_decoder)
  689. return len(to_add_tokens)
  690. def num_special_tokens_to_add(self, pair=False):
  691. """
  692. Returns the number of added tokens when encoding a sequence with special tokens.
  693. Note:
  694. This encodes inputs and checks the number of added tokens, and is therefore not efficient. Do not put this
  695. inside your training loop.
  696. Args:
  697. pair: Returns the number of added tokens in the case of a sequence pair if set to True, returns the
  698. number of added tokens in the case of a single sequence if set to False.
  699. Returns:
  700. Number of tokens added to sequences
  701. """
  702. token_ids_0 = []
  703. token_ids_1 = []
  704. return len(self.build_inputs_with_special_tokens(token_ids_0, token_ids_1 if pair else None))
  705. def add_special_tokens(self, special_tokens_dict):
  706. """
  707. Add a dictionary of special tokens (eos, pad, cls...) to the encoder and link them
  708. to class attributes. If special tokens are NOT in the vocabulary, they are added
  709. to it (indexed starting from the last index of the current vocabulary).
  710. Using `add_special_tokens` will ensure your special tokens can be used in several ways:
  711. - special tokens are carefully handled by the tokenizer (they are never split)
  712. - you can easily refer to special tokens using tokenizer class attributes like `tokenizer.cls_token`. This makes it easy to develop model-agnostic training and fine-tuning scripts.
  713. When possible, special tokens are already registered for provided pretrained models (ex: BertTokenizer cls_token is already registered to be '[CLS]' and XLM's one is also registered to be '</s>')
  714. Args:
  715. special_tokens_dict: dict of string. Keys should be in the list of predefined special attributes:
  716. [``bos_token``, ``eos_token``, ``unk_token``, ``sep_token``, ``pad_token``, ``cls_token``, ``mask_token``,
  717. ``additional_special_tokens``].
  718. Tokens are only added if they are not already in the vocabulary (tested by checking if the tokenizer assign the index of the ``unk_token`` to them).
  719. Returns:
  720. Number of tokens added to the vocabulary.
  721. Examples::
  722. # Let's see how to add a new classification token to GPT-2
  723. tokenizer = GPT2Tokenizer.from_pretrained('gpt2')
  724. model = GPT2Model.from_pretrained('gpt2')
  725. special_tokens_dict = {'cls_token': '<CLS>'}
  726. num_added_toks = tokenizer.add_special_tokens(special_tokens_dict)
  727. print('We have added', num_added_toks, 'tokens')
  728. model.resize_token_embeddings(len(tokenizer)) # Notice: resize_token_embeddings expect to receive the full size of the new vocabulary, i.e. the length of the tokenizer.
  729. assert tokenizer.cls_token == '<CLS>'
  730. """
  731. if not special_tokens_dict:
  732. return 0
  733. added_tokens = 0
  734. for key, value in special_tokens_dict.items():
  735. assert key in self.SPECIAL_TOKENS_ATTRIBUTES
  736. if key == "additional_special_tokens":
  737. assert isinstance(value, (list, tuple)) and all(isinstance(t, str) for t in value)
  738. added_tokens += self.add_tokens(value)
  739. else:
  740. assert isinstance(value, str)
  741. added_tokens += self.add_tokens([value])
  742. logger.info("Assigning %s to the %s key of the tokenizer", value, key)
  743. setattr(self, key, value)
  744. return added_tokens
  745. def tokenize(self, text: TextInput, **kwargs):
  746. """ Converts a string in a sequence of tokens (string), using the tokenizer.
  747. Split in words for word-based vocabulary or sub-words for sub-word-based
  748. vocabularies (BPE/SentencePieces/WordPieces).
  749. Take care of added tokens.
  750. text: The sequence to be encoded.
  751. add_prefix_space: Only applies to GPT-2 and RoBERTa tokenizers. When `True`, this ensures that the sequence
  752. begins with an empty space. False by default except for when using RoBERTa with `add_special_tokens=True`.
  753. **kwargs: passed to the `prepare_for_tokenization` preprocessing method.
  754. """
  755. all_special_tokens = self.all_special_tokens
  756. text = self.prepare_for_tokenization(text, **kwargs)
  757. def lowercase_text(t):
  758. # convert non-special tokens to lowercase
  759. escaped_special_toks = [re.escape(s_tok) for s_tok in all_special_tokens]
  760. pattern = r"(" + r"|".join(escaped_special_toks) + r")|" + r"(.+?)"
  761. return re.sub(pattern, lambda m: m.groups()[0] or m.groups()[1].lower(), t)
  762. if self.init_kwargs.get("do_lower_case", False):
  763. text = lowercase_text(text)
  764. def split_on_token(tok, text):
  765. result = []
  766. split_text = text.split(tok)
  767. for i, sub_text in enumerate(split_text):
  768. sub_text = sub_text.rstrip()
  769. if i == 0 and not sub_text:
  770. result += [tok]
  771. elif i == len(split_text) - 1:
  772. if sub_text:
  773. result += [sub_text]
  774. else:
  775. pass
  776. else:
  777. if sub_text:
  778. result += [sub_text]
  779. result += [tok]
  780. return result
  781. def split_on_tokens(tok_list, text):
  782. if not text.strip():
  783. return []
  784. if not tok_list:
  785. return self._tokenize(text)
  786. tokenized_text = []
  787. text_list = [text]
  788. for tok in tok_list:
  789. tokenized_text = []
  790. for sub_text in text_list:
  791. if sub_text not in self.unique_added_tokens_encoder:
  792. tokenized_text += split_on_token(tok, sub_text)
  793. else:
  794. tokenized_text += [sub_text]
  795. text_list = tokenized_text
  796. return list(
  797. itertools.chain.from_iterable(
  798. (
  799. self._tokenize(token) if token not in self.unique_added_tokens_encoder else [token]
  800. for token in tokenized_text
  801. )
  802. )
  803. )
  804. added_tokens = self.unique_added_tokens_encoder
  805. tokenized_text = split_on_tokens(added_tokens, text)
  806. return tokenized_text
  807. def _tokenize(self, text, **kwargs):
  808. """ Converts a string in a sequence of tokens (string), using the tokenizer.
  809. Split in words for word-based vocabulary or sub-words for sub-word-based
  810. vocabularies (BPE/SentencePieces/WordPieces).
  811. Do NOT take care of added tokens.
  812. """
  813. raise NotImplementedError
  814. def convert_tokens_to_ids(self, tokens):
  815. """ Converts a single token, or a sequence of tokens, (str) in a single integer id
  816. (resp. a sequence of ids), using the vocabulary.
  817. """
  818. if tokens is None:
  819. return None
  820. if isinstance(tokens, str):
  821. return self._convert_token_to_id_with_added_voc(tokens)
  822. ids = []
  823. for token in tokens:
  824. ids.append(self._convert_token_to_id_with_added_voc(token))
  825. return ids
  826. def _convert_token_to_id_with_added_voc(self, token):
  827. if token is None:
  828. return None
  829. if token in self.added_tokens_encoder:
  830. return self.added_tokens_encoder[token]
  831. return self._convert_token_to_id(token)
  832. def _convert_token_to_id(self, token):
  833. raise NotImplementedError
  834. def encode(
  835. self,
  836. text: TextInput,
  837. text_pair: Optional[TextInput] = None,
  838. add_special_tokens: bool = True,
  839. max_length: Optional[int] = None,
  840. stride: int = 0,
  841. truncation_strategy: str = "longest_first",
  842. pad_to_max_length: bool = False,
  843. return_tensors: Optional[str] = None,
  844. **kwargs
  845. ):
  846. """
  847. Converts a string in a sequence of ids (integer), using the tokenizer and vocabulary.
  848. Same as doing ``self.convert_tokens_to_ids(self.tokenize(text))``.
  849. Args:
  850. text (:obj:`str` or :obj:`List[str]`):
  851. The first sequence to be encoded. This can be a string, a list of strings (tokenized string using
  852. the `tokenize` method) or a list of integers (tokenized string ids using the `convert_tokens_to_ids`
  853. method)
  854. text_pair (:obj:`str` or :obj:`List[str]`, `optional`, defaults to :obj:`None`):
  855. Optional second sequence to be encoded. This can be a string, a list of strings (tokenized
  856. string using the `tokenize` method) or a list of integers (tokenized string ids using the
  857. `convert_tokens_to_ids` method)
  858. add_special_tokens (:obj:`bool`, `optional`, defaults to :obj:`True`):
  859. If set to ``True``, the sequences will be encoded with the special tokens relative
  860. to their model.
  861. max_length (:obj:`int`, `optional`, defaults to :obj:`None`):
  862. If set to a number, will limit the total sequence returned so that it has a maximum length.
  863. If there are overflowing tokens, those will be added to the returned dictionary
  864. stride (:obj:`int`, `optional`, defaults to ``0``):
  865. If set to a number along with max_length, the overflowing tokens returned will contain some tokens
  866. from the main sequence returned. The value of this argument defines the number of additional tokens.
  867. truncation_strategy (:obj:`str`, `optional`, defaults to `longest_first`):
  868. String selected in the following options:
  869. - 'longest_first' (default) Iteratively reduce the inputs sequence until the input is under max_length
  870. starting from the longest one at each token (when there is a pair of input sequences)
  871. - 'only_first': Only truncate the first sequence
  872. - 'only_second': Only truncate the second sequence
  873. - 'do_not_truncate': Does not truncate (raise an error if the input sequence is longer than max_length)
  874. pad_to_max_length (:obj:`bool`, `optional`, defaults to :obj:`False`):
  875. If set to True, the returned sequences will be padded according to the model's padding side and
  876. padding index, up to their max length. If no max length is specified, the padding is done up to the
  877. model's max length. The tokenizer padding sides are handled by the class attribute `padding_side`
  878. which can be set to the following strings:
  879. - 'left': pads on the left of the sequences
  880. - 'right': pads on the right of the sequences
  881. Defaults to False: no padding.
  882. return_tensors (:obj:`str`, `optional`, defaults to :obj:`None`):
  883. Can be set to 'tf' or 'pt' to return respectively TensorFlow :obj:`tf.constant`
  884. or PyTorch :obj:`torch.Tensor` instead of a list of python integers.
  885. **kwargs: passed to the `self.tokenize()` method
  886. """
  887. encoded_inputs = self.encode_plus(
  888. text,
  889. text_pair=text_pair,
  890. max_length=max_length,
  891. add_special_tokens=add_special_tokens,
  892. stride=stride,
  893. truncation_strategy=truncation_strategy,
  894. pad_to_max_length=pad_to_max_length,
  895. return_tensors=return_tensors,
  896. **kwargs,
  897. )
  898. return encoded_inputs["input_ids"]
  899. def encode_plus(
  900. self,
  901. text: TextInput,
  902. text_pair: Optional[TextInput] = None,
  903. add_special_tokens: bool = True,
  904. max_length: Optional[int] = None,
  905. stride: int = 0,
  906. truncation_strategy: str = "longest_first",
  907. pad_to_max_length: bool = False,
  908. is_pretokenized: bool = False,
  909. return_tensors: Optional[str] = None,
  910. return_token_type_ids: Optional[bool] = None,
  911. return_attention_mask: Optional[bool] = None,
  912. return_overflowing_tokens: bool = False,
  913. return_special_tokens_mask: bool = False,
  914. return_offsets_mapping: bool = False,
  915. **kwargs
  916. ) -> BatchEncoding:
  917. """
  918. Returns a dictionary containing the encoded sequence or sequence pair and additional information:
  919. the mask for sequence classification and the overflowing elements if a ``max_length`` is specified.
  920. Args:
  921. text (:obj:`str` or :obj:`List[str]`):
  922. The first sequence to be encoded. This can be a string, a list of strings (tokenized string using
  923. the `tokenize` method) or a list of integers (tokenized string ids using the `convert_tokens_to_ids`
  924. method)
  925. text_pair (:obj:`str` or :obj:`List[str]`, `optional`, defaults to :obj:`None`):
  926. Optional second sequence to be encoded. This can be a string, a list of strings (tokenized
  927. string using the `tokenize` method) or a list of integers (tokenized string ids using the
  928. `convert_tokens_to_ids` method)
  929. add_special_tokens (:obj:`bool`, `optional`, defaults to :obj:`True`):
  930. If set to ``True``, the sequences will be encoded with the special tokens relative
  931. to their model.
  932. max_length (:obj:`int`, `optional`, defaults to :obj:`None`):
  933. If set to a number, will limit the total sequence returned so that it has a maximum length.
  934. If there are overflowing tokens, those will be added to the returned dictionary
  935. stride (:obj:`int`, `optional`, defaults to ``0``):
  936. If set to a number along with max_length, the overflowing tokens returned will contain some tokens
  937. from the main sequence returned. The value of this argument defines the number of additional tokens.
  938. truncation_strategy (:obj:`str`, `optional`, defaults to `longest_first`):
  939. String selected in the following options:
  940. - 'longest_first' (default) Iteratively reduce the inputs sequence until the input is under max_length
  941. starting from the longest one at each token (when there is a pair of input sequences)
  942. - 'only_first': Only truncate the first sequence
  943. - 'only_second': Only truncate the second sequence
  944. - 'do_not_truncate': Does not truncate (raise an error if the input sequence is longer than max_length)
  945. pad_to_max_length (:obj:`bool`, `optional`, defaults to :obj:`False`):
  946. If set to True, the returned sequences will be padded according to the model's padding side and
  947. padding index, up to their max length. If no max length is specified, the padding is done up to the
  948. model's max length. The tokenizer padding sides are handled by the class attribute `padding_side`
  949. which can be set to the following strings:
  950. - 'left': pads on the left of the sequences
  951. - 'right': pads on the right of the sequences
  952. Defaults to False: no padding.
  953. is_pretokenized (:obj:`bool`, defaults to :obj:`False`):
  954. Set to True to indicate the input is already tokenized
  955. return_tensors (:obj:`str`, `optional`, defaults to :obj:`None`):
  956. Can be set to 'tf' or 'pt' to return respectively TensorFlow :obj:`tf.constant`
  957. or PyTorch :obj:`torch.Tensor` instead of a list of python integers.
  958. return_token_type_ids (:obj:`bool`, `optional`, defaults to :obj:`None`):
  959. Whether to return token type IDs. If left to the default, will return the token type IDs according
  960. to the specific tokenizer's default, defined by the :obj:`return_outputs` attribute.
  961. `What are token type IDs? <../glossary.html#token-type-ids>`_
  962. return_attention_mask (:obj:`bool`, `optional`, defaults to :obj:`none`):
  963. Whether to return the attention mask. If left to the default, will return the attention mask according
  964. to the specific tokenizer's default, defined by the :obj:`return_outputs` attribute.
  965. `What are attention masks? <../glossary.html#attention-mask>`__
  966. return_overflowing_tokens (:obj:`bool`, `optional`, defaults to :obj:`False`):
  967. Set to True to return overflowing token information (default False).
  968. return_special_tokens_mask (:obj:`bool`, `optional`, defaults to :obj:`False`):
  969. Set to True to return special tokens mask information (default False).
  970. return_offsets_mapping (:obj:`bool`, `optional`, defaults to :obj:`False`):
  971. Set to True to return (char_start, char_end) for each token (default False).
  972. If using Python's tokenizer, this method will raise NotImplementedError. This one is only available on
  973. Rust-based tokenizers inheriting from PreTrainedTokenizerFast.
  974. **kwargs: passed to the `self.tokenize()` method
  975. Return:
  976. A Dictionary of shape::
  977. {
  978. input_ids: list[int],
  979. token_type_ids: list[int] if return_token_type_ids is True (default)
  980. attention_mask: list[int] if return_attention_mask is True (default)
  981. overflowing_tokens: list[int] if a ``max_length`` is specified and return_overflowing_tokens is True
  982. num_truncated_tokens: int if a ``max_length`` is specified and return_overflowing_tokens is True
  983. special_tokens_mask: list[int] if ``add_special_tokens`` if set to ``True`` and return_special_tokens_mask is True
  984. }
  985. With the fields:
  986. - ``input_ids``: list of token ids to be fed to a model
  987. - ``token_type_ids``: list of token type ids to be fed to a model
  988. - ``attention_mask``: list of indices specifying which tokens should be attended to by the model
  989. - ``overflowing_tokens``: list of overflowing tokens if a max length is specified.
  990. - ``num_truncated_tokens``: number of overflowing tokens a ``max_length`` is specified
  991. - ``special_tokens_mask``: if adding special tokens, this is a list of [0, 1], with 0 specifying special added
  992. tokens and 1 specifying sequence tokens.
  993. """
  994. def get_input_ids(text):
  995. if isinstance(text, str):
  996. tokens = self.tokenize(text, add_special_tokens=add_special_tokens, **kwargs)
  997. return self.convert_tokens_to_ids(tokens)
  998. elif isinstance(text, (list, tuple)) and len(text) > 0 and isinstance(text[0], str):
  999. return self.convert_tokens_to_ids(text)
  1000. elif isinstance(text, (list, tuple)) and len(text) > 0 and isinstance(text[0], int):
  1001. return text
  1002. else:
  1003. raise ValueError(
  1004. "Input is not valid. Should be a string, a list/tuple of strings or a list/tuple of integers."
  1005. )
  1006. if return_offsets_mapping:
  1007. raise NotImplementedError(
  1008. "return_offset_mapping is not available when using Python tokenizers."
  1009. "To use this feature, change your tokenizer to one deriving from "
  1010. "transformers.PreTrainedTokenizerFast."
  1011. "More information on available tokenizers at "
  1012. "https://github.com/huggingface/transformers/pull/2674"
  1013. )
  1014. # Throw an error if we can pad because there is no padding token
  1015. if pad_to_max_length and self.pad_token_id is None:
  1016. raise ValueError(
  1017. "Unable to set proper padding strategy as the tokenizer does not have a padding token. In this case please set the `pad_token` `(tokenizer.pad_token = tokenizer.eos_token e.g.)` or add a new pad token via the function add_special_tokens if you want to use a padding strategy"
  1018. )
  1019. first_ids = get_input_ids(text)
  1020. second_ids = get_input_ids(text_pair) if text_pair is not None else None
  1021. return self.prepare_for_model(
  1022. first_ids,
  1023. pair_ids=second_ids,
  1024. max_length=max_length,
  1025. pad_to_max_length=pad_to_max_length,
  1026. add_special_tokens=add_special_tokens,
  1027. stride=stride,
  1028. truncation_strategy=truncation_strategy,
  1029. return_tensors=return_tensors,
  1030. return_attention_mask=return_attention_mask,
  1031. return_token_type_ids=return_token_type_ids,
  1032. return_overflowing_tokens=return_overflowing_tokens,
  1033. return_special_tokens_mask=return_special_tokens_mask,
  1034. )
  1035. def batch_encode_plus(
  1036. self,
  1037. batch_text_or_text_pairs: Union[
  1038. List[TextInput], List[TextPairInput], List[PreTokenizedInput], List[PreTokenizedInputPair]
  1039. ],
  1040. add_special_tokens: bool = True,
  1041. max_length: Optional[int] = None,
  1042. stride: int = 0,
  1043. truncation_strategy: str = "longest_first",
  1044. pad_to_max_length: bool = False,
  1045. is_pretokenized: bool = False,
  1046. return_tensors: Optional[str] = None,
  1047. return_token_type_ids: Optional[bool] = None,
  1048. return_attention_masks: Optional[bool] = None,
  1049. return_overflowing_tokens: bool = False,
  1050. return_special_tokens_masks: bool = False,
  1051. return_offsets_mapping: bool = False,
  1052. return_input_lengths: bool = False,
  1053. **kwargs
  1054. ) -> BatchEncoding:
  1055. """
  1056. Returns a dictionary containing the encoded sequence or sequence pair and additional information:
  1057. the mask for sequence classification and the overflowing elements if a ``max_length`` is specified.
  1058. Args:
  1059. batch_text_or_text_pairs (:obj:`List[str]` or :obj:`List[List[str]]`):
  1060. Batch of sequences or pair of sequences to be encoded.
  1061. This can be a list of string/string-sequences/int-sequences or a list of pair of
  1062. string/string-sequences/int-sequence (see details in encode_plus)
  1063. add_special_tokens (:obj:`bool`, `optional`, defaults to :obj:`True`):
  1064. If set to ``True``, the sequences will be encoded with the special tokens relative
  1065. to their model.
  1066. max_length (:obj:`int`, `optional`, defaults to :obj:`None`):
  1067. If set to a number, will limit the total sequence returned so that it has a maximum length.
  1068. If there are overflowing tokens, those will be added to the returned dictionary
  1069. stride (:obj:`int`, `optional`, defaults to ``0``):
  1070. If set to a number along with max_length, the overflowing tokens returned will contain some tokens
  1071. from the main sequence returned. The value of this argument defines the number of additional tokens.
  1072. truncation_strategy (:obj:`str`, `optional`, defaults to `longest_first`):
  1073. String selected in the following options:
  1074. - 'longest_first' (default) Iteratively reduce the inputs sequence until the input is under max_length
  1075. starting from the longest one at each token (when there is a pair of input sequences)
  1076. - 'only_first': Only truncate the first sequence
  1077. - 'only_second': Only truncate the second sequence
  1078. - 'do_not_truncate': Does not truncate (raise an error if the input sequence is longer than max_length)
  1079. pad_to_max_length (:obj:`bool`, `optional`, defaults to :obj:`False`):
  1080. If set to True, the returned sequences will be padded according to the model's padding side and
  1081. padding index, up to their max length. If no max length is specified, the padding is done up to the
  1082. model's max length. The tokenizer padding sides are handled by the class attribute `padding_side`
  1083. which can be set to the following strings:
  1084. - 'left': pads on the left of the sequences
  1085. - 'right': pads on the right of the sequences
  1086. Defaults to False: no padding.
  1087. is_pretokenized (:obj:`bool`, defaults to :obj:`False`):
  1088. Set to True to indicate the input is already tokenized
  1089. return_tensors (:obj:`str`, `optional`, defaults to :obj:`None`):
  1090. Can be set to 'tf' or 'pt' to return respectively TensorFlow :obj:`tf.constant`
  1091. or PyTorch :obj:`torch.Tensor` instead of a list of python integers.
  1092. return_token_type_ids (:obj:`bool`, `optional`, defaults to :obj:`None`):
  1093. Whether to return token type IDs. If left to the default, will return the token type IDs according
  1094. to the specific tokenizer's default, defined by the :obj:`return_outputs` attribute.
  1095. `What are token type IDs? <../glossary.html#token-type-ids>`_
  1096. return_attention_masks (:obj:`bool`, `optional`, defaults to :obj:`none`):
  1097. Whether to return the attention mask. If left to the default, will return the attention mask according
  1098. to the specific tokenizer's default, defined by the :obj:`return_outputs` attribute.
  1099. `What are attention masks? <../glossary.html#attention-mask>`__
  1100. return_overflowing_tokens (:obj:`bool`, `optional`, defaults to :obj:`False`):
  1101. Set to True to return overflowing token information (default False).
  1102. return_special_tokens_masks (:obj:`bool`, `optional`, defaults to :obj:`False`):
  1103. Set to True to return special tokens mask information (default False).
  1104. return_offsets_mapping (:obj:`bool`, `optional`, defaults to :obj:`False`):
  1105. Set to True to return (char_start, char_end) for each token (default False).
  1106. If using Python's tokenizer, this method will raise NotImplementedError. This one is only available on
  1107. Rust-based tokenizers inheriting from PreTrainedTokenizerFast.
  1108. return_input_lengths (:obj:`bool`, `optional`, defaults to :obj:`False`):
  1109. If set the resulting dictionary will include the length of each sample
  1110. **kwargs: passed to the `self.tokenize()` method
  1111. Return:
  1112. A Dictionary of shape::
  1113. {
  1114. input_ids: list[List[int]],
  1115. token_type_ids: list[List[int]] if return_token_type_ids is True (default)
  1116. attention_mask: list[List[int]] if return_attention_mask is True (default)
  1117. overflowing_tokens: list[List[int]] if a ``max_length`` is specified and return_overflowing_tokens is True
  1118. num_truncated_tokens: List[int] if a ``max_length`` is specified and return_overflowing_tokens is True
  1119. special_tokens_mask: list[List[int]] if ``add_special_tokens`` if set to ``True`` and return_special_tokens_mask is True
  1120. }
  1121. With the fields:
  1122. - ``input_ids``: list of token ids to be fed to a model
  1123. - ``token_type_ids``: list of token type ids to be fed to a model
  1124. - ``attention_mask``: list of indices specifying which tokens should be attended to by the model
  1125. - ``overflowing_tokens``: list of overflowing tokens if a max length is specified.
  1126. - ``num_truncated_tokens``: number of overflowing tokens a ``max_length`` is specified
  1127. - ``special_tokens_mask``: if adding special tokens, this is a list of [0, 1], with 0 specifying special added
  1128. tokens and 1 specifying sequence tokens.
  1129. """
  1130. def get_input_ids(text):
  1131. if isinstance(text, str):
  1132. tokens = self.tokenize(text, add_special_tokens=add_special_tokens, **kwargs)
  1133. return self.convert_tokens_to_ids(tokens)
  1134. elif isinstance(text, (list, tuple)) and len(text) > 0 and isinstance(text[0], str):
  1135. return self.convert_tokens_to_ids(text)
  1136. elif isinstance(text, (list, tuple)) and len(text) > 0 and isinstance(text[0], int):
  1137. return text
  1138. else:
  1139. raise ValueError(
  1140. "Input is not valid. Should be a string, a list/tuple of strings or a list/tuple of integers."
  1141. )
  1142. # Throw an error if we can pad because there is no padding token
  1143. if pad_to_max_length and self.pad_token_id is None:
  1144. raise ValueError(
  1145. "Unable to set proper padding strategy as the tokenizer does not have a padding token. In this case please set the `pad_token` `(tokenizer.pad_token = tokenizer.eos_token e.g.)` or add a new pad token via the function add_special_tokens if you want to use a padding strategy"
  1146. )
  1147. if return_offsets_mapping:
  1148. raise NotImplementedError(
  1149. "return_offset_mapping is not available when using Python tokenizers."
  1150. "To use this feature, change your tokenizer to one deriving from "
  1151. "transformers.PreTrainedTokenizerFast."
  1152. "More information on available tokenizers at "
  1153. "https://github.com/huggingface/transformers/pull/2674"
  1154. )
  1155. input_ids = []
  1156. for ids_or_pair_ids in batch_text_or_text_pairs:
  1157. if isinstance(ids_or_pair_ids, (list, tuple)) and len(ids_or_pair_ids) == 2 and not is_pretokenized:
  1158. ids, pair_ids = ids_or_pair_ids
  1159. else:
  1160. ids, pair_ids = ids_or_pair_ids, None
  1161. first_ids = get_input_ids(ids)
  1162. second_ids = get_input_ids(pair_ids) if pair_ids is not None else None
  1163. input_ids.append((first_ids, second_ids))
  1164. if max_length is None and pad_to_max_length:
  1165. def total_sequence_length(input_pairs):
  1166. first_ids, second_ids = input_pairs
  1167. return len(first_ids) + (
  1168. self.num_special_tokens_to_add()
  1169. if second_ids is None
  1170. else (len(second_ids) + self.num_special_tokens_to_add(pair=True))
  1171. )
  1172. max_length = max([total_sequence_length(ids) for ids in input_ids])
  1173. batch_outputs = {}
  1174. for first_ids, second_ids in input_ids:
  1175. # Prepares a sequence of input id, or a pair of sequences of inputs ids so that it can be used by
  1176. # the model. It adds special tokens, truncates sequences if overflowing while taking into account
  1177. # the special tokens and manages a window stride for overflowing tokens
  1178. outputs = self.prepare_for_model(
  1179. first_ids,
  1180. pair_ids=second_ids,
  1181. max_length=max_length,
  1182. pad_to_max_length=pad_to_max_length,
  1183. add_special_tokens=add_special_tokens,
  1184. stride=stride,
  1185. truncation_strategy=truncation_strategy,
  1186. return_attention_mask=return_attention_masks,
  1187. return_token_type_ids=return_token_type_ids,
  1188. return_overflowing_tokens=return_overflowing_tokens,
  1189. return_special_tokens_mask=return_special_tokens_masks,
  1190. )
  1191. # Append the non-padded length to the output
  1192. if return_input_lengths:
  1193. outputs["input_len"] = len(outputs["input_ids"])
  1194. for key, value in outputs.items():
  1195. if key not in batch_outputs:
  1196. batch_outputs[key] = []
  1197. batch_outputs[key].append(value)
  1198. if return_tensors is not None:
  1199. # Do the tensor conversion in batch
  1200. for key, value in batch_outputs.items():
  1201. if return_tensors == "tf" and is_tf_available():
  1202. try:
  1203. batch_outputs[key] = tf.constant(value)
  1204. except ValueError:
  1205. if None in [item for sequence in value for item in sequence]:
  1206. raise ValueError(self.NO_PAD_TOKEN_FOR_BATCH_MSG)
  1207. else:
  1208. raise ValueError(self.UNEVEN_SEQUENCES_FOR_BATCH_MSG)
  1209. elif return_tensors == "pt" and is_torch_available():
  1210. try:
  1211. batch_outputs[key] = torch.tensor(value)
  1212. except ValueError:
  1213. raise ValueError(self.UNEVEN_SEQUENCES_FOR_BATCH_MSG)
  1214. except RuntimeError:
  1215. if None in [item for sequence in value for item in sequence]:
  1216. raise ValueError(self.NO_PAD_TOKEN_FOR_BATCH_MSG)
  1217. else:
  1218. raise
  1219. elif return_tensors is not None:
  1220. logger.warning(
  1221. "Unable to convert output to tensors format {}, PyTorch or TensorFlow is not available.".format(
  1222. return_tensors
  1223. )
  1224. )
  1225. return BatchEncoding(batch_outputs)
  1226. def prepare_for_model(
  1227. self,
  1228. ids: List[int],
  1229. pair_ids: Optional[List[int]] = None,
  1230. max_length: Optional[int] = None,
  1231. add_special_tokens: bool = True,
  1232. stride: int = 0,
  1233. truncation_strategy: str = "longest_first",
  1234. pad_to_max_length: bool = False,
  1235. return_tensors: Optional[str] = None,
  1236. return_token_type_ids: Optional[bool] = None,
  1237. return_attention_mask: Optional[bool] = None,
  1238. return_overflowing_tokens: bool = False,
  1239. return_special_tokens_mask: bool = False,
  1240. ):
  1241. """
  1242. Prepares a sequence of input id, or a pair of sequences of inputs ids so that it can be used by the model.
  1243. It adds special tokens, truncates
  1244. sequences if overflowing while taking into account the special tokens and manages a window stride for
  1245. overflowing tokens
  1246. Args:
  1247. ids: list of tokenized input ids. Can be obtained from a string by chaining the
  1248. `tokenize` and `convert_tokens_to_ids` methods.
  1249. pair_ids: Optional second list of input ids. Can be obtained from a string by chaining the
  1250. `tokenize` and `convert_tokens_to_ids` methods.
  1251. max_length: maximum length of the returned list. Will truncate by taking into account the special tokens.
  1252. add_special_tokens: if set to ``True``, the sequences will be encoded with the special tokens relative
  1253. to their model.
  1254. stride: window stride for overflowing tokens. Can be useful for edge effect removal when using sequential
  1255. list of inputs.
  1256. truncation_strategy: string selected in the following options:
  1257. - 'longest_first' (default) Iteratively reduce the inputs sequence until the input is under max_length
  1258. starting from the longest one at each token (when there is a pair of input sequences)
  1259. - 'only_first': Only truncate the first sequence
  1260. - 'only_second': Only truncate the second sequence
  1261. - 'do_not_truncate': Does not truncate (raise an error if the input sequence is longer than max_length)
  1262. pad_to_max_length: if set to True, the returned sequences will be padded according to the model's padding side and
  1263. padding index, up to their max length. If no max length is specified, the padding is done up to the model's max length.
  1264. The tokenizer padding sides are handled by the following strings:
  1265. - 'left': pads on the left of the sequences
  1266. - 'right': pads on the right of the sequences
  1267. Defaults to False: no padding.
  1268. return_tensors: (optional) can be set to 'tf' or 'pt' to return respectively TensorFlow tf.constant
  1269. or PyTorch torch.Tensor instead of a list of python integers.
  1270. return_token_type_ids: (optional) Set to False to avoid returning token_type_ids (default True).
  1271. return_attention_mask: (optional) Set to False to avoid returning attention mask (default True)
  1272. return_overflowing_tokens: (optional) Set to True to return overflowing token information (default False).
  1273. return_special_tokens_mask: (optional) Set to True to return special tokens mask information (default False).
  1274. Return:
  1275. A Dictionary of shape::
  1276. {
  1277. input_ids: list[int],
  1278. token_type_ids: list[int] if return_token_type_ids is True (default)
  1279. overflowing_tokens: list[int] if a ``max_length`` is specified and return_overflowing_tokens is True
  1280. num_truncated_tokens: int if a ``max_length`` is specified and return_overflowing_tokens is True
  1281. special_tokens_mask: list[int] if ``add_special_tokens`` if set to ``True`` and return_special_tokens_mask is True
  1282. }
  1283. With the fields:
  1284. ``input_ids``: list of token ids to be fed to a model
  1285. ``token_type_ids``: list of token type ids to be fed to a model
  1286. ``overflowing_tokens``: list of overflowing tokens if a max length is specified.
  1287. ``num_truncated_tokens``: number of overflowing tokens a ``max_length`` is specified
  1288. ``special_tokens_mask``: if adding special tokens, this is a list of [0, 1], with 0 specifying special added
  1289. tokens and 1 specifying sequence tokens.
  1290. """
  1291. pair = bool(pair_ids is not None)
  1292. len_ids = len(ids)
  1293. len_pair_ids = len(pair_ids) if pair else 0
  1294. if return_token_type_ids is None:
  1295. return_token_type_ids = "token_type_ids" in self.model_input_names
  1296. if return_attention_mask is None:
  1297. return_attention_mask = "attention_mask" in self.model_input_names
  1298. encoded_inputs = {}
  1299. # Handle max sequence length
  1300. total_len = len_ids + len_pair_ids + (self.num_special_tokens_to_add(pair=pair) if add_special_tokens else 0)
  1301. if max_length and total_len > max_length:
  1302. ids, pair_ids, overflowing_tokens = self.truncate_sequences(
  1303. ids,
  1304. pair_ids=pair_ids,
  1305. num_tokens_to_remove=total_len - max_length,
  1306. truncation_strategy=truncation_strategy,
  1307. stride=stride,
  1308. )
  1309. if return_overflowing_tokens:
  1310. encoded_inputs["overflowing_tokens"] = overflowing_tokens
  1311. encoded_inputs["num_truncated_tokens"] = total_len - max_length
  1312. # Handle special_tokens
  1313. if add_special_tokens:
  1314. sequence = self.build_inputs_with_special_tokens(ids, pair_ids)
  1315. token_type_ids = self.create_token_type_ids_from_sequences(ids, pair_ids)
  1316. else:
  1317. sequence = ids + pair_ids if pair else ids
  1318. token_type_ids = [0] * len(ids) + ([1] * len(pair_ids) if pair else [])
  1319. if return_special_tokens_mask:
  1320. if add_special_tokens:
  1321. encoded_inputs["special_tokens_mask"] = self.get_special_tokens_mask(ids, pair_ids)
  1322. else:
  1323. encoded_inputs["special_tokens_mask"] = [0] * len(sequence)
  1324. encoded_inputs["input_ids"] = sequence
  1325. if return_token_type_ids:
  1326. encoded_inputs["token_type_ids"] = token_type_ids
  1327. if max_length and len(encoded_inputs["input_ids"]) > max_length:
  1328. encoded_inputs["input_ids"] = encoded_inputs["input_ids"][:max_length]
  1329. if return_token_type_ids:
  1330. encoded_inputs["token_type_ids"] = encoded_inputs["token_type_ids"][:max_length]
  1331. if return_special_tokens_mask:
  1332. encoded_inputs["special_tokens_mask"] = encoded_inputs["special_tokens_mask"][:max_length]
  1333. if max_length is None and len(encoded_inputs["input_ids"]) > self.max_len:
  1334. logger.warning(
  1335. "Token indices sequence length is longer than the specified maximum sequence length "
  1336. "for this model ({} > {}). Running this sequence through the model will result in "
  1337. "indexing errors".format(len(ids), self.max_len)
  1338. )
  1339. needs_to_be_padded = pad_to_max_length and (
  1340. max_length
  1341. and len(encoded_inputs["input_ids"]) < max_length
  1342. or max_length is None
  1343. and len(encoded_inputs["input_ids"]) < self.max_len
  1344. and self.max_len <= 10000
  1345. )
  1346. if pad_to_max_length and max_length is None and self.max_len > 10000:
  1347. logger.warning(
  1348. "Sequence can't be padded as no maximum length is specified and the model maximum length is too high."
  1349. )
  1350. if needs_to_be_padded:
  1351. difference = (max_length if max_length is not None else self.max_len) - len(encoded_inputs["input_ids"])
  1352. if self.padding_side == "right":
  1353. if return_attention_mask:
  1354. encoded_inputs["attention_mask"] = [1] * len(encoded_inputs["input_ids"]) + [0] * difference
  1355. if return_token_type_ids:
  1356. encoded_inputs["token_type_ids"] = (
  1357. encoded_inputs["token_type_ids"] + [self.pad_token_type_id] * difference
  1358. )
  1359. if return_special_tokens_mask:
  1360. encoded_inputs["special_tokens_mask"] = encoded_inputs["special_tokens_mask"] + [1] * difference
  1361. encoded_inputs["input_ids"] = encoded_inputs["input_ids"] + [self.pad_token_id] * difference
  1362. elif self.padding_side == "left":
  1363. if return_attention_mask:
  1364. encoded_inputs["attention_mask"] = [0] * difference + [1] * len(encoded_inputs["input_ids"])
  1365. if return_token_type_ids:
  1366. encoded_inputs["token_type_ids"] = [self.pad_token_type_id] * difference + encoded_inputs[
  1367. "token_type_ids"
  1368. ]
  1369. if return_special_tokens_mask:
  1370. encoded_inputs["special_tokens_mask"] = [1] * difference + encoded_inputs["special_tokens_mask"]
  1371. encoded_inputs["input_ids"] = [self.pad_token_id] * difference + encoded_inputs["input_ids"]
  1372. else:
  1373. raise ValueError("Invalid padding strategy:" + str(self.padding_side))
  1374. elif return_attention_mask:
  1375. encoded_inputs["attention_mask"] = [1] * len(encoded_inputs["input_ids"])
  1376. # Prepare inputs as tensors if asked
  1377. if return_tensors == "tf" and is_tf_available():
  1378. encoded_inputs["input_ids"] = tf.constant([encoded_inputs["input_ids"]])
  1379. if "token_type_ids" in encoded_inputs:
  1380. encoded_inputs["token_type_ids"] = tf.constant([encoded_inputs["token_type_ids"]])
  1381. if "attention_mask" in encoded_inputs:
  1382. encoded_inputs["attention_mask"] = tf.constant([encoded_inputs["attention_mask"]])
  1383. elif return_tensors == "pt" and is_torch_available():
  1384. encoded_inputs["input_ids"] = torch.tensor([encoded_inputs["input_ids"]])
  1385. if "token_type_ids" in encoded_inputs:
  1386. encoded_inputs["token_type_ids"] = torch.tensor([encoded_inputs["token_type_ids"]])
  1387. if "attention_mask" in encoded_inputs:
  1388. encoded_inputs["attention_mask"] = torch.tensor([encoded_inputs["attention_mask"]])
  1389. elif return_tensors is not None:
  1390. logger.warning(
  1391. "Unable to convert output to tensors format {}, PyTorch or TensorFlow is not available.".format(
  1392. return_tensors
  1393. )
  1394. )
  1395. return BatchEncoding(encoded_inputs)
  1396. def prepare_for_tokenization(self, text, **kwargs):
  1397. """ Performs any necessary transformations before tokenization """
  1398. return text
  1399. def truncate_sequences(
  1400. self, ids, pair_ids=None, num_tokens_to_remove=0, truncation_strategy="longest_first", stride=0
  1401. ):
  1402. """Truncates a sequence pair in place to the maximum length.
  1403. truncation_strategy: string selected in the following options:
  1404. - 'longest_first' (default) Iteratively reduce the inputs sequence until the input is under max_length
  1405. starting from the longest one at each token (when there is a pair of input sequences).
  1406. Overflowing tokens only contains overflow from the first sequence.
  1407. - 'only_first': Only truncate the first sequence. raise an error if the first sequence is shorter or equal to than num_tokens_to_remove.
  1408. - 'only_second': Only truncate the second sequence
  1409. - 'do_not_truncate': Does not truncate (raise an error if the input sequence is longer than max_length)
  1410. """
  1411. if num_tokens_to_remove <= 0:
  1412. return ids, pair_ids, []
  1413. if truncation_strategy == "longest_first":
  1414. overflowing_tokens = []
  1415. for _ in range(num_tokens_to_remove):
  1416. if pair_ids is None or len(ids) > len(pair_ids):
  1417. overflowing_tokens = [ids[-1]] + overflowing_tokens
  1418. ids = ids[:-1]
  1419. else:
  1420. pair_ids = pair_ids[:-1]
  1421. window_len = min(len(ids), stride)
  1422. if window_len > 0:
  1423. overflowing_tokens = ids[-window_len:] + overflowing_tokens
  1424. elif truncation_strategy == "only_first":
  1425. assert len(ids) > num_tokens_to_remove
  1426. window_len = min(len(ids), stride + num_tokens_to_remove)
  1427. overflowing_tokens = ids[-window_len:]
  1428. ids = ids[:-num_tokens_to_remove]
  1429. elif truncation_strategy == "only_second":
  1430. assert pair_ids is not None and len(pair_ids) > num_tokens_to_remove
  1431. window_len = min(len(pair_ids), stride + num_tokens_to_remove)
  1432. overflowing_tokens = pair_ids[-window_len:]
  1433. pair_ids = pair_ids[:-num_tokens_to_remove]
  1434. elif truncation_strategy == "do_not_truncate":
  1435. raise ValueError("Input sequence are too long for max_length. Please select a truncation strategy.")
  1436. else:
  1437. raise ValueError(
  1438. "Truncation_strategy should be selected in ['longest_first', 'only_first', 'only_second', 'do_not_truncate']"
  1439. )
  1440. return (ids, pair_ids, overflowing_tokens)
  1441. def create_token_type_ids_from_sequences(self, token_ids_0, token_ids_1=None):
  1442. if token_ids_1 is None:
  1443. return len(token_ids_0) * [0]
  1444. return [0] * len(token_ids_0) + [1] * len(token_ids_1)
  1445. def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None):
  1446. """
  1447. Build model inputs from a sequence or a pair of sequence for sequence classification tasks
  1448. by concatenating and adding special tokens.
  1449. A RoBERTa sequence has the following format:
  1450. single sequence: <s> X </s>
  1451. pair of sequences: <s> A </s></s> B </s>
  1452. """
  1453. if token_ids_1 is None:
  1454. return token_ids_0
  1455. return token_ids_0 + token_ids_1
  1456. def get_special_tokens_mask(self, token_ids_0, token_ids_1=None, already_has_special_tokens=False):
  1457. """
  1458. Retrieves sequence ids from a token list that has no special tokens added. This method is called when adding
  1459. special tokens using the tokenizer ``prepare_for_model`` or ``encode_plus`` methods.
  1460. Args:
  1461. token_ids_0: list of ids (must not contain special tokens)
  1462. token_ids_1: Optional list of ids (must not contain special tokens), necessary when fetching sequence ids
  1463. for sequence pairs
  1464. already_has_special_tokens: (default False) Set to True if the token list is already formated with
  1465. special tokens for the model
  1466. Returns:
  1467. A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
  1468. """
  1469. return [0] * ((len(token_ids_1) if token_ids_1 else 0) + len(token_ids_0))
  1470. def convert_ids_to_tokens(self, ids, skip_special_tokens=False):
  1471. """ Converts a single index or a sequence of indices (integers) in a token "
  1472. (resp.) a sequence of tokens (str), using the vocabulary and added tokens.
  1473. Args:
  1474. skip_special_tokens: Don't decode special tokens (self.all_special_tokens). Default: False
  1475. """
  1476. if isinstance(ids, int):
  1477. if ids in self.added_tokens_decoder:
  1478. return self.added_tokens_decoder[ids]
  1479. else:
  1480. return self._convert_id_to_token(ids)
  1481. tokens = []
  1482. for index in ids:
  1483. index = int(index)
  1484. if skip_special_tokens and index in self.all_special_ids:
  1485. continue
  1486. if index in self.added_tokens_decoder:
  1487. tokens.append(self.added_tokens_decoder[index])
  1488. else:
  1489. tokens.append(self._convert_id_to_token(index))
  1490. return tokens
  1491. def _convert_id_to_token(self, index):
  1492. raise NotImplementedError
  1493. def convert_tokens_to_string(self, tokens):
  1494. """ Converts a sequence of tokens (string) in a single string.
  1495. The most simple way to do it is ' '.join(self.convert_ids_to_tokens(token_ids))
  1496. but we often want to remove sub-word tokenization artifacts at the same time.
  1497. """
  1498. return " ".join(self.convert_ids_to_tokens(tokens))
  1499. def decode(self, token_ids, skip_special_tokens=False, clean_up_tokenization_spaces=True):
  1500. """
  1501. Converts a sequence of ids (integer) in a string, using the tokenizer and vocabulary
  1502. with options to remove special tokens and clean up tokenization spaces.
  1503. Similar to doing ``self.convert_tokens_to_string(self.convert_ids_to_tokens(token_ids))``.
  1504. Args:
  1505. token_ids: list of tokenized input ids. Can be obtained using the `encode` or `encode_plus` methods.
  1506. skip_special_tokens: if set to True, will replace special tokens.
  1507. clean_up_tokenization_spaces: if set to True, will clean up the tokenization spaces.
  1508. """
  1509. filtered_tokens = self.convert_ids_to_tokens(token_ids, skip_special_tokens=skip_special_tokens)
  1510. # To avoid mixing byte-level and unicode for byte-level BPT
  1511. # we need to build string separatly for added tokens and byte-level tokens
  1512. # cf. https://github.com/huggingface/transformers/issues/1133
  1513. sub_texts = []
  1514. current_sub_text = []
  1515. for token in filtered_tokens:
  1516. if skip_special_tokens and token in self.all_special_ids:
  1517. continue
  1518. if token in self.added_tokens_encoder:
  1519. if current_sub_text:
  1520. sub_texts.append(self.convert_tokens_to_string(current_sub_text))
  1521. current_sub_text = []
  1522. sub_texts.append(token)
  1523. else:
  1524. current_sub_text.append(token)
  1525. if current_sub_text:
  1526. sub_texts.append(self.convert_tokens_to_string(current_sub_text))
  1527. text = " ".join(sub_texts)
  1528. if clean_up_tokenization_spaces:
  1529. clean_text = self.clean_up_tokenization(text)
  1530. return clean_text
  1531. else:
  1532. return text
  1533. @staticmethod
  1534. def clean_up_tokenization(out_string):
  1535. """ Clean up a list of simple English tokenization artifacts like spaces before punctuations and abreviated forms.
  1536. """
  1537. out_string = (
  1538. out_string.replace(" .", ".")
  1539. .replace(" ?", "?")
  1540. .replace(" !", "!")
  1541. .replace(" ,", ",")
  1542. .replace(" ' ", "'")
  1543. .replace(" n't", "n't")
  1544. .replace(" 'm", "'m")
  1545. .replace(" do not", " don't")
  1546. .replace(" 's", "'s")
  1547. .replace(" 've", "'ve")
  1548. .replace(" 're", "'re")
  1549. )
  1550. return out_string
  1551. def trim_batch(
  1552. input_ids, pad_token_id, attention_mask=None,
  1553. ):
  1554. """Remove columns that are populated exclusively by pad_token_id"""
  1555. keep_column_mask = input_ids.ne(pad_token_id).any(dim=0)
  1556. if attention_mask is None:
  1557. return input_ids[:, keep_column_mask]
  1558. else:
  1559. return (input_ids[:, keep_column_mask], attention_mask[:, keep_column_mask])
  1560. def load_vocab(vocab_file):
  1561. """Loads a vocabulary file into a dictionary."""
  1562. vocab = collections.OrderedDict()
  1563. with open(vocab_file, "r", encoding="utf-8") as reader:
  1564. tokens = reader.readlines()
  1565. for index, token in enumerate(tokens):
  1566. token = token.rstrip("\n")
  1567. vocab[token] = index
  1568. return vocab
  1569. def whitespace_tokenize(text):
  1570. """Runs basic whitespace cleaning and splitting on a piece of text."""
  1571. text = text.strip()
  1572. if not text:
  1573. return []
  1574. tokens = text.split()
  1575. return tokens
  1576. VOCAB_FILES_NAMES = {"vocab_file": "vocab.txt"}
  1577. PRETRAINED_VOCAB_FILES_MAP = {
  1578. "vocab_file": {
  1579. "bert-base-uncased": "https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-uncased-vocab.txt",
  1580. "bert-large-uncased": "https://s3.amazonaws.com/models.huggingface.co/bert/bert-large-uncased-vocab.txt",
  1581. "bert-base-cased": "https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-cased-vocab.txt",
  1582. "bert-large-cased": "https://s3.amazonaws.com/models.huggingface.co/bert/bert-large-cased-vocab.txt",
  1583. "bert-base-multilingual-uncased": "https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-multilingual-uncased-vocab.txt",
  1584. "bert-base-multilingual-cased": "https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-multilingual-cased-vocab.txt",
  1585. "bert-base-chinese": "https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-chinese-vocab.txt",
  1586. "bert-base-german-cased": "https://int-deepset-models-bert.s3.eu-central-1.amazonaws.com/pytorch/bert-base-german-cased-vocab.txt",
  1587. "bert-large-uncased-whole-word-masking": "https://s3.amazonaws.com/models.huggingface.co/bert/bert-large-uncased-whole-word-masking-vocab.txt",
  1588. "bert-large-cased-whole-word-masking": "https://s3.amazonaws.com/models.huggingface.co/bert/bert-large-cased-whole-word-masking-vocab.txt",
  1589. "bert-large-uncased-whole-word-masking-finetuned-squad": "https://s3.amazonaws.com/models.huggingface.co/bert/bert-large-uncased-whole-word-masking-finetuned-squad-vocab.txt",
  1590. "bert-large-cased-whole-word-masking-finetuned-squad": "https://s3.amazonaws.com/models.huggingface.co/bert/bert-large-cased-whole-word-masking-finetuned-squad-vocab.txt",
  1591. "bert-base-cased-finetuned-mrpc": "https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-cased-finetuned-mrpc-vocab.txt",
  1592. "bert-base-german-dbmdz-cased": "https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-german-dbmdz-cased-vocab.txt",
  1593. "bert-base-german-dbmdz-uncased": "https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-german-dbmdz-uncased-vocab.txt",
  1594. "bert-base-finnish-cased-v1": "https://s3.amazonaws.com/models.huggingface.co/bert/TurkuNLP/bert-base-finnish-cased-v1/vocab.txt",
  1595. "bert-base-finnish-uncased-v1": "https://s3.amazonaws.com/models.huggingface.co/bert/TurkuNLP/bert-base-finnish-uncased-v1/vocab.txt",
  1596. "bert-base-dutch-cased": "https://s3.amazonaws.com/models.huggingface.co/bert/wietsedv/bert-base-dutch-cased/vocab.txt",
  1597. }
  1598. }
  1599. PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES = {
  1600. "bert-base-uncased": 512,
  1601. "bert-large-uncased": 512,
  1602. "bert-base-cased": 512,
  1603. "bert-large-cased": 512,
  1604. "bert-base-multilingual-uncased": 512,
  1605. "bert-base-multilingual-cased": 512,
  1606. "bert-base-chinese": 512,
  1607. "bert-base-german-cased": 512,
  1608. "bert-large-uncased-whole-word-masking": 512,
  1609. "bert-large-cased-whole-word-masking": 512,
  1610. "bert-large-uncased-whole-word-masking-finetuned-squad": 512,
  1611. "bert-large-cased-whole-word-masking-finetuned-squad": 512,
  1612. "bert-base-cased-finetuned-mrpc": 512,
  1613. "bert-base-german-dbmdz-cased": 512,
  1614. "bert-base-german-dbmdz-uncased": 512,
  1615. "bert-base-finnish-cased-v1": 512,
  1616. "bert-base-finnish-uncased-v1": 512,
  1617. "bert-base-dutch-cased": 512,
  1618. }
  1619. PRETRAINED_INIT_CONFIGURATION = {
  1620. "bert-base-uncased": {"do_lower_case": True},
  1621. "bert-large-uncased": {"do_lower_case": True},
  1622. "bert-base-cased": {"do_lower_case": False},
  1623. "bert-large-cased": {"do_lower_case": False},
  1624. "bert-base-multilingual-uncased": {"do_lower_case": True},
  1625. "bert-base-multilingual-cased": {"do_lower_case": False},
  1626. "bert-base-chinese": {"do_lower_case": False},
  1627. "bert-base-german-cased": {"do_lower_case": False},
  1628. "bert-large-uncased-whole-word-masking": {"do_lower_case": True},
  1629. "bert-large-cased-whole-word-masking": {"do_lower_case": False},
  1630. "bert-large-uncased-whole-word-masking-finetuned-squad": {"do_lower_case": True},
  1631. "bert-large-cased-whole-word-masking-finetuned-squad": {"do_lower_case": False},
  1632. "bert-base-cased-finetuned-mrpc": {"do_lower_case": False},
  1633. "bert-base-german-dbmdz-cased": {"do_lower_case": False},
  1634. "bert-base-german-dbmdz-uncased": {"do_lower_case": True},
  1635. "bert-base-finnish-cased-v1": {"do_lower_case": False},
  1636. "bert-base-finnish-uncased-v1": {"do_lower_case": True},
  1637. "bert-base-dutch-cased": {"do_lower_case": False},
  1638. }
  1639. # Bert Classes
  1640. class BertTokenizer(PreTrainedTokenizer):
  1641. r"""
  1642. Constructs a BERT tokenizer. Based on WordPiece.
  1643. This tokenizer inherits from :class:`~transformers.PreTrainedTokenizer` which contains most of the methods. Users
  1644. should refer to the superclass for more information regarding methods.
  1645. Args:
  1646. vocab_file (:obj:`string`):
  1647. File containing the vocabulary.
  1648. do_lower_case (:obj:`bool`, `optional`, defaults to :obj:`True`):
  1649. Whether to lowercase the input when tokenizing.
  1650. do_basic_tokenize (:obj:`bool`, `optional`, defaults to :obj:`True`):
  1651. Whether to do basic tokenization before WordPiece.
  1652. never_split (:obj:`bool`, `optional`, defaults to :obj:`True`):
  1653. List of tokens which will never be split during tokenization. Only has an effect when
  1654. :obj:`do_basic_tokenize=True`
  1655. unk_token (:obj:`string`, `optional`, defaults to "[UNK]"):
  1656. The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
  1657. token instead.
  1658. sep_token (:obj:`string`, `optional`, defaults to "[SEP]"):
  1659. The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences
  1660. for sequence classification or for a text and a question for question answering.
  1661. It is also used as the last token of a sequence built with special tokens.
  1662. pad_token (:obj:`string`, `optional`, defaults to "[PAD]"):
  1663. The token used for padding, for example when batching sequences of different lengths.
  1664. cls_token (:obj:`string`, `optional`, defaults to "[CLS]"):
  1665. The classifier token which is used when doing sequence classification (classification of the whole
  1666. sequence instead of per-token classification). It is the first token of the sequence when built with
  1667. special tokens.
  1668. mask_token (:obj:`string`, `optional`, defaults to "[MASK]"):
  1669. The token used for masking values. This is the token used when training this model with masked language
  1670. modeling. This is the token which the model will try to predict.
  1671. tokenize_chinese_chars (:obj:`bool`, `optional`, defaults to :obj:`True`):
  1672. Whether to tokenize Chinese characters.
  1673. This should likely be deactivated for Japanese:
  1674. see: https://github.com/huggingface/transformers/issues/328
  1675. """
  1676. vocab_files_names = VOCAB_FILES_NAMES
  1677. pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP
  1678. pretrained_init_configuration = PRETRAINED_INIT_CONFIGURATION
  1679. max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
  1680. def __init__(
  1681. self,
  1682. vocab_file,
  1683. do_lower_case=True,
  1684. do_basic_tokenize=True,
  1685. never_split=None,
  1686. unk_token="[UNK]",
  1687. sep_token="[SEP]",
  1688. pad_token="[PAD]",
  1689. cls_token="[CLS]",
  1690. mask_token="[MASK]",
  1691. tokenize_chinese_chars=True,
  1692. **kwargs
  1693. ):
  1694. super().__init__(
  1695. unk_token=unk_token,
  1696. sep_token=sep_token,
  1697. pad_token=pad_token,
  1698. cls_token=cls_token,
  1699. mask_token=mask_token,
  1700. **kwargs,
  1701. )
  1702. self.max_len_single_sentence = self.max_len - 2 # take into account special tokens
  1703. self.max_len_sentences_pair = self.max_len - 3 # take into account special tokens
  1704. if not os.path.isfile(vocab_file):
  1705. raise ValueError(
  1706. "Can't find a vocabulary file at path '{}'. To load the vocabulary from a Google pretrained "
  1707. "model use `tokenizer = BertTokenizer.from_pretrained(PRETRAINED_MODEL_NAME)`".format(vocab_file)
  1708. )
  1709. self.vocab = load_vocab(vocab_file)
  1710. self.ids_to_tokens = collections.OrderedDict([(ids, tok) for tok, ids in self.vocab.items()])
  1711. self.do_basic_tokenize = do_basic_tokenize
  1712. if do_basic_tokenize:
  1713. self.basic_tokenizer = BasicTokenizer(
  1714. do_lower_case=do_lower_case, never_split=never_split, tokenize_chinese_chars=tokenize_chinese_chars
  1715. )
  1716. self.wordpiece_tokenizer = WordpieceTokenizer(vocab=self.vocab, unk_token=self.unk_token)
  1717. @property
  1718. def vocab_size(self):
  1719. return len(self.vocab)
  1720. def get_vocab(self):
  1721. return dict(self.vocab, **self.added_tokens_encoder)
  1722. def _tokenize(self, text):
  1723. split_tokens = []
  1724. if self.do_basic_tokenize:
  1725. for token in self.basic_tokenizer.tokenize(text, never_split=self.all_special_tokens):
  1726. for sub_token in self.wordpiece_tokenizer.tokenize(token):
  1727. split_tokens.append(sub_token)
  1728. else:
  1729. split_tokens = self.wordpiece_tokenizer.tokenize(text)
  1730. return split_tokens
  1731. def _convert_token_to_id(self, token):
  1732. """ Converts a token (str) in an id using the vocab. """
  1733. return self.vocab.get(token, self.vocab.get(self.unk_token))
  1734. def _convert_id_to_token(self, index):
  1735. """Converts an index (integer) in a token (str) using the vocab."""
  1736. return self.ids_to_tokens.get(index, self.unk_token)
  1737. def convert_tokens_to_string(self, tokens):
  1738. """ Converts a sequence of tokens (string) in a single string. """
  1739. out_string = " ".join(tokens).replace(" ##", "").strip()
  1740. return out_string
  1741. def build_inputs_with_special_tokens(
  1742. self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
  1743. ) -> List[int]:
  1744. """
  1745. Build model inputs from a sequence or a pair of sequence for sequence classification tasks
  1746. by concatenating and adding special tokens.
  1747. A BERT sequence has the following format:
  1748. - single sequence: ``[CLS] X [SEP]``
  1749. - pair of sequences: ``[CLS] A [SEP] B [SEP]``
  1750. Args:
  1751. token_ids_0 (:obj:`List[int]`):
  1752. List of IDs to which the special tokens will be added
  1753. token_ids_1 (:obj:`List[int]`, `optional`, defaults to :obj:`None`):
  1754. Optional second list of IDs for sequence pairs.
  1755. Returns:
  1756. :obj:`List[int]`: list of `input IDs <../glossary.html#input-ids>`__ with the appropriate special tokens.
  1757. """
  1758. if token_ids_1 is None:
  1759. return [self.cls_token_id] + token_ids_0 + [self.sep_token_id]
  1760. cls = [self.cls_token_id]
  1761. sep = [self.sep_token_id]
  1762. return cls + token_ids_0 + sep + token_ids_1 + sep
  1763. def get_special_tokens_mask(
  1764. self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None, already_has_special_tokens: bool = False
  1765. ) -> List[int]:
  1766. """
  1767. Retrieves sequence ids from a token list that has no special tokens added. This method is called when adding
  1768. special tokens using the tokenizer ``prepare_for_model`` or ``encode_plus`` methods.
  1769. Args:
  1770. token_ids_0 (:obj:`List[int]`):
  1771. List of ids.
  1772. token_ids_1 (:obj:`List[int]`, `optional`, defaults to :obj:`None`):
  1773. Optional second list of IDs for sequence pairs.
  1774. already_has_special_tokens (:obj:`bool`, `optional`, defaults to :obj:`False`):
  1775. Set to True if the token list is already formatted with special tokens for the model
  1776. Returns:
  1777. :obj:`List[int]`: A list of integers in the range [0, 1]: 0 for a special token, 1 for a sequence token.
  1778. """
  1779. if already_has_special_tokens:
  1780. if token_ids_1 is not None:
  1781. raise ValueError(
  1782. "You should not supply a second sequence if the provided sequence of "
  1783. "ids is already formated with special tokens for the model."
  1784. )
  1785. return list(map(lambda x: 1 if x in [self.sep_token_id, self.cls_token_id] else 0, token_ids_0))
  1786. if token_ids_1 is not None:
  1787. return [1] + ([0] * len(token_ids_0)) + [1] + ([0] * len(token_ids_1)) + [1]
  1788. return [1] + ([0] * len(token_ids_0)) + [1]
  1789. def create_token_type_ids_from_sequences(
  1790. self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
  1791. ) -> List[int]:
  1792. """
  1793. Creates a mask from the two sequences passed to be used in a sequence-pair classification task.
  1794. A BERT sequence pair mask has the following format:
  1795. ::
  1796. 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1
  1797. | first sequence | second sequence |
  1798. if token_ids_1 is None, only returns the first portion of the mask (0's).
  1799. Args:
  1800. token_ids_0 (:obj:`List[int]`):
  1801. List of ids.
  1802. token_ids_1 (:obj:`List[int]`, `optional`, defaults to :obj:`None`):
  1803. Optional second list of IDs for sequence pairs.
  1804. Returns:
  1805. :obj:`List[int]`: List of `token type IDs <../glossary.html#token-type-ids>`_ according to the given
  1806. sequence(s).
  1807. """
  1808. sep = [self.sep_token_id]
  1809. cls = [self.cls_token_id]
  1810. if token_ids_1 is None:
  1811. return len(cls + token_ids_0 + sep) * [0]
  1812. return len(cls + token_ids_0 + sep) * [0] + len(token_ids_1 + sep) * [1]
  1813. def save_vocabulary(self, vocab_path):
  1814. """
  1815. Save the sentencepiece vocabulary (copy original file) and special tokens file to a directory.
  1816. Args:
  1817. vocab_path (:obj:`str`):
  1818. The directory in which to save the vocabulary.
  1819. Returns:
  1820. :obj:`Tuple(str)`: Paths to the files saved.
  1821. """
  1822. index = 0
  1823. if os.path.isdir(vocab_path):
  1824. vocab_file = os.path.join(vocab_path, VOCAB_FILES_NAMES["vocab_file"])
  1825. else:
  1826. vocab_file = vocab_path
  1827. with open(vocab_file, "w", encoding="utf-8") as writer:
  1828. for token, token_index in sorted(self.vocab.items(), key=lambda kv: kv[1]):
  1829. if index != token_index:
  1830. logger.warning(
  1831. "Saving vocabulary to {}: vocabulary indices are not consecutive."
  1832. " Please check that the vocabulary is not corrupted!".format(vocab_file)
  1833. )
  1834. index = token_index
  1835. writer.write(token + "\n")
  1836. index += 1
  1837. return (vocab_file,)
  1838. class BasicTokenizer(object):
  1839. """Runs basic tokenization (punctuation splitting, lower casing, etc.)."""
  1840. def __init__(self, do_lower_case=True, never_split=None, tokenize_chinese_chars=True):
  1841. """ Constructs a BasicTokenizer.
  1842. Args:
  1843. **do_lower_case**: Whether to lower case the input.
  1844. **never_split**: (`optional`) list of str
  1845. Kept for backward compatibility purposes.
  1846. Now implemented directly at the base class level (see :func:`PreTrainedTokenizer.tokenize`)
  1847. List of token not to split.
  1848. **tokenize_chinese_chars**: (`optional`) boolean (default True)
  1849. Whether to tokenize Chinese characters.
  1850. This should likely be deactivated for Japanese:
  1851. see: https://github.com/huggingface/pytorch-pretrained-BERT/issues/328
  1852. """
  1853. if never_split is None:
  1854. never_split = []
  1855. self.do_lower_case = do_lower_case
  1856. self.never_split = never_split
  1857. self.tokenize_chinese_chars = tokenize_chinese_chars
  1858. def tokenize(self, text, never_split=None):
  1859. """ Basic Tokenization of a piece of text.
  1860. Split on "white spaces" only, for sub-word tokenization, see WordPieceTokenizer.
  1861. Args:
  1862. **never_split**: (`optional`) list of str
  1863. Kept for backward compatibility purposes.
  1864. Now implemented directly at the base class level (see :func:`PreTrainedTokenizer.tokenize`)
  1865. List of token not to split.
  1866. """
  1867. never_split = self.never_split + (never_split if never_split is not None else [])
  1868. text = self._clean_text(text)
  1869. # This was added on November 1st, 2018 for the multilingual and Chinese
  1870. # models. This is also applied to the English models now, but it doesn't
  1871. # matter since the English models were not trained on any Chinese data
  1872. # and generally don't have any Chinese data in them (there are Chinese
  1873. # characters in the vocabulary because Wikipedia does have some Chinese
  1874. # words in the English Wikipedia.).
  1875. if self.tokenize_chinese_chars:
  1876. text = self._tokenize_chinese_chars(text)
  1877. orig_tokens = whitespace_tokenize(text)
  1878. split_tokens = []
  1879. for token in orig_tokens:
  1880. if self.do_lower_case and token not in never_split:
  1881. token = token.lower()
  1882. token = self._run_strip_accents(token)
  1883. split_tokens.extend(self._run_split_on_punc(token, never_split))
  1884. output_tokens = whitespace_tokenize(" ".join(split_tokens))
  1885. return output_tokens
  1886. def _run_strip_accents(self, text):
  1887. """Strips accents from a piece of text."""
  1888. text = unicodedata.normalize("NFD", text)
  1889. output = []
  1890. for char in text:
  1891. cat = unicodedata.category(char)
  1892. if cat == "Mn":
  1893. continue
  1894. output.append(char)
  1895. return "".join(output)
  1896. def _run_split_on_punc(self, text, never_split=None):
  1897. """Splits punctuation on a piece of text."""
  1898. if never_split is not None and text in never_split:
  1899. return [text]
  1900. chars = list(text)
  1901. i = 0
  1902. start_new_word = True
  1903. output = []
  1904. while i < len(chars):
  1905. char = chars[i]
  1906. if _is_punctuation(char):
  1907. output.append([char])
  1908. start_new_word = True
  1909. else:
  1910. if start_new_word:
  1911. output.append([])
  1912. start_new_word = False
  1913. output[-1].append(char)
  1914. i += 1
  1915. return ["".join(x) for x in output]
  1916. def _tokenize_chinese_chars(self, text):
  1917. """Adds whitespace around any CJK character."""
  1918. output = []
  1919. for char in text:
  1920. cp = ord(char)
  1921. if self._is_chinese_char(cp):
  1922. output.append(" ")
  1923. output.append(char)
  1924. output.append(" ")
  1925. else:
  1926. output.append(char)
  1927. return "".join(output)
  1928. def _is_chinese_char(self, cp):
  1929. """Checks whether CP is the codepoint of a CJK character."""
  1930. # This defines a "chinese character" as anything in the CJK Unicode block:
  1931. # https://en.wikipedia.org/wiki/CJK_Unified_Ideographs_(Unicode_block)
  1932. #
  1933. # Note that the CJK Unicode block is NOT all Japanese and Korean characters,
  1934. # despite its name. The modern Korean Hangul alphabet is a different block,
  1935. # as is Japanese Hiragana and Katakana. Those alphabets are used to write
  1936. # space-separated words, so they are not treated specially and handled
  1937. # like the all of the other languages.
  1938. if (
  1939. (cp >= 0x4E00 and cp <= 0x9FFF)
  1940. or (cp >= 0x3400 and cp <= 0x4DBF) #
  1941. or (cp >= 0x20000 and cp <= 0x2A6DF) #
  1942. or (cp >= 0x2A700 and cp <= 0x2B73F) #
  1943. or (cp >= 0x2B740 and cp <= 0x2B81F) #
  1944. or (cp >= 0x2B820 and cp <= 0x2CEAF) #
  1945. or (cp >= 0xF900 and cp <= 0xFAFF)
  1946. or (cp >= 0x2F800 and cp <= 0x2FA1F) #
  1947. ): #
  1948. return True
  1949. return False
  1950. def _clean_text(self, text):
  1951. """Performs invalid character removal and whitespace cleanup on text."""
  1952. output = []
  1953. for char in text:
  1954. cp = ord(char)
  1955. if cp == 0 or cp == 0xFFFD or _is_control(char):
  1956. continue
  1957. if _is_whitespace(char):
  1958. output.append(" ")
  1959. else:
  1960. output.append(char)
  1961. return "".join(output)
  1962. class WordpieceTokenizer(object):
  1963. """Runs WordPiece tokenization."""
  1964. def __init__(self, vocab, unk_token, max_input_chars_per_word=100):
  1965. self.vocab = vocab
  1966. self.unk_token = unk_token
  1967. self.max_input_chars_per_word = max_input_chars_per_word
  1968. def tokenize(self, text):
  1969. """Tokenizes a piece of text into its word pieces.
  1970. This uses a greedy longest-match-first algorithm to perform tokenization
  1971. using the given vocabulary.
  1972. For example:
  1973. input = "unaffable"
  1974. output = ["un", "##aff", "##able"]
  1975. Args:
  1976. text: A single token or whitespace separated tokens. This should have
  1977. already been passed through `BasicTokenizer`.
  1978. Returns:
  1979. A list of wordpiece tokens.
  1980. """
  1981. output_tokens = []
  1982. for token in whitespace_tokenize(text):
  1983. chars = list(token)
  1984. if len(chars) > self.max_input_chars_per_word:
  1985. output_tokens.append(self.unk_token)
  1986. continue
  1987. is_bad = False
  1988. start = 0
  1989. sub_tokens = []
  1990. while start < len(chars):
  1991. end = len(chars)
  1992. cur_substr = None
  1993. while start < end:
  1994. substr = "".join(chars[start:end])
  1995. if start > 0:
  1996. substr = "##" + substr
  1997. if substr in self.vocab:
  1998. cur_substr = substr
  1999. break
  2000. end -= 1
  2001. if cur_substr is None:
  2002. is_bad = True
  2003. break
  2004. sub_tokens.append(cur_substr)
  2005. start = end
  2006. if is_bad:
  2007. output_tokens.append(self.unk_token)
  2008. else:
  2009. output_tokens.extend(sub_tokens)
  2010. return output_tokens
  2011. def _is_whitespace(char):
  2012. """Checks whether `chars` is a whitespace character."""
  2013. # \t, \n, and \r are technically contorl characters but we treat them
  2014. # as whitespace since they are generally considered as such.
  2015. if char == " " or char == "\t" or char == "\n" or char == "\r":
  2016. return True
  2017. cat = unicodedata.category(char)
  2018. if cat == "Zs":
  2019. return True
  2020. return False
  2021. def _is_control(char):
  2022. """Checks whether `chars` is a control character."""
  2023. # These are technically control characters but we count them as whitespace
  2024. # characters.
  2025. if char == "\t" or char == "\n" or char == "\r":
  2026. return False
  2027. cat = unicodedata.category(char)
  2028. if cat.startswith("C"):
  2029. return True
  2030. return False
  2031. def _is_punctuation(char):
  2032. """Checks whether `chars` is a punctuation character."""
  2033. cp = ord(char)
  2034. # We treat all non-letter/number ASCII as punctuation.
  2035. # Characters such as "^", "$", and "`" are not in the Unicode
  2036. # Punctuation class but we treat them as punctuation anyways, for
  2037. # consistency.
  2038. if (cp >= 33 and cp <= 47) or (cp >= 58 and cp <= 64) or (cp >= 91 and cp <= 96) or (cp >= 123 and cp <= 126):
  2039. return True
  2040. cat = unicodedata.category(char)
  2041. if cat.startswith("P"):
  2042. return True
  2043. return False