applied-ai-018 commited on
Commit
3b2b052
·
verified ·
1 Parent(s): ae23c25

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. env-llmeval/lib/python3.10/site-packages/transformers/models/__pycache__/__init__.cpython-310.pyc +0 -0
  2. env-llmeval/lib/python3.10/site-packages/transformers/models/bert_japanese/__init__.py +29 -0
  3. env-llmeval/lib/python3.10/site-packages/transformers/models/bert_japanese/__pycache__/__init__.cpython-310.pyc +0 -0
  4. env-llmeval/lib/python3.10/site-packages/transformers/models/bert_japanese/__pycache__/tokenization_bert_japanese.cpython-310.pyc +0 -0
  5. env-llmeval/lib/python3.10/site-packages/transformers/models/bert_japanese/tokenization_bert_japanese.py +1028 -0
  6. env-llmeval/lib/python3.10/site-packages/transformers/models/blenderbot/__init__.py +142 -0
  7. env-llmeval/lib/python3.10/site-packages/transformers/models/blenderbot/__pycache__/__init__.cpython-310.pyc +0 -0
  8. env-llmeval/lib/python3.10/site-packages/transformers/models/blenderbot/__pycache__/configuration_blenderbot.cpython-310.pyc +0 -0
  9. env-llmeval/lib/python3.10/site-packages/transformers/models/blenderbot/__pycache__/convert_blenderbot_original_pytorch_checkpoint_to_pytorch.cpython-310.pyc +0 -0
  10. env-llmeval/lib/python3.10/site-packages/transformers/models/blenderbot/__pycache__/modeling_blenderbot.cpython-310.pyc +0 -0
  11. env-llmeval/lib/python3.10/site-packages/transformers/models/blenderbot/__pycache__/modeling_flax_blenderbot.cpython-310.pyc +0 -0
  12. env-llmeval/lib/python3.10/site-packages/transformers/models/blenderbot/__pycache__/modeling_tf_blenderbot.cpython-310.pyc +0 -0
  13. env-llmeval/lib/python3.10/site-packages/transformers/models/blenderbot/__pycache__/tokenization_blenderbot.cpython-310.pyc +0 -0
  14. env-llmeval/lib/python3.10/site-packages/transformers/models/blenderbot/__pycache__/tokenization_blenderbot_fast.cpython-310.pyc +0 -0
  15. env-llmeval/lib/python3.10/site-packages/transformers/models/blenderbot/configuration_blenderbot.py +397 -0
  16. env-llmeval/lib/python3.10/site-packages/transformers/models/blenderbot/convert_blenderbot_original_pytorch_checkpoint_to_pytorch.py +114 -0
  17. env-llmeval/lib/python3.10/site-packages/transformers/models/blenderbot/modeling_blenderbot.py +1600 -0
  18. env-llmeval/lib/python3.10/site-packages/transformers/models/blenderbot/modeling_flax_blenderbot.py +1505 -0
  19. env-llmeval/lib/python3.10/site-packages/transformers/models/blenderbot/modeling_tf_blenderbot.py +1556 -0
  20. env-llmeval/lib/python3.10/site-packages/transformers/models/blenderbot/tokenization_blenderbot.py +439 -0
  21. env-llmeval/lib/python3.10/site-packages/transformers/models/blenderbot/tokenization_blenderbot_fast.py +321 -0
  22. env-llmeval/lib/python3.10/site-packages/transformers/models/blenderbot_small/__pycache__/__init__.cpython-310.pyc +0 -0
  23. env-llmeval/lib/python3.10/site-packages/transformers/models/blenderbot_small/__pycache__/configuration_blenderbot_small.cpython-310.pyc +0 -0
  24. env-llmeval/lib/python3.10/site-packages/transformers/models/blenderbot_small/__pycache__/modeling_blenderbot_small.cpython-310.pyc +0 -0
  25. env-llmeval/lib/python3.10/site-packages/transformers/models/blenderbot_small/__pycache__/modeling_flax_blenderbot_small.cpython-310.pyc +0 -0
  26. env-llmeval/lib/python3.10/site-packages/transformers/models/blenderbot_small/__pycache__/modeling_tf_blenderbot_small.cpython-310.pyc +0 -0
  27. env-llmeval/lib/python3.10/site-packages/transformers/models/blenderbot_small/__pycache__/tokenization_blenderbot_small.cpython-310.pyc +0 -0
  28. env-llmeval/lib/python3.10/site-packages/transformers/models/blenderbot_small/__pycache__/tokenization_blenderbot_small_fast.cpython-310.pyc +0 -0
  29. env-llmeval/lib/python3.10/site-packages/transformers/models/convnextv2/__pycache__/__init__.cpython-310.pyc +0 -0
  30. env-llmeval/lib/python3.10/site-packages/transformers/models/convnextv2/__pycache__/configuration_convnextv2.cpython-310.pyc +0 -0
  31. env-llmeval/lib/python3.10/site-packages/transformers/models/convnextv2/__pycache__/convert_convnextv2_to_pytorch.cpython-310.pyc +0 -0
  32. env-llmeval/lib/python3.10/site-packages/transformers/models/convnextv2/__pycache__/modeling_convnextv2.cpython-310.pyc +0 -0
  33. env-llmeval/lib/python3.10/site-packages/transformers/models/convnextv2/__pycache__/modeling_tf_convnextv2.cpython-310.pyc +0 -0
  34. env-llmeval/lib/python3.10/site-packages/transformers/models/distilbert/__init__.py +166 -0
  35. env-llmeval/lib/python3.10/site-packages/transformers/models/distilbert/__pycache__/__init__.cpython-310.pyc +0 -0
  36. env-llmeval/lib/python3.10/site-packages/transformers/models/distilbert/__pycache__/tokenization_distilbert.cpython-310.pyc +0 -0
  37. env-llmeval/lib/python3.10/site-packages/transformers/models/distilbert/configuration_distilbert.py +155 -0
  38. env-llmeval/lib/python3.10/site-packages/transformers/models/distilbert/modeling_distilbert.py +1392 -0
  39. env-llmeval/lib/python3.10/site-packages/transformers/models/distilbert/modeling_flax_distilbert.py +895 -0
  40. env-llmeval/lib/python3.10/site-packages/transformers/models/distilbert/modeling_tf_distilbert.py +1146 -0
  41. env-llmeval/lib/python3.10/site-packages/transformers/models/distilbert/tokenization_distilbert.py +553 -0
  42. env-llmeval/lib/python3.10/site-packages/transformers/models/distilbert/tokenization_distilbert_fast.py +231 -0
  43. env-llmeval/lib/python3.10/site-packages/transformers/models/ernie/__init__.py +70 -0
  44. env-llmeval/lib/python3.10/site-packages/transformers/models/ernie/__pycache__/__init__.cpython-310.pyc +0 -0
  45. env-llmeval/lib/python3.10/site-packages/transformers/models/ernie/__pycache__/modeling_ernie.cpython-310.pyc +0 -0
  46. env-llmeval/lib/python3.10/site-packages/transformers/models/ernie/configuration_ernie.py +172 -0
  47. env-llmeval/lib/python3.10/site-packages/transformers/models/ernie/modeling_ernie.py +1832 -0
  48. env-llmeval/lib/python3.10/site-packages/transformers/models/fastspeech2_conformer/__init__.py +77 -0
  49. env-llmeval/lib/python3.10/site-packages/transformers/models/fastspeech2_conformer/__pycache__/configuration_fastspeech2_conformer.cpython-310.pyc +0 -0
  50. env-llmeval/lib/python3.10/site-packages/transformers/models/fastspeech2_conformer/__pycache__/convert_fastspeech2_conformer_original_pytorch_checkpoint_to_pytorch.cpython-310.pyc +0 -0
env-llmeval/lib/python3.10/site-packages/transformers/models/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (4.95 kB). View file
 
env-llmeval/lib/python3.10/site-packages/transformers/models/bert_japanese/__init__.py ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020 The HuggingFace Team. All rights reserved.
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
+
15
+ from typing import TYPE_CHECKING
16
+
17
+ from ...utils import _LazyModule
18
+
19
+
20
+ _import_structure = {"tokenization_bert_japanese": ["BertJapaneseTokenizer", "CharacterTokenizer", "MecabTokenizer"]}
21
+
22
+
23
+ if TYPE_CHECKING:
24
+ from .tokenization_bert_japanese import BertJapaneseTokenizer, CharacterTokenizer, MecabTokenizer
25
+
26
+ else:
27
+ import sys
28
+
29
+ sys.modules[__name__] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
env-llmeval/lib/python3.10/site-packages/transformers/models/bert_japanese/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (575 Bytes). View file
 
env-llmeval/lib/python3.10/site-packages/transformers/models/bert_japanese/__pycache__/tokenization_bert_japanese.cpython-310.pyc ADDED
Binary file (30.7 kB). View file
 
env-llmeval/lib/python3.10/site-packages/transformers/models/bert_japanese/tokenization_bert_japanese.py ADDED
@@ -0,0 +1,1028 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
17
+
18
+ import collections
19
+ import copy
20
+ import os
21
+ import unicodedata
22
+ from typing import Any, Dict, List, Optional, Tuple
23
+
24
+ from ...tokenization_utils import PreTrainedTokenizer, _is_control, _is_punctuation, _is_whitespace
25
+ from ...utils import is_sentencepiece_available, is_sudachi_projection_available, logging
26
+
27
+
28
+ if is_sentencepiece_available():
29
+ import sentencepiece as spm
30
+ else:
31
+ spm = None
32
+
33
+ logger = logging.get_logger(__name__)
34
+
35
+ VOCAB_FILES_NAMES = {"vocab_file": "vocab.txt", "spm_file": "spiece.model"}
36
+
37
+ SPIECE_UNDERLINE = "▁"
38
+
39
+ PRETRAINED_VOCAB_FILES_MAP = {
40
+ "vocab_file": {
41
+ "cl-tohoku/bert-base-japanese": "https://huggingface.co/cl-tohoku/bert-base-japanese/resolve/main/vocab.txt",
42
+ "cl-tohoku/bert-base-japanese-whole-word-masking": (
43
+ "https://huggingface.co/cl-tohoku/bert-base-japanese-whole-word-masking/resolve/main/vocab.txt"
44
+ ),
45
+ "cl-tohoku/bert-base-japanese-char": (
46
+ "https://huggingface.co/cl-tohoku/bert-base-japanese-char/resolve/main/vocab.txt"
47
+ ),
48
+ "cl-tohoku/bert-base-japanese-char-whole-word-masking": (
49
+ "https://huggingface.co/cl-tohoku/bert-base-japanese-char-whole-word-masking/resolve/main/vocab.txt"
50
+ ),
51
+ }
52
+ }
53
+
54
+ PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES = {
55
+ "cl-tohoku/bert-base-japanese": 512,
56
+ "cl-tohoku/bert-base-japanese-whole-word-masking": 512,
57
+ "cl-tohoku/bert-base-japanese-char": 512,
58
+ "cl-tohoku/bert-base-japanese-char-whole-word-masking": 512,
59
+ }
60
+
61
+ PRETRAINED_INIT_CONFIGURATION = {
62
+ "cl-tohoku/bert-base-japanese": {
63
+ "do_lower_case": False,
64
+ "word_tokenizer_type": "mecab",
65
+ "subword_tokenizer_type": "wordpiece",
66
+ },
67
+ "cl-tohoku/bert-base-japanese-whole-word-masking": {
68
+ "do_lower_case": False,
69
+ "word_tokenizer_type": "mecab",
70
+ "subword_tokenizer_type": "wordpiece",
71
+ },
72
+ "cl-tohoku/bert-base-japanese-char": {
73
+ "do_lower_case": False,
74
+ "word_tokenizer_type": "mecab",
75
+ "subword_tokenizer_type": "character",
76
+ },
77
+ "cl-tohoku/bert-base-japanese-char-whole-word-masking": {
78
+ "do_lower_case": False,
79
+ "word_tokenizer_type": "mecab",
80
+ "subword_tokenizer_type": "character",
81
+ },
82
+ }
83
+
84
+
85
+ # Copied from transformers.models.bert.tokenization_bert.load_vocab
86
+ def load_vocab(vocab_file):
87
+ """Loads a vocabulary file into a dictionary."""
88
+ vocab = collections.OrderedDict()
89
+ with open(vocab_file, "r", encoding="utf-8") as reader:
90
+ tokens = reader.readlines()
91
+ for index, token in enumerate(tokens):
92
+ token = token.rstrip("\n")
93
+ vocab[token] = index
94
+ return vocab
95
+
96
+
97
+ # Copied from transformers.models.bert.tokenization_bert.whitespace_tokenize
98
+ def whitespace_tokenize(text):
99
+ """Runs basic whitespace cleaning and splitting on a piece of text."""
100
+ text = text.strip()
101
+ if not text:
102
+ return []
103
+ tokens = text.split()
104
+ return tokens
105
+
106
+
107
+ class BertJapaneseTokenizer(PreTrainedTokenizer):
108
+ r"""
109
+ Construct a BERT tokenizer for Japanese text.
110
+
111
+ This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer
112
+ to: this superclass for more information regarding those methods.
113
+
114
+ Args:
115
+ vocab_file (`str`):
116
+ Path to a one-wordpiece-per-line vocabulary file.
117
+ spm_file (`str`, *optional*):
118
+ Path to [SentencePiece](https://github.com/google/sentencepiece) file (generally has a .spm or .model
119
+ extension) that contains the vocabulary.
120
+ do_lower_case (`bool`, *optional*, defaults to `True`):
121
+ Whether to lower case the input. Only has an effect when do_basic_tokenize=True.
122
+ do_word_tokenize (`bool`, *optional*, defaults to `True`):
123
+ Whether to do word tokenization.
124
+ do_subword_tokenize (`bool`, *optional*, defaults to `True`):
125
+ Whether to do subword tokenization.
126
+ word_tokenizer_type (`str`, *optional*, defaults to `"basic"`):
127
+ Type of word tokenizer. Choose from ["basic", "mecab", "sudachi", "jumanpp"].
128
+ subword_tokenizer_type (`str`, *optional*, defaults to `"wordpiece"`):
129
+ Type of subword tokenizer. Choose from ["wordpiece", "character", "sentencepiece",].
130
+ mecab_kwargs (`dict`, *optional*):
131
+ Dictionary passed to the `MecabTokenizer` constructor.
132
+ sudachi_kwargs (`dict`, *optional*):
133
+ Dictionary passed to the `SudachiTokenizer` constructor.
134
+ jumanpp_kwargs (`dict`, *optional*):
135
+ Dictionary passed to the `JumanppTokenizer` constructor.
136
+ """
137
+
138
+ vocab_files_names = VOCAB_FILES_NAMES
139
+ pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP
140
+ pretrained_init_configuration = PRETRAINED_INIT_CONFIGURATION
141
+ max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
142
+
143
+ def __init__(
144
+ self,
145
+ vocab_file,
146
+ spm_file=None,
147
+ do_lower_case=False,
148
+ do_word_tokenize=True,
149
+ do_subword_tokenize=True,
150
+ word_tokenizer_type="basic",
151
+ subword_tokenizer_type="wordpiece",
152
+ never_split=None,
153
+ unk_token="[UNK]",
154
+ sep_token="[SEP]",
155
+ pad_token="[PAD]",
156
+ cls_token="[CLS]",
157
+ mask_token="[MASK]",
158
+ mecab_kwargs=None,
159
+ sudachi_kwargs=None,
160
+ jumanpp_kwargs=None,
161
+ **kwargs,
162
+ ):
163
+ if subword_tokenizer_type == "sentencepiece":
164
+ if not os.path.isfile(spm_file):
165
+ raise ValueError(
166
+ f"Can't find a vocabulary file at path '{spm_file}'. To load the vocabulary from a Google"
167
+ " pretrained model use `tokenizer = AutoTokenizer.from_pretrained(PRETRAINED_MODEL_NAME)`"
168
+ )
169
+ self.spm_file = spm_file
170
+ else:
171
+ if not os.path.isfile(vocab_file):
172
+ raise ValueError(
173
+ f"Can't find a vocabulary file at path '{vocab_file}'. To load the vocabulary from a Google"
174
+ " pretrained model use `tokenizer = AutoTokenizer.from_pretrained(PRETRAINED_MODEL_NAME)`"
175
+ )
176
+ self.vocab = load_vocab(vocab_file)
177
+ self.ids_to_tokens = collections.OrderedDict([(ids, tok) for tok, ids in self.vocab.items()])
178
+
179
+ self.do_word_tokenize = do_word_tokenize
180
+ self.word_tokenizer_type = word_tokenizer_type
181
+ self.lower_case = do_lower_case
182
+ self.never_split = never_split
183
+ self.mecab_kwargs = copy.deepcopy(mecab_kwargs)
184
+ self.sudachi_kwargs = copy.deepcopy(sudachi_kwargs)
185
+ self.jumanpp_kwargs = copy.deepcopy(jumanpp_kwargs)
186
+ if do_word_tokenize:
187
+ if word_tokenizer_type == "basic":
188
+ self.word_tokenizer = BasicTokenizer(
189
+ do_lower_case=do_lower_case, never_split=never_split, tokenize_chinese_chars=False
190
+ )
191
+ elif word_tokenizer_type == "mecab":
192
+ self.word_tokenizer = MecabTokenizer(
193
+ do_lower_case=do_lower_case, never_split=never_split, **(mecab_kwargs or {})
194
+ )
195
+ elif word_tokenizer_type == "sudachi":
196
+ self.word_tokenizer = SudachiTokenizer(
197
+ do_lower_case=do_lower_case, never_split=never_split, **(sudachi_kwargs or {})
198
+ )
199
+ elif word_tokenizer_type == "jumanpp":
200
+ self.word_tokenizer = JumanppTokenizer(
201
+ do_lower_case=do_lower_case, never_split=never_split, **(jumanpp_kwargs or {})
202
+ )
203
+ else:
204
+ raise ValueError(f"Invalid word_tokenizer_type '{word_tokenizer_type}' is specified.")
205
+
206
+ self.do_subword_tokenize = do_subword_tokenize
207
+ self.subword_tokenizer_type = subword_tokenizer_type
208
+ if do_subword_tokenize:
209
+ if subword_tokenizer_type == "wordpiece":
210
+ self.subword_tokenizer = WordpieceTokenizer(vocab=self.vocab, unk_token=str(unk_token))
211
+ elif subword_tokenizer_type == "character":
212
+ self.subword_tokenizer = CharacterTokenizer(vocab=self.vocab, unk_token=str(unk_token))
213
+ elif subword_tokenizer_type == "sentencepiece":
214
+ self.subword_tokenizer = SentencepieceTokenizer(vocab=self.spm_file, unk_token=str(unk_token))
215
+ else:
216
+ raise ValueError(f"Invalid subword_tokenizer_type '{subword_tokenizer_type}' is specified.")
217
+ super().__init__(
218
+ spm_file=spm_file,
219
+ unk_token=unk_token,
220
+ sep_token=sep_token,
221
+ pad_token=pad_token,
222
+ cls_token=cls_token,
223
+ mask_token=mask_token,
224
+ do_lower_case=do_lower_case,
225
+ do_word_tokenize=do_word_tokenize,
226
+ do_subword_tokenize=do_subword_tokenize,
227
+ word_tokenizer_type=word_tokenizer_type,
228
+ subword_tokenizer_type=subword_tokenizer_type,
229
+ never_split=never_split,
230
+ mecab_kwargs=mecab_kwargs,
231
+ sudachi_kwargs=sudachi_kwargs,
232
+ jumanpp_kwargs=jumanpp_kwargs,
233
+ **kwargs,
234
+ )
235
+
236
+ @property
237
+ def do_lower_case(self):
238
+ return self.lower_case
239
+
240
+ def __getstate__(self):
241
+ state = dict(self.__dict__)
242
+ if self.word_tokenizer_type in ["mecab", "sudachi", "jumanpp"]:
243
+ del state["word_tokenizer"]
244
+ return state
245
+
246
+ def __setstate__(self, state):
247
+ self.__dict__ = state
248
+ if self.word_tokenizer_type == "mecab":
249
+ self.word_tokenizer = MecabTokenizer(
250
+ do_lower_case=self.do_lower_case, never_split=self.never_split, **(self.mecab_kwargs or {})
251
+ )
252
+ elif self.word_tokenizer_type == "sudachi":
253
+ self.word_tokenizer = SudachiTokenizer(
254
+ do_lower_case=self.do_lower_case, never_split=self.never_split, **(self.sudachi_kwargs or {})
255
+ )
256
+ elif self.word_tokenizer_type == "jumanpp":
257
+ self.word_tokenizer = JumanppTokenizer(
258
+ do_lower_case=self.do_lower_case, never_split=self.never_split, **(self.jumanpp_kwargs or {})
259
+ )
260
+
261
+ def _tokenize(self, text):
262
+ if self.do_word_tokenize:
263
+ tokens = self.word_tokenizer.tokenize(text, never_split=self.all_special_tokens)
264
+ else:
265
+ tokens = [text]
266
+
267
+ if self.do_subword_tokenize:
268
+ split_tokens = [sub_token for token in tokens for sub_token in self.subword_tokenizer.tokenize(token)]
269
+ else:
270
+ split_tokens = tokens
271
+
272
+ return split_tokens
273
+
274
+ @property
275
+ def vocab_size(self):
276
+ if self.subword_tokenizer_type == "sentencepiece":
277
+ return len(self.subword_tokenizer.sp_model)
278
+ return len(self.vocab)
279
+
280
+ def get_vocab(self):
281
+ if self.subword_tokenizer_type == "sentencepiece":
282
+ vocab = {self.convert_ids_to_tokens(i): i for i in range(self.vocab_size)}
283
+ vocab.update(self.added_tokens_encoder)
284
+ return vocab
285
+ return dict(self.vocab, **self.added_tokens_encoder)
286
+
287
+ def _convert_token_to_id(self, token):
288
+ """Converts a token (str) in an id using the vocab."""
289
+ if self.subword_tokenizer_type == "sentencepiece":
290
+ return self.subword_tokenizer.sp_model.PieceToId(token)
291
+ return self.vocab.get(token, self.vocab.get(self.unk_token))
292
+
293
+ def _convert_id_to_token(self, index):
294
+ """Converts an index (integer) in a token (str) using the vocab."""
295
+ if self.subword_tokenizer_type == "sentencepiece":
296
+ return self.subword_tokenizer.sp_model.IdToPiece(index)
297
+ return self.ids_to_tokens.get(index, self.unk_token)
298
+
299
+ def convert_tokens_to_string(self, tokens):
300
+ """Converts a sequence of tokens (string) in a single string."""
301
+ if self.subword_tokenizer_type == "sentencepiece":
302
+ return self.subword_tokenizer.sp_model.decode(tokens)
303
+ out_string = " ".join(tokens).replace(" ##", "").strip()
304
+ return out_string
305
+
306
+ # Copied from transformers.models.bert.tokenization_bert.BertTokenizer.build_inputs_with_special_tokens
307
+ def build_inputs_with_special_tokens(
308
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
309
+ ) -> List[int]:
310
+ """
311
+ Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
312
+ adding special tokens. A BERT sequence has the following format:
313
+
314
+ - single sequence: `[CLS] X [SEP]`
315
+ - pair of sequences: `[CLS] A [SEP] B [SEP]`
316
+
317
+ Args:
318
+ token_ids_0 (`List[int]`):
319
+ List of IDs to which the special tokens will be added.
320
+ token_ids_1 (`List[int]`, *optional*):
321
+ Optional second list of IDs for sequence pairs.
322
+
323
+ Returns:
324
+ `List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
325
+ """
326
+ if token_ids_1 is None:
327
+ return [self.cls_token_id] + token_ids_0 + [self.sep_token_id]
328
+ cls = [self.cls_token_id]
329
+ sep = [self.sep_token_id]
330
+ return cls + token_ids_0 + sep + token_ids_1 + sep
331
+
332
+ # Copied from transformers.models.bert.tokenization_bert.BertTokenizer.get_special_tokens_mask
333
+ def get_special_tokens_mask(
334
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None, already_has_special_tokens: bool = False
335
+ ) -> List[int]:
336
+ """
337
+ Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
338
+ special tokens using the tokenizer `prepare_for_model` method.
339
+
340
+ Args:
341
+ token_ids_0 (`List[int]`):
342
+ List of IDs.
343
+ token_ids_1 (`List[int]`, *optional*):
344
+ Optional second list of IDs for sequence pairs.
345
+ already_has_special_tokens (`bool`, *optional*, defaults to `False`):
346
+ Whether or not the token list is already formatted with special tokens for the model.
347
+
348
+ Returns:
349
+ `List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
350
+ """
351
+
352
+ if already_has_special_tokens:
353
+ return super().get_special_tokens_mask(
354
+ token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
355
+ )
356
+
357
+ if token_ids_1 is not None:
358
+ return [1] + ([0] * len(token_ids_0)) + [1] + ([0] * len(token_ids_1)) + [1]
359
+ return [1] + ([0] * len(token_ids_0)) + [1]
360
+
361
+ # Copied from transformers.models.bert.tokenization_bert.BertTokenizer.create_token_type_ids_from_sequences
362
+ def create_token_type_ids_from_sequences(
363
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
364
+ ) -> List[int]:
365
+ """
366
+ Create a mask from the two sequences passed to be used in a sequence-pair classification task. A BERT sequence
367
+ pair mask has the following format:
368
+
369
+ ```
370
+ 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1
371
+ | first sequence | second sequence |
372
+ ```
373
+
374
+ If `token_ids_1` is `None`, this method only returns the first portion of the mask (0s).
375
+
376
+ Args:
377
+ token_ids_0 (`List[int]`):
378
+ List of IDs.
379
+ token_ids_1 (`List[int]`, *optional*):
380
+ Optional second list of IDs for sequence pairs.
381
+
382
+ Returns:
383
+ `List[int]`: List of [token type IDs](../glossary#token-type-ids) according to the given sequence(s).
384
+ """
385
+ sep = [self.sep_token_id]
386
+ cls = [self.cls_token_id]
387
+ if token_ids_1 is None:
388
+ return len(cls + token_ids_0 + sep) * [0]
389
+ return len(cls + token_ids_0 + sep) * [0] + len(token_ids_1 + sep) * [1]
390
+
391
+ def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
392
+ if os.path.isdir(save_directory):
393
+ if self.subword_tokenizer_type == "sentencepiece":
394
+ vocab_file = os.path.join(
395
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["spm_file"]
396
+ )
397
+ else:
398
+ vocab_file = os.path.join(
399
+ save_directory,
400
+ (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"],
401
+ )
402
+ else:
403
+ vocab_file = (filename_prefix + "-" if filename_prefix else "") + save_directory
404
+
405
+ if self.subword_tokenizer_type == "sentencepiece":
406
+ with open(vocab_file, "wb") as writer:
407
+ content_spiece_model = self.subword_tokenizer.sp_model.serialized_model_proto()
408
+ writer.write(content_spiece_model)
409
+ else:
410
+ with open(vocab_file, "w", encoding="utf-8") as writer:
411
+ index = 0
412
+ for token, token_index in sorted(self.vocab.items(), key=lambda kv: kv[1]):
413
+ if index != token_index:
414
+ logger.warning(
415
+ f"Saving vocabulary to {vocab_file}: vocabulary indices are not consecutive."
416
+ " Please check that the vocabulary is not corrupted!"
417
+ )
418
+ index = token_index
419
+ writer.write(token + "\n")
420
+ index += 1
421
+ return (vocab_file,)
422
+
423
+
424
+ class MecabTokenizer:
425
+ """Runs basic tokenization with MeCab morphological parser."""
426
+
427
+ def __init__(
428
+ self,
429
+ do_lower_case=False,
430
+ never_split=None,
431
+ normalize_text=True,
432
+ mecab_dic: Optional[str] = "ipadic",
433
+ mecab_option: Optional[str] = None,
434
+ ):
435
+ """
436
+ Constructs a MecabTokenizer.
437
+
438
+ Args:
439
+ **do_lower_case**: (*optional*) boolean (default True)
440
+ Whether to lowercase the input.
441
+ **never_split**: (*optional*) list of str
442
+ Kept for backward compatibility purposes. Now implemented directly at the base class level (see
443
+ [`PreTrainedTokenizer.tokenize`]) List of tokens not to split.
444
+ **normalize_text**: (*optional*) boolean (default True)
445
+ Whether to apply unicode normalization to text before tokenization.
446
+ **mecab_dic**: (*optional*) string (default "ipadic")
447
+ Name of dictionary to be used for MeCab initialization. If you are using a system-installed dictionary,
448
+ set this option to `None` and modify *mecab_option*.
449
+ **mecab_option**: (*optional*) string
450
+ String passed to MeCab constructor.
451
+ """
452
+ self.do_lower_case = do_lower_case
453
+ self.never_split = never_split if never_split is not None else []
454
+ self.normalize_text = normalize_text
455
+
456
+ try:
457
+ import fugashi
458
+ except ModuleNotFoundError as error:
459
+ raise error.__class__(
460
+ "You need to install fugashi to use MecabTokenizer. "
461
+ "See https://pypi.org/project/fugashi/ for installation."
462
+ )
463
+
464
+ mecab_option = mecab_option or ""
465
+
466
+ if mecab_dic is not None:
467
+ if mecab_dic == "ipadic":
468
+ try:
469
+ import ipadic
470
+ except ModuleNotFoundError as error:
471
+ raise error.__class__(
472
+ "The ipadic dictionary is not installed. "
473
+ "See https://github.com/polm/ipadic-py for installation."
474
+ )
475
+
476
+ dic_dir = ipadic.DICDIR
477
+
478
+ elif mecab_dic == "unidic_lite":
479
+ try:
480
+ import unidic_lite
481
+ except ModuleNotFoundError as error:
482
+ raise error.__class__(
483
+ "The unidic_lite dictionary is not installed. "
484
+ "See https://github.com/polm/unidic-lite for installation."
485
+ )
486
+
487
+ dic_dir = unidic_lite.DICDIR
488
+
489
+ elif mecab_dic == "unidic":
490
+ try:
491
+ import unidic
492
+ except ModuleNotFoundError as error:
493
+ raise error.__class__(
494
+ "The unidic dictionary is not installed. "
495
+ "See https://github.com/polm/unidic-py for installation."
496
+ )
497
+
498
+ dic_dir = unidic.DICDIR
499
+ if not os.path.isdir(dic_dir):
500
+ raise RuntimeError(
501
+ "The unidic dictionary itself is not found. "
502
+ "See https://github.com/polm/unidic-py for installation."
503
+ )
504
+
505
+ else:
506
+ raise ValueError("Invalid mecab_dic is specified.")
507
+
508
+ mecabrc = os.path.join(dic_dir, "mecabrc")
509
+ mecab_option = f'-d "{dic_dir}" -r "{mecabrc}" ' + mecab_option
510
+
511
+ self.mecab = fugashi.GenericTagger(mecab_option)
512
+
513
+ def tokenize(self, text, never_split=None, **kwargs):
514
+ """Tokenizes a piece of text."""
515
+ if self.normalize_text:
516
+ text = unicodedata.normalize("NFKC", text)
517
+
518
+ never_split = self.never_split + (never_split if never_split is not None else [])
519
+ tokens = []
520
+
521
+ for word in self.mecab(text):
522
+ token = word.surface
523
+
524
+ if self.do_lower_case and token not in never_split:
525
+ token = token.lower()
526
+
527
+ tokens.append(token)
528
+
529
+ return tokens
530
+
531
+
532
+ class SudachiTokenizer:
533
+ """Runs basic tokenization with Sudachi morphological parser."""
534
+
535
+ def __init__(
536
+ self,
537
+ do_lower_case=False,
538
+ never_split=None,
539
+ normalize_text=True,
540
+ trim_whitespace=False,
541
+ sudachi_split_mode="A",
542
+ sudachi_config_path=None,
543
+ sudachi_resource_dir=None,
544
+ sudachi_dict_type="core",
545
+ sudachi_projection=None,
546
+ ):
547
+ """
548
+ Constructs a SudachiTokenizer.
549
+
550
+ Args:
551
+ **do_lower_case**: (*optional*) boolean (default True)
552
+ Whether to lowercase the input.
553
+ **never_split**: (*optional*) list of str
554
+ Kept for backward compatibility purposes. Now implemented directly at the base class level (see
555
+ [`PreTrainedTokenizer.tokenize`]) List of tokens not to split.
556
+ **normalize_text**: (*optional*) boolean (default True)
557
+ Whether to apply unicode normalization to text before tokenization.
558
+ **trim_whitespace**: (*optional*) boolean (default False)
559
+ Whether to trim all whitespace, tab, newline from tokens.
560
+ **sudachi_split_mode**: (*optional*) string
561
+ Split mode of sudachi, choose from `["A", "B", "C"]`.
562
+ **sudachi_config_path**: (*optional*) string
563
+ **sudachi_resource_dir**: (*optional*) string
564
+ **sudachi_dict_type**: (*optional*) string
565
+ dict type of sudachi, choose from `["small", "core", "full"]`.
566
+ **sudachi_projection**: (*optional*) string
567
+ Word projection mode of sudachi, choose from `["surface", "normalized", "reading", "dictionary", "dictionary_and_surface", "normalized_and_surface", "normalized_nouns"]`.
568
+ """
569
+
570
+ self.do_lower_case = do_lower_case
571
+ self.never_split = never_split if never_split is not None else []
572
+ self.normalize_text = normalize_text
573
+ self.trim_whitespace = trim_whitespace
574
+
575
+ try:
576
+ from sudachipy import dictionary, tokenizer
577
+ except ImportError:
578
+ raise ImportError(
579
+ "You need to install sudachipy to use SudachiTokenizer. "
580
+ "See https://github.com/WorksApplications/SudachiPy for installation."
581
+ )
582
+
583
+ if sudachi_split_mode == "A":
584
+ self.split_mode = tokenizer.Tokenizer.SplitMode.A
585
+ elif sudachi_split_mode == "B":
586
+ self.split_mode = tokenizer.Tokenizer.SplitMode.B
587
+ elif sudachi_split_mode == "C":
588
+ self.split_mode = tokenizer.Tokenizer.SplitMode.C
589
+ else:
590
+ raise ValueError("Invalid sudachi_split_mode is specified.")
591
+
592
+ self.projection = sudachi_projection
593
+
594
+ sudachi_dictionary = dictionary.Dictionary(
595
+ config_path=sudachi_config_path, resource_dir=sudachi_resource_dir, dict=sudachi_dict_type
596
+ )
597
+ if is_sudachi_projection_available():
598
+ self.sudachi = sudachi_dictionary.create(self.split_mode, projection=self.projection)
599
+ elif self.projection is not None:
600
+ raise ImportError("You need to install sudachipy>=0.6.8 to specify `projection` field in sudachi_kwargs.")
601
+ else:
602
+ self.sudachi = sudachi_dictionary.create(self.split_mode)
603
+
604
+ def tokenize(self, text, never_split=None, **kwargs):
605
+ """Tokenizes a piece of text."""
606
+ if self.normalize_text:
607
+ text = unicodedata.normalize("NFKC", text)
608
+
609
+ never_split = self.never_split + (never_split if never_split is not None else [])
610
+ tokens = []
611
+
612
+ for word in self.sudachi.tokenize(text):
613
+ token = word.surface()
614
+
615
+ if self.do_lower_case and token not in never_split:
616
+ token = token.lower()
617
+
618
+ if self.trim_whitespace:
619
+ if token.strip() == "":
620
+ continue
621
+ else:
622
+ token = token.strip()
623
+
624
+ tokens.append(token)
625
+
626
+ return tokens
627
+
628
+
629
+ class JumanppTokenizer:
630
+ """Runs basic tokenization with jumanpp morphological parser."""
631
+
632
+ def __init__(
633
+ self,
634
+ do_lower_case=False,
635
+ never_split=None,
636
+ normalize_text=True,
637
+ trim_whitespace=False,
638
+ ):
639
+ """
640
+ Constructs a JumanppTokenizer.
641
+
642
+ Args:
643
+ **do_lower_case**: (*optional*) boolean (default True)
644
+ Whether to lowercase the input.
645
+ **never_split**: (*optional*) list of str
646
+ Kept for backward compatibility purposes. Now implemented directly at the base class level (see
647
+ [`PreTrainedTokenizer.tokenize`]) List of tokens not to split.
648
+ **normalize_text**: (*optional*) boolean (default True)
649
+ Whether to apply unicode normalization to text before tokenization.
650
+ **trim_whitespace**: (*optional*) boolean (default False)
651
+ Whether to trim all whitespace, tab, newline from tokens.
652
+ """
653
+
654
+ self.do_lower_case = do_lower_case
655
+ self.never_split = never_split if never_split is not None else []
656
+ self.normalize_text = normalize_text
657
+ self.trim_whitespace = trim_whitespace
658
+
659
+ try:
660
+ import rhoknp
661
+ except ImportError:
662
+ raise ImportError(
663
+ "You need to install rhoknp to use JumanppTokenizer. "
664
+ "See https://github.com/ku-nlp/rhoknp for installation."
665
+ )
666
+
667
+ self.juman = rhoknp.Jumanpp()
668
+
669
+ def tokenize(self, text, never_split=None, **kwargs):
670
+ """Tokenizes a piece of text."""
671
+ if self.normalize_text:
672
+ text = unicodedata.normalize("NFKC", text)
673
+
674
+ text = text.strip()
675
+
676
+ never_split = self.never_split + (never_split if never_split is not None else [])
677
+ tokens = []
678
+
679
+ for mrph in self.juman.apply_to_sentence(text).morphemes:
680
+ token = mrph.text
681
+
682
+ if self.do_lower_case and token not in never_split:
683
+ token = token.lower()
684
+
685
+ if self.trim_whitespace:
686
+ if token.strip() == "":
687
+ continue
688
+ else:
689
+ token = token.strip()
690
+
691
+ tokens.append(token)
692
+
693
+ return tokens
694
+
695
+
696
+ class CharacterTokenizer:
697
+ """Runs Character tokenization."""
698
+
699
+ def __init__(self, vocab, unk_token, normalize_text=True):
700
+ """
701
+ Constructs a CharacterTokenizer.
702
+
703
+ Args:
704
+ **vocab**:
705
+ Vocabulary object.
706
+ **unk_token**: str
707
+ A special symbol for out-of-vocabulary token.
708
+ **normalize_text**: (`optional`) boolean (default True)
709
+ Whether to apply unicode normalization to text before tokenization.
710
+ """
711
+ self.vocab = vocab
712
+ self.unk_token = unk_token
713
+ self.normalize_text = normalize_text
714
+
715
+ def tokenize(self, text):
716
+ """
717
+ Tokenizes a piece of text into characters.
718
+
719
+ For example, `input = "apple""` wil return as output `["a", "p", "p", "l", "e"]`.
720
+
721
+ Args:
722
+ text: A single token or whitespace separated tokens.
723
+ This should have already been passed through *BasicTokenizer*.
724
+
725
+ Returns:
726
+ A list of characters.
727
+ """
728
+ if self.normalize_text:
729
+ text = unicodedata.normalize("NFKC", text)
730
+
731
+ output_tokens = []
732
+ for char in text:
733
+ if char not in self.vocab:
734
+ output_tokens.append(self.unk_token)
735
+ continue
736
+
737
+ output_tokens.append(char)
738
+
739
+ return output_tokens
740
+
741
+
742
+ # Copied from transformers.models.bert.tokenization_bert.BasicTokenizer
743
+ class BasicTokenizer(object):
744
+ """
745
+ Constructs a BasicTokenizer that will run basic tokenization (punctuation splitting, lower casing, etc.).
746
+
747
+ Args:
748
+ do_lower_case (`bool`, *optional*, defaults to `True`):
749
+ Whether or not to lowercase the input when tokenizing.
750
+ never_split (`Iterable`, *optional*):
751
+ Collection of tokens which will never be split during tokenization. Only has an effect when
752
+ `do_basic_tokenize=True`
753
+ tokenize_chinese_chars (`bool`, *optional*, defaults to `True`):
754
+ Whether or not to tokenize Chinese characters.
755
+
756
+ This should likely be deactivated for Japanese (see this
757
+ [issue](https://github.com/huggingface/transformers/issues/328)).
758
+ strip_accents (`bool`, *optional*):
759
+ Whether or not to strip all accents. If this option is not specified, then it will be determined by the
760
+ value for `lowercase` (as in the original BERT).
761
+ do_split_on_punc (`bool`, *optional*, defaults to `True`):
762
+ In some instances we want to skip the basic punctuation splitting so that later tokenization can capture
763
+ the full context of the words, such as contractions.
764
+ """
765
+
766
+ def __init__(
767
+ self,
768
+ do_lower_case=True,
769
+ never_split=None,
770
+ tokenize_chinese_chars=True,
771
+ strip_accents=None,
772
+ do_split_on_punc=True,
773
+ ):
774
+ if never_split is None:
775
+ never_split = []
776
+ self.do_lower_case = do_lower_case
777
+ self.never_split = set(never_split)
778
+ self.tokenize_chinese_chars = tokenize_chinese_chars
779
+ self.strip_accents = strip_accents
780
+ self.do_split_on_punc = do_split_on_punc
781
+
782
+ def tokenize(self, text, never_split=None):
783
+ """
784
+ Basic Tokenization of a piece of text. For sub-word tokenization, see WordPieceTokenizer.
785
+
786
+ Args:
787
+ never_split (`List[str]`, *optional*)
788
+ Kept for backward compatibility purposes. Now implemented directly at the base class level (see
789
+ [`PreTrainedTokenizer.tokenize`]) List of token not to split.
790
+ """
791
+ # union() returns a new set by concatenating the two sets.
792
+ never_split = self.never_split.union(set(never_split)) if never_split else self.never_split
793
+ text = self._clean_text(text)
794
+
795
+ # This was added on November 1st, 2018 for the multilingual and Chinese
796
+ # models. This is also applied to the English models now, but it doesn't
797
+ # matter since the English models were not trained on any Chinese data
798
+ # and generally don't have any Chinese data in them (there are Chinese
799
+ # characters in the vocabulary because Wikipedia does have some Chinese
800
+ # words in the English Wikipedia.).
801
+ if self.tokenize_chinese_chars:
802
+ text = self._tokenize_chinese_chars(text)
803
+ # prevents treating the same character with different unicode codepoints as different characters
804
+ unicode_normalized_text = unicodedata.normalize("NFC", text)
805
+ orig_tokens = whitespace_tokenize(unicode_normalized_text)
806
+ split_tokens = []
807
+ for token in orig_tokens:
808
+ if token not in never_split:
809
+ if self.do_lower_case:
810
+ token = token.lower()
811
+ if self.strip_accents is not False:
812
+ token = self._run_strip_accents(token)
813
+ elif self.strip_accents:
814
+ token = self._run_strip_accents(token)
815
+ split_tokens.extend(self._run_split_on_punc(token, never_split))
816
+
817
+ output_tokens = whitespace_tokenize(" ".join(split_tokens))
818
+ return output_tokens
819
+
820
+ def _run_strip_accents(self, text):
821
+ """Strips accents from a piece of text."""
822
+ text = unicodedata.normalize("NFD", text)
823
+ output = []
824
+ for char in text:
825
+ cat = unicodedata.category(char)
826
+ if cat == "Mn":
827
+ continue
828
+ output.append(char)
829
+ return "".join(output)
830
+
831
+ def _run_split_on_punc(self, text, never_split=None):
832
+ """Splits punctuation on a piece of text."""
833
+ if not self.do_split_on_punc or (never_split is not None and text in never_split):
834
+ return [text]
835
+ chars = list(text)
836
+ i = 0
837
+ start_new_word = True
838
+ output = []
839
+ while i < len(chars):
840
+ char = chars[i]
841
+ if _is_punctuation(char):
842
+ output.append([char])
843
+ start_new_word = True
844
+ else:
845
+ if start_new_word:
846
+ output.append([])
847
+ start_new_word = False
848
+ output[-1].append(char)
849
+ i += 1
850
+
851
+ return ["".join(x) for x in output]
852
+
853
+ def _tokenize_chinese_chars(self, text):
854
+ """Adds whitespace around any CJK character."""
855
+ output = []
856
+ for char in text:
857
+ cp = ord(char)
858
+ if self._is_chinese_char(cp):
859
+ output.append(" ")
860
+ output.append(char)
861
+ output.append(" ")
862
+ else:
863
+ output.append(char)
864
+ return "".join(output)
865
+
866
+ def _is_chinese_char(self, cp):
867
+ """Checks whether CP is the codepoint of a CJK character."""
868
+ # This defines a "chinese character" as anything in the CJK Unicode block:
869
+ # https://en.wikipedia.org/wiki/CJK_Unified_Ideographs_(Unicode_block)
870
+ #
871
+ # Note that the CJK Unicode block is NOT all Japanese and Korean characters,
872
+ # despite its name. The modern Korean Hangul alphabet is a different block,
873
+ # as is Japanese Hiragana and Katakana. Those alphabets are used to write
874
+ # space-separated words, so they are not treated specially and handled
875
+ # like the all of the other languages.
876
+ if (
877
+ (cp >= 0x4E00 and cp <= 0x9FFF)
878
+ or (cp >= 0x3400 and cp <= 0x4DBF) #
879
+ or (cp >= 0x20000 and cp <= 0x2A6DF) #
880
+ or (cp >= 0x2A700 and cp <= 0x2B73F) #
881
+ or (cp >= 0x2B740 and cp <= 0x2B81F) #
882
+ or (cp >= 0x2B820 and cp <= 0x2CEAF) #
883
+ or (cp >= 0xF900 and cp <= 0xFAFF)
884
+ or (cp >= 0x2F800 and cp <= 0x2FA1F) #
885
+ ): #
886
+ return True
887
+
888
+ return False
889
+
890
+ def _clean_text(self, text):
891
+ """Performs invalid character removal and whitespace cleanup on text."""
892
+ output = []
893
+ for char in text:
894
+ cp = ord(char)
895
+ if cp == 0 or cp == 0xFFFD or _is_control(char):
896
+ continue
897
+ if _is_whitespace(char):
898
+ output.append(" ")
899
+ else:
900
+ output.append(char)
901
+ return "".join(output)
902
+
903
+
904
+ # Copied from transformers.models.bert.tokenization_bert.WordpieceTokenizer
905
+ class WordpieceTokenizer(object):
906
+ """Runs WordPiece tokenization."""
907
+
908
+ def __init__(self, vocab, unk_token, max_input_chars_per_word=100):
909
+ self.vocab = vocab
910
+ self.unk_token = unk_token
911
+ self.max_input_chars_per_word = max_input_chars_per_word
912
+
913
+ def tokenize(self, text):
914
+ """
915
+ Tokenizes a piece of text into its word pieces. This uses a greedy longest-match-first algorithm to perform
916
+ tokenization using the given vocabulary.
917
+
918
+ For example, `input = "unaffable"` wil return as output `["un", "##aff", "##able"]`.
919
+
920
+ Args:
921
+ text: A single token or whitespace separated tokens. This should have
922
+ already been passed through *BasicTokenizer*.
923
+
924
+ Returns:
925
+ A list of wordpiece tokens.
926
+ """
927
+
928
+ output_tokens = []
929
+ for token in whitespace_tokenize(text):
930
+ chars = list(token)
931
+ if len(chars) > self.max_input_chars_per_word:
932
+ output_tokens.append(self.unk_token)
933
+ continue
934
+
935
+ is_bad = False
936
+ start = 0
937
+ sub_tokens = []
938
+ while start < len(chars):
939
+ end = len(chars)
940
+ cur_substr = None
941
+ while start < end:
942
+ substr = "".join(chars[start:end])
943
+ if start > 0:
944
+ substr = "##" + substr
945
+ if substr in self.vocab:
946
+ cur_substr = substr
947
+ break
948
+ end -= 1
949
+ if cur_substr is None:
950
+ is_bad = True
951
+ break
952
+ sub_tokens.append(cur_substr)
953
+ start = end
954
+
955
+ if is_bad:
956
+ output_tokens.append(self.unk_token)
957
+ else:
958
+ output_tokens.extend(sub_tokens)
959
+ return output_tokens
960
+
961
+
962
+ class SentencepieceTokenizer(object):
963
+ """
964
+ Runs sentencepiece tokenization. Based on transformers.models.albert.tokenization_albert.AlbertTokenizer.
965
+ """
966
+
967
+ def __init__(
968
+ self,
969
+ vocab,
970
+ unk_token,
971
+ do_lower_case=False,
972
+ remove_space=True,
973
+ keep_accents=True,
974
+ sp_model_kwargs: Optional[Dict[str, Any]] = None,
975
+ ):
976
+ self.vocab = vocab
977
+ self.unk_token = unk_token
978
+ self.do_lower_case = do_lower_case
979
+ self.remove_space = remove_space
980
+ self.keep_accents = keep_accents
981
+
982
+ self.sp_model_kwargs = {} if sp_model_kwargs is None else sp_model_kwargs
983
+ self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
984
+ self.sp_model.Load(self.vocab)
985
+
986
+ def preprocess_text(self, inputs):
987
+ if self.remove_space:
988
+ outputs = " ".join(inputs.strip().split())
989
+ else:
990
+ outputs = inputs
991
+ outputs = outputs.replace("``", '"').replace("''", '"')
992
+
993
+ if not self.keep_accents:
994
+ outputs = unicodedata.normalize("NFKD", outputs)
995
+ outputs = "".join([c for c in outputs if not unicodedata.combining(c)])
996
+ if self.do_lower_case:
997
+ outputs = outputs.lower()
998
+
999
+ return outputs
1000
+
1001
+ def tokenize(self, text):
1002
+ """
1003
+ Tokenizes text by sentencepiece. Based on [SentencePiece](https://github.com/google/sentencepiece).
1004
+ Tokenization needs the given vocabulary.
1005
+
1006
+ Args:
1007
+ text: A string needs to be tokenized.
1008
+
1009
+ Returns:
1010
+ A list of sentencepiece tokens.
1011
+ """
1012
+ text = self.preprocess_text(text)
1013
+ pieces = self.sp_model.encode(text, out_type=str)
1014
+ new_pieces = []
1015
+ for piece in pieces:
1016
+ if len(piece) > 1 and piece[-1] == str(",") and piece[-2].isdigit():
1017
+ cur_pieces = self.sp_model.EncodeAsPieces(piece[:-1].replace(SPIECE_UNDERLINE, ""))
1018
+ if piece[0] != SPIECE_UNDERLINE and cur_pieces[0][0] == SPIECE_UNDERLINE:
1019
+ if len(cur_pieces[0]) == 1:
1020
+ cur_pieces = cur_pieces[1:]
1021
+ else:
1022
+ cur_pieces[0] = cur_pieces[0][1:]
1023
+ cur_pieces.append(piece[-1])
1024
+ new_pieces.extend(cur_pieces)
1025
+ else:
1026
+ new_pieces.append(piece)
1027
+
1028
+ return new_pieces
env-llmeval/lib/python3.10/site-packages/transformers/models/blenderbot/__init__.py ADDED
@@ -0,0 +1,142 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020 The HuggingFace Team. All rights reserved.
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
+
15
+ from typing import TYPE_CHECKING
16
+
17
+ from ...utils import (
18
+ OptionalDependencyNotAvailable,
19
+ _LazyModule,
20
+ is_flax_available,
21
+ is_tf_available,
22
+ is_tokenizers_available,
23
+ is_torch_available,
24
+ )
25
+
26
+
27
+ _import_structure = {
28
+ "configuration_blenderbot": [
29
+ "BLENDERBOT_PRETRAINED_CONFIG_ARCHIVE_MAP",
30
+ "BlenderbotConfig",
31
+ "BlenderbotOnnxConfig",
32
+ ],
33
+ "tokenization_blenderbot": ["BlenderbotTokenizer"],
34
+ }
35
+
36
+ try:
37
+ if not is_tokenizers_available():
38
+ raise OptionalDependencyNotAvailable()
39
+ except OptionalDependencyNotAvailable:
40
+ pass
41
+ else:
42
+ _import_structure["tokenization_blenderbot_fast"] = ["BlenderbotTokenizerFast"]
43
+
44
+ try:
45
+ if not is_torch_available():
46
+ raise OptionalDependencyNotAvailable()
47
+ except OptionalDependencyNotAvailable:
48
+ pass
49
+ else:
50
+ _import_structure["modeling_blenderbot"] = [
51
+ "BLENDERBOT_PRETRAINED_MODEL_ARCHIVE_LIST",
52
+ "BlenderbotForCausalLM",
53
+ "BlenderbotForConditionalGeneration",
54
+ "BlenderbotModel",
55
+ "BlenderbotPreTrainedModel",
56
+ ]
57
+
58
+
59
+ try:
60
+ if not is_tf_available():
61
+ raise OptionalDependencyNotAvailable()
62
+ except OptionalDependencyNotAvailable:
63
+ pass
64
+ else:
65
+ _import_structure["modeling_tf_blenderbot"] = [
66
+ "TFBlenderbotForConditionalGeneration",
67
+ "TFBlenderbotModel",
68
+ "TFBlenderbotPreTrainedModel",
69
+ ]
70
+
71
+
72
+ try:
73
+ if not is_flax_available():
74
+ raise OptionalDependencyNotAvailable()
75
+ except OptionalDependencyNotAvailable:
76
+ pass
77
+ else:
78
+ _import_structure["modeling_flax_blenderbot"] = [
79
+ "FlaxBlenderbotForConditionalGeneration",
80
+ "FlaxBlenderbotModel",
81
+ "FlaxBlenderbotPreTrainedModel",
82
+ ]
83
+
84
+
85
+ if TYPE_CHECKING:
86
+ from .configuration_blenderbot import (
87
+ BLENDERBOT_PRETRAINED_CONFIG_ARCHIVE_MAP,
88
+ BlenderbotConfig,
89
+ BlenderbotOnnxConfig,
90
+ )
91
+ from .tokenization_blenderbot import BlenderbotTokenizer
92
+
93
+ try:
94
+ if not is_tokenizers_available():
95
+ raise OptionalDependencyNotAvailable()
96
+ except OptionalDependencyNotAvailable:
97
+ pass
98
+ else:
99
+ from .tokenization_blenderbot_fast import BlenderbotTokenizerFast
100
+
101
+ try:
102
+ if not is_torch_available():
103
+ raise OptionalDependencyNotAvailable()
104
+ except OptionalDependencyNotAvailable:
105
+ pass
106
+ else:
107
+ from .modeling_blenderbot import (
108
+ BLENDERBOT_PRETRAINED_MODEL_ARCHIVE_LIST,
109
+ BlenderbotForCausalLM,
110
+ BlenderbotForConditionalGeneration,
111
+ BlenderbotModel,
112
+ BlenderbotPreTrainedModel,
113
+ )
114
+
115
+ try:
116
+ if not is_tf_available():
117
+ raise OptionalDependencyNotAvailable()
118
+ except OptionalDependencyNotAvailable:
119
+ pass
120
+ else:
121
+ from .modeling_tf_blenderbot import (
122
+ TFBlenderbotForConditionalGeneration,
123
+ TFBlenderbotModel,
124
+ TFBlenderbotPreTrainedModel,
125
+ )
126
+
127
+ try:
128
+ if not is_flax_available():
129
+ raise OptionalDependencyNotAvailable()
130
+ except OptionalDependencyNotAvailable:
131
+ pass
132
+ else:
133
+ from .modeling_flax_blenderbot import (
134
+ FlaxBlenderbotForConditionalGeneration,
135
+ FlaxBlenderbotModel,
136
+ FlaxBlenderbotPreTrainedModel,
137
+ )
138
+
139
+ else:
140
+ import sys
141
+
142
+ sys.modules[__name__] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
env-llmeval/lib/python3.10/site-packages/transformers/models/blenderbot/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (1.93 kB). View file
 
env-llmeval/lib/python3.10/site-packages/transformers/models/blenderbot/__pycache__/configuration_blenderbot.cpython-310.pyc ADDED
Binary file (12.8 kB). View file
 
env-llmeval/lib/python3.10/site-packages/transformers/models/blenderbot/__pycache__/convert_blenderbot_original_pytorch_checkpoint_to_pytorch.cpython-310.pyc ADDED
Binary file (2.93 kB). View file
 
env-llmeval/lib/python3.10/site-packages/transformers/models/blenderbot/__pycache__/modeling_blenderbot.cpython-310.pyc ADDED
Binary file (53.4 kB). View file
 
env-llmeval/lib/python3.10/site-packages/transformers/models/blenderbot/__pycache__/modeling_flax_blenderbot.cpython-310.pyc ADDED
Binary file (41.9 kB). View file
 
env-llmeval/lib/python3.10/site-packages/transformers/models/blenderbot/__pycache__/modeling_tf_blenderbot.cpython-310.pyc ADDED
Binary file (49.3 kB). View file
 
env-llmeval/lib/python3.10/site-packages/transformers/models/blenderbot/__pycache__/tokenization_blenderbot.cpython-310.pyc ADDED
Binary file (16.5 kB). View file
 
env-llmeval/lib/python3.10/site-packages/transformers/models/blenderbot/__pycache__/tokenization_blenderbot_fast.cpython-310.pyc ADDED
Binary file (11.4 kB). View file
 
env-llmeval/lib/python3.10/site-packages/transformers/models/blenderbot/configuration_blenderbot.py ADDED
@@ -0,0 +1,397 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2021 The Facebook, Inc. and The HuggingFace Inc. team. All rights reserved.
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
+ """ Blenderbot model configuration"""
16
+
17
+ from collections import OrderedDict
18
+ from typing import Any, Mapping, Optional
19
+
20
+ from ... import PreTrainedTokenizer
21
+ from ...configuration_utils import PretrainedConfig
22
+ from ...file_utils import TensorType, is_torch_available
23
+ from ...onnx import OnnxConfig, OnnxConfigWithPast, OnnxSeq2SeqConfigWithPast
24
+ from ...onnx.utils import compute_effective_axis_dimension
25
+ from ...utils import logging
26
+
27
+
28
+ logger = logging.get_logger(__name__)
29
+
30
+ BLENDERBOT_PRETRAINED_CONFIG_ARCHIVE_MAP = {
31
+ "facebook/blenderbot-3B": "https://huggingface.co/facebook/blenderbot-3B/resolve/main/config.json",
32
+ # See all Blenderbot models at https://huggingface.co/models?filter=blenderbot
33
+ }
34
+
35
+
36
+ class BlenderbotConfig(PretrainedConfig):
37
+ r"""
38
+ This is the configuration class to store the configuration of a [`BlenderbotModel`]. It is used to instantiate an
39
+ Blenderbot model according to the specified arguments, defining the model architecture. Instantiating a
40
+ configuration with the defaults will yield a similar configuration to that of the Blenderbot
41
+ [facebook/blenderbot-3B](https://huggingface.co/facebook/blenderbot-3B) architecture.
42
+
43
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
44
+ documentation from [`PretrainedConfig`] for more information.
45
+
46
+
47
+ Args:
48
+ vocab_size (`int`, *optional*, defaults to 50265):
49
+ Vocabulary size of the Blenderbot model. Defines the number of different tokens that can be represented by
50
+ the `inputs_ids` passed when calling [`BlenderbotModel`] or [`TFBlenderbotModel`].
51
+ d_model (`int`, *optional*, defaults to 1024):
52
+ Dimensionality of the layers and the pooler layer.
53
+ encoder_layers (`int`, *optional*, defaults to 12):
54
+ Number of encoder layers.
55
+ decoder_layers (`int`, *optional*, defaults to 12):
56
+ Number of decoder layers.
57
+ encoder_attention_heads (`int`, *optional*, defaults to 16):
58
+ Number of attention heads for each attention layer in the Transformer encoder.
59
+ decoder_attention_heads (`int`, *optional*, defaults to 16):
60
+ Number of attention heads for each attention layer in the Transformer decoder.
61
+ decoder_ffn_dim (`int`, *optional*, defaults to 4096):
62
+ Dimensionality of the "intermediate" (often named feed-forward) layer in decoder.
63
+ encoder_ffn_dim (`int`, *optional*, defaults to 4096):
64
+ Dimensionality of the "intermediate" (often named feed-forward) layer in decoder.
65
+ activation_function (`str` or `function`, *optional*, defaults to `"gelu"`):
66
+ The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
67
+ `"relu"`, `"silu"` and `"gelu_new"` are supported.
68
+ dropout (`float`, *optional*, defaults to 0.1):
69
+ The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
70
+ attention_dropout (`float`, *optional*, defaults to 0.0):
71
+ The dropout ratio for the attention probabilities.
72
+ activation_dropout (`float`, *optional*, defaults to 0.0):
73
+ The dropout ratio for activations inside the fully connected layer.
74
+ max_position_embeddings (`int`, *optional*, defaults to 128):
75
+ The maximum sequence length that this model might ever be used with. Typically set this to something large
76
+ just in case (e.g., 512 or 1024 or 2048).
77
+ init_std (`float`, *optional*, defaults to 0.02):
78
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
79
+ encoder_layerdrop (`float`, *optional*, defaults to 0.0):
80
+ The LayerDrop probability for the encoder. See the [LayerDrop paper](see https://arxiv.org/abs/1909.11556)
81
+ for more details.
82
+ decoder_layerdrop (`float`, *optional*, defaults to 0.0):
83
+ The LayerDrop probability for the decoder. See the [LayerDrop paper](see https://arxiv.org/abs/1909.11556)
84
+ for more details.
85
+ scale_embedding (`bool`, *optional*, defaults to `False`):
86
+ Scale embeddings by diving by sqrt(d_model).
87
+ use_cache (`bool`, *optional*, defaults to `True`):
88
+ Whether or not the model should return the last key/values attentions (not used by all models)
89
+ forced_eos_token_id (`int`, *optional*, defaults to 2):
90
+ The id of the token to force as the last generated token when `max_length` is reached. Usually set to
91
+ `eos_token_id`.
92
+
93
+ Example:
94
+
95
+ ```python
96
+ >>> from transformers import BlenderbotConfig, BlenderbotModel
97
+
98
+ >>> # Initializing a Blenderbot facebook/blenderbot-3B style configuration
99
+ >>> configuration = BlenderbotConfig()
100
+
101
+ >>> # Initializing a model (with random weights) from the facebook/blenderbot-3B style configuration
102
+ >>> model = BlenderbotModel(configuration)
103
+
104
+ >>> # Accessing the model configuration
105
+ >>> configuration = model.config
106
+ ```"""
107
+
108
+ model_type = "blenderbot"
109
+ keys_to_ignore_at_inference = ["past_key_values"]
110
+ attribute_map = {"num_attention_heads": "encoder_attention_heads", "hidden_size": "d_model"}
111
+
112
+ def __init__(
113
+ self,
114
+ vocab_size=8008,
115
+ max_position_embeddings=128,
116
+ encoder_layers=2,
117
+ encoder_ffn_dim=10240,
118
+ encoder_attention_heads=32,
119
+ decoder_layers=24,
120
+ decoder_ffn_dim=10240,
121
+ decoder_attention_heads=32,
122
+ encoder_layerdrop=0.0,
123
+ decoder_layerdrop=0.0,
124
+ use_cache=True,
125
+ is_encoder_decoder=True,
126
+ activation_function="gelu",
127
+ d_model=2560,
128
+ dropout=0.1,
129
+ attention_dropout=0.0,
130
+ activation_dropout=0.0,
131
+ init_std=0.02,
132
+ decoder_start_token_id=1,
133
+ scale_embedding=False,
134
+ pad_token_id=0,
135
+ bos_token_id=1,
136
+ eos_token_id=2,
137
+ encoder_no_repeat_ngram_size=3,
138
+ forced_eos_token_id=2,
139
+ **kwargs,
140
+ ):
141
+ self.vocab_size = vocab_size
142
+ self.max_position_embeddings = max_position_embeddings
143
+ self.d_model = d_model
144
+ self.encoder_ffn_dim = encoder_ffn_dim
145
+ self.encoder_layers = encoder_layers
146
+ self.encoder_attention_heads = encoder_attention_heads
147
+ self.decoder_ffn_dim = decoder_ffn_dim
148
+ self.decoder_layers = decoder_layers
149
+ self.decoder_attention_heads = decoder_attention_heads
150
+ self.dropout = dropout
151
+ self.attention_dropout = attention_dropout
152
+ self.activation_dropout = activation_dropout
153
+ self.activation_function = activation_function
154
+ self.init_std = init_std
155
+ self.encoder_layerdrop = encoder_layerdrop
156
+ self.decoder_layerdrop = decoder_layerdrop
157
+ self.use_cache = use_cache
158
+ self.num_hidden_layers = encoder_layers
159
+ self.scale_embedding = scale_embedding # scale factor will be sqrt(d_model) if True
160
+
161
+ super().__init__(
162
+ pad_token_id=pad_token_id,
163
+ bos_token_id=bos_token_id,
164
+ eos_token_id=eos_token_id,
165
+ is_encoder_decoder=is_encoder_decoder,
166
+ decoder_start_token_id=decoder_start_token_id,
167
+ encoder_no_repeat_ngram_size=encoder_no_repeat_ngram_size,
168
+ forced_eos_token_id=forced_eos_token_id,
169
+ **kwargs,
170
+ )
171
+
172
+
173
+ class BlenderbotOnnxConfig(OnnxSeq2SeqConfigWithPast):
174
+ @property
175
+ def inputs(self) -> Mapping[str, Mapping[int, str]]:
176
+ if self.task in ["default", "seq2seq-lm"]:
177
+ common_inputs = OrderedDict(
178
+ [
179
+ ("input_ids", {0: "batch", 1: "encoder_sequence"}),
180
+ ("attention_mask", {0: "batch", 1: "encoder_sequence"}),
181
+ ]
182
+ )
183
+ if self.use_past:
184
+ common_inputs["decoder_input_ids"] = {0: "batch"}
185
+ common_inputs["decoder_attention_mask"] = {0: "batch", 1: "past_decoder_sequence + sequence"}
186
+ else:
187
+ common_inputs["decoder_input_ids"] = {0: "batch", 1: "decoder_sequence"}
188
+ common_inputs["decoder_attention_mask"] = {0: "batch", 1: "decoder_sequence"}
189
+ if self.use_past:
190
+ self.fill_with_past_key_values_(common_inputs, direction="inputs")
191
+ elif self.task == "causal-lm":
192
+ common_inputs = OrderedDict(
193
+ [
194
+ ("input_ids", {0: "batch", 1: "encoder_sequence"}),
195
+ ("attention_mask", {0: "batch", 1: "encoder_sequence"}),
196
+ ]
197
+ )
198
+ if self.use_past:
199
+ _, num_decoder_layers = self.num_layers
200
+ for i in range(num_decoder_layers):
201
+ common_inputs[f"past_key_values.{i}.key"] = {0: "batch", 2: "past_sequence + sequence"}
202
+ common_inputs[f"past_key_values.{i}.value"] = {0: "batch", 2: "past_sequence + sequence"}
203
+ else:
204
+ common_inputs = OrderedDict(
205
+ [
206
+ ("input_ids", {0: "batch", 1: "encoder_sequence"}),
207
+ ("attention_mask", {0: "batch", 1: "encoder_sequence"}),
208
+ ("decoder_input_ids", {0: "batch", 1: "decoder_sequence"}),
209
+ ("decoder_attention_mask", {0: "batch", 1: "decoder_sequence"}),
210
+ ]
211
+ )
212
+
213
+ return common_inputs
214
+
215
+ @property
216
+ # Copied from transformers.models.bart.configuration_bart.BartOnnxConfig.outputs
217
+ def outputs(self) -> Mapping[str, Mapping[int, str]]:
218
+ if self.task in ["default", "seq2seq-lm"]:
219
+ common_outputs = super().outputs
220
+ else:
221
+ common_outputs = super(OnnxConfigWithPast, self).outputs
222
+ if self.use_past:
223
+ num_encoder_layers, _ = self.num_layers
224
+ for i in range(num_encoder_layers):
225
+ common_outputs[f"present.{i}.key"] = {0: "batch", 2: "past_sequence + sequence"}
226
+ common_outputs[f"present.{i}.value"] = {0: "batch", 2: "past_sequence + sequence"}
227
+ return common_outputs
228
+
229
+ def _generate_dummy_inputs_for_default_and_seq2seq_lm(
230
+ self,
231
+ tokenizer: PreTrainedTokenizer,
232
+ batch_size: int = -1,
233
+ seq_length: int = -1,
234
+ is_pair: bool = False,
235
+ framework: Optional[TensorType] = None,
236
+ ) -> Mapping[str, Any]:
237
+ encoder_inputs = self._generate_dummy_inputs_for_sequence_classification_and_question_answering(
238
+ tokenizer, batch_size, seq_length, is_pair, framework
239
+ )
240
+ # Generate decoder inputs
241
+ decoder_seq_length = seq_length if not self.use_past else 1
242
+ decoder_inputs = self._generate_dummy_inputs_for_sequence_classification_and_question_answering(
243
+ tokenizer, batch_size, decoder_seq_length, is_pair, framework
244
+ )
245
+ decoder_inputs = {f"decoder_{name}": tensor for name, tensor in decoder_inputs.items()}
246
+ common_inputs = dict(**encoder_inputs, **decoder_inputs)
247
+
248
+ if self.use_past:
249
+ if not is_torch_available():
250
+ raise ValueError("Cannot generate dummy past_keys inputs without PyTorch installed.")
251
+ else:
252
+ import torch
253
+ batch, encoder_seq_length = common_inputs["input_ids"].shape
254
+ decoder_seq_length = common_inputs["decoder_input_ids"].shape[1]
255
+ num_encoder_attention_heads, num_decoder_attention_heads = self.num_attention_heads
256
+ encoder_shape = (
257
+ batch,
258
+ num_encoder_attention_heads,
259
+ encoder_seq_length,
260
+ self._config.hidden_size // num_encoder_attention_heads,
261
+ )
262
+ decoder_past_length = decoder_seq_length
263
+ decoder_shape = (
264
+ batch,
265
+ num_decoder_attention_heads,
266
+ decoder_past_length,
267
+ self._config.hidden_size // num_decoder_attention_heads,
268
+ )
269
+ common_inputs["decoder_attention_mask"] = torch.cat(
270
+ [common_inputs["decoder_attention_mask"], torch.ones(batch, decoder_past_length)], dim=1
271
+ )
272
+ common_inputs["past_key_values"] = []
273
+ _, num_decoder_layers = self.num_layers
274
+
275
+ for _ in range(num_decoder_layers):
276
+ common_inputs["past_key_values"].append(
277
+ (
278
+ torch.zeros(decoder_shape),
279
+ torch.zeros(decoder_shape),
280
+ torch.zeros(encoder_shape),
281
+ torch.zeros(encoder_shape),
282
+ )
283
+ )
284
+ return common_inputs
285
+
286
+ def _generate_dummy_inputs_for_causal_lm(
287
+ self,
288
+ tokenizer: PreTrainedTokenizer,
289
+ batch_size: int = -1,
290
+ seq_length: int = -1,
291
+ is_pair: bool = False,
292
+ framework: Optional[TensorType] = None,
293
+ ) -> Mapping[str, Any]:
294
+ common_inputs = self._generate_dummy_inputs_for_sequence_classification_and_question_answering(
295
+ tokenizer, batch_size, seq_length, is_pair, framework
296
+ )
297
+
298
+ if self.use_past:
299
+ if not is_torch_available():
300
+ raise ValueError("Cannot generate dummy past_keys inputs without PyTorch installed.")
301
+ else:
302
+ import torch
303
+ batch, seqlen = common_inputs["input_ids"].shape
304
+ past_key_values_length = seqlen
305
+ _, num_decoder_layers = self.num_layers
306
+ num_encoder_attention_heads, _ = self.num_attention_heads
307
+ past_shape = (
308
+ batch,
309
+ num_encoder_attention_heads,
310
+ past_key_values_length,
311
+ self._config.hidden_size // num_encoder_attention_heads,
312
+ )
313
+ mask_dtype = common_inputs["attention_mask"].dtype
314
+ common_inputs["attention_mask"] = torch.cat(
315
+ [common_inputs["attention_mask"], torch.ones(batch, past_key_values_length, dtype=mask_dtype)], dim=1
316
+ )
317
+ common_inputs["past_key_values"] = [
318
+ (torch.zeros(past_shape), torch.zeros(past_shape)) for _ in range(num_decoder_layers)
319
+ ]
320
+ return common_inputs
321
+
322
+ # Copied from transformers.models.bart.configuration_bart.BartOnnxConfig._generate_dummy_inputs_for_sequence_classification_and_question_answering
323
+ def _generate_dummy_inputs_for_sequence_classification_and_question_answering(
324
+ self,
325
+ tokenizer: PreTrainedTokenizer,
326
+ batch_size: int = -1,
327
+ seq_length: int = -1,
328
+ is_pair: bool = False,
329
+ framework: Optional[TensorType] = None,
330
+ ) -> Mapping[str, Any]:
331
+ # Copied from OnnxConfig.generate_dummy_inputs
332
+ # Did not use super(OnnxConfigWithPast, self).generate_dummy_inputs for code clarity.
333
+ # If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX
334
+ batch_size = compute_effective_axis_dimension(
335
+ batch_size, fixed_dimension=OnnxConfig.default_fixed_batch, num_token_to_add=0
336
+ )
337
+
338
+ # If dynamic axis (-1) we forward with a fixed dimension of 8 tokens to avoid optimizations made by ONNX
339
+ token_to_add = tokenizer.num_special_tokens_to_add(is_pair)
340
+ seq_length = compute_effective_axis_dimension(
341
+ seq_length, fixed_dimension=OnnxConfig.default_fixed_sequence, num_token_to_add=token_to_add
342
+ )
343
+
344
+ # Generate dummy inputs according to compute batch and sequence
345
+ dummy_input = [" ".join([tokenizer.unk_token]) * seq_length] * batch_size
346
+ common_inputs = dict(tokenizer(dummy_input, return_tensors=framework))
347
+ return common_inputs
348
+
349
+ # Copied from transformers.models.bart.configuration_bart.BartOnnxConfig.generate_dummy_inputs
350
+ def generate_dummy_inputs(
351
+ self,
352
+ tokenizer: PreTrainedTokenizer,
353
+ batch_size: int = -1,
354
+ seq_length: int = -1,
355
+ is_pair: bool = False,
356
+ framework: Optional[TensorType] = None,
357
+ ) -> Mapping[str, Any]:
358
+ if self.task in ["default", "seq2seq-lm"]:
359
+ common_inputs = self._generate_dummy_inputs_for_default_and_seq2seq_lm(
360
+ tokenizer, batch_size=batch_size, seq_length=seq_length, is_pair=is_pair, framework=framework
361
+ )
362
+
363
+ elif self.task == "causal-lm":
364
+ common_inputs = self._generate_dummy_inputs_for_causal_lm(
365
+ tokenizer, batch_size=batch_size, seq_length=seq_length, is_pair=is_pair, framework=framework
366
+ )
367
+ else:
368
+ common_inputs = self._generate_dummy_inputs_for_sequence_classification_and_question_answering(
369
+ tokenizer, batch_size=batch_size, seq_length=seq_length, is_pair=is_pair, framework=framework
370
+ )
371
+
372
+ return common_inputs
373
+
374
+ # Copied from transformers.models.bart.configuration_bart.BartOnnxConfig._flatten_past_key_values_
375
+ def _flatten_past_key_values_(self, flattened_output, name, idx, t):
376
+ if self.task in ["default", "seq2seq-lm"]:
377
+ flattened_output = super()._flatten_past_key_values_(flattened_output, name, idx, t)
378
+ else:
379
+ flattened_output = super(OnnxSeq2SeqConfigWithPast, self)._flatten_past_key_values_(
380
+ flattened_output, name, idx, t
381
+ )
382
+
383
+ def fill_with_past_key_values_(self, inputs_or_outputs: Mapping[str, Mapping[int, str]], direction: str):
384
+ if direction not in ["inputs", "outputs"]:
385
+ raise ValueError(f'direction must either be "inputs" or "outputs", but {direction} was given')
386
+
387
+ name = "past_key_values" if direction == "inputs" else "present"
388
+ _, num_decoder_layers = self.num_layers
389
+
390
+ encoder_sequence = "past_encoder_sequence"
391
+ decoder_sequence = "past_decoder_sequence" if direction == "inputs" else "past_decoder_sequence + sequence"
392
+
393
+ for i in range(num_decoder_layers):
394
+ inputs_or_outputs[f"{name}.{i}.decoder.key"] = {0: "batch", 2: decoder_sequence}
395
+ inputs_or_outputs[f"{name}.{i}.decoder.value"] = {0: "batch", 2: decoder_sequence}
396
+ inputs_or_outputs[f"{name}.{i}.encoder.key"] = {0: "batch", 2: encoder_sequence}
397
+ inputs_or_outputs[f"{name}.{i}.encoder.value"] = {0: "batch", 2: encoder_sequence}
env-llmeval/lib/python3.10/site-packages/transformers/models/blenderbot/convert_blenderbot_original_pytorch_checkpoint_to_pytorch.py ADDED
@@ -0,0 +1,114 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2020 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
+ """Convert Blenderbot checkpoint."""
16
+
17
+ import argparse
18
+
19
+ import torch
20
+
21
+ from transformers import BlenderbotConfig, BlenderbotForConditionalGeneration
22
+ from transformers.utils import logging
23
+
24
+
25
+ logging.set_verbosity_info()
26
+ logger = logging.get_logger(__name__)
27
+
28
+ PATTERNS = [
29
+ ["attention", "attn"],
30
+ ["encoder_attention", "encoder_attn"],
31
+ ["q_lin", "q_proj"],
32
+ ["k_lin", "k_proj"],
33
+ ["v_lin", "v_proj"],
34
+ ["out_lin", "out_proj"],
35
+ ["norm_embeddings", "layernorm_embedding"],
36
+ ["position_embeddings", "embed_positions"],
37
+ ["embeddings", "embed_tokens"],
38
+ ["ffn.lin", "fc"],
39
+ ]
40
+
41
+
42
+ def rename_state_dict_key(k):
43
+ if k == "embeddings.weight":
44
+ return "shared.weight"
45
+
46
+ for parlai_name, hf_name in PATTERNS:
47
+ k = k.replace(parlai_name, hf_name)
48
+
49
+ if k.startswith("encoder"):
50
+ k = k.replace(".attn", ".self_attn")
51
+ k = k.replace("norm1", "self_attn_layer_norm")
52
+ k = k.replace("norm2", "final_layer_norm")
53
+ elif k.startswith("decoder"):
54
+ k = k.replace("norm1", "self_attn_layer_norm")
55
+ k = k.replace("norm2", "encoder_attn_layer_norm")
56
+ k = k.replace("norm3", "final_layer_norm")
57
+ return k
58
+
59
+
60
+ def rename_layernorm_keys(sd):
61
+ keys = [
62
+ "model.encoder.layernorm_embedding.weight",
63
+ "model.encoder.layernorm_embedding.bias",
64
+ "model.decoder.layernorm_embedding.weight",
65
+ "model.decoder.layernorm_embedding.bias",
66
+ ]
67
+ for k in keys:
68
+ v = sd.pop(k)
69
+ new_k = k.replace("layernorm_embedding", "layer_norm")
70
+ assert new_k not in sd
71
+ sd[new_k] = v
72
+
73
+
74
+ IGNORE_KEYS = ["START"]
75
+
76
+
77
+ @torch.no_grad()
78
+ def convert_parlai_checkpoint(checkpoint_path, pytorch_dump_folder_path, config_json_path):
79
+ """
80
+ Copy/paste/tweak model's weights to our BERT structure.
81
+ """
82
+ model = torch.load(checkpoint_path, map_location="cpu")
83
+ sd = model["model"]
84
+ cfg = BlenderbotConfig.from_json_file(config_json_path)
85
+ m = BlenderbotForConditionalGeneration(cfg)
86
+ valid_keys = m.model.state_dict().keys()
87
+ failures = []
88
+ mapping = {}
89
+ for k, v in sd.items():
90
+ if k in IGNORE_KEYS:
91
+ continue
92
+
93
+ new_k = rename_state_dict_key(k)
94
+ if new_k not in valid_keys:
95
+ failures.append([k, new_k])
96
+ else:
97
+ mapping[new_k] = v
98
+ if cfg.normalize_before: # Blenderbot-3B checkpoints. Rename layernorm_embedding -> layer_norm
99
+ rename_layernorm_keys(sd)
100
+ m.model.load_state_dict(mapping, strict=True)
101
+ m.half()
102
+ m.save_pretrained(pytorch_dump_folder_path)
103
+
104
+
105
+ if __name__ == "__main__":
106
+ parser = argparse.ArgumentParser()
107
+ # Required parameters
108
+ parser.add_argument("--src_path", type=str, help="like blenderbot-model.bin")
109
+ parser.add_argument("--save_dir", default="hf_blenderbot", type=str, help="Where to save converted model.")
110
+ parser.add_argument(
111
+ "--hf_config_json", default="blenderbot-3b-config.json", type=str, help="Path to config to use"
112
+ )
113
+ args = parser.parse_args()
114
+ convert_parlai_checkpoint(args.src_path, args.save_dir, args.hf_config_json)
env-llmeval/lib/python3.10/site-packages/transformers/models/blenderbot/modeling_blenderbot.py ADDED
@@ -0,0 +1,1600 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2021 The Facebook, Inc. and The HuggingFace Inc. team. All rights reserved.
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
+ """ PyTorch Blenderbot model."""
16
+
17
+
18
+ import copy
19
+ import math
20
+ import os
21
+ import warnings
22
+ from typing import List, Optional, Tuple, Union
23
+
24
+ import torch
25
+ import torch.utils.checkpoint
26
+ from torch import nn
27
+ from torch.nn import CrossEntropyLoss
28
+
29
+ from ...activations import ACT2FN
30
+ from ...modeling_attn_mask_utils import _prepare_4d_attention_mask, _prepare_4d_causal_attention_mask
31
+ from ...modeling_outputs import (
32
+ BaseModelOutput,
33
+ BaseModelOutputWithPastAndCrossAttentions,
34
+ CausalLMOutputWithCrossAttentions,
35
+ Seq2SeqLMOutput,
36
+ Seq2SeqModelOutput,
37
+ )
38
+ from ...modeling_utils import PreTrainedModel
39
+ from ...utils import (
40
+ add_end_docstrings,
41
+ add_start_docstrings,
42
+ add_start_docstrings_to_model_forward,
43
+ logging,
44
+ replace_return_docstrings,
45
+ )
46
+ from ..blenderbot_small import BlenderbotSmallForConditionalGeneration, BlenderbotSmallModel
47
+ from .configuration_blenderbot import BlenderbotConfig
48
+
49
+
50
+ logger = logging.get_logger(__name__)
51
+
52
+ _CONFIG_FOR_DOC = "BlenderbotConfig"
53
+ _CHECKPOINT_FOR_DOC = "facebook/blenderbot-400M-distill"
54
+
55
+
56
+ BLENDERBOT_PRETRAINED_MODEL_ARCHIVE_LIST = [
57
+ "facebook/blenderbot-3B",
58
+ # See all Blenderbot models at https://huggingface.co/models?filter=blenderbot
59
+ ]
60
+
61
+
62
+ # Copied from transformers.models.bart.modeling_bart.shift_tokens_right
63
+ def shift_tokens_right(input_ids: torch.Tensor, pad_token_id: int, decoder_start_token_id: int):
64
+ """
65
+ Shift input ids one token to the right.
66
+ """
67
+ shifted_input_ids = input_ids.new_zeros(input_ids.shape)
68
+ shifted_input_ids[:, 1:] = input_ids[:, :-1].clone()
69
+ shifted_input_ids[:, 0] = decoder_start_token_id
70
+
71
+ if pad_token_id is None:
72
+ raise ValueError("self.model.config.pad_token_id has to be defined.")
73
+ # replace possible -100 values in labels by `pad_token_id`
74
+ shifted_input_ids.masked_fill_(shifted_input_ids == -100, pad_token_id)
75
+
76
+ return shifted_input_ids
77
+
78
+
79
+ class BlenderbotLearnedPositionalEmbedding(nn.Embedding):
80
+ """
81
+ This module learns positional embeddings up to a fixed maximum size.
82
+ """
83
+
84
+ def __init__(self, num_embeddings: int, embedding_dim: int):
85
+ super().__init__(num_embeddings, embedding_dim)
86
+
87
+ def forward(self, input_ids_shape: torch.Size, past_key_values_length: int = 0):
88
+ """`input_ids_shape` is expected to be [bsz x seqlen]."""
89
+ bsz, seq_len = input_ids_shape[:2]
90
+ positions = torch.arange(
91
+ past_key_values_length, past_key_values_length + seq_len, dtype=torch.long, device=self.weight.device
92
+ )
93
+ return super().forward(positions)
94
+
95
+
96
+ # Copied from transformers.models.bart.modeling_bart.BartAttention with Bart->Blenderbot
97
+ class BlenderbotAttention(nn.Module):
98
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
99
+
100
+ def __init__(
101
+ self,
102
+ embed_dim: int,
103
+ num_heads: int,
104
+ dropout: float = 0.0,
105
+ is_decoder: bool = False,
106
+ bias: bool = True,
107
+ is_causal: bool = False,
108
+ config: Optional[BlenderbotConfig] = None,
109
+ ):
110
+ super().__init__()
111
+ self.embed_dim = embed_dim
112
+ self.num_heads = num_heads
113
+ self.dropout = dropout
114
+ self.head_dim = embed_dim // num_heads
115
+ self.config = config
116
+
117
+ if (self.head_dim * num_heads) != self.embed_dim:
118
+ raise ValueError(
119
+ f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim}"
120
+ f" and `num_heads`: {num_heads})."
121
+ )
122
+ self.scaling = self.head_dim**-0.5
123
+ self.is_decoder = is_decoder
124
+ self.is_causal = is_causal
125
+
126
+ self.k_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
127
+ self.v_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
128
+ self.q_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
129
+ self.out_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
130
+
131
+ def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
132
+ return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
133
+
134
+ def forward(
135
+ self,
136
+ hidden_states: torch.Tensor,
137
+ key_value_states: Optional[torch.Tensor] = None,
138
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
139
+ attention_mask: Optional[torch.Tensor] = None,
140
+ layer_head_mask: Optional[torch.Tensor] = None,
141
+ output_attentions: bool = False,
142
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
143
+ """Input shape: Batch x Time x Channel"""
144
+
145
+ # if key_value_states are provided this layer is used as a cross-attention layer
146
+ # for the decoder
147
+ is_cross_attention = key_value_states is not None
148
+
149
+ bsz, tgt_len, _ = hidden_states.size()
150
+
151
+ # get query proj
152
+ query_states = self.q_proj(hidden_states) * self.scaling
153
+ # get key, value proj
154
+ # `past_key_value[0].shape[2] == key_value_states.shape[1]`
155
+ # is checking that the `sequence_length` of the `past_key_value` is the same as
156
+ # the provided `key_value_states` to support prefix tuning
157
+ if (
158
+ is_cross_attention
159
+ and past_key_value is not None
160
+ and past_key_value[0].shape[2] == key_value_states.shape[1]
161
+ ):
162
+ # reuse k,v, cross_attentions
163
+ key_states = past_key_value[0]
164
+ value_states = past_key_value[1]
165
+ elif is_cross_attention:
166
+ # cross_attentions
167
+ key_states = self._shape(self.k_proj(key_value_states), -1, bsz)
168
+ value_states = self._shape(self.v_proj(key_value_states), -1, bsz)
169
+ elif past_key_value is not None:
170
+ # reuse k, v, self_attention
171
+ key_states = self._shape(self.k_proj(hidden_states), -1, bsz)
172
+ value_states = self._shape(self.v_proj(hidden_states), -1, bsz)
173
+ key_states = torch.cat([past_key_value[0], key_states], dim=2)
174
+ value_states = torch.cat([past_key_value[1], value_states], dim=2)
175
+ else:
176
+ # self_attention
177
+ key_states = self._shape(self.k_proj(hidden_states), -1, bsz)
178
+ value_states = self._shape(self.v_proj(hidden_states), -1, bsz)
179
+
180
+ if self.is_decoder:
181
+ # if cross_attention save Tuple(torch.Tensor, torch.Tensor) of all cross attention key/value_states.
182
+ # Further calls to cross_attention layer can then reuse all cross-attention
183
+ # key/value_states (first "if" case)
184
+ # if uni-directional self-attention (decoder) save Tuple(torch.Tensor, torch.Tensor) of
185
+ # all previous decoder key/value_states. Further calls to uni-directional self-attention
186
+ # can concat previous decoder key/value_states to current projected key/value_states (third "elif" case)
187
+ # if encoder bi-directional self-attention `past_key_value` is always `None`
188
+ past_key_value = (key_states, value_states)
189
+
190
+ proj_shape = (bsz * self.num_heads, -1, self.head_dim)
191
+ query_states = self._shape(query_states, tgt_len, bsz).view(*proj_shape)
192
+ key_states = key_states.reshape(*proj_shape)
193
+ value_states = value_states.reshape(*proj_shape)
194
+
195
+ src_len = key_states.size(1)
196
+ attn_weights = torch.bmm(query_states, key_states.transpose(1, 2))
197
+
198
+ if attn_weights.size() != (bsz * self.num_heads, tgt_len, src_len):
199
+ raise ValueError(
200
+ f"Attention weights should be of size {(bsz * self.num_heads, tgt_len, src_len)}, but is"
201
+ f" {attn_weights.size()}"
202
+ )
203
+
204
+ if attention_mask is not None:
205
+ if attention_mask.size() != (bsz, 1, tgt_len, src_len):
206
+ raise ValueError(
207
+ f"Attention mask should be of size {(bsz, 1, tgt_len, src_len)}, but is {attention_mask.size()}"
208
+ )
209
+ attn_weights = attn_weights.view(bsz, self.num_heads, tgt_len, src_len) + attention_mask
210
+ attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len)
211
+
212
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1)
213
+
214
+ if layer_head_mask is not None:
215
+ if layer_head_mask.size() != (self.num_heads,):
216
+ raise ValueError(
217
+ f"Head mask for a single layer should be of size {(self.num_heads,)}, but is"
218
+ f" {layer_head_mask.size()}"
219
+ )
220
+ attn_weights = layer_head_mask.view(1, -1, 1, 1) * attn_weights.view(bsz, self.num_heads, tgt_len, src_len)
221
+ attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len)
222
+
223
+ if output_attentions:
224
+ # this operation is a bit awkward, but it's required to
225
+ # make sure that attn_weights keeps its gradient.
226
+ # In order to do so, attn_weights have to be reshaped
227
+ # twice and have to be reused in the following
228
+ attn_weights_reshaped = attn_weights.view(bsz, self.num_heads, tgt_len, src_len)
229
+ attn_weights = attn_weights_reshaped.view(bsz * self.num_heads, tgt_len, src_len)
230
+ else:
231
+ attn_weights_reshaped = None
232
+
233
+ attn_probs = nn.functional.dropout(attn_weights, p=self.dropout, training=self.training)
234
+
235
+ attn_output = torch.bmm(attn_probs, value_states)
236
+
237
+ if attn_output.size() != (bsz * self.num_heads, tgt_len, self.head_dim):
238
+ raise ValueError(
239
+ f"`attn_output` should be of size {(bsz * self.num_heads, tgt_len, self.head_dim)}, but is"
240
+ f" {attn_output.size()}"
241
+ )
242
+
243
+ attn_output = attn_output.view(bsz, self.num_heads, tgt_len, self.head_dim)
244
+ attn_output = attn_output.transpose(1, 2)
245
+
246
+ # Use the `embed_dim` from the config (stored in the class) rather than `hidden_state` because `attn_output` can be
247
+ # partitioned across GPUs when using tensor-parallelism.
248
+ attn_output = attn_output.reshape(bsz, tgt_len, self.embed_dim)
249
+
250
+ attn_output = self.out_proj(attn_output)
251
+
252
+ return attn_output, attn_weights_reshaped, past_key_value
253
+
254
+
255
+ BLENDERBOT_ATTENTION_CLASSES = {"eager": BlenderbotAttention}
256
+
257
+
258
+ # Copied from transformers.models.mbart.modeling_mbart.MBartEncoderLayer with MBart->Blenderbot, MBART->BLENDERBOT
259
+ class BlenderbotEncoderLayer(nn.Module):
260
+ def __init__(self, config: BlenderbotConfig):
261
+ super().__init__()
262
+ self.embed_dim = config.d_model
263
+
264
+ self.self_attn = BLENDERBOT_ATTENTION_CLASSES[config._attn_implementation](
265
+ embed_dim=self.embed_dim,
266
+ num_heads=config.encoder_attention_heads,
267
+ dropout=config.attention_dropout,
268
+ config=config,
269
+ )
270
+ self.self_attn_layer_norm = nn.LayerNorm(self.embed_dim)
271
+ self.dropout = config.dropout
272
+ self.activation_fn = ACT2FN[config.activation_function]
273
+ self.activation_dropout = config.activation_dropout
274
+ self.fc1 = nn.Linear(self.embed_dim, config.encoder_ffn_dim)
275
+ self.fc2 = nn.Linear(config.encoder_ffn_dim, self.embed_dim)
276
+ self.final_layer_norm = nn.LayerNorm(self.embed_dim)
277
+
278
+ def forward(
279
+ self,
280
+ hidden_states: torch.Tensor,
281
+ attention_mask: torch.Tensor,
282
+ layer_head_mask: torch.Tensor,
283
+ output_attentions: bool = False,
284
+ ) -> torch.Tensor:
285
+ """
286
+ Args:
287
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
288
+ attention_mask (`torch.FloatTensor`): attention mask of size
289
+ `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
290
+ layer_head_mask (`torch.FloatTensor`): mask for attention heads in a given layer of size
291
+ `(encoder_attention_heads,)`.
292
+ output_attentions (`bool`, *optional*):
293
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
294
+ returned tensors for more detail.
295
+ """
296
+ residual = hidden_states
297
+ hidden_states = self.self_attn_layer_norm(hidden_states)
298
+ hidden_states, attn_weights, _ = self.self_attn(
299
+ hidden_states=hidden_states,
300
+ attention_mask=attention_mask,
301
+ layer_head_mask=layer_head_mask,
302
+ output_attentions=output_attentions,
303
+ )
304
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
305
+ hidden_states = residual + hidden_states
306
+
307
+ residual = hidden_states
308
+ hidden_states = self.final_layer_norm(hidden_states)
309
+ hidden_states = self.activation_fn(self.fc1(hidden_states))
310
+ hidden_states = nn.functional.dropout(hidden_states, p=self.activation_dropout, training=self.training)
311
+ hidden_states = self.fc2(hidden_states)
312
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
313
+ hidden_states = residual + hidden_states
314
+
315
+ if hidden_states.dtype == torch.float16 and (
316
+ torch.isinf(hidden_states).any() or torch.isnan(hidden_states).any()
317
+ ):
318
+ clamp_value = torch.finfo(hidden_states.dtype).max - 1000
319
+ hidden_states = torch.clamp(hidden_states, min=-clamp_value, max=clamp_value)
320
+
321
+ outputs = (hidden_states,)
322
+
323
+ if output_attentions:
324
+ outputs += (attn_weights,)
325
+
326
+ return outputs
327
+
328
+
329
+ # Copied from transformers.models.mbart.modeling_mbart.MBartDecoderLayer with MBart->Blenderbot, MBART->BLENDERBOT
330
+ class BlenderbotDecoderLayer(nn.Module):
331
+ def __init__(self, config: BlenderbotConfig):
332
+ super().__init__()
333
+ self.embed_dim = config.d_model
334
+
335
+ self.self_attn = BLENDERBOT_ATTENTION_CLASSES[config._attn_implementation](
336
+ embed_dim=self.embed_dim,
337
+ num_heads=config.decoder_attention_heads,
338
+ dropout=config.attention_dropout,
339
+ is_decoder=True,
340
+ is_causal=True,
341
+ config=config,
342
+ )
343
+ self.dropout = config.dropout
344
+ self.activation_fn = ACT2FN[config.activation_function]
345
+ self.activation_dropout = config.activation_dropout
346
+
347
+ self.self_attn_layer_norm = nn.LayerNorm(self.embed_dim)
348
+ self.encoder_attn = BLENDERBOT_ATTENTION_CLASSES[config._attn_implementation](
349
+ self.embed_dim,
350
+ config.decoder_attention_heads,
351
+ dropout=config.attention_dropout,
352
+ is_decoder=True,
353
+ config=config,
354
+ )
355
+ self.encoder_attn_layer_norm = nn.LayerNorm(self.embed_dim)
356
+ self.fc1 = nn.Linear(self.embed_dim, config.decoder_ffn_dim)
357
+ self.fc2 = nn.Linear(config.decoder_ffn_dim, self.embed_dim)
358
+ self.final_layer_norm = nn.LayerNorm(self.embed_dim)
359
+
360
+ def forward(
361
+ self,
362
+ hidden_states: torch.Tensor,
363
+ attention_mask: Optional[torch.Tensor] = None,
364
+ encoder_hidden_states: Optional[torch.Tensor] = None,
365
+ encoder_attention_mask: Optional[torch.Tensor] = None,
366
+ layer_head_mask: Optional[torch.Tensor] = None,
367
+ cross_attn_layer_head_mask: Optional[torch.Tensor] = None,
368
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
369
+ output_attentions: Optional[bool] = False,
370
+ use_cache: Optional[bool] = True,
371
+ ) -> torch.Tensor:
372
+ """
373
+ Args:
374
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
375
+ attention_mask (`torch.FloatTensor`): attention mask of size
376
+ `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
377
+ encoder_hidden_states (`torch.FloatTensor`):
378
+ cross attention input to the layer of shape `(batch, seq_len, embed_dim)`
379
+ encoder_attention_mask (`torch.FloatTensor`): encoder attention mask of size
380
+ `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
381
+ layer_head_mask (`torch.FloatTensor`): mask for attention heads in a given layer of size
382
+ `(encoder_attention_heads,)`.
383
+ cross_attn_layer_head_mask (`torch.FloatTensor`): mask for cross-attention heads in a given layer of
384
+ size `(decoder_attention_heads,)`.
385
+ past_key_value (`Tuple(torch.FloatTensor)`): cached past key and value projection states
386
+ output_attentions (`bool`, *optional*):
387
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
388
+ returned tensors for more detail.
389
+ """
390
+ residual = hidden_states
391
+ hidden_states = self.self_attn_layer_norm(hidden_states)
392
+
393
+ # Self Attention
394
+ # decoder uni-directional self-attention cached key/values tuple is at positions 1,2
395
+ self_attn_past_key_value = past_key_value[:2] if past_key_value is not None else None
396
+ # add present self-attn cache to positions 1,2 of present_key_value tuple
397
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
398
+ hidden_states=hidden_states,
399
+ past_key_value=self_attn_past_key_value,
400
+ attention_mask=attention_mask,
401
+ layer_head_mask=layer_head_mask,
402
+ output_attentions=output_attentions,
403
+ )
404
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
405
+ hidden_states = residual + hidden_states
406
+
407
+ # Cross-Attention Block
408
+ cross_attn_present_key_value = None
409
+ cross_attn_weights = None
410
+ if encoder_hidden_states is not None:
411
+ residual = hidden_states
412
+ hidden_states = self.encoder_attn_layer_norm(hidden_states)
413
+
414
+ # cross_attn cached key/values tuple is at positions 3,4 of present_key_value tuple
415
+ cross_attn_past_key_value = past_key_value[-2:] if past_key_value is not None else None
416
+ hidden_states, cross_attn_weights, cross_attn_present_key_value = self.encoder_attn(
417
+ hidden_states=hidden_states,
418
+ key_value_states=encoder_hidden_states,
419
+ attention_mask=encoder_attention_mask,
420
+ layer_head_mask=cross_attn_layer_head_mask,
421
+ past_key_value=cross_attn_past_key_value,
422
+ output_attentions=output_attentions,
423
+ )
424
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
425
+ hidden_states = residual + hidden_states
426
+
427
+ # add cross-attn to positions 3,4 of present_key_value tuple
428
+ present_key_value = present_key_value + cross_attn_present_key_value
429
+
430
+ # Fully Connected
431
+ residual = hidden_states
432
+ hidden_states = self.final_layer_norm(hidden_states)
433
+ hidden_states = self.activation_fn(self.fc1(hidden_states))
434
+ hidden_states = nn.functional.dropout(hidden_states, p=self.activation_dropout, training=self.training)
435
+ hidden_states = self.fc2(hidden_states)
436
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
437
+ hidden_states = residual + hidden_states
438
+
439
+ outputs = (hidden_states,)
440
+
441
+ if output_attentions:
442
+ outputs += (self_attn_weights, cross_attn_weights)
443
+
444
+ if use_cache:
445
+ outputs += (present_key_value,)
446
+
447
+ return outputs
448
+
449
+
450
+ class BlenderbotPreTrainedModel(PreTrainedModel):
451
+ config_class = BlenderbotConfig
452
+ base_model_prefix = "model"
453
+ supports_gradient_checkpointing = True
454
+
455
+ def _init_weights(self, module):
456
+ std = self.config.init_std
457
+ if isinstance(module, nn.Linear):
458
+ module.weight.data.normal_(mean=0.0, std=std)
459
+ if module.bias is not None:
460
+ module.bias.data.zero_()
461
+ elif isinstance(module, nn.Embedding):
462
+ module.weight.data.normal_(mean=0.0, std=std)
463
+ if module.padding_idx is not None:
464
+ module.weight.data[module.padding_idx].zero_()
465
+
466
+ @property
467
+ def dummy_inputs(self):
468
+ pad_token = self.config.pad_token_id
469
+ input_ids = torch.tensor([[0, 6, 10, 4, 2], [0, 8, 12, 2, pad_token]], device=self.device)
470
+ dummy_inputs = {
471
+ "attention_mask": input_ids.ne(pad_token),
472
+ "input_ids": input_ids,
473
+ "decoder_input_ids": input_ids,
474
+ }
475
+ return dummy_inputs
476
+
477
+
478
+ BLENDERBOT_START_DOCSTRING = r"""
479
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
480
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
481
+ etc.)
482
+
483
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
484
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
485
+ and behavior.
486
+
487
+ Parameters:
488
+ config ([`BlenderbotConfig`]):
489
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
490
+ load the weights associated with the model, only the configuration. Check out the
491
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
492
+ """
493
+
494
+ BLENDERBOT_GENERATION_EXAMPLE = r"""
495
+ Conversation example:
496
+
497
+ ```python
498
+ >>> from transformers import AutoTokenizer, BlenderbotForConditionalGeneration
499
+
500
+ >>> mname = "facebook/blenderbot-400M-distill"
501
+ >>> model = BlenderbotForConditionalGeneration.from_pretrained(mname)
502
+ >>> tokenizer = AutoTokenizer.from_pretrained(mname)
503
+ >>> UTTERANCE = "My friends are cool but they eat too many carbs."
504
+ >>> print("Human: ", UTTERANCE)
505
+ Human: My friends are cool but they eat too many carbs.
506
+
507
+ >>> inputs = tokenizer([UTTERANCE], return_tensors="pt")
508
+ >>> reply_ids = model.generate(**inputs)
509
+ >>> print("Bot: ", tokenizer.batch_decode(reply_ids, skip_special_tokens=True)[0])
510
+ Bot: That's unfortunate. Are they trying to lose weight or are they just trying to be healthier?
511
+
512
+ >>> REPLY = "I'm not sure"
513
+ >>> print("Human: ", REPLY)
514
+ Human: I'm not sure
515
+
516
+ >>> NEXT_UTTERANCE = (
517
+ ... "My friends are cool but they eat too many carbs.</s> <s>That's unfortunate. "
518
+ ... "Are they trying to lose weight or are they just trying to be healthier?</s> "
519
+ ... "<s> I'm not sure."
520
+ ... )
521
+ >>> inputs = tokenizer([NEXT_UTTERANCE], return_tensors="pt")
522
+ >>> next_reply_ids = model.generate(**inputs)
523
+ >>> print("Bot: ", tokenizer.batch_decode(next_reply_ids, skip_special_tokens=True)[0])
524
+ Bot: I see. Well, it's good that they're trying to change their eating habits.
525
+ ```
526
+ """
527
+
528
+ BLENDERBOT_INPUTS_DOCSTRING = r"""
529
+ Args:
530
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
531
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
532
+ it.
533
+
534
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
535
+ [`PreTrainedTokenizer.__call__`] for details.
536
+
537
+ [What are input IDs?](../glossary#input-ids)
538
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
539
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
540
+
541
+ - 1 for tokens that are **not masked**,
542
+ - 0 for tokens that are **masked**.
543
+
544
+ [What are attention masks?](../glossary#attention-mask)
545
+ decoder_input_ids (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
546
+ Indices of decoder input sequence tokens in the vocabulary.
547
+
548
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
549
+ [`PreTrainedTokenizer.__call__`] for details.
550
+
551
+ [What are decoder input IDs?](../glossary#decoder-input-ids)
552
+
553
+ Blenderbot uses the `bos_token_id` as the starting token for `decoder_input_ids` generation. If
554
+ `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
555
+ `past_key_values`).
556
+ decoder_attention_mask (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
557
+ Default behavior: generate a tensor that ignores pad tokens in `decoder_input_ids`. Causal mask will also
558
+ be used by default.
559
+ head_mask (`torch.Tensor` of shape `(encoder_layers, encoder_attention_heads)`, *optional*):
560
+ Mask to nullify selected heads of the attention modules in the encoder. Mask values selected in `[0, 1]`:
561
+
562
+ - 1 indicates the head is **not masked**,
563
+ - 0 indicates the head is **masked**.
564
+
565
+ decoder_head_mask (`torch.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
566
+ Mask to nullify selected heads of the attention modules in the decoder. Mask values selected in `[0, 1]`:
567
+
568
+ - 1 indicates the head is **not masked**,
569
+ - 0 indicates the head is **masked**.
570
+
571
+ cross_attn_head_mask (`torch.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
572
+ Mask to nullify selected heads of the cross-attention modules in the decoder. Mask values selected in `[0,
573
+ 1]`:
574
+
575
+ - 1 indicates the head is **not masked**,
576
+ - 0 indicates the head is **masked**.
577
+
578
+ encoder_outputs (`tuple(tuple(torch.FloatTensor)`, *optional*):
579
+ Tuple consists of (`last_hidden_state`, *optional*: `hidden_states`, *optional*: `attentions`)
580
+ `last_hidden_state` of shape `(batch_size, sequence_length, hidden_size)`, *optional*) is a sequence of
581
+ hidden-states at the output of the last layer of the encoder. Used in the cross-attention of the decoder.
582
+ past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
583
+ Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
584
+ `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of shape
585
+ `(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`.
586
+
587
+ Contains pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
588
+ blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.
589
+
590
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
591
+ don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
592
+ `decoder_input_ids` of shape `(batch_size, sequence_length)`.
593
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
594
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation.
595
+ This is useful if you want more control over how to convert `input_ids` indices into associated vectors
596
+ than the model's internal embedding lookup matrix.
597
+ decoder_inputs_embeds (`torch.FloatTensor` of shape `(batch_size, target_sequence_length, hidden_size)`, *optional*):
598
+ Optionally, instead of passing `decoder_input_ids` you can choose to directly pass an embedded
599
+ representation. If `past_key_values` is used, optionally only the last `decoder_inputs_embeds` have to be
600
+ input (see `past_key_values`). This is useful if you want more control over how to convert
601
+ `decoder_input_ids` indices into associated vectors than the model's internal embedding lookup matrix.
602
+
603
+ If `decoder_input_ids` and `decoder_inputs_embeds` are both unset, `decoder_inputs_embeds` takes the value
604
+ of `inputs_embeds`.
605
+ use_cache (`bool`, *optional*):
606
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
607
+ `past_key_values`).
608
+ output_attentions (`bool`, *optional*):
609
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
610
+ tensors for more detail.
611
+ output_hidden_states (`bool`, *optional*):
612
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
613
+ more detail.
614
+ return_dict (`bool`, *optional*):
615
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
616
+ """
617
+
618
+
619
+ class BlenderbotEncoder(BlenderbotPreTrainedModel):
620
+ """
621
+ Transformer encoder consisting of *config.encoder_layers* self attention layers. Each layer is a
622
+ [`BlenderbotEncoderLayer`].
623
+
624
+ Args:
625
+ config: BlenderbotConfig
626
+ embed_tokens (nn.Embedding): output embedding
627
+ """
628
+
629
+ def __init__(self, config: BlenderbotConfig, embed_tokens: Optional[nn.Embedding] = None):
630
+ super().__init__(config)
631
+
632
+ self.dropout = config.dropout
633
+ self.layerdrop = config.encoder_layerdrop
634
+
635
+ embed_dim = config.d_model
636
+ self.padding_idx = config.pad_token_id
637
+ self.max_source_positions = config.max_position_embeddings
638
+ self.embed_scale = math.sqrt(embed_dim) if config.scale_embedding else 1.0
639
+
640
+ if embed_tokens is not None:
641
+ self.embed_tokens = embed_tokens
642
+ else:
643
+ self.embed_tokens = nn.Embedding(config.vocab_size, embed_dim, self.padding_idx)
644
+
645
+ self.embed_positions = BlenderbotLearnedPositionalEmbedding(
646
+ config.max_position_embeddings,
647
+ embed_dim,
648
+ )
649
+ self.layers = nn.ModuleList([BlenderbotEncoderLayer(config) for _ in range(config.encoder_layers)])
650
+ self.layer_norm = nn.LayerNorm(config.d_model)
651
+
652
+ self.gradient_checkpointing = False
653
+ # Initialize weights and apply final processing
654
+ self.post_init()
655
+
656
+ def forward(
657
+ self,
658
+ input_ids=None,
659
+ attention_mask=None,
660
+ head_mask=None,
661
+ inputs_embeds=None,
662
+ output_attentions=None,
663
+ output_hidden_states=None,
664
+ return_dict=None,
665
+ ):
666
+ r"""
667
+ Args:
668
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
669
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you
670
+ provide it.
671
+
672
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
673
+ [`PreTrainedTokenizer.__call__`] for details.
674
+
675
+ [What are input IDs?](../glossary#input-ids)
676
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
677
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
678
+
679
+ - 1 for tokens that are **not masked**,
680
+ - 0 for tokens that are **masked**.
681
+
682
+ [What are attention masks?](../glossary#attention-mask)
683
+ head_mask (`torch.Tensor` of shape `(encoder_layers, encoder_attention_heads)`, *optional*):
684
+ Mask to nullify selected heads of the attention modules. Mask values selected in `[0, 1]`:
685
+
686
+ - 1 indicates the head is **not masked**,
687
+ - 0 indicates the head is **masked**.
688
+
689
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
690
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation.
691
+ This is useful if you want more control over how to convert `input_ids` indices into associated vectors
692
+ than the model's internal embedding lookup matrix.
693
+ output_attentions (`bool`, *optional*):
694
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
695
+ returned tensors for more detail.
696
+ output_hidden_states (`bool`, *optional*):
697
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
698
+ for more detail.
699
+ return_dict (`bool`, *optional*):
700
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
701
+ """
702
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
703
+ output_hidden_states = (
704
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
705
+ )
706
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
707
+
708
+ # retrieve input_ids and inputs_embeds
709
+ if input_ids is not None and inputs_embeds is not None:
710
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
711
+ elif input_ids is not None:
712
+ self.warn_if_padding_and_no_attention_mask(input_ids, attention_mask)
713
+ input_shape = input_ids.size()
714
+ input_ids = input_ids.view(-1, input_shape[-1])
715
+ elif inputs_embeds is not None:
716
+ input_shape = inputs_embeds.size()[:-1]
717
+ else:
718
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
719
+
720
+ if inputs_embeds is None:
721
+ inputs_embeds = self.embed_tokens(input_ids) * self.embed_scale
722
+
723
+ embed_pos = self.embed_positions(input_shape)
724
+
725
+ hidden_states = inputs_embeds + embed_pos
726
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
727
+
728
+ # expand attention_mask
729
+ if attention_mask is not None:
730
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
731
+ attention_mask = _prepare_4d_attention_mask(attention_mask, inputs_embeds.dtype)
732
+
733
+ encoder_states = () if output_hidden_states else None
734
+ all_attentions = () if output_attentions else None
735
+
736
+ # check if head_mask has a correct number of layers specified if desired
737
+ if head_mask is not None:
738
+ if head_mask.size()[0] != len(self.layers):
739
+ raise ValueError(
740
+ f"The head_mask should be specified for {len(self.layers)} layers, but it is for"
741
+ f" {head_mask.size()[0]}."
742
+ )
743
+ for idx, encoder_layer in enumerate(self.layers):
744
+ if output_hidden_states:
745
+ encoder_states = encoder_states + (hidden_states,)
746
+ # add LayerDrop (see https://arxiv.org/abs/1909.11556 for description)
747
+ to_drop = False
748
+ if self.training:
749
+ dropout_probability = torch.rand([])
750
+ if dropout_probability < self.layerdrop: # skip the layer
751
+ to_drop = True
752
+
753
+ if to_drop:
754
+ layer_outputs = (None, None)
755
+ else:
756
+ if self.gradient_checkpointing and self.training:
757
+ layer_outputs = self._gradient_checkpointing_func(
758
+ encoder_layer.__call__,
759
+ hidden_states,
760
+ attention_mask,
761
+ (head_mask[idx] if head_mask is not None else None),
762
+ output_attentions,
763
+ )
764
+ else:
765
+ layer_outputs = encoder_layer(
766
+ hidden_states,
767
+ attention_mask,
768
+ layer_head_mask=(head_mask[idx] if head_mask is not None else None),
769
+ output_attentions=output_attentions,
770
+ )
771
+
772
+ hidden_states = layer_outputs[0]
773
+
774
+ if output_attentions:
775
+ all_attentions = all_attentions + (layer_outputs[1],)
776
+
777
+ # add final layer norm
778
+ hidden_states = self.layer_norm(hidden_states)
779
+
780
+ if output_hidden_states:
781
+ encoder_states = encoder_states + (hidden_states,)
782
+
783
+ if not return_dict:
784
+ return tuple(v for v in [hidden_states, encoder_states, all_attentions] if v is not None)
785
+ return BaseModelOutput(
786
+ last_hidden_state=hidden_states, hidden_states=encoder_states, attentions=all_attentions
787
+ )
788
+
789
+
790
+ class BlenderbotDecoder(BlenderbotPreTrainedModel):
791
+ """
792
+ Transformer decoder consisting of *config.decoder_layers* layers. Each layer is a [`BlenderbotDecoderLayer`]
793
+
794
+ Args:
795
+ config: BlenderbotConfig
796
+ embed_tokens (nn.Embedding): output embedding
797
+ """
798
+
799
+ def __init__(self, config: BlenderbotConfig, embed_tokens: Optional[nn.Embedding] = None):
800
+ super().__init__(config)
801
+ self.dropout = config.dropout
802
+ self.layerdrop = config.decoder_layerdrop
803
+ self.padding_idx = config.pad_token_id
804
+ self.max_target_positions = config.max_position_embeddings
805
+ self.embed_scale = math.sqrt(config.d_model) if config.scale_embedding else 1.0
806
+
807
+ if embed_tokens is not None:
808
+ self.embed_tokens = embed_tokens
809
+ else:
810
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.d_model, self.padding_idx)
811
+
812
+ self.embed_positions = BlenderbotLearnedPositionalEmbedding(
813
+ config.max_position_embeddings,
814
+ config.d_model,
815
+ )
816
+ self.layers = nn.ModuleList([BlenderbotDecoderLayer(config) for _ in range(config.decoder_layers)])
817
+ self.layer_norm = nn.LayerNorm(config.d_model)
818
+
819
+ self.gradient_checkpointing = False
820
+ # Initialize weights and apply final processing
821
+ self.post_init()
822
+
823
+ def get_input_embeddings(self):
824
+ return self.embed_tokens
825
+
826
+ def set_input_embeddings(self, value):
827
+ self.embed_tokens = value
828
+
829
+ def forward(
830
+ self,
831
+ input_ids=None,
832
+ attention_mask=None,
833
+ encoder_hidden_states=None,
834
+ encoder_attention_mask=None,
835
+ head_mask=None,
836
+ cross_attn_head_mask=None,
837
+ past_key_values=None,
838
+ inputs_embeds=None,
839
+ use_cache=None,
840
+ output_attentions=None,
841
+ output_hidden_states=None,
842
+ return_dict=None,
843
+ ):
844
+ r"""
845
+ Args:
846
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
847
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you
848
+ provide it.
849
+
850
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
851
+ [`PreTrainedTokenizer.__call__`] for details.
852
+
853
+ [What are input IDs?](../glossary#input-ids)
854
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
855
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
856
+
857
+ - 1 for tokens that are **not masked**,
858
+ - 0 for tokens that are **masked**.
859
+
860
+ [What are attention masks?](../glossary#attention-mask)
861
+ encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, encoder_sequence_length, hidden_size)`, *optional*):
862
+ Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention
863
+ of the decoder.
864
+ encoder_attention_mask (`torch.LongTensor` of shape `(batch_size, encoder_sequence_length)`, *optional*):
865
+ Mask to avoid performing cross-attention on padding tokens indices of encoder input_ids. Mask values
866
+ selected in `[0, 1]`:
867
+
868
+ - 1 for tokens that are **not masked**,
869
+ - 0 for tokens that are **masked**.
870
+
871
+ [What are attention masks?](../glossary#attention-mask)
872
+ head_mask (`torch.Tensor` of shape `(encoder_layers, encoder_attention_heads)`, *optional*):
873
+ Mask to nullify selected heads of the attention modules in the encoder. Mask values selected in `[0,
874
+ 1]`:
875
+
876
+ - 1 indicates the head is **not masked**,
877
+ - 0 indicates the head is **masked**.
878
+
879
+ cross_attn_head_mask (`torch.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
880
+ Mask to nullify selected heads of the cross-attention modules in the decoder to avoid performing
881
+ cross-attention on hidden heads. Mask values selected in `[0, 1]`:
882
+
883
+ - 1 indicates the head is **not masked**,
884
+ - 0 indicates the head is **masked**.
885
+
886
+ past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
887
+ Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
888
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of
889
+ shape `(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`.
890
+
891
+ Contains pre-computed hidden-states (key and values in the self-attention blocks and in the
892
+ cross-attention blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.
893
+
894
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those
895
+ that don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of
896
+ all `decoder_input_ids` of shape `(batch_size, sequence_length)`.
897
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
898
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation.
899
+ This is useful if you want more control over how to convert `input_ids` indices into associated vectors
900
+ than the model's internal embedding lookup matrix.
901
+ output_attentions (`bool`, *optional*):
902
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
903
+ returned tensors for more detail.
904
+ output_hidden_states (`bool`, *optional*):
905
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
906
+ for more detail.
907
+ return_dict (`bool`, *optional*):
908
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
909
+ """
910
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
911
+ output_hidden_states = (
912
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
913
+ )
914
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
915
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
916
+
917
+ # retrieve input_ids and inputs_embeds
918
+ if input_ids is not None and inputs_embeds is not None:
919
+ raise ValueError("You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time")
920
+ elif input_ids is not None:
921
+ input_shape = input_ids.size()
922
+ input_ids = input_ids.view(-1, input_shape[-1])
923
+ elif inputs_embeds is not None:
924
+ input_shape = inputs_embeds.size()[:-1]
925
+ else:
926
+ raise ValueError("You have to specify either decoder_input_ids or decoder_inputs_embeds")
927
+
928
+ # past_key_values_length
929
+ past_key_values_length = past_key_values[0][0].shape[2] if past_key_values is not None else 0
930
+
931
+ if inputs_embeds is None:
932
+ inputs_embeds = self.embed_tokens(input_ids) * self.embed_scale
933
+
934
+ attention_mask = _prepare_4d_causal_attention_mask(
935
+ attention_mask, input_shape, inputs_embeds, past_key_values_length
936
+ )
937
+
938
+ # expand encoder attention mask
939
+ if encoder_hidden_states is not None and encoder_attention_mask is not None:
940
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
941
+ encoder_attention_mask = _prepare_4d_attention_mask(
942
+ encoder_attention_mask, inputs_embeds.dtype, tgt_len=input_shape[-1]
943
+ )
944
+
945
+ # embed positions
946
+ positions = self.embed_positions(input_shape, past_key_values_length)
947
+
948
+ hidden_states = inputs_embeds + positions
949
+
950
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
951
+
952
+ if self.gradient_checkpointing and self.training:
953
+ if use_cache:
954
+ logger.warning(
955
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
956
+ )
957
+ use_cache = False
958
+ # decoder layers
959
+ all_hidden_states = () if output_hidden_states else None
960
+ all_self_attns = () if output_attentions else None
961
+ all_cross_attentions = () if (output_attentions and encoder_hidden_states is not None) else None
962
+ next_decoder_cache = () if use_cache else None
963
+
964
+ # check if head_mask/cross_attn_head_mask has a correct number of layers specified if desired
965
+ for attn_mask, mask_name in zip([head_mask, cross_attn_head_mask], ["head_mask", "cross_attn_head_mask"]):
966
+ if attn_mask is not None:
967
+ if attn_mask.size()[0] != len(self.layers):
968
+ raise ValueError(
969
+ f"The `{mask_name}` should be specified for {len(self.layers)} layers, but it is for"
970
+ f" {head_mask.size()[0]}."
971
+ )
972
+ for idx, decoder_layer in enumerate(self.layers):
973
+ # add LayerDrop (see https://arxiv.org/abs/1909.11556 for description)
974
+ if output_hidden_states:
975
+ all_hidden_states += (hidden_states,)
976
+ if self.training:
977
+ dropout_probability = torch.rand([])
978
+ if dropout_probability < self.layerdrop:
979
+ continue
980
+
981
+ past_key_value = past_key_values[idx] if past_key_values is not None else None
982
+
983
+ if self.gradient_checkpointing and self.training:
984
+ layer_outputs = self._gradient_checkpointing_func(
985
+ decoder_layer.__call__,
986
+ hidden_states,
987
+ attention_mask,
988
+ encoder_hidden_states,
989
+ encoder_attention_mask,
990
+ head_mask[idx] if head_mask is not None else None,
991
+ cross_attn_head_mask[idx] if cross_attn_head_mask is not None else None,
992
+ None,
993
+ output_attentions,
994
+ use_cache,
995
+ )
996
+ else:
997
+ layer_outputs = decoder_layer(
998
+ hidden_states,
999
+ attention_mask=attention_mask,
1000
+ encoder_hidden_states=encoder_hidden_states,
1001
+ encoder_attention_mask=encoder_attention_mask,
1002
+ layer_head_mask=(head_mask[idx] if head_mask is not None else None),
1003
+ cross_attn_layer_head_mask=(
1004
+ cross_attn_head_mask[idx] if cross_attn_head_mask is not None else None
1005
+ ),
1006
+ past_key_value=past_key_value,
1007
+ output_attentions=output_attentions,
1008
+ use_cache=use_cache,
1009
+ )
1010
+ hidden_states = layer_outputs[0]
1011
+
1012
+ if use_cache:
1013
+ next_decoder_cache += (layer_outputs[3 if output_attentions else 1],)
1014
+
1015
+ if output_attentions:
1016
+ all_self_attns += (layer_outputs[1],)
1017
+
1018
+ if encoder_hidden_states is not None:
1019
+ all_cross_attentions += (layer_outputs[2],)
1020
+
1021
+ # add final layer norm
1022
+ hidden_states = self.layer_norm(hidden_states)
1023
+
1024
+ # add hidden states from the last decoder layer
1025
+ if output_hidden_states:
1026
+ all_hidden_states += (hidden_states,)
1027
+
1028
+ next_cache = next_decoder_cache if use_cache else None
1029
+ if not return_dict:
1030
+ return tuple(
1031
+ v
1032
+ for v in [hidden_states, next_cache, all_hidden_states, all_self_attns, all_cross_attentions]
1033
+ if v is not None
1034
+ )
1035
+ return BaseModelOutputWithPastAndCrossAttentions(
1036
+ last_hidden_state=hidden_states,
1037
+ past_key_values=next_cache,
1038
+ hidden_states=all_hidden_states,
1039
+ attentions=all_self_attns,
1040
+ cross_attentions=all_cross_attentions,
1041
+ )
1042
+
1043
+
1044
+ @add_start_docstrings(
1045
+ "The bare Blenderbot Model outputting raw hidden-states without any specific head on top.",
1046
+ BLENDERBOT_START_DOCSTRING,
1047
+ )
1048
+ class BlenderbotModel(BlenderbotPreTrainedModel):
1049
+ _tied_weights_keys = ["decoder.embed_tokens.weight", "encoder.embed_tokens.weight"]
1050
+
1051
+ def __init__(self, config: BlenderbotConfig):
1052
+ super().__init__(config)
1053
+
1054
+ padding_idx, vocab_size = config.pad_token_id, config.vocab_size
1055
+ self.shared = nn.Embedding(vocab_size, config.d_model, padding_idx)
1056
+
1057
+ self.encoder = BlenderbotEncoder(config, self.shared)
1058
+ self.decoder = BlenderbotDecoder(config, self.shared)
1059
+
1060
+ # Initialize weights and apply final processing
1061
+ self.post_init()
1062
+
1063
+ @classmethod
1064
+ def from_pretrained(cls, pretrained_model_name_or_path: Optional[Union[str, os.PathLike]], *model_args, **kwargs):
1065
+ if pretrained_model_name_or_path == "facebook/blenderbot-90M":
1066
+ warnings.warn(
1067
+ "The checkpoint `facebook/blenderbot-90M` is deprecated. In the future, please use the identical"
1068
+ " checkpoint `facebook/small_blenderbot-90M` with"
1069
+ " `BlenderbotSmallModel.from_pretrained('facebook/small_blenderbot-90M')` instead.",
1070
+ FutureWarning,
1071
+ )
1072
+ return BlenderbotSmallModel.from_pretrained(pretrained_model_name_or_path)
1073
+
1074
+ return super(BlenderbotModel, cls).from_pretrained(pretrained_model_name_or_path, *model_args, **kwargs)
1075
+
1076
+ def get_input_embeddings(self):
1077
+ return self.shared
1078
+
1079
+ def set_input_embeddings(self, value):
1080
+ self.shared = value
1081
+ self.encoder.embed_tokens = self.shared
1082
+ self.decoder.embed_tokens = self.shared
1083
+
1084
+ def get_encoder(self):
1085
+ return self.encoder
1086
+
1087
+ def get_decoder(self):
1088
+ return self.decoder
1089
+
1090
+ @add_start_docstrings_to_model_forward(BLENDERBOT_INPUTS_DOCSTRING)
1091
+ @replace_return_docstrings(output_type=Seq2SeqModelOutput, config_class=_CONFIG_FOR_DOC)
1092
+ def forward(
1093
+ self,
1094
+ input_ids: Optional[torch.LongTensor] = None,
1095
+ attention_mask: Optional[torch.Tensor] = None,
1096
+ decoder_input_ids: Optional[torch.LongTensor] = None,
1097
+ decoder_attention_mask: Optional[torch.LongTensor] = None,
1098
+ head_mask: Optional[torch.Tensor] = None,
1099
+ decoder_head_mask: Optional[torch.Tensor] = None,
1100
+ cross_attn_head_mask: Optional[torch.Tensor] = None,
1101
+ encoder_outputs: Optional[Union[Tuple, BaseModelOutput]] = None,
1102
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1103
+ inputs_embeds: Optional[torch.Tensor] = None,
1104
+ decoder_inputs_embeds: Optional[torch.FloatTensor] = None,
1105
+ use_cache: Optional[bool] = None,
1106
+ output_attentions: Optional[bool] = None,
1107
+ output_hidden_states: Optional[bool] = None,
1108
+ return_dict: Optional[bool] = None,
1109
+ ) -> Union[Tuple[torch.FloatTensor], Seq2SeqModelOutput]:
1110
+ r"""
1111
+ Returns:
1112
+
1113
+ Example:
1114
+
1115
+ ```python
1116
+ >>> from transformers import AutoTokenizer, BlenderbotModel
1117
+
1118
+ >>> model = BlenderbotModel.from_pretrained("facebook/blenderbot-400M-distill")
1119
+ >>> tokenizer = AutoTokenizer.from_pretrained("facebook/blenderbot-400M-distill")
1120
+
1121
+ >>> inputs = tokenizer("Studies have been shown that owning a dog is good for you", return_tensors="pt")
1122
+ >>> decoder_input_ids = tokenizer("Studies show that", return_tensors="pt").input_ids # Batch size 1
1123
+ >>> outputs = model(input_ids=inputs.input_ids, decoder_input_ids=decoder_input_ids)
1124
+
1125
+ >>> last_hidden_states = outputs.last_hidden_state
1126
+ >>> list(last_hidden_states.shape)
1127
+ [1, 6, 1280]
1128
+ ```"""
1129
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1130
+ output_hidden_states = (
1131
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1132
+ )
1133
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
1134
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1135
+
1136
+ if encoder_outputs is None:
1137
+ encoder_outputs = self.encoder(
1138
+ input_ids=input_ids,
1139
+ attention_mask=attention_mask,
1140
+ head_mask=head_mask,
1141
+ inputs_embeds=inputs_embeds,
1142
+ output_attentions=output_attentions,
1143
+ output_hidden_states=output_hidden_states,
1144
+ return_dict=return_dict,
1145
+ )
1146
+ # If the user passed a tuple for encoder_outputs, we wrap it in a BaseModelOutput when return_dict=True
1147
+ elif return_dict and not isinstance(encoder_outputs, BaseModelOutput):
1148
+ encoder_outputs = BaseModelOutput(
1149
+ last_hidden_state=encoder_outputs[0],
1150
+ hidden_states=encoder_outputs[1] if len(encoder_outputs) > 1 else None,
1151
+ attentions=encoder_outputs[2] if len(encoder_outputs) > 2 else None,
1152
+ )
1153
+
1154
+ # decoder outputs consists of (dec_features, past_key_value, dec_hidden, dec_attn)
1155
+ decoder_outputs = self.decoder(
1156
+ input_ids=decoder_input_ids,
1157
+ attention_mask=decoder_attention_mask,
1158
+ encoder_hidden_states=encoder_outputs[0],
1159
+ encoder_attention_mask=attention_mask,
1160
+ head_mask=decoder_head_mask,
1161
+ cross_attn_head_mask=cross_attn_head_mask,
1162
+ past_key_values=past_key_values,
1163
+ inputs_embeds=decoder_inputs_embeds,
1164
+ use_cache=use_cache,
1165
+ output_attentions=output_attentions,
1166
+ output_hidden_states=output_hidden_states,
1167
+ return_dict=return_dict,
1168
+ )
1169
+
1170
+ if not return_dict:
1171
+ return decoder_outputs + encoder_outputs
1172
+
1173
+ return Seq2SeqModelOutput(
1174
+ last_hidden_state=decoder_outputs.last_hidden_state,
1175
+ past_key_values=decoder_outputs.past_key_values,
1176
+ decoder_hidden_states=decoder_outputs.hidden_states,
1177
+ decoder_attentions=decoder_outputs.attentions,
1178
+ cross_attentions=decoder_outputs.cross_attentions,
1179
+ encoder_last_hidden_state=encoder_outputs.last_hidden_state,
1180
+ encoder_hidden_states=encoder_outputs.hidden_states,
1181
+ encoder_attentions=encoder_outputs.attentions,
1182
+ )
1183
+
1184
+
1185
+ @add_start_docstrings(
1186
+ "The Blenderbot Model with a language modeling head. Can be used for summarization.", BLENDERBOT_START_DOCSTRING
1187
+ )
1188
+ class BlenderbotForConditionalGeneration(BlenderbotPreTrainedModel):
1189
+ base_model_prefix = "model"
1190
+ _keys_to_ignore_on_load_missing = ["final_logits_bias"]
1191
+ _tied_weights_keys = ["decoder.embed_tokens.weight", "encoder.embed_tokens.weight", "lm_head.weight"]
1192
+
1193
+ def __init__(self, config: BlenderbotConfig):
1194
+ super().__init__(config)
1195
+ self.model = BlenderbotModel(config)
1196
+ self.register_buffer("final_logits_bias", torch.zeros((1, self.model.shared.num_embeddings)))
1197
+ self.lm_head = nn.Linear(config.d_model, self.model.shared.num_embeddings, bias=False)
1198
+
1199
+ # Initialize weights and apply final processing
1200
+ self.post_init()
1201
+
1202
+ @classmethod
1203
+ def from_pretrained(cls, pretrained_model_name_or_path: Optional[Union[str, os.PathLike]], *model_args, **kwargs):
1204
+ if pretrained_model_name_or_path == "facebook/blenderbot-90M":
1205
+ warnings.warn(
1206
+ "The checkpoint `facebook/blenderbot-90M` is deprecated. In the future, please use the identical"
1207
+ " checkpoint `facebook/small_blenderbot-90M` with"
1208
+ " `BlenderbotSmallForConditionalGeneration.from_pretrained('facebook/small_blenderbot-90M')` instead.",
1209
+ FutureWarning,
1210
+ )
1211
+ return BlenderbotSmallForConditionalGeneration.from_pretrained(pretrained_model_name_or_path)
1212
+
1213
+ return super(BlenderbotForConditionalGeneration, cls).from_pretrained(
1214
+ pretrained_model_name_or_path, *model_args, **kwargs
1215
+ )
1216
+
1217
+ def get_encoder(self):
1218
+ return self.model.get_encoder()
1219
+
1220
+ def get_decoder(self):
1221
+ return self.model.get_decoder()
1222
+
1223
+ def resize_token_embeddings(self, new_num_tokens: int, pad_to_multiple_of: Optional[int] = None) -> nn.Embedding:
1224
+ new_embeddings = super().resize_token_embeddings(new_num_tokens, pad_to_multiple_of)
1225
+ self._resize_final_logits_bias(new_embeddings.weight.shape[0])
1226
+ return new_embeddings
1227
+
1228
+ def _resize_final_logits_bias(self, new_num_tokens: int) -> None:
1229
+ old_num_tokens = self.final_logits_bias.shape[-1]
1230
+ if new_num_tokens <= old_num_tokens:
1231
+ new_bias = self.final_logits_bias[:, :new_num_tokens]
1232
+ else:
1233
+ extra_bias = torch.zeros((1, new_num_tokens - old_num_tokens), device=self.final_logits_bias.device)
1234
+ new_bias = torch.cat([self.final_logits_bias, extra_bias], dim=1)
1235
+ self.register_buffer("final_logits_bias", new_bias)
1236
+
1237
+ def get_output_embeddings(self):
1238
+ return self.lm_head
1239
+
1240
+ def set_output_embeddings(self, new_embeddings):
1241
+ self.lm_head = new_embeddings
1242
+
1243
+ @add_start_docstrings_to_model_forward(BLENDERBOT_INPUTS_DOCSTRING)
1244
+ @replace_return_docstrings(output_type=Seq2SeqLMOutput, config_class=_CONFIG_FOR_DOC)
1245
+ @add_end_docstrings(BLENDERBOT_GENERATION_EXAMPLE)
1246
+ def forward(
1247
+ self,
1248
+ input_ids: Optional[torch.LongTensor] = None,
1249
+ attention_mask: Optional[torch.Tensor] = None,
1250
+ decoder_input_ids: Optional[torch.LongTensor] = None,
1251
+ decoder_attention_mask: Optional[torch.LongTensor] = None,
1252
+ head_mask: Optional[torch.Tensor] = None,
1253
+ decoder_head_mask: Optional[torch.Tensor] = None,
1254
+ cross_attn_head_mask: Optional[torch.Tensor] = None,
1255
+ encoder_outputs: Optional[Union[Tuple, BaseModelOutput]] = None,
1256
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1257
+ inputs_embeds: Optional[torch.Tensor] = None,
1258
+ decoder_inputs_embeds: Optional[torch.FloatTensor] = None,
1259
+ labels: Optional[torch.LongTensor] = None,
1260
+ use_cache: Optional[bool] = None,
1261
+ output_attentions: Optional[bool] = None,
1262
+ output_hidden_states: Optional[bool] = None,
1263
+ return_dict: Optional[bool] = None,
1264
+ ) -> Union[Tuple[torch.FloatTensor], Seq2SeqLMOutput]:
1265
+ r"""
1266
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1267
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1268
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1269
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1270
+
1271
+ Returns:
1272
+ """
1273
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1274
+
1275
+ if labels is not None:
1276
+ if use_cache:
1277
+ logger.warning("The `use_cache` argument is changed to `False` since `labels` is provided.")
1278
+ use_cache = False
1279
+ if decoder_input_ids is None and decoder_inputs_embeds is None:
1280
+ decoder_input_ids = shift_tokens_right(
1281
+ labels, self.config.pad_token_id, self.config.decoder_start_token_id
1282
+ )
1283
+
1284
+ outputs = self.model(
1285
+ input_ids,
1286
+ attention_mask=attention_mask,
1287
+ decoder_input_ids=decoder_input_ids,
1288
+ encoder_outputs=encoder_outputs,
1289
+ decoder_attention_mask=decoder_attention_mask,
1290
+ head_mask=head_mask,
1291
+ decoder_head_mask=decoder_head_mask,
1292
+ cross_attn_head_mask=cross_attn_head_mask,
1293
+ past_key_values=past_key_values,
1294
+ inputs_embeds=inputs_embeds,
1295
+ decoder_inputs_embeds=decoder_inputs_embeds,
1296
+ use_cache=use_cache,
1297
+ output_attentions=output_attentions,
1298
+ output_hidden_states=output_hidden_states,
1299
+ return_dict=return_dict,
1300
+ )
1301
+ lm_logits = self.lm_head(outputs[0]) + self.final_logits_bias
1302
+
1303
+ masked_lm_loss = None
1304
+ if labels is not None:
1305
+ loss_fct = CrossEntropyLoss()
1306
+ masked_lm_loss = loss_fct(lm_logits.view(-1, self.config.vocab_size), labels.view(-1))
1307
+
1308
+ if not return_dict:
1309
+ output = (lm_logits,) + outputs[1:]
1310
+ return ((masked_lm_loss,) + output) if masked_lm_loss is not None else output
1311
+
1312
+ return Seq2SeqLMOutput(
1313
+ loss=masked_lm_loss,
1314
+ logits=lm_logits,
1315
+ past_key_values=outputs.past_key_values,
1316
+ decoder_hidden_states=outputs.decoder_hidden_states,
1317
+ decoder_attentions=outputs.decoder_attentions,
1318
+ cross_attentions=outputs.cross_attentions,
1319
+ encoder_last_hidden_state=outputs.encoder_last_hidden_state,
1320
+ encoder_hidden_states=outputs.encoder_hidden_states,
1321
+ encoder_attentions=outputs.encoder_attentions,
1322
+ )
1323
+
1324
+ def prepare_inputs_for_generation(
1325
+ self,
1326
+ decoder_input_ids,
1327
+ past_key_values=None,
1328
+ attention_mask=None,
1329
+ head_mask=None,
1330
+ decoder_head_mask=None,
1331
+ cross_attn_head_mask=None,
1332
+ use_cache=None,
1333
+ encoder_outputs=None,
1334
+ **kwargs,
1335
+ ):
1336
+ # cut decoder_input_ids if past is used
1337
+ if past_key_values is not None:
1338
+ past_length = past_key_values[0][0].shape[2]
1339
+
1340
+ # Some generation methods already pass only the last input ID
1341
+ if decoder_input_ids.shape[1] > past_length:
1342
+ remove_prefix_length = past_length
1343
+ else:
1344
+ # Default to old behavior: keep only final ID
1345
+ remove_prefix_length = decoder_input_ids.shape[1] - 1
1346
+
1347
+ decoder_input_ids = decoder_input_ids[:, remove_prefix_length:]
1348
+
1349
+ return {
1350
+ "input_ids": None, # encoder_outputs is defined. input_ids not needed
1351
+ "encoder_outputs": encoder_outputs,
1352
+ "past_key_values": past_key_values,
1353
+ "decoder_input_ids": decoder_input_ids,
1354
+ "attention_mask": attention_mask,
1355
+ "head_mask": head_mask,
1356
+ "decoder_head_mask": decoder_head_mask,
1357
+ "cross_attn_head_mask": cross_attn_head_mask,
1358
+ "use_cache": use_cache, # change this to avoid caching (presumably for debugging)
1359
+ }
1360
+
1361
+ @staticmethod
1362
+ def _reorder_cache(past_key_values, beam_idx):
1363
+ reordered_past = ()
1364
+ for layer_past in past_key_values:
1365
+ # cached cross_attention states don't have to be reordered -> they are always the same
1366
+ reordered_past += (
1367
+ tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past[:2])
1368
+ + layer_past[2:],
1369
+ )
1370
+ return reordered_past
1371
+
1372
+
1373
+ # Copied from transformers.models.bart.modeling_bart.BartDecoderWrapper with Bart->Blenderbot
1374
+ class BlenderbotDecoderWrapper(BlenderbotPreTrainedModel):
1375
+ """
1376
+ This wrapper class is a helper class to correctly load pretrained checkpoints when the causal language model is
1377
+ used in combination with the [`EncoderDecoderModel`] framework.
1378
+ """
1379
+
1380
+ def __init__(self, config):
1381
+ super().__init__(config)
1382
+ self.decoder = BlenderbotDecoder(config)
1383
+
1384
+ def forward(self, *args, **kwargs):
1385
+ return self.decoder(*args, **kwargs)
1386
+
1387
+
1388
+ # Copied from transformers.models.bart.modeling_bart.BartForCausalLM with Bart->Blenderbot, facebook/bart-base->facebook/blenderbot-400M-distill
1389
+ class BlenderbotForCausalLM(BlenderbotPreTrainedModel):
1390
+ _tied_weights_keys = ["lm_head.weight"]
1391
+
1392
+ def __init__(self, config):
1393
+ config = copy.deepcopy(config)
1394
+ config.is_decoder = True
1395
+ config.is_encoder_decoder = False
1396
+ super().__init__(config)
1397
+ self.model = BlenderbotDecoderWrapper(config)
1398
+
1399
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1400
+
1401
+ # Initialize weights and apply final processing
1402
+ self.post_init()
1403
+
1404
+ def get_input_embeddings(self):
1405
+ return self.model.decoder.embed_tokens
1406
+
1407
+ def set_input_embeddings(self, value):
1408
+ self.model.decoder.embed_tokens = value
1409
+
1410
+ def get_output_embeddings(self):
1411
+ return self.lm_head
1412
+
1413
+ def set_output_embeddings(self, new_embeddings):
1414
+ self.lm_head = new_embeddings
1415
+
1416
+ def set_decoder(self, decoder):
1417
+ self.model.decoder = decoder
1418
+
1419
+ def get_decoder(self):
1420
+ return self.model.decoder
1421
+
1422
+ @replace_return_docstrings(output_type=CausalLMOutputWithCrossAttentions, config_class=_CONFIG_FOR_DOC)
1423
+ def forward(
1424
+ self,
1425
+ input_ids: torch.LongTensor = None,
1426
+ attention_mask: Optional[torch.Tensor] = None,
1427
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
1428
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
1429
+ head_mask: Optional[torch.Tensor] = None,
1430
+ cross_attn_head_mask: Optional[torch.Tensor] = None,
1431
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1432
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1433
+ labels: Optional[torch.LongTensor] = None,
1434
+ use_cache: Optional[bool] = None,
1435
+ output_attentions: Optional[bool] = None,
1436
+ output_hidden_states: Optional[bool] = None,
1437
+ return_dict: Optional[bool] = None,
1438
+ ) -> Union[Tuple, CausalLMOutputWithCrossAttentions]:
1439
+ r"""
1440
+ Args:
1441
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
1442
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you
1443
+ provide it.
1444
+
1445
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
1446
+ [`PreTrainedTokenizer.__call__`] for details.
1447
+
1448
+ [What are input IDs?](../glossary#input-ids)
1449
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
1450
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
1451
+
1452
+ - 1 for tokens that are **not masked**,
1453
+ - 0 for tokens that are **masked**.
1454
+
1455
+ [What are attention masks?](../glossary#attention-mask)
1456
+ encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
1457
+ Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention
1458
+ if the model is configured as a decoder.
1459
+ encoder_attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
1460
+ Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used
1461
+ in the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`:
1462
+ head_mask (`torch.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
1463
+ Mask to nullify selected heads of the attention modules. Mask values selected in `[0, 1]`:
1464
+
1465
+ - 1 indicates the head is **not masked**,
1466
+ - 0 indicates the head is **masked**.
1467
+
1468
+ cross_attn_head_mask (`torch.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
1469
+ Mask to nullify selected heads of the cross-attention modules. Mask values selected in `[0, 1]`:
1470
+
1471
+ - 1 indicates the head is **not masked**,
1472
+ - 0 indicates the head is **masked**.
1473
+
1474
+ past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
1475
+ Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
1476
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of
1477
+ shape `(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`. The two additional
1478
+ tensors are only required when the model is used as a decoder in a Sequence to Sequence model.
1479
+
1480
+ Contains pre-computed hidden-states (key and values in the self-attention blocks and in the
1481
+ cross-attention blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.
1482
+
1483
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those
1484
+ that don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of
1485
+ all `decoder_input_ids` of shape `(batch_size, sequence_length)`.
1486
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1487
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1488
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1489
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1490
+ use_cache (`bool`, *optional*):
1491
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
1492
+ (see `past_key_values`).
1493
+
1494
+ - 1 for tokens that are **not masked**,
1495
+ - 0 for tokens that are **masked**.
1496
+ output_attentions (`bool`, *optional*):
1497
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
1498
+ returned tensors for more detail.
1499
+ output_hidden_states (`bool`, *optional*):
1500
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
1501
+ for more detail.
1502
+ return_dict (`bool`, *optional*):
1503
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
1504
+
1505
+ Returns:
1506
+
1507
+ Example:
1508
+
1509
+ ```python
1510
+ >>> from transformers import AutoTokenizer, BlenderbotForCausalLM
1511
+
1512
+ >>> tokenizer = AutoTokenizer.from_pretrained("facebook/blenderbot-400M-distill")
1513
+ >>> model = BlenderbotForCausalLM.from_pretrained("facebook/blenderbot-400M-distill", add_cross_attention=False)
1514
+ >>> assert model.config.is_decoder, f"{model.__class__} has to be configured as a decoder."
1515
+ >>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")
1516
+ >>> outputs = model(**inputs)
1517
+
1518
+ >>> logits = outputs.logits
1519
+ >>> expected_shape = [1, inputs.input_ids.shape[-1], model.config.vocab_size]
1520
+ >>> list(logits.shape) == expected_shape
1521
+ True
1522
+ ```"""
1523
+
1524
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1525
+ output_hidden_states = (
1526
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1527
+ )
1528
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1529
+
1530
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1531
+ outputs = self.model.decoder(
1532
+ input_ids=input_ids,
1533
+ attention_mask=attention_mask,
1534
+ encoder_hidden_states=encoder_hidden_states,
1535
+ encoder_attention_mask=encoder_attention_mask,
1536
+ head_mask=head_mask,
1537
+ cross_attn_head_mask=cross_attn_head_mask,
1538
+ past_key_values=past_key_values,
1539
+ inputs_embeds=inputs_embeds,
1540
+ use_cache=use_cache,
1541
+ output_attentions=output_attentions,
1542
+ output_hidden_states=output_hidden_states,
1543
+ return_dict=return_dict,
1544
+ )
1545
+
1546
+ logits = self.lm_head(outputs[0])
1547
+
1548
+ loss = None
1549
+ if labels is not None:
1550
+ labels = labels.to(logits.device)
1551
+ loss_fct = CrossEntropyLoss()
1552
+ loss = loss_fct(logits.view(-1, self.config.vocab_size), labels.view(-1))
1553
+
1554
+ if not return_dict:
1555
+ output = (logits,) + outputs[1:]
1556
+ return (loss,) + output if loss is not None else output
1557
+
1558
+ return CausalLMOutputWithCrossAttentions(
1559
+ loss=loss,
1560
+ logits=logits,
1561
+ past_key_values=outputs.past_key_values,
1562
+ hidden_states=outputs.hidden_states,
1563
+ attentions=outputs.attentions,
1564
+ cross_attentions=outputs.cross_attentions,
1565
+ )
1566
+
1567
+ def prepare_inputs_for_generation(
1568
+ self, input_ids, past_key_values=None, attention_mask=None, use_cache=None, **kwargs
1569
+ ):
1570
+ # if model is used as a decoder in encoder-decoder model, the decoder attention mask is created on the fly
1571
+ if attention_mask is None:
1572
+ attention_mask = input_ids.new_ones(input_ids.shape)
1573
+
1574
+ if past_key_values:
1575
+ past_length = past_key_values[0][0].shape[2]
1576
+
1577
+ # Some generation methods already pass only the last input ID
1578
+ if input_ids.shape[1] > past_length:
1579
+ remove_prefix_length = past_length
1580
+ else:
1581
+ # Default to old behavior: keep only final ID
1582
+ remove_prefix_length = input_ids.shape[1] - 1
1583
+
1584
+ input_ids = input_ids[:, remove_prefix_length:]
1585
+ # first step, decoder_cached_states are empty
1586
+ return {
1587
+ "input_ids": input_ids, # encoder_outputs is defined. input_ids not needed
1588
+ "attention_mask": attention_mask,
1589
+ "past_key_values": past_key_values,
1590
+ "use_cache": use_cache,
1591
+ }
1592
+
1593
+ @staticmethod
1594
+ def _reorder_cache(past_key_values, beam_idx):
1595
+ reordered_past = ()
1596
+ for layer_past in past_key_values:
1597
+ reordered_past += (
1598
+ tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
1599
+ )
1600
+ return reordered_past
env-llmeval/lib/python3.10/site-packages/transformers/models/blenderbot/modeling_flax_blenderbot.py ADDED
@@ -0,0 +1,1505 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2021 The Fairseq Authors and The Google Flax Team Authors And The HuggingFace Inc. team. All rights reserved.
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
+ """ Flax Blenderbot model."""
16
+
17
+ import math
18
+ import random
19
+ from functools import partial
20
+ from typing import Callable, Optional, Tuple
21
+
22
+ import flax.linen as nn
23
+ import jax
24
+ import jax.numpy as jnp
25
+ from flax.core.frozen_dict import FrozenDict, freeze, unfreeze
26
+ from flax.linen import combine_masks, make_causal_mask
27
+ from flax.linen.attention import dot_product_attention_weights
28
+ from flax.traverse_util import flatten_dict, unflatten_dict
29
+ from jax import lax
30
+ from jax.random import PRNGKey
31
+
32
+ from ...modeling_flax_outputs import (
33
+ FlaxBaseModelOutput,
34
+ FlaxBaseModelOutputWithPastAndCrossAttentions,
35
+ FlaxCausalLMOutputWithCrossAttentions,
36
+ FlaxSeq2SeqLMOutput,
37
+ FlaxSeq2SeqModelOutput,
38
+ )
39
+ from ...modeling_flax_utils import (
40
+ ACT2FN,
41
+ FlaxPreTrainedModel,
42
+ append_call_sample_docstring,
43
+ append_replace_return_docstrings,
44
+ overwrite_call_docstring,
45
+ )
46
+ from ...utils import add_start_docstrings, add_start_docstrings_to_model_forward, logging, replace_return_docstrings
47
+ from .configuration_blenderbot import BlenderbotConfig
48
+
49
+
50
+ logger = logging.get_logger(__name__)
51
+
52
+ _CONFIG_FOR_DOC = "BlenderbotConfig"
53
+ _CHECKPOINT_FOR_DOC = "facebook/blenderbot-400M-distill"
54
+
55
+
56
+ BLENDERBOT_START_DOCSTRING = r"""
57
+ This model inherits from [`FlaxPreTrainedModel`]. Check the superclass documentation for the generic methods the
58
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
59
+ etc.)
60
+
61
+ This model is also a Flax Linen
62
+ [flax.nn.Module](https://flax.readthedocs.io/en/latest/_autosummary/flax.nn.module.html) subclass. Use it as a
63
+ regular Flax Module and refer to the Flax documentation for all matter related to general usage and behavior.
64
+
65
+ Finally, this model supports inherent JAX features such as:
66
+
67
+ - [Just-In-Time (JIT) compilation](https://jax.readthedocs.io/en/latest/jax.html#just-in-time-compilation-jit)
68
+ - [Automatic Differentiation](https://jax.readthedocs.io/en/latest/jax.html#automatic-differentiation)
69
+ - [Vectorization](https://jax.readthedocs.io/en/latest/jax.html#vectorization-vmap)
70
+ - [Parallelization](https://jax.readthedocs.io/en/latest/jax.html#parallelization-pmap)
71
+
72
+ Parameters:
73
+ config ([`BlenderbotConfig`]): Model configuration class with all the parameters of the model.
74
+ Initializing with a config file does not load the weights associated with the model, only the
75
+ configuration. Check out the [`~FlaxPreTrainedModel.from_pretrained`] method to load the model weights.
76
+ """
77
+
78
+ BLENDERBOT_INPUTS_DOCSTRING = r"""
79
+ Args:
80
+ input_ids (`jnp.ndarray` of shape `(batch_size, sequence_length)`):
81
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
82
+ it.
83
+
84
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
85
+ [`PreTrainedTokenizer.__call__`] for details.
86
+
87
+ [What are input IDs?](../glossary#input-ids)
88
+ attention_mask (`jnp.ndarray` of shape `(batch_size, sequence_length)`, *optional*):
89
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
90
+
91
+ - 1 for tokens that are **not masked**,
92
+ - 0 for tokens that are **masked**.
93
+
94
+ [What are attention masks?](../glossary#attention-mask)
95
+ decoder_input_ids (`jnp.ndarray` of shape `(batch_size, target_sequence_length)`, *optional*):
96
+ Indices of decoder input sequence tokens in the vocabulary.
97
+
98
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
99
+ [`PreTrainedTokenizer.__call__`] for details.
100
+
101
+ [What are decoder input IDs?](../glossary#decoder-input-ids)
102
+
103
+ For translation and summarization training, `decoder_input_ids` should be provided. If no
104
+ `decoder_input_ids` is provided, the model will create this tensor by shifting the `input_ids` to the right
105
+ for denoising pre-training following the paper.
106
+ decoder_attention_mask (`jnp.ndarray` of shape `(batch_size, target_sequence_length)`, *optional*):
107
+ Default behavior: generate a tensor that ignores pad tokens in `decoder_input_ids`. Causal mask will also
108
+ be used by default.
109
+
110
+ If you want to change padding behavior, you should modify to your needs. See diagram 1 in [the
111
+ paper](https://arxiv.org/abs/1910.13461) for more information on the default strategy.
112
+ position_ids (`numpy.ndarray` of shape `(batch_size, sequence_length)`, *optional*):
113
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
114
+ config.max_position_embeddings - 1]`.
115
+ decoder_position_ids (`numpy.ndarray` of shape `(batch_size, sequence_length)`, *optional*):
116
+ Indices of positions of each decoder input sequence tokens in the position embeddings. Selected in the
117
+ range `[0, config.max_position_embeddings - 1]`.
118
+ output_attentions (`bool`, *optional*):
119
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
120
+ tensors for more detail.
121
+ output_hidden_states (`bool`, *optional*):
122
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
123
+ more detail.
124
+ return_dict (`bool`, *optional*):
125
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
126
+ """
127
+
128
+
129
+ BLENDERBOT_ENCODE_INPUTS_DOCSTRING = r"""
130
+ Args:
131
+ input_ids (`jnp.ndarray` of shape `(batch_size, sequence_length)`):
132
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
133
+ it.
134
+
135
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
136
+ [`PreTrainedTokenizer.__call__`] for details.
137
+
138
+ [What are input IDs?](../glossary#input-ids)
139
+ attention_mask (`jnp.ndarray` of shape `(batch_size, sequence_length)`, *optional*):
140
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
141
+
142
+ - 1 for tokens that are **not masked**,
143
+ - 0 for tokens that are **masked**.
144
+
145
+ [What are attention masks?](../glossary#attention-mask)
146
+ position_ids (`numpy.ndarray` of shape `(batch_size, sequence_length)`, *optional*):
147
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
148
+ config.max_position_embeddings - 1]`.
149
+ output_attentions (`bool`, *optional*):
150
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
151
+ tensors for more detail.
152
+ output_hidden_states (`bool`, *optional*):
153
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
154
+ more detail.
155
+ return_dict (`bool`, *optional*):
156
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
157
+ """
158
+
159
+ BLENDERBOT_DECODE_INPUTS_DOCSTRING = r"""
160
+ Args:
161
+ decoder_input_ids (`jnp.ndarray` of shape `(batch_size, target_sequence_length)`):
162
+ Indices of decoder input sequence tokens in the vocabulary.
163
+
164
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
165
+ [`PreTrainedTokenizer.__call__`] for details.
166
+
167
+ [What are decoder input IDs?](../glossary#decoder-input-ids)
168
+
169
+ For translation and summarization training, `decoder_input_ids` should be provided. If no
170
+ `decoder_input_ids` is provided, the model will create this tensor by shifting the `input_ids` to the right
171
+ for denoising pre-training following the paper.
172
+ encoder_outputs (`tuple(tuple(jnp.ndarray)`):
173
+ Tuple consists of (`last_hidden_state`, *optional*: `hidden_states`, *optional*: `attentions`)
174
+ `last_hidden_state` of shape `(batch_size, sequence_length, hidden_size)`, *optional*) is a sequence of
175
+ hidden-states at the output of the last layer of the encoder. Used in the cross-attention of the decoder.
176
+ encoder_attention_mask (`jnp.ndarray` of shape `(batch_size, sequence_length)`, *optional*):
177
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
178
+
179
+ - 1 for tokens that are **not masked**,
180
+ - 0 for tokens that are **masked**.
181
+
182
+ [What are attention masks?](../glossary#attention-mask)
183
+ decoder_attention_mask (`jnp.ndarray` of shape `(batch_size, target_sequence_length)`, *optional*):
184
+ Default behavior: generate a tensor that ignores pad tokens in `decoder_input_ids`. Causal mask will also
185
+ be used by default.
186
+
187
+ If you want to change padding behavior, you should modify to your needs. See diagram 1 in [the
188
+ paper](https://arxiv.org/abs/1910.13461) for more information on the default strategy.
189
+ decoder_position_ids (`numpy.ndarray` of shape `(batch_size, sequence_length)`, *optional*):
190
+ Indices of positions of each decoder input sequence tokens in the position embeddings. Selected in the
191
+ range `[0, config.max_position_embeddings - 1]`.
192
+ past_key_values (`Dict[str, np.ndarray]`, *optional*, returned by `init_cache` or when passing previous `past_key_values`):
193
+ Dictionary of pre-computed hidden-states (key and values in the attention blocks) that can be used for fast
194
+ auto-regressive decoding. Pre-computed key and value hidden-states are of shape *[batch_size, max_length]*.
195
+ output_attentions (`bool`, *optional*):
196
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
197
+ tensors for more detail.
198
+ output_hidden_states (`bool`, *optional*):
199
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
200
+ more detail.
201
+ return_dict (`bool`, *optional*):
202
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
203
+ """
204
+
205
+
206
+ # Copied from transformers.models.bart.modeling_flax_bart.shift_tokens_right
207
+ def shift_tokens_right(input_ids: jnp.ndarray, pad_token_id: int, decoder_start_token_id: int) -> jnp.ndarray:
208
+ """
209
+ Shift input ids one token to the right.
210
+ """
211
+ shifted_input_ids = jnp.zeros_like(input_ids)
212
+ shifted_input_ids = shifted_input_ids.at[:, 1:].set(input_ids[:, :-1])
213
+ shifted_input_ids = shifted_input_ids.at[:, 0].set(decoder_start_token_id)
214
+
215
+ shifted_input_ids = jnp.where(shifted_input_ids == -100, pad_token_id, shifted_input_ids)
216
+ return shifted_input_ids
217
+
218
+
219
+ # Copied from transformers.models.bart.modeling_flax_bart.FlaxBartAttention with Bart->Blenderbot
220
+ class FlaxBlenderbotAttention(nn.Module):
221
+ config: BlenderbotConfig
222
+ embed_dim: int
223
+ num_heads: int
224
+ dropout: float = 0.0
225
+ causal: bool = False
226
+ bias: bool = True
227
+ dtype: jnp.dtype = jnp.float32 # the dtype of the computation
228
+
229
+ def setup(self) -> None:
230
+ self.head_dim = self.embed_dim // self.num_heads
231
+ if self.head_dim * self.num_heads != self.embed_dim:
232
+ raise ValueError(
233
+ f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim}"
234
+ f" and `num_heads`: {self.num_heads})."
235
+ )
236
+
237
+ dense = partial(
238
+ nn.Dense,
239
+ self.embed_dim,
240
+ use_bias=self.bias,
241
+ dtype=self.dtype,
242
+ kernel_init=jax.nn.initializers.normal(self.config.init_std),
243
+ )
244
+
245
+ self.q_proj, self.k_proj, self.v_proj = dense(), dense(), dense()
246
+ self.out_proj = dense()
247
+
248
+ self.dropout_layer = nn.Dropout(rate=self.dropout)
249
+
250
+ if self.causal:
251
+ self.causal_mask = make_causal_mask(
252
+ jnp.ones((1, self.config.max_position_embeddings), dtype="bool"), dtype="bool"
253
+ )
254
+
255
+ def _split_heads(self, hidden_states):
256
+ return hidden_states.reshape(hidden_states.shape[:2] + (self.num_heads, self.head_dim))
257
+
258
+ def _merge_heads(self, hidden_states):
259
+ return hidden_states.reshape(hidden_states.shape[:2] + (self.embed_dim,))
260
+
261
+ @nn.compact
262
+ def _concatenate_to_cache(self, key, value, query, attention_mask):
263
+ """
264
+ This function takes projected key, value states from a single input token and concatenates the states to cached
265
+ states from previous steps. This function is slighly adapted from the official Flax repository:
266
+ https://github.com/google/flax/blob/491ce18759622506588784b4fca0e4bf05f8c8cd/flax/linen/attention.py#L252
267
+ """
268
+ # detect if we're initializing by absence of existing cache data.
269
+ is_initialized = self.has_variable("cache", "cached_key")
270
+ cached_key = self.variable("cache", "cached_key", jnp.zeros, key.shape, key.dtype)
271
+ cached_value = self.variable("cache", "cached_value", jnp.zeros, value.shape, value.dtype)
272
+ cache_index = self.variable("cache", "cache_index", lambda: jnp.array(0, dtype=jnp.int32))
273
+
274
+ if is_initialized:
275
+ *batch_dims, max_length, num_heads, depth_per_head = cached_key.value.shape
276
+ # update key, value caches with our new 1d spatial slices
277
+ cur_index = cache_index.value
278
+ indices = (0,) * len(batch_dims) + (cur_index, 0, 0)
279
+ key = lax.dynamic_update_slice(cached_key.value, key, indices)
280
+ value = lax.dynamic_update_slice(cached_value.value, value, indices)
281
+ cached_key.value = key
282
+ cached_value.value = value
283
+ num_updated_cache_vectors = query.shape[1]
284
+ cache_index.value = cache_index.value + num_updated_cache_vectors
285
+ # causal mask for cached decoder self-attention: our single query position should only attend to those key positions that have already been generated and cached, not the remaining zero elements.
286
+ pad_mask = jnp.broadcast_to(
287
+ jnp.arange(max_length) < cur_index + num_updated_cache_vectors,
288
+ tuple(batch_dims) + (1, num_updated_cache_vectors, max_length),
289
+ )
290
+ attention_mask = combine_masks(pad_mask, attention_mask)
291
+ return key, value, attention_mask
292
+
293
+ def __call__(
294
+ self,
295
+ hidden_states: jnp.ndarray,
296
+ key_value_states: Optional[jnp.ndarray] = None,
297
+ attention_mask: Optional[jnp.ndarray] = None,
298
+ init_cache: bool = False,
299
+ deterministic: bool = True,
300
+ ) -> Tuple[jnp.ndarray]:
301
+ """Input shape: Batch x Time x Channel"""
302
+
303
+ # if key_value_states are provided this layer is used as a cross-attention layer
304
+ # for the decoder
305
+ is_cross_attention = key_value_states is not None
306
+ batch_size = hidden_states.shape[0]
307
+
308
+ # get query proj
309
+ query_states = self.q_proj(hidden_states)
310
+ # get key, value proj
311
+ if is_cross_attention:
312
+ # cross_attentions
313
+ key_states = self.k_proj(key_value_states)
314
+ value_states = self.v_proj(key_value_states)
315
+ else:
316
+ # self_attention
317
+ key_states = self.k_proj(hidden_states)
318
+ value_states = self.v_proj(hidden_states)
319
+
320
+ query_states = self._split_heads(query_states)
321
+ key_states = self._split_heads(key_states)
322
+ value_states = self._split_heads(value_states)
323
+
324
+ # handle cache prepare causal attention mask
325
+ if self.causal:
326
+ query_length, key_length = query_states.shape[1], key_states.shape[1]
327
+ if self.has_variable("cache", "cached_key"):
328
+ mask_shift = self.variables["cache"]["cache_index"]
329
+ max_decoder_length = self.variables["cache"]["cached_key"].shape[1]
330
+ causal_mask = lax.dynamic_slice(
331
+ self.causal_mask, (0, 0, mask_shift, 0), (1, 1, query_length, max_decoder_length)
332
+ )
333
+ else:
334
+ causal_mask = self.causal_mask[:, :, :query_length, :key_length]
335
+ causal_mask = jnp.broadcast_to(causal_mask, (batch_size,) + causal_mask.shape[1:])
336
+
337
+ # combine masks if needed
338
+ if attention_mask is not None and self.causal:
339
+ attention_mask = jnp.broadcast_to(jnp.expand_dims(attention_mask, axis=(-3, -2)), causal_mask.shape)
340
+ attention_mask = combine_masks(attention_mask, causal_mask)
341
+ elif self.causal:
342
+ attention_mask = causal_mask
343
+ elif attention_mask is not None:
344
+ attention_mask = jnp.expand_dims(attention_mask, axis=(-3, -2))
345
+
346
+ # During fast autoregressive decoding, we feed one position at a time,
347
+ # and cache the keys and values step by step.
348
+ if self.causal and (self.has_variable("cache", "cached_key") or init_cache):
349
+ key_states, value_states, attention_mask = self._concatenate_to_cache(
350
+ key_states, value_states, query_states, attention_mask
351
+ )
352
+
353
+ # Convert the boolean attention mask to an attention bias.
354
+ if attention_mask is not None:
355
+ # attention mask in the form of attention bias
356
+ attention_bias = lax.select(
357
+ attention_mask > 0,
358
+ jnp.full(attention_mask.shape, 0.0).astype(self.dtype),
359
+ jnp.full(attention_mask.shape, jnp.finfo(self.dtype).min).astype(self.dtype),
360
+ )
361
+ else:
362
+ attention_bias = None
363
+
364
+ dropout_rng = None
365
+ if not deterministic and self.dropout > 0.0:
366
+ dropout_rng = self.make_rng("dropout")
367
+
368
+ attn_weights = dot_product_attention_weights(
369
+ query_states,
370
+ key_states,
371
+ bias=attention_bias,
372
+ dropout_rng=dropout_rng,
373
+ dropout_rate=self.dropout,
374
+ broadcast_dropout=True,
375
+ deterministic=deterministic,
376
+ dtype=self.dtype,
377
+ precision=None,
378
+ )
379
+
380
+ attn_output = jnp.einsum("...hqk,...khd->...qhd", attn_weights, value_states)
381
+ attn_output = self._merge_heads(attn_output)
382
+ attn_output = self.out_proj(attn_output)
383
+
384
+ return attn_output, attn_weights
385
+
386
+
387
+ # Copied from transformers.models.mbart.modeling_flax_mbart.FlaxMBartEncoderLayer with MBart->Blenderbot
388
+ class FlaxBlenderbotEncoderLayer(nn.Module):
389
+ config: BlenderbotConfig
390
+ dtype: jnp.dtype = jnp.float32
391
+
392
+ def setup(self) -> None:
393
+ self.embed_dim = self.config.d_model
394
+ self.self_attn = FlaxBlenderbotAttention(
395
+ config=self.config,
396
+ embed_dim=self.embed_dim,
397
+ num_heads=self.config.encoder_attention_heads,
398
+ dropout=self.config.attention_dropout,
399
+ dtype=self.dtype,
400
+ )
401
+ self.self_attn_layer_norm = nn.LayerNorm(dtype=self.dtype, epsilon=1e-05)
402
+ self.dropout_layer = nn.Dropout(rate=self.config.dropout)
403
+ self.activation_fn = ACT2FN[self.config.activation_function]
404
+ self.activation_dropout_layer = nn.Dropout(rate=self.config.activation_dropout)
405
+ self.fc1 = nn.Dense(
406
+ self.config.encoder_ffn_dim,
407
+ dtype=self.dtype,
408
+ kernel_init=jax.nn.initializers.normal(self.config.init_std),
409
+ )
410
+ self.fc2 = nn.Dense(
411
+ self.embed_dim, dtype=self.dtype, kernel_init=jax.nn.initializers.normal(self.config.init_std)
412
+ )
413
+ self.final_layer_norm = nn.LayerNorm(dtype=self.dtype, epsilon=1e-05)
414
+
415
+ def __call__(
416
+ self,
417
+ hidden_states: jnp.ndarray,
418
+ attention_mask: jnp.ndarray,
419
+ output_attentions: bool = True,
420
+ deterministic: bool = True,
421
+ ) -> Tuple[jnp.ndarray]:
422
+ residual = hidden_states
423
+ hidden_states = self.self_attn_layer_norm(hidden_states)
424
+ hidden_states, attn_weights = self.self_attn(hidden_states=hidden_states, attention_mask=attention_mask)
425
+ hidden_states = self.dropout_layer(hidden_states, deterministic=deterministic)
426
+ hidden_states = residual + hidden_states
427
+
428
+ residual = hidden_states
429
+ hidden_states = self.final_layer_norm(hidden_states)
430
+ hidden_states = self.activation_fn(self.fc1(hidden_states))
431
+ hidden_states = self.activation_dropout_layer(hidden_states, deterministic=deterministic)
432
+ hidden_states = self.fc2(hidden_states)
433
+ hidden_states = self.dropout_layer(hidden_states, deterministic=deterministic)
434
+ hidden_states = residual + hidden_states
435
+
436
+ outputs = (hidden_states,)
437
+
438
+ if output_attentions:
439
+ outputs += (attn_weights,)
440
+
441
+ return outputs
442
+
443
+
444
+ # Copied from transformers.models.bart.modeling_flax_bart.FlaxBartEncoderLayerCollection with Bart->Blenderbot
445
+ class FlaxBlenderbotEncoderLayerCollection(nn.Module):
446
+ config: BlenderbotConfig
447
+ dtype: jnp.dtype = jnp.float32 # the dtype of the computation
448
+
449
+ def setup(self):
450
+ self.layers = [
451
+ FlaxBlenderbotEncoderLayer(self.config, name=str(i), dtype=self.dtype)
452
+ for i in range(self.config.encoder_layers)
453
+ ]
454
+ self.layerdrop = self.config.encoder_layerdrop
455
+
456
+ def __call__(
457
+ self,
458
+ hidden_states,
459
+ attention_mask,
460
+ deterministic: bool = True,
461
+ output_attentions: bool = False,
462
+ output_hidden_states: bool = False,
463
+ return_dict: bool = True,
464
+ ):
465
+ all_attentions = () if output_attentions else None
466
+ all_hidden_states = () if output_hidden_states else None
467
+
468
+ for encoder_layer in self.layers:
469
+ if output_hidden_states:
470
+ all_hidden_states = all_hidden_states + (hidden_states,)
471
+ # add LayerDrop (see https://arxiv.org/abs/1909.11556 for description)
472
+ dropout_probability = random.uniform(0, 1)
473
+ if not deterministic and (dropout_probability < self.layerdrop): # skip the layer
474
+ layer_outputs = (None, None)
475
+ else:
476
+ layer_outputs = encoder_layer(
477
+ hidden_states,
478
+ attention_mask,
479
+ output_attentions,
480
+ deterministic,
481
+ )
482
+ hidden_states = layer_outputs[0]
483
+ if output_attentions:
484
+ all_attentions = all_attentions + (layer_outputs[1],)
485
+
486
+ if output_hidden_states:
487
+ all_hidden_states += (hidden_states,)
488
+
489
+ outputs = (hidden_states, all_hidden_states, all_attentions)
490
+
491
+ if not return_dict:
492
+ return tuple(v for v in outputs if v is not None)
493
+
494
+ return FlaxBaseModelOutput(
495
+ last_hidden_state=hidden_states, hidden_states=all_hidden_states, attentions=all_attentions
496
+ )
497
+
498
+
499
+ # Copied from transformers.models.mbart.modeling_flax_mbart.FlaxMBartDecoderLayer with MBart->Blenderbot
500
+ class FlaxBlenderbotDecoderLayer(nn.Module):
501
+ config: BlenderbotConfig
502
+ dtype: jnp.dtype = jnp.float32
503
+
504
+ def setup(self) -> None:
505
+ self.embed_dim = self.config.d_model
506
+ self.self_attn = FlaxBlenderbotAttention(
507
+ config=self.config,
508
+ embed_dim=self.embed_dim,
509
+ num_heads=self.config.decoder_attention_heads,
510
+ dropout=self.config.attention_dropout,
511
+ causal=True,
512
+ dtype=self.dtype,
513
+ )
514
+ self.dropout_layer = nn.Dropout(rate=self.config.dropout)
515
+ self.activation_fn = ACT2FN[self.config.activation_function]
516
+ self.activation_dropout_layer = nn.Dropout(rate=self.config.activation_dropout)
517
+
518
+ self.self_attn_layer_norm = nn.LayerNorm(dtype=self.dtype, epsilon=1e-05)
519
+ self.encoder_attn = FlaxBlenderbotAttention(
520
+ config=self.config,
521
+ embed_dim=self.embed_dim,
522
+ num_heads=self.config.decoder_attention_heads,
523
+ dropout=self.config.attention_dropout,
524
+ dtype=self.dtype,
525
+ )
526
+ self.encoder_attn_layer_norm = nn.LayerNorm(dtype=self.dtype, epsilon=1e-05)
527
+ self.fc1 = nn.Dense(
528
+ self.config.decoder_ffn_dim,
529
+ dtype=self.dtype,
530
+ kernel_init=jax.nn.initializers.normal(self.config.init_std),
531
+ )
532
+ self.fc2 = nn.Dense(
533
+ self.embed_dim, dtype=self.dtype, kernel_init=jax.nn.initializers.normal(self.config.init_std)
534
+ )
535
+ self.final_layer_norm = nn.LayerNorm(dtype=self.dtype, epsilon=1e-05)
536
+
537
+ def __call__(
538
+ self,
539
+ hidden_states: jnp.ndarray,
540
+ attention_mask: jnp.ndarray,
541
+ encoder_hidden_states: Optional[jnp.ndarray] = None,
542
+ encoder_attention_mask: Optional[jnp.ndarray] = None,
543
+ init_cache: bool = False,
544
+ output_attentions: bool = True,
545
+ deterministic: bool = True,
546
+ ) -> Tuple[jnp.ndarray]:
547
+ residual = hidden_states
548
+ hidden_states = self.self_attn_layer_norm(hidden_states)
549
+
550
+ # Self Attention
551
+ hidden_states, self_attn_weights = self.self_attn(
552
+ hidden_states=hidden_states, attention_mask=attention_mask, init_cache=init_cache
553
+ )
554
+ hidden_states = self.dropout_layer(hidden_states, deterministic=deterministic)
555
+ hidden_states = residual + hidden_states
556
+
557
+ # Cross-Attention Block
558
+ cross_attn_weights = None
559
+ if encoder_hidden_states is not None:
560
+ residual = hidden_states
561
+
562
+ hidden_states = self.encoder_attn_layer_norm(hidden_states)
563
+ hidden_states, cross_attn_weights = self.encoder_attn(
564
+ hidden_states=hidden_states,
565
+ key_value_states=encoder_hidden_states,
566
+ attention_mask=encoder_attention_mask,
567
+ )
568
+ hidden_states = self.dropout_layer(hidden_states, deterministic=deterministic)
569
+ hidden_states = residual + hidden_states
570
+
571
+ # Fully Connected
572
+ residual = hidden_states
573
+ hidden_states = self.final_layer_norm(hidden_states)
574
+ hidden_states = self.activation_fn(self.fc1(hidden_states))
575
+ hidden_states = self.activation_dropout_layer(hidden_states, deterministic=deterministic)
576
+ hidden_states = self.fc2(hidden_states)
577
+ hidden_states = self.dropout_layer(hidden_states, deterministic=deterministic)
578
+ hidden_states = residual + hidden_states
579
+
580
+ outputs = (hidden_states,)
581
+
582
+ if output_attentions:
583
+ outputs += (self_attn_weights, cross_attn_weights)
584
+
585
+ return outputs
586
+
587
+
588
+ # Copied from transformers.models.bart.modeling_flax_bart.FlaxBartDecoderLayerCollection with Bart->Blenderbot
589
+ class FlaxBlenderbotDecoderLayerCollection(nn.Module):
590
+ config: BlenderbotConfig
591
+ dtype: jnp.dtype = jnp.float32 # the dtype of the computation
592
+
593
+ def setup(self):
594
+ self.layers = [
595
+ FlaxBlenderbotDecoderLayer(self.config, name=str(i), dtype=self.dtype)
596
+ for i in range(self.config.decoder_layers)
597
+ ]
598
+ self.layerdrop = self.config.decoder_layerdrop
599
+
600
+ def __call__(
601
+ self,
602
+ hidden_states,
603
+ attention_mask,
604
+ encoder_hidden_states: Optional[jnp.ndarray] = None,
605
+ encoder_attention_mask: Optional[jnp.ndarray] = None,
606
+ deterministic: bool = True,
607
+ init_cache: bool = False,
608
+ output_attentions: bool = False,
609
+ output_hidden_states: bool = False,
610
+ return_dict: bool = True,
611
+ ):
612
+ # decoder layers
613
+ all_hidden_states = () if output_hidden_states else None
614
+ all_self_attns = () if output_attentions else None
615
+ all_cross_attentions = () if (output_attentions and encoder_hidden_states is not None) else None
616
+
617
+ for decoder_layer in self.layers:
618
+ if output_hidden_states:
619
+ all_hidden_states += (hidden_states,)
620
+ # add LayerDrop (see https://arxiv.org/abs/1909.11556 for description)
621
+ dropout_probability = random.uniform(0, 1)
622
+ if not deterministic and (dropout_probability < self.layerdrop):
623
+ layer_outputs = (None, None, None)
624
+ else:
625
+ layer_outputs = decoder_layer(
626
+ hidden_states,
627
+ attention_mask=attention_mask,
628
+ encoder_hidden_states=encoder_hidden_states,
629
+ encoder_attention_mask=encoder_attention_mask,
630
+ init_cache=init_cache,
631
+ output_attentions=output_attentions,
632
+ deterministic=deterministic,
633
+ )
634
+
635
+ hidden_states = layer_outputs[0]
636
+ if output_attentions:
637
+ all_self_attns += (layer_outputs[1],)
638
+
639
+ if encoder_hidden_states is not None:
640
+ all_cross_attentions += (layer_outputs[2],)
641
+
642
+ # add hidden states from the last decoder layer
643
+ if output_hidden_states:
644
+ all_hidden_states += (hidden_states,)
645
+
646
+ outputs = [hidden_states, all_hidden_states, all_self_attns, all_cross_attentions]
647
+
648
+ if not return_dict:
649
+ return tuple(v for v in outputs if v is not None)
650
+
651
+ return FlaxBaseModelOutputWithPastAndCrossAttentions(
652
+ last_hidden_state=hidden_states,
653
+ hidden_states=all_hidden_states,
654
+ attentions=all_self_attns,
655
+ cross_attentions=all_cross_attentions,
656
+ )
657
+
658
+
659
+ class FlaxBlenderbotEncoder(nn.Module):
660
+ config: BlenderbotConfig
661
+ embed_tokens: nn.Embed
662
+ dtype: jnp.dtype = jnp.float32 # the dtype of the computation
663
+
664
+ def setup(self):
665
+ self.dropout_layer = nn.Dropout(rate=self.config.dropout)
666
+
667
+ embed_dim = self.config.d_model
668
+ self.padding_idx = self.config.pad_token_id
669
+ self.max_source_positions = self.config.max_position_embeddings
670
+ self.embed_scale = math.sqrt(embed_dim) if self.config.scale_embedding else 1.0
671
+
672
+ self.embed_positions = nn.Embed(
673
+ self.config.max_position_embeddings,
674
+ embed_dim,
675
+ embedding_init=jax.nn.initializers.normal(self.config.init_std),
676
+ )
677
+ self.layers = FlaxBlenderbotEncoderLayerCollection(self.config, self.dtype)
678
+ self.layer_norm = nn.LayerNorm(dtype=self.dtype, epsilon=1e-05)
679
+
680
+ def __call__(
681
+ self,
682
+ input_ids,
683
+ attention_mask,
684
+ position_ids,
685
+ output_attentions: bool = False,
686
+ output_hidden_states: bool = False,
687
+ return_dict: bool = True,
688
+ deterministic: bool = True,
689
+ ):
690
+ input_shape = input_ids.shape
691
+ input_ids = input_ids.reshape(-1, input_shape[-1])
692
+
693
+ inputs_embeds = self.embed_tokens(input_ids) * self.embed_scale
694
+
695
+ embed_pos = self.embed_positions(position_ids)
696
+
697
+ hidden_states = inputs_embeds + embed_pos
698
+ hidden_states = self.dropout_layer(hidden_states, deterministic=deterministic)
699
+
700
+ outputs = self.layers(
701
+ hidden_states,
702
+ attention_mask,
703
+ deterministic=deterministic,
704
+ output_attentions=output_attentions,
705
+ output_hidden_states=output_hidden_states,
706
+ return_dict=return_dict,
707
+ )
708
+ last_hidden_states = outputs[0]
709
+ last_hidden_states = self.layer_norm(last_hidden_states)
710
+
711
+ # update the last element in `hidden_states` after applying `layernorm` above
712
+ hidden_states = None
713
+ if output_hidden_states:
714
+ hidden_states = outputs[1]
715
+ hidden_states = hidden_states[:-1] + (last_hidden_states,)
716
+
717
+ if not return_dict:
718
+ outputs = (last_hidden_states, hidden_states) + (outputs[2:] if output_hidden_states else outputs[1:])
719
+ return tuple(v for v in outputs if v is not None)
720
+
721
+ return FlaxBaseModelOutput(
722
+ last_hidden_state=last_hidden_states,
723
+ hidden_states=hidden_states,
724
+ attentions=outputs.attentions,
725
+ )
726
+
727
+
728
+ class FlaxBlenderbotDecoder(nn.Module):
729
+ config: BlenderbotConfig
730
+ embed_tokens: nn.Embed
731
+ dtype: jnp.dtype = jnp.float32 # the dtype of the computation
732
+
733
+ def setup(self):
734
+ self.dropout_layer = nn.Dropout(rate=self.config.dropout)
735
+
736
+ embed_dim = self.config.d_model
737
+ self.padding_idx = self.config.pad_token_id
738
+ self.max_target_positions = self.config.max_position_embeddings
739
+ self.embed_scale = math.sqrt(self.config.d_model) if self.config.scale_embedding else 1.0
740
+
741
+ self.embed_positions = nn.Embed(
742
+ self.config.max_position_embeddings,
743
+ embed_dim,
744
+ embedding_init=jax.nn.initializers.normal(self.config.init_std),
745
+ )
746
+
747
+ self.layers = FlaxBlenderbotDecoderLayerCollection(self.config, self.dtype)
748
+ self.layer_norm = nn.LayerNorm(dtype=self.dtype, epsilon=1e-05)
749
+
750
+ def __call__(
751
+ self,
752
+ input_ids,
753
+ attention_mask,
754
+ position_ids,
755
+ encoder_hidden_states: Optional[jnp.ndarray] = None,
756
+ encoder_attention_mask: Optional[jnp.ndarray] = None,
757
+ init_cache: bool = False,
758
+ output_attentions: bool = False,
759
+ output_hidden_states: bool = False,
760
+ return_dict: bool = True,
761
+ deterministic: bool = True,
762
+ ):
763
+ input_shape = input_ids.shape
764
+ input_ids = input_ids.reshape(-1, input_shape[-1])
765
+
766
+ inputs_embeds = self.embed_tokens(input_ids) * self.embed_scale
767
+
768
+ # embed positions
769
+ positions = self.embed_positions(position_ids)
770
+
771
+ hidden_states = inputs_embeds + positions
772
+ hidden_states = self.dropout_layer(hidden_states, deterministic=deterministic)
773
+
774
+ outputs = self.layers(
775
+ hidden_states,
776
+ attention_mask,
777
+ encoder_hidden_states,
778
+ encoder_attention_mask,
779
+ deterministic=deterministic,
780
+ init_cache=init_cache,
781
+ output_attentions=output_attentions,
782
+ output_hidden_states=output_hidden_states,
783
+ return_dict=return_dict,
784
+ )
785
+
786
+ last_hidden_states = outputs[0]
787
+ last_hidden_states = self.layer_norm(last_hidden_states)
788
+
789
+ # update the last element in `hidden_states` after applying `layernorm` above
790
+ hidden_states = None
791
+ if output_hidden_states:
792
+ hidden_states = outputs[1]
793
+ hidden_states = hidden_states[:-1] + (last_hidden_states,)
794
+
795
+ if not return_dict:
796
+ outputs = (last_hidden_states, hidden_states) + (outputs[2:] if output_hidden_states else outputs[1:])
797
+ return tuple(v for v in outputs if v is not None)
798
+
799
+ return FlaxBaseModelOutputWithPastAndCrossAttentions(
800
+ last_hidden_state=last_hidden_states,
801
+ hidden_states=hidden_states,
802
+ attentions=outputs.attentions,
803
+ cross_attentions=outputs.cross_attentions,
804
+ )
805
+
806
+
807
+ # Copied from transformers.models.bart.modeling_flax_bart.FlaxBartModule with Bart->Blenderbot
808
+ class FlaxBlenderbotModule(nn.Module):
809
+ config: BlenderbotConfig
810
+ dtype: jnp.dtype = jnp.float32 # the dtype of the computation
811
+
812
+ def setup(self):
813
+ self.shared = nn.Embed(
814
+ self.config.vocab_size,
815
+ self.config.d_model,
816
+ embedding_init=jax.nn.initializers.normal(self.config.init_std),
817
+ dtype=self.dtype,
818
+ )
819
+
820
+ self.encoder = FlaxBlenderbotEncoder(self.config, dtype=self.dtype, embed_tokens=self.shared)
821
+ self.decoder = FlaxBlenderbotDecoder(self.config, dtype=self.dtype, embed_tokens=self.shared)
822
+
823
+ def _get_encoder_module(self):
824
+ return self.encoder
825
+
826
+ def _get_decoder_module(self):
827
+ return self.decoder
828
+
829
+ def __call__(
830
+ self,
831
+ input_ids,
832
+ attention_mask,
833
+ decoder_input_ids,
834
+ decoder_attention_mask,
835
+ position_ids,
836
+ decoder_position_ids,
837
+ output_attentions: bool = False,
838
+ output_hidden_states: bool = False,
839
+ return_dict: bool = True,
840
+ deterministic: bool = True,
841
+ ):
842
+ encoder_outputs = self.encoder(
843
+ input_ids=input_ids,
844
+ attention_mask=attention_mask,
845
+ position_ids=position_ids,
846
+ output_attentions=output_attentions,
847
+ output_hidden_states=output_hidden_states,
848
+ return_dict=return_dict,
849
+ deterministic=deterministic,
850
+ )
851
+
852
+ decoder_outputs = self.decoder(
853
+ input_ids=decoder_input_ids,
854
+ attention_mask=decoder_attention_mask,
855
+ position_ids=decoder_position_ids,
856
+ encoder_hidden_states=encoder_outputs[0],
857
+ encoder_attention_mask=attention_mask,
858
+ output_attentions=output_attentions,
859
+ output_hidden_states=output_hidden_states,
860
+ return_dict=return_dict,
861
+ deterministic=deterministic,
862
+ )
863
+
864
+ if not return_dict:
865
+ return decoder_outputs + encoder_outputs
866
+
867
+ return FlaxSeq2SeqModelOutput(
868
+ last_hidden_state=decoder_outputs.last_hidden_state,
869
+ decoder_hidden_states=decoder_outputs.hidden_states,
870
+ decoder_attentions=decoder_outputs.attentions,
871
+ cross_attentions=decoder_outputs.cross_attentions,
872
+ encoder_last_hidden_state=encoder_outputs.last_hidden_state,
873
+ encoder_hidden_states=encoder_outputs.hidden_states,
874
+ encoder_attentions=encoder_outputs.attentions,
875
+ )
876
+
877
+
878
+ class FlaxBlenderbotPreTrainedModel(FlaxPreTrainedModel):
879
+ config_class = BlenderbotConfig
880
+ base_model_prefix: str = "model"
881
+ module_class: nn.Module = None
882
+
883
+ def __init__(
884
+ self,
885
+ config: BlenderbotConfig,
886
+ input_shape: Tuple[int] = (1, 1),
887
+ seed: int = 0,
888
+ dtype: jnp.dtype = jnp.float32,
889
+ _do_init: bool = True,
890
+ **kwargs,
891
+ ):
892
+ module = self.module_class(config=config, dtype=dtype, **kwargs)
893
+ super().__init__(config, module, input_shape=input_shape, seed=seed, dtype=dtype, _do_init=_do_init)
894
+
895
+ def init_weights(self, rng: jax.random.PRNGKey, input_shape: Tuple, params: FrozenDict = None) -> FrozenDict:
896
+ # init input tensors
897
+ input_ids = jnp.zeros(input_shape, dtype="i4")
898
+ # make sure initialization pass will work for FlaxBlenderbotForSequenceClassificationModule
899
+ input_ids = input_ids.at[(..., -1)].set(self.config.eos_token_id)
900
+ attention_mask = jnp.ones_like(input_ids)
901
+ decoder_input_ids = input_ids
902
+ decoder_attention_mask = jnp.ones_like(input_ids)
903
+
904
+ batch_size, sequence_length = input_ids.shape
905
+ position_ids = jnp.broadcast_to(jnp.arange(sequence_length)[None, :], (batch_size, sequence_length))
906
+ decoder_position_ids = jnp.broadcast_to(jnp.arange(sequence_length)[None, :], (batch_size, sequence_length))
907
+
908
+ params_rng, dropout_rng = jax.random.split(rng)
909
+ rngs = {"params": params_rng, "dropout": dropout_rng}
910
+
911
+ random_params = self.module.init(
912
+ rngs,
913
+ input_ids,
914
+ attention_mask,
915
+ decoder_input_ids,
916
+ decoder_attention_mask,
917
+ position_ids,
918
+ decoder_position_ids,
919
+ )["params"]
920
+
921
+ if params is not None:
922
+ random_params = flatten_dict(unfreeze(random_params))
923
+ params = flatten_dict(unfreeze(params))
924
+ for missing_key in self._missing_keys:
925
+ params[missing_key] = random_params[missing_key]
926
+ self._missing_keys = set()
927
+ return freeze(unflatten_dict(params))
928
+ else:
929
+ return random_params
930
+
931
+ def init_cache(self, batch_size, max_length, encoder_outputs):
932
+ r"""
933
+ Args:
934
+ batch_size (`int`):
935
+ batch_size used for fast auto-regressive decoding. Defines the batch size of the initialized cache.
936
+ max_length (`int`):
937
+ maximum possible length for auto-regressive decoding. Defines the sequence length of the initialized
938
+ cache.
939
+ encoder_outputs (`Union[FlaxBaseModelOutput, tuple(tuple(jnp.ndarray)]`):
940
+ `encoder_outputs` consists of (`last_hidden_state`, *optional*: `hidden_states`, *optional*:
941
+ `attentions`). `last_hidden_state` of shape `(batch_size, sequence_length, hidden_size)`, *optional*)
942
+ is a sequence of hidden-states at the output of the last layer of the encoder. Used in the
943
+ cross-attention of the decoder.
944
+ """
945
+ # init input variables to retrieve cache
946
+ decoder_input_ids = jnp.ones((batch_size, max_length), dtype="i4")
947
+ decoder_attention_mask = jnp.ones_like(decoder_input_ids)
948
+ decoder_position_ids = jnp.broadcast_to(
949
+ jnp.arange(jnp.atleast_2d(decoder_input_ids).shape[-1]), decoder_input_ids.shape
950
+ )
951
+
952
+ def _decoder_forward(module, decoder_input_ids, decoder_attention_mask, decoder_position_ids, **kwargs):
953
+ decoder_module = module._get_decoder_module()
954
+ return decoder_module(
955
+ decoder_input_ids,
956
+ decoder_attention_mask,
957
+ decoder_position_ids,
958
+ **kwargs,
959
+ )
960
+
961
+ init_variables = self.module.init(
962
+ jax.random.PRNGKey(0),
963
+ decoder_input_ids=decoder_input_ids,
964
+ decoder_attention_mask=decoder_attention_mask,
965
+ decoder_position_ids=decoder_position_ids,
966
+ encoder_hidden_states=encoder_outputs[0],
967
+ init_cache=True,
968
+ method=_decoder_forward, # we only need to call the decoder to init the cache
969
+ )
970
+ return unfreeze(init_variables["cache"])
971
+
972
+ @add_start_docstrings(BLENDERBOT_ENCODE_INPUTS_DOCSTRING)
973
+ @replace_return_docstrings(output_type=FlaxBaseModelOutput, config_class=BlenderbotConfig)
974
+ def encode(
975
+ self,
976
+ input_ids: jnp.ndarray,
977
+ attention_mask: Optional[jnp.ndarray] = None,
978
+ position_ids: Optional[jnp.ndarray] = None,
979
+ output_attentions: Optional[bool] = None,
980
+ output_hidden_states: Optional[bool] = None,
981
+ return_dict: Optional[bool] = None,
982
+ train: bool = False,
983
+ params: dict = None,
984
+ dropout_rng: PRNGKey = None,
985
+ ):
986
+ r"""
987
+ Returns:
988
+
989
+ Example:
990
+
991
+ ```python
992
+ >>> from transformers import AutoTokenizer, FlaxBlenderbotForConditionalGeneration
993
+
994
+ >>> model = FlaxBlenderbotForConditionalGeneration.from_pretrained("facebook/blenderbot-400M-distill")
995
+ >>> tokenizer = AutoTokenizer.from_pretrained("facebook/blenderbot-400M-distill")
996
+
997
+ >>> text = "My friends are cool but they eat too many carbs."
998
+ >>> inputs = tokenizer(text, max_length=1024, return_tensors="jax")
999
+ >>> encoder_outputs = model.encode(**inputs)
1000
+ ```"""
1001
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1002
+ output_hidden_states = (
1003
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1004
+ )
1005
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
1006
+
1007
+ if attention_mask is None:
1008
+ attention_mask = jnp.ones_like(input_ids)
1009
+ if position_ids is None:
1010
+ batch_size, sequence_length = input_ids.shape
1011
+ position_ids = jnp.broadcast_to(jnp.arange(sequence_length)[None, :], (batch_size, sequence_length))
1012
+
1013
+ # Handle any PRNG if needed
1014
+ rngs = {}
1015
+ if dropout_rng is not None:
1016
+ rngs["dropout"] = dropout_rng
1017
+
1018
+ def _encoder_forward(module, input_ids, attention_mask, position_ids, **kwargs):
1019
+ encode_module = module._get_encoder_module()
1020
+ return encode_module(input_ids, attention_mask, position_ids, **kwargs)
1021
+
1022
+ return self.module.apply(
1023
+ {"params": params or self.params},
1024
+ input_ids=jnp.array(input_ids, dtype="i4"),
1025
+ attention_mask=jnp.array(attention_mask, dtype="i4"),
1026
+ position_ids=jnp.array(position_ids, dtype="i4"),
1027
+ output_attentions=output_attentions,
1028
+ output_hidden_states=output_hidden_states,
1029
+ return_dict=return_dict,
1030
+ deterministic=not train,
1031
+ rngs=rngs,
1032
+ method=_encoder_forward,
1033
+ )
1034
+
1035
+ @add_start_docstrings(BLENDERBOT_DECODE_INPUTS_DOCSTRING)
1036
+ @replace_return_docstrings(
1037
+ output_type=FlaxBaseModelOutputWithPastAndCrossAttentions, config_class=BlenderbotConfig
1038
+ )
1039
+ def decode(
1040
+ self,
1041
+ decoder_input_ids,
1042
+ encoder_outputs,
1043
+ encoder_attention_mask: Optional[jnp.ndarray] = None,
1044
+ decoder_attention_mask: Optional[jnp.ndarray] = None,
1045
+ decoder_position_ids: Optional[jnp.ndarray] = None,
1046
+ past_key_values: dict = None,
1047
+ output_attentions: Optional[bool] = None,
1048
+ output_hidden_states: Optional[bool] = None,
1049
+ return_dict: Optional[bool] = None,
1050
+ train: bool = False,
1051
+ params: dict = None,
1052
+ dropout_rng: PRNGKey = None,
1053
+ ):
1054
+ r"""
1055
+ Returns:
1056
+
1057
+ Example:
1058
+
1059
+ ```python
1060
+ >>> import jax.numpy as jnp
1061
+ >>> from transformers import AutoTokenizer, FlaxBlenderbotForConditionalGeneration
1062
+
1063
+ >>> model = FlaxBlenderbotForConditionalGeneration.from_pretrained("facebook/blenderbot-400M-distill")
1064
+ >>> tokenizer = AutoTokenizer.from_pretrained("facebook/blenderbot-400M-distill")
1065
+
1066
+ >>> text = "My friends are cool but they eat too many carbs."
1067
+ >>> inputs = tokenizer(text, max_length=1024, return_tensors="jax")
1068
+ >>> encoder_outputs = model.encode(**inputs)
1069
+
1070
+ >>> decoder_start_token_id = model.config.decoder_start_token_id
1071
+ >>> decoder_input_ids = jnp.ones((inputs.input_ids.shape[0], 1), dtype="i4") * decoder_start_token_id
1072
+
1073
+ >>> outputs = model.decode(decoder_input_ids, encoder_outputs)
1074
+ >>> last_decoder_hidden_states = outputs.last_hidden_state
1075
+ ```"""
1076
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1077
+ output_hidden_states = (
1078
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1079
+ )
1080
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
1081
+
1082
+ encoder_hidden_states = encoder_outputs[0]
1083
+ if encoder_attention_mask is None:
1084
+ batch_size, sequence_length = encoder_hidden_states.shape[:2]
1085
+ encoder_attention_mask = jnp.ones((batch_size, sequence_length))
1086
+
1087
+ batch_size, sequence_length = decoder_input_ids.shape
1088
+ if decoder_attention_mask is None:
1089
+ decoder_attention_mask = jnp.ones((batch_size, sequence_length))
1090
+
1091
+ if decoder_position_ids is None:
1092
+ if past_key_values is not None:
1093
+ raise ValueError("Make sure to provide `decoder_position_ids` when passing `past_key_values`.")
1094
+
1095
+ decoder_position_ids = jnp.broadcast_to(
1096
+ jnp.arange(sequence_length)[None, :], (batch_size, sequence_length)
1097
+ )
1098
+
1099
+ # Handle any PRNG if needed
1100
+ rngs = {}
1101
+ if dropout_rng is not None:
1102
+ rngs["dropout"] = dropout_rng
1103
+
1104
+ inputs = {"params": params or self.params}
1105
+
1106
+ # if past_key_values are passed then cache is already initialized a private flag init_cache has to be
1107
+ # passed down to ensure cache is used. It has to be made sure that cache is marked as mutable so that
1108
+ # it can be changed by FlaxBlenderbotAttention module
1109
+ if past_key_values:
1110
+ inputs["cache"] = past_key_values
1111
+ mutable = ["cache"]
1112
+ else:
1113
+ mutable = False
1114
+
1115
+ def _decoder_forward(module, decoder_input_ids, decoder_attention_mask, decoder_position_ids, **kwargs):
1116
+ decoder_module = module._get_decoder_module()
1117
+ return decoder_module(
1118
+ decoder_input_ids,
1119
+ decoder_attention_mask,
1120
+ decoder_position_ids,
1121
+ **kwargs,
1122
+ )
1123
+
1124
+ outputs = self.module.apply(
1125
+ inputs,
1126
+ decoder_input_ids=jnp.array(decoder_input_ids, dtype="i4"),
1127
+ decoder_attention_mask=jnp.array(decoder_attention_mask, dtype="i4"),
1128
+ decoder_position_ids=jnp.array(decoder_position_ids, dtype="i4"),
1129
+ encoder_hidden_states=encoder_hidden_states,
1130
+ encoder_attention_mask=jnp.array(encoder_attention_mask, dtype="i4"),
1131
+ output_attentions=output_attentions,
1132
+ output_hidden_states=output_hidden_states,
1133
+ return_dict=return_dict,
1134
+ deterministic=not train,
1135
+ rngs=rngs,
1136
+ mutable=mutable,
1137
+ method=_decoder_forward,
1138
+ )
1139
+
1140
+ # add updated cache to model output
1141
+ if past_key_values is not None and return_dict:
1142
+ outputs, past = outputs
1143
+ outputs["past_key_values"] = unfreeze(past["cache"])
1144
+ return outputs
1145
+ elif past_key_values is not None and not return_dict:
1146
+ outputs, past = outputs
1147
+ outputs = outputs[:1] + (unfreeze(past["cache"]),) + outputs[1:]
1148
+
1149
+ return outputs
1150
+
1151
+ @add_start_docstrings_to_model_forward(BLENDERBOT_INPUTS_DOCSTRING)
1152
+ def __call__(
1153
+ self,
1154
+ input_ids: jnp.ndarray,
1155
+ attention_mask: Optional[jnp.ndarray] = None,
1156
+ decoder_input_ids: Optional[jnp.ndarray] = None,
1157
+ decoder_attention_mask: Optional[jnp.ndarray] = None,
1158
+ position_ids: Optional[jnp.ndarray] = None,
1159
+ decoder_position_ids: Optional[jnp.ndarray] = None,
1160
+ output_attentions: Optional[bool] = None,
1161
+ output_hidden_states: Optional[bool] = None,
1162
+ return_dict: Optional[bool] = None,
1163
+ train: bool = False,
1164
+ params: dict = None,
1165
+ dropout_rng: PRNGKey = None,
1166
+ ):
1167
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1168
+ output_hidden_states = (
1169
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1170
+ )
1171
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
1172
+
1173
+ # prepare encoder inputs
1174
+ if attention_mask is None:
1175
+ attention_mask = jnp.ones_like(input_ids)
1176
+ if position_ids is None:
1177
+ batch_size, sequence_length = input_ids.shape
1178
+ position_ids = jnp.broadcast_to(jnp.arange(sequence_length)[None, :], (batch_size, sequence_length))
1179
+
1180
+ # prepare decoder inputs
1181
+ if decoder_input_ids is None:
1182
+ decoder_input_ids = shift_tokens_right(
1183
+ input_ids, self.config.pad_token_id, decoder_start_token_id=self.config.decoder_start_token_id
1184
+ )
1185
+ if decoder_attention_mask is None:
1186
+ decoder_attention_mask = jnp.ones_like(decoder_input_ids)
1187
+ if decoder_position_ids is None:
1188
+ batch_size, sequence_length = decoder_input_ids.shape
1189
+ decoder_position_ids = jnp.broadcast_to(
1190
+ jnp.arange(sequence_length)[None, :], (batch_size, sequence_length)
1191
+ )
1192
+
1193
+ # Handle any PRNG if needed
1194
+ rngs = {"dropout": dropout_rng} if dropout_rng is not None else {}
1195
+
1196
+ return self.module.apply(
1197
+ {"params": params or self.params},
1198
+ input_ids=jnp.array(input_ids, dtype="i4"),
1199
+ attention_mask=jnp.array(attention_mask, dtype="i4"),
1200
+ position_ids=jnp.array(position_ids, dtype="i4"),
1201
+ decoder_input_ids=jnp.array(decoder_input_ids, dtype="i4"),
1202
+ decoder_attention_mask=jnp.array(decoder_attention_mask, dtype="i4"),
1203
+ decoder_position_ids=jnp.array(decoder_position_ids, dtype="i4"),
1204
+ output_attentions=output_attentions,
1205
+ output_hidden_states=output_hidden_states,
1206
+ return_dict=return_dict,
1207
+ deterministic=not train,
1208
+ rngs=rngs,
1209
+ )
1210
+
1211
+
1212
+ @add_start_docstrings(
1213
+ "The bare MBart Model transformer outputting raw hidden-states without any specific head on top.",
1214
+ BLENDERBOT_START_DOCSTRING,
1215
+ )
1216
+ class FlaxBlenderbotModel(FlaxBlenderbotPreTrainedModel):
1217
+ config: BlenderbotConfig
1218
+ dtype: jnp.dtype = jnp.float32 # the dtype of the computation
1219
+ module_class = FlaxBlenderbotModule
1220
+
1221
+
1222
+ append_call_sample_docstring(FlaxBlenderbotModel, _CHECKPOINT_FOR_DOC, FlaxSeq2SeqModelOutput, _CONFIG_FOR_DOC)
1223
+
1224
+
1225
+ # Copied from transformers.models.bart.modeling_flax_bart.FlaxBartForConditionalGenerationModule with Bart->Blenderbot
1226
+ class FlaxBlenderbotForConditionalGenerationModule(nn.Module):
1227
+ config: BlenderbotConfig
1228
+ dtype: jnp.dtype = jnp.float32
1229
+ bias_init: Callable[..., jnp.ndarray] = jax.nn.initializers.zeros
1230
+
1231
+ def setup(self):
1232
+ self.model = FlaxBlenderbotModule(config=self.config, dtype=self.dtype)
1233
+ self.lm_head = nn.Dense(
1234
+ self.model.shared.num_embeddings,
1235
+ use_bias=False,
1236
+ dtype=self.dtype,
1237
+ kernel_init=jax.nn.initializers.normal(self.config.init_std),
1238
+ )
1239
+ self.final_logits_bias = self.param("final_logits_bias", self.bias_init, (1, self.model.shared.num_embeddings))
1240
+
1241
+ def _get_encoder_module(self):
1242
+ return self.model.encoder
1243
+
1244
+ def _get_decoder_module(self):
1245
+ return self.model.decoder
1246
+
1247
+ def __call__(
1248
+ self,
1249
+ input_ids,
1250
+ attention_mask,
1251
+ decoder_input_ids,
1252
+ decoder_attention_mask,
1253
+ position_ids,
1254
+ decoder_position_ids,
1255
+ output_attentions: bool = False,
1256
+ output_hidden_states: bool = False,
1257
+ return_dict: bool = True,
1258
+ deterministic: bool = True,
1259
+ ):
1260
+ outputs = self.model(
1261
+ input_ids=input_ids,
1262
+ attention_mask=attention_mask,
1263
+ decoder_input_ids=decoder_input_ids,
1264
+ decoder_attention_mask=decoder_attention_mask,
1265
+ position_ids=position_ids,
1266
+ decoder_position_ids=decoder_position_ids,
1267
+ output_attentions=output_attentions,
1268
+ output_hidden_states=output_hidden_states,
1269
+ return_dict=return_dict,
1270
+ deterministic=deterministic,
1271
+ )
1272
+
1273
+ hidden_states = outputs[0]
1274
+
1275
+ if self.config.tie_word_embeddings:
1276
+ shared_embedding = self.model.variables["params"]["shared"]["embedding"]
1277
+ lm_logits = self.lm_head.apply({"params": {"kernel": shared_embedding.T}}, hidden_states)
1278
+ else:
1279
+ lm_logits = self.lm_head(hidden_states)
1280
+
1281
+ lm_logits += jax.lax.stop_gradient(self.final_logits_bias.astype(self.dtype))
1282
+
1283
+ if not return_dict:
1284
+ output = (lm_logits,) + outputs[1:]
1285
+ return output
1286
+
1287
+ return FlaxSeq2SeqLMOutput(
1288
+ logits=lm_logits,
1289
+ decoder_hidden_states=outputs.decoder_hidden_states,
1290
+ decoder_attentions=outputs.decoder_attentions,
1291
+ cross_attentions=outputs.cross_attentions,
1292
+ encoder_last_hidden_state=outputs.encoder_last_hidden_state,
1293
+ encoder_hidden_states=outputs.encoder_hidden_states,
1294
+ encoder_attentions=outputs.encoder_attentions,
1295
+ )
1296
+
1297
+
1298
+ @add_start_docstrings(
1299
+ "The Blenderbot Model with a language modeling head. Can be used for summarization.", BLENDERBOT_START_DOCSTRING
1300
+ )
1301
+ class FlaxBlenderbotForConditionalGeneration(FlaxBlenderbotPreTrainedModel):
1302
+ module_class = FlaxBlenderbotForConditionalGenerationModule
1303
+ dtype: jnp.dtype = jnp.float32
1304
+
1305
+ @add_start_docstrings(BLENDERBOT_DECODE_INPUTS_DOCSTRING)
1306
+ @replace_return_docstrings(output_type=FlaxCausalLMOutputWithCrossAttentions, config_class=BlenderbotConfig)
1307
+ def decode(
1308
+ self,
1309
+ decoder_input_ids,
1310
+ encoder_outputs,
1311
+ encoder_attention_mask: Optional[jnp.ndarray] = None,
1312
+ decoder_attention_mask: Optional[jnp.ndarray] = None,
1313
+ decoder_position_ids: Optional[jnp.ndarray] = None,
1314
+ past_key_values: dict = None,
1315
+ output_attentions: Optional[bool] = None,
1316
+ output_hidden_states: Optional[bool] = None,
1317
+ return_dict: Optional[bool] = None,
1318
+ train: bool = False,
1319
+ params: dict = None,
1320
+ dropout_rng: PRNGKey = None,
1321
+ ):
1322
+ r"""
1323
+ Returns:
1324
+
1325
+ Example:
1326
+
1327
+ ```python
1328
+ >>> import jax.numpy as jnp
1329
+ >>> from transformers import AutoTokenizer, FlaxBlenderbotForConditionalGeneration
1330
+
1331
+ >>> model = FlaxBlenderbotForConditionalGeneration.from_pretrained("facebook/blenderbot-400M-distill")
1332
+ >>> tokenizer = AutoTokenizer.from_pretrained("facebook/blenderbot-400M-distill")
1333
+
1334
+ >>> text = "My friends are cool but they eat too many carbs."
1335
+ >>> inputs = tokenizer(text, max_length=1024, return_tensors="jax")
1336
+ >>> encoder_outputs = model.encode(**inputs)
1337
+
1338
+ >>> decoder_start_token_id = model.config.decoder_start_token_id
1339
+ >>> decoder_input_ids = jnp.ones((inputs.input_ids.shape[0], 1), dtype="i4") * decoder_start_token_id
1340
+
1341
+ >>> outputs = model.decode(decoder_input_ids, encoder_outputs)
1342
+ >>> logits = outputs.logits
1343
+ ```"""
1344
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1345
+ output_hidden_states = (
1346
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1347
+ )
1348
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
1349
+
1350
+ encoder_hidden_states = encoder_outputs[0]
1351
+ if encoder_attention_mask is None:
1352
+ batch_size, sequence_length = encoder_hidden_states.shape[:2]
1353
+ encoder_attention_mask = jnp.ones((batch_size, sequence_length))
1354
+
1355
+ batch_size, sequence_length = decoder_input_ids.shape
1356
+ if decoder_attention_mask is None:
1357
+ decoder_attention_mask = jnp.ones((batch_size, sequence_length))
1358
+
1359
+ if decoder_position_ids is None:
1360
+ if past_key_values is not None:
1361
+ raise ValueError("Make sure to provide `decoder_position_ids` when passing `past_key_values`.")
1362
+
1363
+ decoder_position_ids = jnp.broadcast_to(
1364
+ jnp.arange(sequence_length)[None, :], (batch_size, sequence_length)
1365
+ )
1366
+
1367
+ # Handle any PRNG if needed
1368
+ rngs = {}
1369
+ if dropout_rng is not None:
1370
+ rngs["dropout"] = dropout_rng
1371
+
1372
+ inputs = {"params": params or self.params}
1373
+
1374
+ # if past_key_values are passed then cache is already initialized a private flag init_cache has to be
1375
+ # passed down to ensure cache is used. It has to be made sure that cache is marked as mutable so that
1376
+ # it can be changed by FlaxBlenderbotAttention module
1377
+ if past_key_values:
1378
+ inputs["cache"] = past_key_values
1379
+ mutable = ["cache"]
1380
+ else:
1381
+ mutable = False
1382
+
1383
+ def _decoder_forward(module, decoder_input_ids, decoder_attention_mask, decoder_position_ids, **kwargs):
1384
+ decoder_module = module._get_decoder_module()
1385
+ outputs = decoder_module(
1386
+ decoder_input_ids,
1387
+ decoder_attention_mask,
1388
+ decoder_position_ids,
1389
+ **kwargs,
1390
+ )
1391
+ hidden_states = outputs[0]
1392
+
1393
+ if self.config.tie_word_embeddings:
1394
+ shared_embedding = module.model.variables["params"]["shared"]["embedding"]
1395
+ lm_logits = module.lm_head.apply({"params": {"kernel": shared_embedding.T}}, hidden_states)
1396
+ else:
1397
+ lm_logits = module.lm_head(hidden_states)
1398
+
1399
+ lm_logits += module.final_logits_bias
1400
+ return lm_logits, outputs
1401
+
1402
+ outputs = self.module.apply(
1403
+ inputs,
1404
+ decoder_input_ids=jnp.array(decoder_input_ids, dtype="i4"),
1405
+ decoder_attention_mask=jnp.array(decoder_attention_mask, dtype="i4"),
1406
+ decoder_position_ids=jnp.array(decoder_position_ids, dtype="i4"),
1407
+ encoder_hidden_states=encoder_hidden_states,
1408
+ encoder_attention_mask=jnp.array(encoder_attention_mask, dtype="i4"),
1409
+ output_attentions=output_attentions,
1410
+ output_hidden_states=output_hidden_states,
1411
+ return_dict=return_dict,
1412
+ deterministic=not train,
1413
+ rngs=rngs,
1414
+ mutable=mutable,
1415
+ method=_decoder_forward,
1416
+ )
1417
+
1418
+ if past_key_values is None:
1419
+ lm_logits, decoder_outputs = outputs
1420
+ else:
1421
+ (lm_logits, decoder_outputs), past = outputs
1422
+
1423
+ if return_dict:
1424
+ outputs = FlaxCausalLMOutputWithCrossAttentions(
1425
+ logits=lm_logits,
1426
+ hidden_states=decoder_outputs.hidden_states,
1427
+ attentions=decoder_outputs.attentions,
1428
+ cross_attentions=decoder_outputs.cross_attentions,
1429
+ )
1430
+ else:
1431
+ outputs = (lm_logits,) + decoder_outputs[1:]
1432
+
1433
+ # add updated cache to model output
1434
+ if past_key_values is not None and return_dict:
1435
+ outputs["past_key_values"] = unfreeze(past["cache"])
1436
+ return outputs
1437
+ elif past_key_values is not None and not return_dict:
1438
+ outputs = outputs[:1] + (unfreeze(past["cache"]),) + outputs[1:]
1439
+
1440
+ return outputs
1441
+
1442
+ def prepare_inputs_for_generation(
1443
+ self,
1444
+ decoder_input_ids,
1445
+ max_length,
1446
+ attention_mask: Optional[jax.Array] = None,
1447
+ decoder_attention_mask: Optional[jax.Array] = None,
1448
+ encoder_outputs=None,
1449
+ **kwargs,
1450
+ ):
1451
+ # initializing the cache
1452
+ batch_size, seq_length = decoder_input_ids.shape
1453
+
1454
+ past_key_values = self.init_cache(batch_size, max_length, encoder_outputs)
1455
+ # Note that usually one would have to put 0's in the attention_mask for x > input_ids.shape[-1] and x < cache_length.
1456
+ # But since the decoder uses a causal mask, those positions are masked anyways.
1457
+ # Thus we can create a single static attention_mask here, which is more efficient for compilation
1458
+ extended_attention_mask = jnp.ones((batch_size, max_length), dtype="i4")
1459
+ if decoder_attention_mask is not None:
1460
+ position_ids = decoder_attention_mask.cumsum(axis=-1) - 1
1461
+ extended_attention_mask = lax.dynamic_update_slice(extended_attention_mask, decoder_attention_mask, (0, 0))
1462
+ else:
1463
+ position_ids = jnp.broadcast_to(jnp.arange(seq_length, dtype="i4")[None, :], (batch_size, seq_length))
1464
+
1465
+ return {
1466
+ "past_key_values": past_key_values,
1467
+ "encoder_outputs": encoder_outputs,
1468
+ "encoder_attention_mask": attention_mask,
1469
+ "decoder_attention_mask": extended_attention_mask,
1470
+ "decoder_position_ids": position_ids,
1471
+ }
1472
+
1473
+ def update_inputs_for_generation(self, model_outputs, model_kwargs):
1474
+ model_kwargs["past_key_values"] = model_outputs.past_key_values
1475
+ model_kwargs["decoder_position_ids"] = model_kwargs["decoder_position_ids"][:, -1:] + 1
1476
+ return model_kwargs
1477
+
1478
+
1479
+ FLAX_BLENDERBOT_CONDITIONAL_GENERATION_DOCSTRING = r"""
1480
+ Returns:
1481
+
1482
+ Conversation example::
1483
+
1484
+ ```py
1485
+ >>> from transformers import AutoTokenizer, FlaxBlenderbotForConditionalGeneration
1486
+
1487
+ >>> model = FlaxBlenderbotForConditionalGeneration.from_pretrained("facebook/blenderbot-400M-distill")
1488
+ >>> tokenizer = AutoTokenizer.from_pretrained("facebook/blenderbot-400M-distill")
1489
+
1490
+ >>> UTTERANCE = "My friends are cool but they eat too many carbs."
1491
+ >>> inputs = tokenizer([UTTERANCE], max_length=1024, return_tensors="np")
1492
+
1493
+ >>> # Generate Reply
1494
+ >>> reply_ids = model.generate(inputs["input_ids"], num_beams=4, max_length=5, early_stopping=True).sequences
1495
+ >>> print([tokenizer.decode(g, skip_special_tokens=True, clean_up_tokenization_spaces=False) for g in reply_ids])
1496
+ ```
1497
+ """
1498
+
1499
+ overwrite_call_docstring(
1500
+ FlaxBlenderbotForConditionalGeneration,
1501
+ BLENDERBOT_INPUTS_DOCSTRING + FLAX_BLENDERBOT_CONDITIONAL_GENERATION_DOCSTRING,
1502
+ )
1503
+ append_replace_return_docstrings(
1504
+ FlaxBlenderbotForConditionalGeneration, output_type=FlaxSeq2SeqLMOutput, config_class=_CONFIG_FOR_DOC
1505
+ )
env-llmeval/lib/python3.10/site-packages/transformers/models/blenderbot/modeling_tf_blenderbot.py ADDED
@@ -0,0 +1,1556 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2021 The Facebook, Inc and The HuggingFace Inc. team. All rights reserved.
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
+ """ TF 2.0 Blenderbot model."""
16
+
17
+
18
+ from __future__ import annotations
19
+
20
+ import os
21
+ import random
22
+ import warnings
23
+ from typing import List, Optional, Tuple, Union
24
+
25
+ import tensorflow as tf
26
+
27
+ from ...activations_tf import get_tf_activation
28
+ from ...modeling_tf_outputs import (
29
+ TFBaseModelOutput,
30
+ TFBaseModelOutputWithPastAndCrossAttentions,
31
+ TFSeq2SeqLMOutput,
32
+ TFSeq2SeqModelOutput,
33
+ )
34
+
35
+ # Public API
36
+ from ...modeling_tf_utils import (
37
+ TFCausalLanguageModelingLoss,
38
+ TFPreTrainedModel,
39
+ keras,
40
+ keras_serializable,
41
+ unpack_inputs,
42
+ )
43
+ from ...tf_utils import check_embeddings_within_bounds, shape_list, stable_softmax
44
+ from ...utils import (
45
+ add_code_sample_docstrings,
46
+ add_end_docstrings,
47
+ add_start_docstrings,
48
+ add_start_docstrings_to_model_forward,
49
+ logging,
50
+ replace_return_docstrings,
51
+ )
52
+ from .configuration_blenderbot import BlenderbotConfig
53
+
54
+
55
+ logger = logging.get_logger(__name__)
56
+
57
+ _CHECKPOINT_FOR_DOC = "facebook/blenderbot-400M-distill"
58
+ _CONFIG_FOR_DOC = "BlenderbotConfig"
59
+
60
+
61
+ LARGE_NEGATIVE = -1e8
62
+
63
+
64
+ # Copied from transformers.models.bart.modeling_tf_bart.shift_tokens_right
65
+ def shift_tokens_right(input_ids: tf.Tensor, pad_token_id: int, decoder_start_token_id: int):
66
+ pad_token_id = tf.cast(pad_token_id, input_ids.dtype)
67
+ decoder_start_token_id = tf.cast(decoder_start_token_id, input_ids.dtype)
68
+ start_tokens = tf.fill(
69
+ (shape_list(input_ids)[0], 1), tf.convert_to_tensor(decoder_start_token_id, input_ids.dtype)
70
+ )
71
+ shifted_input_ids = tf.concat([start_tokens, input_ids[:, :-1]], -1)
72
+ # replace possible -100 values in labels by `pad_token_id`
73
+ shifted_input_ids = tf.where(
74
+ shifted_input_ids == -100,
75
+ tf.fill(shape_list(shifted_input_ids), tf.convert_to_tensor(pad_token_id, input_ids.dtype)),
76
+ shifted_input_ids,
77
+ )
78
+
79
+ # "Verify that `labels` has only positive values and -100"
80
+ assert_gte0 = tf.debugging.assert_greater_equal(shifted_input_ids, tf.constant(0, dtype=input_ids.dtype))
81
+
82
+ # Make sure the assertion op is called by wrapping the result in an identity no-op
83
+ with tf.control_dependencies([assert_gte0]):
84
+ shifted_input_ids = tf.identity(shifted_input_ids)
85
+
86
+ return shifted_input_ids
87
+
88
+
89
+ # Copied from transformers.models.bart.modeling_tf_bart._make_causal_mask
90
+ def _make_causal_mask(input_ids_shape: tf.TensorShape, past_key_values_length: int = 0):
91
+ """
92
+ Make causal mask used for bi-directional self-attention.
93
+ """
94
+ bsz = input_ids_shape[0]
95
+ tgt_len = input_ids_shape[1]
96
+ mask = tf.ones((tgt_len, tgt_len)) * LARGE_NEGATIVE
97
+ mask_cond = tf.range(shape_list(mask)[-1])
98
+
99
+ mask = tf.where(mask_cond < tf.reshape(mask_cond + 1, (shape_list(mask)[-1], 1)), 0.0, mask)
100
+
101
+ if past_key_values_length > 0:
102
+ mask = tf.concat([tf.zeros((tgt_len, past_key_values_length)), mask], axis=-1)
103
+
104
+ return tf.tile(mask[None, None, :, :], (bsz, 1, 1, 1))
105
+
106
+
107
+ # Copied from transformers.models.bart.modeling_tf_bart._expand_mask
108
+ def _expand_mask(mask: tf.Tensor, tgt_len: Optional[int] = None):
109
+ """
110
+ Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`.
111
+ """
112
+ src_len = shape_list(mask)[1]
113
+ tgt_len = tgt_len if tgt_len is not None else src_len
114
+ one_cst = tf.constant(1.0)
115
+ mask = tf.cast(mask, dtype=one_cst.dtype)
116
+ expanded_mask = tf.tile(mask[:, None, None, :], (1, 1, tgt_len, 1))
117
+
118
+ return (one_cst - expanded_mask) * LARGE_NEGATIVE
119
+
120
+
121
+ class TFBlenderbotLearnedPositionalEmbedding(keras.layers.Embedding):
122
+ """
123
+ This module learns positional embeddings up to a fixed maximum size.
124
+ """
125
+
126
+ def __init__(self, num_embeddings: int, embedding_dim: int, **kwargs):
127
+ super().__init__(num_embeddings, embedding_dim, **kwargs)
128
+
129
+ def call(
130
+ self, input_shape: tf.TensorShape, past_key_values_length: int = 0, position_ids: tf.Tensor | None = None
131
+ ):
132
+ """Input is expected to be of size [bsz x seqlen]."""
133
+ if position_ids is None:
134
+ seq_len = input_shape[1]
135
+ position_ids = tf.range(seq_len, delta=1, name="range")
136
+ position_ids += past_key_values_length
137
+
138
+ return super().call(tf.cast(position_ids, dtype=tf.int32))
139
+
140
+
141
+ # Copied from transformers.models.bart.modeling_tf_bart.TFBartAttention with Bart->Blenderbot
142
+ class TFBlenderbotAttention(keras.layers.Layer):
143
+ """Multi-headed attention from "Attention Is All You Need"""
144
+
145
+ def __init__(
146
+ self,
147
+ embed_dim: int,
148
+ num_heads: int,
149
+ dropout: float = 0.0,
150
+ is_decoder: bool = False,
151
+ bias: bool = True,
152
+ **kwargs,
153
+ ):
154
+ super().__init__(**kwargs)
155
+ self.embed_dim = embed_dim
156
+
157
+ self.num_heads = num_heads
158
+ self.dropout = keras.layers.Dropout(dropout)
159
+ self.head_dim = embed_dim // num_heads
160
+ if (self.head_dim * num_heads) != self.embed_dim:
161
+ raise ValueError(
162
+ f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim}"
163
+ f" and `num_heads`: {num_heads})."
164
+ )
165
+ self.scaling = self.head_dim**-0.5
166
+ self.is_decoder = is_decoder
167
+
168
+ self.k_proj = keras.layers.Dense(embed_dim, use_bias=bias, name="k_proj")
169
+ self.q_proj = keras.layers.Dense(embed_dim, use_bias=bias, name="q_proj")
170
+ self.v_proj = keras.layers.Dense(embed_dim, use_bias=bias, name="v_proj")
171
+ self.out_proj = keras.layers.Dense(embed_dim, use_bias=bias, name="out_proj")
172
+
173
+ def _shape(self, tensor: tf.Tensor, seq_len: int, bsz: int):
174
+ return tf.transpose(tf.reshape(tensor, (bsz, seq_len, self.num_heads, self.head_dim)), (0, 2, 1, 3))
175
+
176
+ def call(
177
+ self,
178
+ hidden_states: tf.Tensor,
179
+ key_value_states: tf.Tensor | None = None,
180
+ past_key_value: Tuple[Tuple[tf.Tensor]] | None = None,
181
+ attention_mask: tf.Tensor | None = None,
182
+ layer_head_mask: tf.Tensor | None = None,
183
+ training: Optional[bool] = False,
184
+ ) -> Tuple[tf.Tensor, tf.Tensor | None]:
185
+ """Input shape: Batch x Time x Channel"""
186
+
187
+ # if key_value_states are provided this layer is used as a cross-attention layer
188
+ # for the decoder
189
+ is_cross_attention = key_value_states is not None
190
+ bsz, tgt_len, embed_dim = shape_list(hidden_states)
191
+
192
+ # get query proj
193
+ query_states = self.q_proj(hidden_states) * self.scaling
194
+ # get key, value proj
195
+ if is_cross_attention and past_key_value is not None:
196
+ # reuse k,v, cross_attentions
197
+ key_states = past_key_value[0]
198
+ value_states = past_key_value[1]
199
+ elif is_cross_attention:
200
+ # cross_attentions
201
+ key_states = self._shape(self.k_proj(key_value_states), -1, bsz)
202
+ value_states = self._shape(self.v_proj(key_value_states), -1, bsz)
203
+ elif past_key_value is not None:
204
+ # reuse k, v, self_attention
205
+ key_states = self._shape(self.k_proj(hidden_states), -1, bsz)
206
+ value_states = self._shape(self.v_proj(hidden_states), -1, bsz)
207
+ key_states = tf.concat([past_key_value[0], key_states], axis=2)
208
+ value_states = tf.concat([past_key_value[1], value_states], axis=2)
209
+ else:
210
+ # self_attention
211
+ key_states = self._shape(self.k_proj(hidden_states), -1, bsz)
212
+ value_states = self._shape(self.v_proj(hidden_states), -1, bsz)
213
+
214
+ if self.is_decoder:
215
+ # if cross_attention save Tuple(tf.Tensor, tf.Tensor) of all cross attention key/value_states.
216
+ # Further calls to cross_attention layer can then reuse all cross-attention
217
+ # key/value_states (first "if" case)
218
+ # if uni-directional self-attention (decoder) save Tuple(tf.Tensor, tf.Tensor) of
219
+ # all previous decoder key/value_states. Further calls to uni-directional self-attention
220
+ # can concat previous decoder key/value_states to current projected key/value_states (third "elif" case)
221
+ # if encoder bi-directional self-attention `past_key_value` is always `None`
222
+ past_key_value = (key_states, value_states)
223
+
224
+ proj_shape = (bsz * self.num_heads, -1, self.head_dim)
225
+ query_states = tf.reshape(self._shape(query_states, tgt_len, bsz), proj_shape)
226
+ key_states = tf.reshape(key_states, proj_shape)
227
+ value_states = tf.reshape(value_states, proj_shape)
228
+
229
+ src_len = shape_list(key_states)[1]
230
+ attn_weights = tf.matmul(query_states, key_states, transpose_b=True)
231
+
232
+ tf.debugging.assert_equal(
233
+ shape_list(attn_weights),
234
+ [bsz * self.num_heads, tgt_len, src_len],
235
+ message=(
236
+ f"Attention weights should be of size {(bsz * self.num_heads, tgt_len, src_len)}, but is"
237
+ f" {shape_list(attn_weights)}"
238
+ ),
239
+ )
240
+
241
+ if attention_mask is not None:
242
+ tf.debugging.assert_equal(
243
+ shape_list(attention_mask),
244
+ [bsz, 1, tgt_len, src_len],
245
+ message=(
246
+ f"Attention mask should be of size {(bsz, 1, tgt_len, src_len)}, but is"
247
+ f" {shape_list(attention_mask)}"
248
+ ),
249
+ )
250
+
251
+ attention_mask = tf.cast(attention_mask, dtype=attn_weights.dtype)
252
+ attn_weights = tf.reshape(attn_weights, (bsz, self.num_heads, tgt_len, src_len)) + attention_mask
253
+ attn_weights = tf.reshape(attn_weights, (bsz * self.num_heads, tgt_len, src_len))
254
+
255
+ attn_weights = stable_softmax(attn_weights, axis=-1)
256
+
257
+ if layer_head_mask is not None:
258
+ tf.debugging.assert_equal(
259
+ shape_list(layer_head_mask),
260
+ [self.num_heads],
261
+ message=(
262
+ f"Head mask for a single layer should be of size {(self.num_heads)}, but is"
263
+ f" {shape_list(layer_head_mask)}"
264
+ ),
265
+ )
266
+
267
+ attn_weights = tf.reshape(layer_head_mask, (1, -1, 1, 1)) * tf.reshape(
268
+ attn_weights, (bsz, self.num_heads, tgt_len, src_len)
269
+ )
270
+ attn_weights = tf.reshape(attn_weights, (bsz * self.num_heads, tgt_len, src_len))
271
+
272
+ attn_probs = self.dropout(attn_weights, training=training)
273
+ attn_output = tf.matmul(attn_probs, value_states)
274
+
275
+ tf.debugging.assert_equal(
276
+ shape_list(attn_output),
277
+ [bsz * self.num_heads, tgt_len, self.head_dim],
278
+ message=(
279
+ f"`attn_output` should be of size {(bsz, self.num_heads, tgt_len, self.head_dim)}, but is"
280
+ f" {shape_list(attn_output)}"
281
+ ),
282
+ )
283
+
284
+ attn_output = tf.transpose(
285
+ tf.reshape(attn_output, (bsz, self.num_heads, tgt_len, self.head_dim)), (0, 2, 1, 3)
286
+ )
287
+ attn_output = tf.reshape(attn_output, (bsz, tgt_len, embed_dim))
288
+
289
+ attn_output = self.out_proj(attn_output)
290
+ attn_weights: tf.Tensor = tf.reshape(attn_weights, (bsz, self.num_heads, tgt_len, src_len))
291
+
292
+ return attn_output, attn_weights, past_key_value
293
+
294
+ def build(self, input_shape=None):
295
+ if self.built:
296
+ return
297
+ self.built = True
298
+ if getattr(self, "k_proj", None) is not None:
299
+ with tf.name_scope(self.k_proj.name):
300
+ self.k_proj.build([None, None, self.embed_dim])
301
+ if getattr(self, "q_proj", None) is not None:
302
+ with tf.name_scope(self.q_proj.name):
303
+ self.q_proj.build([None, None, self.embed_dim])
304
+ if getattr(self, "v_proj", None) is not None:
305
+ with tf.name_scope(self.v_proj.name):
306
+ self.v_proj.build([None, None, self.embed_dim])
307
+ if getattr(self, "out_proj", None) is not None:
308
+ with tf.name_scope(self.out_proj.name):
309
+ self.out_proj.build([None, None, self.embed_dim])
310
+
311
+
312
+ # Copied from transformers.models.mbart.modeling_tf_mbart.TFMBartEncoderLayer with MBart->Blenderbot
313
+ class TFBlenderbotEncoderLayer(keras.layers.Layer):
314
+ def __init__(self, config: BlenderbotConfig, **kwargs):
315
+ super().__init__(**kwargs)
316
+ self.embed_dim = config.d_model
317
+ self.self_attn = TFBlenderbotAttention(
318
+ self.embed_dim, config.encoder_attention_heads, dropout=config.attention_dropout, name="self_attn"
319
+ )
320
+ self.self_attn_layer_norm = keras.layers.LayerNormalization(epsilon=1e-5, name="self_attn_layer_norm")
321
+ self.dropout = keras.layers.Dropout(config.dropout)
322
+ self.activation_fn = get_tf_activation(config.activation_function)
323
+ self.activation_dropout = keras.layers.Dropout(config.activation_dropout)
324
+ self.fc1 = keras.layers.Dense(config.encoder_ffn_dim, name="fc1")
325
+ self.fc2 = keras.layers.Dense(self.embed_dim, name="fc2")
326
+ self.final_layer_norm = keras.layers.LayerNormalization(epsilon=1e-5, name="final_layer_norm")
327
+ self.config = config
328
+
329
+ def call(
330
+ self,
331
+ hidden_states: tf.Tensor,
332
+ attention_mask: tf.Tensor,
333
+ layer_head_mask: tf.Tensor,
334
+ training: Optional[bool] = False,
335
+ ):
336
+ """
337
+ Args:
338
+ hidden_states (`tf.Tensor`): input to the layer of shape *(batch, seq_len, embed_dim)*
339
+ attention_mask (`tf.Tensor`): attention mask of size
340
+ *(batch, 1, tgt_len, src_len)* where padding elements are indicated by very large negative values.
341
+ layer_head_mask (`tf.Tensor`): mask for attention heads in a given layer of size
342
+ *(encoder_attention_heads,)*
343
+ """
344
+ residual = hidden_states
345
+ hidden_states = self.self_attn_layer_norm(hidden_states)
346
+ hidden_states, self_attn_weights, _ = self.self_attn(
347
+ hidden_states=hidden_states, attention_mask=attention_mask, layer_head_mask=layer_head_mask
348
+ )
349
+
350
+ tf.debugging.assert_equal(
351
+ shape_list(hidden_states),
352
+ shape_list(residual),
353
+ message=f"Self attn modified the shape of query {shape_list(residual)} to {shape_list(hidden_states)}",
354
+ )
355
+
356
+ hidden_states = self.dropout(hidden_states, training=training)
357
+ hidden_states = residual + hidden_states
358
+
359
+ residual = hidden_states
360
+ hidden_states = self.final_layer_norm(hidden_states)
361
+ hidden_states = self.activation_fn(self.fc1(hidden_states))
362
+ hidden_states = self.activation_dropout(hidden_states, training=training)
363
+ hidden_states = self.fc2(hidden_states)
364
+ hidden_states = self.dropout(hidden_states, training=training)
365
+ hidden_states = residual + hidden_states
366
+
367
+ return hidden_states, self_attn_weights
368
+
369
+ def build(self, input_shape=None):
370
+ if self.built:
371
+ return
372
+ self.built = True
373
+ if getattr(self, "self_attn", None) is not None:
374
+ with tf.name_scope(self.self_attn.name):
375
+ self.self_attn.build(None)
376
+ if getattr(self, "self_attn_layer_norm", None) is not None:
377
+ with tf.name_scope(self.self_attn_layer_norm.name):
378
+ self.self_attn_layer_norm.build([None, None, self.embed_dim])
379
+ if getattr(self, "fc1", None) is not None:
380
+ with tf.name_scope(self.fc1.name):
381
+ self.fc1.build([None, None, self.embed_dim])
382
+ if getattr(self, "fc2", None) is not None:
383
+ with tf.name_scope(self.fc2.name):
384
+ self.fc2.build([None, None, self.config.encoder_ffn_dim])
385
+ if getattr(self, "final_layer_norm", None) is not None:
386
+ with tf.name_scope(self.final_layer_norm.name):
387
+ self.final_layer_norm.build([None, None, self.embed_dim])
388
+
389
+
390
+ # Copied from transformers.models.mbart.modeling_tf_mbart.TFMBartDecoderLayer with MBart->Blenderbot
391
+ class TFBlenderbotDecoderLayer(keras.layers.Layer):
392
+ def __init__(self, config: BlenderbotConfig, **kwargs):
393
+ super().__init__(**kwargs)
394
+ self.embed_dim = config.d_model
395
+ self.self_attn = TFBlenderbotAttention(
396
+ embed_dim=self.embed_dim,
397
+ num_heads=config.decoder_attention_heads,
398
+ dropout=config.attention_dropout,
399
+ name="self_attn",
400
+ is_decoder=True,
401
+ )
402
+ self.dropout = keras.layers.Dropout(config.dropout)
403
+ self.activation_fn = get_tf_activation(config.activation_function)
404
+ self.activation_dropout = keras.layers.Dropout(config.activation_dropout)
405
+
406
+ self.self_attn_layer_norm = keras.layers.LayerNormalization(epsilon=1e-5, name="self_attn_layer_norm")
407
+ self.encoder_attn = TFBlenderbotAttention(
408
+ self.embed_dim,
409
+ config.decoder_attention_heads,
410
+ dropout=config.attention_dropout,
411
+ name="encoder_attn",
412
+ is_decoder=True,
413
+ )
414
+ self.encoder_attn_layer_norm = keras.layers.LayerNormalization(epsilon=1e-5, name="encoder_attn_layer_norm")
415
+ self.fc1 = keras.layers.Dense(config.decoder_ffn_dim, name="fc1")
416
+ self.fc2 = keras.layers.Dense(self.embed_dim, name="fc2")
417
+ self.final_layer_norm = keras.layers.LayerNormalization(epsilon=1e-5, name="final_layer_norm")
418
+ self.config = config
419
+
420
+ def call(
421
+ self,
422
+ hidden_states: tf.Tensor,
423
+ attention_mask: tf.Tensor | None = None,
424
+ encoder_hidden_states: tf.Tensor | None = None,
425
+ encoder_attention_mask: tf.Tensor | None = None,
426
+ layer_head_mask: tf.Tensor | None = None,
427
+ cross_attn_layer_head_mask: tf.Tensor | None = None,
428
+ past_key_value: Tuple[tf.Tensor] | None = None,
429
+ training: Optional[bool] = False,
430
+ ) -> Tuple[tf.Tensor, tf.Tensor, Tuple[Tuple[tf.Tensor]]]:
431
+ """
432
+ Args:
433
+ hidden_states (`tf.Tensor`): input to the layer of shape *(batch, seq_len, embed_dim)*
434
+ attention_mask (`tf.Tensor`): attention mask of size
435
+ *(batch, 1, tgt_len, src_len)* where padding elements are indicated by very large negative values.
436
+ encoder_hidden_states (`tf.Tensor`):
437
+ cross attention input to the layer of shape *(batch, seq_len, embed_dim)*
438
+ encoder_attention_mask (`tf.Tensor`): encoder attention mask of size
439
+ *(batch, 1, tgt_len, src_len)* where padding elements are indicated by very large negative values.
440
+ layer_head_mask (`tf.Tensor`): mask for attention heads in a given layer of size
441
+ *(decoder_attention_heads,)*
442
+ cross_attn_layer_head_mask (`tf.Tensor`): mask for heads of the cross-attention module.
443
+ *(decoder_attention_heads,)*
444
+ past_key_value (`Tuple(tf.Tensor)`): cached past key and value projection states
445
+ """
446
+ residual = hidden_states
447
+ hidden_states = self.self_attn_layer_norm(hidden_states)
448
+
449
+ # Self Attention
450
+ # decoder uni-directional self-attention cached key/values tuple is at positions 1,2
451
+ self_attn_past_key_value = past_key_value[:2] if past_key_value is not None else None
452
+ # add present self-attn cache to positions 1,2 of present_key_value tuple
453
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
454
+ hidden_states=hidden_states,
455
+ past_key_value=self_attn_past_key_value,
456
+ attention_mask=attention_mask,
457
+ layer_head_mask=layer_head_mask,
458
+ )
459
+ hidden_states = self.dropout(hidden_states, training=training)
460
+ hidden_states = residual + hidden_states
461
+
462
+ # Cross-Attention Block
463
+ cross_attn_present_key_value = None
464
+ cross_attn_weights = None
465
+ if encoder_hidden_states is not None:
466
+ residual = hidden_states
467
+ hidden_states = self.encoder_attn_layer_norm(hidden_states)
468
+
469
+ # cross_attn cached key/values tuple is at positions 3,4 of present_key_value tuple
470
+ cross_attn_past_key_value = past_key_value[-2:] if past_key_value is not None else None
471
+ hidden_states, cross_attn_weights, cross_attn_present_key_value = self.encoder_attn(
472
+ hidden_states=hidden_states,
473
+ key_value_states=encoder_hidden_states,
474
+ attention_mask=encoder_attention_mask,
475
+ layer_head_mask=cross_attn_layer_head_mask,
476
+ past_key_value=cross_attn_past_key_value,
477
+ )
478
+ hidden_states = self.dropout(hidden_states, training=training)
479
+ hidden_states = residual + hidden_states
480
+
481
+ # add cross-attn to positions 3,4 of present_key_value tuple
482
+ present_key_value = present_key_value + cross_attn_present_key_value
483
+
484
+ # Fully Connected
485
+ residual = hidden_states
486
+ hidden_states = self.final_layer_norm(hidden_states)
487
+ hidden_states = self.activation_fn(self.fc1(hidden_states))
488
+ hidden_states = self.activation_dropout(hidden_states, training=training)
489
+ hidden_states = self.fc2(hidden_states)
490
+ hidden_states = self.dropout(hidden_states, training=training)
491
+ hidden_states = residual + hidden_states
492
+
493
+ return (
494
+ hidden_states,
495
+ self_attn_weights,
496
+ cross_attn_weights,
497
+ present_key_value,
498
+ )
499
+
500
+ def build(self, input_shape=None):
501
+ if self.built:
502
+ return
503
+ self.built = True
504
+ if getattr(self, "self_attn", None) is not None:
505
+ with tf.name_scope(self.self_attn.name):
506
+ self.self_attn.build(None)
507
+ if getattr(self, "self_attn_layer_norm", None) is not None:
508
+ with tf.name_scope(self.self_attn_layer_norm.name):
509
+ self.self_attn_layer_norm.build([None, None, self.embed_dim])
510
+ if getattr(self, "encoder_attn", None) is not None:
511
+ with tf.name_scope(self.encoder_attn.name):
512
+ self.encoder_attn.build(None)
513
+ if getattr(self, "encoder_attn_layer_norm", None) is not None:
514
+ with tf.name_scope(self.encoder_attn_layer_norm.name):
515
+ self.encoder_attn_layer_norm.build([None, None, self.embed_dim])
516
+ if getattr(self, "fc1", None) is not None:
517
+ with tf.name_scope(self.fc1.name):
518
+ self.fc1.build([None, None, self.embed_dim])
519
+ if getattr(self, "fc2", None) is not None:
520
+ with tf.name_scope(self.fc2.name):
521
+ self.fc2.build([None, None, self.config.decoder_ffn_dim])
522
+ if getattr(self, "final_layer_norm", None) is not None:
523
+ with tf.name_scope(self.final_layer_norm.name):
524
+ self.final_layer_norm.build([None, None, self.embed_dim])
525
+
526
+
527
+ class TFBlenderbotPreTrainedModel(TFPreTrainedModel):
528
+ config_class = BlenderbotConfig
529
+ base_model_prefix = "model"
530
+
531
+
532
+ BLENDERBOT_START_DOCSTRING = r"""
533
+ This model inherits from [`TFPreTrainedModel`]. Check the superclass documentation for the generic methods the
534
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
535
+ etc.)
536
+
537
+ This model is also a [keras.Model](https://www.tensorflow.org/api_docs/python/tf/keras/Model) subclass. Use it
538
+ as a regular TF 2.0 Keras Model and refer to the TF 2.0 documentation for all matter related to general usage and
539
+ behavior.
540
+
541
+ <Tip>
542
+
543
+ TensorFlow models and layers in `transformers` accept two formats as input:
544
+
545
+ - having all inputs as keyword arguments (like PyTorch models), or
546
+ - having all inputs as a list, tuple or dict in the first positional argument.
547
+
548
+ The reason the second format is supported is that Keras methods prefer this format when passing inputs to models
549
+ and layers. Because of this support, when using methods like `model.fit()` things should "just work" for you - just
550
+ pass your inputs and labels in any format that `model.fit()` supports! If, however, you want to use the second
551
+ format outside of Keras methods like `fit()` and `predict()`, such as when creating your own layers or models with
552
+ the Keras `Functional` API, there are three possibilities you can use to gather all the input Tensors in the first
553
+ positional argument:
554
+
555
+ - a single Tensor with `input_ids` only and nothing else: `model(input_ids)`
556
+ - a list of varying length with one or several input Tensors IN THE ORDER given in the docstring:
557
+ `model([input_ids, attention_mask])` or `model([input_ids, attention_mask, token_type_ids])`
558
+ - a dictionary with one or several input Tensors associated to the input names given in the docstring:
559
+ `model({"input_ids": input_ids, "token_type_ids": token_type_ids})`
560
+
561
+ Note that when creating models and layers with
562
+ [subclassing](https://keras.io/guides/making_new_layers_and_models_via_subclassing/) then you don't need to worry
563
+ about any of this, as you can just pass inputs like you would to any other Python function!
564
+
565
+ </Tip>
566
+
567
+ Args:
568
+ config ([`BlenderbotConfig`]): Model configuration class with all the parameters of the model.
569
+ Initializing with a config file does not load the weights associated with the model, only the
570
+ configuration. Check out the [`~TFPreTrainedModel.from_pretrained`] method to load the model weights.
571
+ """
572
+
573
+ BLENDERBOT_GENERATION_EXAMPLE = r"""
574
+ Conversation example::
575
+
576
+ ```py
577
+ >>> from transformers import AutoTokenizer, TFBlenderbotForConditionalGeneration
578
+
579
+ >>> mname = "facebook/blenderbot-400M-distill"
580
+ >>> model = TFBlenderbotForConditionalGeneration.from_pretrained(mname)
581
+ >>> tokenizer = AutoTokenizer.from_pretrained(mname)
582
+ >>> UTTERANCE = "My friends are cool but they eat too many carbs."
583
+ >>> print("Human: ", UTTERANCE)
584
+
585
+ >>> inputs = tokenizer([UTTERANCE], return_tensors="tf")
586
+ >>> reply_ids = model.generate(**inputs)
587
+ >>> print("Bot: ", tokenizer.batch_decode(reply_ids, skip_special_tokens=True)[0])
588
+
589
+ >>> REPLY = "I'm not sure"
590
+ >>> print("Human: ", REPLY)
591
+ >>> NEXT_UTTERANCE = (
592
+ ... "My friends are cool but they eat too many carbs.</s> <s>That's unfortunate. "
593
+ ... "Are they trying to lose weight or are they just trying to be healthier?</s> "
594
+ ... "<s> I'm not sure."
595
+ ... )
596
+ >>> inputs = tokenizer([NEXT_UTTERANCE], return_tensors="tf")
597
+ >>> next_reply_ids = model.generate(**inputs)
598
+ >>> print("Bot: ", tokenizer.batch_decode(next_reply_ids, skip_special_tokens=True)[0])
599
+ ```
600
+ """
601
+
602
+ BLENDERBOT_INPUTS_DOCSTRING = r"""
603
+ Args:
604
+ input_ids (`tf.Tensor` of shape `({0})`):
605
+ Indices of input sequence tokens in the vocabulary.
606
+
607
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
608
+ [`PreTrainedTokenizer.__call__`] for details.
609
+
610
+ [What are input IDs?](../glossary#input-ids)
611
+ attention_mask (`tf.Tensor` of shape `({0})`, *optional*):
612
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
613
+
614
+ - 1 for tokens that are **not masked**,
615
+ - 0 for tokens that are **masked**.
616
+
617
+ [What are attention masks?](../glossary#attention-mask)
618
+ decoder_input_ids (`tf.Tensor` of shape `(batch_size, target_sequence_length)`, *optional*):
619
+ Indices of decoder input sequence tokens in the vocabulary.
620
+
621
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
622
+ [`PreTrainedTokenizer.__call__`] for details.
623
+
624
+ [What are decoder input IDs?](../glossary#decoder-input-ids)
625
+
626
+ Blenderbot uses the `bos_token_id` as the starting token for `decoder_input_ids` generation. If
627
+ `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
628
+ `past_key_values`).
629
+ decoder_attention_mask (`tf.Tensor` of shape `(batch_size, target_sequence_length)`, *optional*):
630
+ will be made by default and ignore pad tokens. It is not recommended to set this for most use cases.
631
+ decoder_position_ids (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
632
+ Indices of positions of each decoder input sequence tokens in the position embeddings. Selected in the
633
+ range `[0, config.max_position_embeddings - 1]`.
634
+ head_mask (`tf.Tensor` of shape `(encoder_layers, encoder_attention_heads)`, *optional*):
635
+ Mask to nullify selected heads of the attention modules in the encoder. Mask values selected in `[0, 1]`:
636
+
637
+ - 1 indicates the head is **not masked**,
638
+ - 0 indicates the head is **masked**.
639
+
640
+ decoder_head_mask (`tf.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
641
+ Mask to nullify selected heads of the attention modules in the decoder. Mask values selected in `[0, 1]`:
642
+
643
+ - 1 indicates the head is **not masked**,
644
+ - 0 indicates the head is **masked**.
645
+
646
+ cross_attn_head_mask (`tf.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
647
+ Mask to nullify selected heads of the cross-attention modules. Mask values selected in `[0, 1]`:
648
+
649
+ - 1 indicates the head is **not masked**,
650
+ - 0 indicates the head is **masked**.
651
+
652
+ encoder_outputs (`tf.FloatTensor`, *optional*):
653
+ hidden states at the output of the last layer of the encoder. Used in the cross-attention of the decoder.
654
+ of shape `(batch_size, sequence_length, hidden_size)` is a sequence of
655
+ past_key_values (`Tuple[Tuple[tf.Tensor]]` of length `config.n_layers`)
656
+ contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.
657
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
658
+ don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
659
+ `decoder_input_ids` of shape `(batch_size, sequence_length)`.
660
+ use_cache (`bool`, *optional*, defaults to `True`):
661
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
662
+ `past_key_values`). Set to `False` during training, `True` during generation
663
+ output_attentions (`bool`, *optional*):
664
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
665
+ tensors for more detail. This argument can be used only in eager mode, in graph mode the value in the
666
+ config will be used instead.
667
+ output_hidden_states (`bool`, *optional*):
668
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
669
+ more detail. This argument can be used only in eager mode, in graph mode the value in the config will be
670
+ used instead.
671
+ return_dict (`bool`, *optional*):
672
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. This argument can be used in
673
+ eager mode, in graph mode the value will always be set to True.
674
+ training (`bool`, *optional*, defaults to `False`):
675
+ Whether or not to use the model in training mode (some modules like dropout modules have different
676
+ behaviors between training and evaluation).
677
+ """
678
+
679
+
680
+ @keras_serializable
681
+ class TFBlenderbotEncoder(keras.layers.Layer):
682
+ config_class = BlenderbotConfig
683
+ """
684
+ Transformer encoder consisting of *config.encoder_layers* self attention layers. Each layer is a
685
+ [`TFBlenderbotEncoderLayer`].
686
+
687
+ Args:
688
+ config: BlenderbotConfig
689
+ """
690
+
691
+ def __init__(self, config: BlenderbotConfig, embed_tokens: Optional[keras.layers.Embedding] = None, **kwargs):
692
+ super().__init__(**kwargs)
693
+ self.config = config
694
+ self.dropout = keras.layers.Dropout(config.dropout)
695
+ self.layerdrop = config.encoder_layerdrop
696
+ self.padding_idx = config.pad_token_id
697
+ self.max_source_positions = config.max_position_embeddings
698
+ self.embed_scale = tf.math.sqrt(float(config.d_model)) if config.scale_embedding else 1.0
699
+
700
+ self.embed_tokens = embed_tokens
701
+ self.embed_positions = TFBlenderbotLearnedPositionalEmbedding(
702
+ config.max_position_embeddings,
703
+ config.d_model,
704
+ name="embed_positions",
705
+ )
706
+ self.layers = [TFBlenderbotEncoderLayer(config, name=f"layers.{i}") for i in range(config.encoder_layers)]
707
+ self.layer_norm = keras.layers.LayerNormalization(epsilon=1e-5, name="layer_norm")
708
+
709
+ def get_embed_tokens(self):
710
+ return self.embed_tokens
711
+
712
+ def set_embed_tokens(self, embed_tokens):
713
+ self.embed_tokens = embed_tokens
714
+
715
+ @unpack_inputs
716
+ def call(
717
+ self,
718
+ input_ids=None,
719
+ inputs_embeds=None,
720
+ attention_mask=None,
721
+ head_mask=None,
722
+ output_attentions=None,
723
+ output_hidden_states=None,
724
+ return_dict=None,
725
+ training=False,
726
+ ):
727
+ """
728
+ Args:
729
+ input_ids (`tf.Tensor` of shape `(batch_size, sequence_length)`):
730
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you
731
+ provide it.
732
+
733
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
734
+ [`PreTrainedTokenizer.__call__`] for details.
735
+
736
+ [What are input IDs?](../glossary#input-ids)
737
+ attention_mask (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
738
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
739
+
740
+ - 1 for tokens that are **not masked**,
741
+ - 0 for tokens that are **masked**.
742
+
743
+ [What are attention masks?](../glossary#attention-mask)
744
+ head_mask (`tf.Tensor` of shape `(encoder_layers, encoder_attention_heads)`, `optional):
745
+ Mask to nullify selected heads of the attention modules. Mask values selected in `[0, 1]`:
746
+
747
+ - 1 indicates the head is **not masked**,
748
+ - 0 indicates the head is **masked**.
749
+
750
+ inputs_embeds (`tf.Tensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
751
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation.
752
+ This is useful if you want more control over how to convert `input_ids` indices into associated vectors
753
+ than the model's internal embedding lookup matrix.
754
+ output_attentions (`bool`, *optional*):
755
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
756
+ returned tensors for more detail. This argument can be used only in eager mode, in graph mode the value
757
+ in the config will be used instead.
758
+ output_hidden_states (`bool`, *optional*):
759
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
760
+ for more detail. This argument can be used only in eager mode, in graph mode the value in the config
761
+ will be used instead.
762
+ return_dict (`bool`, *optional*):
763
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. This argument can be used
764
+ in eager mode, in graph mode the value will always be set to True.
765
+ training (`bool`, *optional*, defaults to `False`):
766
+ Whether or not to use the model in training mode (some modules like dropout modules have different
767
+ behaviors between training and evaluation).
768
+ """
769
+ if input_ids is not None and inputs_embeds is not None:
770
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
771
+ elif input_ids is not None:
772
+ input_shape = shape_list(input_ids)
773
+ elif inputs_embeds is not None:
774
+ input_shape = shape_list(inputs_embeds)[:-1]
775
+ else:
776
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
777
+
778
+ if inputs_embeds is None:
779
+ check_embeddings_within_bounds(input_ids, self.embed_tokens.input_dim)
780
+ inputs_embeds = self.embed_tokens(input_ids) * self.embed_scale
781
+
782
+ embed_pos = self.embed_positions(input_shape)
783
+ hidden_states = inputs_embeds + embed_pos
784
+ hidden_states = self.dropout(hidden_states, training=training)
785
+
786
+ # check attention mask and invert
787
+ if attention_mask is not None:
788
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
789
+ attention_mask = _expand_mask(attention_mask)
790
+ else:
791
+ attention_mask = None
792
+
793
+ encoder_states = () if output_hidden_states else None
794
+ all_attentions = () if output_attentions else None
795
+
796
+ # check if head_mask has a correct number of layers specified if desired
797
+ if head_mask is not None:
798
+ tf.debugging.assert_equal(
799
+ shape_list(head_mask)[0],
800
+ len(self.layers),
801
+ message=(
802
+ f"The head_mask should be specified for {len(self.layers)} layers, but it is for"
803
+ f" {shape_list(head_mask)[0]}."
804
+ ),
805
+ )
806
+
807
+ # encoder layers
808
+ for idx, encoder_layer in enumerate(self.layers):
809
+ if output_hidden_states:
810
+ encoder_states = encoder_states + (hidden_states,)
811
+ # add LayerDrop (see https://arxiv.org/abs/1909.11556 for description)
812
+ dropout_probability = random.uniform(0, 1)
813
+ if training and (dropout_probability < self.layerdrop): # skip the layer
814
+ continue
815
+
816
+ hidden_states, attn = encoder_layer(
817
+ hidden_states,
818
+ attention_mask,
819
+ head_mask[idx] if head_mask is not None else None,
820
+ )
821
+
822
+ if output_attentions:
823
+ all_attentions += (attn,)
824
+
825
+ hidden_states = self.layer_norm(hidden_states)
826
+
827
+ if output_hidden_states:
828
+ encoder_states = encoder_states + (hidden_states,)
829
+
830
+ if not return_dict:
831
+ return tuple(v for v in [hidden_states, encoder_states, all_attentions] if v is not None)
832
+ return TFBaseModelOutput(
833
+ last_hidden_state=hidden_states, hidden_states=encoder_states, attentions=all_attentions
834
+ )
835
+
836
+ def build(self, input_shape=None):
837
+ if self.built:
838
+ return
839
+ self.built = True
840
+ if getattr(self, "embed_positions", None) is not None:
841
+ with tf.name_scope(self.embed_positions.name):
842
+ self.embed_positions.build(None)
843
+ if getattr(self, "layer_norm", None) is not None:
844
+ with tf.name_scope(self.layer_norm.name):
845
+ self.layer_norm.build([None, None, self.config.d_model])
846
+ if getattr(self, "layers", None) is not None:
847
+ for layer in self.layers:
848
+ with tf.name_scope(layer.name):
849
+ layer.build(None)
850
+
851
+
852
+ @keras_serializable
853
+ class TFBlenderbotDecoder(keras.layers.Layer):
854
+ config_class = BlenderbotConfig
855
+ """
856
+ Transformer decoder consisting of *config.decoder_layers* layers. Each layer is a [`TFBlenderbotDecoderLayer`]
857
+
858
+ Args:
859
+ config: BlenderbotConfig
860
+ embed_tokens: output embedding
861
+ """
862
+
863
+ def __init__(self, config: BlenderbotConfig, embed_tokens: Optional[keras.layers.Embedding] = None, **kwargs):
864
+ super().__init__(**kwargs)
865
+ self.config = config
866
+ self.padding_idx = config.pad_token_id
867
+ self.embed_tokens = embed_tokens
868
+ self.layerdrop = config.decoder_layerdrop
869
+ self.embed_positions = TFBlenderbotLearnedPositionalEmbedding(
870
+ config.max_position_embeddings,
871
+ config.d_model,
872
+ name="embed_positions",
873
+ )
874
+ self.embed_scale = tf.math.sqrt(float(config.d_model)) if config.scale_embedding else 1.0
875
+ self.layers = [TFBlenderbotDecoderLayer(config, name=f"layers.{i}") for i in range(config.decoder_layers)]
876
+ self.layer_norm = keras.layers.LayerNormalization(epsilon=1e-5, name="layer_norm")
877
+
878
+ self.dropout = keras.layers.Dropout(config.dropout)
879
+
880
+ def get_embed_tokens(self):
881
+ return self.embed_tokens
882
+
883
+ def set_embed_tokens(self, embed_tokens):
884
+ self.embed_tokens = embed_tokens
885
+
886
+ @unpack_inputs
887
+ def call(
888
+ self,
889
+ input_ids=None,
890
+ inputs_embeds=None,
891
+ attention_mask=None,
892
+ position_ids=None,
893
+ encoder_hidden_states=None,
894
+ encoder_attention_mask=None,
895
+ head_mask=None,
896
+ cross_attn_head_mask=None,
897
+ past_key_values=None,
898
+ use_cache=None,
899
+ output_attentions=None,
900
+ output_hidden_states=None,
901
+ return_dict=None,
902
+ training=False,
903
+ ):
904
+ r"""
905
+ Args:
906
+ input_ids (`tf.Tensor` of shape `(batch_size, sequence_length)`):
907
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you
908
+ provide it.
909
+
910
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
911
+ [`PreTrainedTokenizer.__call__`] for details.
912
+
913
+ [What are input IDs?](../glossary#input-ids)
914
+ attention_mask (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
915
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
916
+
917
+ - 1 for tokens that are **not masked**,
918
+ - 0 for tokens that are **masked**.
919
+
920
+ [What are attention masks?](../glossary#attention-mask)
921
+ position_ids (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
922
+ Indices of positions of each decoder input sequence tokens in the position embeddings. Selected in the
923
+ range `[0, config.max_position_embeddings - 1]`.
924
+ encoder_hidden_states (`tf.Tensor` of shape `(batch_size, encoder_sequence_length, hidden_size)`, *optional*):
925
+ Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention
926
+ of the decoder.
927
+ encoder_attention_mask (`tf.Tensor` of shape `(batch_size, encoder_sequence_length)`, *optional*):
928
+ Mask to avoid performing cross-attention on padding tokens indices of encoder input_ids. Mask values
929
+ selected in `[0, 1]`:
930
+
931
+ - 1 for tokens that are **not masked**,
932
+ - 0 for tokens that are **masked**.
933
+
934
+ [What are attention masks?](../glossary#attention-mask)
935
+ head_mask (`tf.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
936
+ Mask to nullify selected heads of the attention modules. Mask values selected in `[0, 1]`:
937
+
938
+ - 1 indicates the head is **not masked**,
939
+ - 0 indicates the head is **masked**.
940
+
941
+ cross_attn_head_mask (`tf.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
942
+ Mask to nullify selected heads of the cross-attention modules. Mask values selected in `[0, 1]`:
943
+
944
+ - 1 indicates the head is **not masked**,
945
+ - 0 indicates the head is **masked**.
946
+
947
+ past_key_values (`Tuple[Tuple[tf.Tensor]]` of length `config.n_layers` with each tuple having 2 tuples each of which has 2 tensors of shape `(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`):
948
+ Contains precomputed key and value hidden-states of the attention blocks. Can be used to speed up
949
+ decoding.
950
+
951
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those
952
+ that don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of
953
+ all `decoder_input_ids` of shape `(batch_size, sequence_length)`.
954
+ inputs_embeds (`tf.Tensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
955
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation.
956
+ This is useful if you want more control over how to convert `input_ids` indices into associated vectors
957
+ than the model's internal embedding lookup matrix.
958
+ output_attentions (`bool`, *optional*):
959
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
960
+ returned tensors for more detail. This argument can be used only in eager mode, in graph mode the value
961
+ in the config will be used instead.
962
+ output_hidden_states (`bool`, *optional*):
963
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
964
+ for more detail. This argument can be used only in eager mode, in graph mode the value in the config
965
+ will be used instead.
966
+ return_dict (`bool`, *optional*):
967
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. This argument can be used
968
+ in eager mode, in graph mode the value will always be set to True.
969
+ training (`bool`, *optional*, defaults to `False`):
970
+ Whether or not to use the model in training mode (some modules like dropout modules have different
971
+ behaviors between training and evaluation).
972
+ """
973
+ if input_ids is not None and inputs_embeds is not None:
974
+ raise ValueError("You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time")
975
+ elif input_ids is not None:
976
+ input_shape = shape_list(input_ids)
977
+ elif inputs_embeds is not None:
978
+ input_shape = shape_list(inputs_embeds)[:-1]
979
+ else:
980
+ raise ValueError("You have to specify either decoder_input_ids or decoder_inputs_embeds")
981
+
982
+ past_key_values_length = shape_list(past_key_values[0][0])[2] if past_key_values is not None else 0
983
+
984
+ # embed positions
985
+ if position_ids is None:
986
+ positions = self.embed_positions(input_shape, past_key_values_length)
987
+ else:
988
+ positions = self.embed_positions(input_shape, position_ids=position_ids)
989
+
990
+ if inputs_embeds is None:
991
+ check_embeddings_within_bounds(input_ids, self.embed_tokens.input_dim)
992
+ inputs_embeds = self.embed_tokens(input_ids) * self.embed_scale
993
+
994
+ hidden_states = inputs_embeds
995
+
996
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
997
+ if input_shape[-1] > 1:
998
+ combined_attention_mask = _make_causal_mask(input_shape, past_key_values_length=past_key_values_length)
999
+ else:
1000
+ combined_attention_mask = _expand_mask(
1001
+ tf.ones((input_shape[0], input_shape[1] + past_key_values_length)), tgt_len=input_shape[-1]
1002
+ )
1003
+
1004
+ if attention_mask is not None:
1005
+ combined_attention_mask = combined_attention_mask + _expand_mask(attention_mask, tgt_len=input_shape[-1])
1006
+
1007
+ if encoder_hidden_states is not None and encoder_attention_mask is not None:
1008
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
1009
+ encoder_attention_mask = _expand_mask(encoder_attention_mask, tgt_len=input_shape[-1])
1010
+
1011
+ hidden_states = hidden_states + positions
1012
+ hidden_states = self.dropout(hidden_states, training=training)
1013
+
1014
+ # decoder layers
1015
+ all_hidden_states = () if output_hidden_states else None
1016
+ all_self_attns = () if output_attentions else None
1017
+ all_cross_attns = () if (output_attentions and encoder_hidden_states is not None) else None
1018
+ present_key_values = () if use_cache else None
1019
+
1020
+ # check if head_mask and cross_attn_head_mask have a correct number of layers specified if desired
1021
+ for attn_mask_name, attn_mask in [("head_mask", head_mask), ("cross_attn_head_mask", cross_attn_head_mask)]:
1022
+ if attn_mask is not None:
1023
+ tf.debugging.assert_equal(
1024
+ shape_list(attn_mask)[0],
1025
+ len(self.layers),
1026
+ message=(
1027
+ f"The {attn_mask_name} should be specified for {len(self.layers)} layers, but it is for"
1028
+ f" {shape_list(attn_mask)[0]}."
1029
+ ),
1030
+ )
1031
+ for idx, decoder_layer in enumerate(self.layers):
1032
+ # add LayerDrop (see https://arxiv.org/abs/1909.11556 for description)
1033
+ if output_hidden_states:
1034
+ all_hidden_states += (hidden_states,)
1035
+ dropout_probability = random.uniform(0, 1)
1036
+
1037
+ if training and (dropout_probability < self.layerdrop):
1038
+ continue
1039
+
1040
+ past_key_value = past_key_values[idx] if past_key_values is not None else None
1041
+
1042
+ hidden_states, layer_self_attn, layer_cross_attn, present_key_value = decoder_layer(
1043
+ hidden_states,
1044
+ attention_mask=combined_attention_mask,
1045
+ encoder_hidden_states=encoder_hidden_states,
1046
+ encoder_attention_mask=encoder_attention_mask,
1047
+ layer_head_mask=head_mask[idx] if head_mask is not None else None,
1048
+ cross_attn_layer_head_mask=cross_attn_head_mask[idx] if cross_attn_head_mask is not None else None,
1049
+ past_key_value=past_key_value,
1050
+ )
1051
+
1052
+ if use_cache:
1053
+ present_key_values += (present_key_value,)
1054
+
1055
+ if output_attentions:
1056
+ all_self_attns += (layer_self_attn,)
1057
+
1058
+ if encoder_hidden_states is not None:
1059
+ all_cross_attns += (layer_cross_attn,)
1060
+
1061
+ hidden_states = self.layer_norm(hidden_states)
1062
+
1063
+ if output_hidden_states:
1064
+ all_hidden_states += (hidden_states,)
1065
+
1066
+ if not return_dict:
1067
+ return hidden_states, present_key_values, all_hidden_states, all_self_attns, all_cross_attns
1068
+ else:
1069
+ return TFBaseModelOutputWithPastAndCrossAttentions(
1070
+ last_hidden_state=hidden_states,
1071
+ past_key_values=present_key_values,
1072
+ hidden_states=all_hidden_states,
1073
+ attentions=all_self_attns,
1074
+ cross_attentions=all_cross_attns,
1075
+ )
1076
+
1077
+ def build(self, input_shape=None):
1078
+ if self.built:
1079
+ return
1080
+ self.built = True
1081
+ if getattr(self, "embed_positions", None) is not None:
1082
+ with tf.name_scope(self.embed_positions.name):
1083
+ self.embed_positions.build(None)
1084
+ if getattr(self, "layer_norm", None) is not None:
1085
+ with tf.name_scope(self.layer_norm.name):
1086
+ self.layer_norm.build([None, None, self.config.d_model])
1087
+ if getattr(self, "layers", None) is not None:
1088
+ for layer in self.layers:
1089
+ with tf.name_scope(layer.name):
1090
+ layer.build(None)
1091
+
1092
+
1093
+ @keras_serializable
1094
+ class TFBlenderbotMainLayer(keras.layers.Layer):
1095
+ config_class = BlenderbotConfig
1096
+
1097
+ def __init__(self, config: BlenderbotConfig, **kwargs):
1098
+ super().__init__(**kwargs)
1099
+
1100
+ self.config = config
1101
+ self.shared = keras.layers.Embedding(
1102
+ input_dim=config.vocab_size,
1103
+ output_dim=config.d_model,
1104
+ embeddings_initializer=keras.initializers.TruncatedNormal(stddev=self.config.init_std),
1105
+ name="model.shared",
1106
+ )
1107
+ # Additional attribute to specify the expected name scope of the layer (for loading/storing weights)
1108
+ self.shared.load_weight_prefix = "model.shared"
1109
+
1110
+ self.encoder = TFBlenderbotEncoder(config, self.shared, name="encoder")
1111
+ self.decoder = TFBlenderbotDecoder(config, self.shared, name="decoder")
1112
+
1113
+ def get_input_embeddings(self):
1114
+ return self.shared
1115
+
1116
+ def set_input_embeddings(self, new_embeddings):
1117
+ self.shared = new_embeddings
1118
+ self.encoder.embed_tokens = self.shared
1119
+ self.decoder.embed_tokens = self.shared
1120
+
1121
+ @unpack_inputs
1122
+ def call(
1123
+ self,
1124
+ input_ids=None,
1125
+ attention_mask=None,
1126
+ decoder_input_ids=None,
1127
+ decoder_attention_mask=None,
1128
+ decoder_position_ids=None,
1129
+ head_mask=None,
1130
+ decoder_head_mask=None,
1131
+ cross_attn_head_mask=None,
1132
+ encoder_outputs: Optional[Union[Tuple, TFBaseModelOutput]] = None,
1133
+ past_key_values=None,
1134
+ inputs_embeds=None,
1135
+ decoder_inputs_embeds=None,
1136
+ use_cache=None,
1137
+ output_attentions=None,
1138
+ output_hidden_states=None,
1139
+ return_dict=None,
1140
+ training=False,
1141
+ **kwargs,
1142
+ ):
1143
+ output_hidden_states = (
1144
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1145
+ )
1146
+
1147
+ if encoder_outputs is None:
1148
+ encoder_outputs = self.encoder(
1149
+ input_ids=input_ids,
1150
+ attention_mask=attention_mask,
1151
+ head_mask=head_mask,
1152
+ inputs_embeds=inputs_embeds,
1153
+ output_attentions=output_attentions,
1154
+ output_hidden_states=output_hidden_states,
1155
+ return_dict=return_dict,
1156
+ training=training,
1157
+ )
1158
+ # If the user passed a tuple for encoder_outputs, we wrap it in a TFBaseModelOutput when return_dict=True
1159
+ elif return_dict and not isinstance(encoder_outputs, TFBaseModelOutput):
1160
+ encoder_outputs = TFBaseModelOutput(
1161
+ last_hidden_state=encoder_outputs[0],
1162
+ hidden_states=encoder_outputs[1] if len(encoder_outputs) > 1 else None,
1163
+ attentions=encoder_outputs[2] if len(encoder_outputs) > 2 else None,
1164
+ )
1165
+ # If the user passed a TFBaseModelOutput for encoder_outputs, we wrap it in a tuple when return_dict=False
1166
+ elif not return_dict and not isinstance(encoder_outputs, tuple):
1167
+ encoder_outputs = encoder_outputs.to_tuple()
1168
+
1169
+ decoder_outputs = self.decoder(
1170
+ decoder_input_ids,
1171
+ attention_mask=decoder_attention_mask,
1172
+ position_ids=decoder_position_ids,
1173
+ encoder_hidden_states=encoder_outputs[0],
1174
+ encoder_attention_mask=attention_mask,
1175
+ head_mask=decoder_head_mask,
1176
+ cross_attn_head_mask=cross_attn_head_mask,
1177
+ past_key_values=past_key_values,
1178
+ inputs_embeds=decoder_inputs_embeds,
1179
+ use_cache=use_cache,
1180
+ output_attentions=output_attentions,
1181
+ output_hidden_states=output_hidden_states,
1182
+ return_dict=return_dict,
1183
+ training=training,
1184
+ )
1185
+
1186
+ if not return_dict:
1187
+ return decoder_outputs + encoder_outputs
1188
+
1189
+ return TFSeq2SeqModelOutput(
1190
+ last_hidden_state=decoder_outputs.last_hidden_state,
1191
+ past_key_values=decoder_outputs.past_key_values,
1192
+ decoder_hidden_states=decoder_outputs.hidden_states,
1193
+ decoder_attentions=decoder_outputs.attentions,
1194
+ cross_attentions=decoder_outputs.cross_attentions,
1195
+ encoder_last_hidden_state=encoder_outputs.last_hidden_state,
1196
+ encoder_hidden_states=encoder_outputs.hidden_states,
1197
+ encoder_attentions=encoder_outputs.attentions,
1198
+ )
1199
+
1200
+ def build(self, input_shape=None):
1201
+ if self.built:
1202
+ return
1203
+ self.built = True
1204
+ # The shared/tied weights expect to be in the model base namespace
1205
+ # Adding "/" to the end (not the start!) of a tf.name_scope puts it in the root namespace rather than
1206
+ # the current one.
1207
+ with tf.name_scope(self.shared.load_weight_prefix + "/" + self.shared.name + "/"):
1208
+ self.shared.build(None)
1209
+ if getattr(self, "encoder", None) is not None:
1210
+ with tf.name_scope(self.encoder.name):
1211
+ self.encoder.build(None)
1212
+ if getattr(self, "decoder", None) is not None:
1213
+ with tf.name_scope(self.decoder.name):
1214
+ self.decoder.build(None)
1215
+
1216
+
1217
+ @add_start_docstrings(
1218
+ "The bare BLENDERBOT Model outputting raw hidden-states without any specific head on top.",
1219
+ BLENDERBOT_START_DOCSTRING,
1220
+ )
1221
+ class TFBlenderbotModel(TFBlenderbotPreTrainedModel):
1222
+ def __init__(self, config: BlenderbotConfig, *inputs, **kwargs):
1223
+ super().__init__(config, *inputs, **kwargs)
1224
+
1225
+ self.model = TFBlenderbotMainLayer(config, name="model")
1226
+
1227
+ def get_encoder(self):
1228
+ return self.model.encoder
1229
+
1230
+ def get_decoder(self):
1231
+ return self.model.decoder
1232
+
1233
+ @classmethod
1234
+ def from_pretrained(cls, pretrained_model_name_or_path: Optional[Union[str, os.PathLike]], *model_args, **kwargs):
1235
+ if pretrained_model_name_or_path == "facebook/blenderbot-90M":
1236
+ from ..blenderbot_small import TFBlenderbotSmallModel
1237
+
1238
+ warnings.warn(
1239
+ "The checkpoint `facebook/blenderbot-90M` is deprecated. In the future, please use the identical"
1240
+ " checkpoint `facebook/small_blenderbot-90M` with"
1241
+ " `TFBlenderbotSmallForConditionalGeneration.from_pretrained('facebook/small_blenderbot-90M')`"
1242
+ " instead.",
1243
+ FutureWarning,
1244
+ )
1245
+ return TFBlenderbotSmallModel.from_pretrained(pretrained_model_name_or_path)
1246
+
1247
+ return super().from_pretrained(pretrained_model_name_or_path, *model_args, **kwargs)
1248
+
1249
+ @unpack_inputs
1250
+ @add_start_docstrings_to_model_forward(BLENDERBOT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
1251
+ @add_code_sample_docstrings(
1252
+ checkpoint=_CHECKPOINT_FOR_DOC,
1253
+ output_type=TFSeq2SeqModelOutput,
1254
+ config_class=_CONFIG_FOR_DOC,
1255
+ )
1256
+ def call(
1257
+ self,
1258
+ input_ids: tf.Tensor | None = None,
1259
+ attention_mask: tf.Tensor | None = None,
1260
+ decoder_input_ids: tf.Tensor | None = None,
1261
+ decoder_attention_mask: tf.Tensor | None = None,
1262
+ decoder_position_ids: tf.Tensor | None = None,
1263
+ head_mask: tf.Tensor | None = None,
1264
+ decoder_head_mask: tf.Tensor | None = None,
1265
+ cross_attn_head_mask: tf.Tensor | None = None,
1266
+ encoder_outputs: Optional[Union[Tuple, TFBaseModelOutput]] = None,
1267
+ past_key_values: List[tf.Tensor] | None = None,
1268
+ inputs_embeds: tf.Tensor | None = None,
1269
+ decoder_inputs_embeds: tf.Tensor | None = None,
1270
+ use_cache: Optional[bool] = None,
1271
+ output_attentions: Optional[bool] = None,
1272
+ output_hidden_states: Optional[bool] = None,
1273
+ return_dict: Optional[bool] = None,
1274
+ training: Optional[bool] = False,
1275
+ **kwargs,
1276
+ ) -> Union[Tuple[tf.Tensor], TFSeq2SeqModelOutput]:
1277
+ outputs = self.model(
1278
+ input_ids=input_ids,
1279
+ attention_mask=attention_mask,
1280
+ decoder_input_ids=decoder_input_ids,
1281
+ decoder_attention_mask=decoder_attention_mask,
1282
+ decoder_position_ids=decoder_position_ids,
1283
+ head_mask=head_mask,
1284
+ decoder_head_mask=decoder_head_mask,
1285
+ cross_attn_head_mask=cross_attn_head_mask,
1286
+ encoder_outputs=encoder_outputs,
1287
+ past_key_values=past_key_values,
1288
+ inputs_embeds=inputs_embeds,
1289
+ decoder_inputs_embeds=decoder_inputs_embeds,
1290
+ use_cache=use_cache,
1291
+ output_attentions=output_attentions,
1292
+ output_hidden_states=output_hidden_states,
1293
+ return_dict=return_dict,
1294
+ training=training,
1295
+ )
1296
+
1297
+ return outputs
1298
+
1299
+ # Copied from transformers.models.bart.modeling_tf_bart.TFBartModel.serving_output
1300
+ def serving_output(self, output):
1301
+ pkv = tf.tuple(output.past_key_values)[1] if self.config.use_cache else None
1302
+ dec_hs = tf.convert_to_tensor(output.decoder_hidden_states) if self.config.output_hidden_states else None
1303
+ dec_attns = tf.convert_to_tensor(output.decoder_attentions) if self.config.output_attentions else None
1304
+ cross_attns = tf.convert_to_tensor(output.cross_attentions) if self.config.output_attentions else None
1305
+ enc_hs = tf.convert_to_tensor(output.encoder_hidden_states) if self.config.output_hidden_states else None
1306
+ enc_attns = tf.convert_to_tensor(output.encoder_attentions) if self.config.output_attentions else None
1307
+
1308
+ return TFSeq2SeqModelOutput(
1309
+ last_hidden_state=output.last_hidden_state,
1310
+ past_key_values=pkv,
1311
+ decoder_hidden_states=dec_hs,
1312
+ decoder_attentions=dec_attns,
1313
+ cross_attentions=cross_attns,
1314
+ encoder_last_hidden_state=output.encoder_last_hidden_state,
1315
+ encoder_hidden_states=enc_hs,
1316
+ encoder_attentions=enc_attns,
1317
+ )
1318
+
1319
+ def build(self, input_shape=None):
1320
+ if self.built:
1321
+ return
1322
+ self.built = True
1323
+ if getattr(self, "model", None) is not None:
1324
+ with tf.name_scope(self.model.name):
1325
+ self.model.build(None)
1326
+
1327
+
1328
+ # Copied from transformers.models.bart.modeling_tf_bart.BiasLayer
1329
+ class BiasLayer(keras.layers.Layer):
1330
+ """
1331
+ Bias as a layer. It is used for serialization purposes: `keras.Model.save_weights` stores on a per-layer basis,
1332
+ so all weights have to be registered in a layer.
1333
+ """
1334
+
1335
+ def __init__(self, shape, initializer, trainable, name, **kwargs):
1336
+ super().__init__(name=name, **kwargs)
1337
+ # Note: the name of this variable will NOT be scoped when serialized, i.e. it will not be in the format of
1338
+ # "outer_layer/inner_layer/.../name:0". Instead, it will be "name:0". For further details, see:
1339
+ # https://github.com/huggingface/transformers/pull/18833#issuecomment-1233090214
1340
+ self.bias = self.add_weight(name=name, shape=shape, initializer=initializer, trainable=trainable)
1341
+
1342
+ def call(self, x):
1343
+ return x + self.bias
1344
+
1345
+
1346
+ @add_start_docstrings(
1347
+ "The BLENDERBOT Model with a language modeling head. Can be used for summarization.",
1348
+ BLENDERBOT_START_DOCSTRING,
1349
+ )
1350
+ class TFBlenderbotForConditionalGeneration(TFBlenderbotPreTrainedModel, TFCausalLanguageModelingLoss):
1351
+ _keys_to_ignore_on_load_unexpected = [
1352
+ r"model.encoder.embed_tokens.weight",
1353
+ r"model.decoder.embed_tokens.weight",
1354
+ ]
1355
+
1356
+ def __init__(self, config, *inputs, **kwargs):
1357
+ super().__init__(config, *inputs, **kwargs)
1358
+ self.model = TFBlenderbotMainLayer(config, name="model")
1359
+ self.use_cache = config.use_cache
1360
+ # final_bias_logits is registered as a buffer in pytorch, so not trainable for the sake of consistency.
1361
+ self.bias_layer = BiasLayer(
1362
+ name="final_logits_bias", shape=[1, config.vocab_size], initializer="zeros", trainable=False
1363
+ )
1364
+
1365
+ def get_decoder(self):
1366
+ return self.model.decoder
1367
+
1368
+ def get_encoder(self):
1369
+ return self.model.encoder
1370
+
1371
+ def get_output_embeddings(self):
1372
+ return self.get_input_embeddings()
1373
+
1374
+ def set_output_embeddings(self, value):
1375
+ self.set_input_embeddings(value)
1376
+
1377
+ def get_bias(self):
1378
+ return {"final_logits_bias": self.bias_layer.bias}
1379
+
1380
+ def set_bias(self, value):
1381
+ # Replaces the existing layers containing bias for correct (de)serialization.
1382
+ vocab_size = value["final_logits_bias"].shape[-1]
1383
+ self.bias_layer = BiasLayer(
1384
+ name="final_logits_bias", shape=[1, vocab_size], initializer="zeros", trainable=False
1385
+ )
1386
+ self.bias_layer.bias.assign(value["final_logits_bias"])
1387
+
1388
+ @classmethod
1389
+ def from_pretrained(cls, pretrained_model_name_or_path: Optional[Union[str, os.PathLike]], *model_args, **kwargs):
1390
+ if pretrained_model_name_or_path == "facebook/blenderbot-90M":
1391
+ from ..blenderbot_small import TFBlenderbotSmallForConditionalGeneration
1392
+
1393
+ warnings.warn(
1394
+ "The checkpoint `facebook/blenderbot-90M` is deprecated. In the future, please use the identical"
1395
+ " checkpoint `facebook/small_blenderbot-90M` with"
1396
+ " `TFBlenderbotSmallForConditionalGeneration.from_pretrained('facebook/small_blenderbot-90M')`"
1397
+ " instead.",
1398
+ FutureWarning,
1399
+ )
1400
+ return TFBlenderbotSmallForConditionalGeneration.from_pretrained(pretrained_model_name_or_path)
1401
+
1402
+ return super().from_pretrained(pretrained_model_name_or_path, *model_args, **kwargs)
1403
+
1404
+ @unpack_inputs
1405
+ @add_start_docstrings_to_model_forward(BLENDERBOT_INPUTS_DOCSTRING)
1406
+ @replace_return_docstrings(output_type=TFSeq2SeqLMOutput, config_class=_CONFIG_FOR_DOC)
1407
+ @add_end_docstrings(BLENDERBOT_GENERATION_EXAMPLE)
1408
+ def call(
1409
+ self,
1410
+ input_ids: tf.Tensor | None = None,
1411
+ attention_mask: tf.Tensor | None = None,
1412
+ decoder_input_ids: tf.Tensor | None = None,
1413
+ decoder_attention_mask: tf.Tensor | None = None,
1414
+ decoder_position_ids: tf.Tensor | None = None,
1415
+ head_mask: tf.Tensor | None = None,
1416
+ decoder_head_mask: tf.Tensor | None = None,
1417
+ cross_attn_head_mask: tf.Tensor | None = None,
1418
+ encoder_outputs: Optional[Union[Tuple, TFBaseModelOutput]] = None,
1419
+ past_key_values: List[tf.Tensor] | None = None,
1420
+ inputs_embeds: tf.Tensor | None = None,
1421
+ decoder_inputs_embeds: tf.Tensor | None = None,
1422
+ use_cache: Optional[bool] = None,
1423
+ output_attentions: Optional[bool] = None,
1424
+ output_hidden_states: Optional[bool] = None,
1425
+ return_dict: Optional[bool] = None,
1426
+ labels: tf.Tensor | None = None,
1427
+ training: Optional[bool] = False,
1428
+ ) -> Union[Tuple[tf.Tensor], TFSeq2SeqLMOutput]:
1429
+ r"""
1430
+ labels (`tf.tensor` of shape `(batch_size, sequence_length)`, *optional*):
1431
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1432
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1433
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1434
+
1435
+ Returns:
1436
+
1437
+ """
1438
+ if labels is not None:
1439
+ labels = tf.where(
1440
+ labels == self.config.pad_token_id,
1441
+ tf.cast(tf.fill(shape_list(labels), -100), labels.dtype),
1442
+ labels,
1443
+ )
1444
+ use_cache = False
1445
+ if decoder_input_ids is None and decoder_inputs_embeds is None:
1446
+ decoder_input_ids = shift_tokens_right(
1447
+ labels, self.config.pad_token_id, self.config.decoder_start_token_id
1448
+ )
1449
+
1450
+ outputs = self.model(
1451
+ input_ids,
1452
+ attention_mask=attention_mask,
1453
+ decoder_input_ids=decoder_input_ids,
1454
+ encoder_outputs=encoder_outputs,
1455
+ decoder_attention_mask=decoder_attention_mask,
1456
+ decoder_position_ids=decoder_position_ids,
1457
+ head_mask=head_mask,
1458
+ decoder_head_mask=decoder_head_mask,
1459
+ cross_attn_head_mask=cross_attn_head_mask,
1460
+ past_key_values=past_key_values,
1461
+ inputs_embeds=inputs_embeds,
1462
+ decoder_inputs_embeds=decoder_inputs_embeds,
1463
+ use_cache=use_cache,
1464
+ output_attentions=output_attentions,
1465
+ output_hidden_states=output_hidden_states,
1466
+ return_dict=return_dict,
1467
+ training=training,
1468
+ )
1469
+ lm_logits = tf.matmul(outputs[0], self.model.shared.weights, transpose_b=True)
1470
+ lm_logits = self.bias_layer(lm_logits)
1471
+ masked_lm_loss = None if labels is None else self.hf_compute_loss(labels, lm_logits)
1472
+
1473
+ if not return_dict:
1474
+ output = (lm_logits,) + outputs[1:]
1475
+ return ((masked_lm_loss,) + output) if masked_lm_loss is not None else output
1476
+ return TFSeq2SeqLMOutput(
1477
+ loss=masked_lm_loss,
1478
+ logits=lm_logits,
1479
+ past_key_values=outputs.past_key_values, # index 1 of d outputs
1480
+ decoder_hidden_states=outputs.decoder_hidden_states, # index 2 of d outputs
1481
+ decoder_attentions=outputs.decoder_attentions, # index 3 of d outputs
1482
+ cross_attentions=outputs.cross_attentions, # index 4 of d outputs
1483
+ encoder_last_hidden_state=outputs.encoder_last_hidden_state, # index 0 of encoder outputs
1484
+ encoder_hidden_states=outputs.encoder_hidden_states, # 1 of e out
1485
+ encoder_attentions=outputs.encoder_attentions, # 2 of e out
1486
+ )
1487
+
1488
+ # Copied from transformers.models.bart.modeling_tf_bart.TFBartForConditionalGeneration.serving_output
1489
+ def serving_output(self, output):
1490
+ pkv = tf.tuple(output.past_key_values)[1] if self.config.use_cache else None
1491
+ dec_hs = tf.convert_to_tensor(output.decoder_hidden_states) if self.config.output_hidden_states else None
1492
+ dec_attns = tf.convert_to_tensor(output.decoder_attentions) if self.config.output_attentions else None
1493
+ cross_attns = tf.convert_to_tensor(output.cross_attentions) if self.config.output_attentions else None
1494
+ enc_hs = tf.convert_to_tensor(output.encoder_hidden_states) if self.config.output_hidden_states else None
1495
+ enc_attns = tf.convert_to_tensor(output.encoder_attentions) if self.config.output_attentions else None
1496
+
1497
+ return TFSeq2SeqLMOutput(
1498
+ logits=output.logits,
1499
+ past_key_values=pkv,
1500
+ decoder_hidden_states=dec_hs,
1501
+ decoder_attentions=dec_attns,
1502
+ cross_attentions=cross_attns,
1503
+ encoder_last_hidden_state=output.encoder_last_hidden_state,
1504
+ encoder_hidden_states=enc_hs,
1505
+ encoder_attentions=enc_attns,
1506
+ )
1507
+
1508
+ # Copied from transformers.models.bart.modeling_tf_bart.TFBartForConditionalGeneration.prepare_inputs_for_generation
1509
+ def prepare_inputs_for_generation(
1510
+ self,
1511
+ decoder_input_ids,
1512
+ past_key_values=None,
1513
+ attention_mask=None,
1514
+ decoder_attention_mask=None,
1515
+ head_mask=None,
1516
+ decoder_head_mask=None,
1517
+ cross_attn_head_mask=None,
1518
+ use_cache=None,
1519
+ encoder_outputs=None,
1520
+ **kwargs,
1521
+ ):
1522
+ # cut decoder_input_ids if past_key_values is used
1523
+ if past_key_values is not None:
1524
+ decoder_input_ids = decoder_input_ids[:, -1:]
1525
+
1526
+ if decoder_attention_mask is not None: # xla
1527
+ decoder_position_ids = tf.math.cumsum(decoder_attention_mask, axis=-1, exclusive=True)[:, -1:]
1528
+ elif past_key_values is not None: # no xla + past_key_values
1529
+ decoder_position_ids = past_key_values[0][0].shape[2]
1530
+ else: # no xla + no past_key_values
1531
+ decoder_position_ids = tf.range(decoder_input_ids.shape[1])
1532
+
1533
+ return {
1534
+ "input_ids": None, # encoder_outputs is defined. input_ids not needed
1535
+ "encoder_outputs": encoder_outputs,
1536
+ "past_key_values": past_key_values,
1537
+ "decoder_input_ids": decoder_input_ids,
1538
+ "attention_mask": attention_mask,
1539
+ "decoder_attention_mask": decoder_attention_mask,
1540
+ "decoder_position_ids": decoder_position_ids,
1541
+ "head_mask": head_mask,
1542
+ "decoder_head_mask": decoder_head_mask,
1543
+ "cross_attn_head_mask": cross_attn_head_mask,
1544
+ "use_cache": use_cache, # change this to avoid caching (presumably for debugging)
1545
+ }
1546
+
1547
+ def build(self, input_shape=None):
1548
+ if self.built:
1549
+ return
1550
+ self.built = True
1551
+ if getattr(self, "model", None) is not None:
1552
+ with tf.name_scope(self.model.name):
1553
+ self.model.build(None)
1554
+ if getattr(self, "bias_layer", None) is not None:
1555
+ with tf.name_scope(self.bias_layer.name):
1556
+ self.bias_layer.build(None)
env-llmeval/lib/python3.10/site-packages/transformers/models/blenderbot/tokenization_blenderbot.py ADDED
@@ -0,0 +1,439 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2021 The Facebook Inc. and The HuggingFace Inc. team. All rights reserved.
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 class for Blenderbot."""
16
+
17
+ import json
18
+ import os
19
+ from functools import lru_cache
20
+ from typing import List, Optional, Tuple
21
+
22
+ import regex as re
23
+
24
+ from ...tokenization_utils import AddedToken, PreTrainedTokenizer
25
+ from ...utils import logging
26
+
27
+
28
+ logger = logging.get_logger(__name__)
29
+
30
+
31
+ VOCAB_FILES_NAMES = {
32
+ "vocab_file": "vocab.json",
33
+ "merges_file": "merges.txt",
34
+ "tokenizer_config_file": "tokenizer_config.json",
35
+ }
36
+
37
+ PRETRAINED_VOCAB_FILES_MAP = {
38
+ "vocab_file": {"facebook/blenderbot-3B": "https://huggingface.co/facebook/blenderbot-3B/resolve/main/vocab.json"},
39
+ "merges_file": {"facebook/blenderbot-3B": "https://huggingface.co/facebook/blenderbot-3B/resolve/main/merges.txt"},
40
+ "tokenizer_config_file": {
41
+ "facebook/blenderbot-3B": "https://huggingface.co/facebook/blenderbot-3B/resolve/main/tokenizer_config.json"
42
+ },
43
+ }
44
+
45
+ PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES = {"facebook/blenderbot-3B": 128}
46
+
47
+
48
+ @lru_cache()
49
+ # Copied from transformers.models.roberta.tokenization_roberta.bytes_to_unicode
50
+ def bytes_to_unicode():
51
+ """
52
+ Returns list of utf-8 byte and a mapping to unicode strings. We specifically avoids mapping to whitespace/control
53
+ characters the bpe code barfs on.
54
+
55
+ The reversible bpe codes work on unicode strings. This means you need a large # of unicode characters in your vocab
56
+ if you want to avoid UNKs. When you're at something like a 10B token dataset you end up needing around 5K for
57
+ decent coverage. This is a significant percentage of your normal, say, 32K bpe vocab. To avoid that, we want lookup
58
+ tables between utf-8 bytes and unicode strings.
59
+ """
60
+ bs = (
61
+ list(range(ord("!"), ord("~") + 1)) + list(range(ord("¡"), ord("¬") + 1)) + list(range(ord("®"), ord("ÿ") + 1))
62
+ )
63
+ cs = bs[:]
64
+ n = 0
65
+ for b in range(2**8):
66
+ if b not in bs:
67
+ bs.append(b)
68
+ cs.append(2**8 + n)
69
+ n += 1
70
+ cs = [chr(n) for n in cs]
71
+ return dict(zip(bs, cs))
72
+
73
+
74
+ # Copied from transformers.models.roberta.tokenization_roberta.get_pairs
75
+ def get_pairs(word):
76
+ """
77
+ Return set of symbol pairs in a word.
78
+
79
+ Word is represented as tuple of symbols (symbols being variable-length strings).
80
+ """
81
+ pairs = set()
82
+ prev_char = word[0]
83
+ for char in word[1:]:
84
+ pairs.add((prev_char, char))
85
+ prev_char = char
86
+ return pairs
87
+
88
+
89
+ class BlenderbotTokenizer(PreTrainedTokenizer):
90
+ """
91
+ Constructs a Blenderbot tokenizer, derived from the GPT-2 tokenizer, using byte-level Byte-Pair-Encoding.
92
+
93
+ This tokenizer has been trained to treat spaces like parts of the tokens (a bit like sentencepiece) so a word will
94
+ be encoded differently whether it is at the beginning of the sentence (without space) or not:
95
+
96
+ ```python
97
+ >>> from transformers import BlenderbotTokenizer
98
+
99
+ >>> tokenizer = BlenderbotTokenizer.from_pretrained("facebook/blenderbot-3B")
100
+ >>> tokenizer.add_prefix_space = False
101
+ >>> tokenizer("Hello world")["input_ids"]
102
+ [47, 921, 86, 1085, 2]
103
+
104
+ >>> tokenizer(" Hello world")["input_ids"]
105
+ [6950, 1085, 2]
106
+ ```
107
+
108
+ You can get around that behavior by passing `add_prefix_space=True` when instantiating this tokenizer or when you
109
+ call it on some text, but since the model was not pretrained this way, it might yield a decrease in performance.
110
+
111
+ <Tip>
112
+
113
+ When used with `is_split_into_words=True`, this tokenizer will add a space before each word (even the first one).
114
+
115
+ </Tip>
116
+
117
+ This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to
118
+ this superclass for more information regarding those methods.
119
+
120
+ Args:
121
+ vocab_file (`str`):
122
+ Path to the vocabulary file.
123
+ merges_file (`str`):
124
+ Path to the merges file.
125
+ errors (`str`, *optional*, defaults to `"replace"`):
126
+ Paradigm to follow when decoding bytes to UTF-8. See
127
+ [bytes.decode](https://docs.python.org/3/library/stdtypes.html#bytes.decode) for more information.
128
+ bos_token (`str`, *optional*, defaults to `"<s>"`):
129
+ The beginning of sequence token that was used during pretraining. Can be used a sequence classifier token.
130
+
131
+ <Tip>
132
+
133
+ When building a sequence using special tokens, this is not the token that is used for the beginning of
134
+ sequence. The token used is the `cls_token`.
135
+
136
+ </Tip>
137
+
138
+ eos_token (`str`, *optional*, defaults to `"</s>"`):
139
+ The end of sequence token.
140
+
141
+ <Tip>
142
+
143
+ When building a sequence using special tokens, this is not the token that is used for the end of sequence.
144
+ The token used is the `sep_token`.
145
+
146
+ </Tip>
147
+
148
+ sep_token (`str`, *optional*, defaults to `"</s>"`):
149
+ The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
150
+ sequence classification or for a text and a question for question answering. It is also used as the last
151
+ token of a sequence built with special tokens.
152
+ cls_token (`str`, *optional*, defaults to `"<s>"`):
153
+ The classifier token which is used when doing sequence classification (classification of the whole sequence
154
+ instead of per-token classification). It is the first token of the sequence when built with special tokens.
155
+ unk_token (`str`, *optional*, defaults to `"<unk>"`):
156
+ The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
157
+ token instead.
158
+ pad_token (`str`, *optional*, defaults to `"<pad>"`):
159
+ The token used for padding, for example when batching sequences of different lengths.
160
+ mask_token (`str`, *optional*, defaults to `"<mask>"`):
161
+ The token used for masking values. This is the token used when training this model with masked language
162
+ modeling. This is the token which the model will try to predict.
163
+ add_prefix_space (`bool`, *optional*, defaults to `False`):
164
+ Whether or not to add an initial space to the input. This allows to treat the leading word just as any
165
+ other word. (Blenderbot tokenizer detect beginning of words by the preceding space).
166
+ """
167
+
168
+ vocab_files_names = VOCAB_FILES_NAMES
169
+ pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP
170
+ max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
171
+ model_input_names = ["input_ids", "attention_mask"]
172
+
173
+ # Copied from transformers.models.roberta.tokenization_roberta.RobertaTokenizer.__init__ with Roberta->Blenderbot, RoBERTa->Blenderbot
174
+ def __init__(
175
+ self,
176
+ vocab_file,
177
+ merges_file,
178
+ errors="replace",
179
+ bos_token="<s>",
180
+ eos_token="</s>",
181
+ sep_token="</s>",
182
+ cls_token="<s>",
183
+ unk_token="<unk>",
184
+ pad_token="<pad>",
185
+ mask_token="<mask>",
186
+ add_prefix_space=False,
187
+ **kwargs,
188
+ ):
189
+ bos_token = AddedToken(bos_token, lstrip=False, rstrip=False) if isinstance(bos_token, str) else bos_token
190
+ pad_token = AddedToken(pad_token, lstrip=False, rstrip=False) if isinstance(pad_token, str) else pad_token
191
+ eos_token = AddedToken(eos_token, lstrip=False, rstrip=False) if isinstance(eos_token, str) else eos_token
192
+ unk_token = AddedToken(unk_token, lstrip=False, rstrip=False) if isinstance(unk_token, str) else unk_token
193
+ sep_token = AddedToken(sep_token, lstrip=False, rstrip=False) if isinstance(sep_token, str) else sep_token
194
+ cls_token = AddedToken(cls_token, lstrip=False, rstrip=False) if isinstance(cls_token, str) else cls_token
195
+
196
+ # Mask token behave like a normal word, i.e. include the space before it
197
+ mask_token = (
198
+ AddedToken(mask_token, lstrip=True, rstrip=False, normalized=False)
199
+ if isinstance(mask_token, str)
200
+ else mask_token
201
+ )
202
+
203
+ # these special tokens are not part of the vocab.json, let's add them in the correct order
204
+
205
+ with open(vocab_file, encoding="utf-8") as vocab_handle:
206
+ self.encoder = json.load(vocab_handle)
207
+ self.decoder = {v: k for k, v in self.encoder.items()}
208
+ self.errors = errors # how to handle errors in decoding
209
+ self.byte_encoder = bytes_to_unicode()
210
+ self.byte_decoder = {v: k for k, v in self.byte_encoder.items()}
211
+ with open(merges_file, encoding="utf-8") as merges_handle:
212
+ bpe_merges = merges_handle.read().split("\n")[1:-1]
213
+ bpe_merges = [tuple(merge.split()) for merge in bpe_merges]
214
+ self.bpe_ranks = dict(zip(bpe_merges, range(len(bpe_merges))))
215
+ self.cache = {}
216
+ self.add_prefix_space = add_prefix_space
217
+
218
+ # Should have added re.IGNORECASE so BPE merges can happen for capitalized versions of contractions
219
+ self.pat = re.compile(r"""'s|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+""")
220
+
221
+ super().__init__(
222
+ errors=errors,
223
+ bos_token=bos_token,
224
+ eos_token=eos_token,
225
+ unk_token=unk_token,
226
+ sep_token=sep_token,
227
+ cls_token=cls_token,
228
+ pad_token=pad_token,
229
+ mask_token=mask_token,
230
+ add_prefix_space=add_prefix_space,
231
+ **kwargs,
232
+ )
233
+
234
+ @property
235
+ # Copied from transformers.models.roberta.tokenization_roberta.RobertaTokenizer.vocab_size with Roberta->Blenderbot, RoBERTa->Blenderbot
236
+ def vocab_size(self):
237
+ return len(self.encoder)
238
+
239
+ # Copied from transformers.models.roberta.tokenization_roberta.RobertaTokenizer.get_vocab with Roberta->Blenderbot, RoBERTa->Blenderbot
240
+ def get_vocab(self):
241
+ vocab = dict(self.encoder).copy()
242
+ vocab.update(self.added_tokens_encoder)
243
+ return vocab
244
+
245
+ # Copied from transformers.models.roberta.tokenization_roberta.RobertaTokenizer.bpe with Roberta->Blenderbot, RoBERTa->Blenderbot
246
+ def bpe(self, token):
247
+ if token in self.cache:
248
+ return self.cache[token]
249
+ word = tuple(token)
250
+ pairs = get_pairs(word)
251
+
252
+ if not pairs:
253
+ return token
254
+
255
+ while True:
256
+ bigram = min(pairs, key=lambda pair: self.bpe_ranks.get(pair, float("inf")))
257
+ if bigram not in self.bpe_ranks:
258
+ break
259
+ first, second = bigram
260
+ new_word = []
261
+ i = 0
262
+ while i < len(word):
263
+ try:
264
+ j = word.index(first, i)
265
+ except ValueError:
266
+ new_word.extend(word[i:])
267
+ break
268
+ else:
269
+ new_word.extend(word[i:j])
270
+ i = j
271
+
272
+ if word[i] == first and i < len(word) - 1 and word[i + 1] == second:
273
+ new_word.append(first + second)
274
+ i += 2
275
+ else:
276
+ new_word.append(word[i])
277
+ i += 1
278
+ new_word = tuple(new_word)
279
+ word = new_word
280
+ if len(word) == 1:
281
+ break
282
+ else:
283
+ pairs = get_pairs(word)
284
+ word = " ".join(word)
285
+ self.cache[token] = word
286
+ return word
287
+
288
+ # Copied from transformers.models.roberta.tokenization_roberta.RobertaTokenizer._tokenize with Roberta->Blenderbot, RoBERTa->Blenderbot
289
+ def _tokenize(self, text):
290
+ """Tokenize a string."""
291
+ bpe_tokens = []
292
+ for token in re.findall(self.pat, text):
293
+ token = "".join(
294
+ self.byte_encoder[b] for b in token.encode("utf-8")
295
+ ) # Maps all our bytes to unicode strings, avoiding control tokens of the BPE (spaces in our case)
296
+ bpe_tokens.extend(bpe_token for bpe_token in self.bpe(token).split(" "))
297
+ return bpe_tokens
298
+
299
+ # Copied from transformers.models.roberta.tokenization_roberta.RobertaTokenizer._convert_token_to_id with Roberta->Blenderbot, RoBERTa->Blenderbot
300
+ def _convert_token_to_id(self, token):
301
+ """Converts a token (str) in an id using the vocab."""
302
+ return self.encoder.get(token, self.encoder.get(self.unk_token))
303
+
304
+ # Copied from transformers.models.roberta.tokenization_roberta.RobertaTokenizer._convert_id_to_token with Roberta->Blenderbot, RoBERTa->Blenderbot
305
+ def _convert_id_to_token(self, index):
306
+ """Converts an index (integer) in a token (str) using the vocab."""
307
+ return self.decoder.get(index)
308
+
309
+ # Copied from transformers.models.roberta.tokenization_roberta.RobertaTokenizer.convert_tokens_to_string with Roberta->Blenderbot, RoBERTa->Blenderbot
310
+ def convert_tokens_to_string(self, tokens):
311
+ """Converts a sequence of tokens (string) in a single string."""
312
+ text = "".join(tokens)
313
+ text = bytearray([self.byte_decoder[c] for c in text]).decode("utf-8", errors=self.errors)
314
+ return text
315
+
316
+ # Copied from transformers.models.roberta.tokenization_roberta.RobertaTokenizer.save_vocabulary with Roberta->Blenderbot, RoBERTa->Blenderbot
317
+ def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
318
+ if not os.path.isdir(save_directory):
319
+ logger.error(f"Vocabulary path ({save_directory}) should be a directory")
320
+ return
321
+ vocab_file = os.path.join(
322
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
323
+ )
324
+ merge_file = os.path.join(
325
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["merges_file"]
326
+ )
327
+
328
+ with open(vocab_file, "w", encoding="utf-8") as f:
329
+ f.write(json.dumps(self.encoder, indent=2, sort_keys=True, ensure_ascii=False) + "\n")
330
+
331
+ index = 0
332
+ with open(merge_file, "w", encoding="utf-8") as writer:
333
+ writer.write("#version: 0.2\n")
334
+ for bpe_tokens, token_index in sorted(self.bpe_ranks.items(), key=lambda kv: kv[1]):
335
+ if index != token_index:
336
+ logger.warning(
337
+ f"Saving vocabulary to {merge_file}: BPE merge indices are not consecutive."
338
+ " Please check that the tokenizer is not corrupted!"
339
+ )
340
+ index = token_index
341
+ writer.write(" ".join(bpe_tokens) + "\n")
342
+ index += 1
343
+
344
+ return vocab_file, merge_file
345
+
346
+ # Copied from transformers.models.roberta.tokenization_roberta.RobertaTokenizer.get_special_tokens_mask with Roberta->Blenderbot, RoBERTa->Blenderbot
347
+ def get_special_tokens_mask(
348
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None, already_has_special_tokens: bool = False
349
+ ) -> List[int]:
350
+ """
351
+ Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
352
+ special tokens using the tokenizer `prepare_for_model` method.
353
+
354
+ Args:
355
+ token_ids_0 (`List[int]`):
356
+ List of IDs.
357
+ token_ids_1 (`List[int]`, *optional*):
358
+ Optional second list of IDs for sequence pairs.
359
+ already_has_special_tokens (`bool`, *optional*, defaults to `False`):
360
+ Whether or not the token list is already formatted with special tokens for the model.
361
+
362
+ Returns:
363
+ `List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
364
+ """
365
+ if already_has_special_tokens:
366
+ return super().get_special_tokens_mask(
367
+ token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
368
+ )
369
+
370
+ if token_ids_1 is None:
371
+ return [1] + ([0] * len(token_ids_0)) + [1]
372
+ return [1] + ([0] * len(token_ids_0)) + [1, 1] + ([0] * len(token_ids_1)) + [1]
373
+
374
+ # Copied from transformers.models.roberta.tokenization_roberta.RobertaTokenizer.create_token_type_ids_from_sequences with Roberta->Blenderbot, RoBERTa->Blenderbot
375
+ def create_token_type_ids_from_sequences(
376
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
377
+ ) -> List[int]:
378
+ """
379
+ Create a mask from the two sequences passed to be used in a sequence-pair classification task. Blenderbot does not
380
+ make use of token type ids, therefore a list of zeros is returned.
381
+
382
+ Args:
383
+ token_ids_0 (`List[int]`):
384
+ List of IDs.
385
+ token_ids_1 (`List[int]`, *optional*):
386
+ Optional second list of IDs for sequence pairs.
387
+
388
+ Returns:
389
+ `List[int]`: List of zeros.
390
+ """
391
+ sep = [self.sep_token_id]
392
+ cls = [self.cls_token_id]
393
+
394
+ if token_ids_1 is None:
395
+ return len(cls + token_ids_0 + sep) * [0]
396
+ return len(cls + token_ids_0 + sep + sep + token_ids_1 + sep) * [0]
397
+
398
+ # Copied from transformers.models.roberta.tokenization_roberta.RobertaTokenizer.prepare_for_tokenization with Roberta->Blenderbot, RoBERTa->Blenderbot
399
+ def prepare_for_tokenization(self, text, is_split_into_words=False, **kwargs):
400
+ add_prefix_space = kwargs.pop("add_prefix_space", self.add_prefix_space)
401
+ if (is_split_into_words or add_prefix_space) and (len(text) > 0 and not text[0].isspace()):
402
+ text = " " + text
403
+ return (text, kwargs)
404
+
405
+ def build_inputs_with_special_tokens(self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None):
406
+ """
407
+ Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
408
+ adding special tokens. A Blenderbot sequence has the following format:
409
+ - single sequence: ` X </s>`
410
+
411
+ Args:
412
+ token_ids_0 (`List[int]`):
413
+ List of IDs to which the special tokens will be added
414
+ token_ids_1 (`List[int]`, *optional*):
415
+ Will be ignored
416
+ Returns:
417
+ `List[int]`: list of [input IDs](../glossary#input-ids) with the appropriate special tokens.
418
+ """
419
+ return token_ids_0 + [self.eos_token_id]
420
+
421
+ @property
422
+ def default_chat_template(self):
423
+ """
424
+ A very simple chat template that just adds whitespace between messages.
425
+ """
426
+ logger.warning_once(
427
+ "\nNo chat template is defined for this tokenizer - using the default template "
428
+ f"for the {self.__class__.__name__} class. If the default is not appropriate for "
429
+ "your model, please set `tokenizer.chat_template` to an appropriate template. "
430
+ "See https://huggingface.co/docs/transformers/main/chat_templating for more information.\n"
431
+ )
432
+ return (
433
+ "{% for message in messages %}"
434
+ "{% if message['role'] == 'user' %}{{ ' ' }}{% endif %}"
435
+ "{{ message['content'] }}"
436
+ "{% if not loop.last %}{{ ' ' }}{% endif %}"
437
+ "{% endfor %}"
438
+ "{{ eos_token }}"
439
+ )
env-llmeval/lib/python3.10/site-packages/transformers/models/blenderbot/tokenization_blenderbot_fast.py ADDED
@@ -0,0 +1,321 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2021 The Facebook Inc. and The HuggingFace Inc. team. All rights reserved.
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
+ """Fast Tokenization class for Blenderbot."""
16
+ import json
17
+ from typing import List, Optional, Tuple
18
+
19
+ from tokenizers import pre_tokenizers, processors
20
+
21
+ from ...tokenization_utils_base import AddedToken, BatchEncoding
22
+ from ...tokenization_utils_fast import PreTrainedTokenizerFast
23
+ from ...utils import logging
24
+ from .tokenization_blenderbot import BlenderbotTokenizer
25
+
26
+
27
+ logger = logging.get_logger(__name__)
28
+
29
+
30
+ VOCAB_FILES_NAMES = {
31
+ "vocab_file": "vocab.json",
32
+ "merges_file": "merges.txt",
33
+ "tokenizer_config_file": "tokenizer_config.json",
34
+ }
35
+
36
+ PRETRAINED_VOCAB_FILES_MAP = {
37
+ "vocab_file": {"facebook/blenderbot-3B": "https://huggingface.co/facebook/blenderbot-3B/resolve/main/vocab.json"},
38
+ "merges_file": {"facebook/blenderbot-3B": "https://huggingface.co/facebook/blenderbot-3B/resolve/main/merges.txt"},
39
+ "tokenizer_config_file": {
40
+ "facebook/blenderbot-3B": "https://huggingface.co/facebook/blenderbot-3B/resolve/main/tokenizer_config.json"
41
+ },
42
+ }
43
+
44
+ PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES = {"facebook/blenderbot-3B": 128}
45
+
46
+
47
+ class BlenderbotTokenizerFast(PreTrainedTokenizerFast):
48
+ """
49
+ Construct a "fast" Blenderbot tokenizer (backed by HuggingFace's *tokenizers* library), derived from the GPT-2
50
+ tokenizer, using byte-level Byte-Pair-Encoding.
51
+
52
+ This tokenizer has been trained to treat spaces like parts of the tokens (a bit like sentencepiece) so a word will
53
+ be encoded differently whether it is at the beginning of the sentence (without space) or not:
54
+
55
+ ```python
56
+ >>> from transformers import BlenderbotTokenizerFast
57
+
58
+ >>> tokenizer = BlenderbotTokenizerFast.from_pretrained("facebook/blenderbot-3B")
59
+ >>> tokenizer("Hello world")["input_ids"]
60
+ [6950, 1085, 2]
61
+
62
+ >>> tokenizer(" Hello world")["input_ids"]
63
+ [6950, 1085, 2]
64
+ ```
65
+
66
+ You can get around that behavior by passing `add_prefix_space=True` when instantiating this tokenizer or when you
67
+ call it on some text, but since the model was not pretrained this way, it might yield a decrease in performance.
68
+
69
+ <Tip>
70
+
71
+ When used with `is_split_into_words=True`, this tokenizer needs to be instantiated with `add_prefix_space=True`.
72
+
73
+ </Tip>
74
+
75
+ This tokenizer inherits from [`PreTrainedTokenizerFast`] which contains most of the main methods. Users should
76
+ refer to this superclass for more information regarding those methods.
77
+
78
+ Args:
79
+ vocab_file (`str`):
80
+ Path to the vocabulary file.
81
+ merges_file (`str`):
82
+ Path to the merges file.
83
+ errors (`str`, *optional*, defaults to `"replace"`):
84
+ Paradigm to follow when decoding bytes to UTF-8. See
85
+ [bytes.decode](https://docs.python.org/3/library/stdtypes.html#bytes.decode) for more information.
86
+ bos_token (`str`, *optional*, defaults to `"<s>"`):
87
+ The beginning of sequence token that was used during pretraining. Can be used a sequence classifier token.
88
+
89
+ <Tip>
90
+
91
+ When building a sequence using special tokens, this is not the token that is used for the beginning of
92
+ sequence. The token used is the `cls_token`.
93
+
94
+ </Tip>
95
+
96
+ eos_token (`str`, *optional*, defaults to `"</s>"`):
97
+ The end of sequence token.
98
+
99
+ <Tip>
100
+
101
+ When building a sequence using special tokens, this is not the token that is used for the end of sequence.
102
+ The token used is the `sep_token`.
103
+
104
+ </Tip>
105
+
106
+ sep_token (`str`, *optional*, defaults to `"</s>"`):
107
+ The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
108
+ sequence classification or for a text and a question for question answering. It is also used as the last
109
+ token of a sequence built with special tokens.
110
+ cls_token (`str`, *optional*, defaults to `"<s>"`):
111
+ The classifier token which is used when doing sequence classification (classification of the whole sequence
112
+ instead of per-token classification). It is the first token of the sequence when built with special tokens.
113
+ unk_token (`str`, *optional*, defaults to `"<unk>"`):
114
+ The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
115
+ token instead.
116
+ pad_token (`str`, *optional*, defaults to `"<pad>"`):
117
+ The token used for padding, for example when batching sequences of different lengths.
118
+ mask_token (`str`, *optional*, defaults to `"<mask>"`):
119
+ The token used for masking values. This is the token used when training this model with masked language
120
+ modeling. This is the token which the model will try to predict.
121
+ add_prefix_space (`bool`, *optional*, defaults to `False`):
122
+ Whether or not to add an initial space to the input. This allows to treat the leading word just as any
123
+ other word. (Blenderbot tokenizer detect beginning of words by the preceding space).
124
+ trim_offsets (`bool`, *optional*, defaults to `True`):
125
+ Whether the post processing step should trim offsets to avoid including whitespaces.
126
+ """
127
+
128
+ vocab_files_names = VOCAB_FILES_NAMES
129
+ pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP
130
+ max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
131
+ model_input_names = ["input_ids", "attention_mask"]
132
+ slow_tokenizer_class = BlenderbotTokenizer
133
+
134
+ # Copied from transformers.models.roberta.tokenization_roberta_fast.RobertaTokenizerFast.__init__ with Roberta->Blenderbot, RoBERTa->Blenderbot
135
+ def __init__(
136
+ self,
137
+ vocab_file=None,
138
+ merges_file=None,
139
+ tokenizer_file=None,
140
+ errors="replace",
141
+ bos_token="<s>",
142
+ eos_token="</s>",
143
+ sep_token="</s>",
144
+ cls_token="<s>",
145
+ unk_token="<unk>",
146
+ pad_token="<pad>",
147
+ mask_token="<mask>",
148
+ add_prefix_space=False,
149
+ trim_offsets=True,
150
+ **kwargs,
151
+ ):
152
+ mask_token = (
153
+ AddedToken(mask_token, lstrip=True, rstrip=False, normalized=False)
154
+ if isinstance(mask_token, str)
155
+ else mask_token
156
+ )
157
+ super().__init__(
158
+ vocab_file,
159
+ merges_file,
160
+ tokenizer_file=tokenizer_file,
161
+ errors=errors,
162
+ bos_token=bos_token,
163
+ eos_token=eos_token,
164
+ sep_token=sep_token,
165
+ cls_token=cls_token,
166
+ unk_token=unk_token,
167
+ pad_token=pad_token,
168
+ mask_token=mask_token,
169
+ add_prefix_space=add_prefix_space,
170
+ trim_offsets=trim_offsets,
171
+ **kwargs,
172
+ )
173
+
174
+ pre_tok_state = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__())
175
+ if pre_tok_state.get("add_prefix_space", add_prefix_space) != add_prefix_space:
176
+ pre_tok_class = getattr(pre_tokenizers, pre_tok_state.pop("type"))
177
+ pre_tok_state["add_prefix_space"] = add_prefix_space
178
+ self.backend_tokenizer.pre_tokenizer = pre_tok_class(**pre_tok_state)
179
+
180
+ self.add_prefix_space = add_prefix_space
181
+
182
+ tokenizer_component = "post_processor"
183
+ tokenizer_component_instance = getattr(self.backend_tokenizer, tokenizer_component, None)
184
+ if tokenizer_component_instance:
185
+ state = json.loads(tokenizer_component_instance.__getstate__())
186
+
187
+ # The lists 'sep' and 'cls' must be cased in tuples for the object `post_processor_class`
188
+ if "sep" in state:
189
+ state["sep"] = tuple(state["sep"])
190
+ if "cls" in state:
191
+ state["cls"] = tuple(state["cls"])
192
+
193
+ changes_to_apply = False
194
+
195
+ if state.get("add_prefix_space", add_prefix_space) != add_prefix_space:
196
+ state["add_prefix_space"] = add_prefix_space
197
+ changes_to_apply = True
198
+
199
+ if state.get("trim_offsets", trim_offsets) != trim_offsets:
200
+ state["trim_offsets"] = trim_offsets
201
+ changes_to_apply = True
202
+
203
+ if changes_to_apply:
204
+ component_class = getattr(processors, state.pop("type"))
205
+ new_value = component_class(**state)
206
+ setattr(self.backend_tokenizer, tokenizer_component, new_value)
207
+
208
+ @property
209
+ # Copied from transformers.models.roberta.tokenization_roberta_fast.RobertaTokenizerFast.mask_token with Roberta->Blenderbot, RoBERTa->Blenderbot
210
+ def mask_token(self) -> str:
211
+ """
212
+ `str`: Mask token, to use when training a model with masked-language modeling. Log an error if used while not
213
+ having been set.
214
+
215
+ Blenderbot tokenizer has a special mask token to be usable in the fill-mask pipeline. The mask token will greedily
216
+ comprise the space before the *<mask>*.
217
+ """
218
+ if self._mask_token is None:
219
+ if self.verbose:
220
+ logger.error("Using mask_token, but it is not set yet.")
221
+ return None
222
+ return str(self._mask_token)
223
+
224
+ @mask_token.setter
225
+ def mask_token(self, value):
226
+ """
227
+ Overriding the default behavior of the mask token to have it eat the space before it.
228
+
229
+ This is needed to preserve backward compatibility with all the previously used models based on Roberta.
230
+ """
231
+ # Mask token behave like a normal word, i.e. include the space before it
232
+ # So we set lstrip to True
233
+ value = AddedToken(value, lstrip=True, rstrip=False) if isinstance(value, str) else value
234
+ self._mask_token = value
235
+
236
+ # Copied from transformers.models.roberta.tokenization_roberta_fast.RobertaTokenizerFast._batch_encode_plus with Roberta->Blenderbot, RoBERTa->Blenderbot
237
+ def _batch_encode_plus(self, *args, **kwargs) -> BatchEncoding:
238
+ is_split_into_words = kwargs.get("is_split_into_words", False)
239
+ assert self.add_prefix_space or not is_split_into_words, (
240
+ f"You need to instantiate {self.__class__.__name__} with add_prefix_space=True "
241
+ "to use it with pretokenized inputs."
242
+ )
243
+
244
+ return super()._batch_encode_plus(*args, **kwargs)
245
+
246
+ # Copied from transformers.models.roberta.tokenization_roberta_fast.RobertaTokenizerFast._encode_plus with Roberta->Blenderbot, RoBERTa->Blenderbot
247
+ def _encode_plus(self, *args, **kwargs) -> BatchEncoding:
248
+ is_split_into_words = kwargs.get("is_split_into_words", False)
249
+
250
+ assert self.add_prefix_space or not is_split_into_words, (
251
+ f"You need to instantiate {self.__class__.__name__} with add_prefix_space=True "
252
+ "to use it with pretokenized inputs."
253
+ )
254
+
255
+ return super()._encode_plus(*args, **kwargs)
256
+
257
+ # Copied from transformers.models.roberta.tokenization_roberta_fast.RobertaTokenizerFast.save_vocabulary with Roberta->Blenderbot, RoBERTa->Blenderbot
258
+ def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
259
+ files = self._tokenizer.model.save(save_directory, name=filename_prefix)
260
+ return tuple(files)
261
+
262
+ # Copied from transformers.models.roberta.tokenization_roberta_fast.RobertaTokenizerFast.create_token_type_ids_from_sequences with Roberta->Blenderbot, RoBERTa->Blenderbot
263
+ def create_token_type_ids_from_sequences(
264
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
265
+ ) -> List[int]:
266
+ """
267
+ Create a mask from the two sequences passed to be used in a sequence-pair classification task. Blenderbot does not
268
+ make use of token type ids, therefore a list of zeros is returned.
269
+
270
+ Args:
271
+ token_ids_0 (`List[int]`):
272
+ List of IDs.
273
+ token_ids_1 (`List[int]`, *optional*):
274
+ Optional second list of IDs for sequence pairs.
275
+
276
+ Returns:
277
+ `List[int]`: List of zeros.
278
+ """
279
+ sep = [self.sep_token_id]
280
+ cls = [self.cls_token_id]
281
+
282
+ if token_ids_1 is None:
283
+ return len(cls + token_ids_0 + sep) * [0]
284
+ return len(cls + token_ids_0 + sep + sep + token_ids_1 + sep) * [0]
285
+
286
+ def build_inputs_with_special_tokens(self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None):
287
+ """
288
+ Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
289
+ adding special tokens. A Blenderbot sequence has the following format:
290
+ - single sequence: ` X </s>`
291
+
292
+ Args:
293
+ token_ids_0 (`List[int]`):
294
+ List of IDs to which the special tokens will be added
295
+ token_ids_1 (`List[int]`, *optional*):
296
+ Will be ignored
297
+ Returns:
298
+ `List[int]`: list of [input IDs](../glossary#input-ids) with the appropriate special tokens.
299
+ """
300
+ return token_ids_0 + [self.eos_token_id]
301
+
302
+ @property
303
+ # Copied from transformers.models.blenderbot.tokenization_blenderbot.BlenderbotTokenizer.default_chat_template
304
+ def default_chat_template(self):
305
+ """
306
+ A very simple chat template that just adds whitespace between messages.
307
+ """
308
+ logger.warning_once(
309
+ "\nNo chat template is defined for this tokenizer - using the default template "
310
+ f"for the {self.__class__.__name__} class. If the default is not appropriate for "
311
+ "your model, please set `tokenizer.chat_template` to an appropriate template. "
312
+ "See https://huggingface.co/docs/transformers/main/chat_templating for more information.\n"
313
+ )
314
+ return (
315
+ "{% for message in messages %}"
316
+ "{% if message['role'] == 'user' %}{{ ' ' }}{% endif %}"
317
+ "{{ message['content'] }}"
318
+ "{% if not loop.last %}{{ ' ' }}{% endif %}"
319
+ "{% endfor %}"
320
+ "{{ eos_token }}"
321
+ )
env-llmeval/lib/python3.10/site-packages/transformers/models/blenderbot_small/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (2.05 kB). View file
 
env-llmeval/lib/python3.10/site-packages/transformers/models/blenderbot_small/__pycache__/configuration_blenderbot_small.cpython-310.pyc ADDED
Binary file (12.5 kB). View file
 
env-llmeval/lib/python3.10/site-packages/transformers/models/blenderbot_small/__pycache__/modeling_blenderbot_small.cpython-310.pyc ADDED
Binary file (52.5 kB). View file
 
env-llmeval/lib/python3.10/site-packages/transformers/models/blenderbot_small/__pycache__/modeling_flax_blenderbot_small.cpython-310.pyc ADDED
Binary file (43.2 kB). View file
 
env-llmeval/lib/python3.10/site-packages/transformers/models/blenderbot_small/__pycache__/modeling_tf_blenderbot_small.cpython-310.pyc ADDED
Binary file (49.2 kB). View file
 
env-llmeval/lib/python3.10/site-packages/transformers/models/blenderbot_small/__pycache__/tokenization_blenderbot_small.cpython-310.pyc ADDED
Binary file (8.73 kB). View file
 
env-llmeval/lib/python3.10/site-packages/transformers/models/blenderbot_small/__pycache__/tokenization_blenderbot_small_fast.cpython-310.pyc ADDED
Binary file (4.15 kB). View file
 
env-llmeval/lib/python3.10/site-packages/transformers/models/convnextv2/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (1.28 kB). View file
 
env-llmeval/lib/python3.10/site-packages/transformers/models/convnextv2/__pycache__/configuration_convnextv2.cpython-310.pyc ADDED
Binary file (5.14 kB). View file
 
env-llmeval/lib/python3.10/site-packages/transformers/models/convnextv2/__pycache__/convert_convnextv2_to_pytorch.cpython-310.pyc ADDED
Binary file (9.13 kB). View file
 
env-llmeval/lib/python3.10/site-packages/transformers/models/convnextv2/__pycache__/modeling_convnextv2.cpython-310.pyc ADDED
Binary file (18.6 kB). View file
 
env-llmeval/lib/python3.10/site-packages/transformers/models/convnextv2/__pycache__/modeling_tf_convnextv2.cpython-310.pyc ADDED
Binary file (22.2 kB). View file
 
env-llmeval/lib/python3.10/site-packages/transformers/models/distilbert/__init__.py ADDED
@@ -0,0 +1,166 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020 The HuggingFace Team. All rights reserved.
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
+
15
+ from typing import TYPE_CHECKING
16
+
17
+ from ...utils import (
18
+ OptionalDependencyNotAvailable,
19
+ _LazyModule,
20
+ is_flax_available,
21
+ is_tf_available,
22
+ is_tokenizers_available,
23
+ is_torch_available,
24
+ )
25
+
26
+
27
+ _import_structure = {
28
+ "configuration_distilbert": [
29
+ "DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP",
30
+ "DistilBertConfig",
31
+ "DistilBertOnnxConfig",
32
+ ],
33
+ "tokenization_distilbert": ["DistilBertTokenizer"],
34
+ }
35
+
36
+ try:
37
+ if not is_tokenizers_available():
38
+ raise OptionalDependencyNotAvailable()
39
+ except OptionalDependencyNotAvailable:
40
+ pass
41
+ else:
42
+ _import_structure["tokenization_distilbert_fast"] = ["DistilBertTokenizerFast"]
43
+
44
+ try:
45
+ if not is_torch_available():
46
+ raise OptionalDependencyNotAvailable()
47
+ except OptionalDependencyNotAvailable:
48
+ pass
49
+ else:
50
+ _import_structure["modeling_distilbert"] = [
51
+ "DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST",
52
+ "DistilBertForMaskedLM",
53
+ "DistilBertForMultipleChoice",
54
+ "DistilBertForQuestionAnswering",
55
+ "DistilBertForSequenceClassification",
56
+ "DistilBertForTokenClassification",
57
+ "DistilBertModel",
58
+ "DistilBertPreTrainedModel",
59
+ ]
60
+
61
+ try:
62
+ if not is_tf_available():
63
+ raise OptionalDependencyNotAvailable()
64
+ except OptionalDependencyNotAvailable:
65
+ pass
66
+ else:
67
+ _import_structure["modeling_tf_distilbert"] = [
68
+ "TF_DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST",
69
+ "TFDistilBertForMaskedLM",
70
+ "TFDistilBertForMultipleChoice",
71
+ "TFDistilBertForQuestionAnswering",
72
+ "TFDistilBertForSequenceClassification",
73
+ "TFDistilBertForTokenClassification",
74
+ "TFDistilBertMainLayer",
75
+ "TFDistilBertModel",
76
+ "TFDistilBertPreTrainedModel",
77
+ ]
78
+
79
+ try:
80
+ if not is_flax_available():
81
+ raise OptionalDependencyNotAvailable()
82
+ except OptionalDependencyNotAvailable:
83
+ pass
84
+ else:
85
+ _import_structure["modeling_flax_distilbert"] = [
86
+ "FlaxDistilBertForMaskedLM",
87
+ "FlaxDistilBertForMultipleChoice",
88
+ "FlaxDistilBertForQuestionAnswering",
89
+ "FlaxDistilBertForSequenceClassification",
90
+ "FlaxDistilBertForTokenClassification",
91
+ "FlaxDistilBertModel",
92
+ "FlaxDistilBertPreTrainedModel",
93
+ ]
94
+
95
+
96
+ if TYPE_CHECKING:
97
+ from .configuration_distilbert import (
98
+ DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP,
99
+ DistilBertConfig,
100
+ DistilBertOnnxConfig,
101
+ )
102
+ from .tokenization_distilbert import DistilBertTokenizer
103
+
104
+ try:
105
+ if not is_tokenizers_available():
106
+ raise OptionalDependencyNotAvailable()
107
+ except OptionalDependencyNotAvailable:
108
+ pass
109
+ else:
110
+ from .tokenization_distilbert_fast import DistilBertTokenizerFast
111
+
112
+ try:
113
+ if not is_torch_available():
114
+ raise OptionalDependencyNotAvailable()
115
+ except OptionalDependencyNotAvailable:
116
+ pass
117
+ else:
118
+ from .modeling_distilbert import (
119
+ DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST,
120
+ DistilBertForMaskedLM,
121
+ DistilBertForMultipleChoice,
122
+ DistilBertForQuestionAnswering,
123
+ DistilBertForSequenceClassification,
124
+ DistilBertForTokenClassification,
125
+ DistilBertModel,
126
+ DistilBertPreTrainedModel,
127
+ )
128
+
129
+ try:
130
+ if not is_tf_available():
131
+ raise OptionalDependencyNotAvailable()
132
+ except OptionalDependencyNotAvailable:
133
+ pass
134
+ else:
135
+ from .modeling_tf_distilbert import (
136
+ TF_DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST,
137
+ TFDistilBertForMaskedLM,
138
+ TFDistilBertForMultipleChoice,
139
+ TFDistilBertForQuestionAnswering,
140
+ TFDistilBertForSequenceClassification,
141
+ TFDistilBertForTokenClassification,
142
+ TFDistilBertMainLayer,
143
+ TFDistilBertModel,
144
+ TFDistilBertPreTrainedModel,
145
+ )
146
+
147
+ try:
148
+ if not is_flax_available():
149
+ raise OptionalDependencyNotAvailable()
150
+ except OptionalDependencyNotAvailable:
151
+ pass
152
+ else:
153
+ from .modeling_flax_distilbert import (
154
+ FlaxDistilBertForMaskedLM,
155
+ FlaxDistilBertForMultipleChoice,
156
+ FlaxDistilBertForQuestionAnswering,
157
+ FlaxDistilBertForSequenceClassification,
158
+ FlaxDistilBertForTokenClassification,
159
+ FlaxDistilBertModel,
160
+ FlaxDistilBertPreTrainedModel,
161
+ )
162
+
163
+ else:
164
+ import sys
165
+
166
+ sys.modules[__name__] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
env-llmeval/lib/python3.10/site-packages/transformers/models/distilbert/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (2.47 kB). View file
 
env-llmeval/lib/python3.10/site-packages/transformers/models/distilbert/__pycache__/tokenization_distilbert.cpython-310.pyc ADDED
Binary file (18.2 kB). View file
 
env-llmeval/lib/python3.10/site-packages/transformers/models/distilbert/configuration_distilbert.py ADDED
@@ -0,0 +1,155 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2019-present, the HuggingFace Inc. team, The Google AI Language Team and Facebook, Inc.
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
+ """ DistilBERT model configuration"""
16
+ from collections import OrderedDict
17
+ from typing import Mapping
18
+
19
+ from ...configuration_utils import PretrainedConfig
20
+ from ...onnx import OnnxConfig
21
+ from ...utils import logging
22
+
23
+
24
+ logger = logging.get_logger(__name__)
25
+
26
+ DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP = {
27
+ "distilbert-base-uncased": "https://huggingface.co/distilbert-base-uncased/resolve/main/config.json",
28
+ "distilbert-base-uncased-distilled-squad": (
29
+ "https://huggingface.co/distilbert-base-uncased-distilled-squad/resolve/main/config.json"
30
+ ),
31
+ "distilbert-base-cased": "https://huggingface.co/distilbert-base-cased/resolve/main/config.json",
32
+ "distilbert-base-cased-distilled-squad": (
33
+ "https://huggingface.co/distilbert-base-cased-distilled-squad/resolve/main/config.json"
34
+ ),
35
+ "distilbert-base-german-cased": "https://huggingface.co/distilbert-base-german-cased/resolve/main/config.json",
36
+ "distilbert-base-multilingual-cased": (
37
+ "https://huggingface.co/distilbert-base-multilingual-cased/resolve/main/config.json"
38
+ ),
39
+ "distilbert-base-uncased-finetuned-sst-2-english": (
40
+ "https://huggingface.co/distilbert-base-uncased-finetuned-sst-2-english/resolve/main/config.json"
41
+ ),
42
+ }
43
+
44
+
45
+ class DistilBertConfig(PretrainedConfig):
46
+ r"""
47
+ This is the configuration class to store the configuration of a [`DistilBertModel`] or a [`TFDistilBertModel`]. It
48
+ is used to instantiate a DistilBERT model according to the specified arguments, defining the model architecture.
49
+ Instantiating a configuration with the defaults will yield a similar configuration to that of the DistilBERT
50
+ [distilbert-base-uncased](https://huggingface.co/distilbert-base-uncased) architecture.
51
+
52
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
53
+ documentation from [`PretrainedConfig`] for more information.
54
+
55
+ Args:
56
+ vocab_size (`int`, *optional*, defaults to 30522):
57
+ Vocabulary size of the DistilBERT model. Defines the number of different tokens that can be represented by
58
+ the `inputs_ids` passed when calling [`DistilBertModel`] or [`TFDistilBertModel`].
59
+ max_position_embeddings (`int`, *optional*, defaults to 512):
60
+ The maximum sequence length that this model might ever be used with. Typically set this to something large
61
+ just in case (e.g., 512 or 1024 or 2048).
62
+ sinusoidal_pos_embds (`boolean`, *optional*, defaults to `False`):
63
+ Whether to use sinusoidal positional embeddings.
64
+ n_layers (`int`, *optional*, defaults to 6):
65
+ Number of hidden layers in the Transformer encoder.
66
+ n_heads (`int`, *optional*, defaults to 12):
67
+ Number of attention heads for each attention layer in the Transformer encoder.
68
+ dim (`int`, *optional*, defaults to 768):
69
+ Dimensionality of the encoder layers and the pooler layer.
70
+ hidden_dim (`int`, *optional*, defaults to 3072):
71
+ The size of the "intermediate" (often named feed-forward) layer in the Transformer encoder.
72
+ dropout (`float`, *optional*, defaults to 0.1):
73
+ The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
74
+ attention_dropout (`float`, *optional*, defaults to 0.1):
75
+ The dropout ratio for the attention probabilities.
76
+ activation (`str` or `Callable`, *optional*, defaults to `"gelu"`):
77
+ The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
78
+ `"relu"`, `"silu"` and `"gelu_new"` are supported.
79
+ initializer_range (`float`, *optional*, defaults to 0.02):
80
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
81
+ qa_dropout (`float`, *optional*, defaults to 0.1):
82
+ The dropout probabilities used in the question answering model [`DistilBertForQuestionAnswering`].
83
+ seq_classif_dropout (`float`, *optional*, defaults to 0.2):
84
+ The dropout probabilities used in the sequence classification and the multiple choice model
85
+ [`DistilBertForSequenceClassification`].
86
+
87
+ Examples:
88
+
89
+ ```python
90
+ >>> from transformers import DistilBertConfig, DistilBertModel
91
+
92
+ >>> # Initializing a DistilBERT configuration
93
+ >>> configuration = DistilBertConfig()
94
+
95
+ >>> # Initializing a model (with random weights) from the configuration
96
+ >>> model = DistilBertModel(configuration)
97
+
98
+ >>> # Accessing the model configuration
99
+ >>> configuration = model.config
100
+ ```"""
101
+
102
+ model_type = "distilbert"
103
+ attribute_map = {
104
+ "hidden_size": "dim",
105
+ "num_attention_heads": "n_heads",
106
+ "num_hidden_layers": "n_layers",
107
+ }
108
+
109
+ def __init__(
110
+ self,
111
+ vocab_size=30522,
112
+ max_position_embeddings=512,
113
+ sinusoidal_pos_embds=False,
114
+ n_layers=6,
115
+ n_heads=12,
116
+ dim=768,
117
+ hidden_dim=4 * 768,
118
+ dropout=0.1,
119
+ attention_dropout=0.1,
120
+ activation="gelu",
121
+ initializer_range=0.02,
122
+ qa_dropout=0.1,
123
+ seq_classif_dropout=0.2,
124
+ pad_token_id=0,
125
+ **kwargs,
126
+ ):
127
+ self.vocab_size = vocab_size
128
+ self.max_position_embeddings = max_position_embeddings
129
+ self.sinusoidal_pos_embds = sinusoidal_pos_embds
130
+ self.n_layers = n_layers
131
+ self.n_heads = n_heads
132
+ self.dim = dim
133
+ self.hidden_dim = hidden_dim
134
+ self.dropout = dropout
135
+ self.attention_dropout = attention_dropout
136
+ self.activation = activation
137
+ self.initializer_range = initializer_range
138
+ self.qa_dropout = qa_dropout
139
+ self.seq_classif_dropout = seq_classif_dropout
140
+ super().__init__(**kwargs, pad_token_id=pad_token_id)
141
+
142
+
143
+ class DistilBertOnnxConfig(OnnxConfig):
144
+ @property
145
+ def inputs(self) -> Mapping[str, Mapping[int, str]]:
146
+ if self.task == "multiple-choice":
147
+ dynamic_axis = {0: "batch", 1: "choice", 2: "sequence"}
148
+ else:
149
+ dynamic_axis = {0: "batch", 1: "sequence"}
150
+ return OrderedDict(
151
+ [
152
+ ("input_ids", dynamic_axis),
153
+ ("attention_mask", dynamic_axis),
154
+ ]
155
+ )
env-llmeval/lib/python3.10/site-packages/transformers/models/distilbert/modeling_distilbert.py ADDED
@@ -0,0 +1,1392 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2019-present, the HuggingFace Inc. team, The Google AI Language Team and Facebook, Inc.
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
+
16
+ """
17
+ PyTorch DistilBERT model adapted in part from Facebook, Inc XLM model (https://github.com/facebookresearch/XLM) and in
18
+ part from HuggingFace PyTorch version of Google AI Bert model (https://github.com/google-research/bert)
19
+ """
20
+
21
+
22
+ import math
23
+ from typing import Dict, List, Optional, Set, Tuple, Union
24
+
25
+ import numpy as np
26
+ import torch
27
+ import torch.nn.functional as F
28
+ from torch import nn
29
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
30
+
31
+ from ...activations import get_activation
32
+ from ...configuration_utils import PretrainedConfig
33
+ from ...integrations.deepspeed import is_deepspeed_zero3_enabled
34
+ from ...modeling_outputs import (
35
+ BaseModelOutput,
36
+ MaskedLMOutput,
37
+ MultipleChoiceModelOutput,
38
+ QuestionAnsweringModelOutput,
39
+ SequenceClassifierOutput,
40
+ TokenClassifierOutput,
41
+ )
42
+ from ...modeling_utils import PreTrainedModel
43
+ from ...pytorch_utils import apply_chunking_to_forward, find_pruneable_heads_and_indices, prune_linear_layer
44
+ from ...utils import (
45
+ add_code_sample_docstrings,
46
+ add_start_docstrings,
47
+ add_start_docstrings_to_model_forward,
48
+ is_flash_attn_2_available,
49
+ is_flash_attn_greater_or_equal_2_10,
50
+ logging,
51
+ replace_return_docstrings,
52
+ )
53
+ from .configuration_distilbert import DistilBertConfig
54
+
55
+
56
+ if is_flash_attn_2_available():
57
+ from flash_attn import flash_attn_func, flash_attn_varlen_func
58
+ from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa
59
+
60
+
61
+ logger = logging.get_logger(__name__)
62
+ _CHECKPOINT_FOR_DOC = "distilbert-base-uncased"
63
+ _CONFIG_FOR_DOC = "DistilBertConfig"
64
+
65
+ DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST = [
66
+ "distilbert-base-uncased",
67
+ "distilbert-base-uncased-distilled-squad",
68
+ "distilbert-base-cased",
69
+ "distilbert-base-cased-distilled-squad",
70
+ "distilbert-base-german-cased",
71
+ "distilbert-base-multilingual-cased",
72
+ "distilbert-base-uncased-finetuned-sst-2-english",
73
+ # See all DistilBERT models at https://huggingface.co/models?filter=distilbert
74
+ ]
75
+
76
+
77
+ # UTILS AND BUILDING BLOCKS OF THE ARCHITECTURE #
78
+
79
+
80
+ # Copied from transformers.models.llama.modeling_llama._get_unpad_data
81
+ def _get_unpad_data(attention_mask):
82
+ seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
83
+ indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
84
+ max_seqlen_in_batch = seqlens_in_batch.max().item()
85
+ cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.int32), (1, 0))
86
+ return (
87
+ indices,
88
+ cu_seqlens,
89
+ max_seqlen_in_batch,
90
+ )
91
+
92
+
93
+ def create_sinusoidal_embeddings(n_pos: int, dim: int, out: torch.Tensor):
94
+ if is_deepspeed_zero3_enabled():
95
+ import deepspeed
96
+
97
+ with deepspeed.zero.GatheredParameters(out, modifier_rank=0):
98
+ if torch.distributed.get_rank() == 0:
99
+ _create_sinusoidal_embeddings(n_pos=n_pos, dim=dim, out=out)
100
+ else:
101
+ _create_sinusoidal_embeddings(n_pos=n_pos, dim=dim, out=out)
102
+
103
+
104
+ def _create_sinusoidal_embeddings(n_pos: int, dim: int, out: torch.Tensor):
105
+ position_enc = np.array([[pos / np.power(10000, 2 * (j // 2) / dim) for j in range(dim)] for pos in range(n_pos)])
106
+ out.requires_grad = False
107
+ out[:, 0::2] = torch.FloatTensor(np.sin(position_enc[:, 0::2]))
108
+ out[:, 1::2] = torch.FloatTensor(np.cos(position_enc[:, 1::2]))
109
+ out.detach_()
110
+
111
+
112
+ class Embeddings(nn.Module):
113
+ def __init__(self, config: PretrainedConfig):
114
+ super().__init__()
115
+ self.word_embeddings = nn.Embedding(config.vocab_size, config.dim, padding_idx=config.pad_token_id)
116
+ self.position_embeddings = nn.Embedding(config.max_position_embeddings, config.dim)
117
+ if config.sinusoidal_pos_embds:
118
+ create_sinusoidal_embeddings(
119
+ n_pos=config.max_position_embeddings, dim=config.dim, out=self.position_embeddings.weight
120
+ )
121
+
122
+ self.LayerNorm = nn.LayerNorm(config.dim, eps=1e-12)
123
+ self.dropout = nn.Dropout(config.dropout)
124
+ self.register_buffer(
125
+ "position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)), persistent=False
126
+ )
127
+
128
+ def forward(self, input_ids: torch.Tensor, input_embeds: Optional[torch.Tensor] = None) -> torch.Tensor:
129
+ """
130
+ Parameters:
131
+ input_ids (torch.Tensor):
132
+ torch.tensor(bs, max_seq_length) The token ids to embed.
133
+ input_embeds (*optional*, torch.Tensor):
134
+ The pre-computed word embeddings. Can only be passed if the input ids are `None`.
135
+
136
+
137
+ Returns: torch.tensor(bs, max_seq_length, dim) The embedded tokens (plus position embeddings, no token_type
138
+ embeddings)
139
+ """
140
+ if input_ids is not None:
141
+ input_embeds = self.word_embeddings(input_ids) # (bs, max_seq_length, dim)
142
+
143
+ seq_length = input_embeds.size(1)
144
+
145
+ # Setting the position-ids to the registered buffer in constructor, it helps
146
+ # when tracing the model without passing position-ids, solves
147
+ # isues similar to issue #5664
148
+ if hasattr(self, "position_ids"):
149
+ position_ids = self.position_ids[:, :seq_length]
150
+ else:
151
+ position_ids = torch.arange(seq_length, dtype=torch.long, device=input_ids.device) # (max_seq_length)
152
+ position_ids = position_ids.unsqueeze(0).expand_as(input_ids) # (bs, max_seq_length)
153
+
154
+ position_embeddings = self.position_embeddings(position_ids) # (bs, max_seq_length, dim)
155
+
156
+ embeddings = input_embeds + position_embeddings # (bs, max_seq_length, dim)
157
+ embeddings = self.LayerNorm(embeddings) # (bs, max_seq_length, dim)
158
+ embeddings = self.dropout(embeddings) # (bs, max_seq_length, dim)
159
+ return embeddings
160
+
161
+
162
+ class MultiHeadSelfAttention(nn.Module):
163
+ def __init__(self, config: PretrainedConfig):
164
+ super().__init__()
165
+ self.config = config
166
+
167
+ self.n_heads = config.n_heads
168
+ self.dim = config.dim
169
+ self.dropout = nn.Dropout(p=config.attention_dropout)
170
+ self.is_causal = False
171
+
172
+ # Have an even number of multi heads that divide the dimensions
173
+ if self.dim % self.n_heads != 0:
174
+ # Raise value errors for even multi-head attention nodes
175
+ raise ValueError(f"self.n_heads: {self.n_heads} must divide self.dim: {self.dim} evenly")
176
+
177
+ self.q_lin = nn.Linear(in_features=config.dim, out_features=config.dim)
178
+ self.k_lin = nn.Linear(in_features=config.dim, out_features=config.dim)
179
+ self.v_lin = nn.Linear(in_features=config.dim, out_features=config.dim)
180
+ self.out_lin = nn.Linear(in_features=config.dim, out_features=config.dim)
181
+
182
+ self.pruned_heads: Set[int] = set()
183
+ self.attention_head_size = self.dim // self.n_heads
184
+
185
+ def prune_heads(self, heads: List[int]):
186
+ if len(heads) == 0:
187
+ return
188
+ heads, index = find_pruneable_heads_and_indices(
189
+ heads, self.n_heads, self.attention_head_size, self.pruned_heads
190
+ )
191
+ # Prune linear layers
192
+ self.q_lin = prune_linear_layer(self.q_lin, index)
193
+ self.k_lin = prune_linear_layer(self.k_lin, index)
194
+ self.v_lin = prune_linear_layer(self.v_lin, index)
195
+ self.out_lin = prune_linear_layer(self.out_lin, index, dim=1)
196
+ # Update hyper params
197
+ self.n_heads = self.n_heads - len(heads)
198
+ self.dim = self.attention_head_size * self.n_heads
199
+ self.pruned_heads = self.pruned_heads.union(heads)
200
+
201
+ def forward(
202
+ self,
203
+ query: torch.Tensor,
204
+ key: torch.Tensor,
205
+ value: torch.Tensor,
206
+ mask: torch.Tensor,
207
+ head_mask: Optional[torch.Tensor] = None,
208
+ output_attentions: bool = False,
209
+ ) -> Tuple[torch.Tensor, ...]:
210
+ """
211
+ Parameters:
212
+ query: torch.tensor(bs, seq_length, dim)
213
+ key: torch.tensor(bs, seq_length, dim)
214
+ value: torch.tensor(bs, seq_length, dim)
215
+ mask: torch.tensor(bs, seq_length)
216
+
217
+ Returns:
218
+ weights: torch.tensor(bs, n_heads, seq_length, seq_length) Attention weights context: torch.tensor(bs,
219
+ seq_length, dim) Contextualized layer. Optional: only if `output_attentions=True`
220
+ """
221
+ bs, q_length, dim = query.size()
222
+ k_length = key.size(1)
223
+ # assert dim == self.dim, f'Dimensions do not match: {dim} input vs {self.dim} configured'
224
+ # assert key.size() == value.size()
225
+
226
+ dim_per_head = self.dim // self.n_heads
227
+
228
+ mask_reshp = (bs, 1, 1, k_length)
229
+
230
+ def shape(x: torch.Tensor) -> torch.Tensor:
231
+ """separate heads"""
232
+ return x.view(bs, -1, self.n_heads, dim_per_head).transpose(1, 2)
233
+
234
+ def unshape(x: torch.Tensor) -> torch.Tensor:
235
+ """group heads"""
236
+ return x.transpose(1, 2).contiguous().view(bs, -1, self.n_heads * dim_per_head)
237
+
238
+ q = shape(self.q_lin(query)) # (bs, n_heads, q_length, dim_per_head)
239
+ k = shape(self.k_lin(key)) # (bs, n_heads, k_length, dim_per_head)
240
+ v = shape(self.v_lin(value)) # (bs, n_heads, k_length, dim_per_head)
241
+
242
+ q = q / math.sqrt(dim_per_head) # (bs, n_heads, q_length, dim_per_head)
243
+ scores = torch.matmul(q, k.transpose(2, 3)) # (bs, n_heads, q_length, k_length)
244
+ mask = (mask == 0).view(mask_reshp).expand_as(scores) # (bs, n_heads, q_length, k_length)
245
+ scores = scores.masked_fill(
246
+ mask, torch.tensor(torch.finfo(scores.dtype).min)
247
+ ) # (bs, n_heads, q_length, k_length)
248
+
249
+ weights = nn.functional.softmax(scores, dim=-1) # (bs, n_heads, q_length, k_length)
250
+ weights = self.dropout(weights) # (bs, n_heads, q_length, k_length)
251
+
252
+ # Mask heads if we want to
253
+ if head_mask is not None:
254
+ weights = weights * head_mask
255
+
256
+ context = torch.matmul(weights, v) # (bs, n_heads, q_length, dim_per_head)
257
+ context = unshape(context) # (bs, q_length, dim)
258
+ context = self.out_lin(context) # (bs, q_length, dim)
259
+
260
+ if output_attentions:
261
+ return (context, weights)
262
+ else:
263
+ return (context,)
264
+
265
+
266
+ class DistilBertFlashAttention2(MultiHeadSelfAttention):
267
+ """
268
+ DistilBert flash attention module. This module inherits from `MultiHeadSelfAttention` as the weights of the module
269
+ stays untouched. The only required change would be on the forward pass where it needs to correctly call the public
270
+ API of flash attention and deal with padding tokens in case the input contains any of them.
271
+ """
272
+
273
+ # Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2.__init__
274
+ def __init__(self, *args, **kwargs):
275
+ super().__init__(*args, **kwargs)
276
+
277
+ # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
278
+ # flash_attn<2.1 generates top-left aligned causal mask, while what is needed here is bottom-right alignement, that was made default for flash_attn>=2.1. This attribute is used to handle this difference. Reference: https://github.com/Dao-AILab/flash-attention/releases/tag/v2.1.0.
279
+ # Beware that with flash_attn<2.1, using q_seqlen != k_seqlen (except for the case q_seqlen == 1) produces a wrong mask (top-left).
280
+ self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
281
+
282
+ def forward(
283
+ self,
284
+ query: torch.Tensor,
285
+ key: torch.Tensor,
286
+ value: torch.Tensor,
287
+ mask: torch.Tensor,
288
+ head_mask: Optional[torch.Tensor] = None,
289
+ output_attentions: bool = False,
290
+ ) -> Tuple[torch.Tensor, ...]:
291
+ """
292
+ Parameters:
293
+ query: torch.tensor(bs, seq_length, dim)
294
+ key: torch.tensor(bs, seq_length, dim)
295
+ value: torch.tensor(bs, seq_length, dim)
296
+ mask: torch.tensor(bs, seq_length)
297
+
298
+ Returns:
299
+ weights: torch.tensor(bs, n_heads, seq_length, seq_length) Attention weights context: torch.tensor(bs,
300
+ seq_length, dim) Contextualized layer. Optional: only if `output_attentions=True`
301
+ """
302
+ batch_size, q_length, dim = query.size()
303
+
304
+ dim_per_head = self.dim // self.n_heads
305
+
306
+ def reshape(x: torch.Tensor) -> torch.Tensor:
307
+ """separate heads"""
308
+ return x.view(batch_size, -1, self.n_heads, dim_per_head)
309
+
310
+ # Flash attention requires the input to have the shape
311
+ # batch_size x seq_length x head_dim x hidden_dim
312
+ query_states = reshape(self.q_lin(query))
313
+ key_states = reshape(self.k_lin(key))
314
+ value_states = reshape(self.v_lin(value))
315
+
316
+ attn_dropout = self.config.attention_dropout if self.training else 0.0
317
+
318
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
319
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
320
+ # cast them back in the correct dtype just to be sure everything works as expected.
321
+ # This might slowdown training & inference so it is recommended to not cast the LayerNorms
322
+ # in fp32. (LlamaRMSNorm handles it correctly)
323
+
324
+ if query_states.dtype == torch.float32:
325
+ if torch.is_autocast_enabled():
326
+ target_dtype = torch.get_autocast_gpu_dtype()
327
+ # Handle the case where the model is quantized
328
+ elif hasattr(self.config, "_pre_quantization_dtype"):
329
+ target_dtype = self.config._pre_quantization_dtype
330
+ else:
331
+ target_dtype = self.q_lin.weight.dtype
332
+
333
+ logger.warning_once(
334
+ f"The input hidden states seems to be silently casted in float32, this might be related to"
335
+ f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
336
+ f" {target_dtype}."
337
+ )
338
+
339
+ query_states = query_states.to(target_dtype)
340
+ key_states = key_states.to(target_dtype)
341
+ value_states = value_states.to(target_dtype)
342
+
343
+ attn_weights = self._flash_attention_forward(
344
+ query_states, key_states, value_states, mask, q_length, dropout=attn_dropout
345
+ )
346
+
347
+ attn_weights_reshaped = attn_weights.reshape(batch_size, q_length, self.n_heads * dim_per_head)
348
+ attn_output = self.out_lin(attn_weights_reshaped)
349
+
350
+ if output_attentions:
351
+ return (attn_output, attn_weights)
352
+ else:
353
+ return (attn_output,)
354
+
355
+ # Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2._flash_attention_forward with causal=True->causal=False
356
+ def _flash_attention_forward(
357
+ self, query_states, key_states, value_states, attention_mask, query_length, dropout=0.0, softmax_scale=None
358
+ ):
359
+ """
360
+ Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
361
+ first unpad the input, then computes the attention scores and pad the final attention scores.
362
+
363
+ Args:
364
+ query_states (`torch.Tensor`):
365
+ Input query states to be passed to Flash Attention API
366
+ key_states (`torch.Tensor`):
367
+ Input key states to be passed to Flash Attention API
368
+ value_states (`torch.Tensor`):
369
+ Input value states to be passed to Flash Attention API
370
+ attention_mask (`torch.Tensor`):
371
+ The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
372
+ position of padding tokens and 1 for the position of non-padding tokens.
373
+ dropout (`float`):
374
+ Attention dropout
375
+ softmax_scale (`float`, *optional*):
376
+ The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
377
+ """
378
+ if not self._flash_attn_uses_top_left_mask:
379
+ causal = self.is_causal
380
+ else:
381
+ # TODO: Remove the `query_length != 1` check once Flash Attention for RoCm is bumped to 2.1. For details, please see the comment in LlamaFlashAttention2 __init__.
382
+ causal = self.is_causal and query_length != 1
383
+
384
+ # Contains at least one padding token in the sequence
385
+ if attention_mask is not None:
386
+ batch_size = query_states.shape[0]
387
+ query_states, key_states, value_states, indices_q, cu_seq_lens, max_seq_lens = self._upad_input(
388
+ query_states, key_states, value_states, attention_mask, query_length
389
+ )
390
+
391
+ cu_seqlens_q, cu_seqlens_k = cu_seq_lens
392
+ max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
393
+
394
+ attn_output_unpad = flash_attn_varlen_func(
395
+ query_states,
396
+ key_states,
397
+ value_states,
398
+ cu_seqlens_q=cu_seqlens_q,
399
+ cu_seqlens_k=cu_seqlens_k,
400
+ max_seqlen_q=max_seqlen_in_batch_q,
401
+ max_seqlen_k=max_seqlen_in_batch_k,
402
+ dropout_p=dropout,
403
+ softmax_scale=softmax_scale,
404
+ causal=causal,
405
+ )
406
+
407
+ attn_output = pad_input(attn_output_unpad, indices_q, batch_size, query_length)
408
+ else:
409
+ attn_output = flash_attn_func(
410
+ query_states, key_states, value_states, dropout, softmax_scale=softmax_scale, causal=causal
411
+ )
412
+
413
+ return attn_output
414
+
415
+ # Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2._upad_input with num_heads->n_heads
416
+ def _upad_input(self, query_layer, key_layer, value_layer, attention_mask, query_length):
417
+ indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
418
+ batch_size, kv_seq_len, num_key_value_heads, head_dim = key_layer.shape
419
+
420
+ key_layer = index_first_axis(
421
+ key_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
422
+ )
423
+ value_layer = index_first_axis(
424
+ value_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
425
+ )
426
+ if query_length == kv_seq_len:
427
+ query_layer = index_first_axis(
428
+ query_layer.reshape(batch_size * kv_seq_len, self.n_heads, head_dim), indices_k
429
+ )
430
+ cu_seqlens_q = cu_seqlens_k
431
+ max_seqlen_in_batch_q = max_seqlen_in_batch_k
432
+ indices_q = indices_k
433
+ elif query_length == 1:
434
+ max_seqlen_in_batch_q = 1
435
+ cu_seqlens_q = torch.arange(
436
+ batch_size + 1, dtype=torch.int32, device=query_layer.device
437
+ ) # There is a memcpy here, that is very bad.
438
+ indices_q = cu_seqlens_q[:-1]
439
+ query_layer = query_layer.squeeze(1)
440
+ else:
441
+ # The -q_len: slice assumes left padding.
442
+ attention_mask = attention_mask[:, -query_length:]
443
+ query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(query_layer, attention_mask)
444
+
445
+ return (
446
+ query_layer,
447
+ key_layer,
448
+ value_layer,
449
+ indices_q,
450
+ (cu_seqlens_q, cu_seqlens_k),
451
+ (max_seqlen_in_batch_q, max_seqlen_in_batch_k),
452
+ )
453
+
454
+
455
+ class FFN(nn.Module):
456
+ def __init__(self, config: PretrainedConfig):
457
+ super().__init__()
458
+ self.dropout = nn.Dropout(p=config.dropout)
459
+ self.chunk_size_feed_forward = config.chunk_size_feed_forward
460
+ self.seq_len_dim = 1
461
+ self.lin1 = nn.Linear(in_features=config.dim, out_features=config.hidden_dim)
462
+ self.lin2 = nn.Linear(in_features=config.hidden_dim, out_features=config.dim)
463
+ self.activation = get_activation(config.activation)
464
+
465
+ def forward(self, input: torch.Tensor) -> torch.Tensor:
466
+ return apply_chunking_to_forward(self.ff_chunk, self.chunk_size_feed_forward, self.seq_len_dim, input)
467
+
468
+ def ff_chunk(self, input: torch.Tensor) -> torch.Tensor:
469
+ x = self.lin1(input)
470
+ x = self.activation(x)
471
+ x = self.lin2(x)
472
+ x = self.dropout(x)
473
+ return x
474
+
475
+
476
+ DISTILBERT_ATTENTION_CLASSES = {
477
+ "eager": MultiHeadSelfAttention,
478
+ "flash_attention_2": DistilBertFlashAttention2,
479
+ }
480
+
481
+
482
+ class TransformerBlock(nn.Module):
483
+ def __init__(self, config: PretrainedConfig):
484
+ super().__init__()
485
+
486
+ # Have an even number of Configure multi-heads
487
+ if config.dim % config.n_heads != 0:
488
+ raise ValueError(f"config.n_heads {config.n_heads} must divide config.dim {config.dim} evenly")
489
+
490
+ self.attention = DISTILBERT_ATTENTION_CLASSES[config._attn_implementation](config)
491
+ self.sa_layer_norm = nn.LayerNorm(normalized_shape=config.dim, eps=1e-12)
492
+
493
+ self.ffn = FFN(config)
494
+ self.output_layer_norm = nn.LayerNorm(normalized_shape=config.dim, eps=1e-12)
495
+
496
+ def forward(
497
+ self,
498
+ x: torch.Tensor,
499
+ attn_mask: Optional[torch.Tensor] = None,
500
+ head_mask: Optional[torch.Tensor] = None,
501
+ output_attentions: bool = False,
502
+ ) -> Tuple[torch.Tensor, ...]:
503
+ """
504
+ Parameters:
505
+ x: torch.tensor(bs, seq_length, dim)
506
+ attn_mask: torch.tensor(bs, seq_length)
507
+
508
+ Returns:
509
+ sa_weights: torch.tensor(bs, n_heads, seq_length, seq_length) The attention weights ffn_output:
510
+ torch.tensor(bs, seq_length, dim) The output of the transformer block contextualization.
511
+ """
512
+ # Self-Attention
513
+ sa_output = self.attention(
514
+ query=x,
515
+ key=x,
516
+ value=x,
517
+ mask=attn_mask,
518
+ head_mask=head_mask,
519
+ output_attentions=output_attentions,
520
+ )
521
+ if output_attentions:
522
+ sa_output, sa_weights = sa_output # (bs, seq_length, dim), (bs, n_heads, seq_length, seq_length)
523
+ else: # To handle these `output_attentions` or `output_hidden_states` cases returning tuples
524
+ if type(sa_output) != tuple:
525
+ raise TypeError(f"sa_output must be a tuple but it is {type(sa_output)} type")
526
+
527
+ sa_output = sa_output[0]
528
+ sa_output = self.sa_layer_norm(sa_output + x) # (bs, seq_length, dim)
529
+
530
+ # Feed Forward Network
531
+ ffn_output = self.ffn(sa_output) # (bs, seq_length, dim)
532
+ ffn_output: torch.Tensor = self.output_layer_norm(ffn_output + sa_output) # (bs, seq_length, dim)
533
+
534
+ output = (ffn_output,)
535
+ if output_attentions:
536
+ output = (sa_weights,) + output
537
+ return output
538
+
539
+
540
+ class Transformer(nn.Module):
541
+ def __init__(self, config: PretrainedConfig):
542
+ super().__init__()
543
+ self.n_layers = config.n_layers
544
+ self.layer = nn.ModuleList([TransformerBlock(config) for _ in range(config.n_layers)])
545
+ self.gradient_checkpointing = False
546
+
547
+ def forward(
548
+ self,
549
+ x: torch.Tensor,
550
+ attn_mask: Optional[torch.Tensor] = None,
551
+ head_mask: Optional[torch.Tensor] = None,
552
+ output_attentions: bool = False,
553
+ output_hidden_states: bool = False,
554
+ return_dict: Optional[bool] = None,
555
+ ) -> Union[BaseModelOutput, Tuple[torch.Tensor, ...]]: # docstyle-ignore
556
+ """
557
+ Parameters:
558
+ x: torch.tensor(bs, seq_length, dim) Input sequence embedded.
559
+ attn_mask: torch.tensor(bs, seq_length) Attention mask on the sequence.
560
+
561
+ Returns:
562
+ hidden_state: torch.tensor(bs, seq_length, dim) Sequence of hidden states in the last (top)
563
+ layer all_hidden_states: Tuple[torch.tensor(bs, seq_length, dim)]
564
+ Tuple of length n_layers with the hidden states from each layer.
565
+ Optional: only if output_hidden_states=True
566
+ all_attentions: Tuple[torch.tensor(bs, n_heads, seq_length, seq_length)]
567
+ Tuple of length n_layers with the attention weights from each layer
568
+ Optional: only if output_attentions=True
569
+ """
570
+ all_hidden_states = () if output_hidden_states else None
571
+ all_attentions = () if output_attentions else None
572
+
573
+ hidden_state = x
574
+ for i, layer_module in enumerate(self.layer):
575
+ if output_hidden_states:
576
+ all_hidden_states = all_hidden_states + (hidden_state,)
577
+
578
+ if self.gradient_checkpointing and self.training:
579
+ layer_outputs = self._gradient_checkpointing_func(
580
+ layer_module.__call__,
581
+ hidden_state,
582
+ attn_mask,
583
+ head_mask[i],
584
+ output_attentions,
585
+ )
586
+ else:
587
+ layer_outputs = layer_module(
588
+ hidden_state,
589
+ attn_mask,
590
+ head_mask[i],
591
+ output_attentions,
592
+ )
593
+
594
+ hidden_state = layer_outputs[-1]
595
+
596
+ if output_attentions:
597
+ if len(layer_outputs) != 2:
598
+ raise ValueError(f"The length of the layer_outputs should be 2, but it is {len(layer_outputs)}")
599
+
600
+ attentions = layer_outputs[0]
601
+ all_attentions = all_attentions + (attentions,)
602
+ else:
603
+ if len(layer_outputs) != 1:
604
+ raise ValueError(f"The length of the layer_outputs should be 1, but it is {len(layer_outputs)}")
605
+
606
+ # Add last layer
607
+ if output_hidden_states:
608
+ all_hidden_states = all_hidden_states + (hidden_state,)
609
+
610
+ if not return_dict:
611
+ return tuple(v for v in [hidden_state, all_hidden_states, all_attentions] if v is not None)
612
+ return BaseModelOutput(
613
+ last_hidden_state=hidden_state, hidden_states=all_hidden_states, attentions=all_attentions
614
+ )
615
+
616
+
617
+ # INTERFACE FOR ENCODER AND TASK SPECIFIC MODEL #
618
+ class DistilBertPreTrainedModel(PreTrainedModel):
619
+ """
620
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
621
+ models.
622
+ """
623
+
624
+ config_class = DistilBertConfig
625
+ load_tf_weights = None
626
+ base_model_prefix = "distilbert"
627
+ supports_gradient_checkpointing = True
628
+ _supports_flash_attn_2 = True
629
+
630
+ def _init_weights(self, module: nn.Module):
631
+ """Initialize the weights."""
632
+ if isinstance(module, nn.Linear):
633
+ # Slightly different from the TF version which uses truncated_normal for initialization
634
+ # cf https://github.com/pytorch/pytorch/pull/5617
635
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
636
+ if module.bias is not None:
637
+ module.bias.data.zero_()
638
+ elif isinstance(module, nn.Embedding):
639
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
640
+ if module.padding_idx is not None:
641
+ module.weight.data[module.padding_idx].zero_()
642
+ elif isinstance(module, nn.LayerNorm):
643
+ module.bias.data.zero_()
644
+ module.weight.data.fill_(1.0)
645
+
646
+
647
+ DISTILBERT_START_DOCSTRING = r"""
648
+
649
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
650
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
651
+ etc.)
652
+
653
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
654
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
655
+ and behavior.
656
+
657
+ Parameters:
658
+ config ([`DistilBertConfig`]): Model configuration class with all the parameters of the model.
659
+ Initializing with a config file does not load the weights associated with the model, only the
660
+ configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
661
+ """
662
+
663
+ DISTILBERT_INPUTS_DOCSTRING = r"""
664
+ Args:
665
+ input_ids (`torch.LongTensor` of shape `({0})`):
666
+ Indices of input sequence tokens in the vocabulary.
667
+
668
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
669
+ [`PreTrainedTokenizer.__call__`] for details.
670
+
671
+ [What are input IDs?](../glossary#input-ids)
672
+ attention_mask (`torch.FloatTensor` of shape `({0})`, *optional*):
673
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
674
+
675
+ - 1 for tokens that are **not masked**,
676
+ - 0 for tokens that are **masked**.
677
+
678
+ [What are attention masks?](../glossary#attention-mask)
679
+ head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
680
+ Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:
681
+
682
+ - 1 indicates the head is **not masked**,
683
+ - 0 indicates the head is **masked**.
684
+
685
+ inputs_embeds (`torch.FloatTensor` of shape `({0}, hidden_size)`, *optional*):
686
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
687
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
688
+ model's internal embedding lookup matrix.
689
+ output_attentions (`bool`, *optional*):
690
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
691
+ tensors for more detail.
692
+ output_hidden_states (`bool`, *optional*):
693
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
694
+ more detail.
695
+ return_dict (`bool`, *optional*):
696
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
697
+ """
698
+
699
+
700
+ @add_start_docstrings(
701
+ "The bare DistilBERT encoder/transformer outputting raw hidden-states without any specific head on top.",
702
+ DISTILBERT_START_DOCSTRING,
703
+ )
704
+ class DistilBertModel(DistilBertPreTrainedModel):
705
+ def __init__(self, config: PretrainedConfig):
706
+ super().__init__(config)
707
+
708
+ self.embeddings = Embeddings(config) # Embeddings
709
+ self.transformer = Transformer(config) # Encoder
710
+ self._use_flash_attention_2 = config._attn_implementation == "flash_attention_2"
711
+
712
+ # Initialize weights and apply final processing
713
+ self.post_init()
714
+
715
+ def get_position_embeddings(self) -> nn.Embedding:
716
+ """
717
+ Returns the position embeddings
718
+ """
719
+ return self.embeddings.position_embeddings
720
+
721
+ def resize_position_embeddings(self, new_num_position_embeddings: int):
722
+ """
723
+ Resizes position embeddings of the model if `new_num_position_embeddings != config.max_position_embeddings`.
724
+
725
+ Arguments:
726
+ new_num_position_embeddings (`int`):
727
+ The number of new position embedding matrix. If position embeddings are learned, increasing the size
728
+ will add newly initialized vectors at the end, whereas reducing the size will remove vectors from the
729
+ end. If position embeddings are not learned (*e.g.* sinusoidal position embeddings), increasing the
730
+ size will add correct vectors at the end following the position encoding algorithm, whereas reducing
731
+ the size will remove vectors from the end.
732
+ """
733
+ num_position_embeds_diff = new_num_position_embeddings - self.config.max_position_embeddings
734
+
735
+ # no resizing needs to be done if the length stays the same
736
+ if num_position_embeds_diff == 0:
737
+ return
738
+
739
+ logger.info(f"Setting `config.max_position_embeddings={new_num_position_embeddings}`...")
740
+ self.config.max_position_embeddings = new_num_position_embeddings
741
+
742
+ old_position_embeddings_weight = self.embeddings.position_embeddings.weight.clone()
743
+
744
+ self.embeddings.position_embeddings = nn.Embedding(self.config.max_position_embeddings, self.config.dim)
745
+
746
+ if self.config.sinusoidal_pos_embds:
747
+ create_sinusoidal_embeddings(
748
+ n_pos=self.config.max_position_embeddings, dim=self.config.dim, out=self.position_embeddings.weight
749
+ )
750
+ else:
751
+ with torch.no_grad():
752
+ if num_position_embeds_diff > 0:
753
+ self.embeddings.position_embeddings.weight[:-num_position_embeds_diff] = nn.Parameter(
754
+ old_position_embeddings_weight
755
+ )
756
+ else:
757
+ self.embeddings.position_embeddings.weight = nn.Parameter(
758
+ old_position_embeddings_weight[:num_position_embeds_diff]
759
+ )
760
+ # move position_embeddings to correct device
761
+ self.embeddings.position_embeddings.to(self.device)
762
+
763
+ def get_input_embeddings(self) -> nn.Embedding:
764
+ return self.embeddings.word_embeddings
765
+
766
+ def set_input_embeddings(self, new_embeddings: nn.Embedding):
767
+ self.embeddings.word_embeddings = new_embeddings
768
+
769
+ def _prune_heads(self, heads_to_prune: Dict[int, List[List[int]]]):
770
+ """
771
+ Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
772
+ class PreTrainedModel
773
+ """
774
+ for layer, heads in heads_to_prune.items():
775
+ self.transformer.layer[layer].attention.prune_heads(heads)
776
+
777
+ @add_start_docstrings_to_model_forward(DISTILBERT_INPUTS_DOCSTRING.format("batch_size, num_choices"))
778
+ @add_code_sample_docstrings(
779
+ checkpoint=_CHECKPOINT_FOR_DOC,
780
+ output_type=BaseModelOutput,
781
+ config_class=_CONFIG_FOR_DOC,
782
+ )
783
+ def forward(
784
+ self,
785
+ input_ids: Optional[torch.Tensor] = None,
786
+ attention_mask: Optional[torch.Tensor] = None,
787
+ head_mask: Optional[torch.Tensor] = None,
788
+ inputs_embeds: Optional[torch.Tensor] = None,
789
+ output_attentions: Optional[bool] = None,
790
+ output_hidden_states: Optional[bool] = None,
791
+ return_dict: Optional[bool] = None,
792
+ ) -> Union[BaseModelOutput, Tuple[torch.Tensor, ...]]:
793
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
794
+ output_hidden_states = (
795
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
796
+ )
797
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
798
+
799
+ if input_ids is not None and inputs_embeds is not None:
800
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
801
+ elif input_ids is not None:
802
+ self.warn_if_padding_and_no_attention_mask(input_ids, attention_mask)
803
+ input_shape = input_ids.size()
804
+ elif inputs_embeds is not None:
805
+ input_shape = inputs_embeds.size()[:-1]
806
+ else:
807
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
808
+
809
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
810
+
811
+ # Prepare head mask if needed
812
+ head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)
813
+
814
+ embeddings = self.embeddings(input_ids, inputs_embeds) # (bs, seq_length, dim)
815
+
816
+ if self._use_flash_attention_2:
817
+ attention_mask = attention_mask if (attention_mask is not None and 0 in attention_mask) else None
818
+ else:
819
+ if attention_mask is None:
820
+ attention_mask = torch.ones(input_shape, device=device) # (bs, seq_length)
821
+
822
+ return self.transformer(
823
+ x=embeddings,
824
+ attn_mask=attention_mask,
825
+ head_mask=head_mask,
826
+ output_attentions=output_attentions,
827
+ output_hidden_states=output_hidden_states,
828
+ return_dict=return_dict,
829
+ )
830
+
831
+
832
+ @add_start_docstrings(
833
+ """DistilBert Model with a `masked language modeling` head on top.""",
834
+ DISTILBERT_START_DOCSTRING,
835
+ )
836
+ class DistilBertForMaskedLM(DistilBertPreTrainedModel):
837
+ _tied_weights_keys = ["vocab_projector.weight"]
838
+
839
+ def __init__(self, config: PretrainedConfig):
840
+ super().__init__(config)
841
+
842
+ self.activation = get_activation(config.activation)
843
+
844
+ self.distilbert = DistilBertModel(config)
845
+ self.vocab_transform = nn.Linear(config.dim, config.dim)
846
+ self.vocab_layer_norm = nn.LayerNorm(config.dim, eps=1e-12)
847
+ self.vocab_projector = nn.Linear(config.dim, config.vocab_size)
848
+
849
+ # Initialize weights and apply final processing
850
+ self.post_init()
851
+
852
+ self.mlm_loss_fct = nn.CrossEntropyLoss()
853
+
854
+ def get_position_embeddings(self) -> nn.Embedding:
855
+ """
856
+ Returns the position embeddings
857
+ """
858
+ return self.distilbert.get_position_embeddings()
859
+
860
+ def resize_position_embeddings(self, new_num_position_embeddings: int):
861
+ """
862
+ Resizes position embeddings of the model if `new_num_position_embeddings != config.max_position_embeddings`.
863
+
864
+ Arguments:
865
+ new_num_position_embeddings (`int`):
866
+ The number of new position embedding matrix. If position embeddings are learned, increasing the size
867
+ will add newly initialized vectors at the end, whereas reducing the size will remove vectors from the
868
+ end. If position embeddings are not learned (*e.g.* sinusoidal position embeddings), increasing the
869
+ size will add correct vectors at the end following the position encoding algorithm, whereas reducing
870
+ the size will remove vectors from the end.
871
+ """
872
+ self.distilbert.resize_position_embeddings(new_num_position_embeddings)
873
+
874
+ def get_output_embeddings(self) -> nn.Module:
875
+ return self.vocab_projector
876
+
877
+ def set_output_embeddings(self, new_embeddings: nn.Module):
878
+ self.vocab_projector = new_embeddings
879
+
880
+ @add_start_docstrings_to_model_forward(DISTILBERT_INPUTS_DOCSTRING.format("batch_size, num_choices"))
881
+ @add_code_sample_docstrings(
882
+ checkpoint=_CHECKPOINT_FOR_DOC,
883
+ output_type=MaskedLMOutput,
884
+ config_class=_CONFIG_FOR_DOC,
885
+ )
886
+ def forward(
887
+ self,
888
+ input_ids: Optional[torch.Tensor] = None,
889
+ attention_mask: Optional[torch.Tensor] = None,
890
+ head_mask: Optional[torch.Tensor] = None,
891
+ inputs_embeds: Optional[torch.Tensor] = None,
892
+ labels: Optional[torch.LongTensor] = None,
893
+ output_attentions: Optional[bool] = None,
894
+ output_hidden_states: Optional[bool] = None,
895
+ return_dict: Optional[bool] = None,
896
+ ) -> Union[MaskedLMOutput, Tuple[torch.Tensor, ...]]:
897
+ r"""
898
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
899
+ Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
900
+ config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the
901
+ loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
902
+ """
903
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
904
+
905
+ dlbrt_output = self.distilbert(
906
+ input_ids=input_ids,
907
+ attention_mask=attention_mask,
908
+ head_mask=head_mask,
909
+ inputs_embeds=inputs_embeds,
910
+ output_attentions=output_attentions,
911
+ output_hidden_states=output_hidden_states,
912
+ return_dict=return_dict,
913
+ )
914
+ hidden_states = dlbrt_output[0] # (bs, seq_length, dim)
915
+ prediction_logits = self.vocab_transform(hidden_states) # (bs, seq_length, dim)
916
+ prediction_logits = self.activation(prediction_logits) # (bs, seq_length, dim)
917
+ prediction_logits = self.vocab_layer_norm(prediction_logits) # (bs, seq_length, dim)
918
+ prediction_logits = self.vocab_projector(prediction_logits) # (bs, seq_length, vocab_size)
919
+
920
+ mlm_loss = None
921
+ if labels is not None:
922
+ mlm_loss = self.mlm_loss_fct(prediction_logits.view(-1, prediction_logits.size(-1)), labels.view(-1))
923
+
924
+ if not return_dict:
925
+ output = (prediction_logits,) + dlbrt_output[1:]
926
+ return ((mlm_loss,) + output) if mlm_loss is not None else output
927
+
928
+ return MaskedLMOutput(
929
+ loss=mlm_loss,
930
+ logits=prediction_logits,
931
+ hidden_states=dlbrt_output.hidden_states,
932
+ attentions=dlbrt_output.attentions,
933
+ )
934
+
935
+
936
+ @add_start_docstrings(
937
+ """
938
+ DistilBert Model transformer with a sequence classification/regression head on top (a linear layer on top of the
939
+ pooled output) e.g. for GLUE tasks.
940
+ """,
941
+ DISTILBERT_START_DOCSTRING,
942
+ )
943
+ class DistilBertForSequenceClassification(DistilBertPreTrainedModel):
944
+ def __init__(self, config: PretrainedConfig):
945
+ super().__init__(config)
946
+ self.num_labels = config.num_labels
947
+ self.config = config
948
+
949
+ self.distilbert = DistilBertModel(config)
950
+ self.pre_classifier = nn.Linear(config.dim, config.dim)
951
+ self.classifier = nn.Linear(config.dim, config.num_labels)
952
+ self.dropout = nn.Dropout(config.seq_classif_dropout)
953
+
954
+ # Initialize weights and apply final processing
955
+ self.post_init()
956
+
957
+ def get_position_embeddings(self) -> nn.Embedding:
958
+ """
959
+ Returns the position embeddings
960
+ """
961
+ return self.distilbert.get_position_embeddings()
962
+
963
+ def resize_position_embeddings(self, new_num_position_embeddings: int):
964
+ """
965
+ Resizes position embeddings of the model if `new_num_position_embeddings != config.max_position_embeddings`.
966
+
967
+ Arguments:
968
+ new_num_position_embeddings (`int`):
969
+ The number of new position embedding matrix. If position embeddings are learned, increasing the size
970
+ will add newly initialized vectors at the end, whereas reducing the size will remove vectors from the
971
+ end. If position embeddings are not learned (*e.g.* sinusoidal position embeddings), increasing the
972
+ size will add correct vectors at the end following the position encoding algorithm, whereas reducing
973
+ the size will remove vectors from the end.
974
+ """
975
+ self.distilbert.resize_position_embeddings(new_num_position_embeddings)
976
+
977
+ @add_start_docstrings_to_model_forward(DISTILBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
978
+ @add_code_sample_docstrings(
979
+ checkpoint=_CHECKPOINT_FOR_DOC,
980
+ output_type=SequenceClassifierOutput,
981
+ config_class=_CONFIG_FOR_DOC,
982
+ )
983
+ def forward(
984
+ self,
985
+ input_ids: Optional[torch.Tensor] = None,
986
+ attention_mask: Optional[torch.Tensor] = None,
987
+ head_mask: Optional[torch.Tensor] = None,
988
+ inputs_embeds: Optional[torch.Tensor] = None,
989
+ labels: Optional[torch.LongTensor] = None,
990
+ output_attentions: Optional[bool] = None,
991
+ output_hidden_states: Optional[bool] = None,
992
+ return_dict: Optional[bool] = None,
993
+ ) -> Union[SequenceClassifierOutput, Tuple[torch.Tensor, ...]]:
994
+ r"""
995
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
996
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
997
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
998
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
999
+ """
1000
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1001
+
1002
+ distilbert_output = self.distilbert(
1003
+ input_ids=input_ids,
1004
+ attention_mask=attention_mask,
1005
+ head_mask=head_mask,
1006
+ inputs_embeds=inputs_embeds,
1007
+ output_attentions=output_attentions,
1008
+ output_hidden_states=output_hidden_states,
1009
+ return_dict=return_dict,
1010
+ )
1011
+ hidden_state = distilbert_output[0] # (bs, seq_len, dim)
1012
+ pooled_output = hidden_state[:, 0] # (bs, dim)
1013
+ pooled_output = self.pre_classifier(pooled_output) # (bs, dim)
1014
+ pooled_output = nn.ReLU()(pooled_output) # (bs, dim)
1015
+ pooled_output = self.dropout(pooled_output) # (bs, dim)
1016
+ logits = self.classifier(pooled_output) # (bs, num_labels)
1017
+
1018
+ loss = None
1019
+ if labels is not None:
1020
+ if self.config.problem_type is None:
1021
+ if self.num_labels == 1:
1022
+ self.config.problem_type = "regression"
1023
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1024
+ self.config.problem_type = "single_label_classification"
1025
+ else:
1026
+ self.config.problem_type = "multi_label_classification"
1027
+
1028
+ if self.config.problem_type == "regression":
1029
+ loss_fct = MSELoss()
1030
+ if self.num_labels == 1:
1031
+ loss = loss_fct(logits.squeeze(), labels.squeeze())
1032
+ else:
1033
+ loss = loss_fct(logits, labels)
1034
+ elif self.config.problem_type == "single_label_classification":
1035
+ loss_fct = CrossEntropyLoss()
1036
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
1037
+ elif self.config.problem_type == "multi_label_classification":
1038
+ loss_fct = BCEWithLogitsLoss()
1039
+ loss = loss_fct(logits, labels)
1040
+
1041
+ if not return_dict:
1042
+ output = (logits,) + distilbert_output[1:]
1043
+ return ((loss,) + output) if loss is not None else output
1044
+
1045
+ return SequenceClassifierOutput(
1046
+ loss=loss,
1047
+ logits=logits,
1048
+ hidden_states=distilbert_output.hidden_states,
1049
+ attentions=distilbert_output.attentions,
1050
+ )
1051
+
1052
+
1053
+ @add_start_docstrings(
1054
+ """
1055
+ DistilBert Model with a span classification head on top for extractive question-answering tasks like SQuAD (a
1056
+ linear layers on top of the hidden-states output to compute `span start logits` and `span end logits`).
1057
+ """,
1058
+ DISTILBERT_START_DOCSTRING,
1059
+ )
1060
+ class DistilBertForQuestionAnswering(DistilBertPreTrainedModel):
1061
+ def __init__(self, config: PretrainedConfig):
1062
+ super().__init__(config)
1063
+
1064
+ self.distilbert = DistilBertModel(config)
1065
+ self.qa_outputs = nn.Linear(config.dim, config.num_labels)
1066
+ if config.num_labels != 2:
1067
+ raise ValueError(f"config.num_labels should be 2, but it is {config.num_labels}")
1068
+
1069
+ self.dropout = nn.Dropout(config.qa_dropout)
1070
+
1071
+ # Initialize weights and apply final processing
1072
+ self.post_init()
1073
+
1074
+ def get_position_embeddings(self) -> nn.Embedding:
1075
+ """
1076
+ Returns the position embeddings
1077
+ """
1078
+ return self.distilbert.get_position_embeddings()
1079
+
1080
+ def resize_position_embeddings(self, new_num_position_embeddings: int):
1081
+ """
1082
+ Resizes position embeddings of the model if `new_num_position_embeddings != config.max_position_embeddings`.
1083
+
1084
+ Arguments:
1085
+ new_num_position_embeddings (`int`):
1086
+ The number of new position embedding matrix. If position embeddings are learned, increasing the size
1087
+ will add newly initialized vectors at the end, whereas reducing the size will remove vectors from the
1088
+ end. If position embeddings are not learned (*e.g.* sinusoidal position embeddings), increasing the
1089
+ size will add correct vectors at the end following the position encoding algorithm, whereas reducing
1090
+ the size will remove vectors from the end.
1091
+ """
1092
+ self.distilbert.resize_position_embeddings(new_num_position_embeddings)
1093
+
1094
+ @add_start_docstrings_to_model_forward(DISTILBERT_INPUTS_DOCSTRING.format("batch_size, num_choices"))
1095
+ @add_code_sample_docstrings(
1096
+ checkpoint=_CHECKPOINT_FOR_DOC,
1097
+ output_type=QuestionAnsweringModelOutput,
1098
+ config_class=_CONFIG_FOR_DOC,
1099
+ )
1100
+ def forward(
1101
+ self,
1102
+ input_ids: Optional[torch.Tensor] = None,
1103
+ attention_mask: Optional[torch.Tensor] = None,
1104
+ head_mask: Optional[torch.Tensor] = None,
1105
+ inputs_embeds: Optional[torch.Tensor] = None,
1106
+ start_positions: Optional[torch.Tensor] = None,
1107
+ end_positions: Optional[torch.Tensor] = None,
1108
+ output_attentions: Optional[bool] = None,
1109
+ output_hidden_states: Optional[bool] = None,
1110
+ return_dict: Optional[bool] = None,
1111
+ ) -> Union[QuestionAnsweringModelOutput, Tuple[torch.Tensor, ...]]:
1112
+ r"""
1113
+ start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1114
+ Labels for position (index) of the start of the labelled span for computing the token classification loss.
1115
+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
1116
+ are not taken into account for computing the loss.
1117
+ end_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1118
+ Labels for position (index) of the end of the labelled span for computing the token classification loss.
1119
+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
1120
+ are not taken into account for computing the loss.
1121
+ """
1122
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1123
+
1124
+ distilbert_output = self.distilbert(
1125
+ input_ids=input_ids,
1126
+ attention_mask=attention_mask,
1127
+ head_mask=head_mask,
1128
+ inputs_embeds=inputs_embeds,
1129
+ output_attentions=output_attentions,
1130
+ output_hidden_states=output_hidden_states,
1131
+ return_dict=return_dict,
1132
+ )
1133
+ hidden_states = distilbert_output[0] # (bs, max_query_len, dim)
1134
+
1135
+ hidden_states = self.dropout(hidden_states) # (bs, max_query_len, dim)
1136
+ logits = self.qa_outputs(hidden_states) # (bs, max_query_len, 2)
1137
+ start_logits, end_logits = logits.split(1, dim=-1)
1138
+ start_logits = start_logits.squeeze(-1).contiguous() # (bs, max_query_len)
1139
+ end_logits = end_logits.squeeze(-1).contiguous() # (bs, max_query_len)
1140
+
1141
+ total_loss = None
1142
+ if start_positions is not None and end_positions is not None:
1143
+ # If we are on multi-GPU, split add a dimension
1144
+ if len(start_positions.size()) > 1:
1145
+ start_positions = start_positions.squeeze(-1)
1146
+ if len(end_positions.size()) > 1:
1147
+ end_positions = end_positions.squeeze(-1)
1148
+ # sometimes the start/end positions are outside our model inputs, we ignore these terms
1149
+ ignored_index = start_logits.size(1)
1150
+ start_positions = start_positions.clamp(0, ignored_index)
1151
+ end_positions = end_positions.clamp(0, ignored_index)
1152
+
1153
+ loss_fct = nn.CrossEntropyLoss(ignore_index=ignored_index)
1154
+ start_loss = loss_fct(start_logits, start_positions)
1155
+ end_loss = loss_fct(end_logits, end_positions)
1156
+ total_loss = (start_loss + end_loss) / 2
1157
+
1158
+ if not return_dict:
1159
+ output = (start_logits, end_logits) + distilbert_output[1:]
1160
+ return ((total_loss,) + output) if total_loss is not None else output
1161
+
1162
+ return QuestionAnsweringModelOutput(
1163
+ loss=total_loss,
1164
+ start_logits=start_logits,
1165
+ end_logits=end_logits,
1166
+ hidden_states=distilbert_output.hidden_states,
1167
+ attentions=distilbert_output.attentions,
1168
+ )
1169
+
1170
+
1171
+ @add_start_docstrings(
1172
+ """
1173
+ DistilBert Model with a token classification head on top (a linear layer on top of the hidden-states output) e.g.
1174
+ for Named-Entity-Recognition (NER) tasks.
1175
+ """,
1176
+ DISTILBERT_START_DOCSTRING,
1177
+ )
1178
+ class DistilBertForTokenClassification(DistilBertPreTrainedModel):
1179
+ def __init__(self, config: PretrainedConfig):
1180
+ super().__init__(config)
1181
+ self.num_labels = config.num_labels
1182
+
1183
+ self.distilbert = DistilBertModel(config)
1184
+ self.dropout = nn.Dropout(config.dropout)
1185
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels)
1186
+
1187
+ # Initialize weights and apply final processing
1188
+ self.post_init()
1189
+
1190
+ def get_position_embeddings(self) -> nn.Embedding:
1191
+ """
1192
+ Returns the position embeddings
1193
+ """
1194
+ return self.distilbert.get_position_embeddings()
1195
+
1196
+ def resize_position_embeddings(self, new_num_position_embeddings: int):
1197
+ """
1198
+ Resizes position embeddings of the model if `new_num_position_embeddings != config.max_position_embeddings`.
1199
+
1200
+ Arguments:
1201
+ new_num_position_embeddings (`int`):
1202
+ The number of new position embedding matrix. If position embeddings are learned, increasing the size
1203
+ will add newly initialized vectors at the end, whereas reducing the size will remove vectors from the
1204
+ end. If position embeddings are not learned (*e.g.* sinusoidal position embeddings), increasing the
1205
+ size will add correct vectors at the end following the position encoding algorithm, whereas reducing
1206
+ the size will remove vectors from the end.
1207
+ """
1208
+ self.distilbert.resize_position_embeddings(new_num_position_embeddings)
1209
+
1210
+ @add_start_docstrings_to_model_forward(DISTILBERT_INPUTS_DOCSTRING)
1211
+ @add_code_sample_docstrings(
1212
+ checkpoint=_CHECKPOINT_FOR_DOC,
1213
+ output_type=TokenClassifierOutput,
1214
+ config_class=_CONFIG_FOR_DOC,
1215
+ )
1216
+ def forward(
1217
+ self,
1218
+ input_ids: Optional[torch.Tensor] = None,
1219
+ attention_mask: Optional[torch.Tensor] = None,
1220
+ head_mask: Optional[torch.Tensor] = None,
1221
+ inputs_embeds: Optional[torch.Tensor] = None,
1222
+ labels: Optional[torch.LongTensor] = None,
1223
+ output_attentions: Optional[bool] = None,
1224
+ output_hidden_states: Optional[bool] = None,
1225
+ return_dict: Optional[bool] = None,
1226
+ ) -> Union[TokenClassifierOutput, Tuple[torch.Tensor, ...]]:
1227
+ r"""
1228
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1229
+ Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`.
1230
+ """
1231
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1232
+
1233
+ outputs = self.distilbert(
1234
+ input_ids,
1235
+ attention_mask=attention_mask,
1236
+ head_mask=head_mask,
1237
+ inputs_embeds=inputs_embeds,
1238
+ output_attentions=output_attentions,
1239
+ output_hidden_states=output_hidden_states,
1240
+ return_dict=return_dict,
1241
+ )
1242
+
1243
+ sequence_output = outputs[0]
1244
+
1245
+ sequence_output = self.dropout(sequence_output)
1246
+ logits = self.classifier(sequence_output)
1247
+
1248
+ loss = None
1249
+ if labels is not None:
1250
+ loss_fct = CrossEntropyLoss()
1251
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
1252
+
1253
+ if not return_dict:
1254
+ output = (logits,) + outputs[1:]
1255
+ return ((loss,) + output) if loss is not None else output
1256
+
1257
+ return TokenClassifierOutput(
1258
+ loss=loss,
1259
+ logits=logits,
1260
+ hidden_states=outputs.hidden_states,
1261
+ attentions=outputs.attentions,
1262
+ )
1263
+
1264
+
1265
+ @add_start_docstrings(
1266
+ """
1267
+ DistilBert Model with a multiple choice classification head on top (a linear layer on top of the pooled output and
1268
+ a softmax) e.g. for RocStories/SWAG tasks.
1269
+ """,
1270
+ DISTILBERT_START_DOCSTRING,
1271
+ )
1272
+ class DistilBertForMultipleChoice(DistilBertPreTrainedModel):
1273
+ def __init__(self, config: PretrainedConfig):
1274
+ super().__init__(config)
1275
+
1276
+ self.distilbert = DistilBertModel(config)
1277
+ self.pre_classifier = nn.Linear(config.dim, config.dim)
1278
+ self.classifier = nn.Linear(config.dim, 1)
1279
+ self.dropout = nn.Dropout(config.seq_classif_dropout)
1280
+
1281
+ # Initialize weights and apply final processing
1282
+ self.post_init()
1283
+
1284
+ def get_position_embeddings(self) -> nn.Embedding:
1285
+ """
1286
+ Returns the position embeddings
1287
+ """
1288
+ return self.distilbert.get_position_embeddings()
1289
+
1290
+ def resize_position_embeddings(self, new_num_position_embeddings: int):
1291
+ """
1292
+ Resizes position embeddings of the model if `new_num_position_embeddings != config.max_position_embeddings`.
1293
+
1294
+ Arguments:
1295
+ new_num_position_embeddings (`int`)
1296
+ The number of new position embeddings. If position embeddings are learned, increasing the size will add
1297
+ newly initialized vectors at the end, whereas reducing the size will remove vectors from the end. If
1298
+ position embeddings are not learned (*e.g.* sinusoidal position embeddings), increasing the size will
1299
+ add correct vectors at the end following the position encoding algorithm, whereas reducing the size
1300
+ will remove vectors from the end.
1301
+ """
1302
+ self.distilbert.resize_position_embeddings(new_num_position_embeddings)
1303
+
1304
+ @add_start_docstrings_to_model_forward(
1305
+ DISTILBERT_INPUTS_DOCSTRING.format("batch_size, num_choices, sequence_length")
1306
+ )
1307
+ @replace_return_docstrings(output_type=MultipleChoiceModelOutput, config_class=_CONFIG_FOR_DOC)
1308
+ def forward(
1309
+ self,
1310
+ input_ids: Optional[torch.Tensor] = None,
1311
+ attention_mask: Optional[torch.Tensor] = None,
1312
+ head_mask: Optional[torch.Tensor] = None,
1313
+ inputs_embeds: Optional[torch.Tensor] = None,
1314
+ labels: Optional[torch.LongTensor] = None,
1315
+ output_attentions: Optional[bool] = None,
1316
+ output_hidden_states: Optional[bool] = None,
1317
+ return_dict: Optional[bool] = None,
1318
+ ) -> Union[MultipleChoiceModelOutput, Tuple[torch.Tensor, ...]]:
1319
+ r"""
1320
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1321
+ Labels for computing the multiple choice classification loss. Indices should be in `[0, ...,
1322
+ num_choices-1]` where `num_choices` is the size of the second dimension of the input tensors. (See
1323
+ `input_ids` above)
1324
+
1325
+ Returns:
1326
+
1327
+ Examples:
1328
+
1329
+ ```python
1330
+ >>> from transformers import AutoTokenizer, DistilBertForMultipleChoice
1331
+ >>> import torch
1332
+
1333
+ >>> tokenizer = AutoTokenizer.from_pretrained("distilbert-base-cased")
1334
+ >>> model = DistilBertForMultipleChoice.from_pretrained("distilbert-base-cased")
1335
+
1336
+ >>> prompt = "In Italy, pizza served in formal settings, such as at a restaurant, is presented unsliced."
1337
+ >>> choice0 = "It is eaten with a fork and a knife."
1338
+ >>> choice1 = "It is eaten while held in the hand."
1339
+ >>> labels = torch.tensor(0).unsqueeze(0) # choice0 is correct (according to Wikipedia ;)), batch size 1
1340
+
1341
+ >>> encoding = tokenizer([[prompt, choice0], [prompt, choice1]], return_tensors="pt", padding=True)
1342
+ >>> outputs = model(**{k: v.unsqueeze(0) for k, v in encoding.items()}, labels=labels) # batch size is 1
1343
+
1344
+ >>> # the linear classifier still needs to be trained
1345
+ >>> loss = outputs.loss
1346
+ >>> logits = outputs.logits
1347
+ ```"""
1348
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1349
+ num_choices = input_ids.shape[1] if input_ids is not None else inputs_embeds.shape[1]
1350
+
1351
+ input_ids = input_ids.view(-1, input_ids.size(-1)) if input_ids is not None else None
1352
+ attention_mask = attention_mask.view(-1, attention_mask.size(-1)) if attention_mask is not None else None
1353
+ inputs_embeds = (
1354
+ inputs_embeds.view(-1, inputs_embeds.size(-2), inputs_embeds.size(-1))
1355
+ if inputs_embeds is not None
1356
+ else None
1357
+ )
1358
+
1359
+ outputs = self.distilbert(
1360
+ input_ids,
1361
+ attention_mask=attention_mask,
1362
+ head_mask=head_mask,
1363
+ inputs_embeds=inputs_embeds,
1364
+ output_attentions=output_attentions,
1365
+ output_hidden_states=output_hidden_states,
1366
+ return_dict=return_dict,
1367
+ )
1368
+
1369
+ hidden_state = outputs[0] # (bs * num_choices, seq_len, dim)
1370
+ pooled_output = hidden_state[:, 0] # (bs * num_choices, dim)
1371
+ pooled_output = self.pre_classifier(pooled_output) # (bs * num_choices, dim)
1372
+ pooled_output = nn.ReLU()(pooled_output) # (bs * num_choices, dim)
1373
+ pooled_output = self.dropout(pooled_output) # (bs * num_choices, dim)
1374
+ logits = self.classifier(pooled_output) # (bs * num_choices, 1)
1375
+
1376
+ reshaped_logits = logits.view(-1, num_choices) # (bs, num_choices)
1377
+
1378
+ loss = None
1379
+ if labels is not None:
1380
+ loss_fct = CrossEntropyLoss()
1381
+ loss = loss_fct(reshaped_logits, labels)
1382
+
1383
+ if not return_dict:
1384
+ output = (reshaped_logits,) + outputs[1:]
1385
+ return ((loss,) + output) if loss is not None else output
1386
+
1387
+ return MultipleChoiceModelOutput(
1388
+ loss=loss,
1389
+ logits=reshaped_logits,
1390
+ hidden_states=outputs.hidden_states,
1391
+ attentions=outputs.attentions,
1392
+ )
env-llmeval/lib/python3.10/site-packages/transformers/models/distilbert/modeling_flax_distilbert.py ADDED
@@ -0,0 +1,895 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2019-present, the HuggingFace Inc. team, The Google AI Language Team and Facebook, Inc.
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
+
16
+ import math
17
+ from typing import Callable, Optional, Tuple
18
+
19
+ import flax.linen as nn
20
+ import jax
21
+ import jax.numpy as jnp
22
+ import numpy as np
23
+ from flax.core.frozen_dict import FrozenDict, freeze, unfreeze
24
+ from flax.traverse_util import flatten_dict, unflatten_dict
25
+ from jax import lax
26
+
27
+ from ...modeling_flax_outputs import (
28
+ FlaxBaseModelOutput,
29
+ FlaxMaskedLMOutput,
30
+ FlaxMultipleChoiceModelOutput,
31
+ FlaxQuestionAnsweringModelOutput,
32
+ FlaxSequenceClassifierOutput,
33
+ FlaxTokenClassifierOutput,
34
+ )
35
+ from ...modeling_flax_utils import ACT2FN, FlaxPreTrainedModel, append_call_sample_docstring, overwrite_call_docstring
36
+ from ...utils import add_start_docstrings, add_start_docstrings_to_model_forward, logging
37
+ from .configuration_distilbert import DistilBertConfig
38
+
39
+
40
+ logger = logging.get_logger(__name__)
41
+
42
+ _CHECKPOINT_FOR_DOC = "distilbert-base-uncased"
43
+ _CONFIG_FOR_DOC = "DistilBertConfig"
44
+
45
+
46
+ FLAX_DISTILBERT_START_DOCSTRING = r"""
47
+
48
+ This model inherits from [`FlaxPreTrainedModel`]. Check the superclass documentation for the generic methods the
49
+ library implements for all its model (such as downloading, saving and converting weights from PyTorch models)
50
+
51
+ This model is also a
52
+ [flax.linen.Module](https://flax.readthedocs.io/en/latest/api_reference/flax.linen/module.html) subclass. Use it as
53
+ a regular Flax linen Module and refer to the Flax documentation for all matter related to general usage and
54
+ behavior.
55
+
56
+ Finally, this model supports inherent JAX features such as:
57
+
58
+ - [Just-In-Time (JIT) compilation](https://jax.readthedocs.io/en/latest/jax.html#just-in-time-compilation-jit)
59
+ - [Automatic Differentiation](https://jax.readthedocs.io/en/latest/jax.html#automatic-differentiation)
60
+ - [Vectorization](https://jax.readthedocs.io/en/latest/jax.html#vectorization-vmap)
61
+ - [Parallelization](https://jax.readthedocs.io/en/latest/jax.html#parallelization-pmap)
62
+
63
+ Parameters:
64
+ config ([`DistilBertConfig`]): Model configuration class with all the parameters of the model.
65
+ Initializing with a config file does not load the weights associated with the model, only the
66
+ configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
67
+ """
68
+
69
+ DISTILBERT_INPUTS_DOCSTRING = r"""
70
+ Args:
71
+ input_ids (`numpy.ndarray` of shape `({0})`):
72
+ Indices of input sequence tokens in the vocabulary.
73
+
74
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
75
+ [`PreTrainedTokenizer.__call__`] for details.
76
+
77
+ [What are input IDs?](../glossary#input-ids)
78
+ attention_mask (`numpy.ndarray` of shape `({0})`, *optional*):
79
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
80
+
81
+ - 1 for tokens that are **not masked**,
82
+ - 0 for tokens that are **masked**.
83
+
84
+ [What are attention masks?](../glossary#attention-mask)
85
+ output_attentions (`bool`, *optional*):
86
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
87
+ tensors for more detail.
88
+ output_hidden_states (`bool`, *optional*):
89
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
90
+ more detail.
91
+ return_dict (`bool`, *optional*):
92
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
93
+ """
94
+
95
+
96
+ def get_angles(pos, i, d_model):
97
+ angle_rates = 1 / np.power(10000, (2 * (i // 2)) / np.float32(d_model))
98
+ return pos * angle_rates
99
+
100
+
101
+ def positional_encoding(position, d_model):
102
+ # create the sinusoidal pattern for the positional encoding
103
+ angle_rads = get_angles(np.arange(position)[:, np.newaxis], np.arange(d_model)[np.newaxis, :], d_model)
104
+
105
+ # apply sin to even indices in the array; 2i
106
+ angle_rads[:, 0::2] = np.sin(angle_rads[:, 0::2])
107
+
108
+ # apply cos to odd indices in the array; 2i+1
109
+ angle_rads[:, 1::2] = np.cos(angle_rads[:, 1::2])
110
+
111
+ pos_encoding = angle_rads[np.newaxis, ...]
112
+
113
+ return jnp.array(pos_encoding)
114
+
115
+
116
+ class FlaxEmbeddings(nn.Module):
117
+ """Construct the embeddings from word, position and token_type embeddings."""
118
+
119
+ config: DistilBertConfig
120
+ dtype: jnp.dtype = jnp.float32 # the dtype of the computation
121
+
122
+ def setup(self):
123
+ self.word_embeddings = nn.Embed(
124
+ self.config.vocab_size,
125
+ self.config.dim,
126
+ embedding_init=jax.nn.initializers.normal(stddev=self.config.initializer_range),
127
+ )
128
+ if not self.config.sinusoidal_pos_embds:
129
+ self.position_embeddings = nn.Embed(
130
+ self.config.max_position_embeddings,
131
+ self.config.dim,
132
+ embedding_init=jax.nn.initializers.normal(stddev=self.config.initializer_range),
133
+ )
134
+ else:
135
+ self.pos_encoding = positional_encoding(self.config.max_position_embeddings, self.config.dim)
136
+ self.LayerNorm = nn.LayerNorm(epsilon=1e-12, dtype=self.dtype)
137
+ self.dropout = nn.Dropout(rate=self.config.dropout)
138
+
139
+ def __call__(self, input_ids, deterministic: bool = True):
140
+ # Embed
141
+ batch_size, seq_length = input_ids.shape
142
+ inputs_embeds = self.word_embeddings(input_ids.astype("i4"))
143
+ if not self.config.sinusoidal_pos_embds:
144
+ position_ids = jnp.arange(seq_length).astype("i4")
145
+ position_ids = jnp.broadcast_to(position_ids, shape=(batch_size, seq_length))
146
+ position_embeds = self.position_embeddings(position_ids.astype("i4"))
147
+ else:
148
+ position_embeds = self.pos_encoding[:, :seq_length, :]
149
+ # explicitly cast the positions here, since self.embed_positions are not registered as parameters
150
+ position_embeds = position_embeds.astype(inputs_embeds.dtype)
151
+
152
+ # Sum all embeddings
153
+ hidden_states = inputs_embeds + position_embeds
154
+
155
+ # Layer Norm
156
+ hidden_states = self.LayerNorm(hidden_states)
157
+ hidden_states = self.dropout(hidden_states, deterministic=deterministic)
158
+ return hidden_states
159
+
160
+
161
+ class FlaxMultiHeadSelfAttention(nn.Module):
162
+ config: DistilBertConfig
163
+ dtype: jnp.dtype = jnp.float32 # the dtype of the computation
164
+
165
+ def setup(self):
166
+ self.n_heads = self.config.n_heads
167
+ self.dim = self.config.dim
168
+ self.dropout = nn.Dropout(rate=self.config.attention_dropout)
169
+
170
+ if not (self.dim % self.n_heads == 0):
171
+ raise ValueError(f"Hidden size {self.dim} not dividable by number of heads {self.n_heads}")
172
+
173
+ self.q_lin = nn.Dense(
174
+ self.dim,
175
+ dtype=self.dtype,
176
+ kernel_init=jax.nn.initializers.normal(stddev=self.config.initializer_range),
177
+ )
178
+ self.k_lin = nn.Dense(
179
+ self.dim,
180
+ dtype=self.dtype,
181
+ kernel_init=jax.nn.initializers.normal(stddev=self.config.initializer_range),
182
+ )
183
+ self.v_lin = nn.Dense(
184
+ self.dim,
185
+ dtype=self.dtype,
186
+ kernel_init=jax.nn.initializers.normal(stddev=self.config.initializer_range),
187
+ )
188
+ self.out_lin = nn.Dense(
189
+ self.dim,
190
+ dtype=self.dtype,
191
+ kernel_init=jax.nn.initializers.normal(stddev=self.config.initializer_range),
192
+ )
193
+
194
+ def __call__(
195
+ self,
196
+ query,
197
+ key,
198
+ value,
199
+ mask,
200
+ deterministic: bool = True,
201
+ output_attentions: bool = False,
202
+ ):
203
+ bs, q_len, dim = query.shape
204
+ k_len = key.shape[1]
205
+ # assert dim == self.dim, f'Dimensions do not match: {dim} input vs {self.dim} configured'
206
+ # assert key.size() == value.size()
207
+
208
+ dim_per_head = self.dim // self.n_heads
209
+
210
+ mask_reshp = (bs, 1, 1, k_len)
211
+
212
+ def shape(x):
213
+ """separate heads"""
214
+ return x.reshape(bs, -1, self.n_heads, dim_per_head).transpose(0, 2, 1, 3)
215
+
216
+ def unshape(x):
217
+ """group heads"""
218
+ return x.transpose(0, 2, 1, 3).reshape(bs, -1, self.n_heads * dim_per_head)
219
+
220
+ q = shape(self.q_lin(query)) # (bs, n_heads, q_len, dim_per_head)
221
+ k = shape(self.k_lin(key)) # (bs, n_heads, k_len, dim_per_head)
222
+ v = shape(self.v_lin(value)) # (bs, n_heads, k_len, dim_per_head)
223
+
224
+ q = q / math.sqrt(dim_per_head) # (bs, n_heads, q_len, dim_per_head)
225
+ scores = jnp.matmul(q, k.transpose(0, 1, 3, 2)) # (bs, n_heads, q_len, k_len)
226
+ mask = jnp.reshape(mask, mask_reshp)
227
+
228
+ mask = mask.astype(scores.dtype)
229
+ scores = scores - 1e30 * (1.0 - mask)
230
+
231
+ weights = nn.softmax(scores, axis=-1) # (bs, n_heads, q_len, k_len)
232
+ weights = self.dropout(weights, deterministic=deterministic)
233
+
234
+ context = jnp.matmul(weights, v) # (bs, n_heads, q_len, dim_per_head)
235
+ context = unshape(context) # (bs, q_len, dim)
236
+ context = self.out_lin(context) # (bs, q_len, dim)
237
+
238
+ if output_attentions:
239
+ return (context, weights)
240
+ else:
241
+ return (context,)
242
+
243
+
244
+ class FlaxFFN(nn.Module):
245
+ config: DistilBertConfig
246
+ dtype: jnp.dtype = jnp.float32 # the dtype of the computation
247
+
248
+ def setup(self):
249
+ self.dropout = nn.Dropout(rate=self.config.dropout)
250
+ self.chunk_size_feed_forward = self.config.chunk_size_feed_forward
251
+ self.seq_len_dim = 1
252
+ self.lin1 = nn.Dense(
253
+ self.config.hidden_dim,
254
+ dtype=self.dtype,
255
+ kernel_init=jax.nn.initializers.normal(stddev=self.config.initializer_range),
256
+ )
257
+ self.lin2 = nn.Dense(
258
+ self.config.dim,
259
+ dtype=self.dtype,
260
+ kernel_init=jax.nn.initializers.normal(stddev=self.config.initializer_range),
261
+ )
262
+
263
+ self.activation = ACT2FN[self.config.activation]
264
+
265
+ def __call__(self, hidden_states, deterministic: bool = True):
266
+ hidden_states = self.lin1(hidden_states)
267
+ hidden_states = self.activation(hidden_states)
268
+ hidden_states = self.lin2(hidden_states)
269
+ hidden_states = self.dropout(hidden_states, deterministic=deterministic)
270
+ return hidden_states
271
+
272
+
273
+ class FlaxTransformerBlock(nn.Module):
274
+ config: DistilBertConfig
275
+ dtype: jnp.dtype = jnp.float32 # the dtype of the computation
276
+
277
+ def setup(self):
278
+ assert (
279
+ self.config.dim % self.config.n_heads == 0
280
+ ), f"Hidden size {self.config.dim} not dividable by number of heads {self.config.n_heads}"
281
+
282
+ self.attention = FlaxMultiHeadSelfAttention(self.config, dtype=self.dtype)
283
+ self.sa_layer_norm = nn.LayerNorm(epsilon=1e-12, dtype=self.dtype)
284
+
285
+ self.ffn = FlaxFFN(self.config, dtype=self.dtype)
286
+ self.output_layer_norm = nn.LayerNorm(epsilon=1e-12, dtype=self.dtype)
287
+
288
+ def __call__(
289
+ self,
290
+ hidden_states,
291
+ attn_mask,
292
+ output_attentions: bool = False,
293
+ deterministic: bool = True,
294
+ ):
295
+ # Self-Attention
296
+ sa_output = self.attention(
297
+ query=hidden_states,
298
+ key=hidden_states,
299
+ value=hidden_states,
300
+ mask=attn_mask,
301
+ output_attentions=output_attentions,
302
+ deterministic=deterministic,
303
+ )
304
+ if output_attentions:
305
+ sa_output, sa_weights = sa_output
306
+ else:
307
+ assert type(sa_output) == tuple
308
+ sa_output = sa_output[0]
309
+ sa_output = self.sa_layer_norm(sa_output + hidden_states)
310
+
311
+ # Feed Forward Network
312
+ ffn_output = self.ffn(sa_output, deterministic=deterministic)
313
+ ffn_output = self.output_layer_norm(ffn_output + sa_output)
314
+ output = (ffn_output,)
315
+ if output_attentions:
316
+ output = (sa_weights,) + output
317
+ return output
318
+
319
+
320
+ class FlaxTransformer(nn.Module):
321
+ config: DistilBertConfig
322
+ dtype: jnp.dtype = jnp.float32 # the dtype of the computation
323
+
324
+ def setup(self):
325
+ self.layers = [
326
+ FlaxTransformerBlock(self.config, name=str(i), dtype=self.dtype) for i in range(self.config.n_layers)
327
+ ]
328
+
329
+ def __call__(
330
+ self,
331
+ hidden_states,
332
+ attention_mask,
333
+ output_attentions: bool = False,
334
+ output_hidden_states: bool = False,
335
+ deterministic: bool = True,
336
+ return_dict: bool = False,
337
+ ):
338
+ all_hidden_states = () if output_hidden_states else None
339
+ all_attentions = () if output_attentions else None
340
+
341
+ for layer_module in self.layers:
342
+ if output_hidden_states:
343
+ all_hidden_states = all_hidden_states + (hidden_states,)
344
+
345
+ layer_outputs = layer_module(
346
+ hidden_states=hidden_states,
347
+ attn_mask=attention_mask,
348
+ output_attentions=output_attentions,
349
+ deterministic=deterministic,
350
+ )
351
+ hidden_states = layer_outputs[-1]
352
+
353
+ if output_attentions:
354
+ assert len(layer_outputs) == 2
355
+ attentions = layer_outputs[0]
356
+ all_attentions = all_attentions + (attentions,)
357
+ else:
358
+ assert len(layer_outputs) == 1
359
+
360
+ # Add last layer
361
+ if output_hidden_states:
362
+ all_hidden_states = all_hidden_states + (hidden_states,)
363
+
364
+ if not return_dict:
365
+ return tuple(v for v in [hidden_states, all_attentions, all_hidden_states] if v is not None)
366
+ return FlaxBaseModelOutput(
367
+ last_hidden_state=hidden_states, hidden_states=all_hidden_states, attentions=all_attentions
368
+ )
369
+
370
+
371
+ class FlaxTransformerEncoder(nn.Module):
372
+ config: DistilBertConfig
373
+ dtype: jnp.dtype = jnp.float32 # the dtype of the computation
374
+
375
+ def setup(self):
376
+ self.layer = FlaxTransformer(self.config, dtype=self.dtype)
377
+
378
+ def __call__(
379
+ self,
380
+ hidden_states,
381
+ attention_mask,
382
+ output_attentions: bool = False,
383
+ output_hidden_states: bool = False,
384
+ deterministic: bool = True,
385
+ return_dict: bool = False,
386
+ ):
387
+ return self.layer(
388
+ hidden_states=hidden_states,
389
+ attention_mask=attention_mask,
390
+ output_attentions=output_attentions,
391
+ output_hidden_states=output_hidden_states,
392
+ deterministic=deterministic,
393
+ return_dict=return_dict,
394
+ )
395
+
396
+
397
+ class FlaxDistilBertLMDecoder(nn.Module):
398
+ config: DistilBertConfig
399
+ dtype: jnp.dtype = jnp.float32 # the dtype of the computation
400
+ bias_init: Callable[..., np.ndarray] = jax.nn.initializers.zeros
401
+
402
+ def setup(self):
403
+ self.bias = self.param("bias", self.bias_init, (self.config.vocab_size,))
404
+
405
+ def __call__(self, inputs, kernel):
406
+ inputs = jnp.asarray(inputs, self.dtype)
407
+ kernel = jnp.asarray(kernel, self.dtype)
408
+ y = lax.dot_general(inputs, kernel, (((inputs.ndim - 1,), (0,)), ((), ())))
409
+ bias = jnp.asarray(self.bias, self.dtype)
410
+ y = y + bias
411
+ return y
412
+
413
+
414
+ class FlaxDistilBertPreTrainedModel(FlaxPreTrainedModel):
415
+ """
416
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
417
+ models.
418
+ """
419
+
420
+ config_class = DistilBertConfig
421
+ base_model_prefix = "distilbert"
422
+ module_class: nn.Module = None
423
+
424
+ def __init__(
425
+ self,
426
+ config: DistilBertConfig,
427
+ input_shape: Tuple = (1, 1),
428
+ seed: int = 0,
429
+ dtype: jnp.dtype = jnp.float32,
430
+ _do_init: bool = True,
431
+ **kwargs,
432
+ ):
433
+ module = self.module_class(config=config, dtype=dtype, **kwargs)
434
+ super().__init__(config, module, input_shape=input_shape, seed=seed, dtype=dtype, _do_init=_do_init)
435
+
436
+ def init_weights(self, rng: jax.random.PRNGKey, input_shape: Tuple, params: FrozenDict = None) -> FrozenDict:
437
+ # init input tensors
438
+ input_ids = jnp.zeros(input_shape, dtype="i4")
439
+ attention_mask = jnp.ones_like(input_ids)
440
+
441
+ params_rng, dropout_rng = jax.random.split(rng)
442
+ rngs = {"params": params_rng, "dropout": dropout_rng}
443
+
444
+ random_params = self.module.init(rngs, input_ids, attention_mask, return_dict=False)["params"]
445
+
446
+ if params is not None:
447
+ random_params = flatten_dict(unfreeze(random_params))
448
+ params = flatten_dict(unfreeze(params))
449
+ for missing_key in self._missing_keys:
450
+ params[missing_key] = random_params[missing_key]
451
+ self._missing_keys = set()
452
+ return freeze(unflatten_dict(params))
453
+ else:
454
+ return random_params
455
+
456
+ @add_start_docstrings_to_model_forward(DISTILBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
457
+ def __call__(
458
+ self,
459
+ input_ids,
460
+ attention_mask=None,
461
+ head_mask=None,
462
+ params: dict = None,
463
+ dropout_rng: jax.random.PRNGKey = None,
464
+ train: bool = False,
465
+ output_attentions: Optional[bool] = None,
466
+ output_hidden_states: Optional[bool] = None,
467
+ return_dict: Optional[bool] = None,
468
+ ):
469
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
470
+ output_hidden_states = (
471
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
472
+ )
473
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
474
+
475
+ if attention_mask is None:
476
+ attention_mask = jnp.ones_like(input_ids)
477
+
478
+ # Handle any PRNG if needed
479
+ rngs = {}
480
+ if dropout_rng is not None:
481
+ rngs["dropout"] = dropout_rng
482
+
483
+ return self.module.apply(
484
+ {"params": params or self.params},
485
+ jnp.array(input_ids, dtype="i4"),
486
+ jnp.array(attention_mask, dtype="i4"),
487
+ not train,
488
+ output_attentions,
489
+ output_hidden_states,
490
+ return_dict,
491
+ rngs=rngs,
492
+ )
493
+
494
+
495
+ class FlaxDistilBertModule(nn.Module):
496
+ config: DistilBertConfig
497
+ dtype: jnp.dtype = jnp.float32 # the dtype of the computation
498
+
499
+ def setup(self):
500
+ self.embeddings = FlaxEmbeddings(self.config, dtype=self.dtype)
501
+ self.transformer = FlaxTransformerEncoder(self.config, dtype=self.dtype)
502
+
503
+ def __call__(
504
+ self,
505
+ input_ids,
506
+ attention_mask,
507
+ deterministic: bool = True,
508
+ output_attentions: bool = False,
509
+ output_hidden_states: bool = False,
510
+ return_dict: bool = True,
511
+ ):
512
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
513
+ output_hidden_states = (
514
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
515
+ )
516
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
517
+
518
+ input_embeds = self.embeddings(input_ids, deterministic=deterministic)
519
+ return self.transformer(
520
+ hidden_states=input_embeds,
521
+ attention_mask=attention_mask,
522
+ deterministic=deterministic,
523
+ output_attentions=output_attentions,
524
+ output_hidden_states=output_hidden_states,
525
+ return_dict=return_dict,
526
+ )
527
+
528
+
529
+ @add_start_docstrings(
530
+ "The bare DistilBert Model transformer outputting raw hidden-states without any specific head on top.",
531
+ FLAX_DISTILBERT_START_DOCSTRING,
532
+ )
533
+ class FlaxDistilBertModel(FlaxDistilBertPreTrainedModel):
534
+ module_class = FlaxDistilBertModule
535
+
536
+
537
+ append_call_sample_docstring(FlaxDistilBertModel, _CHECKPOINT_FOR_DOC, None, _CONFIG_FOR_DOC)
538
+
539
+
540
+ class FlaxDistilBertForMaskedLMModule(nn.Module):
541
+ config: DistilBertConfig
542
+ dtype: jnp.dtype = jnp.float32 # the dtype of the computation
543
+
544
+ def setup(self):
545
+ self.distilbert = FlaxDistilBertModule(self.config, dtype=self.dtype)
546
+ self.vocab_transform = nn.Dense(
547
+ self.config.dim,
548
+ dtype=self.dtype,
549
+ kernel_init=jax.nn.initializers.normal(stddev=self.config.initializer_range),
550
+ )
551
+ self.vocab_layer_norm = nn.LayerNorm(epsilon=1e-12, dtype=self.dtype)
552
+ if self.config.tie_word_embeddings:
553
+ self.vocab_projector = FlaxDistilBertLMDecoder(
554
+ self.config,
555
+ dtype=self.dtype,
556
+ )
557
+ else:
558
+ self.vocab_projector = nn.Dense(
559
+ self.config.vocab_size,
560
+ dtype=self.dtype,
561
+ kernel_init=jax.nn.initializers.normal(stddev=self.config.initializer_range),
562
+ )
563
+
564
+ def __call__(
565
+ self,
566
+ input_ids,
567
+ attention_mask,
568
+ deterministic: bool = True,
569
+ output_attentions: bool = False,
570
+ output_hidden_states: bool = False,
571
+ return_dict: bool = True,
572
+ ):
573
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
574
+
575
+ dlbrt_output = self.distilbert(
576
+ input_ids=input_ids,
577
+ attention_mask=attention_mask,
578
+ output_attentions=output_attentions,
579
+ output_hidden_states=output_hidden_states,
580
+ deterministic=deterministic,
581
+ return_dict=return_dict,
582
+ )
583
+ hidden_states = dlbrt_output[0]
584
+ prediction_logits = self.vocab_transform(hidden_states)
585
+ prediction_logits = ACT2FN[self.config.activation](prediction_logits)
586
+ prediction_logits = self.vocab_layer_norm(prediction_logits)
587
+
588
+ if self.config.tie_word_embeddings:
589
+ shared_embedding = self.distilbert.variables["params"]["embeddings"]["word_embeddings"]["embedding"]
590
+ prediction_logits = self.vocab_projector(prediction_logits, shared_embedding.T)
591
+ else:
592
+ prediction_logits = self.vocab_projector(prediction_logits)
593
+
594
+ if not return_dict:
595
+ output = (prediction_logits,) + dlbrt_output[1:]
596
+ return output
597
+
598
+ return FlaxMaskedLMOutput(
599
+ logits=prediction_logits,
600
+ hidden_states=dlbrt_output.hidden_states,
601
+ attentions=dlbrt_output.attentions,
602
+ )
603
+
604
+
605
+ @add_start_docstrings("""DistilBert Model with a `language modeling` head on top.""", FLAX_DISTILBERT_START_DOCSTRING)
606
+ class FlaxDistilBertForMaskedLM(FlaxDistilBertPreTrainedModel):
607
+ module_class = FlaxDistilBertForMaskedLMModule
608
+
609
+
610
+ append_call_sample_docstring(FlaxDistilBertForMaskedLM, _CHECKPOINT_FOR_DOC, FlaxMaskedLMOutput, _CONFIG_FOR_DOC)
611
+
612
+
613
+ class FlaxDistilBertForSequenceClassificationModule(nn.Module):
614
+ config: DistilBertConfig
615
+ dtype: jnp.dtype = jnp.float32
616
+
617
+ def setup(self):
618
+ self.distilbert = FlaxDistilBertModule(config=self.config, dtype=self.dtype)
619
+ self.pre_classifier = nn.Dense(
620
+ self.config.dim,
621
+ dtype=self.dtype,
622
+ kernel_init=jax.nn.initializers.normal(stddev=self.config.initializer_range),
623
+ )
624
+ self.dropout = nn.Dropout(rate=self.config.seq_classif_dropout)
625
+ self.classifier = nn.Dense(
626
+ self.config.num_labels,
627
+ dtype=self.dtype,
628
+ )
629
+
630
+ def __call__(
631
+ self,
632
+ input_ids,
633
+ attention_mask,
634
+ deterministic: bool = True,
635
+ output_attentions: bool = False,
636
+ output_hidden_states: bool = False,
637
+ return_dict: bool = True,
638
+ ):
639
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
640
+ # Model
641
+ distilbert_output = self.distilbert(
642
+ input_ids,
643
+ attention_mask,
644
+ deterministic=deterministic,
645
+ output_attentions=output_attentions,
646
+ output_hidden_states=output_hidden_states,
647
+ return_dict=return_dict,
648
+ )
649
+ hidden_state = distilbert_output[0] # (bs, seq_len, dim)
650
+ pooled_output = hidden_state[:, 0] # (bs, dim)
651
+ pooled_output = self.pre_classifier(pooled_output) # (bs, dim)
652
+ pooled_output = ACT2FN["relu"](pooled_output)
653
+ pooled_output = self.dropout(pooled_output, deterministic=deterministic)
654
+ logits = self.classifier(pooled_output) # (bs, dim)
655
+
656
+ if not return_dict:
657
+ return (logits,) + distilbert_output[1:]
658
+
659
+ return FlaxSequenceClassifierOutput(
660
+ logits=logits,
661
+ hidden_states=distilbert_output.hidden_states,
662
+ attentions=distilbert_output.attentions,
663
+ )
664
+
665
+
666
+ @add_start_docstrings(
667
+ """
668
+ DistilBert Model transformer with a sequence classification/regression head on top (a linear layer on top of the
669
+ pooled output) e.g. for GLUE tasks.
670
+ """,
671
+ FLAX_DISTILBERT_START_DOCSTRING,
672
+ )
673
+ class FlaxDistilBertForSequenceClassification(FlaxDistilBertPreTrainedModel):
674
+ module_class = FlaxDistilBertForSequenceClassificationModule
675
+
676
+
677
+ append_call_sample_docstring(
678
+ FlaxDistilBertForSequenceClassification,
679
+ _CHECKPOINT_FOR_DOC,
680
+ FlaxSequenceClassifierOutput,
681
+ _CONFIG_FOR_DOC,
682
+ )
683
+
684
+
685
+ class FlaxDistilBertForMultipleChoiceModule(nn.Module):
686
+ config: DistilBertConfig
687
+ dtype: jnp.dtype = jnp.float32
688
+
689
+ def setup(self):
690
+ self.distilbert = FlaxDistilBertModule(config=self.config, dtype=self.dtype)
691
+ self.pre_classifier = nn.Dense(
692
+ self.config.dim,
693
+ dtype=self.dtype,
694
+ kernel_init=jax.nn.initializers.normal(stddev=self.config.initializer_range),
695
+ )
696
+ self.dropout = nn.Dropout(rate=self.config.seq_classif_dropout)
697
+ self.classifier = nn.Dense(
698
+ 1,
699
+ dtype=self.dtype,
700
+ )
701
+
702
+ def __call__(
703
+ self,
704
+ input_ids,
705
+ attention_mask,
706
+ deterministic: bool = True,
707
+ output_attentions: bool = False,
708
+ output_hidden_states: bool = False,
709
+ return_dict: bool = True,
710
+ ):
711
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
712
+ num_choices = input_ids.shape[1]
713
+ input_ids = input_ids.reshape(-1, input_ids.shape[-1]) if input_ids is not None else None
714
+ attention_mask = attention_mask.reshape(-1, attention_mask.shape[-1]) if attention_mask is not None else None
715
+
716
+ # Model
717
+ outputs = self.distilbert(
718
+ input_ids,
719
+ attention_mask,
720
+ deterministic=deterministic,
721
+ output_attentions=output_attentions,
722
+ output_hidden_states=output_hidden_states,
723
+ return_dict=return_dict,
724
+ )
725
+
726
+ hidden_state = outputs[0]
727
+ pooled_output = hidden_state[:, 0]
728
+ pooled_output = self.pre_classifier(pooled_output)
729
+ pooled_output = ACT2FN["relu"](pooled_output)
730
+ pooled_output = self.dropout(pooled_output, deterministic=deterministic)
731
+ logits = self.classifier(pooled_output)
732
+
733
+ reshaped_logits = logits.reshape(-1, num_choices)
734
+
735
+ if not return_dict:
736
+ return (reshaped_logits,) + outputs[2:]
737
+
738
+ return FlaxMultipleChoiceModelOutput(
739
+ logits=reshaped_logits,
740
+ hidden_states=outputs.hidden_states,
741
+ attentions=outputs.attentions,
742
+ )
743
+
744
+
745
+ @add_start_docstrings(
746
+ """
747
+ DistilBert Model with a multiple choice classification head on top (a linear layer on top of the pooled output and
748
+ a softmax) e.g. for RocStories/SWAG tasks.
749
+ """,
750
+ FLAX_DISTILBERT_START_DOCSTRING,
751
+ )
752
+ class FlaxDistilBertForMultipleChoice(FlaxDistilBertPreTrainedModel):
753
+ module_class = FlaxDistilBertForMultipleChoiceModule
754
+
755
+
756
+ overwrite_call_docstring(
757
+ FlaxDistilBertForMultipleChoice, DISTILBERT_INPUTS_DOCSTRING.format("batch_size, num_choices, sequence_length")
758
+ )
759
+ append_call_sample_docstring(
760
+ FlaxDistilBertForMultipleChoice,
761
+ _CHECKPOINT_FOR_DOC,
762
+ FlaxMultipleChoiceModelOutput,
763
+ _CONFIG_FOR_DOC,
764
+ )
765
+
766
+
767
+ class FlaxDistilBertForTokenClassificationModule(nn.Module):
768
+ config: DistilBertConfig
769
+ dtype: jnp.dtype = jnp.float32
770
+
771
+ def setup(self):
772
+ self.distilbert = FlaxDistilBertModule(config=self.config, dtype=self.dtype)
773
+ self.dropout = nn.Dropout(rate=self.config.dropout)
774
+ self.classifier = nn.Dense(self.config.num_labels, dtype=self.dtype)
775
+
776
+ def __call__(
777
+ self,
778
+ input_ids,
779
+ attention_mask,
780
+ deterministic: bool = True,
781
+ output_attentions: bool = False,
782
+ output_hidden_states: bool = False,
783
+ return_dict: bool = True,
784
+ ):
785
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
786
+ # Model
787
+ outputs = self.distilbert(
788
+ input_ids,
789
+ attention_mask,
790
+ deterministic=deterministic,
791
+ output_attentions=output_attentions,
792
+ output_hidden_states=output_hidden_states,
793
+ return_dict=return_dict,
794
+ )
795
+
796
+ hidden_states = outputs[0]
797
+ hidden_states = self.dropout(hidden_states, deterministic=deterministic)
798
+ logits = self.classifier(hidden_states)
799
+
800
+ if not return_dict:
801
+ return (logits,) + outputs[1:]
802
+
803
+ return FlaxTokenClassifierOutput(
804
+ logits=logits,
805
+ hidden_states=outputs.hidden_states,
806
+ attentions=outputs.attentions,
807
+ )
808
+
809
+
810
+ @add_start_docstrings(
811
+ """
812
+ DistilBert Model with a token classification head on top (a linear layer on top of the hidden-states output) e.g.
813
+ for Named-Entity-Recognition (NER) tasks.
814
+ """,
815
+ FLAX_DISTILBERT_START_DOCSTRING,
816
+ )
817
+ class FlaxDistilBertForTokenClassification(FlaxDistilBertPreTrainedModel):
818
+ module_class = FlaxDistilBertForTokenClassificationModule
819
+
820
+
821
+ append_call_sample_docstring(
822
+ FlaxDistilBertForTokenClassification,
823
+ _CHECKPOINT_FOR_DOC,
824
+ FlaxTokenClassifierOutput,
825
+ _CONFIG_FOR_DOC,
826
+ )
827
+
828
+
829
+ class FlaxDistilBertForQuestionAnsweringModule(nn.Module):
830
+ config: DistilBertConfig
831
+ dtype: jnp.dtype = jnp.float32
832
+
833
+ def setup(self):
834
+ self.distilbert = FlaxDistilBertModule(config=self.config, dtype=self.dtype)
835
+ self.qa_outputs = nn.Dense(self.config.num_labels, dtype=self.dtype)
836
+ assert self.config.num_labels == 2
837
+ self.dropout = nn.Dropout(rate=self.config.qa_dropout)
838
+
839
+ def __call__(
840
+ self,
841
+ input_ids,
842
+ attention_mask,
843
+ deterministic: bool = True,
844
+ output_attentions: bool = False,
845
+ output_hidden_states: bool = False,
846
+ return_dict: bool = True,
847
+ ):
848
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
849
+
850
+ # Model
851
+ distilbert_output = self.distilbert(
852
+ input_ids,
853
+ attention_mask,
854
+ deterministic=deterministic,
855
+ output_attentions=output_attentions,
856
+ output_hidden_states=output_hidden_states,
857
+ return_dict=return_dict,
858
+ )
859
+
860
+ hidden_states = distilbert_output[0]
861
+
862
+ hidden_states = self.dropout(hidden_states, deterministic=deterministic)
863
+ logits = self.qa_outputs(hidden_states)
864
+ start_logits, end_logits = logits.split(self.config.num_labels, axis=-1)
865
+ start_logits = start_logits.squeeze(-1)
866
+ end_logits = end_logits.squeeze(-1)
867
+
868
+ if not return_dict:
869
+ return (start_logits, end_logits) + distilbert_output[1:]
870
+
871
+ return FlaxQuestionAnsweringModelOutput(
872
+ start_logits=start_logits,
873
+ end_logits=end_logits,
874
+ hidden_states=distilbert_output.hidden_states,
875
+ attentions=distilbert_output.attentions,
876
+ )
877
+
878
+
879
+ @add_start_docstrings(
880
+ """
881
+ DistilBert Model with a span classification head on top for extractive question-answering tasks like SQuAD (a
882
+ linear layers on top of the hidden-states output to compute `span start logits` and `span end logits`).
883
+ """,
884
+ FLAX_DISTILBERT_START_DOCSTRING,
885
+ )
886
+ class FlaxDistilBertForQuestionAnswering(FlaxDistilBertPreTrainedModel):
887
+ module_class = FlaxDistilBertForQuestionAnsweringModule
888
+
889
+
890
+ append_call_sample_docstring(
891
+ FlaxDistilBertForQuestionAnswering,
892
+ _CHECKPOINT_FOR_DOC,
893
+ FlaxQuestionAnsweringModelOutput,
894
+ _CONFIG_FOR_DOC,
895
+ )
env-llmeval/lib/python3.10/site-packages/transformers/models/distilbert/modeling_tf_distilbert.py ADDED
@@ -0,0 +1,1146 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2019-present, the HuggingFace Inc. team, The Google AI Language Team and Facebook, Inc.
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
+ """
16
+ TF 2.0 DistilBERT model
17
+ """
18
+
19
+
20
+ from __future__ import annotations
21
+
22
+ import warnings
23
+ from typing import Optional, Tuple, Union
24
+
25
+ import numpy as np
26
+ import tensorflow as tf
27
+
28
+ from ...activations_tf import get_tf_activation
29
+ from ...modeling_tf_outputs import (
30
+ TFBaseModelOutput,
31
+ TFMaskedLMOutput,
32
+ TFMultipleChoiceModelOutput,
33
+ TFQuestionAnsweringModelOutput,
34
+ TFSequenceClassifierOutput,
35
+ TFTokenClassifierOutput,
36
+ )
37
+ from ...modeling_tf_utils import (
38
+ TFMaskedLanguageModelingLoss,
39
+ TFModelInputType,
40
+ TFMultipleChoiceLoss,
41
+ TFPreTrainedModel,
42
+ TFQuestionAnsweringLoss,
43
+ TFSequenceClassificationLoss,
44
+ TFTokenClassificationLoss,
45
+ get_initializer,
46
+ keras,
47
+ keras_serializable,
48
+ unpack_inputs,
49
+ )
50
+ from ...tf_utils import check_embeddings_within_bounds, shape_list, stable_softmax
51
+ from ...utils import (
52
+ add_code_sample_docstrings,
53
+ add_start_docstrings,
54
+ add_start_docstrings_to_model_forward,
55
+ logging,
56
+ )
57
+ from .configuration_distilbert import DistilBertConfig
58
+
59
+
60
+ logger = logging.get_logger(__name__)
61
+
62
+ _CHECKPOINT_FOR_DOC = "distilbert-base-uncased"
63
+ _CONFIG_FOR_DOC = "DistilBertConfig"
64
+
65
+ TF_DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST = [
66
+ "distilbert-base-uncased",
67
+ "distilbert-base-uncased-distilled-squad",
68
+ "distilbert-base-cased",
69
+ "distilbert-base-cased-distilled-squad",
70
+ "distilbert-base-multilingual-cased",
71
+ "distilbert-base-uncased-finetuned-sst-2-english",
72
+ # See all DistilBERT models at https://huggingface.co/models?filter=distilbert
73
+ ]
74
+
75
+
76
+ class TFEmbeddings(keras.layers.Layer):
77
+ """Construct the embeddings from word, position and token_type embeddings."""
78
+
79
+ def __init__(self, config, **kwargs):
80
+ super().__init__(**kwargs)
81
+ self.config = config
82
+ self.dim = config.dim
83
+ self.initializer_range = config.initializer_range
84
+ self.max_position_embeddings = config.max_position_embeddings
85
+ self.LayerNorm = keras.layers.LayerNormalization(epsilon=1e-12, name="LayerNorm")
86
+ self.dropout = keras.layers.Dropout(rate=config.dropout)
87
+
88
+ def build(self, input_shape=None):
89
+ with tf.name_scope("word_embeddings"):
90
+ self.weight = self.add_weight(
91
+ name="weight",
92
+ shape=[self.config.vocab_size, self.dim],
93
+ initializer=get_initializer(initializer_range=self.initializer_range),
94
+ )
95
+
96
+ with tf.name_scope("position_embeddings"):
97
+ self.position_embeddings = self.add_weight(
98
+ name="embeddings",
99
+ shape=[self.max_position_embeddings, self.dim],
100
+ initializer=get_initializer(initializer_range=self.initializer_range),
101
+ )
102
+
103
+ if self.built:
104
+ return
105
+ self.built = True
106
+ if getattr(self, "LayerNorm", None) is not None:
107
+ with tf.name_scope(self.LayerNorm.name):
108
+ self.LayerNorm.build([None, None, self.config.dim])
109
+
110
+ def call(self, input_ids=None, position_ids=None, inputs_embeds=None, training=False):
111
+ """
112
+ Applies embedding based on inputs tensor.
113
+
114
+ Returns:
115
+ final_embeddings (`tf.Tensor`): output embedding tensor.
116
+ """
117
+ assert not (input_ids is None and inputs_embeds is None)
118
+
119
+ if input_ids is not None:
120
+ check_embeddings_within_bounds(input_ids, self.config.vocab_size)
121
+ inputs_embeds = tf.gather(params=self.weight, indices=input_ids)
122
+
123
+ input_shape = shape_list(inputs_embeds)[:-1]
124
+
125
+ if position_ids is None:
126
+ position_ids = tf.expand_dims(tf.range(start=0, limit=input_shape[-1]), axis=0)
127
+
128
+ position_embeds = tf.gather(params=self.position_embeddings, indices=position_ids)
129
+ final_embeddings = inputs_embeds + position_embeds
130
+ final_embeddings = self.LayerNorm(inputs=final_embeddings)
131
+ final_embeddings = self.dropout(inputs=final_embeddings, training=training)
132
+
133
+ return final_embeddings
134
+
135
+
136
+ class TFMultiHeadSelfAttention(keras.layers.Layer):
137
+ def __init__(self, config, **kwargs):
138
+ super().__init__(**kwargs)
139
+
140
+ self.n_heads = config.n_heads
141
+ self.dim = config.dim
142
+ self.dropout = keras.layers.Dropout(config.attention_dropout)
143
+ self.output_attentions = config.output_attentions
144
+
145
+ assert self.dim % self.n_heads == 0, f"Hidden size {self.dim} not dividable by number of heads {self.n_heads}"
146
+
147
+ self.q_lin = keras.layers.Dense(
148
+ config.dim, kernel_initializer=get_initializer(config.initializer_range), name="q_lin"
149
+ )
150
+ self.k_lin = keras.layers.Dense(
151
+ config.dim, kernel_initializer=get_initializer(config.initializer_range), name="k_lin"
152
+ )
153
+ self.v_lin = keras.layers.Dense(
154
+ config.dim, kernel_initializer=get_initializer(config.initializer_range), name="v_lin"
155
+ )
156
+ self.out_lin = keras.layers.Dense(
157
+ config.dim, kernel_initializer=get_initializer(config.initializer_range), name="out_lin"
158
+ )
159
+
160
+ self.pruned_heads = set()
161
+ self.config = config
162
+
163
+ def prune_heads(self, heads):
164
+ raise NotImplementedError
165
+
166
+ def call(self, query, key, value, mask, head_mask, output_attentions, training=False):
167
+ """
168
+ Parameters:
169
+ query: tf.Tensor(bs, seq_length, dim)
170
+ key: tf.Tensor(bs, seq_length, dim)
171
+ value: tf.Tensor(bs, seq_length, dim)
172
+ mask: tf.Tensor(bs, seq_length)
173
+
174
+ Returns:
175
+ weights: tf.Tensor(bs, n_heads, seq_length, seq_length) Attention weights context: tf.Tensor(bs,
176
+ seq_length, dim) Contextualized layer. Optional: only if `output_attentions=True`
177
+ """
178
+ bs, q_length, dim = shape_list(query)
179
+ k_length = shape_list(key)[1]
180
+ # assert dim == self.dim, f'Dimensions do not match: {dim} input vs {self.dim} configured'
181
+ # assert key.size() == value.size()
182
+ dim_per_head = int(self.dim / self.n_heads)
183
+ dim_per_head = tf.cast(dim_per_head, dtype=tf.int32)
184
+ mask_reshape = [bs, 1, 1, k_length]
185
+
186
+ def shape(x):
187
+ """separate heads"""
188
+ return tf.transpose(tf.reshape(x, (bs, -1, self.n_heads, dim_per_head)), perm=(0, 2, 1, 3))
189
+
190
+ def unshape(x):
191
+ """group heads"""
192
+ return tf.reshape(tf.transpose(x, perm=(0, 2, 1, 3)), (bs, -1, self.n_heads * dim_per_head))
193
+
194
+ q = shape(self.q_lin(query)) # (bs, n_heads, q_length, dim_per_head)
195
+ k = shape(self.k_lin(key)) # (bs, n_heads, k_length, dim_per_head)
196
+ v = shape(self.v_lin(value)) # (bs, n_heads, k_length, dim_per_head)
197
+ q = tf.cast(q, dtype=tf.float32)
198
+ q = tf.multiply(q, tf.math.rsqrt(tf.cast(dim_per_head, dtype=tf.float32)))
199
+ k = tf.cast(k, dtype=q.dtype)
200
+ scores = tf.matmul(q, k, transpose_b=True) # (bs, n_heads, q_length, k_length)
201
+ mask = tf.reshape(mask, mask_reshape) # (bs, n_heads, qlen, klen)
202
+ # scores.masked_fill_(mask, -float('inf')) # (bs, n_heads, q_length, k_length)
203
+
204
+ mask = tf.cast(mask, dtype=scores.dtype)
205
+ scores = scores - 1e30 * (1.0 - mask)
206
+ weights = stable_softmax(scores, axis=-1) # (bs, n_heads, qlen, klen)
207
+ weights = self.dropout(weights, training=training) # (bs, n_heads, qlen, klen)
208
+
209
+ # Mask heads if we want to
210
+ if head_mask is not None:
211
+ weights = weights * head_mask
212
+
213
+ context = tf.matmul(weights, v) # (bs, n_heads, qlen, dim_per_head)
214
+ context = unshape(context) # (bs, q_length, dim)
215
+ context = self.out_lin(context) # (bs, q_length, dim)
216
+
217
+ if output_attentions:
218
+ return (context, weights)
219
+ else:
220
+ return (context,)
221
+
222
+ def build(self, input_shape=None):
223
+ if self.built:
224
+ return
225
+ self.built = True
226
+ if getattr(self, "q_lin", None) is not None:
227
+ with tf.name_scope(self.q_lin.name):
228
+ self.q_lin.build([None, None, self.config.dim])
229
+ if getattr(self, "k_lin", None) is not None:
230
+ with tf.name_scope(self.k_lin.name):
231
+ self.k_lin.build([None, None, self.config.dim])
232
+ if getattr(self, "v_lin", None) is not None:
233
+ with tf.name_scope(self.v_lin.name):
234
+ self.v_lin.build([None, None, self.config.dim])
235
+ if getattr(self, "out_lin", None) is not None:
236
+ with tf.name_scope(self.out_lin.name):
237
+ self.out_lin.build([None, None, self.config.dim])
238
+
239
+
240
+ class TFFFN(keras.layers.Layer):
241
+ def __init__(self, config, **kwargs):
242
+ super().__init__(**kwargs)
243
+ self.dropout = keras.layers.Dropout(config.dropout)
244
+ self.lin1 = keras.layers.Dense(
245
+ config.hidden_dim, kernel_initializer=get_initializer(config.initializer_range), name="lin1"
246
+ )
247
+ self.lin2 = keras.layers.Dense(
248
+ config.dim, kernel_initializer=get_initializer(config.initializer_range), name="lin2"
249
+ )
250
+ self.activation = get_tf_activation(config.activation)
251
+ self.config = config
252
+
253
+ def call(self, input, training=False):
254
+ x = self.lin1(input)
255
+ x = self.activation(x)
256
+ x = self.lin2(x)
257
+ x = self.dropout(x, training=training)
258
+ return x
259
+
260
+ def build(self, input_shape=None):
261
+ if self.built:
262
+ return
263
+ self.built = True
264
+ if getattr(self, "lin1", None) is not None:
265
+ with tf.name_scope(self.lin1.name):
266
+ self.lin1.build([None, None, self.config.dim])
267
+ if getattr(self, "lin2", None) is not None:
268
+ with tf.name_scope(self.lin2.name):
269
+ self.lin2.build([None, None, self.config.hidden_dim])
270
+
271
+
272
+ class TFTransformerBlock(keras.layers.Layer):
273
+ def __init__(self, config, **kwargs):
274
+ super().__init__(**kwargs)
275
+
276
+ self.n_heads = config.n_heads
277
+ self.dim = config.dim
278
+ self.hidden_dim = config.hidden_dim
279
+ self.dropout = keras.layers.Dropout(config.dropout)
280
+ self.activation = config.activation
281
+ self.output_attentions = config.output_attentions
282
+
283
+ assert (
284
+ config.dim % config.n_heads == 0
285
+ ), f"Hidden size {config.dim} not dividable by number of heads {config.n_heads}"
286
+
287
+ self.attention = TFMultiHeadSelfAttention(config, name="attention")
288
+ self.sa_layer_norm = keras.layers.LayerNormalization(epsilon=1e-12, name="sa_layer_norm")
289
+
290
+ self.ffn = TFFFN(config, name="ffn")
291
+ self.output_layer_norm = keras.layers.LayerNormalization(epsilon=1e-12, name="output_layer_norm")
292
+ self.config = config
293
+
294
+ def call(self, x, attn_mask, head_mask, output_attentions, training=False): # removed: src_enc=None, src_len=None
295
+ """
296
+ Parameters:
297
+ x: tf.Tensor(bs, seq_length, dim)
298
+ attn_mask: tf.Tensor(bs, seq_length)
299
+
300
+ Outputs: sa_weights: tf.Tensor(bs, n_heads, seq_length, seq_length) The attention weights ffn_output:
301
+ tf.Tensor(bs, seq_length, dim) The output of the transformer block contextualization.
302
+ """
303
+ # Self-Attention
304
+ sa_output = self.attention(x, x, x, attn_mask, head_mask, output_attentions, training=training)
305
+ if output_attentions:
306
+ sa_output, sa_weights = sa_output # (bs, seq_length, dim), (bs, n_heads, seq_length, seq_length)
307
+ else: # To handle these `output_attentions` or `output_hidden_states` cases returning tuples
308
+ # assert type(sa_output) == tuple
309
+ sa_output = sa_output[0]
310
+ sa_output = self.sa_layer_norm(sa_output + x) # (bs, seq_length, dim)
311
+
312
+ # Feed Forward Network
313
+ ffn_output = self.ffn(sa_output, training=training) # (bs, seq_length, dim)
314
+ ffn_output = self.output_layer_norm(ffn_output + sa_output) # (bs, seq_length, dim)
315
+
316
+ output = (ffn_output,)
317
+ if output_attentions:
318
+ output = (sa_weights,) + output
319
+ return output
320
+
321
+ def build(self, input_shape=None):
322
+ if self.built:
323
+ return
324
+ self.built = True
325
+ if getattr(self, "attention", None) is not None:
326
+ with tf.name_scope(self.attention.name):
327
+ self.attention.build(None)
328
+ if getattr(self, "sa_layer_norm", None) is not None:
329
+ with tf.name_scope(self.sa_layer_norm.name):
330
+ self.sa_layer_norm.build([None, None, self.config.dim])
331
+ if getattr(self, "ffn", None) is not None:
332
+ with tf.name_scope(self.ffn.name):
333
+ self.ffn.build(None)
334
+ if getattr(self, "output_layer_norm", None) is not None:
335
+ with tf.name_scope(self.output_layer_norm.name):
336
+ self.output_layer_norm.build([None, None, self.config.dim])
337
+
338
+
339
+ class TFTransformer(keras.layers.Layer):
340
+ def __init__(self, config, **kwargs):
341
+ super().__init__(**kwargs)
342
+ self.n_layers = config.n_layers
343
+ self.output_hidden_states = config.output_hidden_states
344
+ self.output_attentions = config.output_attentions
345
+
346
+ self.layer = [TFTransformerBlock(config, name=f"layer_._{i}") for i in range(config.n_layers)]
347
+
348
+ def call(self, x, attn_mask, head_mask, output_attentions, output_hidden_states, return_dict, training=False):
349
+ # docstyle-ignore
350
+ """
351
+ Parameters:
352
+ x: tf.Tensor(bs, seq_length, dim) Input sequence embedded.
353
+ attn_mask: tf.Tensor(bs, seq_length) Attention mask on the sequence.
354
+
355
+ Returns:
356
+ hidden_state: tf.Tensor(bs, seq_length, dim)
357
+ Sequence of hidden states in the last (top) layer
358
+ all_hidden_states: Tuple[tf.Tensor(bs, seq_length, dim)]
359
+ Tuple of length n_layers with the hidden states from each layer.
360
+ Optional: only if output_hidden_states=True
361
+ all_attentions: Tuple[tf.Tensor(bs, n_heads, seq_length, seq_length)]
362
+ Tuple of length n_layers with the attention weights from each layer
363
+ Optional: only if output_attentions=True
364
+ """
365
+ all_hidden_states = () if output_hidden_states else None
366
+ all_attentions = () if output_attentions else None
367
+
368
+ hidden_state = x
369
+ for i, layer_module in enumerate(self.layer):
370
+ if output_hidden_states:
371
+ all_hidden_states = all_hidden_states + (hidden_state,)
372
+
373
+ layer_outputs = layer_module(hidden_state, attn_mask, head_mask[i], output_attentions, training=training)
374
+ hidden_state = layer_outputs[-1]
375
+
376
+ if output_attentions:
377
+ assert len(layer_outputs) == 2
378
+ attentions = layer_outputs[0]
379
+ all_attentions = all_attentions + (attentions,)
380
+ else:
381
+ assert len(layer_outputs) == 1, f"Incorrect number of outputs {len(layer_outputs)} instead of 1"
382
+
383
+ # Add last layer
384
+ if output_hidden_states:
385
+ all_hidden_states = all_hidden_states + (hidden_state,)
386
+
387
+ if not return_dict:
388
+ return tuple(v for v in [hidden_state, all_hidden_states, all_attentions] if v is not None)
389
+ return TFBaseModelOutput(
390
+ last_hidden_state=hidden_state, hidden_states=all_hidden_states, attentions=all_attentions
391
+ )
392
+
393
+ def build(self, input_shape=None):
394
+ if self.built:
395
+ return
396
+ self.built = True
397
+ if getattr(self, "layer", None) is not None:
398
+ for layer in self.layer:
399
+ with tf.name_scope(layer.name):
400
+ layer.build(None)
401
+
402
+
403
+ @keras_serializable
404
+ class TFDistilBertMainLayer(keras.layers.Layer):
405
+ config_class = DistilBertConfig
406
+
407
+ def __init__(self, config, **kwargs):
408
+ super().__init__(**kwargs)
409
+
410
+ self.config = config
411
+ self.num_hidden_layers = config.num_hidden_layers
412
+ self.output_attentions = config.output_attentions
413
+ self.output_hidden_states = config.output_hidden_states
414
+ self.return_dict = config.use_return_dict
415
+
416
+ self.embeddings = TFEmbeddings(config, name="embeddings") # Embeddings
417
+ self.transformer = TFTransformer(config, name="transformer") # Encoder
418
+
419
+ def get_input_embeddings(self):
420
+ return self.embeddings
421
+
422
+ def set_input_embeddings(self, value):
423
+ self.embeddings.weight = value
424
+ self.embeddings.vocab_size = value.shape[0]
425
+
426
+ def _prune_heads(self, heads_to_prune):
427
+ raise NotImplementedError
428
+
429
+ @unpack_inputs
430
+ def call(
431
+ self,
432
+ input_ids=None,
433
+ attention_mask=None,
434
+ head_mask=None,
435
+ inputs_embeds=None,
436
+ output_attentions=None,
437
+ output_hidden_states=None,
438
+ return_dict=None,
439
+ training=False,
440
+ ):
441
+ if input_ids is not None and inputs_embeds is not None:
442
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
443
+ elif input_ids is not None:
444
+ input_shape = shape_list(input_ids)
445
+ elif inputs_embeds is not None:
446
+ input_shape = shape_list(inputs_embeds)[:-1]
447
+ else:
448
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
449
+
450
+ if attention_mask is None:
451
+ attention_mask = tf.ones(input_shape) # (bs, seq_length)
452
+
453
+ attention_mask = tf.cast(attention_mask, dtype=tf.float32)
454
+
455
+ # Prepare head mask if needed
456
+ # 1.0 in head_mask indicate we keep the head
457
+ # attention_probs has shape bsz x n_heads x N x N
458
+ # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]
459
+ # and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]
460
+ if head_mask is not None:
461
+ raise NotImplementedError
462
+ else:
463
+ head_mask = [None] * self.num_hidden_layers
464
+
465
+ embedding_output = self.embeddings(input_ids, inputs_embeds=inputs_embeds) # (bs, seq_length, dim)
466
+ tfmr_output = self.transformer(
467
+ embedding_output,
468
+ attention_mask,
469
+ head_mask,
470
+ output_attentions,
471
+ output_hidden_states,
472
+ return_dict,
473
+ training=training,
474
+ )
475
+
476
+ return tfmr_output # last-layer hidden-state, (all hidden_states), (all attentions)
477
+
478
+ def build(self, input_shape=None):
479
+ if self.built:
480
+ return
481
+ self.built = True
482
+ if getattr(self, "embeddings", None) is not None:
483
+ with tf.name_scope(self.embeddings.name):
484
+ self.embeddings.build(None)
485
+ if getattr(self, "transformer", None) is not None:
486
+ with tf.name_scope(self.transformer.name):
487
+ self.transformer.build(None)
488
+
489
+
490
+ # INTERFACE FOR ENCODER AND TASK SPECIFIC MODEL #
491
+ class TFDistilBertPreTrainedModel(TFPreTrainedModel):
492
+ """
493
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
494
+ models.
495
+ """
496
+
497
+ config_class = DistilBertConfig
498
+ base_model_prefix = "distilbert"
499
+
500
+
501
+ DISTILBERT_START_DOCSTRING = r"""
502
+
503
+ This model inherits from [`TFPreTrainedModel`]. Check the superclass documentation for the generic methods the
504
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
505
+ etc.)
506
+
507
+ This model is also a [keras.Model](https://www.tensorflow.org/api_docs/python/tf/keras/Model) subclass. Use it
508
+ as a regular TF 2.0 Keras Model and refer to the TF 2.0 documentation for all matter related to general usage and
509
+ behavior.
510
+
511
+ <Tip>
512
+
513
+ TensorFlow models and layers in `transformers` accept two formats as input:
514
+
515
+ - having all inputs as keyword arguments (like PyTorch models), or
516
+ - having all inputs as a list, tuple or dict in the first positional argument.
517
+
518
+ The reason the second format is supported is that Keras methods prefer this format when passing inputs to models
519
+ and layers. Because of this support, when using methods like `model.fit()` things should "just work" for you - just
520
+ pass your inputs and labels in any format that `model.fit()` supports! If, however, you want to use the second
521
+ format outside of Keras methods like `fit()` and `predict()`, such as when creating your own layers or models with
522
+ the Keras `Functional` API, there are three possibilities you can use to gather all the input Tensors in the first
523
+ positional argument:
524
+
525
+ - a single Tensor with `input_ids` only and nothing else: `model(input_ids)`
526
+ - a list of varying length with one or several input Tensors IN THE ORDER given in the docstring:
527
+ `model([input_ids, attention_mask])` or `model([input_ids, attention_mask, token_type_ids])`
528
+ - a dictionary with one or several input Tensors associated to the input names given in the docstring:
529
+ `model({"input_ids": input_ids, "token_type_ids": token_type_ids})`
530
+
531
+ Note that when creating models and layers with
532
+ [subclassing](https://keras.io/guides/making_new_layers_and_models_via_subclassing/) then you don't need to worry
533
+ about any of this, as you can just pass inputs like you would to any other Python function!
534
+
535
+ </Tip>
536
+
537
+ Parameters:
538
+ config ([`DistilBertConfig`]): Model configuration class with all the parameters of the model.
539
+ Initializing with a config file does not load the weights associated with the model, only the
540
+ configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
541
+ """
542
+
543
+ DISTILBERT_INPUTS_DOCSTRING = r"""
544
+ Args:
545
+ input_ids (`Numpy array` or `tf.Tensor` of shape `({0})`):
546
+ Indices of input sequence tokens in the vocabulary.
547
+
548
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.__call__`] and
549
+ [`PreTrainedTokenizer.encode`] for details.
550
+
551
+ [What are input IDs?](../glossary#input-ids)
552
+ attention_mask (`Numpy array` or `tf.Tensor` of shape `({0})`, *optional*):
553
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
554
+
555
+ - 1 for tokens that are **not masked**,
556
+ - 0 for tokens that are **masked**.
557
+
558
+ [What are attention masks?](../glossary#attention-mask)
559
+ head_mask (`Numpy array` or `tf.Tensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
560
+ Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:
561
+
562
+ - 1 indicates the head is **not masked**,
563
+ - 0 indicates the head is **masked**.
564
+
565
+ inputs_embeds (`tf.Tensor` of shape `({0}, hidden_size)`, *optional*):
566
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
567
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
568
+ model's internal embedding lookup matrix.
569
+ output_attentions (`bool`, *optional*):
570
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
571
+ tensors for more detail. This argument can be used only in eager mode, in graph mode the value in the
572
+ config will be used instead.
573
+ output_hidden_states (`bool`, *optional*):
574
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
575
+ more detail. This argument can be used only in eager mode, in graph mode the value in the config will be
576
+ used instead.
577
+ return_dict (`bool`, *optional*):
578
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. This argument can be used in
579
+ eager mode, in graph mode the value will always be set to True.
580
+ training (`bool`, *optional*, defaults to `False`):
581
+ Whether or not to use the model in training mode (some modules like dropout modules have different
582
+ behaviors between training and evaluation).
583
+ """
584
+
585
+
586
+ @add_start_docstrings(
587
+ "The bare DistilBERT encoder/transformer outputting raw hidden-states without any specific head on top.",
588
+ DISTILBERT_START_DOCSTRING,
589
+ )
590
+ class TFDistilBertModel(TFDistilBertPreTrainedModel):
591
+ def __init__(self, config, *inputs, **kwargs):
592
+ super().__init__(config, *inputs, **kwargs)
593
+ self.distilbert = TFDistilBertMainLayer(config, name="distilbert") # Embeddings
594
+
595
+ @unpack_inputs
596
+ @add_start_docstrings_to_model_forward(DISTILBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
597
+ @add_code_sample_docstrings(
598
+ checkpoint=_CHECKPOINT_FOR_DOC,
599
+ output_type=TFBaseModelOutput,
600
+ config_class=_CONFIG_FOR_DOC,
601
+ )
602
+ def call(
603
+ self,
604
+ input_ids: TFModelInputType | None = None,
605
+ attention_mask: np.ndarray | tf.Tensor | None = None,
606
+ head_mask: np.ndarray | tf.Tensor | None = None,
607
+ inputs_embeds: np.ndarray | tf.Tensor | None = None,
608
+ output_attentions: Optional[bool] = None,
609
+ output_hidden_states: Optional[bool] = None,
610
+ return_dict: Optional[bool] = None,
611
+ training: Optional[bool] = False,
612
+ ) -> Union[TFBaseModelOutput, Tuple[tf.Tensor]]:
613
+ outputs = self.distilbert(
614
+ input_ids=input_ids,
615
+ attention_mask=attention_mask,
616
+ head_mask=head_mask,
617
+ inputs_embeds=inputs_embeds,
618
+ output_attentions=output_attentions,
619
+ output_hidden_states=output_hidden_states,
620
+ return_dict=return_dict,
621
+ training=training,
622
+ )
623
+ return outputs
624
+
625
+ def build(self, input_shape=None):
626
+ if self.built:
627
+ return
628
+ self.built = True
629
+ if getattr(self, "distilbert", None) is not None:
630
+ with tf.name_scope(self.distilbert.name):
631
+ self.distilbert.build(None)
632
+
633
+
634
+ class TFDistilBertLMHead(keras.layers.Layer):
635
+ def __init__(self, config, input_embeddings, **kwargs):
636
+ super().__init__(**kwargs)
637
+
638
+ self.config = config
639
+ self.dim = config.dim
640
+
641
+ # The output weights are the same as the input embeddings, but there is
642
+ # an output-only bias for each token.
643
+ self.input_embeddings = input_embeddings
644
+
645
+ def build(self, input_shape):
646
+ self.bias = self.add_weight(shape=(self.config.vocab_size,), initializer="zeros", trainable=True, name="bias")
647
+
648
+ super().build(input_shape)
649
+
650
+ def get_output_embeddings(self):
651
+ return self.input_embeddings
652
+
653
+ def set_output_embeddings(self, value):
654
+ self.input_embeddings.weight = value
655
+ self.input_embeddings.vocab_size = shape_list(value)[0]
656
+
657
+ def get_bias(self):
658
+ return {"bias": self.bias}
659
+
660
+ def set_bias(self, value):
661
+ self.bias = value["bias"]
662
+ self.config.vocab_size = shape_list(value["bias"])[0]
663
+
664
+ def call(self, hidden_states):
665
+ seq_length = shape_list(tensor=hidden_states)[1]
666
+ hidden_states = tf.reshape(tensor=hidden_states, shape=[-1, self.dim])
667
+ hidden_states = tf.matmul(a=hidden_states, b=self.input_embeddings.weight, transpose_b=True)
668
+ hidden_states = tf.reshape(tensor=hidden_states, shape=[-1, seq_length, self.config.vocab_size])
669
+ hidden_states = tf.nn.bias_add(value=hidden_states, bias=self.bias)
670
+
671
+ return hidden_states
672
+
673
+
674
+ @add_start_docstrings(
675
+ """DistilBert Model with a `masked language modeling` head on top.""",
676
+ DISTILBERT_START_DOCSTRING,
677
+ )
678
+ class TFDistilBertForMaskedLM(TFDistilBertPreTrainedModel, TFMaskedLanguageModelingLoss):
679
+ def __init__(self, config, *inputs, **kwargs):
680
+ super().__init__(config, *inputs, **kwargs)
681
+ self.config = config
682
+
683
+ self.distilbert = TFDistilBertMainLayer(config, name="distilbert")
684
+ self.vocab_transform = keras.layers.Dense(
685
+ config.dim, kernel_initializer=get_initializer(config.initializer_range), name="vocab_transform"
686
+ )
687
+ self.act = get_tf_activation(config.activation)
688
+ self.vocab_layer_norm = keras.layers.LayerNormalization(epsilon=1e-12, name="vocab_layer_norm")
689
+ self.vocab_projector = TFDistilBertLMHead(config, self.distilbert.embeddings, name="vocab_projector")
690
+
691
+ def get_lm_head(self):
692
+ return self.vocab_projector
693
+
694
+ def get_prefix_bias_name(self):
695
+ warnings.warn("The method get_prefix_bias_name is deprecated. Please use `get_bias` instead.", FutureWarning)
696
+ return self.name + "/" + self.vocab_projector.name
697
+
698
+ @unpack_inputs
699
+ @add_start_docstrings_to_model_forward(DISTILBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
700
+ @add_code_sample_docstrings(
701
+ checkpoint=_CHECKPOINT_FOR_DOC,
702
+ output_type=TFMaskedLMOutput,
703
+ config_class=_CONFIG_FOR_DOC,
704
+ )
705
+ def call(
706
+ self,
707
+ input_ids: TFModelInputType | None = None,
708
+ attention_mask: np.ndarray | tf.Tensor | None = None,
709
+ head_mask: np.ndarray | tf.Tensor | None = None,
710
+ inputs_embeds: np.ndarray | tf.Tensor | None = None,
711
+ output_attentions: Optional[bool] = None,
712
+ output_hidden_states: Optional[bool] = None,
713
+ return_dict: Optional[bool] = None,
714
+ labels: np.ndarray | tf.Tensor | None = None,
715
+ training: Optional[bool] = False,
716
+ ) -> Union[TFMaskedLMOutput, Tuple[tf.Tensor]]:
717
+ r"""
718
+ labels (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
719
+ Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
720
+ config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the
721
+ loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
722
+ """
723
+ distilbert_output = self.distilbert(
724
+ input_ids=input_ids,
725
+ attention_mask=attention_mask,
726
+ head_mask=head_mask,
727
+ inputs_embeds=inputs_embeds,
728
+ output_attentions=output_attentions,
729
+ output_hidden_states=output_hidden_states,
730
+ return_dict=return_dict,
731
+ training=training,
732
+ )
733
+ hidden_states = distilbert_output[0] # (bs, seq_length, dim)
734
+ prediction_logits = self.vocab_transform(hidden_states) # (bs, seq_length, dim)
735
+ prediction_logits = self.act(prediction_logits) # (bs, seq_length, dim)
736
+ prediction_logits = self.vocab_layer_norm(prediction_logits) # (bs, seq_length, dim)
737
+ prediction_logits = self.vocab_projector(prediction_logits)
738
+
739
+ loss = None if labels is None else self.hf_compute_loss(labels, prediction_logits)
740
+
741
+ if not return_dict:
742
+ output = (prediction_logits,) + distilbert_output[1:]
743
+ return ((loss,) + output) if loss is not None else output
744
+
745
+ return TFMaskedLMOutput(
746
+ loss=loss,
747
+ logits=prediction_logits,
748
+ hidden_states=distilbert_output.hidden_states,
749
+ attentions=distilbert_output.attentions,
750
+ )
751
+
752
+ def build(self, input_shape=None):
753
+ if self.built:
754
+ return
755
+ self.built = True
756
+ if getattr(self, "distilbert", None) is not None:
757
+ with tf.name_scope(self.distilbert.name):
758
+ self.distilbert.build(None)
759
+ if getattr(self, "vocab_transform", None) is not None:
760
+ with tf.name_scope(self.vocab_transform.name):
761
+ self.vocab_transform.build([None, None, self.config.dim])
762
+ if getattr(self, "vocab_layer_norm", None) is not None:
763
+ with tf.name_scope(self.vocab_layer_norm.name):
764
+ self.vocab_layer_norm.build([None, None, self.config.dim])
765
+ if getattr(self, "vocab_projector", None) is not None:
766
+ with tf.name_scope(self.vocab_projector.name):
767
+ self.vocab_projector.build(None)
768
+
769
+
770
+ @add_start_docstrings(
771
+ """
772
+ DistilBert Model transformer with a sequence classification/regression head on top (a linear layer on top of the
773
+ pooled output) e.g. for GLUE tasks.
774
+ """,
775
+ DISTILBERT_START_DOCSTRING,
776
+ )
777
+ class TFDistilBertForSequenceClassification(TFDistilBertPreTrainedModel, TFSequenceClassificationLoss):
778
+ def __init__(self, config, *inputs, **kwargs):
779
+ super().__init__(config, *inputs, **kwargs)
780
+ self.num_labels = config.num_labels
781
+
782
+ self.distilbert = TFDistilBertMainLayer(config, name="distilbert")
783
+ self.pre_classifier = keras.layers.Dense(
784
+ config.dim,
785
+ kernel_initializer=get_initializer(config.initializer_range),
786
+ activation="relu",
787
+ name="pre_classifier",
788
+ )
789
+ self.classifier = keras.layers.Dense(
790
+ config.num_labels, kernel_initializer=get_initializer(config.initializer_range), name="classifier"
791
+ )
792
+ self.dropout = keras.layers.Dropout(config.seq_classif_dropout)
793
+ self.config = config
794
+
795
+ @unpack_inputs
796
+ @add_start_docstrings_to_model_forward(DISTILBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
797
+ @add_code_sample_docstrings(
798
+ checkpoint=_CHECKPOINT_FOR_DOC,
799
+ output_type=TFSequenceClassifierOutput,
800
+ config_class=_CONFIG_FOR_DOC,
801
+ )
802
+ def call(
803
+ self,
804
+ input_ids: TFModelInputType | None = None,
805
+ attention_mask: np.ndarray | tf.Tensor | None = None,
806
+ head_mask: np.ndarray | tf.Tensor | None = None,
807
+ inputs_embeds: np.ndarray | tf.Tensor | None = None,
808
+ output_attentions: Optional[bool] = None,
809
+ output_hidden_states: Optional[bool] = None,
810
+ return_dict: Optional[bool] = None,
811
+ labels: np.ndarray | tf.Tensor | None = None,
812
+ training: Optional[bool] = False,
813
+ ) -> Union[TFSequenceClassifierOutput, Tuple[tf.Tensor]]:
814
+ r"""
815
+ labels (`tf.Tensor` of shape `(batch_size,)`, *optional*):
816
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
817
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
818
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
819
+ """
820
+ distilbert_output = self.distilbert(
821
+ input_ids=input_ids,
822
+ attention_mask=attention_mask,
823
+ head_mask=head_mask,
824
+ inputs_embeds=inputs_embeds,
825
+ output_attentions=output_attentions,
826
+ output_hidden_states=output_hidden_states,
827
+ return_dict=return_dict,
828
+ training=training,
829
+ )
830
+ hidden_state = distilbert_output[0] # (bs, seq_len, dim)
831
+ pooled_output = hidden_state[:, 0] # (bs, dim)
832
+ pooled_output = self.pre_classifier(pooled_output) # (bs, dim)
833
+ pooled_output = self.dropout(pooled_output, training=training) # (bs, dim)
834
+ logits = self.classifier(pooled_output) # (bs, dim)
835
+
836
+ loss = None if labels is None else self.hf_compute_loss(labels, logits)
837
+
838
+ if not return_dict:
839
+ output = (logits,) + distilbert_output[1:]
840
+ return ((loss,) + output) if loss is not None else output
841
+
842
+ return TFSequenceClassifierOutput(
843
+ loss=loss,
844
+ logits=logits,
845
+ hidden_states=distilbert_output.hidden_states,
846
+ attentions=distilbert_output.attentions,
847
+ )
848
+
849
+ def build(self, input_shape=None):
850
+ if self.built:
851
+ return
852
+ self.built = True
853
+ if getattr(self, "distilbert", None) is not None:
854
+ with tf.name_scope(self.distilbert.name):
855
+ self.distilbert.build(None)
856
+ if getattr(self, "pre_classifier", None) is not None:
857
+ with tf.name_scope(self.pre_classifier.name):
858
+ self.pre_classifier.build([None, None, self.config.dim])
859
+ if getattr(self, "classifier", None) is not None:
860
+ with tf.name_scope(self.classifier.name):
861
+ self.classifier.build([None, None, self.config.dim])
862
+
863
+
864
+ @add_start_docstrings(
865
+ """
866
+ DistilBert Model with a token classification head on top (a linear layer on top of the hidden-states output) e.g.
867
+ for Named-Entity-Recognition (NER) tasks.
868
+ """,
869
+ DISTILBERT_START_DOCSTRING,
870
+ )
871
+ class TFDistilBertForTokenClassification(TFDistilBertPreTrainedModel, TFTokenClassificationLoss):
872
+ def __init__(self, config, *inputs, **kwargs):
873
+ super().__init__(config, *inputs, **kwargs)
874
+ self.num_labels = config.num_labels
875
+
876
+ self.distilbert = TFDistilBertMainLayer(config, name="distilbert")
877
+ self.dropout = keras.layers.Dropout(config.dropout)
878
+ self.classifier = keras.layers.Dense(
879
+ config.num_labels, kernel_initializer=get_initializer(config.initializer_range), name="classifier"
880
+ )
881
+ self.config = config
882
+
883
+ @unpack_inputs
884
+ @add_start_docstrings_to_model_forward(DISTILBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
885
+ @add_code_sample_docstrings(
886
+ checkpoint=_CHECKPOINT_FOR_DOC,
887
+ output_type=TFTokenClassifierOutput,
888
+ config_class=_CONFIG_FOR_DOC,
889
+ )
890
+ def call(
891
+ self,
892
+ input_ids: TFModelInputType | None = None,
893
+ attention_mask: np.ndarray | tf.Tensor | None = None,
894
+ head_mask: np.ndarray | tf.Tensor | None = None,
895
+ inputs_embeds: np.ndarray | tf.Tensor | None = None,
896
+ output_attentions: Optional[bool] = None,
897
+ output_hidden_states: Optional[bool] = None,
898
+ return_dict: Optional[bool] = None,
899
+ labels: np.ndarray | tf.Tensor | None = None,
900
+ training: Optional[bool] = False,
901
+ ) -> Union[TFTokenClassifierOutput, Tuple[tf.Tensor]]:
902
+ r"""
903
+ labels (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
904
+ Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`.
905
+ """
906
+ outputs = self.distilbert(
907
+ input_ids=input_ids,
908
+ attention_mask=attention_mask,
909
+ head_mask=head_mask,
910
+ inputs_embeds=inputs_embeds,
911
+ output_attentions=output_attentions,
912
+ output_hidden_states=output_hidden_states,
913
+ return_dict=return_dict,
914
+ training=training,
915
+ )
916
+ sequence_output = outputs[0]
917
+ sequence_output = self.dropout(sequence_output, training=training)
918
+ logits = self.classifier(sequence_output)
919
+ loss = None if labels is None else self.hf_compute_loss(labels, logits)
920
+
921
+ if not return_dict:
922
+ output = (logits,) + outputs[1:]
923
+ return ((loss,) + output) if loss is not None else output
924
+
925
+ return TFTokenClassifierOutput(
926
+ loss=loss,
927
+ logits=logits,
928
+ hidden_states=outputs.hidden_states,
929
+ attentions=outputs.attentions,
930
+ )
931
+
932
+ def build(self, input_shape=None):
933
+ if self.built:
934
+ return
935
+ self.built = True
936
+ if getattr(self, "distilbert", None) is not None:
937
+ with tf.name_scope(self.distilbert.name):
938
+ self.distilbert.build(None)
939
+ if getattr(self, "classifier", None) is not None:
940
+ with tf.name_scope(self.classifier.name):
941
+ self.classifier.build([None, None, self.config.hidden_size])
942
+
943
+
944
+ @add_start_docstrings(
945
+ """
946
+ DistilBert Model with a multiple choice classification head on top (a linear layer on top of the pooled output and
947
+ a softmax) e.g. for RocStories/SWAG tasks.
948
+ """,
949
+ DISTILBERT_START_DOCSTRING,
950
+ )
951
+ class TFDistilBertForMultipleChoice(TFDistilBertPreTrainedModel, TFMultipleChoiceLoss):
952
+ def __init__(self, config, *inputs, **kwargs):
953
+ super().__init__(config, *inputs, **kwargs)
954
+
955
+ self.distilbert = TFDistilBertMainLayer(config, name="distilbert")
956
+ self.dropout = keras.layers.Dropout(config.seq_classif_dropout)
957
+ self.pre_classifier = keras.layers.Dense(
958
+ config.dim,
959
+ kernel_initializer=get_initializer(config.initializer_range),
960
+ activation="relu",
961
+ name="pre_classifier",
962
+ )
963
+ self.classifier = keras.layers.Dense(
964
+ 1, kernel_initializer=get_initializer(config.initializer_range), name="classifier"
965
+ )
966
+ self.config = config
967
+
968
+ @unpack_inputs
969
+ @add_start_docstrings_to_model_forward(
970
+ DISTILBERT_INPUTS_DOCSTRING.format("batch_size, num_choices, sequence_length")
971
+ )
972
+ @add_code_sample_docstrings(
973
+ checkpoint=_CHECKPOINT_FOR_DOC,
974
+ output_type=TFMultipleChoiceModelOutput,
975
+ config_class=_CONFIG_FOR_DOC,
976
+ )
977
+ def call(
978
+ self,
979
+ input_ids: TFModelInputType | None = None,
980
+ attention_mask: np.ndarray | tf.Tensor | None = None,
981
+ head_mask: np.ndarray | tf.Tensor | None = None,
982
+ inputs_embeds: np.ndarray | tf.Tensor | None = None,
983
+ output_attentions: Optional[bool] = None,
984
+ output_hidden_states: Optional[bool] = None,
985
+ return_dict: Optional[bool] = None,
986
+ labels: np.ndarray | tf.Tensor | None = None,
987
+ training: Optional[bool] = False,
988
+ ) -> Union[TFMultipleChoiceModelOutput, Tuple[tf.Tensor]]:
989
+ r"""
990
+ labels (`tf.Tensor` of shape `(batch_size,)`, *optional*):
991
+ Labels for computing the multiple choice classification loss. Indices should be in `[0, ..., num_choices]`
992
+ where `num_choices` is the size of the second dimension of the input tensors. (See `input_ids` above)
993
+ """
994
+ if input_ids is not None:
995
+ num_choices = shape_list(input_ids)[1]
996
+ seq_length = shape_list(input_ids)[2]
997
+ else:
998
+ num_choices = shape_list(inputs_embeds)[1]
999
+ seq_length = shape_list(inputs_embeds)[2]
1000
+
1001
+ flat_input_ids = tf.reshape(input_ids, (-1, seq_length)) if input_ids is not None else None
1002
+ flat_attention_mask = tf.reshape(attention_mask, (-1, seq_length)) if attention_mask is not None else None
1003
+ flat_inputs_embeds = (
1004
+ tf.reshape(inputs_embeds, (-1, seq_length, shape_list(inputs_embeds)[3]))
1005
+ if inputs_embeds is not None
1006
+ else None
1007
+ )
1008
+ distilbert_output = self.distilbert(
1009
+ flat_input_ids,
1010
+ flat_attention_mask,
1011
+ head_mask,
1012
+ flat_inputs_embeds,
1013
+ output_attentions,
1014
+ output_hidden_states,
1015
+ return_dict=return_dict,
1016
+ training=training,
1017
+ )
1018
+ hidden_state = distilbert_output[0] # (bs, seq_len, dim)
1019
+ pooled_output = hidden_state[:, 0] # (bs, dim)
1020
+ pooled_output = self.pre_classifier(pooled_output) # (bs, dim)
1021
+ pooled_output = self.dropout(pooled_output, training=training) # (bs, dim)
1022
+ logits = self.classifier(pooled_output)
1023
+ reshaped_logits = tf.reshape(logits, (-1, num_choices))
1024
+
1025
+ loss = None if labels is None else self.hf_compute_loss(labels, reshaped_logits)
1026
+
1027
+ if not return_dict:
1028
+ output = (reshaped_logits,) + distilbert_output[1:]
1029
+ return ((loss,) + output) if loss is not None else output
1030
+
1031
+ return TFMultipleChoiceModelOutput(
1032
+ loss=loss,
1033
+ logits=reshaped_logits,
1034
+ hidden_states=distilbert_output.hidden_states,
1035
+ attentions=distilbert_output.attentions,
1036
+ )
1037
+
1038
+ def build(self, input_shape=None):
1039
+ if self.built:
1040
+ return
1041
+ self.built = True
1042
+ if getattr(self, "distilbert", None) is not None:
1043
+ with tf.name_scope(self.distilbert.name):
1044
+ self.distilbert.build(None)
1045
+ if getattr(self, "pre_classifier", None) is not None:
1046
+ with tf.name_scope(self.pre_classifier.name):
1047
+ self.pre_classifier.build([None, None, self.config.dim])
1048
+ if getattr(self, "classifier", None) is not None:
1049
+ with tf.name_scope(self.classifier.name):
1050
+ self.classifier.build([None, None, self.config.dim])
1051
+
1052
+
1053
+ @add_start_docstrings(
1054
+ """
1055
+ DistilBert Model with a span classification head on top for extractive question-answering tasks like SQuAD (a
1056
+ linear layer on top of the hidden-states output to compute `span start logits` and `span end logits`).
1057
+ """,
1058
+ DISTILBERT_START_DOCSTRING,
1059
+ )
1060
+ class TFDistilBertForQuestionAnswering(TFDistilBertPreTrainedModel, TFQuestionAnsweringLoss):
1061
+ def __init__(self, config, *inputs, **kwargs):
1062
+ super().__init__(config, *inputs, **kwargs)
1063
+
1064
+ self.distilbert = TFDistilBertMainLayer(config, name="distilbert")
1065
+ self.qa_outputs = keras.layers.Dense(
1066
+ config.num_labels, kernel_initializer=get_initializer(config.initializer_range), name="qa_outputs"
1067
+ )
1068
+ assert config.num_labels == 2, f"Incorrect number of labels {config.num_labels} instead of 2"
1069
+ self.dropout = keras.layers.Dropout(config.qa_dropout)
1070
+ self.config = config
1071
+
1072
+ @unpack_inputs
1073
+ @add_start_docstrings_to_model_forward(DISTILBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
1074
+ @add_code_sample_docstrings(
1075
+ checkpoint=_CHECKPOINT_FOR_DOC,
1076
+ output_type=TFQuestionAnsweringModelOutput,
1077
+ config_class=_CONFIG_FOR_DOC,
1078
+ )
1079
+ def call(
1080
+ self,
1081
+ input_ids: TFModelInputType | None = None,
1082
+ attention_mask: np.ndarray | tf.Tensor | None = None,
1083
+ head_mask: np.ndarray | tf.Tensor | None = None,
1084
+ inputs_embeds: np.ndarray | tf.Tensor | None = None,
1085
+ output_attentions: Optional[bool] = None,
1086
+ output_hidden_states: Optional[bool] = None,
1087
+ return_dict: Optional[bool] = None,
1088
+ start_positions: np.ndarray | tf.Tensor | None = None,
1089
+ end_positions: np.ndarray | tf.Tensor | None = None,
1090
+ training: Optional[bool] = False,
1091
+ ) -> Union[TFQuestionAnsweringModelOutput, Tuple[tf.Tensor]]:
1092
+ r"""
1093
+ start_positions (`tf.Tensor` of shape `(batch_size,)`, *optional*):
1094
+ Labels for position (index) of the start of the labelled span for computing the token classification loss.
1095
+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
1096
+ are not taken into account for computing the loss.
1097
+ end_positions (`tf.Tensor` of shape `(batch_size,)`, *optional*):
1098
+ Labels for position (index) of the end of the labelled span for computing the token classification loss.
1099
+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
1100
+ are not taken into account for computing the loss.
1101
+ """
1102
+ distilbert_output = self.distilbert(
1103
+ input_ids=input_ids,
1104
+ attention_mask=attention_mask,
1105
+ head_mask=head_mask,
1106
+ inputs_embeds=inputs_embeds,
1107
+ output_attentions=output_attentions,
1108
+ output_hidden_states=output_hidden_states,
1109
+ return_dict=return_dict,
1110
+ training=training,
1111
+ )
1112
+ hidden_states = distilbert_output[0] # (bs, max_query_len, dim)
1113
+ hidden_states = self.dropout(hidden_states, training=training) # (bs, max_query_len, dim)
1114
+ logits = self.qa_outputs(hidden_states) # (bs, max_query_len, 2)
1115
+ start_logits, end_logits = tf.split(logits, 2, axis=-1)
1116
+ start_logits = tf.squeeze(start_logits, axis=-1)
1117
+ end_logits = tf.squeeze(end_logits, axis=-1)
1118
+
1119
+ loss = None
1120
+ if start_positions is not None and end_positions is not None:
1121
+ labels = {"start_position": start_positions}
1122
+ labels["end_position"] = end_positions
1123
+ loss = self.hf_compute_loss(labels, (start_logits, end_logits))
1124
+
1125
+ if not return_dict:
1126
+ output = (start_logits, end_logits) + distilbert_output[1:]
1127
+ return ((loss,) + output) if loss is not None else output
1128
+
1129
+ return TFQuestionAnsweringModelOutput(
1130
+ loss=loss,
1131
+ start_logits=start_logits,
1132
+ end_logits=end_logits,
1133
+ hidden_states=distilbert_output.hidden_states,
1134
+ attentions=distilbert_output.attentions,
1135
+ )
1136
+
1137
+ def build(self, input_shape=None):
1138
+ if self.built:
1139
+ return
1140
+ self.built = True
1141
+ if getattr(self, "distilbert", None) is not None:
1142
+ with tf.name_scope(self.distilbert.name):
1143
+ self.distilbert.build(None)
1144
+ if getattr(self, "qa_outputs", None) is not None:
1145
+ with tf.name_scope(self.qa_outputs.name):
1146
+ self.qa_outputs.build([None, None, self.config.dim])
env-llmeval/lib/python3.10/site-packages/transformers/models/distilbert/tokenization_distilbert.py ADDED
@@ -0,0 +1,553 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2018 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 DistilBERT."""
16
+
17
+ import collections
18
+ import os
19
+ import unicodedata
20
+ from typing import List, Optional, Tuple
21
+
22
+ from ...tokenization_utils import PreTrainedTokenizer, _is_control, _is_punctuation, _is_whitespace
23
+ from ...utils import logging
24
+
25
+
26
+ logger = logging.get_logger(__name__)
27
+
28
+ VOCAB_FILES_NAMES = {"vocab_file": "vocab.txt"}
29
+
30
+ PRETRAINED_VOCAB_FILES_MAP = {
31
+ "vocab_file": {
32
+ "distilbert-base-uncased": "https://huggingface.co/distilbert-base-uncased/resolve/main/vocab.txt",
33
+ "distilbert-base-uncased-distilled-squad": (
34
+ "https://huggingface.co/distilbert-base-uncased-distilled-squad/resolve/main/vocab.txt"
35
+ ),
36
+ "distilbert-base-cased": "https://huggingface.co/distilbert-base-cased/resolve/main/vocab.txt",
37
+ "distilbert-base-cased-distilled-squad": (
38
+ "https://huggingface.co/distilbert-base-cased-distilled-squad/resolve/main/vocab.txt"
39
+ ),
40
+ "distilbert-base-german-cased": "https://huggingface.co/distilbert-base-german-cased/resolve/main/vocab.txt",
41
+ "distilbert-base-multilingual-cased": (
42
+ "https://huggingface.co/distilbert-base-multilingual-cased/resolve/main/vocab.txt"
43
+ ),
44
+ }
45
+ }
46
+
47
+ PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES = {
48
+ "distilbert-base-uncased": 512,
49
+ "distilbert-base-uncased-distilled-squad": 512,
50
+ "distilbert-base-cased": 512,
51
+ "distilbert-base-cased-distilled-squad": 512,
52
+ "distilbert-base-german-cased": 512,
53
+ "distilbert-base-multilingual-cased": 512,
54
+ }
55
+
56
+
57
+ PRETRAINED_INIT_CONFIGURATION = {
58
+ "distilbert-base-uncased": {"do_lower_case": True},
59
+ "distilbert-base-uncased-distilled-squad": {"do_lower_case": True},
60
+ "distilbert-base-cased": {"do_lower_case": False},
61
+ "distilbert-base-cased-distilled-squad": {"do_lower_case": False},
62
+ "distilbert-base-german-cased": {"do_lower_case": False},
63
+ "distilbert-base-multilingual-cased": {"do_lower_case": False},
64
+ }
65
+
66
+
67
+ # Copied from transformers.models.bert.tokenization_bert.load_vocab
68
+ def load_vocab(vocab_file):
69
+ """Loads a vocabulary file into a dictionary."""
70
+ vocab = collections.OrderedDict()
71
+ with open(vocab_file, "r", encoding="utf-8") as reader:
72
+ tokens = reader.readlines()
73
+ for index, token in enumerate(tokens):
74
+ token = token.rstrip("\n")
75
+ vocab[token] = index
76
+ return vocab
77
+
78
+
79
+ # Copied from transformers.models.bert.tokenization_bert.whitespace_tokenize
80
+ def whitespace_tokenize(text):
81
+ """Runs basic whitespace cleaning and splitting on a piece of text."""
82
+ text = text.strip()
83
+ if not text:
84
+ return []
85
+ tokens = text.split()
86
+ return tokens
87
+
88
+
89
+ class DistilBertTokenizer(PreTrainedTokenizer):
90
+ r"""
91
+ Construct a DistilBERT tokenizer. Based on WordPiece.
92
+
93
+ This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to
94
+ this superclass for more information regarding those methods.
95
+
96
+ Args:
97
+ vocab_file (`str`):
98
+ File containing the vocabulary.
99
+ do_lower_case (`bool`, *optional*, defaults to `True`):
100
+ Whether or not to lowercase the input when tokenizing.
101
+ do_basic_tokenize (`bool`, *optional*, defaults to `True`):
102
+ Whether or not to do basic tokenization before WordPiece.
103
+ never_split (`Iterable`, *optional*):
104
+ Collection of tokens which will never be split during tokenization. Only has an effect when
105
+ `do_basic_tokenize=True`
106
+ unk_token (`str`, *optional*, defaults to `"[UNK]"`):
107
+ The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
108
+ token instead.
109
+ sep_token (`str`, *optional*, defaults to `"[SEP]"`):
110
+ The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
111
+ sequence classification or for a text and a question for question answering. It is also used as the last
112
+ token of a sequence built with special tokens.
113
+ pad_token (`str`, *optional*, defaults to `"[PAD]"`):
114
+ The token used for padding, for example when batching sequences of different lengths.
115
+ cls_token (`str`, *optional*, defaults to `"[CLS]"`):
116
+ The classifier token which is used when doing sequence classification (classification of the whole sequence
117
+ instead of per-token classification). It is the first token of the sequence when built with special tokens.
118
+ mask_token (`str`, *optional*, defaults to `"[MASK]"`):
119
+ The token used for masking values. This is the token used when training this model with masked language
120
+ modeling. This is the token which the model will try to predict.
121
+ tokenize_chinese_chars (`bool`, *optional*, defaults to `True`):
122
+ Whether or not to tokenize Chinese characters.
123
+
124
+ This should likely be deactivated for Japanese (see this
125
+ [issue](https://github.com/huggingface/transformers/issues/328)).
126
+ strip_accents (`bool`, *optional*):
127
+ Whether or not to strip all accents. If this option is not specified, then it will be determined by the
128
+ value for `lowercase` (as in the original BERT).
129
+ """
130
+
131
+ vocab_files_names = VOCAB_FILES_NAMES
132
+ pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP
133
+ pretrained_init_configuration = PRETRAINED_INIT_CONFIGURATION
134
+ max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
135
+ model_input_names = ["input_ids", "attention_mask"]
136
+
137
+ def __init__(
138
+ self,
139
+ vocab_file,
140
+ do_lower_case=True,
141
+ do_basic_tokenize=True,
142
+ never_split=None,
143
+ unk_token="[UNK]",
144
+ sep_token="[SEP]",
145
+ pad_token="[PAD]",
146
+ cls_token="[CLS]",
147
+ mask_token="[MASK]",
148
+ tokenize_chinese_chars=True,
149
+ strip_accents=None,
150
+ **kwargs,
151
+ ):
152
+ if not os.path.isfile(vocab_file):
153
+ raise ValueError(
154
+ f"Can't find a vocabulary file at path '{vocab_file}'. To load the vocabulary from a Google pretrained"
155
+ " model use `tokenizer = DistilBertTokenizer.from_pretrained(PRETRAINED_MODEL_NAME)`"
156
+ )
157
+ self.vocab = load_vocab(vocab_file)
158
+ self.ids_to_tokens = collections.OrderedDict([(ids, tok) for tok, ids in self.vocab.items()])
159
+ self.do_basic_tokenize = do_basic_tokenize
160
+ if do_basic_tokenize:
161
+ self.basic_tokenizer = BasicTokenizer(
162
+ do_lower_case=do_lower_case,
163
+ never_split=never_split,
164
+ tokenize_chinese_chars=tokenize_chinese_chars,
165
+ strip_accents=strip_accents,
166
+ )
167
+ self.wordpiece_tokenizer = WordpieceTokenizer(vocab=self.vocab, unk_token=str(unk_token))
168
+
169
+ super().__init__(
170
+ do_lower_case=do_lower_case,
171
+ do_basic_tokenize=do_basic_tokenize,
172
+ never_split=never_split,
173
+ unk_token=unk_token,
174
+ sep_token=sep_token,
175
+ pad_token=pad_token,
176
+ cls_token=cls_token,
177
+ mask_token=mask_token,
178
+ tokenize_chinese_chars=tokenize_chinese_chars,
179
+ strip_accents=strip_accents,
180
+ **kwargs,
181
+ )
182
+
183
+ @property
184
+ # Copied from transformers.models.bert.tokenization_bert.BertTokenizer.do_lower_case
185
+ def do_lower_case(self):
186
+ return self.basic_tokenizer.do_lower_case
187
+
188
+ @property
189
+ # Copied from transformers.models.bert.tokenization_bert.BertTokenizer.vocab_size
190
+ def vocab_size(self):
191
+ return len(self.vocab)
192
+
193
+ # Copied from transformers.models.bert.tokenization_bert.BertTokenizer.get_vocab
194
+ def get_vocab(self):
195
+ return dict(self.vocab, **self.added_tokens_encoder)
196
+
197
+ # Copied from transformers.models.bert.tokenization_bert.BertTokenizer._tokenize
198
+ def _tokenize(self, text, split_special_tokens=False):
199
+ split_tokens = []
200
+ if self.do_basic_tokenize:
201
+ for token in self.basic_tokenizer.tokenize(
202
+ text, never_split=self.all_special_tokens if not split_special_tokens else None
203
+ ):
204
+ # If the token is part of the never_split set
205
+ if token in self.basic_tokenizer.never_split:
206
+ split_tokens.append(token)
207
+ else:
208
+ split_tokens += self.wordpiece_tokenizer.tokenize(token)
209
+ else:
210
+ split_tokens = self.wordpiece_tokenizer.tokenize(text)
211
+ return split_tokens
212
+
213
+ # Copied from transformers.models.bert.tokenization_bert.BertTokenizer._convert_token_to_id
214
+ def _convert_token_to_id(self, token):
215
+ """Converts a token (str) in an id using the vocab."""
216
+ return self.vocab.get(token, self.vocab.get(self.unk_token))
217
+
218
+ # Copied from transformers.models.bert.tokenization_bert.BertTokenizer._convert_id_to_token
219
+ def _convert_id_to_token(self, index):
220
+ """Converts an index (integer) in a token (str) using the vocab."""
221
+ return self.ids_to_tokens.get(index, self.unk_token)
222
+
223
+ # Copied from transformers.models.bert.tokenization_bert.BertTokenizer.convert_tokens_to_string
224
+ def convert_tokens_to_string(self, tokens):
225
+ """Converts a sequence of tokens (string) in a single string."""
226
+ out_string = " ".join(tokens).replace(" ##", "").strip()
227
+ return out_string
228
+
229
+ # Copied from transformers.models.bert.tokenization_bert.BertTokenizer.build_inputs_with_special_tokens
230
+ def build_inputs_with_special_tokens(
231
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
232
+ ) -> List[int]:
233
+ """
234
+ Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
235
+ adding special tokens. A BERT sequence has the following format:
236
+
237
+ - single sequence: `[CLS] X [SEP]`
238
+ - pair of sequences: `[CLS] A [SEP] B [SEP]`
239
+
240
+ Args:
241
+ token_ids_0 (`List[int]`):
242
+ List of IDs to which the special tokens will be added.
243
+ token_ids_1 (`List[int]`, *optional*):
244
+ Optional second list of IDs for sequence pairs.
245
+
246
+ Returns:
247
+ `List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
248
+ """
249
+ if token_ids_1 is None:
250
+ return [self.cls_token_id] + token_ids_0 + [self.sep_token_id]
251
+ cls = [self.cls_token_id]
252
+ sep = [self.sep_token_id]
253
+ return cls + token_ids_0 + sep + token_ids_1 + sep
254
+
255
+ # Copied from transformers.models.bert.tokenization_bert.BertTokenizer.get_special_tokens_mask
256
+ def get_special_tokens_mask(
257
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None, already_has_special_tokens: bool = False
258
+ ) -> List[int]:
259
+ """
260
+ Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
261
+ special tokens using the tokenizer `prepare_for_model` method.
262
+
263
+ Args:
264
+ token_ids_0 (`List[int]`):
265
+ List of IDs.
266
+ token_ids_1 (`List[int]`, *optional*):
267
+ Optional second list of IDs for sequence pairs.
268
+ already_has_special_tokens (`bool`, *optional*, defaults to `False`):
269
+ Whether or not the token list is already formatted with special tokens for the model.
270
+
271
+ Returns:
272
+ `List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
273
+ """
274
+
275
+ if already_has_special_tokens:
276
+ return super().get_special_tokens_mask(
277
+ token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
278
+ )
279
+
280
+ if token_ids_1 is not None:
281
+ return [1] + ([0] * len(token_ids_0)) + [1] + ([0] * len(token_ids_1)) + [1]
282
+ return [1] + ([0] * len(token_ids_0)) + [1]
283
+
284
+ # Copied from transformers.models.bert.tokenization_bert.BertTokenizer.create_token_type_ids_from_sequences
285
+ def create_token_type_ids_from_sequences(
286
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
287
+ ) -> List[int]:
288
+ """
289
+ Create a mask from the two sequences passed to be used in a sequence-pair classification task. A BERT sequence
290
+ pair mask has the following format:
291
+
292
+ ```
293
+ 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1
294
+ | first sequence | second sequence |
295
+ ```
296
+
297
+ If `token_ids_1` is `None`, this method only returns the first portion of the mask (0s).
298
+
299
+ Args:
300
+ token_ids_0 (`List[int]`):
301
+ List of IDs.
302
+ token_ids_1 (`List[int]`, *optional*):
303
+ Optional second list of IDs for sequence pairs.
304
+
305
+ Returns:
306
+ `List[int]`: List of [token type IDs](../glossary#token-type-ids) according to the given sequence(s).
307
+ """
308
+ sep = [self.sep_token_id]
309
+ cls = [self.cls_token_id]
310
+ if token_ids_1 is None:
311
+ return len(cls + token_ids_0 + sep) * [0]
312
+ return len(cls + token_ids_0 + sep) * [0] + len(token_ids_1 + sep) * [1]
313
+
314
+ # Copied from transformers.models.bert.tokenization_bert.BertTokenizer.save_vocabulary
315
+ def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
316
+ index = 0
317
+ if os.path.isdir(save_directory):
318
+ vocab_file = os.path.join(
319
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
320
+ )
321
+ else:
322
+ vocab_file = (filename_prefix + "-" if filename_prefix else "") + save_directory
323
+ with open(vocab_file, "w", encoding="utf-8") as writer:
324
+ for token, token_index in sorted(self.vocab.items(), key=lambda kv: kv[1]):
325
+ if index != token_index:
326
+ logger.warning(
327
+ f"Saving vocabulary to {vocab_file}: vocabulary indices are not consecutive."
328
+ " Please check that the vocabulary is not corrupted!"
329
+ )
330
+ index = token_index
331
+ writer.write(token + "\n")
332
+ index += 1
333
+ return (vocab_file,)
334
+
335
+
336
+ # Copied from transformers.models.bert.tokenization_bert.BasicTokenizer
337
+ class BasicTokenizer(object):
338
+ """
339
+ Constructs a BasicTokenizer that will run basic tokenization (punctuation splitting, lower casing, etc.).
340
+
341
+ Args:
342
+ do_lower_case (`bool`, *optional*, defaults to `True`):
343
+ Whether or not to lowercase the input when tokenizing.
344
+ never_split (`Iterable`, *optional*):
345
+ Collection of tokens which will never be split during tokenization. Only has an effect when
346
+ `do_basic_tokenize=True`
347
+ tokenize_chinese_chars (`bool`, *optional*, defaults to `True`):
348
+ Whether or not to tokenize Chinese characters.
349
+
350
+ This should likely be deactivated for Japanese (see this
351
+ [issue](https://github.com/huggingface/transformers/issues/328)).
352
+ strip_accents (`bool`, *optional*):
353
+ Whether or not to strip all accents. If this option is not specified, then it will be determined by the
354
+ value for `lowercase` (as in the original BERT).
355
+ do_split_on_punc (`bool`, *optional*, defaults to `True`):
356
+ In some instances we want to skip the basic punctuation splitting so that later tokenization can capture
357
+ the full context of the words, such as contractions.
358
+ """
359
+
360
+ def __init__(
361
+ self,
362
+ do_lower_case=True,
363
+ never_split=None,
364
+ tokenize_chinese_chars=True,
365
+ strip_accents=None,
366
+ do_split_on_punc=True,
367
+ ):
368
+ if never_split is None:
369
+ never_split = []
370
+ self.do_lower_case = do_lower_case
371
+ self.never_split = set(never_split)
372
+ self.tokenize_chinese_chars = tokenize_chinese_chars
373
+ self.strip_accents = strip_accents
374
+ self.do_split_on_punc = do_split_on_punc
375
+
376
+ def tokenize(self, text, never_split=None):
377
+ """
378
+ Basic Tokenization of a piece of text. For sub-word tokenization, see WordPieceTokenizer.
379
+
380
+ Args:
381
+ never_split (`List[str]`, *optional*)
382
+ Kept for backward compatibility purposes. Now implemented directly at the base class level (see
383
+ [`PreTrainedTokenizer.tokenize`]) List of token not to split.
384
+ """
385
+ # union() returns a new set by concatenating the two sets.
386
+ never_split = self.never_split.union(set(never_split)) if never_split else self.never_split
387
+ text = self._clean_text(text)
388
+
389
+ # This was added on November 1st, 2018 for the multilingual and Chinese
390
+ # models. This is also applied to the English models now, but it doesn't
391
+ # matter since the English models were not trained on any Chinese data
392
+ # and generally don't have any Chinese data in them (there are Chinese
393
+ # characters in the vocabulary because Wikipedia does have some Chinese
394
+ # words in the English Wikipedia.).
395
+ if self.tokenize_chinese_chars:
396
+ text = self._tokenize_chinese_chars(text)
397
+ # prevents treating the same character with different unicode codepoints as different characters
398
+ unicode_normalized_text = unicodedata.normalize("NFC", text)
399
+ orig_tokens = whitespace_tokenize(unicode_normalized_text)
400
+ split_tokens = []
401
+ for token in orig_tokens:
402
+ if token not in never_split:
403
+ if self.do_lower_case:
404
+ token = token.lower()
405
+ if self.strip_accents is not False:
406
+ token = self._run_strip_accents(token)
407
+ elif self.strip_accents:
408
+ token = self._run_strip_accents(token)
409
+ split_tokens.extend(self._run_split_on_punc(token, never_split))
410
+
411
+ output_tokens = whitespace_tokenize(" ".join(split_tokens))
412
+ return output_tokens
413
+
414
+ def _run_strip_accents(self, text):
415
+ """Strips accents from a piece of text."""
416
+ text = unicodedata.normalize("NFD", text)
417
+ output = []
418
+ for char in text:
419
+ cat = unicodedata.category(char)
420
+ if cat == "Mn":
421
+ continue
422
+ output.append(char)
423
+ return "".join(output)
424
+
425
+ def _run_split_on_punc(self, text, never_split=None):
426
+ """Splits punctuation on a piece of text."""
427
+ if not self.do_split_on_punc or (never_split is not None and text in never_split):
428
+ return [text]
429
+ chars = list(text)
430
+ i = 0
431
+ start_new_word = True
432
+ output = []
433
+ while i < len(chars):
434
+ char = chars[i]
435
+ if _is_punctuation(char):
436
+ output.append([char])
437
+ start_new_word = True
438
+ else:
439
+ if start_new_word:
440
+ output.append([])
441
+ start_new_word = False
442
+ output[-1].append(char)
443
+ i += 1
444
+
445
+ return ["".join(x) for x in output]
446
+
447
+ def _tokenize_chinese_chars(self, text):
448
+ """Adds whitespace around any CJK character."""
449
+ output = []
450
+ for char in text:
451
+ cp = ord(char)
452
+ if self._is_chinese_char(cp):
453
+ output.append(" ")
454
+ output.append(char)
455
+ output.append(" ")
456
+ else:
457
+ output.append(char)
458
+ return "".join(output)
459
+
460
+ def _is_chinese_char(self, cp):
461
+ """Checks whether CP is the codepoint of a CJK character."""
462
+ # This defines a "chinese character" as anything in the CJK Unicode block:
463
+ # https://en.wikipedia.org/wiki/CJK_Unified_Ideographs_(Unicode_block)
464
+ #
465
+ # Note that the CJK Unicode block is NOT all Japanese and Korean characters,
466
+ # despite its name. The modern Korean Hangul alphabet is a different block,
467
+ # as is Japanese Hiragana and Katakana. Those alphabets are used to write
468
+ # space-separated words, so they are not treated specially and handled
469
+ # like the all of the other languages.
470
+ if (
471
+ (cp >= 0x4E00 and cp <= 0x9FFF)
472
+ or (cp >= 0x3400 and cp <= 0x4DBF) #
473
+ or (cp >= 0x20000 and cp <= 0x2A6DF) #
474
+ or (cp >= 0x2A700 and cp <= 0x2B73F) #
475
+ or (cp >= 0x2B740 and cp <= 0x2B81F) #
476
+ or (cp >= 0x2B820 and cp <= 0x2CEAF) #
477
+ or (cp >= 0xF900 and cp <= 0xFAFF)
478
+ or (cp >= 0x2F800 and cp <= 0x2FA1F) #
479
+ ): #
480
+ return True
481
+
482
+ return False
483
+
484
+ def _clean_text(self, text):
485
+ """Performs invalid character removal and whitespace cleanup on text."""
486
+ output = []
487
+ for char in text:
488
+ cp = ord(char)
489
+ if cp == 0 or cp == 0xFFFD or _is_control(char):
490
+ continue
491
+ if _is_whitespace(char):
492
+ output.append(" ")
493
+ else:
494
+ output.append(char)
495
+ return "".join(output)
496
+
497
+
498
+ # Copied from transformers.models.bert.tokenization_bert.WordpieceTokenizer
499
+ class WordpieceTokenizer(object):
500
+ """Runs WordPiece tokenization."""
501
+
502
+ def __init__(self, vocab, unk_token, max_input_chars_per_word=100):
503
+ self.vocab = vocab
504
+ self.unk_token = unk_token
505
+ self.max_input_chars_per_word = max_input_chars_per_word
506
+
507
+ def tokenize(self, text):
508
+ """
509
+ Tokenizes a piece of text into its word pieces. This uses a greedy longest-match-first algorithm to perform
510
+ tokenization using the given vocabulary.
511
+
512
+ For example, `input = "unaffable"` wil return as output `["un", "##aff", "##able"]`.
513
+
514
+ Args:
515
+ text: A single token or whitespace separated tokens. This should have
516
+ already been passed through *BasicTokenizer*.
517
+
518
+ Returns:
519
+ A list of wordpiece tokens.
520
+ """
521
+
522
+ output_tokens = []
523
+ for token in whitespace_tokenize(text):
524
+ chars = list(token)
525
+ if len(chars) > self.max_input_chars_per_word:
526
+ output_tokens.append(self.unk_token)
527
+ continue
528
+
529
+ is_bad = False
530
+ start = 0
531
+ sub_tokens = []
532
+ while start < len(chars):
533
+ end = len(chars)
534
+ cur_substr = None
535
+ while start < end:
536
+ substr = "".join(chars[start:end])
537
+ if start > 0:
538
+ substr = "##" + substr
539
+ if substr in self.vocab:
540
+ cur_substr = substr
541
+ break
542
+ end -= 1
543
+ if cur_substr is None:
544
+ is_bad = True
545
+ break
546
+ sub_tokens.append(cur_substr)
547
+ start = end
548
+
549
+ if is_bad:
550
+ output_tokens.append(self.unk_token)
551
+ else:
552
+ output_tokens.extend(sub_tokens)
553
+ return output_tokens
env-llmeval/lib/python3.10/site-packages/transformers/models/distilbert/tokenization_distilbert_fast.py ADDED
@@ -0,0 +1,231 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2018 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 DistilBERT."""
16
+
17
+ import json
18
+ from typing import List, Optional, Tuple
19
+
20
+ from tokenizers import normalizers
21
+
22
+ from ...tokenization_utils_fast import PreTrainedTokenizerFast
23
+ from ...utils import logging
24
+ from .tokenization_distilbert import DistilBertTokenizer
25
+
26
+
27
+ logger = logging.get_logger(__name__)
28
+
29
+ VOCAB_FILES_NAMES = {"vocab_file": "vocab.txt", "tokenizer_file": "tokenizer.json"}
30
+
31
+ PRETRAINED_VOCAB_FILES_MAP = {
32
+ "vocab_file": {
33
+ "distilbert-base-uncased": "https://huggingface.co/distilbert-base-uncased/resolve/main/vocab.txt",
34
+ "distilbert-base-uncased-distilled-squad": (
35
+ "https://huggingface.co/distilbert-base-uncased-distilled-squad/resolve/main/vocab.txt"
36
+ ),
37
+ "distilbert-base-cased": "https://huggingface.co/distilbert-base-cased/resolve/main/vocab.txt",
38
+ "distilbert-base-cased-distilled-squad": (
39
+ "https://huggingface.co/distilbert-base-cased-distilled-squad/resolve/main/vocab.txt"
40
+ ),
41
+ "distilbert-base-german-cased": "https://huggingface.co/distilbert-base-german-cased/resolve/main/vocab.txt",
42
+ "distilbert-base-multilingual-cased": (
43
+ "https://huggingface.co/distilbert-base-multilingual-cased/resolve/main/vocab.txt"
44
+ ),
45
+ },
46
+ "tokenizer_file": {
47
+ "distilbert-base-uncased": "https://huggingface.co/distilbert-base-uncased/resolve/main/tokenizer.json",
48
+ "distilbert-base-uncased-distilled-squad": (
49
+ "https://huggingface.co/distilbert-base-uncased-distilled-squad/resolve/main/tokenizer.json"
50
+ ),
51
+ "distilbert-base-cased": "https://huggingface.co/distilbert-base-cased/resolve/main/tokenizer.json",
52
+ "distilbert-base-cased-distilled-squad": (
53
+ "https://huggingface.co/distilbert-base-cased-distilled-squad/resolve/main/tokenizer.json"
54
+ ),
55
+ "distilbert-base-german-cased": (
56
+ "https://huggingface.co/distilbert-base-german-cased/resolve/main/tokenizer.json"
57
+ ),
58
+ "distilbert-base-multilingual-cased": (
59
+ "https://huggingface.co/distilbert-base-multilingual-cased/resolve/main/tokenizer.json"
60
+ ),
61
+ },
62
+ }
63
+
64
+ PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES = {
65
+ "distilbert-base-uncased": 512,
66
+ "distilbert-base-uncased-distilled-squad": 512,
67
+ "distilbert-base-cased": 512,
68
+ "distilbert-base-cased-distilled-squad": 512,
69
+ "distilbert-base-german-cased": 512,
70
+ "distilbert-base-multilingual-cased": 512,
71
+ }
72
+
73
+
74
+ PRETRAINED_INIT_CONFIGURATION = {
75
+ "distilbert-base-uncased": {"do_lower_case": True},
76
+ "distilbert-base-uncased-distilled-squad": {"do_lower_case": True},
77
+ "distilbert-base-cased": {"do_lower_case": False},
78
+ "distilbert-base-cased-distilled-squad": {"do_lower_case": False},
79
+ "distilbert-base-german-cased": {"do_lower_case": False},
80
+ "distilbert-base-multilingual-cased": {"do_lower_case": False},
81
+ }
82
+
83
+
84
+ class DistilBertTokenizerFast(PreTrainedTokenizerFast):
85
+ r"""
86
+ Construct a "fast" DistilBERT tokenizer (backed by HuggingFace's *tokenizers* library). Based on WordPiece.
87
+
88
+ This tokenizer inherits from [`PreTrainedTokenizerFast`] which contains most of the main methods. Users should
89
+ refer to this superclass for more information regarding those methods.
90
+
91
+ Args:
92
+ vocab_file (`str`):
93
+ File containing the vocabulary.
94
+ do_lower_case (`bool`, *optional*, defaults to `True`):
95
+ Whether or not to lowercase the input when tokenizing.
96
+ unk_token (`str`, *optional*, defaults to `"[UNK]"`):
97
+ The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
98
+ token instead.
99
+ sep_token (`str`, *optional*, defaults to `"[SEP]"`):
100
+ The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
101
+ sequence classification or for a text and a question for question answering. It is also used as the last
102
+ token of a sequence built with special tokens.
103
+ pad_token (`str`, *optional*, defaults to `"[PAD]"`):
104
+ The token used for padding, for example when batching sequences of different lengths.
105
+ cls_token (`str`, *optional*, defaults to `"[CLS]"`):
106
+ The classifier token which is used when doing sequence classification (classification of the whole sequence
107
+ instead of per-token classification). It is the first token of the sequence when built with special tokens.
108
+ mask_token (`str`, *optional*, defaults to `"[MASK]"`):
109
+ The token used for masking values. This is the token used when training this model with masked language
110
+ modeling. This is the token which the model will try to predict.
111
+ clean_text (`bool`, *optional*, defaults to `True`):
112
+ Whether or not to clean the text before tokenization by removing any control characters and replacing all
113
+ whitespaces by the classic one.
114
+ tokenize_chinese_chars (`bool`, *optional*, defaults to `True`):
115
+ Whether or not to tokenize Chinese characters. This should likely be deactivated for Japanese (see [this
116
+ issue](https://github.com/huggingface/transformers/issues/328)).
117
+ strip_accents (`bool`, *optional*):
118
+ Whether or not to strip all accents. If this option is not specified, then it will be determined by the
119
+ value for `lowercase` (as in the original BERT).
120
+ wordpieces_prefix (`str`, *optional*, defaults to `"##"`):
121
+ The prefix for subwords.
122
+ """
123
+
124
+ vocab_files_names = VOCAB_FILES_NAMES
125
+ pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP
126
+ max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
127
+ pretrained_init_configuration = PRETRAINED_INIT_CONFIGURATION
128
+ model_input_names = ["input_ids", "attention_mask"]
129
+ slow_tokenizer_class = DistilBertTokenizer
130
+
131
+ def __init__(
132
+ self,
133
+ vocab_file=None,
134
+ tokenizer_file=None,
135
+ do_lower_case=True,
136
+ unk_token="[UNK]",
137
+ sep_token="[SEP]",
138
+ pad_token="[PAD]",
139
+ cls_token="[CLS]",
140
+ mask_token="[MASK]",
141
+ tokenize_chinese_chars=True,
142
+ strip_accents=None,
143
+ **kwargs,
144
+ ):
145
+ super().__init__(
146
+ vocab_file,
147
+ tokenizer_file=tokenizer_file,
148
+ do_lower_case=do_lower_case,
149
+ unk_token=unk_token,
150
+ sep_token=sep_token,
151
+ pad_token=pad_token,
152
+ cls_token=cls_token,
153
+ mask_token=mask_token,
154
+ tokenize_chinese_chars=tokenize_chinese_chars,
155
+ strip_accents=strip_accents,
156
+ **kwargs,
157
+ )
158
+
159
+ normalizer_state = json.loads(self.backend_tokenizer.normalizer.__getstate__())
160
+ if (
161
+ normalizer_state.get("lowercase", do_lower_case) != do_lower_case
162
+ or normalizer_state.get("strip_accents", strip_accents) != strip_accents
163
+ or normalizer_state.get("handle_chinese_chars", tokenize_chinese_chars) != tokenize_chinese_chars
164
+ ):
165
+ normalizer_class = getattr(normalizers, normalizer_state.pop("type"))
166
+ normalizer_state["lowercase"] = do_lower_case
167
+ normalizer_state["strip_accents"] = strip_accents
168
+ normalizer_state["handle_chinese_chars"] = tokenize_chinese_chars
169
+ self.backend_tokenizer.normalizer = normalizer_class(**normalizer_state)
170
+
171
+ self.do_lower_case = do_lower_case
172
+
173
+ # Copied from transformers.models.bert.tokenization_bert_fast.BertTokenizerFast.build_inputs_with_special_tokens
174
+ def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None):
175
+ """
176
+ Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
177
+ adding special tokens. A BERT sequence has the following format:
178
+
179
+ - single sequence: `[CLS] X [SEP]`
180
+ - pair of sequences: `[CLS] A [SEP] B [SEP]`
181
+
182
+ Args:
183
+ token_ids_0 (`List[int]`):
184
+ List of IDs to which the special tokens will be added.
185
+ token_ids_1 (`List[int]`, *optional*):
186
+ Optional second list of IDs for sequence pairs.
187
+
188
+ Returns:
189
+ `List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
190
+ """
191
+ output = [self.cls_token_id] + token_ids_0 + [self.sep_token_id]
192
+
193
+ if token_ids_1 is not None:
194
+ output += token_ids_1 + [self.sep_token_id]
195
+
196
+ return output
197
+
198
+ # Copied from transformers.models.bert.tokenization_bert_fast.BertTokenizerFast.create_token_type_ids_from_sequences
199
+ def create_token_type_ids_from_sequences(
200
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
201
+ ) -> List[int]:
202
+ """
203
+ Create a mask from the two sequences passed to be used in a sequence-pair classification task. A BERT sequence
204
+ pair mask has the following format:
205
+
206
+ ```
207
+ 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1
208
+ | first sequence | second sequence |
209
+ ```
210
+
211
+ If `token_ids_1` is `None`, this method only returns the first portion of the mask (0s).
212
+
213
+ Args:
214
+ token_ids_0 (`List[int]`):
215
+ List of IDs.
216
+ token_ids_1 (`List[int]`, *optional*):
217
+ Optional second list of IDs for sequence pairs.
218
+
219
+ Returns:
220
+ `List[int]`: List of [token type IDs](../glossary#token-type-ids) according to the given sequence(s).
221
+ """
222
+ sep = [self.sep_token_id]
223
+ cls = [self.cls_token_id]
224
+ if token_ids_1 is None:
225
+ return len(cls + token_ids_0 + sep) * [0]
226
+ return len(cls + token_ids_0 + sep) * [0] + len(token_ids_1 + sep) * [1]
227
+
228
+ # Copied from transformers.models.bert.tokenization_bert_fast.BertTokenizerFast.save_vocabulary
229
+ def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
230
+ files = self._tokenizer.model.save(save_directory, name=filename_prefix)
231
+ return tuple(files)
env-llmeval/lib/python3.10/site-packages/transformers/models/ernie/__init__.py ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2022 The HuggingFace Team. All rights reserved.
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
+
15
+ from typing import TYPE_CHECKING
16
+
17
+ from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tensorflow_text_available, is_torch_available
18
+
19
+
20
+ _import_structure = {
21
+ "configuration_ernie": ["ERNIE_PRETRAINED_CONFIG_ARCHIVE_MAP", "ErnieConfig", "ErnieOnnxConfig"],
22
+ }
23
+
24
+ try:
25
+ if not is_torch_available():
26
+ raise OptionalDependencyNotAvailable()
27
+ except OptionalDependencyNotAvailable:
28
+ pass
29
+ else:
30
+ _import_structure["modeling_ernie"] = [
31
+ "ERNIE_PRETRAINED_MODEL_ARCHIVE_LIST",
32
+ "ErnieForCausalLM",
33
+ "ErnieForMaskedLM",
34
+ "ErnieForMultipleChoice",
35
+ "ErnieForNextSentencePrediction",
36
+ "ErnieForPreTraining",
37
+ "ErnieForQuestionAnswering",
38
+ "ErnieForSequenceClassification",
39
+ "ErnieForTokenClassification",
40
+ "ErnieModel",
41
+ "ErniePreTrainedModel",
42
+ ]
43
+
44
+ if TYPE_CHECKING:
45
+ from .configuration_ernie import ERNIE_PRETRAINED_CONFIG_ARCHIVE_MAP, ErnieConfig, ErnieOnnxConfig
46
+
47
+ try:
48
+ if not is_torch_available():
49
+ raise OptionalDependencyNotAvailable()
50
+ except OptionalDependencyNotAvailable:
51
+ pass
52
+ else:
53
+ from .modeling_ernie import (
54
+ ERNIE_PRETRAINED_MODEL_ARCHIVE_LIST,
55
+ ErnieForCausalLM,
56
+ ErnieForMaskedLM,
57
+ ErnieForMultipleChoice,
58
+ ErnieForNextSentencePrediction,
59
+ ErnieForPreTraining,
60
+ ErnieForQuestionAnswering,
61
+ ErnieForSequenceClassification,
62
+ ErnieForTokenClassification,
63
+ ErnieModel,
64
+ ErniePreTrainedModel,
65
+ )
66
+
67
+ else:
68
+ import sys
69
+
70
+ sys.modules[__name__] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
env-llmeval/lib/python3.10/site-packages/transformers/models/ernie/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (1.2 kB). View file
 
env-llmeval/lib/python3.10/site-packages/transformers/models/ernie/__pycache__/modeling_ernie.cpython-310.pyc ADDED
Binary file (53.1 kB). View file
 
env-llmeval/lib/python3.10/site-packages/transformers/models/ernie/configuration_ernie.py ADDED
@@ -0,0 +1,172 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 The Google AI Language Team Authors and The HuggingFace Inc. team.
3
+ # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+ """ ERNIE model configuration"""
17
+ from collections import OrderedDict
18
+ from typing import Mapping
19
+
20
+ from ...configuration_utils import PretrainedConfig
21
+ from ...onnx import OnnxConfig
22
+ from ...utils import logging
23
+
24
+
25
+ logger = logging.get_logger(__name__)
26
+
27
+ ERNIE_PRETRAINED_CONFIG_ARCHIVE_MAP = {
28
+ "nghuyong/ernie-1.0-base-zh": "https://huggingface.co/nghuyong/ernie-1.0-base-zh/resolve/main/config.json",
29
+ "nghuyong/ernie-2.0-base-en": "https://huggingface.co/nghuyong/ernie-2.0-base-en/resolve/main/config.json",
30
+ "nghuyong/ernie-2.0-large-en": "https://huggingface.co/nghuyong/ernie-2.0-large-en/resolve/main/config.json",
31
+ "nghuyong/ernie-3.0-base-zh": "https://huggingface.co/nghuyong/ernie-3.0-base-zh/resolve/main/config.json",
32
+ "nghuyong/ernie-3.0-medium-zh": "https://huggingface.co/nghuyong/ernie-3.0-medium-zh/resolve/main/config.json",
33
+ "nghuyong/ernie-3.0-mini-zh": "https://huggingface.co/nghuyong/ernie-3.0-mini-zh/resolve/main/config.json",
34
+ "nghuyong/ernie-3.0-micro-zh": "https://huggingface.co/nghuyong/ernie-3.0-micro-zh/resolve/main/config.json",
35
+ "nghuyong/ernie-3.0-nano-zh": "https://huggingface.co/nghuyong/ernie-3.0-nano-zh/resolve/main/config.json",
36
+ "nghuyong/ernie-gram-zh": "https://huggingface.co/nghuyong/ernie-gram-zh/resolve/main/config.json",
37
+ "nghuyong/ernie-health-zh": "https://huggingface.co/nghuyong/ernie-health-zh/resolve/main/config.json",
38
+ }
39
+
40
+
41
+ class ErnieConfig(PretrainedConfig):
42
+ r"""
43
+ This is the configuration class to store the configuration of a [`ErnieModel`] or a [`TFErnieModel`]. It is used to
44
+ instantiate a ERNIE model according to the specified arguments, defining the model architecture. Instantiating a
45
+ configuration with the defaults will yield a similar configuration to that of the ERNIE
46
+ [nghuyong/ernie-3.0-base-zh](https://huggingface.co/nghuyong/ernie-3.0-base-zh) architecture.
47
+
48
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
49
+ documentation from [`PretrainedConfig`] for more information.
50
+
51
+
52
+ Args:
53
+ vocab_size (`int`, *optional*, defaults to 30522):
54
+ Vocabulary size of the ERNIE model. Defines the number of different tokens that can be represented by the
55
+ `inputs_ids` passed when calling [`ErnieModel`] or [`TFErnieModel`].
56
+ hidden_size (`int`, *optional*, defaults to 768):
57
+ Dimensionality of the encoder layers and the pooler layer.
58
+ num_hidden_layers (`int`, *optional*, defaults to 12):
59
+ Number of hidden layers in the Transformer encoder.
60
+ num_attention_heads (`int`, *optional*, defaults to 12):
61
+ Number of attention heads for each attention layer in the Transformer encoder.
62
+ intermediate_size (`int`, *optional*, defaults to 3072):
63
+ Dimensionality of the "intermediate" (often named feed-forward) layer in the Transformer encoder.
64
+ hidden_act (`str` or `Callable`, *optional*, defaults to `"gelu"`):
65
+ The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
66
+ `"relu"`, `"silu"` and `"gelu_new"` are supported.
67
+ hidden_dropout_prob (`float`, *optional*, defaults to 0.1):
68
+ The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
69
+ attention_probs_dropout_prob (`float`, *optional*, defaults to 0.1):
70
+ The dropout ratio for the attention probabilities.
71
+ max_position_embeddings (`int`, *optional*, defaults to 512):
72
+ The maximum sequence length that this model might ever be used with. Typically set this to something large
73
+ just in case (e.g., 512 or 1024 or 2048).
74
+ type_vocab_size (`int`, *optional*, defaults to 2):
75
+ The vocabulary size of the `token_type_ids` passed when calling [`ErnieModel`] or [`TFErnieModel`].
76
+ task_type_vocab_size (`int`, *optional*, defaults to 3):
77
+ The vocabulary size of the `task_type_ids` for ERNIE2.0/ERNIE3.0 model
78
+ use_task_id (`bool`, *optional*, defaults to `False`):
79
+ Whether or not the model support `task_type_ids`
80
+ initializer_range (`float`, *optional*, defaults to 0.02):
81
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
82
+ layer_norm_eps (`float`, *optional*, defaults to 1e-12):
83
+ The epsilon used by the layer normalization layers.
84
+ pad_token_id (`int`, *optional*, defaults to 0):
85
+ Padding token id.
86
+ position_embedding_type (`str`, *optional*, defaults to `"absolute"`):
87
+ Type of position embedding. Choose one of `"absolute"`, `"relative_key"`, `"relative_key_query"`. For
88
+ positional embeddings use `"absolute"`. For more information on `"relative_key"`, please refer to
89
+ [Self-Attention with Relative Position Representations (Shaw et al.)](https://arxiv.org/abs/1803.02155).
90
+ For more information on `"relative_key_query"`, please refer to *Method 4* in [Improve Transformer Models
91
+ with Better Relative Position Embeddings (Huang et al.)](https://arxiv.org/abs/2009.13658).
92
+ use_cache (`bool`, *optional*, defaults to `True`):
93
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
94
+ relevant if `config.is_decoder=True`.
95
+ classifier_dropout (`float`, *optional*):
96
+ The dropout ratio for the classification head.
97
+
98
+ Examples:
99
+
100
+ ```python
101
+ >>> from transformers import ErnieConfig, ErnieModel
102
+
103
+ >>> # Initializing a ERNIE nghuyong/ernie-3.0-base-zh style configuration
104
+ >>> configuration = ErnieConfig()
105
+
106
+ >>> # Initializing a model (with random weights) from the nghuyong/ernie-3.0-base-zh style configuration
107
+ >>> model = ErnieModel(configuration)
108
+
109
+ >>> # Accessing the model configuration
110
+ >>> configuration = model.config
111
+ ```"""
112
+
113
+ model_type = "ernie"
114
+
115
+ def __init__(
116
+ self,
117
+ vocab_size=30522,
118
+ hidden_size=768,
119
+ num_hidden_layers=12,
120
+ num_attention_heads=12,
121
+ intermediate_size=3072,
122
+ hidden_act="gelu",
123
+ hidden_dropout_prob=0.1,
124
+ attention_probs_dropout_prob=0.1,
125
+ max_position_embeddings=512,
126
+ type_vocab_size=2,
127
+ task_type_vocab_size=3,
128
+ use_task_id=False,
129
+ initializer_range=0.02,
130
+ layer_norm_eps=1e-12,
131
+ pad_token_id=0,
132
+ position_embedding_type="absolute",
133
+ use_cache=True,
134
+ classifier_dropout=None,
135
+ **kwargs,
136
+ ):
137
+ super().__init__(pad_token_id=pad_token_id, **kwargs)
138
+
139
+ self.vocab_size = vocab_size
140
+ self.hidden_size = hidden_size
141
+ self.num_hidden_layers = num_hidden_layers
142
+ self.num_attention_heads = num_attention_heads
143
+ self.hidden_act = hidden_act
144
+ self.intermediate_size = intermediate_size
145
+ self.hidden_dropout_prob = hidden_dropout_prob
146
+ self.attention_probs_dropout_prob = attention_probs_dropout_prob
147
+ self.max_position_embeddings = max_position_embeddings
148
+ self.type_vocab_size = type_vocab_size
149
+ self.task_type_vocab_size = task_type_vocab_size
150
+ self.use_task_id = use_task_id
151
+ self.initializer_range = initializer_range
152
+ self.layer_norm_eps = layer_norm_eps
153
+ self.position_embedding_type = position_embedding_type
154
+ self.use_cache = use_cache
155
+ self.classifier_dropout = classifier_dropout
156
+
157
+
158
+ class ErnieOnnxConfig(OnnxConfig):
159
+ @property
160
+ def inputs(self) -> Mapping[str, Mapping[int, str]]:
161
+ if self.task == "multiple-choice":
162
+ dynamic_axis = {0: "batch", 1: "choice", 2: "sequence"}
163
+ else:
164
+ dynamic_axis = {0: "batch", 1: "sequence"}
165
+ return OrderedDict(
166
+ [
167
+ ("input_ids", dynamic_axis),
168
+ ("attention_mask", dynamic_axis),
169
+ ("token_type_ids", dynamic_axis),
170
+ ("task_type_ids", dynamic_axis),
171
+ ]
172
+ )
env-llmeval/lib/python3.10/site-packages/transformers/models/ernie/modeling_ernie.py ADDED
@@ -0,0 +1,1832 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 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
+ """PyTorch ERNIE model."""
16
+
17
+
18
+ import math
19
+ import warnings
20
+ from dataclasses import dataclass
21
+ from typing import List, Optional, Tuple, Union
22
+
23
+ import torch
24
+ import torch.utils.checkpoint
25
+ from torch import nn
26
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
27
+
28
+ from ...activations import ACT2FN
29
+ from ...modeling_outputs import (
30
+ BaseModelOutputWithPastAndCrossAttentions,
31
+ BaseModelOutputWithPoolingAndCrossAttentions,
32
+ CausalLMOutputWithCrossAttentions,
33
+ MaskedLMOutput,
34
+ MultipleChoiceModelOutput,
35
+ NextSentencePredictorOutput,
36
+ QuestionAnsweringModelOutput,
37
+ SequenceClassifierOutput,
38
+ TokenClassifierOutput,
39
+ )
40
+ from ...modeling_utils import PreTrainedModel
41
+ from ...pytorch_utils import apply_chunking_to_forward, find_pruneable_heads_and_indices, prune_linear_layer
42
+ from ...utils import (
43
+ ModelOutput,
44
+ add_code_sample_docstrings,
45
+ add_start_docstrings,
46
+ add_start_docstrings_to_model_forward,
47
+ logging,
48
+ replace_return_docstrings,
49
+ )
50
+ from .configuration_ernie import ErnieConfig
51
+
52
+
53
+ logger = logging.get_logger(__name__)
54
+
55
+ _CHECKPOINT_FOR_DOC = "nghuyong/ernie-1.0-base-zh"
56
+ _CONFIG_FOR_DOC = "ErnieConfig"
57
+
58
+
59
+ ERNIE_PRETRAINED_MODEL_ARCHIVE_LIST = [
60
+ "nghuyong/ernie-1.0-base-zh",
61
+ "nghuyong/ernie-2.0-base-en",
62
+ "nghuyong/ernie-2.0-large-en",
63
+ "nghuyong/ernie-3.0-base-zh",
64
+ "nghuyong/ernie-3.0-medium-zh",
65
+ "nghuyong/ernie-3.0-mini-zh",
66
+ "nghuyong/ernie-3.0-micro-zh",
67
+ "nghuyong/ernie-3.0-nano-zh",
68
+ "nghuyong/ernie-gram-zh",
69
+ "nghuyong/ernie-health-zh",
70
+ # See all ERNIE models at https://huggingface.co/models?filter=ernie
71
+ ]
72
+
73
+
74
+ class ErnieEmbeddings(nn.Module):
75
+ """Construct the embeddings from word, position and token_type embeddings."""
76
+
77
+ def __init__(self, config):
78
+ super().__init__()
79
+ self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id)
80
+ self.position_embeddings = nn.Embedding(config.max_position_embeddings, config.hidden_size)
81
+ self.token_type_embeddings = nn.Embedding(config.type_vocab_size, config.hidden_size)
82
+ self.use_task_id = config.use_task_id
83
+ if config.use_task_id:
84
+ self.task_type_embeddings = nn.Embedding(config.task_type_vocab_size, config.hidden_size)
85
+
86
+ # self.LayerNorm is not snake-cased to stick with TensorFlow model variable name and be able to load
87
+ # any TensorFlow checkpoint file
88
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
89
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
90
+ # position_ids (1, len position emb) is contiguous in memory and exported when serialized
91
+ self.position_embedding_type = getattr(config, "position_embedding_type", "absolute")
92
+ self.register_buffer(
93
+ "position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)), persistent=False
94
+ )
95
+ self.register_buffer(
96
+ "token_type_ids", torch.zeros(self.position_ids.size(), dtype=torch.long), persistent=False
97
+ )
98
+
99
+ def forward(
100
+ self,
101
+ input_ids: Optional[torch.LongTensor] = None,
102
+ token_type_ids: Optional[torch.LongTensor] = None,
103
+ task_type_ids: Optional[torch.LongTensor] = None,
104
+ position_ids: Optional[torch.LongTensor] = None,
105
+ inputs_embeds: Optional[torch.FloatTensor] = None,
106
+ past_key_values_length: int = 0,
107
+ ) -> torch.Tensor:
108
+ if input_ids is not None:
109
+ input_shape = input_ids.size()
110
+ else:
111
+ input_shape = inputs_embeds.size()[:-1]
112
+
113
+ seq_length = input_shape[1]
114
+
115
+ if position_ids is None:
116
+ position_ids = self.position_ids[:, past_key_values_length : seq_length + past_key_values_length]
117
+
118
+ # Setting the token_type_ids to the registered buffer in constructor where it is all zeros, which usually occurs
119
+ # when its auto-generated, registered buffer helps users when tracing the model without passing token_type_ids, solves
120
+ # issue #5664
121
+ if token_type_ids is None:
122
+ if hasattr(self, "token_type_ids"):
123
+ buffered_token_type_ids = self.token_type_ids[:, :seq_length]
124
+ buffered_token_type_ids_expanded = buffered_token_type_ids.expand(input_shape[0], seq_length)
125
+ token_type_ids = buffered_token_type_ids_expanded
126
+ else:
127
+ token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=self.position_ids.device)
128
+
129
+ if inputs_embeds is None:
130
+ inputs_embeds = self.word_embeddings(input_ids)
131
+ token_type_embeddings = self.token_type_embeddings(token_type_ids)
132
+
133
+ embeddings = inputs_embeds + token_type_embeddings
134
+ if self.position_embedding_type == "absolute":
135
+ position_embeddings = self.position_embeddings(position_ids)
136
+ embeddings += position_embeddings
137
+
138
+ # add `task_type_id` for ERNIE model
139
+ if self.use_task_id:
140
+ if task_type_ids is None:
141
+ task_type_ids = torch.zeros(input_shape, dtype=torch.long, device=self.position_ids.device)
142
+ task_type_embeddings = self.task_type_embeddings(task_type_ids)
143
+ embeddings += task_type_embeddings
144
+
145
+ embeddings = self.LayerNorm(embeddings)
146
+ embeddings = self.dropout(embeddings)
147
+ return embeddings
148
+
149
+
150
+ # Copied from transformers.models.bert.modeling_bert.BertSelfAttention with Bert->Ernie
151
+ class ErnieSelfAttention(nn.Module):
152
+ def __init__(self, config, position_embedding_type=None):
153
+ super().__init__()
154
+ if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):
155
+ raise ValueError(
156
+ f"The hidden size ({config.hidden_size}) is not a multiple of the number of attention "
157
+ f"heads ({config.num_attention_heads})"
158
+ )
159
+
160
+ self.num_attention_heads = config.num_attention_heads
161
+ self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
162
+ self.all_head_size = self.num_attention_heads * self.attention_head_size
163
+
164
+ self.query = nn.Linear(config.hidden_size, self.all_head_size)
165
+ self.key = nn.Linear(config.hidden_size, self.all_head_size)
166
+ self.value = nn.Linear(config.hidden_size, self.all_head_size)
167
+
168
+ self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
169
+ self.position_embedding_type = position_embedding_type or getattr(
170
+ config, "position_embedding_type", "absolute"
171
+ )
172
+ if self.position_embedding_type == "relative_key" or self.position_embedding_type == "relative_key_query":
173
+ self.max_position_embeddings = config.max_position_embeddings
174
+ self.distance_embedding = nn.Embedding(2 * config.max_position_embeddings - 1, self.attention_head_size)
175
+
176
+ self.is_decoder = config.is_decoder
177
+
178
+ def transpose_for_scores(self, x: torch.Tensor) -> torch.Tensor:
179
+ new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.attention_head_size)
180
+ x = x.view(new_x_shape)
181
+ return x.permute(0, 2, 1, 3)
182
+
183
+ def forward(
184
+ self,
185
+ hidden_states: torch.Tensor,
186
+ attention_mask: Optional[torch.FloatTensor] = None,
187
+ head_mask: Optional[torch.FloatTensor] = None,
188
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
189
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
190
+ past_key_value: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
191
+ output_attentions: Optional[bool] = False,
192
+ ) -> Tuple[torch.Tensor]:
193
+ mixed_query_layer = self.query(hidden_states)
194
+
195
+ # If this is instantiated as a cross-attention module, the keys
196
+ # and values come from an encoder; the attention mask needs to be
197
+ # such that the encoder's padding tokens are not attended to.
198
+ is_cross_attention = encoder_hidden_states is not None
199
+
200
+ if is_cross_attention and past_key_value is not None:
201
+ # reuse k,v, cross_attentions
202
+ key_layer = past_key_value[0]
203
+ value_layer = past_key_value[1]
204
+ attention_mask = encoder_attention_mask
205
+ elif is_cross_attention:
206
+ key_layer = self.transpose_for_scores(self.key(encoder_hidden_states))
207
+ value_layer = self.transpose_for_scores(self.value(encoder_hidden_states))
208
+ attention_mask = encoder_attention_mask
209
+ elif past_key_value is not None:
210
+ key_layer = self.transpose_for_scores(self.key(hidden_states))
211
+ value_layer = self.transpose_for_scores(self.value(hidden_states))
212
+ key_layer = torch.cat([past_key_value[0], key_layer], dim=2)
213
+ value_layer = torch.cat([past_key_value[1], value_layer], dim=2)
214
+ else:
215
+ key_layer = self.transpose_for_scores(self.key(hidden_states))
216
+ value_layer = self.transpose_for_scores(self.value(hidden_states))
217
+
218
+ query_layer = self.transpose_for_scores(mixed_query_layer)
219
+
220
+ use_cache = past_key_value is not None
221
+ if self.is_decoder:
222
+ # if cross_attention save Tuple(torch.Tensor, torch.Tensor) of all cross attention key/value_states.
223
+ # Further calls to cross_attention layer can then reuse all cross-attention
224
+ # key/value_states (first "if" case)
225
+ # if uni-directional self-attention (decoder) save Tuple(torch.Tensor, torch.Tensor) of
226
+ # all previous decoder key/value_states. Further calls to uni-directional self-attention
227
+ # can concat previous decoder key/value_states to current projected key/value_states (third "elif" case)
228
+ # if encoder bi-directional self-attention `past_key_value` is always `None`
229
+ past_key_value = (key_layer, value_layer)
230
+
231
+ # Take the dot product between "query" and "key" to get the raw attention scores.
232
+ attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))
233
+
234
+ if self.position_embedding_type == "relative_key" or self.position_embedding_type == "relative_key_query":
235
+ query_length, key_length = query_layer.shape[2], key_layer.shape[2]
236
+ if use_cache:
237
+ position_ids_l = torch.tensor(key_length - 1, dtype=torch.long, device=hidden_states.device).view(
238
+ -1, 1
239
+ )
240
+ else:
241
+ position_ids_l = torch.arange(query_length, dtype=torch.long, device=hidden_states.device).view(-1, 1)
242
+ position_ids_r = torch.arange(key_length, dtype=torch.long, device=hidden_states.device).view(1, -1)
243
+ distance = position_ids_l - position_ids_r
244
+
245
+ positional_embedding = self.distance_embedding(distance + self.max_position_embeddings - 1)
246
+ positional_embedding = positional_embedding.to(dtype=query_layer.dtype) # fp16 compatibility
247
+
248
+ if self.position_embedding_type == "relative_key":
249
+ relative_position_scores = torch.einsum("bhld,lrd->bhlr", query_layer, positional_embedding)
250
+ attention_scores = attention_scores + relative_position_scores
251
+ elif self.position_embedding_type == "relative_key_query":
252
+ relative_position_scores_query = torch.einsum("bhld,lrd->bhlr", query_layer, positional_embedding)
253
+ relative_position_scores_key = torch.einsum("bhrd,lrd->bhlr", key_layer, positional_embedding)
254
+ attention_scores = attention_scores + relative_position_scores_query + relative_position_scores_key
255
+
256
+ attention_scores = attention_scores / math.sqrt(self.attention_head_size)
257
+ if attention_mask is not None:
258
+ # Apply the attention mask is (precomputed for all layers in ErnieModel forward() function)
259
+ attention_scores = attention_scores + attention_mask
260
+
261
+ # Normalize the attention scores to probabilities.
262
+ attention_probs = nn.functional.softmax(attention_scores, dim=-1)
263
+
264
+ # This is actually dropping out entire tokens to attend to, which might
265
+ # seem a bit unusual, but is taken from the original Transformer paper.
266
+ attention_probs = self.dropout(attention_probs)
267
+
268
+ # Mask heads if we want to
269
+ if head_mask is not None:
270
+ attention_probs = attention_probs * head_mask
271
+
272
+ context_layer = torch.matmul(attention_probs, value_layer)
273
+
274
+ context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
275
+ new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
276
+ context_layer = context_layer.view(new_context_layer_shape)
277
+
278
+ outputs = (context_layer, attention_probs) if output_attentions else (context_layer,)
279
+
280
+ if self.is_decoder:
281
+ outputs = outputs + (past_key_value,)
282
+ return outputs
283
+
284
+
285
+ # Copied from transformers.models.bert.modeling_bert.BertSelfOutput with Bert->Ernie
286
+ class ErnieSelfOutput(nn.Module):
287
+ def __init__(self, config):
288
+ super().__init__()
289
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
290
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
291
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
292
+
293
+ def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
294
+ hidden_states = self.dense(hidden_states)
295
+ hidden_states = self.dropout(hidden_states)
296
+ hidden_states = self.LayerNorm(hidden_states + input_tensor)
297
+ return hidden_states
298
+
299
+
300
+ # Copied from transformers.models.bert.modeling_bert.BertAttention with Bert->Ernie
301
+ class ErnieAttention(nn.Module):
302
+ def __init__(self, config, position_embedding_type=None):
303
+ super().__init__()
304
+ self.self = ErnieSelfAttention(config, position_embedding_type=position_embedding_type)
305
+ self.output = ErnieSelfOutput(config)
306
+ self.pruned_heads = set()
307
+
308
+ def prune_heads(self, heads):
309
+ if len(heads) == 0:
310
+ return
311
+ heads, index = find_pruneable_heads_and_indices(
312
+ heads, self.self.num_attention_heads, self.self.attention_head_size, self.pruned_heads
313
+ )
314
+
315
+ # Prune linear layers
316
+ self.self.query = prune_linear_layer(self.self.query, index)
317
+ self.self.key = prune_linear_layer(self.self.key, index)
318
+ self.self.value = prune_linear_layer(self.self.value, index)
319
+ self.output.dense = prune_linear_layer(self.output.dense, index, dim=1)
320
+
321
+ # Update hyper params and store pruned heads
322
+ self.self.num_attention_heads = self.self.num_attention_heads - len(heads)
323
+ self.self.all_head_size = self.self.attention_head_size * self.self.num_attention_heads
324
+ self.pruned_heads = self.pruned_heads.union(heads)
325
+
326
+ def forward(
327
+ self,
328
+ hidden_states: torch.Tensor,
329
+ attention_mask: Optional[torch.FloatTensor] = None,
330
+ head_mask: Optional[torch.FloatTensor] = None,
331
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
332
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
333
+ past_key_value: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
334
+ output_attentions: Optional[bool] = False,
335
+ ) -> Tuple[torch.Tensor]:
336
+ self_outputs = self.self(
337
+ hidden_states,
338
+ attention_mask,
339
+ head_mask,
340
+ encoder_hidden_states,
341
+ encoder_attention_mask,
342
+ past_key_value,
343
+ output_attentions,
344
+ )
345
+ attention_output = self.output(self_outputs[0], hidden_states)
346
+ outputs = (attention_output,) + self_outputs[1:] # add attentions if we output them
347
+ return outputs
348
+
349
+
350
+ # Copied from transformers.models.bert.modeling_bert.BertIntermediate with Bert->Ernie
351
+ class ErnieIntermediate(nn.Module):
352
+ def __init__(self, config):
353
+ super().__init__()
354
+ self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
355
+ if isinstance(config.hidden_act, str):
356
+ self.intermediate_act_fn = ACT2FN[config.hidden_act]
357
+ else:
358
+ self.intermediate_act_fn = config.hidden_act
359
+
360
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
361
+ hidden_states = self.dense(hidden_states)
362
+ hidden_states = self.intermediate_act_fn(hidden_states)
363
+ return hidden_states
364
+
365
+
366
+ # Copied from transformers.models.bert.modeling_bert.BertOutput with Bert->Ernie
367
+ class ErnieOutput(nn.Module):
368
+ def __init__(self, config):
369
+ super().__init__()
370
+ self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
371
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
372
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
373
+
374
+ def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
375
+ hidden_states = self.dense(hidden_states)
376
+ hidden_states = self.dropout(hidden_states)
377
+ hidden_states = self.LayerNorm(hidden_states + input_tensor)
378
+ return hidden_states
379
+
380
+
381
+ # Copied from transformers.models.bert.modeling_bert.BertLayer with Bert->Ernie
382
+ class ErnieLayer(nn.Module):
383
+ def __init__(self, config):
384
+ super().__init__()
385
+ self.chunk_size_feed_forward = config.chunk_size_feed_forward
386
+ self.seq_len_dim = 1
387
+ self.attention = ErnieAttention(config)
388
+ self.is_decoder = config.is_decoder
389
+ self.add_cross_attention = config.add_cross_attention
390
+ if self.add_cross_attention:
391
+ if not self.is_decoder:
392
+ raise ValueError(f"{self} should be used as a decoder model if cross attention is added")
393
+ self.crossattention = ErnieAttention(config, position_embedding_type="absolute")
394
+ self.intermediate = ErnieIntermediate(config)
395
+ self.output = ErnieOutput(config)
396
+
397
+ def forward(
398
+ self,
399
+ hidden_states: torch.Tensor,
400
+ attention_mask: Optional[torch.FloatTensor] = None,
401
+ head_mask: Optional[torch.FloatTensor] = None,
402
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
403
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
404
+ past_key_value: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
405
+ output_attentions: Optional[bool] = False,
406
+ ) -> Tuple[torch.Tensor]:
407
+ # decoder uni-directional self-attention cached key/values tuple is at positions 1,2
408
+ self_attn_past_key_value = past_key_value[:2] if past_key_value is not None else None
409
+ self_attention_outputs = self.attention(
410
+ hidden_states,
411
+ attention_mask,
412
+ head_mask,
413
+ output_attentions=output_attentions,
414
+ past_key_value=self_attn_past_key_value,
415
+ )
416
+ attention_output = self_attention_outputs[0]
417
+
418
+ # if decoder, the last output is tuple of self-attn cache
419
+ if self.is_decoder:
420
+ outputs = self_attention_outputs[1:-1]
421
+ present_key_value = self_attention_outputs[-1]
422
+ else:
423
+ outputs = self_attention_outputs[1:] # add self attentions if we output attention weights
424
+
425
+ cross_attn_present_key_value = None
426
+ if self.is_decoder and encoder_hidden_states is not None:
427
+ if not hasattr(self, "crossattention"):
428
+ raise ValueError(
429
+ f"If `encoder_hidden_states` are passed, {self} has to be instantiated with cross-attention layers"
430
+ " by setting `config.add_cross_attention=True`"
431
+ )
432
+
433
+ # cross_attn cached key/values tuple is at positions 3,4 of past_key_value tuple
434
+ cross_attn_past_key_value = past_key_value[-2:] if past_key_value is not None else None
435
+ cross_attention_outputs = self.crossattention(
436
+ attention_output,
437
+ attention_mask,
438
+ head_mask,
439
+ encoder_hidden_states,
440
+ encoder_attention_mask,
441
+ cross_attn_past_key_value,
442
+ output_attentions,
443
+ )
444
+ attention_output = cross_attention_outputs[0]
445
+ outputs = outputs + cross_attention_outputs[1:-1] # add cross attentions if we output attention weights
446
+
447
+ # add cross-attn cache to positions 3,4 of present_key_value tuple
448
+ cross_attn_present_key_value = cross_attention_outputs[-1]
449
+ present_key_value = present_key_value + cross_attn_present_key_value
450
+
451
+ layer_output = apply_chunking_to_forward(
452
+ self.feed_forward_chunk, self.chunk_size_feed_forward, self.seq_len_dim, attention_output
453
+ )
454
+ outputs = (layer_output,) + outputs
455
+
456
+ # if decoder, return the attn key/values as the last output
457
+ if self.is_decoder:
458
+ outputs = outputs + (present_key_value,)
459
+
460
+ return outputs
461
+
462
+ def feed_forward_chunk(self, attention_output):
463
+ intermediate_output = self.intermediate(attention_output)
464
+ layer_output = self.output(intermediate_output, attention_output)
465
+ return layer_output
466
+
467
+
468
+ # Copied from transformers.models.bert.modeling_bert.BertEncoder with Bert->Ernie
469
+ class ErnieEncoder(nn.Module):
470
+ def __init__(self, config):
471
+ super().__init__()
472
+ self.config = config
473
+ self.layer = nn.ModuleList([ErnieLayer(config) for _ in range(config.num_hidden_layers)])
474
+ self.gradient_checkpointing = False
475
+
476
+ def forward(
477
+ self,
478
+ hidden_states: torch.Tensor,
479
+ attention_mask: Optional[torch.FloatTensor] = None,
480
+ head_mask: Optional[torch.FloatTensor] = None,
481
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
482
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
483
+ past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
484
+ use_cache: Optional[bool] = None,
485
+ output_attentions: Optional[bool] = False,
486
+ output_hidden_states: Optional[bool] = False,
487
+ return_dict: Optional[bool] = True,
488
+ ) -> Union[Tuple[torch.Tensor], BaseModelOutputWithPastAndCrossAttentions]:
489
+ all_hidden_states = () if output_hidden_states else None
490
+ all_self_attentions = () if output_attentions else None
491
+ all_cross_attentions = () if output_attentions and self.config.add_cross_attention else None
492
+
493
+ if self.gradient_checkpointing and self.training:
494
+ if use_cache:
495
+ logger.warning_once(
496
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
497
+ )
498
+ use_cache = False
499
+
500
+ next_decoder_cache = () if use_cache else None
501
+ for i, layer_module in enumerate(self.layer):
502
+ if output_hidden_states:
503
+ all_hidden_states = all_hidden_states + (hidden_states,)
504
+
505
+ layer_head_mask = head_mask[i] if head_mask is not None else None
506
+ past_key_value = past_key_values[i] if past_key_values is not None else None
507
+
508
+ if self.gradient_checkpointing and self.training:
509
+ layer_outputs = self._gradient_checkpointing_func(
510
+ layer_module.__call__,
511
+ hidden_states,
512
+ attention_mask,
513
+ layer_head_mask,
514
+ encoder_hidden_states,
515
+ encoder_attention_mask,
516
+ past_key_value,
517
+ output_attentions,
518
+ )
519
+ else:
520
+ layer_outputs = layer_module(
521
+ hidden_states,
522
+ attention_mask,
523
+ layer_head_mask,
524
+ encoder_hidden_states,
525
+ encoder_attention_mask,
526
+ past_key_value,
527
+ output_attentions,
528
+ )
529
+
530
+ hidden_states = layer_outputs[0]
531
+ if use_cache:
532
+ next_decoder_cache += (layer_outputs[-1],)
533
+ if output_attentions:
534
+ all_self_attentions = all_self_attentions + (layer_outputs[1],)
535
+ if self.config.add_cross_attention:
536
+ all_cross_attentions = all_cross_attentions + (layer_outputs[2],)
537
+
538
+ if output_hidden_states:
539
+ all_hidden_states = all_hidden_states + (hidden_states,)
540
+
541
+ if not return_dict:
542
+ return tuple(
543
+ v
544
+ for v in [
545
+ hidden_states,
546
+ next_decoder_cache,
547
+ all_hidden_states,
548
+ all_self_attentions,
549
+ all_cross_attentions,
550
+ ]
551
+ if v is not None
552
+ )
553
+ return BaseModelOutputWithPastAndCrossAttentions(
554
+ last_hidden_state=hidden_states,
555
+ past_key_values=next_decoder_cache,
556
+ hidden_states=all_hidden_states,
557
+ attentions=all_self_attentions,
558
+ cross_attentions=all_cross_attentions,
559
+ )
560
+
561
+
562
+ # Copied from transformers.models.bert.modeling_bert.BertPooler with Bert->Ernie
563
+ class ErniePooler(nn.Module):
564
+ def __init__(self, config):
565
+ super().__init__()
566
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
567
+ self.activation = nn.Tanh()
568
+
569
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
570
+ # We "pool" the model by simply taking the hidden state corresponding
571
+ # to the first token.
572
+ first_token_tensor = hidden_states[:, 0]
573
+ pooled_output = self.dense(first_token_tensor)
574
+ pooled_output = self.activation(pooled_output)
575
+ return pooled_output
576
+
577
+
578
+ # Copied from transformers.models.bert.modeling_bert.BertPredictionHeadTransform with Bert->Ernie
579
+ class ErniePredictionHeadTransform(nn.Module):
580
+ def __init__(self, config):
581
+ super().__init__()
582
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
583
+ if isinstance(config.hidden_act, str):
584
+ self.transform_act_fn = ACT2FN[config.hidden_act]
585
+ else:
586
+ self.transform_act_fn = config.hidden_act
587
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
588
+
589
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
590
+ hidden_states = self.dense(hidden_states)
591
+ hidden_states = self.transform_act_fn(hidden_states)
592
+ hidden_states = self.LayerNorm(hidden_states)
593
+ return hidden_states
594
+
595
+
596
+ # Copied from transformers.models.bert.modeling_bert.BertLMPredictionHead with Bert->Ernie
597
+ class ErnieLMPredictionHead(nn.Module):
598
+ def __init__(self, config):
599
+ super().__init__()
600
+ self.transform = ErniePredictionHeadTransform(config)
601
+
602
+ # The output weights are the same as the input embeddings, but there is
603
+ # an output-only bias for each token.
604
+ self.decoder = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
605
+
606
+ self.bias = nn.Parameter(torch.zeros(config.vocab_size))
607
+
608
+ # Need a link between the two variables so that the bias is correctly resized with `resize_token_embeddings`
609
+ self.decoder.bias = self.bias
610
+
611
+ def forward(self, hidden_states):
612
+ hidden_states = self.transform(hidden_states)
613
+ hidden_states = self.decoder(hidden_states)
614
+ return hidden_states
615
+
616
+
617
+ # Copied from transformers.models.bert.modeling_bert.BertOnlyMLMHead with Bert->Ernie
618
+ class ErnieOnlyMLMHead(nn.Module):
619
+ def __init__(self, config):
620
+ super().__init__()
621
+ self.predictions = ErnieLMPredictionHead(config)
622
+
623
+ def forward(self, sequence_output: torch.Tensor) -> torch.Tensor:
624
+ prediction_scores = self.predictions(sequence_output)
625
+ return prediction_scores
626
+
627
+
628
+ # Copied from transformers.models.bert.modeling_bert.BertOnlyNSPHead with Bert->Ernie
629
+ class ErnieOnlyNSPHead(nn.Module):
630
+ def __init__(self, config):
631
+ super().__init__()
632
+ self.seq_relationship = nn.Linear(config.hidden_size, 2)
633
+
634
+ def forward(self, pooled_output):
635
+ seq_relationship_score = self.seq_relationship(pooled_output)
636
+ return seq_relationship_score
637
+
638
+
639
+ # Copied from transformers.models.bert.modeling_bert.BertPreTrainingHeads with Bert->Ernie
640
+ class ErniePreTrainingHeads(nn.Module):
641
+ def __init__(self, config):
642
+ super().__init__()
643
+ self.predictions = ErnieLMPredictionHead(config)
644
+ self.seq_relationship = nn.Linear(config.hidden_size, 2)
645
+
646
+ def forward(self, sequence_output, pooled_output):
647
+ prediction_scores = self.predictions(sequence_output)
648
+ seq_relationship_score = self.seq_relationship(pooled_output)
649
+ return prediction_scores, seq_relationship_score
650
+
651
+
652
+ class ErniePreTrainedModel(PreTrainedModel):
653
+ """
654
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
655
+ models.
656
+ """
657
+
658
+ config_class = ErnieConfig
659
+ base_model_prefix = "ernie"
660
+ supports_gradient_checkpointing = True
661
+
662
+ def _init_weights(self, module):
663
+ """Initialize the weights"""
664
+ if isinstance(module, nn.Linear):
665
+ # Slightly different from the TF version which uses truncated_normal for initialization
666
+ # cf https://github.com/pytorch/pytorch/pull/5617
667
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
668
+ if module.bias is not None:
669
+ module.bias.data.zero_()
670
+ elif isinstance(module, nn.Embedding):
671
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
672
+ if module.padding_idx is not None:
673
+ module.weight.data[module.padding_idx].zero_()
674
+ elif isinstance(module, nn.LayerNorm):
675
+ module.bias.data.zero_()
676
+ module.weight.data.fill_(1.0)
677
+
678
+
679
+ @dataclass
680
+ # Copied from transformers.models.bert.modeling_bert.BertForPreTrainingOutput with Bert->Ernie
681
+ class ErnieForPreTrainingOutput(ModelOutput):
682
+ """
683
+ Output type of [`ErnieForPreTraining`].
684
+
685
+ Args:
686
+ loss (*optional*, returned when `labels` is provided, `torch.FloatTensor` of shape `(1,)`):
687
+ Total loss as the sum of the masked language modeling loss and the next sequence prediction
688
+ (classification) loss.
689
+ prediction_logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
690
+ Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
691
+ seq_relationship_logits (`torch.FloatTensor` of shape `(batch_size, 2)`):
692
+ Prediction scores of the next sequence prediction (classification) head (scores of True/False continuation
693
+ before SoftMax).
694
+ hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
695
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of
696
+ shape `(batch_size, sequence_length, hidden_size)`.
697
+
698
+ Hidden-states of the model at the output of each layer plus the initial embedding outputs.
699
+ attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
700
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
701
+ sequence_length)`.
702
+
703
+ Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
704
+ heads.
705
+ """
706
+
707
+ loss: Optional[torch.FloatTensor] = None
708
+ prediction_logits: torch.FloatTensor = None
709
+ seq_relationship_logits: torch.FloatTensor = None
710
+ hidden_states: Optional[Tuple[torch.FloatTensor]] = None
711
+ attentions: Optional[Tuple[torch.FloatTensor]] = None
712
+
713
+
714
+ ERNIE_START_DOCSTRING = r"""
715
+
716
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
717
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
718
+ etc.)
719
+
720
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
721
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
722
+ and behavior.
723
+
724
+ Parameters:
725
+ config ([`ErnieConfig`]): Model configuration class with all the parameters of the model.
726
+ Initializing with a config file does not load the weights associated with the model, only the
727
+ configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
728
+ """
729
+
730
+ ERNIE_INPUTS_DOCSTRING = r"""
731
+ Args:
732
+ input_ids (`torch.LongTensor` of shape `({0})`):
733
+ Indices of input sequence tokens in the vocabulary.
734
+
735
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
736
+ [`PreTrainedTokenizer.__call__`] for details.
737
+
738
+ [What are input IDs?](../glossary#input-ids)
739
+ attention_mask (`torch.FloatTensor` of shape `({0})`, *optional*):
740
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
741
+
742
+ - 1 for tokens that are **not masked**,
743
+ - 0 for tokens that are **masked**.
744
+
745
+ [What are attention masks?](../glossary#attention-mask)
746
+ token_type_ids (`torch.LongTensor` of shape `({0})`, *optional*):
747
+ Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
748
+ 1]`:
749
+
750
+ - 0 corresponds to a *sentence A* token,
751
+ - 1 corresponds to a *sentence B* token.
752
+
753
+ [What are token type IDs?](../glossary#token-type-ids)
754
+ task_type_ids (`torch.LongTensor` of shape `({0})`, *optional*):
755
+ Task type embedding is a special embedding to represent the characteristic of different tasks, such as
756
+ word-aware pre-training task, structure-aware pre-training task and semantic-aware pre-training task. We
757
+ assign a `task_type_id` to each task and the `task_type_id` is in the range `[0,
758
+ config.task_type_vocab_size-1]
759
+ position_ids (`torch.LongTensor` of shape `({0})`, *optional*):
760
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
761
+ config.max_position_embeddings - 1]`.
762
+
763
+ [What are position IDs?](../glossary#position-ids)
764
+ head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
765
+ Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:
766
+
767
+ - 1 indicates the head is **not masked**,
768
+ - 0 indicates the head is **masked**.
769
+
770
+ inputs_embeds (`torch.FloatTensor` of shape `({0}, hidden_size)`, *optional*):
771
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
772
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
773
+ model's internal embedding lookup matrix.
774
+ output_attentions (`bool`, *optional*):
775
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
776
+ tensors for more detail.
777
+ output_hidden_states (`bool`, *optional*):
778
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
779
+ more detail.
780
+ return_dict (`bool`, *optional*):
781
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
782
+ """
783
+
784
+
785
+ @add_start_docstrings(
786
+ "The bare Ernie Model transformer outputting raw hidden-states without any specific head on top.",
787
+ ERNIE_START_DOCSTRING,
788
+ )
789
+ class ErnieModel(ErniePreTrainedModel):
790
+ """
791
+
792
+ The model can behave as an encoder (with only self-attention) as well as a decoder, in which case a layer of
793
+ cross-attention is added between the self-attention layers, following the architecture described in [Attention is
794
+ all you need](https://arxiv.org/abs/1706.03762) by Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit,
795
+ Llion Jones, Aidan N. Gomez, Lukasz Kaiser and Illia Polosukhin.
796
+
797
+ To behave as an decoder the model needs to be initialized with the `is_decoder` argument of the configuration set
798
+ to `True`. To be used in a Seq2Seq model, the model needs to initialized with both `is_decoder` argument and
799
+ `add_cross_attention` set to `True`; an `encoder_hidden_states` is then expected as an input to the forward pass.
800
+ """
801
+
802
+ # Copied from transformers.models.bert.modeling_bert.BertModel.__init__ with Bert->Ernie
803
+ def __init__(self, config, add_pooling_layer=True):
804
+ super().__init__(config)
805
+ self.config = config
806
+
807
+ self.embeddings = ErnieEmbeddings(config)
808
+ self.encoder = ErnieEncoder(config)
809
+
810
+ self.pooler = ErniePooler(config) if add_pooling_layer else None
811
+
812
+ # Initialize weights and apply final processing
813
+ self.post_init()
814
+
815
+ # Copied from transformers.models.bert.modeling_bert.BertModel.get_input_embeddings
816
+ def get_input_embeddings(self):
817
+ return self.embeddings.word_embeddings
818
+
819
+ # Copied from transformers.models.bert.modeling_bert.BertModel.set_input_embeddings
820
+ def set_input_embeddings(self, value):
821
+ self.embeddings.word_embeddings = value
822
+
823
+ # Copied from transformers.models.bert.modeling_bert.BertModel._prune_heads
824
+ def _prune_heads(self, heads_to_prune):
825
+ """
826
+ Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
827
+ class PreTrainedModel
828
+ """
829
+ for layer, heads in heads_to_prune.items():
830
+ self.encoder.layer[layer].attention.prune_heads(heads)
831
+
832
+ @add_start_docstrings_to_model_forward(ERNIE_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
833
+ @add_code_sample_docstrings(
834
+ checkpoint=_CHECKPOINT_FOR_DOC,
835
+ output_type=BaseModelOutputWithPoolingAndCrossAttentions,
836
+ config_class=_CONFIG_FOR_DOC,
837
+ )
838
+ def forward(
839
+ self,
840
+ input_ids: Optional[torch.Tensor] = None,
841
+ attention_mask: Optional[torch.Tensor] = None,
842
+ token_type_ids: Optional[torch.Tensor] = None,
843
+ task_type_ids: Optional[torch.Tensor] = None,
844
+ position_ids: Optional[torch.Tensor] = None,
845
+ head_mask: Optional[torch.Tensor] = None,
846
+ inputs_embeds: Optional[torch.Tensor] = None,
847
+ encoder_hidden_states: Optional[torch.Tensor] = None,
848
+ encoder_attention_mask: Optional[torch.Tensor] = None,
849
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
850
+ use_cache: Optional[bool] = None,
851
+ output_attentions: Optional[bool] = None,
852
+ output_hidden_states: Optional[bool] = None,
853
+ return_dict: Optional[bool] = None,
854
+ ) -> Union[Tuple[torch.Tensor], BaseModelOutputWithPoolingAndCrossAttentions]:
855
+ r"""
856
+ encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
857
+ Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if
858
+ the model is configured as a decoder.
859
+ encoder_attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
860
+ Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in
861
+ the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`:
862
+
863
+ - 1 for tokens that are **not masked**,
864
+ - 0 for tokens that are **masked**.
865
+ past_key_values (`tuple(tuple(torch.FloatTensor))` of length `config.n_layers` with each tuple having 4 tensors of shape `(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`):
866
+ Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.
867
+
868
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
869
+ don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
870
+ `decoder_input_ids` of shape `(batch_size, sequence_length)`.
871
+ use_cache (`bool`, *optional*):
872
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
873
+ `past_key_values`).
874
+ """
875
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
876
+ output_hidden_states = (
877
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
878
+ )
879
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
880
+
881
+ if self.config.is_decoder:
882
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
883
+ else:
884
+ use_cache = False
885
+
886
+ if input_ids is not None and inputs_embeds is not None:
887
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
888
+ elif input_ids is not None:
889
+ self.warn_if_padding_and_no_attention_mask(input_ids, attention_mask)
890
+ input_shape = input_ids.size()
891
+ elif inputs_embeds is not None:
892
+ input_shape = inputs_embeds.size()[:-1]
893
+ else:
894
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
895
+
896
+ batch_size, seq_length = input_shape
897
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
898
+
899
+ # past_key_values_length
900
+ past_key_values_length = past_key_values[0][0].shape[2] if past_key_values is not None else 0
901
+
902
+ if attention_mask is None:
903
+ attention_mask = torch.ones(((batch_size, seq_length + past_key_values_length)), device=device)
904
+
905
+ if token_type_ids is None:
906
+ if hasattr(self.embeddings, "token_type_ids"):
907
+ buffered_token_type_ids = self.embeddings.token_type_ids[:, :seq_length]
908
+ buffered_token_type_ids_expanded = buffered_token_type_ids.expand(batch_size, seq_length)
909
+ token_type_ids = buffered_token_type_ids_expanded
910
+ else:
911
+ token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=device)
912
+
913
+ # We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length]
914
+ # ourselves in which case we just need to make it broadcastable to all heads.
915
+ extended_attention_mask: torch.Tensor = self.get_extended_attention_mask(attention_mask, input_shape)
916
+
917
+ # If a 2D or 3D attention mask is provided for the cross-attention
918
+ # we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length]
919
+ if self.config.is_decoder and encoder_hidden_states is not None:
920
+ encoder_batch_size, encoder_sequence_length, _ = encoder_hidden_states.size()
921
+ encoder_hidden_shape = (encoder_batch_size, encoder_sequence_length)
922
+ if encoder_attention_mask is None:
923
+ encoder_attention_mask = torch.ones(encoder_hidden_shape, device=device)
924
+ encoder_extended_attention_mask = self.invert_attention_mask(encoder_attention_mask)
925
+ else:
926
+ encoder_extended_attention_mask = None
927
+
928
+ # Prepare head mask if needed
929
+ # 1.0 in head_mask indicate we keep the head
930
+ # attention_probs has shape bsz x n_heads x N x N
931
+ # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]
932
+ # and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]
933
+ head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)
934
+
935
+ embedding_output = self.embeddings(
936
+ input_ids=input_ids,
937
+ position_ids=position_ids,
938
+ token_type_ids=token_type_ids,
939
+ task_type_ids=task_type_ids,
940
+ inputs_embeds=inputs_embeds,
941
+ past_key_values_length=past_key_values_length,
942
+ )
943
+ encoder_outputs = self.encoder(
944
+ embedding_output,
945
+ attention_mask=extended_attention_mask,
946
+ head_mask=head_mask,
947
+ encoder_hidden_states=encoder_hidden_states,
948
+ encoder_attention_mask=encoder_extended_attention_mask,
949
+ past_key_values=past_key_values,
950
+ use_cache=use_cache,
951
+ output_attentions=output_attentions,
952
+ output_hidden_states=output_hidden_states,
953
+ return_dict=return_dict,
954
+ )
955
+ sequence_output = encoder_outputs[0]
956
+ pooled_output = self.pooler(sequence_output) if self.pooler is not None else None
957
+
958
+ if not return_dict:
959
+ return (sequence_output, pooled_output) + encoder_outputs[1:]
960
+
961
+ return BaseModelOutputWithPoolingAndCrossAttentions(
962
+ last_hidden_state=sequence_output,
963
+ pooler_output=pooled_output,
964
+ past_key_values=encoder_outputs.past_key_values,
965
+ hidden_states=encoder_outputs.hidden_states,
966
+ attentions=encoder_outputs.attentions,
967
+ cross_attentions=encoder_outputs.cross_attentions,
968
+ )
969
+
970
+
971
+ @add_start_docstrings(
972
+ """
973
+ Ernie Model with two heads on top as done during the pretraining: a `masked language modeling` head and a `next
974
+ sentence prediction (classification)` head.
975
+ """,
976
+ ERNIE_START_DOCSTRING,
977
+ )
978
+ class ErnieForPreTraining(ErniePreTrainedModel):
979
+ _tied_weights_keys = ["cls.predictions.decoder.bias", "cls.predictions.decoder.weight"]
980
+
981
+ # Copied from transformers.models.bert.modeling_bert.BertForPreTraining.__init__ with Bert->Ernie,bert->ernie
982
+ def __init__(self, config):
983
+ super().__init__(config)
984
+
985
+ self.ernie = ErnieModel(config)
986
+ self.cls = ErniePreTrainingHeads(config)
987
+
988
+ # Initialize weights and apply final processing
989
+ self.post_init()
990
+
991
+ # Copied from transformers.models.bert.modeling_bert.BertForPreTraining.get_output_embeddings
992
+ def get_output_embeddings(self):
993
+ return self.cls.predictions.decoder
994
+
995
+ # Copied from transformers.models.bert.modeling_bert.BertForPreTraining.set_output_embeddings
996
+ def set_output_embeddings(self, new_embeddings):
997
+ self.cls.predictions.decoder = new_embeddings
998
+
999
+ @add_start_docstrings_to_model_forward(ERNIE_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
1000
+ @replace_return_docstrings(output_type=ErnieForPreTrainingOutput, config_class=_CONFIG_FOR_DOC)
1001
+ def forward(
1002
+ self,
1003
+ input_ids: Optional[torch.Tensor] = None,
1004
+ attention_mask: Optional[torch.Tensor] = None,
1005
+ token_type_ids: Optional[torch.Tensor] = None,
1006
+ task_type_ids: Optional[torch.Tensor] = None,
1007
+ position_ids: Optional[torch.Tensor] = None,
1008
+ head_mask: Optional[torch.Tensor] = None,
1009
+ inputs_embeds: Optional[torch.Tensor] = None,
1010
+ labels: Optional[torch.Tensor] = None,
1011
+ next_sentence_label: Optional[torch.Tensor] = None,
1012
+ output_attentions: Optional[bool] = None,
1013
+ output_hidden_states: Optional[bool] = None,
1014
+ return_dict: Optional[bool] = None,
1015
+ ) -> Union[Tuple[torch.Tensor], ErnieForPreTrainingOutput]:
1016
+ r"""
1017
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1018
+ Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
1019
+ config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked),
1020
+ the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
1021
+ next_sentence_label (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1022
+ Labels for computing the next sequence prediction (classification) loss. Input should be a sequence
1023
+ pair (see `input_ids` docstring) Indices should be in `[0, 1]`:
1024
+
1025
+ - 0 indicates sequence B is a continuation of sequence A,
1026
+ - 1 indicates sequence B is a random sequence.
1027
+ kwargs (`Dict[str, any]`, optional, defaults to *{}*):
1028
+ Used to hide legacy arguments that have been deprecated.
1029
+
1030
+ Returns:
1031
+
1032
+ Example:
1033
+
1034
+ ```python
1035
+ >>> from transformers import AutoTokenizer, ErnieForPreTraining
1036
+ >>> import torch
1037
+
1038
+ >>> tokenizer = AutoTokenizer.from_pretrained("nghuyong/ernie-1.0-base-zh")
1039
+ >>> model = ErnieForPreTraining.from_pretrained("nghuyong/ernie-1.0-base-zh")
1040
+
1041
+ >>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")
1042
+ >>> outputs = model(**inputs)
1043
+
1044
+ >>> prediction_logits = outputs.prediction_logits
1045
+ >>> seq_relationship_logits = outputs.seq_relationship_logits
1046
+ ```
1047
+ """
1048
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1049
+
1050
+ outputs = self.ernie(
1051
+ input_ids,
1052
+ attention_mask=attention_mask,
1053
+ token_type_ids=token_type_ids,
1054
+ task_type_ids=task_type_ids,
1055
+ position_ids=position_ids,
1056
+ head_mask=head_mask,
1057
+ inputs_embeds=inputs_embeds,
1058
+ output_attentions=output_attentions,
1059
+ output_hidden_states=output_hidden_states,
1060
+ return_dict=return_dict,
1061
+ )
1062
+
1063
+ sequence_output, pooled_output = outputs[:2]
1064
+ prediction_scores, seq_relationship_score = self.cls(sequence_output, pooled_output)
1065
+
1066
+ total_loss = None
1067
+ if labels is not None and next_sentence_label is not None:
1068
+ loss_fct = CrossEntropyLoss()
1069
+ masked_lm_loss = loss_fct(prediction_scores.view(-1, self.config.vocab_size), labels.view(-1))
1070
+ next_sentence_loss = loss_fct(seq_relationship_score.view(-1, 2), next_sentence_label.view(-1))
1071
+ total_loss = masked_lm_loss + next_sentence_loss
1072
+
1073
+ if not return_dict:
1074
+ output = (prediction_scores, seq_relationship_score) + outputs[2:]
1075
+ return ((total_loss,) + output) if total_loss is not None else output
1076
+
1077
+ return ErnieForPreTrainingOutput(
1078
+ loss=total_loss,
1079
+ prediction_logits=prediction_scores,
1080
+ seq_relationship_logits=seq_relationship_score,
1081
+ hidden_states=outputs.hidden_states,
1082
+ attentions=outputs.attentions,
1083
+ )
1084
+
1085
+
1086
+ @add_start_docstrings(
1087
+ """Ernie Model with a `language modeling` head on top for CLM fine-tuning.""", ERNIE_START_DOCSTRING
1088
+ )
1089
+ class ErnieForCausalLM(ErniePreTrainedModel):
1090
+ _tied_weights_keys = ["cls.predictions.decoder.bias", "cls.predictions.decoder.weight"]
1091
+
1092
+ # Copied from transformers.models.bert.modeling_bert.BertLMHeadModel.__init__ with BertLMHeadModel->ErnieForCausalLM,Bert->Ernie,bert->ernie
1093
+ def __init__(self, config):
1094
+ super().__init__(config)
1095
+
1096
+ if not config.is_decoder:
1097
+ logger.warning("If you want to use `ErnieForCausalLM` as a standalone, add `is_decoder=True.`")
1098
+
1099
+ self.ernie = ErnieModel(config, add_pooling_layer=False)
1100
+ self.cls = ErnieOnlyMLMHead(config)
1101
+
1102
+ # Initialize weights and apply final processing
1103
+ self.post_init()
1104
+
1105
+ # Copied from transformers.models.bert.modeling_bert.BertLMHeadModel.get_output_embeddings
1106
+ def get_output_embeddings(self):
1107
+ return self.cls.predictions.decoder
1108
+
1109
+ # Copied from transformers.models.bert.modeling_bert.BertLMHeadModel.set_output_embeddings
1110
+ def set_output_embeddings(self, new_embeddings):
1111
+ self.cls.predictions.decoder = new_embeddings
1112
+
1113
+ @add_start_docstrings_to_model_forward(ERNIE_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
1114
+ @add_code_sample_docstrings(
1115
+ checkpoint=_CHECKPOINT_FOR_DOC,
1116
+ output_type=CausalLMOutputWithCrossAttentions,
1117
+ config_class=_CONFIG_FOR_DOC,
1118
+ )
1119
+ def forward(
1120
+ self,
1121
+ input_ids: Optional[torch.Tensor] = None,
1122
+ attention_mask: Optional[torch.Tensor] = None,
1123
+ token_type_ids: Optional[torch.Tensor] = None,
1124
+ task_type_ids: Optional[torch.Tensor] = None,
1125
+ position_ids: Optional[torch.Tensor] = None,
1126
+ head_mask: Optional[torch.Tensor] = None,
1127
+ inputs_embeds: Optional[torch.Tensor] = None,
1128
+ encoder_hidden_states: Optional[torch.Tensor] = None,
1129
+ encoder_attention_mask: Optional[torch.Tensor] = None,
1130
+ labels: Optional[torch.Tensor] = None,
1131
+ past_key_values: Optional[List[torch.Tensor]] = None,
1132
+ use_cache: Optional[bool] = None,
1133
+ output_attentions: Optional[bool] = None,
1134
+ output_hidden_states: Optional[bool] = None,
1135
+ return_dict: Optional[bool] = None,
1136
+ ) -> Union[Tuple[torch.Tensor], CausalLMOutputWithCrossAttentions]:
1137
+ r"""
1138
+ encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
1139
+ Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if
1140
+ the model is configured as a decoder.
1141
+ encoder_attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
1142
+ Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in
1143
+ the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`:
1144
+
1145
+ - 1 for tokens that are **not masked**,
1146
+ - 0 for tokens that are **masked**.
1147
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1148
+ Labels for computing the left-to-right language modeling loss (next word prediction). Indices should be in
1149
+ `[-100, 0, ..., config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are
1150
+ ignored (masked), the loss is only computed for the tokens with labels n `[0, ..., config.vocab_size]`
1151
+ past_key_values (`tuple(tuple(torch.FloatTensor))` of length `config.n_layers` with each tuple having 4 tensors of shape `(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`):
1152
+ Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.
1153
+
1154
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
1155
+ don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
1156
+ `decoder_input_ids` of shape `(batch_size, sequence_length)`.
1157
+ use_cache (`bool`, *optional*):
1158
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
1159
+ `past_key_values`).
1160
+ """
1161
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1162
+ if labels is not None:
1163
+ use_cache = False
1164
+
1165
+ outputs = self.ernie(
1166
+ input_ids,
1167
+ attention_mask=attention_mask,
1168
+ token_type_ids=token_type_ids,
1169
+ task_type_ids=task_type_ids,
1170
+ position_ids=position_ids,
1171
+ head_mask=head_mask,
1172
+ inputs_embeds=inputs_embeds,
1173
+ encoder_hidden_states=encoder_hidden_states,
1174
+ encoder_attention_mask=encoder_attention_mask,
1175
+ past_key_values=past_key_values,
1176
+ use_cache=use_cache,
1177
+ output_attentions=output_attentions,
1178
+ output_hidden_states=output_hidden_states,
1179
+ return_dict=return_dict,
1180
+ )
1181
+
1182
+ sequence_output = outputs[0]
1183
+ prediction_scores = self.cls(sequence_output)
1184
+
1185
+ lm_loss = None
1186
+ if labels is not None:
1187
+ # we are doing next-token prediction; shift prediction scores and input ids by one
1188
+ shifted_prediction_scores = prediction_scores[:, :-1, :].contiguous()
1189
+ labels = labels[:, 1:].contiguous()
1190
+ loss_fct = CrossEntropyLoss()
1191
+ lm_loss = loss_fct(shifted_prediction_scores.view(-1, self.config.vocab_size), labels.view(-1))
1192
+
1193
+ if not return_dict:
1194
+ output = (prediction_scores,) + outputs[2:]
1195
+ return ((lm_loss,) + output) if lm_loss is not None else output
1196
+
1197
+ return CausalLMOutputWithCrossAttentions(
1198
+ loss=lm_loss,
1199
+ logits=prediction_scores,
1200
+ past_key_values=outputs.past_key_values,
1201
+ hidden_states=outputs.hidden_states,
1202
+ attentions=outputs.attentions,
1203
+ cross_attentions=outputs.cross_attentions,
1204
+ )
1205
+
1206
+ # Copied from transformers.models.bert.modeling_bert.BertLMHeadModel.prepare_inputs_for_generation
1207
+ def prepare_inputs_for_generation(
1208
+ self, input_ids, past_key_values=None, attention_mask=None, use_cache=True, **model_kwargs
1209
+ ):
1210
+ input_shape = input_ids.shape
1211
+ # if model is used as a decoder in encoder-decoder model, the decoder attention mask is created on the fly
1212
+ if attention_mask is None:
1213
+ attention_mask = input_ids.new_ones(input_shape)
1214
+
1215
+ # cut decoder_input_ids if past_key_values is used
1216
+ if past_key_values is not None:
1217
+ past_length = past_key_values[0][0].shape[2]
1218
+
1219
+ # Some generation methods already pass only the last input ID
1220
+ if input_ids.shape[1] > past_length:
1221
+ remove_prefix_length = past_length
1222
+ else:
1223
+ # Default to old behavior: keep only final ID
1224
+ remove_prefix_length = input_ids.shape[1] - 1
1225
+
1226
+ input_ids = input_ids[:, remove_prefix_length:]
1227
+
1228
+ return {
1229
+ "input_ids": input_ids,
1230
+ "attention_mask": attention_mask,
1231
+ "past_key_values": past_key_values,
1232
+ "use_cache": use_cache,
1233
+ }
1234
+
1235
+ # Copied from transformers.models.bert.modeling_bert.BertLMHeadModel._reorder_cache
1236
+ def _reorder_cache(self, past_key_values, beam_idx):
1237
+ reordered_past = ()
1238
+ for layer_past in past_key_values:
1239
+ reordered_past += (
1240
+ tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
1241
+ )
1242
+ return reordered_past
1243
+
1244
+
1245
+ @add_start_docstrings("""Ernie Model with a `language modeling` head on top.""", ERNIE_START_DOCSTRING)
1246
+ class ErnieForMaskedLM(ErniePreTrainedModel):
1247
+ _tied_weights_keys = ["cls.predictions.decoder.bias", "cls.predictions.decoder.weight"]
1248
+
1249
+ # Copied from transformers.models.bert.modeling_bert.BertForMaskedLM.__init__ with Bert->Ernie,bert->ernie
1250
+ def __init__(self, config):
1251
+ super().__init__(config)
1252
+
1253
+ if config.is_decoder:
1254
+ logger.warning(
1255
+ "If you want to use `ErnieForMaskedLM` make sure `config.is_decoder=False` for "
1256
+ "bi-directional self-attention."
1257
+ )
1258
+
1259
+ self.ernie = ErnieModel(config, add_pooling_layer=False)
1260
+ self.cls = ErnieOnlyMLMHead(config)
1261
+
1262
+ # Initialize weights and apply final processing
1263
+ self.post_init()
1264
+
1265
+ # Copied from transformers.models.bert.modeling_bert.BertForMaskedLM.get_output_embeddings
1266
+ def get_output_embeddings(self):
1267
+ return self.cls.predictions.decoder
1268
+
1269
+ # Copied from transformers.models.bert.modeling_bert.BertForMaskedLM.set_output_embeddings
1270
+ def set_output_embeddings(self, new_embeddings):
1271
+ self.cls.predictions.decoder = new_embeddings
1272
+
1273
+ @add_start_docstrings_to_model_forward(ERNIE_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
1274
+ @add_code_sample_docstrings(
1275
+ checkpoint=_CHECKPOINT_FOR_DOC,
1276
+ output_type=MaskedLMOutput,
1277
+ config_class=_CONFIG_FOR_DOC,
1278
+ expected_output="'paris'",
1279
+ expected_loss=0.88,
1280
+ )
1281
+ def forward(
1282
+ self,
1283
+ input_ids: Optional[torch.Tensor] = None,
1284
+ attention_mask: Optional[torch.Tensor] = None,
1285
+ token_type_ids: Optional[torch.Tensor] = None,
1286
+ task_type_ids: Optional[torch.Tensor] = None,
1287
+ position_ids: Optional[torch.Tensor] = None,
1288
+ head_mask: Optional[torch.Tensor] = None,
1289
+ inputs_embeds: Optional[torch.Tensor] = None,
1290
+ encoder_hidden_states: Optional[torch.Tensor] = None,
1291
+ encoder_attention_mask: Optional[torch.Tensor] = None,
1292
+ labels: Optional[torch.Tensor] = None,
1293
+ output_attentions: Optional[bool] = None,
1294
+ output_hidden_states: Optional[bool] = None,
1295
+ return_dict: Optional[bool] = None,
1296
+ ) -> Union[Tuple[torch.Tensor], MaskedLMOutput]:
1297
+ r"""
1298
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1299
+ Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
1300
+ config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the
1301
+ loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
1302
+ """
1303
+
1304
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1305
+
1306
+ outputs = self.ernie(
1307
+ input_ids,
1308
+ attention_mask=attention_mask,
1309
+ token_type_ids=token_type_ids,
1310
+ task_type_ids=task_type_ids,
1311
+ position_ids=position_ids,
1312
+ head_mask=head_mask,
1313
+ inputs_embeds=inputs_embeds,
1314
+ encoder_hidden_states=encoder_hidden_states,
1315
+ encoder_attention_mask=encoder_attention_mask,
1316
+ output_attentions=output_attentions,
1317
+ output_hidden_states=output_hidden_states,
1318
+ return_dict=return_dict,
1319
+ )
1320
+
1321
+ sequence_output = outputs[0]
1322
+ prediction_scores = self.cls(sequence_output)
1323
+
1324
+ masked_lm_loss = None
1325
+ if labels is not None:
1326
+ loss_fct = CrossEntropyLoss() # -100 index = padding token
1327
+ masked_lm_loss = loss_fct(prediction_scores.view(-1, self.config.vocab_size), labels.view(-1))
1328
+
1329
+ if not return_dict:
1330
+ output = (prediction_scores,) + outputs[2:]
1331
+ return ((masked_lm_loss,) + output) if masked_lm_loss is not None else output
1332
+
1333
+ return MaskedLMOutput(
1334
+ loss=masked_lm_loss,
1335
+ logits=prediction_scores,
1336
+ hidden_states=outputs.hidden_states,
1337
+ attentions=outputs.attentions,
1338
+ )
1339
+
1340
+ # Copied from transformers.models.bert.modeling_bert.BertForMaskedLM.prepare_inputs_for_generation
1341
+ def prepare_inputs_for_generation(self, input_ids, attention_mask=None, **model_kwargs):
1342
+ input_shape = input_ids.shape
1343
+ effective_batch_size = input_shape[0]
1344
+
1345
+ # add a dummy token
1346
+ if self.config.pad_token_id is None:
1347
+ raise ValueError("The PAD token should be defined for generation")
1348
+
1349
+ attention_mask = torch.cat([attention_mask, attention_mask.new_zeros((attention_mask.shape[0], 1))], dim=-1)
1350
+ dummy_token = torch.full(
1351
+ (effective_batch_size, 1), self.config.pad_token_id, dtype=torch.long, device=input_ids.device
1352
+ )
1353
+ input_ids = torch.cat([input_ids, dummy_token], dim=1)
1354
+
1355
+ return {"input_ids": input_ids, "attention_mask": attention_mask}
1356
+
1357
+
1358
+ @add_start_docstrings(
1359
+ """Ernie Model with a `next sentence prediction (classification)` head on top.""",
1360
+ ERNIE_START_DOCSTRING,
1361
+ )
1362
+ class ErnieForNextSentencePrediction(ErniePreTrainedModel):
1363
+ # Copied from transformers.models.bert.modeling_bert.BertForNextSentencePrediction.__init__ with Bert->Ernie,bert->ernie
1364
+ def __init__(self, config):
1365
+ super().__init__(config)
1366
+
1367
+ self.ernie = ErnieModel(config)
1368
+ self.cls = ErnieOnlyNSPHead(config)
1369
+
1370
+ # Initialize weights and apply final processing
1371
+ self.post_init()
1372
+
1373
+ @add_start_docstrings_to_model_forward(ERNIE_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
1374
+ @replace_return_docstrings(output_type=NextSentencePredictorOutput, config_class=_CONFIG_FOR_DOC)
1375
+ def forward(
1376
+ self,
1377
+ input_ids: Optional[torch.Tensor] = None,
1378
+ attention_mask: Optional[torch.Tensor] = None,
1379
+ token_type_ids: Optional[torch.Tensor] = None,
1380
+ task_type_ids: Optional[torch.Tensor] = None,
1381
+ position_ids: Optional[torch.Tensor] = None,
1382
+ head_mask: Optional[torch.Tensor] = None,
1383
+ inputs_embeds: Optional[torch.Tensor] = None,
1384
+ labels: Optional[torch.Tensor] = None,
1385
+ output_attentions: Optional[bool] = None,
1386
+ output_hidden_states: Optional[bool] = None,
1387
+ return_dict: Optional[bool] = None,
1388
+ **kwargs,
1389
+ ) -> Union[Tuple[torch.Tensor], NextSentencePredictorOutput]:
1390
+ r"""
1391
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1392
+ Labels for computing the next sequence prediction (classification) loss. Input should be a sequence pair
1393
+ (see `input_ids` docstring). Indices should be in `[0, 1]`:
1394
+
1395
+ - 0 indicates sequence B is a continuation of sequence A,
1396
+ - 1 indicates sequence B is a random sequence.
1397
+
1398
+ Returns:
1399
+
1400
+ Example:
1401
+
1402
+ ```python
1403
+ >>> from transformers import AutoTokenizer, ErnieForNextSentencePrediction
1404
+ >>> import torch
1405
+
1406
+ >>> tokenizer = AutoTokenizer.from_pretrained("nghuyong/ernie-1.0-base-zh")
1407
+ >>> model = ErnieForNextSentencePrediction.from_pretrained("nghuyong/ernie-1.0-base-zh")
1408
+
1409
+ >>> prompt = "In Italy, pizza served in formal settings, such as at a restaurant, is presented unsliced."
1410
+ >>> next_sentence = "The sky is blue due to the shorter wavelength of blue light."
1411
+ >>> encoding = tokenizer(prompt, next_sentence, return_tensors="pt")
1412
+
1413
+ >>> outputs = model(**encoding, labels=torch.LongTensor([1]))
1414
+ >>> logits = outputs.logits
1415
+ >>> assert logits[0, 0] < logits[0, 1] # next sentence was random
1416
+ ```
1417
+ """
1418
+
1419
+ if "next_sentence_label" in kwargs:
1420
+ warnings.warn(
1421
+ "The `next_sentence_label` argument is deprecated and will be removed in a future version, use"
1422
+ " `labels` instead.",
1423
+ FutureWarning,
1424
+ )
1425
+ labels = kwargs.pop("next_sentence_label")
1426
+
1427
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1428
+
1429
+ outputs = self.ernie(
1430
+ input_ids,
1431
+ attention_mask=attention_mask,
1432
+ token_type_ids=token_type_ids,
1433
+ task_type_ids=task_type_ids,
1434
+ position_ids=position_ids,
1435
+ head_mask=head_mask,
1436
+ inputs_embeds=inputs_embeds,
1437
+ output_attentions=output_attentions,
1438
+ output_hidden_states=output_hidden_states,
1439
+ return_dict=return_dict,
1440
+ )
1441
+
1442
+ pooled_output = outputs[1]
1443
+
1444
+ seq_relationship_scores = self.cls(pooled_output)
1445
+
1446
+ next_sentence_loss = None
1447
+ if labels is not None:
1448
+ loss_fct = CrossEntropyLoss()
1449
+ next_sentence_loss = loss_fct(seq_relationship_scores.view(-1, 2), labels.view(-1))
1450
+
1451
+ if not return_dict:
1452
+ output = (seq_relationship_scores,) + outputs[2:]
1453
+ return ((next_sentence_loss,) + output) if next_sentence_loss is not None else output
1454
+
1455
+ return NextSentencePredictorOutput(
1456
+ loss=next_sentence_loss,
1457
+ logits=seq_relationship_scores,
1458
+ hidden_states=outputs.hidden_states,
1459
+ attentions=outputs.attentions,
1460
+ )
1461
+
1462
+
1463
+ @add_start_docstrings(
1464
+ """
1465
+ Ernie Model transformer with a sequence classification/regression head on top (a linear layer on top of the pooled
1466
+ output) e.g. for GLUE tasks.
1467
+ """,
1468
+ ERNIE_START_DOCSTRING,
1469
+ )
1470
+ class ErnieForSequenceClassification(ErniePreTrainedModel):
1471
+ # Copied from transformers.models.bert.modeling_bert.BertForSequenceClassification.__init__ with Bert->Ernie,bert->ernie
1472
+ def __init__(self, config):
1473
+ super().__init__(config)
1474
+ self.num_labels = config.num_labels
1475
+ self.config = config
1476
+
1477
+ self.ernie = ErnieModel(config)
1478
+ classifier_dropout = (
1479
+ config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob
1480
+ )
1481
+ self.dropout = nn.Dropout(classifier_dropout)
1482
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels)
1483
+
1484
+ # Initialize weights and apply final processing
1485
+ self.post_init()
1486
+
1487
+ @add_start_docstrings_to_model_forward(ERNIE_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
1488
+ def forward(
1489
+ self,
1490
+ input_ids: Optional[torch.Tensor] = None,
1491
+ attention_mask: Optional[torch.Tensor] = None,
1492
+ token_type_ids: Optional[torch.Tensor] = None,
1493
+ task_type_ids: Optional[torch.Tensor] = None,
1494
+ position_ids: Optional[torch.Tensor] = None,
1495
+ head_mask: Optional[torch.Tensor] = None,
1496
+ inputs_embeds: Optional[torch.Tensor] = None,
1497
+ labels: Optional[torch.Tensor] = None,
1498
+ output_attentions: Optional[bool] = None,
1499
+ output_hidden_states: Optional[bool] = None,
1500
+ return_dict: Optional[bool] = None,
1501
+ ) -> Union[Tuple[torch.Tensor], SequenceClassifierOutput]:
1502
+ r"""
1503
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1504
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1505
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1506
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1507
+ """
1508
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1509
+
1510
+ outputs = self.ernie(
1511
+ input_ids,
1512
+ attention_mask=attention_mask,
1513
+ token_type_ids=token_type_ids,
1514
+ task_type_ids=task_type_ids,
1515
+ position_ids=position_ids,
1516
+ head_mask=head_mask,
1517
+ inputs_embeds=inputs_embeds,
1518
+ output_attentions=output_attentions,
1519
+ output_hidden_states=output_hidden_states,
1520
+ return_dict=return_dict,
1521
+ )
1522
+
1523
+ pooled_output = outputs[1]
1524
+
1525
+ pooled_output = self.dropout(pooled_output)
1526
+ logits = self.classifier(pooled_output)
1527
+
1528
+ loss = None
1529
+ if labels is not None:
1530
+ if self.config.problem_type is None:
1531
+ if self.num_labels == 1:
1532
+ self.config.problem_type = "regression"
1533
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1534
+ self.config.problem_type = "single_label_classification"
1535
+ else:
1536
+ self.config.problem_type = "multi_label_classification"
1537
+
1538
+ if self.config.problem_type == "regression":
1539
+ loss_fct = MSELoss()
1540
+ if self.num_labels == 1:
1541
+ loss = loss_fct(logits.squeeze(), labels.squeeze())
1542
+ else:
1543
+ loss = loss_fct(logits, labels)
1544
+ elif self.config.problem_type == "single_label_classification":
1545
+ loss_fct = CrossEntropyLoss()
1546
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
1547
+ elif self.config.problem_type == "multi_label_classification":
1548
+ loss_fct = BCEWithLogitsLoss()
1549
+ loss = loss_fct(logits, labels)
1550
+ if not return_dict:
1551
+ output = (logits,) + outputs[2:]
1552
+ return ((loss,) + output) if loss is not None else output
1553
+
1554
+ return SequenceClassifierOutput(
1555
+ loss=loss,
1556
+ logits=logits,
1557
+ hidden_states=outputs.hidden_states,
1558
+ attentions=outputs.attentions,
1559
+ )
1560
+
1561
+
1562
+ @add_start_docstrings(
1563
+ """
1564
+ Ernie Model with a multiple choice classification head on top (a linear layer on top of the pooled output and a
1565
+ softmax) e.g. for RocStories/SWAG tasks.
1566
+ """,
1567
+ ERNIE_START_DOCSTRING,
1568
+ )
1569
+ class ErnieForMultipleChoice(ErniePreTrainedModel):
1570
+ # Copied from transformers.models.bert.modeling_bert.BertForMultipleChoice.__init__ with Bert->Ernie,bert->ernie
1571
+ def __init__(self, config):
1572
+ super().__init__(config)
1573
+
1574
+ self.ernie = ErnieModel(config)
1575
+ classifier_dropout = (
1576
+ config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob
1577
+ )
1578
+ self.dropout = nn.Dropout(classifier_dropout)
1579
+ self.classifier = nn.Linear(config.hidden_size, 1)
1580
+
1581
+ # Initialize weights and apply final processing
1582
+ self.post_init()
1583
+
1584
+ @add_start_docstrings_to_model_forward(ERNIE_INPUTS_DOCSTRING.format("batch_size, num_choices, sequence_length"))
1585
+ @add_code_sample_docstrings(
1586
+ checkpoint=_CHECKPOINT_FOR_DOC,
1587
+ output_type=MultipleChoiceModelOutput,
1588
+ config_class=_CONFIG_FOR_DOC,
1589
+ )
1590
+ def forward(
1591
+ self,
1592
+ input_ids: Optional[torch.Tensor] = None,
1593
+ attention_mask: Optional[torch.Tensor] = None,
1594
+ token_type_ids: Optional[torch.Tensor] = None,
1595
+ task_type_ids: Optional[torch.Tensor] = None,
1596
+ position_ids: Optional[torch.Tensor] = None,
1597
+ head_mask: Optional[torch.Tensor] = None,
1598
+ inputs_embeds: Optional[torch.Tensor] = None,
1599
+ labels: Optional[torch.Tensor] = None,
1600
+ output_attentions: Optional[bool] = None,
1601
+ output_hidden_states: Optional[bool] = None,
1602
+ return_dict: Optional[bool] = None,
1603
+ ) -> Union[Tuple[torch.Tensor], MultipleChoiceModelOutput]:
1604
+ r"""
1605
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1606
+ Labels for computing the multiple choice classification loss. Indices should be in `[0, ...,
1607
+ num_choices-1]` where `num_choices` is the size of the second dimension of the input tensors. (See
1608
+ `input_ids` above)
1609
+ """
1610
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1611
+ num_choices = input_ids.shape[1] if input_ids is not None else inputs_embeds.shape[1]
1612
+
1613
+ input_ids = input_ids.view(-1, input_ids.size(-1)) if input_ids is not None else None
1614
+ attention_mask = attention_mask.view(-1, attention_mask.size(-1)) if attention_mask is not None else None
1615
+ token_type_ids = token_type_ids.view(-1, token_type_ids.size(-1)) if token_type_ids is not None else None
1616
+ position_ids = position_ids.view(-1, position_ids.size(-1)) if position_ids is not None else None
1617
+ inputs_embeds = (
1618
+ inputs_embeds.view(-1, inputs_embeds.size(-2), inputs_embeds.size(-1))
1619
+ if inputs_embeds is not None
1620
+ else None
1621
+ )
1622
+
1623
+ outputs = self.ernie(
1624
+ input_ids,
1625
+ attention_mask=attention_mask,
1626
+ token_type_ids=token_type_ids,
1627
+ task_type_ids=task_type_ids,
1628
+ position_ids=position_ids,
1629
+ head_mask=head_mask,
1630
+ inputs_embeds=inputs_embeds,
1631
+ output_attentions=output_attentions,
1632
+ output_hidden_states=output_hidden_states,
1633
+ return_dict=return_dict,
1634
+ )
1635
+
1636
+ pooled_output = outputs[1]
1637
+
1638
+ pooled_output = self.dropout(pooled_output)
1639
+ logits = self.classifier(pooled_output)
1640
+ reshaped_logits = logits.view(-1, num_choices)
1641
+
1642
+ loss = None
1643
+ if labels is not None:
1644
+ loss_fct = CrossEntropyLoss()
1645
+ loss = loss_fct(reshaped_logits, labels)
1646
+
1647
+ if not return_dict:
1648
+ output = (reshaped_logits,) + outputs[2:]
1649
+ return ((loss,) + output) if loss is not None else output
1650
+
1651
+ return MultipleChoiceModelOutput(
1652
+ loss=loss,
1653
+ logits=reshaped_logits,
1654
+ hidden_states=outputs.hidden_states,
1655
+ attentions=outputs.attentions,
1656
+ )
1657
+
1658
+
1659
+ @add_start_docstrings(
1660
+ """
1661
+ Ernie Model with a token classification head on top (a linear layer on top of the hidden-states output) e.g. for
1662
+ Named-Entity-Recognition (NER) tasks.
1663
+ """,
1664
+ ERNIE_START_DOCSTRING,
1665
+ )
1666
+ class ErnieForTokenClassification(ErniePreTrainedModel):
1667
+ # Copied from transformers.models.bert.modeling_bert.BertForTokenClassification.__init__ with Bert->Ernie,bert->ernie
1668
+ def __init__(self, config):
1669
+ super().__init__(config)
1670
+ self.num_labels = config.num_labels
1671
+
1672
+ self.ernie = ErnieModel(config, add_pooling_layer=False)
1673
+ classifier_dropout = (
1674
+ config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob
1675
+ )
1676
+ self.dropout = nn.Dropout(classifier_dropout)
1677
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels)
1678
+
1679
+ # Initialize weights and apply final processing
1680
+ self.post_init()
1681
+
1682
+ @add_start_docstrings_to_model_forward(ERNIE_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
1683
+ def forward(
1684
+ self,
1685
+ input_ids: Optional[torch.Tensor] = None,
1686
+ attention_mask: Optional[torch.Tensor] = None,
1687
+ token_type_ids: Optional[torch.Tensor] = None,
1688
+ task_type_ids: Optional[torch.Tensor] = None,
1689
+ position_ids: Optional[torch.Tensor] = None,
1690
+ head_mask: Optional[torch.Tensor] = None,
1691
+ inputs_embeds: Optional[torch.Tensor] = None,
1692
+ labels: Optional[torch.Tensor] = None,
1693
+ output_attentions: Optional[bool] = None,
1694
+ output_hidden_states: Optional[bool] = None,
1695
+ return_dict: Optional[bool] = None,
1696
+ ) -> Union[Tuple[torch.Tensor], TokenClassifierOutput]:
1697
+ r"""
1698
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1699
+ Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`.
1700
+ """
1701
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1702
+
1703
+ outputs = self.ernie(
1704
+ input_ids,
1705
+ attention_mask=attention_mask,
1706
+ token_type_ids=token_type_ids,
1707
+ task_type_ids=task_type_ids,
1708
+ position_ids=position_ids,
1709
+ head_mask=head_mask,
1710
+ inputs_embeds=inputs_embeds,
1711
+ output_attentions=output_attentions,
1712
+ output_hidden_states=output_hidden_states,
1713
+ return_dict=return_dict,
1714
+ )
1715
+
1716
+ sequence_output = outputs[0]
1717
+
1718
+ sequence_output = self.dropout(sequence_output)
1719
+ logits = self.classifier(sequence_output)
1720
+
1721
+ loss = None
1722
+ if labels is not None:
1723
+ loss_fct = CrossEntropyLoss()
1724
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
1725
+
1726
+ if not return_dict:
1727
+ output = (logits,) + outputs[2:]
1728
+ return ((loss,) + output) if loss is not None else output
1729
+
1730
+ return TokenClassifierOutput(
1731
+ loss=loss,
1732
+ logits=logits,
1733
+ hidden_states=outputs.hidden_states,
1734
+ attentions=outputs.attentions,
1735
+ )
1736
+
1737
+
1738
+ @add_start_docstrings(
1739
+ """
1740
+ Ernie Model with a span classification head on top for extractive question-answering tasks like SQuAD (a linear
1741
+ layers on top of the hidden-states output to compute `span start logits` and `span end logits`).
1742
+ """,
1743
+ ERNIE_START_DOCSTRING,
1744
+ )
1745
+ class ErnieForQuestionAnswering(ErniePreTrainedModel):
1746
+ # Copied from transformers.models.bert.modeling_bert.BertForQuestionAnswering.__init__ with Bert->Ernie,bert->ernie
1747
+ def __init__(self, config):
1748
+ super().__init__(config)
1749
+ self.num_labels = config.num_labels
1750
+
1751
+ self.ernie = ErnieModel(config, add_pooling_layer=False)
1752
+ self.qa_outputs = nn.Linear(config.hidden_size, config.num_labels)
1753
+
1754
+ # Initialize weights and apply final processing
1755
+ self.post_init()
1756
+
1757
+ @add_start_docstrings_to_model_forward(ERNIE_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
1758
+ def forward(
1759
+ self,
1760
+ input_ids: Optional[torch.Tensor] = None,
1761
+ attention_mask: Optional[torch.Tensor] = None,
1762
+ token_type_ids: Optional[torch.Tensor] = None,
1763
+ task_type_ids: Optional[torch.Tensor] = None,
1764
+ position_ids: Optional[torch.Tensor] = None,
1765
+ head_mask: Optional[torch.Tensor] = None,
1766
+ inputs_embeds: Optional[torch.Tensor] = None,
1767
+ start_positions: Optional[torch.Tensor] = None,
1768
+ end_positions: Optional[torch.Tensor] = None,
1769
+ output_attentions: Optional[bool] = None,
1770
+ output_hidden_states: Optional[bool] = None,
1771
+ return_dict: Optional[bool] = None,
1772
+ ) -> Union[Tuple[torch.Tensor], QuestionAnsweringModelOutput]:
1773
+ r"""
1774
+ start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1775
+ Labels for position (index) of the start of the labelled span for computing the token classification loss.
1776
+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
1777
+ are not taken into account for computing the loss.
1778
+ end_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1779
+ Labels for position (index) of the end of the labelled span for computing the token classification loss.
1780
+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
1781
+ are not taken into account for computing the loss.
1782
+ """
1783
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1784
+
1785
+ outputs = self.ernie(
1786
+ input_ids,
1787
+ attention_mask=attention_mask,
1788
+ token_type_ids=token_type_ids,
1789
+ task_type_ids=task_type_ids,
1790
+ position_ids=position_ids,
1791
+ head_mask=head_mask,
1792
+ inputs_embeds=inputs_embeds,
1793
+ output_attentions=output_attentions,
1794
+ output_hidden_states=output_hidden_states,
1795
+ return_dict=return_dict,
1796
+ )
1797
+
1798
+ sequence_output = outputs[0]
1799
+
1800
+ logits = self.qa_outputs(sequence_output)
1801
+ start_logits, end_logits = logits.split(1, dim=-1)
1802
+ start_logits = start_logits.squeeze(-1).contiguous()
1803
+ end_logits = end_logits.squeeze(-1).contiguous()
1804
+
1805
+ total_loss = None
1806
+ if start_positions is not None and end_positions is not None:
1807
+ # If we are on multi-GPU, split add a dimension
1808
+ if len(start_positions.size()) > 1:
1809
+ start_positions = start_positions.squeeze(-1)
1810
+ if len(end_positions.size()) > 1:
1811
+ end_positions = end_positions.squeeze(-1)
1812
+ # sometimes the start/end positions are outside our model inputs, we ignore these terms
1813
+ ignored_index = start_logits.size(1)
1814
+ start_positions = start_positions.clamp(0, ignored_index)
1815
+ end_positions = end_positions.clamp(0, ignored_index)
1816
+
1817
+ loss_fct = CrossEntropyLoss(ignore_index=ignored_index)
1818
+ start_loss = loss_fct(start_logits, start_positions)
1819
+ end_loss = loss_fct(end_logits, end_positions)
1820
+ total_loss = (start_loss + end_loss) / 2
1821
+
1822
+ if not return_dict:
1823
+ output = (start_logits, end_logits) + outputs[2:]
1824
+ return ((total_loss,) + output) if total_loss is not None else output
1825
+
1826
+ return QuestionAnsweringModelOutput(
1827
+ loss=total_loss,
1828
+ start_logits=start_logits,
1829
+ end_logits=end_logits,
1830
+ hidden_states=outputs.hidden_states,
1831
+ attentions=outputs.attentions,
1832
+ )
env-llmeval/lib/python3.10/site-packages/transformers/models/fastspeech2_conformer/__init__.py ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 The HuggingFace Team. All rights reserved.
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 typing import TYPE_CHECKING
15
+
16
+ from ...utils import (
17
+ OptionalDependencyNotAvailable,
18
+ _LazyModule,
19
+ is_torch_available,
20
+ )
21
+
22
+
23
+ _import_structure = {
24
+ "configuration_fastspeech2_conformer": [
25
+ "FASTSPEECH2_CONFORMER_HIFIGAN_PRETRAINED_CONFIG_ARCHIVE_MAP",
26
+ "FASTSPEECH2_CONFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP",
27
+ "FASTSPEECH2_CONFORMER_WITH_HIFIGAN_PRETRAINED_CONFIG_ARCHIVE_MAP",
28
+ "FastSpeech2ConformerConfig",
29
+ "FastSpeech2ConformerHifiGanConfig",
30
+ "FastSpeech2ConformerWithHifiGanConfig",
31
+ ],
32
+ "tokenization_fastspeech2_conformer": ["FastSpeech2ConformerTokenizer"],
33
+ }
34
+
35
+ try:
36
+ if not is_torch_available():
37
+ raise OptionalDependencyNotAvailable()
38
+ except OptionalDependencyNotAvailable:
39
+ pass
40
+ else:
41
+ _import_structure["modeling_fastspeech2_conformer"] = [
42
+ "FASTSPEECH2_CONFORMER_PRETRAINED_MODEL_ARCHIVE_LIST",
43
+ "FastSpeech2ConformerWithHifiGan",
44
+ "FastSpeech2ConformerHifiGan",
45
+ "FastSpeech2ConformerModel",
46
+ "FastSpeech2ConformerPreTrainedModel",
47
+ ]
48
+
49
+ if TYPE_CHECKING:
50
+ from .configuration_fastspeech2_conformer import (
51
+ FASTSPEECH2_CONFORMER_HIFIGAN_PRETRAINED_CONFIG_ARCHIVE_MAP,
52
+ FASTSPEECH2_CONFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP,
53
+ FASTSPEECH2_CONFORMER_WITH_HIFIGAN_PRETRAINED_CONFIG_ARCHIVE_MAP,
54
+ FastSpeech2ConformerConfig,
55
+ FastSpeech2ConformerHifiGanConfig,
56
+ FastSpeech2ConformerWithHifiGanConfig,
57
+ )
58
+ from .tokenization_fastspeech2_conformer import FastSpeech2ConformerTokenizer
59
+
60
+ try:
61
+ if not is_torch_available():
62
+ raise OptionalDependencyNotAvailable()
63
+ except OptionalDependencyNotAvailable:
64
+ pass
65
+ else:
66
+ from .modeling_fastspeech2_conformer import (
67
+ FASTSPEECH2_CONFORMER_PRETRAINED_MODEL_ARCHIVE_LIST,
68
+ FastSpeech2ConformerHifiGan,
69
+ FastSpeech2ConformerModel,
70
+ FastSpeech2ConformerPreTrainedModel,
71
+ FastSpeech2ConformerWithHifiGan,
72
+ )
73
+
74
+ else:
75
+ import sys
76
+
77
+ sys.modules[__name__] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
env-llmeval/lib/python3.10/site-packages/transformers/models/fastspeech2_conformer/__pycache__/configuration_fastspeech2_conformer.cpython-310.pyc ADDED
Binary file (20.8 kB). View file
 
env-llmeval/lib/python3.10/site-packages/transformers/models/fastspeech2_conformer/__pycache__/convert_fastspeech2_conformer_original_pytorch_checkpoint_to_pytorch.cpython-310.pyc ADDED
Binary file (6.49 kB). View file