tokenization.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546
  1. # Copyright 2021-2022 The Alibaba DAMO NLP Team Authors.
  2. # Copyright 2020 Microsoft and the HuggingFace Inc. team.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. """Tokenization classes for DeBERTa. mainly copied from :module:`~transformers.tokenization_deberta`"""
  16. import os
  17. import unicodedata
  18. from typing import Any, Dict, List, Optional, Tuple
  19. import sentencepiece as sp
  20. from transformers.tokenization_utils import PreTrainedTokenizer
  21. PRETRAINED_VOCAB_FILES_MAP = {'vocab_file': {}}
  22. PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES = {}
  23. PRETRAINED_INIT_CONFIGURATION = {}
  24. VOCAB_FILES_NAMES = {'vocab_file': 'spm.model'}
  25. class DebertaV2Tokenizer(PreTrainedTokenizer):
  26. r"""
  27. Constructs a DeBERTa-v2 tokenizer. Based on [SentencePiece](https://github.com/google/sentencepiece)
  28. and [jieba](https://github.com/fxsjy/jieba).
  29. Args:
  30. vocab_file (`str`):
  31. [SentencePiece](https://github.com/google/sentencepiece) file (generally has a *.spm* extension) that
  32. contains the vocabulary necessary to instantiate a tokenizer.
  33. do_lower_case (`bool`, *optional*, defaults to `False`):
  34. Whether or not to lowercase the input when tokenizing.
  35. bos_token (`string`, *optional*, defaults to `"[CLS]"`):
  36. The beginning of sequence token that was used during pre-training. Can be used a sequence classifier token.
  37. When building a sequence using special tokens, this is not the token that is used for the beginning of
  38. sequence. The token used is the `cls_token`.
  39. eos_token (`string`, *optional*, defaults to `"[SEP]"`):
  40. The end of sequence token. When building a sequence using special tokens, this is not the token that is
  41. used for the end of sequence. The token used is the `sep_token`.
  42. unk_token (`str`, *optional*, defaults to `"[UNK]"`):
  43. The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
  44. token instead.
  45. sep_token (`str`, *optional*, defaults to `"[SEP]"`):
  46. The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
  47. sequence classification or for a text and a question for question answering. It is also used as the last
  48. token of a sequence built with special tokens.
  49. pad_token (`str`, *optional*, defaults to `"[PAD]"`):
  50. The token used for padding, for example when batching sequences of different lengths.
  51. cls_token (`str`, *optional*, defaults to `"[CLS]"`):
  52. The classifier token which is used when doing sequence classification (classification of the whole sequence
  53. instead of per-token classification). It is the first token of the sequence when built with special tokens.
  54. mask_token (`str`, *optional*, defaults to `"[MASK]"`):
  55. The token used for masking values. This is the token used when training this model with masked language
  56. modeling. This is the token which the model will try to predict.
  57. sp_model_kwargs (`dict`, *optional*):
  58. Will be passed to the `SentencePieceProcessor.__init__()` method. The [Python wrapper for
  59. SentencePiece](https://github.com/google/sentencepiece/tree/master/python) can be used, among other things,
  60. to set:
  61. - `enable_sampling`: Enable subword regularization.
  62. - `nbest_size`: Sampling parameters for unigram. Invalid for BPE-Dropout.
  63. - `nbest_size = {0,1}`: No sampling is performed.
  64. - `nbest_size > 1`: samples from the nbest_size results.
  65. - `nbest_size < 0`: assuming that nbest_size is infinite and samples from the all hypothesis (lattice)
  66. using forward-filtering-and-backward-sampling algorithm.
  67. - `alpha`: Smoothing parameter for unigram sampling, and dropout probability of merge operations for
  68. BPE-dropout.
  69. """
  70. vocab_files_names = VOCAB_FILES_NAMES
  71. pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP
  72. pretrained_init_configuration = PRETRAINED_INIT_CONFIGURATION
  73. max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
  74. def __init__(self,
  75. vocab_file,
  76. do_lower_case=False,
  77. split_by_punct=False,
  78. split_chinese=True,
  79. bos_token='[CLS]',
  80. eos_token='[SEP]',
  81. unk_token='[UNK]',
  82. sep_token='[SEP]',
  83. pad_token='[PAD]',
  84. cls_token='[CLS]',
  85. mask_token='[MASK]',
  86. sp_model_kwargs: Optional[Dict[str, Any]] = None,
  87. **kwargs) -> None:
  88. self.sp_model_kwargs = {} if sp_model_kwargs is None else sp_model_kwargs
  89. super().__init__(
  90. do_lower_case=do_lower_case,
  91. bos_token=bos_token,
  92. eos_token=eos_token,
  93. unk_token=unk_token,
  94. sep_token=sep_token,
  95. pad_token=pad_token,
  96. cls_token=cls_token,
  97. mask_token=mask_token,
  98. split_by_punct=split_by_punct,
  99. split_chinese=split_chinese,
  100. sp_model_kwargs=self.sp_model_kwargs,
  101. **kwargs,
  102. )
  103. if not os.path.isfile(vocab_file):
  104. raise ValueError(
  105. f"Can't find a vocabulary file at path '{vocab_file}'. To load the vocabulary from a Google pretrained"
  106. ' model use `tokenizer = AutoTokenizer.from_pretrained(PRETRAINED_MODEL_NAME)`'
  107. )
  108. self.do_lower_case = do_lower_case
  109. self.split_by_punct = split_by_punct
  110. self.split_chinese = split_chinese
  111. self.vocab_file = vocab_file
  112. self._tokenizer = SPMTokenizer(
  113. vocab_file,
  114. split_by_punct=split_by_punct,
  115. sp_model_kwargs=self.sp_model_kwargs)
  116. self.jieba = None
  117. if self.split_chinese:
  118. try:
  119. import jieba
  120. except ImportError:
  121. raise ImportError(
  122. 'You need to install jieba to split chinese and use DebertaV2Tokenizer. '
  123. 'See https://pypi.org/project/jieba/ for installation.')
  124. self.jieba = jieba
  125. @property
  126. def vocab_size(self):
  127. return len(self.vocab)
  128. @property
  129. def vocab(self):
  130. return self._tokenizer.vocab
  131. def get_vocab(self):
  132. vocab = self.vocab.copy()
  133. vocab.update(self.get_added_vocab())
  134. return vocab
  135. def _tokenize(self, text: str) -> List[str]:
  136. """Take as input a string and return a list of strings (tokens) for words/sub-words"""
  137. if self.do_lower_case:
  138. text = text.lower()
  139. if self.split_chinese:
  140. seg_list = [x for x in self.jieba.cut(text)]
  141. text = ' '.join(seg_list)
  142. return self._tokenizer.tokenize(text)
  143. def _convert_token_to_id(self, token):
  144. """Converts a token (str) in an id using the vocab."""
  145. return self._tokenizer.spm.PieceToId(token)
  146. def _convert_id_to_token(self, index):
  147. """Converts an index (integer) in a token (str) using the vocab."""
  148. return self._tokenizer.spm.IdToPiece(
  149. index) if index < self.vocab_size else self.unk_token
  150. def convert_tokens_to_string(self, tokens):
  151. """Converts a sequence of tokens (string) in a single string."""
  152. return self._tokenizer.decode(tokens)
  153. def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None):
  154. """
  155. Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
  156. adding special tokens. A DeBERTa sequence has the following format:
  157. - single sequence: [CLS] X [SEP]
  158. - pair of sequences: [CLS] A [SEP] B [SEP]
  159. Args:
  160. token_ids_0 (`List[int]`):
  161. List of IDs to which the special tokens will be added.
  162. token_ids_1 (`List[int]`, *optional*):
  163. Optional second list of IDs for sequence pairs.
  164. Returns:
  165. `List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
  166. """
  167. if token_ids_1 is None:
  168. return [self.cls_token_id] + token_ids_0 + [self.sep_token_id]
  169. cls = [self.cls_token_id]
  170. sep = [self.sep_token_id]
  171. return cls + token_ids_0 + sep + token_ids_1 + sep
  172. def get_special_tokens_mask(self,
  173. token_ids_0,
  174. token_ids_1=None,
  175. already_has_special_tokens=False):
  176. """
  177. Retrieves sequence ids from a token list that has no special tokens added. This method is called when adding
  178. special tokens using the tokenizer `prepare_for_model` or `encode_plus` methods.
  179. Args:
  180. token_ids_0 (`List[int]`):
  181. List of IDs.
  182. token_ids_1 (`List[int]`, *optional*):
  183. Optional second list of IDs for sequence pairs.
  184. already_has_special_tokens (`bool`, *optional*, defaults to `False`):
  185. Whether or not the token list is already formatted with special tokens for the model.
  186. Returns:
  187. `List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
  188. """
  189. if already_has_special_tokens:
  190. return super().get_special_tokens_mask(
  191. token_ids_0=token_ids_0,
  192. token_ids_1=token_ids_1,
  193. already_has_special_tokens=True)
  194. if token_ids_1 is not None:
  195. return [1] + ([0] * len(token_ids_0)) + [1] + (
  196. [0] * len(token_ids_1)) + [1]
  197. return [1] + ([0] * len(token_ids_0)) + [1]
  198. def create_token_type_ids_from_sequences(self,
  199. token_ids_0,
  200. token_ids_1=None):
  201. """
  202. Create a mask from the two sequences passed to be used in a sequence-pair classification task. A DeBERTa
  203. sequence pair mask has the following format:
  204. ```
  205. 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1
  206. | first sequence | second sequence |
  207. ```
  208. If `token_ids_1` is `None`, this method only returns the first portion of the mask (0s).
  209. Args:
  210. token_ids_0 (`List[int]`):
  211. List of IDs.
  212. token_ids_1 (`List[int]`, *optional*):
  213. Optional second list of IDs for sequence pairs.
  214. Returns:
  215. `List[int]`: List of [token type IDs](../glossary#token-type-ids) according to the given sequence(s).
  216. """
  217. sep = [self.sep_token_id]
  218. cls = [self.cls_token_id]
  219. if token_ids_1 is None:
  220. return len(cls + token_ids_0 + sep) * [0]
  221. return len(cls + token_ids_0 + sep) * [0] + len(token_ids_1
  222. + sep) * [1]
  223. def prepare_for_tokenization(self,
  224. text,
  225. is_split_into_words=False,
  226. **kwargs):
  227. add_prefix_space = kwargs.pop('add_prefix_space', False)
  228. if is_split_into_words or add_prefix_space:
  229. text = ' ' + text
  230. return (text, kwargs)
  231. def save_vocabulary(self,
  232. save_directory: str,
  233. filename_prefix: Optional[str] = None) -> Tuple[str]:
  234. return self._tokenizer.save_pretrained(
  235. save_directory, filename_prefix=filename_prefix)
  236. class SPMTokenizer:
  237. r"""
  238. Constructs a tokenizer based on [SentencePiece](https://github.com/google/sentencepiece).
  239. Args:
  240. vocab_file (`str`):
  241. [SentencePiece](https://github.com/google/sentencepiece) file (generally has a *.spm* extension) that
  242. contains the vocabulary necessary to instantiate a tokenizer.
  243. sp_model_kwargs (`dict`, *optional*):
  244. Will be passed to the `SentencePieceProcessor.__init__()` method. The [Python wrapper for
  245. SentencePiece](https://github.com/google/sentencepiece/tree/master/python) can be used, among other things,
  246. to set:
  247. - `enable_sampling`: Enable subword regularization.
  248. - `nbest_size`: Sampling parameters for unigram. Invalid for BPE-Dropout.
  249. - `nbest_size = {0,1}`: No sampling is performed.
  250. - `nbest_size > 1`: samples from the nbest_size results.
  251. - `nbest_size < 0`: assuming that nbest_size is infinite and samples from the all hypothesis (lattice)
  252. using forward-filtering-and-backward-sampling algorithm.
  253. - `alpha`: Smoothing parameter for unigram sampling, and dropout probability of merge operations for
  254. BPE-dropout.
  255. """
  256. def __init__(self,
  257. vocab_file,
  258. split_by_punct=False,
  259. sp_model_kwargs: Optional[Dict[str, Any]] = None):
  260. self.split_by_punct = split_by_punct
  261. self.vocab_file = vocab_file
  262. self.sp_model_kwargs = {} if sp_model_kwargs is None else sp_model_kwargs
  263. spm = sp.SentencePieceProcessor(**self.sp_model_kwargs)
  264. if not os.path.exists(vocab_file):
  265. raise FileNotFoundError(f'{vocab_file} does not exist!')
  266. spm.load(vocab_file)
  267. bpe_vocab_size = spm.GetPieceSize()
  268. # Token map
  269. # <unk> 0+1
  270. # <s> 1+1
  271. # </s> 2+1
  272. self.vocab = {spm.IdToPiece(i): i for i in range(bpe_vocab_size)}
  273. self.ids_to_tokens = [spm.IdToPiece(i) for i in range(bpe_vocab_size)]
  274. # self.vocab['[PAD]'] = 0
  275. # self.vocab['[CLS]'] = 1
  276. # self.vocab['[SEP]'] = 2
  277. # self.vocab['[UNK]'] = 3
  278. self.spm = spm
  279. def __getstate__(self):
  280. state = self.__dict__.copy()
  281. state['spm'] = None
  282. return state
  283. def __setstate__(self, d):
  284. self.__dict__ = d
  285. # for backward compatibility
  286. if not hasattr(self, 'sp_model_kwargs'):
  287. self.sp_model_kwargs = {}
  288. self.spm = sp.SentencePieceProcessor(**self.sp_model_kwargs)
  289. self.spm.Load(self.vocab_file)
  290. def tokenize(self, text):
  291. return self._encode_as_pieces(text)
  292. def convert_ids_to_tokens(self, ids):
  293. tokens = []
  294. for i in ids:
  295. tokens.append(self.ids_to_tokens[i])
  296. return tokens
  297. def decode(self, tokens, start=-1, end=-1, raw_text=None):
  298. if raw_text is None:
  299. return self.spm.decode_pieces([t for t in tokens])
  300. else:
  301. words = self.split_to_words(raw_text)
  302. word_tokens = [self.tokenize(w) for w in words]
  303. token2words = [0] * len(tokens)
  304. tid = 0
  305. for i, w in enumerate(word_tokens):
  306. for k, t in enumerate(w):
  307. token2words[tid] = i
  308. tid += 1
  309. word_start = token2words[start]
  310. word_end = token2words[end] if end < len(tokens) else len(words)
  311. text = ''.join(words[word_start:word_end])
  312. return text
  313. def add_special_token(self, token):
  314. if token not in self.special_tokens:
  315. self.special_tokens.append(token)
  316. if token not in self.vocab:
  317. self.vocab[token] = len(self.vocab) - 1
  318. self.ids_to_tokens.append(token)
  319. return self.id(token)
  320. def part_of_whole_word(self, token, is_bos=False):
  321. if is_bos:
  322. return True
  323. if (len(token) == 1 and (_is_whitespace(list(token)[0]))):
  324. return False
  325. if _is_control(list(token)[0]):
  326. return False
  327. if _is_punctuation(list(token)[0]):
  328. return False
  329. if token in self.add_special_token:
  330. return False
  331. word_start = b'\xe2\x96\x81'.decode('utf-8')
  332. return not token.startswith(word_start)
  333. def pad(self):
  334. return '[PAD]'
  335. def bos(self):
  336. return '[CLS]'
  337. def eos(self):
  338. return '[SEP]'
  339. def unk(self):
  340. return '[UNK]'
  341. def mask(self):
  342. return '[MASK]'
  343. def sym(self, id):
  344. return self.ids_to_tokens[id]
  345. def id(self, sym):
  346. return self.vocab[sym] if sym in self.vocab else 1
  347. def _encode_as_pieces(self, text):
  348. text = convert_to_unicode(text)
  349. if self.split_by_punct:
  350. words = self._run_split_on_punc(text)
  351. pieces = [self.spm.encode(w, out_type=str) for w in words]
  352. return [p for w in pieces for p in w]
  353. else:
  354. return self.spm.encode(text, out_type=str)
  355. def split_to_words(self, text):
  356. pieces = self._encode_as_pieces(text)
  357. word_start = b'\xe2\x96\x81'.decode('utf-8')
  358. words = []
  359. offset = 0
  360. prev_end = 0
  361. for i, p in enumerate(pieces):
  362. if p.startswith(word_start):
  363. if offset > prev_end:
  364. words.append(text[prev_end:offset])
  365. prev_end = offset
  366. w = p.replace(word_start, '')
  367. else:
  368. w = p
  369. try:
  370. s = text.index(w, offset)
  371. pn = ''
  372. k = i + 1
  373. while k < len(pieces):
  374. pn = pieces[k].replace(word_start, '')
  375. if len(pn) > 0:
  376. break
  377. k += 1
  378. if len(pn) > 0 and pn in text[offset:s]:
  379. offset = offset + 1
  380. else:
  381. offset = s + len(w)
  382. except Exception:
  383. offset = offset + 1
  384. if prev_end < offset:
  385. words.append(text[prev_end:offset])
  386. return words
  387. def _run_strip_accents(self, text):
  388. """Strips accents from a piece of text."""
  389. text = unicodedata.normalize('NFD', text)
  390. output = []
  391. for char in text:
  392. cat = unicodedata.category(char)
  393. if cat == 'Mn':
  394. continue
  395. output.append(char)
  396. return ''.join(output)
  397. def _run_split_on_punc(self, text):
  398. """Splits punctuation on a piece of text."""
  399. chars = list(text)
  400. i = 0
  401. start_new_word = True
  402. output = []
  403. while i < len(chars):
  404. char = chars[i]
  405. if _is_punctuation(char):
  406. output.append([char])
  407. start_new_word = True
  408. else:
  409. if start_new_word:
  410. output.append([])
  411. start_new_word = False
  412. output[-1].append(char)
  413. i += 1
  414. return [''.join(x) for x in output]
  415. def save_pretrained(self, path: str, filename_prefix: str = None):
  416. filename = VOCAB_FILES_NAMES[list(VOCAB_FILES_NAMES.keys())[0]]
  417. if filename_prefix is not None:
  418. filename = filename_prefix + '-' + filename
  419. full_path = os.path.join(path, filename)
  420. with open(full_path, 'wb') as fs:
  421. fs.write(self.spm.serialized_model_proto())
  422. return (full_path, )
  423. def _is_whitespace(char):
  424. """Checks whether `chars` is a whitespace character."""
  425. # \t, \n, and \r are technically control characters but we treat them
  426. # as whitespace since they are generally considered as such.
  427. if char == ' ' or char == '\t' or char == '\n' or char == '\r':
  428. return True
  429. cat = unicodedata.category(char)
  430. if cat == 'Zs':
  431. return True
  432. return False
  433. def _is_control(char):
  434. """Checks whether `chars` is a control character."""
  435. # These are technically control characters but we count them as whitespace
  436. # characters.
  437. if char == '\t' or char == '\n' or char == '\r':
  438. return False
  439. cat = unicodedata.category(char)
  440. if cat.startswith('C'):
  441. return True
  442. return False
  443. def _is_punctuation(char):
  444. """Checks whether `chars` is a punctuation character."""
  445. cp = ord(char)
  446. # We treat all non-letter/number ASCII as punctuation.
  447. # Characters such as "^", "$", and "`" are not in the Unicode
  448. # Punctuation class but we treat them as punctuation anyways, for
  449. # consistency.
  450. if (cp >= 33 and cp <= 47) or (cp >= 58 and cp <= 64) or (
  451. cp >= 91 and cp <= 96) or (cp >= 123 and cp <= 126):
  452. return True
  453. cat = unicodedata.category(char)
  454. if cat.startswith('P'):
  455. return True
  456. return False
  457. def convert_to_unicode(text):
  458. """Converts `text` to Unicode (if it's not already), assuming utf-8 input."""
  459. if isinstance(text, str):
  460. return text
  461. elif isinstance(text, bytes):
  462. return text.decode('utf-8', 'ignore')
  463. else:
  464. raise ValueError(f'Unsupported string type: {type(text)}')