tokenization_gemma.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  1. # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
  2. # This file was automatically generated from src/transformers/models/gemma/modular_gemma.py.
  3. # Do NOT edit this file manually as any edits will be overwritten by the generation of
  4. # the file from the modular. If any change should be done, please apply the change to the
  5. # modular_gemma.py file directly. One of our CI enforces this.
  6. # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
  7. # coding=utf-8
  8. # Copyright 2024 Google Inc. HuggingFace Inc. team. All rights reserved.
  9. #
  10. #
  11. # Licensed under the Apache License, Version 2.0 (the "License");
  12. # you may not use this file except in compliance with the License.
  13. # You may obtain a copy of the License at
  14. #
  15. # http://www.apache.org/licenses/LICENSE-2.0
  16. #
  17. # Unless required by applicable law or agreed to in writing, software
  18. # distributed under the License is distributed on an "AS IS" BASIS,
  19. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  20. # See the License for the specific language governing permissions and
  21. # limitations under the License.
  22. import os
  23. from shutil import copyfile
  24. from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple
  25. import sentencepiece as spm
  26. from ...tokenization_utils import AddedToken, PreTrainedTokenizer
  27. from ...utils import logging
  28. if TYPE_CHECKING:
  29. from ...tokenization_utils_base import TextInput
  30. logger = logging.get_logger(__name__)
  31. VOCAB_FILES_NAMES = {"vocab_file": "tokenizer.model"}
  32. SPIECE_UNDERLINE = "▁"
  33. class GemmaTokenizer(PreTrainedTokenizer):
  34. """
  35. Construct a Gemma tokenizer. Based on byte-level Byte-Pair-Encoding. The default padding token is unset as there is
  36. no padding token in the original model.
  37. Args:
  38. vocab_file (`str`):
  39. Path to the vocabulary file.
  40. unk_token (`str` or `tokenizers.AddedToken`, *optional*, defaults to `"<unk>"`):
  41. The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
  42. token instead.
  43. bos_token (`str` or `tokenizers.AddedToken`, *optional*, defaults to `"<bos>"`):
  44. The beginning of sequence token that was used during pretraining. Can be used a sequence classifier token.
  45. eos_token (`str` or `tokenizers.AddedToken`, *optional*, defaults to `"<eos>"`):
  46. The end of sequence token.
  47. pad_token (`str` or `tokenizers.AddedToken`, *optional*, defaults to `"<pad>"`):
  48. A special token used to make arrays of tokens the same size for batching purpose. Will then be ignored by
  49. attention mechanisms or loss computation.
  50. sp_model_kwargs (`Dict[str, Any]`, `Optional`, *optional*):
  51. Will be passed to the `SentencePieceProcessor.__init__()` method. The [Python wrapper for
  52. SentencePiece](https://github.com/google/sentencepiece/tree/master/python) can be used, among other things,
  53. to set:
  54. - `enable_sampling`: Enable subword regularization.
  55. - `nbest_size`: Sampling parameters for unigram. Invalid for BPE-Dropout.
  56. - `nbest_size = {0,1}`: No sampling is performed.
  57. - `nbest_size > 1`: samples from the nbest_size results.
  58. - `nbest_size < 0`: assuming that nbest_size is infinite and samples from the all hypothesis (lattice)
  59. using forward-filtering-and-backward-sampling algorithm.
  60. - `alpha`: Smoothing parameter for unigram sampling, and dropout probability of merge operations for
  61. BPE-dropout.
  62. add_bos_token (`bool`, *optional*, defaults to `True`):
  63. Whether or not to add an `bos_token` at the start of sequences.
  64. add_eos_token (`bool`, *optional*, defaults to `False`):
  65. Whether or not to add an `eos_token` at the end of sequences.
  66. clean_up_tokenization_spaces (`bool`, *optional*, defaults to `False`):
  67. Whether or not to cleanup spaces after decoding, cleanup consists in removing potential artifacts like
  68. extra spaces.
  69. use_default_system_prompt (`bool`, *optional*, defaults to `False`):
  70. Whether or not the default system prompt for Gemma should be used.
  71. spaces_between_special_tokens (`bool`, *optional*, defaults to `False`):
  72. Whether or not to add spaces between special tokens.
  73. """
  74. vocab_files_names = VOCAB_FILES_NAMES
  75. model_input_names = ["input_ids", "attention_mask"]
  76. def __init__(
  77. self,
  78. vocab_file,
  79. unk_token="<unk>",
  80. bos_token="<bos>",
  81. eos_token="<eos>",
  82. pad_token="<pad>",
  83. sp_model_kwargs: Optional[Dict[str, Any]] = None,
  84. add_bos_token=True,
  85. add_eos_token=False,
  86. clean_up_tokenization_spaces=False,
  87. use_default_system_prompt=False,
  88. spaces_between_special_tokens=False,
  89. **kwargs,
  90. ):
  91. self.sp_model_kwargs = {} if sp_model_kwargs is None else sp_model_kwargs
  92. bos_token = AddedToken(bos_token, normalized=False, special=True) if isinstance(bos_token, str) else bos_token
  93. eos_token = AddedToken(eos_token, normalized=False, special=True) if isinstance(eos_token, str) else eos_token
  94. unk_token = AddedToken(unk_token, normalized=False, special=True) if isinstance(unk_token, str) else unk_token
  95. pad_token = AddedToken(pad_token, normalized=False, special=True) if isinstance(pad_token, str) else pad_token
  96. self.vocab_file = vocab_file
  97. self.add_bos_token = add_bos_token
  98. self.add_eos_token = add_eos_token
  99. self.use_default_system_prompt = use_default_system_prompt
  100. self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
  101. self.sp_model.Load(vocab_file)
  102. super().__init__(
  103. bos_token=bos_token,
  104. eos_token=eos_token,
  105. unk_token=unk_token,
  106. pad_token=pad_token,
  107. add_bos_token=add_bos_token,
  108. add_eos_token=add_eos_token,
  109. sp_model_kwargs=sp_model_kwargs,
  110. clean_up_tokenization_spaces=clean_up_tokenization_spaces,
  111. use_default_system_prompt=use_default_system_prompt,
  112. spaces_between_special_tokens=spaces_between_special_tokens,
  113. **kwargs,
  114. )
  115. def __getstate__(self):
  116. state = self.__dict__.copy()
  117. state["sp_model"] = None
  118. state["sp_model_proto"] = self.sp_model.serialized_model_proto()
  119. return state
  120. def __setstate__(self, d):
  121. self.__dict__ = d
  122. self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
  123. self.sp_model.LoadFromSerializedProto(self.sp_model_proto)
  124. @property
  125. def vocab_size(self):
  126. """Returns vocab size"""
  127. return self.sp_model.get_piece_size()
  128. def get_vocab(self):
  129. """Returns vocab as a dict"""
  130. vocab = {self.convert_ids_to_tokens(i): i for i in range(self.vocab_size)}
  131. vocab.update(self.added_tokens_encoder)
  132. return vocab
  133. def tokenize(self, text: "TextInput", **kwargs) -> List[str]:
  134. """
  135. Args:
  136. text: TextInput
  137. Simply calls PreTrainedTokenizer's method
  138. """
  139. return super().tokenize(text, **kwargs)
  140. def _tokenize(self, text, **kwargs):
  141. """
  142. Args:
  143. text: TextInput
  144. Returns a tokenized string. The Gemma tokenizer never adds a prefix space.
  145. """
  146. return self.sp_model.encode(text, out_type=str)
  147. def _convert_token_to_id(self, token):
  148. """Converts a token (str) in an id using the vocab."""
  149. return self.sp_model.piece_to_id(token)
  150. def _convert_id_to_token(self, index):
  151. """Converts an index (integer) in a token (str) using the vocab."""
  152. token = self.sp_model.IdToPiece(index)
  153. return token
  154. def convert_tokens_to_string(self, tokens):
  155. """Converts a sequence of tokens (string) in a single string."""
  156. current_sub_tokens = []
  157. out_string = ""
  158. for token in tokens:
  159. # make sure that special tokens are not decoded using sentencepiece model
  160. if token in self._added_tokens_encoder:
  161. out_string += self.sp_model.decode(current_sub_tokens) + token
  162. current_sub_tokens = []
  163. else:
  164. current_sub_tokens.append(token)
  165. out_string += self.sp_model.decode(current_sub_tokens)
  166. return out_string
  167. def save_vocabulary(self, save_directory, filename_prefix: Optional[str] = None) -> Tuple[str]:
  168. """
  169. Save the vocabulary and special tokens file to a directory.
  170. Args:
  171. save_directory (`str`):
  172. The directory in which to save the vocabulary.
  173. Returns:
  174. `Tuple(str)`: Paths to the files saved.
  175. """
  176. if not os.path.isdir(save_directory):
  177. logger.error(f"Vocabulary path ({save_directory}) should be a directory")
  178. return
  179. out_vocab_file = os.path.join(
  180. save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
  181. )
  182. if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file) and os.path.isfile(self.vocab_file):
  183. copyfile(self.vocab_file, out_vocab_file)
  184. elif not os.path.isfile(self.vocab_file):
  185. with open(out_vocab_file, "wb") as fi:
  186. content_spiece_model = self.sp_model.serialized_model_proto()
  187. fi.write(content_spiece_model)
  188. return (out_vocab_file,)
  189. def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None):
  190. bos_token_id = [self.bos_token_id] if self.add_bos_token else []
  191. eos_token_id = [self.eos_token_id] if self.add_eos_token else []
  192. output = bos_token_id + token_ids_0 + eos_token_id
  193. if token_ids_1 is not None:
  194. output = output + bos_token_id + token_ids_1 + eos_token_id
  195. return output
  196. def get_special_tokens_mask(
  197. self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None, already_has_special_tokens: bool = False
  198. ) -> List[int]:
  199. """
  200. Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
  201. special tokens using the tokenizer `prepare_for_model` method.
  202. Args:
  203. token_ids_0 (`List[int]`):
  204. List of IDs.
  205. token_ids_1 (`List[int]`, *optional*):
  206. Optional second list of IDs for sequence pairs.
  207. already_has_special_tokens (`bool`, *optional*, defaults to `False`):
  208. Whether or not the token list is already formatted with special tokens for the model.
  209. Returns:
  210. `List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
  211. """
  212. if already_has_special_tokens:
  213. return super().get_special_tokens_mask(
  214. token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
  215. )
  216. bos_token_id = [1] if self.add_bos_token else []
  217. eos_token_id = [1] if self.add_eos_token else []
  218. if token_ids_1 is None:
  219. return bos_token_id + ([0] * len(token_ids_0)) + eos_token_id
  220. return (
  221. bos_token_id
  222. + ([0] * len(token_ids_0))
  223. + eos_token_id
  224. + bos_token_id
  225. + ([0] * len(token_ids_1))
  226. + eos_token_id
  227. )
  228. def create_token_type_ids_from_sequences(
  229. self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
  230. ) -> List[int]:
  231. """
  232. Creates a mask from the two sequences passed to be used in a sequence-pair classification task. An ALBERT
  233. sequence pair mask has the following format:
  234. ```
  235. 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1
  236. | first sequence | second sequence |
  237. ```
  238. if token_ids_1 is None, only returns the first portion of the mask (0s).
  239. Args:
  240. token_ids_0 (`List[int]`):
  241. List of ids.
  242. token_ids_1 (`List[int]`, *optional*):
  243. Optional second list of IDs for sequence pairs.
  244. Returns:
  245. `List[int]`: List of [token type IDs](../glossary#token-type-ids) according to the given sequence(s).
  246. """
  247. bos_token_id = [self.bos_token_id] if self.add_bos_token else []
  248. eos_token_id = [self.eos_token_id] if self.add_eos_token else []
  249. output = [0] * len(bos_token_id + token_ids_0 + eos_token_id)
  250. if token_ids_1 is not None:
  251. output += [1] * len(bos_token_id + token_ids_1 + eos_token_id)
  252. return output
  253. def _decode(
  254. self,
  255. token_ids: List[int],
  256. skip_special_tokens: bool = False,
  257. spaces_between_special_tokens: bool = False,
  258. **kwargs,
  259. ) -> str:
  260. sub_texts = []
  261. current_sub_text = []
  262. for ids in token_ids:
  263. if skip_special_tokens and ids in self.all_special_ids:
  264. continue
  265. if ids in self._added_tokens_decoder:
  266. if current_sub_text:
  267. sub_texts.append(self.sp_model.decode(current_sub_text))
  268. sub_texts.append(self._added_tokens_decoder[ids].content)
  269. current_sub_text = []
  270. else:
  271. current_sub_text.append(ids)
  272. if current_sub_text:
  273. sub_texts.append(self.sp_model.decode(current_sub_text))
  274. if spaces_between_special_tokens:
  275. sub_texts = " ".join(sub_texts)
  276. else:
  277. sub_texts = "".join(sub_texts)
  278. return sub_texts.replace(SPIECE_UNDERLINE, " ")
  279. __all__ = ["GemmaTokenizer"]