tokenization_cpm.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350
  1. # coding=utf-8
  2. # Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. """Tokenization classes."""
  16. import os
  17. import unicodedata
  18. from shutil import copyfile
  19. from typing import Any, Optional
  20. import sentencepiece as spm
  21. from ...tokenization_utils import AddedToken, PreTrainedTokenizer
  22. from ...utils import SPIECE_UNDERLINE, logging
  23. from ...utils.import_utils import requires
  24. logger = logging.get_logger(__name__)
  25. VOCAB_FILES_NAMES = {"vocab_file": "spiece.model"}
  26. @requires(backends=("sentencepiece",))
  27. class CpmTokenizer(PreTrainedTokenizer):
  28. """Runs pre-tokenization with Jieba-RS segmentation tool. It is used in CPM models."""
  29. vocab_files_names = VOCAB_FILES_NAMES
  30. def __init__(
  31. self,
  32. vocab_file,
  33. do_lower_case=False,
  34. remove_space=True,
  35. keep_accents=False,
  36. bos_token="<s>",
  37. eos_token="</s>",
  38. unk_token="<unk>",
  39. sep_token="<sep>",
  40. pad_token="<pad>",
  41. cls_token="<cls>",
  42. mask_token="<mask>",
  43. additional_special_tokens=["<eop>", "<eod>"],
  44. sp_model_kwargs: Optional[dict[str, Any]] = None,
  45. **kwargs,
  46. ) -> None:
  47. """
  48. Construct a CPM tokenizer. Based on [Jieba-RS](https://pypi.org/project/rjieba/) and
  49. [SentencePiece](https://github.com/google/sentencepiece).
  50. This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should
  51. refer to this superclass for more information regarding those methods.
  52. Args:
  53. vocab_file (`str`):
  54. [SentencePiece](https://github.com/google/sentencepiece) file (generally has a .spm extension) that
  55. contains the vocabulary necessary to instantiate a tokenizer.
  56. do_lower_case (`bool`, *optional*, defaults to `True`):
  57. Whether to lowercase the input when tokenizing.
  58. remove_space (`bool`, *optional*, defaults to `True`):
  59. Whether to strip the text when tokenizing (removing excess spaces before and after the string).
  60. keep_accents (`bool`, *optional*, defaults to `False`):
  61. Whether to keep accents when tokenizing.
  62. bos_token (`str`, *optional*, defaults to `"<s>"`):
  63. The beginning of sequence token that was used during pretraining. Can be used a sequence classifier
  64. token.
  65. <Tip>
  66. When building a sequence using special tokens, this is not the token that is used for the beginning of
  67. sequence. The token used is the `cls_token`.
  68. </Tip>
  69. eos_token (`str`, *optional*, defaults to `"</s>"`):
  70. The end of sequence token.
  71. <Tip>
  72. When building a sequence using special tokens, this is not the token that is used for the end of
  73. sequence. The token used is the `sep_token`.
  74. </Tip>
  75. unk_token (`str`, *optional*, defaults to `"<unk>"`):
  76. The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be
  77. this token instead.
  78. sep_token (`str`, *optional*, defaults to `"<sep>"`):
  79. The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences
  80. for sequence classification or for a text and a question for question answering. It is also used as the
  81. last token of a sequence built with special tokens.
  82. pad_token (`str`, *optional*, defaults to `"<pad>"`):
  83. The token used for padding, for example when batching sequences of different lengths.
  84. cls_token (`str`, *optional*, defaults to `"<cls>"`):
  85. The classifier token which is used when doing sequence classification (classification of the whole
  86. sequence instead of per-token classification). It is the first token of the sequence when built with
  87. special tokens.
  88. mask_token (`str`, *optional*, defaults to `"<mask>"`):
  89. The token used for masking values. This is the token used when training this model with masked language
  90. modeling. This is the token which the model will try to predict.
  91. additional_special_tokens (`list[str]`, *optional*, defaults to `["<eop>", "<eod>"]`):
  92. Additional special tokens used by the tokenizer.
  93. Attributes:
  94. sp_model (`SentencePieceProcessor`):
  95. The *SentencePiece* processor that is used for every conversion (string, tokens and IDs).
  96. """
  97. # Mask token behave like a normal word, i.e. include the space before it
  98. mask_token = AddedToken(mask_token, lstrip=True, rstrip=False) if isinstance(mask_token, str) else mask_token
  99. self.sp_model_kwargs = {} if sp_model_kwargs is None else sp_model_kwargs
  100. self.do_lower_case = do_lower_case
  101. self.remove_space = remove_space
  102. self.keep_accents = keep_accents
  103. self.vocab_file = vocab_file
  104. self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
  105. self.sp_model.Load(vocab_file)
  106. try:
  107. import rjieba
  108. except ModuleNotFoundError as error:
  109. raise error.__class__(
  110. "You need to install rjieba to use CpmTokenizer or CpmTokenizerFast. "
  111. "See https://pypi.org/project/rjieba/ for installation."
  112. )
  113. self.jieba = rjieba
  114. self.translator = str.maketrans(" \n", "\u2582\u2583")
  115. super().__init__(
  116. do_lower_case=do_lower_case,
  117. remove_space=remove_space,
  118. keep_accents=keep_accents,
  119. bos_token=bos_token,
  120. eos_token=eos_token,
  121. unk_token=unk_token,
  122. sep_token=sep_token,
  123. pad_token=pad_token,
  124. cls_token=cls_token,
  125. mask_token=mask_token,
  126. additional_special_tokens=additional_special_tokens,
  127. sp_model_kwargs=self.sp_model_kwargs,
  128. **kwargs,
  129. )
  130. self._pad_token_type_id = 3
  131. @property
  132. # Copied from transformers.models.xlnet.tokenization_xlnet.XLNetTokenizer.vocab_size
  133. def vocab_size(self):
  134. return len(self.sp_model)
  135. # Copied from transformers.models.xlnet.tokenization_xlnet.XLNetTokenizer.get_vocab
  136. def get_vocab(self):
  137. vocab = {self.convert_ids_to_tokens(i): i for i in range(self.vocab_size)}
  138. vocab.update(self.added_tokens_encoder)
  139. return vocab
  140. # Copied from transformers.models.xlnet.tokenization_xlnet.XLNetTokenizer.__getstate__
  141. def __getstate__(self):
  142. state = self.__dict__.copy()
  143. state["sp_model"] = None
  144. return state
  145. # Copied from transformers.models.xlnet.tokenization_xlnet.XLNetTokenizer.__setstate__
  146. def __setstate__(self, d):
  147. self.__dict__ = d
  148. # for backward compatibility
  149. if not hasattr(self, "sp_model_kwargs"):
  150. self.sp_model_kwargs = {}
  151. self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
  152. self.sp_model.Load(self.vocab_file)
  153. # Copied from transformers.models.xlnet.tokenization_xlnet.XLNetTokenizer.preprocess_text
  154. def preprocess_text(self, inputs):
  155. if self.remove_space:
  156. outputs = " ".join(inputs.strip().split())
  157. else:
  158. outputs = inputs
  159. outputs = outputs.replace("``", '"').replace("''", '"')
  160. if not self.keep_accents:
  161. outputs = unicodedata.normalize("NFKD", outputs)
  162. outputs = "".join([c for c in outputs if not unicodedata.combining(c)])
  163. if self.do_lower_case:
  164. outputs = outputs.lower()
  165. return outputs
  166. # Copied from transformers.models.xlnet.tokenization_xlnet.XLNetTokenizer._tokenize
  167. def _tokenize(self, text: str) -> list[str]:
  168. """Tokenize a string."""
  169. text = self.preprocess_text(text)
  170. pieces = self.sp_model.encode(text, out_type=str)
  171. new_pieces = []
  172. for piece in pieces:
  173. if len(piece) > 1 and piece[-1] == "," and piece[-2].isdigit():
  174. cur_pieces = self.sp_model.EncodeAsPieces(piece[:-1].replace(SPIECE_UNDERLINE, ""))
  175. if piece[0] != SPIECE_UNDERLINE and cur_pieces[0][0] == SPIECE_UNDERLINE:
  176. if len(cur_pieces[0]) == 1:
  177. cur_pieces = cur_pieces[1:]
  178. else:
  179. cur_pieces[0] = cur_pieces[0][1:]
  180. cur_pieces.append(piece[-1])
  181. new_pieces.extend(cur_pieces)
  182. else:
  183. new_pieces.append(piece)
  184. return new_pieces
  185. # Copied from transformers.models.xlnet.tokenization_xlnet.XLNetTokenizer._convert_token_to_id
  186. def _convert_token_to_id(self, token):
  187. """Converts a token (str) in an id using the vocab."""
  188. return self.sp_model.PieceToId(token)
  189. # Copied from transformers.models.xlnet.tokenization_xlnet.XLNetTokenizer._convert_id_to_token
  190. def _convert_id_to_token(self, index):
  191. """Converts an index (integer) in a token (str) using the vocab."""
  192. return self.sp_model.IdToPiece(index)
  193. # Copied from transformers.models.xlnet.tokenization_xlnet.XLNetTokenizer.convert_tokens_to_string
  194. def convert_tokens_to_string(self, tokens):
  195. """Converts a sequence of tokens (strings for sub-words) in a single string."""
  196. out_string = "".join(tokens).replace(SPIECE_UNDERLINE, " ").strip()
  197. return out_string
  198. # Copied from transformers.models.xlnet.tokenization_xlnet.XLNetTokenizer.build_inputs_with_special_tokens
  199. def build_inputs_with_special_tokens(
  200. self, token_ids_0: list[int], token_ids_1: Optional[list[int]] = None
  201. ) -> list[int]:
  202. """
  203. Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
  204. adding special tokens. An XLNet sequence has the following format:
  205. - single sequence: `X <sep> <cls>`
  206. - pair of sequences: `A <sep> B <sep> <cls>`
  207. Args:
  208. token_ids_0 (`list[int]`):
  209. List of IDs to which the special tokens will be added.
  210. token_ids_1 (`list[int]`, *optional*):
  211. Optional second list of IDs for sequence pairs.
  212. Returns:
  213. `list[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
  214. """
  215. sep = [self.sep_token_id]
  216. cls = [self.cls_token_id]
  217. if token_ids_1 is None:
  218. return token_ids_0 + sep + cls
  219. return token_ids_0 + sep + token_ids_1 + sep + cls
  220. # Copied from transformers.models.xlnet.tokenization_xlnet.XLNetTokenizer.get_special_tokens_mask
  221. def get_special_tokens_mask(
  222. self, token_ids_0: list[int], token_ids_1: Optional[list[int]] = None, already_has_special_tokens: bool = False
  223. ) -> list[int]:
  224. """
  225. Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
  226. special tokens using the tokenizer `prepare_for_model` method.
  227. Args:
  228. token_ids_0 (`list[int]`):
  229. List of IDs.
  230. token_ids_1 (`list[int]`, *optional*):
  231. Optional second list of IDs for sequence pairs.
  232. already_has_special_tokens (`bool`, *optional*, defaults to `False`):
  233. Whether or not the token list is already formatted with special tokens for the model.
  234. Returns:
  235. `list[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
  236. """
  237. if already_has_special_tokens:
  238. return super().get_special_tokens_mask(
  239. token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
  240. )
  241. if token_ids_1 is not None:
  242. return ([0] * len(token_ids_0)) + [1] + ([0] * len(token_ids_1)) + [1, 1]
  243. return ([0] * len(token_ids_0)) + [1, 1]
  244. # Copied from transformers.models.xlnet.tokenization_xlnet.XLNetTokenizer.create_token_type_ids_from_sequences
  245. def create_token_type_ids_from_sequences(
  246. self, token_ids_0: list[int], token_ids_1: Optional[list[int]] = None
  247. ) -> list[int]:
  248. """
  249. Create a mask from the two sequences passed to be used in a sequence-pair classification task. An XLNet
  250. sequence pair mask has the following format:
  251. ```
  252. 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1
  253. | first sequence | second sequence |
  254. ```
  255. If `token_ids_1` is `None`, this method only returns the first portion of the mask (0s).
  256. Args:
  257. token_ids_0 (`list[int]`):
  258. List of IDs.
  259. token_ids_1 (`list[int]`, *optional*):
  260. Optional second list of IDs for sequence pairs.
  261. Returns:
  262. `list[int]`: List of [token type IDs](../glossary#token-type-ids) according to the given sequence(s).
  263. """
  264. sep = [self.sep_token_id]
  265. cls_segment_id = [2]
  266. if token_ids_1 is None:
  267. return len(token_ids_0 + sep) * [0] + cls_segment_id
  268. return len(token_ids_0 + sep) * [0] + len(token_ids_1 + sep) * [1] + cls_segment_id
  269. # Copied from transformers.models.xlnet.tokenization_xlnet.XLNetTokenizer.save_vocabulary
  270. def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> tuple[str]:
  271. if not os.path.isdir(save_directory):
  272. logger.error(f"Vocabulary path ({save_directory}) should be a directory")
  273. return
  274. out_vocab_file = os.path.join(
  275. save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
  276. )
  277. if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file) and os.path.isfile(self.vocab_file):
  278. copyfile(self.vocab_file, out_vocab_file)
  279. elif not os.path.isfile(self.vocab_file):
  280. with open(out_vocab_file, "wb") as fi:
  281. content_spiece_model = self.sp_model.serialized_model_proto()
  282. fi.write(content_spiece_model)
  283. return (out_vocab_file,)
  284. def _decode(self, *args, **kwargs):
  285. text = super()._decode(*args, **kwargs)
  286. text = text.replace(" ", "").replace("\u2582", " ").replace("\u2583", "\n")
  287. return text
  288. __all__ = ["CpmTokenizer"]