tokenizer_utils_base.py 151 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505
  1. # Copyright (c) 2024 PaddlePaddle Authors. All Rights Reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import copy
  15. import io
  16. import json
  17. import os
  18. import warnings
  19. from collections import OrderedDict, UserDict
  20. from dataclasses import dataclass, field
  21. from enum import Enum
  22. from typing import Any, Dict, List, NamedTuple, Optional, Sequence, Tuple, Union
  23. import numpy as np
  24. from .....utils import logging
  25. __all__ = [
  26. "AddedToken",
  27. "FastEncoding",
  28. "ExplicitEnum",
  29. "PaddingStrategy",
  30. "TensorType",
  31. "TruncationStrategy",
  32. "CharSpan",
  33. "TokenSpan",
  34. "BatchEncoding",
  35. "SpecialTokensMixin",
  36. "PretrainedTokenizerBase",
  37. ]
  38. TOKENIZER_CONFIG_NAME = "tokenizer_config.json"
  39. CHAT_TEMPLATE_CONFIG_NAME = "chat_template.json"
  40. CHAT_TEMPLATE_CONFIG_NAME = "chat_template.json"
  41. VERY_LARGE_INTEGER = int(
  42. 1e30
  43. ) # This is used to set the max input length for a model with infinite size input
  44. LARGE_INTEGER = int(
  45. 1e20
  46. ) # This is used when we need something big but slightly smaller than VERY_LARGE_INTEGER
  47. # Define type aliases and NamedTuples
  48. TextInput = str
  49. PreTokenizedInput = List[str]
  50. EncodedInput = List[int]
  51. TextInputPair = Tuple[str, str]
  52. PreTokenizedInputPair = Tuple[List[str], List[str]]
  53. EncodedInputPair = Tuple[List[int], List[int]]
  54. # Slow tokenizers used to be saved in three separated files
  55. SPECIAL_TOKENS_MAP_FILE = "special_tokens_map.json"
  56. ADDED_TOKENS_FILE = "added_tokens.json"
  57. TOKENIZER_CONFIG_FILE = "tokenizer_config.json"
  58. @dataclass(frozen=True, eq=True)
  59. class AddedToken:
  60. """
  61. AddedToken represents a token to be added to a Tokenizer An AddedToken can have special options defining the
  62. way it should behave.
  63. """
  64. content: str = field(default_factory=str)
  65. single_word: bool = False
  66. lstrip: bool = False
  67. rstrip: bool = False
  68. normalized: bool = True
  69. special: bool = True
  70. def __getstate__(self):
  71. return self.__dict__
  72. def __str__(self):
  73. return self.content
  74. @dataclass
  75. class FastEncoding:
  76. """This is dummy class reserved for fast tokenizer"""
  77. class ExplicitEnum(Enum):
  78. """
  79. Enum with more explicit error message for missing values.
  80. """
  81. @classmethod
  82. def _missing_(cls, value):
  83. raise ValueError(
  84. f"{value} is not a valid {cls.__name__}, please select one of {list(cls._value2member_map_.keys())}"
  85. )
  86. class PaddingStrategy(ExplicitEnum):
  87. """
  88. Possible values for the `padding` argument in [`PretrainedTokenizerBase.__call__`]. Useful for tab-completion in an
  89. IDE.
  90. """
  91. LONGEST = "longest"
  92. MAX_LENGTH = "max_length"
  93. DO_NOT_PAD = "do_not_pad"
  94. class TensorType(ExplicitEnum):
  95. """
  96. Possible values for the `return_tensors` argument in [`PretrainedTokenizerBase.__call__`]. Useful for
  97. tab-completion in an IDE.
  98. """
  99. PADDLE = "pd"
  100. NUMPY = "np"
  101. def to_py_obj(obj):
  102. """
  103. Convert a Paddle tensor, Numpy array or python list to a python list.
  104. """
  105. import paddle
  106. if isinstance(obj, (dict, UserDict)):
  107. return {k: to_py_obj(v) for k, v in obj.items()}
  108. elif isinstance(obj, (list, tuple)):
  109. return [to_py_obj(o) for o in obj]
  110. elif isinstance(obj, paddle.Tensor):
  111. return obj.numpy().tolist()
  112. elif isinstance(obj, (np.ndarray, np.number)): # tolist also works on 0d np arrays
  113. return obj.tolist()
  114. else:
  115. return obj
  116. def _is_numpy(x):
  117. return isinstance(x, np.ndarray)
  118. class TruncationStrategy(ExplicitEnum):
  119. """
  120. Possible values for the `truncation` argument in [`PretrainedTokenizerBase.__call__`]. Useful for tab-completion in
  121. an IDE.
  122. """
  123. ONLY_FIRST = "only_first"
  124. ONLY_SECOND = "only_second"
  125. LONGEST_FIRST = "longest_first"
  126. DO_NOT_TRUNCATE = "do_not_truncate"
  127. class CharSpan(NamedTuple):
  128. """
  129. Character span in the original string.
  130. Args:
  131. start (`int`): Index of the first character in the original string.
  132. end (`int`): Index of the character following the last character in the original string.
  133. """
  134. start: int
  135. end: int
  136. class TokenSpan(NamedTuple):
  137. """
  138. Token span in an encoded string (list of tokens).
  139. Args:
  140. start (`int`): Index of the first token in the span.
  141. end (`int`): Index of the token following the last token in the span.
  142. """
  143. start: int
  144. end: int
  145. class BatchEncoding(UserDict):
  146. """
  147. Holds the output of the [`PretrainedTokenizerBase.__call__`],
  148. [`PretrainedTokenizerBase.encode_plus`] and
  149. [`PretrainedTokenizerBase.batch_encode_plus`] methods (tokens, attention_masks, etc).
  150. This class is derived from a python dictionary and can be used as a dictionary. In addition, this class exposes
  151. utility methods to map from word/character space to token space.
  152. Args:
  153. data (`dict`):
  154. Dictionary of lists/arrays/tensors returned by the `__call__`/`encode`/`batch_encode` methods
  155. ('input_ids', 'attention_mask', etc.).
  156. tensor_type (`Union[None, str, TensorType]`, *optional*):
  157. You can give a tensor_type here to convert the lists of integers in Paddle/Numpy Tensors at
  158. initialization.
  159. prepend_batch_axis (`bool`, *optional*, defaults to `False`):
  160. Whether or not to add a batch axis when converting to tensors (see `tensor_type` above).
  161. """
  162. def __init__(
  163. self,
  164. data: Optional[Dict[str, Any]] = None,
  165. encoding: Optional[Union[FastEncoding, Sequence[FastEncoding]]] = None,
  166. tensor_type: Union[None, str] = None,
  167. prepend_batch_axis: bool = False,
  168. n_sequences: Optional[int] = None,
  169. ):
  170. super().__init__(data)
  171. if isinstance(encoding, FastEncoding):
  172. encoding = [encoding]
  173. self._encodings = encoding
  174. if n_sequences is None and encoding is not None and len(encoding):
  175. n_sequences = encoding[0].n_sequences
  176. self._n_sequences = n_sequences
  177. self.convert_to_tensors(
  178. tensor_type=tensor_type, prepend_batch_axis=prepend_batch_axis
  179. )
  180. @property
  181. def n_sequences(self) -> Optional[int]:
  182. """
  183. `Optional[int]`: The number of sequences used to generate each sample from the batch encoded in this
  184. [`BatchEncoding`]. Currently can be one of `None` (unknown), `1` (a single sentence) or `2` (a pair of
  185. sentences)
  186. """
  187. return self._n_sequences
  188. @property
  189. def is_fast(self) -> bool:
  190. """
  191. `bool`: Indicate whether this [`BatchEncoding`] was generated from the result of a [`PretrainedFastTokenizer`]
  192. or not.
  193. """
  194. return self._encodings is not None
  195. def __getitem__(self, item: Union[int, str]) -> Union[Any, FastEncoding]:
  196. """
  197. If the key is a string, returns the value of the dict associated to `key` ('input_ids', 'attention_mask',
  198. etc.).
  199. If the key is an integer, get the `Encoding` for batch item with index `key`.
  200. """
  201. if isinstance(item, str):
  202. return self.data[item]
  203. elif self._encodings is not None:
  204. return self._encodings[item]
  205. else:
  206. raise KeyError(
  207. "Indexing with integers is not available when using tokenizer.__call__()"
  208. " with return_dict=True. Please set return_dict to False to use integer indexing."
  209. )
  210. def __getattr__(self, item: str):
  211. try:
  212. return self.data[item]
  213. except KeyError:
  214. raise AttributeError
  215. def __getstate__(self):
  216. return {"data": self.data, "encodings": self._encodings}
  217. def __setstate__(self, state):
  218. if "data" in state:
  219. self.data = state["data"]
  220. if "encodings" in state:
  221. self._encodings = state["encodings"]
  222. def keys(self):
  223. return self.data.keys()
  224. def values(self):
  225. return self.data.values()
  226. def items(self):
  227. return self.data.items()
  228. # After this point:
  229. # Extended properties and methods only available for fast tokenizers
  230. # not yet supported
  231. @property
  232. def encodings(self) -> Optional[List[FastEncoding]]:
  233. """
  234. `Optional[List[FastEncoding]]`: The list all encodings from the tokenization process. Returns `None` if
  235. the input was tokenized through Python (i.e., not a fast) tokenizer.
  236. """
  237. return self._encodings
  238. def tokens(self, batch_index: int = 0) -> List[str]:
  239. """
  240. Return the list of tokens (sub-parts of the input strings after word/subword splitting and before conversion to
  241. integer indices) at a given batch index (only works for the output of a fast tokenizer).
  242. Args:
  243. batch_index (`int`, *optional*, defaults to 0): The index to access in the batch.
  244. Returns:
  245. `List[str]`: The list of tokens at that index.
  246. """
  247. if not self._encodings:
  248. raise ValueError(
  249. "tokens() is not available when using Python-based tokenizers"
  250. )
  251. return self._encodings[batch_index].tokens
  252. def sequence_ids(self, batch_index: int = 0) -> List[Optional[int]]:
  253. """
  254. Return a list mapping the tokens to the id of their original sentences:
  255. - `None` for special tokens added around or between sequences,
  256. - `0` for tokens corresponding to words in the first sequence,
  257. - `1` for tokens corresponding to words in the second sequence when a pair of sequences was jointly
  258. encoded.
  259. Args:
  260. batch_index (`int`, *optional*, defaults to 0): The index to access in the batch.
  261. Returns:
  262. `List[Optional[int]]`: A list indicating the sequence id corresponding to each token. Special tokens added
  263. by the tokenizer are mapped to `None` and other tokens are mapped to the index of their corresponding
  264. sequence.
  265. """
  266. if not self._encodings:
  267. raise ValueError(
  268. "sequence_ids() is not available when using Python-based tokenizers"
  269. )
  270. return self._encodings[batch_index].sequence_ids
  271. def words(self, batch_index: int = 0) -> List[Optional[int]]:
  272. """
  273. Return a list mapping the tokens to their actual word in the initial sentence for a fast tokenizer.
  274. Args:
  275. batch_index (`int`, *optional*, defaults to 0): The index to access in the batch.
  276. Returns:
  277. `List[Optional[int]]`: A list indicating the word corresponding to each token. Special tokens added by the
  278. tokenizer are mapped to `None` and other tokens are mapped to the index of their corresponding word
  279. (several tokens will be mapped to the same word index if they are parts of that word).
  280. """
  281. if not self._encodings:
  282. raise ValueError(
  283. "words() is not available when using Python-based tokenizers"
  284. )
  285. warnings.warn(
  286. "`BatchEncoding.words()` property is deprecated and should be replaced with the identical, "
  287. "but more self-explanatory `BatchEncoding.word_ids()` property.",
  288. FutureWarning,
  289. )
  290. return self.word_ids(batch_index)
  291. def word_ids(self, batch_index: int = 0) -> List[Optional[int]]:
  292. """
  293. Return a list mapping the tokens to their actual word in the initial sentence for a fast tokenizer.
  294. Args:
  295. batch_index (`int`, *optional*, defaults to 0): The index to access in the batch.
  296. Returns:
  297. `List[Optional[int]]`: A list indicating the word corresponding to each token. Special tokens added by the
  298. tokenizer are mapped to `None` and other tokens are mapped to the index of their corresponding word
  299. (several tokens will be mapped to the same word index if they are parts of that word).
  300. """
  301. if not self._encodings:
  302. raise ValueError(
  303. "word_ids() is not available when using Python-based tokenizers"
  304. )
  305. return self._encodings[batch_index].word_ids
  306. def token_to_sequence(
  307. self, batch_or_token_index: int, token_index: Optional[int] = None
  308. ) -> int:
  309. """
  310. Get the index of the sequence represented by the given token. In the general use case, this method returns `0`
  311. for a single sequence or the first sequence of a pair, and `1` for the second sequence of a pair
  312. Can be called as:
  313. - `self.token_to_sequence(token_index)` if batch size is 1
  314. - `self.token_to_sequence(batch_index, token_index)` if batch size is greater than 1
  315. This method is particularly suited when the input sequences are provided as pre-tokenized sequences (i.e.,
  316. words are defined by the user). In this case it allows to easily associate encoded tokens with provided
  317. tokenized words.
  318. Args:
  319. batch_or_token_index (`int`):
  320. Index of the sequence in the batch. If the batch only comprises one sequence, this can be the index of
  321. the token in the sequence.
  322. token_index (`int`, *optional*):
  323. If a batch index is provided in *batch_or_token_index*, this can be the index of the token in the
  324. sequence.
  325. Returns:
  326. `int`: Index of the word in the input sequence.
  327. """
  328. if not self._encodings:
  329. raise ValueError(
  330. "token_to_sequence() is not available when using Python based tokenizers"
  331. )
  332. if token_index is not None:
  333. batch_index = batch_or_token_index
  334. else:
  335. batch_index = 0
  336. token_index = batch_or_token_index
  337. if batch_index < 0:
  338. batch_index = self._batch_size + batch_index
  339. if token_index < 0:
  340. token_index = self._seq_len + token_index
  341. return self._encodings[batch_index].token_to_sequence(token_index)
  342. def token_to_word(
  343. self, batch_or_token_index: int, token_index: Optional[int] = None
  344. ) -> int:
  345. """
  346. Get the index of the word corresponding (i.e. comprising) to an encoded token in a sequence of the batch.
  347. Can be called as:
  348. - `self.token_to_word(token_index)` if batch size is 1
  349. - `self.token_to_word(batch_index, token_index)` if batch size is greater than 1
  350. This method is particularly suited when the input sequences are provided as pre-tokenized sequences (i.e.,
  351. words are defined by the user). In this case it allows to easily associate encoded tokens with provided
  352. tokenized words.
  353. Args:
  354. batch_or_token_index (`int`):
  355. Index of the sequence in the batch. If the batch only comprise one sequence, this can be the index of
  356. the token in the sequence.
  357. token_index (`int`, *optional*):
  358. If a batch index is provided in *batch_or_token_index*, this can be the index of the token in the
  359. sequence.
  360. Returns:
  361. `int`: Index of the word in the input sequence.
  362. """
  363. if not self._encodings:
  364. raise ValueError(
  365. "token_to_word() is not available when using Python based tokenizers"
  366. )
  367. if token_index is not None:
  368. batch_index = batch_or_token_index
  369. else:
  370. batch_index = 0
  371. token_index = batch_or_token_index
  372. if batch_index < 0:
  373. batch_index = self._batch_size + batch_index
  374. if token_index < 0:
  375. token_index = self._seq_len + token_index
  376. return self._encodings[batch_index].token_to_word(token_index)
  377. def word_to_tokens(
  378. self,
  379. batch_or_word_index: int,
  380. word_index: Optional[int] = None,
  381. sequence_index: int = 0,
  382. ) -> Optional[TokenSpan]:
  383. """
  384. Get the encoded token span corresponding to a word in a sequence of the batch.
  385. Token spans are returned as a [`TokenSpan`] with:
  386. - **start** -- Index of the first token.
  387. - **end** -- Index of the token following the last token.
  388. Can be called as:
  389. - `self.word_to_tokens(word_index, sequence_index: int = 0)` if batch size is 1
  390. - `self.word_to_tokens(batch_index, word_index, sequence_index: int = 0)` if batch size is greater or equal to
  391. 1
  392. This method is particularly suited when the input sequences are provided as pre-tokenized sequences (i.e. words
  393. are defined by the user). In this case it allows to easily associate encoded tokens with provided tokenized
  394. words.
  395. Args:
  396. batch_or_word_index (`int`):
  397. Index of the sequence in the batch. If the batch only comprises one sequence, this can be the index of
  398. the word in the sequence.
  399. word_index (`int`, *optional*):
  400. If a batch index is provided in *batch_or_token_index*, this can be the index of the word in the
  401. sequence.
  402. sequence_index (`int`, *optional*, defaults to 0):
  403. If pair of sequences are encoded in the batch this can be used to specify which sequence in the pair (0
  404. or 1) the provided word index belongs to.
  405. Returns:
  406. Optional [`TokenSpan`] Span of tokens in the encoded sequence. Returns `None` if
  407. no tokens correspond to the word.
  408. """
  409. if not self._encodings:
  410. raise ValueError(
  411. "word_to_tokens() is not available when using Python based tokenizers"
  412. )
  413. if word_index is not None:
  414. batch_index = batch_or_word_index
  415. else:
  416. batch_index = 0
  417. word_index = batch_or_word_index
  418. if batch_index < 0:
  419. batch_index = self._batch_size + batch_index
  420. if word_index < 0:
  421. word_index = self._seq_len + word_index
  422. span = self._encodings[batch_index].word_to_tokens(word_index, sequence_index)
  423. return TokenSpan(*span) if span is not None else None
  424. def token_to_chars(
  425. self, batch_or_token_index: int, token_index: Optional[int] = None
  426. ) -> CharSpan:
  427. """
  428. Get the character span corresponding to an encoded token in a sequence of the batch.
  429. Character spans are returned as a [`CharSpan`] with:
  430. - **start** -- Index of the first character in the original string associated to the token.
  431. - **end** -- Index of the character following the last character in the original string associated to the
  432. token.
  433. Can be called as:
  434. - `self.token_to_chars(token_index)` if batch size is 1
  435. - `self.token_to_chars(batch_index, token_index)` if batch size is greater or equal to 1
  436. Args:
  437. batch_or_token_index (`int`):
  438. Index of the sequence in the batch. If the batch only comprise one sequence, this can be the index of
  439. the token in the sequence.
  440. token_index (`int`, *optional*):
  441. If a batch index is provided in *batch_or_token_index*, this can be the index of the token or tokens in
  442. the sequence.
  443. Returns:
  444. [`CharSpan`]: Span of characters in the original string.
  445. """
  446. if not self._encodings:
  447. raise ValueError(
  448. "token_to_chars() is not available when using Python based tokenizers"
  449. )
  450. if token_index is not None:
  451. batch_index = batch_or_token_index
  452. else:
  453. batch_index = 0
  454. token_index = batch_or_token_index
  455. return CharSpan(*(self._encodings[batch_index].token_to_chars(token_index)))
  456. def char_to_token(
  457. self,
  458. batch_or_char_index: int,
  459. char_index: Optional[int] = None,
  460. sequence_index: int = 0,
  461. ) -> int:
  462. """
  463. Get the index of the token in the encoded output comprising a character in the original string for a sequence
  464. of the batch.
  465. Can be called as:
  466. - `self.char_to_token(char_index)` if batch size is 1
  467. - `self.char_to_token(batch_index, char_index)` if batch size is greater or equal to 1
  468. This method is particularly suited when the input sequences are provided as pre-tokenized sequences (i.e. words
  469. are defined by the user). In this case it allows to easily associate encoded tokens with provided tokenized
  470. words.
  471. Args:
  472. batch_or_char_index (`int`):
  473. Index of the sequence in the batch. If the batch only comprise one sequence, this can be the index of
  474. the word in the sequence
  475. char_index (`int`, *optional*):
  476. If a batch index is provided in *batch_or_token_index*, this can be the index of the word in the
  477. sequence.
  478. sequence_index (`int`, *optional*, defaults to 0):
  479. If pair of sequences are encoded in the batch this can be used to specify which sequence in the pair (0
  480. or 1) the provided character index belongs to.
  481. Returns:
  482. `int`: Index of the token.
  483. """
  484. if not self._encodings:
  485. raise ValueError(
  486. "char_to_token() is not available when using Python based tokenizers"
  487. )
  488. if char_index is not None:
  489. batch_index = batch_or_char_index
  490. else:
  491. batch_index = 0
  492. char_index = batch_or_char_index
  493. return self._encodings[batch_index].char_to_token(char_index, sequence_index)
  494. def word_to_chars(
  495. self,
  496. batch_or_word_index: int,
  497. word_index: Optional[int] = None,
  498. sequence_index: int = 0,
  499. ) -> CharSpan:
  500. """
  501. Get the character span in the original string corresponding to given word in a sequence of the batch.
  502. Character spans are returned as a CharSpan NamedTuple with:
  503. - start: index of the first character in the original string
  504. - end: index of the character following the last character in the original string
  505. Can be called as:
  506. - `self.word_to_chars(word_index)` if batch size is 1
  507. - `self.word_to_chars(batch_index, word_index)` if batch size is greater or equal to 1
  508. Args:
  509. batch_or_word_index (`int`):
  510. Index of the sequence in the batch. If the batch only comprise one sequence, this can be the index of
  511. the word in the sequence
  512. word_index (`int`, *optional*):
  513. If a batch index is provided in *batch_or_token_index*, this can be the index of the word in the
  514. sequence.
  515. sequence_index (`int`, *optional*, defaults to 0):
  516. If pair of sequences are encoded in the batch this can be used to specify which sequence in the pair (0
  517. or 1) the provided word index belongs to.
  518. Returns:
  519. `CharSpan` or `List[CharSpan]`: Span(s) of the associated character or characters in the string. CharSpan
  520. are NamedTuple with:
  521. - start: index of the first character associated to the token in the original string
  522. - end: index of the character following the last character associated to the token in the original
  523. string
  524. """
  525. if not self._encodings:
  526. raise ValueError(
  527. "word_to_chars() is not available when using Python based tokenizers"
  528. )
  529. if word_index is not None:
  530. batch_index = batch_or_word_index
  531. else:
  532. batch_index = 0
  533. word_index = batch_or_word_index
  534. return CharSpan(
  535. *(self._encodings[batch_index].word_to_chars(word_index, sequence_index))
  536. )
  537. def char_to_word(
  538. self,
  539. batch_or_char_index: int,
  540. char_index: Optional[int] = None,
  541. sequence_index: int = 0,
  542. ) -> int:
  543. """
  544. Get the word in the original string corresponding to a character in the original string of a sequence of the
  545. batch.
  546. Can be called as:
  547. - `self.char_to_word(char_index)` if batch size is 1
  548. - `self.char_to_word(batch_index, char_index)` if batch size is greater than 1
  549. This method is particularly suited when the input sequences are provided as pre-tokenized sequences (i.e. words
  550. are defined by the user). In this case it allows to easily associate encoded tokens with provided tokenized
  551. words.
  552. Args:
  553. batch_or_char_index (`int`):
  554. Index of the sequence in the batch. If the batch only comprise one sequence, this can be the index of
  555. the character in the original string.
  556. char_index (`int`, *optional*):
  557. If a batch index is provided in *batch_or_token_index*, this can be the index of the character in the
  558. original string.
  559. sequence_index (`int`, *optional*, defaults to 0):
  560. If pair of sequences are encoded in the batch this can be used to specify which sequence in the pair (0
  561. or 1) the provided character index belongs to.
  562. Returns:
  563. `int` or `List[int]`: Index or indices of the associated encoded token(s).
  564. """
  565. if not self._encodings:
  566. raise ValueError(
  567. "char_to_word() is not available when using Python based tokenizers"
  568. )
  569. if char_index is not None:
  570. batch_index = batch_or_char_index
  571. else:
  572. batch_index = 0
  573. char_index = batch_or_char_index
  574. return self._encodings[batch_index].char_to_word(char_index, sequence_index)
  575. def convert_to_tensors(
  576. self,
  577. tensor_type: Optional[Union[str, TensorType]] = None,
  578. prepend_batch_axis: bool = False,
  579. ):
  580. """
  581. Convert the inner content to tensors.
  582. Args:
  583. tensor_type (`str` or [`TensorType`], *optional*):
  584. The type of tensors to use. If `str`, should be one of the values of the enum [`TensorType`]. If
  585. `None`, no modification is done.
  586. prepend_batch_axis (`int`, *optional*, defaults to `False`):
  587. Whether or not to add the batch dimension during the conversion.
  588. """
  589. import paddle
  590. if tensor_type is None:
  591. return self
  592. # Convert to TensorType
  593. if not isinstance(tensor_type, TensorType):
  594. tensor_type = TensorType(tensor_type)
  595. # Get a function reference for the correct framework
  596. if tensor_type == TensorType.PADDLE:
  597. as_tensor = paddle.to_tensor
  598. is_tensor = paddle.is_tensor
  599. else:
  600. as_tensor = np.asarray
  601. is_tensor = _is_numpy
  602. # Do the tensor conversion in batch
  603. for key, value in self.items():
  604. try:
  605. if prepend_batch_axis:
  606. value = [value]
  607. if not is_tensor(value):
  608. tensor = as_tensor(value)
  609. self[key] = tensor
  610. except: # noqa E722
  611. if key == "overflowing_tokens":
  612. raise ValueError(
  613. "Unable to create tensor returning overflowing tokens of different lengths. "
  614. "Please see if a fast version of this tokenizer is available to have this feature available."
  615. )
  616. raise ValueError(
  617. "Unable to create tensor, you should probably activate truncation and/or padding "
  618. "with 'padding=True' 'truncation=True' to have batched tensors with the same length."
  619. )
  620. return self
  621. class SpecialTokensMixin:
  622. """
  623. A mixin derived by [`PretrainedTokenizer`] to handle specific behaviors related to
  624. special tokens. In particular, this class hold the attributes which can be used to directly access these special
  625. tokens in a model-independent manner and allow to set and update the special tokens.
  626. Args:
  627. bos_token (`str` or `AddedToken`, *optional*):
  628. A special token representing the beginning of a sentence.
  629. eos_token (`str` or `AddedToken`, *optional*):
  630. A special token representing the end of a sentence.
  631. unk_token (`str` or `AddedToken`, *optional*):
  632. A special token representing an out-of-vocabulary token.
  633. sep_token (`str` or `AddedToken`, *optional*):
  634. A special token separating two different sentences in the same input (used by BERT for instance).
  635. pad_token (`str` or `AddedToken`, *optional*):
  636. A special token used to make arrays of tokens the same size for batching purpose. Will then be ignored by
  637. attention mechanisms or loss computation.
  638. cls_token (`str` or `AddedToken`, *optional*):
  639. A special token representing the class of the input (used by BERT for instance).
  640. mask_token (`str` or `AddedToken`, *optional*):
  641. A special token representing a masked token (used by masked-language modeling pretraining objectives, like
  642. BERT).
  643. additional_special_tokens (tuple or list of `str` or `AddedToken`, *optional*):
  644. A tuple or a list of additional special tokens.
  645. """
  646. SPECIAL_TOKENS_ATTRIBUTES = [
  647. "bos_token",
  648. "eos_token",
  649. "unk_token",
  650. "sep_token",
  651. "pad_token",
  652. "cls_token",
  653. "mask_token",
  654. "additional_special_tokens",
  655. ]
  656. def __init__(self, verbose=True, **kwargs):
  657. # note(guosheng): Since `__init__` might be called multiple times which
  658. # is hooked before `PretrainedTokenizer` init, we do not set to None as
  659. # HF to avoid unintentional overriding.
  660. self._bos_token = getattr(self, "_bos_token", None)
  661. self._eos_token = getattr(self, "_eos_token", None)
  662. self._unk_token = getattr(self, "_unk_token", None)
  663. self._sep_token = getattr(self, "_sep_token", None)
  664. self._pad_token = getattr(self, "_pad_token", None)
  665. self._cls_token = getattr(self, "_cls_token", None)
  666. self._mask_token = getattr(self, "_mask_token", None)
  667. self._pad_token_type_id = getattr(self, "_pad_token_type_id", 0)
  668. self._additional_special_tokens = getattr(
  669. self, "_additional_special_tokens", []
  670. )
  671. self.verbose = verbose
  672. # We directly set the hidden value to allow initialization with special tokens
  673. # which are not yet in the vocabulary. Necessary for serialization/de-serialization
  674. # TODO clean this up at some point (probably by switching to fast tokenizers)
  675. for key, value in kwargs.items():
  676. if value is None:
  677. continue
  678. if key in self.SPECIAL_TOKENS_ATTRIBUTES:
  679. if key == "additional_special_tokens":
  680. assert isinstance(
  681. value, (list, tuple)
  682. ), f"Value {value} is not a list or tuple"
  683. assert all(
  684. isinstance(t, (str, AddedToken)) for t in value
  685. ), "One of the tokens is not a string or an AddedToken"
  686. setattr(self, key, value)
  687. elif isinstance(value, (str, AddedToken)):
  688. setattr(self, key, value)
  689. else:
  690. raise TypeError(
  691. f"special token {key} has to be either str or AddedToken but got: {type(value)}"
  692. )
  693. def sanitize_special_tokens(self) -> int:
  694. """
  695. Make sure that all the special tokens attributes of the tokenizer (`tokenizer.mask_token`,
  696. `tokenizer.cls_token`, etc.) are in the vocabulary.
  697. Add the missing ones to the vocabulary if needed.
  698. Return:
  699. `int`: The number of tokens added in the vocabulary during the operation.
  700. """
  701. return self.add_tokens(self.all_special_tokens_extended, special_tokens=True)
  702. def add_special_tokens(
  703. self, special_tokens_dict: Dict[str, Union[str, AddedToken]]
  704. ) -> int:
  705. """
  706. Add a dictionary of special tokens (eos, pad, cls, etc.) to the encoder and link them to class attributes. If
  707. special tokens are NOT in the vocabulary, they are added to it (indexed starting from the last index of the
  708. current vocabulary).
  709. Note,None When adding new tokens to the vocabulary, you should make sure to also resize the token embedding
  710. matrix of the model so that its embedding matrix matches the tokenizer.
  711. In order to do that, please use the [`~PreTrainedModel.resize_token_embeddings`] method.
  712. Using `add_special_tokens` will ensure your special tokens can be used in several ways:
  713. - Special tokens are carefully handled by the tokenizer (they are never split).
  714. - You can easily refer to special tokens using tokenizer class attributes like `tokenizer.cls_token`. This
  715. makes it easy to develop model-agnostic training and fine-tuning scripts.
  716. When possible, special tokens are already registered for provided pretrained models (for instance
  717. [`BertTokenizer`] `cls_token` is already registered to be :obj*'[CLS]'* and XLM's one is also registered to be
  718. `'</s>'`).
  719. Args:
  720. special_tokens_dict (dictionary *str* to *str* or `AddedToken`):
  721. Keys should be in the list of predefined special attributes: [`bos_token`, `eos_token`, `unk_token`,
  722. `sep_token`, `pad_token`, `cls_token`, `mask_token`, `additional_special_tokens`].
  723. Tokens are only added if they are not already in the vocabulary (tested by checking if the tokenizer
  724. assign the index of the `unk_token` to them).
  725. Returns:
  726. `int`: Number of tokens added to the vocabulary.
  727. Examples:
  728. ```python
  729. # Let's see how to add a new classification token to GPT-2
  730. tokenizer = GPT2Tokenizer.from_pretrained("gpt2")
  731. model = GPT2Model.from_pretrained("gpt2")
  732. special_tokens_dict = {"cls_token": "<CLS>"}
  733. num_added_toks = tokenizer.add_special_tokens(special_tokens_dict)
  734. print("We have added", num_added_toks, "tokens")
  735. # Notice: resize_token_embeddings expect to receive the full size of the new vocabulary, i.e., the length of the tokenizer.
  736. model.resize_token_embeddings(len(tokenizer))
  737. assert tokenizer.cls_token == "<CLS>"
  738. ```"""
  739. if not special_tokens_dict:
  740. return 0
  741. added_tokens = 0
  742. for key, value in special_tokens_dict.items():
  743. assert (
  744. key in self.SPECIAL_TOKENS_ATTRIBUTES
  745. ), f"Key {key} is not a special token"
  746. if self.verbose:
  747. logging.info(f"Assigning {value} to the {key} key of the tokenizer")
  748. setattr(self, key, value)
  749. if key == "additional_special_tokens":
  750. assert isinstance(value, (list, tuple)) and all(
  751. isinstance(t, (str, AddedToken)) for t in value
  752. ), f"Tokens {value} for key {key} should all be str or AddedToken instances"
  753. added_tokens += self.add_tokens(value, special_tokens=True)
  754. else:
  755. assert isinstance(
  756. value, (str, AddedToken)
  757. ), f"Token {value} for key {key} should be a str or an AddedToken instance"
  758. added_tokens += self.add_tokens([value], special_tokens=True)
  759. return added_tokens
  760. def add_tokens(
  761. self,
  762. new_tokens: Union[str, AddedToken, List[Union[str, AddedToken]]],
  763. special_tokens: bool = False,
  764. ) -> int:
  765. """
  766. Add a list of new tokens to the tokenizer class. If the new tokens are not in the vocabulary, they are added to
  767. it with indices starting from length of the current vocabulary.
  768. Note,None When adding new tokens to the vocabulary, you should make sure to also resize the token embedding
  769. matrix of the model so that its embedding matrix matches the tokenizer.
  770. In order to do that, please use the [`~PreTrainedModel.resize_token_embeddings`] method.
  771. Args:
  772. new_tokens (`str`, `AddedToken` or a list of *str* or `AddedToken`):
  773. Tokens are only added if they are not already in the vocabulary. `AddedToken` wraps a string
  774. token to let you personalize its behavior: whether this token should only match against a single word,
  775. whether this token should strip all potential whitespaces on the left side, whether this token should
  776. strip all potential whitespaces on the right side, etc.
  777. special_tokens (`bool`, *optional*, defaults to `False`):
  778. Can be used to specify if the token is a special token. This mostly change the normalization behavior
  779. (special tokens like CLS or [MASK] are usually not lower-cased for instance).
  780. Returns:
  781. `int`: Number of tokens added to the vocabulary.
  782. Examples:
  783. ```python
  784. # Let's see how to increase the vocabulary of Bert model and tokenizer
  785. tokenizer = BertTokenizer.from_pretrained("bert-base-uncased")
  786. model = BertModel.from_pretrained("bert-base-uncased")
  787. num_added_toks = tokenizer.add_tokens(["new_tok1", "my_new-tok2"])
  788. print("We have added", num_added_toks, "tokens")
  789. # Notice: resize_token_embeddings expect to receive the full size of the new vocabulary, i.e., the length of the tokenizer.
  790. model.resize_token_embeddings(len(tokenizer))
  791. ```"""
  792. if not new_tokens:
  793. return 0
  794. if not isinstance(new_tokens, (list, tuple)):
  795. new_tokens = [new_tokens]
  796. return self._add_tokens(new_tokens, special_tokens=special_tokens)
  797. def _add_tokens(
  798. self,
  799. new_tokens: Union[List[str], List[AddedToken]],
  800. special_tokens: bool = False,
  801. ) -> int:
  802. raise NotImplementedError
  803. @property
  804. def bos_token(self) -> str:
  805. """
  806. `str`: Beginning of sentence token. Log an error if used while not having been set.
  807. """
  808. if self._bos_token is None and self.verbose:
  809. logging.error("Using bos_token, but it is not set yet.")
  810. return None
  811. return str(self._bos_token)
  812. @property
  813. def eos_token(self) -> str:
  814. """
  815. `str`: End of sentence token. Log an error if used while not having been set.
  816. """
  817. if self._eos_token is None and self.verbose:
  818. logging.error("Using eos_token, but it is not set yet.")
  819. return None
  820. return str(self._eos_token)
  821. @property
  822. def unk_token(self) -> str:
  823. """
  824. `str`: Unknown token. Log an error if used while not having been set.
  825. """
  826. if self._unk_token is None and self.verbose:
  827. logging.error("Using unk_token, but it is not set yet.")
  828. return None
  829. return str(self._unk_token)
  830. @property
  831. def sep_token(self) -> str:
  832. """
  833. `str`: Separation token, to separate context and query in an input sequence. Log an error if used while not
  834. having been set.
  835. """
  836. if self._sep_token is None and self.verbose:
  837. logging.error("Using sep_token, but it is not set yet.")
  838. return None
  839. return str(self._sep_token)
  840. @property
  841. def pad_token(self) -> str:
  842. """
  843. `str`: Padding token. Log an error if used while not having been set.
  844. """
  845. if self._pad_token is None and self.verbose:
  846. logging.error("Using pad_token, but it is not set yet.")
  847. return None
  848. return str(self._pad_token)
  849. @property
  850. def cls_token(self) -> str:
  851. """
  852. `str`: Classification token, to extract a summary of an input sequence leveraging self-attention along the full
  853. depth of the model. Log an error if used while not having been set.
  854. """
  855. if self._cls_token is None and self.verbose:
  856. logging.error("Using cls_token, but it is not set yet.")
  857. return None
  858. return str(self._cls_token)
  859. @property
  860. def mask_token(self) -> str:
  861. """
  862. `str`: Mask token, to use when training a model with masked-language modeling. Log an error if used while not
  863. having been set.
  864. """
  865. if self._mask_token is None and self.verbose:
  866. logging.error("Using mask_token, but it is not set yet.")
  867. return None
  868. return str(self._mask_token)
  869. @property
  870. def additional_special_tokens(self) -> List[str]:
  871. """
  872. `List[str]`: All the additional special tokens you may want to use. Log an error if used while not having been
  873. set.
  874. """
  875. if self._additional_special_tokens is None and self.verbose:
  876. logging.error("Using additional_special_tokens, but it is not set yet.")
  877. return None
  878. return [str(tok) for tok in self._additional_special_tokens]
  879. @bos_token.setter
  880. def bos_token(self, value):
  881. self._bos_token = value
  882. @eos_token.setter
  883. def eos_token(self, value):
  884. self._eos_token = value
  885. @unk_token.setter
  886. def unk_token(self, value):
  887. self._unk_token = value
  888. @sep_token.setter
  889. def sep_token(self, value):
  890. self._sep_token = value
  891. @pad_token.setter
  892. def pad_token(self, value):
  893. self._pad_token = value
  894. @cls_token.setter
  895. def cls_token(self, value):
  896. self._cls_token = value
  897. @mask_token.setter
  898. def mask_token(self, value):
  899. self._mask_token = value
  900. @additional_special_tokens.setter
  901. def additional_special_tokens(self, value):
  902. self._additional_special_tokens = value
  903. @property
  904. def bos_token_id(self) -> Optional[int]:
  905. """
  906. `Optional[int]`: Id of the beginning of sentence token in the vocabulary. Returns `None` if the token has not
  907. been set.
  908. """
  909. if self._bos_token is None:
  910. return None
  911. return self.convert_tokens_to_ids(self.bos_token)
  912. @property
  913. def eos_token_id(self) -> Optional[int]:
  914. """
  915. `Optional[int]`: Id of the end of sentence token in the vocabulary. Returns `None` if the token has not been
  916. set.
  917. """
  918. if self._eos_token is None:
  919. return None
  920. return self.convert_tokens_to_ids(self.eos_token)
  921. @property
  922. def unk_token_id(self) -> Optional[int]:
  923. """
  924. `Optional[int]`: Id of the unknown token in the vocabulary. Returns `None` if the token has not been set.
  925. """
  926. if self._unk_token is None:
  927. return None
  928. return self.convert_tokens_to_ids(self.unk_token)
  929. @property
  930. def sep_token_id(self) -> Optional[int]:
  931. """
  932. `Optional[int]`: Id of the separation token in the vocabulary, to separate context and query in an input
  933. sequence. Returns `None` if the token has not been set.
  934. """
  935. if self._sep_token is None:
  936. return None
  937. return self.convert_tokens_to_ids(self.sep_token)
  938. @property
  939. def pad_token_id(self) -> Optional[int]:
  940. """
  941. `Optional[int]`: Id of the padding token in the vocabulary. Returns `None` if the token has not been set.
  942. """
  943. if self._pad_token is None:
  944. return None
  945. return self.convert_tokens_to_ids(self.pad_token)
  946. @property
  947. def pad_token_type_id(self) -> int:
  948. """
  949. `int`: Id of the padding token type in the vocabulary.
  950. """
  951. return self._pad_token_type_id
  952. @property
  953. def cls_token_id(self) -> Optional[int]:
  954. """
  955. `Optional[int]`: Id of the classification token in the vocabulary, to extract a summary of an input sequence
  956. leveraging self-attention along the full depth of the model.
  957. Returns `None` if the token has not been set.
  958. """
  959. if self._cls_token is None:
  960. return None
  961. return self.convert_tokens_to_ids(self.cls_token)
  962. @property
  963. def mask_token_id(self) -> Optional[int]:
  964. """
  965. `Optional[int]`: Id of the mask token in the vocabulary, used when training a model with masked-language
  966. modeling. Returns `None` if the token has not been set.
  967. """
  968. if self._mask_token is None:
  969. return None
  970. return self.convert_tokens_to_ids(self.mask_token)
  971. @property
  972. def additional_special_tokens_ids(self) -> List[int]:
  973. """
  974. `List[int]`: Ids of all the additional special tokens in the vocabulary. Log an error if used while not having
  975. been set.
  976. """
  977. return self.convert_tokens_to_ids(self.additional_special_tokens)
  978. @bos_token_id.setter
  979. def bos_token_id(self, value):
  980. self._bos_token = (
  981. self.convert_ids_to_tokens(value) if value is not None else None
  982. )
  983. @eos_token_id.setter
  984. def eos_token_id(self, value):
  985. self._eos_token = (
  986. self.convert_ids_to_tokens(value) if value is not None else None
  987. )
  988. @unk_token_id.setter
  989. def unk_token_id(self, value):
  990. self._unk_token = (
  991. self.convert_ids_to_tokens(value) if value is not None else None
  992. )
  993. @sep_token_id.setter
  994. def sep_token_id(self, value):
  995. self._sep_token = (
  996. self.convert_ids_to_tokens(value) if value is not None else None
  997. )
  998. @pad_token_id.setter
  999. def pad_token_id(self, value):
  1000. self._pad_token = (
  1001. self.convert_ids_to_tokens(value) if value is not None else None
  1002. )
  1003. @cls_token_id.setter
  1004. def cls_token_id(self, value):
  1005. self._cls_token = (
  1006. self.convert_ids_to_tokens(value) if value is not None else None
  1007. )
  1008. @mask_token_id.setter
  1009. def mask_token_id(self, value):
  1010. self._mask_token = (
  1011. self.convert_ids_to_tokens(value) if value is not None else None
  1012. )
  1013. @additional_special_tokens_ids.setter
  1014. def additional_special_tokens_ids(self, values):
  1015. self._additional_special_tokens = [
  1016. self.convert_ids_to_tokens(value) for value in values
  1017. ]
  1018. @property
  1019. def special_tokens_map(self) -> Dict[str, Union[str, List[str]]]:
  1020. """
  1021. `Dict[str, Union[str, List[str]]]`: A dictionary mapping special token class attributes (`cls_token`,
  1022. `unk_token`, etc.) to their values (`'<unk>'`, `'<cls>'`, etc.).
  1023. Convert potential tokens of `AddedToken` type to string.
  1024. """
  1025. set_attr = {}
  1026. for attr in self.SPECIAL_TOKENS_ATTRIBUTES:
  1027. attr_value = getattr(self, "_" + attr)
  1028. if attr_value:
  1029. set_attr[attr] = (
  1030. type(attr_value)(
  1031. str(attr_value_sub) for attr_value_sub in attr_value
  1032. )
  1033. if isinstance(attr_value, (list, tuple))
  1034. else str(attr_value)
  1035. )
  1036. return set_attr
  1037. @property
  1038. def special_tokens_map_extended(
  1039. self,
  1040. ) -> Dict[str, Union[str, AddedToken, List[Union[str, AddedToken]]]]:
  1041. """
  1042. `Dict[str, Union[str, AddedToken, List[Union[str, AddedToken]]]]`: A dictionary mapping
  1043. special token class attributes (`cls_token`, `unk_token`, etc.) to their values (`'<unk>'`, `'<cls>'`, etc.).
  1044. Don't convert tokens of `AddedToken` type to string so they can be used to control more finely how
  1045. special tokens are tokenized.
  1046. """
  1047. set_attr = {}
  1048. for attr in self.SPECIAL_TOKENS_ATTRIBUTES:
  1049. attr_value = getattr(self, "_" + attr, None)
  1050. if attr_value:
  1051. set_attr[attr] = attr_value
  1052. return set_attr
  1053. @property
  1054. def all_special_tokens(self) -> List[str]:
  1055. """
  1056. `List[str]`: All the special tokens (`'<unk>'`, `'<cls>'`, etc.) mapped to class attributes.
  1057. Convert tokens of `AddedToken` type to string.
  1058. """
  1059. all_toks = [str(s) for s in self.all_special_tokens_extended]
  1060. return all_toks
  1061. @property
  1062. def all_special_tokens_extended(self) -> List[Union[str, AddedToken]]:
  1063. """
  1064. `List[Union[str, AddedToken]]`: All the special tokens (`'<unk>'`, `'<cls>'`, etc.) mapped to class
  1065. attributes.
  1066. Don't convert tokens of `AddedToken` type to string so they can be used to control more finely how
  1067. special tokens are tokenized.
  1068. """
  1069. all_toks = []
  1070. set_attr = self.special_tokens_map_extended
  1071. for attr_value in set_attr.values():
  1072. all_toks = all_toks + (
  1073. list(attr_value)
  1074. if isinstance(attr_value, (list, tuple))
  1075. else [attr_value]
  1076. )
  1077. all_toks = list(OrderedDict.fromkeys(all_toks))
  1078. return all_toks
  1079. @property
  1080. def all_special_ids(self) -> List[int]:
  1081. """
  1082. `List[int]`: List the ids of the special tokens(`'<unk>'`, `'<cls>'`, etc.) mapped to class attributes.
  1083. """
  1084. all_toks = self.all_special_tokens
  1085. all_ids = self.convert_tokens_to_ids(all_toks)
  1086. return all_ids
  1087. class PretrainedTokenizerBase(SpecialTokensMixin):
  1088. """
  1089. Base class for [`PretrainedTokenizer`].
  1090. Class attributes (overridden by derived classes)
  1091. - **resource_files_names** (`Dict[str, str]`) -- A dictionary with, as keys, the `__init__` keyword name of each
  1092. vocabulary file required by the model, and as associated values, the filename for saving the associated file
  1093. (string).
  1094. - **pretrained_resource_files_map** (`Dict[str, Dict[str, str]]`) -- A dictionary of dictionaries, with the
  1095. high-level keys being the `__init__` keyword name of each vocabulary file required by the model, the
  1096. low-level being the `short-cut-names` of the pretrained models with, as associated values, the `url` to the
  1097. associated pretrained vocabulary file.
  1098. - **max_model_input_sizes** (`Dict[str, Optional[int]]`) -- A dictionary with, as keys, the `short-cut-names`
  1099. of the pretrained models, and as associated values, the maximum length of the sequence inputs of this model,
  1100. or `None` if the model has no maximum input size.
  1101. - **pretrained_init_configuration** (`Dict[str, Dict[str, Any]]`) -- A dictionary with, as keys, the
  1102. `short-cut-names` of the pretrained models, and as associated values, a dictionary of specific arguments to
  1103. pass to the `__init__` method of the tokenizer class for this pretrained model when loading the tokenizer
  1104. with the [`~tokenizer_utils_base.PretrainedTokenizerBase.from_pretrained`] method.
  1105. - **model_input_names** (`List[str]`) -- A list of inputs expected in the forward pass of the model.
  1106. - **padding_side** (`str`) -- The default value for the side on which the model should have padding applied.
  1107. Should be `'right'` or `'left'`.
  1108. - **truncation_side** (`str`) -- The default value for the side on which the model should have truncation
  1109. applied. Should be `'right'` or `'left'`.
  1110. Args:
  1111. model_max_length (`int`, *optional*):
  1112. The maximum length (in number of tokens) for the inputs to the transformer model. When the tokenizer is
  1113. loaded with [`~tokenizer_utils_base.PretrainedTokenizerBase.from_pretrained`], this will be set to the
  1114. value stored for the associated model in `max_model_input_sizes` (see above). If no value is provided, will
  1115. default to VERY_LARGE_INTEGER (`int(1e30)`).
  1116. padding_side (`str`, *optional*):
  1117. The side on which the model should have padding applied. Should be selected between ['right', 'left'].
  1118. Default value is picked from the class attribute of the same name.
  1119. truncation_side (`str`, *optional*):
  1120. The side on which the model should have truncation applied. Should be selected between ['right', 'left'].
  1121. Default value is picked from the class attribute of the same name.
  1122. model_input_names (`List[string]`, *optional*):
  1123. The list of inputs accepted by the forward pass of the model (like `"token_type_ids"` or
  1124. `"attention_mask"`). Default value is picked from the class attribute of the same name.
  1125. bos_token (`str` or `AddedToken`, *optional*):
  1126. A special token representing the beginning of a sentence. Will be associated to `self.bos_token` and
  1127. `self.bos_token_id`.
  1128. eos_token (`str` or `AddedToken`, *optional*):
  1129. A special token representing the end of a sentence. Will be associated to `self.eos_token` and
  1130. `self.eos_token_id`.
  1131. unk_token (`str` or `AddedToken`, *optional*):
  1132. A special token representing an out-of-vocabulary token. Will be associated to `self.unk_token` and
  1133. `self.unk_token_id`.
  1134. sep_token (`str` or `AddedToken`, *optional*):
  1135. A special token separating two different sentences in the same input (used by BERT for instance). Will be
  1136. associated to `self.sep_token` and `self.sep_token_id`.
  1137. pad_token (`str` or `AddedToken`, *optional*):
  1138. A special token used to make arrays of tokens the same size for batching purpose. Will then be ignored by
  1139. attention mechanisms or loss computation. Will be associated to `self.pad_token` and `self.pad_token_id`.
  1140. cls_token (`str` or `AddedToken`, *optional*):
  1141. A special token representing the class of the input (used by BERT for instance). Will be associated to
  1142. `self.cls_token` and `self.cls_token_id`.
  1143. mask_token (`str` or `AddedToken`, *optional*):
  1144. A special token representing a masked token (used by masked-language modeling pretraining objectives, like
  1145. BERT). Will be associated to `self.mask_token` and `self.mask_token_id`.
  1146. additional_special_tokens (tuple or list of `str` or `AddedToken`, *optional*):
  1147. A tuple or a list of additional special tokens. Add them here to ensure they won't be split by the
  1148. tokenization process. Will be associated to `self.additional_special_tokens` and
  1149. `self.additional_special_tokens_ids`.
  1150. """
  1151. resource_files_names: Dict[str, str] = {}
  1152. pretrained_resource_files_map: Dict[str, Dict[str, str]] = {}
  1153. pretrained_init_configuration: Dict[str, Dict[str, Any]] = {}
  1154. max_model_input_sizes: Dict[str, Optional[int]] = {}
  1155. _auto_class: Optional[str] = None
  1156. tokenizer_config_file = TOKENIZER_CONFIG_NAME
  1157. # first name has to correspond to main model input name
  1158. # to make sure `tokenizer.pad(...)` works correctly
  1159. model_input_names: List[str] = ["input_ids", "token_type_ids"]
  1160. padding_side: str = "right"
  1161. truncation_side: str = "right"
  1162. slow_tokenizer_class = None
  1163. def __init__(self, **kwargs):
  1164. # inputs and kwargs for saving and re-loading (see ``from_pretrained`` and ``save_pretrained``)
  1165. self.init_inputs = ()
  1166. self.init_kwargs = getattr(self, "init_kwargs", None) or copy.deepcopy(kwargs)
  1167. self.name_or_path = kwargs.pop("name_or_path", "")
  1168. self._processor_class = kwargs.pop("processor_class", None)
  1169. # For backward compatibility we fallback to set model_max_length from max_len if provided
  1170. model_max_length = kwargs.pop("model_max_length", kwargs.pop("max_len", None))
  1171. self.model_max_length = (
  1172. model_max_length if model_max_length is not None else VERY_LARGE_INTEGER
  1173. )
  1174. # Padding and truncation side are right by default and overridden in subclasses. If specified in the kwargs, it
  1175. # is changed.
  1176. self.padding_side = kwargs.pop("padding_side", self.padding_side)
  1177. if self.padding_side not in ["right", "left"]:
  1178. raise ValueError(
  1179. f"Padding side should be selected between 'right' and 'left', current value: {self.padding_side}"
  1180. )
  1181. self.truncation_side = kwargs.pop("truncation_side", self.truncation_side)
  1182. if self.truncation_side not in ["right", "left"]:
  1183. raise ValueError(
  1184. f"Padding side should be selected between 'right' and 'left', current value: {self.truncation_side}"
  1185. )
  1186. self.model_input_names = kwargs.pop("model_input_names", self.model_input_names)
  1187. self.deprecation_warnings = (
  1188. {}
  1189. ) # Use to store when we have already noticed a deprecation warning (avoid overlogging).
  1190. super().__init__(**kwargs)
  1191. @property
  1192. def max_len_single_sentence(self) -> int:
  1193. """
  1194. `int`: The maximum length of a sentence that can be fed to the model.
  1195. """
  1196. return self.model_max_length - self.num_special_tokens_to_add(pair=False)
  1197. @property
  1198. def max_len_sentences_pair(self) -> int:
  1199. """
  1200. `int`: The maximum combined length of a pair of sentences that can be fed to the model.
  1201. """
  1202. return self.model_max_length - self.num_special_tokens_to_add(pair=True)
  1203. @max_len_single_sentence.setter
  1204. def max_len_single_sentence(self, value) -> int:
  1205. # For backward compatibility, allow to try to setup 'max_len_single_sentence'.
  1206. if (
  1207. value == self.model_max_length - self.num_special_tokens_to_add(pair=False)
  1208. and self.verbose
  1209. ):
  1210. if not self.deprecation_warnings.get("max_len_single_sentence", False):
  1211. warnings.warn(
  1212. "Setting 'max_len_single_sentence' is now deprecated. "
  1213. "This value is automatically set up."
  1214. )
  1215. self.deprecation_warnings["max_len_single_sentence"] = True
  1216. else:
  1217. raise ValueError(
  1218. "Setting 'max_len_single_sentence' is now deprecated. "
  1219. "This value is automatically set up."
  1220. )
  1221. def _switch_to_input_mode(self):
  1222. """
  1223. Private method to put the tokenizer in input mode (when it has different modes for input/outputs)
  1224. """
  1225. @max_len_sentences_pair.setter
  1226. def max_len_sentences_pair(self, value) -> int:
  1227. # For backward compatibility, allow to try to setup 'max_len_sentences_pair'.
  1228. if (
  1229. value == self.model_max_length - self.num_special_tokens_to_add(pair=True)
  1230. and self.verbose
  1231. ):
  1232. if not self.deprecation_warnings.get("max_len_sentences_pair", False):
  1233. warnings.warn(
  1234. "Setting 'max_len_sentences_pair' is now deprecated. "
  1235. "This value is automatically set up."
  1236. )
  1237. self.deprecation_warnings["max_len_sentences_pair"] = True
  1238. else:
  1239. raise ValueError(
  1240. "Setting 'max_len_sentences_pair' is now deprecated. "
  1241. "This value is automatically set up."
  1242. )
  1243. def _set_processor_class(self, processor_class: str):
  1244. """Sets processor class as an attribute."""
  1245. self._processor_class = processor_class
  1246. def __repr__(self) -> str:
  1247. return (
  1248. f"{'PretrainedTokenizer'}(name_or_path='{self.name_or_path}', "
  1249. f"vocab_size={self.vocab_size}, model_max_len={self.model_max_length}, "
  1250. f"padding_side='{self.padding_side}', truncation_side='{self.truncation_side}', special_tokens={self.special_tokens_map_extended})"
  1251. )
  1252. def get_vocab(self) -> Dict[str, int]:
  1253. """
  1254. Returns the vocabulary as a dictionary of token to index.
  1255. `tokenizer.get_vocab()[token]` is equivalent to `tokenizer.convert_tokens_to_ids(token)` when `token` is in the
  1256. vocab.
  1257. Returns:
  1258. `Dict[str, int]`: The vocabulary.
  1259. """
  1260. raise NotImplementedError()
  1261. @classmethod
  1262. def from_pretrained(cls, pretrained_model_name_or_path, *args, **kwargs):
  1263. """
  1264. Creates an instance of `PretrainedTokenizer`. Related resources are loaded
  1265. by specifying name of a built-in pretrained model, or a community-contributed
  1266. pretrained model, or a local file directory path.
  1267. Args:
  1268. pretrained_model_name_or_path (str): Name of pretrained model or dir path
  1269. to load from. The string can be:
  1270. - Name of built-in pretrained model
  1271. - Name of a community-contributed pretrained model.
  1272. - Local directory path which contains tokenizer related resources
  1273. and tokenizer config file ("tokenizer_config.json").
  1274. from_hf_hub (bool, optional): whether to load from Huggingface Hub
  1275. subfolder (str, optional) An optional value corresponding to a folder inside the repo.
  1276. Only works when loading from Huggingface Hub.
  1277. *args (tuple): position arguments for model `__init__`. If provided,
  1278. use these as position argument values for tokenizer initialization.
  1279. **kwargs (dict): keyword arguments for model `__init__`. If provided,
  1280. use these to update pre-defined keyword argument values for tokenizer
  1281. initialization.
  1282. Returns:
  1283. PretrainedTokenizer: An instance of `PretrainedTokenizer`.
  1284. Example:
  1285. .. code-block::
  1286. from paddlenlp.transformers import BertTokenizer
  1287. # Name of built-in pretrained model
  1288. tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')
  1289. # Name of community-contributed pretrained model
  1290. tokenizer = BertTokenizer.from_pretrained('yingyibiao/bert-base-uncased-sst-2-finetuned')
  1291. # Load from local directory path
  1292. tokenizer = BertTokenizer.from_pretrained('./my_bert/')
  1293. """
  1294. pretrained_model_name_or_path = str(pretrained_model_name_or_path)
  1295. cache_dir = kwargs.pop("cache_dir", None)
  1296. from_hf_hub = kwargs.pop("from_hf_hub", False)
  1297. from_aistudio = kwargs.pop("from_aistudio", False)
  1298. subfolder = kwargs.pop("subfolder", "")
  1299. return_tokenizer_file_dir = kwargs.pop("return_tokenizer_file_dir", False)
  1300. if subfolder is None:
  1301. subfolder = ""
  1302. vocab_files = {}
  1303. init_configuration = {}
  1304. additional_files_names = {
  1305. "added_tokens_file": ADDED_TOKENS_FILE,
  1306. "special_tokens_map_file": SPECIAL_TOKENS_MAP_FILE,
  1307. "tokenizer_config_file": TOKENIZER_CONFIG_FILE,
  1308. "chat_template_file": CHAT_TEMPLATE_CONFIG_NAME,
  1309. }
  1310. vocab_files_target = {**cls.resource_files_names, **additional_files_names}
  1311. # From HF Hub or AI Studio
  1312. if from_hf_hub or from_aistudio:
  1313. # Only include the necessary resource files specified by the tokenizer cls
  1314. # Deep copy to avoid modifiying the class attributes
  1315. vocab_files = copy.deepcopy(cls.resource_files_names)
  1316. vocab_files["tokenizer_config_file"] = cls.tokenizer_config_file
  1317. # From built-in pretrained models
  1318. elif pretrained_model_name_or_path in cls.pretrained_init_configuration:
  1319. for file_id, map_list in cls.pretrained_resource_files_map.items():
  1320. vocab_files[file_id] = map_list[pretrained_model_name_or_path]
  1321. init_configuration = copy.deepcopy(
  1322. cls.pretrained_init_configuration[pretrained_model_name_or_path]
  1323. )
  1324. # From local dir path
  1325. elif os.path.isdir(pretrained_model_name_or_path):
  1326. vocab_files_target["tokenizer_config_file"] = cls.tokenizer_config_file
  1327. for file_id, file_name in vocab_files_target.items():
  1328. full_file_name = os.path.join(
  1329. pretrained_model_name_or_path, subfolder, file_name
  1330. )
  1331. if os.path.isfile(full_file_name):
  1332. vocab_files[file_id] = full_file_name
  1333. else:
  1334. # Assuming from community-contributed pretrained models
  1335. for file_id, file_name in vocab_files_target.items():
  1336. vocab_files[file_id] = file_name
  1337. resolved_vocab_files = {}
  1338. for file_id, file_path in vocab_files.items():
  1339. if file_path is None or os.path.isfile(file_path):
  1340. resolved_vocab_files[file_id] = file_path
  1341. continue
  1342. else:
  1343. logging.warnings("need to download tokenizer, but not support yet.")
  1344. # tokenizer download not support yet
  1345. # resolved_vocab_files[file_id] = resolve_file_path(
  1346. # pretrained_model_name_or_path,
  1347. # [file_path],
  1348. # subfolder,
  1349. # cache_dir=cache_dir,
  1350. # from_aistudio=from_aistudio,
  1351. # from_hf_hub=from_hf_hub,
  1352. # )
  1353. for file_id, file_path in resolved_vocab_files.items():
  1354. if resolved_vocab_files[file_id] is not None:
  1355. cache_dir = os.path.dirname(resolved_vocab_files[file_id])
  1356. break
  1357. tokenizer_config_file_dir_list = set()
  1358. for k, v in resolved_vocab_files.items():
  1359. if v is not None and os.path.isfile(v):
  1360. tokenizer_config_file_dir_list.add(os.path.dirname(v))
  1361. tokenizer_config_file_dir_list = list(tokenizer_config_file_dir_list)
  1362. # TODO: check this
  1363. assert (
  1364. len(tokenizer_config_file_dir_list) > 0
  1365. ), "All tokenizer files should be in the same directory."
  1366. # Prepare tokenizer initialization kwargs
  1367. # Did we saved some inputs and kwargs to reload ?
  1368. has_tokenizer_file = (
  1369. resolved_vocab_files.get("tokenizer_file", None) is not None
  1370. )
  1371. tokenizer_config_file = resolved_vocab_files.pop("tokenizer_config_file", None)
  1372. if tokenizer_config_file is not None:
  1373. with io.open(tokenizer_config_file, encoding="utf-8") as f:
  1374. init_kwargs = json.load(f)
  1375. else:
  1376. init_kwargs = init_configuration
  1377. # position args are stored in kwargs, maybe better not include
  1378. init_args = init_kwargs.pop("init_args", ())
  1379. init_kwargs.pop("init_class", None)
  1380. # Update with newly provided args and kwargs
  1381. init_args = init_args if not args else args
  1382. init_kwargs.update(kwargs)
  1383. def convert_added_tokens(obj):
  1384. if (
  1385. isinstance(obj, dict)
  1386. and "__type" in obj
  1387. and obj["__type"] == "AddedToken"
  1388. ):
  1389. obj.pop("__type")
  1390. return AddedToken(**obj)
  1391. elif isinstance(obj, (list, tuple)):
  1392. return list(convert_added_tokens(o) for o in obj)
  1393. elif isinstance(obj, dict):
  1394. return {k: convert_added_tokens(v) for k, v in obj.items()}
  1395. return obj
  1396. init_kwargs = convert_added_tokens(init_kwargs)
  1397. # Set max length if needed
  1398. if pretrained_model_name_or_path in cls.max_model_input_sizes:
  1399. # if we're using a pretrained model, ensure the tokenizer
  1400. # wont index sequences longer than the number of positional embeddings
  1401. model_max_length = cls.max_model_input_sizes[pretrained_model_name_or_path]
  1402. if model_max_length is not None and isinstance(
  1403. model_max_length, (int, float)
  1404. ):
  1405. init_kwargs["model_max_length"] = min(
  1406. init_kwargs.get("model_max_length", int(1e30)), model_max_length
  1407. )
  1408. added_tokens_file = resolved_vocab_files.pop("added_tokens_file", None)
  1409. # Merge resolved_vocab_files arguments in init_kwargs if not including.
  1410. # Maybe need more ways to load resources.
  1411. for args_name, file_path in resolved_vocab_files.items():
  1412. # when `pretrained_model_name_or_path` is a pretrained model name,
  1413. # use pretrained_init_configuration as `init_kwargs` to init which
  1414. # does not include the vocab file in it, thus add vocab file into
  1415. # args.
  1416. if args_name not in init_kwargs:
  1417. init_kwargs[args_name] = file_path
  1418. # when `pretrained_model_name_or_path` is a pretrained model dir,
  1419. # use tokenizer_config_file.json as `init_kwargs` to init which
  1420. # does include a vocab file path in it. However, if the vocab file
  1421. # path included in json does not exist, such as was deleted, to make
  1422. # it still work, use the vocab file under this dir.
  1423. elif not os.path.isfile(init_kwargs[args_name] or "") and os.path.isfile(
  1424. file_path
  1425. ):
  1426. init_kwargs[args_name] = file_path
  1427. # TODO(zhoushunjie): It's not supportted to load tokenizer.json of hf so far.
  1428. if from_hf_hub and "tokenizer_file" in init_kwargs:
  1429. init_kwargs.pop("tokenizer_file")
  1430. # TODO(guosheng): avoid reduplication of position args and key word args
  1431. tokenizer = cls(*init_args, **init_kwargs)
  1432. chat_template = init_kwargs.pop("chat_template", None)
  1433. if chat_template is not None:
  1434. tokenizer.init_chat_template(chat_template)
  1435. special_tokens_map_file = resolved_vocab_files.pop(
  1436. "special_tokens_map_file", None
  1437. )
  1438. if special_tokens_map_file is not None:
  1439. with open(
  1440. special_tokens_map_file, encoding="utf-8"
  1441. ) as special_tokens_map_handle:
  1442. special_tokens_map = json.load(special_tokens_map_handle)
  1443. for key, value in special_tokens_map.items():
  1444. if key in kwargs and kwargs[key]:
  1445. # This value has already been redefined by the kwargs
  1446. # We keep this new value and ignore the one stored in the special_tokens_map_file
  1447. continue
  1448. if isinstance(value, dict):
  1449. value = AddedToken(**value)
  1450. elif isinstance(value, list):
  1451. value = [
  1452. AddedToken(**token) if isinstance(token, dict) else token
  1453. for token in value
  1454. ]
  1455. setattr(tokenizer, key, value)
  1456. # Add supplementary tokens.
  1457. special_tokens = tokenizer.all_special_tokens
  1458. if added_tokens_file is not None:
  1459. with open(added_tokens_file, encoding="utf-8") as added_tokens_handle:
  1460. added_tok_encoder = json.load(added_tokens_handle)
  1461. # Sort added tokens by index
  1462. added_tok_encoder_sorted = list(
  1463. sorted(added_tok_encoder.items(), key=lambda x: x[1])
  1464. )
  1465. for token, index in added_tok_encoder_sorted:
  1466. if (
  1467. has_tokenizer_file
  1468. and index != len(tokenizer)
  1469. and tokenizer.convert_tokens_to_ids(token) != index
  1470. ):
  1471. # index is the current length of the tokenizer (not in vocabulary)
  1472. raise ValueError(
  1473. f"Wrong index found for {token}: should be {tokenizer.convert_tokens_to_ids(token)} but found "
  1474. f"{index}."
  1475. )
  1476. elif not has_tokenizer_file and index != len(tokenizer):
  1477. # Tokenizer slow: added token cannot already be in the vocabulary so its index needs to be the
  1478. # current length of the tokenizer.
  1479. raise ValueError(
  1480. f"Non-consecutive added token '{token}' found. "
  1481. f"Should have index {len(tokenizer)} but has index {index} in saved vocabulary."
  1482. )
  1483. tokenizer.add_tokens(
  1484. token, special_tokens=bool(token in special_tokens)
  1485. )
  1486. # Check all our special tokens are registered as "no split" token (we don't cut them) and are in the vocab
  1487. added_tokens = tokenizer.sanitize_special_tokens()
  1488. if added_tokens:
  1489. logging.info(
  1490. "Special tokens have been added in the vocabulary, make sure the associated word embeddings are fine-tuned or trained."
  1491. )
  1492. # save all of related things into default root dir
  1493. if pretrained_model_name_or_path in cls.pretrained_init_configuration:
  1494. # tokenizer.save_pretrained(os.path.join(cache_dir, pretrained_model_name_or_path, subfolder))
  1495. tokenizer.save_pretrained(cache_dir)
  1496. if return_tokenizer_file_dir:
  1497. return tokenizer, list(tokenizer_config_file_dir_list)[0]
  1498. return tokenizer
  1499. def save_pretrained(
  1500. self, save_directory, filename_prefix: Optional[str] = None, **kwargs
  1501. ):
  1502. """
  1503. Save tokenizer configuration and related resources to files under
  1504. `save_directory`. The tokenizer configuration would be saved into
  1505. `tokenizer_config_file` indicating file (thus `tokenizer_config.json`),
  1506. and resources would be saved into `resource_files_names` indicating files
  1507. by using `self.save_resources(save_directory)`.
  1508. The `save_directory` can be used in `from_pretrained` as argument value
  1509. of `pretrained_model_name_or_path` to re-load the tokenizer.
  1510. Args:
  1511. save_directory (str): Directory to save files into.
  1512. filename_prefix: (str, optional):
  1513. A prefix to add to the names of the files saved by the tokenizer.
  1514. Example:
  1515. .. code-block::
  1516. from paddlenlp.transformers import BertTokenizer
  1517. tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')
  1518. tokenizer.save_pretrained('trained_model')
  1519. # reload from save_directory
  1520. tokenizer = BertTokenizer.from_pretrained('trained_model')
  1521. """
  1522. assert not os.path.isfile(
  1523. save_directory
  1524. ), "Saving directory ({}) should be a directory, not a file".format(
  1525. save_directory
  1526. )
  1527. os.makedirs(save_directory, exist_ok=True)
  1528. special_tokens_map_file = os.path.join(
  1529. save_directory,
  1530. (filename_prefix + "-" if filename_prefix else "")
  1531. + SPECIAL_TOKENS_MAP_FILE,
  1532. )
  1533. tokenizer_config_file = os.path.join(
  1534. save_directory,
  1535. (filename_prefix + "-" if filename_prefix else "")
  1536. + self.tokenizer_config_file,
  1537. )
  1538. tokenizer_config = copy.deepcopy(self.init_kwargs)
  1539. if len(self.init_inputs) > 0:
  1540. tokenizer_config["init_inputs"] = copy.deepcopy(self.init_inputs)
  1541. for file_id in self.resource_files_names.keys():
  1542. tokenizer_config.pop(file_id, None)
  1543. # Sanitize AddedTokens
  1544. def convert_added_tokens(obj: Union[AddedToken, Any], add_type_field=True):
  1545. if isinstance(obj, AddedToken):
  1546. out = obj.__getstate__()
  1547. if add_type_field:
  1548. out["__type"] = "AddedToken"
  1549. return out
  1550. elif isinstance(obj, (list, tuple)):
  1551. return list(
  1552. convert_added_tokens(o, add_type_field=add_type_field) for o in obj
  1553. )
  1554. elif isinstance(obj, dict):
  1555. return {
  1556. k: convert_added_tokens(v, add_type_field=add_type_field)
  1557. for k, v in obj.items()
  1558. }
  1559. return obj
  1560. # add_type_field=True to allow dicts in the kwargs / differentiate from AddedToken serialization
  1561. tokenizer_config = convert_added_tokens(tokenizer_config, add_type_field=True)
  1562. # Add tokenizer class to the tokenizer config to be able to reload it with from_pretrained
  1563. tokenizer_class = self.__class__.__name__
  1564. tokenizer_config["tokenizer_class"] = tokenizer_class
  1565. with io.open(tokenizer_config_file, "w", encoding="utf-8") as f:
  1566. f.write(json.dumps(tokenizer_config, ensure_ascii=False))
  1567. logging.info(f"tokenizer config file saved in {tokenizer_config_file}")
  1568. # Sanitize AddedTokens in special_tokens_map
  1569. write_dict = convert_added_tokens(
  1570. self.special_tokens_map_extended, add_type_field=False
  1571. )
  1572. with open(special_tokens_map_file, "w", encoding="utf-8") as f:
  1573. f.write(json.dumps(write_dict, ensure_ascii=False))
  1574. logging.info(f"Special tokens file saved in {special_tokens_map_file}")
  1575. file_names = (tokenizer_config_file, special_tokens_map_file)
  1576. save_files = self._save_pretrained(
  1577. save_directory=save_directory,
  1578. file_names=file_names,
  1579. filename_prefix=filename_prefix,
  1580. )
  1581. return save_files
  1582. def _save_pretrained(
  1583. self,
  1584. save_directory: Union[str, os.PathLike],
  1585. file_names: Tuple[str],
  1586. filename_prefix: Optional[str] = None,
  1587. ) -> Tuple[str]:
  1588. """
  1589. Save a tokenizer using the tokenizer format: vocabulary + added tokens.
  1590. """
  1591. save_directory = str(save_directory)
  1592. added_tokens_file = os.path.join(
  1593. save_directory,
  1594. (filename_prefix + "-" if filename_prefix else "") + ADDED_TOKENS_FILE,
  1595. )
  1596. added_vocab = self.get_added_vocab()
  1597. if added_vocab:
  1598. with open(added_tokens_file, "w", encoding="utf-8") as f:
  1599. out_str = json.dumps(added_vocab, ensure_ascii=False)
  1600. f.write(out_str)
  1601. logging.info(f"added tokens file saved in {added_tokens_file}")
  1602. self.save_resources(save_directory)
  1603. return file_names + (added_tokens_file,)
  1604. def tokenize(
  1605. self,
  1606. text: str,
  1607. pair: Optional[str] = None,
  1608. add_special_tokens: bool = False,
  1609. **kwargs,
  1610. ) -> List[str]:
  1611. """
  1612. Converts a string in a sequence of tokens, replacing unknown tokens with the `unk_token`.
  1613. Args:
  1614. text (`str`):
  1615. The sequence to be encoded.
  1616. pair (`str`, *optional*):
  1617. A second sequence to be encoded with the first.
  1618. add_special_tokens (`bool`, *optional*, defaults to `False`):
  1619. Whether or not to add the special tokens associated with the corresponding model.
  1620. kwargs (additional keyword arguments, *optional*):
  1621. Will be passed to the underlying model specific encode method. See details in
  1622. [`~PretrainedTokenizerBase.__call__`]
  1623. Returns:
  1624. `List[str]`: The list of tokens.
  1625. """
  1626. raise NotImplementedError
  1627. def num_special_tokens_to_add(self, pair: bool = False) -> int:
  1628. raise NotImplementedError
  1629. def _get_padding_truncation_strategies(
  1630. self,
  1631. padding=False,
  1632. truncation=False,
  1633. max_length=None,
  1634. pad_to_multiple_of=None,
  1635. verbose=True,
  1636. **kwargs,
  1637. ):
  1638. """
  1639. Find the correct padding/truncation strategy with backward compatibility for old arguments (truncation_strategy
  1640. and pad_to_max_length) and behaviors.
  1641. """
  1642. old_truncation_strategy = kwargs.pop("truncation_strategy", "do_not_truncate")
  1643. old_pad_to_max_length = kwargs.pop("pad_to_max_seq_len", False)
  1644. # Backward compatibility for previous behavior, maybe we should deprecate it:
  1645. # If you only set max_length, it activates truncation for max_length
  1646. if max_length is not None and padding is False and truncation is False:
  1647. if verbose:
  1648. if not self.deprecation_warnings.get(
  1649. "Truncation-not-explicitly-activated", False
  1650. ):
  1651. warnings.warn(
  1652. "Truncation was not explicitly activated but `max_length` is provided a specific value, "
  1653. "please use `truncation=True` to explicitly truncate examples to max length. "
  1654. "Defaulting to 'longest_first' truncation strategy. "
  1655. "If you encode pairs of sequences (GLUE-style) with the tokenizer you can select this strategy "
  1656. "more precisely by providing a specific strategy to `truncation`."
  1657. )
  1658. self.deprecation_warnings["Truncation-not-explicitly-activated"] = True
  1659. truncation = "longest_first"
  1660. # Get padding strategy
  1661. if padding is False and old_pad_to_max_length:
  1662. if verbose:
  1663. warnings.warn(
  1664. "The `pad_to_max_length` argument is deprecated and will be removed in a future version, "
  1665. "use `padding=True` or `padding='longest'` to pad to the longest sequence in the batch, or "
  1666. "use `padding='max_length'` to pad to a max length. In this case, you can give a specific "
  1667. "length with `max_length` (e.g. `max_length=45`) or leave max_length to None to pad to the "
  1668. "maximal input size of the model (e.g. 512 for Bert).",
  1669. FutureWarning,
  1670. )
  1671. if max_length is None:
  1672. padding_strategy = PaddingStrategy.LONGEST
  1673. else:
  1674. padding_strategy = PaddingStrategy.MAX_LENGTH
  1675. elif padding is not False:
  1676. if padding is True:
  1677. if verbose:
  1678. if max_length is not None and (
  1679. truncation is False or truncation == "do_not_truncate"
  1680. ):
  1681. warnings.warn(
  1682. "`max_length` is ignored when `padding`=`True` and there is no truncation strategy. "
  1683. "To pad to max length, use `padding='max_length'`."
  1684. )
  1685. if old_pad_to_max_length is not False:
  1686. warnings.warn(
  1687. "Though `pad_to_max_length` = `True`, it is ignored because `padding`=`True`."
  1688. )
  1689. # Default to pad to the longest sequence in the batch
  1690. padding_strategy = PaddingStrategy.LONGEST
  1691. elif not isinstance(padding, PaddingStrategy):
  1692. padding_strategy = PaddingStrategy(padding)
  1693. elif isinstance(padding, PaddingStrategy):
  1694. padding_strategy = padding
  1695. else:
  1696. padding_strategy = PaddingStrategy.DO_NOT_PAD
  1697. # Get truncation strategy
  1698. if truncation is False and old_truncation_strategy != "do_not_truncate":
  1699. if verbose:
  1700. warnings.warn(
  1701. "The `truncation_strategy` argument is deprecated and will be removed in a future version, "
  1702. "use `truncation=True` to truncate examples to a max length. You can give a specific "
  1703. "length with `max_length` (e.g. `max_length=45`) or leave max_length to None to truncate to the "
  1704. "maximal input size of the model (e.g. 512 for Bert). "
  1705. " If you have pairs of inputs, you can give a specific truncation strategy selected among "
  1706. "`truncation='only_first'` (will only truncate the first sentence in the pairs) "
  1707. "`truncation='only_second'` (will only truncate the second sentence in the pairs) "
  1708. "or `truncation='longest_first'` (will iteratively remove tokens from the longest sentence in the pairs).",
  1709. FutureWarning,
  1710. )
  1711. truncation_strategy = TruncationStrategy(old_truncation_strategy)
  1712. elif truncation is not False and truncation is not None:
  1713. if truncation is True:
  1714. truncation_strategy = (
  1715. TruncationStrategy.LONGEST_FIRST
  1716. ) # Default to truncate the longest sequences in pairs of inputs
  1717. elif not isinstance(truncation, TruncationStrategy):
  1718. truncation_strategy = TruncationStrategy(truncation)
  1719. elif isinstance(truncation, TruncationStrategy):
  1720. truncation_strategy = truncation
  1721. else:
  1722. truncation_strategy = TruncationStrategy.DO_NOT_TRUNCATE
  1723. # Set max length if needed
  1724. if max_length is None:
  1725. if padding_strategy == PaddingStrategy.MAX_LENGTH:
  1726. if self.model_max_length > LARGE_INTEGER:
  1727. if verbose:
  1728. if not self.deprecation_warnings.get(
  1729. "Asking-to-pad-to-max_length", False
  1730. ):
  1731. warnings.warn(
  1732. "Asking to pad to max_length but no maximum length is provided and the model has no predefined maximum length. "
  1733. "Default to no padding."
  1734. )
  1735. self.deprecation_warnings["Asking-to-pad-to-max_length"] = True
  1736. padding_strategy = PaddingStrategy.DO_NOT_PAD
  1737. else:
  1738. max_length = self.model_max_length
  1739. if truncation_strategy != TruncationStrategy.DO_NOT_TRUNCATE:
  1740. if self.model_max_length > LARGE_INTEGER:
  1741. if verbose:
  1742. if not self.deprecation_warnings.get(
  1743. "Asking-to-truncate-to-max_length", False
  1744. ):
  1745. warnings.warn(
  1746. "Asking to truncate to max_length but no maximum length is provided and the model has no predefined maximum length. "
  1747. "Default to no truncation."
  1748. )
  1749. self.deprecation_warnings[
  1750. "Asking-to-truncate-to-max_length"
  1751. ] = True
  1752. truncation_strategy = TruncationStrategy.DO_NOT_TRUNCATE
  1753. else:
  1754. max_length = self.model_max_length
  1755. # Test if we have a padding token
  1756. if padding_strategy != PaddingStrategy.DO_NOT_PAD and (
  1757. not self.pad_token or self.pad_token_id < 0
  1758. ):
  1759. raise ValueError(
  1760. "Asking to pad but the tokenizer does not have a padding token. "
  1761. "Please select a token to use as `pad_token` `(tokenizer.pad_token = tokenizer.eos_token e.g.)` "
  1762. "or add a new pad token via `tokenizer.add_special_tokens({'pad_token': '[PAD]'})`."
  1763. )
  1764. # Check that we will truncate to a multiple of pad_to_multiple_of if both are provided
  1765. if (
  1766. truncation_strategy != TruncationStrategy.DO_NOT_TRUNCATE
  1767. and padding_strategy != PaddingStrategy.DO_NOT_PAD
  1768. and pad_to_multiple_of is not None
  1769. and max_length is not None
  1770. and (max_length % pad_to_multiple_of != 0)
  1771. ):
  1772. raise ValueError(
  1773. f"Truncation and padding are both activated but "
  1774. f"truncation length ({max_length}) is not a multiple of pad_to_multiple_of ({pad_to_multiple_of})."
  1775. )
  1776. return padding_strategy, truncation_strategy, max_length, kwargs
  1777. def __call__(
  1778. self,
  1779. text: Union[str, List[str], List[List[str]]],
  1780. text_pair: Optional[Union[str, List[str], List[List[str]]]] = None,
  1781. max_length: Optional[int] = None,
  1782. stride: int = 0,
  1783. is_split_into_words: Union[bool, str] = False,
  1784. padding: Union[bool, str, PaddingStrategy] = False,
  1785. truncation: Union[bool, str, TruncationStrategy] = False,
  1786. return_position_ids: bool = None,
  1787. return_token_type_ids: Optional[bool] = None,
  1788. return_attention_mask: Optional[bool] = None,
  1789. return_length: bool = False,
  1790. return_overflowing_tokens: bool = False,
  1791. return_special_tokens_mask: bool = False,
  1792. return_dict: bool = True,
  1793. return_offsets_mapping: bool = False,
  1794. add_special_tokens: bool = True,
  1795. pad_to_multiple_of: Optional[int] = None,
  1796. return_tensors: Optional[Union[str, TensorType]] = None,
  1797. verbose: bool = True,
  1798. **kwargs,
  1799. ):
  1800. """
  1801. Performs tokenization and uses the tokenized tokens to prepare model
  1802. inputs. It supports sequence or sequence pair as input, and batch input
  1803. is allowed. `self.encode()` or `self.batch_encode()` would be called
  1804. separately for single or batch input depending on input format and
  1805. `is_split_into_words` argument.
  1806. Args:
  1807. text (str, List[str] or List[List[str]]):
  1808. The sequence or batch of sequences to be processed. One sequence
  1809. is a string or a list of strings depending on whether it has been
  1810. pretokenized. If each sequence is provided as a list of strings
  1811. (pretokenized), you must set `is_split_into_words` as `True` to
  1812. disambiguate with a batch of sequences.
  1813. text_pair (str, List[str] or List[List[str]], optional):
  1814. Same as `text` argument, while it represents for the latter
  1815. sequence of the sequence pair.
  1816. max_length (int, optional):
  1817. If set to a number, will limit the total sequence returned so
  1818. that it has a maximum length. If there are overflowing tokens,
  1819. those overflowing tokens will be added to the returned dictionary
  1820. when `return_overflowing_tokens` is `True`. Defaults to `None`.
  1821. stride (int, optional):
  1822. Only available for batch input of sequence pair and mainly for
  1823. question answering usage. When for QA, `text` represents questions
  1824. and `text_pair` represents contexts. If `stride` is set to a
  1825. positive number, the context will be split into multiple spans
  1826. where `stride` defines the number of (tokenized) tokens to skip
  1827. from the start of one span to get the next span, thus will produce
  1828. a bigger batch than inputs to include all spans. Moreover, 'overflow_to_sample'
  1829. and 'offset_mapping' preserving the original example and position
  1830. information will be added to the returned dictionary. Defaults to 0.
  1831. is_split_into_words (Union[bool, str], optional):
  1832. when the text is words or tokens, `is_split_into_words` should be True or `token`.
  1833. `True`: means that the text should be words which should be tokenized.
  1834. `token`: means that the text should be tokens which already be tokenized, so it should not be tokenized again.
  1835. padding (bool, str or [PaddingStrategy], optional):
  1836. Activates and controls padding. Accepts the following values:
  1837. - `True` or `'longest'`: Pad to the longest sequence in the batch (or no padding if only a single
  1838. sequence if provided).
  1839. - `'max_length'`: Pad to a maximum length specified with the argument `max_length` or to the maximum
  1840. acceptable input length for the model if that argument is not provided.
  1841. - `False` or `'do_not_pad'` (default): No padding (i.e., can output a batch with sequences of different
  1842. lengths).
  1843. Defaults to `False`.
  1844. truncation (bool, str or [TruncationStrategy], optional):
  1845. Activates and controls truncation. Accepts the following values:
  1846. - `True` or `'longest_first'`: Truncate to a maximum length specified with the argument `max_length` or
  1847. to the maximum acceptable input length for the model if that argument is not provided. This will
  1848. truncate token by token, removing a token from the longest sequence in the pair if a pair of
  1849. sequences (or a batch of pairs) is provided.
  1850. - `'only_first'`: Truncate to a maximum length specified with the argument `max_length` or to the
  1851. maximum acceptable input length for the model if that argument is not provided. This will only
  1852. truncate the first sequence of a pair if a pair of sequences (or a batch of pairs) is provided.
  1853. - `'only_second'`: Truncate to a maximum length specified with the argument `max_length` or to the
  1854. maximum acceptable input length for the model if that argument is not provided. This will only
  1855. truncate the second sequence of a pair if a pair of sequences (or a batch of pairs) is provided.
  1856. - `False` or `'do_not_truncate'` (default): No truncation (i.e., can output batch with sequence lengths
  1857. greater than the model maximum admissible input size).
  1858. Defaults to `False`.
  1859. return_position_ids (bool, optional):
  1860. Whether to include tokens position ids in the returned dictionary.
  1861. Defaults to `False`.
  1862. return_token_type_ids (bool, optional):
  1863. Whether to include token type ids in the returned dictionary.
  1864. Defaults to `True`.
  1865. return_attention_mask (bool, optional):
  1866. Whether to include the attention mask in the returned dictionary.
  1867. Defaults to `False`.
  1868. return_length (bool, optional):
  1869. Whether to include the length of each encoded inputs in the
  1870. returned dictionary. Defaults to `False`.
  1871. return_overflowing_tokens (bool, optional):
  1872. Whether to include overflowing token information in the returned
  1873. dictionary. Defaults to `False`.
  1874. return_special_tokens_mask (bool, optional):
  1875. Whether to include special tokens mask information in the returned
  1876. dictionary. Defaults to `False`.
  1877. return_dict (bool, optional):
  1878. Decide the format for returned encoded batch inputs. Only works when
  1879. input is a batch of data.
  1880. ::
  1881. - If True, encoded inputs would be a dictionary like:
  1882. {'input_ids': [[1, 4444, 4385, 1545, 6712],[1, 4444, 4385]],
  1883. 'token_type_ids': [[0, 0, 0, 0, 0], [0, 0, 0]]}
  1884. - If False, encoded inputs would be a list like:
  1885. [{'input_ids': [1, 4444, 4385, 1545, 6712],
  1886. 'token_type_ids': [0, 0, 0, 0, 0]},
  1887. {'input_ids': [1, 4444, 4385], 'token_type_ids': [0, 0, 0]}]
  1888. Defaults to `True`.
  1889. return_offsets_mapping (bool, optional):
  1890. Whether to include the list of pair preserving the index of start
  1891. and end char in original input for each token in the returned
  1892. dictionary. Would be automatically set to `True` when `stride` > 0.
  1893. Defaults to `False`.
  1894. add_special_tokens (bool, optional):
  1895. Whether to add the special tokens associated with the corresponding model
  1896. to the encoded inputs. Defaults to `True`
  1897. pad_to_multiple_of (int, optional):
  1898. If set will pad the sequence to a multiple of the provided value. This is especially useful to enable
  1899. the use of Tensor Cores on NVIDIA hardware with compute capability >= 7.5 (Volta).
  1900. Defaults to `None`.
  1901. return_tensors (str or [TensorType], optional):
  1902. If set, will return tensors instead of list of python integers. Acceptable values are:
  1903. - `'pd'`: Return Paddle `paddle.Tensor` objects.
  1904. - `'np'`: Return Numpy `np.ndarray` objects.
  1905. Defaults to `None`.
  1906. verbose (bool, optional):
  1907. Whether or not to print more information and warnings. Defaults to True.
  1908. Returns:
  1909. dict or list[dict] (for batch input):
  1910. The dict has the following optional items:
  1911. - **input_ids** (list[int] or list[list[int]]): List of token ids to be fed to a model.
  1912. - **position_ids** (list[int] or list[list[int]], optional): List of token position ids to be
  1913. fed to a model. Included when `return_position_ids` is `True`
  1914. - **token_type_ids** (list[int] or list[list[int]], optional): List of token type ids to be
  1915. fed to a model. Included when `return_token_type_ids` is `True`.
  1916. - **attention_mask** (list[int] or list[list[int]], optional): List of integers valued 0 or 1,
  1917. where 0 specifies paddings and should not be attended to by the
  1918. model. Included when `return_attention_mask` is `True`.
  1919. - **seq_len** (int or list[int], optional): The input_ids length. Included when `return_length`
  1920. is `True`.
  1921. - **overflowing_tokens** (list[int] or list[list[int]], optional): List of overflowing tokens.
  1922. Included when if `max_length` is specified and `return_overflowing_tokens`
  1923. is True.
  1924. - **num_truncated_tokens** (int or list[int], optional): The number of overflowing tokens.
  1925. Included when if `max_length` is specified and `return_overflowing_tokens`
  1926. is True.
  1927. - **special_tokens_mask** (list[int] or list[list[int]], optional): List of integers valued 0 or 1,
  1928. with 0 specifying special added tokens and 1 specifying sequence tokens.
  1929. Included when `return_special_tokens_mask` is `True`.
  1930. - **offset_mapping** (list[int], optional): list of pair preserving the
  1931. index of start and end char in original input for each token.
  1932. For a sqecial token, the index pair is `(0, 0)`. Included when
  1933. `return_overflowing_tokens` is True or `stride` > 0.
  1934. - **overflow_to_sample** (int or list[int], optional): Index of example from which this
  1935. feature is generated. Included when `stride` works.
  1936. """
  1937. # Input type checking for clearer error
  1938. def _is_valid_text_input(t):
  1939. if isinstance(t, str):
  1940. # Strings are fine
  1941. return True
  1942. elif isinstance(t, (list, tuple)):
  1943. # List are fine as long as they are...
  1944. if len(t) == 0:
  1945. # ... empty
  1946. return True
  1947. elif isinstance(t[0], str):
  1948. # ... list of strings
  1949. return True
  1950. elif isinstance(t[0], (list, tuple)):
  1951. # ... list with an empty list or with a list of strings
  1952. return len(t[0]) == 0 or isinstance(t[0][0], str)
  1953. else:
  1954. return False
  1955. else:
  1956. return False
  1957. if not _is_valid_text_input(text):
  1958. raise ValueError(
  1959. "text input must of type `str` (single example), `List[str]` (batch or single pretokenized example) "
  1960. "or `List[List[str]]` (batch of pretokenized examples)."
  1961. )
  1962. if text_pair is not None and not _is_valid_text_input(text_pair):
  1963. raise ValueError(
  1964. "text input must of type `str` (single example), `List[str]` (batch or single pretokenized example) "
  1965. "or `List[List[str]]` (batch of pretokenized examples)."
  1966. )
  1967. # check `split_into_words` value
  1968. if isinstance(is_split_into_words, str) and is_split_into_words != "token":
  1969. raise ValueError(
  1970. "the value of `is_split_into_words` should be one of: {True, False, 'token'} but receive: <%s>",
  1971. is_split_into_words,
  1972. )
  1973. if is_split_into_words:
  1974. is_batched = (
  1975. isinstance(text, (list, tuple))
  1976. and text
  1977. and isinstance(text[0], (list, tuple))
  1978. )
  1979. else:
  1980. is_batched = isinstance(text, (list, tuple))
  1981. if is_batched:
  1982. if isinstance(text_pair, str):
  1983. raise TypeError(
  1984. "when tokenizing batches of text, `text_pair` must be a list or tuple with the same length as `text`."
  1985. )
  1986. if text_pair is not None and len(text) != len(text_pair):
  1987. raise ValueError(
  1988. f"batch length of `text`: {len(text)} does not match batch length of `text_pair`: {len(text_pair)}."
  1989. )
  1990. batch_text_or_text_pairs = (
  1991. list(zip(text, text_pair)) if text_pair is not None else text
  1992. )
  1993. return self.batch_encode(
  1994. batch_text_or_text_pairs=batch_text_or_text_pairs,
  1995. max_length=max_length,
  1996. stride=stride,
  1997. is_split_into_words=is_split_into_words,
  1998. padding=padding,
  1999. truncation=truncation,
  2000. return_position_ids=return_position_ids,
  2001. return_token_type_ids=return_token_type_ids,
  2002. return_attention_mask=return_attention_mask,
  2003. return_length=return_length,
  2004. return_overflowing_tokens=return_overflowing_tokens,
  2005. return_special_tokens_mask=return_special_tokens_mask,
  2006. return_dict=return_dict,
  2007. return_offsets_mapping=return_offsets_mapping,
  2008. add_special_tokens=add_special_tokens,
  2009. pad_to_multiple_of=pad_to_multiple_of,
  2010. return_tensors=return_tensors,
  2011. verbose=verbose,
  2012. **kwargs,
  2013. )
  2014. else:
  2015. return self.encode(
  2016. text=text,
  2017. text_pair=text_pair,
  2018. max_length=max_length,
  2019. stride=stride,
  2020. is_split_into_words=is_split_into_words,
  2021. padding=padding,
  2022. truncation=truncation,
  2023. return_position_ids=return_position_ids,
  2024. return_token_type_ids=return_token_type_ids,
  2025. return_attention_mask=return_attention_mask,
  2026. return_length=return_length,
  2027. return_overflowing_tokens=return_overflowing_tokens,
  2028. return_special_tokens_mask=return_special_tokens_mask,
  2029. return_offsets_mapping=return_offsets_mapping,
  2030. add_special_tokens=add_special_tokens,
  2031. pad_to_multiple_of=pad_to_multiple_of,
  2032. return_tensors=return_tensors,
  2033. verbose=verbose,
  2034. **kwargs,
  2035. )
  2036. def encode(
  2037. self,
  2038. text,
  2039. text_pair=None,
  2040. add_special_tokens=True,
  2041. padding: Union[bool, str, PaddingStrategy] = False,
  2042. truncation: Union[bool, str, TruncationStrategy] = False,
  2043. max_length: Optional[int] = None,
  2044. stride: int = 0,
  2045. is_split_into_words: bool = False,
  2046. pad_to_multiple_of: Optional[int] = None,
  2047. return_tensors: Optional[Union[str, TensorType]] = None,
  2048. return_token_type_ids: Optional[bool] = None,
  2049. return_attention_mask: Optional[bool] = None,
  2050. return_overflowing_tokens: bool = False,
  2051. return_special_tokens_mask: bool = False,
  2052. return_offsets_mapping: bool = False,
  2053. return_length: bool = False,
  2054. verbose: bool = True,
  2055. return_position_ids=None,
  2056. **kwargs,
  2057. ) -> BatchEncoding:
  2058. """
  2059. Tokenize and prepare for the model a sequence or a pair of sequences.
  2060. Args:
  2061. text (`str`, `List[str]` or `List[int]`):
  2062. The first sequence to be encoded. This can be a string, a list of strings (tokenized string using the
  2063. `tokenize` method) or a list of integers (tokenized string ids using the `convert_tokens_to_ids`
  2064. method).
  2065. text_pair (`str`, `List[str]` or `List[int]`, *optional*):
  2066. Optional second sequence to be encoded. This can be a string, a list of strings (tokenized string using
  2067. the `tokenize` method) or a list of integers (tokenized string ids using the `convert_tokens_to_ids`
  2068. method).
  2069. """
  2070. # Backward compatibility for 'max_seq_len'
  2071. old_max_seq_len = kwargs.get("max_seq_len", None)
  2072. if max_length is None and old_max_seq_len:
  2073. if verbose:
  2074. warnings.warn(
  2075. "The `max_seq_len` argument is deprecated and will be removed in a future version, "
  2076. "please use `max_length` instead.",
  2077. FutureWarning,
  2078. )
  2079. max_length = old_max_seq_len
  2080. # Backward compatibility for 'truncation_strategy', 'pad_to_max_length'
  2081. padding_strategy, truncation_strategy, max_length, kwargs = (
  2082. self._get_padding_truncation_strategies(
  2083. padding=padding,
  2084. truncation=truncation,
  2085. max_length=max_length,
  2086. pad_to_multiple_of=pad_to_multiple_of,
  2087. verbose=verbose,
  2088. **kwargs,
  2089. )
  2090. )
  2091. return self._encode_plus(
  2092. text=text,
  2093. text_pair=text_pair,
  2094. add_special_tokens=add_special_tokens,
  2095. padding_strategy=padding_strategy,
  2096. truncation_strategy=truncation_strategy,
  2097. max_length=max_length,
  2098. stride=stride,
  2099. is_split_into_words=is_split_into_words,
  2100. pad_to_multiple_of=pad_to_multiple_of,
  2101. return_tensors=return_tensors,
  2102. return_position_ids=return_position_ids,
  2103. return_token_type_ids=return_token_type_ids,
  2104. return_attention_mask=return_attention_mask,
  2105. return_overflowing_tokens=return_overflowing_tokens,
  2106. return_special_tokens_mask=return_special_tokens_mask,
  2107. return_offsets_mapping=return_offsets_mapping,
  2108. return_length=return_length,
  2109. verbose=verbose,
  2110. **kwargs,
  2111. )
  2112. def encode_plus(
  2113. self,
  2114. text: Union[TextInput, PreTokenizedInput, EncodedInput],
  2115. text_pair: Optional[Union[TextInput, PreTokenizedInput, EncodedInput]] = None,
  2116. add_special_tokens: bool = True,
  2117. padding: Union[bool, str, PaddingStrategy] = False,
  2118. truncation: Union[bool, str, TruncationStrategy] = None,
  2119. max_length: Optional[int] = None,
  2120. stride: int = 0,
  2121. is_split_into_words: bool = False,
  2122. pad_to_multiple_of: Optional[int] = None,
  2123. return_tensors: Optional[Union[str, TensorType]] = None,
  2124. return_token_type_ids: Optional[bool] = None,
  2125. return_attention_mask: Optional[bool] = None,
  2126. return_overflowing_tokens: bool = False,
  2127. return_special_tokens_mask: bool = False,
  2128. return_offsets_mapping: bool = False,
  2129. return_length: bool = False,
  2130. verbose: bool = True,
  2131. **kwargs,
  2132. ) -> BatchEncoding:
  2133. """
  2134. Tokenize and prepare for the model a sequence or a pair of sequences.
  2135. <Tip warning={true}>
  2136. This method is deprecated, `__call__` should be used instead.
  2137. </Tip>
  2138. Args:
  2139. text (`str`, `List[str]` or `List[int]` (the latter only for not-fast tokenizers)):
  2140. The first sequence to be encoded. This can be a string, a list of strings (tokenized string using the
  2141. `tokenize` method) or a list of integers (tokenized string ids using the `convert_tokens_to_ids`
  2142. method).
  2143. text_pair (`str`, `List[str]` or `List[int]`, *optional*):
  2144. Optional second sequence to be encoded. This can be a string, a list of strings (tokenized string using
  2145. the `tokenize` method) or a list of integers (tokenized string ids using the `convert_tokens_to_ids`
  2146. method).
  2147. """
  2148. # Backward compatibility for 'truncation_strategy', 'pad_to_max_length'
  2149. padding_strategy, truncation_strategy, max_length, kwargs = (
  2150. self._get_padding_truncation_strategies(
  2151. padding=padding,
  2152. truncation=truncation,
  2153. max_length=max_length,
  2154. pad_to_multiple_of=pad_to_multiple_of,
  2155. verbose=verbose,
  2156. **kwargs,
  2157. )
  2158. )
  2159. return self._encode_plus(
  2160. text=text,
  2161. text_pair=text_pair,
  2162. add_special_tokens=add_special_tokens,
  2163. padding_strategy=padding_strategy,
  2164. truncation_strategy=truncation_strategy,
  2165. max_length=max_length,
  2166. stride=stride,
  2167. is_split_into_words=is_split_into_words,
  2168. pad_to_multiple_of=pad_to_multiple_of,
  2169. return_tensors=return_tensors,
  2170. return_token_type_ids=return_token_type_ids,
  2171. return_attention_mask=return_attention_mask,
  2172. return_overflowing_tokens=return_overflowing_tokens,
  2173. return_special_tokens_mask=return_special_tokens_mask,
  2174. return_offsets_mapping=return_offsets_mapping,
  2175. return_length=return_length,
  2176. verbose=verbose,
  2177. **kwargs,
  2178. )
  2179. def _encode_plus(
  2180. self,
  2181. text: Union[TextInput, PreTokenizedInput, EncodedInput],
  2182. text_pair: Optional[Union[TextInput, PreTokenizedInput, EncodedInput]] = None,
  2183. add_special_tokens: bool = True,
  2184. padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD,
  2185. truncation_strategy: TruncationStrategy = TruncationStrategy.DO_NOT_TRUNCATE,
  2186. max_length: Optional[int] = None,
  2187. stride: int = 0,
  2188. is_split_into_words: bool = False,
  2189. pad_to_multiple_of: Optional[int] = None,
  2190. return_position_ids: Optional[bool] = None,
  2191. return_tensors: Optional[Union[str, TensorType]] = None,
  2192. return_token_type_ids: Optional[bool] = None,
  2193. return_attention_mask: Optional[bool] = None,
  2194. return_overflowing_tokens: bool = False,
  2195. return_special_tokens_mask: bool = False,
  2196. return_offsets_mapping: bool = False,
  2197. return_length: bool = False,
  2198. verbose: bool = True,
  2199. **kwargs,
  2200. ) -> BatchEncoding:
  2201. raise NotImplementedError
  2202. def batch_encode(
  2203. self,
  2204. batch_text_or_text_pairs: Union[
  2205. List[TextInput],
  2206. List[TextInputPair],
  2207. List[PreTokenizedInput],
  2208. List[PreTokenizedInputPair],
  2209. List[EncodedInput],
  2210. List[EncodedInputPair],
  2211. ],
  2212. max_length=None,
  2213. stride: int = 0,
  2214. is_split_into_words: bool = False,
  2215. padding: Union[bool, str, PaddingStrategy] = False,
  2216. truncation: Union[bool, str, TruncationStrategy] = False,
  2217. return_position_ids=None,
  2218. # TODO(wj-mcat): keep align with `encode` method
  2219. return_token_type_ids=None,
  2220. return_attention_mask=None,
  2221. return_length=False,
  2222. return_overflowing_tokens=False,
  2223. return_special_tokens_mask=False,
  2224. return_dict=True,
  2225. return_offsets_mapping=False,
  2226. add_special_tokens=True,
  2227. pad_to_multiple_of: Optional[int] = None,
  2228. return_tensors: Optional[Union[str, TensorType]] = None,
  2229. verbose: bool = True,
  2230. **kwargs,
  2231. ) -> BatchEncoding:
  2232. """
  2233. Performs tokenization and uses the tokenized tokens to prepare model
  2234. inputs. It supports batch inputs of sequence or sequence pair.
  2235. Args:
  2236. batch_text_or_text_pairs (list):
  2237. The element of list can be sequence or sequence pair, and the
  2238. sequence is a string or a list of strings depending on whether
  2239. it has been pretokenized. If each sequence is provided as a list
  2240. of strings (pretokenized), you must set `is_split_into_words` as
  2241. `True` to disambiguate with a sequence pair.
  2242. Returns:
  2243. dict or list[dict]:
  2244. The dict has the following optional items:
  2245. """
  2246. # Backward compatibility for 'max_seq_len'
  2247. old_max_seq_len = kwargs.get("max_seq_len", None)
  2248. if max_length is None and old_max_seq_len:
  2249. if verbose:
  2250. warnings.warn(
  2251. "The `max_seq_len` argument is deprecated and will be removed in a future version, "
  2252. "please use `max_length` instead.",
  2253. FutureWarning,
  2254. )
  2255. max_length = old_max_seq_len
  2256. # Backward compatibility for 'truncation_strategy', 'pad_to_max_length'
  2257. padding_strategy, truncation_strategy, max_length, kwargs = (
  2258. self._get_padding_truncation_strategies(
  2259. padding=padding,
  2260. truncation=truncation,
  2261. max_length=max_length,
  2262. pad_to_multiple_of=pad_to_multiple_of,
  2263. verbose=verbose,
  2264. **kwargs,
  2265. )
  2266. )
  2267. return self._batch_encode_plus(
  2268. batch_text_or_text_pairs=batch_text_or_text_pairs,
  2269. add_special_tokens=add_special_tokens,
  2270. padding_strategy=padding_strategy,
  2271. truncation_strategy=truncation_strategy,
  2272. max_length=max_length,
  2273. stride=stride,
  2274. is_split_into_words=is_split_into_words,
  2275. pad_to_multiple_of=pad_to_multiple_of,
  2276. return_tensors=return_tensors,
  2277. return_position_ids=return_position_ids,
  2278. return_token_type_ids=return_token_type_ids,
  2279. return_attention_mask=return_attention_mask,
  2280. return_overflowing_tokens=return_overflowing_tokens,
  2281. return_special_tokens_mask=return_special_tokens_mask,
  2282. return_dict=return_dict,
  2283. return_offsets_mapping=return_offsets_mapping,
  2284. return_length=return_length,
  2285. verbose=verbose,
  2286. **kwargs,
  2287. )
  2288. def _batch_encode_plus(
  2289. self,
  2290. batch_text_or_text_pairs: Union[
  2291. List[TextInput],
  2292. List[TextInputPair],
  2293. List[PreTokenizedInput],
  2294. List[PreTokenizedInputPair],
  2295. List[EncodedInput],
  2296. List[EncodedInputPair],
  2297. ],
  2298. add_special_tokens: bool = True,
  2299. padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD,
  2300. truncation_strategy: TruncationStrategy = TruncationStrategy.DO_NOT_TRUNCATE,
  2301. max_length: Optional[int] = None,
  2302. stride: int = 0,
  2303. is_split_into_words: bool = False,
  2304. pad_to_multiple_of: Optional[int] = None,
  2305. return_position_ids: Optional[bool] = None,
  2306. return_tensors: Optional[Union[str, TensorType]] = None,
  2307. return_token_type_ids: Optional[bool] = None,
  2308. return_attention_mask: Optional[bool] = None,
  2309. return_overflowing_tokens: bool = False,
  2310. return_special_tokens_mask: bool = False,
  2311. return_dict: bool = True,
  2312. return_offsets_mapping: bool = False,
  2313. return_length: bool = False,
  2314. verbose: bool = True,
  2315. **kwargs,
  2316. ) -> BatchEncoding:
  2317. raise NotImplementedError
  2318. def pad(
  2319. self,
  2320. encoded_inputs: Union[
  2321. BatchEncoding,
  2322. List[BatchEncoding],
  2323. Dict[str, EncodedInput],
  2324. Dict[str, List[EncodedInput]],
  2325. List[Dict[str, EncodedInput]],
  2326. ],
  2327. padding: Union[bool, str, PaddingStrategy] = True,
  2328. max_length: Optional[int] = None,
  2329. pad_to_multiple_of: Optional[int] = None,
  2330. return_attention_mask: Optional[bool] = None,
  2331. return_tensors: Optional[Union[str, TensorType]] = None,
  2332. verbose: bool = True,
  2333. ) -> BatchEncoding:
  2334. """
  2335. Pad a single encoded input or a batch of encoded inputs up to predefined length or to the max sequence length
  2336. in the batch.
  2337. Padding side (left/right) padding token ids are defined at the tokenizer level (with `self.padding_side`,
  2338. `self.pad_token_id` and `self.pad_token_type_id`)
  2339. <Tip>
  2340. If the `encoded_inputs` passed are dictionary of numpy arrays, Paddle tensors, the
  2341. result will use the same type unless you provide a different tensor type with `return_tensors`.
  2342. </Tip>
  2343. Args:
  2344. encoded_inputs ([`BatchEncoding`], list of [`BatchEncoding`], `Dict[str, List[int]]`, `Dict[str, List[List[int]]` or `List[Dict[str, List[int]]]`):
  2345. Tokenized inputs. Can represent one input ([`BatchEncoding`] or `Dict[str, List[int]]`) or a batch of
  2346. tokenized inputs (list of [`BatchEncoding`], *Dict[str, List[List[int]]]* or *List[Dict[str,
  2347. List[int]]]*) so you can use this method during preprocessing as well as in a Paddle Dataloader
  2348. collate function.
  2349. Instead of `List[int]` you can have tensors (numpy arrays, Paddle tensors), see
  2350. the note above for the return type.
  2351. padding (`bool`, `str` or [`PaddingStrategy`], *optional*, defaults to `True`):
  2352. Select a strategy to pad the returned sequences (according to the model's padding side and padding
  2353. index) among:
  2354. - `True` or `'longest'`: Pad to the longest sequence in the batch (or no padding if only a single
  2355. sequence if provided).
  2356. - `'max_length'`: Pad to a maximum length specified with the argument `max_length` or to the maximum
  2357. acceptable input length for the model if that argument is not provided.
  2358. - `False` or `'do_not_pad'` (default): No padding (i.e., can output a batch with sequences of different
  2359. lengths).
  2360. max_length (`int`, *optional*):
  2361. Maximum length of the returned list and optionally padding length (see above).
  2362. pad_to_multiple_of (`int`, *optional*):
  2363. If set will pad the sequence to a multiple of the provided value.
  2364. This is especially useful to enable the use of Tensor Cores on NVIDIA hardware with compute capability
  2365. >= 7.5 (Volta).
  2366. return_attention_mask (`bool`, *optional*):
  2367. Whether to return the attention mask. If left to the default, will return the attention mask according
  2368. to the specific tokenizer's default, defined by the `return_outputs` attribute.
  2369. [What are attention masks?](../glossary#attention-mask)
  2370. return_tensors (`str` or [`TensorType`], *optional*):
  2371. If set, will return tensors instead of list of python integers. Acceptable values are:
  2372. - `'pd'`: Return Paddle `paddle.Tensor` objects.
  2373. - `'np'`: Return Numpy `np.ndarray` objects.
  2374. verbose (`bool`, *optional*, defaults to `True`):
  2375. Whether or not to print more information and warnings.
  2376. """
  2377. import paddle
  2378. # If we have a list of dicts, let's convert it in a dict of lists
  2379. if isinstance(encoded_inputs, (list, tuple)) and isinstance(
  2380. encoded_inputs[0], (dict, BatchEncoding)
  2381. ):
  2382. encoded_inputs = {
  2383. key: [example[key] for example in encoded_inputs]
  2384. for key in encoded_inputs[0].keys()
  2385. }
  2386. # The model's main input name, usually `input_ids`, has be passed for padding
  2387. if self.model_input_names[0] not in encoded_inputs:
  2388. raise ValueError(
  2389. "You should supply an encoding or a list of encodings to this method "
  2390. f"that includes {self.model_input_names[0]}, but you provided {list(encoded_inputs.keys())}"
  2391. )
  2392. required_input = encoded_inputs[self.model_input_names[0]]
  2393. if not required_input:
  2394. if return_attention_mask:
  2395. encoded_inputs["attention_mask"] = []
  2396. return encoded_inputs
  2397. # If we have Paddle/NumPy tensors/arrays as inputs, we cast them as python objects
  2398. # and rebuild them afterwards if no return_tensors is specified
  2399. first_element = required_input[0]
  2400. if isinstance(first_element, (list, tuple)):
  2401. # first_element might be an empty list/tuple in some edge cases so we grab the first non empty element.
  2402. for item in required_input:
  2403. if len(item) != 0:
  2404. first_element = item[0]
  2405. break
  2406. # At this state, if `first_element` is still a list/tuple, it's an empty one so there is nothing to do.
  2407. if not isinstance(first_element, (int, list, tuple)):
  2408. if isinstance(first_element, paddle.Tensor):
  2409. return_tensors = "pd" if return_tensors is None else return_tensors
  2410. else:
  2411. raise ValueError(
  2412. f"type of {first_element} unknown: {type(first_element)}. "
  2413. f"Should be either python or paddle object."
  2414. )
  2415. for key, value in encoded_inputs.items():
  2416. encoded_inputs[key] = to_py_obj(value)
  2417. # Convert padding_strategy in PaddingStrategy
  2418. padding_strategy, _, max_length, _ = self._get_padding_truncation_strategies(
  2419. padding=padding, max_length=max_length, verbose=verbose
  2420. )
  2421. required_input = encoded_inputs[self.model_input_names[0]]
  2422. if required_input and not isinstance(required_input[0], (list, tuple)):
  2423. encoded_inputs = self._pad(
  2424. encoded_inputs,
  2425. max_length=max_length,
  2426. padding_strategy=padding_strategy,
  2427. pad_to_multiple_of=pad_to_multiple_of,
  2428. return_attention_mask=return_attention_mask,
  2429. )
  2430. return BatchEncoding(encoded_inputs, tensor_type=return_tensors)
  2431. batch_size = len(required_input)
  2432. assert all(
  2433. len(v) == batch_size for v in encoded_inputs.values()
  2434. ), "Some items in the output dictionary have a different batch size than others."
  2435. if padding_strategy == PaddingStrategy.LONGEST:
  2436. max_length = max(len(inputs) for inputs in required_input)
  2437. padding_strategy = PaddingStrategy.MAX_LENGTH
  2438. batch_outputs = {}
  2439. for i in range(batch_size):
  2440. inputs = dict((k, v[i]) for k, v in encoded_inputs.items())
  2441. outputs = self._pad(
  2442. inputs,
  2443. max_length=max_length,
  2444. padding_strategy=padding_strategy,
  2445. pad_to_multiple_of=pad_to_multiple_of,
  2446. return_attention_mask=return_attention_mask,
  2447. )
  2448. for key, value in outputs.items():
  2449. if key not in batch_outputs:
  2450. batch_outputs[key] = []
  2451. batch_outputs[key].append(value)
  2452. return BatchEncoding(batch_outputs, tensor_type=return_tensors)
  2453. def create_token_type_ids_from_sequences(
  2454. self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
  2455. ) -> List[int]:
  2456. """
  2457. Create the token type IDs corresponding to the sequences passed. [What are token type
  2458. IDs?](../glossary#token-type-ids)
  2459. Should be overridden in a subclass if the model has a special way of building those.
  2460. Args:
  2461. token_ids_0 (`List[int]`): The first tokenized sequence.
  2462. token_ids_1 (`List[int]`, *optional*): The second tokenized sequence.
  2463. Returns:
  2464. `List[int]`: The token type ids.
  2465. """
  2466. if token_ids_1 is None:
  2467. return len(token_ids_0) * [0]
  2468. return [0] * len(token_ids_0) + [1] * len(token_ids_1)
  2469. def build_inputs_with_special_tokens(
  2470. self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
  2471. ) -> List[int]:
  2472. """
  2473. Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
  2474. adding special tokens.
  2475. This implementation does not add special tokens and this method should be overridden in a subclass.
  2476. Args:
  2477. token_ids_0 (`List[int]`): The first tokenized sequence.
  2478. token_ids_1 (`List[int]`, *optional*): The second tokenized sequence.
  2479. Returns:
  2480. `List[int]`: The model input with special tokens.
  2481. """
  2482. if token_ids_1 is None:
  2483. return token_ids_0
  2484. return token_ids_0 + token_ids_1
  2485. def build_offset_mapping_with_special_tokens(
  2486. self, offset_mapping_0, offset_mapping_1=None
  2487. ):
  2488. """
  2489. Build offset map from a pair of offset map by concatenating and adding offsets of special tokens.
  2490. Should be overridden in a subclass if the model has a special way of building those.
  2491. Args:
  2492. offset_mapping_0 (List[tuple]):
  2493. List of char offsets to which the special tokens will be added.
  2494. offset_mapping_1 (List[tuple], optional):
  2495. Optional second list of char offsets for offset mapping pairs.
  2496. Returns:
  2497. List[tuple]: List of char offsets with the appropriate offsets of special tokens.
  2498. """
  2499. if offset_mapping_1 is None:
  2500. return offset_mapping_0
  2501. return offset_mapping_0 + offset_mapping_1
  2502. def prepare_for_model(
  2503. self,
  2504. ids,
  2505. pair_ids=None,
  2506. padding: Union[bool, str, PaddingStrategy] = False,
  2507. truncation: Union[bool, str, TruncationStrategy] = False,
  2508. max_length: Optional[int] = None,
  2509. stride: int = 0,
  2510. pad_to_multiple_of: Optional[int] = None,
  2511. return_tensors: Optional[Union[str, TensorType]] = None,
  2512. return_position_ids=None,
  2513. return_token_type_ids: Optional[bool] = None,
  2514. return_attention_mask: Optional[bool] = None,
  2515. return_length=False,
  2516. return_overflowing_tokens=False,
  2517. return_special_tokens_mask=False,
  2518. return_offsets_mapping=False,
  2519. add_special_tokens=True,
  2520. verbose: bool = True,
  2521. prepend_batch_axis: bool = False,
  2522. **kwargs,
  2523. ):
  2524. """
  2525. Performs tokenization and uses the tokenized tokens to prepare model
  2526. inputs. It supports sequence or sequence pair as input, and batch input
  2527. is not allowed.
  2528. """
  2529. padding_strategy, truncation_strategy, max_length, kwargs = (
  2530. self._get_padding_truncation_strategies(
  2531. padding=padding,
  2532. truncation=truncation,
  2533. max_length=max_length,
  2534. pad_to_multiple_of=pad_to_multiple_of,
  2535. verbose=verbose,
  2536. **kwargs,
  2537. )
  2538. )
  2539. pair = bool(pair_ids is not None)
  2540. len_ids = len(ids)
  2541. len_pair_ids = len(pair_ids) if pair else 0
  2542. if return_token_type_ids and not add_special_tokens:
  2543. raise ValueError(
  2544. "Asking to return token_type_ids while setting add_special_tokens to False "
  2545. "results in an undefined behavior. Please set add_special_tokens to True or "
  2546. "set return_token_type_ids to None."
  2547. )
  2548. if (
  2549. return_overflowing_tokens
  2550. and truncation_strategy == TruncationStrategy.LONGEST_FIRST
  2551. and pair_ids is not None
  2552. ):
  2553. raise ValueError(
  2554. "Not possible to return overflowing tokens for pair of sequences with the "
  2555. "`longest_first`. Please select another truncation strategy than `longest_first`, "
  2556. "for instance `only_second` or `only_first`."
  2557. )
  2558. # Load from model defaults
  2559. if return_token_type_ids is None:
  2560. return_token_type_ids = "token_type_ids" in self.model_input_names
  2561. if return_attention_mask is None:
  2562. return_attention_mask = "attention_mask" in self.model_input_names
  2563. if return_position_ids is None:
  2564. return_position_ids = "position_ids" in self.model_input_names
  2565. encoded_inputs = {}
  2566. # Truncation: Handle max sequence length
  2567. total_len = (
  2568. len_ids
  2569. + len_pair_ids
  2570. + (self.num_special_tokens_to_add(pair=pair) if add_special_tokens else 0)
  2571. )
  2572. overflowing_tokens = []
  2573. if (
  2574. truncation_strategy != TruncationStrategy.DO_NOT_TRUNCATE
  2575. and max_length
  2576. and total_len > max_length
  2577. ):
  2578. ids, pair_ids, overflowing_tokens = self.truncate_sequences(
  2579. ids,
  2580. pair_ids=pair_ids,
  2581. num_tokens_to_remove=total_len - max_length,
  2582. truncation_strategy=truncation_strategy,
  2583. stride=stride,
  2584. )
  2585. if return_overflowing_tokens:
  2586. encoded_inputs["overflowing_tokens"] = overflowing_tokens
  2587. encoded_inputs["num_truncated_tokens"] = total_len - max_length
  2588. # Add special tokens
  2589. if add_special_tokens:
  2590. sequence = self.build_inputs_with_special_tokens(ids, pair_ids)
  2591. token_type_ids = self.create_token_type_ids_from_sequences(ids, pair_ids)
  2592. else:
  2593. sequence = ids + pair_ids if pair else ids
  2594. token_type_ids = [0] * len(ids) + ([0] * len(pair_ids) if pair else [])
  2595. # Build output dictionnary
  2596. encoded_inputs["input_ids"] = sequence
  2597. if return_token_type_ids:
  2598. encoded_inputs["token_type_ids"] = token_type_ids
  2599. if return_special_tokens_mask:
  2600. if add_special_tokens:
  2601. encoded_inputs["special_tokens_mask"] = self.get_special_tokens_mask(
  2602. ids, pair_ids
  2603. )
  2604. else:
  2605. encoded_inputs["special_tokens_mask"] = [0] * len(sequence)
  2606. if return_offsets_mapping and "text" in kwargs and "text_pair" in kwargs:
  2607. text = kwargs.pop("text")
  2608. text_pair = kwargs.pop("text_pair")
  2609. token_offset_mapping = self.get_offset_mapping(text)
  2610. token_pair_offset_mapping = (
  2611. self.get_offset_mapping(text_pair) if text_pair is not None else None
  2612. )
  2613. if max_length and total_len > max_length:
  2614. token_offset_mapping, token_pair_offset_mapping, _ = (
  2615. self.truncate_sequences(
  2616. token_offset_mapping,
  2617. pair_ids=token_pair_offset_mapping,
  2618. num_tokens_to_remove=total_len - max_length,
  2619. truncation_strategy=truncation_strategy,
  2620. stride=stride,
  2621. )
  2622. )
  2623. if add_special_tokens:
  2624. offset_mapping = self.build_offset_mapping_with_special_tokens(
  2625. token_offset_mapping, token_pair_offset_mapping
  2626. )
  2627. else:
  2628. offset_mapping = (
  2629. token_offset_mapping + token_pair_offset_mapping
  2630. if token_pair_offset_mapping
  2631. else token_offset_mapping
  2632. )
  2633. encoded_inputs["offset_mapping"] = offset_mapping
  2634. # Check lengths
  2635. self._eventual_warn_about_too_long_sequence(
  2636. encoded_inputs["input_ids"], max_length, verbose
  2637. )
  2638. if return_position_ids:
  2639. encoded_inputs["position_ids"] = list(
  2640. range(len(encoded_inputs["input_ids"]))
  2641. )
  2642. if padding_strategy != PaddingStrategy.DO_NOT_PAD or return_attention_mask:
  2643. encoded_inputs = self.pad(
  2644. encoded_inputs,
  2645. max_length=max_length,
  2646. padding=padding_strategy.value,
  2647. pad_to_multiple_of=pad_to_multiple_of,
  2648. return_attention_mask=return_attention_mask,
  2649. )
  2650. if return_length:
  2651. encoded_inputs["length"] = len(encoded_inputs["input_ids"])
  2652. # for compatibility
  2653. encoded_inputs["seq_len"] = encoded_inputs["length"]
  2654. batch_outputs = BatchEncoding(
  2655. encoded_inputs,
  2656. tensor_type=return_tensors,
  2657. prepend_batch_axis=prepend_batch_axis,
  2658. )
  2659. return batch_outputs
  2660. def truncate_sequences(
  2661. self,
  2662. ids: List[int],
  2663. pair_ids: Optional[List[int]] = None,
  2664. num_tokens_to_remove: int = 0,
  2665. truncation_strategy: Union[str, TruncationStrategy] = "longest_first",
  2666. stride: int = 0,
  2667. ) -> Tuple[List[int], List[int], List[int]]:
  2668. """
  2669. Truncates a sequence pair in-place following the strategy.
  2670. Args:
  2671. ids (`List[int]`):
  2672. Tokenized input ids of the first sequence. Can be obtained from a string by chaining the `tokenize` and
  2673. `convert_tokens_to_ids` methods.
  2674. pair_ids (`List[int]`, *optional*):
  2675. Tokenized input ids of the second sequence. Can be obtained from a string by chaining the `tokenize`
  2676. and `convert_tokens_to_ids` methods.
  2677. num_tokens_to_remove (`int`, *optional*, defaults to 0):
  2678. Number of tokens to remove using the truncation strategy.
  2679. truncation_strategy (`str` or [`TruncationStrategy`], *optional*, defaults to `False`):
  2680. The strategy to follow for truncation. Can be:
  2681. - `'longest_first'`: Truncate to a maximum length specified with the argument `max_length` or to the
  2682. maximum acceptable input length for the model if that argument is not provided. This will truncate
  2683. token by token, removing a token from the longest sequence in the pair if a pair of sequences (or a
  2684. batch of pairs) is provided.
  2685. - `'only_first'`: Truncate to a maximum length specified with the argument `max_length` or to the
  2686. maximum acceptable input length for the model if that argument is not provided. This will only
  2687. truncate the first sequence of a pair if a pair of sequences (or a batch of pairs) is provided.
  2688. - `'only_second'`: Truncate to a maximum length specified with the argument `max_length` or to the
  2689. maximum acceptable input length for the model if that argument is not provided. This will only
  2690. truncate the second sequence of a pair if a pair of sequences (or a batch of pairs) is provided.
  2691. - `'do_not_truncate'` (default): No truncation (i.e., can output batch with sequence lengths greater
  2692. than the model maximum admissible input size).
  2693. stride (`int`, *optional*, defaults to 0):
  2694. If set to a positive number, the overflowing tokens returned will contain some tokens from the main
  2695. sequence returned. The value of this argument defines the number of additional tokens.
  2696. Returns:
  2697. `Tuple[List[int], List[int], List[int]]`: The truncated `ids`, the truncated `pair_ids` and the list of
  2698. overflowing tokens. Note: The *longest_first* strategy returns empty list of overflowing tokens if a pair
  2699. of sequences (or a batch of pairs) is provided.
  2700. """
  2701. if num_tokens_to_remove <= 0:
  2702. return ids, pair_ids, []
  2703. if not isinstance(truncation_strategy, TruncationStrategy):
  2704. truncation_strategy = TruncationStrategy(truncation_strategy)
  2705. overflowing_tokens = []
  2706. if truncation_strategy == TruncationStrategy.ONLY_FIRST or (
  2707. truncation_strategy == TruncationStrategy.LONGEST_FIRST and pair_ids is None
  2708. ):
  2709. if len(ids) > num_tokens_to_remove:
  2710. window_len = min(len(ids), stride + num_tokens_to_remove)
  2711. if self.truncation_side == "left":
  2712. overflowing_tokens = ids[:window_len]
  2713. ids = ids[num_tokens_to_remove:]
  2714. elif self.truncation_side == "right":
  2715. overflowing_tokens = ids[-window_len:]
  2716. ids = ids[:-num_tokens_to_remove]
  2717. else:
  2718. raise ValueError(
  2719. f"invalid truncation strategy: {self.truncation_side}, use 'left' or 'right'."
  2720. )
  2721. else:
  2722. error_msg = (
  2723. f"We need to remove {num_tokens_to_remove} to truncate the input "
  2724. f"but the first sequence has a length {len(ids)}. "
  2725. )
  2726. if truncation_strategy == TruncationStrategy.ONLY_FIRST:
  2727. error_msg = (
  2728. error_msg + "Please select another truncation strategy than "
  2729. f"{truncation_strategy}, for instance 'longest_first' or 'only_second'."
  2730. )
  2731. logging.error(error_msg)
  2732. elif truncation_strategy == TruncationStrategy.LONGEST_FIRST:
  2733. warnings.warn(
  2734. f"Be aware, overflowing tokens are not returned for the setting you have chosen,"
  2735. f" i.e. sequence pairs with the '{TruncationStrategy.LONGEST_FIRST.value}' "
  2736. f"truncation strategy. So the returned list will always be empty even if some "
  2737. f"tokens have been removed."
  2738. )
  2739. for _ in range(num_tokens_to_remove):
  2740. if pair_ids is None or len(ids) > len(pair_ids):
  2741. if self.truncation_side == "right":
  2742. ids = ids[:-1]
  2743. elif self.truncation_side == "left":
  2744. ids = ids[1:]
  2745. else:
  2746. raise ValueError(
  2747. "invalid truncation strategy:" + str(self.truncation_side)
  2748. )
  2749. else:
  2750. if self.truncation_side == "right":
  2751. pair_ids = pair_ids[:-1]
  2752. elif self.truncation_side == "left":
  2753. pair_ids = pair_ids[1:]
  2754. else:
  2755. raise ValueError(
  2756. "invalid truncation strategy:" + str(self.truncation_side)
  2757. )
  2758. elif (
  2759. truncation_strategy == TruncationStrategy.ONLY_SECOND
  2760. and pair_ids is not None
  2761. ):
  2762. if len(pair_ids) > num_tokens_to_remove:
  2763. window_len = min(len(pair_ids), stride + num_tokens_to_remove)
  2764. if self.truncation_side == "right":
  2765. overflowing_tokens = pair_ids[-window_len:]
  2766. pair_ids = pair_ids[:-num_tokens_to_remove]
  2767. elif self.truncation_side == "left":
  2768. overflowing_tokens = pair_ids[:window_len]
  2769. pair_ids = pair_ids[num_tokens_to_remove:]
  2770. else:
  2771. raise ValueError(
  2772. "invalid truncation strategy:" + str(self.truncation_side)
  2773. )
  2774. else:
  2775. logging.error(
  2776. f"We need to remove {num_tokens_to_remove} to truncate the input "
  2777. f"but the second sequence has a length {len(pair_ids)}. "
  2778. f"Please select another truncation strategy than {truncation_strategy}, "
  2779. f"for instance 'longest_first' or 'only_first'."
  2780. )
  2781. return (ids, pair_ids, overflowing_tokens)
  2782. def _pad(
  2783. self,
  2784. encoded_inputs: Union[Dict[str, EncodedInput], BatchEncoding],
  2785. max_length: Optional[int] = None,
  2786. padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD,
  2787. pad_to_multiple_of: Optional[int] = None,
  2788. return_attention_mask: Optional[bool] = None,
  2789. ) -> dict:
  2790. """
  2791. Pad encoded inputs (on left/right and up to predefined length or max length in the batch)
  2792. Args:
  2793. encoded_inputs:
  2794. Dictionary of tokenized inputs (`List[int]`) or batch of tokenized inputs (`List[List[int]]`).
  2795. max_length: maximum length of the returned list and optionally padding length (see below).
  2796. Will truncate by taking into account the special tokens.
  2797. padding_strategy: PaddingStrategy to use for padding.
  2798. - PaddingStrategy.LONGEST Pad to the longest sequence in the batch
  2799. - PaddingStrategy.MAX_LENGTH: Pad to the max length (default)
  2800. - PaddingStrategy.DO_NOT_PAD: Do not pad
  2801. The tokenizer padding sides are defined in self.padding_side:
  2802. - 'left': pads on the left of the sequences
  2803. - 'right': pads on the right of the sequences
  2804. pad_to_multiple_of: (optional) Integer if set will pad the sequence to a multiple of the provided value.
  2805. This is especially useful to enable the use of Tensor Core on NVIDIA hardware with compute capability
  2806. >= 7.5 (Volta).
  2807. return_attention_mask:
  2808. (optional) Set to False to avoid returning attention mask (default: set to model specifics)
  2809. """
  2810. # Load from model defaults
  2811. if return_attention_mask is None:
  2812. return_attention_mask = (
  2813. "attention_mask" in self.model_input_names
  2814. or "attention_mask" in encoded_inputs
  2815. )
  2816. required_input = encoded_inputs[self.model_input_names[0]]
  2817. if padding_strategy == PaddingStrategy.LONGEST:
  2818. max_length = len(required_input)
  2819. if (
  2820. max_length is not None
  2821. and pad_to_multiple_of is not None
  2822. and (max_length % pad_to_multiple_of != 0)
  2823. ):
  2824. max_length = ((max_length // pad_to_multiple_of) + 1) * pad_to_multiple_of
  2825. needs_to_be_padded = (
  2826. padding_strategy != PaddingStrategy.DO_NOT_PAD
  2827. and len(required_input) != max_length
  2828. )
  2829. # Initialize attention mask if not present.
  2830. if return_attention_mask and "attention_mask" not in encoded_inputs:
  2831. encoded_inputs["attention_mask"] = [1] * len(required_input)
  2832. if needs_to_be_padded:
  2833. difference = max_length - len(required_input)
  2834. if self.padding_side == "right":
  2835. if return_attention_mask:
  2836. encoded_inputs["attention_mask"] = (
  2837. encoded_inputs["attention_mask"] + [0] * difference
  2838. )
  2839. if "token_type_ids" in encoded_inputs:
  2840. encoded_inputs["token_type_ids"] = (
  2841. encoded_inputs["token_type_ids"]
  2842. + [self.pad_token_type_id] * difference
  2843. )
  2844. if "special_tokens_mask" in encoded_inputs:
  2845. encoded_inputs["special_tokens_mask"] = (
  2846. encoded_inputs["special_tokens_mask"] + [1] * difference
  2847. )
  2848. if "offset_mapping" in encoded_inputs:
  2849. encoded_inputs["offset_mapping"] = (
  2850. encoded_inputs["offset_mapping"] + [(0, 0)] * difference
  2851. )
  2852. if "position_ids" in encoded_inputs:
  2853. encoded_inputs["position_ids"] = (
  2854. encoded_inputs["position_ids"] + [0] * difference
  2855. )
  2856. # NOTE: In ernie3.0-qa, the type of `*_positions` is int.
  2857. if "start_positions" in encoded_inputs and isinstance(
  2858. encoded_inputs["start_positions"], list
  2859. ):
  2860. encoded_inputs["start_positions"] = (
  2861. encoded_inputs["start_positions"] + [0] * difference
  2862. )
  2863. if "end_positions" in encoded_inputs and isinstance(
  2864. encoded_inputs["end_positions"], list
  2865. ):
  2866. encoded_inputs["end_positions"] = (
  2867. encoded_inputs["end_positions"] + [0] * difference
  2868. )
  2869. encoded_inputs[self.model_input_names[0]] = (
  2870. required_input + [self.pad_token_id] * difference
  2871. )
  2872. elif self.padding_side == "left":
  2873. if return_attention_mask:
  2874. encoded_inputs["attention_mask"] = [
  2875. 0
  2876. ] * difference + encoded_inputs["attention_mask"]
  2877. if "token_type_ids" in encoded_inputs:
  2878. encoded_inputs["token_type_ids"] = [
  2879. self.pad_token_type_id
  2880. ] * difference + encoded_inputs["token_type_ids"]
  2881. if "special_tokens_mask" in encoded_inputs:
  2882. encoded_inputs["special_tokens_mask"] = [
  2883. 1
  2884. ] * difference + encoded_inputs["special_tokens_mask"]
  2885. if "offset_mapping" in encoded_inputs:
  2886. encoded_inputs["offset_mapping"] = [
  2887. (0, 0)
  2888. ] * difference + encoded_inputs["offset_mapping"]
  2889. if "position_ids" in encoded_inputs:
  2890. encoded_inputs["position_ids"] = [0] * difference + encoded_inputs[
  2891. "position_ids"
  2892. ]
  2893. if "start_positions" in encoded_inputs and isinstance(
  2894. encoded_inputs["start_positions"], list
  2895. ):
  2896. encoded_inputs["start_positions"] = [
  2897. 0
  2898. ] * difference + encoded_inputs["start_positions"]
  2899. if "end_positions" in encoded_inputs and isinstance(
  2900. encoded_inputs["end_positions"], list
  2901. ):
  2902. encoded_inputs["end_positions"] = [0] * difference + encoded_inputs[
  2903. "end_positions"
  2904. ]
  2905. encoded_inputs[self.model_input_names[0]] = [
  2906. self.pad_token_id
  2907. ] * difference + required_input
  2908. else:
  2909. raise ValueError("Invalid padding strategy:" + str(self.padding_side))
  2910. return encoded_inputs
  2911. def convert_tokens_to_string(self, tokens: List[str]) -> str:
  2912. """
  2913. Converts a sequence of tokens in a single string. The most simple way to do it is `" ".join(tokens)` but we
  2914. often want to remove sub-word tokenization artifacts at the same time.
  2915. Args:
  2916. tokens (`List[str]`): The token to join in a string.
  2917. Returns:
  2918. `str`: The joined tokens.
  2919. """
  2920. raise NotImplementedError
  2921. def batch_decode(
  2922. self,
  2923. sequences,
  2924. skip_special_tokens: bool = False,
  2925. clean_up_tokenization_spaces: bool = True,
  2926. **kwargs,
  2927. ) -> List[str]:
  2928. """
  2929. Convert a list of lists of token ids into a list of strings by calling decode.
  2930. Args:
  2931. sequences (`Union[List[int], List[List[int]], np.ndarray, paddle.Tensor]`):
  2932. List of tokenized input ids. Can be obtained using the `__call__` method.
  2933. skip_special_tokens (`bool`, *optional*, defaults to `False`):
  2934. Whether or not to remove special tokens in the decoding.
  2935. clean_up_tokenization_spaces (`bool`, *optional*, defaults to `True`):
  2936. Whether or not to clean up the tokenization spaces.
  2937. kwargs (additional keyword arguments, *optional*):
  2938. Will be passed to the underlying model specific decode method.
  2939. Returns:
  2940. `List[str]`: The list of decoded sentences.
  2941. """
  2942. return [
  2943. self.decode(
  2944. seq,
  2945. skip_special_tokens=skip_special_tokens,
  2946. clean_up_tokenization_spaces=clean_up_tokenization_spaces,
  2947. **kwargs,
  2948. )
  2949. for seq in sequences
  2950. ]
  2951. def decode(
  2952. self,
  2953. token_ids,
  2954. skip_special_tokens: bool = False,
  2955. clean_up_tokenization_spaces: bool = True,
  2956. **kwargs,
  2957. ) -> str:
  2958. """
  2959. Converts a sequence of ids in a string, using the tokenizer and vocabulary with options to remove special
  2960. tokens and clean up tokenization spaces.
  2961. Similar to doing `self.convert_tokens_to_string(self.convert_ids_to_tokens(token_ids))`.
  2962. Args:
  2963. token_ids (`Union[int, List[int], np.ndarray, paddle.Tensor]`):
  2964. List of tokenized input ids. Can be obtained using the `__call__` method.
  2965. skip_special_tokens (`bool`, *optional*, defaults to `False`):
  2966. Whether or not to remove special tokens in the decoding.
  2967. clean_up_tokenization_spaces (`bool`, *optional*, defaults to `True`):
  2968. Whether or not to clean up the tokenization spaces.
  2969. kwargs (additional keyword arguments, *optional*):
  2970. Will be passed to the underlying model specific decode method.
  2971. Returns:
  2972. `str`: The decoded sentence.
  2973. """
  2974. # Convert inputs to python lists
  2975. token_ids = to_py_obj(token_ids)
  2976. return self._decode(
  2977. token_ids=token_ids,
  2978. skip_special_tokens=skip_special_tokens,
  2979. clean_up_tokenization_spaces=clean_up_tokenization_spaces,
  2980. **kwargs,
  2981. )
  2982. def _decode(
  2983. self,
  2984. token_ids: Union[int, List[int]],
  2985. skip_special_tokens: bool = False,
  2986. clean_up_tokenization_spaces: bool = True,
  2987. **kwargs,
  2988. ) -> str:
  2989. raise NotImplementedError
  2990. def get_special_tokens_mask(
  2991. self,
  2992. token_ids_0: List[int],
  2993. token_ids_1: Optional[List[int]] = None,
  2994. already_has_special_tokens: bool = False,
  2995. ) -> List[int]:
  2996. """
  2997. Retrieves sequence ids from a token list that has no special tokens added. This method is called when adding
  2998. special tokens using the tokenizer `prepare_for_model` or `encode_plus` methods.
  2999. Args:
  3000. token_ids_0 (`List[int]`):
  3001. List of ids of the first sequence.
  3002. token_ids_1 (`List[int]`, *optional*):
  3003. List of ids of the second sequence.
  3004. already_has_special_tokens (`bool`, *optional*, defaults to `False`):
  3005. Whether or not the token list is already formatted with special tokens for the model.
  3006. Returns:
  3007. A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
  3008. """
  3009. assert already_has_special_tokens and token_ids_1 is None, (
  3010. "You cannot use ``already_has_special_tokens=False`` with this tokenizer. "
  3011. "Please use a slow (full python) tokenizer to activate this argument. "
  3012. "Or set `return_special_tokens_mask=True` when calling the encoding method "
  3013. "to get the special tokens mask in any tokenizer. "
  3014. )
  3015. all_special_ids = self.all_special_ids # cache the property
  3016. special_tokens_mask = [
  3017. 1 if token in all_special_ids else 0 for token in token_ids_0
  3018. ]
  3019. return special_tokens_mask
  3020. @staticmethod
  3021. def clean_up_tokenization(out_string: str) -> str:
  3022. """
  3023. Clean up a list of simple English tokenization artifacts like spaces before punctuations and abbreviated forms.
  3024. Args:
  3025. out_string (`str`): The text to clean up.
  3026. Returns:
  3027. `str`: The cleaned-up string.
  3028. """
  3029. out_string = (
  3030. out_string.replace(" .", ".")
  3031. .replace(" ?", "?")
  3032. .replace(" !", "!")
  3033. .replace(" ,", ",")
  3034. .replace(" ' ", "'")
  3035. .replace(" n't", "n't")
  3036. .replace(" 'm", "'m")
  3037. .replace(" 's", "'s")
  3038. .replace(" 've", "'ve")
  3039. .replace(" 're", "'re")
  3040. )
  3041. return out_string
  3042. def _eventual_warn_about_too_long_sequence(
  3043. self, ids: List[int], max_length: Optional[int], verbose: bool
  3044. ):
  3045. """
  3046. Depending on the input and internal state we might trigger a warning about a sequence that is too long for its
  3047. corresponding model
  3048. Args:
  3049. ids (`List[str]`): The ids produced by the tokenization
  3050. max_length (`int`, *optional*): The max_length desired (does not trigger a warning if it is set)
  3051. verbose (`bool`): Whether or not to print more information and warnings.
  3052. """
  3053. if max_length is None and len(ids) > self.model_max_length and verbose:
  3054. if not self.deprecation_warnings.get(
  3055. "sequence-length-is-longer-than-the-specified-maximum", False
  3056. ):
  3057. logging.warning(
  3058. "Token indices sequence length is longer than the specified maximum sequence length "
  3059. f"for this model ({len(ids)} > {self.model_max_length}). Running this sequence through the model "
  3060. "will result in indexing errors"
  3061. )
  3062. self.deprecation_warnings[
  3063. "sequence-length-is-longer-than-the-specified-maximum"
  3064. ] = True