tokenizer_utils.py 84 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150
  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 bisect
  15. import functools
  16. import inspect
  17. import io
  18. import itertools
  19. import json
  20. import os
  21. import re
  22. import unicodedata
  23. from collections import OrderedDict
  24. from dataclasses import asdict, dataclass
  25. from functools import lru_cache
  26. from typing import Any, Dict, List, Optional, Tuple, Union
  27. import numpy as np
  28. from .....utils import logging
  29. from .....utils.deps import (
  30. class_requires_deps,
  31. function_requires_deps,
  32. is_dep_available,
  33. )
  34. from .tokenizer_utils_base import (
  35. CHAT_TEMPLATE_CONFIG_NAME,
  36. AddedToken,
  37. BatchEncoding,
  38. EncodedInput,
  39. EncodedInputPair,
  40. PaddingStrategy,
  41. PreTokenizedInput,
  42. PreTokenizedInputPair,
  43. PretrainedTokenizerBase,
  44. TensorType,
  45. TextInput,
  46. TextInputPair,
  47. TruncationStrategy,
  48. )
  49. from .utils import convert_to_dict_message, fn_args_to_dict
  50. from .vocab import Vocab
  51. if is_dep_available("Jinja2"):
  52. from jinja2 import Template
  53. from jinja2.exceptions import TemplateError, TemplateSyntaxError
  54. from jinja2.sandbox import ImmutableSandboxedEnvironment
  55. __all__ = [
  56. "ChatTemplate",
  57. "Trie",
  58. "ChatTemplateMixin",
  59. "PretrainedTokenizer",
  60. "InitTrackerMeta",
  61. ]
  62. @class_requires_deps("Jinja2")
  63. @dataclass
  64. class ChatTemplate:
  65. conversation: Union[List[str], None] = None
  66. system: Union[str, None] = None
  67. query: str = None
  68. @staticmethod
  69. @lru_cache()
  70. def _compile_jinja_template(chat_template) -> "Template":
  71. def raise_exception(message):
  72. raise TemplateError(message)
  73. jinja_env = ImmutableSandboxedEnvironment(
  74. trim_blocks=True, lstrip_blocks=True, keep_trailing_newline=True
  75. )
  76. jinja_env.globals["raise_exception"] = raise_exception
  77. return jinja_env.from_string(chat_template)
  78. def render_conversation(
  79. self,
  80. conversation_data: Union[List[str], Dict[str, str]],
  81. index: int = 0,
  82. context_data: Dict[str, Any] = {},
  83. ) -> List[str]:
  84. """
  85. Args:
  86. conversation_data (list[str]): the conversation data which must be two parts
  87. index (int): the index of current conversation
  88. Returns:
  89. list[str]: the rendered conversation data
  90. """
  91. if self.conversation is None:
  92. raise ValueError(
  93. "The template for multi-turns is invalid, please check `conversation` filed in your chat-template."
  94. )
  95. if isinstance(conversation_data, (list, tuple)):
  96. assert (
  97. len(conversation_data) == 2
  98. ), "Each round/turn of conversation must be two participants, eg: [user-query, bot-query]"
  99. conversation_data = {
  100. "user": conversation_data[0],
  101. "bot": conversation_data[1],
  102. "index": index,
  103. }
  104. conversation_data.update(context_data)
  105. one_turn_conversation = []
  106. for conversation in self.conversation:
  107. template = self._compile_jinja_template(conversation)
  108. result = template.render(conversation_data)
  109. one_turn_conversation.append(result)
  110. return one_turn_conversation
  111. def render_query(
  112. self, query: str, index: int = 0, context_data: Dict[str, Union[int, str]] = {}
  113. ):
  114. if self.query is None:
  115. return query
  116. template = self._compile_jinja_template(self.query)
  117. return template.render(query=query, index=index, **context_data)
  118. def _init_context_data(
  119. self, context_data: Dict[str, Union[int, str]] = {}
  120. ) -> Dict[str, Union[int, str]]:
  121. """init the context data for chat-template"""
  122. context_data["is_training"] = context_data.get("is_training", False)
  123. return context_data
  124. def render_system(self, context_data: Dict[str, Union[int, str]] = {}) -> str:
  125. if self.system is None:
  126. return ""
  127. template = self._compile_jinja_template(self.system)
  128. return template.render(**context_data)
  129. def __call__(
  130. self,
  131. conversations: Union[List[List[str]], str],
  132. context_data: Dict[str, Union[int, str]] = {},
  133. ) -> str:
  134. """render the conversations by chat-template
  135. Args:
  136. conversations (list[list[str]]): the conversations of use and bot
  137. Returns:
  138. str: the result of conversation
  139. """
  140. if isinstance(conversations, str):
  141. conversations = [[conversations]]
  142. # [1 ... n-1] conversation
  143. final_query = self.render_system(context_data=context_data)
  144. context_data["length"] = len(conversations)
  145. for index, conversation in enumerate(conversations[:-1]):
  146. context_data["is_first"] = index == 0
  147. context_data["is_last"] = False
  148. final_query += "".join(
  149. self.render_conversation(
  150. conversation, index=index, context_data=context_data
  151. )
  152. )
  153. if not isinstance(conversations[-1], list) and not len(conversations[-1]) != 1:
  154. raise ValueError(
  155. "The length of last conversation must be one, eg: [[user-query, bot-answer], [user-query, bot-answer], ..., [user-query]]"
  156. )
  157. if len(conversations[-1]) > 1:
  158. logging.warning(
  159. f"The last conversation is not a single-round, chat-template will skip the conversation: {conversations[-1][1:]}"
  160. )
  161. final_query += self.render_query(
  162. conversations[-1][0],
  163. index=len(conversations) - 1,
  164. context_data=context_data,
  165. )
  166. return final_query
  167. @classmethod
  168. def from_dict(cls, config: Dict):
  169. return cls(**config)
  170. @classmethod
  171. def from_file(cls, file: str):
  172. with open(file, "r", encoding="utf-8") as f:
  173. config = json.load(f)
  174. return cls.from_dict(config)
  175. @function_requires_deps("paddlepaddle")
  176. def adapt_stale_fwd_patch(self, name, value):
  177. """
  178. Since there are some monkey patches for forward of PretrainedModel, such as
  179. model compression, we make these patches compatible with the latest forward
  180. method.
  181. """
  182. if name == "forward":
  183. # NOTE(guosheng): In dygraph to static, `layer.forward` would be patched
  184. # by an instance of `StaticFunction`. And use string compare to avoid to
  185. # import fluid.
  186. if type(value).__name__.endswith(
  187. "StaticFunction"
  188. ) or self.forward.__class__.__name__.endswith("StaticFunction"):
  189. return value
  190. (
  191. patch_spec_args,
  192. patch_spec_varargs,
  193. patch_spec_varkw,
  194. patch_spec_defaults,
  195. _,
  196. _,
  197. _,
  198. ) = inspect.getfullargspec(value)
  199. (spec_args, spec_varargs, spec_varkw, spec_defaults, _, _, _) = (
  200. inspect.getfullargspec(self.forward)
  201. )
  202. new_args = [
  203. arg
  204. for arg in ("output_hidden_states", "output_attentions", "return_dict")
  205. if arg not in patch_spec_args and arg in spec_args
  206. ]
  207. if new_args:
  208. import paddle
  209. if self.__module__.startswith("paddlenlp"):
  210. logging.warning(
  211. f"The `forward` method of {self.__class__ if isinstance(self, paddle.nn.Layer) else self} is patched and the patch "
  212. "might be based on an old oversion which missing some "
  213. f"arguments compared with the latest, such as {new_args}. "
  214. "We automatically add compatibility on the patch for "
  215. "these arguemnts, and maybe the patch should be updated."
  216. )
  217. else:
  218. logging.warning(
  219. f"The `forward` method of {self.__class__ if isinstance(self, paddle.nn.Layer) else self} "
  220. "is patched and the patch might be conflict with patches made "
  221. f"by paddlenlp which seems have more arguments such as {new_args}. "
  222. "We automatically add compatibility on the patch for "
  223. "these arguemnts, and maybe the patch should be updated."
  224. )
  225. if isinstance(self, paddle.nn.Layer) and inspect.isfunction(value):
  226. @functools.wraps(value)
  227. def wrap_fwd(*args, **kwargs):
  228. for arg in new_args:
  229. kwargs.pop(arg, None)
  230. return value(self, *args, **kwargs)
  231. else:
  232. @functools.wraps(value)
  233. def wrap_fwd(*args, **kwargs):
  234. for arg in new_args:
  235. kwargs.pop(arg, None)
  236. return value(*args, **kwargs)
  237. return wrap_fwd
  238. return value
  239. # NOTE:
  240. # Modification:
  241. # class InitTrackerMeta(type(paddle.nn.Layer)) -> class InitTrackerMeta(type)
  242. # Context:
  243. # 1. In paddle 3.0rc, type(paddle.nn.Layer) == type
  244. # 2. Solve the conflict between ultra-infer and paddle
  245. class InitTrackerMeta(type):
  246. """
  247. This metaclass wraps the `__init__` method of a class to add `init_config`
  248. attribute for instances of that class, and `init_config` use a dict to track
  249. the initial configuration. If the class has `_pre_init` or `_post_init`
  250. method, it would be hooked before or after `__init__` and called as
  251. `_pre_init(self, init_fn, init_args)` or `_post_init(self, init_fn, init_args)`.
  252. Since InitTrackerMeta would be used as metaclass for pretrained model classes,
  253. which always are Layer and `type(Layer)` is not `type`, thus use `type(Layer)`
  254. rather than `type` as base class for it to avoid inheritance metaclass
  255. conflicts.
  256. """
  257. def __init__(cls, name, bases, attrs):
  258. init_func = cls.__init__
  259. # If attrs has `__init__`, wrap it using accessable `_pre_init, _post_init`.
  260. # Otherwise, no need to wrap again since the super cls has been wraped.
  261. # TODO: remove reduplicated tracker if using super cls `__init__`
  262. pre_init_func = getattr(cls, "_pre_init", None) if "__init__" in attrs else None
  263. post_init_func = (
  264. getattr(cls, "_post_init", None) if "__init__" in attrs else None
  265. )
  266. cls.__init__ = InitTrackerMeta.init_and_track_conf(
  267. init_func, pre_init_func, post_init_func
  268. )
  269. super(InitTrackerMeta, cls).__init__(name, bases, attrs)
  270. @staticmethod
  271. def init_and_track_conf(init_func, pre_init_func=None, post_init_func=None):
  272. """
  273. wraps `init_func` which is `__init__` method of a class to add `init_config`
  274. attribute for instances of that class.
  275. Args:
  276. init_func (callable): It should be the `__init__` method of a class.
  277. warning: `self` always is the class type of down-stream model, eg: BertForTokenClassification
  278. pre_init_func (callable, optional): If provided, it would be hooked after
  279. `init_func` and called as `pre_init_func(self, init_func, *init_args, **init_args)`.
  280. Default None.
  281. post_init_func (callable, optional): If provided, it would be hooked after
  282. `init_func` and called as `post_init_func(self, init_func, *init_args, **init_args)`.
  283. Default None.
  284. Returns:
  285. function: the wrapped function
  286. """
  287. @functools.wraps(init_func)
  288. def __impl__(self, *args, **kwargs):
  289. # registed helper by `pre_init_func`
  290. if pre_init_func:
  291. pre_init_func(self, init_func, *args, **kwargs)
  292. # keep full configuration
  293. init_func(self, *args, **kwargs)
  294. # registed helper by `post_init_func`
  295. if post_init_func:
  296. post_init_func(self, init_func, *args, **kwargs)
  297. self.init_config = kwargs
  298. if args:
  299. kwargs["init_args"] = args
  300. kwargs["init_class"] = self.__class__.__name__
  301. return __impl__
  302. def __setattr__(self, name, value):
  303. value = adapt_stale_fwd_patch(self, name, value)
  304. return super(InitTrackerMeta, self).__setattr__(name, value)
  305. class Trie:
  306. """
  307. Trie in Python. Creates a Trie out of a list of words. The trie is used to split on `added_tokens` in one pass
  308. Loose reference https://en.wikipedia.org/wiki/Trie
  309. """
  310. def __init__(self):
  311. self.data = {}
  312. def add(self, word: str):
  313. """
  314. Passes over every char (utf-8 char) on word and recursively adds it to the internal `data` trie representation.
  315. The special key `""` is used to represent termination.
  316. This function is idempotent, adding twice the same word will leave the trie unchanged
  317. Example:
  318. ```python
  319. >>> trie = Trie()
  320. >>> trie.add("Hello 友達")
  321. >>> trie.data
  322. {"H": {"e": {"l": {"l": {"o": {" ": {"友": {"達": {"": 1}}}}}}}}}
  323. >>> trie.add("Hello")
  324. >>> trie.data
  325. {"H": {"e": {"l": {"l": {"o": {"": 1, " ": {"友": {"達": {"": 1}}}}}}}}}
  326. ```
  327. """
  328. if not word:
  329. # Prevent empty string
  330. return
  331. ref = self.data
  332. for char in word:
  333. ref[char] = char in ref and ref[char] or {}
  334. ref = ref[char]
  335. ref[""] = 1
  336. def split(self, text: str) -> List[str]:
  337. """
  338. Will look for the words added to the trie within `text`. Output is the original string splitted along the
  339. boundaries of the words found.
  340. This trie will match the longest possible word first !
  341. Example:
  342. ```python
  343. >>> trie = Trie()
  344. >>> trie.split("[CLS] This is a extra_id_100")
  345. ["[CLS] This is a extra_id_100"]
  346. >>> trie.add("[CLS]")
  347. >>> trie.add("extra_id_1")
  348. >>> trie.add("extra_id_100")
  349. >>> trie.split("[CLS] This is a extra_id_100")
  350. ["[CLS]", " This is a ", "extra_id_100"]
  351. ```
  352. """
  353. # indexes are counted left of the chars index.
  354. # "hello", index 0, is left of h, index 1 is between h and e.
  355. # index 5 is right of the "o".
  356. # States are going to capture every possible start (indexes as above)
  357. # as keys, and have as values, a pointer to the position in the trie
  358. # where we're at. This is a partial match for now.
  359. # This enables to keep track of multiple matches while we're iterating
  360. # the string
  361. # If the trie contains, "blowing", and "lower" and we encounter the
  362. # string "blower", we need to split into ["b", "lower"].
  363. # This is where we need to keep track of multiple possible starts.
  364. states = OrderedDict()
  365. # This will contain every indices where we need
  366. # to cut.
  367. # We force to cut at offset 0 and len(text) (added later)
  368. offsets = [0]
  369. # This is used by the lookahead which needs to skip over
  370. # some text where the full match exceeded the place in the initial
  371. # for loop
  372. skip = 0
  373. # Main loop, Giving this algorithm O(n) complexity
  374. for current, current_char in enumerate(text):
  375. if skip and current < skip:
  376. # Prevents the lookahead for matching twice
  377. # like extra_id_100 and id_100
  378. continue
  379. # This will track every state
  380. # that stop matching, we need to stop tracking them.
  381. # If we look at "lowball", we're going to match "l" (add it to states), "o", "w", then
  382. # fail on "b", we need to remove 0 from the valid states.
  383. to_remove = set()
  384. # Whenever we found a match, we need to drop everything
  385. # this is a greedy algorithm, it will match on the first found token
  386. reset = False
  387. # In this case, we already have partial matches (But unfinished)
  388. for start, trie_pointer in states.items():
  389. if "" in trie_pointer:
  390. # This is a final match, we need to reset and
  391. # store the results in `offsets`.
  392. # Lookahead to match longest first
  393. # Important in case of extra_id_1 vs extra_id_100
  394. # Here we are also actively looking for other earlier partial
  395. # matches
  396. # "[CLS]", "L", we need to match CLS even if L is special
  397. for lookstart, looktrie_pointer in states.items():
  398. if lookstart > start:
  399. # This partial match is later, we can stop looking
  400. break
  401. elif lookstart < start:
  402. # This partial match is earlier, the trie pointer
  403. # was already updated, so index is + 1
  404. lookahead_index = current + 1
  405. end = current + 1
  406. else:
  407. # Here lookstart == start and
  408. # looktrie_pointer == trie_pointer
  409. # It wasn't updated yet so indices are current ones
  410. lookahead_index = current
  411. end = current
  412. next_char = (
  413. text[lookahead_index]
  414. if lookahead_index < len(text)
  415. else None
  416. )
  417. if "" in looktrie_pointer:
  418. start = lookstart
  419. end = lookahead_index
  420. skip = lookahead_index
  421. while next_char in looktrie_pointer:
  422. looktrie_pointer = looktrie_pointer[next_char]
  423. lookahead_index += 1
  424. if "" in looktrie_pointer:
  425. start = lookstart
  426. end = lookahead_index
  427. skip = lookahead_index
  428. if lookahead_index == len(text):
  429. # End of string
  430. break
  431. next_char = text[lookahead_index]
  432. # End lookahead
  433. # Storing and resetting
  434. offsets.append(start)
  435. offsets.append(end)
  436. reset = True
  437. break
  438. elif current_char in trie_pointer:
  439. # The current character being looked at has a match within the trie
  440. # update the pointer (it will be stored back into states later).
  441. trie_pointer = trie_pointer[current_char]
  442. # Storing back the new pointer into the states.
  443. # Partial matches got longer by one.
  444. states[start] = trie_pointer
  445. else:
  446. # The new character has not match in the trie, we need
  447. # to stop keeping track of this partial match.
  448. # We can't do it directly within the loop because of how
  449. # python iteration works
  450. to_remove.add(start)
  451. # Either clearing the full start (we found a real match)
  452. # Or clearing only the partial matches that didn't work.
  453. if reset:
  454. states = {}
  455. else:
  456. for start in to_remove:
  457. del states[start]
  458. # If this character is a starting character within the trie
  459. # start keeping track of this partial match.
  460. if current >= skip and current_char in self.data:
  461. states[current] = self.data[current_char]
  462. # We have a cut at the end with states.
  463. for start, trie_pointer in states.items():
  464. if "" in trie_pointer:
  465. # This is a final match, we need to reset and
  466. # store the results in `offsets`.
  467. end = len(text)
  468. offsets.append(start)
  469. offsets.append(end)
  470. # Longest cut is always the one with lower start so the first
  471. # item so we need to break.
  472. break
  473. return self.cut_text(text, offsets)
  474. def cut_text(self, text, offsets):
  475. # We have all the offsets now, we just need to do the actual splitting.
  476. # We need to eventually add the first part of the string and the eventual
  477. # last part.
  478. offsets.append(len(text))
  479. tokens = []
  480. start = 0
  481. for end in offsets:
  482. if start > end:
  483. logging.error(
  484. "There was a bug in Trie algorithm in tokenization. Attempting to recover. Please report it anyway."
  485. )
  486. continue
  487. elif start == end:
  488. # This might happen if there's a match at index 0
  489. # we're also preventing zero-width cuts in case of two
  490. # consecutive matches
  491. continue
  492. tokens.append(text[start:end])
  493. start = end
  494. return tokens
  495. def _insert_one_token_to_ordered_list(token_list: List[str], new_token: str):
  496. """
  497. Inserts one token to an ordered list if it does not already exist. Note: token_list must be sorted.
  498. """
  499. insertion_idx = bisect.bisect_left(token_list, new_token)
  500. # Checks if new_token is already in the ordered token_list
  501. if insertion_idx < len(token_list) and token_list[insertion_idx] == new_token:
  502. # new_token is in token_list, don't add
  503. return
  504. else:
  505. token_list.insert(insertion_idx, new_token)
  506. def _is_control(char):
  507. """Checks whether `chars` is a control character."""
  508. # These are technically control characters but we count them as whitespace
  509. # characters.
  510. if char == "\t" or char == "\n" or char == "\r":
  511. return False
  512. cat = unicodedata.category(char)
  513. if cat.startswith("C"):
  514. return True
  515. return False
  516. def _is_nonnormalized_char(char):
  517. """Check whther `chars` is a non-normalized character."""
  518. cp = ord(char)
  519. if (
  520. (0xFF00 <= cp <= 0xFFEF)
  521. or (0xFE50 <= cp <= 0xFE6B) # Halfwidth and Fullwidth Forms
  522. or (0x3358 <= cp <= 0x33FF) # Small Form Variants
  523. or (0x249C <= cp <= 0x24E9) # CJK Compatibility
  524. or (0x3200 <= cp <= 0x32FF) # Enclosed Alphanumerics: Ⓛ ⒰
  525. ): # Enclosed CJK Letters and Months
  526. return True
  527. return False
  528. def _is_nonnormalized_numeric(char):
  529. """Check whether `chars` is a non-normalized numeric character."""
  530. cp = ord(char)
  531. if (
  532. (0x2460 <= cp <= 0x249B)
  533. or (0x24EA <= cp <= 0x24FF) #
  534. or (0x2776 <= cp <= 0x2793) #
  535. or (0x2160 <= cp <= 0x217F) # Enclosed Alphanumerics
  536. ): # Number Forms
  537. return True
  538. return False
  539. def normalize_chars(text):
  540. """
  541. Normalize the text for multiligual and chinese models. Unicode range:
  542. https://www.ling.upenn.edu/courses/Spring_2003/ling538/UnicodeRanges.html
  543. """
  544. output = []
  545. for char in text:
  546. if _is_nonnormalized_char(char):
  547. for c in unicodedata.normalize("NFKC", char):
  548. output.append(c)
  549. elif _is_nonnormalized_numeric(char):
  550. output.append(" ")
  551. for c in str(int(unicodedata.numeric(char))):
  552. output.append(c)
  553. output.append(" ")
  554. elif ord(char) == 0xF979: # https://www.zhihu.com/question/20697984
  555. output.append("凉")
  556. else:
  557. output.append(char)
  558. return "".join(output)
  559. @class_requires_deps("paddlepaddle", "Jinja2")
  560. class ChatTemplateMixin:
  561. chat_template: Optional[ChatTemplate] = None
  562. def apply_chat_template(
  563. self,
  564. conversation: Union[Dict[str, str], str],
  565. tokenize: bool = True,
  566. context_data: Dict[str, Any] = {},
  567. **tokenizer_kwargs,
  568. ):
  569. """apply chat_template rules to conversation which should not be batched data
  570. Args:
  571. conversation (List[List[str, str]] | str): the conversation messages between user and bot
  572. context_data (Dict[str, Any]): the context data for chat_template.json
  573. tokenize (bool, optional): whether do tokenization. Defaults to True.
  574. Returns:
  575. str | dict[str, Union[numpy.ndarray, paddle.Tensor]]: return the result of applied data
  576. """
  577. if not self.chat_template:
  578. raise ValueError(
  579. "chat_template is not set, please set chat_template first."
  580. )
  581. elif isinstance(self.chat_template, Template):
  582. add_generation_prompt = tokenizer_kwargs.pop("add_generation_prompt", True)
  583. query = self._apply_chat_template(
  584. conversation, add_generation_prompt=add_generation_prompt
  585. )
  586. elif isinstance(self.chat_template, ChatTemplate):
  587. query = self._apply_chat_template_paddle(conversation, context_data)
  588. if not tokenize:
  589. return query
  590. # chat_template should not add special tokens
  591. tokenizer_kwargs["add_special_tokens"] = False
  592. return self(query, **tokenizer_kwargs)
  593. def _apply_chat_template_paddle(
  594. self,
  595. conversation: Union[List[Dict[str, str]], str],
  596. context_data: Dict[str, Any] = {},
  597. ):
  598. context_data = self.chat_template._init_context_data(context_data)
  599. if isinstance(conversation, str):
  600. conversation = [[conversation]]
  601. elif isinstance(conversation, list) and isinstance(conversation[0], str):
  602. raise ValueError(
  603. "apply_chat_template do not support appling batch conversations, "
  604. "so you should apply the conversation one by one."
  605. )
  606. query = self.chat_template(conversation, context_data=context_data)
  607. return query
  608. def _apply_chat_template(
  609. self,
  610. conversation: Union[Dict[str, str], str],
  611. add_generation_prompt=True,
  612. ):
  613. if isinstance(conversation, str):
  614. conversations = [{"role": "user", "content": conversation}]
  615. elif isinstance(conversation, list):
  616. assert len(conversation) > 0, "empty conversation is not allowed"
  617. if isinstance(conversation[0], list):
  618. conversations = convert_to_dict_message(conversation)
  619. elif isinstance(conversation[0], dict):
  620. conversations = conversation
  621. else:
  622. raise ValueError(
  623. "apply_chat_template do not support appling batch conversations, "
  624. "so you should apply the conversation one by one."
  625. )
  626. query = self.chat_template.render(
  627. messages=conversations,
  628. **self.special_tokens_map,
  629. add_generation_prompt=add_generation_prompt,
  630. )
  631. return query
  632. def encode_chat_inputs(
  633. self,
  634. conversations: List[Dict[str, str]],
  635. context_data: Dict[str, Any] = {},
  636. **kwargs,
  637. ):
  638. """Encodes conversation to pairs of token ids.
  639. Turn 0: bos + system + sep + user bot + eos
  640. Turn t: sep + bot + query bot + eos
  641. Args:
  642. conversation (List[Dict[str, str]]): the conversation of data
  643. context_data (Dict[str, Any]): the context data of conversation
  644. Returns:
  645. List[list[int], list[int]]: the pair of input_ids and target_ids
  646. """
  647. if not self.chat_template:
  648. raise ValueError(
  649. "chat_template is not set, please set chat_template first."
  650. )
  651. elif isinstance(self.chat_template, Template):
  652. add_generation_prompt = kwargs.pop("add_generation_prompt", True)
  653. query = self._encode_chat_inputs(
  654. conversations, context_data, add_generation_prompt=add_generation_prompt
  655. )
  656. elif isinstance(self.chat_template, ChatTemplate):
  657. query = self._encode_chat_inputs_paddle(conversations, context_data)
  658. return query
  659. def _encode_chat_inputs_paddle(
  660. self, conversations: List[Dict[str, str]], context_data: Dict[str, Any] = {}
  661. ):
  662. context_data = self.chat_template._init_context_data(context_data)
  663. # encode system
  664. result = {}
  665. if self.chat_template.system:
  666. system = self.chat_template.render_system(context_data)
  667. result["system"] = self.encode(system, add_special_tokens=False)[
  668. "input_ids"
  669. ]
  670. # encode conversation
  671. conversation_ids = []
  672. for index, conversation in enumerate(conversations):
  673. # give more control to chat_template
  674. context_data["is_first"] = index == 0
  675. context_data["is_last"] = index == len(conversations) - 1
  676. user_input, bot_output = self.chat_template.render_conversation(
  677. conversation, index=index, context_data=context_data
  678. )
  679. user_ids = self.encode(user_input, add_special_tokens=False)["input_ids"]
  680. bot_ids = self.encode(bot_output, add_special_tokens=False)["input_ids"]
  681. conversation_ids.append([user_ids, bot_ids])
  682. result["conversations"] = conversation_ids
  683. return result
  684. def _encode_chat_inputs(
  685. self,
  686. conversations: List[Dict[str, str]],
  687. context_data: Dict[str, Any] = {},
  688. system: str = None,
  689. add_generation_prompt=True,
  690. ):
  691. result = {}
  692. # Some template do not support system msg, so we need to check it first.
  693. if system:
  694. try:
  695. self.chat_template.render(
  696. messages={"role": "system", "content": system}
  697. )
  698. except Exception as e:
  699. raise ValueError("System is not supported in this tokenizer.", e)
  700. # convert list msg to role dict msg
  701. conversation_dict = []
  702. origin_msg = []
  703. for round in conversations:
  704. round_role = [
  705. {"role": "user", "content": round[0]},
  706. {"role": "assistant", "content": round[1]},
  707. ]
  708. origin_msg.extend(round_role)
  709. conversation_dict.append(round_role)
  710. ans = []
  711. # get answer in single round, then compile the chat entirely and split by single round ans
  712. # attention: answer should include end token!
  713. for conv in conversation_dict:
  714. roundi = [system] + conv if system else conv
  715. roundi_str = self.chat_template.render(
  716. messages=roundi, add_generation_prompt=False, **self.special_tokens_map
  717. )
  718. roundi_no_ans = [system] + [conv[0]] if system else [conv[0]]
  719. roundi_no_ans_str = self.chat_template.render(
  720. messages=roundi_no_ans,
  721. add_generation_prompt=add_generation_prompt,
  722. **self.special_tokens_map,
  723. )
  724. ans_roundi = roundi_str[len(roundi_no_ans_str) :]
  725. ans.append(ans_roundi)
  726. non_learnable_parts = self._extract_non_learnable_parts(origin_msg, ans)
  727. assert len(non_learnable_parts) == len(ans)
  728. conversation_ids = []
  729. for i in range(len(non_learnable_parts)):
  730. conversation_ids.append(
  731. self.batch_encode(
  732. [non_learnable_parts[i], ans[i]],
  733. add_special_tokens=False,
  734. padding=False,
  735. )["input_ids"]
  736. )
  737. result["conversations"] = conversation_ids
  738. return result
  739. def _extract_non_learnable_parts(
  740. self, origin_msg: List[Dict[str, str]], split_s: List[str]
  741. ):
  742. """Split the entire chat by specified words. Extract the non-learnable parts."""
  743. # distingish and replace the special words in original string to an uncompiled form: Like | -> \|
  744. regex_pattern = "|".join(map(re.escape, split_s))
  745. # splited by replaced specified words
  746. non_learnable_parts = re.split(
  747. r"(?:%s)" % regex_pattern,
  748. self.chat_template.render(
  749. messages=origin_msg,
  750. add_generation_prompt=False,
  751. **self.special_tokens_map,
  752. ),
  753. )
  754. if non_learnable_parts[-1] == "":
  755. non_learnable_parts.pop()
  756. return non_learnable_parts
  757. @classmethod
  758. def from_pretrained(cls, pretrained_model_name_or_path, *args, **kwargs):
  759. cache_dir = kwargs.pop("cache_dir", None)
  760. from_hf_hub = kwargs.pop("from_hf_hub", False)
  761. from_aistudio = kwargs.pop("from_aistudio", False)
  762. subfolder = kwargs.pop("subfolder", "")
  763. if subfolder is None:
  764. subfolder = ""
  765. kwargs["subfolder"] = subfolder
  766. kwargs["cache_dir"] = cache_dir
  767. kwargs["from_hf_hub"] = from_hf_hub
  768. kwargs["from_aistudio"] = from_aistudio
  769. kwargs["return_tokenizer_file_dir"] = True
  770. tokenizer, tokenizer_config_file_dir = super().from_pretrained(
  771. pretrained_model_name_or_path, *args, **kwargs
  772. )
  773. # load chat-template
  774. chat_template_file = os.path.join(
  775. tokenizer_config_file_dir, CHAT_TEMPLATE_CONFIG_NAME
  776. )
  777. if not os.path.exists(chat_template_file):
  778. return tokenizer
  779. if tokenizer.chat_template is not None:
  780. logging.warning(
  781. "Chat-template already exists in config file, it will be overwritten by chat_template.json file."
  782. )
  783. logging.warning(
  784. "`chat_template.json` will be deprecated in the future! Please set it in `tokenizer_config.json`."
  785. )
  786. tokenizer.init_chat_template(chat_template_file)
  787. return tokenizer
  788. def init_chat_template(self, chat_template: Union[str, Dict]):
  789. """init chat_tempalte by file_path or template dict data
  790. Args:
  791. chat_template (str | dict): file_path or template dict data
  792. """
  793. if isinstance(chat_template, str):
  794. if not os.path.exists(chat_template):
  795. try:
  796. self.chat_template: Template = ChatTemplate._compile_jinja_template(
  797. chat_template
  798. )
  799. except TemplateSyntaxError:
  800. # It is neither jinjia string nor path string
  801. raise TemplateSyntaxError(
  802. "The chat-template in json is not valid jinja string: {}".format(
  803. chat_template
  804. ),
  805. lineno=0, # fake lineno, useless required msg
  806. )
  807. else:
  808. self.chat_template = ChatTemplate.from_file(chat_template)
  809. elif isinstance(chat_template, dict):
  810. self.chat_template = ChatTemplate.from_dict(chat_template)
  811. elif isinstance(chat_template, ChatTemplate):
  812. self.chat_template = chat_template
  813. else:
  814. raise ValueError("Receive error chat_template data: ", chat_template)
  815. def save_resources(self, save_directory):
  816. super().save_resources(save_directory)
  817. if isinstance(
  818. self.chat_template, ChatTemplate
  819. ): # Future remove if ChatTemplate is deprecated
  820. chat_template_file = os.path.join(save_directory, CHAT_TEMPLATE_CONFIG_NAME)
  821. with open(chat_template_file, "w", encoding="utf-8") as f:
  822. json.dump(asdict(self.chat_template), f, ensure_ascii=False, indent=4)
  823. logging.info("Chat-template config file saved in " + chat_template_file)
  824. class PretrainedTokenizer(
  825. ChatTemplateMixin, PretrainedTokenizerBase, metaclass=InitTrackerMeta
  826. ):
  827. """
  828. Base class for all tokenizers.
  829. Inherits from [`~tokenizer_utils_base.PretrainedTokenizerBase`].
  830. Handle all the shared methods for tokenization and special tokens as well as methods downloading/caching/loading
  831. pretrained tokenizers as well as adding tokens to the vocabulary.
  832. This class also contain the added tokens in a unified way on top of all tokenizers so we don't have to handle the
  833. specific vocabulary augmentation methods of the various underlying dictionary structures (BPE, sentencepiece...).
  834. - **resource_files_names** (`Dict[str, str]`) -- A dictionary with, as keys, the `__init__` keyword name of each
  835. vocabulary file required by the model, and as associated values, the filename for saving the associated file
  836. (string).
  837. - **pretrained_resource_files_map** (`Dict[str, Dict[str, str]]`) -- A dictionary of dictionaries, with the
  838. high-level keys being the `__init__` keyword name of each vocabulary file required by the model, the
  839. low-level being the `short-cut-names` of the pretrained models with, as associated values, the `url` to the
  840. associated pretrained vocabulary file.
  841. - **max_model_input_sizes** (`Dict[str, Optional[int]]`) -- A dictionary with, as keys, the `short-cut-names`
  842. of the pretrained models, and as associated values, the maximum length of the sequence inputs of this model,
  843. or `None` if the model has no maximum input size.
  844. - **pretrained_init_configuration** (`Dict[str, Dict[str, Any]]`) -- A dictionary with, as keys, the
  845. `short-cut-names` of the pretrained models, and as associated values, a dictionary of specific arguments to
  846. pass to the `__init__` method of the tokenizer class for this pretrained model when loading the tokenizer
  847. with the [`~tokenizer_utils_base.PretrainedTokenizerBase.from_pretrained`] method.
  848. - **model_input_names** (`List[str]`) -- A list of inputs expected in the forward pass of the model.
  849. - **padding_side** (`str`) -- The default value for the side on which the model should have padding applied.
  850. Should be `'right'` or `'left'`.
  851. - **truncation_side** (`str`) -- The default value for the side on which the model should have truncation
  852. applied. Should be `'right'` or `'left'`.
  853. Moreover, methods common to tokenizers for tokenization, token/id conversion
  854. and encoding as model inputs are also provided here.
  855. Besides, metaclass `InitTrackerMeta` is used to create `PretrainedTokenizer`,
  856. by which subclasses can track arguments for initialization automatically
  857. and expose special tokens initialization used as attributes.
  858. """
  859. added_tokens_encoder: Dict[str, int] = {}
  860. added_tokens_decoder: Dict[int, str] = {}
  861. unique_no_split_tokens: List[str] = []
  862. tokens_trie = Trie()
  863. _decode_use_source_tokenizer = False
  864. def _pre_init(self, original_init, *args, **kwargs):
  865. """
  866. It would be hooked before `__init__` to add specials tokens (arguments of
  867. `__init__` whose name ends with `_token`) as attributes of the tokenizer
  868. instance.
  869. """
  870. init_dict = fn_args_to_dict(original_init, *((self,) + args), **kwargs)
  871. init_dict.pop("self", None)
  872. super(PretrainedTokenizer, self).__init__(**init_dict)
  873. self.added_tokens_encoder: Dict[str, int] = {}
  874. self.added_tokens_decoder: Dict[int, str] = {}
  875. self.unique_no_split_tokens: List[str] = []
  876. self.tokens_trie = Trie()
  877. self._decode_use_source_tokenizer = False
  878. def _build_special_tokens_map_extended(self, **kwargs):
  879. for key, value in kwargs.items():
  880. if value is None:
  881. continue
  882. if key in self.SPECIAL_TOKENS_ATTRIBUTES:
  883. if key == "additional_special_tokens":
  884. assert isinstance(
  885. value, (list, tuple)
  886. ), f"Value {value} is not a list or tuple"
  887. assert all(
  888. isinstance(t, (str, AddedToken)) for t in value
  889. ), "One of the tokens is not a string or an AddedToken"
  890. setattr(self, key, value)
  891. elif isinstance(value, (str, AddedToken)):
  892. setattr(self, key, value)
  893. else:
  894. raise TypeError(
  895. f"special token {key} has to be either str or AddedToken but got: {type(value)}"
  896. )
  897. @property
  898. def vocab_size(self) -> int:
  899. """
  900. `int`: Size of the base vocabulary (without the added tokens).
  901. """
  902. raise NotImplementedError
  903. @property
  904. def is_fast(self) -> bool:
  905. return False
  906. def get_added_vocab(self) -> Dict[str, int]:
  907. """
  908. Returns the added tokens in the vocabulary as a dictionary of token to index.
  909. Returns:
  910. `Dict[str, int]`: The added tokens.
  911. """
  912. return self.added_tokens_encoder
  913. def __len__(self):
  914. """
  915. Size of the full vocabulary with the added tokens.
  916. """
  917. return self.vocab_size + len(self.added_tokens_encoder)
  918. def _add_tokens(
  919. self,
  920. new_tokens: Union[List[str], List[AddedToken]],
  921. special_tokens: bool = False,
  922. ) -> int:
  923. """
  924. Add a list of new tokens to the tokenizer class. If the new tokens are not in the vocabulary, they are added to
  925. it with indices starting from length of the current vocabulary.
  926. Args:
  927. new_tokens (`List[str]`or `List[AddedToken]`):
  928. Token(s) to add in vocabulary. A token is only added if it's not already in the vocabulary (tested by
  929. checking if the tokenizer assign the index of the `unk_token` to them).
  930. special_tokens (`bool`, *optional*, defaults to `False`):
  931. Whether or not the tokens should be added as special tokens.
  932. Returns:
  933. `int`: The number of tokens actually added to the vocabulary.
  934. Examples:
  935. ```python
  936. # Let's see how to increase the vocabulary of Bert model and tokenizer
  937. tokenizer = BertTokenizer.from_pretrained("bert-base-uncased")
  938. model = BertModel.from_pretrained("bert-base-uncased")
  939. num_added_toks = tokenizer.add_tokens(["new_tok1", "my_new-tok2"])
  940. print("We have added", num_added_toks, "tokens")
  941. ```"""
  942. new_tokens = [str(tok) for tok in new_tokens]
  943. tokens_to_add = []
  944. for token in new_tokens:
  945. if not isinstance(token, str):
  946. raise TypeError(f"Token {token} is not a string but a {type(token)}.")
  947. if (
  948. not special_tokens
  949. and hasattr(self, "do_lower_case")
  950. and self.do_lower_case
  951. ):
  952. token = token.lower()
  953. if (
  954. token != self.unk_token
  955. and self.convert_tokens_to_ids(token)
  956. == self.convert_tokens_to_ids(self.unk_token)
  957. and token not in tokens_to_add
  958. ):
  959. tokens_to_add.append(token)
  960. if self.verbose:
  961. logging.info(f"Adding {token} to the vocabulary")
  962. added_tok_encoder = dict(
  963. (tok, len(self) + i) for i, tok in enumerate(tokens_to_add)
  964. )
  965. added_tok_decoder = {v: k for k, v in added_tok_encoder.items()}
  966. self.added_tokens_encoder.update(added_tok_encoder)
  967. self.added_tokens_decoder.update(added_tok_decoder)
  968. # Make sure we don't split on any special tokens (even they were already in the vocab before e.g. for Albert)
  969. if special_tokens:
  970. if len(new_tokens) == 1:
  971. _insert_one_token_to_ordered_list(
  972. self.unique_no_split_tokens, new_tokens[0]
  973. )
  974. else:
  975. self.unique_no_split_tokens = sorted(
  976. set(self.unique_no_split_tokens).union(set(new_tokens))
  977. )
  978. else:
  979. # Or on the newly added tokens
  980. if len(tokens_to_add) == 1:
  981. _insert_one_token_to_ordered_list(
  982. self.unique_no_split_tokens, tokens_to_add[0]
  983. )
  984. else:
  985. self.unique_no_split_tokens = sorted(
  986. set(self.unique_no_split_tokens).union(set(tokens_to_add))
  987. )
  988. self._create_trie(self.unique_no_split_tokens)
  989. return len(tokens_to_add)
  990. def _create_trie(self, unique_no_split_tokens):
  991. trie = Trie()
  992. for token in unique_no_split_tokens:
  993. if (
  994. hasattr(self, "do_lower_case")
  995. and self.do_lower_case
  996. and token not in self.all_special_tokens
  997. ):
  998. trie.add(token.lower())
  999. else:
  1000. trie.add(token)
  1001. self.tokens_trie = trie
  1002. def prepare_for_tokenization(self, text, is_split_into_words=False, **kwargs):
  1003. """
  1004. Performs any necessary transformations before tokenization.
  1005. This method should pop the arguments from kwargs and return the remaining `kwargs` as well. We test the
  1006. `kwargs` at the end of the encoding process to be sure all the arguments have been used.
  1007. Args:
  1008. text (`str`):
  1009. The text to prepare.
  1010. is_split_into_words (`bool`, *optional*, defaults to `False`):
  1011. Whether or not the input is already pre-tokenized (e.g., split into words). If set to `True`, the
  1012. tokenizer assumes the input is already split into words (for instance, by splitting it on whitespace)
  1013. which it will tokenize. This is useful for NER or token classification.
  1014. kwargs:
  1015. Keyword arguments to use for the tokenization.
  1016. Returns:
  1017. `Tuple[str, Dict[str, Any]]`: The prepared text and the unused kwargs.
  1018. """
  1019. return (text, kwargs)
  1020. def tokenize(self, text: TextInput, **kwargs) -> List[str]:
  1021. """
  1022. Converts a string in a sequence of tokens, using the tokenizer.
  1023. Split in words for word-based vocabulary or sub-words for sub-word-based vocabularies
  1024. (BPE/SentencePieces/WordPieces). Takes care of added tokens.
  1025. Args:
  1026. text (`str`):
  1027. The sequence to be encoded.
  1028. **kwargs (additional keyword arguments):
  1029. Passed along to the model-specific `prepare_for_tokenization` preprocessing method.
  1030. Returns:
  1031. `List[str]`: The list of tokens.
  1032. """
  1033. # Simple mapping string => AddedToken for special tokens with specific tokenization behaviors
  1034. all_special_tokens_extended = dict(
  1035. (str(t), t)
  1036. for t in self.all_special_tokens_extended
  1037. if isinstance(t, AddedToken)
  1038. )
  1039. text, kwargs = self.prepare_for_tokenization(text, **kwargs)
  1040. # TODO: should this be in the base class?
  1041. if hasattr(self, "do_lower_case") and self.do_lower_case:
  1042. # convert non-special tokens to lowercase
  1043. escaped_special_toks = [
  1044. re.escape(s_tok)
  1045. for s_tok in (self.unique_no_split_tokens + self.all_special_tokens)
  1046. ]
  1047. pattern = r"(" + r"|".join(escaped_special_toks) + r")|" + r"(.+?)"
  1048. text = re.sub(
  1049. pattern, lambda m: m.groups()[0] or m.groups()[1].lower(), text
  1050. )
  1051. no_split_token = set(self.unique_no_split_tokens)
  1052. tokens = self.tokens_trie.split(text)
  1053. # ["This is something", "<special_token_1>", " else"]
  1054. for i, token in enumerate(tokens):
  1055. if token in no_split_token:
  1056. tok_extended = all_special_tokens_extended.get(token, None)
  1057. left = tokens[i - 1] if i > 0 else None
  1058. right = tokens[i + 1] if i < len(tokens) - 1 else None
  1059. if isinstance(tok_extended, AddedToken):
  1060. if tok_extended.rstrip and right:
  1061. # A bit counter-intuitive but we strip the left of the string
  1062. # since tok_extended.rstrip means the special token is eating all white spaces on its right
  1063. tokens[i + 1] = right.lstrip()
  1064. # Strip white spaces on the left
  1065. if tok_extended.lstrip and left:
  1066. tokens[i - 1] = left.rstrip() # Opposite here
  1067. else:
  1068. # We strip left and right by default
  1069. if right:
  1070. tokens[i + 1] = right.lstrip()
  1071. if left:
  1072. tokens[i - 1] = left.rstrip()
  1073. # ["This is something", "<special_token_1>", "else"]
  1074. tokenized_text = []
  1075. for token in tokens:
  1076. # Need to skip eventual empty (fully stripped) tokens
  1077. if not token:
  1078. continue
  1079. if token in no_split_token:
  1080. tokenized_text.append(token)
  1081. else:
  1082. tokenized_text.extend(self._tokenize(token))
  1083. # ["This", " is", " something", "<special_token_1>", "else"]
  1084. return tokenized_text
  1085. def _tokenize(self, text, **kwargs):
  1086. """
  1087. Converts a string in a sequence of tokens (string), using the tokenizer. Split in words for word-based
  1088. vocabulary or sub-words for sub-word-based vocabularies (BPE/SentencePieces/WordPieces).
  1089. Do NOT take care of added tokens.
  1090. """
  1091. raise NotImplementedError
  1092. def convert_tokens_to_ids(self, tokens):
  1093. if tokens is None:
  1094. return None
  1095. if isinstance(tokens, str):
  1096. return self._convert_token_to_id_with_added_voc(tokens)
  1097. ids = []
  1098. for token in tokens:
  1099. ids.append(self._convert_token_to_id_with_added_voc(token))
  1100. return ids
  1101. def _convert_token_to_id_with_added_voc(self, token):
  1102. if token is None:
  1103. return None
  1104. if token in self.added_tokens_encoder:
  1105. return self.added_tokens_encoder[token]
  1106. return self._convert_token_to_id(token)
  1107. def _convert_token_to_id(self, token):
  1108. return self.vocab.to_indices(token)
  1109. def convert_tokens_to_string(self, tokens):
  1110. """
  1111. Converts a sequence of tokens (list of string) to a single string by
  1112. using ``' '.join(tokens)`` .
  1113. Args:
  1114. tokens (list[str]): A sequence of tokens.
  1115. Returns:
  1116. str: Converted string.
  1117. """
  1118. return " ".join(tokens)
  1119. def convert_ids_to_tokens(self, ids, skip_special_tokens=False):
  1120. if isinstance(ids, int):
  1121. if ids in self.added_tokens_decoder:
  1122. return self.added_tokens_decoder[ids]
  1123. else:
  1124. return self._convert_id_to_token(ids)
  1125. tokens = []
  1126. for index in ids:
  1127. index = int(index)
  1128. if skip_special_tokens and index in self.all_special_ids:
  1129. continue
  1130. if index in self.added_tokens_decoder:
  1131. tokens.append(self.added_tokens_decoder[index])
  1132. else:
  1133. tokens.append(self._convert_id_to_token(index))
  1134. return tokens
  1135. def _convert_id_to_token(self, index):
  1136. return self.vocab.to_tokens(index)
  1137. @staticmethod
  1138. def load_vocabulary(
  1139. filepath,
  1140. unk_token=None,
  1141. pad_token=None,
  1142. bos_token=None,
  1143. eos_token=None,
  1144. **kwargs,
  1145. ):
  1146. """
  1147. Instantiate an instance of `Vocab` from a file reserving all tokens
  1148. by using `Vocab.from_dict`. The file contains a token per line, and the
  1149. line number would be the index of corresponding token.
  1150. Args:
  1151. filepath (str): path of file to construct vocabulary.
  1152. unk_token (str): special token for unknown token. If no need, it also
  1153. could be `None`. Defaults to `None`.
  1154. pad_token (str): special token for padding token. If no need, it also
  1155. could be `None`. Defaults to `None`.
  1156. bos_token (str): special token for bos token. If no need, it also
  1157. could be `None`. Defaults to `None`.
  1158. eos_token (str): special token for eos token. If no need, it also
  1159. could be `None`. Defaults to `None`.
  1160. **kwargs (dict): keyword arguments for `Vocab.from_dict`.
  1161. Returns:
  1162. Vocab: An instance of `Vocab`.
  1163. """
  1164. token_to_idx = {}
  1165. with io.open(filepath, "r", encoding="utf-8") as f:
  1166. for index, line in enumerate(f):
  1167. token = line.rstrip("\n")
  1168. token_to_idx[token] = int(index)
  1169. vocab = Vocab.from_dict(
  1170. token_to_idx,
  1171. unk_token=unk_token,
  1172. pad_token=pad_token,
  1173. bos_token=bos_token,
  1174. eos_token=eos_token,
  1175. **kwargs,
  1176. )
  1177. return vocab
  1178. @staticmethod
  1179. def save_vocabulary(filepath, vocab):
  1180. """
  1181. Save all tokens to a vocabulary file. The file contains a token per line,
  1182. and the line number would be the index of corresponding token.
  1183. Args:
  1184. filepath (str): File path to be saved to.
  1185. vocab (Vocab|dict): The `Vocab` or `dict` instance to be saved.
  1186. """
  1187. if isinstance(vocab, Vocab):
  1188. tokens = vocab.idx_to_token
  1189. else:
  1190. tokens = sorted(vocab.keys(), key=lambda token: vocab[token])
  1191. with io.open(filepath, "w", encoding="utf-8") as f:
  1192. for token in tokens:
  1193. f.write(token + "\n")
  1194. def get_special_tokens_mask(
  1195. self, token_ids_0, token_ids_1=None, already_has_special_tokens=False
  1196. ):
  1197. """
  1198. Retrieves sequence ids from a token list that has no special tokens added. This method is called when adding
  1199. special tokens using the tokenizer ``encode`` methods.
  1200. Args:
  1201. token_ids_0 (List[int]): List of ids of the first sequence.
  1202. token_ids_1 (List[int], optional): List of ids of the second sequence.
  1203. already_has_special_tokens (bool, optional): Whether or not the token list is already
  1204. formatted with special tokens for the model. Defaults to None.
  1205. Returns:
  1206. results (List[int]): The list of integers in the range [0, 1]:
  1207. 1 for a special token, 0 for a sequence token.
  1208. """
  1209. if already_has_special_tokens:
  1210. if token_ids_1 is not None:
  1211. raise ValueError(
  1212. "You should not supply a second sequence if the provided sequence of "
  1213. "ids is already formatted with special tokens for the model."
  1214. )
  1215. return super().get_special_tokens_mask(
  1216. token_ids_0=token_ids_0,
  1217. token_ids_1=token_ids_1,
  1218. already_has_special_tokens=True,
  1219. )
  1220. return [0] * ((len(token_ids_1) if token_ids_1 else 0) + len(token_ids_0))
  1221. def num_special_tokens_to_add(self, pair):
  1222. """
  1223. Returns the number of added tokens when encoding a sequence with special tokens.
  1224. Args:
  1225. pair (bool, optional):
  1226. Whether the number of added tokens should be computed in the case of a sequence pair or a single
  1227. sequence. Defaults to `False`.
  1228. Returns:
  1229. int: Number of special tokens added to sequences.
  1230. """
  1231. token_ids_0 = []
  1232. token_ids_1 = []
  1233. return len(
  1234. self.build_inputs_with_special_tokens(
  1235. token_ids_0, token_ids_1 if pair else None
  1236. )
  1237. )
  1238. def _encode_plus(
  1239. self,
  1240. text: Union[TextInput, PreTokenizedInput, EncodedInput],
  1241. text_pair: Optional[Union[TextInput, PreTokenizedInput, EncodedInput]] = None,
  1242. add_special_tokens: bool = True,
  1243. padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD,
  1244. truncation_strategy: TruncationStrategy = TruncationStrategy.DO_NOT_TRUNCATE,
  1245. max_length: Optional[int] = None,
  1246. stride: int = 0,
  1247. is_split_into_words: bool = False,
  1248. pad_to_multiple_of: Optional[int] = None,
  1249. return_tensors: Optional[Union[str, TensorType]] = None,
  1250. return_position_ids: Optional[bool] = None,
  1251. return_token_type_ids: Optional[bool] = None,
  1252. return_attention_mask: Optional[bool] = None,
  1253. return_overflowing_tokens: bool = False,
  1254. return_special_tokens_mask: bool = False,
  1255. return_offsets_mapping: bool = False,
  1256. return_length: bool = False,
  1257. verbose: bool = True,
  1258. **kwargs,
  1259. ) -> BatchEncoding:
  1260. def get_input_ids(text):
  1261. if isinstance(text, str):
  1262. tokens = self.tokenize(text, **kwargs)
  1263. return self.convert_tokens_to_ids(tokens)
  1264. elif (
  1265. isinstance(text, (list, tuple))
  1266. and len(text) > 0
  1267. and isinstance(text[0], str)
  1268. ):
  1269. if is_split_into_words:
  1270. tokens = list(
  1271. itertools.chain(
  1272. *(
  1273. self.tokenize(t, is_split_into_words=True, **kwargs)
  1274. for t in text
  1275. )
  1276. )
  1277. )
  1278. return self.convert_tokens_to_ids(tokens)
  1279. else:
  1280. return self.convert_tokens_to_ids(text)
  1281. elif (
  1282. isinstance(text, (list, tuple))
  1283. and len(text) > 0
  1284. and isinstance(text[0], int)
  1285. ):
  1286. return text
  1287. else:
  1288. if is_split_into_words:
  1289. raise ValueError(
  1290. f"Input {text} is not valid. Should be a string or a list/tuple of strings when `is_split_into_words=True`."
  1291. )
  1292. else:
  1293. raise ValueError(
  1294. f"Input {text} is not valid. Should be a string, a list/tuple of strings or a list/tuple of integers."
  1295. )
  1296. first_ids = get_input_ids(text)
  1297. second_ids = get_input_ids(text_pair) if text_pair is not None else None
  1298. if return_offsets_mapping:
  1299. kwargs["text"] = text
  1300. kwargs["text_pair"] = text_pair
  1301. return self.prepare_for_model(
  1302. first_ids,
  1303. pair_ids=second_ids,
  1304. add_special_tokens=add_special_tokens,
  1305. padding=padding_strategy.value,
  1306. truncation=truncation_strategy.value,
  1307. max_length=max_length,
  1308. stride=stride,
  1309. pad_to_multiple_of=pad_to_multiple_of,
  1310. return_tensors=return_tensors,
  1311. prepend_batch_axis=True,
  1312. return_position_ids=return_position_ids,
  1313. return_attention_mask=return_attention_mask,
  1314. return_token_type_ids=return_token_type_ids,
  1315. return_overflowing_tokens=return_overflowing_tokens,
  1316. return_special_tokens_mask=return_special_tokens_mask,
  1317. return_offsets_mapping=return_offsets_mapping,
  1318. return_length=return_length,
  1319. verbose=verbose,
  1320. **kwargs,
  1321. )
  1322. def _batch_encode_plus(
  1323. self,
  1324. batch_text_or_text_pairs: Union[
  1325. List[TextInput],
  1326. List[TextInputPair],
  1327. List[PreTokenizedInput],
  1328. List[PreTokenizedInputPair],
  1329. List[EncodedInput],
  1330. List[EncodedInputPair],
  1331. ],
  1332. add_special_tokens: bool = True,
  1333. padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD,
  1334. truncation_strategy: TruncationStrategy = TruncationStrategy.DO_NOT_TRUNCATE,
  1335. max_length: Optional[int] = None,
  1336. stride: int = 0,
  1337. is_split_into_words: bool = False,
  1338. pad_to_multiple_of: Optional[int] = None,
  1339. return_position_ids: Optional[bool] = None,
  1340. return_tensors: Optional[Union[str, TensorType]] = None,
  1341. return_token_type_ids: Optional[bool] = None,
  1342. return_attention_mask: Optional[bool] = None,
  1343. return_overflowing_tokens: bool = False,
  1344. return_special_tokens_mask: bool = False,
  1345. return_dict: bool = True,
  1346. return_offsets_mapping: bool = False,
  1347. return_length: bool = False,
  1348. verbose: bool = True,
  1349. **kwargs,
  1350. ) -> BatchEncoding:
  1351. def get_input_ids(text):
  1352. if isinstance(text, str):
  1353. tokens = self.tokenize(text, **kwargs)
  1354. return self.convert_tokens_to_ids(tokens)
  1355. elif (
  1356. isinstance(text, (list, tuple))
  1357. and len(text) > 0
  1358. and isinstance(text[0], str)
  1359. ):
  1360. if is_split_into_words:
  1361. tokens = list(
  1362. itertools.chain(
  1363. *(
  1364. self.tokenize(t, is_split_into_words=True, **kwargs)
  1365. for t in text
  1366. )
  1367. )
  1368. )
  1369. return self.convert_tokens_to_ids(tokens)
  1370. else:
  1371. return self.convert_tokens_to_ids(text)
  1372. elif (
  1373. isinstance(text, (list, tuple))
  1374. and len(text) > 0
  1375. and isinstance(text[0], int)
  1376. ):
  1377. return text
  1378. else:
  1379. raise ValueError(
  1380. "Input is not valid. Should be a string, a list/tuple of strings or a list/tuple of integers."
  1381. )
  1382. input_ids = []
  1383. for ids_or_pair_ids in batch_text_or_text_pairs:
  1384. if not isinstance(ids_or_pair_ids, (list, tuple)):
  1385. ids, pair_ids = ids_or_pair_ids, None
  1386. elif is_split_into_words and not isinstance(
  1387. ids_or_pair_ids[0], (list, tuple)
  1388. ):
  1389. ids, pair_ids = ids_or_pair_ids, None
  1390. else:
  1391. ids, pair_ids = ids_or_pair_ids
  1392. first_ids = get_input_ids(ids)
  1393. second_ids = get_input_ids(pair_ids) if pair_ids is not None else None
  1394. input_ids.append((first_ids, second_ids))
  1395. if stride > 0 and second_ids is not None:
  1396. kwargs["batch_text_or_text_pairs"] = batch_text_or_text_pairs
  1397. else:
  1398. if return_offsets_mapping:
  1399. has_pair = False
  1400. if len(batch_text_or_text_pairs) > 0:
  1401. if isinstance(batch_text_or_text_pairs[0], (list, tuple)):
  1402. has_pair = True
  1403. kwargs["texts"] = None
  1404. kwargs["text_pairs"] = None
  1405. if has_pair:
  1406. kwargs["texts"] = [text[0] for text in batch_text_or_text_pairs]
  1407. kwargs["text_pairs"] = [
  1408. text[1] for text in batch_text_or_text_pairs
  1409. ]
  1410. else:
  1411. kwargs["texts"] = [text for text in batch_text_or_text_pairs]
  1412. batch_outputs = self._batch_prepare_for_model(
  1413. input_ids,
  1414. add_special_tokens=add_special_tokens,
  1415. padding_strategy=padding_strategy,
  1416. truncation_strategy=truncation_strategy,
  1417. max_length=max_length,
  1418. stride=stride,
  1419. pad_to_multiple_of=pad_to_multiple_of,
  1420. return_position_ids=return_position_ids,
  1421. return_attention_mask=return_attention_mask,
  1422. return_token_type_ids=return_token_type_ids,
  1423. return_overflowing_tokens=return_overflowing_tokens,
  1424. return_special_tokens_mask=return_special_tokens_mask,
  1425. return_dict=return_dict,
  1426. return_offsets_mapping=return_offsets_mapping,
  1427. return_length=return_length,
  1428. return_tensors=return_tensors,
  1429. verbose=verbose,
  1430. **kwargs,
  1431. )
  1432. return batch_outputs
  1433. def _batch_prepare_for_model(
  1434. self,
  1435. batch_ids_pairs: List[Union[PreTokenizedInputPair, Tuple[List[int], None]]],
  1436. add_special_tokens: bool = True,
  1437. padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD,
  1438. truncation_strategy: TruncationStrategy = TruncationStrategy.DO_NOT_TRUNCATE,
  1439. max_length: Optional[int] = None,
  1440. stride: int = 0,
  1441. pad_to_multiple_of: Optional[int] = None,
  1442. return_position_ids: Optional[bool] = None,
  1443. return_tensors: Optional[str] = None,
  1444. return_token_type_ids: Optional[bool] = None,
  1445. return_attention_mask: Optional[bool] = None,
  1446. return_overflowing_tokens: bool = False,
  1447. return_special_tokens_mask: bool = False,
  1448. return_dict: bool = True,
  1449. return_offsets_mapping: bool = False,
  1450. return_length: bool = False,
  1451. verbose: bool = True,
  1452. **kwargs,
  1453. ) -> BatchEncoding:
  1454. """
  1455. Prepares a sequence of input id, or a pair of sequences of inputs ids so that it can be used by the model. It
  1456. adds special tokens, truncates sequences if overflowing while taking into account the special tokens and
  1457. manages a moving window (with user defined stride) for overflowing tokens
  1458. Args:
  1459. batch_ids_pairs: list of tokenized input ids or input ids pairs
  1460. """
  1461. if return_token_type_ids and not add_special_tokens:
  1462. raise ValueError(
  1463. "Asking to return token_type_ids while setting add_special_tokens to False "
  1464. "results in an undefined behavior. Please set add_special_tokens to True or "
  1465. "set return_token_type_ids to None."
  1466. )
  1467. batch_outputs = {}
  1468. batch_outputs_list = []
  1469. for example_id, (first_ids, second_ids) in enumerate(batch_ids_pairs):
  1470. if stride > 0 and second_ids is not None:
  1471. if return_token_type_ids is None:
  1472. return_token_type_ids = "token_type_ids" in self.model_input_names
  1473. if return_attention_mask is None:
  1474. return_attention_mask = "attention_mask" in self.model_input_names
  1475. max_len_for_pair = (
  1476. max_length
  1477. - len(first_ids)
  1478. - (
  1479. self.num_special_tokens_to_add(pair=True)
  1480. if add_special_tokens
  1481. else 0
  1482. )
  1483. )
  1484. text, text_pair = kwargs["batch_text_or_text_pairs"][example_id]
  1485. token_offset_mapping = self.get_offset_mapping(text)
  1486. token_pair_offset_mapping = self.get_offset_mapping(text_pair)
  1487. offset = 0
  1488. while offset < len(second_ids):
  1489. encoded_inputs = {}
  1490. length = len(second_ids) - offset
  1491. if length > max_len_for_pair:
  1492. length = max_len_for_pair
  1493. ids = first_ids
  1494. pair_ids = second_ids[offset : offset + length]
  1495. pair = bool(pair_ids is not None)
  1496. mapping = token_offset_mapping
  1497. pair_mapping = token_pair_offset_mapping[offset : offset + length]
  1498. if add_special_tokens:
  1499. offset_mapping = self.build_offset_mapping_with_special_tokens(
  1500. mapping, pair_mapping
  1501. )
  1502. sequence = self.build_inputs_with_special_tokens(ids, pair_ids)
  1503. token_type_ids = self.create_token_type_ids_from_sequences(
  1504. ids, pair_ids
  1505. )
  1506. else:
  1507. offset_mapping = mapping + pair_mapping
  1508. sequence = ids + pair_ids if pair else ids
  1509. token_type_ids = [0] * len(ids) + (
  1510. [0] * len(pair_ids) if pair else []
  1511. )
  1512. encoded_inputs["offset_mapping"] = offset_mapping
  1513. # Build output dictionnary
  1514. encoded_inputs["input_ids"] = sequence
  1515. if return_token_type_ids:
  1516. encoded_inputs["token_type_ids"] = token_type_ids
  1517. if return_special_tokens_mask:
  1518. if add_special_tokens:
  1519. encoded_inputs["special_tokens_mask"] = (
  1520. self.get_special_tokens_mask(ids, pair_ids)
  1521. )
  1522. else:
  1523. encoded_inputs["special_tokens_mask"] = [0] * len(sequence)
  1524. # Check lengths
  1525. self._eventual_warn_about_too_long_sequence(
  1526. encoded_inputs["input_ids"], max_length, verbose
  1527. )
  1528. if return_position_ids:
  1529. encoded_inputs["position_ids"] = list(
  1530. range(len(encoded_inputs["input_ids"]))
  1531. )
  1532. if return_length:
  1533. encoded_inputs["length"] = len(encoded_inputs["input_ids"])
  1534. encoded_inputs["seq_len"] = encoded_inputs["length"]
  1535. encoded_inputs["overflow_to_sample"] = example_id
  1536. for key, value in encoded_inputs.items():
  1537. if key not in batch_outputs:
  1538. batch_outputs[key] = []
  1539. batch_outputs[key].append(value)
  1540. if offset + length == len(second_ids):
  1541. break
  1542. offset += min(length, stride)
  1543. else:
  1544. if return_offsets_mapping:
  1545. kwargs["text"] = kwargs["texts"][example_id]
  1546. kwargs["text_pair"] = None
  1547. if kwargs["text_pairs"] is not None:
  1548. kwargs["text_pair"] = kwargs["text_pairs"][example_id]
  1549. encoded_inputs = self.prepare_for_model(
  1550. first_ids,
  1551. second_ids,
  1552. add_special_tokens=add_special_tokens,
  1553. padding=PaddingStrategy.DO_NOT_PAD.value, # we pad in batch afterward
  1554. truncation=truncation_strategy.value,
  1555. max_length=max_length,
  1556. stride=stride,
  1557. pad_to_multiple_of=None, # we pad in batch afterward
  1558. return_position_ids=return_position_ids, # we pad in batch afterward
  1559. return_attention_mask=False, # we pad in batch afterward
  1560. return_token_type_ids=return_token_type_ids,
  1561. return_overflowing_tokens=return_overflowing_tokens,
  1562. return_special_tokens_mask=return_special_tokens_mask,
  1563. return_offsets_mapping=return_offsets_mapping,
  1564. return_length=return_length,
  1565. return_tensors=None, # We convert the whole batch to tensors at the end
  1566. prepend_batch_axis=False,
  1567. verbose=verbose,
  1568. **kwargs,
  1569. )
  1570. for key, value in encoded_inputs.items():
  1571. if key not in batch_outputs:
  1572. batch_outputs[key] = []
  1573. batch_outputs[key].append(value)
  1574. batch_outputs = self.pad(
  1575. batch_outputs,
  1576. padding=padding_strategy.value,
  1577. max_length=max_length,
  1578. pad_to_multiple_of=pad_to_multiple_of,
  1579. return_attention_mask=return_attention_mask,
  1580. )
  1581. if return_dict:
  1582. batch_outputs = BatchEncoding(batch_outputs, tensor_type=return_tensors)
  1583. return batch_outputs
  1584. else:
  1585. for k, v in batch_outputs.items():
  1586. for i in range(len(v)):
  1587. if i >= len(batch_outputs_list):
  1588. batch_outputs_list.append({k: v[i]})
  1589. else:
  1590. batch_outputs_list[i][k] = v[i]
  1591. return batch_outputs_list
  1592. def _get_bert_like_offset_mapping(self, text: str):
  1593. """
  1594. Returns the map of tokens and the start and end index of their start and end character.
  1595. Modified from https://github.com/bojone/bert4keras/blob/master/bert4keras/tokenizers.py#L372
  1596. Args:
  1597. text (str):
  1598. Input text.
  1599. Returns:
  1600. list: The offset map of input text.
  1601. """
  1602. if text is None:
  1603. return None
  1604. split_tokens = self.tokenize(text)
  1605. normalized_text, char_mapping = "", []
  1606. for i, ch in enumerate(text):
  1607. if hasattr(self, "do_lower_case") and self.do_lower_case:
  1608. ch = ch.lower()
  1609. if self.basic_tokenizer.strip_accents is not False:
  1610. ch = unicodedata.normalize("NFD", ch)
  1611. ch = "".join([c for c in ch if unicodedata.category(c) != "Mn"])
  1612. elif self.basic_tokenizer.strip_accents:
  1613. ch = unicodedata.normalize("NFD", ch)
  1614. ch = "".join([c for c in ch if unicodedata.category(c) != "Mn"])
  1615. ch = "".join(
  1616. [
  1617. c
  1618. for c in ch
  1619. if not (ord(c) == 0 or ord(c) == 0xFFFD or _is_control(c))
  1620. ]
  1621. )
  1622. normalized_text += ch
  1623. char_mapping.extend([i] * len(ch))
  1624. text, token_mapping, offset = normalized_text, [], 0
  1625. char_mapping_indexes = []
  1626. for index, token in enumerate(split_tokens):
  1627. if token[:2] == "##":
  1628. token = token[2:]
  1629. if token in self.all_special_tokens:
  1630. token = (
  1631. token.lower()
  1632. if hasattr(self, "do_lower_case") and self.do_lower_case
  1633. else token
  1634. )
  1635. # The greek letter "sigma" has 2 forms of lowercase, σ and ς respectively.
  1636. # When used as a final letter of a word, the final form (ς) is used. Otherwise, the form (σ) is used.
  1637. # https://latin.stackexchange.com/questions/6168/how-and-when-did-we-get-two-forms-of-sigma
  1638. if "σ" in token or "ς" in token:
  1639. start = (
  1640. text[offset:].replace("ς", "σ").index(token.replace("ς", "σ"))
  1641. + offset
  1642. )
  1643. else:
  1644. # try to fix: https://github.com/PaddlePaddle/PaddleNLP/issues/3985
  1645. if token not in text[offset:]:
  1646. # check whether there are consecutive UNK tokens, eg: ['好', '[UNK]', '[UNK]', 'good']
  1647. if (
  1648. index < len(split_tokens) - 1
  1649. and split_tokens[index + 1] in self.all_special_tokens
  1650. ):
  1651. start = offset
  1652. token = " " # only contains one char
  1653. else:
  1654. start = -1
  1655. else:
  1656. start = text[offset:].index(token) + offset
  1657. end = start + len(token)
  1658. char_mapping_indexes.append([start, end])
  1659. if start != -1:
  1660. offset = end
  1661. token_mapping = []
  1662. for index, (start, end) in enumerate(char_mapping_indexes):
  1663. if start == -1:
  1664. # init start
  1665. if index == 0:
  1666. start = 0
  1667. else:
  1668. start = char_mapping_indexes[index - 1][1]
  1669. # init end
  1670. if index == len(char_mapping_indexes) - 1:
  1671. end = len(char_mapping)
  1672. else:
  1673. # next start
  1674. end = char_mapping_indexes[index + 1][0]
  1675. token_mapping.append((char_mapping[start], char_mapping[end - 1] + 1))
  1676. return token_mapping
  1677. def get_offset_mapping(self, text: str, split_tokens: Optional[List[str]] = None):
  1678. """
  1679. Returns the map of tokens and the start and end index of their start and end character.
  1680. Modified from https://github.com/bojone/bert4keras/blob/master/bert4keras/tokenizers.py#L372
  1681. Args:
  1682. text (str):
  1683. Input text.
  1684. split_tokens (Optional[List[str]]):
  1685. the tokens which has been split which can accelerate the operation.
  1686. Returns:
  1687. list: The offset map of input text.
  1688. """
  1689. if text is None:
  1690. return None
  1691. split_tokens = self.tokenize(text)
  1692. # bert-like tokenizer use the old-school code block
  1693. if hasattr(self, "basic_tokenizer") or hasattr(self, "wordpiece_tokenizer"):
  1694. return self._get_bert_like_offset_mapping(text)
  1695. if not split_tokens:
  1696. split_tokens = self.tokenize(text)
  1697. normalized_text, char_mapping = "", []
  1698. for i, ch in enumerate(text):
  1699. normalized_text += normalize_chars(ch)
  1700. char_mapping.extend([i] * len(ch))
  1701. text, token_mapping, offset = normalized_text, [], 0
  1702. do_lower_case = getattr(self, "do_lower_case", False)
  1703. # lower the text if the token is lower-cased
  1704. # keep align with token
  1705. if do_lower_case:
  1706. text = text.lower()
  1707. char_mapping_indexes = []
  1708. for token in split_tokens:
  1709. # convert tokens into original string
  1710. token: str = self.convert_tokens_to_string(token).strip()
  1711. if token in self.all_special_tokens:
  1712. if do_lower_case:
  1713. token = token.lower()
  1714. # The greek letter "sigma" has 2 forms of lowercase, σ and ς respectively.
  1715. # When used as a final letter of a word, the final form (ς) is used. Otherwise, the form (σ) is used.
  1716. # https://latin.stackexchange.com/questions/6168/how-and-when-did-we-get-two-forms-of-sigma
  1717. if "σ" in token or "ς" in token:
  1718. start = (
  1719. text[offset:].replace("ς", "σ").index(token.replace("ς", "σ"))
  1720. + offset
  1721. )
  1722. else:
  1723. # try to fix: https://github.com/PaddlePaddle/PaddleNLP/issues/3985
  1724. if token not in text[offset:]:
  1725. start = -1
  1726. else:
  1727. start = text[offset:].index(token) + offset
  1728. end = start + len(token)
  1729. char_mapping_indexes.append([start, end])
  1730. if start != -1:
  1731. offset = end
  1732. token_mapping = []
  1733. for index, (start, end) in enumerate(char_mapping_indexes):
  1734. if start == -1:
  1735. # init start
  1736. if index == 0:
  1737. start = 0
  1738. else:
  1739. start = char_mapping_indexes[index - 1][1]
  1740. # init end
  1741. if index == len(char_mapping_indexes) - 1:
  1742. end = len(char_mapping)
  1743. else:
  1744. # next start
  1745. end = char_mapping_indexes[index + 1][0]
  1746. token_mapping.append((char_mapping[start], char_mapping[end - 1] + 1))
  1747. return token_mapping
  1748. def _decode(
  1749. self,
  1750. token_ids: List[int],
  1751. skip_special_tokens: bool = False,
  1752. clean_up_tokenization_spaces: bool = True,
  1753. spaces_between_special_tokens: bool = True,
  1754. **kwargs,
  1755. ) -> str:
  1756. if isinstance(token_ids, np.ndarray):
  1757. token_ids = token_ids.tolist()
  1758. self._decode_use_source_tokenizer = kwargs.pop("use_source_tokenizer", False)
  1759. filtered_tokens = self.convert_ids_to_tokens(
  1760. token_ids, skip_special_tokens=skip_special_tokens
  1761. )
  1762. # To avoid mixing byte-level and unicode for byte-level BPT
  1763. # we need to build string separately for added tokens and byte-level tokens
  1764. # cf. https://github.com/huggingface/transformers/issues/1133
  1765. sub_texts = []
  1766. current_sub_text = []
  1767. for token in filtered_tokens:
  1768. if skip_special_tokens and token in self.all_special_ids:
  1769. continue
  1770. if token in self.added_tokens_encoder:
  1771. if current_sub_text:
  1772. sub_texts.append(self.convert_tokens_to_string(current_sub_text))
  1773. current_sub_text = []
  1774. sub_texts.append(token)
  1775. else:
  1776. current_sub_text.append(token)
  1777. if current_sub_text:
  1778. sub_texts.append(self.convert_tokens_to_string(current_sub_text))
  1779. if spaces_between_special_tokens:
  1780. text = " ".join(sub_texts)
  1781. else:
  1782. text = "".join(sub_texts)
  1783. if clean_up_tokenization_spaces:
  1784. clean_text = self.clean_up_tokenization(text)
  1785. return clean_text
  1786. else:
  1787. return text
  1788. def decode_token(
  1789. self,
  1790. all_input_ids: List[int],
  1791. prefix_offset: int = 0,
  1792. read_offset: int = 0,
  1793. ) -> Tuple[str, int, int]:
  1794. """tokenizer decoding for the streaming generation use case. This method can be overrided for tokenizer that doesn't follow this API"""
  1795. # The prefix text is necessary only to defeat cleanup algorithms in the decode
  1796. # which decide to add a space or not depending on the surrounding ids.
  1797. prefix_text = self.decode(
  1798. all_input_ids[prefix_offset:read_offset], skip_special_tokens=False
  1799. )
  1800. new_text = self.decode(all_input_ids[prefix_offset:], skip_special_tokens=False)
  1801. if len(new_text) > len(prefix_text) and not new_text.endswith("�"):
  1802. # utf-8 char at the end means it's a potential unfinished byte sequence
  1803. # from byte fallback tokenization.
  1804. # If it's in the middle, it's probably a real invalid id generated
  1805. # by the model
  1806. prefix_index = new_text.index(prefix_text)
  1807. new_text = new_text[prefix_index + len(prefix_text) :]
  1808. return new_text, read_offset, len(all_input_ids)
  1809. else:
  1810. return "", prefix_offset, read_offset
  1811. def _is_control(char):
  1812. """Checks whether `chars` is a control character."""
  1813. # These are technically control characters but we count them as whitespace
  1814. # characters.
  1815. if char == "\t" or char == "\n" or char == "\r":
  1816. return False
  1817. cat = unicodedata.category(char)
  1818. if cat.startswith("C"):
  1819. return True
  1820. return False
  1821. def _is_punctuation(char):
  1822. """Checks whether `chars` is a punctuation character."""
  1823. cp = ord(char)
  1824. # We treat all non-letter/number ASCII as punctuation.
  1825. # Characters such as "^", "$", and "`" are not in the Unicode
  1826. # Punctuation class but we treat them as punctuation anyways, for
  1827. # consistency.
  1828. if (
  1829. (cp >= 33 and cp <= 47)
  1830. or (cp >= 58 and cp <= 64)
  1831. or (cp >= 91 and cp <= 96)
  1832. or (cp >= 123 and cp <= 126)
  1833. ):
  1834. return True
  1835. cat = unicodedata.category(char)
  1836. if cat.startswith("P"):
  1837. return True
  1838. return False
  1839. def _is_symbol(char):
  1840. """Check whether CP is the codepoint of a Symbol character."""
  1841. cp = ord(char)
  1842. if unicodedata.category(char).startswith("S") or (
  1843. cp in [0x00AD, 0x00B2, 0x00BA, 0x3007, 0x00B5, 0x00D8, 0x014B, 0x01B1]
  1844. ):
  1845. return True
  1846. return False
  1847. def _is_whitespace(char):
  1848. """
  1849. Checks whether `chars` is a whitespace character.
  1850. """
  1851. # \t, \n, and \r are technically contorl characters but we treat them
  1852. # as whitespace since they are generally considered as such.
  1853. if char == " " or char == "\t" or char == "\n" or char == "\r":
  1854. return True
  1855. cat = unicodedata.category(char)
  1856. if cat == "Zs":
  1857. return True
  1858. return False
  1859. def convert_to_unicode(text):
  1860. """
  1861. Converts `text` to Unicode (if it's not already), assuming utf-8 input.
  1862. Args:
  1863. text (str|bytes): Text to be converted to unicode.
  1864. Returns:
  1865. str: converted text.
  1866. """
  1867. if isinstance(text, str):
  1868. return text
  1869. elif isinstance(text, bytes):
  1870. return text.decode("utf-8", "ignore")
  1871. else:
  1872. raise ValueError("Unsupported string type: %s" % (type(text)))
  1873. def whitespace_tokenize(text):
  1874. """
  1875. Runs basic whitespace cleaning and splitting on a peice of text.
  1876. Args:
  1877. text (str): Text to be tokenized.
  1878. Returns:
  1879. list(str): Token list.
  1880. """
  1881. text = text.strip()
  1882. if not text:
  1883. return []
  1884. tokens = text.split()
  1885. return tokens