tokenization_gemma.py 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. # Copyright 2024 The HuggingFace Inc. team.
  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. from tokenizers import Tokenizer, decoders, normalizers, pre_tokenizers
  15. from tokenizers.models import BPE
  16. from ...tokenization_utils_tokenizers import TokenizersBackend
  17. from ...utils import logging
  18. logger = logging.get_logger(__name__)
  19. VOCAB_FILES_NAMES = {"tokenizer_file": "tokenizer.json"}
  20. class GemmaTokenizer(TokenizersBackend):
  21. """
  22. Construct a fast Gemma tokenizer (backed by HuggingFace's tokenizers library).
  23. This tokenizer uses a BPE model with byte fallback, no prefix space, and a normalizer that replaces
  24. spaces with "▁".
  25. Args:
  26. tokenizer_file (`str`, optional):
  27. A tokenizers JSON file containing the serialization of a tokenizer.
  28. unk_token (`str`, optional, defaults to "<unk>"):
  29. The unknown token.
  30. bos_token (`str`, optional, defaults to "<bos>"):
  31. The beginning of sequence token.
  32. eos_token (`str`, optional, defaults to "<eos>"):
  33. The end of sequence token.
  34. pad_token (`str`, optional, defaults to "<pad>"):
  35. The padding token.
  36. mask_token (`str`, optional, defaults to "<mask>"):
  37. The mask token.
  38. add_bos_token (`bool`, optional, defaults to True):
  39. Whether or not to add a `bos_token` at the start of sequences.
  40. add_eos_token (`bool`, optional, defaults to False):
  41. Whether or not to add an `eos_token` at the end of sequences.
  42. vocab (`str` or `dict[str, int]`, optional):
  43. Custom vocabulary dict. If not provided, a minimal vocabulary is created using the special tokens.
  44. """
  45. vocab_files_names = VOCAB_FILES_NAMES
  46. padding_side = "left"
  47. model_input_names = ["input_ids", "attention_mask"]
  48. model = BPE
  49. def __init__(
  50. self,
  51. vocab: str | dict[str, int] | None = None,
  52. merges: str | list[str] | None = None,
  53. unk_token: str = "<unk>",
  54. bos_token: str = "<bos>",
  55. eos_token: str = "<eos>",
  56. pad_token: str = "<pad>",
  57. mask_token: str = "<mask>",
  58. **kwargs,
  59. ):
  60. if vocab is None:
  61. vocab = {
  62. str(pad_token): 0,
  63. str(eos_token): 1,
  64. str(bos_token): 2,
  65. str(unk_token): 3,
  66. str(mask_token): 4,
  67. }
  68. self._vocab = vocab
  69. self._merges = merges or []
  70. self._tokenizer = Tokenizer(
  71. BPE(
  72. vocab=self._vocab,
  73. merges=self._merges,
  74. fuse_unk=True,
  75. unk_token=str(unk_token),
  76. dropout=None,
  77. byte_fallback=True,
  78. )
  79. )
  80. self._tokenizer.pre_tokenizer = pre_tokenizers.Split(
  81. pattern=" ", behavior="merged_with_previous", invert=False
  82. )
  83. self._tokenizer.decoder = decoders.Sequence(
  84. [decoders.Replace("▁", " "), decoders.ByteFallback(), decoders.Fuse()]
  85. )
  86. self._tokenizer.normalizer = normalizers.Replace(" ", "▁")
  87. super().__init__(
  88. unk_token=unk_token,
  89. bos_token=bos_token,
  90. eos_token=eos_token,
  91. pad_token=pad_token,
  92. mask_token=mask_token,
  93. **kwargs,
  94. )
  95. __all__ = ["GemmaTokenizer"]