tokenizer_utils.py 83 KB

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