ZTWHHH commited on
Commit
2f1cd2c
·
verified ·
1 Parent(s): 1fdac67

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. pllava/lib/python3.10/site-packages/transformers/generation/__init__.py +304 -0
  2. pllava/lib/python3.10/site-packages/transformers/generation/flax_utils.py +1020 -0
  3. pllava/lib/python3.10/site-packages/transformers/generation/logits_process.py +0 -0
  4. pllava/lib/python3.10/site-packages/transformers/generation/stopping_criteria.py +151 -0
  5. pllava/lib/python3.10/site-packages/transformers/models/beit/__init__.py +112 -0
  6. pllava/lib/python3.10/site-packages/transformers/models/beit/__pycache__/__init__.cpython-310.pyc +0 -0
  7. pllava/lib/python3.10/site-packages/transformers/models/beit/__pycache__/configuration_beit.cpython-310.pyc +0 -0
  8. pllava/lib/python3.10/site-packages/transformers/models/beit/__pycache__/convert_beit_unilm_to_pytorch.cpython-310.pyc +0 -0
  9. pllava/lib/python3.10/site-packages/transformers/models/beit/__pycache__/feature_extraction_beit.cpython-310.pyc +0 -0
  10. pllava/lib/python3.10/site-packages/transformers/models/beit/__pycache__/image_processing_beit.cpython-310.pyc +0 -0
  11. pllava/lib/python3.10/site-packages/transformers/models/beit/__pycache__/modeling_beit.cpython-310.pyc +0 -0
  12. pllava/lib/python3.10/site-packages/transformers/models/beit/__pycache__/modeling_flax_beit.cpython-310.pyc +0 -0
  13. pllava/lib/python3.10/site-packages/transformers/models/beit/configuration_beit.py +235 -0
  14. pllava/lib/python3.10/site-packages/transformers/models/beit/convert_beit_unilm_to_pytorch.py +374 -0
  15. pllava/lib/python3.10/site-packages/transformers/models/beit/feature_extraction_beit.py +33 -0
  16. pllava/lib/python3.10/site-packages/transformers/models/beit/image_processing_beit.py +505 -0
  17. pllava/lib/python3.10/site-packages/transformers/models/beit/modeling_beit.py +1427 -0
  18. pllava/lib/python3.10/site-packages/transformers/models/beit/modeling_flax_beit.py +948 -0
  19. pllava/lib/python3.10/site-packages/transformers/models/convbert/__init__.py +130 -0
  20. pllava/lib/python3.10/site-packages/transformers/models/convbert/__pycache__/__init__.cpython-310.pyc +0 -0
  21. pllava/lib/python3.10/site-packages/transformers/models/convbert/__pycache__/configuration_convbert.cpython-310.pyc +0 -0
  22. pllava/lib/python3.10/site-packages/transformers/models/convbert/__pycache__/convert_convbert_original_tf1_checkpoint_to_pytorch_and_tf2.cpython-310.pyc +0 -0
  23. pllava/lib/python3.10/site-packages/transformers/models/convbert/__pycache__/modeling_convbert.cpython-310.pyc +0 -0
  24. pllava/lib/python3.10/site-packages/transformers/models/convbert/__pycache__/modeling_tf_convbert.cpython-310.pyc +0 -0
  25. pllava/lib/python3.10/site-packages/transformers/models/convbert/__pycache__/tokenization_convbert.cpython-310.pyc +0 -0
  26. pllava/lib/python3.10/site-packages/transformers/models/convbert/__pycache__/tokenization_convbert_fast.cpython-310.pyc +0 -0
  27. pllava/lib/python3.10/site-packages/transformers/models/convbert/configuration_convbert.py +166 -0
  28. pllava/lib/python3.10/site-packages/transformers/models/convbert/convert_convbert_original_tf1_checkpoint_to_pytorch_and_tf2.py +57 -0
  29. pllava/lib/python3.10/site-packages/transformers/models/convbert/modeling_convbert.py +1341 -0
  30. pllava/lib/python3.10/site-packages/transformers/models/convbert/modeling_tf_convbert.py +1471 -0
  31. pllava/lib/python3.10/site-packages/transformers/models/convbert/tokenization_convbert.py +529 -0
  32. pllava/lib/python3.10/site-packages/transformers/models/convbert/tokenization_convbert_fast.py +198 -0
  33. pllava/lib/python3.10/site-packages/transformers/models/electra/__init__.py +168 -0
  34. pllava/lib/python3.10/site-packages/transformers/models/electra/__pycache__/__init__.cpython-310.pyc +0 -0
  35. pllava/lib/python3.10/site-packages/transformers/models/electra/__pycache__/configuration_electra.cpython-310.pyc +0 -0
  36. pllava/lib/python3.10/site-packages/transformers/models/electra/__pycache__/convert_electra_original_tf_checkpoint_to_pytorch.cpython-310.pyc +0 -0
  37. pllava/lib/python3.10/site-packages/transformers/models/electra/__pycache__/modeling_electra.cpython-310.pyc +0 -0
  38. pllava/lib/python3.10/site-packages/transformers/models/electra/__pycache__/modeling_flax_electra.cpython-310.pyc +0 -0
  39. pllava/lib/python3.10/site-packages/transformers/models/electra/__pycache__/modeling_tf_electra.cpython-310.pyc +0 -0
  40. pllava/lib/python3.10/site-packages/transformers/models/electra/__pycache__/tokenization_electra.cpython-310.pyc +0 -0
  41. pllava/lib/python3.10/site-packages/transformers/models/electra/__pycache__/tokenization_electra_fast.cpython-310.pyc +0 -0
  42. pllava/lib/python3.10/site-packages/transformers/models/electra/configuration_electra.py +199 -0
  43. pllava/lib/python3.10/site-packages/transformers/models/electra/modeling_electra.py +1686 -0
  44. pllava/lib/python3.10/site-packages/transformers/models/electra/modeling_flax_electra.py +1601 -0
  45. pllava/lib/python3.10/site-packages/transformers/models/electra/modeling_tf_electra.py +1774 -0
  46. pllava/lib/python3.10/site-packages/transformers/models/electra/tokenization_electra.py +546 -0
  47. pllava/lib/python3.10/site-packages/transformers/models/groupvit/__init__.py +97 -0
  48. pllava/lib/python3.10/site-packages/transformers/models/patchtst/__init__.py +66 -0
  49. pllava/lib/python3.10/site-packages/transformers/models/patchtst/__pycache__/configuration_patchtst.cpython-310.pyc +0 -0
  50. pllava/lib/python3.10/site-packages/transformers/models/patchtst/modeling_patchtst.py +2034 -0
pllava/lib/python3.10/site-packages/transformers/generation/__init__.py ADDED
@@ -0,0 +1,304 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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_flax_available, is_tf_available, is_torch_available
18
+
19
+
20
+ _import_structure = {
21
+ "configuration_utils": ["GenerationConfig"],
22
+ "streamers": ["TextIteratorStreamer", "TextStreamer"],
23
+ }
24
+
25
+ try:
26
+ if not is_torch_available():
27
+ raise OptionalDependencyNotAvailable()
28
+ except OptionalDependencyNotAvailable:
29
+ pass
30
+ else:
31
+ _import_structure["beam_constraints"] = [
32
+ "Constraint",
33
+ "ConstraintListState",
34
+ "DisjunctiveConstraint",
35
+ "PhrasalConstraint",
36
+ ]
37
+ _import_structure["beam_search"] = [
38
+ "BeamHypotheses",
39
+ "BeamScorer",
40
+ "BeamSearchScorer",
41
+ "ConstrainedBeamSearchScorer",
42
+ ]
43
+ _import_structure["logits_process"] = [
44
+ "AlternatingCodebooksLogitsProcessor",
45
+ "ClassifierFreeGuidanceLogitsProcessor",
46
+ "EncoderNoRepeatNGramLogitsProcessor",
47
+ "EncoderRepetitionPenaltyLogitsProcessor",
48
+ "EpsilonLogitsWarper",
49
+ "EtaLogitsWarper",
50
+ "ExponentialDecayLengthPenalty",
51
+ "ForcedBOSTokenLogitsProcessor",
52
+ "ForcedEOSTokenLogitsProcessor",
53
+ "ForceTokensLogitsProcessor",
54
+ "HammingDiversityLogitsProcessor",
55
+ "InfNanRemoveLogitsProcessor",
56
+ "LogitNormalization",
57
+ "LogitsProcessor",
58
+ "LogitsProcessorList",
59
+ "LogitsWarper",
60
+ "MinLengthLogitsProcessor",
61
+ "MinNewTokensLengthLogitsProcessor",
62
+ "NoBadWordsLogitsProcessor",
63
+ "NoRepeatNGramLogitsProcessor",
64
+ "PrefixConstrainedLogitsProcessor",
65
+ "RepetitionPenaltyLogitsProcessor",
66
+ "SequenceBiasLogitsProcessor",
67
+ "SuppressTokensLogitsProcessor",
68
+ "SuppressTokensAtBeginLogitsProcessor",
69
+ "TemperatureLogitsWarper",
70
+ "TopKLogitsWarper",
71
+ "TopPLogitsWarper",
72
+ "TypicalLogitsWarper",
73
+ "UnbatchedClassifierFreeGuidanceLogitsProcessor",
74
+ "WhisperTimeStampLogitsProcessor",
75
+ ]
76
+ _import_structure["stopping_criteria"] = [
77
+ "MaxNewTokensCriteria",
78
+ "MaxLengthCriteria",
79
+ "MaxTimeCriteria",
80
+ "StoppingCriteria",
81
+ "StoppingCriteriaList",
82
+ "validate_stopping_criteria",
83
+ ]
84
+ _import_structure["utils"] = [
85
+ "GenerationMixin",
86
+ "top_k_top_p_filtering",
87
+ "GreedySearchEncoderDecoderOutput",
88
+ "GreedySearchDecoderOnlyOutput",
89
+ "SampleEncoderDecoderOutput",
90
+ "SampleDecoderOnlyOutput",
91
+ "BeamSearchEncoderDecoderOutput",
92
+ "BeamSearchDecoderOnlyOutput",
93
+ "BeamSampleEncoderDecoderOutput",
94
+ "BeamSampleDecoderOnlyOutput",
95
+ "ContrastiveSearchEncoderDecoderOutput",
96
+ "ContrastiveSearchDecoderOnlyOutput",
97
+ "GenerateBeamDecoderOnlyOutput",
98
+ "GenerateBeamEncoderDecoderOutput",
99
+ "GenerateDecoderOnlyOutput",
100
+ "GenerateEncoderDecoderOutput",
101
+ ]
102
+
103
+ try:
104
+ if not is_tf_available():
105
+ raise OptionalDependencyNotAvailable()
106
+ except OptionalDependencyNotAvailable:
107
+ pass
108
+ else:
109
+ _import_structure["tf_logits_process"] = [
110
+ "TFForcedBOSTokenLogitsProcessor",
111
+ "TFForcedEOSTokenLogitsProcessor",
112
+ "TFForceTokensLogitsProcessor",
113
+ "TFLogitsProcessor",
114
+ "TFLogitsProcessorList",
115
+ "TFLogitsWarper",
116
+ "TFMinLengthLogitsProcessor",
117
+ "TFNoBadWordsLogitsProcessor",
118
+ "TFNoRepeatNGramLogitsProcessor",
119
+ "TFRepetitionPenaltyLogitsProcessor",
120
+ "TFSuppressTokensAtBeginLogitsProcessor",
121
+ "TFSuppressTokensLogitsProcessor",
122
+ "TFTemperatureLogitsWarper",
123
+ "TFTopKLogitsWarper",
124
+ "TFTopPLogitsWarper",
125
+ ]
126
+ _import_structure["tf_utils"] = [
127
+ "TFGenerationMixin",
128
+ "tf_top_k_top_p_filtering",
129
+ "TFGreedySearchDecoderOnlyOutput",
130
+ "TFGreedySearchEncoderDecoderOutput",
131
+ "TFSampleEncoderDecoderOutput",
132
+ "TFSampleDecoderOnlyOutput",
133
+ "TFBeamSearchEncoderDecoderOutput",
134
+ "TFBeamSearchDecoderOnlyOutput",
135
+ "TFBeamSampleEncoderDecoderOutput",
136
+ "TFBeamSampleDecoderOnlyOutput",
137
+ "TFContrastiveSearchEncoderDecoderOutput",
138
+ "TFContrastiveSearchDecoderOnlyOutput",
139
+ ]
140
+
141
+ try:
142
+ if not is_flax_available():
143
+ raise OptionalDependencyNotAvailable()
144
+ except OptionalDependencyNotAvailable:
145
+ pass
146
+ else:
147
+ _import_structure["flax_logits_process"] = [
148
+ "FlaxForcedBOSTokenLogitsProcessor",
149
+ "FlaxForcedEOSTokenLogitsProcessor",
150
+ "FlaxForceTokensLogitsProcessor",
151
+ "FlaxLogitsProcessor",
152
+ "FlaxLogitsProcessorList",
153
+ "FlaxLogitsWarper",
154
+ "FlaxMinLengthLogitsProcessor",
155
+ "FlaxSuppressTokensAtBeginLogitsProcessor",
156
+ "FlaxSuppressTokensLogitsProcessor",
157
+ "FlaxTemperatureLogitsWarper",
158
+ "FlaxTopKLogitsWarper",
159
+ "FlaxTopPLogitsWarper",
160
+ "FlaxWhisperTimeStampLogitsProcessor",
161
+ ]
162
+ _import_structure["flax_utils"] = [
163
+ "FlaxGenerationMixin",
164
+ "FlaxGreedySearchOutput",
165
+ "FlaxSampleOutput",
166
+ "FlaxBeamSearchOutput",
167
+ ]
168
+
169
+ if TYPE_CHECKING:
170
+ from .configuration_utils import GenerationConfig
171
+ from .streamers import TextIteratorStreamer, TextStreamer
172
+
173
+ try:
174
+ if not is_torch_available():
175
+ raise OptionalDependencyNotAvailable()
176
+ except OptionalDependencyNotAvailable:
177
+ pass
178
+ else:
179
+ from .beam_constraints import Constraint, ConstraintListState, DisjunctiveConstraint, PhrasalConstraint
180
+ from .beam_search import BeamHypotheses, BeamScorer, BeamSearchScorer, ConstrainedBeamSearchScorer
181
+ from .logits_process import (
182
+ AlternatingCodebooksLogitsProcessor,
183
+ ClassifierFreeGuidanceLogitsProcessor,
184
+ EncoderNoRepeatNGramLogitsProcessor,
185
+ EncoderRepetitionPenaltyLogitsProcessor,
186
+ EpsilonLogitsWarper,
187
+ EtaLogitsWarper,
188
+ ExponentialDecayLengthPenalty,
189
+ ForcedBOSTokenLogitsProcessor,
190
+ ForcedEOSTokenLogitsProcessor,
191
+ ForceTokensLogitsProcessor,
192
+ HammingDiversityLogitsProcessor,
193
+ InfNanRemoveLogitsProcessor,
194
+ LogitNormalization,
195
+ LogitsProcessor,
196
+ LogitsProcessorList,
197
+ LogitsWarper,
198
+ MinLengthLogitsProcessor,
199
+ MinNewTokensLengthLogitsProcessor,
200
+ NoBadWordsLogitsProcessor,
201
+ NoRepeatNGramLogitsProcessor,
202
+ PrefixConstrainedLogitsProcessor,
203
+ RepetitionPenaltyLogitsProcessor,
204
+ SequenceBiasLogitsProcessor,
205
+ SuppressTokensAtBeginLogitsProcessor,
206
+ SuppressTokensLogitsProcessor,
207
+ TemperatureLogitsWarper,
208
+ TopKLogitsWarper,
209
+ TopPLogitsWarper,
210
+ TypicalLogitsWarper,
211
+ UnbatchedClassifierFreeGuidanceLogitsProcessor,
212
+ WhisperTimeStampLogitsProcessor,
213
+ )
214
+ from .stopping_criteria import (
215
+ MaxLengthCriteria,
216
+ MaxNewTokensCriteria,
217
+ MaxTimeCriteria,
218
+ StoppingCriteria,
219
+ StoppingCriteriaList,
220
+ validate_stopping_criteria,
221
+ )
222
+ from .utils import (
223
+ BeamSampleDecoderOnlyOutput,
224
+ BeamSampleEncoderDecoderOutput,
225
+ BeamSearchDecoderOnlyOutput,
226
+ BeamSearchEncoderDecoderOutput,
227
+ ContrastiveSearchDecoderOnlyOutput,
228
+ ContrastiveSearchEncoderDecoderOutput,
229
+ GenerateBeamDecoderOnlyOutput,
230
+ GenerateBeamEncoderDecoderOutput,
231
+ GenerateDecoderOnlyOutput,
232
+ GenerateEncoderDecoderOutput,
233
+ GenerationMixin,
234
+ GreedySearchDecoderOnlyOutput,
235
+ GreedySearchEncoderDecoderOutput,
236
+ SampleDecoderOnlyOutput,
237
+ SampleEncoderDecoderOutput,
238
+ top_k_top_p_filtering,
239
+ )
240
+
241
+ try:
242
+ if not is_tf_available():
243
+ raise OptionalDependencyNotAvailable()
244
+ except OptionalDependencyNotAvailable:
245
+ pass
246
+ else:
247
+ from .tf_logits_process import (
248
+ TFForcedBOSTokenLogitsProcessor,
249
+ TFForcedEOSTokenLogitsProcessor,
250
+ TFForceTokensLogitsProcessor,
251
+ TFLogitsProcessor,
252
+ TFLogitsProcessorList,
253
+ TFLogitsWarper,
254
+ TFMinLengthLogitsProcessor,
255
+ TFNoBadWordsLogitsProcessor,
256
+ TFNoRepeatNGramLogitsProcessor,
257
+ TFRepetitionPenaltyLogitsProcessor,
258
+ TFSuppressTokensAtBeginLogitsProcessor,
259
+ TFSuppressTokensLogitsProcessor,
260
+ TFTemperatureLogitsWarper,
261
+ TFTopKLogitsWarper,
262
+ TFTopPLogitsWarper,
263
+ )
264
+ from .tf_utils import (
265
+ TFBeamSampleDecoderOnlyOutput,
266
+ TFBeamSampleEncoderDecoderOutput,
267
+ TFBeamSearchDecoderOnlyOutput,
268
+ TFBeamSearchEncoderDecoderOutput,
269
+ TFContrastiveSearchDecoderOnlyOutput,
270
+ TFContrastiveSearchEncoderDecoderOutput,
271
+ TFGenerationMixin,
272
+ TFGreedySearchDecoderOnlyOutput,
273
+ TFGreedySearchEncoderDecoderOutput,
274
+ TFSampleDecoderOnlyOutput,
275
+ TFSampleEncoderDecoderOutput,
276
+ tf_top_k_top_p_filtering,
277
+ )
278
+
279
+ try:
280
+ if not is_flax_available():
281
+ raise OptionalDependencyNotAvailable()
282
+ except OptionalDependencyNotAvailable:
283
+ pass
284
+ else:
285
+ from .flax_logits_process import (
286
+ FlaxForcedBOSTokenLogitsProcessor,
287
+ FlaxForcedEOSTokenLogitsProcessor,
288
+ FlaxForceTokensLogitsProcessor,
289
+ FlaxLogitsProcessor,
290
+ FlaxLogitsProcessorList,
291
+ FlaxLogitsWarper,
292
+ FlaxMinLengthLogitsProcessor,
293
+ FlaxSuppressTokensAtBeginLogitsProcessor,
294
+ FlaxSuppressTokensLogitsProcessor,
295
+ FlaxTemperatureLogitsWarper,
296
+ FlaxTopKLogitsWarper,
297
+ FlaxTopPLogitsWarper,
298
+ FlaxWhisperTimeStampLogitsProcessor,
299
+ )
300
+ from .flax_utils import FlaxBeamSearchOutput, FlaxGenerationMixin, FlaxGreedySearchOutput, FlaxSampleOutput
301
+ else:
302
+ import sys
303
+
304
+ sys.modules[__name__] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
pllava/lib/python3.10/site-packages/transformers/generation/flax_utils.py ADDED
@@ -0,0 +1,1020 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2021 The Google AI Flax Team Authors, and The HuggingFace Inc. team.
3
+ # Copyright (c) 2020, 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
+
17
+
18
+ import copy
19
+ import inspect
20
+ import warnings
21
+ from functools import partial
22
+ from typing import Any, Dict, Optional, Union
23
+
24
+ import flax
25
+ import jax
26
+ import jax.numpy as jnp
27
+ import numpy as np
28
+ from jax import lax
29
+
30
+ from ..models.auto import (
31
+ FLAX_MODEL_FOR_CAUSAL_LM_MAPPING,
32
+ FLAX_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING,
33
+ FLAX_MODEL_FOR_VISION_2_SEQ_MAPPING,
34
+ )
35
+ from ..utils import ModelOutput, logging
36
+ from .configuration_utils import GenerationConfig
37
+ from .flax_logits_process import (
38
+ FlaxForcedBOSTokenLogitsProcessor,
39
+ FlaxForcedEOSTokenLogitsProcessor,
40
+ FlaxForceTokensLogitsProcessor,
41
+ FlaxLogitsProcessorList,
42
+ FlaxMinLengthLogitsProcessor,
43
+ FlaxSuppressTokensAtBeginLogitsProcessor,
44
+ FlaxSuppressTokensLogitsProcessor,
45
+ FlaxTemperatureLogitsWarper,
46
+ FlaxTopKLogitsWarper,
47
+ FlaxTopPLogitsWarper,
48
+ )
49
+
50
+
51
+ logger = logging.get_logger(__name__)
52
+
53
+
54
+ @flax.struct.dataclass
55
+ class FlaxGreedySearchOutput(ModelOutput):
56
+ """
57
+ Flax Base class for outputs of decoder-only generation models using greedy search.
58
+
59
+
60
+ Args:
61
+ sequences (`jnp.ndarray` of shape `(batch_size, max_length)`):
62
+ The generated sequences.
63
+ """
64
+
65
+ sequences: jnp.ndarray = None
66
+
67
+
68
+ @flax.struct.dataclass
69
+ class FlaxSampleOutput(ModelOutput):
70
+ """
71
+ Flax Base class for outputs of decoder-only generation models using sampling.
72
+
73
+
74
+ Args:
75
+ sequences (`jnp.ndarray` of shape `(batch_size, max_length)`):
76
+ The generated sequences.
77
+ """
78
+
79
+ sequences: jnp.ndarray = None
80
+
81
+
82
+ @flax.struct.dataclass
83
+ class FlaxBeamSearchOutput(ModelOutput):
84
+ """
85
+ Flax Base class for outputs of decoder-only generation models using greedy search.
86
+
87
+
88
+ Args:
89
+ sequences (`jnp.ndarray` of shape `(batch_size, max_length)`):
90
+ The generated sequences.
91
+ scores (`jnp.ndarray` of shape `(batch_size,)`):
92
+ The scores (log probabilities) of the generated sequences.
93
+ """
94
+
95
+ sequences: jnp.ndarray = None
96
+ scores: jnp.ndarray = None
97
+
98
+
99
+ @flax.struct.dataclass
100
+ class GreedyState:
101
+ cur_len: jnp.ndarray
102
+ sequences: jnp.ndarray
103
+ running_token: jnp.ndarray
104
+ is_sent_finished: jnp.ndarray
105
+ model_kwargs: Dict[str, jnp.ndarray]
106
+
107
+
108
+ @flax.struct.dataclass
109
+ class SampleState:
110
+ cur_len: jnp.ndarray
111
+ sequences: jnp.ndarray
112
+ running_token: jnp.ndarray
113
+ is_sent_finished: jnp.ndarray
114
+ prng_key: jnp.ndarray
115
+ model_kwargs: Dict[str, jnp.ndarray]
116
+
117
+
118
+ @flax.struct.dataclass
119
+ class BeamSearchState:
120
+ cur_len: jnp.ndarray
121
+ running_sequences: jnp.ndarray
122
+ running_scores: jnp.ndarray
123
+ sequences: jnp.ndarray
124
+ scores: jnp.ndarray
125
+ is_sent_finished: jnp.ndarray
126
+ model_kwargs: Dict[str, jnp.ndarray]
127
+
128
+
129
+ class FlaxGenerationMixin:
130
+ """
131
+ A class containing all functions for auto-regressive text generation, to be used as a mixin in
132
+ [`FlaxPreTrainedModel`].
133
+
134
+ The class exposes [`~generation.FlaxGenerationMixin.generate`], which can be used for:
135
+ - *greedy decoding* by calling [`~generation.FlaxGenerationMixin._greedy_search`] if `num_beams=1` and
136
+ `do_sample=False`
137
+ - *multinomial sampling* by calling [`~generation.FlaxGenerationMixin._sample`] if `num_beams=1` and
138
+ `do_sample=True`
139
+ - *beam-search decoding* by calling [`~generation.FlaxGenerationMixin._beam_search`] if `num_beams>1` and
140
+ `do_sample=False`
141
+
142
+ You do not need to call any of the above methods directly. Pass custom parameter values to 'generate' instead. To
143
+ learn more about decoding strategies refer to the [text generation strategies guide](../generation_strategies).
144
+ """
145
+
146
+ def prepare_inputs_for_generation(self, *args, **kwargs):
147
+ raise NotImplementedError(
148
+ "A model class needs to define a `prepare_inputs_for_generation` method in order to use `generate`."
149
+ )
150
+
151
+ @staticmethod
152
+ def _run_loop_in_debug(cond_fn, body_fn, init_state):
153
+ """
154
+ Run generation in untraced mode. This should only be used for debugging purposes.
155
+ """
156
+ state = init_state
157
+ while cond_fn(state):
158
+ state = body_fn(state)
159
+ return state
160
+
161
+ def _prepare_encoder_decoder_kwargs_for_generation(self, input_ids, params, model_kwargs):
162
+ encoder_kwargs = {
163
+ argument: value
164
+ for argument, value in model_kwargs.items()
165
+ if not (argument.startswith("decoder_") or argument.startswith("cross_attn"))
166
+ }
167
+ model_kwargs["encoder_outputs"] = self.encode(input_ids, params=params, return_dict=True, **encoder_kwargs)
168
+ return model_kwargs
169
+
170
+ def _prepare_decoder_input_ids_for_generation(
171
+ self,
172
+ batch_size: int,
173
+ decoder_start_token_id: int = None,
174
+ bos_token_id: int = None,
175
+ model_kwargs: Optional[Dict[str, jnp.ndarray]] = None,
176
+ ) -> jnp.ndarray:
177
+ if model_kwargs is not None and "decoder_input_ids" in model_kwargs:
178
+ # Only use this arg if not None, otherwise just remove from model_kwargs
179
+ decoder_input_ids = model_kwargs.pop("decoder_input_ids")
180
+ if decoder_input_ids is not None:
181
+ return decoder_input_ids
182
+ decoder_start_token_id = self._get_decoder_start_token_id(decoder_start_token_id, bos_token_id)
183
+ return jnp.array(decoder_start_token_id, dtype="i4").reshape(1, -1).repeat(batch_size, axis=0)
184
+
185
+ def _get_decoder_start_token_id(self, decoder_start_token_id: int = None, bos_token_id: int = None) -> int:
186
+ # retrieve decoder_start_token_id for encoder-decoder models
187
+ # fall back to bos_token_id if necessary
188
+ decoder_start_token_id = (
189
+ decoder_start_token_id
190
+ if decoder_start_token_id is not None
191
+ else self.generation_config.decoder_start_token_id
192
+ )
193
+ bos_token_id = bos_token_id if bos_token_id is not None else self.generation_config.bos_token_id
194
+ if decoder_start_token_id is not None:
195
+ return decoder_start_token_id
196
+ elif (
197
+ hasattr(self.config, "decoder")
198
+ and hasattr(self.config.decoder, "decoder_start_token_id")
199
+ and self.config.decoder.decoder_start_token_id is not None
200
+ ):
201
+ return self.config.decoder.decoder_start_token_id
202
+ elif bos_token_id is not None:
203
+ return bos_token_id
204
+ elif (
205
+ hasattr(self.config, "decoder")
206
+ and hasattr(self.config.decoder, "bos_token_id")
207
+ and self.config.decoder.bos_token_id is not None
208
+ ):
209
+ return self.config.decoder.bos_token_id
210
+ raise ValueError(
211
+ "`decoder_start_token_id` or `bos_token_id` has to be defined for encoder-decoder generation."
212
+ )
213
+
214
+ @staticmethod
215
+ def _expand_to_num_beams(tensor, num_beams):
216
+ return jnp.broadcast_to(tensor[:, None], (tensor.shape[0], num_beams) + tensor.shape[1:])
217
+
218
+ def _adapt_logits_for_beam_search(self, logits):
219
+ """
220
+ This function can be overwritten in the specific modeling_flax_<model-name>.py classes to allow for custom beam
221
+ search behavior. Note that the only model that overwrites this method is [`~transformes.FlaxMarianMTModel`].
222
+ """
223
+ return logits
224
+
225
+ def _validate_model_class(self):
226
+ """
227
+ Confirms that the model class is compatible with generation. If not, raises an exception that points to the
228
+ right class to use.
229
+ """
230
+ if not self.can_generate():
231
+ generate_compatible_mappings = [
232
+ FLAX_MODEL_FOR_CAUSAL_LM_MAPPING,
233
+ FLAX_MODEL_FOR_VISION_2_SEQ_MAPPING,
234
+ FLAX_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING,
235
+ ]
236
+ generate_compatible_classes = set()
237
+ for model_mapping in generate_compatible_mappings:
238
+ supported_models = model_mapping.get(type(self.config), default=None)
239
+ if supported_models is not None:
240
+ generate_compatible_classes.add(supported_models.__name__)
241
+ exception_message = (
242
+ f"The current model class ({self.__class__.__name__}) is not compatible with `.generate()`, as "
243
+ "it doesn't have a language model head."
244
+ )
245
+ if generate_compatible_classes:
246
+ exception_message += f" Please use one of the following classes instead: {generate_compatible_classes}"
247
+ raise TypeError(exception_message)
248
+
249
+ def _validate_model_kwargs(self, model_kwargs: Dict[str, Any]):
250
+ """Validates model kwargs for generation. Generate argument typos will also be caught here."""
251
+ unused_model_args = []
252
+ model_args = set(inspect.signature(self.prepare_inputs_for_generation).parameters)
253
+ # `kwargs`/`model_kwargs` is often used to handle optional forward pass inputs like `attention_mask`. If
254
+ # `prepare_inputs_for_generation` doesn't accept them, then a stricter check can be made ;)
255
+ if "kwargs" in model_args or "model_kwargs" in model_args:
256
+ model_args |= set(inspect.signature(self.__call__).parameters)
257
+ for key, value in model_kwargs.items():
258
+ if value is not None and key not in model_args:
259
+ unused_model_args.append(key)
260
+
261
+ if unused_model_args:
262
+ raise ValueError(
263
+ f"The following `model_kwargs` are not used by the model: {unused_model_args} (note: typos in the"
264
+ " generate arguments will also show up in this list)"
265
+ )
266
+
267
+ def generate(
268
+ self,
269
+ input_ids: jnp.ndarray,
270
+ generation_config: Optional[GenerationConfig] = None,
271
+ prng_key: Optional[jnp.ndarray] = None,
272
+ trace: bool = True,
273
+ params: Optional[Dict[str, jnp.ndarray]] = None,
274
+ logits_processor: Optional[FlaxLogitsProcessorList] = None,
275
+ **kwargs,
276
+ ):
277
+ r"""
278
+ Generates sequences of token ids for models with a language modeling head.
279
+
280
+ Parameters:
281
+ input_ids (`jnp.ndarray` of shape `(batch_size, sequence_length)`):
282
+ The sequence used as a prompt for the generation.
283
+ generation_config (`~generation.GenerationConfig`, *optional*):
284
+ The generation configuration to be used as base parametrization for the generation call. `**kwargs`
285
+ passed to generate matching the attributes of `generation_config` will override them. If
286
+ `generation_config` is not provided, the default will be used, which had the following loading
287
+ priority: 1) from the `generation_config.json` model file, if it exists; 2) from the model
288
+ configuration. Please note that unspecified parameters will inherit [`~generation.GenerationConfig`]'s
289
+ default values, whose documentation should be checked to parameterize generation.
290
+ trace (`bool`, *optional*, defaults to `True`):
291
+ Whether to trace generation. Setting `trace=False` should only be used for debugging and will lead to a
292
+ considerably slower runtime.
293
+ params (`Dict[str, jnp.ndarray]`, *optional*):
294
+ Optionally the model parameters can be passed. Can be useful for parallelized generation.
295
+ logits_processor (`FlaxLogitsProcessorList `, *optional*):
296
+ Custom logits processors that complement the default logits processors built from arguments and
297
+ generation config. If a logit processor is passed that is already created with the arguments or a
298
+ generation config an error is thrown. This feature is intended for advanced users.
299
+ kwargs (`Dict[str, Any]`, *optional*):
300
+ Ad hoc parametrization of `generate_config` and/or additional model-specific kwargs that will be
301
+ forwarded to the `forward` function of the model. If the model is an encoder-decoder model, encoder
302
+ specific kwargs should not be prefixed and decoder specific kwargs should be prefixed with *decoder_*.
303
+
304
+ Return:
305
+ [`~utils.ModelOutput`].
306
+
307
+ """
308
+ # Handle `generation_config` and kwargs that might update it, and validate the `.generate()` call
309
+ self._validate_model_class()
310
+
311
+ # priority: `generation_config` argument > `model.generation_config` (the default generation config)
312
+ if generation_config is None:
313
+ # legacy: users may modify the model configuration to control generation. To trigger this legacy behavior,
314
+ # two conditions must be met
315
+ # 1) the generation config must have been created from the model config (`_from_model_config` field);
316
+ # 2) the generation config must have seen no modification since its creation (the hash is the same).
317
+ if self.generation_config._from_model_config and self.generation_config._original_object_hash == hash(
318
+ self.generation_config
319
+ ):
320
+ new_generation_config = GenerationConfig.from_model_config(self.config)
321
+ if new_generation_config != self.generation_config:
322
+ warnings.warn(
323
+ "You have modified the pretrained model configuration to control generation. This is a"
324
+ " deprecated strategy to control generation and will be removed soon, in a future version."
325
+ " Please use and modify the model generation configuration (see"
326
+ " https://huggingface.co/docs/transformers/generation_strategies#default-text-generation-configuration )"
327
+ )
328
+ self.generation_config = new_generation_config
329
+ generation_config = self.generation_config
330
+
331
+ generation_config = copy.deepcopy(generation_config)
332
+ model_kwargs = generation_config.update(**kwargs) # All unused kwargs must be model kwargs
333
+ generation_config.validate()
334
+ self._validate_model_kwargs(model_kwargs.copy())
335
+
336
+ logits_processor = logits_processor if logits_processor is not None else FlaxLogitsProcessorList()
337
+
338
+ # set init values
339
+ prng_key = prng_key if prng_key is not None else jax.random.PRNGKey(0)
340
+
341
+ if generation_config.pad_token_id is None and generation_config.eos_token_id is not None:
342
+ if model_kwargs.get("attention_mask") is None:
343
+ logger.warning(
344
+ "The attention mask and the pad token id were not set. As a consequence, you may observe "
345
+ "unexpected behavior. Please pass your input's `attention_mask` to obtain reliable results."
346
+ )
347
+ eos_token_id = generation_config.eos_token_id
348
+ if isinstance(eos_token_id, list):
349
+ eos_token_id = eos_token_id[0]
350
+ logger.warning(f"Setting `pad_token_id` to `eos_token_id`:{eos_token_id} for open-end generation.")
351
+ generation_config.pad_token_id = eos_token_id
352
+
353
+ if generation_config.decoder_start_token_id is None and self.config.is_encoder_decoder:
354
+ raise ValueError("`decoder_start_token_id` has to be defined for encoder-decoder generation.")
355
+
356
+ # decoder-only models should use left-padding for generation (can't be checked with `trace=True`)
357
+ if not self.config.is_encoder_decoder and not trace:
358
+ if (
359
+ generation_config.pad_token_id is not None
360
+ and jnp.sum(input_ids[:, -1] == generation_config.pad_token_id) > 0
361
+ ):
362
+ logger.warning(
363
+ "A decoder-only architecture is being used, but right-padding was detected! For correct "
364
+ "generation results, please set `padding_side='left'` when initializing the tokenizer."
365
+ )
366
+
367
+ batch_size = input_ids.shape[0]
368
+
369
+ if self.config.is_encoder_decoder:
370
+ # add encoder_outputs to model_kwargs
371
+ if model_kwargs.get("encoder_outputs") is None:
372
+ model_kwargs = self._prepare_encoder_decoder_kwargs_for_generation(input_ids, params, model_kwargs)
373
+ # prepare decoder_input_ids for generation
374
+ input_ids = self._prepare_decoder_input_ids_for_generation(
375
+ batch_size,
376
+ decoder_start_token_id=generation_config.decoder_start_token_id,
377
+ bos_token_id=generation_config.bos_token_id,
378
+ model_kwargs=model_kwargs,
379
+ )
380
+
381
+ # Prepare `max_length` depending on other stopping criteria.
382
+ input_ids_seq_length = input_ids.shape[-1]
383
+ has_default_max_length = kwargs.get("max_length") is None and generation_config.max_length is not None
384
+ if has_default_max_length and generation_config.max_new_tokens is None and generation_config.max_length == 20:
385
+ # 20 is the default max_length of the generation config
386
+ warnings.warn(
387
+ f"Using the model-agnostic default `max_length` (={generation_config.max_length}) "
388
+ "to control the generation length. recommend setting `max_new_tokens` to control the maximum length of the generation.",
389
+ UserWarning,
390
+ )
391
+ elif generation_config.max_new_tokens is not None:
392
+ if not has_default_max_length and generation_config.max_length is not None:
393
+ logger.warning(
394
+ f"Both `max_new_tokens` (={generation_config.max_new_tokens}) and `max_length`(="
395
+ f"{generation_config.max_length}) seem to have been set. `max_new_tokens` will take precedence. "
396
+ "Please refer to the documentation for more information. "
397
+ "(https://huggingface.co/docs/transformers/main/en/main_classes/text_generation)"
398
+ )
399
+ generation_config.max_length = generation_config.max_new_tokens + input_ids_seq_length
400
+
401
+ if generation_config.min_length is not None and generation_config.min_length > generation_config.max_length:
402
+ raise ValueError(
403
+ f"Unfeasable length constraints: the minimum length ({generation_config.min_length}) is larger than"
404
+ f" the maximum length ({generation_config.max_length})"
405
+ )
406
+ if input_ids_seq_length >= generation_config.max_length:
407
+ input_ids_string = "decoder_input_ids" if self.config.is_encoder_decoder else "input_ids"
408
+ logger.warning(
409
+ f"Input length of {input_ids_string} is {input_ids_seq_length}, but `max_length` is set to"
410
+ f" {generation_config.max_length}. This can lead to unexpected behavior. You should consider"
411
+ " increasing`max_new_tokens`."
412
+ )
413
+
414
+ logits_processor = self._get_logits_processor(
415
+ generation_config=generation_config,
416
+ input_ids_seq_length=input_ids_seq_length,
417
+ logits_processor=logits_processor,
418
+ )
419
+
420
+ if not generation_config.do_sample and generation_config.num_beams == 1:
421
+ return self._greedy_search(
422
+ input_ids,
423
+ generation_config.max_length,
424
+ generation_config.pad_token_id,
425
+ generation_config.eos_token_id,
426
+ logits_processor=logits_processor,
427
+ trace=trace,
428
+ params=params,
429
+ model_kwargs=model_kwargs,
430
+ )
431
+ elif generation_config.do_sample and generation_config.num_beams == 1:
432
+ logits_warper = self._get_logits_warper(generation_config=generation_config)
433
+ return self._sample(
434
+ input_ids,
435
+ generation_config.max_length,
436
+ generation_config.pad_token_id,
437
+ generation_config.eos_token_id,
438
+ prng_key,
439
+ logits_warper=logits_warper,
440
+ logits_processor=logits_processor,
441
+ trace=trace,
442
+ params=params,
443
+ model_kwargs=model_kwargs,
444
+ )
445
+ elif not generation_config.do_sample and generation_config.num_beams > 1:
446
+ # broadcast input_ids & encoder_outputs
447
+ input_ids = self._expand_to_num_beams(input_ids, num_beams=generation_config.num_beams)
448
+
449
+ if "encoder_outputs" in model_kwargs:
450
+ model_kwargs["encoder_outputs"]["last_hidden_state"] = self._expand_to_num_beams(
451
+ model_kwargs["encoder_outputs"]["last_hidden_state"], num_beams=generation_config.num_beams
452
+ )
453
+
454
+ for kwarg in ["attention_mask", "decoder_attention_mask"]:
455
+ if kwarg in model_kwargs:
456
+ model_kwargs[kwarg] = self._expand_to_num_beams(
457
+ model_kwargs[kwarg], num_beams=generation_config.num_beams
458
+ )
459
+
460
+ return self._beam_search(
461
+ input_ids,
462
+ generation_config.max_length,
463
+ generation_config.pad_token_id,
464
+ generation_config.eos_token_id,
465
+ length_penalty=generation_config.length_penalty,
466
+ early_stopping=generation_config.early_stopping,
467
+ logits_processor=logits_processor,
468
+ trace=trace,
469
+ params=params,
470
+ num_return_sequences=generation_config.num_return_sequences,
471
+ model_kwargs=model_kwargs,
472
+ )
473
+ else:
474
+ raise NotImplementedError("`Beam sampling is currently not implemented.")
475
+
476
+ def _get_logits_warper(self, generation_config: GenerationConfig) -> FlaxLogitsProcessorList:
477
+ """
478
+ This class returns a [`FlaxLogitsProcessorList`] list object that contains all relevant [`FlaxLogitsWarper`]
479
+ instances used for multinomial sampling.
480
+ """
481
+ warpers = FlaxLogitsProcessorList()
482
+
483
+ if generation_config.temperature is not None and generation_config.temperature != 1.0:
484
+ warpers.append(FlaxTemperatureLogitsWarper(generation_config.temperature))
485
+ if generation_config.top_k is not None and generation_config.top_k != 0:
486
+ warpers.append(FlaxTopKLogitsWarper(top_k=generation_config.top_k, min_tokens_to_keep=1))
487
+ if generation_config.top_p is not None and generation_config.top_p < 1.0:
488
+ warpers.append(FlaxTopPLogitsWarper(top_p=generation_config.top_p, min_tokens_to_keep=1))
489
+
490
+ return warpers
491
+
492
+ def _get_logits_processor(
493
+ self,
494
+ generation_config: GenerationConfig,
495
+ input_ids_seq_length: int,
496
+ logits_processor: Optional[FlaxLogitsProcessorList],
497
+ ) -> FlaxLogitsProcessorList:
498
+ """
499
+ This class returns a [`FlaxLogitsProcessorList`] list object that contains all relevant [`FlaxLogitsProcessor`]
500
+ instances used to modify the scores of the language model head.
501
+ """
502
+ processors = FlaxLogitsProcessorList()
503
+
504
+ if (
505
+ generation_config.min_length is not None
506
+ and generation_config.eos_token_id is not None
507
+ and generation_config.min_length > -1
508
+ ):
509
+ processors.append(
510
+ FlaxMinLengthLogitsProcessor(generation_config.min_length, generation_config.eos_token_id)
511
+ )
512
+ if generation_config.forced_bos_token_id is not None:
513
+ processors.append(FlaxForcedBOSTokenLogitsProcessor(generation_config.forced_bos_token_id))
514
+ if generation_config.forced_eos_token_id is not None:
515
+ processors.append(
516
+ FlaxForcedEOSTokenLogitsProcessor(generation_config.max_length, generation_config.forced_eos_token_id)
517
+ )
518
+ if generation_config.suppress_tokens is not None:
519
+ processors.append(FlaxSuppressTokensLogitsProcessor(generation_config.suppress_tokens))
520
+ if generation_config.begin_suppress_tokens is not None:
521
+ begin_index = input_ids_seq_length
522
+ begin_index = (
523
+ begin_index
524
+ if (input_ids_seq_length > 1 or generation_config.forced_bos_token_id is None)
525
+ else begin_index + 1
526
+ )
527
+ if generation_config.forced_decoder_ids is not None and len(generation_config.forced_decoder_ids) > 0:
528
+ # generation starts after the last token that is forced
529
+ begin_index += generation_config.forced_decoder_ids[-1][0]
530
+ processors.append(
531
+ FlaxSuppressTokensAtBeginLogitsProcessor(generation_config.begin_suppress_tokens, begin_index)
532
+ )
533
+ if generation_config.forced_decoder_ids is not None:
534
+ forced_decoder_ids = [
535
+ [input_ids_seq_length + i[0] - 1, i[1]] for i in generation_config.forced_decoder_ids
536
+ ]
537
+ processors.append(FlaxForceTokensLogitsProcessor(forced_decoder_ids))
538
+ processors = self._merge_criteria_processor_list(processors, logits_processor)
539
+
540
+ return processors
541
+
542
+ def _merge_criteria_processor_list(
543
+ self,
544
+ default_list: FlaxLogitsProcessorList,
545
+ custom_list: FlaxLogitsProcessorList,
546
+ ) -> FlaxLogitsProcessorList:
547
+ if len(custom_list) == 0:
548
+ return default_list
549
+ for default in default_list:
550
+ for custom in custom_list:
551
+ if type(custom) is type(default):
552
+ object_type = "logits processor"
553
+ raise ValueError(
554
+ f"A custom {object_type} of type {type(custom)} with values {custom} has been passed to"
555
+ f" `generate`, but it has already been created with the values {default}. {default} has been"
556
+ " created by passing the corresponding arguments to generate or by the model's config default"
557
+ f" values. If you just want to change the default values of {object_type} consider passing"
558
+ f" them as arguments to `generate` instead of using a custom {object_type}."
559
+ )
560
+ default_list.extend(custom_list)
561
+ return default_list
562
+
563
+ def _greedy_search(
564
+ self,
565
+ input_ids: None,
566
+ max_length: Optional[int] = None,
567
+ pad_token_id: Optional[int] = None,
568
+ eos_token_id: Optional[int] = None,
569
+ logits_processor: Optional[FlaxLogitsProcessorList] = None,
570
+ trace: bool = True,
571
+ params: Optional[Dict[str, jnp.ndarray]] = None,
572
+ model_kwargs: Optional[Dict[str, jnp.ndarray]] = None,
573
+ ):
574
+ # init values
575
+ max_length = max_length if max_length is not None else self.generation_config.max_length
576
+ pad_token_id = pad_token_id if pad_token_id is not None else self.generation_config.pad_token_id
577
+ eos_token_id = eos_token_id if eos_token_id is not None else self.generation_config.eos_token_id
578
+
579
+ batch_size, cur_len = input_ids.shape
580
+
581
+ eos_token_id = jnp.array(eos_token_id, dtype=jnp.int32 if eos_token_id is not None else None)
582
+ pad_token_id = jnp.array(pad_token_id, dtype=jnp.int32)
583
+ cur_len = jnp.array(cur_len)
584
+
585
+ # per batch-item holding current token in loop.
586
+ sequences = jnp.full((batch_size, max_length), pad_token_id, dtype=jnp.int32)
587
+ sequences = lax.dynamic_update_slice(sequences, input_ids, (0, 0))
588
+
589
+ # per batch-item state bit indicating if sentence has finished.
590
+ is_sent_finished = jnp.zeros((batch_size,), dtype=jnp.bool_)
591
+
592
+ # For Seq2Seq generation, we only need to use the decoder instead of the whole model in generation loop
593
+ # and pass it the `encoder_outputs`, which are part of the `model_kwargs`.
594
+ model = self.decode if self.config.is_encoder_decoder else self
595
+ # initialize model specific kwargs
596
+ model_kwargs = self.prepare_inputs_for_generation(input_ids, max_length, **model_kwargs)
597
+
598
+ # initialize state
599
+ state = GreedyState(
600
+ cur_len=cur_len,
601
+ sequences=sequences,
602
+ running_token=input_ids,
603
+ is_sent_finished=is_sent_finished,
604
+ model_kwargs=model_kwargs,
605
+ )
606
+
607
+ def greedy_search_cond_fn(state):
608
+ """state termination condition fn."""
609
+ has_reached_max_length = state.cur_len == max_length
610
+ all_sequence_finished = jnp.all(state.is_sent_finished)
611
+ finish_generation = jnp.logical_or(has_reached_max_length, all_sequence_finished)
612
+ return ~finish_generation
613
+
614
+ def greedy_search_body_fn(state):
615
+ """state update fn."""
616
+ model_outputs = model(state.running_token, params=params, **state.model_kwargs)
617
+ logits = model_outputs.logits[:, -1]
618
+
619
+ # apply min_length, ...
620
+ logits = logits_processor(state.sequences, logits, state.cur_len)
621
+
622
+ next_token = jnp.argmax(logits, axis=-1)
623
+
624
+ next_token = next_token * ~state.is_sent_finished + pad_token_id * state.is_sent_finished
625
+ next_is_sent_finished = state.is_sent_finished | (next_token == eos_token_id)
626
+ next_token = next_token[:, None]
627
+
628
+ next_sequences = lax.dynamic_update_slice(state.sequences, next_token, (0, state.cur_len))
629
+ next_model_kwargs = self.update_inputs_for_generation(model_outputs, state.model_kwargs)
630
+ return GreedyState(
631
+ cur_len=state.cur_len + 1,
632
+ sequences=next_sequences,
633
+ running_token=next_token,
634
+ is_sent_finished=next_is_sent_finished,
635
+ model_kwargs=next_model_kwargs,
636
+ )
637
+
638
+ # The very first prompt often has sequence length > 1, so run outside of `lax.while_loop` to comply with TPU
639
+ if input_ids.shape[1] > 1:
640
+ state = greedy_search_body_fn(state)
641
+
642
+ if not trace:
643
+ state = self._run_loop_in_debug(greedy_search_cond_fn, greedy_search_body_fn, state)
644
+ else:
645
+ state = lax.while_loop(greedy_search_cond_fn, greedy_search_body_fn, state)
646
+
647
+ return FlaxGreedySearchOutput(sequences=state.sequences)
648
+
649
+ def _sample(
650
+ self,
651
+ input_ids: None,
652
+ max_length: Optional[int] = None,
653
+ pad_token_id: Optional[int] = None,
654
+ eos_token_id: Optional[int] = None,
655
+ prng_key: Optional[jnp.ndarray] = None,
656
+ logits_processor: Optional[FlaxLogitsProcessorList] = None,
657
+ logits_warper: Optional[FlaxLogitsProcessorList] = None,
658
+ trace: bool = True,
659
+ params: Optional[Dict[str, jnp.ndarray]] = None,
660
+ model_kwargs: Optional[Dict[str, jnp.ndarray]] = None,
661
+ ):
662
+ # init values
663
+ max_length = max_length if max_length is not None else self.generation_config.max_length
664
+ pad_token_id = pad_token_id if pad_token_id is not None else self.generation_config.pad_token_id
665
+ eos_token_id = eos_token_id if eos_token_id is not None else self.generation_config.eos_token_id
666
+ prng_key = prng_key if prng_key is not None else jax.random.PRNGKey(0)
667
+
668
+ batch_size, cur_len = input_ids.shape
669
+
670
+ eos_token_id = jnp.array(eos_token_id, dtype=jnp.int32 if eos_token_id is not None else None)
671
+ pad_token_id = jnp.array(pad_token_id, dtype=jnp.int32)
672
+ cur_len = jnp.array(cur_len)
673
+
674
+ # per batch-item holding current token in loop.
675
+ sequences = jnp.full((batch_size, max_length), pad_token_id, dtype=jnp.int32)
676
+ sequences = lax.dynamic_update_slice(sequences, input_ids, (0, 0))
677
+
678
+ # per batch-item state bit indicating if sentence has finished.
679
+ is_sent_finished = jnp.zeros((batch_size,), dtype=jnp.bool_)
680
+
681
+ # For Seq2Seq generation, we only need to use the decoder instead of the whole model in generation loop
682
+ # and pass it the `encoder_outputs`, which are part of the `model_kwargs`.
683
+ model = self.decode if self.config.is_encoder_decoder else self
684
+
685
+ # initialize model specific kwargs
686
+ model_kwargs = self.prepare_inputs_for_generation(input_ids, max_length, **model_kwargs)
687
+
688
+ # initialize state
689
+ state = SampleState(
690
+ cur_len=cur_len,
691
+ sequences=sequences,
692
+ running_token=input_ids,
693
+ is_sent_finished=is_sent_finished,
694
+ prng_key=prng_key,
695
+ model_kwargs=model_kwargs,
696
+ )
697
+
698
+ def sample_search_cond_fn(state):
699
+ """state termination condition fn."""
700
+ has_reached_max_length = state.cur_len == max_length
701
+ all_sequence_finished = jnp.all(state.is_sent_finished)
702
+ finish_generation = jnp.logical_or(has_reached_max_length, all_sequence_finished)
703
+ return ~finish_generation
704
+
705
+ def sample_search_body_fn(state):
706
+ """state update fn."""
707
+ prng_key, prng_key_next = jax.random.split(state.prng_key)
708
+ model_outputs = model(state.running_token, params=params, **state.model_kwargs)
709
+
710
+ logits = model_outputs.logits[:, -1]
711
+
712
+ # apply min_length, ...
713
+ logits = logits_processor(state.sequences, logits, state.cur_len)
714
+ # apply top_p, top_k, temperature
715
+ logits = logits_warper(logits, logits, state.cur_len)
716
+
717
+ next_token = jax.random.categorical(prng_key, logits, axis=-1)
718
+
719
+ next_token = next_token * ~state.is_sent_finished + pad_token_id * state.is_sent_finished
720
+ next_is_sent_finished = state.is_sent_finished | (next_token == eos_token_id)
721
+ next_token = next_token[:, None]
722
+
723
+ next_sequences = lax.dynamic_update_slice(state.sequences, next_token, (0, state.cur_len))
724
+ next_model_kwargs = self.update_inputs_for_generation(model_outputs, state.model_kwargs)
725
+
726
+ return SampleState(
727
+ cur_len=state.cur_len + 1,
728
+ sequences=next_sequences,
729
+ running_token=next_token,
730
+ is_sent_finished=next_is_sent_finished,
731
+ model_kwargs=next_model_kwargs,
732
+ prng_key=prng_key_next,
733
+ )
734
+
735
+ # The very first prompt often has sequence length > 1, so run outside of `lax.while_loop` to comply with TPU
736
+ if input_ids.shape[1] > 1:
737
+ state = sample_search_body_fn(state)
738
+
739
+ if not trace:
740
+ state = self._run_loop_in_debug(sample_search_cond_fn, sample_search_body_fn, state)
741
+ else:
742
+ state = lax.while_loop(sample_search_cond_fn, sample_search_body_fn, state)
743
+
744
+ return FlaxSampleOutput(sequences=state.sequences)
745
+
746
+ def _beam_search(
747
+ self,
748
+ input_ids: None,
749
+ max_length: Optional[int] = None,
750
+ pad_token_id: Optional[int] = None,
751
+ eos_token_id: Optional[int] = None,
752
+ length_penalty: Optional[float] = None,
753
+ early_stopping: Optional[Union[bool, str]] = None,
754
+ logits_processor: Optional[FlaxLogitsProcessorList] = None,
755
+ trace: bool = True,
756
+ params: Optional[Dict[str, jnp.ndarray]] = None,
757
+ num_return_sequences: Optional[int] = None,
758
+ model_kwargs: Optional[Dict[str, jnp.ndarray]] = None,
759
+ ):
760
+ """
761
+ This beam search function is heavily inspired by Flax's official example:
762
+ https://github.com/google/flax/blob/main/examples/wmt/decode.py
763
+ """
764
+
765
+ def flatten_beam_dim(tensor):
766
+ """Flattens the first two dimensions of a non-scalar array."""
767
+ # ignore scalars (e.g. cache index)
768
+ if tensor.ndim == 0:
769
+ return tensor
770
+ return tensor.reshape((tensor.shape[0] * tensor.shape[1],) + tensor.shape[2:])
771
+
772
+ def unflatten_beam_dim(tensor, batch_size, num_beams):
773
+ """Unflattens the first, flat batch*beam dimension of a non-scalar array."""
774
+ # ignore scalars (e.g. cache index)
775
+ if tensor.ndim == 0:
776
+ return tensor
777
+ return tensor.reshape((batch_size, num_beams) + tensor.shape[1:])
778
+
779
+ def gather_beams(nested, beam_indices, batch_size, new_num_beams):
780
+ """
781
+ Gathers the beam slices indexed by beam_indices into new beam array.
782
+ """
783
+ batch_indices = jnp.reshape(
784
+ jnp.arange(batch_size * new_num_beams) // new_num_beams, (batch_size, new_num_beams)
785
+ )
786
+
787
+ def gather_fn(tensor):
788
+ # ignore scalars (e.g. cache index)
789
+ if tensor.ndim == 0:
790
+ return tensor
791
+ else:
792
+ return tensor[batch_indices, beam_indices]
793
+
794
+ return jax.tree_util.tree_map(gather_fn, nested)
795
+
796
+ # init values
797
+ max_length = max_length if max_length is not None else self.generation_config.max_length
798
+ pad_token_id = pad_token_id if pad_token_id is not None else self.generation_config.pad_token_id
799
+ eos_token_id = eos_token_id if eos_token_id is not None else self.generation_config.eos_token_id
800
+ length_penalty = length_penalty if length_penalty is not None else self.generation_config.length_penalty
801
+ early_stopping = early_stopping if early_stopping is not None else self.generation_config.early_stopping
802
+ num_return_sequences = (
803
+ num_return_sequences if num_return_sequences is not None else self.generation_config.num_return_sequences
804
+ )
805
+
806
+ batch_size, num_beams, cur_len = input_ids.shape
807
+
808
+ eos_token_id = jnp.array(eos_token_id, dtype=jnp.int32 if eos_token_id is not None else None)
809
+ pad_token_id = jnp.array(pad_token_id, dtype=jnp.int32)
810
+ cur_len = jnp.array(cur_len)
811
+
812
+ # record the prompt length of decoder
813
+ decoder_prompt_len = input_ids.shape[-1]
814
+
815
+ # per batch,beam-item holding current token in loop.
816
+ sequences = jnp.full((batch_size, num_beams, max_length), pad_token_id, dtype=jnp.int32)
817
+ running_sequences = jnp.full((batch_size, num_beams, max_length), pad_token_id, dtype=jnp.int32)
818
+ running_sequences = lax.dynamic_update_slice(sequences, input_ids, (0, 0, 0))
819
+
820
+ # per batch,beam-item state bit indicating if sentence has finished.
821
+ is_sent_finished = jnp.zeros((batch_size, num_beams), dtype=jnp.bool_)
822
+
823
+ # per batch,beam-item score, logprobs
824
+ running_scores = jnp.tile(jnp.array([0.0] + [np.array(-1.0e7)] * (num_beams - 1)), [batch_size, 1])
825
+ scores = jnp.ones((batch_size, num_beams)) * np.array(-1.0e7)
826
+
827
+ # For Seq2Seq generation, we only need to use the decoder instead of the whole model in generation loop
828
+ # and pass it the `encoder_outputs`, which are part of the `model_kwargs`.
829
+ model = self.decode if self.config.is_encoder_decoder else self
830
+
831
+ # flatten beam dim
832
+ if "encoder_outputs" in model_kwargs:
833
+ model_kwargs["encoder_outputs"]["last_hidden_state"] = flatten_beam_dim(
834
+ model_kwargs["encoder_outputs"]["last_hidden_state"]
835
+ )
836
+ for kwarg in ["attention_mask", "decoder_attention_mask"]:
837
+ if kwarg in model_kwargs:
838
+ model_kwargs[kwarg] = flatten_beam_dim(model_kwargs[kwarg])
839
+
840
+ # initialize model specific kwargs
841
+ model_kwargs = self.prepare_inputs_for_generation(flatten_beam_dim(input_ids), max_length, **model_kwargs)
842
+
843
+ # initialize state
844
+ state = BeamSearchState(
845
+ cur_len=cur_len,
846
+ running_sequences=running_sequences,
847
+ running_scores=running_scores,
848
+ sequences=sequences,
849
+ scores=scores,
850
+ is_sent_finished=is_sent_finished,
851
+ model_kwargs=model_kwargs,
852
+ )
853
+
854
+ def beam_search_cond_fn(state):
855
+ """beam search state termination condition fn."""
856
+
857
+ # 1. is less than max length?
858
+ not_max_length_yet = state.cur_len < max_length
859
+
860
+ # 2. can the new beams still improve?
861
+ # early_stopping == False -> apply heuristic = always get the best score from `cur_len`. See the discussion
862
+ # below for more details.
863
+ # https://github.com/huggingface/transformers/pull/20901#issuecomment-1369845565
864
+ # early_stopping == "never" -> compute the best score from max_length or cur_len, depending on the sign of
865
+ # length_penalty. Positive length_penalty favors longer sequences, thus we use max_length there.
866
+ if early_stopping == "never" and length_penalty > 0.0:
867
+ best_running_score = state.running_scores[:, :1] / (
868
+ (max_length - decoder_prompt_len) ** length_penalty
869
+ )
870
+ else:
871
+ best_running_score = state.running_scores[:, :1] / (
872
+ (state.cur_len - decoder_prompt_len) ** length_penalty
873
+ )
874
+ worst_finished_score = jnp.where(
875
+ state.is_sent_finished, jnp.min(state.scores, axis=1, keepdims=True), np.array(-1.0e7)
876
+ )
877
+ improvement_still_possible = jnp.any(best_running_score > worst_finished_score)
878
+
879
+ # 3. is there still a beam that has not finished?
880
+ still_open_beam = ~(jnp.all(state.is_sent_finished) & (early_stopping is True))
881
+
882
+ return not_max_length_yet & still_open_beam & improvement_still_possible
883
+
884
+ def beam_search_body_fn(state, input_ids_length=1):
885
+ """beam search state update fn."""
886
+ # 1. Forward current tokens
887
+ # Collect the current position slice along length to feed the fast
888
+ # autoregressive decoder model. Flatten the beam dimension into batch
889
+ # dimension for feeding into the model.
890
+ # unflatten beam dimension
891
+ # Unflatten beam dimension in attention cache arrays
892
+ input_token = flatten_beam_dim(
893
+ lax.dynamic_slice(
894
+ state.running_sequences,
895
+ (0, 0, state.cur_len - input_ids_length),
896
+ (batch_size, num_beams, input_ids_length),
897
+ )
898
+ )
899
+ model_outputs = model(input_token, params=params, **state.model_kwargs)
900
+
901
+ logits = unflatten_beam_dim(model_outputs.logits[:, -1], batch_size, num_beams)
902
+ cache = jax.tree_util.tree_map(
903
+ lambda tensor: unflatten_beam_dim(tensor, batch_size, num_beams), model_outputs.past_key_values
904
+ )
905
+
906
+ # adapt logits for FlaxMarianMTModel
907
+ logits = self._adapt_logits_for_beam_search(logits)
908
+
909
+ # 2. Compute log probs
910
+ # get log probabilities from logits,
911
+ # process logits with processors (*e.g.* min_length, ...), and
912
+ # add new logprobs to existing running logprobs scores.
913
+ log_probs = jax.nn.log_softmax(logits)
914
+ log_probs = logits_processor(
915
+ flatten_beam_dim(running_sequences), flatten_beam_dim(log_probs), state.cur_len
916
+ )
917
+ log_probs = unflatten_beam_dim(log_probs, batch_size, num_beams)
918
+ log_probs = log_probs + jnp.expand_dims(state.running_scores, axis=2)
919
+ vocab_size = log_probs.shape[2]
920
+ log_probs = log_probs.reshape((batch_size, num_beams * vocab_size))
921
+
922
+ # 3. Retrieve top-K
923
+ # Each item in batch has num_beams * vocab_size candidate sequences.
924
+ # For each item, get the top 2*k candidates with the highest log-
925
+ # probabilities. We gather the top 2*K beams here so that even if the best
926
+ # K sequences reach EOS simultaneously, we have another K sequences
927
+ # remaining to continue the live beam search.
928
+ # Gather the top 2*K scores from _all_ beams.
929
+ # Gather 2*k top beams.
930
+ # Recover the beam index by floor division.
931
+ # Recover token id by modulo division and expand Id array for broadcasting.
932
+ # Update sequences for the 2*K top-k new sequences.
933
+ beams_to_keep = 2 * num_beams
934
+ topk_log_probs, topk_indices = lax.top_k(log_probs, k=beams_to_keep)
935
+ topk_beam_indices = topk_indices // vocab_size
936
+ topk_running_sequences = gather_beams(
937
+ state.running_sequences, topk_beam_indices, batch_size, beams_to_keep
938
+ )
939
+ topk_ids = jnp.expand_dims(topk_indices % vocab_size, axis=2)
940
+ topk_sequences = lax.dynamic_update_slice(topk_running_sequences, topk_ids, (0, 0, state.cur_len))
941
+
942
+ # 4. Check which sequences have ended
943
+ # Update current sequences:
944
+ # Did any of these sequences reach an end marker?
945
+ # To prevent these just finished sequences from being added to the current sequences
946
+ # set of active beam search sequences, set their log probs to a very large
947
+ # negative value.
948
+ did_topk_just_finished = topk_sequences[:, :, state.cur_len] == eos_token_id
949
+ running_topk_log_probs = topk_log_probs + did_topk_just_finished * np.array(-1.0e7)
950
+ # 5. Get running sequences scores for next
951
+ # Determine the top k beam indices (from top 2*k beams) from log probs
952
+ # and gather top k beams (from top 2*k beams).
953
+ next_topk_indices = lax.top_k(running_topk_log_probs, k=num_beams)[1]
954
+ next_running_sequences, next_running_scores = gather_beams(
955
+ [topk_sequences, running_topk_log_probs], next_topk_indices, batch_size, num_beams
956
+ )
957
+
958
+ # 6. Process topk logits
959
+ # Further process log probs:
960
+ # - add length penalty
961
+ # - make sure no scores can be added anymore if beam is full
962
+ # - make sure still running sequences cannot be chosen as finalized beam
963
+ topk_log_probs = topk_log_probs / ((state.cur_len + 1 - decoder_prompt_len) ** length_penalty)
964
+ beams_in_batch_are_full = jnp.broadcast_to(
965
+ state.is_sent_finished.all(axis=-1, keepdims=True), did_topk_just_finished.shape
966
+ ) & (early_stopping is True)
967
+ add_penalty = ~did_topk_just_finished | beams_in_batch_are_full
968
+ topk_log_probs += add_penalty * np.array(-1.0e7)
969
+
970
+ # 7. Get scores, sequences, is sentence finished for next.
971
+ # Combine sequences, scores, and flags along the beam dimension and compare
972
+ # new finished sequence scores to existing finished scores and select the
973
+ # best from the new set of beams
974
+ merged_sequences = jnp.concatenate([state.sequences, topk_sequences], axis=1)
975
+ merged_scores = jnp.concatenate([state.scores, topk_log_probs], axis=1)
976
+ merged_is_sent_finished = jnp.concatenate([state.is_sent_finished, did_topk_just_finished], axis=1)
977
+ topk_merged_indices = lax.top_k(merged_scores, k=num_beams)[1]
978
+ next_sequences, next_scores, next_is_sent_finished = gather_beams(
979
+ [merged_sequences, merged_scores, merged_is_sent_finished], topk_merged_indices, batch_size, num_beams
980
+ )
981
+
982
+ # 8. Update model kwargs.
983
+ # Determine the top k beam indices from the original set of all beams.
984
+ # With these, gather the top k beam-associated caches.
985
+ next_running_indices = gather_beams(topk_beam_indices, next_topk_indices, batch_size, num_beams)
986
+ next_cache = gather_beams(cache, next_running_indices, batch_size, num_beams)
987
+ model_outputs["past_key_values"] = jax.tree_util.tree_map(lambda x: flatten_beam_dim(x), next_cache)
988
+ next_model_kwargs = self.update_inputs_for_generation(model_outputs, state.model_kwargs)
989
+
990
+ return BeamSearchState(
991
+ cur_len=state.cur_len + 1,
992
+ running_scores=next_running_scores,
993
+ running_sequences=next_running_sequences,
994
+ scores=next_scores,
995
+ sequences=next_sequences,
996
+ is_sent_finished=next_is_sent_finished,
997
+ model_kwargs=next_model_kwargs,
998
+ )
999
+
1000
+ # Always run first iteration outside of `lax.while_loop` to avoid calling `beam_search_cond_fn`
1001
+ # when `state.cur_len` equals `decoder_prompt_len`. This also helps to comply with TPU when
1002
+ # the very first prompt has sequence length > 1.
1003
+ state = partial(beam_search_body_fn, input_ids_length=input_ids.shape[-1])(state)
1004
+
1005
+ if not trace:
1006
+ state = self._run_loop_in_debug(beam_search_cond_fn, beam_search_body_fn, state)
1007
+ else:
1008
+ state = lax.while_loop(beam_search_cond_fn, beam_search_body_fn, state)
1009
+
1010
+ # Account for the edge-case where there are no finished sequences for a
1011
+ # particular batch item. If so, return running sequences for that batch item.
1012
+ none_finished = jnp.any(state.is_sent_finished, axis=1)
1013
+ sequences = jnp.where(none_finished[:, None, None], state.sequences, state.running_sequences)
1014
+ scores = jnp.where(none_finished[:, None], state.scores, state.running_scores)
1015
+
1016
+ # Take best beams for each batch (the score is sorted in descending order)
1017
+ sequences = flatten_beam_dim(sequences[:, :num_return_sequences, :])
1018
+ scores = flatten_beam_dim(scores[:, :num_return_sequences])
1019
+
1020
+ return FlaxBeamSearchOutput(sequences=sequences, scores=scores)
pllava/lib/python3.10/site-packages/transformers/generation/logits_process.py ADDED
The diff for this file is too large to render. See raw diff
 
pllava/lib/python3.10/site-packages/transformers/generation/stopping_criteria.py ADDED
@@ -0,0 +1,151 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import time
2
+ import warnings
3
+ from abc import ABC
4
+ from copy import deepcopy
5
+ from typing import Optional
6
+
7
+ import torch
8
+
9
+ from ..utils import add_start_docstrings, logging
10
+
11
+
12
+ logger = logging.get_logger(__name__)
13
+
14
+
15
+ STOPPING_CRITERIA_INPUTS_DOCSTRING = r"""
16
+ Args:
17
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
18
+ Indices of input sequence tokens in the vocabulary.
19
+
20
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
21
+ [`PreTrainedTokenizer.__call__`] for details.
22
+
23
+ [What are input IDs?](../glossary#input-ids)
24
+ scores (`torch.FloatTensor` of shape `(batch_size, config.vocab_size)`):
25
+ Prediction scores of a language modeling head. These can be scores for each vocabulary token before SoftMax
26
+ or scores for each vocabulary token after SoftMax. If this stopping criteria depends on the `scores` input,
27
+ make sure you pass `return_dict_in_generate=True, output_scores=True` to `generate`.
28
+ kwargs (`Dict[str, Any]`, *optional*):
29
+ Additional stopping criteria specific kwargs.
30
+
31
+ Return:
32
+ `bool`. `False` indicates we should continue, `True` indicates we should stop.
33
+
34
+ """
35
+
36
+
37
+ class StoppingCriteria(ABC):
38
+ """Abstract base class for all stopping criteria that can be applied during generation.
39
+
40
+ If your stopping criteria depends on the `scores` input, make sure you pass `return_dict_in_generate=True,
41
+ output_scores=True` to `generate`.
42
+ """
43
+
44
+ @add_start_docstrings(STOPPING_CRITERIA_INPUTS_DOCSTRING)
45
+ def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor, **kwargs) -> bool:
46
+ raise NotImplementedError("StoppingCriteria needs to be subclassed")
47
+
48
+
49
+ class MaxLengthCriteria(StoppingCriteria):
50
+ """
51
+ This class can be used to stop generation whenever the full generated number of tokens exceeds `max_length`. Keep
52
+ in mind for decoder-only type of transformers, this will include the initial prompted tokens.
53
+
54
+ Args:
55
+ max_length (`int`):
56
+ The maximum length that the output sequence can have in number of tokens.
57
+ max_position_embeddings (`int`, *optional*):
58
+ The maximum model length, as defined by the model's `config.max_position_embeddings` attribute.
59
+ """
60
+
61
+ def __init__(self, max_length: int, max_position_embeddings: Optional[int] = None):
62
+ self.max_length = max_length
63
+ self.max_position_embeddings = max_position_embeddings
64
+
65
+ @add_start_docstrings(STOPPING_CRITERIA_INPUTS_DOCSTRING)
66
+ def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor, **kwargs) -> bool:
67
+ cur_len = input_ids.shape[-1]
68
+ is_done = cur_len >= self.max_length
69
+ if self.max_position_embeddings is not None and not is_done and cur_len >= self.max_position_embeddings:
70
+ logger.warning_once(
71
+ "This is a friendly reminder - the current text generation call will exceed the model's predefined "
72
+ f"maximum length ({self.max_position_embeddings}). Depending on the model, you may observe "
73
+ "exceptions, performance degradation, or nothing at all."
74
+ )
75
+ return is_done
76
+
77
+
78
+ class MaxNewTokensCriteria(StoppingCriteria):
79
+ """
80
+ This class can be used to stop generation whenever the generated number of tokens exceeds `max_new_tokens`. Keep in
81
+ mind for decoder-only type of transformers, this will **not** include the initial prompted tokens. This is very
82
+ close to `MaxLengthCriteria` but ignores the number of initial tokens.
83
+
84
+ Args:
85
+ start_length (`int`):
86
+ The number of initial tokens.
87
+ max_new_tokens (`int`):
88
+ The maximum number of tokens to generate.
89
+ """
90
+
91
+ def __init__(self, start_length: int, max_new_tokens: int):
92
+ warnings.warn(
93
+ "The class `MaxNewTokensCriteria` is deprecated. "
94
+ f"Please use `MaxLengthCriteria(max_length={start_length + max_new_tokens})` "
95
+ "with `max_length = start_length + max_new_tokens` instead.",
96
+ FutureWarning,
97
+ )
98
+ self.start_length = start_length
99
+ self.max_new_tokens = max_new_tokens
100
+ self.max_length = start_length + max_new_tokens
101
+
102
+ @add_start_docstrings(STOPPING_CRITERIA_INPUTS_DOCSTRING)
103
+ def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor, **kwargs) -> bool:
104
+ return input_ids.shape[-1] >= self.max_length
105
+
106
+
107
+ class MaxTimeCriteria(StoppingCriteria):
108
+ """
109
+ This class can be used to stop generation whenever the full generation exceeds some amount of time. By default, the
110
+ time will start being counted when you initialize this function. You can override this by passing an
111
+ `initial_time`.
112
+
113
+ Args:
114
+ max_time (`float`):
115
+ The maximum allowed time in seconds for the generation.
116
+ initial_time (`float`, *optional*, defaults to `time.time()`):
117
+ The start of the generation allowed time.
118
+ """
119
+
120
+ def __init__(self, max_time: float, initial_timestamp: Optional[float] = None):
121
+ self.max_time = max_time
122
+ self.initial_timestamp = time.time() if initial_timestamp is None else initial_timestamp
123
+
124
+ @add_start_docstrings(STOPPING_CRITERIA_INPUTS_DOCSTRING)
125
+ def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor, **kwargs) -> bool:
126
+ return time.time() - self.initial_timestamp > self.max_time
127
+
128
+
129
+ class StoppingCriteriaList(list):
130
+ @add_start_docstrings(STOPPING_CRITERIA_INPUTS_DOCSTRING)
131
+ def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor, **kwargs) -> bool:
132
+ return any(criteria(input_ids, scores) for criteria in self)
133
+
134
+ @property
135
+ def max_length(self) -> Optional[int]:
136
+ for stopping_criterium in self:
137
+ if isinstance(stopping_criterium, MaxLengthCriteria):
138
+ return stopping_criterium.max_length
139
+ elif isinstance(stopping_criterium, MaxNewTokensCriteria):
140
+ return stopping_criterium.max_length
141
+ return None
142
+
143
+
144
+ def validate_stopping_criteria(stopping_criteria: StoppingCriteriaList, max_length: int) -> StoppingCriteriaList:
145
+ stopping_max_length = stopping_criteria.max_length
146
+ new_stopping_criteria = deepcopy(stopping_criteria)
147
+ if stopping_max_length is not None and stopping_max_length != max_length:
148
+ warnings.warn("You set different `max_length` for stopping criteria and `max_length` parameter", UserWarning)
149
+ elif stopping_max_length is None:
150
+ new_stopping_criteria.append(MaxLengthCriteria(max_length=max_length))
151
+ return new_stopping_criteria
pllava/lib/python3.10/site-packages/transformers/models/beit/__init__.py ADDED
@@ -0,0 +1,112 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2021 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_torch_available,
22
+ is_vision_available,
23
+ )
24
+
25
+
26
+ _import_structure = {"configuration_beit": ["BEIT_PRETRAINED_CONFIG_ARCHIVE_MAP", "BeitConfig", "BeitOnnxConfig"]}
27
+
28
+ try:
29
+ if not is_vision_available():
30
+ raise OptionalDependencyNotAvailable()
31
+ except OptionalDependencyNotAvailable:
32
+ pass
33
+ else:
34
+ _import_structure["feature_extraction_beit"] = ["BeitFeatureExtractor"]
35
+ _import_structure["image_processing_beit"] = ["BeitImageProcessor"]
36
+
37
+ try:
38
+ if not is_torch_available():
39
+ raise OptionalDependencyNotAvailable()
40
+ except OptionalDependencyNotAvailable:
41
+ pass
42
+ else:
43
+ _import_structure["modeling_beit"] = [
44
+ "BEIT_PRETRAINED_MODEL_ARCHIVE_LIST",
45
+ "BeitForImageClassification",
46
+ "BeitForMaskedImageModeling",
47
+ "BeitForSemanticSegmentation",
48
+ "BeitModel",
49
+ "BeitPreTrainedModel",
50
+ "BeitBackbone",
51
+ ]
52
+
53
+
54
+ try:
55
+ if not is_flax_available():
56
+ raise OptionalDependencyNotAvailable()
57
+ except OptionalDependencyNotAvailable:
58
+ pass
59
+ else:
60
+ _import_structure["modeling_flax_beit"] = [
61
+ "FlaxBeitForImageClassification",
62
+ "FlaxBeitForMaskedImageModeling",
63
+ "FlaxBeitModel",
64
+ "FlaxBeitPreTrainedModel",
65
+ ]
66
+
67
+ if TYPE_CHECKING:
68
+ from .configuration_beit import BEIT_PRETRAINED_CONFIG_ARCHIVE_MAP, BeitConfig, BeitOnnxConfig
69
+
70
+ try:
71
+ if not is_vision_available():
72
+ raise OptionalDependencyNotAvailable()
73
+ except OptionalDependencyNotAvailable:
74
+ pass
75
+ else:
76
+ from .feature_extraction_beit import BeitFeatureExtractor
77
+ from .image_processing_beit import BeitImageProcessor
78
+
79
+ try:
80
+ if not is_torch_available():
81
+ raise OptionalDependencyNotAvailable()
82
+ except OptionalDependencyNotAvailable:
83
+ pass
84
+ else:
85
+ from .modeling_beit import (
86
+ BEIT_PRETRAINED_MODEL_ARCHIVE_LIST,
87
+ BeitBackbone,
88
+ BeitForImageClassification,
89
+ BeitForMaskedImageModeling,
90
+ BeitForSemanticSegmentation,
91
+ BeitModel,
92
+ BeitPreTrainedModel,
93
+ )
94
+
95
+ try:
96
+ if not is_flax_available():
97
+ raise OptionalDependencyNotAvailable()
98
+ except OptionalDependencyNotAvailable:
99
+ pass
100
+ else:
101
+ from .modeling_flax_beit import (
102
+ FlaxBeitForImageClassification,
103
+ FlaxBeitForMaskedImageModeling,
104
+ FlaxBeitModel,
105
+ FlaxBeitPreTrainedModel,
106
+ )
107
+
108
+
109
+ else:
110
+ import sys
111
+
112
+ sys.modules[__name__] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
pllava/lib/python3.10/site-packages/transformers/models/beit/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (1.66 kB). View file
 
pllava/lib/python3.10/site-packages/transformers/models/beit/__pycache__/configuration_beit.cpython-310.pyc ADDED
Binary file (10.2 kB). View file
 
pllava/lib/python3.10/site-packages/transformers/models/beit/__pycache__/convert_beit_unilm_to_pytorch.cpython-310.pyc ADDED
Binary file (10.9 kB). View file
 
pllava/lib/python3.10/site-packages/transformers/models/beit/__pycache__/feature_extraction_beit.cpython-310.pyc ADDED
Binary file (981 Bytes). View file
 
pllava/lib/python3.10/site-packages/transformers/models/beit/__pycache__/image_processing_beit.cpython-310.pyc ADDED
Binary file (18.3 kB). View file
 
pllava/lib/python3.10/site-packages/transformers/models/beit/__pycache__/modeling_beit.cpython-310.pyc ADDED
Binary file (44.7 kB). View file
 
pllava/lib/python3.10/site-packages/transformers/models/beit/__pycache__/modeling_flax_beit.cpython-310.pyc ADDED
Binary file (28.3 kB). View file
 
pllava/lib/python3.10/site-packages/transformers/models/beit/configuration_beit.py ADDED
@@ -0,0 +1,235 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright Microsoft Research 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
+ """ BEiT model configuration"""
16
+ from collections import OrderedDict
17
+ from typing import Mapping
18
+
19
+ from packaging import version
20
+
21
+ from ...configuration_utils import PretrainedConfig
22
+ from ...onnx import OnnxConfig
23
+ from ...utils import logging
24
+ from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices
25
+
26
+
27
+ logger = logging.get_logger(__name__)
28
+
29
+ BEIT_PRETRAINED_CONFIG_ARCHIVE_MAP = {
30
+ "microsoft/beit-base-patch16-224-pt22k": (
31
+ "https://huggingface.co/microsoft/beit-base-patch16-224-pt22k/resolve/main/config.json"
32
+ ),
33
+ # See all BEiT models at https://huggingface.co/models?filter=beit
34
+ }
35
+
36
+
37
+ class BeitConfig(BackboneConfigMixin, PretrainedConfig):
38
+ r"""
39
+ This is the configuration class to store the configuration of a [`BeitModel`]. It is used to instantiate an BEiT
40
+ model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
41
+ defaults will yield a similar configuration to that of the BEiT
42
+ [microsoft/beit-base-patch16-224-pt22k](https://huggingface.co/microsoft/beit-base-patch16-224-pt22k) architecture.
43
+
44
+ Args:
45
+ vocab_size (`int`, *optional*, defaults to 8192):
46
+ Vocabulary size of the BEiT model. Defines the number of different image tokens that can be used during
47
+ pre-training.
48
+ hidden_size (`int`, *optional*, defaults to 768):
49
+ Dimensionality of the encoder layers and the pooler layer.
50
+ num_hidden_layers (`int`, *optional*, defaults to 12):
51
+ Number of hidden layers in the Transformer encoder.
52
+ num_attention_heads (`int`, *optional*, defaults to 12):
53
+ Number of attention heads for each attention layer in the Transformer encoder.
54
+ intermediate_size (`int`, *optional*, defaults to 3072):
55
+ Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
56
+ hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):
57
+ The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
58
+ `"relu"`, `"selu"` and `"gelu_new"` are supported.
59
+ hidden_dropout_prob (`float`, *optional*, defaults to 0.0):
60
+ The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
61
+ attention_probs_dropout_prob (`float`, *optional*, defaults to 0.0):
62
+ The dropout ratio for the attention probabilities.
63
+ initializer_range (`float`, *optional*, defaults to 0.02):
64
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
65
+ layer_norm_eps (`float`, *optional*, defaults to 1e-12):
66
+ The epsilon used by the layer normalization layers.
67
+ image_size (`int`, *optional*, defaults to 224):
68
+ The size (resolution) of each image.
69
+ patch_size (`int`, *optional*, defaults to 16):
70
+ The size (resolution) of each patch.
71
+ num_channels (`int`, *optional*, defaults to 3):
72
+ The number of input channels.
73
+ use_mask_token (`bool`, *optional*, defaults to `False`):
74
+ Whether to use a mask token for masked image modeling.
75
+ use_absolute_position_embeddings (`bool`, *optional*, defaults to `False`):
76
+ Whether to use BERT-style absolute position embeddings.
77
+ use_relative_position_bias (`bool`, *optional*, defaults to `False`):
78
+ Whether to use T5-style relative position embeddings in the self-attention layers.
79
+ use_shared_relative_position_bias (`bool`, *optional*, defaults to `False`):
80
+ Whether to use the same relative position embeddings across all self-attention layers of the Transformer.
81
+ layer_scale_init_value (`float`, *optional*, defaults to 0.1):
82
+ Scale to use in the self-attention layers. 0.1 for base, 1e-5 for large. Set 0 to disable layer scale.
83
+ drop_path_rate (`float`, *optional*, defaults to 0.1):
84
+ Stochastic depth rate per sample (when applied in the main path of residual layers).
85
+ use_mean_pooling (`bool`, *optional*, defaults to `True`):
86
+ Whether to mean pool the final hidden states of the patches instead of using the final hidden state of the
87
+ CLS token, before applying the classification head.
88
+ pool_scales (`Tuple[int]`, *optional*, defaults to `[1, 2, 3, 6]`):
89
+ Pooling scales used in Pooling Pyramid Module applied on the last feature map.
90
+ use_auxiliary_head (`bool`, *optional*, defaults to `True`):
91
+ Whether to use an auxiliary head during training.
92
+ auxiliary_loss_weight (`float`, *optional*, defaults to 0.4):
93
+ Weight of the cross-entropy loss of the auxiliary head.
94
+ auxiliary_channels (`int`, *optional*, defaults to 256):
95
+ Number of channels to use in the auxiliary head.
96
+ auxiliary_num_convs (`int`, *optional*, defaults to 1):
97
+ Number of convolutional layers to use in the auxiliary head.
98
+ auxiliary_concat_input (`bool`, *optional*, defaults to `False`):
99
+ Whether to concatenate the output of the auxiliary head with the input before the classification layer.
100
+ semantic_loss_ignore_index (`int`, *optional*, defaults to 255):
101
+ The index that is ignored by the loss function of the semantic segmentation model.
102
+ out_features (`List[str]`, *optional*):
103
+ If used as backbone, list of features to output. Can be any of `"stem"`, `"stage1"`, `"stage2"`, etc.
104
+ (depending on how many stages the model has). If unset and `out_indices` is set, will default to the
105
+ corresponding stages. If unset and `out_indices` is unset, will default to the last stage. Must be in the
106
+ same order as defined in the `stage_names` attribute.
107
+ out_indices (`List[int]`, *optional*):
108
+ If used as backbone, list of indices of features to output. Can be any of 0, 1, 2, etc. (depending on how
109
+ many stages the model has). If unset and `out_features` is set, will default to the corresponding stages.
110
+ If unset and `out_features` is unset, will default to the last stage. Must be in the
111
+ same order as defined in the `stage_names` attribute.
112
+ add_fpn (`bool`, *optional*, defaults to `False`):
113
+ Whether to add a FPN as part of the backbone. Only relevant for [`BeitBackbone`].
114
+ reshape_hidden_states (`bool`, *optional*, defaults to `True`):
115
+ Whether to reshape the feature maps to 4D tensors of shape `(batch_size, hidden_size, height, width)` in
116
+ case the model is used as backbone. If `False`, the feature maps will be 3D tensors of shape `(batch_size,
117
+ seq_len, hidden_size)`. Only relevant for [`BeitBackbone`].
118
+
119
+ Example:
120
+
121
+ ```python
122
+ >>> from transformers import BeitConfig, BeitModel
123
+
124
+ >>> # Initializing a BEiT beit-base-patch16-224-pt22k style configuration
125
+ >>> configuration = BeitConfig()
126
+
127
+ >>> # Initializing a model (with random weights) from the beit-base-patch16-224-pt22k style configuration
128
+ >>> model = BeitModel(configuration)
129
+
130
+ >>> # Accessing the model configuration
131
+ >>> configuration = model.config
132
+ ```"""
133
+
134
+ model_type = "beit"
135
+
136
+ def __init__(
137
+ self,
138
+ vocab_size=8192,
139
+ hidden_size=768,
140
+ num_hidden_layers=12,
141
+ num_attention_heads=12,
142
+ intermediate_size=3072,
143
+ hidden_act="gelu",
144
+ hidden_dropout_prob=0.0,
145
+ attention_probs_dropout_prob=0.0,
146
+ initializer_range=0.02,
147
+ layer_norm_eps=1e-12,
148
+ image_size=224,
149
+ patch_size=16,
150
+ num_channels=3,
151
+ use_mask_token=False,
152
+ use_absolute_position_embeddings=False,
153
+ use_relative_position_bias=False,
154
+ use_shared_relative_position_bias=False,
155
+ layer_scale_init_value=0.1,
156
+ drop_path_rate=0.1,
157
+ use_mean_pooling=True,
158
+ pool_scales=[1, 2, 3, 6],
159
+ use_auxiliary_head=True,
160
+ auxiliary_loss_weight=0.4,
161
+ auxiliary_channels=256,
162
+ auxiliary_num_convs=1,
163
+ auxiliary_concat_input=False,
164
+ semantic_loss_ignore_index=255,
165
+ out_features=None,
166
+ out_indices=None,
167
+ add_fpn=False,
168
+ reshape_hidden_states=True,
169
+ **kwargs,
170
+ ):
171
+ super().__init__(**kwargs)
172
+
173
+ self.vocab_size = vocab_size
174
+ self.hidden_size = hidden_size
175
+ self.num_hidden_layers = num_hidden_layers
176
+ self.num_attention_heads = num_attention_heads
177
+ self.intermediate_size = intermediate_size
178
+ self.hidden_act = hidden_act
179
+ self.hidden_dropout_prob = hidden_dropout_prob
180
+ self.attention_probs_dropout_prob = attention_probs_dropout_prob
181
+ self.initializer_range = initializer_range
182
+ self.layer_norm_eps = layer_norm_eps
183
+
184
+ self.image_size = image_size
185
+ self.patch_size = patch_size
186
+ self.num_channels = num_channels
187
+ self.use_mask_token = use_mask_token
188
+ self.use_absolute_position_embeddings = use_absolute_position_embeddings
189
+ self.use_relative_position_bias = use_relative_position_bias
190
+ self.use_shared_relative_position_bias = use_shared_relative_position_bias
191
+ self.layer_scale_init_value = layer_scale_init_value
192
+ self.drop_path_rate = drop_path_rate
193
+ self.use_mean_pooling = use_mean_pooling
194
+ # decode head attributes (semantic segmentation)
195
+ self.pool_scales = pool_scales
196
+ # auxiliary head attributes (semantic segmentation)
197
+ self.use_auxiliary_head = use_auxiliary_head
198
+ self.auxiliary_loss_weight = auxiliary_loss_weight
199
+ self.auxiliary_channels = auxiliary_channels
200
+ self.auxiliary_num_convs = auxiliary_num_convs
201
+ self.auxiliary_concat_input = auxiliary_concat_input
202
+ self.semantic_loss_ignore_index = semantic_loss_ignore_index
203
+
204
+ # handle backwards compatibility
205
+ if "segmentation_indices" in kwargs:
206
+ logger.warning(
207
+ "The `segmentation_indices` argument is deprecated and will be removed in a future version, use `out_indices` instead.",
208
+ FutureWarning,
209
+ )
210
+ out_indices = kwargs.pop("segmentation_indices")
211
+
212
+ # backbone attributes
213
+ self.stage_names = ["stem"] + [f"stage{idx}" for idx in range(1, self.num_hidden_layers + 1)]
214
+ self._out_features, self._out_indices = get_aligned_output_features_output_indices(
215
+ out_features=out_features, out_indices=out_indices, stage_names=self.stage_names
216
+ )
217
+ self.add_fpn = add_fpn
218
+ self.reshape_hidden_states = reshape_hidden_states
219
+
220
+
221
+ # Copied from transformers.models.vit.configuration_vit.ViTOnnxConfig
222
+ class BeitOnnxConfig(OnnxConfig):
223
+ torch_onnx_minimum_version = version.parse("1.11")
224
+
225
+ @property
226
+ def inputs(self) -> Mapping[str, Mapping[int, str]]:
227
+ return OrderedDict(
228
+ [
229
+ ("pixel_values", {0: "batch", 1: "num_channels", 2: "height", 3: "width"}),
230
+ ]
231
+ )
232
+
233
+ @property
234
+ def atol_for_validation(self) -> float:
235
+ return 1e-4
pllava/lib/python3.10/site-packages/transformers/models/beit/convert_beit_unilm_to_pytorch.py ADDED
@@ -0,0 +1,374 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2021 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 BEiT checkpoints from the unilm repository."""
16
+
17
+
18
+ import argparse
19
+ import json
20
+ from pathlib import Path
21
+
22
+ import requests
23
+ import torch
24
+ from datasets import load_dataset
25
+ from huggingface_hub import hf_hub_download
26
+ from PIL import Image
27
+
28
+ from transformers import (
29
+ BeitConfig,
30
+ BeitForImageClassification,
31
+ BeitForMaskedImageModeling,
32
+ BeitForSemanticSegmentation,
33
+ BeitImageProcessor,
34
+ )
35
+ from transformers.image_utils import PILImageResampling
36
+ from transformers.utils import logging
37
+
38
+
39
+ logging.set_verbosity_info()
40
+ logger = logging.get_logger(__name__)
41
+
42
+
43
+ # here we list all keys to be renamed (original name on the left, our name on the right)
44
+ def create_rename_keys(config, has_lm_head=False, is_semantic=False):
45
+ prefix = "backbone." if is_semantic else ""
46
+
47
+ rename_keys = []
48
+ for i in range(config.num_hidden_layers):
49
+ # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms
50
+ rename_keys.append((f"{prefix}blocks.{i}.norm1.weight", f"beit.encoder.layer.{i}.layernorm_before.weight"))
51
+ rename_keys.append((f"{prefix}blocks.{i}.norm1.bias", f"beit.encoder.layer.{i}.layernorm_before.bias"))
52
+ rename_keys.append(
53
+ (f"{prefix}blocks.{i}.attn.proj.weight", f"beit.encoder.layer.{i}.attention.output.dense.weight")
54
+ )
55
+ rename_keys.append(
56
+ (f"{prefix}blocks.{i}.attn.proj.bias", f"beit.encoder.layer.{i}.attention.output.dense.bias")
57
+ )
58
+ rename_keys.append((f"{prefix}blocks.{i}.norm2.weight", f"beit.encoder.layer.{i}.layernorm_after.weight"))
59
+ rename_keys.append((f"{prefix}blocks.{i}.norm2.bias", f"beit.encoder.layer.{i}.layernorm_after.bias"))
60
+ rename_keys.append((f"{prefix}blocks.{i}.mlp.fc1.weight", f"beit.encoder.layer.{i}.intermediate.dense.weight"))
61
+ rename_keys.append((f"{prefix}blocks.{i}.mlp.fc1.bias", f"beit.encoder.layer.{i}.intermediate.dense.bias"))
62
+ rename_keys.append((f"{prefix}blocks.{i}.mlp.fc2.weight", f"beit.encoder.layer.{i}.output.dense.weight"))
63
+ rename_keys.append((f"{prefix}blocks.{i}.mlp.fc2.bias", f"beit.encoder.layer.{i}.output.dense.bias"))
64
+
65
+ # projection layer + position embeddings
66
+ rename_keys.extend(
67
+ [
68
+ (f"{prefix}cls_token", "beit.embeddings.cls_token"),
69
+ (f"{prefix}patch_embed.proj.weight", "beit.embeddings.patch_embeddings.projection.weight"),
70
+ (f"{prefix}patch_embed.proj.bias", "beit.embeddings.patch_embeddings.projection.bias"),
71
+ ]
72
+ )
73
+
74
+ if has_lm_head:
75
+ # mask token + shared relative position bias + layernorm
76
+ rename_keys.extend(
77
+ [
78
+ ("mask_token", "beit.embeddings.mask_token"),
79
+ (
80
+ "rel_pos_bias.relative_position_bias_table",
81
+ "beit.encoder.relative_position_bias.relative_position_bias_table",
82
+ ),
83
+ (
84
+ "rel_pos_bias.relative_position_index",
85
+ "beit.encoder.relative_position_bias.relative_position_index",
86
+ ),
87
+ ("norm.weight", "layernorm.weight"),
88
+ ("norm.bias", "layernorm.bias"),
89
+ ]
90
+ )
91
+ elif is_semantic:
92
+ # semantic segmentation classification heads
93
+ rename_keys.extend(
94
+ [
95
+ ("decode_head.conv_seg.weight", "decode_head.classifier.weight"),
96
+ ("decode_head.conv_seg.bias", "decode_head.classifier.bias"),
97
+ ("auxiliary_head.conv_seg.weight", "auxiliary_head.classifier.weight"),
98
+ ("auxiliary_head.conv_seg.bias", "auxiliary_head.classifier.bias"),
99
+ ]
100
+ )
101
+ else:
102
+ # layernorm + classification head
103
+ rename_keys.extend(
104
+ [
105
+ ("fc_norm.weight", "beit.pooler.layernorm.weight"),
106
+ ("fc_norm.bias", "beit.pooler.layernorm.bias"),
107
+ ("head.weight", "classifier.weight"),
108
+ ("head.bias", "classifier.bias"),
109
+ ]
110
+ )
111
+
112
+ return rename_keys
113
+
114
+
115
+ # we split up the matrix of each encoder layer into queries, keys and values
116
+ def read_in_q_k_v(state_dict, config, has_lm_head=False, is_semantic=False):
117
+ for i in range(config.num_hidden_layers):
118
+ prefix = "backbone." if is_semantic else ""
119
+ # queries, keys and values
120
+ in_proj_weight = state_dict.pop(f"{prefix}blocks.{i}.attn.qkv.weight")
121
+ q_bias = state_dict.pop(f"{prefix}blocks.{i}.attn.q_bias")
122
+ v_bias = state_dict.pop(f"{prefix}blocks.{i}.attn.v_bias")
123
+
124
+ state_dict[f"beit.encoder.layer.{i}.attention.attention.query.weight"] = in_proj_weight[
125
+ : config.hidden_size, :
126
+ ]
127
+ state_dict[f"beit.encoder.layer.{i}.attention.attention.query.bias"] = q_bias
128
+ state_dict[f"beit.encoder.layer.{i}.attention.attention.key.weight"] = in_proj_weight[
129
+ config.hidden_size : config.hidden_size * 2, :
130
+ ]
131
+ state_dict[f"beit.encoder.layer.{i}.attention.attention.value.weight"] = in_proj_weight[
132
+ -config.hidden_size :, :
133
+ ]
134
+ state_dict[f"beit.encoder.layer.{i}.attention.attention.value.bias"] = v_bias
135
+
136
+ # gamma_1 and gamma_2
137
+ # we call them lambda because otherwise they are renamed when using .from_pretrained
138
+ gamma_1 = state_dict.pop(f"{prefix}blocks.{i}.gamma_1")
139
+ gamma_2 = state_dict.pop(f"{prefix}blocks.{i}.gamma_2")
140
+
141
+ state_dict[f"beit.encoder.layer.{i}.lambda_1"] = gamma_1
142
+ state_dict[f"beit.encoder.layer.{i}.lambda_2"] = gamma_2
143
+
144
+ # relative_position bias table + index
145
+ if not has_lm_head:
146
+ # each layer has its own relative position bias
147
+ table = state_dict.pop(f"{prefix}blocks.{i}.attn.relative_position_bias_table")
148
+ index = state_dict.pop(f"{prefix}blocks.{i}.attn.relative_position_index")
149
+
150
+ state_dict[
151
+ f"beit.encoder.layer.{i}.attention.attention.relative_position_bias.relative_position_bias_table"
152
+ ] = table
153
+ state_dict[
154
+ f"beit.encoder.layer.{i}.attention.attention.relative_position_bias.relative_position_index"
155
+ ] = index
156
+
157
+
158
+ def rename_key(dct, old, new):
159
+ val = dct.pop(old)
160
+ dct[new] = val
161
+
162
+
163
+ # We will verify our results on an image of cute cats
164
+ def prepare_img():
165
+ url = "http://images.cocodataset.org/val2017/000000039769.jpg"
166
+ im = Image.open(requests.get(url, stream=True).raw)
167
+ return im
168
+
169
+
170
+ @torch.no_grad()
171
+ def convert_beit_checkpoint(checkpoint_url, pytorch_dump_folder_path):
172
+ """
173
+ Copy/paste/tweak model's weights to our BEiT structure.
174
+ """
175
+
176
+ # define default BEiT configuration
177
+ config = BeitConfig()
178
+ has_lm_head = False
179
+ is_semantic = False
180
+ repo_id = "huggingface/label-files"
181
+ # set config parameters based on URL
182
+ if checkpoint_url[-9:-4] == "pt22k":
183
+ # masked image modeling
184
+ config.use_shared_relative_position_bias = True
185
+ config.use_mask_token = True
186
+ has_lm_head = True
187
+ elif checkpoint_url[-9:-4] == "ft22k":
188
+ # intermediate fine-tuning on ImageNet-22k
189
+ config.use_relative_position_bias = True
190
+ config.num_labels = 21841
191
+ filename = "imagenet-22k-id2label.json"
192
+ id2label = json.load(open(hf_hub_download(repo_id, filename, repo_type="dataset"), "r"))
193
+ id2label = {int(k): v for k, v in id2label.items()}
194
+ # this dataset contains 21843 labels but the model only has 21841
195
+ # we delete the classes as mentioned in https://github.com/google-research/big_transfer/issues/18
196
+ del id2label[9205]
197
+ del id2label[15027]
198
+ config.id2label = id2label
199
+ config.label2id = {v: k for k, v in id2label.items()}
200
+ elif checkpoint_url[-8:-4] == "to1k":
201
+ # fine-tuning on ImageNet-1k
202
+ config.use_relative_position_bias = True
203
+ config.num_labels = 1000
204
+ filename = "imagenet-1k-id2label.json"
205
+ id2label = json.load(open(hf_hub_download(repo_id, filename, repo_type="dataset"), "r"))
206
+ id2label = {int(k): v for k, v in id2label.items()}
207
+ config.id2label = id2label
208
+ config.label2id = {v: k for k, v in id2label.items()}
209
+ if "384" in checkpoint_url:
210
+ config.image_size = 384
211
+ if "512" in checkpoint_url:
212
+ config.image_size = 512
213
+ elif "ade20k" in checkpoint_url:
214
+ # fine-tuning
215
+ config.use_relative_position_bias = True
216
+ config.num_labels = 150
217
+ filename = "ade20k-id2label.json"
218
+ id2label = json.load(open(hf_hub_download(repo_id, filename, repo_type="dataset"), "r"))
219
+ id2label = {int(k): v for k, v in id2label.items()}
220
+ config.id2label = id2label
221
+ config.label2id = {v: k for k, v in id2label.items()}
222
+ config.image_size = 640
223
+ is_semantic = True
224
+ else:
225
+ raise ValueError("Checkpoint not supported, URL should either end with 'pt22k', 'ft22k', 'to1k' or 'ade20k'")
226
+
227
+ # size of the architecture
228
+ if "base" in checkpoint_url:
229
+ pass
230
+ elif "large" in checkpoint_url:
231
+ config.hidden_size = 1024
232
+ config.intermediate_size = 4096
233
+ config.num_hidden_layers = 24
234
+ config.num_attention_heads = 16
235
+ if "ade20k" in checkpoint_url:
236
+ config.image_size = 640
237
+ config.out_indices = [7, 11, 15, 23]
238
+ else:
239
+ raise ValueError("Should either find 'base' or 'large' in checkpoint URL")
240
+
241
+ # load state_dict of original model, remove and rename some keys
242
+ state_dict = torch.hub.load_state_dict_from_url(checkpoint_url, map_location="cpu", check_hash=True)
243
+ state_dict = state_dict["model"] if "ade20k" not in checkpoint_url else state_dict["state_dict"]
244
+
245
+ rename_keys = create_rename_keys(config, has_lm_head=has_lm_head, is_semantic=is_semantic)
246
+ for src, dest in rename_keys:
247
+ rename_key(state_dict, src, dest)
248
+ read_in_q_k_v(state_dict, config, has_lm_head=has_lm_head, is_semantic=is_semantic)
249
+ if is_semantic:
250
+ # add prefix to decoder keys
251
+ for key, val in state_dict.copy().items():
252
+ val = state_dict.pop(key)
253
+ if key.startswith("backbone.fpn"):
254
+ key = key.replace("backbone.fpn", "fpn")
255
+ state_dict[key] = val
256
+
257
+ # load HuggingFace model
258
+ if checkpoint_url[-9:-4] == "pt22k":
259
+ model = BeitForMaskedImageModeling(config)
260
+ elif "ade20k" in checkpoint_url:
261
+ model = BeitForSemanticSegmentation(config)
262
+ else:
263
+ model = BeitForImageClassification(config)
264
+ model.eval()
265
+ model.load_state_dict(state_dict)
266
+
267
+ # Check outputs on an image
268
+ if is_semantic:
269
+ image_processor = BeitImageProcessor(size=config.image_size, do_center_crop=False)
270
+ ds = load_dataset("hf-internal-testing/fixtures_ade20k", split="test")
271
+ image = Image.open(ds[0]["file"])
272
+ else:
273
+ image_processor = BeitImageProcessor(
274
+ size=config.image_size, resample=PILImageResampling.BILINEAR, do_center_crop=False
275
+ )
276
+ image = prepare_img()
277
+
278
+ encoding = image_processor(images=image, return_tensors="pt")
279
+ pixel_values = encoding["pixel_values"]
280
+
281
+ outputs = model(pixel_values)
282
+ logits = outputs.logits
283
+
284
+ # verify logits
285
+ expected_shape = torch.Size([1, 1000])
286
+ if checkpoint_url[:-4].endswith("beit_base_patch16_224_pt22k"):
287
+ expected_shape = torch.Size([1, 196, 8192])
288
+ elif checkpoint_url[:-4].endswith("beit_large_patch16_224_pt22k"):
289
+ expected_shape = torch.Size([1, 196, 8192])
290
+ elif checkpoint_url[:-4].endswith("beit_base_patch16_224_pt22k_ft22k"):
291
+ expected_shape = torch.Size([1, 21841])
292
+ expected_logits = torch.tensor([2.2288, 2.4671, 0.7395])
293
+ expected_class_idx = 2397
294
+ elif checkpoint_url[:-4].endswith("beit_large_patch16_224_pt22k_ft22k"):
295
+ expected_shape = torch.Size([1, 21841])
296
+ expected_logits = torch.tensor([1.6881, -0.2787, 0.5901])
297
+ expected_class_idx = 2396
298
+ elif checkpoint_url[:-4].endswith("beit_base_patch16_224_pt22k_ft1k"):
299
+ expected_logits = torch.tensor([0.1241, 0.0798, -0.6569])
300
+ expected_class_idx = 285
301
+ elif checkpoint_url[:-4].endswith("beit_base_patch16_224_pt22k_ft22kto1k"):
302
+ expected_logits = torch.tensor([-1.2385, -1.0987, -1.0108])
303
+ expected_class_idx = 281
304
+ elif checkpoint_url[:-4].endswith("beit_base_patch16_384_pt22k_ft22kto1k"):
305
+ expected_logits = torch.tensor([-1.5303, -0.9484, -0.3147])
306
+ expected_class_idx = 761
307
+ elif checkpoint_url[:-4].endswith("beit_large_patch16_224_pt22k_ft1k"):
308
+ expected_logits = torch.tensor([0.4610, -0.0928, 0.2086])
309
+ expected_class_idx = 761
310
+ elif checkpoint_url[:-4].endswith("beit_large_patch16_224_pt22k_ft22kto1k"):
311
+ expected_logits = torch.tensor([-0.4804, 0.6257, -0.1837])
312
+ expected_class_idx = 761
313
+ elif checkpoint_url[:-4].endswith("beit_large_patch16_384_pt22k_ft22kto1k"):
314
+ expected_logits = torch.tensor([[-0.5122, 0.5117, -0.2113]])
315
+ expected_class_idx = 761
316
+ elif checkpoint_url[:-4].endswith("beit_large_patch16_512_pt22k_ft22kto1k"):
317
+ expected_logits = torch.tensor([-0.3062, 0.7261, 0.4852])
318
+ expected_class_idx = 761
319
+ elif checkpoint_url[:-4].endswith("beit_base_patch16_640_pt22k_ft22ktoade20k"):
320
+ expected_shape = (1, 150, 160, 160)
321
+ expected_logits = torch.tensor(
322
+ [
323
+ [[-4.9225, -2.3954, -3.0522], [-2.8822, -1.0046, -1.7561], [-2.9549, -1.3228, -2.1347]],
324
+ [[-5.8168, -3.4129, -4.0778], [-3.8651, -2.2214, -3.0277], [-3.8356, -2.4643, -3.3535]],
325
+ [[-0.0078, 3.9952, 4.0754], [2.9856, 4.6944, 5.0035], [3.2413, 4.7813, 4.9969]],
326
+ ]
327
+ )
328
+ elif checkpoint_url[:-4].endswith("beit_large_patch16_640_pt22k_ft22ktoade20k"):
329
+ expected_shape = (1, 150, 160, 160)
330
+ expected_logits = torch.tensor(
331
+ [
332
+ [[-4.3305, -2.3049, -3.0161], [-2.9591, -1.5305, -2.2251], [-3.4198, -1.8004, -2.9062]],
333
+ [[-5.8922, -3.7435, -4.3978], [-4.2063, -2.7872, -3.4755], [-4.2791, -3.1874, -4.1681]],
334
+ [[0.9895, 4.3467, 4.7663], [4.2476, 5.6830, 6.1518], [4.5550, 6.2495, 6.5154]],
335
+ ]
336
+ )
337
+ else:
338
+ raise ValueError("Can't verify logits as model is not supported")
339
+
340
+ if logits.shape != expected_shape:
341
+ raise ValueError(f"Shape of logits not as expected. {logits.shape=}, {expected_shape=}")
342
+ if not has_lm_head:
343
+ if is_semantic:
344
+ if not torch.allclose(logits[0, :3, :3, :3], expected_logits, atol=1e-3):
345
+ raise ValueError("First elements of logits not as expected")
346
+ else:
347
+ print("Predicted class idx:", logits.argmax(-1).item())
348
+
349
+ if not torch.allclose(logits[0, :3], expected_logits, atol=1e-3):
350
+ raise ValueError("First elements of logits not as expected")
351
+ if logits.argmax(-1).item() != expected_class_idx:
352
+ raise ValueError("Predicted class index not as expected")
353
+
354
+ Path(pytorch_dump_folder_path).mkdir(exist_ok=True)
355
+ print(f"Saving model to {pytorch_dump_folder_path}")
356
+ model.save_pretrained(pytorch_dump_folder_path)
357
+ print(f"Saving image processor to {pytorch_dump_folder_path}")
358
+ image_processor.save_pretrained(pytorch_dump_folder_path)
359
+
360
+
361
+ if __name__ == "__main__":
362
+ parser = argparse.ArgumentParser()
363
+
364
+ parser.add_argument(
365
+ "--checkpoint_url",
366
+ default="https://conversationhub.blob.core.windows.net/beit-share-public/beit/beit_base_patch16_224_pt22k_ft22kto1k.pth",
367
+ type=str,
368
+ help="URL to the original PyTorch checkpoint (.pth file).",
369
+ )
370
+ parser.add_argument(
371
+ "--pytorch_dump_folder_path", default=None, type=str, help="Path to the folder to output PyTorch model."
372
+ )
373
+ args = parser.parse_args()
374
+ convert_beit_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path)
pllava/lib/python3.10/site-packages/transformers/models/beit/feature_extraction_beit.py ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2021 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
+ """Feature extractor class for BEiT."""
16
+
17
+ import warnings
18
+
19
+ from ...utils import logging
20
+ from .image_processing_beit import BeitImageProcessor
21
+
22
+
23
+ logger = logging.get_logger(__name__)
24
+
25
+
26
+ class BeitFeatureExtractor(BeitImageProcessor):
27
+ def __init__(self, *args, **kwargs) -> None:
28
+ warnings.warn(
29
+ "The class BeitFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please"
30
+ " use BeitImageProcessor instead.",
31
+ FutureWarning,
32
+ )
33
+ super().__init__(*args, **kwargs)
pllava/lib/python3.10/site-packages/transformers/models/beit/image_processing_beit.py ADDED
@@ -0,0 +1,505 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 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
+ """Image processor class for Beit."""
16
+
17
+ import warnings
18
+ from typing import Any, Dict, List, Optional, Tuple, Union
19
+
20
+ import numpy as np
21
+
22
+ from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
23
+ from ...image_transforms import resize, to_channel_dimension_format
24
+ from ...image_utils import (
25
+ IMAGENET_STANDARD_MEAN,
26
+ IMAGENET_STANDARD_STD,
27
+ ChannelDimension,
28
+ ImageInput,
29
+ PILImageResampling,
30
+ infer_channel_dimension_format,
31
+ is_scaled_image,
32
+ make_list_of_images,
33
+ to_numpy_array,
34
+ valid_images,
35
+ )
36
+ from ...utils import TensorType, is_torch_available, is_torch_tensor, is_vision_available, logging
37
+
38
+
39
+ if is_vision_available():
40
+ import PIL
41
+
42
+ if is_torch_available():
43
+ import torch
44
+
45
+
46
+ logger = logging.get_logger(__name__)
47
+
48
+
49
+ class BeitImageProcessor(BaseImageProcessor):
50
+ r"""
51
+ Constructs a BEiT image processor.
52
+
53
+ Args:
54
+ do_resize (`bool`, *optional*, defaults to `True`):
55
+ Whether to resize the image's (height, width) dimensions to the specified `size`. Can be overridden by the
56
+ `do_resize` parameter in the `preprocess` method.
57
+ size (`Dict[str, int]` *optional*, defaults to `{"height": 256, "width": 256}`):
58
+ Size of the output image after resizing. Can be overridden by the `size` parameter in the `preprocess`
59
+ method.
60
+ resample (`PILImageResampling`, *optional*, defaults to `Resampling.BICUBIC`):
61
+ Resampling filter to use if resizing the image. Can be overridden by the `resample` parameter in the
62
+ `preprocess` method.
63
+ do_center_crop (`bool`, *optional*, defaults to `True`):
64
+ Whether to center crop the image. If the input size is smaller than `crop_size` along any edge, the image
65
+ is padded with 0's and then center cropped. Can be overridden by the `do_center_crop` parameter in the
66
+ `preprocess` method.
67
+ crop_size (`Dict[str, int]`, *optional*, defaults to `{"height": 224, "width": 224}`):
68
+ Desired output size when applying center-cropping. Only has an effect if `do_center_crop` is set to `True`.
69
+ Can be overridden by the `crop_size` parameter in the `preprocess` method.
70
+ rescale_factor (`int` or `float`, *optional*, defaults to `1/255`):
71
+ Scale factor to use if rescaling the image. Can be overridden by the `rescale_factor` parameter in the
72
+ `preprocess` method.
73
+ do_rescale (`bool`, *optional*, defaults to `True`):
74
+ Whether to rescale the image by the specified scale `rescale_factor`. Can be overridden by the `do_rescale`
75
+ parameter in the `preprocess` method.
76
+ do_normalize (`bool`, *optional*, defaults to `True`):
77
+ Whether to normalize the image. Can be overridden by the `do_normalize` parameter in the `preprocess`
78
+ method.
79
+ image_mean (`float` or `List[float]`, *optional*, defaults to `IMAGENET_STANDARD_MEAN`):
80
+ The mean to use if normalizing the image. This is a float or list of floats of length of the number of
81
+ channels of the image. Can be overridden by the `image_mean` parameter in the `preprocess` method.
82
+ image_std (`float` or `List[float]`, *optional*, defaults to `IMAGENET_STANDARD_STD`):
83
+ The standard deviation to use if normalizing the image. This is a float or list of floats of length of the
84
+ number of channels of the image. Can be overridden by the `image_std` parameter in the `preprocess` method.
85
+ do_reduce_labels (`bool`, *optional*, defaults to `False`):
86
+ Whether or not to reduce all label values of segmentation maps by 1. Usually used for datasets where 0 is
87
+ used for background, and background itself is not included in all classes of a dataset (e.g. ADE20k). The
88
+ background label will be replaced by 255. Can be overridden by the `do_reduce_labels` parameter in the
89
+ `preprocess` method.
90
+ """
91
+
92
+ model_input_names = ["pixel_values"]
93
+
94
+ def __init__(
95
+ self,
96
+ do_resize: bool = True,
97
+ size: Dict[str, int] = None,
98
+ resample: PILImageResampling = PILImageResampling.BICUBIC,
99
+ do_center_crop: bool = True,
100
+ crop_size: Dict[str, int] = None,
101
+ rescale_factor: Union[int, float] = 1 / 255,
102
+ do_rescale: bool = True,
103
+ do_normalize: bool = True,
104
+ image_mean: Optional[Union[float, List[float]]] = None,
105
+ image_std: Optional[Union[float, List[float]]] = None,
106
+ do_reduce_labels: bool = False,
107
+ **kwargs,
108
+ ) -> None:
109
+ if "reduce_labels" in kwargs:
110
+ warnings.warn(
111
+ "The `reduce_labels` parameter is deprecated and will be removed in a future version. Please use"
112
+ " `do_reduce_labels` instead.",
113
+ FutureWarning,
114
+ )
115
+ do_reduce_labels = kwargs.pop("reduce_labels")
116
+ super().__init__(**kwargs)
117
+ size = size if size is not None else {"height": 256, "width": 256}
118
+ size = get_size_dict(size)
119
+ crop_size = crop_size if crop_size is not None else {"height": 224, "width": 224}
120
+ crop_size = get_size_dict(crop_size, param_name="crop_size")
121
+ self.do_resize = do_resize
122
+ self.size = size
123
+ self.resample = resample
124
+ self.do_center_crop = do_center_crop
125
+ self.crop_size = crop_size
126
+ self.do_rescale = do_rescale
127
+ self.rescale_factor = rescale_factor
128
+ self.do_normalize = do_normalize
129
+ self.image_mean = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
130
+ self.image_std = image_std if image_std is not None else IMAGENET_STANDARD_STD
131
+ self.do_reduce_labels = do_reduce_labels
132
+
133
+ @classmethod
134
+ def from_dict(cls, image_processor_dict: Dict[str, Any], **kwargs):
135
+ """
136
+ Overrides the `from_dict` method from the base class to make sure `reduce_labels` is updated if image processor
137
+ is created using from_dict and kwargs e.g. `BeitImageProcessor.from_pretrained(checkpoint, reduce_labels=True)`
138
+ """
139
+ image_processor_dict = image_processor_dict.copy()
140
+ if "reduce_labels" in kwargs:
141
+ image_processor_dict["reduce_labels"] = kwargs.pop("reduce_labels")
142
+ return super().from_dict(image_processor_dict, **kwargs)
143
+
144
+ def resize(
145
+ self,
146
+ image: np.ndarray,
147
+ size: Dict[str, int],
148
+ resample: PILImageResampling = PILImageResampling.BICUBIC,
149
+ data_format: Optional[Union[str, ChannelDimension]] = None,
150
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
151
+ **kwargs,
152
+ ) -> np.ndarray:
153
+ """
154
+ Resize an image to (size["height"], size["width"]).
155
+
156
+ Args:
157
+ image (`np.ndarray`):
158
+ Image to resize.
159
+ size (`Dict[str, int]`):
160
+ Size of the output image.
161
+ resample (`PILImageResampling`, *optional*, defaults to `PIL.Image.BICUBIC`):
162
+ Resampling filter to use when resiizing the image.
163
+ data_format (`str` or `ChannelDimension`, *optional*):
164
+ The channel dimension format of the image. If not provided, it will be the same as the input image.
165
+ input_data_format (`str` or `ChannelDimension`, *optional*):
166
+ The channel dimension format of the input image. If not provided, it will be inferred.
167
+ """
168
+ size = get_size_dict(size, default_to_square=True, param_name="size")
169
+ if "height" not in size or "width" not in size:
170
+ raise ValueError(f"The `size` argument must contain `height` and `width` keys. Got {size.keys()}")
171
+ return resize(
172
+ image,
173
+ size=(size["height"], size["width"]),
174
+ resample=resample,
175
+ data_format=data_format,
176
+ input_data_format=input_data_format,
177
+ **kwargs,
178
+ )
179
+
180
+ def reduce_label(self, label: ImageInput) -> np.ndarray:
181
+ label = to_numpy_array(label)
182
+ # Avoid using underflow conversion
183
+ label[label == 0] = 255
184
+ label = label - 1
185
+ label[label == 254] = 255
186
+ return label
187
+
188
+ def _preprocess(
189
+ self,
190
+ image: ImageInput,
191
+ do_reduce_labels: bool = None,
192
+ do_resize: bool = None,
193
+ size: Dict[str, int] = None,
194
+ resample: PILImageResampling = None,
195
+ do_center_crop: bool = None,
196
+ crop_size: Dict[str, int] = None,
197
+ do_rescale: bool = None,
198
+ rescale_factor: float = None,
199
+ do_normalize: bool = None,
200
+ image_mean: Optional[Union[float, List[float]]] = None,
201
+ image_std: Optional[Union[float, List[float]]] = None,
202
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
203
+ ):
204
+ if do_reduce_labels:
205
+ image = self.reduce_label(image)
206
+
207
+ if do_resize:
208
+ image = self.resize(image=image, size=size, resample=resample, input_data_format=input_data_format)
209
+
210
+ if do_center_crop:
211
+ image = self.center_crop(image=image, size=crop_size, input_data_format=input_data_format)
212
+
213
+ if do_rescale:
214
+ image = self.rescale(image=image, scale=rescale_factor, input_data_format=input_data_format)
215
+
216
+ if do_normalize:
217
+ image = self.normalize(image=image, mean=image_mean, std=image_std, input_data_format=input_data_format)
218
+
219
+ return image
220
+
221
+ def _preprocess_image(
222
+ self,
223
+ image: ImageInput,
224
+ do_resize: bool = None,
225
+ size: Dict[str, int] = None,
226
+ resample: PILImageResampling = None,
227
+ do_center_crop: bool = None,
228
+ crop_size: Dict[str, int] = None,
229
+ do_rescale: bool = None,
230
+ rescale_factor: float = None,
231
+ do_normalize: bool = None,
232
+ image_mean: Optional[Union[float, List[float]]] = None,
233
+ image_std: Optional[Union[float, List[float]]] = None,
234
+ data_format: Optional[Union[str, ChannelDimension]] = None,
235
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
236
+ ) -> np.ndarray:
237
+ """Preprocesses a single image."""
238
+ # All transformations expect numpy arrays.
239
+ image = to_numpy_array(image)
240
+ if is_scaled_image(image) and do_rescale:
241
+ logger.warning_once(
242
+ "It looks like you are trying to rescale already rescaled images. If the input"
243
+ " images have pixel values between 0 and 1, set `do_rescale=False` to avoid rescaling them again."
244
+ )
245
+ if input_data_format is None:
246
+ input_data_format = infer_channel_dimension_format(image)
247
+ image = self._preprocess(
248
+ image,
249
+ do_reduce_labels=False,
250
+ do_resize=do_resize,
251
+ size=size,
252
+ resample=resample,
253
+ do_center_crop=do_center_crop,
254
+ crop_size=crop_size,
255
+ do_rescale=do_rescale,
256
+ rescale_factor=rescale_factor,
257
+ do_normalize=do_normalize,
258
+ image_mean=image_mean,
259
+ image_std=image_std,
260
+ input_data_format=input_data_format,
261
+ )
262
+ if data_format is not None:
263
+ image = to_channel_dimension_format(image, data_format, input_channel_dim=input_data_format)
264
+ return image
265
+
266
+ def _preprocess_segmentation_map(
267
+ self,
268
+ segmentation_map: ImageInput,
269
+ do_resize: bool = None,
270
+ size: Dict[str, int] = None,
271
+ resample: PILImageResampling = None,
272
+ do_center_crop: bool = None,
273
+ crop_size: Dict[str, int] = None,
274
+ do_reduce_labels: bool = None,
275
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
276
+ ):
277
+ """Preprocesses a single segmentation map."""
278
+ # All transformations expect numpy arrays.
279
+ segmentation_map = to_numpy_array(segmentation_map)
280
+ # Add an axis to the segmentation maps for transformations.
281
+ if segmentation_map.ndim == 2:
282
+ segmentation_map = segmentation_map[None, ...]
283
+ added_dimension = True
284
+ input_data_format = ChannelDimension.FIRST
285
+ else:
286
+ added_dimension = False
287
+ if input_data_format is None:
288
+ input_data_format = infer_channel_dimension_format(segmentation_map, num_channels=1)
289
+ segmentation_map = self._preprocess(
290
+ image=segmentation_map,
291
+ do_reduce_labels=do_reduce_labels,
292
+ do_resize=do_resize,
293
+ resample=resample,
294
+ size=size,
295
+ do_center_crop=do_center_crop,
296
+ crop_size=crop_size,
297
+ do_normalize=False,
298
+ do_rescale=False,
299
+ input_data_format=ChannelDimension.FIRST,
300
+ )
301
+ # Remove extra axis if added
302
+ if added_dimension:
303
+ segmentation_map = np.squeeze(segmentation_map, axis=0)
304
+ segmentation_map = segmentation_map.astype(np.int64)
305
+ return segmentation_map
306
+
307
+ def __call__(self, images, segmentation_maps=None, **kwargs):
308
+ # Overrides the `__call__` method of the `Preprocessor` class such that the images and segmentation maps can both
309
+ # be passed in as positional arguments.
310
+ return super().__call__(images, segmentation_maps=segmentation_maps, **kwargs)
311
+
312
+ def preprocess(
313
+ self,
314
+ images: ImageInput,
315
+ segmentation_maps: Optional[ImageInput] = None,
316
+ do_resize: bool = None,
317
+ size: Dict[str, int] = None,
318
+ resample: PILImageResampling = None,
319
+ do_center_crop: bool = None,
320
+ crop_size: Dict[str, int] = None,
321
+ do_rescale: bool = None,
322
+ rescale_factor: float = None,
323
+ do_normalize: bool = None,
324
+ image_mean: Optional[Union[float, List[float]]] = None,
325
+ image_std: Optional[Union[float, List[float]]] = None,
326
+ do_reduce_labels: Optional[bool] = None,
327
+ return_tensors: Optional[Union[str, TensorType]] = None,
328
+ data_format: ChannelDimension = ChannelDimension.FIRST,
329
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
330
+ **kwargs,
331
+ ) -> PIL.Image.Image:
332
+ """
333
+ Preprocess an image or batch of images.
334
+
335
+ Args:
336
+ images (`ImageInput`):
337
+ Image to preprocess. Expects a single or batch of images with pixel values ranging from 0 to 255. If
338
+ passing in images with pixel values between 0 and 1, set `do_rescale=False`.
339
+ do_resize (`bool`, *optional*, defaults to `self.do_resize`):
340
+ Whether to resize the image.
341
+ size (`Dict[str, int]`, *optional*, defaults to `self.size`):
342
+ Size of the image after resizing.
343
+ resample (`int`, *optional*, defaults to `self.resample`):
344
+ Resampling filter to use if resizing the image. This can be one of the enum `PILImageResampling`, Only
345
+ has an effect if `do_resize` is set to `True`.
346
+ do_center_crop (`bool`, *optional*, defaults to `self.do_center_crop`):
347
+ Whether to center crop the image.
348
+ crop_size (`Dict[str, int]`, *optional*, defaults to `self.crop_size`):
349
+ Size of the image after center crop. If one edge the image is smaller than `crop_size`, it will be
350
+ padded with zeros and then cropped
351
+ do_rescale (`bool`, *optional*, defaults to `self.do_rescale`):
352
+ Whether to rescale the image values between [0 - 1].
353
+ rescale_factor (`float`, *optional*, defaults to `self.rescale_factor`):
354
+ Rescale factor to rescale the image by if `do_rescale` is set to `True`.
355
+ do_normalize (`bool`, *optional*, defaults to `self.do_normalize`):
356
+ Whether to normalize the image.
357
+ image_mean (`float` or `List[float]`, *optional*, defaults to `self.image_mean`):
358
+ Image mean.
359
+ image_std (`float` or `List[float]`, *optional*, defaults to `self.image_std`):
360
+ Image standard deviation.
361
+ do_reduce_labels (`bool`, *optional*, defaults to `self.do_reduce_labels`):
362
+ Whether or not to reduce all label values of segmentation maps by 1. Usually used for datasets where 0
363
+ is used for background, and background itself is not included in all classes of a dataset (e.g.
364
+ ADE20k). The background label will be replaced by 255.
365
+ return_tensors (`str` or `TensorType`, *optional*):
366
+ The type of tensors to return. Can be one of:
367
+ - Unset: Return a list of `np.ndarray`.
368
+ - `TensorType.TENSORFLOW` or `'tf'`: Return a batch of type `tf.Tensor`.
369
+ - `TensorType.PYTORCH` or `'pt'`: Return a batch of type `torch.Tensor`.
370
+ - `TensorType.NUMPY` or `'np'`: Return a batch of type `np.ndarray`.
371
+ - `TensorType.JAX` or `'jax'`: Return a batch of type `jax.numpy.ndarray`.
372
+ data_format (`ChannelDimension` or `str`, *optional*, defaults to `ChannelDimension.FIRST`):
373
+ The channel dimension format for the output image. Can be one of:
374
+ - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
375
+ - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
376
+ - Unset: Use the channel dimension format of the input image.
377
+ input_data_format (`ChannelDimension` or `str`, *optional*):
378
+ The channel dimension format for the input image. If unset, the channel dimension format is inferred
379
+ from the input image. Can be one of:
380
+ - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
381
+ - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
382
+ - `"none"` or `ChannelDimension.NONE`: image in (height, width) format.
383
+ """
384
+ do_resize = do_resize if do_resize is not None else self.do_resize
385
+ size = size if size is not None else self.size
386
+ size = get_size_dict(size, default_to_square=True, param_name="size")
387
+ resample = resample if resample is not None else self.resample
388
+ do_center_crop = do_center_crop if do_center_crop is not None else self.do_center_crop
389
+ crop_size = crop_size if crop_size is not None else self.crop_size
390
+ crop_size = get_size_dict(crop_size, default_to_square=True, param_name="crop_size")
391
+ do_rescale = do_rescale if do_rescale is not None else self.do_rescale
392
+ rescale_factor = rescale_factor if rescale_factor is not None else self.rescale_factor
393
+ do_normalize = do_normalize if do_normalize is not None else self.do_normalize
394
+ image_mean = image_mean if image_mean is not None else self.image_mean
395
+ image_std = image_std if image_std is not None else self.image_std
396
+ do_reduce_labels = do_reduce_labels if do_reduce_labels is not None else self.do_reduce_labels
397
+
398
+ images = make_list_of_images(images)
399
+ if segmentation_maps is not None:
400
+ segmentation_maps = make_list_of_images(segmentation_maps, expected_ndims=2)
401
+
402
+ if not valid_images(images):
403
+ raise ValueError(
404
+ "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, "
405
+ "torch.Tensor, tf.Tensor or jax.ndarray."
406
+ )
407
+
408
+ if segmentation_maps is not None and not valid_images(segmentation_maps):
409
+ raise ValueError(
410
+ "Invalid segmentation map type. Must be of type PIL.Image.Image, numpy.ndarray, "
411
+ "torch.Tensor, tf.Tensor or jax.ndarray."
412
+ )
413
+
414
+ if do_resize and size is None or resample is None:
415
+ raise ValueError("Size and resample must be specified if do_resize is True.")
416
+
417
+ if do_center_crop and crop_size is None:
418
+ raise ValueError("Crop size must be specified if do_center_crop is True.")
419
+
420
+ if do_rescale and rescale_factor is None:
421
+ raise ValueError("Rescale factor must be specified if do_rescale is True.")
422
+
423
+ if do_normalize and (image_mean is None or image_std is None):
424
+ raise ValueError("Image mean and std must be specified if do_normalize is True.")
425
+
426
+ images = [
427
+ self._preprocess_image(
428
+ image=img,
429
+ do_resize=do_resize,
430
+ do_center_crop=do_center_crop,
431
+ do_rescale=do_rescale,
432
+ do_normalize=do_normalize,
433
+ resample=resample,
434
+ size=size,
435
+ rescale_factor=rescale_factor,
436
+ crop_size=crop_size,
437
+ image_mean=image_mean,
438
+ image_std=image_std,
439
+ data_format=data_format,
440
+ input_data_format=input_data_format,
441
+ )
442
+ for img in images
443
+ ]
444
+
445
+ data = {"pixel_values": images}
446
+
447
+ if segmentation_maps is not None:
448
+ segmentation_maps = [
449
+ self._preprocess_segmentation_map(
450
+ segmentation_map=segmentation_map,
451
+ do_reduce_labels=do_reduce_labels,
452
+ do_resize=do_resize,
453
+ resample=resample,
454
+ size=size,
455
+ do_center_crop=do_center_crop,
456
+ crop_size=crop_size,
457
+ )
458
+ for segmentation_map in segmentation_maps
459
+ ]
460
+ data["labels"] = segmentation_maps
461
+
462
+ return BatchFeature(data=data, tensor_type=return_tensors)
463
+
464
+ def post_process_semantic_segmentation(self, outputs, target_sizes: List[Tuple] = None):
465
+ """
466
+ Converts the output of [`BeitForSemanticSegmentation`] into semantic segmentation maps. Only supports PyTorch.
467
+
468
+ Args:
469
+ outputs ([`BeitForSemanticSegmentation`]):
470
+ Raw outputs of the model.
471
+ target_sizes (`List[Tuple]` of length `batch_size`, *optional*):
472
+ List of tuples corresponding to the requested final size (height, width) of each prediction. If unset,
473
+ predictions will not be resized.
474
+
475
+ Returns:
476
+ semantic_segmentation: `List[torch.Tensor]` of length `batch_size`, where each item is a semantic
477
+ segmentation map of shape (height, width) corresponding to the target_sizes entry (if `target_sizes` is
478
+ specified). Each entry of each `torch.Tensor` correspond to a semantic class id.
479
+ """
480
+ # TODO: add support for other frameworks
481
+ logits = outputs.logits
482
+
483
+ # Resize logits and compute semantic segmentation maps
484
+ if target_sizes is not None:
485
+ if len(logits) != len(target_sizes):
486
+ raise ValueError(
487
+ "Make sure that you pass in as many target sizes as the batch dimension of the logits"
488
+ )
489
+
490
+ if is_torch_tensor(target_sizes):
491
+ target_sizes = target_sizes.numpy()
492
+
493
+ semantic_segmentation = []
494
+
495
+ for idx in range(len(logits)):
496
+ resized_logits = torch.nn.functional.interpolate(
497
+ logits[idx].unsqueeze(dim=0), size=target_sizes[idx], mode="bilinear", align_corners=False
498
+ )
499
+ semantic_map = resized_logits[0].argmax(dim=0)
500
+ semantic_segmentation.append(semantic_map)
501
+ else:
502
+ semantic_segmentation = logits.argmax(dim=1)
503
+ semantic_segmentation = [semantic_segmentation[i] for i in range(semantic_segmentation.shape[0])]
504
+
505
+ return semantic_segmentation
pllava/lib/python3.10/site-packages/transformers/models/beit/modeling_beit.py ADDED
@@ -0,0 +1,1427 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2021 Microsoft Research 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 BEiT model."""
16
+
17
+
18
+ import collections.abc
19
+ import math
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 Tensor, nn
26
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
27
+
28
+ from ...activations import ACT2FN
29
+ from ...modeling_outputs import (
30
+ BackboneOutput,
31
+ BaseModelOutput,
32
+ BaseModelOutputWithPooling,
33
+ ImageClassifierOutput,
34
+ MaskedLMOutput,
35
+ SemanticSegmenterOutput,
36
+ )
37
+ from ...modeling_utils import PreTrainedModel
38
+ from ...pytorch_utils import find_pruneable_heads_and_indices, meshgrid, prune_linear_layer
39
+ from ...utils import (
40
+ add_code_sample_docstrings,
41
+ add_start_docstrings,
42
+ add_start_docstrings_to_model_forward,
43
+ logging,
44
+ replace_return_docstrings,
45
+ )
46
+ from ...utils.backbone_utils import BackboneMixin
47
+ from .configuration_beit import BeitConfig
48
+
49
+
50
+ logger = logging.get_logger(__name__)
51
+
52
+ # General docstring
53
+ _CONFIG_FOR_DOC = "BeitConfig"
54
+
55
+ # Base docstring
56
+ _CHECKPOINT_FOR_DOC = "microsoft/beit-base-patch16-224-pt22k"
57
+ _EXPECTED_OUTPUT_SHAPE = [1, 197, 768]
58
+
59
+ # Image classification docstring
60
+ _IMAGE_CLASS_CHECKPOINT = "microsoft/beit-base-patch16-224"
61
+ _IMAGE_CLASS_EXPECTED_OUTPUT = "tabby, tabby cat"
62
+
63
+ BEIT_PRETRAINED_MODEL_ARCHIVE_LIST = [
64
+ "microsoft/beit-base-patch16-224",
65
+ # See all BEiT models at https://huggingface.co/models?filter=beit
66
+ ]
67
+
68
+
69
+ @dataclass
70
+ class BeitModelOutputWithPooling(BaseModelOutputWithPooling):
71
+ """
72
+ Class for outputs of [`BeitModel`].
73
+
74
+ Args:
75
+ last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
76
+ Sequence of hidden-states at the output of the last layer of the model.
77
+ pooler_output (`torch.FloatTensor` of shape `(batch_size, hidden_size)`):
78
+ Average of the last layer hidden states of the patch tokens (excluding the *[CLS]* token) if
79
+ *config.use_mean_pooling* is set to True. If set to False, then the final hidden state of the *[CLS]* token
80
+ will be returned.
81
+ hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
82
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of
83
+ shape `(batch_size, sequence_length, hidden_size)`.
84
+
85
+ Hidden-states of the model at the output of each layer plus the initial embedding outputs.
86
+ attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
87
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
88
+ sequence_length)`.
89
+
90
+ Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
91
+ heads.
92
+ """
93
+
94
+
95
+ def drop_path(input: torch.Tensor, drop_prob: float = 0.0, training: bool = False) -> torch.Tensor:
96
+ """
97
+ Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).
98
+
99
+ Comment by Ross Wightman: This is the same as the DropConnect impl I created for EfficientNet, etc networks,
100
+ however, the original name is misleading as 'Drop Connect' is a different form of dropout in a separate paper...
101
+ See discussion: https://github.com/tensorflow/tpu/issues/494#issuecomment-532968956 ... I've opted for changing the
102
+ layer and argument names to 'drop path' rather than mix DropConnect as a layer name and use 'survival rate' as the
103
+ argument.
104
+ """
105
+ if drop_prob == 0.0 or not training:
106
+ return input
107
+ keep_prob = 1 - drop_prob
108
+ shape = (input.shape[0],) + (1,) * (input.ndim - 1) # work with diff dim tensors, not just 2D ConvNets
109
+ random_tensor = keep_prob + torch.rand(shape, dtype=input.dtype, device=input.device)
110
+ random_tensor.floor_() # binarize
111
+ output = input.div(keep_prob) * random_tensor
112
+ return output
113
+
114
+
115
+ class BeitDropPath(nn.Module):
116
+ """Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks)."""
117
+
118
+ def __init__(self, drop_prob: Optional[float] = None) -> None:
119
+ super().__init__()
120
+ self.drop_prob = drop_prob
121
+
122
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
123
+ return drop_path(hidden_states, self.drop_prob, self.training)
124
+
125
+ def extra_repr(self) -> str:
126
+ return "p={}".format(self.drop_prob)
127
+
128
+
129
+ # Based on timm implementation, which can be found here:
130
+ # https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/vision_transformer.py
131
+ class BeitEmbeddings(nn.Module):
132
+ """
133
+ Construct the CLS token, position and patch embeddings. Optionally, also the mask token.
134
+
135
+ """
136
+
137
+ def __init__(self, config: BeitConfig) -> None:
138
+ super().__init__()
139
+
140
+ self.cls_token = nn.Parameter(torch.zeros(1, 1, config.hidden_size))
141
+ if config.use_mask_token:
142
+ self.mask_token = nn.Parameter(torch.zeros(1, 1, config.hidden_size))
143
+ else:
144
+ self.mask_token = None
145
+ self.patch_embeddings = BeitPatchEmbeddings(config)
146
+ num_patches = self.patch_embeddings.num_patches
147
+ if config.use_absolute_position_embeddings:
148
+ self.position_embeddings = nn.Parameter(torch.zeros(1, num_patches + 1, config.hidden_size))
149
+ else:
150
+ self.position_embeddings = None
151
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
152
+
153
+ def forward(self, pixel_values: torch.Tensor, bool_masked_pos: Optional[torch.BoolTensor] = None) -> torch.Tensor:
154
+ embeddings, (patch_height, patch_width) = self.patch_embeddings(
155
+ pixel_values, self.position_embeddings[:, 1:, :] if self.position_embeddings is not None else None
156
+ )
157
+ batch_size, seq_len, _ = embeddings.size()
158
+
159
+ if bool_masked_pos is not None:
160
+ mask_tokens = self.mask_token.expand(batch_size, seq_len, -1)
161
+ # replace the masked visual tokens by mask_tokens
162
+ w = bool_masked_pos.unsqueeze(-1).type_as(mask_tokens)
163
+ embeddings = embeddings * (1 - w) + mask_tokens * w
164
+
165
+ cls_tokens = self.cls_token.expand(batch_size, -1, -1)
166
+ if self.position_embeddings is not None:
167
+ cls_tokens = cls_tokens + self.position_embeddings[:, :1, :]
168
+
169
+ embeddings = torch.cat((cls_tokens, embeddings), dim=1)
170
+
171
+ embeddings = self.dropout(embeddings)
172
+
173
+ return embeddings, (patch_height, patch_width)
174
+
175
+
176
+ class BeitPatchEmbeddings(nn.Module):
177
+ """
178
+ This class turns `pixel_values` of shape `(batch_size, num_channels, height, width)` into the initial
179
+ `hidden_states` (patch embeddings) of shape `(batch_size, seq_length, hidden_size)` to be consumed by a
180
+ Transformer.
181
+ """
182
+
183
+ def __init__(self, config):
184
+ super().__init__()
185
+ image_size, patch_size = config.image_size, config.patch_size
186
+ num_channels, hidden_size = config.num_channels, config.hidden_size
187
+
188
+ image_size = image_size if isinstance(image_size, collections.abc.Iterable) else (image_size, image_size)
189
+ patch_size = patch_size if isinstance(patch_size, collections.abc.Iterable) else (patch_size, patch_size)
190
+ num_patches = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
191
+ patch_shape = (image_size[0] // patch_size[0], image_size[1] // patch_size[1])
192
+ self.image_size = image_size
193
+ self.patch_size = patch_size
194
+ self.num_channels = num_channels
195
+ self.num_patches = num_patches
196
+ self.patch_shape = patch_shape
197
+
198
+ self.projection = nn.Conv2d(num_channels, hidden_size, kernel_size=patch_size, stride=patch_size)
199
+
200
+ def forward(self, pixel_values: torch.Tensor, position_embedding: Optional[torch.Tensor] = None) -> torch.Tensor:
201
+ batch_size, num_channels, height, width = pixel_values.shape
202
+ if num_channels != self.num_channels:
203
+ raise ValueError(
204
+ "Make sure that the channel dimension of the pixel values match with the one set in the configuration."
205
+ )
206
+
207
+ embeddings = self.projection(pixel_values)
208
+ patch_height, patch_width = embeddings.shape[2], embeddings.shape[3]
209
+
210
+ if position_embedding is not None:
211
+ # interpolate the position embedding to the corresponding size
212
+ position_embedding = position_embedding.view(1, self.patch_shape[0], self.patch_shape[1], -1).permute(
213
+ 0, 3, 1, 2
214
+ )
215
+ position_embedding = nn.functional.interpolate(
216
+ position_embedding, size=(patch_height, patch_width), mode="bicubic"
217
+ )
218
+ embeddings = embeddings + position_embedding
219
+
220
+ embeddings = embeddings.flatten(2).transpose(1, 2)
221
+
222
+ return embeddings, (patch_height, patch_width)
223
+
224
+
225
+ class BeitSelfAttention(nn.Module):
226
+ def __init__(self, config: BeitConfig, window_size: Optional[tuple] = None) -> None:
227
+ super().__init__()
228
+ if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):
229
+ raise ValueError(
230
+ f"The hidden size {config.hidden_size,} is not a multiple of the number of attention "
231
+ f"heads {config.num_attention_heads}."
232
+ )
233
+
234
+ self.num_attention_heads = config.num_attention_heads
235
+ self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
236
+ self.all_head_size = self.num_attention_heads * self.attention_head_size
237
+
238
+ self.query = nn.Linear(config.hidden_size, self.all_head_size)
239
+ self.key = nn.Linear(config.hidden_size, self.all_head_size, bias=False)
240
+ self.value = nn.Linear(config.hidden_size, self.all_head_size)
241
+
242
+ self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
243
+
244
+ if window_size:
245
+ self.relative_position_bias = BeitRelativePositionBias(config, window_size=window_size)
246
+ else:
247
+ self.relative_position_bias = None
248
+
249
+ def transpose_for_scores(self, x):
250
+ new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.attention_head_size)
251
+ x = x.view(*new_x_shape)
252
+ return x.permute(0, 2, 1, 3)
253
+
254
+ def forward(
255
+ self,
256
+ hidden_states: torch.Tensor,
257
+ head_mask: Optional[torch.Tensor] = None,
258
+ output_attentions: bool = False,
259
+ relative_position_bias: Optional["BeitRelativePositionBias"] = None,
260
+ ) -> Union[Tuple[torch.Tensor], Tuple[torch.Tensor, torch.Tensor]]:
261
+ mixed_query_layer = self.query(hidden_states)
262
+
263
+ key_layer = self.transpose_for_scores(self.key(hidden_states))
264
+ value_layer = self.transpose_for_scores(self.value(hidden_states))
265
+ query_layer = self.transpose_for_scores(mixed_query_layer)
266
+
267
+ # Take the dot product between "query" and "key" to get the raw attention scores.
268
+ attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))
269
+
270
+ attention_scores = attention_scores / math.sqrt(self.attention_head_size)
271
+
272
+ # Add relative position bias if present.
273
+ if self.relative_position_bias is not None:
274
+ attention_scores = attention_scores + self.relative_position_bias().unsqueeze(0)
275
+
276
+ # Add shared relative position bias if provided.
277
+ if relative_position_bias is not None:
278
+ attention_scores = attention_scores + relative_position_bias
279
+
280
+ # Normalize the attention scores to probabilities.
281
+ attention_probs = nn.functional.softmax(attention_scores, dim=-1)
282
+
283
+ # This is actually dropping out entire tokens to attend to, which might
284
+ # seem a bit unusual, but is taken from the original Transformer paper.
285
+ attention_probs = self.dropout(attention_probs)
286
+
287
+ # Mask heads if we want to
288
+ if head_mask is not None:
289
+ attention_probs = attention_probs * head_mask
290
+
291
+ context_layer = torch.matmul(attention_probs, value_layer)
292
+
293
+ context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
294
+ new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
295
+ context_layer = context_layer.view(*new_context_layer_shape)
296
+
297
+ outputs = (context_layer, attention_probs) if output_attentions else (context_layer,)
298
+
299
+ return outputs
300
+
301
+
302
+ class BeitSelfOutput(nn.Module):
303
+ """
304
+ The residual connection is defined in BeitLayer instead of here (as is the case with other models), due to the
305
+ layernorm applied before each block.
306
+ """
307
+
308
+ def __init__(self, config: BeitConfig) -> None:
309
+ super().__init__()
310
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
311
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
312
+
313
+ def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor, gamma=None) -> torch.Tensor:
314
+ hidden_states = self.dense(hidden_states)
315
+ hidden_states = self.dropout(hidden_states)
316
+
317
+ return hidden_states
318
+
319
+
320
+ class BeitAttention(nn.Module):
321
+ def __init__(self, config: BeitConfig, window_size: Optional[tuple] = None) -> None:
322
+ super().__init__()
323
+ self.attention = BeitSelfAttention(config, window_size=window_size)
324
+ self.output = BeitSelfOutput(config)
325
+ self.pruned_heads = set()
326
+
327
+ def prune_heads(self, heads):
328
+ if len(heads) == 0:
329
+ return
330
+ heads, index = find_pruneable_heads_and_indices(
331
+ heads, self.attention.num_attention_heads, self.attention.attention_head_size, self.pruned_heads
332
+ )
333
+
334
+ # Prune linear layers
335
+ self.attention.query = prune_linear_layer(self.attention.query, index)
336
+ self.attention.key = prune_linear_layer(self.attention.key, index)
337
+ self.attention.value = prune_linear_layer(self.attention.value, index)
338
+ self.output.dense = prune_linear_layer(self.output.dense, index, dim=1)
339
+
340
+ # Update hyper params and store pruned heads
341
+ self.attention.num_attention_heads = self.attention.num_attention_heads - len(heads)
342
+ self.attention.all_head_size = self.attention.attention_head_size * self.attention.num_attention_heads
343
+ self.pruned_heads = self.pruned_heads.union(heads)
344
+
345
+ def forward(
346
+ self,
347
+ hidden_states: torch.Tensor,
348
+ head_mask: Optional[torch.Tensor] = None,
349
+ output_attentions: bool = False,
350
+ relative_position_bias: Optional["BeitRelativePositionBias"] = None,
351
+ ) -> Union[Tuple[torch.Tensor], Tuple[torch.Tensor, torch.Tensor]]:
352
+ self_outputs = self.attention(hidden_states, head_mask, output_attentions, relative_position_bias)
353
+
354
+ attention_output = self.output(self_outputs[0], hidden_states)
355
+
356
+ outputs = (attention_output,) + self_outputs[1:] # add attentions if we output them
357
+ return outputs
358
+
359
+
360
+ class BeitIntermediate(nn.Module):
361
+ def __init__(self, config: BeitConfig) -> None:
362
+ super().__init__()
363
+ self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
364
+ if isinstance(config.hidden_act, str):
365
+ self.intermediate_act_fn = ACT2FN[config.hidden_act]
366
+ else:
367
+ self.intermediate_act_fn = config.hidden_act
368
+
369
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
370
+ hidden_states = self.dense(hidden_states)
371
+ hidden_states = self.intermediate_act_fn(hidden_states)
372
+
373
+ return hidden_states
374
+
375
+
376
+ class BeitOutput(nn.Module):
377
+ def __init__(self, config: BeitConfig) -> None:
378
+ super().__init__()
379
+ self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
380
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
381
+
382
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
383
+ hidden_states = self.dense(hidden_states)
384
+ hidden_states = self.dropout(hidden_states)
385
+
386
+ return hidden_states
387
+
388
+
389
+ class BeitLayer(nn.Module):
390
+ """This corresponds to the Block class in the timm implementation."""
391
+
392
+ def __init__(self, config: BeitConfig, window_size: Optional[tuple] = None, drop_path_rate: float = 0.0) -> None:
393
+ super().__init__()
394
+ self.chunk_size_feed_forward = config.chunk_size_feed_forward
395
+ self.seq_len_dim = 1
396
+ self.attention = BeitAttention(config, window_size=window_size)
397
+ self.intermediate = BeitIntermediate(config)
398
+ self.output = BeitOutput(config)
399
+ self.layernorm_before = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
400
+ self.drop_path = BeitDropPath(drop_path_rate) if drop_path_rate > 0.0 else nn.Identity()
401
+ self.layernorm_after = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
402
+
403
+ init_values = config.layer_scale_init_value
404
+ if init_values > 0:
405
+ self.lambda_1 = nn.Parameter(init_values * torch.ones((config.hidden_size)), requires_grad=True)
406
+ self.lambda_2 = nn.Parameter(init_values * torch.ones((config.hidden_size)), requires_grad=True)
407
+ else:
408
+ self.lambda_1, self.lambda_2 = None, None
409
+
410
+ def forward(
411
+ self,
412
+ hidden_states: torch.Tensor,
413
+ head_mask: Optional[torch.Tensor] = None,
414
+ output_attentions: bool = False,
415
+ relative_position_bias: Optional["BeitRelativePositionBias"] = None,
416
+ ) -> Union[Tuple[torch.Tensor], Tuple[torch.Tensor, torch.Tensor]]:
417
+ self_attention_outputs = self.attention(
418
+ self.layernorm_before(hidden_states), # in BEiT, layernorm is applied before self-attention
419
+ head_mask,
420
+ output_attentions=output_attentions,
421
+ relative_position_bias=relative_position_bias,
422
+ )
423
+ attention_output = self_attention_outputs[0]
424
+ outputs = self_attention_outputs[1:] # add self attentions if we output attention weights
425
+
426
+ # apply lambda_1 if present
427
+ if self.lambda_1 is not None:
428
+ attention_output = self.lambda_1 * attention_output
429
+
430
+ # first residual connection
431
+ hidden_states = self.drop_path(attention_output) + hidden_states
432
+
433
+ # in BEiT, layernorm is also applied after self-attention
434
+ layer_output = self.layernorm_after(hidden_states)
435
+
436
+ layer_output = self.intermediate(layer_output)
437
+ layer_output = self.output(layer_output)
438
+
439
+ if self.lambda_2 is not None:
440
+ layer_output = self.lambda_2 * layer_output
441
+
442
+ # second residual connection
443
+ layer_output = self.drop_path(layer_output) + hidden_states
444
+
445
+ outputs = (layer_output,) + outputs
446
+
447
+ return outputs
448
+
449
+
450
+ class BeitRelativePositionBias(nn.Module):
451
+ def __init__(self, config: BeitConfig, window_size: tuple) -> None:
452
+ super().__init__()
453
+ self.window_size = window_size
454
+ self.num_relative_distance = (2 * window_size[0] - 1) * (2 * window_size[1] - 1) + 3
455
+ self.relative_position_bias_table = nn.Parameter(
456
+ torch.zeros(self.num_relative_distance, config.num_attention_heads)
457
+ ) # 2*Wh-1 * 2*Ww-1, nH
458
+ # cls to token & token 2 cls & cls to cls
459
+
460
+ # get pair-wise relative position index for each token inside the window
461
+ coords_h = torch.arange(window_size[0])
462
+ coords_w = torch.arange(window_size[1])
463
+ coords = torch.stack(meshgrid([coords_h, coords_w], indexing="ij")) # 2, Wh, Ww
464
+ coords_flatten = torch.flatten(coords, 1) # 2, Wh*Ww
465
+ relative_coords = coords_flatten[:, :, None] - coords_flatten[:, None, :] # 2, Wh*Ww, Wh*Ww
466
+ relative_coords = relative_coords.permute(1, 2, 0).contiguous() # Wh*Ww, Wh*Ww, 2
467
+ relative_coords[:, :, 0] += window_size[0] - 1 # shift to start from 0
468
+ relative_coords[:, :, 1] += window_size[1] - 1
469
+ relative_coords[:, :, 0] *= 2 * window_size[1] - 1
470
+ relative_position_index = torch.zeros(
471
+ size=(window_size[0] * window_size[1] + 1,) * 2, dtype=relative_coords.dtype
472
+ )
473
+ relative_position_index[1:, 1:] = relative_coords.sum(-1) # Wh*Ww, Wh*Ww
474
+ relative_position_index[0, 0:] = self.num_relative_distance - 3
475
+ relative_position_index[0:, 0] = self.num_relative_distance - 2
476
+ relative_position_index[0, 0] = self.num_relative_distance - 1
477
+
478
+ self.register_buffer("relative_position_index", relative_position_index, persistent=False)
479
+
480
+ def forward(self) -> torch.Tensor:
481
+ relative_position_bias = self.relative_position_bias_table[self.relative_position_index.view(-1)].view(
482
+ self.window_size[0] * self.window_size[1] + 1, self.window_size[0] * self.window_size[1] + 1, -1
483
+ ) # Wh*Ww,Wh*Ww,nH
484
+
485
+ return relative_position_bias.permute(2, 0, 1).contiguous() # nH, Wh*Ww, Wh*Ww
486
+
487
+
488
+ class BeitEncoder(nn.Module):
489
+ def __init__(self, config: BeitConfig, window_size: Optional[tuple] = None) -> None:
490
+ super().__init__()
491
+ self.config = config
492
+ if config.use_shared_relative_position_bias:
493
+ self.relative_position_bias = BeitRelativePositionBias(config, window_size=window_size)
494
+ else:
495
+ self.relative_position_bias = None
496
+
497
+ # stochastic depth decay rule
498
+ dpr = [x.item() for x in torch.linspace(0, config.drop_path_rate, config.num_hidden_layers)]
499
+ self.layer = nn.ModuleList(
500
+ [
501
+ BeitLayer(
502
+ config,
503
+ window_size=window_size if config.use_relative_position_bias else None,
504
+ drop_path_rate=dpr[i],
505
+ )
506
+ for i in range(config.num_hidden_layers)
507
+ ]
508
+ )
509
+ self.gradient_checkpointing = False
510
+
511
+ def forward(
512
+ self,
513
+ hidden_states: torch.Tensor,
514
+ head_mask: Optional[torch.Tensor] = None,
515
+ output_attentions: bool = False,
516
+ output_hidden_states: bool = False,
517
+ return_dict: bool = True,
518
+ ) -> Union[tuple, BaseModelOutput]:
519
+ all_hidden_states = () if output_hidden_states else None
520
+ all_self_attentions = () if output_attentions else None
521
+
522
+ for i, layer_module in enumerate(self.layer):
523
+ if output_hidden_states:
524
+ all_hidden_states = all_hidden_states + (hidden_states,)
525
+
526
+ layer_head_mask = head_mask[i] if head_mask is not None else None
527
+
528
+ if self.gradient_checkpointing and self.training:
529
+ layer_outputs = self._gradient_checkpointing_func(
530
+ layer_module.__call__,
531
+ hidden_states,
532
+ layer_head_mask,
533
+ output_attentions,
534
+ )
535
+ else:
536
+ relative_position_bias = (
537
+ self.relative_position_bias() if self.relative_position_bias is not None else None
538
+ )
539
+ layer_outputs = layer_module(hidden_states, layer_head_mask, output_attentions, relative_position_bias)
540
+
541
+ hidden_states = layer_outputs[0]
542
+
543
+ if output_attentions:
544
+ all_self_attentions = all_self_attentions + (layer_outputs[1],)
545
+
546
+ if output_hidden_states:
547
+ all_hidden_states = all_hidden_states + (hidden_states,)
548
+
549
+ if not return_dict:
550
+ return tuple(v for v in [hidden_states, all_hidden_states, all_self_attentions] if v is not None)
551
+ return BaseModelOutput(
552
+ last_hidden_state=hidden_states,
553
+ hidden_states=all_hidden_states,
554
+ attentions=all_self_attentions,
555
+ )
556
+
557
+
558
+ class BeitPreTrainedModel(PreTrainedModel):
559
+ """
560
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
561
+ models.
562
+ """
563
+
564
+ config_class = BeitConfig
565
+ base_model_prefix = "beit"
566
+ main_input_name = "pixel_values"
567
+ supports_gradient_checkpointing = True
568
+
569
+ def _init_weights(self, module):
570
+ """Initialize the weights"""
571
+ if isinstance(module, (nn.Linear, nn.Conv2d, nn.ConvTranspose2d)):
572
+ # Slightly different from the TF version which uses truncated_normal for initialization
573
+ # cf https://github.com/pytorch/pytorch/pull/5617
574
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
575
+ if module.bias is not None:
576
+ module.bias.data.zero_()
577
+ elif isinstance(module, nn.Embedding):
578
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
579
+ if module.padding_idx is not None:
580
+ module.weight.data[module.padding_idx].zero_()
581
+ elif isinstance(module, nn.LayerNorm):
582
+ module.bias.data.zero_()
583
+ module.weight.data.fill_(1.0)
584
+
585
+
586
+ BEIT_START_DOCSTRING = r"""
587
+ This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it
588
+ as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and
589
+ behavior.
590
+
591
+ Parameters:
592
+ config ([`BeitConfig`]): Model configuration class with all the parameters of the model.
593
+ Initializing with a config file does not load the weights associated with the model, only the
594
+ configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
595
+ """
596
+
597
+ BEIT_INPUTS_DOCSTRING = r"""
598
+ Args:
599
+ pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
600
+ Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See
601
+ [`BeitImageProcessor.__call__`] for details.
602
+
603
+ head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
604
+ Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:
605
+
606
+ - 1 indicates the head is **not masked**,
607
+ - 0 indicates the head is **masked**.
608
+
609
+ output_attentions (`bool`, *optional*):
610
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
611
+ tensors for more detail.
612
+ output_hidden_states (`bool`, *optional*):
613
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
614
+ more detail.
615
+ return_dict (`bool`, *optional*):
616
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
617
+ """
618
+
619
+
620
+ @add_start_docstrings(
621
+ "The bare Beit Model transformer outputting raw hidden-states without any specific head on top.",
622
+ BEIT_START_DOCSTRING,
623
+ )
624
+ class BeitModel(BeitPreTrainedModel):
625
+ def __init__(self, config: BeitConfig, add_pooling_layer: bool = True) -> None:
626
+ super().__init__(config)
627
+ self.config = config
628
+
629
+ self.embeddings = BeitEmbeddings(config)
630
+ self.encoder = BeitEncoder(config, window_size=self.embeddings.patch_embeddings.patch_shape)
631
+
632
+ self.layernorm = (
633
+ nn.Identity() if config.use_mean_pooling else nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
634
+ )
635
+ self.pooler = BeitPooler(config) if add_pooling_layer else None
636
+
637
+ # Initialize weights and apply final processing
638
+ self.post_init()
639
+
640
+ def get_input_embeddings(self):
641
+ return self.embeddings.patch_embeddings
642
+
643
+ def _prune_heads(self, heads_to_prune):
644
+ """
645
+ Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
646
+ class PreTrainedModel
647
+ """
648
+ for layer, heads in heads_to_prune.items():
649
+ self.encoder.layer[layer].attention.prune_heads(heads)
650
+
651
+ @add_start_docstrings_to_model_forward(BEIT_INPUTS_DOCSTRING)
652
+ @add_code_sample_docstrings(
653
+ checkpoint=_CHECKPOINT_FOR_DOC,
654
+ output_type=BeitModelOutputWithPooling,
655
+ config_class=_CONFIG_FOR_DOC,
656
+ modality="vision",
657
+ expected_output=_EXPECTED_OUTPUT_SHAPE,
658
+ )
659
+ def forward(
660
+ self,
661
+ pixel_values: Optional[torch.Tensor] = None,
662
+ bool_masked_pos: Optional[torch.BoolTensor] = None,
663
+ head_mask: Optional[torch.Tensor] = None,
664
+ output_attentions: Optional[bool] = None,
665
+ output_hidden_states: Optional[bool] = None,
666
+ return_dict: Optional[bool] = None,
667
+ ) -> Union[tuple, BeitModelOutputWithPooling]:
668
+ r"""
669
+ bool_masked_pos (`torch.BoolTensor` of shape `(batch_size, num_patches)`, *optional*):
670
+ Boolean masked positions. Indicates which patches are masked (1) and which aren't (0).
671
+ """
672
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
673
+ output_hidden_states = (
674
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
675
+ )
676
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
677
+
678
+ if pixel_values is None:
679
+ raise ValueError("You have to specify pixel_values")
680
+
681
+ # Prepare head mask if needed
682
+ # 1.0 in head_mask indicate we keep the head
683
+ # attention_probs has shape bsz x n_heads x N x N
684
+ # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]
685
+ # and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]
686
+ head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)
687
+
688
+ embedding_output, (patch_height, patch_width) = self.embeddings(pixel_values, bool_masked_pos)
689
+
690
+ encoder_outputs = self.encoder(
691
+ embedding_output,
692
+ head_mask=head_mask,
693
+ output_attentions=output_attentions,
694
+ output_hidden_states=output_hidden_states,
695
+ return_dict=return_dict,
696
+ )
697
+ sequence_output = encoder_outputs[0]
698
+ sequence_output = self.layernorm(sequence_output)
699
+ pooled_output = self.pooler(sequence_output) if self.pooler is not None else None
700
+
701
+ if not return_dict:
702
+ head_outputs = (sequence_output, pooled_output) if pooled_output is not None else (sequence_output,)
703
+ return head_outputs + encoder_outputs[1:]
704
+
705
+ return BeitModelOutputWithPooling(
706
+ last_hidden_state=sequence_output,
707
+ pooler_output=pooled_output,
708
+ hidden_states=encoder_outputs.hidden_states,
709
+ attentions=encoder_outputs.attentions,
710
+ )
711
+
712
+
713
+ class BeitPooler(nn.Module):
714
+ def __init__(self, config: BeitConfig) -> None:
715
+ super().__init__()
716
+ self.layernorm = (
717
+ nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps) if config.use_mean_pooling else None
718
+ )
719
+
720
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
721
+ if self.layernorm is not None:
722
+ # Mean pool the final hidden states of the patch tokens
723
+ patch_tokens = hidden_states[:, 1:, :]
724
+ pooled_output = self.layernorm(patch_tokens.mean(1))
725
+ else:
726
+ # Pool by simply taking the final hidden state of the [CLS] token
727
+ pooled_output = hidden_states[:, 0]
728
+
729
+ return pooled_output
730
+
731
+
732
+ @add_start_docstrings(
733
+ """Beit Model transformer with a 'language' modeling head on top. BEiT does masked image modeling by predicting
734
+ visual tokens of a Vector-Quantize Variational Autoencoder (VQ-VAE), whereas other vision models like ViT and DeiT
735
+ predict RGB pixel values. As a result, this class is incompatible with [`AutoModelForMaskedImageModeling`], so you
736
+ will need to use [`BeitForMaskedImageModeling`] directly if you wish to do masked image modeling with BEiT.""",
737
+ BEIT_START_DOCSTRING,
738
+ )
739
+ class BeitForMaskedImageModeling(BeitPreTrainedModel):
740
+ def __init__(self, config: BeitConfig) -> None:
741
+ super().__init__(config)
742
+
743
+ self.num_labels = config.num_labels
744
+ self.beit = BeitModel(config, add_pooling_layer=False)
745
+
746
+ # Classifier head
747
+ self.layernorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
748
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size)
749
+
750
+ # Initialize weights and apply final processing
751
+ self.post_init()
752
+
753
+ @add_start_docstrings_to_model_forward(BEIT_INPUTS_DOCSTRING)
754
+ @replace_return_docstrings(output_type=MaskedLMOutput, config_class=_CONFIG_FOR_DOC)
755
+ def forward(
756
+ self,
757
+ pixel_values: Optional[torch.Tensor] = None,
758
+ bool_masked_pos: Optional[torch.BoolTensor] = None,
759
+ head_mask: Optional[torch.Tensor] = None,
760
+ labels: Optional[torch.Tensor] = None,
761
+ output_attentions: Optional[bool] = None,
762
+ output_hidden_states: Optional[bool] = None,
763
+ return_dict: Optional[bool] = None,
764
+ ) -> Union[tuple, MaskedLMOutput]:
765
+ r"""
766
+ bool_masked_pos (`torch.BoolTensor` of shape `(batch_size, num_patches)`):
767
+ Boolean masked positions. Indicates which patches are masked (1) and which aren't (0).
768
+
769
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
770
+ Labels for computing the image classification/regression loss. Indices should be in `[0, ...,
771
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
772
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
773
+
774
+ Returns:
775
+
776
+ Examples:
777
+
778
+ ```python
779
+ >>> from transformers import AutoImageProcessor, BeitForMaskedImageModeling
780
+ >>> import torch
781
+ >>> from PIL import Image
782
+ >>> import requests
783
+
784
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
785
+ >>> image = Image.open(requests.get(url, stream=True).raw)
786
+
787
+ >>> image_processor = AutoImageProcessor.from_pretrained("microsoft/beit-base-patch16-224-pt22k")
788
+ >>> model = BeitForMaskedImageModeling.from_pretrained("microsoft/beit-base-patch16-224-pt22k")
789
+
790
+ >>> num_patches = (model.config.image_size // model.config.patch_size) ** 2
791
+ >>> pixel_values = image_processor(images=image, return_tensors="pt").pixel_values
792
+ >>> # create random boolean mask of shape (batch_size, num_patches)
793
+ >>> bool_masked_pos = torch.randint(low=0, high=2, size=(1, num_patches)).bool()
794
+
795
+ >>> outputs = model(pixel_values, bool_masked_pos=bool_masked_pos)
796
+ >>> loss, logits = outputs.loss, outputs.logits
797
+ >>> list(logits.shape)
798
+ [1, 196, 8192]
799
+ ```"""
800
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
801
+
802
+ outputs = self.beit(
803
+ pixel_values,
804
+ bool_masked_pos=bool_masked_pos,
805
+ head_mask=head_mask,
806
+ output_attentions=output_attentions,
807
+ output_hidden_states=output_hidden_states,
808
+ return_dict=return_dict,
809
+ )
810
+
811
+ sequence_output = outputs[0]
812
+ sequence_output = self.layernorm(sequence_output)
813
+ prediction_scores = self.lm_head(sequence_output[:, 1:])
814
+
815
+ masked_lm_loss = None
816
+ if labels is not None:
817
+ loss_fct = CrossEntropyLoss() # -100 index = padding token
818
+ masked_lm_loss = loss_fct(prediction_scores[bool_masked_pos], labels)
819
+
820
+ if not return_dict:
821
+ output = (prediction_scores,) + outputs[1:]
822
+ return ((masked_lm_loss,) + output) if masked_lm_loss is not None else output
823
+
824
+ return MaskedLMOutput(
825
+ loss=masked_lm_loss,
826
+ logits=prediction_scores,
827
+ hidden_states=outputs.hidden_states,
828
+ attentions=outputs.attentions,
829
+ )
830
+
831
+
832
+ @add_start_docstrings(
833
+ """
834
+ Beit Model transformer with an image classification head on top (a linear layer on top of the average of the final
835
+ hidden states of the patch tokens) e.g. for ImageNet.
836
+ """,
837
+ BEIT_START_DOCSTRING,
838
+ )
839
+ class BeitForImageClassification(BeitPreTrainedModel):
840
+ def __init__(self, config: BeitConfig) -> None:
841
+ super().__init__(config)
842
+
843
+ self.num_labels = config.num_labels
844
+ self.beit = BeitModel(config, add_pooling_layer=True)
845
+
846
+ # Classifier head
847
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels) if config.num_labels > 0 else nn.Identity()
848
+
849
+ # Initialize weights and apply final processing
850
+ self.post_init()
851
+
852
+ @add_start_docstrings_to_model_forward(BEIT_INPUTS_DOCSTRING)
853
+ @add_code_sample_docstrings(
854
+ checkpoint=_IMAGE_CLASS_CHECKPOINT,
855
+ output_type=ImageClassifierOutput,
856
+ config_class=_CONFIG_FOR_DOC,
857
+ expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT,
858
+ )
859
+ def forward(
860
+ self,
861
+ pixel_values: Optional[torch.Tensor] = None,
862
+ head_mask: Optional[torch.Tensor] = None,
863
+ labels: Optional[torch.Tensor] = None,
864
+ output_attentions: Optional[bool] = None,
865
+ output_hidden_states: Optional[bool] = None,
866
+ return_dict: Optional[bool] = None,
867
+ ) -> Union[tuple, ImageClassifierOutput]:
868
+ r"""
869
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
870
+ Labels for computing the image classification/regression loss. Indices should be in `[0, ...,
871
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
872
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
873
+ """
874
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
875
+ outputs = self.beit(
876
+ pixel_values,
877
+ head_mask=head_mask,
878
+ output_attentions=output_attentions,
879
+ output_hidden_states=output_hidden_states,
880
+ return_dict=return_dict,
881
+ )
882
+
883
+ pooled_output = outputs.pooler_output if return_dict else outputs[1]
884
+
885
+ logits = self.classifier(pooled_output)
886
+
887
+ loss = None
888
+ if labels is not None:
889
+ if self.config.problem_type is None:
890
+ if self.num_labels == 1:
891
+ self.config.problem_type = "regression"
892
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
893
+ self.config.problem_type = "single_label_classification"
894
+ else:
895
+ self.config.problem_type = "multi_label_classification"
896
+
897
+ if self.config.problem_type == "regression":
898
+ loss_fct = MSELoss()
899
+ if self.num_labels == 1:
900
+ loss = loss_fct(logits.squeeze(), labels.squeeze())
901
+ else:
902
+ loss = loss_fct(logits, labels)
903
+ elif self.config.problem_type == "single_label_classification":
904
+ loss_fct = CrossEntropyLoss()
905
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
906
+ elif self.config.problem_type == "multi_label_classification":
907
+ loss_fct = BCEWithLogitsLoss()
908
+ loss = loss_fct(logits, labels)
909
+ if not return_dict:
910
+ output = (logits,) + outputs[2:]
911
+ return ((loss,) + output) if loss is not None else output
912
+
913
+ return ImageClassifierOutput(
914
+ loss=loss,
915
+ logits=logits,
916
+ hidden_states=outputs.hidden_states,
917
+ attentions=outputs.attentions,
918
+ )
919
+
920
+
921
+ class BeitConvModule(nn.Module):
922
+ """
923
+ A convolutional block that bundles conv/norm/activation layers. This block simplifies the usage of convolution
924
+ layers, which are commonly used with a norm layer (e.g., BatchNorm) and activation layer (e.g., ReLU).
925
+
926
+ Based on OpenMMLab's implementation, found in https://github.com/open-mmlab/mmsegmentation.
927
+ """
928
+
929
+ def __init__(
930
+ self,
931
+ in_channels: int,
932
+ out_channels: int,
933
+ kernel_size: Union[int, Tuple[int, int]],
934
+ padding: Union[int, Tuple[int, int], str] = 0,
935
+ bias: bool = False,
936
+ dilation: Union[int, Tuple[int, int]] = 1,
937
+ ) -> None:
938
+ super().__init__()
939
+ self.conv = nn.Conv2d(
940
+ in_channels=in_channels,
941
+ out_channels=out_channels,
942
+ kernel_size=kernel_size,
943
+ padding=padding,
944
+ bias=bias,
945
+ dilation=dilation,
946
+ )
947
+ self.bn = nn.BatchNorm2d(out_channels)
948
+ self.activation = nn.ReLU()
949
+
950
+ def forward(self, input: torch.Tensor) -> torch.Tensor:
951
+ output = self.conv(input)
952
+ output = self.bn(output)
953
+ output = self.activation(output)
954
+
955
+ return output
956
+
957
+
958
+ class BeitPyramidPoolingBlock(nn.Module):
959
+ def __init__(self, pool_scale: int, in_channels: int, channels: int) -> None:
960
+ super().__init__()
961
+ self.layers = [
962
+ nn.AdaptiveAvgPool2d(pool_scale),
963
+ BeitConvModule(in_channels, channels, kernel_size=1),
964
+ ]
965
+ for i, layer in enumerate(self.layers):
966
+ self.add_module(str(i), layer)
967
+
968
+ def forward(self, input: torch.Tensor) -> torch.Tensor:
969
+ hidden_state = input
970
+ for layer in self.layers:
971
+ hidden_state = layer(hidden_state)
972
+ return hidden_state
973
+
974
+
975
+ class BeitPyramidPoolingModule(nn.Module):
976
+ """
977
+ Pyramid Pooling Module (PPM) used in PSPNet.
978
+
979
+ Args:
980
+ pool_scales (tuple[int]): Pooling scales used in Pooling Pyramid
981
+ Module.
982
+ in_channels (int): Input channels.
983
+ channels (int): Channels after modules, before conv_seg.
984
+ align_corners (bool): align_corners argument of F.interpolate.
985
+
986
+ Based on OpenMMLab's implementation, found in https://github.com/open-mmlab/mmsegmentation.
987
+ """
988
+
989
+ def __init__(self, pool_scales: Tuple[int, ...], in_channels: int, channels: int, align_corners: bool) -> None:
990
+ super().__init__()
991
+ self.pool_scales = pool_scales
992
+ self.align_corners = align_corners
993
+ self.in_channels = in_channels
994
+ self.channels = channels
995
+ self.blocks = []
996
+ for i, pool_scale in enumerate(pool_scales):
997
+ block = BeitPyramidPoolingBlock(pool_scale=pool_scale, in_channels=in_channels, channels=channels)
998
+ self.blocks.append(block)
999
+ self.add_module(str(i), block)
1000
+
1001
+ def forward(self, x: torch.Tensor) -> List[torch.Tensor]:
1002
+ ppm_outs = []
1003
+ for ppm in self.blocks:
1004
+ ppm_out = ppm(x)
1005
+ upsampled_ppm_out = nn.functional.interpolate(
1006
+ ppm_out, size=x.size()[2:], mode="bilinear", align_corners=self.align_corners
1007
+ )
1008
+ ppm_outs.append(upsampled_ppm_out)
1009
+ return ppm_outs
1010
+
1011
+
1012
+ class BeitUperHead(nn.Module):
1013
+ """
1014
+ Unified Perceptual Parsing for Scene Understanding. This head is the implementation of
1015
+ [UPerNet](https://arxiv.org/abs/1807.10221).
1016
+
1017
+ Based on OpenMMLab's implementation, found in https://github.com/open-mmlab/mmsegmentation.
1018
+ """
1019
+
1020
+ def __init__(self, config: BeitConfig) -> None:
1021
+ super().__init__()
1022
+
1023
+ self.pool_scales = config.pool_scales # e.g. (1, 2, 3, 6)
1024
+ self.in_channels = [config.hidden_size] * 4 # e.g. [768, 768, 768, 768]
1025
+ self.channels = config.hidden_size
1026
+ self.align_corners = False
1027
+ self.classifier = nn.Conv2d(self.channels, config.num_labels, kernel_size=1)
1028
+
1029
+ # PSP Module
1030
+ self.psp_modules = BeitPyramidPoolingModule(
1031
+ self.pool_scales,
1032
+ self.in_channels[-1],
1033
+ self.channels,
1034
+ align_corners=self.align_corners,
1035
+ )
1036
+ self.bottleneck = BeitConvModule(
1037
+ self.in_channels[-1] + len(self.pool_scales) * self.channels,
1038
+ self.channels,
1039
+ kernel_size=3,
1040
+ padding=1,
1041
+ )
1042
+ # FPN Module
1043
+ self.lateral_convs = nn.ModuleList()
1044
+ self.fpn_convs = nn.ModuleList()
1045
+ for in_channels in self.in_channels[:-1]: # skip the top layer
1046
+ l_conv = BeitConvModule(in_channels, self.channels, kernel_size=1)
1047
+ fpn_conv = BeitConvModule(self.channels, self.channels, kernel_size=3, padding=1)
1048
+ self.lateral_convs.append(l_conv)
1049
+ self.fpn_convs.append(fpn_conv)
1050
+
1051
+ self.fpn_bottleneck = BeitConvModule(
1052
+ len(self.in_channels) * self.channels,
1053
+ self.channels,
1054
+ kernel_size=3,
1055
+ padding=1,
1056
+ )
1057
+
1058
+ def psp_forward(self, inputs):
1059
+ x = inputs[-1]
1060
+ psp_outs = [x]
1061
+ psp_outs.extend(self.psp_modules(x))
1062
+ psp_outs = torch.cat(psp_outs, dim=1)
1063
+ output = self.bottleneck(psp_outs)
1064
+
1065
+ return output
1066
+
1067
+ def forward(self, encoder_hidden_states: torch.Tensor) -> torch.Tensor:
1068
+ # build laterals
1069
+ laterals = [lateral_conv(encoder_hidden_states[i]) for i, lateral_conv in enumerate(self.lateral_convs)]
1070
+
1071
+ laterals.append(self.psp_forward(encoder_hidden_states))
1072
+
1073
+ # build top-down path
1074
+ used_backbone_levels = len(laterals)
1075
+ for i in range(used_backbone_levels - 1, 0, -1):
1076
+ prev_shape = laterals[i - 1].shape[2:]
1077
+ laterals[i - 1] = laterals[i - 1] + nn.functional.interpolate(
1078
+ laterals[i], size=prev_shape, mode="bilinear", align_corners=self.align_corners
1079
+ )
1080
+
1081
+ # build outputs
1082
+ fpn_outs = [self.fpn_convs[i](laterals[i]) for i in range(used_backbone_levels - 1)]
1083
+ # append psp feature
1084
+ fpn_outs.append(laterals[-1])
1085
+
1086
+ for i in range(used_backbone_levels - 1, 0, -1):
1087
+ fpn_outs[i] = nn.functional.interpolate(
1088
+ fpn_outs[i], size=fpn_outs[0].shape[2:], mode="bilinear", align_corners=self.align_corners
1089
+ )
1090
+ fpn_outs = torch.cat(fpn_outs, dim=1)
1091
+ output = self.fpn_bottleneck(fpn_outs)
1092
+ output = self.classifier(output)
1093
+
1094
+ return output
1095
+
1096
+
1097
+ class BeitFCNHead(nn.Module):
1098
+ """
1099
+ Fully Convolution Networks for Semantic Segmentation. This head is implemented of
1100
+ [FCNNet](https://arxiv.org/abs/1411.4038>).
1101
+
1102
+ Args:
1103
+ config (BeitConfig): Configuration.
1104
+ in_channels
1105
+ kernel_size (int): The kernel size for convs in the head. Default: 3.
1106
+ dilation (int): The dilation rate for convs in the head. Default: 1.
1107
+
1108
+
1109
+ Based on OpenMMLab's implementation, found in https://github.com/open-mmlab/mmsegmentation.
1110
+ """
1111
+
1112
+ def __init__(
1113
+ self, config: BeitConfig, in_index: int = 2, kernel_size: int = 3, dilation: Union[int, Tuple[int, int]] = 1
1114
+ ) -> None:
1115
+ super().__init__()
1116
+ self.in_channels = config.hidden_size
1117
+ self.channels = config.auxiliary_channels
1118
+ self.num_convs = config.auxiliary_num_convs
1119
+ self.concat_input = config.auxiliary_concat_input
1120
+ self.in_index = in_index
1121
+
1122
+ conv_padding = (kernel_size // 2) * dilation
1123
+ convs = []
1124
+ convs.append(
1125
+ BeitConvModule(
1126
+ self.in_channels, self.channels, kernel_size=kernel_size, padding=conv_padding, dilation=dilation
1127
+ )
1128
+ )
1129
+ for i in range(self.num_convs - 1):
1130
+ convs.append(
1131
+ BeitConvModule(
1132
+ self.channels, self.channels, kernel_size=kernel_size, padding=conv_padding, dilation=dilation
1133
+ )
1134
+ )
1135
+ if self.num_convs == 0:
1136
+ self.convs = nn.Identity()
1137
+ else:
1138
+ self.convs = nn.Sequential(*convs)
1139
+ if self.concat_input:
1140
+ self.conv_cat = BeitConvModule(
1141
+ self.in_channels + self.channels, self.channels, kernel_size=kernel_size, padding=kernel_size // 2
1142
+ )
1143
+
1144
+ self.classifier = nn.Conv2d(self.channels, config.num_labels, kernel_size=1)
1145
+
1146
+ def forward(self, encoder_hidden_states: torch.Tensor) -> torch.Tensor:
1147
+ # just take the relevant feature maps
1148
+ hidden_states = encoder_hidden_states[self.in_index]
1149
+ output = self.convs(hidden_states)
1150
+ if self.concat_input:
1151
+ output = self.conv_cat(torch.cat([hidden_states, output], dim=1))
1152
+ output = self.classifier(output)
1153
+ return output
1154
+
1155
+
1156
+ @add_start_docstrings(
1157
+ """
1158
+ Beit Model transformer with a semantic segmentation head on top e.g. for ADE20k, CityScapes.
1159
+ """,
1160
+ BEIT_START_DOCSTRING,
1161
+ )
1162
+ class BeitForSemanticSegmentation(BeitPreTrainedModel):
1163
+ def __init__(self, config: BeitConfig) -> None:
1164
+ super().__init__(config)
1165
+
1166
+ self.num_labels = config.num_labels
1167
+ self.beit = BeitModel(config, add_pooling_layer=False)
1168
+
1169
+ # FPNs
1170
+ if len(self.config.out_indices) != 4:
1171
+ raise ValueError(
1172
+ "BeitForSemanticSegmentation requires config.out_indices to be a list of 4 integers, "
1173
+ "specifying which features to use from the backbone. One can use [3, 5, 7, 11] in case of "
1174
+ "a base-sized architecture."
1175
+ )
1176
+ self.fpn1 = nn.Sequential(
1177
+ nn.ConvTranspose2d(config.hidden_size, config.hidden_size, kernel_size=2, stride=2),
1178
+ nn.BatchNorm2d(config.hidden_size),
1179
+ nn.GELU(),
1180
+ nn.ConvTranspose2d(config.hidden_size, config.hidden_size, kernel_size=2, stride=2),
1181
+ )
1182
+ self.fpn2 = nn.Sequential(
1183
+ nn.ConvTranspose2d(config.hidden_size, config.hidden_size, kernel_size=2, stride=2),
1184
+ )
1185
+ self.fpn3 = nn.Identity()
1186
+ self.fpn4 = nn.MaxPool2d(kernel_size=2, stride=2)
1187
+
1188
+ # Semantic segmentation head(s)
1189
+ self.decode_head = BeitUperHead(config)
1190
+ self.auxiliary_head = BeitFCNHead(config) if config.use_auxiliary_head else None
1191
+
1192
+ # Initialize weights and apply final processing
1193
+ self.post_init()
1194
+
1195
+ def compute_loss(self, logits, auxiliary_logits, labels):
1196
+ # upsample logits to the images' original size
1197
+ upsampled_logits = nn.functional.interpolate(
1198
+ logits, size=labels.shape[-2:], mode="bilinear", align_corners=False
1199
+ )
1200
+ if auxiliary_logits is not None:
1201
+ upsampled_auxiliary_logits = nn.functional.interpolate(
1202
+ auxiliary_logits, size=labels.shape[-2:], mode="bilinear", align_corners=False
1203
+ )
1204
+ # compute weighted loss
1205
+ loss_fct = CrossEntropyLoss(ignore_index=self.config.semantic_loss_ignore_index)
1206
+ main_loss = loss_fct(upsampled_logits, labels)
1207
+ loss = main_loss
1208
+ if auxiliary_logits is not None:
1209
+ auxiliary_loss = loss_fct(upsampled_auxiliary_logits, labels)
1210
+ loss += self.config.auxiliary_loss_weight * auxiliary_loss
1211
+
1212
+ return loss
1213
+
1214
+ @add_start_docstrings_to_model_forward(BEIT_INPUTS_DOCSTRING)
1215
+ @replace_return_docstrings(output_type=SemanticSegmenterOutput, config_class=_CONFIG_FOR_DOC)
1216
+ def forward(
1217
+ self,
1218
+ pixel_values: Optional[torch.Tensor] = None,
1219
+ head_mask: Optional[torch.Tensor] = None,
1220
+ labels: Optional[torch.Tensor] = None,
1221
+ output_attentions: Optional[bool] = None,
1222
+ output_hidden_states: Optional[bool] = None,
1223
+ return_dict: Optional[bool] = None,
1224
+ ) -> Union[tuple, SemanticSegmenterOutput]:
1225
+ r"""
1226
+ labels (`torch.LongTensor` of shape `(batch_size, height, width)`, *optional*):
1227
+ Ground truth semantic segmentation maps for computing the loss. Indices should be in `[0, ...,
1228
+ config.num_labels - 1]`. If `config.num_labels > 1`, a classification loss is computed (Cross-Entropy).
1229
+
1230
+ Returns:
1231
+
1232
+ Examples:
1233
+
1234
+ ```python
1235
+ >>> from transformers import AutoImageProcessor, BeitForSemanticSegmentation
1236
+ >>> from PIL import Image
1237
+ >>> import requests
1238
+
1239
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
1240
+ >>> image = Image.open(requests.get(url, stream=True).raw)
1241
+
1242
+ >>> image_processor = AutoImageProcessor.from_pretrained("microsoft/beit-base-finetuned-ade-640-640")
1243
+ >>> model = BeitForSemanticSegmentation.from_pretrained("microsoft/beit-base-finetuned-ade-640-640")
1244
+
1245
+ >>> inputs = image_processor(images=image, return_tensors="pt")
1246
+ >>> outputs = model(**inputs)
1247
+ >>> # logits are of shape (batch_size, num_labels, height, width)
1248
+ >>> logits = outputs.logits
1249
+ ```"""
1250
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1251
+ output_hidden_states = (
1252
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1253
+ )
1254
+
1255
+ outputs = self.beit(
1256
+ pixel_values,
1257
+ head_mask=head_mask,
1258
+ output_attentions=output_attentions,
1259
+ output_hidden_states=True, # we need the intermediate hidden states
1260
+ return_dict=return_dict,
1261
+ )
1262
+
1263
+ encoder_hidden_states = outputs.hidden_states if return_dict else outputs[1]
1264
+
1265
+ # only keep certain features, and reshape
1266
+ # note that we do +1 as the encoder_hidden_states also includes the initial embeddings
1267
+ features = [feature for idx, feature in enumerate(encoder_hidden_states) if idx + 1 in self.config.out_indices]
1268
+ batch_size = pixel_values.shape[0]
1269
+ patch_resolution = self.config.image_size // self.config.patch_size
1270
+ features = [
1271
+ x[:, 1:, :].permute(0, 2, 1).reshape(batch_size, -1, patch_resolution, patch_resolution) for x in features
1272
+ ]
1273
+
1274
+ # apply FPNs
1275
+ ops = [self.fpn1, self.fpn2, self.fpn3, self.fpn4]
1276
+ for i in range(len(features)):
1277
+ features[i] = ops[i](features[i])
1278
+
1279
+ logits = self.decode_head(features)
1280
+
1281
+ auxiliary_logits = None
1282
+ if self.auxiliary_head is not None:
1283
+ auxiliary_logits = self.auxiliary_head(features)
1284
+
1285
+ loss = None
1286
+ if labels is not None:
1287
+ if self.config.num_labels == 1:
1288
+ raise ValueError("The number of labels should be greater than one")
1289
+ else:
1290
+ loss = self.compute_loss(logits, auxiliary_logits, labels)
1291
+
1292
+ if not return_dict:
1293
+ if output_hidden_states:
1294
+ output = (logits,) + outputs[1:]
1295
+ else:
1296
+ output = (logits,) + outputs[2:]
1297
+ return ((loss,) + output) if loss is not None else output
1298
+
1299
+ return SemanticSegmenterOutput(
1300
+ loss=loss,
1301
+ logits=logits,
1302
+ hidden_states=outputs.hidden_states if output_hidden_states else None,
1303
+ attentions=outputs.attentions,
1304
+ )
1305
+
1306
+
1307
+ @add_start_docstrings(
1308
+ """
1309
+ BEiT backbone, to be used with frameworks like DETR and MaskFormer.
1310
+ """,
1311
+ BEIT_START_DOCSTRING,
1312
+ )
1313
+ class BeitBackbone(BeitPreTrainedModel, BackboneMixin):
1314
+ def __init__(self, config):
1315
+ super().__init__(config)
1316
+ super()._init_backbone(config)
1317
+
1318
+ self.num_features = [config.hidden_size for _ in range(config.num_hidden_layers + 1)]
1319
+ self.embeddings = BeitEmbeddings(config)
1320
+ self.encoder = BeitEncoder(config, window_size=self.embeddings.patch_embeddings.patch_shape)
1321
+
1322
+ if config.add_fpn:
1323
+ if len(self.config.out_indices) != 4:
1324
+ raise ValueError(
1325
+ "BeitBackbone requires config.out_indices to be a list of 4 integers, "
1326
+ "specifying which features to use from the backbone. One can use [3, 5, 7, 11] in case of "
1327
+ "a base-sized architecture."
1328
+ )
1329
+ hidden_size = config.hidden_size
1330
+ self.fpn1 = nn.Sequential(
1331
+ nn.ConvTranspose2d(hidden_size, hidden_size, kernel_size=2, stride=2),
1332
+ nn.BatchNorm2d(hidden_size, eps=config.batch_norm_eps),
1333
+ nn.GELU(),
1334
+ nn.ConvTranspose2d(hidden_size, hidden_size, kernel_size=2, stride=2),
1335
+ )
1336
+
1337
+ self.fpn2 = nn.Sequential(nn.ConvTranspose2d(hidden_size, hidden_size, kernel_size=2, stride=2))
1338
+ self.fpn3 = nn.Identity()
1339
+ self.fpn4 = nn.MaxPool2d(kernel_size=2, stride=2)
1340
+
1341
+ # initialize weights and apply final processing
1342
+ self.post_init()
1343
+
1344
+ def get_input_embeddings(self):
1345
+ return self.embeddings.patch_embeddings
1346
+
1347
+ @add_start_docstrings_to_model_forward(BEIT_INPUTS_DOCSTRING)
1348
+ @replace_return_docstrings(output_type=BackboneOutput, config_class=_CONFIG_FOR_DOC)
1349
+ def forward(
1350
+ self,
1351
+ pixel_values: Tensor,
1352
+ output_hidden_states: Optional[bool] = None,
1353
+ output_attentions: Optional[bool] = None,
1354
+ return_dict: Optional[bool] = None,
1355
+ ) -> BackboneOutput:
1356
+ """
1357
+ Returns:
1358
+
1359
+ Examples:
1360
+
1361
+ ```python
1362
+ >>> from transformers import AutoImageProcessor, AutoBackbone
1363
+ >>> import torch
1364
+ >>> from PIL import Image
1365
+ >>> import requests
1366
+
1367
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
1368
+ >>> image = Image.open(requests.get(url, stream=True).raw)
1369
+
1370
+ >>> processor = AutoImageProcessor.from_pretrained("microsoft/beit-base-patch16-224")
1371
+ >>> model = AutoBackbone.from_pretrained(
1372
+ ... "microsoft/beit-base-patch16-224", out_features=["stage1", "stage2", "stage3", "stage4"]
1373
+ ... )
1374
+
1375
+ >>> inputs = processor(image, return_tensors="pt")
1376
+
1377
+ >>> outputs = model(**inputs)
1378
+ >>> feature_maps = outputs.feature_maps
1379
+ >>> list(feature_maps[-1].shape)
1380
+ [1, 768, 14, 14]
1381
+ ```"""
1382
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1383
+ output_hidden_states = (
1384
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1385
+ )
1386
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1387
+
1388
+ batch_size = pixel_values.shape[0]
1389
+ embedding_output, (patch_height, patch_width) = self.embeddings(pixel_values)
1390
+
1391
+ outputs = self.encoder(
1392
+ embedding_output, output_hidden_states=True, output_attentions=output_attentions, return_dict=return_dict
1393
+ )
1394
+
1395
+ hidden_states = outputs.hidden_states if return_dict else outputs[1]
1396
+
1397
+ feature_maps = ()
1398
+ for stage, hidden_state in zip(self.stage_names, hidden_states):
1399
+ if stage in self.out_features:
1400
+ if self.config.reshape_hidden_states:
1401
+ hidden_state = hidden_state[:, 1:, :]
1402
+ hidden_state = hidden_state.permute(0, 2, 1)
1403
+ hidden_state = hidden_state.reshape(batch_size, -1, patch_height, patch_width)
1404
+
1405
+ feature_maps += (hidden_state,)
1406
+
1407
+ if self.config.add_fpn:
1408
+ feature_maps = [
1409
+ self.fpn1(feature_maps[0]),
1410
+ self.fpn2(feature_maps[1]),
1411
+ self.fpn3(feature_maps[2]),
1412
+ self.fpn4(feature_maps[3]),
1413
+ ]
1414
+ feature_maps = tuple(feature_maps)
1415
+
1416
+ if not return_dict:
1417
+ if output_hidden_states:
1418
+ output = (feature_maps,) + outputs[1:]
1419
+ else:
1420
+ output = (feature_maps,) + outputs[2:]
1421
+ return output
1422
+
1423
+ return BackboneOutput(
1424
+ feature_maps=feature_maps,
1425
+ hidden_states=outputs.hidden_states if output_hidden_states else None,
1426
+ attentions=outputs.attentions,
1427
+ )
pllava/lib/python3.10/site-packages/transformers/models/beit/modeling_flax_beit.py ADDED
@@ -0,0 +1,948 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2021 Microsoft Research 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
+
16
+
17
+ from typing import Callable, List, Optional, Tuple
18
+
19
+ import flax
20
+ import flax.linen as nn
21
+ import jax
22
+ import jax.numpy as jnp
23
+ import numpy as np
24
+ from flax.core.frozen_dict import FrozenDict, freeze, unfreeze
25
+ from flax.linen.attention import dot_product_attention_weights
26
+ from flax.traverse_util import flatten_dict, unflatten_dict
27
+
28
+ from ...modeling_flax_outputs import (
29
+ FlaxBaseModelOutput,
30
+ FlaxBaseModelOutputWithPooling,
31
+ FlaxMaskedLMOutput,
32
+ FlaxSequenceClassifierOutput,
33
+ )
34
+ from ...modeling_flax_utils import (
35
+ ACT2FN,
36
+ FlaxPreTrainedModel,
37
+ append_replace_return_docstrings,
38
+ overwrite_call_docstring,
39
+ )
40
+ from ...utils import add_start_docstrings, add_start_docstrings_to_model_forward
41
+ from .configuration_beit import BeitConfig
42
+
43
+
44
+ @flax.struct.dataclass
45
+ class FlaxBeitModelOutputWithPooling(FlaxBaseModelOutputWithPooling):
46
+ """
47
+ Class for outputs of [`FlaxBeitModel`].
48
+
49
+ Args:
50
+ last_hidden_state (`jnp.ndarray` of shape `(batch_size, sequence_length, hidden_size)`):
51
+ Sequence of hidden-states at the output of the last layer of the model.
52
+ pooler_output (`jnp.ndarray` of shape `(batch_size, hidden_size)`):
53
+ Average of the last layer hidden states of the patch tokens (excluding the *[CLS]* token) if
54
+ *config.use_mean_pooling* is set to True. If set to False, then the final hidden state of the *[CLS]* token
55
+ will be returned.
56
+ hidden_states (`tuple(jnp.ndarray)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
57
+ Tuple of `jnp.ndarray` (one for the output of the embeddings + one for the output of each layer) of shape
58
+ `(batch_size, sequence_length, hidden_size)`. Hidden-states of the model at the output of each layer plus
59
+ the initial embedding outputs.
60
+ attentions (`tuple(jnp.ndarray)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
61
+ Tuple of `jnp.ndarray` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
62
+ sequence_length)`. Attentions weights after the attention softmax, used to compute the weighted average in
63
+ the self-attention heads.
64
+ """
65
+
66
+
67
+ BEIT_START_DOCSTRING = r"""
68
+
69
+ This model inherits from [`FlaxPreTrainedModel`]. Check the superclass documentation for the generic methods the
70
+ library implements for all its model (such as downloading, saving and converting weights from PyTorch models)
71
+
72
+ This model is also a
73
+ [flax.linen.Module](https://flax.readthedocs.io/en/latest/api_reference/flax.linen/module.html) subclass. Use it as
74
+ a regular Flax linen Module and refer to the Flax documentation for all matter related to general usage and
75
+ behavior.
76
+
77
+ Finally, this model supports inherent JAX features such as:
78
+
79
+ - [Just-In-Time (JIT) compilation](https://jax.readthedocs.io/en/latest/jax.html#just-in-time-compilation-jit)
80
+ - [Automatic Differentiation](https://jax.readthedocs.io/en/latest/jax.html#automatic-differentiation)
81
+ - [Vectorization](https://jax.readthedocs.io/en/latest/jax.html#vectorization-vmap)
82
+ - [Parallelization](https://jax.readthedocs.io/en/latest/jax.html#parallelization-pmap)
83
+
84
+ Parameters:
85
+ config ([`BeitConfig`]): Model configuration class with all the parameters of the model.
86
+ Initializing with a config file does not load the weights associated with the model, only the
87
+ configuration. Check out the [`~FlaxPreTrainedModel.from_pretrained`] method to load the model weights.
88
+ dtype (`jax.numpy.dtype`, *optional*, defaults to `jax.numpy.float32`):
89
+ The data type of the computation. Can be one of `jax.numpy.float32`, `jax.numpy.float16` (on GPUs) and
90
+ `jax.numpy.bfloat16` (on TPUs).
91
+
92
+ This can be used to enable mixed-precision training or half-precision inference on GPUs or TPUs. If
93
+ specified all the computation will be performed with the given `dtype`.
94
+
95
+ **Note that this only specifies the dtype of the computation and does not influence the dtype of model
96
+ parameters.**
97
+
98
+ If you wish to change the dtype of the model parameters, see [`~FlaxPreTrainedModel.to_fp16`] and
99
+ [`~FlaxPreTrainedModel.to_bf16`].
100
+ """
101
+
102
+ BEIT_INPUTS_DOCSTRING = r"""
103
+ Args:
104
+ pixel_values (`numpy.ndarray` of shape `(batch_size, num_channels, height, width)`):
105
+ Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See
106
+ [`AutoImageProcessor.__call__`] for details.
107
+
108
+ output_attentions (`bool`, *optional*):
109
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
110
+ tensors for more detail.
111
+ output_hidden_states (`bool`, *optional*):
112
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
113
+ more detail.
114
+ return_dict (`bool`, *optional*):
115
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
116
+ """
117
+
118
+
119
+ def relative_position_index_init(window_size: Tuple[int, int]) -> jnp.ndarray:
120
+ """
121
+ get pair-wise relative position index for each token inside the window
122
+ """
123
+ num_relative_distance = (2 * window_size[0] - 1) * (2 * window_size[1] - 1) + 3
124
+
125
+ coords_h = np.arange(window_size[0])
126
+ coords_w = np.arange(window_size[1])
127
+ coords = np.stack(np.meshgrid(coords_h, coords_w, indexing="ij")) # 2, Wh, Ww
128
+ coords_flatten = np.reshape(coords, (2, -1))
129
+ relative_coords = coords_flatten[:, :, None] - coords_flatten[:, None, :] # 2, Wh*Ww, Wh*Ww
130
+ relative_coords = np.transpose(relative_coords, (1, 2, 0)) # Wh*Ww, Wh*Ww, 2
131
+ relative_coords[:, :, 0] += window_size[0] - 1 # shift to start from 0
132
+ relative_coords[:, :, 1] += window_size[1] - 1
133
+ relative_coords[:, :, 0] *= 2 * window_size[1] - 1
134
+
135
+ relative_position_index = np.zeros(shape=(window_size[0] * window_size[1] + 1,) * 2, dtype=relative_coords.dtype)
136
+ relative_position_index[1:, 1:] = relative_coords.sum(-1) # Wh*Ww, Wh*Ww
137
+ relative_position_index[0, 0:] = num_relative_distance - 3
138
+ relative_position_index[0:, 0] = num_relative_distance - 2
139
+ relative_position_index[0, 0] = num_relative_distance - 1
140
+ return jnp.array(relative_position_index)
141
+
142
+
143
+ def ones_with_scale(key, shape, scale, dtype=jnp.float32):
144
+ return jnp.ones(shape, dtype) * scale
145
+
146
+
147
+ class FlaxBeitDropPath(nn.Module):
148
+ """Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks)."""
149
+
150
+ rate: float
151
+
152
+ @nn.module.compact
153
+ def __call__(self, inputs, deterministic: Optional[bool] = True):
154
+ if self.rate == 0.0:
155
+ return inputs
156
+ keep_prob = 1.0 - self.rate
157
+ if deterministic:
158
+ return inputs
159
+ else:
160
+ shape = (inputs.shape[0],) + (1,) * (inputs.ndim - 1) # work with diff dim tensors, not just 2D ConvNets
161
+ rng = self.make_rng("droppath")
162
+ random_tensor = keep_prob + jax.random.uniform(rng, shape=shape, dtype=inputs.dtype)
163
+ binary_tensor = jnp.floor(random_tensor)
164
+ output = inputs / keep_prob * binary_tensor
165
+ return output
166
+
167
+
168
+ class FlaxBeitPatchEmbeddings(nn.Module):
169
+ config: BeitConfig
170
+ dtype: jnp.dtype = jnp.float32 # the dtype of the computation
171
+
172
+ def setup(self):
173
+ self.num_channels = self.config.num_channels
174
+ image_size = self.config.image_size
175
+ patch_size = self.config.patch_size
176
+ num_patches = (image_size // patch_size) * (image_size // patch_size)
177
+ patch_shape = (image_size // patch_size, image_size // patch_size)
178
+ self.num_patches = num_patches
179
+ self.patch_shape = patch_shape
180
+ self.projection = nn.Conv(
181
+ self.config.hidden_size,
182
+ kernel_size=(patch_size, patch_size),
183
+ strides=(patch_size, patch_size),
184
+ padding="VALID",
185
+ dtype=self.dtype,
186
+ kernel_init=jax.nn.initializers.normal(self.config.initializer_range),
187
+ )
188
+
189
+ def __call__(self, pixel_values):
190
+ num_channels = pixel_values.shape[-1]
191
+ if num_channels != self.num_channels:
192
+ raise ValueError(
193
+ "Make sure that the channel dimension of the pixel values match with the one set in the configuration."
194
+ )
195
+ embeddings = self.projection(pixel_values)
196
+ batch_size, _, _, channels = embeddings.shape
197
+ return jnp.reshape(embeddings, (batch_size, -1, channels))
198
+
199
+
200
+ class FlaxBeitEmbeddings(nn.Module):
201
+ """Construct the CLS token, position and patch embeddings."""
202
+
203
+ config: BeitConfig
204
+ dtype: jnp.dtype = jnp.float32 # the dtype of the computation
205
+
206
+ def setup(self):
207
+ self.cls_token = self.param("cls_token", nn.initializers.zeros, (1, 1, self.config.hidden_size))
208
+ if self.config.use_mask_token:
209
+ self.mask_token = self.param("mask_token", nn.initializers.zeros, (1, 1, self.config.hidden_size))
210
+ self.patch_embeddings = FlaxBeitPatchEmbeddings(self.config, dtype=self.dtype)
211
+ num_patches = self.patch_embeddings.num_patches
212
+ if self.config.use_absolute_position_embeddings:
213
+ self.position_embeddings = self.param(
214
+ "position_embeddings", nn.initializers.zeros, (1, num_patches + 1, self.config.hidden_size)
215
+ )
216
+ self.dropout = nn.Dropout(rate=self.config.hidden_dropout_prob)
217
+
218
+ def __call__(self, pixel_values, bool_masked_pos=None, deterministic=True):
219
+ embeddings = self.patch_embeddings(pixel_values)
220
+ batch_size, seq_len, _ = embeddings.shape
221
+
222
+ cls_tokens = jnp.broadcast_to(self.cls_token, (batch_size, 1, self.config.hidden_size))
223
+ cls_tokens = cls_tokens.astype(embeddings.dtype)
224
+
225
+ if bool_masked_pos is not None:
226
+ mask_tokens = jnp.broadcast_to(self.mask_token, (batch_size, seq_len, self.config.hidden_size))
227
+ mask_tokens = mask_tokens.astype(embeddings.dtype)
228
+ # replace the masked visual tokens by mask_tokens
229
+ w = jnp.expand_dims(bool_masked_pos, axis=-1)
230
+ embeddings = embeddings * (1 - w) + mask_tokens * w
231
+
232
+ embeddings = jnp.concatenate((cls_tokens, embeddings), axis=1)
233
+
234
+ if self.config.use_absolute_position_embeddings:
235
+ embeddings = embeddings + self.position_embeddings.astype(embeddings.dtype)
236
+
237
+ embeddings = self.dropout(embeddings, deterministic=deterministic)
238
+ return embeddings
239
+
240
+
241
+ class FlaxBeitRelativePositionBias(nn.Module):
242
+ config: BeitConfig
243
+ window_size: Tuple[int, int]
244
+ dtype: jnp.dtype = jnp.float32 # the dtype of the computation
245
+
246
+ def setup(self):
247
+ num_relative_distance = (2 * self.window_size[0] - 1) * (2 * self.window_size[1] - 1) + 3
248
+ self.relative_position_bias_table = self.param(
249
+ "relative_position_bias_table",
250
+ nn.initializers.zeros,
251
+ (num_relative_distance, self.config.num_attention_heads),
252
+ ) # 2*Wh-1 * 2*Ww-1, nH
253
+ # cls to token & token 2 cls & cls to cls
254
+
255
+ self.relative_position_index = relative_position_index_init(self.window_size)
256
+
257
+ def __call__(self):
258
+ index = self.relative_position_index.reshape(-1)
259
+ shape = (self.window_size[0] * self.window_size[1] + 1, self.window_size[0] * self.window_size[1] + 1, -1)
260
+ relative_position_bias = self.relative_position_bias_table[index].reshape(shape) # Wh*Ww,Wh*Ww,nH
261
+ return jnp.transpose(relative_position_bias, (2, 0, 1))
262
+
263
+
264
+ class FlaxBeitSelfAttention(nn.Module):
265
+ config: BeitConfig
266
+ window_size: Tuple[int, int]
267
+ dtype: jnp.dtype = jnp.float32 # the dtype of the computation
268
+
269
+ def setup(self):
270
+ if self.config.hidden_size % self.config.num_attention_heads != 0 and not hasattr(
271
+ self.config, "embedding_size"
272
+ ):
273
+ raise ValueError(
274
+ f"The hidden size {self.config.hidden_size,} is not a multiple of the number of attention "
275
+ f"heads {self.config.num_attention_heads}."
276
+ )
277
+
278
+ self.query = nn.Dense(
279
+ self.config.hidden_size,
280
+ dtype=self.dtype,
281
+ kernel_init=jax.nn.initializers.normal(self.config.initializer_range),
282
+ )
283
+ self.key = nn.Dense(
284
+ self.config.hidden_size,
285
+ dtype=self.dtype,
286
+ kernel_init=jax.nn.initializers.normal(self.config.initializer_range),
287
+ use_bias=False,
288
+ )
289
+ self.value = nn.Dense(
290
+ self.config.hidden_size,
291
+ dtype=self.dtype,
292
+ kernel_init=jax.nn.initializers.normal(self.config.initializer_range),
293
+ )
294
+
295
+ self.relative_position_bias = (
296
+ FlaxBeitRelativePositionBias(self.config, window_size=self.window_size, dtype=self.dtype)
297
+ if self.window_size
298
+ else None
299
+ )
300
+
301
+ def __call__(
302
+ self, hidden_states, relative_position_bias=None, deterministic: bool = True, output_attentions: bool = False
303
+ ):
304
+ head_dim = self.config.hidden_size // self.config.num_attention_heads
305
+
306
+ query_states = self.query(hidden_states).reshape(
307
+ hidden_states.shape[:2] + (self.config.num_attention_heads, head_dim)
308
+ )
309
+ value_states = self.value(hidden_states).reshape(
310
+ hidden_states.shape[:2] + (self.config.num_attention_heads, head_dim)
311
+ )
312
+ key_states = self.key(hidden_states).reshape(
313
+ hidden_states.shape[:2] + (self.config.num_attention_heads, head_dim)
314
+ )
315
+
316
+ dropout_rng = None
317
+ if not deterministic and self.config.attention_probs_dropout_prob > 0.0:
318
+ dropout_rng = self.make_rng("dropout")
319
+
320
+ attention_bias = jnp.array(0.0, dtype=self.dtype)
321
+ # Add relative position bias if present.
322
+ if self.relative_position_bias is not None:
323
+ attention_bias = jnp.expand_dims(self.relative_position_bias(), 0)
324
+ attention_bias = attention_bias.astype(query_states.dtype)
325
+
326
+ # Add shared relative position bias if provided.
327
+ if relative_position_bias is not None:
328
+ attention_bias = attention_bias + relative_position_bias.astype(attention_bias.dtype)
329
+
330
+ attn_weights = dot_product_attention_weights(
331
+ query_states,
332
+ key_states,
333
+ bias=attention_bias,
334
+ dropout_rng=dropout_rng,
335
+ dropout_rate=self.config.attention_probs_dropout_prob,
336
+ broadcast_dropout=True,
337
+ deterministic=deterministic,
338
+ dtype=self.dtype,
339
+ precision=None,
340
+ )
341
+
342
+ attn_output = jnp.einsum("...hqk,...khd->...qhd", attn_weights, value_states)
343
+ attn_output = attn_output.reshape(attn_output.shape[:2] + (-1,))
344
+
345
+ outputs = (attn_output, attn_weights) if output_attentions else (attn_output,)
346
+ return outputs
347
+
348
+
349
+ class FlaxBeitSelfOutput(nn.Module):
350
+ config: BeitConfig
351
+ dtype: jnp.dtype = jnp.float32 # the dtype of the computation
352
+
353
+ def setup(self):
354
+ self.dense = nn.Dense(
355
+ self.config.hidden_size,
356
+ kernel_init=jax.nn.initializers.normal(self.config.initializer_range),
357
+ dtype=self.dtype,
358
+ )
359
+ self.dropout = nn.Dropout(rate=self.config.hidden_dropout_prob)
360
+
361
+ def __call__(self, hidden_states, deterministic: bool = True):
362
+ hidden_states = self.dense(hidden_states)
363
+ hidden_states = self.dropout(hidden_states, deterministic=deterministic)
364
+ return hidden_states
365
+
366
+
367
+ class FlaxBeitAttention(nn.Module):
368
+ config: BeitConfig
369
+ window_size: Tuple[int, int]
370
+ dtype: jnp.dtype = jnp.float32
371
+
372
+ def setup(self):
373
+ self.attention = FlaxBeitSelfAttention(self.config, self.window_size, dtype=self.dtype)
374
+ self.output = FlaxBeitSelfOutput(self.config, dtype=self.dtype)
375
+
376
+ def __call__(
377
+ self, hidden_states, relative_position_bias=None, deterministic=True, output_attentions: bool = False
378
+ ):
379
+ attn_outputs = self.attention(
380
+ hidden_states, relative_position_bias, deterministic=deterministic, output_attentions=output_attentions
381
+ )
382
+ attn_output = attn_outputs[0]
383
+ attn_output = self.output(attn_output, deterministic=deterministic)
384
+
385
+ outputs = (attn_output,)
386
+
387
+ if output_attentions:
388
+ outputs += (attn_outputs[1],)
389
+
390
+ return outputs
391
+
392
+
393
+ class FlaxBeitIntermediate(nn.Module):
394
+ config: BeitConfig
395
+ dtype: jnp.dtype = jnp.float32 # the dtype of the computation
396
+
397
+ def setup(self):
398
+ self.dense = nn.Dense(
399
+ self.config.intermediate_size,
400
+ kernel_init=jax.nn.initializers.normal(self.config.initializer_range),
401
+ dtype=self.dtype,
402
+ )
403
+ self.activation = ACT2FN[self.config.hidden_act]
404
+
405
+ def __call__(self, hidden_states):
406
+ hidden_states = self.dense(hidden_states)
407
+ hidden_states = self.activation(hidden_states)
408
+
409
+ return hidden_states
410
+
411
+
412
+ class FlaxBeitOutput(nn.Module):
413
+ config: BeitConfig
414
+ dtype: jnp.dtype = jnp.float32 # the dtype of the computation
415
+
416
+ def setup(self):
417
+ self.dense = nn.Dense(
418
+ self.config.hidden_size,
419
+ kernel_init=jax.nn.initializers.normal(self.config.initializer_range),
420
+ dtype=self.dtype,
421
+ )
422
+ self.dropout = nn.Dropout(rate=self.config.hidden_dropout_prob)
423
+
424
+ def __call__(self, hidden_states, deterministic: bool = True):
425
+ hidden_states = self.dense(hidden_states)
426
+ hidden_states = self.dropout(hidden_states, deterministic=deterministic)
427
+
428
+ return hidden_states
429
+
430
+
431
+ class FlaxBeitLayer(nn.Module):
432
+ config: BeitConfig
433
+ window_size: Tuple[int, int]
434
+ drop_path_rate: float
435
+ dtype: jnp.dtype = jnp.float32 # the dtype of the computation
436
+
437
+ def setup(self):
438
+ self.attention = FlaxBeitAttention(self.config, self.window_size, dtype=self.dtype)
439
+ self.intermediate = FlaxBeitIntermediate(self.config, dtype=self.dtype)
440
+ self.output = FlaxBeitOutput(self.config, dtype=self.dtype)
441
+ self.layernorm_before = nn.LayerNorm(epsilon=self.config.layer_norm_eps, dtype=self.dtype)
442
+ self.drop_path = FlaxBeitDropPath(rate=self.drop_path_rate)
443
+ self.layernorm_after = nn.LayerNorm(epsilon=self.config.layer_norm_eps, dtype=self.dtype)
444
+
445
+ self.init_values = self.config.layer_scale_init_value
446
+ if self.init_values > 0:
447
+ self.lambda_1 = self.param("lambda_1", ones_with_scale, (self.config.hidden_size), self.init_values)
448
+ self.lambda_2 = self.param("lambda_2", ones_with_scale, (self.config.hidden_size), self.init_values)
449
+ else:
450
+ self.lambda_1 = None
451
+ self.lambda_2 = None
452
+
453
+ def __call__(
454
+ self, hidden_states, relative_position_bias=None, deterministic: bool = True, output_attentions: bool = False
455
+ ):
456
+ self_attention_outputs = self.attention(
457
+ self.layernorm_before(hidden_states), # in BEiT, layernorm is applied before self-attention
458
+ relative_position_bias,
459
+ deterministic=deterministic,
460
+ output_attentions=output_attentions,
461
+ )
462
+ attention_output = self_attention_outputs[0]
463
+
464
+ # apply lambda_1 if present
465
+ if self.lambda_1 is not None:
466
+ attention_output = self.lambda_1.astype(attention_output.dtype) * attention_output
467
+
468
+ # first residual connection
469
+ hidden_states = self.drop_path(attention_output, deterministic=deterministic) + hidden_states
470
+
471
+ # in BEiT, layernorm is also applied after self-attention
472
+ layer_output = self.layernorm_after(hidden_states)
473
+
474
+ layer_output = self.intermediate(layer_output)
475
+ layer_output = self.output(layer_output, deterministic=deterministic)
476
+
477
+ # apply lambda_2 if present
478
+ if self.lambda_2 is not None:
479
+ layer_output = self.lambda_2.astype(layer_output.dtype) * layer_output
480
+
481
+ # second residual connection
482
+ layer_output = self.drop_path(layer_output, deterministic=deterministic) + hidden_states
483
+
484
+ outputs = (layer_output,)
485
+
486
+ if output_attentions:
487
+ outputs += (self_attention_outputs[1],)
488
+
489
+ return outputs
490
+
491
+
492
+ class FlaxBeitLayerCollection(nn.Module):
493
+ config: BeitConfig
494
+ window_size: Tuple[int, int]
495
+ drop_path_rates: List[float]
496
+ relative_position_bias: Callable[[], jnp.ndarray]
497
+ dtype: jnp.dtype = jnp.float32 # the dtype of the computation
498
+
499
+ def setup(self):
500
+ self.layers = [
501
+ FlaxBeitLayer(
502
+ self.config,
503
+ window_size=self.window_size if self.config.use_relative_position_bias else None,
504
+ drop_path_rate=self.drop_path_rates[i],
505
+ name=str(i),
506
+ dtype=self.dtype,
507
+ )
508
+ for i in range(self.config.num_hidden_layers)
509
+ ]
510
+
511
+ def __call__(
512
+ self,
513
+ hidden_states,
514
+ deterministic: bool = True,
515
+ output_attentions: bool = False,
516
+ output_hidden_states: bool = False,
517
+ return_dict: bool = True,
518
+ ):
519
+ all_attentions = () if output_attentions else None
520
+ all_hidden_states = () if output_hidden_states else None
521
+
522
+ for i, layer in enumerate(self.layers):
523
+ if output_hidden_states:
524
+ all_hidden_states += (hidden_states,)
525
+ relative_position_bias = self.relative_position_bias() if self.relative_position_bias is not None else None
526
+ layer_outputs = layer(
527
+ hidden_states, relative_position_bias, deterministic=deterministic, output_attentions=output_attentions
528
+ )
529
+
530
+ hidden_states = layer_outputs[0]
531
+
532
+ if output_attentions:
533
+ all_attentions += (layer_outputs[1],)
534
+
535
+ if output_hidden_states:
536
+ all_hidden_states += (hidden_states,)
537
+
538
+ outputs = (hidden_states,)
539
+ if not return_dict:
540
+ return tuple(v for v in outputs if v is not None)
541
+
542
+ return FlaxBaseModelOutput(
543
+ last_hidden_state=hidden_states, hidden_states=all_hidden_states, attentions=all_attentions
544
+ )
545
+
546
+
547
+ class FlaxBeitEncoder(nn.Module):
548
+ config: BeitConfig
549
+ window_size: Tuple[int, int]
550
+ dtype: jnp.dtype = jnp.float32 # the dtype of the computation
551
+
552
+ def setup(self):
553
+ if self.config.use_shared_relative_position_bias:
554
+ self.relative_position_bias = FlaxBeitRelativePositionBias(
555
+ config=self.config, window_size=self.window_size, dtype=self.dtype
556
+ )
557
+
558
+ # stochastic depth decay rule
559
+ drop_path_rates = list(np.linspace(0, self.config.drop_path_rate, self.config.num_hidden_layers))
560
+ self.layer = FlaxBeitLayerCollection(
561
+ self.config,
562
+ window_size=self.window_size,
563
+ drop_path_rates=drop_path_rates,
564
+ relative_position_bias=self.relative_position_bias
565
+ if self.config.use_shared_relative_position_bias
566
+ else None,
567
+ dtype=self.dtype,
568
+ )
569
+
570
+ def __call__(
571
+ self,
572
+ hidden_states,
573
+ deterministic: bool = True,
574
+ output_attentions: bool = False,
575
+ output_hidden_states: bool = False,
576
+ return_dict: bool = True,
577
+ ):
578
+ return self.layer(
579
+ hidden_states,
580
+ deterministic=deterministic,
581
+ output_attentions=output_attentions,
582
+ output_hidden_states=output_hidden_states,
583
+ return_dict=return_dict,
584
+ )
585
+
586
+
587
+ class FlaxBeitPreTrainedModel(FlaxPreTrainedModel):
588
+ """
589
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
590
+ models.
591
+ """
592
+
593
+ config_class = BeitConfig
594
+ base_model_prefix = "beit"
595
+ main_input_name = "pixel_values"
596
+ module_class: nn.Module = None
597
+
598
+ def __init__(
599
+ self,
600
+ config: BeitConfig,
601
+ input_shape=None,
602
+ seed: int = 0,
603
+ dtype: jnp.dtype = jnp.float32,
604
+ _do_init: bool = True,
605
+ **kwargs,
606
+ ):
607
+ module = self.module_class(config=config, dtype=dtype, **kwargs)
608
+ if input_shape is None:
609
+ input_shape = (1, config.image_size, config.image_size, config.num_channels)
610
+ super().__init__(config, module, input_shape=input_shape, seed=seed, dtype=dtype, _do_init=_do_init)
611
+
612
+ def init_weights(self, rng: jax.random.PRNGKey, input_shape: Tuple, params: FrozenDict = None) -> FrozenDict:
613
+ # init input tensors
614
+ pixel_values = jnp.zeros(input_shape, dtype=self.dtype)
615
+
616
+ params_rng, dropout_rng = jax.random.split(rng)
617
+ dropout_rng, droppath_rng = jax.random.split(dropout_rng)
618
+ rngs = {"params": params_rng, "dropout": dropout_rng, "droppath": droppath_rng}
619
+
620
+ random_params = self.module.init(rngs, pixel_values, return_dict=False)["params"]
621
+
622
+ if params is not None:
623
+ random_params = flatten_dict(unfreeze(random_params))
624
+ params = flatten_dict(unfreeze(params))
625
+ for missing_key in self._missing_keys:
626
+ params[missing_key] = random_params[missing_key]
627
+ self._missing_keys = set()
628
+ return freeze(unflatten_dict(params))
629
+ else:
630
+ return random_params
631
+
632
+ @add_start_docstrings_to_model_forward(BEIT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
633
+ def __call__(
634
+ self,
635
+ pixel_values,
636
+ bool_masked_pos=None,
637
+ params: dict = None,
638
+ dropout_rng: jax.random.PRNGKey = None,
639
+ train: bool = False,
640
+ output_attentions: Optional[bool] = None,
641
+ output_hidden_states: Optional[bool] = None,
642
+ return_dict: Optional[bool] = None,
643
+ ):
644
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
645
+ output_hidden_states = (
646
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
647
+ )
648
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
649
+
650
+ pixel_values = jnp.transpose(pixel_values, (0, 2, 3, 1))
651
+ # Handle any PRNG if needed
652
+ rngs = {}
653
+ if dropout_rng is not None:
654
+ dropout_rng, droppath_rng = jax.random.split(dropout_rng)
655
+ rngs["dropout"] = dropout_rng
656
+ rngs["droppath"] = droppath_rng
657
+
658
+ return self.module.apply(
659
+ {"params": params or self.params},
660
+ jnp.array(pixel_values, dtype=jnp.float32),
661
+ bool_masked_pos,
662
+ not train,
663
+ output_attentions,
664
+ output_hidden_states,
665
+ return_dict,
666
+ rngs=rngs,
667
+ )
668
+
669
+
670
+ class FlaxBeitPooler(nn.Module):
671
+ config: BeitConfig
672
+ dtype: jnp.dtype = jnp.float32 # the dtype of the computation
673
+
674
+ def setup(self):
675
+ if self.config.use_mean_pooling:
676
+ self.layernorm = nn.LayerNorm(epsilon=self.config.layer_norm_eps, dtype=self.dtype)
677
+
678
+ def __call__(self, hidden_states):
679
+ if self.config.use_mean_pooling:
680
+ # Mean pool the final hidden states of the patch tokens
681
+ patch_tokens = hidden_states[:, 1:, :]
682
+ pooled_output = self.layernorm(jnp.mean(patch_tokens, axis=1))
683
+ else:
684
+ # Pool by simply taking the final hidden state of the [CLS] token
685
+ pooled_output = hidden_states[:, 0]
686
+
687
+ return pooled_output
688
+
689
+
690
+ class FlaxBeitModule(nn.Module):
691
+ config: BeitConfig
692
+ dtype: jnp.dtype = jnp.float32 # the dtype of the computation
693
+ add_pooling_layer: bool = True
694
+
695
+ def setup(self):
696
+ self.embeddings = FlaxBeitEmbeddings(self.config, dtype=self.dtype)
697
+ self.encoder = FlaxBeitEncoder(
698
+ self.config, window_size=self.embeddings.patch_embeddings.patch_shape, dtype=self.dtype
699
+ )
700
+ if not self.config.use_mean_pooling:
701
+ self.layernorm = nn.LayerNorm(epsilon=self.config.layer_norm_eps, dtype=self.dtype)
702
+ self.pooler = FlaxBeitPooler(self.config, dtype=self.dtype) if self.add_pooling_layer else None
703
+
704
+ def __call__(
705
+ self,
706
+ pixel_values,
707
+ bool_masked_pos=None,
708
+ deterministic: bool = True,
709
+ output_attentions: bool = False,
710
+ output_hidden_states: bool = False,
711
+ return_dict: bool = True,
712
+ ):
713
+ hidden_states = self.embeddings(pixel_values, bool_masked_pos, deterministic=deterministic)
714
+
715
+ outputs = self.encoder(
716
+ hidden_states,
717
+ deterministic=deterministic,
718
+ output_attentions=output_attentions,
719
+ output_hidden_states=output_hidden_states,
720
+ return_dict=return_dict,
721
+ )
722
+ hidden_states = outputs[0]
723
+ if not self.config.use_mean_pooling:
724
+ hidden_states = self.layernorm(hidden_states)
725
+ pooled = self.pooler(hidden_states) if self.add_pooling_layer else None
726
+
727
+ if not return_dict:
728
+ # if pooled is None, don't return it
729
+ if pooled is None:
730
+ return (hidden_states,) + outputs[1:]
731
+ return (hidden_states, pooled) + outputs[1:]
732
+
733
+ return FlaxBeitModelOutputWithPooling(
734
+ last_hidden_state=hidden_states,
735
+ pooler_output=pooled,
736
+ hidden_states=outputs.hidden_states,
737
+ attentions=outputs.attentions,
738
+ )
739
+
740
+
741
+ @add_start_docstrings(
742
+ "The bare Beit Model transformer outputting raw hidden-states without any specific head on top.",
743
+ BEIT_START_DOCSTRING,
744
+ )
745
+ class FlaxBeitModel(FlaxBeitPreTrainedModel):
746
+ module_class = FlaxBeitModule
747
+
748
+
749
+ FLAX_BEIT_MODEL_DOCSTRING = """
750
+ Returns:
751
+
752
+ Examples:
753
+
754
+ ```python
755
+ >>> from transformers import AutoImageProcessor, FlaxBeitModel
756
+ >>> from PIL import Image
757
+ >>> import requests
758
+
759
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
760
+ >>> image = Image.open(requests.get(url, stream=True).raw)
761
+
762
+ >>> image_processor = AutoImageProcessor.from_pretrained("microsoft/beit-base-patch16-224-pt22k-ft22k")
763
+ >>> model = FlaxBeitModel.from_pretrained("microsoft/beit-base-patch16-224-pt22k-ft22k")
764
+
765
+ >>> inputs = image_processor(images=image, return_tensors="np")
766
+ >>> outputs = model(**inputs)
767
+ >>> last_hidden_states = outputs.last_hidden_state
768
+ ```
769
+ """
770
+
771
+ overwrite_call_docstring(FlaxBeitModel, FLAX_BEIT_MODEL_DOCSTRING)
772
+ append_replace_return_docstrings(FlaxBeitModel, output_type=FlaxBeitModelOutputWithPooling, config_class=BeitConfig)
773
+
774
+
775
+ class FlaxBeitForMaskedImageModelingModule(nn.Module):
776
+ config: BeitConfig
777
+ dtype: jnp.dtype = jnp.float32 # the dtype of the computation
778
+
779
+ def setup(self):
780
+ self.beit = FlaxBeitModule(self.config, add_pooling_layer=False, dtype=self.dtype)
781
+
782
+ # Classifier head
783
+ self.layernorm = nn.LayerNorm(epsilon=self.config.layer_norm_eps, dtype=self.dtype)
784
+ self.lm_head = nn.Dense(
785
+ self.config.vocab_size,
786
+ kernel_init=jax.nn.initializers.normal(self.config.initializer_range),
787
+ dtype=self.dtype,
788
+ )
789
+
790
+ def __call__(
791
+ self,
792
+ pixel_values=None,
793
+ bool_masked_pos=None,
794
+ deterministic: bool = True,
795
+ output_attentions=None,
796
+ output_hidden_states=None,
797
+ return_dict=None,
798
+ ):
799
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
800
+
801
+ outputs = self.beit(
802
+ pixel_values,
803
+ bool_masked_pos,
804
+ deterministic=deterministic,
805
+ output_attentions=output_attentions,
806
+ output_hidden_states=output_hidden_states,
807
+ return_dict=return_dict,
808
+ )
809
+
810
+ sequence_output = outputs[0]
811
+ sequence_output = self.layernorm(sequence_output)
812
+ prediction_scores = self.lm_head(sequence_output[:, 1:])
813
+
814
+ if not return_dict:
815
+ output = (prediction_scores,) + outputs[2:]
816
+ return output
817
+
818
+ return FlaxMaskedLMOutput(
819
+ logits=prediction_scores,
820
+ hidden_states=outputs.hidden_states,
821
+ attentions=outputs.attentions,
822
+ )
823
+
824
+
825
+ @add_start_docstrings(
826
+ "Beit Model transformer with a 'language' modeling head on top (to predict visual tokens).",
827
+ BEIT_START_DOCSTRING,
828
+ )
829
+ class FlaxBeitForMaskedImageModeling(FlaxBeitPreTrainedModel):
830
+ module_class = FlaxBeitForMaskedImageModelingModule
831
+
832
+
833
+ FLAX_BEIT_MLM_DOCSTRING = """
834
+ bool_masked_pos (`numpy.ndarray` of shape `(batch_size, num_patches)`):
835
+ Boolean masked positions. Indicates which patches are masked (1) and which aren't (0).
836
+
837
+ Returns:
838
+
839
+ Examples:
840
+
841
+ ```python
842
+ >>> from transformers import AutoImageProcessor, BeitForMaskedImageModeling
843
+ >>> from PIL import Image
844
+ >>> import requests
845
+
846
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
847
+ >>> image = Image.open(requests.get(url, stream=True).raw)
848
+
849
+ >>> image_processor = AutoImageProcessor.from_pretrained("microsoft/beit-base-patch16-224-pt22k")
850
+ >>> model = BeitForMaskedImageModeling.from_pretrained("microsoft/beit-base-patch16-224-pt22k")
851
+
852
+ >>> inputs = image_processor(images=image, return_tensors="np")
853
+ >>> outputs = model(**inputs)
854
+ >>> logits = outputs.logits
855
+ ```
856
+ """
857
+
858
+ overwrite_call_docstring(FlaxBeitForMaskedImageModeling, FLAX_BEIT_MLM_DOCSTRING)
859
+ append_replace_return_docstrings(
860
+ FlaxBeitForMaskedImageModeling, output_type=FlaxMaskedLMOutput, config_class=BeitConfig
861
+ )
862
+
863
+
864
+ class FlaxBeitForImageClassificationModule(nn.Module):
865
+ config: BeitConfig
866
+ dtype: jnp.dtype = jnp.float32
867
+
868
+ def setup(self):
869
+ self.beit = FlaxBeitModule(config=self.config, dtype=self.dtype, add_pooling_layer=True)
870
+ self.classifier = nn.Dense(
871
+ self.config.num_labels,
872
+ kernel_init=jax.nn.initializers.normal(self.config.initializer_range),
873
+ dtype=self.dtype,
874
+ )
875
+
876
+ def __call__(
877
+ self,
878
+ pixel_values=None,
879
+ bool_masked_pos=None,
880
+ deterministic: bool = True,
881
+ output_attentions=None,
882
+ output_hidden_states=None,
883
+ return_dict=None,
884
+ ):
885
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
886
+
887
+ outputs = self.beit(
888
+ pixel_values,
889
+ deterministic=deterministic,
890
+ output_attentions=output_attentions,
891
+ output_hidden_states=output_hidden_states,
892
+ return_dict=return_dict,
893
+ )
894
+
895
+ pooled_output = outputs[1]
896
+ logits = self.classifier(pooled_output)
897
+
898
+ if not return_dict:
899
+ output = (logits,) + outputs[2:]
900
+ return output
901
+
902
+ return FlaxSequenceClassifierOutput(
903
+ logits=logits,
904
+ hidden_states=outputs.hidden_states,
905
+ attentions=outputs.attentions,
906
+ )
907
+
908
+
909
+ @add_start_docstrings(
910
+ """
911
+ Beit Model transformer with an image classification head on top (a linear layer on top of the average of the final
912
+ hidden states of the patch tokens) e.g. for ImageNet.
913
+ """,
914
+ BEIT_START_DOCSTRING,
915
+ )
916
+ class FlaxBeitForImageClassification(FlaxBeitPreTrainedModel):
917
+ module_class = FlaxBeitForImageClassificationModule
918
+
919
+
920
+ FLAX_BEIT_CLASSIF_DOCSTRING = """
921
+ Returns:
922
+
923
+ Example:
924
+
925
+ ```python
926
+ >>> from transformers import AutoImageProcessor, FlaxBeitForImageClassification
927
+ >>> from PIL import Image
928
+ >>> import requests
929
+
930
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
931
+ >>> image = Image.open(requests.get(url, stream=True).raw)
932
+
933
+ >>> image_processor = AutoImageProcessor.from_pretrained("microsoft/beit-base-patch16-224")
934
+ >>> model = FlaxBeitForImageClassification.from_pretrained("microsoft/beit-base-patch16-224")
935
+
936
+ >>> inputs = image_processor(images=image, return_tensors="np")
937
+ >>> outputs = model(**inputs)
938
+ >>> logits = outputs.logits
939
+ >>> # model predicts one of the 1000 ImageNet classes
940
+ >>> predicted_class_idx = logits.argmax(-1).item()
941
+ >>> print("Predicted class:", model.config.id2label[predicted_class_idx])
942
+ ```
943
+ """
944
+
945
+ overwrite_call_docstring(FlaxBeitForImageClassification, FLAX_BEIT_CLASSIF_DOCSTRING)
946
+ append_replace_return_docstrings(
947
+ FlaxBeitForImageClassification, output_type=FlaxSequenceClassifierOutput, config_class=BeitConfig
948
+ )
pllava/lib/python3.10/site-packages/transformers/models/convbert/__init__.py ADDED
@@ -0,0 +1,130 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ from typing import TYPE_CHECKING
15
+
16
+ from ...utils import (
17
+ OptionalDependencyNotAvailable,
18
+ _LazyModule,
19
+ is_tf_available,
20
+ is_tokenizers_available,
21
+ is_torch_available,
22
+ )
23
+
24
+
25
+ _import_structure = {
26
+ "configuration_convbert": ["CONVBERT_PRETRAINED_CONFIG_ARCHIVE_MAP", "ConvBertConfig", "ConvBertOnnxConfig"],
27
+ "tokenization_convbert": ["ConvBertTokenizer"],
28
+ }
29
+
30
+ try:
31
+ if not is_tokenizers_available():
32
+ raise OptionalDependencyNotAvailable()
33
+ except OptionalDependencyNotAvailable:
34
+ pass
35
+ else:
36
+ _import_structure["tokenization_convbert_fast"] = ["ConvBertTokenizerFast"]
37
+
38
+ try:
39
+ if not is_torch_available():
40
+ raise OptionalDependencyNotAvailable()
41
+ except OptionalDependencyNotAvailable:
42
+ pass
43
+ else:
44
+ _import_structure["modeling_convbert"] = [
45
+ "CONVBERT_PRETRAINED_MODEL_ARCHIVE_LIST",
46
+ "ConvBertForMaskedLM",
47
+ "ConvBertForMultipleChoice",
48
+ "ConvBertForQuestionAnswering",
49
+ "ConvBertForSequenceClassification",
50
+ "ConvBertForTokenClassification",
51
+ "ConvBertLayer",
52
+ "ConvBertModel",
53
+ "ConvBertPreTrainedModel",
54
+ "load_tf_weights_in_convbert",
55
+ ]
56
+
57
+
58
+ try:
59
+ if not is_tf_available():
60
+ raise OptionalDependencyNotAvailable()
61
+ except OptionalDependencyNotAvailable:
62
+ pass
63
+ else:
64
+ _import_structure["modeling_tf_convbert"] = [
65
+ "TF_CONVBERT_PRETRAINED_MODEL_ARCHIVE_LIST",
66
+ "TFConvBertForMaskedLM",
67
+ "TFConvBertForMultipleChoice",
68
+ "TFConvBertForQuestionAnswering",
69
+ "TFConvBertForSequenceClassification",
70
+ "TFConvBertForTokenClassification",
71
+ "TFConvBertLayer",
72
+ "TFConvBertModel",
73
+ "TFConvBertPreTrainedModel",
74
+ ]
75
+
76
+
77
+ if TYPE_CHECKING:
78
+ from .configuration_convbert import CONVBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ConvBertConfig, ConvBertOnnxConfig
79
+ from .tokenization_convbert import ConvBertTokenizer
80
+
81
+ try:
82
+ if not is_tokenizers_available():
83
+ raise OptionalDependencyNotAvailable()
84
+ except OptionalDependencyNotAvailable:
85
+ pass
86
+ else:
87
+ from .tokenization_convbert_fast import ConvBertTokenizerFast
88
+
89
+ try:
90
+ if not is_torch_available():
91
+ raise OptionalDependencyNotAvailable()
92
+ except OptionalDependencyNotAvailable:
93
+ pass
94
+ else:
95
+ from .modeling_convbert import (
96
+ CONVBERT_PRETRAINED_MODEL_ARCHIVE_LIST,
97
+ ConvBertForMaskedLM,
98
+ ConvBertForMultipleChoice,
99
+ ConvBertForQuestionAnswering,
100
+ ConvBertForSequenceClassification,
101
+ ConvBertForTokenClassification,
102
+ ConvBertLayer,
103
+ ConvBertModel,
104
+ ConvBertPreTrainedModel,
105
+ load_tf_weights_in_convbert,
106
+ )
107
+
108
+ try:
109
+ if not is_tf_available():
110
+ raise OptionalDependencyNotAvailable()
111
+ except OptionalDependencyNotAvailable:
112
+ pass
113
+ else:
114
+ from .modeling_tf_convbert import (
115
+ TF_CONVBERT_PRETRAINED_MODEL_ARCHIVE_LIST,
116
+ TFConvBertForMaskedLM,
117
+ TFConvBertForMultipleChoice,
118
+ TFConvBertForQuestionAnswering,
119
+ TFConvBertForSequenceClassification,
120
+ TFConvBertForTokenClassification,
121
+ TFConvBertLayer,
122
+ TFConvBertModel,
123
+ TFConvBertPreTrainedModel,
124
+ )
125
+
126
+
127
+ else:
128
+ import sys
129
+
130
+ sys.modules[__name__] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
pllava/lib/python3.10/site-packages/transformers/models/convbert/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (1.98 kB). View file
 
pllava/lib/python3.10/site-packages/transformers/models/convbert/__pycache__/configuration_convbert.cpython-310.pyc ADDED
Binary file (6.35 kB). View file
 
pllava/lib/python3.10/site-packages/transformers/models/convbert/__pycache__/convert_convbert_original_tf1_checkpoint_to_pytorch_and_tf2.cpython-310.pyc ADDED
Binary file (1.41 kB). View file
 
pllava/lib/python3.10/site-packages/transformers/models/convbert/__pycache__/modeling_convbert.cpython-310.pyc ADDED
Binary file (38.6 kB). View file
 
pllava/lib/python3.10/site-packages/transformers/models/convbert/__pycache__/modeling_tf_convbert.cpython-310.pyc ADDED
Binary file (43.3 kB). View file
 
pllava/lib/python3.10/site-packages/transformers/models/convbert/__pycache__/tokenization_convbert.cpython-310.pyc ADDED
Binary file (17.6 kB). View file
 
pllava/lib/python3.10/site-packages/transformers/models/convbert/__pycache__/tokenization_convbert_fast.cpython-310.pyc ADDED
Binary file (7.38 kB). View file
 
pllava/lib/python3.10/site-packages/transformers/models/convbert/configuration_convbert.py ADDED
@@ -0,0 +1,166 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright The HuggingFace 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
+ """ ConvBERT model configuration"""
16
+
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
+ CONVBERT_PRETRAINED_CONFIG_ARCHIVE_MAP = {
28
+ "YituTech/conv-bert-base": "https://huggingface.co/YituTech/conv-bert-base/resolve/main/config.json",
29
+ "YituTech/conv-bert-medium-small": (
30
+ "https://huggingface.co/YituTech/conv-bert-medium-small/resolve/main/config.json"
31
+ ),
32
+ "YituTech/conv-bert-small": "https://huggingface.co/YituTech/conv-bert-small/resolve/main/config.json",
33
+ # See all ConvBERT models at https://huggingface.co/models?filter=convbert
34
+ }
35
+
36
+
37
+ class ConvBertConfig(PretrainedConfig):
38
+ r"""
39
+ This is the configuration class to store the configuration of a [`ConvBertModel`]. It is used to instantiate an
40
+ ConvBERT model according to the specified arguments, defining the model architecture. Instantiating a configuration
41
+ with the defaults will yield a similar configuration to that of the ConvBERT
42
+ [YituTech/conv-bert-base](https://huggingface.co/YituTech/conv-bert-base) architecture.
43
+
44
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
45
+ documentation from [`PretrainedConfig`] for more information.
46
+
47
+
48
+ Args:
49
+ vocab_size (`int`, *optional*, defaults to 30522):
50
+ Vocabulary size of the ConvBERT model. Defines the number of different tokens that can be represented by
51
+ the `inputs_ids` passed when calling [`ConvBertModel`] or [`TFConvBertModel`].
52
+ hidden_size (`int`, *optional*, defaults to 768):
53
+ Dimensionality of the encoder layers and the pooler layer.
54
+ num_hidden_layers (`int`, *optional*, defaults to 12):
55
+ Number of hidden layers in the Transformer encoder.
56
+ num_attention_heads (`int`, *optional*, defaults to 12):
57
+ Number of attention heads for each attention layer in the Transformer encoder.
58
+ intermediate_size (`int`, *optional*, defaults to 3072):
59
+ Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
60
+ hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):
61
+ The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
62
+ `"relu"`, `"selu"` and `"gelu_new"` are supported.
63
+ hidden_dropout_prob (`float`, *optional*, defaults to 0.1):
64
+ The dropout probabilitiy for all fully connected layers in the embeddings, encoder, and pooler.
65
+ attention_probs_dropout_prob (`float`, *optional*, defaults to 0.1):
66
+ The dropout ratio for the attention probabilities.
67
+ max_position_embeddings (`int`, *optional*, defaults to 512):
68
+ The maximum sequence length that this model might ever be used with. Typically set this to something large
69
+ just in case (e.g., 512 or 1024 or 2048).
70
+ type_vocab_size (`int`, *optional*, defaults to 2):
71
+ The vocabulary size of the `token_type_ids` passed when calling [`ConvBertModel`] or [`TFConvBertModel`].
72
+ initializer_range (`float`, *optional*, defaults to 0.02):
73
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
74
+ layer_norm_eps (`float`, *optional*, defaults to 1e-12):
75
+ The epsilon used by the layer normalization layers.
76
+ head_ratio (`int`, *optional*, defaults to 2):
77
+ Ratio gamma to reduce the number of attention heads.
78
+ num_groups (`int`, *optional*, defaults to 1):
79
+ The number of groups for grouped linear layers for ConvBert model
80
+ conv_kernel_size (`int`, *optional*, defaults to 9):
81
+ The size of the convolutional kernel.
82
+ classifier_dropout (`float`, *optional*):
83
+ The dropout ratio for the classification head.
84
+
85
+ Example:
86
+
87
+ ```python
88
+ >>> from transformers import ConvBertConfig, ConvBertModel
89
+
90
+ >>> # Initializing a ConvBERT convbert-base-uncased style configuration
91
+ >>> configuration = ConvBertConfig()
92
+
93
+ >>> # Initializing a model (with random weights) from the convbert-base-uncased style configuration
94
+ >>> model = ConvBertModel(configuration)
95
+
96
+ >>> # Accessing the model configuration
97
+ >>> configuration = model.config
98
+ ```"""
99
+
100
+ model_type = "convbert"
101
+
102
+ def __init__(
103
+ self,
104
+ vocab_size=30522,
105
+ hidden_size=768,
106
+ num_hidden_layers=12,
107
+ num_attention_heads=12,
108
+ intermediate_size=3072,
109
+ hidden_act="gelu",
110
+ hidden_dropout_prob=0.1,
111
+ attention_probs_dropout_prob=0.1,
112
+ max_position_embeddings=512,
113
+ type_vocab_size=2,
114
+ initializer_range=0.02,
115
+ layer_norm_eps=1e-12,
116
+ pad_token_id=1,
117
+ bos_token_id=0,
118
+ eos_token_id=2,
119
+ embedding_size=768,
120
+ head_ratio=2,
121
+ conv_kernel_size=9,
122
+ num_groups=1,
123
+ classifier_dropout=None,
124
+ **kwargs,
125
+ ):
126
+ super().__init__(
127
+ pad_token_id=pad_token_id,
128
+ bos_token_id=bos_token_id,
129
+ eos_token_id=eos_token_id,
130
+ **kwargs,
131
+ )
132
+
133
+ self.vocab_size = vocab_size
134
+ self.hidden_size = hidden_size
135
+ self.num_hidden_layers = num_hidden_layers
136
+ self.num_attention_heads = num_attention_heads
137
+ self.intermediate_size = intermediate_size
138
+ self.hidden_act = hidden_act
139
+ self.hidden_dropout_prob = hidden_dropout_prob
140
+ self.attention_probs_dropout_prob = attention_probs_dropout_prob
141
+ self.max_position_embeddings = max_position_embeddings
142
+ self.type_vocab_size = type_vocab_size
143
+ self.initializer_range = initializer_range
144
+ self.layer_norm_eps = layer_norm_eps
145
+ self.embedding_size = embedding_size
146
+ self.head_ratio = head_ratio
147
+ self.conv_kernel_size = conv_kernel_size
148
+ self.num_groups = num_groups
149
+ self.classifier_dropout = classifier_dropout
150
+
151
+
152
+ # Copied from transformers.models.bert.configuration_bert.BertOnnxConfig
153
+ class ConvBertOnnxConfig(OnnxConfig):
154
+ @property
155
+ def inputs(self) -> Mapping[str, Mapping[int, str]]:
156
+ if self.task == "multiple-choice":
157
+ dynamic_axis = {0: "batch", 1: "choice", 2: "sequence"}
158
+ else:
159
+ dynamic_axis = {0: "batch", 1: "sequence"}
160
+ return OrderedDict(
161
+ [
162
+ ("input_ids", dynamic_axis),
163
+ ("attention_mask", dynamic_axis),
164
+ ("token_type_ids", dynamic_axis),
165
+ ]
166
+ )
pllava/lib/python3.10/site-packages/transformers/models/convbert/convert_convbert_original_tf1_checkpoint_to_pytorch_and_tf2.py ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 ConvBERT checkpoint."""
16
+
17
+ import argparse
18
+
19
+ from transformers import ConvBertConfig, ConvBertModel, TFConvBertModel, load_tf_weights_in_convbert
20
+ from transformers.utils import logging
21
+
22
+
23
+ logging.set_verbosity_info()
24
+
25
+
26
+ def convert_orig_tf1_checkpoint_to_pytorch(tf_checkpoint_path, convbert_config_file, pytorch_dump_path):
27
+ conf = ConvBertConfig.from_json_file(convbert_config_file)
28
+ model = ConvBertModel(conf)
29
+
30
+ model = load_tf_weights_in_convbert(model, conf, tf_checkpoint_path)
31
+ model.save_pretrained(pytorch_dump_path)
32
+
33
+ tf_model = TFConvBertModel.from_pretrained(pytorch_dump_path, from_pt=True)
34
+ tf_model.save_pretrained(pytorch_dump_path)
35
+
36
+
37
+ if __name__ == "__main__":
38
+ parser = argparse.ArgumentParser()
39
+ # Required parameters
40
+ parser.add_argument(
41
+ "--tf_checkpoint_path", default=None, type=str, required=True, help="Path to the TensorFlow checkpoint path."
42
+ )
43
+ parser.add_argument(
44
+ "--convbert_config_file",
45
+ default=None,
46
+ type=str,
47
+ required=True,
48
+ help=(
49
+ "The config json file corresponding to the pre-trained ConvBERT model. \n"
50
+ "This specifies the model architecture."
51
+ ),
52
+ )
53
+ parser.add_argument(
54
+ "--pytorch_dump_path", default=None, type=str, required=True, help="Path to the output PyTorch model."
55
+ )
56
+ args = parser.parse_args()
57
+ convert_orig_tf1_checkpoint_to_pytorch(args.tf_checkpoint_path, args.convbert_config_file, args.pytorch_dump_path)
pllava/lib/python3.10/site-packages/transformers/models/convbert/modeling_convbert.py ADDED
@@ -0,0 +1,1341 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2021 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 ConvBERT model."""
16
+
17
+
18
+ import math
19
+ import os
20
+ from operator import attrgetter
21
+ from typing import 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, get_activation
29
+ from ...modeling_outputs import (
30
+ BaseModelOutputWithCrossAttentions,
31
+ MaskedLMOutput,
32
+ MultipleChoiceModelOutput,
33
+ QuestionAnsweringModelOutput,
34
+ SequenceClassifierOutput,
35
+ TokenClassifierOutput,
36
+ )
37
+ from ...modeling_utils import PreTrainedModel, SequenceSummary
38
+ from ...pytorch_utils import apply_chunking_to_forward, find_pruneable_heads_and_indices, prune_linear_layer
39
+ from ...utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward, logging
40
+ from .configuration_convbert import ConvBertConfig
41
+
42
+
43
+ logger = logging.get_logger(__name__)
44
+
45
+ _CHECKPOINT_FOR_DOC = "YituTech/conv-bert-base"
46
+ _CONFIG_FOR_DOC = "ConvBertConfig"
47
+
48
+ CONVBERT_PRETRAINED_MODEL_ARCHIVE_LIST = [
49
+ "YituTech/conv-bert-base",
50
+ "YituTech/conv-bert-medium-small",
51
+ "YituTech/conv-bert-small",
52
+ # See all ConvBERT models at https://huggingface.co/models?filter=convbert
53
+ ]
54
+
55
+
56
+ def load_tf_weights_in_convbert(model, config, tf_checkpoint_path):
57
+ """Load tf checkpoints in a pytorch model."""
58
+ try:
59
+ import tensorflow as tf
60
+ except ImportError:
61
+ logger.error(
62
+ "Loading a TensorFlow model in PyTorch, requires TensorFlow to be installed. Please see "
63
+ "https://www.tensorflow.org/install/ for installation instructions."
64
+ )
65
+ raise
66
+ tf_path = os.path.abspath(tf_checkpoint_path)
67
+ logger.info(f"Converting TensorFlow checkpoint from {tf_path}")
68
+ # Load weights from TF model
69
+ init_vars = tf.train.list_variables(tf_path)
70
+ tf_data = {}
71
+ for name, shape in init_vars:
72
+ logger.info(f"Loading TF weight {name} with shape {shape}")
73
+ array = tf.train.load_variable(tf_path, name)
74
+ tf_data[name] = array
75
+
76
+ param_mapping = {
77
+ "embeddings.word_embeddings.weight": "electra/embeddings/word_embeddings",
78
+ "embeddings.position_embeddings.weight": "electra/embeddings/position_embeddings",
79
+ "embeddings.token_type_embeddings.weight": "electra/embeddings/token_type_embeddings",
80
+ "embeddings.LayerNorm.weight": "electra/embeddings/LayerNorm/gamma",
81
+ "embeddings.LayerNorm.bias": "electra/embeddings/LayerNorm/beta",
82
+ "embeddings_project.weight": "electra/embeddings_project/kernel",
83
+ "embeddings_project.bias": "electra/embeddings_project/bias",
84
+ }
85
+ if config.num_groups > 1:
86
+ group_dense_name = "g_dense"
87
+ else:
88
+ group_dense_name = "dense"
89
+
90
+ for j in range(config.num_hidden_layers):
91
+ param_mapping[
92
+ f"encoder.layer.{j}.attention.self.query.weight"
93
+ ] = f"electra/encoder/layer_{j}/attention/self/query/kernel"
94
+ param_mapping[
95
+ f"encoder.layer.{j}.attention.self.query.bias"
96
+ ] = f"electra/encoder/layer_{j}/attention/self/query/bias"
97
+ param_mapping[
98
+ f"encoder.layer.{j}.attention.self.key.weight"
99
+ ] = f"electra/encoder/layer_{j}/attention/self/key/kernel"
100
+ param_mapping[
101
+ f"encoder.layer.{j}.attention.self.key.bias"
102
+ ] = f"electra/encoder/layer_{j}/attention/self/key/bias"
103
+ param_mapping[
104
+ f"encoder.layer.{j}.attention.self.value.weight"
105
+ ] = f"electra/encoder/layer_{j}/attention/self/value/kernel"
106
+ param_mapping[
107
+ f"encoder.layer.{j}.attention.self.value.bias"
108
+ ] = f"electra/encoder/layer_{j}/attention/self/value/bias"
109
+ param_mapping[
110
+ f"encoder.layer.{j}.attention.self.key_conv_attn_layer.depthwise.weight"
111
+ ] = f"electra/encoder/layer_{j}/attention/self/conv_attn_key/depthwise_kernel"
112
+ param_mapping[
113
+ f"encoder.layer.{j}.attention.self.key_conv_attn_layer.pointwise.weight"
114
+ ] = f"electra/encoder/layer_{j}/attention/self/conv_attn_key/pointwise_kernel"
115
+ param_mapping[
116
+ f"encoder.layer.{j}.attention.self.key_conv_attn_layer.bias"
117
+ ] = f"electra/encoder/layer_{j}/attention/self/conv_attn_key/bias"
118
+ param_mapping[
119
+ f"encoder.layer.{j}.attention.self.conv_kernel_layer.weight"
120
+ ] = f"electra/encoder/layer_{j}/attention/self/conv_attn_kernel/kernel"
121
+ param_mapping[
122
+ f"encoder.layer.{j}.attention.self.conv_kernel_layer.bias"
123
+ ] = f"electra/encoder/layer_{j}/attention/self/conv_attn_kernel/bias"
124
+ param_mapping[
125
+ f"encoder.layer.{j}.attention.self.conv_out_layer.weight"
126
+ ] = f"electra/encoder/layer_{j}/attention/self/conv_attn_point/kernel"
127
+ param_mapping[
128
+ f"encoder.layer.{j}.attention.self.conv_out_layer.bias"
129
+ ] = f"electra/encoder/layer_{j}/attention/self/conv_attn_point/bias"
130
+ param_mapping[
131
+ f"encoder.layer.{j}.attention.output.dense.weight"
132
+ ] = f"electra/encoder/layer_{j}/attention/output/dense/kernel"
133
+ param_mapping[
134
+ f"encoder.layer.{j}.attention.output.LayerNorm.weight"
135
+ ] = f"electra/encoder/layer_{j}/attention/output/LayerNorm/gamma"
136
+ param_mapping[
137
+ f"encoder.layer.{j}.attention.output.dense.bias"
138
+ ] = f"electra/encoder/layer_{j}/attention/output/dense/bias"
139
+ param_mapping[
140
+ f"encoder.layer.{j}.attention.output.LayerNorm.bias"
141
+ ] = f"electra/encoder/layer_{j}/attention/output/LayerNorm/beta"
142
+ param_mapping[
143
+ f"encoder.layer.{j}.intermediate.dense.weight"
144
+ ] = f"electra/encoder/layer_{j}/intermediate/{group_dense_name}/kernel"
145
+ param_mapping[
146
+ f"encoder.layer.{j}.intermediate.dense.bias"
147
+ ] = f"electra/encoder/layer_{j}/intermediate/{group_dense_name}/bias"
148
+ param_mapping[
149
+ f"encoder.layer.{j}.output.dense.weight"
150
+ ] = f"electra/encoder/layer_{j}/output/{group_dense_name}/kernel"
151
+ param_mapping[
152
+ f"encoder.layer.{j}.output.dense.bias"
153
+ ] = f"electra/encoder/layer_{j}/output/{group_dense_name}/bias"
154
+ param_mapping[
155
+ f"encoder.layer.{j}.output.LayerNorm.weight"
156
+ ] = f"electra/encoder/layer_{j}/output/LayerNorm/gamma"
157
+ param_mapping[f"encoder.layer.{j}.output.LayerNorm.bias"] = f"electra/encoder/layer_{j}/output/LayerNorm/beta"
158
+
159
+ for param in model.named_parameters():
160
+ param_name = param[0]
161
+ retriever = attrgetter(param_name)
162
+ result = retriever(model)
163
+ tf_name = param_mapping[param_name]
164
+ value = torch.from_numpy(tf_data[tf_name])
165
+ logger.info(f"TF: {tf_name}, PT: {param_name} ")
166
+ if tf_name.endswith("/kernel"):
167
+ if not tf_name.endswith("/intermediate/g_dense/kernel"):
168
+ if not tf_name.endswith("/output/g_dense/kernel"):
169
+ value = value.T
170
+ if tf_name.endswith("/depthwise_kernel"):
171
+ value = value.permute(1, 2, 0) # 2, 0, 1
172
+ if tf_name.endswith("/pointwise_kernel"):
173
+ value = value.permute(2, 1, 0) # 2, 1, 0
174
+ if tf_name.endswith("/conv_attn_key/bias"):
175
+ value = value.unsqueeze(-1)
176
+ result.data = value
177
+ return model
178
+
179
+
180
+ class ConvBertEmbeddings(nn.Module):
181
+ """Construct the embeddings from word, position and token_type embeddings."""
182
+
183
+ def __init__(self, config):
184
+ super().__init__()
185
+ self.word_embeddings = nn.Embedding(config.vocab_size, config.embedding_size, padding_idx=config.pad_token_id)
186
+ self.position_embeddings = nn.Embedding(config.max_position_embeddings, config.embedding_size)
187
+ self.token_type_embeddings = nn.Embedding(config.type_vocab_size, config.embedding_size)
188
+
189
+ # self.LayerNorm is not snake-cased to stick with TensorFlow model variable name and be able to load
190
+ # any TensorFlow checkpoint file
191
+ self.LayerNorm = nn.LayerNorm(config.embedding_size, eps=config.layer_norm_eps)
192
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
193
+ # position_ids (1, len position emb) is contiguous in memory and exported when serialized
194
+ self.register_buffer(
195
+ "position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)), persistent=False
196
+ )
197
+ self.register_buffer(
198
+ "token_type_ids", torch.zeros(self.position_ids.size(), dtype=torch.long), persistent=False
199
+ )
200
+
201
+ def forward(
202
+ self,
203
+ input_ids: Optional[torch.LongTensor] = None,
204
+ token_type_ids: Optional[torch.LongTensor] = None,
205
+ position_ids: Optional[torch.LongTensor] = None,
206
+ inputs_embeds: Optional[torch.FloatTensor] = None,
207
+ ) -> torch.LongTensor:
208
+ if input_ids is not None:
209
+ input_shape = input_ids.size()
210
+ else:
211
+ input_shape = inputs_embeds.size()[:-1]
212
+
213
+ seq_length = input_shape[1]
214
+
215
+ if position_ids is None:
216
+ position_ids = self.position_ids[:, :seq_length]
217
+
218
+ # Setting the token_type_ids to the registered buffer in constructor where it is all zeros, which usually occurs
219
+ # when its auto-generated, registered buffer helps users when tracing the model without passing token_type_ids, solves
220
+ # issue #5664
221
+ if token_type_ids is None:
222
+ if hasattr(self, "token_type_ids"):
223
+ buffered_token_type_ids = self.token_type_ids[:, :seq_length]
224
+ buffered_token_type_ids_expanded = buffered_token_type_ids.expand(input_shape[0], seq_length)
225
+ token_type_ids = buffered_token_type_ids_expanded
226
+ else:
227
+ token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=self.position_ids.device)
228
+
229
+ if inputs_embeds is None:
230
+ inputs_embeds = self.word_embeddings(input_ids)
231
+ position_embeddings = self.position_embeddings(position_ids)
232
+ token_type_embeddings = self.token_type_embeddings(token_type_ids)
233
+
234
+ embeddings = inputs_embeds + position_embeddings + token_type_embeddings
235
+ embeddings = self.LayerNorm(embeddings)
236
+ embeddings = self.dropout(embeddings)
237
+ return embeddings
238
+
239
+
240
+ class ConvBertPreTrainedModel(PreTrainedModel):
241
+ """
242
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
243
+ models.
244
+ """
245
+
246
+ config_class = ConvBertConfig
247
+ load_tf_weights = load_tf_weights_in_convbert
248
+ base_model_prefix = "convbert"
249
+ supports_gradient_checkpointing = True
250
+
251
+ def _init_weights(self, module):
252
+ """Initialize the weights"""
253
+ if isinstance(module, nn.Linear):
254
+ # Slightly different from the TF version which uses truncated_normal for initialization
255
+ # cf https://github.com/pytorch/pytorch/pull/5617
256
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
257
+ if module.bias is not None:
258
+ module.bias.data.zero_()
259
+ elif isinstance(module, nn.Embedding):
260
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
261
+ if module.padding_idx is not None:
262
+ module.weight.data[module.padding_idx].zero_()
263
+ elif isinstance(module, nn.LayerNorm):
264
+ module.bias.data.zero_()
265
+ module.weight.data.fill_(1.0)
266
+
267
+
268
+ class SeparableConv1D(nn.Module):
269
+ """This class implements separable convolution, i.e. a depthwise and a pointwise layer"""
270
+
271
+ def __init__(self, config, input_filters, output_filters, kernel_size, **kwargs):
272
+ super().__init__()
273
+ self.depthwise = nn.Conv1d(
274
+ input_filters,
275
+ input_filters,
276
+ kernel_size=kernel_size,
277
+ groups=input_filters,
278
+ padding=kernel_size // 2,
279
+ bias=False,
280
+ )
281
+ self.pointwise = nn.Conv1d(input_filters, output_filters, kernel_size=1, bias=False)
282
+ self.bias = nn.Parameter(torch.zeros(output_filters, 1))
283
+
284
+ self.depthwise.weight.data.normal_(mean=0.0, std=config.initializer_range)
285
+ self.pointwise.weight.data.normal_(mean=0.0, std=config.initializer_range)
286
+
287
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
288
+ x = self.depthwise(hidden_states)
289
+ x = self.pointwise(x)
290
+ x += self.bias
291
+ return x
292
+
293
+
294
+ class ConvBertSelfAttention(nn.Module):
295
+ def __init__(self, config):
296
+ super().__init__()
297
+ if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):
298
+ raise ValueError(
299
+ f"The hidden size ({config.hidden_size}) is not a multiple of the number of attention "
300
+ f"heads ({config.num_attention_heads})"
301
+ )
302
+
303
+ new_num_attention_heads = config.num_attention_heads // config.head_ratio
304
+ if new_num_attention_heads < 1:
305
+ self.head_ratio = config.num_attention_heads
306
+ self.num_attention_heads = 1
307
+ else:
308
+ self.num_attention_heads = new_num_attention_heads
309
+ self.head_ratio = config.head_ratio
310
+
311
+ self.conv_kernel_size = config.conv_kernel_size
312
+ if config.hidden_size % self.num_attention_heads != 0:
313
+ raise ValueError("hidden_size should be divisible by num_attention_heads")
314
+
315
+ self.attention_head_size = (config.hidden_size // self.num_attention_heads) // 2
316
+ self.all_head_size = self.num_attention_heads * self.attention_head_size
317
+
318
+ self.query = nn.Linear(config.hidden_size, self.all_head_size)
319
+ self.key = nn.Linear(config.hidden_size, self.all_head_size)
320
+ self.value = nn.Linear(config.hidden_size, self.all_head_size)
321
+
322
+ self.key_conv_attn_layer = SeparableConv1D(
323
+ config, config.hidden_size, self.all_head_size, self.conv_kernel_size
324
+ )
325
+ self.conv_kernel_layer = nn.Linear(self.all_head_size, self.num_attention_heads * self.conv_kernel_size)
326
+ self.conv_out_layer = nn.Linear(config.hidden_size, self.all_head_size)
327
+
328
+ self.unfold = nn.Unfold(
329
+ kernel_size=[self.conv_kernel_size, 1], padding=[int((self.conv_kernel_size - 1) / 2), 0]
330
+ )
331
+
332
+ self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
333
+
334
+ def transpose_for_scores(self, x):
335
+ new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.attention_head_size)
336
+ x = x.view(*new_x_shape)
337
+ return x.permute(0, 2, 1, 3)
338
+
339
+ def forward(
340
+ self,
341
+ hidden_states: torch.Tensor,
342
+ attention_mask: Optional[torch.FloatTensor] = None,
343
+ head_mask: Optional[torch.FloatTensor] = None,
344
+ encoder_hidden_states: Optional[torch.Tensor] = None,
345
+ output_attentions: Optional[bool] = False,
346
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor]]:
347
+ mixed_query_layer = self.query(hidden_states)
348
+ batch_size = hidden_states.size(0)
349
+ # If this is instantiated as a cross-attention module, the keys
350
+ # and values come from an encoder; the attention mask needs to be
351
+ # such that the encoder's padding tokens are not attended to.
352
+ if encoder_hidden_states is not None:
353
+ mixed_key_layer = self.key(encoder_hidden_states)
354
+ mixed_value_layer = self.value(encoder_hidden_states)
355
+ else:
356
+ mixed_key_layer = self.key(hidden_states)
357
+ mixed_value_layer = self.value(hidden_states)
358
+
359
+ mixed_key_conv_attn_layer = self.key_conv_attn_layer(hidden_states.transpose(1, 2))
360
+ mixed_key_conv_attn_layer = mixed_key_conv_attn_layer.transpose(1, 2)
361
+
362
+ query_layer = self.transpose_for_scores(mixed_query_layer)
363
+ key_layer = self.transpose_for_scores(mixed_key_layer)
364
+ value_layer = self.transpose_for_scores(mixed_value_layer)
365
+ conv_attn_layer = torch.multiply(mixed_key_conv_attn_layer, mixed_query_layer)
366
+
367
+ conv_kernel_layer = self.conv_kernel_layer(conv_attn_layer)
368
+ conv_kernel_layer = torch.reshape(conv_kernel_layer, [-1, self.conv_kernel_size, 1])
369
+ conv_kernel_layer = torch.softmax(conv_kernel_layer, dim=1)
370
+
371
+ conv_out_layer = self.conv_out_layer(hidden_states)
372
+ conv_out_layer = torch.reshape(conv_out_layer, [batch_size, -1, self.all_head_size])
373
+ conv_out_layer = conv_out_layer.transpose(1, 2).contiguous().unsqueeze(-1)
374
+ conv_out_layer = nn.functional.unfold(
375
+ conv_out_layer,
376
+ kernel_size=[self.conv_kernel_size, 1],
377
+ dilation=1,
378
+ padding=[(self.conv_kernel_size - 1) // 2, 0],
379
+ stride=1,
380
+ )
381
+ conv_out_layer = conv_out_layer.transpose(1, 2).reshape(
382
+ batch_size, -1, self.all_head_size, self.conv_kernel_size
383
+ )
384
+ conv_out_layer = torch.reshape(conv_out_layer, [-1, self.attention_head_size, self.conv_kernel_size])
385
+ conv_out_layer = torch.matmul(conv_out_layer, conv_kernel_layer)
386
+ conv_out_layer = torch.reshape(conv_out_layer, [-1, self.all_head_size])
387
+
388
+ # Take the dot product between "query" and "key" to get the raw attention scores.
389
+ attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))
390
+ attention_scores = attention_scores / math.sqrt(self.attention_head_size)
391
+ if attention_mask is not None:
392
+ # Apply the attention mask is (precomputed for all layers in ConvBertModel forward() function)
393
+ attention_scores = attention_scores + attention_mask
394
+
395
+ # Normalize the attention scores to probabilities.
396
+ attention_probs = nn.functional.softmax(attention_scores, dim=-1)
397
+
398
+ # This is actually dropping out entire tokens to attend to, which might
399
+ # seem a bit unusual, but is taken from the original Transformer paper.
400
+ attention_probs = self.dropout(attention_probs)
401
+
402
+ # Mask heads if we want to
403
+ if head_mask is not None:
404
+ attention_probs = attention_probs * head_mask
405
+
406
+ context_layer = torch.matmul(attention_probs, value_layer)
407
+ context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
408
+
409
+ conv_out = torch.reshape(conv_out_layer, [batch_size, -1, self.num_attention_heads, self.attention_head_size])
410
+ context_layer = torch.cat([context_layer, conv_out], 2)
411
+
412
+ # conv and context
413
+ new_context_layer_shape = context_layer.size()[:-2] + (
414
+ self.num_attention_heads * self.attention_head_size * 2,
415
+ )
416
+ context_layer = context_layer.view(*new_context_layer_shape)
417
+
418
+ outputs = (context_layer, attention_probs) if output_attentions else (context_layer,)
419
+ return outputs
420
+
421
+
422
+ class ConvBertSelfOutput(nn.Module):
423
+ def __init__(self, config):
424
+ super().__init__()
425
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
426
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
427
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
428
+
429
+ def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
430
+ hidden_states = self.dense(hidden_states)
431
+ hidden_states = self.dropout(hidden_states)
432
+ hidden_states = self.LayerNorm(hidden_states + input_tensor)
433
+ return hidden_states
434
+
435
+
436
+ class ConvBertAttention(nn.Module):
437
+ def __init__(self, config):
438
+ super().__init__()
439
+ self.self = ConvBertSelfAttention(config)
440
+ self.output = ConvBertSelfOutput(config)
441
+ self.pruned_heads = set()
442
+
443
+ def prune_heads(self, heads):
444
+ if len(heads) == 0:
445
+ return
446
+ heads, index = find_pruneable_heads_and_indices(
447
+ heads, self.self.num_attention_heads, self.self.attention_head_size, self.pruned_heads
448
+ )
449
+
450
+ # Prune linear layers
451
+ self.self.query = prune_linear_layer(self.self.query, index)
452
+ self.self.key = prune_linear_layer(self.self.key, index)
453
+ self.self.value = prune_linear_layer(self.self.value, index)
454
+ self.output.dense = prune_linear_layer(self.output.dense, index, dim=1)
455
+
456
+ # Update hyper params and store pruned heads
457
+ self.self.num_attention_heads = self.self.num_attention_heads - len(heads)
458
+ self.self.all_head_size = self.self.attention_head_size * self.self.num_attention_heads
459
+ self.pruned_heads = self.pruned_heads.union(heads)
460
+
461
+ def forward(
462
+ self,
463
+ hidden_states: torch.Tensor,
464
+ attention_mask: Optional[torch.FloatTensor] = None,
465
+ head_mask: Optional[torch.FloatTensor] = None,
466
+ encoder_hidden_states: Optional[torch.Tensor] = None,
467
+ output_attentions: Optional[bool] = False,
468
+ ) -> Tuple[torch.Tensor, Optional[torch.FloatTensor]]:
469
+ self_outputs = self.self(
470
+ hidden_states,
471
+ attention_mask,
472
+ head_mask,
473
+ encoder_hidden_states,
474
+ output_attentions,
475
+ )
476
+ attention_output = self.output(self_outputs[0], hidden_states)
477
+ outputs = (attention_output,) + self_outputs[1:] # add attentions if we output them
478
+ return outputs
479
+
480
+
481
+ class GroupedLinearLayer(nn.Module):
482
+ def __init__(self, input_size, output_size, num_groups):
483
+ super().__init__()
484
+ self.input_size = input_size
485
+ self.output_size = output_size
486
+ self.num_groups = num_groups
487
+ self.group_in_dim = self.input_size // self.num_groups
488
+ self.group_out_dim = self.output_size // self.num_groups
489
+ self.weight = nn.Parameter(torch.empty(self.num_groups, self.group_in_dim, self.group_out_dim))
490
+ self.bias = nn.Parameter(torch.empty(output_size))
491
+
492
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
493
+ batch_size = list(hidden_states.size())[0]
494
+ x = torch.reshape(hidden_states, [-1, self.num_groups, self.group_in_dim])
495
+ x = x.permute(1, 0, 2)
496
+ x = torch.matmul(x, self.weight)
497
+ x = x.permute(1, 0, 2)
498
+ x = torch.reshape(x, [batch_size, -1, self.output_size])
499
+ x = x + self.bias
500
+ return x
501
+
502
+
503
+ class ConvBertIntermediate(nn.Module):
504
+ def __init__(self, config):
505
+ super().__init__()
506
+ if config.num_groups == 1:
507
+ self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
508
+ else:
509
+ self.dense = GroupedLinearLayer(
510
+ input_size=config.hidden_size, output_size=config.intermediate_size, num_groups=config.num_groups
511
+ )
512
+ if isinstance(config.hidden_act, str):
513
+ self.intermediate_act_fn = ACT2FN[config.hidden_act]
514
+ else:
515
+ self.intermediate_act_fn = config.hidden_act
516
+
517
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
518
+ hidden_states = self.dense(hidden_states)
519
+ hidden_states = self.intermediate_act_fn(hidden_states)
520
+ return hidden_states
521
+
522
+
523
+ class ConvBertOutput(nn.Module):
524
+ def __init__(self, config):
525
+ super().__init__()
526
+ if config.num_groups == 1:
527
+ self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
528
+ else:
529
+ self.dense = GroupedLinearLayer(
530
+ input_size=config.intermediate_size, output_size=config.hidden_size, num_groups=config.num_groups
531
+ )
532
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
533
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
534
+
535
+ def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
536
+ hidden_states = self.dense(hidden_states)
537
+ hidden_states = self.dropout(hidden_states)
538
+ hidden_states = self.LayerNorm(hidden_states + input_tensor)
539
+ return hidden_states
540
+
541
+
542
+ class ConvBertLayer(nn.Module):
543
+ def __init__(self, config):
544
+ super().__init__()
545
+ self.chunk_size_feed_forward = config.chunk_size_feed_forward
546
+ self.seq_len_dim = 1
547
+ self.attention = ConvBertAttention(config)
548
+ self.is_decoder = config.is_decoder
549
+ self.add_cross_attention = config.add_cross_attention
550
+ if self.add_cross_attention:
551
+ if not self.is_decoder:
552
+ raise TypeError(f"{self} should be used as a decoder model if cross attention is added")
553
+ self.crossattention = ConvBertAttention(config)
554
+ self.intermediate = ConvBertIntermediate(config)
555
+ self.output = ConvBertOutput(config)
556
+
557
+ def forward(
558
+ self,
559
+ hidden_states: torch.Tensor,
560
+ attention_mask: Optional[torch.FloatTensor] = None,
561
+ head_mask: Optional[torch.FloatTensor] = None,
562
+ encoder_hidden_states: Optional[torch.Tensor] = None,
563
+ encoder_attention_mask: Optional[torch.Tensor] = None,
564
+ output_attentions: Optional[bool] = False,
565
+ ) -> Tuple[torch.Tensor, Optional[torch.FloatTensor]]:
566
+ self_attention_outputs = self.attention(
567
+ hidden_states,
568
+ attention_mask,
569
+ head_mask,
570
+ output_attentions=output_attentions,
571
+ )
572
+ attention_output = self_attention_outputs[0]
573
+ outputs = self_attention_outputs[1:] # add self attentions if we output attention weights
574
+
575
+ if self.is_decoder and encoder_hidden_states is not None:
576
+ if not hasattr(self, "crossattention"):
577
+ raise AttributeError(
578
+ f"If `encoder_hidden_states` are passed, {self} has to be instantiated with cross-attention layers"
579
+ " by setting `config.add_cross_attention=True`"
580
+ )
581
+ cross_attention_outputs = self.crossattention(
582
+ attention_output,
583
+ encoder_attention_mask,
584
+ head_mask,
585
+ encoder_hidden_states,
586
+ output_attentions,
587
+ )
588
+ attention_output = cross_attention_outputs[0]
589
+ outputs = outputs + cross_attention_outputs[1:] # add cross attentions if we output attention weights
590
+
591
+ layer_output = apply_chunking_to_forward(
592
+ self.feed_forward_chunk, self.chunk_size_feed_forward, self.seq_len_dim, attention_output
593
+ )
594
+ outputs = (layer_output,) + outputs
595
+ return outputs
596
+
597
+ def feed_forward_chunk(self, attention_output):
598
+ intermediate_output = self.intermediate(attention_output)
599
+ layer_output = self.output(intermediate_output, attention_output)
600
+ return layer_output
601
+
602
+
603
+ class ConvBertEncoder(nn.Module):
604
+ def __init__(self, config):
605
+ super().__init__()
606
+ self.config = config
607
+ self.layer = nn.ModuleList([ConvBertLayer(config) for _ in range(config.num_hidden_layers)])
608
+ self.gradient_checkpointing = False
609
+
610
+ def forward(
611
+ self,
612
+ hidden_states: torch.Tensor,
613
+ attention_mask: Optional[torch.FloatTensor] = None,
614
+ head_mask: Optional[torch.FloatTensor] = None,
615
+ encoder_hidden_states: Optional[torch.Tensor] = None,
616
+ encoder_attention_mask: Optional[torch.Tensor] = None,
617
+ output_attentions: Optional[bool] = False,
618
+ output_hidden_states: Optional[bool] = False,
619
+ return_dict: Optional[bool] = True,
620
+ ) -> Union[Tuple, BaseModelOutputWithCrossAttentions]:
621
+ all_hidden_states = () if output_hidden_states else None
622
+ all_self_attentions = () if output_attentions else None
623
+ all_cross_attentions = () if output_attentions and self.config.add_cross_attention else None
624
+ for i, layer_module in enumerate(self.layer):
625
+ if output_hidden_states:
626
+ all_hidden_states = all_hidden_states + (hidden_states,)
627
+
628
+ layer_head_mask = head_mask[i] if head_mask is not None else None
629
+
630
+ if self.gradient_checkpointing and self.training:
631
+ layer_outputs = self._gradient_checkpointing_func(
632
+ layer_module.__call__,
633
+ hidden_states,
634
+ attention_mask,
635
+ layer_head_mask,
636
+ encoder_hidden_states,
637
+ encoder_attention_mask,
638
+ output_attentions,
639
+ )
640
+ else:
641
+ layer_outputs = layer_module(
642
+ hidden_states,
643
+ attention_mask,
644
+ layer_head_mask,
645
+ encoder_hidden_states,
646
+ encoder_attention_mask,
647
+ output_attentions,
648
+ )
649
+ hidden_states = layer_outputs[0]
650
+ if output_attentions:
651
+ all_self_attentions = all_self_attentions + (layer_outputs[1],)
652
+ if self.config.add_cross_attention:
653
+ all_cross_attentions = all_cross_attentions + (layer_outputs[2],)
654
+
655
+ if output_hidden_states:
656
+ all_hidden_states = all_hidden_states + (hidden_states,)
657
+
658
+ if not return_dict:
659
+ return tuple(
660
+ v
661
+ for v in [hidden_states, all_hidden_states, all_self_attentions, all_cross_attentions]
662
+ if v is not None
663
+ )
664
+ return BaseModelOutputWithCrossAttentions(
665
+ last_hidden_state=hidden_states,
666
+ hidden_states=all_hidden_states,
667
+ attentions=all_self_attentions,
668
+ cross_attentions=all_cross_attentions,
669
+ )
670
+
671
+
672
+ class ConvBertPredictionHeadTransform(nn.Module):
673
+ def __init__(self, config):
674
+ super().__init__()
675
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
676
+ if isinstance(config.hidden_act, str):
677
+ self.transform_act_fn = ACT2FN[config.hidden_act]
678
+ else:
679
+ self.transform_act_fn = config.hidden_act
680
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
681
+
682
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
683
+ hidden_states = self.dense(hidden_states)
684
+ hidden_states = self.transform_act_fn(hidden_states)
685
+ hidden_states = self.LayerNorm(hidden_states)
686
+ return hidden_states
687
+
688
+
689
+ CONVBERT_START_DOCSTRING = r"""
690
+ This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) sub-class. Use
691
+ it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and
692
+ behavior.
693
+
694
+ Parameters:
695
+ config ([`ConvBertConfig`]): Model configuration class with all the parameters of the model.
696
+ Initializing with a config file does not load the weights associated with the model, only the
697
+ configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
698
+ """
699
+
700
+ CONVBERT_INPUTS_DOCSTRING = r"""
701
+ Args:
702
+ input_ids (`torch.LongTensor` of shape `({0})`):
703
+ Indices of input sequence tokens in the vocabulary.
704
+
705
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
706
+ [`PreTrainedTokenizer.__call__`] for details.
707
+
708
+ [What are input IDs?](../glossary#input-ids)
709
+ attention_mask (`torch.FloatTensor` of shape `({0})`, *optional*):
710
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
711
+
712
+
713
+ - 1 for tokens that are **not masked**,
714
+ - 0 for tokens that are **masked**.
715
+
716
+ [What are attention masks?](../glossary#attention-mask)
717
+ token_type_ids (`torch.LongTensor` of shape `({0})`, *optional*):
718
+ Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
719
+ 1]`:
720
+
721
+
722
+ - 0 corresponds to a *sentence A* token,
723
+ - 1 corresponds to a *sentence B* token.
724
+
725
+ [What are token type IDs?](../glossary#token-type-ids)
726
+ position_ids (`torch.LongTensor` of shape `({0})`, *optional*):
727
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
728
+ config.max_position_embeddings - 1]`.
729
+
730
+ [What are position IDs?](../glossary#position-ids)
731
+ head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
732
+ Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:
733
+
734
+
735
+ - 1 indicates the head is **not masked**,
736
+ - 0 indicates the head is **masked**.
737
+
738
+ inputs_embeds (`torch.FloatTensor` of shape `({0}, hidden_size)`, *optional*):
739
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
740
+ is useful if you want more control over how to convert *input_ids* indices into associated vectors than the
741
+ model's internal embedding lookup matrix.
742
+ output_attentions (`bool`, *optional*):
743
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
744
+ tensors for more detail.
745
+ output_hidden_states (`bool`, *optional*):
746
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
747
+ more detail.
748
+ return_dict (`bool`, *optional*):
749
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
750
+ """
751
+
752
+
753
+ @add_start_docstrings(
754
+ "The bare ConvBERT Model transformer outputting raw hidden-states without any specific head on top.",
755
+ CONVBERT_START_DOCSTRING,
756
+ )
757
+ class ConvBertModel(ConvBertPreTrainedModel):
758
+ def __init__(self, config):
759
+ super().__init__(config)
760
+ self.embeddings = ConvBertEmbeddings(config)
761
+
762
+ if config.embedding_size != config.hidden_size:
763
+ self.embeddings_project = nn.Linear(config.embedding_size, config.hidden_size)
764
+
765
+ self.encoder = ConvBertEncoder(config)
766
+ self.config = config
767
+ # Initialize weights and apply final processing
768
+ self.post_init()
769
+
770
+ def get_input_embeddings(self):
771
+ return self.embeddings.word_embeddings
772
+
773
+ def set_input_embeddings(self, value):
774
+ self.embeddings.word_embeddings = value
775
+
776
+ def _prune_heads(self, heads_to_prune):
777
+ """
778
+ Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
779
+ class PreTrainedModel
780
+ """
781
+ for layer, heads in heads_to_prune.items():
782
+ self.encoder.layer[layer].attention.prune_heads(heads)
783
+
784
+ @add_start_docstrings_to_model_forward(CONVBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
785
+ @add_code_sample_docstrings(
786
+ checkpoint=_CHECKPOINT_FOR_DOC,
787
+ output_type=BaseModelOutputWithCrossAttentions,
788
+ config_class=_CONFIG_FOR_DOC,
789
+ )
790
+ def forward(
791
+ self,
792
+ input_ids: Optional[torch.LongTensor] = None,
793
+ attention_mask: Optional[torch.FloatTensor] = None,
794
+ token_type_ids: Optional[torch.LongTensor] = None,
795
+ position_ids: Optional[torch.LongTensor] = None,
796
+ head_mask: Optional[torch.FloatTensor] = None,
797
+ inputs_embeds: Optional[torch.FloatTensor] = None,
798
+ output_attentions: Optional[bool] = None,
799
+ output_hidden_states: Optional[bool] = None,
800
+ return_dict: Optional[bool] = None,
801
+ ) -> Union[Tuple, BaseModelOutputWithCrossAttentions]:
802
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
803
+ output_hidden_states = (
804
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
805
+ )
806
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
807
+
808
+ if input_ids is not None and inputs_embeds is not None:
809
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
810
+ elif input_ids is not None:
811
+ self.warn_if_padding_and_no_attention_mask(input_ids, attention_mask)
812
+ input_shape = input_ids.size()
813
+ elif inputs_embeds is not None:
814
+ input_shape = inputs_embeds.size()[:-1]
815
+ else:
816
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
817
+
818
+ batch_size, seq_length = input_shape
819
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
820
+
821
+ if attention_mask is None:
822
+ attention_mask = torch.ones(input_shape, device=device)
823
+ if token_type_ids is None:
824
+ if hasattr(self.embeddings, "token_type_ids"):
825
+ buffered_token_type_ids = self.embeddings.token_type_ids[:, :seq_length]
826
+ buffered_token_type_ids_expanded = buffered_token_type_ids.expand(batch_size, seq_length)
827
+ token_type_ids = buffered_token_type_ids_expanded
828
+ else:
829
+ token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=device)
830
+
831
+ extended_attention_mask = self.get_extended_attention_mask(attention_mask, input_shape)
832
+ head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)
833
+
834
+ hidden_states = self.embeddings(
835
+ input_ids=input_ids, position_ids=position_ids, token_type_ids=token_type_ids, inputs_embeds=inputs_embeds
836
+ )
837
+
838
+ if hasattr(self, "embeddings_project"):
839
+ hidden_states = self.embeddings_project(hidden_states)
840
+
841
+ hidden_states = self.encoder(
842
+ hidden_states,
843
+ attention_mask=extended_attention_mask,
844
+ head_mask=head_mask,
845
+ output_attentions=output_attentions,
846
+ output_hidden_states=output_hidden_states,
847
+ return_dict=return_dict,
848
+ )
849
+
850
+ return hidden_states
851
+
852
+
853
+ class ConvBertGeneratorPredictions(nn.Module):
854
+ """Prediction module for the generator, made up of two dense layers."""
855
+
856
+ def __init__(self, config):
857
+ super().__init__()
858
+
859
+ self.activation = get_activation("gelu")
860
+ self.LayerNorm = nn.LayerNorm(config.embedding_size, eps=config.layer_norm_eps)
861
+ self.dense = nn.Linear(config.hidden_size, config.embedding_size)
862
+
863
+ def forward(self, generator_hidden_states: torch.FloatTensor) -> torch.FloatTensor:
864
+ hidden_states = self.dense(generator_hidden_states)
865
+ hidden_states = self.activation(hidden_states)
866
+ hidden_states = self.LayerNorm(hidden_states)
867
+
868
+ return hidden_states
869
+
870
+
871
+ @add_start_docstrings("""ConvBERT Model with a `language modeling` head on top.""", CONVBERT_START_DOCSTRING)
872
+ class ConvBertForMaskedLM(ConvBertPreTrainedModel):
873
+ _tied_weights_keys = ["generator.lm_head.weight"]
874
+
875
+ def __init__(self, config):
876
+ super().__init__(config)
877
+
878
+ self.convbert = ConvBertModel(config)
879
+ self.generator_predictions = ConvBertGeneratorPredictions(config)
880
+
881
+ self.generator_lm_head = nn.Linear(config.embedding_size, config.vocab_size)
882
+ # Initialize weights and apply final processing
883
+ self.post_init()
884
+
885
+ def get_output_embeddings(self):
886
+ return self.generator_lm_head
887
+
888
+ def set_output_embeddings(self, word_embeddings):
889
+ self.generator_lm_head = word_embeddings
890
+
891
+ @add_start_docstrings_to_model_forward(CONVBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
892
+ @add_code_sample_docstrings(
893
+ checkpoint=_CHECKPOINT_FOR_DOC,
894
+ output_type=MaskedLMOutput,
895
+ config_class=_CONFIG_FOR_DOC,
896
+ )
897
+ def forward(
898
+ self,
899
+ input_ids: Optional[torch.LongTensor] = None,
900
+ attention_mask: Optional[torch.FloatTensor] = None,
901
+ token_type_ids: Optional[torch.LongTensor] = None,
902
+ position_ids: Optional[torch.LongTensor] = None,
903
+ head_mask: Optional[torch.FloatTensor] = None,
904
+ inputs_embeds: Optional[torch.FloatTensor] = None,
905
+ labels: Optional[torch.LongTensor] = None,
906
+ output_attentions: Optional[bool] = None,
907
+ output_hidden_states: Optional[bool] = None,
908
+ return_dict: Optional[bool] = None,
909
+ ) -> Union[Tuple, MaskedLMOutput]:
910
+ r"""
911
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
912
+ Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
913
+ config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the
914
+ loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
915
+ """
916
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
917
+
918
+ generator_hidden_states = self.convbert(
919
+ input_ids,
920
+ attention_mask,
921
+ token_type_ids,
922
+ position_ids,
923
+ head_mask,
924
+ inputs_embeds,
925
+ output_attentions,
926
+ output_hidden_states,
927
+ return_dict,
928
+ )
929
+ generator_sequence_output = generator_hidden_states[0]
930
+
931
+ prediction_scores = self.generator_predictions(generator_sequence_output)
932
+ prediction_scores = self.generator_lm_head(prediction_scores)
933
+
934
+ loss = None
935
+ # Masked language modeling softmax layer
936
+ if labels is not None:
937
+ loss_fct = nn.CrossEntropyLoss() # -100 index = padding token
938
+ loss = loss_fct(prediction_scores.view(-1, self.config.vocab_size), labels.view(-1))
939
+
940
+ if not return_dict:
941
+ output = (prediction_scores,) + generator_hidden_states[1:]
942
+ return ((loss,) + output) if loss is not None else output
943
+
944
+ return MaskedLMOutput(
945
+ loss=loss,
946
+ logits=prediction_scores,
947
+ hidden_states=generator_hidden_states.hidden_states,
948
+ attentions=generator_hidden_states.attentions,
949
+ )
950
+
951
+
952
+ class ConvBertClassificationHead(nn.Module):
953
+ """Head for sentence-level classification tasks."""
954
+
955
+ def __init__(self, config):
956
+ super().__init__()
957
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
958
+ classifier_dropout = (
959
+ config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob
960
+ )
961
+ self.dropout = nn.Dropout(classifier_dropout)
962
+ self.out_proj = nn.Linear(config.hidden_size, config.num_labels)
963
+
964
+ self.config = config
965
+
966
+ def forward(self, hidden_states: torch.Tensor, **kwargs) -> torch.Tensor:
967
+ x = hidden_states[:, 0, :] # take <s> token (equiv. to [CLS])
968
+ x = self.dropout(x)
969
+ x = self.dense(x)
970
+ x = ACT2FN[self.config.hidden_act](x)
971
+ x = self.dropout(x)
972
+ x = self.out_proj(x)
973
+ return x
974
+
975
+
976
+ @add_start_docstrings(
977
+ """
978
+ ConvBERT Model transformer with a sequence classification/regression head on top (a linear layer on top of the
979
+ pooled output) e.g. for GLUE tasks.
980
+ """,
981
+ CONVBERT_START_DOCSTRING,
982
+ )
983
+ class ConvBertForSequenceClassification(ConvBertPreTrainedModel):
984
+ def __init__(self, config):
985
+ super().__init__(config)
986
+ self.num_labels = config.num_labels
987
+ self.config = config
988
+ self.convbert = ConvBertModel(config)
989
+ self.classifier = ConvBertClassificationHead(config)
990
+
991
+ # Initialize weights and apply final processing
992
+ self.post_init()
993
+
994
+ @add_start_docstrings_to_model_forward(CONVBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
995
+ @add_code_sample_docstrings(
996
+ checkpoint=_CHECKPOINT_FOR_DOC,
997
+ output_type=SequenceClassifierOutput,
998
+ config_class=_CONFIG_FOR_DOC,
999
+ )
1000
+ def forward(
1001
+ self,
1002
+ input_ids: Optional[torch.LongTensor] = None,
1003
+ attention_mask: Optional[torch.FloatTensor] = None,
1004
+ token_type_ids: Optional[torch.LongTensor] = None,
1005
+ position_ids: Optional[torch.LongTensor] = None,
1006
+ head_mask: Optional[torch.FloatTensor] = None,
1007
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1008
+ labels: Optional[torch.LongTensor] = None,
1009
+ output_attentions: Optional[bool] = None,
1010
+ output_hidden_states: Optional[bool] = None,
1011
+ return_dict: Optional[bool] = None,
1012
+ ) -> Union[Tuple, SequenceClassifierOutput]:
1013
+ r"""
1014
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1015
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1016
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1017
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1018
+ """
1019
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1020
+
1021
+ outputs = self.convbert(
1022
+ input_ids,
1023
+ attention_mask=attention_mask,
1024
+ token_type_ids=token_type_ids,
1025
+ position_ids=position_ids,
1026
+ head_mask=head_mask,
1027
+ inputs_embeds=inputs_embeds,
1028
+ output_attentions=output_attentions,
1029
+ output_hidden_states=output_hidden_states,
1030
+ return_dict=return_dict,
1031
+ )
1032
+
1033
+ sequence_output = outputs[0]
1034
+ logits = self.classifier(sequence_output)
1035
+
1036
+ loss = None
1037
+ if labels is not None:
1038
+ if self.config.problem_type is None:
1039
+ if self.num_labels == 1:
1040
+ self.config.problem_type = "regression"
1041
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1042
+ self.config.problem_type = "single_label_classification"
1043
+ else:
1044
+ self.config.problem_type = "multi_label_classification"
1045
+
1046
+ if self.config.problem_type == "regression":
1047
+ loss_fct = MSELoss()
1048
+ if self.num_labels == 1:
1049
+ loss = loss_fct(logits.squeeze(), labels.squeeze())
1050
+ else:
1051
+ loss = loss_fct(logits, labels)
1052
+ elif self.config.problem_type == "single_label_classification":
1053
+ loss_fct = CrossEntropyLoss()
1054
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
1055
+ elif self.config.problem_type == "multi_label_classification":
1056
+ loss_fct = BCEWithLogitsLoss()
1057
+ loss = loss_fct(logits, labels)
1058
+
1059
+ if not return_dict:
1060
+ output = (logits,) + outputs[1:]
1061
+ return ((loss,) + output) if loss is not None else output
1062
+
1063
+ return SequenceClassifierOutput(
1064
+ loss=loss,
1065
+ logits=logits,
1066
+ hidden_states=outputs.hidden_states,
1067
+ attentions=outputs.attentions,
1068
+ )
1069
+
1070
+
1071
+ @add_start_docstrings(
1072
+ """
1073
+ ConvBERT Model with a multiple choice classification head on top (a linear layer on top of the pooled output and a
1074
+ softmax) e.g. for RocStories/SWAG tasks.
1075
+ """,
1076
+ CONVBERT_START_DOCSTRING,
1077
+ )
1078
+ class ConvBertForMultipleChoice(ConvBertPreTrainedModel):
1079
+ def __init__(self, config):
1080
+ super().__init__(config)
1081
+
1082
+ self.convbert = ConvBertModel(config)
1083
+ self.sequence_summary = SequenceSummary(config)
1084
+ self.classifier = nn.Linear(config.hidden_size, 1)
1085
+
1086
+ # Initialize weights and apply final processing
1087
+ self.post_init()
1088
+
1089
+ @add_start_docstrings_to_model_forward(
1090
+ CONVBERT_INPUTS_DOCSTRING.format("batch_size, num_choices, sequence_length")
1091
+ )
1092
+ @add_code_sample_docstrings(
1093
+ checkpoint=_CHECKPOINT_FOR_DOC,
1094
+ output_type=MultipleChoiceModelOutput,
1095
+ config_class=_CONFIG_FOR_DOC,
1096
+ )
1097
+ def forward(
1098
+ self,
1099
+ input_ids: Optional[torch.LongTensor] = None,
1100
+ attention_mask: Optional[torch.FloatTensor] = None,
1101
+ token_type_ids: Optional[torch.LongTensor] = None,
1102
+ position_ids: Optional[torch.LongTensor] = None,
1103
+ head_mask: Optional[torch.FloatTensor] = None,
1104
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1105
+ labels: Optional[torch.LongTensor] = None,
1106
+ output_attentions: Optional[bool] = None,
1107
+ output_hidden_states: Optional[bool] = None,
1108
+ return_dict: Optional[bool] = None,
1109
+ ) -> Union[Tuple, MultipleChoiceModelOutput]:
1110
+ r"""
1111
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1112
+ Labels for computing the multiple choice classification loss. Indices should be in `[0, ...,
1113
+ num_choices-1]` where `num_choices` is the size of the second dimension of the input tensors. (See
1114
+ `input_ids` above)
1115
+ """
1116
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1117
+ num_choices = input_ids.shape[1] if input_ids is not None else inputs_embeds.shape[1]
1118
+
1119
+ input_ids = input_ids.view(-1, input_ids.size(-1)) if input_ids is not None else None
1120
+ attention_mask = attention_mask.view(-1, attention_mask.size(-1)) if attention_mask is not None else None
1121
+ token_type_ids = token_type_ids.view(-1, token_type_ids.size(-1)) if token_type_ids is not None else None
1122
+ position_ids = position_ids.view(-1, position_ids.size(-1)) if position_ids is not None else None
1123
+ inputs_embeds = (
1124
+ inputs_embeds.view(-1, inputs_embeds.size(-2), inputs_embeds.size(-1))
1125
+ if inputs_embeds is not None
1126
+ else None
1127
+ )
1128
+
1129
+ outputs = self.convbert(
1130
+ input_ids,
1131
+ attention_mask=attention_mask,
1132
+ token_type_ids=token_type_ids,
1133
+ position_ids=position_ids,
1134
+ head_mask=head_mask,
1135
+ inputs_embeds=inputs_embeds,
1136
+ output_attentions=output_attentions,
1137
+ output_hidden_states=output_hidden_states,
1138
+ return_dict=return_dict,
1139
+ )
1140
+
1141
+ sequence_output = outputs[0]
1142
+
1143
+ pooled_output = self.sequence_summary(sequence_output)
1144
+ logits = self.classifier(pooled_output)
1145
+ reshaped_logits = logits.view(-1, num_choices)
1146
+
1147
+ loss = None
1148
+ if labels is not None:
1149
+ loss_fct = CrossEntropyLoss()
1150
+ loss = loss_fct(reshaped_logits, labels)
1151
+
1152
+ if not return_dict:
1153
+ output = (reshaped_logits,) + outputs[1:]
1154
+ return ((loss,) + output) if loss is not None else output
1155
+
1156
+ return MultipleChoiceModelOutput(
1157
+ loss=loss,
1158
+ logits=reshaped_logits,
1159
+ hidden_states=outputs.hidden_states,
1160
+ attentions=outputs.attentions,
1161
+ )
1162
+
1163
+
1164
+ @add_start_docstrings(
1165
+ """
1166
+ ConvBERT Model with a token classification head on top (a linear layer on top of the hidden-states output) e.g. for
1167
+ Named-Entity-Recognition (NER) tasks.
1168
+ """,
1169
+ CONVBERT_START_DOCSTRING,
1170
+ )
1171
+ class ConvBertForTokenClassification(ConvBertPreTrainedModel):
1172
+ def __init__(self, config):
1173
+ super().__init__(config)
1174
+ self.num_labels = config.num_labels
1175
+
1176
+ self.convbert = ConvBertModel(config)
1177
+ classifier_dropout = (
1178
+ config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob
1179
+ )
1180
+ self.dropout = nn.Dropout(classifier_dropout)
1181
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels)
1182
+
1183
+ # Initialize weights and apply final processing
1184
+ self.post_init()
1185
+
1186
+ @add_start_docstrings_to_model_forward(CONVBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
1187
+ @add_code_sample_docstrings(
1188
+ checkpoint=_CHECKPOINT_FOR_DOC,
1189
+ output_type=TokenClassifierOutput,
1190
+ config_class=_CONFIG_FOR_DOC,
1191
+ )
1192
+ def forward(
1193
+ self,
1194
+ input_ids: Optional[torch.LongTensor] = None,
1195
+ attention_mask: Optional[torch.FloatTensor] = None,
1196
+ token_type_ids: Optional[torch.LongTensor] = None,
1197
+ position_ids: Optional[torch.LongTensor] = None,
1198
+ head_mask: Optional[torch.FloatTensor] = None,
1199
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1200
+ labels: Optional[torch.LongTensor] = None,
1201
+ output_attentions: Optional[bool] = None,
1202
+ output_hidden_states: Optional[bool] = None,
1203
+ return_dict: Optional[bool] = None,
1204
+ ) -> Union[Tuple, TokenClassifierOutput]:
1205
+ r"""
1206
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1207
+ Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`.
1208
+ """
1209
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1210
+
1211
+ outputs = self.convbert(
1212
+ input_ids,
1213
+ attention_mask=attention_mask,
1214
+ token_type_ids=token_type_ids,
1215
+ position_ids=position_ids,
1216
+ head_mask=head_mask,
1217
+ inputs_embeds=inputs_embeds,
1218
+ output_attentions=output_attentions,
1219
+ output_hidden_states=output_hidden_states,
1220
+ return_dict=return_dict,
1221
+ )
1222
+
1223
+ sequence_output = outputs[0]
1224
+
1225
+ sequence_output = self.dropout(sequence_output)
1226
+ logits = self.classifier(sequence_output)
1227
+
1228
+ loss = None
1229
+ if labels is not None:
1230
+ loss_fct = CrossEntropyLoss()
1231
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
1232
+
1233
+ if not return_dict:
1234
+ output = (logits,) + outputs[1:]
1235
+ return ((loss,) + output) if loss is not None else output
1236
+
1237
+ return TokenClassifierOutput(
1238
+ loss=loss,
1239
+ logits=logits,
1240
+ hidden_states=outputs.hidden_states,
1241
+ attentions=outputs.attentions,
1242
+ )
1243
+
1244
+
1245
+ @add_start_docstrings(
1246
+ """
1247
+ ConvBERT Model with a span classification head on top for extractive question-answering tasks like SQuAD (a linear
1248
+ layers on top of the hidden-states output to compute `span start logits` and `span end logits`).
1249
+ """,
1250
+ CONVBERT_START_DOCSTRING,
1251
+ )
1252
+ class ConvBertForQuestionAnswering(ConvBertPreTrainedModel):
1253
+ def __init__(self, config):
1254
+ super().__init__(config)
1255
+
1256
+ self.num_labels = config.num_labels
1257
+ self.convbert = ConvBertModel(config)
1258
+ self.qa_outputs = nn.Linear(config.hidden_size, config.num_labels)
1259
+
1260
+ # Initialize weights and apply final processing
1261
+ self.post_init()
1262
+
1263
+ @add_start_docstrings_to_model_forward(CONVBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
1264
+ @add_code_sample_docstrings(
1265
+ checkpoint=_CHECKPOINT_FOR_DOC,
1266
+ output_type=QuestionAnsweringModelOutput,
1267
+ config_class=_CONFIG_FOR_DOC,
1268
+ )
1269
+ def forward(
1270
+ self,
1271
+ input_ids: Optional[torch.LongTensor] = None,
1272
+ attention_mask: Optional[torch.FloatTensor] = None,
1273
+ token_type_ids: Optional[torch.LongTensor] = None,
1274
+ position_ids: Optional[torch.LongTensor] = None,
1275
+ head_mask: Optional[torch.FloatTensor] = None,
1276
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1277
+ start_positions: Optional[torch.LongTensor] = None,
1278
+ end_positions: Optional[torch.LongTensor] = None,
1279
+ output_attentions: Optional[bool] = None,
1280
+ output_hidden_states: Optional[bool] = None,
1281
+ return_dict: Optional[bool] = None,
1282
+ ) -> Union[Tuple, QuestionAnsweringModelOutput]:
1283
+ r"""
1284
+ start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1285
+ Labels for position (index) of the start of the labelled span for computing the token classification loss.
1286
+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
1287
+ are not taken into account for computing the loss.
1288
+ end_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1289
+ Labels for position (index) of the end of the labelled span for computing the token classification loss.
1290
+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
1291
+ are not taken into account for computing the loss.
1292
+ """
1293
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1294
+
1295
+ outputs = self.convbert(
1296
+ input_ids,
1297
+ attention_mask=attention_mask,
1298
+ token_type_ids=token_type_ids,
1299
+ position_ids=position_ids,
1300
+ head_mask=head_mask,
1301
+ inputs_embeds=inputs_embeds,
1302
+ output_attentions=output_attentions,
1303
+ output_hidden_states=output_hidden_states,
1304
+ return_dict=return_dict,
1305
+ )
1306
+
1307
+ sequence_output = outputs[0]
1308
+
1309
+ logits = self.qa_outputs(sequence_output)
1310
+ start_logits, end_logits = logits.split(1, dim=-1)
1311
+ start_logits = start_logits.squeeze(-1).contiguous()
1312
+ end_logits = end_logits.squeeze(-1).contiguous()
1313
+
1314
+ total_loss = None
1315
+ if start_positions is not None and end_positions is not None:
1316
+ # If we are on multi-GPU, split add a dimension
1317
+ if len(start_positions.size()) > 1:
1318
+ start_positions = start_positions.squeeze(-1)
1319
+ if len(end_positions.size()) > 1:
1320
+ end_positions = end_positions.squeeze(-1)
1321
+ # sometimes the start/end positions are outside our model inputs, we ignore these terms
1322
+ ignored_index = start_logits.size(1)
1323
+ start_positions = start_positions.clamp(0, ignored_index)
1324
+ end_positions = end_positions.clamp(0, ignored_index)
1325
+
1326
+ loss_fct = CrossEntropyLoss(ignore_index=ignored_index)
1327
+ start_loss = loss_fct(start_logits, start_positions)
1328
+ end_loss = loss_fct(end_logits, end_positions)
1329
+ total_loss = (start_loss + end_loss) / 2
1330
+
1331
+ if not return_dict:
1332
+ output = (start_logits, end_logits) + outputs[1:]
1333
+ return ((total_loss,) + output) if total_loss is not None else output
1334
+
1335
+ return QuestionAnsweringModelOutput(
1336
+ loss=total_loss,
1337
+ start_logits=start_logits,
1338
+ end_logits=end_logits,
1339
+ hidden_states=outputs.hidden_states,
1340
+ attentions=outputs.attentions,
1341
+ )
pllava/lib/python3.10/site-packages/transformers/models/convbert/modeling_tf_convbert.py ADDED
@@ -0,0 +1,1471 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2021 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 ConvBERT model."""
16
+
17
+
18
+ from __future__ import annotations
19
+
20
+ from typing import Optional, Tuple, Union
21
+
22
+ import numpy as np
23
+ import tensorflow as tf
24
+
25
+ from ...activations_tf import get_tf_activation
26
+ from ...modeling_tf_outputs import (
27
+ TFBaseModelOutput,
28
+ TFMaskedLMOutput,
29
+ TFMultipleChoiceModelOutput,
30
+ TFQuestionAnsweringModelOutput,
31
+ TFSequenceClassifierOutput,
32
+ TFTokenClassifierOutput,
33
+ )
34
+ from ...modeling_tf_utils import (
35
+ TFMaskedLanguageModelingLoss,
36
+ TFModelInputType,
37
+ TFMultipleChoiceLoss,
38
+ TFPreTrainedModel,
39
+ TFQuestionAnsweringLoss,
40
+ TFSequenceClassificationLoss,
41
+ TFSequenceSummary,
42
+ TFTokenClassificationLoss,
43
+ get_initializer,
44
+ keras_serializable,
45
+ unpack_inputs,
46
+ )
47
+ from ...tf_utils import check_embeddings_within_bounds, shape_list, stable_softmax
48
+ from ...utils import (
49
+ add_code_sample_docstrings,
50
+ add_start_docstrings,
51
+ add_start_docstrings_to_model_forward,
52
+ logging,
53
+ )
54
+ from .configuration_convbert import ConvBertConfig
55
+
56
+
57
+ logger = logging.get_logger(__name__)
58
+
59
+ _CHECKPOINT_FOR_DOC = "YituTech/conv-bert-base"
60
+ _CONFIG_FOR_DOC = "ConvBertConfig"
61
+
62
+ TF_CONVBERT_PRETRAINED_MODEL_ARCHIVE_LIST = [
63
+ "YituTech/conv-bert-base",
64
+ "YituTech/conv-bert-medium-small",
65
+ "YituTech/conv-bert-small",
66
+ # See all ConvBERT models at https://huggingface.co/models?filter=convbert
67
+ ]
68
+
69
+
70
+ # Copied from transformers.models.albert.modeling_tf_albert.TFAlbertEmbeddings with Albert->ConvBert
71
+ class TFConvBertEmbeddings(tf.keras.layers.Layer):
72
+ """Construct the embeddings from word, position and token_type embeddings."""
73
+
74
+ def __init__(self, config: ConvBertConfig, **kwargs):
75
+ super().__init__(**kwargs)
76
+
77
+ self.config = config
78
+ self.embedding_size = config.embedding_size
79
+ self.max_position_embeddings = config.max_position_embeddings
80
+ self.initializer_range = config.initializer_range
81
+ self.LayerNorm = tf.keras.layers.LayerNormalization(epsilon=config.layer_norm_eps, name="LayerNorm")
82
+ self.dropout = tf.keras.layers.Dropout(rate=config.hidden_dropout_prob)
83
+
84
+ def build(self, input_shape=None):
85
+ with tf.name_scope("word_embeddings"):
86
+ self.weight = self.add_weight(
87
+ name="weight",
88
+ shape=[self.config.vocab_size, self.embedding_size],
89
+ initializer=get_initializer(self.initializer_range),
90
+ )
91
+
92
+ with tf.name_scope("token_type_embeddings"):
93
+ self.token_type_embeddings = self.add_weight(
94
+ name="embeddings",
95
+ shape=[self.config.type_vocab_size, self.embedding_size],
96
+ initializer=get_initializer(self.initializer_range),
97
+ )
98
+
99
+ with tf.name_scope("position_embeddings"):
100
+ self.position_embeddings = self.add_weight(
101
+ name="embeddings",
102
+ shape=[self.max_position_embeddings, self.embedding_size],
103
+ initializer=get_initializer(self.initializer_range),
104
+ )
105
+
106
+ if self.built:
107
+ return
108
+ self.built = True
109
+ if getattr(self, "LayerNorm", None) is not None:
110
+ with tf.name_scope(self.LayerNorm.name):
111
+ self.LayerNorm.build([None, None, self.config.embedding_size])
112
+
113
+ # Copied from transformers.models.bert.modeling_tf_bert.TFBertEmbeddings.call
114
+ def call(
115
+ self,
116
+ input_ids: tf.Tensor = None,
117
+ position_ids: tf.Tensor = None,
118
+ token_type_ids: tf.Tensor = None,
119
+ inputs_embeds: tf.Tensor = None,
120
+ past_key_values_length=0,
121
+ training: bool = False,
122
+ ) -> tf.Tensor:
123
+ """
124
+ Applies embedding based on inputs tensor.
125
+
126
+ Returns:
127
+ final_embeddings (`tf.Tensor`): output embedding tensor.
128
+ """
129
+ if input_ids is None and inputs_embeds is None:
130
+ raise ValueError("Need to provide either `input_ids` or `input_embeds`.")
131
+
132
+ if input_ids is not None:
133
+ check_embeddings_within_bounds(input_ids, self.config.vocab_size)
134
+ inputs_embeds = tf.gather(params=self.weight, indices=input_ids)
135
+
136
+ input_shape = shape_list(inputs_embeds)[:-1]
137
+
138
+ if token_type_ids is None:
139
+ token_type_ids = tf.fill(dims=input_shape, value=0)
140
+
141
+ if position_ids is None:
142
+ position_ids = tf.expand_dims(
143
+ tf.range(start=past_key_values_length, limit=input_shape[1] + past_key_values_length), axis=0
144
+ )
145
+
146
+ position_embeds = tf.gather(params=self.position_embeddings, indices=position_ids)
147
+ token_type_embeds = tf.gather(params=self.token_type_embeddings, indices=token_type_ids)
148
+ final_embeddings = inputs_embeds + position_embeds + token_type_embeds
149
+ final_embeddings = self.LayerNorm(inputs=final_embeddings)
150
+ final_embeddings = self.dropout(inputs=final_embeddings, training=training)
151
+
152
+ return final_embeddings
153
+
154
+
155
+ class TFConvBertSelfAttention(tf.keras.layers.Layer):
156
+ def __init__(self, config, **kwargs):
157
+ super().__init__(**kwargs)
158
+
159
+ if config.hidden_size % config.num_attention_heads != 0:
160
+ raise ValueError(
161
+ f"The hidden size ({config.hidden_size}) is not a multiple of the number of attention "
162
+ f"heads ({config.num_attention_heads})"
163
+ )
164
+
165
+ new_num_attention_heads = int(config.num_attention_heads / config.head_ratio)
166
+ if new_num_attention_heads < 1:
167
+ self.head_ratio = config.num_attention_heads
168
+ num_attention_heads = 1
169
+ else:
170
+ num_attention_heads = new_num_attention_heads
171
+ self.head_ratio = config.head_ratio
172
+
173
+ self.num_attention_heads = num_attention_heads
174
+ self.conv_kernel_size = config.conv_kernel_size
175
+
176
+ if config.hidden_size % self.num_attention_heads != 0:
177
+ raise ValueError("hidden_size should be divisible by num_attention_heads")
178
+
179
+ self.attention_head_size = config.hidden_size // config.num_attention_heads
180
+ self.all_head_size = self.num_attention_heads * self.attention_head_size
181
+ self.query = tf.keras.layers.Dense(
182
+ self.all_head_size, kernel_initializer=get_initializer(config.initializer_range), name="query"
183
+ )
184
+ self.key = tf.keras.layers.Dense(
185
+ self.all_head_size, kernel_initializer=get_initializer(config.initializer_range), name="key"
186
+ )
187
+ self.value = tf.keras.layers.Dense(
188
+ self.all_head_size, kernel_initializer=get_initializer(config.initializer_range), name="value"
189
+ )
190
+
191
+ self.key_conv_attn_layer = tf.keras.layers.SeparableConv1D(
192
+ self.all_head_size,
193
+ self.conv_kernel_size,
194
+ padding="same",
195
+ activation=None,
196
+ depthwise_initializer=get_initializer(1 / self.conv_kernel_size),
197
+ pointwise_initializer=get_initializer(config.initializer_range),
198
+ name="key_conv_attn_layer",
199
+ )
200
+
201
+ self.conv_kernel_layer = tf.keras.layers.Dense(
202
+ self.num_attention_heads * self.conv_kernel_size,
203
+ activation=None,
204
+ name="conv_kernel_layer",
205
+ kernel_initializer=get_initializer(config.initializer_range),
206
+ )
207
+
208
+ self.conv_out_layer = tf.keras.layers.Dense(
209
+ self.all_head_size,
210
+ activation=None,
211
+ name="conv_out_layer",
212
+ kernel_initializer=get_initializer(config.initializer_range),
213
+ )
214
+
215
+ self.dropout = tf.keras.layers.Dropout(config.attention_probs_dropout_prob)
216
+ self.config = config
217
+
218
+ def transpose_for_scores(self, x, batch_size):
219
+ # Reshape from [batch_size, seq_length, all_head_size] to [batch_size, seq_length, num_attention_heads, attention_head_size]
220
+ x = tf.reshape(x, (batch_size, -1, self.num_attention_heads, self.attention_head_size))
221
+ return tf.transpose(x, perm=[0, 2, 1, 3])
222
+
223
+ def call(self, hidden_states, attention_mask, head_mask, output_attentions, training=False):
224
+ batch_size = shape_list(hidden_states)[0]
225
+ mixed_query_layer = self.query(hidden_states)
226
+ mixed_key_layer = self.key(hidden_states)
227
+ mixed_value_layer = self.value(hidden_states)
228
+
229
+ mixed_key_conv_attn_layer = self.key_conv_attn_layer(hidden_states)
230
+
231
+ query_layer = self.transpose_for_scores(mixed_query_layer, batch_size)
232
+ key_layer = self.transpose_for_scores(mixed_key_layer, batch_size)
233
+ conv_attn_layer = tf.multiply(mixed_key_conv_attn_layer, mixed_query_layer)
234
+
235
+ conv_kernel_layer = self.conv_kernel_layer(conv_attn_layer)
236
+ conv_kernel_layer = tf.reshape(conv_kernel_layer, [-1, self.conv_kernel_size, 1])
237
+ conv_kernel_layer = stable_softmax(conv_kernel_layer, axis=1)
238
+
239
+ paddings = tf.constant(
240
+ [
241
+ [
242
+ 0,
243
+ 0,
244
+ ],
245
+ [int((self.conv_kernel_size - 1) / 2), int((self.conv_kernel_size - 1) / 2)],
246
+ [0, 0],
247
+ ]
248
+ )
249
+
250
+ conv_out_layer = self.conv_out_layer(hidden_states)
251
+ conv_out_layer = tf.reshape(conv_out_layer, [batch_size, -1, self.all_head_size])
252
+ conv_out_layer = tf.pad(conv_out_layer, paddings, "CONSTANT")
253
+
254
+ unfold_conv_out_layer = tf.stack(
255
+ [
256
+ tf.slice(conv_out_layer, [0, i, 0], [batch_size, shape_list(mixed_query_layer)[1], self.all_head_size])
257
+ for i in range(self.conv_kernel_size)
258
+ ],
259
+ axis=-1,
260
+ )
261
+
262
+ conv_out_layer = tf.reshape(unfold_conv_out_layer, [-1, self.attention_head_size, self.conv_kernel_size])
263
+
264
+ conv_out_layer = tf.matmul(conv_out_layer, conv_kernel_layer)
265
+ conv_out_layer = tf.reshape(conv_out_layer, [-1, self.all_head_size])
266
+
267
+ # Take the dot product between "query" and "key" to get the raw attention scores.
268
+ attention_scores = tf.matmul(
269
+ query_layer, key_layer, transpose_b=True
270
+ ) # (batch size, num_heads, seq_len_q, seq_len_k)
271
+ dk = tf.cast(shape_list(key_layer)[-1], attention_scores.dtype) # scale attention_scores
272
+ attention_scores = attention_scores / tf.math.sqrt(dk)
273
+
274
+ if attention_mask is not None:
275
+ # Apply the attention mask is (precomputed for all layers in TFBertModel call() function)
276
+ attention_scores = attention_scores + attention_mask
277
+
278
+ # Normalize the attention scores to probabilities.
279
+ attention_probs = stable_softmax(attention_scores, axis=-1)
280
+
281
+ # This is actually dropping out entire tokens to attend to, which might
282
+ # seem a bit unusual, but is taken from the original Transformer paper.
283
+ attention_probs = self.dropout(attention_probs, training=training)
284
+
285
+ # Mask heads if we want to
286
+ if head_mask is not None:
287
+ attention_probs = attention_probs * head_mask
288
+
289
+ value_layer = tf.reshape(
290
+ mixed_value_layer, [batch_size, -1, self.num_attention_heads, self.attention_head_size]
291
+ )
292
+ value_layer = tf.transpose(value_layer, [0, 2, 1, 3])
293
+
294
+ context_layer = tf.matmul(attention_probs, value_layer)
295
+ context_layer = tf.transpose(context_layer, perm=[0, 2, 1, 3])
296
+
297
+ conv_out = tf.reshape(conv_out_layer, [batch_size, -1, self.num_attention_heads, self.attention_head_size])
298
+ context_layer = tf.concat([context_layer, conv_out], 2)
299
+ context_layer = tf.reshape(
300
+ context_layer, (batch_size, -1, self.head_ratio * self.all_head_size)
301
+ ) # (batch_size, seq_len_q, all_head_size)
302
+ outputs = (context_layer, attention_probs) if output_attentions else (context_layer,)
303
+
304
+ return outputs
305
+
306
+ def build(self, input_shape=None):
307
+ if self.built:
308
+ return
309
+ self.built = True
310
+ if getattr(self, "query", None) is not None:
311
+ with tf.name_scope(self.query.name):
312
+ self.query.build([None, None, self.config.hidden_size])
313
+ if getattr(self, "key", None) is not None:
314
+ with tf.name_scope(self.key.name):
315
+ self.key.build([None, None, self.config.hidden_size])
316
+ if getattr(self, "value", None) is not None:
317
+ with tf.name_scope(self.value.name):
318
+ self.value.build([None, None, self.config.hidden_size])
319
+ if getattr(self, "key_conv_attn_layer", None) is not None:
320
+ with tf.name_scope(self.key_conv_attn_layer.name):
321
+ self.key_conv_attn_layer.build([None, None, self.config.hidden_size])
322
+ if getattr(self, "conv_kernel_layer", None) is not None:
323
+ with tf.name_scope(self.conv_kernel_layer.name):
324
+ self.conv_kernel_layer.build([None, None, self.all_head_size])
325
+ if getattr(self, "conv_out_layer", None) is not None:
326
+ with tf.name_scope(self.conv_out_layer.name):
327
+ self.conv_out_layer.build([None, None, self.config.hidden_size])
328
+
329
+
330
+ class TFConvBertSelfOutput(tf.keras.layers.Layer):
331
+ def __init__(self, config, **kwargs):
332
+ super().__init__(**kwargs)
333
+
334
+ self.dense = tf.keras.layers.Dense(
335
+ config.hidden_size, kernel_initializer=get_initializer(config.initializer_range), name="dense"
336
+ )
337
+ self.LayerNorm = tf.keras.layers.LayerNormalization(epsilon=config.layer_norm_eps, name="LayerNorm")
338
+ self.dropout = tf.keras.layers.Dropout(config.hidden_dropout_prob)
339
+ self.config = config
340
+
341
+ def call(self, hidden_states, input_tensor, training=False):
342
+ hidden_states = self.dense(hidden_states)
343
+ hidden_states = self.dropout(hidden_states, training=training)
344
+ hidden_states = self.LayerNorm(hidden_states + input_tensor)
345
+
346
+ return hidden_states
347
+
348
+ def build(self, input_shape=None):
349
+ if self.built:
350
+ return
351
+ self.built = True
352
+ if getattr(self, "dense", None) is not None:
353
+ with tf.name_scope(self.dense.name):
354
+ self.dense.build([None, None, self.config.hidden_size])
355
+ if getattr(self, "LayerNorm", None) is not None:
356
+ with tf.name_scope(self.LayerNorm.name):
357
+ self.LayerNorm.build([None, None, self.config.hidden_size])
358
+
359
+
360
+ class TFConvBertAttention(tf.keras.layers.Layer):
361
+ def __init__(self, config, **kwargs):
362
+ super().__init__(**kwargs)
363
+
364
+ self.self_attention = TFConvBertSelfAttention(config, name="self")
365
+ self.dense_output = TFConvBertSelfOutput(config, name="output")
366
+
367
+ def prune_heads(self, heads):
368
+ raise NotImplementedError
369
+
370
+ def call(self, input_tensor, attention_mask, head_mask, output_attentions, training=False):
371
+ self_outputs = self.self_attention(
372
+ input_tensor, attention_mask, head_mask, output_attentions, training=training
373
+ )
374
+ attention_output = self.dense_output(self_outputs[0], input_tensor, training=training)
375
+ outputs = (attention_output,) + self_outputs[1:] # add attentions if we output them
376
+
377
+ return outputs
378
+
379
+ def build(self, input_shape=None):
380
+ if self.built:
381
+ return
382
+ self.built = True
383
+ if getattr(self, "self_attention", None) is not None:
384
+ with tf.name_scope(self.self_attention.name):
385
+ self.self_attention.build(None)
386
+ if getattr(self, "dense_output", None) is not None:
387
+ with tf.name_scope(self.dense_output.name):
388
+ self.dense_output.build(None)
389
+
390
+
391
+ class GroupedLinearLayer(tf.keras.layers.Layer):
392
+ def __init__(self, input_size, output_size, num_groups, kernel_initializer, **kwargs):
393
+ super().__init__(**kwargs)
394
+ self.input_size = input_size
395
+ self.output_size = output_size
396
+ self.num_groups = num_groups
397
+ self.kernel_initializer = kernel_initializer
398
+ self.group_in_dim = self.input_size // self.num_groups
399
+ self.group_out_dim = self.output_size // self.num_groups
400
+
401
+ def build(self, input_shape=None):
402
+ self.kernel = self.add_weight(
403
+ "kernel",
404
+ shape=[self.group_out_dim, self.group_in_dim, self.num_groups],
405
+ initializer=self.kernel_initializer,
406
+ trainable=True,
407
+ )
408
+
409
+ self.bias = self.add_weight(
410
+ "bias", shape=[self.output_size], initializer=self.kernel_initializer, dtype=self.dtype, trainable=True
411
+ )
412
+ super().build(input_shape)
413
+
414
+ def call(self, hidden_states):
415
+ batch_size = shape_list(hidden_states)[0]
416
+ x = tf.transpose(tf.reshape(hidden_states, [-1, self.num_groups, self.group_in_dim]), [1, 0, 2])
417
+ x = tf.matmul(x, tf.transpose(self.kernel, [2, 1, 0]))
418
+ x = tf.transpose(x, [1, 0, 2])
419
+ x = tf.reshape(x, [batch_size, -1, self.output_size])
420
+ x = tf.nn.bias_add(value=x, bias=self.bias)
421
+ return x
422
+
423
+
424
+ class TFConvBertIntermediate(tf.keras.layers.Layer):
425
+ def __init__(self, config, **kwargs):
426
+ super().__init__(**kwargs)
427
+ if config.num_groups == 1:
428
+ self.dense = tf.keras.layers.Dense(
429
+ config.intermediate_size, kernel_initializer=get_initializer(config.initializer_range), name="dense"
430
+ )
431
+ else:
432
+ self.dense = GroupedLinearLayer(
433
+ config.hidden_size,
434
+ config.intermediate_size,
435
+ num_groups=config.num_groups,
436
+ kernel_initializer=get_initializer(config.initializer_range),
437
+ name="dense",
438
+ )
439
+
440
+ if isinstance(config.hidden_act, str):
441
+ self.intermediate_act_fn = get_tf_activation(config.hidden_act)
442
+ else:
443
+ self.intermediate_act_fn = config.hidden_act
444
+ self.config = config
445
+
446
+ def call(self, hidden_states):
447
+ hidden_states = self.dense(hidden_states)
448
+ hidden_states = self.intermediate_act_fn(hidden_states)
449
+
450
+ return hidden_states
451
+
452
+ def build(self, input_shape=None):
453
+ if self.built:
454
+ return
455
+ self.built = True
456
+ if getattr(self, "dense", None) is not None:
457
+ with tf.name_scope(self.dense.name):
458
+ self.dense.build([None, None, self.config.hidden_size])
459
+
460
+
461
+ class TFConvBertOutput(tf.keras.layers.Layer):
462
+ def __init__(self, config, **kwargs):
463
+ super().__init__(**kwargs)
464
+
465
+ if config.num_groups == 1:
466
+ self.dense = tf.keras.layers.Dense(
467
+ config.hidden_size, kernel_initializer=get_initializer(config.initializer_range), name="dense"
468
+ )
469
+ else:
470
+ self.dense = GroupedLinearLayer(
471
+ config.intermediate_size,
472
+ config.hidden_size,
473
+ num_groups=config.num_groups,
474
+ kernel_initializer=get_initializer(config.initializer_range),
475
+ name="dense",
476
+ )
477
+ self.LayerNorm = tf.keras.layers.LayerNormalization(epsilon=config.layer_norm_eps, name="LayerNorm")
478
+ self.dropout = tf.keras.layers.Dropout(config.hidden_dropout_prob)
479
+ self.config = config
480
+
481
+ def call(self, hidden_states, input_tensor, training=False):
482
+ hidden_states = self.dense(hidden_states)
483
+ hidden_states = self.dropout(hidden_states, training=training)
484
+ hidden_states = self.LayerNorm(hidden_states + input_tensor)
485
+
486
+ return hidden_states
487
+
488
+ def build(self, input_shape=None):
489
+ if self.built:
490
+ return
491
+ self.built = True
492
+ if getattr(self, "LayerNorm", None) is not None:
493
+ with tf.name_scope(self.LayerNorm.name):
494
+ self.LayerNorm.build([None, None, self.config.hidden_size])
495
+ if getattr(self, "dense", None) is not None:
496
+ with tf.name_scope(self.dense.name):
497
+ self.dense.build([None, None, self.config.intermediate_size])
498
+
499
+
500
+ class TFConvBertLayer(tf.keras.layers.Layer):
501
+ def __init__(self, config, **kwargs):
502
+ super().__init__(**kwargs)
503
+
504
+ self.attention = TFConvBertAttention(config, name="attention")
505
+ self.intermediate = TFConvBertIntermediate(config, name="intermediate")
506
+ self.bert_output = TFConvBertOutput(config, name="output")
507
+
508
+ def call(self, hidden_states, attention_mask, head_mask, output_attentions, training=False):
509
+ attention_outputs = self.attention(
510
+ hidden_states, attention_mask, head_mask, output_attentions, training=training
511
+ )
512
+ attention_output = attention_outputs[0]
513
+ intermediate_output = self.intermediate(attention_output)
514
+ layer_output = self.bert_output(intermediate_output, attention_output, training=training)
515
+ outputs = (layer_output,) + attention_outputs[1:] # add attentions if we output them
516
+
517
+ return outputs
518
+
519
+ def build(self, input_shape=None):
520
+ if self.built:
521
+ return
522
+ self.built = True
523
+ if getattr(self, "attention", None) is not None:
524
+ with tf.name_scope(self.attention.name):
525
+ self.attention.build(None)
526
+ if getattr(self, "intermediate", None) is not None:
527
+ with tf.name_scope(self.intermediate.name):
528
+ self.intermediate.build(None)
529
+ if getattr(self, "bert_output", None) is not None:
530
+ with tf.name_scope(self.bert_output.name):
531
+ self.bert_output.build(None)
532
+
533
+
534
+ class TFConvBertEncoder(tf.keras.layers.Layer):
535
+ def __init__(self, config, **kwargs):
536
+ super().__init__(**kwargs)
537
+
538
+ self.layer = [TFConvBertLayer(config, name=f"layer_._{i}") for i in range(config.num_hidden_layers)]
539
+
540
+ def call(
541
+ self,
542
+ hidden_states,
543
+ attention_mask,
544
+ head_mask,
545
+ output_attentions,
546
+ output_hidden_states,
547
+ return_dict,
548
+ training=False,
549
+ ):
550
+ all_hidden_states = () if output_hidden_states else None
551
+ all_attentions = () if output_attentions else None
552
+
553
+ for i, layer_module in enumerate(self.layer):
554
+ if output_hidden_states:
555
+ all_hidden_states = all_hidden_states + (hidden_states,)
556
+
557
+ layer_outputs = layer_module(
558
+ hidden_states, attention_mask, head_mask[i], output_attentions, training=training
559
+ )
560
+ hidden_states = layer_outputs[0]
561
+
562
+ if output_attentions:
563
+ all_attentions = all_attentions + (layer_outputs[1],)
564
+
565
+ # Add last layer
566
+ if output_hidden_states:
567
+ all_hidden_states = all_hidden_states + (hidden_states,)
568
+
569
+ if not return_dict:
570
+ return tuple(v for v in [hidden_states, all_hidden_states, all_attentions] if v is not None)
571
+
572
+ return TFBaseModelOutput(
573
+ last_hidden_state=hidden_states, hidden_states=all_hidden_states, attentions=all_attentions
574
+ )
575
+
576
+ def build(self, input_shape=None):
577
+ if self.built:
578
+ return
579
+ self.built = True
580
+ if getattr(self, "layer", None) is not None:
581
+ for layer in self.layer:
582
+ with tf.name_scope(layer.name):
583
+ layer.build(None)
584
+
585
+
586
+ class TFConvBertPredictionHeadTransform(tf.keras.layers.Layer):
587
+ def __init__(self, config, **kwargs):
588
+ super().__init__(**kwargs)
589
+
590
+ self.dense = tf.keras.layers.Dense(
591
+ config.embedding_size, kernel_initializer=get_initializer(config.initializer_range), name="dense"
592
+ )
593
+
594
+ if isinstance(config.hidden_act, str):
595
+ self.transform_act_fn = get_tf_activation(config.hidden_act)
596
+ else:
597
+ self.transform_act_fn = config.hidden_act
598
+
599
+ self.LayerNorm = tf.keras.layers.LayerNormalization(epsilon=config.layer_norm_eps, name="LayerNorm")
600
+ self.config = config
601
+
602
+ def call(self, hidden_states):
603
+ hidden_states = self.dense(hidden_states)
604
+ hidden_states = self.transform_act_fn(hidden_states)
605
+ hidden_states = self.LayerNorm(hidden_states)
606
+
607
+ return hidden_states
608
+
609
+ def build(self, input_shape=None):
610
+ if self.built:
611
+ return
612
+ self.built = True
613
+ if getattr(self, "dense", None) is not None:
614
+ with tf.name_scope(self.dense.name):
615
+ self.dense.build([None, None, self.config.hidden_size])
616
+ if getattr(self, "LayerNorm", None) is not None:
617
+ with tf.name_scope(self.LayerNorm.name):
618
+ self.LayerNorm.build([None, None, self.config.hidden_size])
619
+
620
+
621
+ @keras_serializable
622
+ class TFConvBertMainLayer(tf.keras.layers.Layer):
623
+ config_class = ConvBertConfig
624
+
625
+ def __init__(self, config, **kwargs):
626
+ super().__init__(**kwargs)
627
+
628
+ self.embeddings = TFConvBertEmbeddings(config, name="embeddings")
629
+
630
+ if config.embedding_size != config.hidden_size:
631
+ self.embeddings_project = tf.keras.layers.Dense(config.hidden_size, name="embeddings_project")
632
+
633
+ self.encoder = TFConvBertEncoder(config, name="encoder")
634
+ self.config = config
635
+
636
+ def get_input_embeddings(self):
637
+ return self.embeddings
638
+
639
+ def set_input_embeddings(self, value):
640
+ self.embeddings.weight = value
641
+ self.embeddings.vocab_size = value.shape[0]
642
+
643
+ def _prune_heads(self, heads_to_prune):
644
+ """
645
+ Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
646
+ class PreTrainedModel
647
+ """
648
+ raise NotImplementedError
649
+
650
+ def get_extended_attention_mask(self, attention_mask, input_shape, dtype):
651
+ if attention_mask is None:
652
+ attention_mask = tf.fill(input_shape, 1)
653
+
654
+ # We create a 3D attention mask from a 2D tensor mask.
655
+ # Sizes are [batch_size, 1, 1, to_seq_length]
656
+ # So we can broadcast to [batch_size, num_heads, from_seq_length, to_seq_length]
657
+ # this attention mask is more simple than the triangular masking of causal attention
658
+ # used in OpenAI GPT, we just need to prepare the broadcast dimension here.
659
+ extended_attention_mask = tf.reshape(attention_mask, (input_shape[0], 1, 1, input_shape[1]))
660
+
661
+ # Since attention_mask is 1.0 for positions we want to attend and 0.0 for
662
+ # masked positions, this operation will create a tensor which is 0.0 for
663
+ # positions we want to attend and -10000.0 for masked positions.
664
+ # Since we are adding it to the raw scores before the softmax, this is
665
+ # effectively the same as removing these entirely.
666
+ extended_attention_mask = tf.cast(extended_attention_mask, dtype)
667
+ extended_attention_mask = (1.0 - extended_attention_mask) * -10000.0
668
+
669
+ return extended_attention_mask
670
+
671
+ def get_head_mask(self, head_mask):
672
+ if head_mask is not None:
673
+ raise NotImplementedError
674
+ else:
675
+ head_mask = [None] * self.config.num_hidden_layers
676
+
677
+ return head_mask
678
+
679
+ @unpack_inputs
680
+ def call(
681
+ self,
682
+ input_ids=None,
683
+ attention_mask=None,
684
+ token_type_ids=None,
685
+ position_ids=None,
686
+ head_mask=None,
687
+ inputs_embeds=None,
688
+ output_attentions=None,
689
+ output_hidden_states=None,
690
+ return_dict=None,
691
+ training=False,
692
+ ):
693
+ if input_ids is not None and inputs_embeds is not None:
694
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
695
+ elif input_ids is not None:
696
+ input_shape = shape_list(input_ids)
697
+ elif inputs_embeds is not None:
698
+ input_shape = shape_list(inputs_embeds)[:-1]
699
+ else:
700
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
701
+
702
+ if attention_mask is None:
703
+ attention_mask = tf.fill(input_shape, 1)
704
+
705
+ if token_type_ids is None:
706
+ token_type_ids = tf.fill(input_shape, 0)
707
+
708
+ hidden_states = self.embeddings(input_ids, position_ids, token_type_ids, inputs_embeds, training=training)
709
+ extended_attention_mask = self.get_extended_attention_mask(attention_mask, input_shape, hidden_states.dtype)
710
+ head_mask = self.get_head_mask(head_mask)
711
+
712
+ if hasattr(self, "embeddings_project"):
713
+ hidden_states = self.embeddings_project(hidden_states, training=training)
714
+
715
+ hidden_states = self.encoder(
716
+ hidden_states,
717
+ extended_attention_mask,
718
+ head_mask,
719
+ output_attentions,
720
+ output_hidden_states,
721
+ return_dict,
722
+ training=training,
723
+ )
724
+
725
+ return hidden_states
726
+
727
+ def build(self, input_shape=None):
728
+ if self.built:
729
+ return
730
+ self.built = True
731
+ if getattr(self, "embeddings", None) is not None:
732
+ with tf.name_scope(self.embeddings.name):
733
+ self.embeddings.build(None)
734
+ if getattr(self, "encoder", None) is not None:
735
+ with tf.name_scope(self.encoder.name):
736
+ self.encoder.build(None)
737
+ if getattr(self, "embeddings_project", None) is not None:
738
+ with tf.name_scope(self.embeddings_project.name):
739
+ self.embeddings_project.build([None, None, self.config.embedding_size])
740
+
741
+
742
+ class TFConvBertPreTrainedModel(TFPreTrainedModel):
743
+ """
744
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
745
+ models.
746
+ """
747
+
748
+ config_class = ConvBertConfig
749
+ base_model_prefix = "convbert"
750
+
751
+
752
+ CONVBERT_START_DOCSTRING = r"""
753
+
754
+ This model inherits from [`TFPreTrainedModel`]. Check the superclass documentation for the generic methods the
755
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
756
+ etc.)
757
+
758
+ This model is also a [tf.keras.Model](https://www.tensorflow.org/api_docs/python/tf/keras/Model) subclass. Use it
759
+ as a regular TF 2.0 Keras Model and refer to the TF 2.0 documentation for all matter related to general usage and
760
+ behavior.
761
+
762
+ <Tip>
763
+
764
+ TensorFlow models and layers in `transformers` accept two formats as input:
765
+
766
+ - having all inputs as keyword arguments (like PyTorch models), or
767
+ - having all inputs as a list, tuple or dict in the first positional argument.
768
+
769
+ The reason the second format is supported is that Keras methods prefer this format when passing inputs to models
770
+ and layers. Because of this support, when using methods like `model.fit()` things should "just work" for you - just
771
+ pass your inputs and labels in any format that `model.fit()` supports! If, however, you want to use the second
772
+ format outside of Keras methods like `fit()` and `predict()`, such as when creating your own layers or models with
773
+ the Keras `Functional` API, there are three possibilities you can use to gather all the input Tensors in the first
774
+ positional argument:
775
+
776
+ - a single Tensor with `input_ids` only and nothing else: `model(input_ids)`
777
+ - a list of varying length with one or several input Tensors IN THE ORDER given in the docstring:
778
+ `model([input_ids, attention_mask])` or `model([input_ids, attention_mask, token_type_ids])`
779
+ - a dictionary with one or several input Tensors associated to the input names given in the docstring:
780
+ `model({"input_ids": input_ids, "token_type_ids": token_type_ids})`
781
+
782
+ Note that when creating models and layers with
783
+ [subclassing](https://keras.io/guides/making_new_layers_and_models_via_subclassing/) then you don't need to worry
784
+ about any of this, as you can just pass inputs like you would to any other Python function!
785
+
786
+ </Tip>
787
+
788
+ Args:
789
+ config ([`ConvBertConfig`]): Model configuration class with all the parameters of the model.
790
+ Initializing with a config file does not load the weights associated with the model, only the
791
+ configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
792
+ """
793
+
794
+ CONVBERT_INPUTS_DOCSTRING = r"""
795
+ Args:
796
+ input_ids (`Numpy array` or `tf.Tensor` of shape `({0})`):
797
+ Indices of input sequence tokens in the vocabulary.
798
+
799
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.__call__`] and
800
+ [`PreTrainedTokenizer.encode`] for details.
801
+
802
+ [What are input IDs?](../glossary#input-ids)
803
+ attention_mask (`Numpy array` or `tf.Tensor` of shape `({0})`, *optional*):
804
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
805
+
806
+ - 1 for tokens that are **not masked**,
807
+ - 0 for tokens that are **masked**.
808
+
809
+ [What are attention masks?](../glossary#attention-mask)
810
+ token_type_ids (`Numpy array` or `tf.Tensor` of shape `({0})`, *optional*):
811
+ Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
812
+ 1]`:
813
+
814
+ - 0 corresponds to a *sentence A* token,
815
+ - 1 corresponds to a *sentence B* token.
816
+
817
+ [What are token type IDs?](../glossary#token-type-ids)
818
+ position_ids (`Numpy array` or `tf.Tensor` of shape `({0})`, *optional*):
819
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
820
+ config.max_position_embeddings - 1]`.
821
+
822
+ [What are position IDs?](../glossary#position-ids)
823
+ head_mask (`Numpy array` or `tf.Tensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
824
+ Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:
825
+
826
+ - 1 indicates the head is **not masked**,
827
+ - 0 indicates the head is **masked**.
828
+
829
+ inputs_embeds (`tf.Tensor` of shape `({0}, hidden_size)`, *optional*):
830
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
831
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
832
+ model's internal embedding lookup matrix.
833
+ output_attentions (`bool`, *optional*):
834
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
835
+ tensors for more detail. This argument can be used only in eager mode, in graph mode the value in the
836
+ config will be used instead.
837
+ output_hidden_states (`bool`, *optional*):
838
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
839
+ more detail. This argument can be used only in eager mode, in graph mode the value in the config will be
840
+ used instead.
841
+ return_dict (`bool`, *optional*):
842
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. This argument can be used in
843
+ eager mode, in graph mode the value will always be set to True.
844
+ training (`bool`, *optional*, defaults to `False`):
845
+ Whether or not to use the model in training mode (some modules like dropout modules have different
846
+ behaviors between training and evaluation).
847
+ """
848
+
849
+
850
+ @add_start_docstrings(
851
+ "The bare ConvBERT Model transformer outputting raw hidden-states without any specific head on top.",
852
+ CONVBERT_START_DOCSTRING,
853
+ )
854
+ class TFConvBertModel(TFConvBertPreTrainedModel):
855
+ def __init__(self, config, *inputs, **kwargs):
856
+ super().__init__(config, *inputs, **kwargs)
857
+
858
+ self.convbert = TFConvBertMainLayer(config, name="convbert")
859
+
860
+ @unpack_inputs
861
+ @add_start_docstrings_to_model_forward(CONVBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
862
+ @add_code_sample_docstrings(
863
+ checkpoint=_CHECKPOINT_FOR_DOC,
864
+ output_type=TFBaseModelOutput,
865
+ config_class=_CONFIG_FOR_DOC,
866
+ )
867
+ def call(
868
+ self,
869
+ input_ids: TFModelInputType | None = None,
870
+ attention_mask: Optional[Union[np.array, tf.Tensor]] = None,
871
+ token_type_ids: Optional[Union[np.array, tf.Tensor]] = None,
872
+ position_ids: Optional[Union[np.array, tf.Tensor]] = None,
873
+ head_mask: Optional[Union[np.array, tf.Tensor]] = None,
874
+ inputs_embeds: tf.Tensor | None = None,
875
+ output_attentions: Optional[bool] = None,
876
+ output_hidden_states: Optional[bool] = None,
877
+ return_dict: Optional[bool] = None,
878
+ training: bool = False,
879
+ ) -> Union[TFBaseModelOutput, Tuple[tf.Tensor]]:
880
+ outputs = self.convbert(
881
+ input_ids=input_ids,
882
+ attention_mask=attention_mask,
883
+ token_type_ids=token_type_ids,
884
+ position_ids=position_ids,
885
+ head_mask=head_mask,
886
+ inputs_embeds=inputs_embeds,
887
+ output_attentions=output_attentions,
888
+ output_hidden_states=output_hidden_states,
889
+ return_dict=return_dict,
890
+ training=training,
891
+ )
892
+
893
+ return outputs
894
+
895
+ def build(self, input_shape=None):
896
+ if self.built:
897
+ return
898
+ self.built = True
899
+ if getattr(self, "convbert", None) is not None:
900
+ with tf.name_scope(self.convbert.name):
901
+ self.convbert.build(None)
902
+
903
+
904
+ class TFConvBertMaskedLMHead(tf.keras.layers.Layer):
905
+ def __init__(self, config, input_embeddings, **kwargs):
906
+ super().__init__(**kwargs)
907
+
908
+ self.config = config
909
+ self.embedding_size = config.embedding_size
910
+ self.input_embeddings = input_embeddings
911
+
912
+ def build(self, input_shape):
913
+ self.bias = self.add_weight(shape=(self.config.vocab_size,), initializer="zeros", trainable=True, name="bias")
914
+
915
+ super().build(input_shape)
916
+
917
+ def get_output_embeddings(self):
918
+ return self.input_embeddings
919
+
920
+ def set_output_embeddings(self, value):
921
+ self.input_embeddings.weight = value
922
+ self.input_embeddings.vocab_size = shape_list(value)[0]
923
+
924
+ def get_bias(self):
925
+ return {"bias": self.bias}
926
+
927
+ def set_bias(self, value):
928
+ self.bias = value["bias"]
929
+ self.config.vocab_size = shape_list(value["bias"])[0]
930
+
931
+ def call(self, hidden_states):
932
+ seq_length = shape_list(tensor=hidden_states)[1]
933
+ hidden_states = tf.reshape(tensor=hidden_states, shape=[-1, self.embedding_size])
934
+ hidden_states = tf.matmul(a=hidden_states, b=self.input_embeddings.weight, transpose_b=True)
935
+ hidden_states = tf.reshape(tensor=hidden_states, shape=[-1, seq_length, self.config.vocab_size])
936
+ hidden_states = tf.nn.bias_add(value=hidden_states, bias=self.bias)
937
+
938
+ return hidden_states
939
+
940
+
941
+ class TFConvBertGeneratorPredictions(tf.keras.layers.Layer):
942
+ def __init__(self, config, **kwargs):
943
+ super().__init__(**kwargs)
944
+
945
+ self.LayerNorm = tf.keras.layers.LayerNormalization(epsilon=config.layer_norm_eps, name="LayerNorm")
946
+ self.dense = tf.keras.layers.Dense(config.embedding_size, name="dense")
947
+ self.config = config
948
+
949
+ def call(self, generator_hidden_states, training=False):
950
+ hidden_states = self.dense(generator_hidden_states)
951
+ hidden_states = get_tf_activation("gelu")(hidden_states)
952
+ hidden_states = self.LayerNorm(hidden_states)
953
+
954
+ return hidden_states
955
+
956
+ def build(self, input_shape=None):
957
+ if self.built:
958
+ return
959
+ self.built = True
960
+ if getattr(self, "LayerNorm", None) is not None:
961
+ with tf.name_scope(self.LayerNorm.name):
962
+ self.LayerNorm.build([None, None, self.config.embedding_size])
963
+ if getattr(self, "dense", None) is not None:
964
+ with tf.name_scope(self.dense.name):
965
+ self.dense.build([None, None, self.config.hidden_size])
966
+
967
+
968
+ @add_start_docstrings("""ConvBERT Model with a `language modeling` head on top.""", CONVBERT_START_DOCSTRING)
969
+ class TFConvBertForMaskedLM(TFConvBertPreTrainedModel, TFMaskedLanguageModelingLoss):
970
+ def __init__(self, config, *inputs, **kwargs):
971
+ super().__init__(config, **kwargs)
972
+
973
+ self.config = config
974
+ self.convbert = TFConvBertMainLayer(config, name="convbert")
975
+ self.generator_predictions = TFConvBertGeneratorPredictions(config, name="generator_predictions")
976
+
977
+ if isinstance(config.hidden_act, str):
978
+ self.activation = get_tf_activation(config.hidden_act)
979
+ else:
980
+ self.activation = config.hidden_act
981
+
982
+ self.generator_lm_head = TFConvBertMaskedLMHead(config, self.convbert.embeddings, name="generator_lm_head")
983
+
984
+ def get_lm_head(self):
985
+ return self.generator_lm_head
986
+
987
+ def get_prefix_bias_name(self):
988
+ return self.name + "/" + self.generator_lm_head.name
989
+
990
+ @unpack_inputs
991
+ @add_start_docstrings_to_model_forward(CONVBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
992
+ @add_code_sample_docstrings(
993
+ checkpoint=_CHECKPOINT_FOR_DOC,
994
+ output_type=TFMaskedLMOutput,
995
+ config_class=_CONFIG_FOR_DOC,
996
+ )
997
+ def call(
998
+ self,
999
+ input_ids: TFModelInputType | None = None,
1000
+ attention_mask: np.ndarray | tf.Tensor | None = None,
1001
+ token_type_ids: np.ndarray | tf.Tensor | None = None,
1002
+ position_ids: np.ndarray | tf.Tensor | None = None,
1003
+ head_mask: np.ndarray | tf.Tensor | None = None,
1004
+ inputs_embeds: tf.Tensor | None = None,
1005
+ output_attentions: Optional[bool] = None,
1006
+ output_hidden_states: Optional[bool] = None,
1007
+ return_dict: Optional[bool] = None,
1008
+ labels: tf.Tensor | None = None,
1009
+ training: Optional[bool] = False,
1010
+ ) -> Union[Tuple, TFMaskedLMOutput]:
1011
+ r"""
1012
+ labels (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
1013
+ Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
1014
+ config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the
1015
+ loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
1016
+ """
1017
+ generator_hidden_states = self.convbert(
1018
+ input_ids=input_ids,
1019
+ attention_mask=attention_mask,
1020
+ token_type_ids=token_type_ids,
1021
+ position_ids=position_ids,
1022
+ head_mask=head_mask,
1023
+ inputs_embeds=inputs_embeds,
1024
+ output_attentions=output_attentions,
1025
+ output_hidden_states=output_hidden_states,
1026
+ return_dict=return_dict,
1027
+ training=training,
1028
+ )
1029
+ generator_sequence_output = generator_hidden_states[0]
1030
+ prediction_scores = self.generator_predictions(generator_sequence_output, training=training)
1031
+ prediction_scores = self.generator_lm_head(prediction_scores, training=training)
1032
+ loss = None if labels is None else self.hf_compute_loss(labels, prediction_scores)
1033
+
1034
+ if not return_dict:
1035
+ output = (prediction_scores,) + generator_hidden_states[1:]
1036
+
1037
+ return ((loss,) + output) if loss is not None else output
1038
+
1039
+ return TFMaskedLMOutput(
1040
+ loss=loss,
1041
+ logits=prediction_scores,
1042
+ hidden_states=generator_hidden_states.hidden_states,
1043
+ attentions=generator_hidden_states.attentions,
1044
+ )
1045
+
1046
+ def build(self, input_shape=None):
1047
+ if self.built:
1048
+ return
1049
+ self.built = True
1050
+ if getattr(self, "convbert", None) is not None:
1051
+ with tf.name_scope(self.convbert.name):
1052
+ self.convbert.build(None)
1053
+ if getattr(self, "generator_predictions", None) is not None:
1054
+ with tf.name_scope(self.generator_predictions.name):
1055
+ self.generator_predictions.build(None)
1056
+ if getattr(self, "generator_lm_head", None) is not None:
1057
+ with tf.name_scope(self.generator_lm_head.name):
1058
+ self.generator_lm_head.build(None)
1059
+
1060
+
1061
+ class TFConvBertClassificationHead(tf.keras.layers.Layer):
1062
+ """Head for sentence-level classification tasks."""
1063
+
1064
+ def __init__(self, config, **kwargs):
1065
+ super().__init__(**kwargs)
1066
+
1067
+ self.dense = tf.keras.layers.Dense(
1068
+ config.hidden_size, kernel_initializer=get_initializer(config.initializer_range), name="dense"
1069
+ )
1070
+ classifier_dropout = (
1071
+ config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob
1072
+ )
1073
+ self.dropout = tf.keras.layers.Dropout(classifier_dropout)
1074
+ self.out_proj = tf.keras.layers.Dense(
1075
+ config.num_labels, kernel_initializer=get_initializer(config.initializer_range), name="out_proj"
1076
+ )
1077
+
1078
+ self.config = config
1079
+
1080
+ def call(self, hidden_states, **kwargs):
1081
+ x = hidden_states[:, 0, :] # take <s> token (equiv. to [CLS])
1082
+ x = self.dropout(x)
1083
+ x = self.dense(x)
1084
+ x = get_tf_activation(self.config.hidden_act)(x)
1085
+ x = self.dropout(x)
1086
+ x = self.out_proj(x)
1087
+
1088
+ return x
1089
+
1090
+ def build(self, input_shape=None):
1091
+ if self.built:
1092
+ return
1093
+ self.built = True
1094
+ if getattr(self, "dense", None) is not None:
1095
+ with tf.name_scope(self.dense.name):
1096
+ self.dense.build([None, None, self.config.hidden_size])
1097
+ if getattr(self, "out_proj", None) is not None:
1098
+ with tf.name_scope(self.out_proj.name):
1099
+ self.out_proj.build([None, None, self.config.hidden_size])
1100
+
1101
+
1102
+ @add_start_docstrings(
1103
+ """
1104
+ ConvBERT Model transformer with a sequence classification/regression head on top e.g., for GLUE tasks.
1105
+ """,
1106
+ CONVBERT_START_DOCSTRING,
1107
+ )
1108
+ class TFConvBertForSequenceClassification(TFConvBertPreTrainedModel, TFSequenceClassificationLoss):
1109
+ def __init__(self, config, *inputs, **kwargs):
1110
+ super().__init__(config, *inputs, **kwargs)
1111
+ self.num_labels = config.num_labels
1112
+ self.convbert = TFConvBertMainLayer(config, name="convbert")
1113
+ self.classifier = TFConvBertClassificationHead(config, name="classifier")
1114
+
1115
+ @unpack_inputs
1116
+ @add_start_docstrings_to_model_forward(CONVBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
1117
+ @add_code_sample_docstrings(
1118
+ checkpoint=_CHECKPOINT_FOR_DOC,
1119
+ output_type=TFSequenceClassifierOutput,
1120
+ config_class=_CONFIG_FOR_DOC,
1121
+ )
1122
+ def call(
1123
+ self,
1124
+ input_ids: TFModelInputType | None = None,
1125
+ attention_mask: np.ndarray | tf.Tensor | None = None,
1126
+ token_type_ids: np.ndarray | tf.Tensor | None = None,
1127
+ position_ids: np.ndarray | tf.Tensor | None = None,
1128
+ head_mask: np.ndarray | tf.Tensor | None = None,
1129
+ inputs_embeds: tf.Tensor | None = None,
1130
+ output_attentions: Optional[bool] = None,
1131
+ output_hidden_states: Optional[bool] = None,
1132
+ return_dict: Optional[bool] = None,
1133
+ labels: tf.Tensor | None = None,
1134
+ training: Optional[bool] = False,
1135
+ ) -> Union[Tuple, TFSequenceClassifierOutput]:
1136
+ r"""
1137
+ labels (`tf.Tensor` of shape `(batch_size,)`, *optional*):
1138
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1139
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1140
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1141
+ """
1142
+ outputs = self.convbert(
1143
+ input_ids,
1144
+ attention_mask=attention_mask,
1145
+ token_type_ids=token_type_ids,
1146
+ position_ids=position_ids,
1147
+ head_mask=head_mask,
1148
+ inputs_embeds=inputs_embeds,
1149
+ output_attentions=output_attentions,
1150
+ output_hidden_states=output_hidden_states,
1151
+ return_dict=return_dict,
1152
+ training=training,
1153
+ )
1154
+ logits = self.classifier(outputs[0], training=training)
1155
+ loss = None if labels is None else self.hf_compute_loss(labels, logits)
1156
+
1157
+ if not return_dict:
1158
+ output = (logits,) + outputs[1:]
1159
+
1160
+ return ((loss,) + output) if loss is not None else output
1161
+
1162
+ return TFSequenceClassifierOutput(
1163
+ loss=loss,
1164
+ logits=logits,
1165
+ hidden_states=outputs.hidden_states,
1166
+ attentions=outputs.attentions,
1167
+ )
1168
+
1169
+ def build(self, input_shape=None):
1170
+ if self.built:
1171
+ return
1172
+ self.built = True
1173
+ if getattr(self, "convbert", None) is not None:
1174
+ with tf.name_scope(self.convbert.name):
1175
+ self.convbert.build(None)
1176
+ if getattr(self, "classifier", None) is not None:
1177
+ with tf.name_scope(self.classifier.name):
1178
+ self.classifier.build(None)
1179
+
1180
+
1181
+ @add_start_docstrings(
1182
+ """
1183
+ ConvBERT Model with a multiple choice classification head on top (a linear layer on top of the pooled output and a
1184
+ softmax) e.g. for RocStories/SWAG tasks.
1185
+ """,
1186
+ CONVBERT_START_DOCSTRING,
1187
+ )
1188
+ class TFConvBertForMultipleChoice(TFConvBertPreTrainedModel, TFMultipleChoiceLoss):
1189
+ def __init__(self, config, *inputs, **kwargs):
1190
+ super().__init__(config, *inputs, **kwargs)
1191
+
1192
+ self.convbert = TFConvBertMainLayer(config, name="convbert")
1193
+ self.sequence_summary = TFSequenceSummary(
1194
+ config, initializer_range=config.initializer_range, name="sequence_summary"
1195
+ )
1196
+ self.classifier = tf.keras.layers.Dense(
1197
+ 1, kernel_initializer=get_initializer(config.initializer_range), name="classifier"
1198
+ )
1199
+ self.config = config
1200
+
1201
+ @unpack_inputs
1202
+ @add_start_docstrings_to_model_forward(
1203
+ CONVBERT_INPUTS_DOCSTRING.format("batch_size, num_choices, sequence_length")
1204
+ )
1205
+ @add_code_sample_docstrings(
1206
+ checkpoint=_CHECKPOINT_FOR_DOC,
1207
+ output_type=TFMultipleChoiceModelOutput,
1208
+ config_class=_CONFIG_FOR_DOC,
1209
+ )
1210
+ def call(
1211
+ self,
1212
+ input_ids: TFModelInputType | None = None,
1213
+ attention_mask: np.ndarray | tf.Tensor | None = None,
1214
+ token_type_ids: np.ndarray | tf.Tensor | None = None,
1215
+ position_ids: np.ndarray | tf.Tensor | None = None,
1216
+ head_mask: np.ndarray | tf.Tensor | None = None,
1217
+ inputs_embeds: tf.Tensor | None = None,
1218
+ output_attentions: Optional[bool] = None,
1219
+ output_hidden_states: Optional[bool] = None,
1220
+ return_dict: Optional[bool] = None,
1221
+ labels: tf.Tensor | None = None,
1222
+ training: Optional[bool] = False,
1223
+ ) -> Union[Tuple, TFMultipleChoiceModelOutput]:
1224
+ r"""
1225
+ labels (`tf.Tensor` of shape `(batch_size,)`, *optional*):
1226
+ Labels for computing the multiple choice classification loss. Indices should be in `[0, ..., num_choices]`
1227
+ where `num_choices` is the size of the second dimension of the input tensors. (See `input_ids` above)
1228
+ """
1229
+ if input_ids is not None:
1230
+ num_choices = shape_list(input_ids)[1]
1231
+ seq_length = shape_list(input_ids)[2]
1232
+ else:
1233
+ num_choices = shape_list(inputs_embeds)[1]
1234
+ seq_length = shape_list(inputs_embeds)[2]
1235
+
1236
+ flat_input_ids = tf.reshape(input_ids, (-1, seq_length)) if input_ids is not None else None
1237
+ flat_attention_mask = tf.reshape(attention_mask, (-1, seq_length)) if attention_mask is not None else None
1238
+ flat_token_type_ids = tf.reshape(token_type_ids, (-1, seq_length)) if token_type_ids is not None else None
1239
+ flat_position_ids = tf.reshape(position_ids, (-1, seq_length)) if position_ids is not None else None
1240
+ flat_inputs_embeds = (
1241
+ tf.reshape(inputs_embeds, (-1, seq_length, shape_list(inputs_embeds)[3]))
1242
+ if inputs_embeds is not None
1243
+ else None
1244
+ )
1245
+ outputs = self.convbert(
1246
+ flat_input_ids,
1247
+ flat_attention_mask,
1248
+ flat_token_type_ids,
1249
+ flat_position_ids,
1250
+ head_mask,
1251
+ flat_inputs_embeds,
1252
+ output_attentions,
1253
+ output_hidden_states,
1254
+ return_dict=return_dict,
1255
+ training=training,
1256
+ )
1257
+ logits = self.sequence_summary(outputs[0], training=training)
1258
+ logits = self.classifier(logits)
1259
+ reshaped_logits = tf.reshape(logits, (-1, num_choices))
1260
+ loss = None if labels is None else self.hf_compute_loss(labels, reshaped_logits)
1261
+
1262
+ if not return_dict:
1263
+ output = (reshaped_logits,) + outputs[1:]
1264
+
1265
+ return ((loss,) + output) if loss is not None else output
1266
+
1267
+ return TFMultipleChoiceModelOutput(
1268
+ loss=loss,
1269
+ logits=reshaped_logits,
1270
+ hidden_states=outputs.hidden_states,
1271
+ attentions=outputs.attentions,
1272
+ )
1273
+
1274
+ def build(self, input_shape=None):
1275
+ if self.built:
1276
+ return
1277
+ self.built = True
1278
+ if getattr(self, "convbert", None) is not None:
1279
+ with tf.name_scope(self.convbert.name):
1280
+ self.convbert.build(None)
1281
+ if getattr(self, "sequence_summary", None) is not None:
1282
+ with tf.name_scope(self.sequence_summary.name):
1283
+ self.sequence_summary.build(None)
1284
+ if getattr(self, "classifier", None) is not None:
1285
+ with tf.name_scope(self.classifier.name):
1286
+ self.classifier.build([None, None, self.config.hidden_size])
1287
+
1288
+
1289
+ @add_start_docstrings(
1290
+ """
1291
+ ConvBERT Model with a token classification head on top (a linear layer on top of the hidden-states output) e.g. for
1292
+ Named-Entity-Recognition (NER) tasks.
1293
+ """,
1294
+ CONVBERT_START_DOCSTRING,
1295
+ )
1296
+ class TFConvBertForTokenClassification(TFConvBertPreTrainedModel, TFTokenClassificationLoss):
1297
+ def __init__(self, config, *inputs, **kwargs):
1298
+ super().__init__(config, *inputs, **kwargs)
1299
+
1300
+ self.num_labels = config.num_labels
1301
+ self.convbert = TFConvBertMainLayer(config, name="convbert")
1302
+ classifier_dropout = (
1303
+ config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob
1304
+ )
1305
+ self.dropout = tf.keras.layers.Dropout(classifier_dropout)
1306
+ self.classifier = tf.keras.layers.Dense(
1307
+ config.num_labels, kernel_initializer=get_initializer(config.initializer_range), name="classifier"
1308
+ )
1309
+ self.config = config
1310
+
1311
+ @unpack_inputs
1312
+ @add_start_docstrings_to_model_forward(CONVBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
1313
+ @add_code_sample_docstrings(
1314
+ checkpoint=_CHECKPOINT_FOR_DOC,
1315
+ output_type=TFTokenClassifierOutput,
1316
+ config_class=_CONFIG_FOR_DOC,
1317
+ )
1318
+ def call(
1319
+ self,
1320
+ input_ids: TFModelInputType | None = None,
1321
+ attention_mask: np.ndarray | tf.Tensor | None = None,
1322
+ token_type_ids: np.ndarray | tf.Tensor | None = None,
1323
+ position_ids: np.ndarray | tf.Tensor | None = None,
1324
+ head_mask: np.ndarray | tf.Tensor | None = None,
1325
+ inputs_embeds: tf.Tensor | None = None,
1326
+ output_attentions: Optional[bool] = None,
1327
+ output_hidden_states: Optional[bool] = None,
1328
+ return_dict: Optional[bool] = None,
1329
+ labels: tf.Tensor | None = None,
1330
+ training: Optional[bool] = False,
1331
+ ) -> Union[Tuple, TFTokenClassifierOutput]:
1332
+ r"""
1333
+ labels (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
1334
+ Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`.
1335
+ """
1336
+ outputs = self.convbert(
1337
+ input_ids,
1338
+ attention_mask=attention_mask,
1339
+ token_type_ids=token_type_ids,
1340
+ position_ids=position_ids,
1341
+ head_mask=head_mask,
1342
+ inputs_embeds=inputs_embeds,
1343
+ output_attentions=output_attentions,
1344
+ output_hidden_states=output_hidden_states,
1345
+ return_dict=return_dict,
1346
+ training=training,
1347
+ )
1348
+ sequence_output = outputs[0]
1349
+ sequence_output = self.dropout(sequence_output, training=training)
1350
+ logits = self.classifier(sequence_output)
1351
+ loss = None if labels is None else self.hf_compute_loss(labels, logits)
1352
+
1353
+ if not return_dict:
1354
+ output = (logits,) + outputs[1:]
1355
+ return ((loss,) + output) if loss is not None else output
1356
+
1357
+ return TFTokenClassifierOutput(
1358
+ loss=loss,
1359
+ logits=logits,
1360
+ hidden_states=outputs.hidden_states,
1361
+ attentions=outputs.attentions,
1362
+ )
1363
+
1364
+ def build(self, input_shape=None):
1365
+ if self.built:
1366
+ return
1367
+ self.built = True
1368
+ if getattr(self, "convbert", None) is not None:
1369
+ with tf.name_scope(self.convbert.name):
1370
+ self.convbert.build(None)
1371
+ if getattr(self, "classifier", None) is not None:
1372
+ with tf.name_scope(self.classifier.name):
1373
+ self.classifier.build([None, None, self.config.hidden_size])
1374
+
1375
+
1376
+ @add_start_docstrings(
1377
+ """
1378
+ ConvBERT Model with a span classification head on top for extractive question-answering tasks like SQuAD (a linear
1379
+ layer on top of the hidden-states output to compute `span start logits` and `span end logits`).
1380
+ """,
1381
+ CONVBERT_START_DOCSTRING,
1382
+ )
1383
+ class TFConvBertForQuestionAnswering(TFConvBertPreTrainedModel, TFQuestionAnsweringLoss):
1384
+ def __init__(self, config, *inputs, **kwargs):
1385
+ super().__init__(config, *inputs, **kwargs)
1386
+
1387
+ self.num_labels = config.num_labels
1388
+ self.convbert = TFConvBertMainLayer(config, name="convbert")
1389
+ self.qa_outputs = tf.keras.layers.Dense(
1390
+ config.num_labels, kernel_initializer=get_initializer(config.initializer_range), name="qa_outputs"
1391
+ )
1392
+ self.config = config
1393
+
1394
+ @unpack_inputs
1395
+ @add_start_docstrings_to_model_forward(CONVBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
1396
+ @add_code_sample_docstrings(
1397
+ checkpoint=_CHECKPOINT_FOR_DOC,
1398
+ output_type=TFQuestionAnsweringModelOutput,
1399
+ config_class=_CONFIG_FOR_DOC,
1400
+ )
1401
+ def call(
1402
+ self,
1403
+ input_ids: TFModelInputType | None = None,
1404
+ attention_mask: np.ndarray | tf.Tensor | None = None,
1405
+ token_type_ids: np.ndarray | tf.Tensor | None = None,
1406
+ position_ids: np.ndarray | tf.Tensor | None = None,
1407
+ head_mask: np.ndarray | tf.Tensor | None = None,
1408
+ inputs_embeds: tf.Tensor | None = None,
1409
+ output_attentions: Optional[bool] = None,
1410
+ output_hidden_states: Optional[bool] = None,
1411
+ return_dict: Optional[bool] = None,
1412
+ start_positions: tf.Tensor | None = None,
1413
+ end_positions: tf.Tensor | None = None,
1414
+ training: Optional[bool] = False,
1415
+ ) -> Union[Tuple, TFQuestionAnsweringModelOutput]:
1416
+ r"""
1417
+ start_positions (`tf.Tensor` of shape `(batch_size,)`, *optional*):
1418
+ Labels for position (index) of the start of the labelled span for computing the token classification loss.
1419
+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
1420
+ are not taken into account for computing the loss.
1421
+ end_positions (`tf.Tensor` of shape `(batch_size,)`, *optional*):
1422
+ Labels for position (index) of the end of the labelled span for computing the token classification loss.
1423
+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
1424
+ are not taken into account for computing the loss.
1425
+ """
1426
+ outputs = self.convbert(
1427
+ input_ids,
1428
+ attention_mask=attention_mask,
1429
+ token_type_ids=token_type_ids,
1430
+ position_ids=position_ids,
1431
+ head_mask=head_mask,
1432
+ inputs_embeds=inputs_embeds,
1433
+ output_attentions=output_attentions,
1434
+ output_hidden_states=output_hidden_states,
1435
+ return_dict=return_dict,
1436
+ training=training,
1437
+ )
1438
+ sequence_output = outputs[0]
1439
+ logits = self.qa_outputs(sequence_output)
1440
+ start_logits, end_logits = tf.split(logits, 2, axis=-1)
1441
+ start_logits = tf.squeeze(start_logits, axis=-1)
1442
+ end_logits = tf.squeeze(end_logits, axis=-1)
1443
+ loss = None
1444
+
1445
+ if start_positions is not None and end_positions is not None:
1446
+ labels = {"start_position": start_positions}
1447
+ labels["end_position"] = end_positions
1448
+ loss = self.hf_compute_loss(labels, (start_logits, end_logits))
1449
+
1450
+ if not return_dict:
1451
+ output = (start_logits, end_logits) + outputs[1:]
1452
+ return ((loss,) + output) if loss is not None else output
1453
+
1454
+ return TFQuestionAnsweringModelOutput(
1455
+ loss=loss,
1456
+ start_logits=start_logits,
1457
+ end_logits=end_logits,
1458
+ hidden_states=outputs.hidden_states,
1459
+ attentions=outputs.attentions,
1460
+ )
1461
+
1462
+ def build(self, input_shape=None):
1463
+ if self.built:
1464
+ return
1465
+ self.built = True
1466
+ if getattr(self, "convbert", None) is not None:
1467
+ with tf.name_scope(self.convbert.name):
1468
+ self.convbert.build(None)
1469
+ if getattr(self, "qa_outputs", None) is not None:
1470
+ with tf.name_scope(self.qa_outputs.name):
1471
+ self.qa_outputs.build([None, None, self.config.hidden_size])
pllava/lib/python3.10/site-packages/transformers/models/convbert/tokenization_convbert.py ADDED
@@ -0,0 +1,529 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 ConvBERT."""
16
+ import collections
17
+ import os
18
+ import unicodedata
19
+ from typing import List, Optional, Tuple
20
+
21
+ from ...tokenization_utils import PreTrainedTokenizer, _is_control, _is_punctuation, _is_whitespace
22
+ from ...utils import logging
23
+
24
+
25
+ logger = logging.get_logger(__name__)
26
+
27
+ VOCAB_FILES_NAMES = {"vocab_file": "vocab.txt"}
28
+
29
+ PRETRAINED_VOCAB_FILES_MAP = {
30
+ "vocab_file": {
31
+ "YituTech/conv-bert-base": "https://huggingface.co/YituTech/conv-bert-base/resolve/main/vocab.txt",
32
+ "YituTech/conv-bert-medium-small": (
33
+ "https://huggingface.co/YituTech/conv-bert-medium-small/resolve/main/vocab.txt"
34
+ ),
35
+ "YituTech/conv-bert-small": "https://huggingface.co/YituTech/conv-bert-small/resolve/main/vocab.txt",
36
+ }
37
+ }
38
+
39
+ PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES = {
40
+ "YituTech/conv-bert-base": 512,
41
+ "YituTech/conv-bert-medium-small": 512,
42
+ "YituTech/conv-bert-small": 512,
43
+ }
44
+
45
+
46
+ PRETRAINED_INIT_CONFIGURATION = {
47
+ "YituTech/conv-bert-base": {"do_lower_case": True},
48
+ "YituTech/conv-bert-medium-small": {"do_lower_case": True},
49
+ "YituTech/conv-bert-small": {"do_lower_case": True},
50
+ }
51
+
52
+
53
+ # Copied from transformers.models.bert.tokenization_bert.load_vocab
54
+ def load_vocab(vocab_file):
55
+ """Loads a vocabulary file into a dictionary."""
56
+ vocab = collections.OrderedDict()
57
+ with open(vocab_file, "r", encoding="utf-8") as reader:
58
+ tokens = reader.readlines()
59
+ for index, token in enumerate(tokens):
60
+ token = token.rstrip("\n")
61
+ vocab[token] = index
62
+ return vocab
63
+
64
+
65
+ # Copied from transformers.models.bert.tokenization_bert.whitespace_tokenize
66
+ def whitespace_tokenize(text):
67
+ """Runs basic whitespace cleaning and splitting on a piece of text."""
68
+ text = text.strip()
69
+ if not text:
70
+ return []
71
+ tokens = text.split()
72
+ return tokens
73
+
74
+
75
+ # Copied from transformers.models.bert.tokenization_bert.BertTokenizer with bert-base-cased->YituTech/conv-bert-base, ConvBertTokenizer->BertTokenizer, BERT->ConvBERT
76
+ class ConvBertTokenizer(PreTrainedTokenizer):
77
+ r"""
78
+ Construct a ConvBERT tokenizer. Based on WordPiece.
79
+
80
+ This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to
81
+ this superclass for more information regarding those methods.
82
+
83
+ Args:
84
+ vocab_file (`str`):
85
+ File containing the vocabulary.
86
+ do_lower_case (`bool`, *optional*, defaults to `True`):
87
+ Whether or not to lowercase the input when tokenizing.
88
+ do_basic_tokenize (`bool`, *optional*, defaults to `True`):
89
+ Whether or not to do basic tokenization before WordPiece.
90
+ never_split (`Iterable`, *optional*):
91
+ Collection of tokens which will never be split during tokenization. Only has an effect when
92
+ `do_basic_tokenize=True`
93
+ unk_token (`str`, *optional*, defaults to `"[UNK]"`):
94
+ The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
95
+ token instead.
96
+ sep_token (`str`, *optional*, defaults to `"[SEP]"`):
97
+ The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
98
+ sequence classification or for a text and a question for question answering. It is also used as the last
99
+ token of a sequence built with special tokens.
100
+ pad_token (`str`, *optional*, defaults to `"[PAD]"`):
101
+ The token used for padding, for example when batching sequences of different lengths.
102
+ cls_token (`str`, *optional*, defaults to `"[CLS]"`):
103
+ The classifier token which is used when doing sequence classification (classification of the whole sequence
104
+ instead of per-token classification). It is the first token of the sequence when built with special tokens.
105
+ mask_token (`str`, *optional*, defaults to `"[MASK]"`):
106
+ The token used for masking values. This is the token used when training this model with masked language
107
+ modeling. This is the token which the model will try to predict.
108
+ tokenize_chinese_chars (`bool`, *optional*, defaults to `True`):
109
+ Whether or not to tokenize Chinese characters.
110
+
111
+ This should likely be deactivated for Japanese (see this
112
+ [issue](https://github.com/huggingface/transformers/issues/328)).
113
+ strip_accents (`bool`, *optional*):
114
+ Whether or not to strip all accents. If this option is not specified, then it will be determined by the
115
+ value for `lowercase` (as in the original ConvBERT).
116
+ """
117
+
118
+ vocab_files_names = VOCAB_FILES_NAMES
119
+ pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP
120
+ pretrained_init_configuration = PRETRAINED_INIT_CONFIGURATION
121
+ max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
122
+
123
+ def __init__(
124
+ self,
125
+ vocab_file,
126
+ do_lower_case=True,
127
+ do_basic_tokenize=True,
128
+ never_split=None,
129
+ unk_token="[UNK]",
130
+ sep_token="[SEP]",
131
+ pad_token="[PAD]",
132
+ cls_token="[CLS]",
133
+ mask_token="[MASK]",
134
+ tokenize_chinese_chars=True,
135
+ strip_accents=None,
136
+ **kwargs,
137
+ ):
138
+ if not os.path.isfile(vocab_file):
139
+ raise ValueError(
140
+ f"Can't find a vocabulary file at path '{vocab_file}'. To load the vocabulary from a Google pretrained"
141
+ " model use `tokenizer = BertTokenizer.from_pretrained(PRETRAINED_MODEL_NAME)`"
142
+ )
143
+ self.vocab = load_vocab(vocab_file)
144
+ self.ids_to_tokens = collections.OrderedDict([(ids, tok) for tok, ids in self.vocab.items()])
145
+ self.do_basic_tokenize = do_basic_tokenize
146
+ if do_basic_tokenize:
147
+ self.basic_tokenizer = BasicTokenizer(
148
+ do_lower_case=do_lower_case,
149
+ never_split=never_split,
150
+ tokenize_chinese_chars=tokenize_chinese_chars,
151
+ strip_accents=strip_accents,
152
+ )
153
+
154
+ self.wordpiece_tokenizer = WordpieceTokenizer(vocab=self.vocab, unk_token=str(unk_token))
155
+
156
+ super().__init__(
157
+ do_lower_case=do_lower_case,
158
+ do_basic_tokenize=do_basic_tokenize,
159
+ never_split=never_split,
160
+ unk_token=unk_token,
161
+ sep_token=sep_token,
162
+ pad_token=pad_token,
163
+ cls_token=cls_token,
164
+ mask_token=mask_token,
165
+ tokenize_chinese_chars=tokenize_chinese_chars,
166
+ strip_accents=strip_accents,
167
+ **kwargs,
168
+ )
169
+
170
+ @property
171
+ def do_lower_case(self):
172
+ return self.basic_tokenizer.do_lower_case
173
+
174
+ @property
175
+ def vocab_size(self):
176
+ return len(self.vocab)
177
+
178
+ def get_vocab(self):
179
+ return dict(self.vocab, **self.added_tokens_encoder)
180
+
181
+ def _tokenize(self, text, split_special_tokens=False):
182
+ split_tokens = []
183
+ if self.do_basic_tokenize:
184
+ for token in self.basic_tokenizer.tokenize(
185
+ text, never_split=self.all_special_tokens if not split_special_tokens else None
186
+ ):
187
+ # If the token is part of the never_split set
188
+ if token in self.basic_tokenizer.never_split:
189
+ split_tokens.append(token)
190
+ else:
191
+ split_tokens += self.wordpiece_tokenizer.tokenize(token)
192
+ else:
193
+ split_tokens = self.wordpiece_tokenizer.tokenize(text)
194
+ return split_tokens
195
+
196
+ def _convert_token_to_id(self, token):
197
+ """Converts a token (str) in an id using the vocab."""
198
+ return self.vocab.get(token, self.vocab.get(self.unk_token))
199
+
200
+ def _convert_id_to_token(self, index):
201
+ """Converts an index (integer) in a token (str) using the vocab."""
202
+ return self.ids_to_tokens.get(index, self.unk_token)
203
+
204
+ def convert_tokens_to_string(self, tokens):
205
+ """Converts a sequence of tokens (string) in a single string."""
206
+ out_string = " ".join(tokens).replace(" ##", "").strip()
207
+ return out_string
208
+
209
+ def build_inputs_with_special_tokens(
210
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
211
+ ) -> List[int]:
212
+ """
213
+ Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
214
+ adding special tokens. A ConvBERT sequence has the following format:
215
+
216
+ - single sequence: `[CLS] X [SEP]`
217
+ - pair of sequences: `[CLS] A [SEP] B [SEP]`
218
+
219
+ Args:
220
+ token_ids_0 (`List[int]`):
221
+ List of IDs to which the special tokens will be added.
222
+ token_ids_1 (`List[int]`, *optional*):
223
+ Optional second list of IDs for sequence pairs.
224
+
225
+ Returns:
226
+ `List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
227
+ """
228
+ if token_ids_1 is None:
229
+ return [self.cls_token_id] + token_ids_0 + [self.sep_token_id]
230
+ cls = [self.cls_token_id]
231
+ sep = [self.sep_token_id]
232
+ return cls + token_ids_0 + sep + token_ids_1 + sep
233
+
234
+ def get_special_tokens_mask(
235
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None, already_has_special_tokens: bool = False
236
+ ) -> List[int]:
237
+ """
238
+ Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
239
+ special tokens using the tokenizer `prepare_for_model` method.
240
+
241
+ Args:
242
+ token_ids_0 (`List[int]`):
243
+ List of IDs.
244
+ token_ids_1 (`List[int]`, *optional*):
245
+ Optional second list of IDs for sequence pairs.
246
+ already_has_special_tokens (`bool`, *optional*, defaults to `False`):
247
+ Whether or not the token list is already formatted with special tokens for the model.
248
+
249
+ Returns:
250
+ `List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
251
+ """
252
+
253
+ if already_has_special_tokens:
254
+ return super().get_special_tokens_mask(
255
+ token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
256
+ )
257
+
258
+ if token_ids_1 is not None:
259
+ return [1] + ([0] * len(token_ids_0)) + [1] + ([0] * len(token_ids_1)) + [1]
260
+ return [1] + ([0] * len(token_ids_0)) + [1]
261
+
262
+ def create_token_type_ids_from_sequences(
263
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
264
+ ) -> List[int]:
265
+ """
266
+ Create a mask from the two sequences passed to be used in a sequence-pair classification task. A ConvBERT sequence
267
+ pair mask has the following format:
268
+
269
+ ```
270
+ 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1
271
+ | first sequence | second sequence |
272
+ ```
273
+
274
+ If `token_ids_1` is `None`, this method only returns the first portion of the mask (0s).
275
+
276
+ Args:
277
+ token_ids_0 (`List[int]`):
278
+ List of IDs.
279
+ token_ids_1 (`List[int]`, *optional*):
280
+ Optional second list of IDs for sequence pairs.
281
+
282
+ Returns:
283
+ `List[int]`: List of [token type IDs](../glossary#token-type-ids) according to the given sequence(s).
284
+ """
285
+ sep = [self.sep_token_id]
286
+ cls = [self.cls_token_id]
287
+ if token_ids_1 is None:
288
+ return len(cls + token_ids_0 + sep) * [0]
289
+ return len(cls + token_ids_0 + sep) * [0] + len(token_ids_1 + sep) * [1]
290
+
291
+ def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
292
+ index = 0
293
+ if os.path.isdir(save_directory):
294
+ vocab_file = os.path.join(
295
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
296
+ )
297
+ else:
298
+ vocab_file = (filename_prefix + "-" if filename_prefix else "") + save_directory
299
+ with open(vocab_file, "w", encoding="utf-8") as writer:
300
+ for token, token_index in sorted(self.vocab.items(), key=lambda kv: kv[1]):
301
+ if index != token_index:
302
+ logger.warning(
303
+ f"Saving vocabulary to {vocab_file}: vocabulary indices are not consecutive."
304
+ " Please check that the vocabulary is not corrupted!"
305
+ )
306
+ index = token_index
307
+ writer.write(token + "\n")
308
+ index += 1
309
+ return (vocab_file,)
310
+
311
+
312
+ # Copied from transformers.models.bert.tokenization_bert.BasicTokenizer
313
+ class BasicTokenizer(object):
314
+ """
315
+ Constructs a BasicTokenizer that will run basic tokenization (punctuation splitting, lower casing, etc.).
316
+
317
+ Args:
318
+ do_lower_case (`bool`, *optional*, defaults to `True`):
319
+ Whether or not to lowercase the input when tokenizing.
320
+ never_split (`Iterable`, *optional*):
321
+ Collection of tokens which will never be split during tokenization. Only has an effect when
322
+ `do_basic_tokenize=True`
323
+ tokenize_chinese_chars (`bool`, *optional*, defaults to `True`):
324
+ Whether or not to tokenize Chinese characters.
325
+
326
+ This should likely be deactivated for Japanese (see this
327
+ [issue](https://github.com/huggingface/transformers/issues/328)).
328
+ strip_accents (`bool`, *optional*):
329
+ Whether or not to strip all accents. If this option is not specified, then it will be determined by the
330
+ value for `lowercase` (as in the original BERT).
331
+ do_split_on_punc (`bool`, *optional*, defaults to `True`):
332
+ In some instances we want to skip the basic punctuation splitting so that later tokenization can capture
333
+ the full context of the words, such as contractions.
334
+ """
335
+
336
+ def __init__(
337
+ self,
338
+ do_lower_case=True,
339
+ never_split=None,
340
+ tokenize_chinese_chars=True,
341
+ strip_accents=None,
342
+ do_split_on_punc=True,
343
+ ):
344
+ if never_split is None:
345
+ never_split = []
346
+ self.do_lower_case = do_lower_case
347
+ self.never_split = set(never_split)
348
+ self.tokenize_chinese_chars = tokenize_chinese_chars
349
+ self.strip_accents = strip_accents
350
+ self.do_split_on_punc = do_split_on_punc
351
+
352
+ def tokenize(self, text, never_split=None):
353
+ """
354
+ Basic Tokenization of a piece of text. For sub-word tokenization, see WordPieceTokenizer.
355
+
356
+ Args:
357
+ never_split (`List[str]`, *optional*)
358
+ Kept for backward compatibility purposes. Now implemented directly at the base class level (see
359
+ [`PreTrainedTokenizer.tokenize`]) List of token not to split.
360
+ """
361
+ # union() returns a new set by concatenating the two sets.
362
+ never_split = self.never_split.union(set(never_split)) if never_split else self.never_split
363
+ text = self._clean_text(text)
364
+
365
+ # This was added on November 1st, 2018 for the multilingual and Chinese
366
+ # models. This is also applied to the English models now, but it doesn't
367
+ # matter since the English models were not trained on any Chinese data
368
+ # and generally don't have any Chinese data in them (there are Chinese
369
+ # characters in the vocabulary because Wikipedia does have some Chinese
370
+ # words in the English Wikipedia.).
371
+ if self.tokenize_chinese_chars:
372
+ text = self._tokenize_chinese_chars(text)
373
+ # prevents treating the same character with different unicode codepoints as different characters
374
+ unicode_normalized_text = unicodedata.normalize("NFC", text)
375
+ orig_tokens = whitespace_tokenize(unicode_normalized_text)
376
+ split_tokens = []
377
+ for token in orig_tokens:
378
+ if token not in never_split:
379
+ if self.do_lower_case:
380
+ token = token.lower()
381
+ if self.strip_accents is not False:
382
+ token = self._run_strip_accents(token)
383
+ elif self.strip_accents:
384
+ token = self._run_strip_accents(token)
385
+ split_tokens.extend(self._run_split_on_punc(token, never_split))
386
+
387
+ output_tokens = whitespace_tokenize(" ".join(split_tokens))
388
+ return output_tokens
389
+
390
+ def _run_strip_accents(self, text):
391
+ """Strips accents from a piece of text."""
392
+ text = unicodedata.normalize("NFD", text)
393
+ output = []
394
+ for char in text:
395
+ cat = unicodedata.category(char)
396
+ if cat == "Mn":
397
+ continue
398
+ output.append(char)
399
+ return "".join(output)
400
+
401
+ def _run_split_on_punc(self, text, never_split=None):
402
+ """Splits punctuation on a piece of text."""
403
+ if not self.do_split_on_punc or (never_split is not None and text in never_split):
404
+ return [text]
405
+ chars = list(text)
406
+ i = 0
407
+ start_new_word = True
408
+ output = []
409
+ while i < len(chars):
410
+ char = chars[i]
411
+ if _is_punctuation(char):
412
+ output.append([char])
413
+ start_new_word = True
414
+ else:
415
+ if start_new_word:
416
+ output.append([])
417
+ start_new_word = False
418
+ output[-1].append(char)
419
+ i += 1
420
+
421
+ return ["".join(x) for x in output]
422
+
423
+ def _tokenize_chinese_chars(self, text):
424
+ """Adds whitespace around any CJK character."""
425
+ output = []
426
+ for char in text:
427
+ cp = ord(char)
428
+ if self._is_chinese_char(cp):
429
+ output.append(" ")
430
+ output.append(char)
431
+ output.append(" ")
432
+ else:
433
+ output.append(char)
434
+ return "".join(output)
435
+
436
+ def _is_chinese_char(self, cp):
437
+ """Checks whether CP is the codepoint of a CJK character."""
438
+ # This defines a "chinese character" as anything in the CJK Unicode block:
439
+ # https://en.wikipedia.org/wiki/CJK_Unified_Ideographs_(Unicode_block)
440
+ #
441
+ # Note that the CJK Unicode block is NOT all Japanese and Korean characters,
442
+ # despite its name. The modern Korean Hangul alphabet is a different block,
443
+ # as is Japanese Hiragana and Katakana. Those alphabets are used to write
444
+ # space-separated words, so they are not treated specially and handled
445
+ # like the all of the other languages.
446
+ if (
447
+ (cp >= 0x4E00 and cp <= 0x9FFF)
448
+ or (cp >= 0x3400 and cp <= 0x4DBF) #
449
+ or (cp >= 0x20000 and cp <= 0x2A6DF) #
450
+ or (cp >= 0x2A700 and cp <= 0x2B73F) #
451
+ or (cp >= 0x2B740 and cp <= 0x2B81F) #
452
+ or (cp >= 0x2B820 and cp <= 0x2CEAF) #
453
+ or (cp >= 0xF900 and cp <= 0xFAFF)
454
+ or (cp >= 0x2F800 and cp <= 0x2FA1F) #
455
+ ): #
456
+ return True
457
+
458
+ return False
459
+
460
+ def _clean_text(self, text):
461
+ """Performs invalid character removal and whitespace cleanup on text."""
462
+ output = []
463
+ for char in text:
464
+ cp = ord(char)
465
+ if cp == 0 or cp == 0xFFFD or _is_control(char):
466
+ continue
467
+ if _is_whitespace(char):
468
+ output.append(" ")
469
+ else:
470
+ output.append(char)
471
+ return "".join(output)
472
+
473
+
474
+ # Copied from transformers.models.bert.tokenization_bert.WordpieceTokenizer
475
+ class WordpieceTokenizer(object):
476
+ """Runs WordPiece tokenization."""
477
+
478
+ def __init__(self, vocab, unk_token, max_input_chars_per_word=100):
479
+ self.vocab = vocab
480
+ self.unk_token = unk_token
481
+ self.max_input_chars_per_word = max_input_chars_per_word
482
+
483
+ def tokenize(self, text):
484
+ """
485
+ Tokenizes a piece of text into its word pieces. This uses a greedy longest-match-first algorithm to perform
486
+ tokenization using the given vocabulary.
487
+
488
+ For example, `input = "unaffable"` wil return as output `["un", "##aff", "##able"]`.
489
+
490
+ Args:
491
+ text: A single token or whitespace separated tokens. This should have
492
+ already been passed through *BasicTokenizer*.
493
+
494
+ Returns:
495
+ A list of wordpiece tokens.
496
+ """
497
+
498
+ output_tokens = []
499
+ for token in whitespace_tokenize(text):
500
+ chars = list(token)
501
+ if len(chars) > self.max_input_chars_per_word:
502
+ output_tokens.append(self.unk_token)
503
+ continue
504
+
505
+ is_bad = False
506
+ start = 0
507
+ sub_tokens = []
508
+ while start < len(chars):
509
+ end = len(chars)
510
+ cur_substr = None
511
+ while start < end:
512
+ substr = "".join(chars[start:end])
513
+ if start > 0:
514
+ substr = "##" + substr
515
+ if substr in self.vocab:
516
+ cur_substr = substr
517
+ break
518
+ end -= 1
519
+ if cur_substr is None:
520
+ is_bad = True
521
+ break
522
+ sub_tokens.append(cur_substr)
523
+ start = end
524
+
525
+ if is_bad:
526
+ output_tokens.append(self.unk_token)
527
+ else:
528
+ output_tokens.extend(sub_tokens)
529
+ return output_tokens
pllava/lib/python3.10/site-packages/transformers/models/convbert/tokenization_convbert_fast.py ADDED
@@ -0,0 +1,198 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 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 classes for ConvBERT."""
16
+ import json
17
+ from typing import List, Optional, Tuple
18
+
19
+ from tokenizers import normalizers
20
+
21
+ from ...tokenization_utils_fast import PreTrainedTokenizerFast
22
+ from ...utils import logging
23
+ from .tokenization_convbert import ConvBertTokenizer
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
+ "YituTech/conv-bert-base": "https://huggingface.co/YituTech/conv-bert-base/resolve/main/vocab.txt",
33
+ "YituTech/conv-bert-medium-small": (
34
+ "https://huggingface.co/YituTech/conv-bert-medium-small/resolve/main/vocab.txt"
35
+ ),
36
+ "YituTech/conv-bert-small": "https://huggingface.co/YituTech/conv-bert-small/resolve/main/vocab.txt",
37
+ }
38
+ }
39
+
40
+ PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES = {
41
+ "YituTech/conv-bert-base": 512,
42
+ "YituTech/conv-bert-medium-small": 512,
43
+ "YituTech/conv-bert-small": 512,
44
+ }
45
+
46
+
47
+ PRETRAINED_INIT_CONFIGURATION = {
48
+ "YituTech/conv-bert-base": {"do_lower_case": True},
49
+ "YituTech/conv-bert-medium-small": {"do_lower_case": True},
50
+ "YituTech/conv-bert-small": {"do_lower_case": True},
51
+ }
52
+
53
+
54
+ # Copied from transformers.models.bert.tokenization_bert_fast.BertTokenizerFast with bert-base-cased->YituTech/conv-bert-base, Bert->ConvBert, BERT->ConvBERT
55
+ class ConvBertTokenizerFast(PreTrainedTokenizerFast):
56
+ r"""
57
+ Construct a "fast" ConvBERT tokenizer (backed by HuggingFace's *tokenizers* library). Based on WordPiece.
58
+
59
+ This tokenizer inherits from [`PreTrainedTokenizerFast`] which contains most of the main methods. Users should
60
+ refer to this superclass for more information regarding those methods.
61
+
62
+ Args:
63
+ vocab_file (`str`):
64
+ File containing the vocabulary.
65
+ do_lower_case (`bool`, *optional*, defaults to `True`):
66
+ Whether or not to lowercase the input when tokenizing.
67
+ unk_token (`str`, *optional*, defaults to `"[UNK]"`):
68
+ The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
69
+ token instead.
70
+ sep_token (`str`, *optional*, defaults to `"[SEP]"`):
71
+ The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
72
+ sequence classification or for a text and a question for question answering. It is also used as the last
73
+ token of a sequence built with special tokens.
74
+ pad_token (`str`, *optional*, defaults to `"[PAD]"`):
75
+ The token used for padding, for example when batching sequences of different lengths.
76
+ cls_token (`str`, *optional*, defaults to `"[CLS]"`):
77
+ The classifier token which is used when doing sequence classification (classification of the whole sequence
78
+ instead of per-token classification). It is the first token of the sequence when built with special tokens.
79
+ mask_token (`str`, *optional*, defaults to `"[MASK]"`):
80
+ The token used for masking values. This is the token used when training this model with masked language
81
+ modeling. This is the token which the model will try to predict.
82
+ clean_text (`bool`, *optional*, defaults to `True`):
83
+ Whether or not to clean the text before tokenization by removing any control characters and replacing all
84
+ whitespaces by the classic one.
85
+ tokenize_chinese_chars (`bool`, *optional*, defaults to `True`):
86
+ Whether or not to tokenize Chinese characters. This should likely be deactivated for Japanese (see [this
87
+ issue](https://github.com/huggingface/transformers/issues/328)).
88
+ strip_accents (`bool`, *optional*):
89
+ Whether or not to strip all accents. If this option is not specified, then it will be determined by the
90
+ value for `lowercase` (as in the original ConvBERT).
91
+ wordpieces_prefix (`str`, *optional*, defaults to `"##"`):
92
+ The prefix for subwords.
93
+ """
94
+
95
+ vocab_files_names = VOCAB_FILES_NAMES
96
+ pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP
97
+ pretrained_init_configuration = PRETRAINED_INIT_CONFIGURATION
98
+ max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
99
+ slow_tokenizer_class = ConvBertTokenizer
100
+
101
+ def __init__(
102
+ self,
103
+ vocab_file=None,
104
+ tokenizer_file=None,
105
+ do_lower_case=True,
106
+ unk_token="[UNK]",
107
+ sep_token="[SEP]",
108
+ pad_token="[PAD]",
109
+ cls_token="[CLS]",
110
+ mask_token="[MASK]",
111
+ tokenize_chinese_chars=True,
112
+ strip_accents=None,
113
+ **kwargs,
114
+ ):
115
+ super().__init__(
116
+ vocab_file,
117
+ tokenizer_file=tokenizer_file,
118
+ do_lower_case=do_lower_case,
119
+ unk_token=unk_token,
120
+ sep_token=sep_token,
121
+ pad_token=pad_token,
122
+ cls_token=cls_token,
123
+ mask_token=mask_token,
124
+ tokenize_chinese_chars=tokenize_chinese_chars,
125
+ strip_accents=strip_accents,
126
+ **kwargs,
127
+ )
128
+
129
+ normalizer_state = json.loads(self.backend_tokenizer.normalizer.__getstate__())
130
+ if (
131
+ normalizer_state.get("lowercase", do_lower_case) != do_lower_case
132
+ or normalizer_state.get("strip_accents", strip_accents) != strip_accents
133
+ or normalizer_state.get("handle_chinese_chars", tokenize_chinese_chars) != tokenize_chinese_chars
134
+ ):
135
+ normalizer_class = getattr(normalizers, normalizer_state.pop("type"))
136
+ normalizer_state["lowercase"] = do_lower_case
137
+ normalizer_state["strip_accents"] = strip_accents
138
+ normalizer_state["handle_chinese_chars"] = tokenize_chinese_chars
139
+ self.backend_tokenizer.normalizer = normalizer_class(**normalizer_state)
140
+
141
+ self.do_lower_case = do_lower_case
142
+
143
+ def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None):
144
+ """
145
+ Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
146
+ adding special tokens. A ConvBERT sequence has the following format:
147
+
148
+ - single sequence: `[CLS] X [SEP]`
149
+ - pair of sequences: `[CLS] A [SEP] B [SEP]`
150
+
151
+ Args:
152
+ token_ids_0 (`List[int]`):
153
+ List of IDs to which the special tokens will be added.
154
+ token_ids_1 (`List[int]`, *optional*):
155
+ Optional second list of IDs for sequence pairs.
156
+
157
+ Returns:
158
+ `List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
159
+ """
160
+ output = [self.cls_token_id] + token_ids_0 + [self.sep_token_id]
161
+
162
+ if token_ids_1 is not None:
163
+ output += token_ids_1 + [self.sep_token_id]
164
+
165
+ return output
166
+
167
+ def create_token_type_ids_from_sequences(
168
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
169
+ ) -> List[int]:
170
+ """
171
+ Create a mask from the two sequences passed to be used in a sequence-pair classification task. A ConvBERT sequence
172
+ pair mask has the following format:
173
+
174
+ ```
175
+ 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1
176
+ | first sequence | second sequence |
177
+ ```
178
+
179
+ If `token_ids_1` is `None`, this method only returns the first portion of the mask (0s).
180
+
181
+ Args:
182
+ token_ids_0 (`List[int]`):
183
+ List of IDs.
184
+ token_ids_1 (`List[int]`, *optional*):
185
+ Optional second list of IDs for sequence pairs.
186
+
187
+ Returns:
188
+ `List[int]`: List of [token type IDs](../glossary#token-type-ids) according to the given sequence(s).
189
+ """
190
+ sep = [self.sep_token_id]
191
+ cls = [self.cls_token_id]
192
+ if token_ids_1 is None:
193
+ return len(cls + token_ids_0 + sep) * [0]
194
+ return len(cls + token_ids_0 + sep) * [0] + len(token_ids_1 + sep) * [1]
195
+
196
+ def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
197
+ files = self._tokenizer.model.save(save_directory, name=filename_prefix)
198
+ return tuple(files)
pllava/lib/python3.10/site-packages/transformers/models/electra/__init__.py ADDED
@@ -0,0 +1,168 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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_electra": ["ELECTRA_PRETRAINED_CONFIG_ARCHIVE_MAP", "ElectraConfig", "ElectraOnnxConfig"],
29
+ "tokenization_electra": ["ElectraTokenizer"],
30
+ }
31
+
32
+ try:
33
+ if not is_tokenizers_available():
34
+ raise OptionalDependencyNotAvailable()
35
+ except OptionalDependencyNotAvailable:
36
+ pass
37
+ else:
38
+ _import_structure["tokenization_electra_fast"] = ["ElectraTokenizerFast"]
39
+
40
+ try:
41
+ if not is_torch_available():
42
+ raise OptionalDependencyNotAvailable()
43
+ except OptionalDependencyNotAvailable:
44
+ pass
45
+ else:
46
+ _import_structure["modeling_electra"] = [
47
+ "ELECTRA_PRETRAINED_MODEL_ARCHIVE_LIST",
48
+ "ElectraForCausalLM",
49
+ "ElectraForMaskedLM",
50
+ "ElectraForMultipleChoice",
51
+ "ElectraForPreTraining",
52
+ "ElectraForQuestionAnswering",
53
+ "ElectraForSequenceClassification",
54
+ "ElectraForTokenClassification",
55
+ "ElectraModel",
56
+ "ElectraPreTrainedModel",
57
+ "load_tf_weights_in_electra",
58
+ ]
59
+
60
+ try:
61
+ if not is_tf_available():
62
+ raise OptionalDependencyNotAvailable()
63
+ except OptionalDependencyNotAvailable:
64
+ pass
65
+ else:
66
+ _import_structure["modeling_tf_electra"] = [
67
+ "TF_ELECTRA_PRETRAINED_MODEL_ARCHIVE_LIST",
68
+ "TFElectraForMaskedLM",
69
+ "TFElectraForMultipleChoice",
70
+ "TFElectraForPreTraining",
71
+ "TFElectraForQuestionAnswering",
72
+ "TFElectraForSequenceClassification",
73
+ "TFElectraForTokenClassification",
74
+ "TFElectraModel",
75
+ "TFElectraPreTrainedModel",
76
+ ]
77
+
78
+ try:
79
+ if not is_flax_available():
80
+ raise OptionalDependencyNotAvailable()
81
+ except OptionalDependencyNotAvailable:
82
+ pass
83
+ else:
84
+ _import_structure["modeling_flax_electra"] = [
85
+ "FlaxElectraForCausalLM",
86
+ "FlaxElectraForMaskedLM",
87
+ "FlaxElectraForMultipleChoice",
88
+ "FlaxElectraForPreTraining",
89
+ "FlaxElectraForQuestionAnswering",
90
+ "FlaxElectraForSequenceClassification",
91
+ "FlaxElectraForTokenClassification",
92
+ "FlaxElectraModel",
93
+ "FlaxElectraPreTrainedModel",
94
+ ]
95
+
96
+
97
+ if TYPE_CHECKING:
98
+ from .configuration_electra import ELECTRA_PRETRAINED_CONFIG_ARCHIVE_MAP, ElectraConfig, ElectraOnnxConfig
99
+ from .tokenization_electra import ElectraTokenizer
100
+
101
+ try:
102
+ if not is_tokenizers_available():
103
+ raise OptionalDependencyNotAvailable()
104
+ except OptionalDependencyNotAvailable:
105
+ pass
106
+ else:
107
+ from .tokenization_electra_fast import ElectraTokenizerFast
108
+
109
+ try:
110
+ if not is_torch_available():
111
+ raise OptionalDependencyNotAvailable()
112
+ except OptionalDependencyNotAvailable:
113
+ pass
114
+ else:
115
+ from .modeling_electra import (
116
+ ELECTRA_PRETRAINED_MODEL_ARCHIVE_LIST,
117
+ ElectraForCausalLM,
118
+ ElectraForMaskedLM,
119
+ ElectraForMultipleChoice,
120
+ ElectraForPreTraining,
121
+ ElectraForQuestionAnswering,
122
+ ElectraForSequenceClassification,
123
+ ElectraForTokenClassification,
124
+ ElectraModel,
125
+ ElectraPreTrainedModel,
126
+ load_tf_weights_in_electra,
127
+ )
128
+
129
+ try:
130
+ if not is_tf_available():
131
+ raise OptionalDependencyNotAvailable()
132
+ except OptionalDependencyNotAvailable:
133
+ pass
134
+ else:
135
+ from .modeling_tf_electra import (
136
+ TF_ELECTRA_PRETRAINED_MODEL_ARCHIVE_LIST,
137
+ TFElectraForMaskedLM,
138
+ TFElectraForMultipleChoice,
139
+ TFElectraForPreTraining,
140
+ TFElectraForQuestionAnswering,
141
+ TFElectraForSequenceClassification,
142
+ TFElectraForTokenClassification,
143
+ TFElectraModel,
144
+ TFElectraPreTrainedModel,
145
+ )
146
+
147
+ try:
148
+ if not is_flax_available():
149
+ raise OptionalDependencyNotAvailable()
150
+ except OptionalDependencyNotAvailable:
151
+ pass
152
+ else:
153
+ from .modeling_flax_electra import (
154
+ FlaxElectraForCausalLM,
155
+ FlaxElectraForMaskedLM,
156
+ FlaxElectraForMultipleChoice,
157
+ FlaxElectraForPreTraining,
158
+ FlaxElectraForQuestionAnswering,
159
+ FlaxElectraForSequenceClassification,
160
+ FlaxElectraForTokenClassification,
161
+ FlaxElectraModel,
162
+ FlaxElectraPreTrainedModel,
163
+ )
164
+
165
+ else:
166
+ import sys
167
+
168
+ sys.modules[__name__] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
pllava/lib/python3.10/site-packages/transformers/models/electra/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (2.52 kB). View file
 
pllava/lib/python3.10/site-packages/transformers/models/electra/__pycache__/configuration_electra.cpython-310.pyc ADDED
Binary file (8.91 kB). View file
 
pllava/lib/python3.10/site-packages/transformers/models/electra/__pycache__/convert_electra_original_tf_checkpoint_to_pytorch.cpython-310.pyc ADDED
Binary file (1.85 kB). View file
 
pllava/lib/python3.10/site-packages/transformers/models/electra/__pycache__/modeling_electra.cpython-310.pyc ADDED
Binary file (49.1 kB). View file
 
pllava/lib/python3.10/site-packages/transformers/models/electra/__pycache__/modeling_flax_electra.cpython-310.pyc ADDED
Binary file (40.6 kB). View file
 
pllava/lib/python3.10/site-packages/transformers/models/electra/__pycache__/modeling_tf_electra.cpython-310.pyc ADDED
Binary file (51.8 kB). View file
 
pllava/lib/python3.10/site-packages/transformers/models/electra/__pycache__/tokenization_electra.cpython-310.pyc ADDED
Binary file (18 kB). View file
 
pllava/lib/python3.10/site-packages/transformers/models/electra/__pycache__/tokenization_electra_fast.cpython-310.pyc ADDED
Binary file (8.23 kB). View file
 
pllava/lib/python3.10/site-packages/transformers/models/electra/configuration_electra.py ADDED
@@ -0,0 +1,199 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2018 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
+ """ ELECTRA model configuration"""
17
+
18
+ from collections import OrderedDict
19
+ from typing import Mapping
20
+
21
+ from ...configuration_utils import PretrainedConfig
22
+ from ...onnx import OnnxConfig
23
+ from ...utils import logging
24
+
25
+
26
+ logger = logging.get_logger(__name__)
27
+
28
+ ELECTRA_PRETRAINED_CONFIG_ARCHIVE_MAP = {
29
+ "google/electra-small-generator": "https://huggingface.co/google/electra-small-generator/resolve/main/config.json",
30
+ "google/electra-base-generator": "https://huggingface.co/google/electra-base-generator/resolve/main/config.json",
31
+ "google/electra-large-generator": "https://huggingface.co/google/electra-large-generator/resolve/main/config.json",
32
+ "google/electra-small-discriminator": (
33
+ "https://huggingface.co/google/electra-small-discriminator/resolve/main/config.json"
34
+ ),
35
+ "google/electra-base-discriminator": (
36
+ "https://huggingface.co/google/electra-base-discriminator/resolve/main/config.json"
37
+ ),
38
+ "google/electra-large-discriminator": (
39
+ "https://huggingface.co/google/electra-large-discriminator/resolve/main/config.json"
40
+ ),
41
+ }
42
+
43
+
44
+ class ElectraConfig(PretrainedConfig):
45
+ r"""
46
+ This is the configuration class to store the configuration of a [`ElectraModel`] or a [`TFElectraModel`]. It is
47
+ used to instantiate a ELECTRA model according to the specified arguments, defining the model architecture.
48
+ Instantiating a configuration with the defaults will yield a similar configuration to that of the ELECTRA
49
+ [google/electra-small-discriminator](https://huggingface.co/google/electra-small-discriminator) architecture.
50
+
51
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
52
+ documentation from [`PretrainedConfig`] for more information.
53
+
54
+
55
+ Args:
56
+ vocab_size (`int`, *optional*, defaults to 30522):
57
+ Vocabulary size of the ELECTRA model. Defines the number of different tokens that can be represented by the
58
+ `inputs_ids` passed when calling [`ElectraModel`] or [`TFElectraModel`].
59
+ embedding_size (`int`, *optional*, defaults to 128):
60
+ Dimensionality of the encoder layers and the pooler layer.
61
+ hidden_size (`int`, *optional*, defaults to 256):
62
+ Dimensionality of the encoder layers and the pooler layer.
63
+ num_hidden_layers (`int`, *optional*, defaults to 12):
64
+ Number of hidden layers in the Transformer encoder.
65
+ num_attention_heads (`int`, *optional*, defaults to 4):
66
+ Number of attention heads for each attention layer in the Transformer encoder.
67
+ intermediate_size (`int`, *optional*, defaults to 1024):
68
+ Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
69
+ hidden_act (`str` or `Callable`, *optional*, defaults to `"gelu"`):
70
+ The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
71
+ `"relu"`, `"silu"` and `"gelu_new"` are supported.
72
+ hidden_dropout_prob (`float`, *optional*, defaults to 0.1):
73
+ The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
74
+ attention_probs_dropout_prob (`float`, *optional*, defaults to 0.1):
75
+ The dropout ratio for the attention probabilities.
76
+ max_position_embeddings (`int`, *optional*, defaults to 512):
77
+ The maximum sequence length that this model might ever be used with. Typically set this to something large
78
+ just in case (e.g., 512 or 1024 or 2048).
79
+ type_vocab_size (`int`, *optional*, defaults to 2):
80
+ The vocabulary size of the `token_type_ids` passed when calling [`ElectraModel`] or [`TFElectraModel`].
81
+ initializer_range (`float`, *optional*, defaults to 0.02):
82
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
83
+ layer_norm_eps (`float`, *optional*, defaults to 1e-12):
84
+ The epsilon used by the layer normalization layers.
85
+ summary_type (`str`, *optional*, defaults to `"first"`):
86
+ Argument used when doing sequence summary. Used in the sequence classification and multiple choice models.
87
+
88
+ Has to be one of the following options:
89
+
90
+ - `"last"`: Take the last token hidden state (like XLNet).
91
+ - `"first"`: Take the first token hidden state (like BERT).
92
+ - `"mean"`: Take the mean of all tokens hidden states.
93
+ - `"cls_index"`: Supply a Tensor of classification token position (like GPT/GPT-2).
94
+ - `"attn"`: Not implemented now, use multi-head attention.
95
+ summary_use_proj (`bool`, *optional*, defaults to `True`):
96
+ Argument used when doing sequence summary. Used in the sequence classification and multiple choice models.
97
+
98
+ Whether or not to add a projection after the vector extraction.
99
+ summary_activation (`str`, *optional*):
100
+ Argument used when doing sequence summary. Used in the sequence classification and multiple choice models.
101
+
102
+ Pass `"gelu"` for a gelu activation to the output, any other value will result in no activation.
103
+ summary_last_dropout (`float`, *optional*, defaults to 0.0):
104
+ Argument used when doing sequence summary. Used in the sequence classification and multiple choice models.
105
+
106
+ The dropout ratio to be used after the projection and activation.
107
+ position_embedding_type (`str`, *optional*, defaults to `"absolute"`):
108
+ Type of position embedding. Choose one of `"absolute"`, `"relative_key"`, `"relative_key_query"`. For
109
+ positional embeddings use `"absolute"`. For more information on `"relative_key"`, please refer to
110
+ [Self-Attention with Relative Position Representations (Shaw et al.)](https://arxiv.org/abs/1803.02155).
111
+ For more information on `"relative_key_query"`, please refer to *Method 4* in [Improve Transformer Models
112
+ with Better Relative Position Embeddings (Huang et al.)](https://arxiv.org/abs/2009.13658).
113
+ use_cache (`bool`, *optional*, defaults to `True`):
114
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
115
+ relevant if `config.is_decoder=True`.
116
+ classifier_dropout (`float`, *optional*):
117
+ The dropout ratio for the classification head.
118
+
119
+ Examples:
120
+
121
+ ```python
122
+ >>> from transformers import ElectraConfig, ElectraModel
123
+
124
+ >>> # Initializing a ELECTRA electra-base-uncased style configuration
125
+ >>> configuration = ElectraConfig()
126
+
127
+ >>> # Initializing a model (with random weights) from the electra-base-uncased style configuration
128
+ >>> model = ElectraModel(configuration)
129
+
130
+ >>> # Accessing the model configuration
131
+ >>> configuration = model.config
132
+ ```"""
133
+
134
+ model_type = "electra"
135
+
136
+ def __init__(
137
+ self,
138
+ vocab_size=30522,
139
+ embedding_size=128,
140
+ hidden_size=256,
141
+ num_hidden_layers=12,
142
+ num_attention_heads=4,
143
+ intermediate_size=1024,
144
+ hidden_act="gelu",
145
+ hidden_dropout_prob=0.1,
146
+ attention_probs_dropout_prob=0.1,
147
+ max_position_embeddings=512,
148
+ type_vocab_size=2,
149
+ initializer_range=0.02,
150
+ layer_norm_eps=1e-12,
151
+ summary_type="first",
152
+ summary_use_proj=True,
153
+ summary_activation="gelu",
154
+ summary_last_dropout=0.1,
155
+ pad_token_id=0,
156
+ position_embedding_type="absolute",
157
+ use_cache=True,
158
+ classifier_dropout=None,
159
+ **kwargs,
160
+ ):
161
+ super().__init__(pad_token_id=pad_token_id, **kwargs)
162
+
163
+ self.vocab_size = vocab_size
164
+ self.embedding_size = embedding_size
165
+ self.hidden_size = hidden_size
166
+ self.num_hidden_layers = num_hidden_layers
167
+ self.num_attention_heads = num_attention_heads
168
+ self.intermediate_size = intermediate_size
169
+ self.hidden_act = hidden_act
170
+ self.hidden_dropout_prob = hidden_dropout_prob
171
+ self.attention_probs_dropout_prob = attention_probs_dropout_prob
172
+ self.max_position_embeddings = max_position_embeddings
173
+ self.type_vocab_size = type_vocab_size
174
+ self.initializer_range = initializer_range
175
+ self.layer_norm_eps = layer_norm_eps
176
+
177
+ self.summary_type = summary_type
178
+ self.summary_use_proj = summary_use_proj
179
+ self.summary_activation = summary_activation
180
+ self.summary_last_dropout = summary_last_dropout
181
+ self.position_embedding_type = position_embedding_type
182
+ self.use_cache = use_cache
183
+ self.classifier_dropout = classifier_dropout
184
+
185
+
186
+ class ElectraOnnxConfig(OnnxConfig):
187
+ @property
188
+ def inputs(self) -> Mapping[str, Mapping[int, str]]:
189
+ if self.task == "multiple-choice":
190
+ dynamic_axis = {0: "batch", 1: "choice", 2: "sequence"}
191
+ else:
192
+ dynamic_axis = {0: "batch", 1: "sequence"}
193
+ return OrderedDict(
194
+ [
195
+ ("input_ids", dynamic_axis),
196
+ ("attention_mask", dynamic_axis),
197
+ ("token_type_ids", dynamic_axis),
198
+ ]
199
+ )
pllava/lib/python3.10/site-packages/transformers/models/electra/modeling_electra.py ADDED
@@ -0,0 +1,1686 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2019 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
+ """PyTorch ELECTRA model."""
16
+
17
+ import math
18
+ import os
19
+ from dataclasses import dataclass
20
+ from typing import List, Optional, Tuple, Union
21
+
22
+ import torch
23
+ import torch.utils.checkpoint
24
+ from torch import nn
25
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
26
+
27
+ from ...activations import ACT2FN, get_activation
28
+ from ...modeling_outputs import (
29
+ BaseModelOutputWithCrossAttentions,
30
+ BaseModelOutputWithPastAndCrossAttentions,
31
+ CausalLMOutputWithCrossAttentions,
32
+ MaskedLMOutput,
33
+ MultipleChoiceModelOutput,
34
+ QuestionAnsweringModelOutput,
35
+ SequenceClassifierOutput,
36
+ TokenClassifierOutput,
37
+ )
38
+ from ...modeling_utils import PreTrainedModel, SequenceSummary
39
+ from ...pytorch_utils import apply_chunking_to_forward, find_pruneable_heads_and_indices, prune_linear_layer
40
+ from ...utils import (
41
+ ModelOutput,
42
+ add_code_sample_docstrings,
43
+ add_start_docstrings,
44
+ add_start_docstrings_to_model_forward,
45
+ logging,
46
+ replace_return_docstrings,
47
+ )
48
+ from .configuration_electra import ElectraConfig
49
+
50
+
51
+ logger = logging.get_logger(__name__)
52
+
53
+ _CHECKPOINT_FOR_DOC = "google/electra-small-discriminator"
54
+ _CONFIG_FOR_DOC = "ElectraConfig"
55
+
56
+ ELECTRA_PRETRAINED_MODEL_ARCHIVE_LIST = [
57
+ "google/electra-small-generator",
58
+ "google/electra-base-generator",
59
+ "google/electra-large-generator",
60
+ "google/electra-small-discriminator",
61
+ "google/electra-base-discriminator",
62
+ "google/electra-large-discriminator",
63
+ # See all ELECTRA models at https://huggingface.co/models?filter=electra
64
+ ]
65
+
66
+
67
+ def load_tf_weights_in_electra(model, config, tf_checkpoint_path, discriminator_or_generator="discriminator"):
68
+ """Load tf checkpoints in a pytorch model."""
69
+ try:
70
+ import re
71
+
72
+ import numpy as np
73
+ import tensorflow as tf
74
+ except ImportError:
75
+ logger.error(
76
+ "Loading a TensorFlow model in PyTorch, requires TensorFlow to be installed. Please see "
77
+ "https://www.tensorflow.org/install/ for installation instructions."
78
+ )
79
+ raise
80
+ tf_path = os.path.abspath(tf_checkpoint_path)
81
+ logger.info(f"Converting TensorFlow checkpoint from {tf_path}")
82
+ # Load weights from TF model
83
+ init_vars = tf.train.list_variables(tf_path)
84
+ names = []
85
+ arrays = []
86
+ for name, shape in init_vars:
87
+ logger.info(f"Loading TF weight {name} with shape {shape}")
88
+ array = tf.train.load_variable(tf_path, name)
89
+ names.append(name)
90
+ arrays.append(array)
91
+ for name, array in zip(names, arrays):
92
+ original_name: str = name
93
+
94
+ try:
95
+ if isinstance(model, ElectraForMaskedLM):
96
+ name = name.replace("electra/embeddings/", "generator/embeddings/")
97
+
98
+ if discriminator_or_generator == "generator":
99
+ name = name.replace("electra/", "discriminator/")
100
+ name = name.replace("generator/", "electra/")
101
+
102
+ name = name.replace("dense_1", "dense_prediction")
103
+ name = name.replace("generator_predictions/output_bias", "generator_lm_head/bias")
104
+
105
+ name = name.split("/")
106
+ # print(original_name, name)
107
+ # adam_v and adam_m are variables used in AdamWeightDecayOptimizer to calculated m and v
108
+ # which are not required for using pretrained model
109
+ if any(n in ["global_step", "temperature"] for n in name):
110
+ logger.info(f"Skipping {original_name}")
111
+ continue
112
+ pointer = model
113
+ for m_name in name:
114
+ if re.fullmatch(r"[A-Za-z]+_\d+", m_name):
115
+ scope_names = re.split(r"_(\d+)", m_name)
116
+ else:
117
+ scope_names = [m_name]
118
+ if scope_names[0] == "kernel" or scope_names[0] == "gamma":
119
+ pointer = getattr(pointer, "weight")
120
+ elif scope_names[0] == "output_bias" or scope_names[0] == "beta":
121
+ pointer = getattr(pointer, "bias")
122
+ elif scope_names[0] == "output_weights":
123
+ pointer = getattr(pointer, "weight")
124
+ elif scope_names[0] == "squad":
125
+ pointer = getattr(pointer, "classifier")
126
+ else:
127
+ pointer = getattr(pointer, scope_names[0])
128
+ if len(scope_names) >= 2:
129
+ num = int(scope_names[1])
130
+ pointer = pointer[num]
131
+ if m_name.endswith("_embeddings"):
132
+ pointer = getattr(pointer, "weight")
133
+ elif m_name == "kernel":
134
+ array = np.transpose(array)
135
+ try:
136
+ if pointer.shape != array.shape:
137
+ raise ValueError(f"Pointer shape {pointer.shape} and array shape {array.shape} mismatched")
138
+ except ValueError as e:
139
+ e.args += (pointer.shape, array.shape)
140
+ raise
141
+ print(f"Initialize PyTorch weight {name}", original_name)
142
+ pointer.data = torch.from_numpy(array)
143
+ except AttributeError as e:
144
+ print(f"Skipping {original_name}", name, e)
145
+ continue
146
+ return model
147
+
148
+
149
+ class ElectraEmbeddings(nn.Module):
150
+ """Construct the embeddings from word, position and token_type embeddings."""
151
+
152
+ def __init__(self, config):
153
+ super().__init__()
154
+ self.word_embeddings = nn.Embedding(config.vocab_size, config.embedding_size, padding_idx=config.pad_token_id)
155
+ self.position_embeddings = nn.Embedding(config.max_position_embeddings, config.embedding_size)
156
+ self.token_type_embeddings = nn.Embedding(config.type_vocab_size, config.embedding_size)
157
+
158
+ # self.LayerNorm is not snake-cased to stick with TensorFlow model variable name and be able to load
159
+ # any TensorFlow checkpoint file
160
+ self.LayerNorm = nn.LayerNorm(config.embedding_size, eps=config.layer_norm_eps)
161
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
162
+
163
+ # position_ids (1, len position emb) is contiguous in memory and exported when serialized
164
+ self.register_buffer(
165
+ "position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)), persistent=False
166
+ )
167
+ self.position_embedding_type = getattr(config, "position_embedding_type", "absolute")
168
+ self.register_buffer(
169
+ "token_type_ids", torch.zeros(self.position_ids.size(), dtype=torch.long), persistent=False
170
+ )
171
+
172
+ # Copied from transformers.models.bert.modeling_bert.BertEmbeddings.forward
173
+ def forward(
174
+ self,
175
+ input_ids: Optional[torch.LongTensor] = None,
176
+ token_type_ids: Optional[torch.LongTensor] = None,
177
+ position_ids: Optional[torch.LongTensor] = None,
178
+ inputs_embeds: Optional[torch.FloatTensor] = None,
179
+ past_key_values_length: int = 0,
180
+ ) -> torch.Tensor:
181
+ if input_ids is not None:
182
+ input_shape = input_ids.size()
183
+ else:
184
+ input_shape = inputs_embeds.size()[:-1]
185
+
186
+ seq_length = input_shape[1]
187
+
188
+ if position_ids is None:
189
+ position_ids = self.position_ids[:, past_key_values_length : seq_length + past_key_values_length]
190
+
191
+ # Setting the token_type_ids to the registered buffer in constructor where it is all zeros, which usually occurs
192
+ # when its auto-generated, registered buffer helps users when tracing the model without passing token_type_ids, solves
193
+ # issue #5664
194
+ if token_type_ids is None:
195
+ if hasattr(self, "token_type_ids"):
196
+ buffered_token_type_ids = self.token_type_ids[:, :seq_length]
197
+ buffered_token_type_ids_expanded = buffered_token_type_ids.expand(input_shape[0], seq_length)
198
+ token_type_ids = buffered_token_type_ids_expanded
199
+ else:
200
+ token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=self.position_ids.device)
201
+
202
+ if inputs_embeds is None:
203
+ inputs_embeds = self.word_embeddings(input_ids)
204
+ token_type_embeddings = self.token_type_embeddings(token_type_ids)
205
+
206
+ embeddings = inputs_embeds + token_type_embeddings
207
+ if self.position_embedding_type == "absolute":
208
+ position_embeddings = self.position_embeddings(position_ids)
209
+ embeddings += position_embeddings
210
+ embeddings = self.LayerNorm(embeddings)
211
+ embeddings = self.dropout(embeddings)
212
+ return embeddings
213
+
214
+
215
+ # Copied from transformers.models.bert.modeling_bert.BertSelfAttention with Bert->Electra
216
+ class ElectraSelfAttention(nn.Module):
217
+ def __init__(self, config, position_embedding_type=None):
218
+ super().__init__()
219
+ if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):
220
+ raise ValueError(
221
+ f"The hidden size ({config.hidden_size}) is not a multiple of the number of attention "
222
+ f"heads ({config.num_attention_heads})"
223
+ )
224
+
225
+ self.num_attention_heads = config.num_attention_heads
226
+ self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
227
+ self.all_head_size = self.num_attention_heads * self.attention_head_size
228
+
229
+ self.query = nn.Linear(config.hidden_size, self.all_head_size)
230
+ self.key = nn.Linear(config.hidden_size, self.all_head_size)
231
+ self.value = nn.Linear(config.hidden_size, self.all_head_size)
232
+
233
+ self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
234
+ self.position_embedding_type = position_embedding_type or getattr(
235
+ config, "position_embedding_type", "absolute"
236
+ )
237
+ if self.position_embedding_type == "relative_key" or self.position_embedding_type == "relative_key_query":
238
+ self.max_position_embeddings = config.max_position_embeddings
239
+ self.distance_embedding = nn.Embedding(2 * config.max_position_embeddings - 1, self.attention_head_size)
240
+
241
+ self.is_decoder = config.is_decoder
242
+
243
+ def transpose_for_scores(self, x: torch.Tensor) -> torch.Tensor:
244
+ new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.attention_head_size)
245
+ x = x.view(new_x_shape)
246
+ return x.permute(0, 2, 1, 3)
247
+
248
+ def forward(
249
+ self,
250
+ hidden_states: torch.Tensor,
251
+ attention_mask: Optional[torch.FloatTensor] = None,
252
+ head_mask: Optional[torch.FloatTensor] = None,
253
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
254
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
255
+ past_key_value: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
256
+ output_attentions: Optional[bool] = False,
257
+ ) -> Tuple[torch.Tensor]:
258
+ mixed_query_layer = self.query(hidden_states)
259
+
260
+ # If this is instantiated as a cross-attention module, the keys
261
+ # and values come from an encoder; the attention mask needs to be
262
+ # such that the encoder's padding tokens are not attended to.
263
+ is_cross_attention = encoder_hidden_states is not None
264
+
265
+ if is_cross_attention and past_key_value is not None:
266
+ # reuse k,v, cross_attentions
267
+ key_layer = past_key_value[0]
268
+ value_layer = past_key_value[1]
269
+ attention_mask = encoder_attention_mask
270
+ elif is_cross_attention:
271
+ key_layer = self.transpose_for_scores(self.key(encoder_hidden_states))
272
+ value_layer = self.transpose_for_scores(self.value(encoder_hidden_states))
273
+ attention_mask = encoder_attention_mask
274
+ elif past_key_value is not None:
275
+ key_layer = self.transpose_for_scores(self.key(hidden_states))
276
+ value_layer = self.transpose_for_scores(self.value(hidden_states))
277
+ key_layer = torch.cat([past_key_value[0], key_layer], dim=2)
278
+ value_layer = torch.cat([past_key_value[1], value_layer], dim=2)
279
+ else:
280
+ key_layer = self.transpose_for_scores(self.key(hidden_states))
281
+ value_layer = self.transpose_for_scores(self.value(hidden_states))
282
+
283
+ query_layer = self.transpose_for_scores(mixed_query_layer)
284
+
285
+ use_cache = past_key_value is not None
286
+ if self.is_decoder:
287
+ # if cross_attention save Tuple(torch.Tensor, torch.Tensor) of all cross attention key/value_states.
288
+ # Further calls to cross_attention layer can then reuse all cross-attention
289
+ # key/value_states (first "if" case)
290
+ # if uni-directional self-attention (decoder) save Tuple(torch.Tensor, torch.Tensor) of
291
+ # all previous decoder key/value_states. Further calls to uni-directional self-attention
292
+ # can concat previous decoder key/value_states to current projected key/value_states (third "elif" case)
293
+ # if encoder bi-directional self-attention `past_key_value` is always `None`
294
+ past_key_value = (key_layer, value_layer)
295
+
296
+ # Take the dot product between "query" and "key" to get the raw attention scores.
297
+ attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))
298
+
299
+ if self.position_embedding_type == "relative_key" or self.position_embedding_type == "relative_key_query":
300
+ query_length, key_length = query_layer.shape[2], key_layer.shape[2]
301
+ if use_cache:
302
+ position_ids_l = torch.tensor(key_length - 1, dtype=torch.long, device=hidden_states.device).view(
303
+ -1, 1
304
+ )
305
+ else:
306
+ position_ids_l = torch.arange(query_length, dtype=torch.long, device=hidden_states.device).view(-1, 1)
307
+ position_ids_r = torch.arange(key_length, dtype=torch.long, device=hidden_states.device).view(1, -1)
308
+ distance = position_ids_l - position_ids_r
309
+
310
+ positional_embedding = self.distance_embedding(distance + self.max_position_embeddings - 1)
311
+ positional_embedding = positional_embedding.to(dtype=query_layer.dtype) # fp16 compatibility
312
+
313
+ if self.position_embedding_type == "relative_key":
314
+ relative_position_scores = torch.einsum("bhld,lrd->bhlr", query_layer, positional_embedding)
315
+ attention_scores = attention_scores + relative_position_scores
316
+ elif self.position_embedding_type == "relative_key_query":
317
+ relative_position_scores_query = torch.einsum("bhld,lrd->bhlr", query_layer, positional_embedding)
318
+ relative_position_scores_key = torch.einsum("bhrd,lrd->bhlr", key_layer, positional_embedding)
319
+ attention_scores = attention_scores + relative_position_scores_query + relative_position_scores_key
320
+
321
+ attention_scores = attention_scores / math.sqrt(self.attention_head_size)
322
+ if attention_mask is not None:
323
+ # Apply the attention mask is (precomputed for all layers in ElectraModel forward() function)
324
+ attention_scores = attention_scores + attention_mask
325
+
326
+ # Normalize the attention scores to probabilities.
327
+ attention_probs = nn.functional.softmax(attention_scores, dim=-1)
328
+
329
+ # This is actually dropping out entire tokens to attend to, which might
330
+ # seem a bit unusual, but is taken from the original Transformer paper.
331
+ attention_probs = self.dropout(attention_probs)
332
+
333
+ # Mask heads if we want to
334
+ if head_mask is not None:
335
+ attention_probs = attention_probs * head_mask
336
+
337
+ context_layer = torch.matmul(attention_probs, value_layer)
338
+
339
+ context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
340
+ new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
341
+ context_layer = context_layer.view(new_context_layer_shape)
342
+
343
+ outputs = (context_layer, attention_probs) if output_attentions else (context_layer,)
344
+
345
+ if self.is_decoder:
346
+ outputs = outputs + (past_key_value,)
347
+ return outputs
348
+
349
+
350
+ # Copied from transformers.models.bert.modeling_bert.BertSelfOutput
351
+ class ElectraSelfOutput(nn.Module):
352
+ def __init__(self, config):
353
+ super().__init__()
354
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
355
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
356
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
357
+
358
+ def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
359
+ hidden_states = self.dense(hidden_states)
360
+ hidden_states = self.dropout(hidden_states)
361
+ hidden_states = self.LayerNorm(hidden_states + input_tensor)
362
+ return hidden_states
363
+
364
+
365
+ # Copied from transformers.models.bert.modeling_bert.BertAttention with Bert->Electra
366
+ class ElectraAttention(nn.Module):
367
+ def __init__(self, config, position_embedding_type=None):
368
+ super().__init__()
369
+ self.self = ElectraSelfAttention(config, position_embedding_type=position_embedding_type)
370
+ self.output = ElectraSelfOutput(config)
371
+ self.pruned_heads = set()
372
+
373
+ def prune_heads(self, heads):
374
+ if len(heads) == 0:
375
+ return
376
+ heads, index = find_pruneable_heads_and_indices(
377
+ heads, self.self.num_attention_heads, self.self.attention_head_size, self.pruned_heads
378
+ )
379
+
380
+ # Prune linear layers
381
+ self.self.query = prune_linear_layer(self.self.query, index)
382
+ self.self.key = prune_linear_layer(self.self.key, index)
383
+ self.self.value = prune_linear_layer(self.self.value, index)
384
+ self.output.dense = prune_linear_layer(self.output.dense, index, dim=1)
385
+
386
+ # Update hyper params and store pruned heads
387
+ self.self.num_attention_heads = self.self.num_attention_heads - len(heads)
388
+ self.self.all_head_size = self.self.attention_head_size * self.self.num_attention_heads
389
+ self.pruned_heads = self.pruned_heads.union(heads)
390
+
391
+ def forward(
392
+ self,
393
+ hidden_states: torch.Tensor,
394
+ attention_mask: Optional[torch.FloatTensor] = None,
395
+ head_mask: Optional[torch.FloatTensor] = None,
396
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
397
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
398
+ past_key_value: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
399
+ output_attentions: Optional[bool] = False,
400
+ ) -> Tuple[torch.Tensor]:
401
+ self_outputs = self.self(
402
+ hidden_states,
403
+ attention_mask,
404
+ head_mask,
405
+ encoder_hidden_states,
406
+ encoder_attention_mask,
407
+ past_key_value,
408
+ output_attentions,
409
+ )
410
+ attention_output = self.output(self_outputs[0], hidden_states)
411
+ outputs = (attention_output,) + self_outputs[1:] # add attentions if we output them
412
+ return outputs
413
+
414
+
415
+ # Copied from transformers.models.bert.modeling_bert.BertIntermediate
416
+ class ElectraIntermediate(nn.Module):
417
+ def __init__(self, config):
418
+ super().__init__()
419
+ self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
420
+ if isinstance(config.hidden_act, str):
421
+ self.intermediate_act_fn = ACT2FN[config.hidden_act]
422
+ else:
423
+ self.intermediate_act_fn = config.hidden_act
424
+
425
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
426
+ hidden_states = self.dense(hidden_states)
427
+ hidden_states = self.intermediate_act_fn(hidden_states)
428
+ return hidden_states
429
+
430
+
431
+ # Copied from transformers.models.bert.modeling_bert.BertOutput
432
+ class ElectraOutput(nn.Module):
433
+ def __init__(self, config):
434
+ super().__init__()
435
+ self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
436
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
437
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
438
+
439
+ def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
440
+ hidden_states = self.dense(hidden_states)
441
+ hidden_states = self.dropout(hidden_states)
442
+ hidden_states = self.LayerNorm(hidden_states + input_tensor)
443
+ return hidden_states
444
+
445
+
446
+ # Copied from transformers.models.bert.modeling_bert.BertLayer with Bert->Electra
447
+ class ElectraLayer(nn.Module):
448
+ def __init__(self, config):
449
+ super().__init__()
450
+ self.chunk_size_feed_forward = config.chunk_size_feed_forward
451
+ self.seq_len_dim = 1
452
+ self.attention = ElectraAttention(config)
453
+ self.is_decoder = config.is_decoder
454
+ self.add_cross_attention = config.add_cross_attention
455
+ if self.add_cross_attention:
456
+ if not self.is_decoder:
457
+ raise ValueError(f"{self} should be used as a decoder model if cross attention is added")
458
+ self.crossattention = ElectraAttention(config, position_embedding_type="absolute")
459
+ self.intermediate = ElectraIntermediate(config)
460
+ self.output = ElectraOutput(config)
461
+
462
+ def forward(
463
+ self,
464
+ hidden_states: torch.Tensor,
465
+ attention_mask: Optional[torch.FloatTensor] = None,
466
+ head_mask: Optional[torch.FloatTensor] = None,
467
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
468
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
469
+ past_key_value: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
470
+ output_attentions: Optional[bool] = False,
471
+ ) -> Tuple[torch.Tensor]:
472
+ # decoder uni-directional self-attention cached key/values tuple is at positions 1,2
473
+ self_attn_past_key_value = past_key_value[:2] if past_key_value is not None else None
474
+ self_attention_outputs = self.attention(
475
+ hidden_states,
476
+ attention_mask,
477
+ head_mask,
478
+ output_attentions=output_attentions,
479
+ past_key_value=self_attn_past_key_value,
480
+ )
481
+ attention_output = self_attention_outputs[0]
482
+
483
+ # if decoder, the last output is tuple of self-attn cache
484
+ if self.is_decoder:
485
+ outputs = self_attention_outputs[1:-1]
486
+ present_key_value = self_attention_outputs[-1]
487
+ else:
488
+ outputs = self_attention_outputs[1:] # add self attentions if we output attention weights
489
+
490
+ cross_attn_present_key_value = None
491
+ if self.is_decoder and encoder_hidden_states is not None:
492
+ if not hasattr(self, "crossattention"):
493
+ raise ValueError(
494
+ f"If `encoder_hidden_states` are passed, {self} has to be instantiated with cross-attention layers"
495
+ " by setting `config.add_cross_attention=True`"
496
+ )
497
+
498
+ # cross_attn cached key/values tuple is at positions 3,4 of past_key_value tuple
499
+ cross_attn_past_key_value = past_key_value[-2:] if past_key_value is not None else None
500
+ cross_attention_outputs = self.crossattention(
501
+ attention_output,
502
+ attention_mask,
503
+ head_mask,
504
+ encoder_hidden_states,
505
+ encoder_attention_mask,
506
+ cross_attn_past_key_value,
507
+ output_attentions,
508
+ )
509
+ attention_output = cross_attention_outputs[0]
510
+ outputs = outputs + cross_attention_outputs[1:-1] # add cross attentions if we output attention weights
511
+
512
+ # add cross-attn cache to positions 3,4 of present_key_value tuple
513
+ cross_attn_present_key_value = cross_attention_outputs[-1]
514
+ present_key_value = present_key_value + cross_attn_present_key_value
515
+
516
+ layer_output = apply_chunking_to_forward(
517
+ self.feed_forward_chunk, self.chunk_size_feed_forward, self.seq_len_dim, attention_output
518
+ )
519
+ outputs = (layer_output,) + outputs
520
+
521
+ # if decoder, return the attn key/values as the last output
522
+ if self.is_decoder:
523
+ outputs = outputs + (present_key_value,)
524
+
525
+ return outputs
526
+
527
+ def feed_forward_chunk(self, attention_output):
528
+ intermediate_output = self.intermediate(attention_output)
529
+ layer_output = self.output(intermediate_output, attention_output)
530
+ return layer_output
531
+
532
+
533
+ # Copied from transformers.models.bert.modeling_bert.BertEncoder with Bert->Electra
534
+ class ElectraEncoder(nn.Module):
535
+ def __init__(self, config):
536
+ super().__init__()
537
+ self.config = config
538
+ self.layer = nn.ModuleList([ElectraLayer(config) for _ in range(config.num_hidden_layers)])
539
+ self.gradient_checkpointing = False
540
+
541
+ def forward(
542
+ self,
543
+ hidden_states: torch.Tensor,
544
+ attention_mask: Optional[torch.FloatTensor] = None,
545
+ head_mask: Optional[torch.FloatTensor] = None,
546
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
547
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
548
+ past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
549
+ use_cache: Optional[bool] = None,
550
+ output_attentions: Optional[bool] = False,
551
+ output_hidden_states: Optional[bool] = False,
552
+ return_dict: Optional[bool] = True,
553
+ ) -> Union[Tuple[torch.Tensor], BaseModelOutputWithPastAndCrossAttentions]:
554
+ all_hidden_states = () if output_hidden_states else None
555
+ all_self_attentions = () if output_attentions else None
556
+ all_cross_attentions = () if output_attentions and self.config.add_cross_attention else None
557
+
558
+ if self.gradient_checkpointing and self.training:
559
+ if use_cache:
560
+ logger.warning_once(
561
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
562
+ )
563
+ use_cache = False
564
+
565
+ next_decoder_cache = () if use_cache else None
566
+ for i, layer_module in enumerate(self.layer):
567
+ if output_hidden_states:
568
+ all_hidden_states = all_hidden_states + (hidden_states,)
569
+
570
+ layer_head_mask = head_mask[i] if head_mask is not None else None
571
+ past_key_value = past_key_values[i] if past_key_values is not None else None
572
+
573
+ if self.gradient_checkpointing and self.training:
574
+ layer_outputs = self._gradient_checkpointing_func(
575
+ layer_module.__call__,
576
+ hidden_states,
577
+ attention_mask,
578
+ layer_head_mask,
579
+ encoder_hidden_states,
580
+ encoder_attention_mask,
581
+ past_key_value,
582
+ output_attentions,
583
+ )
584
+ else:
585
+ layer_outputs = layer_module(
586
+ hidden_states,
587
+ attention_mask,
588
+ layer_head_mask,
589
+ encoder_hidden_states,
590
+ encoder_attention_mask,
591
+ past_key_value,
592
+ output_attentions,
593
+ )
594
+
595
+ hidden_states = layer_outputs[0]
596
+ if use_cache:
597
+ next_decoder_cache += (layer_outputs[-1],)
598
+ if output_attentions:
599
+ all_self_attentions = all_self_attentions + (layer_outputs[1],)
600
+ if self.config.add_cross_attention:
601
+ all_cross_attentions = all_cross_attentions + (layer_outputs[2],)
602
+
603
+ if output_hidden_states:
604
+ all_hidden_states = all_hidden_states + (hidden_states,)
605
+
606
+ if not return_dict:
607
+ return tuple(
608
+ v
609
+ for v in [
610
+ hidden_states,
611
+ next_decoder_cache,
612
+ all_hidden_states,
613
+ all_self_attentions,
614
+ all_cross_attentions,
615
+ ]
616
+ if v is not None
617
+ )
618
+ return BaseModelOutputWithPastAndCrossAttentions(
619
+ last_hidden_state=hidden_states,
620
+ past_key_values=next_decoder_cache,
621
+ hidden_states=all_hidden_states,
622
+ attentions=all_self_attentions,
623
+ cross_attentions=all_cross_attentions,
624
+ )
625
+
626
+
627
+ class ElectraDiscriminatorPredictions(nn.Module):
628
+ """Prediction module for the discriminator, made up of two dense layers."""
629
+
630
+ def __init__(self, config):
631
+ super().__init__()
632
+
633
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
634
+ self.activation = get_activation(config.hidden_act)
635
+ self.dense_prediction = nn.Linear(config.hidden_size, 1)
636
+ self.config = config
637
+
638
+ def forward(self, discriminator_hidden_states):
639
+ hidden_states = self.dense(discriminator_hidden_states)
640
+ hidden_states = self.activation(hidden_states)
641
+ logits = self.dense_prediction(hidden_states).squeeze(-1)
642
+
643
+ return logits
644
+
645
+
646
+ class ElectraGeneratorPredictions(nn.Module):
647
+ """Prediction module for the generator, made up of two dense layers."""
648
+
649
+ def __init__(self, config):
650
+ super().__init__()
651
+
652
+ self.activation = get_activation("gelu")
653
+ self.LayerNorm = nn.LayerNorm(config.embedding_size, eps=config.layer_norm_eps)
654
+ self.dense = nn.Linear(config.hidden_size, config.embedding_size)
655
+
656
+ def forward(self, generator_hidden_states):
657
+ hidden_states = self.dense(generator_hidden_states)
658
+ hidden_states = self.activation(hidden_states)
659
+ hidden_states = self.LayerNorm(hidden_states)
660
+
661
+ return hidden_states
662
+
663
+
664
+ class ElectraPreTrainedModel(PreTrainedModel):
665
+ """
666
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
667
+ models.
668
+ """
669
+
670
+ config_class = ElectraConfig
671
+ load_tf_weights = load_tf_weights_in_electra
672
+ base_model_prefix = "electra"
673
+ supports_gradient_checkpointing = True
674
+
675
+ # Copied from transformers.models.bert.modeling_bert.BertPreTrainedModel._init_weights
676
+ def _init_weights(self, module):
677
+ """Initialize the weights"""
678
+ if isinstance(module, nn.Linear):
679
+ # Slightly different from the TF version which uses truncated_normal for initialization
680
+ # cf https://github.com/pytorch/pytorch/pull/5617
681
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
682
+ if module.bias is not None:
683
+ module.bias.data.zero_()
684
+ elif isinstance(module, nn.Embedding):
685
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
686
+ if module.padding_idx is not None:
687
+ module.weight.data[module.padding_idx].zero_()
688
+ elif isinstance(module, nn.LayerNorm):
689
+ module.bias.data.zero_()
690
+ module.weight.data.fill_(1.0)
691
+
692
+
693
+ @dataclass
694
+ class ElectraForPreTrainingOutput(ModelOutput):
695
+ """
696
+ Output type of [`ElectraForPreTraining`].
697
+
698
+ Args:
699
+ loss (*optional*, returned when `labels` is provided, `torch.FloatTensor` of shape `(1,)`):
700
+ Total loss of the ELECTRA objective.
701
+ logits (`torch.FloatTensor` of shape `(batch_size, sequence_length)`):
702
+ Prediction scores of the head (scores for each token before SoftMax).
703
+ hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
704
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of
705
+ shape `(batch_size, sequence_length, hidden_size)`.
706
+
707
+ Hidden-states of the model at the output of each layer plus the initial embedding outputs.
708
+ attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
709
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
710
+ sequence_length)`.
711
+
712
+ Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
713
+ heads.
714
+ """
715
+
716
+ loss: Optional[torch.FloatTensor] = None
717
+ logits: torch.FloatTensor = None
718
+ hidden_states: Optional[Tuple[torch.FloatTensor]] = None
719
+ attentions: Optional[Tuple[torch.FloatTensor]] = None
720
+
721
+
722
+ ELECTRA_START_DOCSTRING = r"""
723
+
724
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
725
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
726
+ etc.)
727
+
728
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
729
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
730
+ and behavior.
731
+
732
+ Parameters:
733
+ config ([`ElectraConfig`]): Model configuration class with all the parameters of the model.
734
+ Initializing with a config file does not load the weights associated with the model, only the
735
+ configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
736
+ """
737
+
738
+ ELECTRA_INPUTS_DOCSTRING = r"""
739
+ Args:
740
+ input_ids (`torch.LongTensor` of shape `({0})`):
741
+ Indices of input sequence tokens in the vocabulary.
742
+
743
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
744
+ [`PreTrainedTokenizer.__call__`] for details.
745
+
746
+ [What are input IDs?](../glossary#input-ids)
747
+ attention_mask (`torch.FloatTensor` of shape `({0})`, *optional*):
748
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
749
+
750
+ - 1 for tokens that are **not masked**,
751
+ - 0 for tokens that are **masked**.
752
+
753
+ [What are attention masks?](../glossary#attention-mask)
754
+ token_type_ids (`torch.LongTensor` of shape `({0})`, *optional*):
755
+ Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
756
+ 1]`:
757
+
758
+ - 0 corresponds to a *sentence A* token,
759
+ - 1 corresponds to a *sentence B* token.
760
+
761
+ [What are token type IDs?](../glossary#token-type-ids)
762
+ position_ids (`torch.LongTensor` of shape `({0})`, *optional*):
763
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
764
+ config.max_position_embeddings - 1]`.
765
+
766
+ [What are position IDs?](../glossary#position-ids)
767
+ head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
768
+ Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:
769
+
770
+ - 1 indicates the head is **not masked**,
771
+ - 0 indicates the head is **masked**.
772
+
773
+ inputs_embeds (`torch.FloatTensor` of shape `({0}, hidden_size)`, *optional*):
774
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
775
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
776
+ model's internal embedding lookup matrix.
777
+ encoder_hidden_states (`torch.FloatTensor` of shape `({0}, hidden_size)`, *optional*):
778
+ Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if
779
+ the model is configured as a decoder.
780
+ encoder_attention_mask (`torch.FloatTensor` of shape `({0})`, *optional*):
781
+ Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in
782
+ the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`:
783
+
784
+ - 1 indicates the head is **not masked**,
785
+ - 0 indicates the head is **masked**.
786
+
787
+ output_attentions (`bool`, *optional*):
788
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
789
+ tensors for more detail.
790
+ output_hidden_states (`bool`, *optional*):
791
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
792
+ more detail.
793
+ return_dict (`bool`, *optional*):
794
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
795
+ """
796
+
797
+
798
+ @add_start_docstrings(
799
+ "The bare Electra Model transformer outputting raw hidden-states without any specific head on top. Identical to "
800
+ "the BERT model except that it uses an additional linear layer between the embedding layer and the encoder if the "
801
+ "hidden size and embedding size are different. "
802
+ ""
803
+ "Both the generator and discriminator checkpoints may be loaded into this model.",
804
+ ELECTRA_START_DOCSTRING,
805
+ )
806
+ class ElectraModel(ElectraPreTrainedModel):
807
+ def __init__(self, config):
808
+ super().__init__(config)
809
+ self.embeddings = ElectraEmbeddings(config)
810
+
811
+ if config.embedding_size != config.hidden_size:
812
+ self.embeddings_project = nn.Linear(config.embedding_size, config.hidden_size)
813
+
814
+ self.encoder = ElectraEncoder(config)
815
+ self.config = config
816
+ # Initialize weights and apply final processing
817
+ self.post_init()
818
+
819
+ def get_input_embeddings(self):
820
+ return self.embeddings.word_embeddings
821
+
822
+ def set_input_embeddings(self, value):
823
+ self.embeddings.word_embeddings = value
824
+
825
+ def _prune_heads(self, heads_to_prune):
826
+ """
827
+ Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
828
+ class PreTrainedModel
829
+ """
830
+ for layer, heads in heads_to_prune.items():
831
+ self.encoder.layer[layer].attention.prune_heads(heads)
832
+
833
+ @add_start_docstrings_to_model_forward(ELECTRA_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
834
+ @add_code_sample_docstrings(
835
+ checkpoint=_CHECKPOINT_FOR_DOC,
836
+ output_type=BaseModelOutputWithCrossAttentions,
837
+ config_class=_CONFIG_FOR_DOC,
838
+ )
839
+ def forward(
840
+ self,
841
+ input_ids: Optional[torch.Tensor] = None,
842
+ attention_mask: Optional[torch.Tensor] = None,
843
+ token_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], BaseModelOutputWithCrossAttentions]:
855
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
856
+ output_hidden_states = (
857
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
858
+ )
859
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
860
+
861
+ if input_ids is not None and inputs_embeds is not None:
862
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
863
+ elif input_ids is not None:
864
+ self.warn_if_padding_and_no_attention_mask(input_ids, attention_mask)
865
+ input_shape = input_ids.size()
866
+ elif inputs_embeds is not None:
867
+ input_shape = inputs_embeds.size()[:-1]
868
+ else:
869
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
870
+
871
+ batch_size, seq_length = input_shape
872
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
873
+
874
+ # past_key_values_length
875
+ past_key_values_length = past_key_values[0][0].shape[2] if past_key_values is not None else 0
876
+
877
+ if attention_mask is None:
878
+ attention_mask = torch.ones(input_shape, device=device)
879
+ if token_type_ids is None:
880
+ if hasattr(self.embeddings, "token_type_ids"):
881
+ buffered_token_type_ids = self.embeddings.token_type_ids[:, :seq_length]
882
+ buffered_token_type_ids_expanded = buffered_token_type_ids.expand(batch_size, seq_length)
883
+ token_type_ids = buffered_token_type_ids_expanded
884
+ else:
885
+ token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=device)
886
+
887
+ extended_attention_mask = self.get_extended_attention_mask(attention_mask, input_shape)
888
+
889
+ # If a 2D or 3D attention mask is provided for the cross-attention
890
+ # we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length]
891
+ if self.config.is_decoder and encoder_hidden_states is not None:
892
+ encoder_batch_size, encoder_sequence_length, _ = encoder_hidden_states.size()
893
+ encoder_hidden_shape = (encoder_batch_size, encoder_sequence_length)
894
+ if encoder_attention_mask is None:
895
+ encoder_attention_mask = torch.ones(encoder_hidden_shape, device=device)
896
+ encoder_extended_attention_mask = self.invert_attention_mask(encoder_attention_mask)
897
+ else:
898
+ encoder_extended_attention_mask = None
899
+
900
+ head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)
901
+
902
+ hidden_states = self.embeddings(
903
+ input_ids=input_ids,
904
+ position_ids=position_ids,
905
+ token_type_ids=token_type_ids,
906
+ inputs_embeds=inputs_embeds,
907
+ past_key_values_length=past_key_values_length,
908
+ )
909
+
910
+ if hasattr(self, "embeddings_project"):
911
+ hidden_states = self.embeddings_project(hidden_states)
912
+
913
+ hidden_states = self.encoder(
914
+ hidden_states,
915
+ attention_mask=extended_attention_mask,
916
+ head_mask=head_mask,
917
+ encoder_hidden_states=encoder_hidden_states,
918
+ encoder_attention_mask=encoder_extended_attention_mask,
919
+ past_key_values=past_key_values,
920
+ use_cache=use_cache,
921
+ output_attentions=output_attentions,
922
+ output_hidden_states=output_hidden_states,
923
+ return_dict=return_dict,
924
+ )
925
+
926
+ return hidden_states
927
+
928
+
929
+ class ElectraClassificationHead(nn.Module):
930
+ """Head for sentence-level classification tasks."""
931
+
932
+ def __init__(self, config):
933
+ super().__init__()
934
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
935
+ classifier_dropout = (
936
+ config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob
937
+ )
938
+ self.activation = get_activation("gelu")
939
+ self.dropout = nn.Dropout(classifier_dropout)
940
+ self.out_proj = nn.Linear(config.hidden_size, config.num_labels)
941
+
942
+ def forward(self, features, **kwargs):
943
+ x = features[:, 0, :] # take <s> token (equiv. to [CLS])
944
+ x = self.dropout(x)
945
+ x = self.dense(x)
946
+ x = self.activation(x) # although BERT uses tanh here, it seems Electra authors used gelu here
947
+ x = self.dropout(x)
948
+ x = self.out_proj(x)
949
+ return x
950
+
951
+
952
+ @add_start_docstrings(
953
+ """
954
+ ELECTRA Model transformer with a sequence classification/regression head on top (a linear layer on top of the
955
+ pooled output) e.g. for GLUE tasks.
956
+ """,
957
+ ELECTRA_START_DOCSTRING,
958
+ )
959
+ class ElectraForSequenceClassification(ElectraPreTrainedModel):
960
+ def __init__(self, config):
961
+ super().__init__(config)
962
+ self.num_labels = config.num_labels
963
+ self.config = config
964
+ self.electra = ElectraModel(config)
965
+ self.classifier = ElectraClassificationHead(config)
966
+
967
+ # Initialize weights and apply final processing
968
+ self.post_init()
969
+
970
+ @add_start_docstrings_to_model_forward(ELECTRA_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
971
+ @add_code_sample_docstrings(
972
+ checkpoint="bhadresh-savani/electra-base-emotion",
973
+ output_type=SequenceClassifierOutput,
974
+ config_class=_CONFIG_FOR_DOC,
975
+ expected_output="'joy'",
976
+ expected_loss=0.06,
977
+ )
978
+ def forward(
979
+ self,
980
+ input_ids: Optional[torch.Tensor] = None,
981
+ attention_mask: Optional[torch.Tensor] = None,
982
+ token_type_ids: Optional[torch.Tensor] = None,
983
+ position_ids: Optional[torch.Tensor] = None,
984
+ head_mask: Optional[torch.Tensor] = None,
985
+ inputs_embeds: Optional[torch.Tensor] = None,
986
+ labels: Optional[torch.Tensor] = None,
987
+ output_attentions: Optional[bool] = None,
988
+ output_hidden_states: Optional[bool] = None,
989
+ return_dict: Optional[bool] = None,
990
+ ) -> Union[Tuple[torch.Tensor], SequenceClassifierOutput]:
991
+ r"""
992
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
993
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
994
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
995
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
996
+ """
997
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
998
+
999
+ discriminator_hidden_states = self.electra(
1000
+ input_ids,
1001
+ attention_mask=attention_mask,
1002
+ token_type_ids=token_type_ids,
1003
+ position_ids=position_ids,
1004
+ head_mask=head_mask,
1005
+ inputs_embeds=inputs_embeds,
1006
+ output_attentions=output_attentions,
1007
+ output_hidden_states=output_hidden_states,
1008
+ return_dict=return_dict,
1009
+ )
1010
+
1011
+ sequence_output = discriminator_hidden_states[0]
1012
+ logits = self.classifier(sequence_output)
1013
+
1014
+ loss = None
1015
+ if labels is not None:
1016
+ if self.config.problem_type is None:
1017
+ if self.num_labels == 1:
1018
+ self.config.problem_type = "regression"
1019
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1020
+ self.config.problem_type = "single_label_classification"
1021
+ else:
1022
+ self.config.problem_type = "multi_label_classification"
1023
+
1024
+ if self.config.problem_type == "regression":
1025
+ loss_fct = MSELoss()
1026
+ if self.num_labels == 1:
1027
+ loss = loss_fct(logits.squeeze(), labels.squeeze())
1028
+ else:
1029
+ loss = loss_fct(logits, labels)
1030
+ elif self.config.problem_type == "single_label_classification":
1031
+ loss_fct = CrossEntropyLoss()
1032
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
1033
+ elif self.config.problem_type == "multi_label_classification":
1034
+ loss_fct = BCEWithLogitsLoss()
1035
+ loss = loss_fct(logits, labels)
1036
+
1037
+ if not return_dict:
1038
+ output = (logits,) + discriminator_hidden_states[1:]
1039
+ return ((loss,) + output) if loss is not None else output
1040
+
1041
+ return SequenceClassifierOutput(
1042
+ loss=loss,
1043
+ logits=logits,
1044
+ hidden_states=discriminator_hidden_states.hidden_states,
1045
+ attentions=discriminator_hidden_states.attentions,
1046
+ )
1047
+
1048
+
1049
+ @add_start_docstrings(
1050
+ """
1051
+ Electra model with a binary classification head on top as used during pretraining for identifying generated tokens.
1052
+
1053
+ It is recommended to load the discriminator checkpoint into that model.
1054
+ """,
1055
+ ELECTRA_START_DOCSTRING,
1056
+ )
1057
+ class ElectraForPreTraining(ElectraPreTrainedModel):
1058
+ def __init__(self, config):
1059
+ super().__init__(config)
1060
+
1061
+ self.electra = ElectraModel(config)
1062
+ self.discriminator_predictions = ElectraDiscriminatorPredictions(config)
1063
+ # Initialize weights and apply final processing
1064
+ self.post_init()
1065
+
1066
+ @add_start_docstrings_to_model_forward(ELECTRA_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
1067
+ @replace_return_docstrings(output_type=ElectraForPreTrainingOutput, config_class=_CONFIG_FOR_DOC)
1068
+ def forward(
1069
+ self,
1070
+ input_ids: Optional[torch.Tensor] = None,
1071
+ attention_mask: Optional[torch.Tensor] = None,
1072
+ token_type_ids: Optional[torch.Tensor] = None,
1073
+ position_ids: Optional[torch.Tensor] = None,
1074
+ head_mask: Optional[torch.Tensor] = None,
1075
+ inputs_embeds: Optional[torch.Tensor] = None,
1076
+ labels: Optional[torch.Tensor] = None,
1077
+ output_attentions: Optional[bool] = None,
1078
+ output_hidden_states: Optional[bool] = None,
1079
+ return_dict: Optional[bool] = None,
1080
+ ) -> Union[Tuple[torch.Tensor], ElectraForPreTrainingOutput]:
1081
+ r"""
1082
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1083
+ Labels for computing the ELECTRA loss. Input should be a sequence of tokens (see `input_ids` docstring)
1084
+ Indices should be in `[0, 1]`:
1085
+
1086
+ - 0 indicates the token is an original token,
1087
+ - 1 indicates the token was replaced.
1088
+
1089
+ Returns:
1090
+
1091
+ Examples:
1092
+
1093
+ ```python
1094
+ >>> from transformers import ElectraForPreTraining, AutoTokenizer
1095
+ >>> import torch
1096
+
1097
+ >>> discriminator = ElectraForPreTraining.from_pretrained("google/electra-base-discriminator")
1098
+ >>> tokenizer = AutoTokenizer.from_pretrained("google/electra-base-discriminator")
1099
+
1100
+ >>> sentence = "The quick brown fox jumps over the lazy dog"
1101
+ >>> fake_sentence = "The quick brown fox fake over the lazy dog"
1102
+
1103
+ >>> fake_tokens = tokenizer.tokenize(fake_sentence, add_special_tokens=True)
1104
+ >>> fake_inputs = tokenizer.encode(fake_sentence, return_tensors="pt")
1105
+ >>> discriminator_outputs = discriminator(fake_inputs)
1106
+ >>> predictions = torch.round((torch.sign(discriminator_outputs[0]) + 1) / 2)
1107
+
1108
+ >>> fake_tokens
1109
+ ['[CLS]', 'the', 'quick', 'brown', 'fox', 'fake', 'over', 'the', 'lazy', 'dog', '[SEP]']
1110
+
1111
+ >>> predictions.squeeze().tolist()
1112
+ [0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0]
1113
+ ```"""
1114
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1115
+
1116
+ discriminator_hidden_states = self.electra(
1117
+ input_ids,
1118
+ attention_mask=attention_mask,
1119
+ token_type_ids=token_type_ids,
1120
+ position_ids=position_ids,
1121
+ head_mask=head_mask,
1122
+ inputs_embeds=inputs_embeds,
1123
+ output_attentions=output_attentions,
1124
+ output_hidden_states=output_hidden_states,
1125
+ return_dict=return_dict,
1126
+ )
1127
+ discriminator_sequence_output = discriminator_hidden_states[0]
1128
+
1129
+ logits = self.discriminator_predictions(discriminator_sequence_output)
1130
+
1131
+ loss = None
1132
+ if labels is not None:
1133
+ loss_fct = nn.BCEWithLogitsLoss()
1134
+ if attention_mask is not None:
1135
+ active_loss = attention_mask.view(-1, discriminator_sequence_output.shape[1]) == 1
1136
+ active_logits = logits.view(-1, discriminator_sequence_output.shape[1])[active_loss]
1137
+ active_labels = labels[active_loss]
1138
+ loss = loss_fct(active_logits, active_labels.float())
1139
+ else:
1140
+ loss = loss_fct(logits.view(-1, discriminator_sequence_output.shape[1]), labels.float())
1141
+
1142
+ if not return_dict:
1143
+ output = (logits,) + discriminator_hidden_states[1:]
1144
+ return ((loss,) + output) if loss is not None else output
1145
+
1146
+ return ElectraForPreTrainingOutput(
1147
+ loss=loss,
1148
+ logits=logits,
1149
+ hidden_states=discriminator_hidden_states.hidden_states,
1150
+ attentions=discriminator_hidden_states.attentions,
1151
+ )
1152
+
1153
+
1154
+ @add_start_docstrings(
1155
+ """
1156
+ Electra model with a language modeling head on top.
1157
+
1158
+ Even though both the discriminator and generator may be loaded into this model, the generator is the only model of
1159
+ the two to have been trained for the masked language modeling task.
1160
+ """,
1161
+ ELECTRA_START_DOCSTRING,
1162
+ )
1163
+ class ElectraForMaskedLM(ElectraPreTrainedModel):
1164
+ _tied_weights_keys = ["generator_lm_head.weight"]
1165
+
1166
+ def __init__(self, config):
1167
+ super().__init__(config)
1168
+
1169
+ self.electra = ElectraModel(config)
1170
+ self.generator_predictions = ElectraGeneratorPredictions(config)
1171
+
1172
+ self.generator_lm_head = nn.Linear(config.embedding_size, config.vocab_size)
1173
+ # Initialize weights and apply final processing
1174
+ self.post_init()
1175
+
1176
+ def get_output_embeddings(self):
1177
+ return self.generator_lm_head
1178
+
1179
+ def set_output_embeddings(self, word_embeddings):
1180
+ self.generator_lm_head = word_embeddings
1181
+
1182
+ @add_start_docstrings_to_model_forward(ELECTRA_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
1183
+ @add_code_sample_docstrings(
1184
+ checkpoint="google/electra-small-generator",
1185
+ output_type=MaskedLMOutput,
1186
+ config_class=_CONFIG_FOR_DOC,
1187
+ mask="[MASK]",
1188
+ expected_output="'paris'",
1189
+ expected_loss=1.22,
1190
+ )
1191
+ def forward(
1192
+ self,
1193
+ input_ids: Optional[torch.Tensor] = None,
1194
+ attention_mask: Optional[torch.Tensor] = None,
1195
+ token_type_ids: Optional[torch.Tensor] = None,
1196
+ position_ids: Optional[torch.Tensor] = None,
1197
+ head_mask: Optional[torch.Tensor] = None,
1198
+ inputs_embeds: Optional[torch.Tensor] = None,
1199
+ labels: Optional[torch.Tensor] = None,
1200
+ output_attentions: Optional[bool] = None,
1201
+ output_hidden_states: Optional[bool] = None,
1202
+ return_dict: Optional[bool] = None,
1203
+ ) -> Union[Tuple[torch.Tensor], MaskedLMOutput]:
1204
+ r"""
1205
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1206
+ Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
1207
+ config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the
1208
+ loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
1209
+ """
1210
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1211
+
1212
+ generator_hidden_states = self.electra(
1213
+ input_ids,
1214
+ attention_mask=attention_mask,
1215
+ token_type_ids=token_type_ids,
1216
+ position_ids=position_ids,
1217
+ head_mask=head_mask,
1218
+ inputs_embeds=inputs_embeds,
1219
+ output_attentions=output_attentions,
1220
+ output_hidden_states=output_hidden_states,
1221
+ return_dict=return_dict,
1222
+ )
1223
+ generator_sequence_output = generator_hidden_states[0]
1224
+
1225
+ prediction_scores = self.generator_predictions(generator_sequence_output)
1226
+ prediction_scores = self.generator_lm_head(prediction_scores)
1227
+
1228
+ loss = None
1229
+ # Masked language modeling softmax layer
1230
+ if labels is not None:
1231
+ loss_fct = nn.CrossEntropyLoss() # -100 index = padding token
1232
+ loss = loss_fct(prediction_scores.view(-1, self.config.vocab_size), labels.view(-1))
1233
+
1234
+ if not return_dict:
1235
+ output = (prediction_scores,) + generator_hidden_states[1:]
1236
+ return ((loss,) + output) if loss is not None else output
1237
+
1238
+ return MaskedLMOutput(
1239
+ loss=loss,
1240
+ logits=prediction_scores,
1241
+ hidden_states=generator_hidden_states.hidden_states,
1242
+ attentions=generator_hidden_states.attentions,
1243
+ )
1244
+
1245
+
1246
+ @add_start_docstrings(
1247
+ """
1248
+ Electra model with a token classification head on top.
1249
+
1250
+ Both the discriminator and generator may be loaded into this model.
1251
+ """,
1252
+ ELECTRA_START_DOCSTRING,
1253
+ )
1254
+ class ElectraForTokenClassification(ElectraPreTrainedModel):
1255
+ def __init__(self, config):
1256
+ super().__init__(config)
1257
+ self.num_labels = config.num_labels
1258
+
1259
+ self.electra = ElectraModel(config)
1260
+ classifier_dropout = (
1261
+ config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob
1262
+ )
1263
+ self.dropout = nn.Dropout(classifier_dropout)
1264
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels)
1265
+ # Initialize weights and apply final processing
1266
+ self.post_init()
1267
+
1268
+ @add_start_docstrings_to_model_forward(ELECTRA_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
1269
+ @add_code_sample_docstrings(
1270
+ checkpoint="bhadresh-savani/electra-base-discriminator-finetuned-conll03-english",
1271
+ output_type=TokenClassifierOutput,
1272
+ config_class=_CONFIG_FOR_DOC,
1273
+ expected_output="['B-LOC', 'B-ORG', 'O', 'O', 'O', 'O', 'O', 'B-LOC', 'O', 'B-LOC', 'I-LOC']",
1274
+ expected_loss=0.11,
1275
+ )
1276
+ def forward(
1277
+ self,
1278
+ input_ids: Optional[torch.Tensor] = None,
1279
+ attention_mask: Optional[torch.Tensor] = None,
1280
+ token_type_ids: Optional[torch.Tensor] = None,
1281
+ position_ids: Optional[torch.Tensor] = None,
1282
+ head_mask: Optional[torch.Tensor] = None,
1283
+ inputs_embeds: Optional[torch.Tensor] = None,
1284
+ labels: Optional[torch.Tensor] = None,
1285
+ output_attentions: Optional[bool] = None,
1286
+ output_hidden_states: Optional[bool] = None,
1287
+ return_dict: Optional[bool] = None,
1288
+ ) -> Union[Tuple[torch.Tensor], TokenClassifierOutput]:
1289
+ r"""
1290
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1291
+ Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`.
1292
+ """
1293
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1294
+
1295
+ discriminator_hidden_states = self.electra(
1296
+ input_ids,
1297
+ attention_mask=attention_mask,
1298
+ token_type_ids=token_type_ids,
1299
+ position_ids=position_ids,
1300
+ head_mask=head_mask,
1301
+ inputs_embeds=inputs_embeds,
1302
+ output_attentions=output_attentions,
1303
+ output_hidden_states=output_hidden_states,
1304
+ return_dict=return_dict,
1305
+ )
1306
+ discriminator_sequence_output = discriminator_hidden_states[0]
1307
+
1308
+ discriminator_sequence_output = self.dropout(discriminator_sequence_output)
1309
+ logits = self.classifier(discriminator_sequence_output)
1310
+
1311
+ loss = None
1312
+ if labels is not None:
1313
+ loss_fct = CrossEntropyLoss()
1314
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
1315
+
1316
+ if not return_dict:
1317
+ output = (logits,) + discriminator_hidden_states[1:]
1318
+ return ((loss,) + output) if loss is not None else output
1319
+
1320
+ return TokenClassifierOutput(
1321
+ loss=loss,
1322
+ logits=logits,
1323
+ hidden_states=discriminator_hidden_states.hidden_states,
1324
+ attentions=discriminator_hidden_states.attentions,
1325
+ )
1326
+
1327
+
1328
+ @add_start_docstrings(
1329
+ """
1330
+ ELECTRA Model with a span classification head on top for extractive question-answering tasks like SQuAD (a linear
1331
+ layers on top of the hidden-states output to compute `span start logits` and `span end logits`).
1332
+ """,
1333
+ ELECTRA_START_DOCSTRING,
1334
+ )
1335
+ class ElectraForQuestionAnswering(ElectraPreTrainedModel):
1336
+ config_class = ElectraConfig
1337
+ base_model_prefix = "electra"
1338
+
1339
+ def __init__(self, config):
1340
+ super().__init__(config)
1341
+ self.num_labels = config.num_labels
1342
+
1343
+ self.electra = ElectraModel(config)
1344
+ self.qa_outputs = nn.Linear(config.hidden_size, config.num_labels)
1345
+
1346
+ # Initialize weights and apply final processing
1347
+ self.post_init()
1348
+
1349
+ @add_start_docstrings_to_model_forward(ELECTRA_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
1350
+ @add_code_sample_docstrings(
1351
+ checkpoint="bhadresh-savani/electra-base-squad2",
1352
+ output_type=QuestionAnsweringModelOutput,
1353
+ config_class=_CONFIG_FOR_DOC,
1354
+ qa_target_start_index=11,
1355
+ qa_target_end_index=12,
1356
+ expected_output="'a nice puppet'",
1357
+ expected_loss=2.64,
1358
+ )
1359
+ def forward(
1360
+ self,
1361
+ input_ids: Optional[torch.Tensor] = None,
1362
+ attention_mask: Optional[torch.Tensor] = None,
1363
+ token_type_ids: Optional[torch.Tensor] = None,
1364
+ position_ids: Optional[torch.Tensor] = None,
1365
+ head_mask: Optional[torch.Tensor] = None,
1366
+ inputs_embeds: Optional[torch.Tensor] = None,
1367
+ start_positions: Optional[torch.Tensor] = None,
1368
+ end_positions: Optional[torch.Tensor] = None,
1369
+ output_attentions: Optional[bool] = None,
1370
+ output_hidden_states: Optional[bool] = None,
1371
+ return_dict: Optional[bool] = None,
1372
+ ) -> Union[Tuple[torch.Tensor], QuestionAnsweringModelOutput]:
1373
+ r"""
1374
+ start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1375
+ Labels for position (index) of the start of the labelled span for computing the token classification loss.
1376
+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
1377
+ are not taken into account for computing the loss.
1378
+ end_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1379
+ Labels for position (index) of the end of the labelled span for computing the token classification loss.
1380
+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
1381
+ are not taken into account for computing the loss.
1382
+ """
1383
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1384
+
1385
+ discriminator_hidden_states = self.electra(
1386
+ input_ids,
1387
+ attention_mask=attention_mask,
1388
+ token_type_ids=token_type_ids,
1389
+ position_ids=position_ids,
1390
+ head_mask=head_mask,
1391
+ inputs_embeds=inputs_embeds,
1392
+ output_attentions=output_attentions,
1393
+ output_hidden_states=output_hidden_states,
1394
+ )
1395
+
1396
+ sequence_output = discriminator_hidden_states[0]
1397
+
1398
+ logits = self.qa_outputs(sequence_output)
1399
+ start_logits, end_logits = logits.split(1, dim=-1)
1400
+ start_logits = start_logits.squeeze(-1).contiguous()
1401
+ end_logits = end_logits.squeeze(-1).contiguous()
1402
+
1403
+ total_loss = None
1404
+ if start_positions is not None and end_positions is not None:
1405
+ # If we are on multi-GPU, split add a dimension
1406
+ if len(start_positions.size()) > 1:
1407
+ start_positions = start_positions.squeeze(-1)
1408
+ if len(end_positions.size()) > 1:
1409
+ end_positions = end_positions.squeeze(-1)
1410
+ # sometimes the start/end positions are outside our model inputs, we ignore these terms
1411
+ ignored_index = start_logits.size(1)
1412
+ start_positions = start_positions.clamp(0, ignored_index)
1413
+ end_positions = end_positions.clamp(0, ignored_index)
1414
+
1415
+ loss_fct = CrossEntropyLoss(ignore_index=ignored_index)
1416
+ start_loss = loss_fct(start_logits, start_positions)
1417
+ end_loss = loss_fct(end_logits, end_positions)
1418
+ total_loss = (start_loss + end_loss) / 2
1419
+
1420
+ if not return_dict:
1421
+ output = (
1422
+ start_logits,
1423
+ end_logits,
1424
+ ) + discriminator_hidden_states[1:]
1425
+ return ((total_loss,) + output) if total_loss is not None else output
1426
+
1427
+ return QuestionAnsweringModelOutput(
1428
+ loss=total_loss,
1429
+ start_logits=start_logits,
1430
+ end_logits=end_logits,
1431
+ hidden_states=discriminator_hidden_states.hidden_states,
1432
+ attentions=discriminator_hidden_states.attentions,
1433
+ )
1434
+
1435
+
1436
+ @add_start_docstrings(
1437
+ """
1438
+ ELECTRA Model with a multiple choice classification head on top (a linear layer on top of the pooled output and a
1439
+ softmax) e.g. for RocStories/SWAG tasks.
1440
+ """,
1441
+ ELECTRA_START_DOCSTRING,
1442
+ )
1443
+ class ElectraForMultipleChoice(ElectraPreTrainedModel):
1444
+ def __init__(self, config):
1445
+ super().__init__(config)
1446
+
1447
+ self.electra = ElectraModel(config)
1448
+ self.sequence_summary = SequenceSummary(config)
1449
+ self.classifier = nn.Linear(config.hidden_size, 1)
1450
+
1451
+ # Initialize weights and apply final processing
1452
+ self.post_init()
1453
+
1454
+ @add_start_docstrings_to_model_forward(ELECTRA_INPUTS_DOCSTRING.format("batch_size, num_choices, sequence_length"))
1455
+ @add_code_sample_docstrings(
1456
+ checkpoint=_CHECKPOINT_FOR_DOC,
1457
+ output_type=MultipleChoiceModelOutput,
1458
+ config_class=_CONFIG_FOR_DOC,
1459
+ )
1460
+ def forward(
1461
+ self,
1462
+ input_ids: Optional[torch.Tensor] = None,
1463
+ attention_mask: Optional[torch.Tensor] = None,
1464
+ token_type_ids: Optional[torch.Tensor] = None,
1465
+ position_ids: Optional[torch.Tensor] = None,
1466
+ head_mask: Optional[torch.Tensor] = None,
1467
+ inputs_embeds: Optional[torch.Tensor] = None,
1468
+ labels: Optional[torch.Tensor] = None,
1469
+ output_attentions: Optional[bool] = None,
1470
+ output_hidden_states: Optional[bool] = None,
1471
+ return_dict: Optional[bool] = None,
1472
+ ) -> Union[Tuple[torch.Tensor], MultipleChoiceModelOutput]:
1473
+ r"""
1474
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1475
+ Labels for computing the multiple choice classification loss. Indices should be in `[0, ...,
1476
+ num_choices-1]` where `num_choices` is the size of the second dimension of the input tensors. (See
1477
+ `input_ids` above)
1478
+ """
1479
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1480
+ num_choices = input_ids.shape[1] if input_ids is not None else inputs_embeds.shape[1]
1481
+
1482
+ input_ids = input_ids.view(-1, input_ids.size(-1)) if input_ids is not None else None
1483
+ attention_mask = attention_mask.view(-1, attention_mask.size(-1)) if attention_mask is not None else None
1484
+ token_type_ids = token_type_ids.view(-1, token_type_ids.size(-1)) if token_type_ids is not None else None
1485
+ position_ids = position_ids.view(-1, position_ids.size(-1)) if position_ids is not None else None
1486
+ inputs_embeds = (
1487
+ inputs_embeds.view(-1, inputs_embeds.size(-2), inputs_embeds.size(-1))
1488
+ if inputs_embeds is not None
1489
+ else None
1490
+ )
1491
+
1492
+ discriminator_hidden_states = self.electra(
1493
+ input_ids,
1494
+ attention_mask=attention_mask,
1495
+ token_type_ids=token_type_ids,
1496
+ position_ids=position_ids,
1497
+ head_mask=head_mask,
1498
+ inputs_embeds=inputs_embeds,
1499
+ output_attentions=output_attentions,
1500
+ output_hidden_states=output_hidden_states,
1501
+ return_dict=return_dict,
1502
+ )
1503
+
1504
+ sequence_output = discriminator_hidden_states[0]
1505
+
1506
+ pooled_output = self.sequence_summary(sequence_output)
1507
+ logits = self.classifier(pooled_output)
1508
+ reshaped_logits = logits.view(-1, num_choices)
1509
+
1510
+ loss = None
1511
+ if labels is not None:
1512
+ loss_fct = CrossEntropyLoss()
1513
+ loss = loss_fct(reshaped_logits, labels)
1514
+
1515
+ if not return_dict:
1516
+ output = (reshaped_logits,) + discriminator_hidden_states[1:]
1517
+ return ((loss,) + output) if loss is not None else output
1518
+
1519
+ return MultipleChoiceModelOutput(
1520
+ loss=loss,
1521
+ logits=reshaped_logits,
1522
+ hidden_states=discriminator_hidden_states.hidden_states,
1523
+ attentions=discriminator_hidden_states.attentions,
1524
+ )
1525
+
1526
+
1527
+ @add_start_docstrings(
1528
+ """ELECTRA Model with a `language modeling` head on top for CLM fine-tuning.""", ELECTRA_START_DOCSTRING
1529
+ )
1530
+ class ElectraForCausalLM(ElectraPreTrainedModel):
1531
+ _tied_weights_keys = ["generator_lm_head.weight"]
1532
+
1533
+ def __init__(self, config):
1534
+ super().__init__(config)
1535
+
1536
+ if not config.is_decoder:
1537
+ logger.warning("If you want to use `ElectraForCausalLM` as a standalone, add `is_decoder=True.`")
1538
+
1539
+ self.electra = ElectraModel(config)
1540
+ self.generator_predictions = ElectraGeneratorPredictions(config)
1541
+ self.generator_lm_head = nn.Linear(config.embedding_size, config.vocab_size)
1542
+
1543
+ self.init_weights()
1544
+
1545
+ def get_output_embeddings(self):
1546
+ return self.generator_lm_head
1547
+
1548
+ def set_output_embeddings(self, new_embeddings):
1549
+ self.generator_lm_head = new_embeddings
1550
+
1551
+ @add_start_docstrings_to_model_forward(ELECTRA_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
1552
+ @replace_return_docstrings(output_type=CausalLMOutputWithCrossAttentions, config_class=_CONFIG_FOR_DOC)
1553
+ def forward(
1554
+ self,
1555
+ input_ids: Optional[torch.Tensor] = None,
1556
+ attention_mask: Optional[torch.Tensor] = None,
1557
+ token_type_ids: Optional[torch.Tensor] = None,
1558
+ position_ids: Optional[torch.Tensor] = None,
1559
+ head_mask: Optional[torch.Tensor] = None,
1560
+ inputs_embeds: Optional[torch.Tensor] = None,
1561
+ encoder_hidden_states: Optional[torch.Tensor] = None,
1562
+ encoder_attention_mask: Optional[torch.Tensor] = None,
1563
+ labels: Optional[torch.Tensor] = None,
1564
+ past_key_values: Optional[List[torch.Tensor]] = None,
1565
+ use_cache: Optional[bool] = None,
1566
+ output_attentions: Optional[bool] = None,
1567
+ output_hidden_states: Optional[bool] = None,
1568
+ return_dict: Optional[bool] = None,
1569
+ ) -> Union[Tuple[torch.Tensor], CausalLMOutputWithCrossAttentions]:
1570
+ r"""
1571
+ encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
1572
+ Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if
1573
+ the model is configured as a decoder.
1574
+ encoder_attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
1575
+ Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in
1576
+ the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`:
1577
+
1578
+ - 1 for tokens that are **not masked**,
1579
+ - 0 for tokens that are **masked**.
1580
+
1581
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1582
+ Labels for computing the left-to-right language modeling loss (next word prediction). Indices should be in
1583
+ `[-100, 0, ..., config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are
1584
+ ignored (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
1585
+ 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)`):
1586
+ Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.
1587
+
1588
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
1589
+ don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
1590
+ `decoder_input_ids` of shape `(batch_size, sequence_length)`.
1591
+ use_cache (`bool`, *optional*):
1592
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
1593
+ `past_key_values`).
1594
+
1595
+ Returns:
1596
+
1597
+ Example:
1598
+
1599
+ ```python
1600
+ >>> from transformers import AutoTokenizer, ElectraForCausalLM, ElectraConfig
1601
+ >>> import torch
1602
+
1603
+ >>> tokenizer = AutoTokenizer.from_pretrained("google/electra-base-generator")
1604
+ >>> config = ElectraConfig.from_pretrained("google/electra-base-generator")
1605
+ >>> config.is_decoder = True
1606
+ >>> model = ElectraForCausalLM.from_pretrained("google/electra-base-generator", config=config)
1607
+
1608
+ >>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")
1609
+ >>> outputs = model(**inputs)
1610
+
1611
+ >>> prediction_logits = outputs.logits
1612
+ ```"""
1613
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1614
+ if labels is not None:
1615
+ use_cache = False
1616
+
1617
+ outputs = self.electra(
1618
+ input_ids,
1619
+ attention_mask=attention_mask,
1620
+ token_type_ids=token_type_ids,
1621
+ position_ids=position_ids,
1622
+ head_mask=head_mask,
1623
+ inputs_embeds=inputs_embeds,
1624
+ encoder_hidden_states=encoder_hidden_states,
1625
+ encoder_attention_mask=encoder_attention_mask,
1626
+ past_key_values=past_key_values,
1627
+ use_cache=use_cache,
1628
+ output_attentions=output_attentions,
1629
+ output_hidden_states=output_hidden_states,
1630
+ return_dict=return_dict,
1631
+ )
1632
+
1633
+ sequence_output = outputs[0]
1634
+ prediction_scores = self.generator_lm_head(self.generator_predictions(sequence_output))
1635
+
1636
+ lm_loss = None
1637
+ if labels is not None:
1638
+ # we are doing next-token prediction; shift prediction scores and input ids by one
1639
+ shifted_prediction_scores = prediction_scores[:, :-1, :].contiguous()
1640
+ labels = labels[:, 1:].contiguous()
1641
+ loss_fct = CrossEntropyLoss()
1642
+ lm_loss = loss_fct(shifted_prediction_scores.view(-1, self.config.vocab_size), labels.view(-1))
1643
+
1644
+ if not return_dict:
1645
+ output = (prediction_scores,) + outputs[1:]
1646
+ return ((lm_loss,) + output) if lm_loss is not None else output
1647
+
1648
+ return CausalLMOutputWithCrossAttentions(
1649
+ loss=lm_loss,
1650
+ logits=prediction_scores,
1651
+ past_key_values=outputs.past_key_values,
1652
+ hidden_states=outputs.hidden_states,
1653
+ attentions=outputs.attentions,
1654
+ cross_attentions=outputs.cross_attentions,
1655
+ )
1656
+
1657
+ # Copied from transformers.models.roberta.modeling_roberta.RobertaForCausalLM.prepare_inputs_for_generation
1658
+ def prepare_inputs_for_generation(self, input_ids, past_key_values=None, attention_mask=None, **model_kwargs):
1659
+ input_shape = input_ids.shape
1660
+ # if model is used as a decoder in encoder-decoder model, the decoder attention mask is created on the fly
1661
+ if attention_mask is None:
1662
+ attention_mask = input_ids.new_ones(input_shape)
1663
+
1664
+ # cut decoder_input_ids if past_key_values is used
1665
+ if past_key_values is not None:
1666
+ past_length = past_key_values[0][0].shape[2]
1667
+
1668
+ # Some generation methods already pass only the last input ID
1669
+ if input_ids.shape[1] > past_length:
1670
+ remove_prefix_length = past_length
1671
+ else:
1672
+ # Default to old behavior: keep only final ID
1673
+ remove_prefix_length = input_ids.shape[1] - 1
1674
+
1675
+ input_ids = input_ids[:, remove_prefix_length:]
1676
+
1677
+ return {"input_ids": input_ids, "attention_mask": attention_mask, "past_key_values": past_key_values}
1678
+
1679
+ # Copied from transformers.models.roberta.modeling_roberta.RobertaForCausalLM._reorder_cache
1680
+ def _reorder_cache(self, past_key_values, beam_idx):
1681
+ reordered_past = ()
1682
+ for layer_past in past_key_values:
1683
+ reordered_past += (
1684
+ tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
1685
+ )
1686
+ return reordered_past
pllava/lib/python3.10/site-packages/transformers/models/electra/modeling_flax_electra.py ADDED
@@ -0,0 +1,1601 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2021 The Google Flax 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
+
16
+ from typing import Callable, Optional, Tuple
17
+
18
+ import flax
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.linen import combine_masks, make_causal_mask
25
+ from flax.linen import partitioning as nn_partitioning
26
+ from flax.linen.attention import dot_product_attention_weights
27
+ from flax.traverse_util import flatten_dict, unflatten_dict
28
+ from jax import lax
29
+
30
+ from ...modeling_flax_outputs import (
31
+ FlaxBaseModelOutput,
32
+ FlaxBaseModelOutputWithPastAndCrossAttentions,
33
+ FlaxCausalLMOutputWithCrossAttentions,
34
+ FlaxMaskedLMOutput,
35
+ FlaxMultipleChoiceModelOutput,
36
+ FlaxQuestionAnsweringModelOutput,
37
+ FlaxSequenceClassifierOutput,
38
+ FlaxTokenClassifierOutput,
39
+ )
40
+ from ...modeling_flax_utils import (
41
+ ACT2FN,
42
+ FlaxPreTrainedModel,
43
+ append_call_sample_docstring,
44
+ append_replace_return_docstrings,
45
+ overwrite_call_docstring,
46
+ )
47
+ from ...utils import ModelOutput, add_start_docstrings, add_start_docstrings_to_model_forward, logging
48
+ from .configuration_electra import ElectraConfig
49
+
50
+
51
+ logger = logging.get_logger(__name__)
52
+
53
+ _CHECKPOINT_FOR_DOC = "google/electra-small-discriminator"
54
+ _CONFIG_FOR_DOC = "ElectraConfig"
55
+
56
+ remat = nn_partitioning.remat
57
+
58
+
59
+ @flax.struct.dataclass
60
+ class FlaxElectraForPreTrainingOutput(ModelOutput):
61
+ """
62
+ Output type of [`ElectraForPreTraining`].
63
+
64
+ Args:
65
+ logits (`jnp.ndarray` of shape `(batch_size, sequence_length, config.vocab_size)`):
66
+ Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
67
+ hidden_states (`tuple(jnp.ndarray)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
68
+ Tuple of `jnp.ndarray` (one for the output of the embeddings + one for the output of each layer) of shape
69
+ `(batch_size, sequence_length, hidden_size)`.
70
+
71
+ Hidden-states of the model at the output of each layer plus the initial embedding outputs.
72
+ attentions (`tuple(jnp.ndarray)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
73
+ Tuple of `jnp.ndarray` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
74
+ sequence_length)`.
75
+
76
+ Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
77
+ heads.
78
+ """
79
+
80
+ logits: jnp.ndarray = None
81
+ hidden_states: Optional[Tuple[jnp.ndarray]] = None
82
+ attentions: Optional[Tuple[jnp.ndarray]] = None
83
+
84
+
85
+ ELECTRA_START_DOCSTRING = r"""
86
+
87
+ This model inherits from [`FlaxPreTrainedModel`]. Check the superclass documentation for the generic methods the
88
+ library implements for all its model (such as downloading, saving and converting weights from PyTorch models)
89
+
90
+ This model is also a Flax Linen
91
+ [flax.nn.Module](https://flax.readthedocs.io/en/latest/_autosummary/flax.nn.module.html) subclass. Use it as a
92
+ regular Flax Module and refer to the Flax documentation for all matter related to general usage and behavior.
93
+
94
+ Finally, this model supports inherent JAX features such as:
95
+
96
+ - [Just-In-Time (JIT) compilation](https://jax.readthedocs.io/en/latest/jax.html#just-in-time-compilation-jit)
97
+ - [Automatic Differentiation](https://jax.readthedocs.io/en/latest/jax.html#automatic-differentiation)
98
+ - [Vectorization](https://jax.readthedocs.io/en/latest/jax.html#vectorization-vmap)
99
+ - [Parallelization](https://jax.readthedocs.io/en/latest/jax.html#parallelization-pmap)
100
+
101
+ Parameters:
102
+ config ([`ElectraConfig`]): Model configuration class with all the parameters of the model.
103
+ Initializing with a config file does not load the weights associated with the model, only the
104
+ configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
105
+ """
106
+
107
+ ELECTRA_INPUTS_DOCSTRING = r"""
108
+ Args:
109
+ input_ids (`numpy.ndarray` of shape `({0})`):
110
+ Indices of input sequence tokens in the vocabulary.
111
+
112
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
113
+ [`PreTrainedTokenizer.__call__`] for details.
114
+
115
+ [What are input IDs?](../glossary#input-ids)
116
+ attention_mask (`numpy.ndarray` of shape `({0})`, *optional*):
117
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
118
+
119
+ - 1 for tokens that are **not masked**,
120
+ - 0 for tokens that are **masked**.
121
+
122
+ [What are attention masks?](../glossary#attention-mask)
123
+ token_type_ids (`numpy.ndarray` of shape `({0})`, *optional*):
124
+ Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
125
+ 1]`:
126
+
127
+ - 0 corresponds to a *sentence A* token,
128
+ - 1 corresponds to a *sentence B* token.
129
+
130
+ [What are token type IDs?](../glossary#token-type-ids)
131
+ position_ids (`numpy.ndarray` of shape `({0})`, *optional*):
132
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
133
+ config.max_position_embeddings - 1]`.
134
+ head_mask (`numpy.ndarray` of shape `({0})`, `optional):
135
+ Mask to nullify selected heads of the attention modules. Mask values selected in `[0, 1]`:
136
+
137
+ - 1 indicates the head is **not masked**,
138
+ - 0 indicates the head is **masked**.
139
+
140
+ return_dict (`bool`, *optional*):
141
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
142
+
143
+ """
144
+
145
+
146
+ class FlaxElectraEmbeddings(nn.Module):
147
+ """Construct the embeddings from word, position and token_type embeddings."""
148
+
149
+ config: ElectraConfig
150
+ dtype: jnp.dtype = jnp.float32 # the dtype of the computation
151
+
152
+ def setup(self):
153
+ self.word_embeddings = nn.Embed(
154
+ self.config.vocab_size,
155
+ self.config.embedding_size,
156
+ embedding_init=jax.nn.initializers.normal(stddev=self.config.initializer_range),
157
+ )
158
+ self.position_embeddings = nn.Embed(
159
+ self.config.max_position_embeddings,
160
+ self.config.embedding_size,
161
+ embedding_init=jax.nn.initializers.normal(stddev=self.config.initializer_range),
162
+ )
163
+ self.token_type_embeddings = nn.Embed(
164
+ self.config.type_vocab_size,
165
+ self.config.embedding_size,
166
+ embedding_init=jax.nn.initializers.normal(stddev=self.config.initializer_range),
167
+ )
168
+ self.LayerNorm = nn.LayerNorm(epsilon=self.config.layer_norm_eps, dtype=self.dtype)
169
+ self.dropout = nn.Dropout(rate=self.config.hidden_dropout_prob)
170
+
171
+ # Copied from transformers.models.bert.modeling_flax_bert.FlaxBertEmbeddings.__call__
172
+ def __call__(self, input_ids, token_type_ids, position_ids, attention_mask, deterministic: bool = True):
173
+ # Embed
174
+ inputs_embeds = self.word_embeddings(input_ids.astype("i4"))
175
+ position_embeds = self.position_embeddings(position_ids.astype("i4"))
176
+ token_type_embeddings = self.token_type_embeddings(token_type_ids.astype("i4"))
177
+
178
+ # Sum all embeddings
179
+ hidden_states = inputs_embeds + token_type_embeddings + position_embeds
180
+
181
+ # Layer Norm
182
+ hidden_states = self.LayerNorm(hidden_states)
183
+ hidden_states = self.dropout(hidden_states, deterministic=deterministic)
184
+ return hidden_states
185
+
186
+
187
+ # Copied from transformers.models.bert.modeling_flax_bert.FlaxBertSelfAttention with Bert->Electra
188
+ class FlaxElectraSelfAttention(nn.Module):
189
+ config: ElectraConfig
190
+ causal: bool = False
191
+ dtype: jnp.dtype = jnp.float32 # the dtype of the computation
192
+
193
+ def setup(self):
194
+ self.head_dim = self.config.hidden_size // self.config.num_attention_heads
195
+ if self.config.hidden_size % self.config.num_attention_heads != 0:
196
+ raise ValueError(
197
+ "`config.hidden_size`: {self.config.hidden_size} has to be a multiple of `config.num_attention_heads` "
198
+ " : {self.config.num_attention_heads}"
199
+ )
200
+
201
+ self.query = nn.Dense(
202
+ self.config.hidden_size,
203
+ dtype=self.dtype,
204
+ kernel_init=jax.nn.initializers.normal(self.config.initializer_range),
205
+ )
206
+ self.key = nn.Dense(
207
+ self.config.hidden_size,
208
+ dtype=self.dtype,
209
+ kernel_init=jax.nn.initializers.normal(self.config.initializer_range),
210
+ )
211
+ self.value = nn.Dense(
212
+ self.config.hidden_size,
213
+ dtype=self.dtype,
214
+ kernel_init=jax.nn.initializers.normal(self.config.initializer_range),
215
+ )
216
+
217
+ if self.causal:
218
+ self.causal_mask = make_causal_mask(
219
+ jnp.ones((1, self.config.max_position_embeddings), dtype="bool"), dtype="bool"
220
+ )
221
+
222
+ def _split_heads(self, hidden_states):
223
+ return hidden_states.reshape(hidden_states.shape[:2] + (self.config.num_attention_heads, self.head_dim))
224
+
225
+ def _merge_heads(self, hidden_states):
226
+ return hidden_states.reshape(hidden_states.shape[:2] + (self.config.hidden_size,))
227
+
228
+ @nn.compact
229
+ # Copied from transformers.models.bart.modeling_flax_bart.FlaxBartAttention._concatenate_to_cache
230
+ def _concatenate_to_cache(self, key, value, query, attention_mask):
231
+ """
232
+ This function takes projected key, value states from a single input token and concatenates the states to cached
233
+ states from previous steps. This function is slighly adapted from the official Flax repository:
234
+ https://github.com/google/flax/blob/491ce18759622506588784b4fca0e4bf05f8c8cd/flax/linen/attention.py#L252
235
+ """
236
+ # detect if we're initializing by absence of existing cache data.
237
+ is_initialized = self.has_variable("cache", "cached_key")
238
+ cached_key = self.variable("cache", "cached_key", jnp.zeros, key.shape, key.dtype)
239
+ cached_value = self.variable("cache", "cached_value", jnp.zeros, value.shape, value.dtype)
240
+ cache_index = self.variable("cache", "cache_index", lambda: jnp.array(0, dtype=jnp.int32))
241
+
242
+ if is_initialized:
243
+ *batch_dims, max_length, num_heads, depth_per_head = cached_key.value.shape
244
+ # update key, value caches with our new 1d spatial slices
245
+ cur_index = cache_index.value
246
+ indices = (0,) * len(batch_dims) + (cur_index, 0, 0)
247
+ key = lax.dynamic_update_slice(cached_key.value, key, indices)
248
+ value = lax.dynamic_update_slice(cached_value.value, value, indices)
249
+ cached_key.value = key
250
+ cached_value.value = value
251
+ num_updated_cache_vectors = query.shape[1]
252
+ cache_index.value = cache_index.value + num_updated_cache_vectors
253
+ # 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.
254
+ pad_mask = jnp.broadcast_to(
255
+ jnp.arange(max_length) < cur_index + num_updated_cache_vectors,
256
+ tuple(batch_dims) + (1, num_updated_cache_vectors, max_length),
257
+ )
258
+ attention_mask = combine_masks(pad_mask, attention_mask)
259
+ return key, value, attention_mask
260
+
261
+ def __call__(
262
+ self,
263
+ hidden_states,
264
+ attention_mask,
265
+ layer_head_mask,
266
+ key_value_states: Optional[jnp.ndarray] = None,
267
+ init_cache: bool = False,
268
+ deterministic=True,
269
+ output_attentions: bool = False,
270
+ ):
271
+ # if key_value_states are provided this layer is used as a cross-attention layer
272
+ # for the decoder
273
+ is_cross_attention = key_value_states is not None
274
+ batch_size = hidden_states.shape[0]
275
+
276
+ # get query proj
277
+ query_states = self.query(hidden_states)
278
+ # get key, value proj
279
+ if is_cross_attention:
280
+ # cross_attentions
281
+ key_states = self.key(key_value_states)
282
+ value_states = self.value(key_value_states)
283
+ else:
284
+ # self_attention
285
+ key_states = self.key(hidden_states)
286
+ value_states = self.value(hidden_states)
287
+
288
+ query_states = self._split_heads(query_states)
289
+ key_states = self._split_heads(key_states)
290
+ value_states = self._split_heads(value_states)
291
+
292
+ # handle cache prepare causal attention mask
293
+ if self.causal:
294
+ query_length, key_length = query_states.shape[1], key_states.shape[1]
295
+ if self.has_variable("cache", "cached_key"):
296
+ mask_shift = self.variables["cache"]["cache_index"]
297
+ max_decoder_length = self.variables["cache"]["cached_key"].shape[1]
298
+ causal_mask = lax.dynamic_slice(
299
+ self.causal_mask, (0, 0, mask_shift, 0), (1, 1, query_length, max_decoder_length)
300
+ )
301
+ else:
302
+ causal_mask = self.causal_mask[:, :, :query_length, :key_length]
303
+ causal_mask = jnp.broadcast_to(causal_mask, (batch_size,) + causal_mask.shape[1:])
304
+
305
+ # combine masks if needed
306
+ if attention_mask is not None and self.causal:
307
+ attention_mask = jnp.broadcast_to(jnp.expand_dims(attention_mask, axis=(-3, -2)), causal_mask.shape)
308
+ attention_mask = combine_masks(attention_mask, causal_mask)
309
+ elif self.causal:
310
+ attention_mask = causal_mask
311
+ elif attention_mask is not None:
312
+ attention_mask = jnp.expand_dims(attention_mask, axis=(-3, -2))
313
+
314
+ # During fast autoregressive decoding, we feed one position at a time,
315
+ # and cache the keys and values step by step.
316
+ if self.causal and (self.has_variable("cache", "cached_key") or init_cache):
317
+ key_states, value_states, attention_mask = self._concatenate_to_cache(
318
+ key_states, value_states, query_states, attention_mask
319
+ )
320
+
321
+ # Convert the boolean attention mask to an attention bias.
322
+ if attention_mask is not None:
323
+ # attention mask in the form of attention bias
324
+ attention_bias = lax.select(
325
+ attention_mask > 0,
326
+ jnp.full(attention_mask.shape, 0.0).astype(self.dtype),
327
+ jnp.full(attention_mask.shape, jnp.finfo(self.dtype).min).astype(self.dtype),
328
+ )
329
+ else:
330
+ attention_bias = None
331
+
332
+ dropout_rng = None
333
+ if not deterministic and self.config.attention_probs_dropout_prob > 0.0:
334
+ dropout_rng = self.make_rng("dropout")
335
+
336
+ attn_weights = dot_product_attention_weights(
337
+ query_states,
338
+ key_states,
339
+ bias=attention_bias,
340
+ dropout_rng=dropout_rng,
341
+ dropout_rate=self.config.attention_probs_dropout_prob,
342
+ broadcast_dropout=True,
343
+ deterministic=deterministic,
344
+ dtype=self.dtype,
345
+ precision=None,
346
+ )
347
+
348
+ # Mask heads if we want to
349
+ if layer_head_mask is not None:
350
+ attn_weights = jnp.einsum("...hqk,h->...hqk", attn_weights, layer_head_mask)
351
+
352
+ attn_output = jnp.einsum("...hqk,...khd->...qhd", attn_weights, value_states)
353
+ attn_output = attn_output.reshape(attn_output.shape[:2] + (-1,))
354
+
355
+ outputs = (attn_output, attn_weights) if output_attentions else (attn_output,)
356
+ return outputs
357
+
358
+
359
+ # Copied from transformers.models.bert.modeling_flax_bert.FlaxBertSelfOutput with Bert->Electra
360
+ class FlaxElectraSelfOutput(nn.Module):
361
+ config: ElectraConfig
362
+ dtype: jnp.dtype = jnp.float32 # the dtype of the computation
363
+
364
+ def setup(self):
365
+ self.dense = nn.Dense(
366
+ self.config.hidden_size,
367
+ kernel_init=jax.nn.initializers.normal(self.config.initializer_range),
368
+ dtype=self.dtype,
369
+ )
370
+ self.LayerNorm = nn.LayerNorm(epsilon=self.config.layer_norm_eps, dtype=self.dtype)
371
+ self.dropout = nn.Dropout(rate=self.config.hidden_dropout_prob)
372
+
373
+ def __call__(self, hidden_states, input_tensor, deterministic: bool = True):
374
+ hidden_states = self.dense(hidden_states)
375
+ hidden_states = self.dropout(hidden_states, deterministic=deterministic)
376
+ hidden_states = self.LayerNorm(hidden_states + input_tensor)
377
+ return hidden_states
378
+
379
+
380
+ # Copied from transformers.models.bert.modeling_flax_bert.FlaxBertAttention with Bert->Electra
381
+ class FlaxElectraAttention(nn.Module):
382
+ config: ElectraConfig
383
+ causal: bool = False
384
+ dtype: jnp.dtype = jnp.float32
385
+
386
+ def setup(self):
387
+ self.self = FlaxElectraSelfAttention(self.config, causal=self.causal, dtype=self.dtype)
388
+ self.output = FlaxElectraSelfOutput(self.config, dtype=self.dtype)
389
+
390
+ def __call__(
391
+ self,
392
+ hidden_states,
393
+ attention_mask,
394
+ layer_head_mask,
395
+ key_value_states=None,
396
+ init_cache=False,
397
+ deterministic=True,
398
+ output_attentions: bool = False,
399
+ ):
400
+ # Attention mask comes in as attention_mask.shape == (*batch_sizes, kv_length)
401
+ # FLAX expects: attention_mask.shape == (*batch_sizes, 1, 1, kv_length) such that it is broadcastable
402
+ # with attn_weights.shape == (*batch_sizes, num_heads, q_length, kv_length)
403
+ attn_outputs = self.self(
404
+ hidden_states,
405
+ attention_mask,
406
+ layer_head_mask=layer_head_mask,
407
+ key_value_states=key_value_states,
408
+ init_cache=init_cache,
409
+ deterministic=deterministic,
410
+ output_attentions=output_attentions,
411
+ )
412
+ attn_output = attn_outputs[0]
413
+ hidden_states = self.output(attn_output, hidden_states, deterministic=deterministic)
414
+
415
+ outputs = (hidden_states,)
416
+
417
+ if output_attentions:
418
+ outputs += (attn_outputs[1],)
419
+
420
+ return outputs
421
+
422
+
423
+ # Copied from transformers.models.bert.modeling_flax_bert.FlaxBertIntermediate with Bert->Electra
424
+ class FlaxElectraIntermediate(nn.Module):
425
+ config: ElectraConfig
426
+ dtype: jnp.dtype = jnp.float32 # the dtype of the computation
427
+
428
+ def setup(self):
429
+ self.dense = nn.Dense(
430
+ self.config.intermediate_size,
431
+ kernel_init=jax.nn.initializers.normal(self.config.initializer_range),
432
+ dtype=self.dtype,
433
+ )
434
+ self.activation = ACT2FN[self.config.hidden_act]
435
+
436
+ def __call__(self, hidden_states):
437
+ hidden_states = self.dense(hidden_states)
438
+ hidden_states = self.activation(hidden_states)
439
+ return hidden_states
440
+
441
+
442
+ # Copied from transformers.models.bert.modeling_flax_bert.FlaxBertOutput with Bert->Electra
443
+ class FlaxElectraOutput(nn.Module):
444
+ config: ElectraConfig
445
+ dtype: jnp.dtype = jnp.float32 # the dtype of the computation
446
+
447
+ def setup(self):
448
+ self.dense = nn.Dense(
449
+ self.config.hidden_size,
450
+ kernel_init=jax.nn.initializers.normal(self.config.initializer_range),
451
+ dtype=self.dtype,
452
+ )
453
+ self.dropout = nn.Dropout(rate=self.config.hidden_dropout_prob)
454
+ self.LayerNorm = nn.LayerNorm(epsilon=self.config.layer_norm_eps, dtype=self.dtype)
455
+
456
+ def __call__(self, hidden_states, attention_output, deterministic: bool = True):
457
+ hidden_states = self.dense(hidden_states)
458
+ hidden_states = self.dropout(hidden_states, deterministic=deterministic)
459
+ hidden_states = self.LayerNorm(hidden_states + attention_output)
460
+ return hidden_states
461
+
462
+
463
+ # Copied from transformers.models.bert.modeling_flax_bert.FlaxBertLayer with Bert->Electra
464
+ class FlaxElectraLayer(nn.Module):
465
+ config: ElectraConfig
466
+ dtype: jnp.dtype = jnp.float32 # the dtype of the computation
467
+
468
+ def setup(self):
469
+ self.attention = FlaxElectraAttention(self.config, causal=self.config.is_decoder, dtype=self.dtype)
470
+ self.intermediate = FlaxElectraIntermediate(self.config, dtype=self.dtype)
471
+ self.output = FlaxElectraOutput(self.config, dtype=self.dtype)
472
+ if self.config.add_cross_attention:
473
+ self.crossattention = FlaxElectraAttention(self.config, causal=False, dtype=self.dtype)
474
+
475
+ def __call__(
476
+ self,
477
+ hidden_states,
478
+ attention_mask,
479
+ layer_head_mask,
480
+ encoder_hidden_states: Optional[jnp.ndarray] = None,
481
+ encoder_attention_mask: Optional[jnp.ndarray] = None,
482
+ init_cache: bool = False,
483
+ deterministic: bool = True,
484
+ output_attentions: bool = False,
485
+ ):
486
+ # Self Attention
487
+ attention_outputs = self.attention(
488
+ hidden_states,
489
+ attention_mask,
490
+ layer_head_mask=layer_head_mask,
491
+ init_cache=init_cache,
492
+ deterministic=deterministic,
493
+ output_attentions=output_attentions,
494
+ )
495
+ attention_output = attention_outputs[0]
496
+
497
+ # Cross-Attention Block
498
+ if encoder_hidden_states is not None:
499
+ cross_attention_outputs = self.crossattention(
500
+ attention_output,
501
+ attention_mask=encoder_attention_mask,
502
+ layer_head_mask=layer_head_mask,
503
+ key_value_states=encoder_hidden_states,
504
+ deterministic=deterministic,
505
+ output_attentions=output_attentions,
506
+ )
507
+ attention_output = cross_attention_outputs[0]
508
+
509
+ hidden_states = self.intermediate(attention_output)
510
+ hidden_states = self.output(hidden_states, attention_output, deterministic=deterministic)
511
+
512
+ outputs = (hidden_states,)
513
+
514
+ if output_attentions:
515
+ outputs += (attention_outputs[1],)
516
+ if encoder_hidden_states is not None:
517
+ outputs += (cross_attention_outputs[1],)
518
+ return outputs
519
+
520
+
521
+ # Copied from transformers.models.bert.modeling_flax_bert.FlaxBertLayerCollection with Bert->Electra
522
+ class FlaxElectraLayerCollection(nn.Module):
523
+ config: ElectraConfig
524
+ dtype: jnp.dtype = jnp.float32 # the dtype of the computation
525
+ gradient_checkpointing: bool = False
526
+
527
+ def setup(self):
528
+ if self.gradient_checkpointing:
529
+ FlaxElectraCheckpointLayer = remat(FlaxElectraLayer, static_argnums=(5, 6, 7))
530
+ self.layers = [
531
+ FlaxElectraCheckpointLayer(self.config, name=str(i), dtype=self.dtype)
532
+ for i in range(self.config.num_hidden_layers)
533
+ ]
534
+ else:
535
+ self.layers = [
536
+ FlaxElectraLayer(self.config, name=str(i), dtype=self.dtype)
537
+ for i in range(self.config.num_hidden_layers)
538
+ ]
539
+
540
+ def __call__(
541
+ self,
542
+ hidden_states,
543
+ attention_mask,
544
+ head_mask,
545
+ encoder_hidden_states: Optional[jnp.ndarray] = None,
546
+ encoder_attention_mask: Optional[jnp.ndarray] = None,
547
+ init_cache: bool = False,
548
+ deterministic: bool = True,
549
+ output_attentions: bool = False,
550
+ output_hidden_states: bool = False,
551
+ return_dict: bool = True,
552
+ ):
553
+ all_attentions = () if output_attentions else None
554
+ all_hidden_states = () if output_hidden_states else None
555
+ all_cross_attentions = () if (output_attentions and encoder_hidden_states is not None) else None
556
+
557
+ # Check if head_mask has a correct number of layers specified if desired
558
+ if head_mask is not None:
559
+ if head_mask.shape[0] != (len(self.layers)):
560
+ raise ValueError(
561
+ f"The head_mask should be specified for {len(self.layers)} layers, but it is for "
562
+ f" {head_mask.shape[0]}."
563
+ )
564
+
565
+ for i, layer in enumerate(self.layers):
566
+ if output_hidden_states:
567
+ all_hidden_states += (hidden_states,)
568
+
569
+ layer_outputs = layer(
570
+ hidden_states,
571
+ attention_mask,
572
+ head_mask[i] if head_mask is not None else None,
573
+ encoder_hidden_states,
574
+ encoder_attention_mask,
575
+ init_cache,
576
+ deterministic,
577
+ output_attentions,
578
+ )
579
+
580
+ hidden_states = layer_outputs[0]
581
+
582
+ if output_attentions:
583
+ all_attentions += (layer_outputs[1],)
584
+
585
+ if encoder_hidden_states is not None:
586
+ all_cross_attentions += (layer_outputs[2],)
587
+
588
+ if output_hidden_states:
589
+ all_hidden_states += (hidden_states,)
590
+
591
+ outputs = (hidden_states, all_hidden_states, all_attentions, all_cross_attentions)
592
+
593
+ if not return_dict:
594
+ return tuple(v for v in outputs if v is not None)
595
+
596
+ return FlaxBaseModelOutputWithPastAndCrossAttentions(
597
+ last_hidden_state=hidden_states,
598
+ hidden_states=all_hidden_states,
599
+ attentions=all_attentions,
600
+ cross_attentions=all_cross_attentions,
601
+ )
602
+
603
+
604
+ # Copied from transformers.models.bert.modeling_flax_bert.FlaxBertEncoder with Bert->Electra
605
+ class FlaxElectraEncoder(nn.Module):
606
+ config: ElectraConfig
607
+ dtype: jnp.dtype = jnp.float32 # the dtype of the computation
608
+ gradient_checkpointing: bool = False
609
+
610
+ def setup(self):
611
+ self.layer = FlaxElectraLayerCollection(
612
+ self.config,
613
+ dtype=self.dtype,
614
+ gradient_checkpointing=self.gradient_checkpointing,
615
+ )
616
+
617
+ def __call__(
618
+ self,
619
+ hidden_states,
620
+ attention_mask,
621
+ head_mask,
622
+ encoder_hidden_states: Optional[jnp.ndarray] = None,
623
+ encoder_attention_mask: Optional[jnp.ndarray] = None,
624
+ init_cache: bool = False,
625
+ deterministic: bool = True,
626
+ output_attentions: bool = False,
627
+ output_hidden_states: bool = False,
628
+ return_dict: bool = True,
629
+ ):
630
+ return self.layer(
631
+ hidden_states,
632
+ attention_mask,
633
+ head_mask=head_mask,
634
+ encoder_hidden_states=encoder_hidden_states,
635
+ encoder_attention_mask=encoder_attention_mask,
636
+ init_cache=init_cache,
637
+ deterministic=deterministic,
638
+ output_attentions=output_attentions,
639
+ output_hidden_states=output_hidden_states,
640
+ return_dict=return_dict,
641
+ )
642
+
643
+
644
+ class FlaxElectraGeneratorPredictions(nn.Module):
645
+ config: ElectraConfig
646
+ dtype: jnp.dtype = jnp.float32
647
+
648
+ def setup(self):
649
+ self.LayerNorm = nn.LayerNorm(epsilon=self.config.layer_norm_eps, dtype=self.dtype)
650
+ self.dense = nn.Dense(self.config.embedding_size, dtype=self.dtype)
651
+
652
+ def __call__(self, hidden_states):
653
+ hidden_states = self.dense(hidden_states)
654
+ hidden_states = ACT2FN[self.config.hidden_act](hidden_states)
655
+ hidden_states = self.LayerNorm(hidden_states)
656
+ return hidden_states
657
+
658
+
659
+ class FlaxElectraDiscriminatorPredictions(nn.Module):
660
+ """Prediction module for the discriminator, made up of two dense layers."""
661
+
662
+ config: ElectraConfig
663
+ dtype: jnp.dtype = jnp.float32
664
+
665
+ def setup(self):
666
+ self.dense = nn.Dense(self.config.hidden_size, dtype=self.dtype)
667
+ self.dense_prediction = nn.Dense(1, dtype=self.dtype)
668
+
669
+ def __call__(self, hidden_states):
670
+ hidden_states = self.dense(hidden_states)
671
+ hidden_states = ACT2FN[self.config.hidden_act](hidden_states)
672
+ hidden_states = self.dense_prediction(hidden_states).squeeze(-1)
673
+ return hidden_states
674
+
675
+
676
+ class FlaxElectraPreTrainedModel(FlaxPreTrainedModel):
677
+ """
678
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
679
+ models.
680
+ """
681
+
682
+ config_class = ElectraConfig
683
+ base_model_prefix = "electra"
684
+ module_class: nn.Module = None
685
+
686
+ def __init__(
687
+ self,
688
+ config: ElectraConfig,
689
+ input_shape: Tuple = (1, 1),
690
+ seed: int = 0,
691
+ dtype: jnp.dtype = jnp.float32,
692
+ _do_init: bool = True,
693
+ gradient_checkpointing: bool = False,
694
+ **kwargs,
695
+ ):
696
+ module = self.module_class(config=config, dtype=dtype, gradient_checkpointing=gradient_checkpointing, **kwargs)
697
+ super().__init__(config, module, input_shape=input_shape, seed=seed, dtype=dtype, _do_init=_do_init)
698
+
699
+ # Copied from transformers.models.bert.modeling_flax_bert.FlaxBertPreTrainedModel.enable_gradient_checkpointing
700
+ def enable_gradient_checkpointing(self):
701
+ self._module = self.module_class(
702
+ config=self.config,
703
+ dtype=self.dtype,
704
+ gradient_checkpointing=True,
705
+ )
706
+
707
+ # Copied from transformers.models.bert.modeling_flax_bert.FlaxBertPreTrainedModel.init_weights
708
+ def init_weights(self, rng: jax.random.PRNGKey, input_shape: Tuple, params: FrozenDict = None) -> FrozenDict:
709
+ # init input tensors
710
+ input_ids = jnp.zeros(input_shape, dtype="i4")
711
+ token_type_ids = jnp.zeros_like(input_ids)
712
+ position_ids = jnp.broadcast_to(jnp.arange(jnp.atleast_2d(input_ids).shape[-1]), input_shape)
713
+ attention_mask = jnp.ones_like(input_ids)
714
+ head_mask = jnp.ones((self.config.num_hidden_layers, self.config.num_attention_heads))
715
+
716
+ params_rng, dropout_rng = jax.random.split(rng)
717
+ rngs = {"params": params_rng, "dropout": dropout_rng}
718
+
719
+ if self.config.add_cross_attention:
720
+ encoder_hidden_states = jnp.zeros(input_shape + (self.config.hidden_size,))
721
+ encoder_attention_mask = attention_mask
722
+ module_init_outputs = self.module.init(
723
+ rngs,
724
+ input_ids,
725
+ attention_mask,
726
+ token_type_ids,
727
+ position_ids,
728
+ head_mask,
729
+ encoder_hidden_states,
730
+ encoder_attention_mask,
731
+ return_dict=False,
732
+ )
733
+ else:
734
+ module_init_outputs = self.module.init(
735
+ rngs, input_ids, attention_mask, token_type_ids, position_ids, head_mask, return_dict=False
736
+ )
737
+
738
+ random_params = module_init_outputs["params"]
739
+
740
+ if params is not None:
741
+ random_params = flatten_dict(unfreeze(random_params))
742
+ params = flatten_dict(unfreeze(params))
743
+ for missing_key in self._missing_keys:
744
+ params[missing_key] = random_params[missing_key]
745
+ self._missing_keys = set()
746
+ return freeze(unflatten_dict(params))
747
+ else:
748
+ return random_params
749
+
750
+ # Copied from transformers.models.bart.modeling_flax_bart.FlaxBartDecoderPreTrainedModel.init_cache
751
+ def init_cache(self, batch_size, max_length):
752
+ r"""
753
+ Args:
754
+ batch_size (`int`):
755
+ batch_size used for fast auto-regressive decoding. Defines the batch size of the initialized cache.
756
+ max_length (`int`):
757
+ maximum possible length for auto-regressive decoding. Defines the sequence length of the initialized
758
+ cache.
759
+ """
760
+ # init input variables to retrieve cache
761
+ input_ids = jnp.ones((batch_size, max_length), dtype="i4")
762
+ attention_mask = jnp.ones_like(input_ids, dtype="i4")
763
+ position_ids = jnp.broadcast_to(jnp.arange(jnp.atleast_2d(input_ids).shape[-1]), input_ids.shape)
764
+
765
+ init_variables = self.module.init(
766
+ jax.random.PRNGKey(0), input_ids, attention_mask, position_ids, return_dict=False, init_cache=True
767
+ )
768
+ return unfreeze(init_variables["cache"])
769
+
770
+ @add_start_docstrings_to_model_forward(ELECTRA_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
771
+ def __call__(
772
+ self,
773
+ input_ids,
774
+ attention_mask=None,
775
+ token_type_ids=None,
776
+ position_ids=None,
777
+ head_mask=None,
778
+ encoder_hidden_states=None,
779
+ encoder_attention_mask=None,
780
+ params: dict = None,
781
+ dropout_rng: jax.random.PRNGKey = None,
782
+ train: bool = False,
783
+ output_attentions: Optional[bool] = None,
784
+ output_hidden_states: Optional[bool] = None,
785
+ return_dict: Optional[bool] = None,
786
+ past_key_values: dict = None,
787
+ ):
788
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
789
+ output_hidden_states = (
790
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
791
+ )
792
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
793
+
794
+ # init input tensors if not passed
795
+ if token_type_ids is None:
796
+ token_type_ids = jnp.ones_like(input_ids)
797
+
798
+ if position_ids is None:
799
+ position_ids = jnp.broadcast_to(jnp.arange(jnp.atleast_2d(input_ids).shape[-1]), input_ids.shape)
800
+
801
+ if attention_mask is None:
802
+ attention_mask = jnp.ones_like(input_ids)
803
+
804
+ if head_mask is None:
805
+ head_mask = jnp.ones((self.config.num_hidden_layers, self.config.num_attention_heads))
806
+
807
+ # Handle any PRNG if needed
808
+ rngs = {}
809
+ if dropout_rng is not None:
810
+ rngs["dropout"] = dropout_rng
811
+
812
+ inputs = {"params": params or self.params}
813
+
814
+ if self.config.add_cross_attention:
815
+ # if past_key_values are passed then cache is already initialized a private flag init_cache has to be passed
816
+ # down to ensure cache is used. It has to be made sure that cache is marked as mutable so that it can be
817
+ # changed by FlaxElectraAttention module
818
+ if past_key_values:
819
+ inputs["cache"] = past_key_values
820
+ mutable = ["cache"]
821
+ else:
822
+ mutable = False
823
+
824
+ outputs = self.module.apply(
825
+ inputs,
826
+ jnp.array(input_ids, dtype="i4"),
827
+ jnp.array(attention_mask, dtype="i4"),
828
+ token_type_ids=jnp.array(token_type_ids, dtype="i4"),
829
+ position_ids=jnp.array(position_ids, dtype="i4"),
830
+ head_mask=jnp.array(head_mask, dtype="i4"),
831
+ encoder_hidden_states=encoder_hidden_states,
832
+ encoder_attention_mask=encoder_attention_mask,
833
+ deterministic=not train,
834
+ output_attentions=output_attentions,
835
+ output_hidden_states=output_hidden_states,
836
+ return_dict=return_dict,
837
+ rngs=rngs,
838
+ mutable=mutable,
839
+ )
840
+
841
+ # add updated cache to model output
842
+ if past_key_values is not None and return_dict:
843
+ outputs, past_key_values = outputs
844
+ outputs["past_key_values"] = unfreeze(past_key_values["cache"])
845
+ return outputs
846
+ elif past_key_values is not None and not return_dict:
847
+ outputs, past_key_values = outputs
848
+ outputs = outputs[:1] + (unfreeze(past_key_values["cache"]),) + outputs[1:]
849
+
850
+ else:
851
+ outputs = self.module.apply(
852
+ inputs,
853
+ jnp.array(input_ids, dtype="i4"),
854
+ jnp.array(attention_mask, dtype="i4"),
855
+ token_type_ids=jnp.array(token_type_ids, dtype="i4"),
856
+ position_ids=jnp.array(position_ids, dtype="i4"),
857
+ head_mask=jnp.array(head_mask, dtype="i4"),
858
+ deterministic=not train,
859
+ output_attentions=output_attentions,
860
+ output_hidden_states=output_hidden_states,
861
+ return_dict=return_dict,
862
+ rngs=rngs,
863
+ )
864
+
865
+ return outputs
866
+
867
+
868
+ class FlaxElectraModule(nn.Module):
869
+ config: ElectraConfig
870
+ dtype: jnp.dtype = jnp.float32 # the dtype of the computation
871
+ gradient_checkpointing: bool = False
872
+
873
+ def setup(self):
874
+ self.embeddings = FlaxElectraEmbeddings(self.config, dtype=self.dtype)
875
+ if self.config.embedding_size != self.config.hidden_size:
876
+ self.embeddings_project = nn.Dense(self.config.hidden_size, dtype=self.dtype)
877
+ self.encoder = FlaxElectraEncoder(
878
+ self.config, dtype=self.dtype, gradient_checkpointing=self.gradient_checkpointing
879
+ )
880
+
881
+ def __call__(
882
+ self,
883
+ input_ids,
884
+ attention_mask,
885
+ token_type_ids,
886
+ position_ids,
887
+ head_mask: Optional[np.ndarray] = None,
888
+ encoder_hidden_states: Optional[jnp.ndarray] = None,
889
+ encoder_attention_mask: Optional[jnp.ndarray] = None,
890
+ init_cache: bool = False,
891
+ deterministic: bool = True,
892
+ output_attentions: bool = False,
893
+ output_hidden_states: bool = False,
894
+ return_dict: bool = True,
895
+ ):
896
+ embeddings = self.embeddings(
897
+ input_ids, token_type_ids, position_ids, attention_mask, deterministic=deterministic
898
+ )
899
+ if hasattr(self, "embeddings_project"):
900
+ embeddings = self.embeddings_project(embeddings)
901
+
902
+ return self.encoder(
903
+ embeddings,
904
+ attention_mask,
905
+ head_mask=head_mask,
906
+ deterministic=deterministic,
907
+ encoder_hidden_states=encoder_hidden_states,
908
+ encoder_attention_mask=encoder_attention_mask,
909
+ init_cache=init_cache,
910
+ output_attentions=output_attentions,
911
+ output_hidden_states=output_hidden_states,
912
+ return_dict=return_dict,
913
+ )
914
+
915
+
916
+ @add_start_docstrings(
917
+ "The bare Electra Model transformer outputting raw hidden-states without any specific head on top.",
918
+ ELECTRA_START_DOCSTRING,
919
+ )
920
+ class FlaxElectraModel(FlaxElectraPreTrainedModel):
921
+ module_class = FlaxElectraModule
922
+
923
+
924
+ append_call_sample_docstring(FlaxElectraModel, _CHECKPOINT_FOR_DOC, FlaxBaseModelOutput, _CONFIG_FOR_DOC)
925
+
926
+
927
+ class FlaxElectraTiedDense(nn.Module):
928
+ embedding_size: int
929
+ dtype: jnp.dtype = jnp.float32
930
+ precision = None
931
+ bias_init: Callable[..., np.ndarray] = jax.nn.initializers.zeros
932
+
933
+ def setup(self):
934
+ self.bias = self.param("bias", self.bias_init, (self.embedding_size,))
935
+
936
+ def __call__(self, x, kernel):
937
+ x = jnp.asarray(x, self.dtype)
938
+ kernel = jnp.asarray(kernel, self.dtype)
939
+ y = lax.dot_general(
940
+ x,
941
+ kernel,
942
+ (((x.ndim - 1,), (0,)), ((), ())),
943
+ precision=self.precision,
944
+ )
945
+ bias = jnp.asarray(self.bias, self.dtype)
946
+ return y + bias
947
+
948
+
949
+ class FlaxElectraForMaskedLMModule(nn.Module):
950
+ config: ElectraConfig
951
+ dtype: jnp.dtype = jnp.float32
952
+ gradient_checkpointing: bool = False
953
+
954
+ def setup(self):
955
+ self.electra = FlaxElectraModule(
956
+ config=self.config, dtype=self.dtype, gradient_checkpointing=self.gradient_checkpointing
957
+ )
958
+ self.generator_predictions = FlaxElectraGeneratorPredictions(config=self.config, dtype=self.dtype)
959
+ if self.config.tie_word_embeddings:
960
+ self.generator_lm_head = FlaxElectraTiedDense(self.config.vocab_size, dtype=self.dtype)
961
+ else:
962
+ self.generator_lm_head = nn.Dense(self.config.vocab_size, dtype=self.dtype)
963
+
964
+ def __call__(
965
+ self,
966
+ input_ids,
967
+ attention_mask=None,
968
+ token_type_ids=None,
969
+ position_ids=None,
970
+ head_mask=None,
971
+ deterministic: bool = True,
972
+ output_attentions: bool = False,
973
+ output_hidden_states: bool = False,
974
+ return_dict: bool = True,
975
+ ):
976
+ outputs = self.electra(
977
+ input_ids,
978
+ attention_mask,
979
+ token_type_ids,
980
+ position_ids,
981
+ head_mask,
982
+ deterministic=deterministic,
983
+ output_attentions=output_attentions,
984
+ output_hidden_states=output_hidden_states,
985
+ return_dict=return_dict,
986
+ )
987
+ hidden_states = outputs[0]
988
+ prediction_scores = self.generator_predictions(hidden_states)
989
+
990
+ if self.config.tie_word_embeddings:
991
+ shared_embedding = self.electra.variables["params"]["embeddings"]["word_embeddings"]["embedding"]
992
+ prediction_scores = self.generator_lm_head(prediction_scores, shared_embedding.T)
993
+ else:
994
+ prediction_scores = self.generator_lm_head(prediction_scores)
995
+
996
+ if not return_dict:
997
+ return (prediction_scores,) + outputs[1:]
998
+
999
+ return FlaxMaskedLMOutput(
1000
+ logits=prediction_scores,
1001
+ hidden_states=outputs.hidden_states,
1002
+ attentions=outputs.attentions,
1003
+ )
1004
+
1005
+
1006
+ @add_start_docstrings("""Electra Model with a `language modeling` head on top.""", ELECTRA_START_DOCSTRING)
1007
+ class FlaxElectraForMaskedLM(FlaxElectraPreTrainedModel):
1008
+ module_class = FlaxElectraForMaskedLMModule
1009
+
1010
+
1011
+ append_call_sample_docstring(FlaxElectraForMaskedLM, _CHECKPOINT_FOR_DOC, FlaxMaskedLMOutput, _CONFIG_FOR_DOC)
1012
+
1013
+
1014
+ class FlaxElectraForPreTrainingModule(nn.Module):
1015
+ config: ElectraConfig
1016
+ dtype: jnp.dtype = jnp.float32
1017
+ gradient_checkpointing: bool = False
1018
+
1019
+ def setup(self):
1020
+ self.electra = FlaxElectraModule(
1021
+ config=self.config, dtype=self.dtype, gradient_checkpointing=self.gradient_checkpointing
1022
+ )
1023
+ self.discriminator_predictions = FlaxElectraDiscriminatorPredictions(config=self.config, dtype=self.dtype)
1024
+
1025
+ def __call__(
1026
+ self,
1027
+ input_ids,
1028
+ attention_mask=None,
1029
+ token_type_ids=None,
1030
+ position_ids=None,
1031
+ head_mask=None,
1032
+ deterministic: bool = True,
1033
+ output_attentions: bool = False,
1034
+ output_hidden_states: bool = False,
1035
+ return_dict: bool = True,
1036
+ ):
1037
+ # Model
1038
+ outputs = self.electra(
1039
+ input_ids,
1040
+ attention_mask,
1041
+ token_type_ids,
1042
+ position_ids,
1043
+ head_mask,
1044
+ deterministic=deterministic,
1045
+ output_attentions=output_attentions,
1046
+ output_hidden_states=output_hidden_states,
1047
+ return_dict=return_dict,
1048
+ )
1049
+ hidden_states = outputs[0]
1050
+
1051
+ logits = self.discriminator_predictions(hidden_states)
1052
+
1053
+ if not return_dict:
1054
+ return (logits,) + outputs[1:]
1055
+
1056
+ return FlaxElectraForPreTrainingOutput(
1057
+ logits=logits,
1058
+ hidden_states=outputs.hidden_states,
1059
+ attentions=outputs.attentions,
1060
+ )
1061
+
1062
+
1063
+ @add_start_docstrings(
1064
+ """
1065
+ Electra model with a binary classification head on top as used during pretraining for identifying generated tokens.
1066
+
1067
+ It is recommended to load the discriminator checkpoint into that model.
1068
+ """,
1069
+ ELECTRA_START_DOCSTRING,
1070
+ )
1071
+ class FlaxElectraForPreTraining(FlaxElectraPreTrainedModel):
1072
+ module_class = FlaxElectraForPreTrainingModule
1073
+
1074
+
1075
+ FLAX_ELECTRA_FOR_PRETRAINING_DOCSTRING = """
1076
+ Returns:
1077
+
1078
+ Example:
1079
+
1080
+ ```python
1081
+ >>> from transformers import AutoTokenizer, FlaxElectraForPreTraining
1082
+
1083
+ >>> tokenizer = AutoTokenizer.from_pretrained("google/electra-small-discriminator")
1084
+ >>> model = FlaxElectraForPreTraining.from_pretrained("google/electra-small-discriminator")
1085
+
1086
+ >>> inputs = tokenizer("Hello, my dog is cute", return_tensors="np")
1087
+ >>> outputs = model(**inputs)
1088
+
1089
+ >>> prediction_logits = outputs.logits
1090
+ ```
1091
+ """
1092
+
1093
+ overwrite_call_docstring(
1094
+ FlaxElectraForPreTraining,
1095
+ ELECTRA_INPUTS_DOCSTRING.format("batch_size, sequence_length") + FLAX_ELECTRA_FOR_PRETRAINING_DOCSTRING,
1096
+ )
1097
+ append_replace_return_docstrings(
1098
+ FlaxElectraForPreTraining, output_type=FlaxElectraForPreTrainingOutput, config_class=_CONFIG_FOR_DOC
1099
+ )
1100
+
1101
+
1102
+ class FlaxElectraForTokenClassificationModule(nn.Module):
1103
+ config: ElectraConfig
1104
+ dtype: jnp.dtype = jnp.float32
1105
+ gradient_checkpointing: bool = False
1106
+
1107
+ def setup(self):
1108
+ self.electra = FlaxElectraModule(
1109
+ config=self.config, dtype=self.dtype, gradient_checkpointing=self.gradient_checkpointing
1110
+ )
1111
+ classifier_dropout = (
1112
+ self.config.classifier_dropout
1113
+ if self.config.classifier_dropout is not None
1114
+ else self.config.hidden_dropout_prob
1115
+ )
1116
+ self.dropout = nn.Dropout(classifier_dropout)
1117
+ self.classifier = nn.Dense(self.config.num_labels, dtype=self.dtype)
1118
+
1119
+ def __call__(
1120
+ self,
1121
+ input_ids,
1122
+ attention_mask=None,
1123
+ token_type_ids=None,
1124
+ position_ids=None,
1125
+ head_mask=None,
1126
+ deterministic: bool = True,
1127
+ output_attentions: bool = False,
1128
+ output_hidden_states: bool = False,
1129
+ return_dict: bool = True,
1130
+ ):
1131
+ # Model
1132
+ outputs = self.electra(
1133
+ input_ids,
1134
+ attention_mask,
1135
+ token_type_ids,
1136
+ position_ids,
1137
+ head_mask,
1138
+ deterministic=deterministic,
1139
+ output_attentions=output_attentions,
1140
+ output_hidden_states=output_hidden_states,
1141
+ return_dict=return_dict,
1142
+ )
1143
+ hidden_states = outputs[0]
1144
+
1145
+ hidden_states = self.dropout(hidden_states, deterministic=deterministic)
1146
+ logits = self.classifier(hidden_states)
1147
+
1148
+ if not return_dict:
1149
+ return (logits,) + outputs[1:]
1150
+
1151
+ return FlaxTokenClassifierOutput(
1152
+ logits=logits,
1153
+ hidden_states=outputs.hidden_states,
1154
+ attentions=outputs.attentions,
1155
+ )
1156
+
1157
+
1158
+ @add_start_docstrings(
1159
+ """
1160
+ Electra model with a token classification head on top.
1161
+
1162
+ Both the discriminator and generator may be loaded into this model.
1163
+ """,
1164
+ ELECTRA_START_DOCSTRING,
1165
+ )
1166
+ class FlaxElectraForTokenClassification(FlaxElectraPreTrainedModel):
1167
+ module_class = FlaxElectraForTokenClassificationModule
1168
+
1169
+
1170
+ append_call_sample_docstring(
1171
+ FlaxElectraForTokenClassification,
1172
+ _CHECKPOINT_FOR_DOC,
1173
+ FlaxTokenClassifierOutput,
1174
+ _CONFIG_FOR_DOC,
1175
+ )
1176
+
1177
+
1178
+ def identity(x, **kwargs):
1179
+ return x
1180
+
1181
+
1182
+ class FlaxElectraSequenceSummary(nn.Module):
1183
+ r"""
1184
+ Compute a single vector summary of a sequence hidden states.
1185
+
1186
+ Args:
1187
+ config ([`PretrainedConfig`]):
1188
+ The config used by the model. Relevant arguments in the config class of the model are (refer to the actual
1189
+ config class of your model for the default values it uses):
1190
+
1191
+ - **summary_use_proj** (`bool`) -- Add a projection after the vector extraction.
1192
+ - **summary_proj_to_labels** (`bool`) -- If `True`, the projection outputs to `config.num_labels` classes
1193
+ (otherwise to `config.hidden_size`).
1194
+ - **summary_activation** (`Optional[str]`) -- Set to `"tanh"` to add a tanh activation to the output,
1195
+ another string or `None` will add no activation.
1196
+ - **summary_first_dropout** (`float`) -- Optional dropout probability before the projection and activation.
1197
+ - **summary_last_dropout** (`float`)-- Optional dropout probability after the projection and activation.
1198
+ """
1199
+
1200
+ config: ElectraConfig
1201
+ dtype: jnp.dtype = jnp.float32
1202
+
1203
+ def setup(self):
1204
+ self.summary = identity
1205
+ if hasattr(self.config, "summary_use_proj") and self.config.summary_use_proj:
1206
+ if (
1207
+ hasattr(self.config, "summary_proj_to_labels")
1208
+ and self.config.summary_proj_to_labels
1209
+ and self.config.num_labels > 0
1210
+ ):
1211
+ num_classes = self.config.num_labels
1212
+ else:
1213
+ num_classes = self.config.hidden_size
1214
+ self.summary = nn.Dense(num_classes, dtype=self.dtype)
1215
+
1216
+ activation_string = getattr(self.config, "summary_activation", None)
1217
+ self.activation = ACT2FN[activation_string] if activation_string else lambda x: x # noqa F407
1218
+
1219
+ self.first_dropout = identity
1220
+ if hasattr(self.config, "summary_first_dropout") and self.config.summary_first_dropout > 0:
1221
+ self.first_dropout = nn.Dropout(self.config.summary_first_dropout)
1222
+
1223
+ self.last_dropout = identity
1224
+ if hasattr(self.config, "summary_last_dropout") and self.config.summary_last_dropout > 0:
1225
+ self.last_dropout = nn.Dropout(self.config.summary_last_dropout)
1226
+
1227
+ def __call__(self, hidden_states, cls_index=None, deterministic: bool = True):
1228
+ """
1229
+ Compute a single vector summary of a sequence hidden states.
1230
+
1231
+ Args:
1232
+ hidden_states (`jnp.ndarray` of shape `[batch_size, seq_len, hidden_size]`):
1233
+ The hidden states of the last layer.
1234
+ cls_index (`jnp.ndarray` of shape `[batch_size]` or `[batch_size, ...]` where ... are optional leading dimensions of `hidden_states`, *optional*):
1235
+ Used if `summary_type == "cls_index"` and takes the last token of the sequence as classification token.
1236
+
1237
+ Returns:
1238
+ `jnp.ndarray`: The summary of the sequence hidden states.
1239
+ """
1240
+ # NOTE: this doest "first" type summary always
1241
+ output = hidden_states[:, 0]
1242
+ output = self.first_dropout(output, deterministic=deterministic)
1243
+ output = self.summary(output)
1244
+ output = self.activation(output)
1245
+ output = self.last_dropout(output, deterministic=deterministic)
1246
+ return output
1247
+
1248
+
1249
+ class FlaxElectraForMultipleChoiceModule(nn.Module):
1250
+ config: ElectraConfig
1251
+ dtype: jnp.dtype = jnp.float32
1252
+ gradient_checkpointing: bool = False
1253
+
1254
+ def setup(self):
1255
+ self.electra = FlaxElectraModule(
1256
+ config=self.config, dtype=self.dtype, gradient_checkpointing=self.gradient_checkpointing
1257
+ )
1258
+ self.sequence_summary = FlaxElectraSequenceSummary(config=self.config, dtype=self.dtype)
1259
+ self.classifier = nn.Dense(1, dtype=self.dtype)
1260
+
1261
+ def __call__(
1262
+ self,
1263
+ input_ids,
1264
+ attention_mask=None,
1265
+ token_type_ids=None,
1266
+ position_ids=None,
1267
+ head_mask=None,
1268
+ deterministic: bool = True,
1269
+ output_attentions: bool = False,
1270
+ output_hidden_states: bool = False,
1271
+ return_dict: bool = True,
1272
+ ):
1273
+ num_choices = input_ids.shape[1]
1274
+ input_ids = input_ids.reshape(-1, input_ids.shape[-1]) if input_ids is not None else None
1275
+ attention_mask = attention_mask.reshape(-1, attention_mask.shape[-1]) if attention_mask is not None else None
1276
+ token_type_ids = token_type_ids.reshape(-1, token_type_ids.shape[-1]) if token_type_ids is not None else None
1277
+ position_ids = position_ids.reshape(-1, position_ids.shape[-1]) if position_ids is not None else None
1278
+
1279
+ # Model
1280
+ outputs = self.electra(
1281
+ input_ids,
1282
+ attention_mask,
1283
+ token_type_ids,
1284
+ position_ids,
1285
+ head_mask,
1286
+ deterministic=deterministic,
1287
+ output_attentions=output_attentions,
1288
+ output_hidden_states=output_hidden_states,
1289
+ return_dict=return_dict,
1290
+ )
1291
+ hidden_states = outputs[0]
1292
+ pooled_output = self.sequence_summary(hidden_states, deterministic=deterministic)
1293
+ logits = self.classifier(pooled_output)
1294
+
1295
+ reshaped_logits = logits.reshape(-1, num_choices)
1296
+
1297
+ if not return_dict:
1298
+ return (reshaped_logits,) + outputs[1:]
1299
+
1300
+ return FlaxMultipleChoiceModelOutput(
1301
+ logits=reshaped_logits,
1302
+ hidden_states=outputs.hidden_states,
1303
+ attentions=outputs.attentions,
1304
+ )
1305
+
1306
+
1307
+ @add_start_docstrings(
1308
+ """
1309
+ ELECTRA Model with a multiple choice classification head on top (a linear layer on top of the pooled output and a
1310
+ softmax) e.g. for RocStories/SWAG tasks.
1311
+ """,
1312
+ ELECTRA_START_DOCSTRING,
1313
+ )
1314
+ class FlaxElectraForMultipleChoice(FlaxElectraPreTrainedModel):
1315
+ module_class = FlaxElectraForMultipleChoiceModule
1316
+
1317
+
1318
+ # adapt docstring slightly for FlaxElectraForMultipleChoice
1319
+ overwrite_call_docstring(
1320
+ FlaxElectraForMultipleChoice, ELECTRA_INPUTS_DOCSTRING.format("batch_size, num_choices, sequence_length")
1321
+ )
1322
+ append_call_sample_docstring(
1323
+ FlaxElectraForMultipleChoice,
1324
+ _CHECKPOINT_FOR_DOC,
1325
+ FlaxMultipleChoiceModelOutput,
1326
+ _CONFIG_FOR_DOC,
1327
+ )
1328
+
1329
+
1330
+ class FlaxElectraForQuestionAnsweringModule(nn.Module):
1331
+ config: ElectraConfig
1332
+ dtype: jnp.dtype = jnp.float32
1333
+ gradient_checkpointing: bool = False
1334
+
1335
+ def setup(self):
1336
+ self.electra = FlaxElectraModule(
1337
+ config=self.config, dtype=self.dtype, gradient_checkpointing=self.gradient_checkpointing
1338
+ )
1339
+ self.qa_outputs = nn.Dense(self.config.num_labels, dtype=self.dtype)
1340
+
1341
+ def __call__(
1342
+ self,
1343
+ input_ids,
1344
+ attention_mask=None,
1345
+ token_type_ids=None,
1346
+ position_ids=None,
1347
+ head_mask=None,
1348
+ deterministic: bool = True,
1349
+ output_attentions: bool = False,
1350
+ output_hidden_states: bool = False,
1351
+ return_dict: bool = True,
1352
+ ):
1353
+ # Model
1354
+ outputs = self.electra(
1355
+ input_ids,
1356
+ attention_mask,
1357
+ token_type_ids,
1358
+ position_ids,
1359
+ head_mask,
1360
+ deterministic=deterministic,
1361
+ output_attentions=output_attentions,
1362
+ output_hidden_states=output_hidden_states,
1363
+ return_dict=return_dict,
1364
+ )
1365
+ hidden_states = outputs[0]
1366
+ logits = self.qa_outputs(hidden_states)
1367
+ start_logits, end_logits = logits.split(self.config.num_labels, axis=-1)
1368
+ start_logits = start_logits.squeeze(-1)
1369
+ end_logits = end_logits.squeeze(-1)
1370
+
1371
+ if not return_dict:
1372
+ return (start_logits, end_logits) + outputs[1:]
1373
+
1374
+ return FlaxQuestionAnsweringModelOutput(
1375
+ start_logits=start_logits,
1376
+ end_logits=end_logits,
1377
+ hidden_states=outputs.hidden_states,
1378
+ attentions=outputs.attentions,
1379
+ )
1380
+
1381
+
1382
+ @add_start_docstrings(
1383
+ """
1384
+ ELECTRA Model with a span classification head on top for extractive question-answering tasks like SQuAD (a linear
1385
+ layers on top of the hidden-states output to compute `span start logits` and `span end logits`).
1386
+ """,
1387
+ ELECTRA_START_DOCSTRING,
1388
+ )
1389
+ class FlaxElectraForQuestionAnswering(FlaxElectraPreTrainedModel):
1390
+ module_class = FlaxElectraForQuestionAnsweringModule
1391
+
1392
+
1393
+ append_call_sample_docstring(
1394
+ FlaxElectraForQuestionAnswering,
1395
+ _CHECKPOINT_FOR_DOC,
1396
+ FlaxQuestionAnsweringModelOutput,
1397
+ _CONFIG_FOR_DOC,
1398
+ )
1399
+
1400
+
1401
+ class FlaxElectraClassificationHead(nn.Module):
1402
+ """Head for sentence-level classification tasks."""
1403
+
1404
+ config: ElectraConfig
1405
+ dtype: jnp.dtype = jnp.float32
1406
+
1407
+ def setup(self):
1408
+ self.dense = nn.Dense(self.config.hidden_size, dtype=self.dtype)
1409
+ classifier_dropout = (
1410
+ self.config.classifier_dropout
1411
+ if self.config.classifier_dropout is not None
1412
+ else self.config.hidden_dropout_prob
1413
+ )
1414
+ self.dropout = nn.Dropout(classifier_dropout)
1415
+ self.out_proj = nn.Dense(self.config.num_labels, dtype=self.dtype)
1416
+
1417
+ def __call__(self, hidden_states, deterministic: bool = True):
1418
+ x = hidden_states[:, 0, :] # take <s> token (equiv. to [CLS])
1419
+ x = self.dropout(x, deterministic=deterministic)
1420
+ x = self.dense(x)
1421
+ x = ACT2FN["gelu"](x) # although BERT uses tanh here, it seems Electra authors used gelu
1422
+ x = self.dropout(x, deterministic=deterministic)
1423
+ x = self.out_proj(x)
1424
+ return x
1425
+
1426
+
1427
+ class FlaxElectraForSequenceClassificationModule(nn.Module):
1428
+ config: ElectraConfig
1429
+ dtype: jnp.dtype = jnp.float32
1430
+ gradient_checkpointing: bool = False
1431
+
1432
+ def setup(self):
1433
+ self.electra = FlaxElectraModule(
1434
+ config=self.config, dtype=self.dtype, gradient_checkpointing=self.gradient_checkpointing
1435
+ )
1436
+ self.classifier = FlaxElectraClassificationHead(config=self.config, dtype=self.dtype)
1437
+
1438
+ def __call__(
1439
+ self,
1440
+ input_ids,
1441
+ attention_mask=None,
1442
+ token_type_ids=None,
1443
+ position_ids=None,
1444
+ head_mask=None,
1445
+ deterministic: bool = True,
1446
+ output_attentions: bool = False,
1447
+ output_hidden_states: bool = False,
1448
+ return_dict: bool = True,
1449
+ ):
1450
+ # Model
1451
+ outputs = self.electra(
1452
+ input_ids,
1453
+ attention_mask,
1454
+ token_type_ids,
1455
+ position_ids,
1456
+ head_mask,
1457
+ deterministic=deterministic,
1458
+ output_attentions=output_attentions,
1459
+ output_hidden_states=output_hidden_states,
1460
+ return_dict=return_dict,
1461
+ )
1462
+ hidden_states = outputs[0]
1463
+ logits = self.classifier(hidden_states, deterministic=deterministic)
1464
+
1465
+ if not return_dict:
1466
+ return (logits,) + outputs[1:]
1467
+
1468
+ return FlaxSequenceClassifierOutput(
1469
+ logits=logits,
1470
+ hidden_states=outputs.hidden_states,
1471
+ attentions=outputs.attentions,
1472
+ )
1473
+
1474
+
1475
+ @add_start_docstrings(
1476
+ """
1477
+ Electra Model transformer with a sequence classification/regression head on top (a linear layer on top of the
1478
+ pooled output) e.g. for GLUE tasks.
1479
+ """,
1480
+ ELECTRA_START_DOCSTRING,
1481
+ )
1482
+ class FlaxElectraForSequenceClassification(FlaxElectraPreTrainedModel):
1483
+ module_class = FlaxElectraForSequenceClassificationModule
1484
+
1485
+
1486
+ append_call_sample_docstring(
1487
+ FlaxElectraForSequenceClassification,
1488
+ _CHECKPOINT_FOR_DOC,
1489
+ FlaxSequenceClassifierOutput,
1490
+ _CONFIG_FOR_DOC,
1491
+ )
1492
+
1493
+
1494
+ class FlaxElectraForCausalLMModule(nn.Module):
1495
+ config: ElectraConfig
1496
+ dtype: jnp.dtype = jnp.float32
1497
+ gradient_checkpointing: bool = False
1498
+
1499
+ def setup(self):
1500
+ self.electra = FlaxElectraModule(
1501
+ config=self.config, dtype=self.dtype, gradient_checkpointing=self.gradient_checkpointing
1502
+ )
1503
+ self.generator_predictions = FlaxElectraGeneratorPredictions(config=self.config, dtype=self.dtype)
1504
+ if self.config.tie_word_embeddings:
1505
+ self.generator_lm_head = FlaxElectraTiedDense(self.config.vocab_size, dtype=self.dtype)
1506
+ else:
1507
+ self.generator_lm_head = nn.Dense(self.config.vocab_size, dtype=self.dtype)
1508
+
1509
+ def __call__(
1510
+ self,
1511
+ input_ids,
1512
+ attention_mask: Optional[jnp.ndarray] = None,
1513
+ token_type_ids: Optional[jnp.ndarray] = None,
1514
+ position_ids: Optional[jnp.ndarray] = None,
1515
+ head_mask: Optional[jnp.ndarray] = None,
1516
+ encoder_hidden_states: Optional[jnp.ndarray] = None,
1517
+ encoder_attention_mask: Optional[jnp.ndarray] = None,
1518
+ init_cache: bool = False,
1519
+ deterministic: bool = True,
1520
+ output_attentions: bool = False,
1521
+ output_hidden_states: bool = False,
1522
+ return_dict: bool = True,
1523
+ ):
1524
+ outputs = self.electra(
1525
+ input_ids,
1526
+ attention_mask,
1527
+ token_type_ids,
1528
+ position_ids,
1529
+ head_mask,
1530
+ encoder_hidden_states=encoder_hidden_states,
1531
+ encoder_attention_mask=encoder_attention_mask,
1532
+ init_cache=init_cache,
1533
+ deterministic=deterministic,
1534
+ output_attentions=output_attentions,
1535
+ output_hidden_states=output_hidden_states,
1536
+ return_dict=return_dict,
1537
+ )
1538
+ hidden_states = outputs[0]
1539
+ prediction_scores = self.generator_predictions(hidden_states)
1540
+
1541
+ if self.config.tie_word_embeddings:
1542
+ shared_embedding = self.electra.variables["params"]["embeddings"]["word_embeddings"]["embedding"]
1543
+ prediction_scores = self.generator_lm_head(prediction_scores, shared_embedding.T)
1544
+ else:
1545
+ prediction_scores = self.generator_lm_head(prediction_scores)
1546
+
1547
+ if not return_dict:
1548
+ return (prediction_scores,) + outputs[1:]
1549
+
1550
+ return FlaxCausalLMOutputWithCrossAttentions(
1551
+ logits=prediction_scores,
1552
+ hidden_states=outputs.hidden_states,
1553
+ attentions=outputs.attentions,
1554
+ cross_attentions=outputs.cross_attentions,
1555
+ )
1556
+
1557
+
1558
+ @add_start_docstrings(
1559
+ """
1560
+ Electra Model with a language modeling head on top (a linear layer on top of the hidden-states output) e.g for
1561
+ autoregressive tasks.
1562
+ """,
1563
+ ELECTRA_START_DOCSTRING,
1564
+ )
1565
+ # Copied from transformers.models.bert.modeling_flax_bert.FlaxBertForCausalLM with Bert->Electra
1566
+ class FlaxElectraForCausalLM(FlaxElectraPreTrainedModel):
1567
+ module_class = FlaxElectraForCausalLMModule
1568
+
1569
+ def prepare_inputs_for_generation(self, input_ids, max_length, attention_mask: Optional[jax.Array] = None):
1570
+ # initializing the cache
1571
+ batch_size, seq_length = input_ids.shape
1572
+
1573
+ past_key_values = self.init_cache(batch_size, max_length)
1574
+ # Note that usually one would have to put 0's in the attention_mask for x > input_ids.shape[-1] and x < cache_length.
1575
+ # But since the decoder uses a causal mask, those positions are masked anyway.
1576
+ # Thus, we can create a single static attention_mask here, which is more efficient for compilation
1577
+ extended_attention_mask = jnp.ones((batch_size, max_length), dtype="i4")
1578
+ if attention_mask is not None:
1579
+ position_ids = attention_mask.cumsum(axis=-1) - 1
1580
+ extended_attention_mask = lax.dynamic_update_slice(extended_attention_mask, attention_mask, (0, 0))
1581
+ else:
1582
+ position_ids = jnp.broadcast_to(jnp.arange(seq_length, dtype="i4")[None, :], (batch_size, seq_length))
1583
+
1584
+ return {
1585
+ "past_key_values": past_key_values,
1586
+ "attention_mask": extended_attention_mask,
1587
+ "position_ids": position_ids,
1588
+ }
1589
+
1590
+ def update_inputs_for_generation(self, model_outputs, model_kwargs):
1591
+ model_kwargs["past_key_values"] = model_outputs.past_key_values
1592
+ model_kwargs["position_ids"] = model_kwargs["position_ids"][:, -1:] + 1
1593
+ return model_kwargs
1594
+
1595
+
1596
+ append_call_sample_docstring(
1597
+ FlaxElectraForCausalLM,
1598
+ _CHECKPOINT_FOR_DOC,
1599
+ FlaxCausalLMOutputWithCrossAttentions,
1600
+ _CONFIG_FOR_DOC,
1601
+ )
pllava/lib/python3.10/site-packages/transformers/models/electra/modeling_tf_electra.py ADDED
@@ -0,0 +1,1774 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2019 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
+ """ TF Electra model."""
16
+
17
+
18
+ from __future__ import annotations
19
+
20
+ import math
21
+ import warnings
22
+ from dataclasses import dataclass
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
+ TFBaseModelOutputWithPastAndCrossAttentions,
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
+ TFSequenceSummary,
45
+ TFTokenClassificationLoss,
46
+ get_initializer,
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
+ ModelOutput,
53
+ add_code_sample_docstrings,
54
+ add_start_docstrings,
55
+ add_start_docstrings_to_model_forward,
56
+ logging,
57
+ replace_return_docstrings,
58
+ )
59
+ from .configuration_electra import ElectraConfig
60
+
61
+
62
+ logger = logging.get_logger(__name__)
63
+
64
+ _CHECKPOINT_FOR_DOC = "google/electra-small-discriminator"
65
+ _CONFIG_FOR_DOC = "ElectraConfig"
66
+
67
+ TF_ELECTRA_PRETRAINED_MODEL_ARCHIVE_LIST = [
68
+ "google/electra-small-generator",
69
+ "google/electra-base-generator",
70
+ "google/electra-large-generator",
71
+ "google/electra-small-discriminator",
72
+ "google/electra-base-discriminator",
73
+ "google/electra-large-discriminator",
74
+ # See all ELECTRA models at https://huggingface.co/models?filter=electra
75
+ ]
76
+
77
+
78
+ # Copied from transformers.models.bert.modeling_tf_bert.TFBertSelfAttention with Bert->Electra
79
+ class TFElectraSelfAttention(tf.keras.layers.Layer):
80
+ def __init__(self, config: ElectraConfig, **kwargs):
81
+ super().__init__(**kwargs)
82
+
83
+ if config.hidden_size % config.num_attention_heads != 0:
84
+ raise ValueError(
85
+ f"The hidden size ({config.hidden_size}) is not a multiple of the number "
86
+ f"of attention heads ({config.num_attention_heads})"
87
+ )
88
+
89
+ self.num_attention_heads = config.num_attention_heads
90
+ self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
91
+ self.all_head_size = self.num_attention_heads * self.attention_head_size
92
+ self.sqrt_att_head_size = math.sqrt(self.attention_head_size)
93
+
94
+ self.query = tf.keras.layers.Dense(
95
+ units=self.all_head_size, kernel_initializer=get_initializer(config.initializer_range), name="query"
96
+ )
97
+ self.key = tf.keras.layers.Dense(
98
+ units=self.all_head_size, kernel_initializer=get_initializer(config.initializer_range), name="key"
99
+ )
100
+ self.value = tf.keras.layers.Dense(
101
+ units=self.all_head_size, kernel_initializer=get_initializer(config.initializer_range), name="value"
102
+ )
103
+ self.dropout = tf.keras.layers.Dropout(rate=config.attention_probs_dropout_prob)
104
+
105
+ self.is_decoder = config.is_decoder
106
+ self.config = config
107
+
108
+ def transpose_for_scores(self, tensor: tf.Tensor, batch_size: int) -> tf.Tensor:
109
+ # Reshape from [batch_size, seq_length, all_head_size] to [batch_size, seq_length, num_attention_heads, attention_head_size]
110
+ tensor = tf.reshape(tensor=tensor, shape=(batch_size, -1, self.num_attention_heads, self.attention_head_size))
111
+
112
+ # Transpose the tensor from [batch_size, seq_length, num_attention_heads, attention_head_size] to [batch_size, num_attention_heads, seq_length, attention_head_size]
113
+ return tf.transpose(tensor, perm=[0, 2, 1, 3])
114
+
115
+ def call(
116
+ self,
117
+ hidden_states: tf.Tensor,
118
+ attention_mask: tf.Tensor,
119
+ head_mask: tf.Tensor,
120
+ encoder_hidden_states: tf.Tensor,
121
+ encoder_attention_mask: tf.Tensor,
122
+ past_key_value: Tuple[tf.Tensor],
123
+ output_attentions: bool,
124
+ training: bool = False,
125
+ ) -> Tuple[tf.Tensor]:
126
+ batch_size = shape_list(hidden_states)[0]
127
+ mixed_query_layer = self.query(inputs=hidden_states)
128
+
129
+ # If this is instantiated as a cross-attention module, the keys
130
+ # and values come from an encoder; the attention mask needs to be
131
+ # such that the encoder's padding tokens are not attended to.
132
+ is_cross_attention = encoder_hidden_states is not None
133
+
134
+ if is_cross_attention and past_key_value is not None:
135
+ # reuse k,v, cross_attentions
136
+ key_layer = past_key_value[0]
137
+ value_layer = past_key_value[1]
138
+ attention_mask = encoder_attention_mask
139
+ elif is_cross_attention:
140
+ key_layer = self.transpose_for_scores(self.key(inputs=encoder_hidden_states), batch_size)
141
+ value_layer = self.transpose_for_scores(self.value(inputs=encoder_hidden_states), batch_size)
142
+ attention_mask = encoder_attention_mask
143
+ elif past_key_value is not None:
144
+ key_layer = self.transpose_for_scores(self.key(inputs=hidden_states), batch_size)
145
+ value_layer = self.transpose_for_scores(self.value(inputs=hidden_states), batch_size)
146
+ key_layer = tf.concat([past_key_value[0], key_layer], axis=2)
147
+ value_layer = tf.concat([past_key_value[1], value_layer], axis=2)
148
+ else:
149
+ key_layer = self.transpose_for_scores(self.key(inputs=hidden_states), batch_size)
150
+ value_layer = self.transpose_for_scores(self.value(inputs=hidden_states), batch_size)
151
+
152
+ query_layer = self.transpose_for_scores(mixed_query_layer, batch_size)
153
+
154
+ if self.is_decoder:
155
+ # if cross_attention save Tuple(tf.Tensor, tf.Tensor) of all cross attention key/value_states.
156
+ # Further calls to cross_attention layer can then reuse all cross-attention
157
+ # key/value_states (first "if" case)
158
+ # if uni-directional self-attention (decoder) save Tuple(tf.Tensor, tf.Tensor) of
159
+ # all previous decoder key/value_states. Further calls to uni-directional self-attention
160
+ # can concat previous decoder key/value_states to current projected key/value_states (third "elif" case)
161
+ # if encoder bi-directional self-attention `past_key_value` is always `None`
162
+ past_key_value = (key_layer, value_layer)
163
+
164
+ # Take the dot product between "query" and "key" to get the raw attention scores.
165
+ # (batch size, num_heads, seq_len_q, seq_len_k)
166
+ attention_scores = tf.matmul(query_layer, key_layer, transpose_b=True)
167
+ dk = tf.cast(self.sqrt_att_head_size, dtype=attention_scores.dtype)
168
+ attention_scores = tf.divide(attention_scores, dk)
169
+
170
+ if attention_mask is not None:
171
+ # Apply the attention mask is (precomputed for all layers in TFElectraModel call() function)
172
+ attention_scores = tf.add(attention_scores, attention_mask)
173
+
174
+ # Normalize the attention scores to probabilities.
175
+ attention_probs = stable_softmax(logits=attention_scores, axis=-1)
176
+
177
+ # This is actually dropping out entire tokens to attend to, which might
178
+ # seem a bit unusual, but is taken from the original Transformer paper.
179
+ attention_probs = self.dropout(inputs=attention_probs, training=training)
180
+
181
+ # Mask heads if we want to
182
+ if head_mask is not None:
183
+ attention_probs = tf.multiply(attention_probs, head_mask)
184
+
185
+ attention_output = tf.matmul(attention_probs, value_layer)
186
+ attention_output = tf.transpose(attention_output, perm=[0, 2, 1, 3])
187
+
188
+ # (batch_size, seq_len_q, all_head_size)
189
+ attention_output = tf.reshape(tensor=attention_output, shape=(batch_size, -1, self.all_head_size))
190
+ outputs = (attention_output, attention_probs) if output_attentions else (attention_output,)
191
+
192
+ if self.is_decoder:
193
+ outputs = outputs + (past_key_value,)
194
+ return outputs
195
+
196
+ def build(self, input_shape=None):
197
+ if self.built:
198
+ return
199
+ self.built = True
200
+ if getattr(self, "query", None) is not None:
201
+ with tf.name_scope(self.query.name):
202
+ self.query.build([None, None, self.config.hidden_size])
203
+ if getattr(self, "key", None) is not None:
204
+ with tf.name_scope(self.key.name):
205
+ self.key.build([None, None, self.config.hidden_size])
206
+ if getattr(self, "value", None) is not None:
207
+ with tf.name_scope(self.value.name):
208
+ self.value.build([None, None, self.config.hidden_size])
209
+
210
+
211
+ # Copied from transformers.models.bert.modeling_tf_bert.TFBertSelfOutput with Bert->Electra
212
+ class TFElectraSelfOutput(tf.keras.layers.Layer):
213
+ def __init__(self, config: ElectraConfig, **kwargs):
214
+ super().__init__(**kwargs)
215
+
216
+ self.dense = tf.keras.layers.Dense(
217
+ units=config.hidden_size, kernel_initializer=get_initializer(config.initializer_range), name="dense"
218
+ )
219
+ self.LayerNorm = tf.keras.layers.LayerNormalization(epsilon=config.layer_norm_eps, name="LayerNorm")
220
+ self.dropout = tf.keras.layers.Dropout(rate=config.hidden_dropout_prob)
221
+ self.config = config
222
+
223
+ def call(self, hidden_states: tf.Tensor, input_tensor: tf.Tensor, training: bool = False) -> tf.Tensor:
224
+ hidden_states = self.dense(inputs=hidden_states)
225
+ hidden_states = self.dropout(inputs=hidden_states, training=training)
226
+ hidden_states = self.LayerNorm(inputs=hidden_states + input_tensor)
227
+
228
+ return hidden_states
229
+
230
+ def build(self, input_shape=None):
231
+ if self.built:
232
+ return
233
+ self.built = True
234
+ if getattr(self, "dense", None) is not None:
235
+ with tf.name_scope(self.dense.name):
236
+ self.dense.build([None, None, self.config.hidden_size])
237
+ if getattr(self, "LayerNorm", None) is not None:
238
+ with tf.name_scope(self.LayerNorm.name):
239
+ self.LayerNorm.build([None, None, self.config.hidden_size])
240
+
241
+
242
+ # Copied from transformers.models.bert.modeling_tf_bert.TFBertAttention with Bert->Electra
243
+ class TFElectraAttention(tf.keras.layers.Layer):
244
+ def __init__(self, config: ElectraConfig, **kwargs):
245
+ super().__init__(**kwargs)
246
+
247
+ self.self_attention = TFElectraSelfAttention(config, name="self")
248
+ self.dense_output = TFElectraSelfOutput(config, name="output")
249
+
250
+ def prune_heads(self, heads):
251
+ raise NotImplementedError
252
+
253
+ def call(
254
+ self,
255
+ input_tensor: tf.Tensor,
256
+ attention_mask: tf.Tensor,
257
+ head_mask: tf.Tensor,
258
+ encoder_hidden_states: tf.Tensor,
259
+ encoder_attention_mask: tf.Tensor,
260
+ past_key_value: Tuple[tf.Tensor],
261
+ output_attentions: bool,
262
+ training: bool = False,
263
+ ) -> Tuple[tf.Tensor]:
264
+ self_outputs = self.self_attention(
265
+ hidden_states=input_tensor,
266
+ attention_mask=attention_mask,
267
+ head_mask=head_mask,
268
+ encoder_hidden_states=encoder_hidden_states,
269
+ encoder_attention_mask=encoder_attention_mask,
270
+ past_key_value=past_key_value,
271
+ output_attentions=output_attentions,
272
+ training=training,
273
+ )
274
+ attention_output = self.dense_output(
275
+ hidden_states=self_outputs[0], input_tensor=input_tensor, training=training
276
+ )
277
+ # add attentions (possibly with past_key_value) if we output them
278
+ outputs = (attention_output,) + self_outputs[1:]
279
+
280
+ return outputs
281
+
282
+ def build(self, input_shape=None):
283
+ if self.built:
284
+ return
285
+ self.built = True
286
+ if getattr(self, "self_attention", None) is not None:
287
+ with tf.name_scope(self.self_attention.name):
288
+ self.self_attention.build(None)
289
+ if getattr(self, "dense_output", None) is not None:
290
+ with tf.name_scope(self.dense_output.name):
291
+ self.dense_output.build(None)
292
+
293
+
294
+ # Copied from transformers.models.bert.modeling_tf_bert.TFBertIntermediate with Bert->Electra
295
+ class TFElectraIntermediate(tf.keras.layers.Layer):
296
+ def __init__(self, config: ElectraConfig, **kwargs):
297
+ super().__init__(**kwargs)
298
+
299
+ self.dense = tf.keras.layers.Dense(
300
+ units=config.intermediate_size, kernel_initializer=get_initializer(config.initializer_range), name="dense"
301
+ )
302
+
303
+ if isinstance(config.hidden_act, str):
304
+ self.intermediate_act_fn = get_tf_activation(config.hidden_act)
305
+ else:
306
+ self.intermediate_act_fn = config.hidden_act
307
+ self.config = config
308
+
309
+ def call(self, hidden_states: tf.Tensor) -> tf.Tensor:
310
+ hidden_states = self.dense(inputs=hidden_states)
311
+ hidden_states = self.intermediate_act_fn(hidden_states)
312
+
313
+ return hidden_states
314
+
315
+ def build(self, input_shape=None):
316
+ if self.built:
317
+ return
318
+ self.built = True
319
+ if getattr(self, "dense", None) is not None:
320
+ with tf.name_scope(self.dense.name):
321
+ self.dense.build([None, None, self.config.hidden_size])
322
+
323
+
324
+ # Copied from transformers.models.bert.modeling_tf_bert.TFBertOutput with Bert->Electra
325
+ class TFElectraOutput(tf.keras.layers.Layer):
326
+ def __init__(self, config: ElectraConfig, **kwargs):
327
+ super().__init__(**kwargs)
328
+
329
+ self.dense = tf.keras.layers.Dense(
330
+ units=config.hidden_size, kernel_initializer=get_initializer(config.initializer_range), name="dense"
331
+ )
332
+ self.LayerNorm = tf.keras.layers.LayerNormalization(epsilon=config.layer_norm_eps, name="LayerNorm")
333
+ self.dropout = tf.keras.layers.Dropout(rate=config.hidden_dropout_prob)
334
+ self.config = config
335
+
336
+ def call(self, hidden_states: tf.Tensor, input_tensor: tf.Tensor, training: bool = False) -> tf.Tensor:
337
+ hidden_states = self.dense(inputs=hidden_states)
338
+ hidden_states = self.dropout(inputs=hidden_states, training=training)
339
+ hidden_states = self.LayerNorm(inputs=hidden_states + input_tensor)
340
+
341
+ return hidden_states
342
+
343
+ def build(self, input_shape=None):
344
+ if self.built:
345
+ return
346
+ self.built = True
347
+ if getattr(self, "dense", None) is not None:
348
+ with tf.name_scope(self.dense.name):
349
+ self.dense.build([None, None, self.config.intermediate_size])
350
+ if getattr(self, "LayerNorm", None) is not None:
351
+ with tf.name_scope(self.LayerNorm.name):
352
+ self.LayerNorm.build([None, None, self.config.hidden_size])
353
+
354
+
355
+ # Copied from transformers.models.bert.modeling_tf_bert.TFBertLayer with Bert->Electra
356
+ class TFElectraLayer(tf.keras.layers.Layer):
357
+ def __init__(self, config: ElectraConfig, **kwargs):
358
+ super().__init__(**kwargs)
359
+
360
+ self.attention = TFElectraAttention(config, name="attention")
361
+ self.is_decoder = config.is_decoder
362
+ self.add_cross_attention = config.add_cross_attention
363
+ if self.add_cross_attention:
364
+ if not self.is_decoder:
365
+ raise ValueError(f"{self} should be used as a decoder model if cross attention is added")
366
+ self.crossattention = TFElectraAttention(config, name="crossattention")
367
+ self.intermediate = TFElectraIntermediate(config, name="intermediate")
368
+ self.bert_output = TFElectraOutput(config, name="output")
369
+
370
+ def call(
371
+ self,
372
+ hidden_states: tf.Tensor,
373
+ attention_mask: tf.Tensor,
374
+ head_mask: tf.Tensor,
375
+ encoder_hidden_states: tf.Tensor | None,
376
+ encoder_attention_mask: tf.Tensor | None,
377
+ past_key_value: Tuple[tf.Tensor] | None,
378
+ output_attentions: bool,
379
+ training: bool = False,
380
+ ) -> Tuple[tf.Tensor]:
381
+ # decoder uni-directional self-attention cached key/values tuple is at positions 1,2
382
+ self_attn_past_key_value = past_key_value[:2] if past_key_value is not None else None
383
+ self_attention_outputs = self.attention(
384
+ input_tensor=hidden_states,
385
+ attention_mask=attention_mask,
386
+ head_mask=head_mask,
387
+ encoder_hidden_states=None,
388
+ encoder_attention_mask=None,
389
+ past_key_value=self_attn_past_key_value,
390
+ output_attentions=output_attentions,
391
+ training=training,
392
+ )
393
+ attention_output = self_attention_outputs[0]
394
+
395
+ # if decoder, the last output is tuple of self-attn cache
396
+ if self.is_decoder:
397
+ outputs = self_attention_outputs[1:-1]
398
+ present_key_value = self_attention_outputs[-1]
399
+ else:
400
+ outputs = self_attention_outputs[1:] # add self attentions if we output attention weights
401
+
402
+ cross_attn_present_key_value = None
403
+ if self.is_decoder and encoder_hidden_states is not None:
404
+ if not hasattr(self, "crossattention"):
405
+ raise ValueError(
406
+ f"If `encoder_hidden_states` are passed, {self} has to be instantiated with cross-attention layers"
407
+ " by setting `config.add_cross_attention=True`"
408
+ )
409
+
410
+ # cross_attn cached key/values tuple is at positions 3,4 of past_key_value tuple
411
+ cross_attn_past_key_value = past_key_value[-2:] if past_key_value is not None else None
412
+ cross_attention_outputs = self.crossattention(
413
+ input_tensor=attention_output,
414
+ attention_mask=attention_mask,
415
+ head_mask=head_mask,
416
+ encoder_hidden_states=encoder_hidden_states,
417
+ encoder_attention_mask=encoder_attention_mask,
418
+ past_key_value=cross_attn_past_key_value,
419
+ output_attentions=output_attentions,
420
+ training=training,
421
+ )
422
+ attention_output = cross_attention_outputs[0]
423
+ outputs = outputs + cross_attention_outputs[1:-1] # add cross attentions if we output attention weights
424
+
425
+ # add cross-attn cache to positions 3,4 of present_key_value tuple
426
+ cross_attn_present_key_value = cross_attention_outputs[-1]
427
+ present_key_value = present_key_value + cross_attn_present_key_value
428
+
429
+ intermediate_output = self.intermediate(hidden_states=attention_output)
430
+ layer_output = self.bert_output(
431
+ hidden_states=intermediate_output, input_tensor=attention_output, training=training
432
+ )
433
+ outputs = (layer_output,) + outputs # add attentions if we output them
434
+
435
+ # if decoder, return the attn key/values as the last output
436
+ if self.is_decoder:
437
+ outputs = outputs + (present_key_value,)
438
+
439
+ return outputs
440
+
441
+ def build(self, input_shape=None):
442
+ if self.built:
443
+ return
444
+ self.built = True
445
+ if getattr(self, "attention", None) is not None:
446
+ with tf.name_scope(self.attention.name):
447
+ self.attention.build(None)
448
+ if getattr(self, "intermediate", None) is not None:
449
+ with tf.name_scope(self.intermediate.name):
450
+ self.intermediate.build(None)
451
+ if getattr(self, "bert_output", None) is not None:
452
+ with tf.name_scope(self.bert_output.name):
453
+ self.bert_output.build(None)
454
+ if getattr(self, "crossattention", None) is not None:
455
+ with tf.name_scope(self.crossattention.name):
456
+ self.crossattention.build(None)
457
+
458
+
459
+ # Copied from transformers.models.bert.modeling_tf_bert.TFBertEncoder with Bert->Electra
460
+ class TFElectraEncoder(tf.keras.layers.Layer):
461
+ def __init__(self, config: ElectraConfig, **kwargs):
462
+ super().__init__(**kwargs)
463
+ self.config = config
464
+ self.layer = [TFElectraLayer(config, name=f"layer_._{i}") for i in range(config.num_hidden_layers)]
465
+
466
+ def call(
467
+ self,
468
+ hidden_states: tf.Tensor,
469
+ attention_mask: tf.Tensor,
470
+ head_mask: tf.Tensor,
471
+ encoder_hidden_states: tf.Tensor | None,
472
+ encoder_attention_mask: tf.Tensor | None,
473
+ past_key_values: Tuple[Tuple[tf.Tensor]] | None,
474
+ use_cache: Optional[bool],
475
+ output_attentions: bool,
476
+ output_hidden_states: bool,
477
+ return_dict: bool,
478
+ training: bool = False,
479
+ ) -> Union[TFBaseModelOutputWithPastAndCrossAttentions, Tuple[tf.Tensor]]:
480
+ all_hidden_states = () if output_hidden_states else None
481
+ all_attentions = () if output_attentions else None
482
+ all_cross_attentions = () if output_attentions and self.config.add_cross_attention else None
483
+
484
+ next_decoder_cache = () if use_cache else None
485
+ for i, layer_module in enumerate(self.layer):
486
+ if output_hidden_states:
487
+ all_hidden_states = all_hidden_states + (hidden_states,)
488
+
489
+ past_key_value = past_key_values[i] if past_key_values is not None else None
490
+
491
+ layer_outputs = layer_module(
492
+ hidden_states=hidden_states,
493
+ attention_mask=attention_mask,
494
+ head_mask=head_mask[i],
495
+ encoder_hidden_states=encoder_hidden_states,
496
+ encoder_attention_mask=encoder_attention_mask,
497
+ past_key_value=past_key_value,
498
+ output_attentions=output_attentions,
499
+ training=training,
500
+ )
501
+ hidden_states = layer_outputs[0]
502
+
503
+ if use_cache:
504
+ next_decoder_cache += (layer_outputs[-1],)
505
+
506
+ if output_attentions:
507
+ all_attentions = all_attentions + (layer_outputs[1],)
508
+ if self.config.add_cross_attention and encoder_hidden_states is not None:
509
+ all_cross_attentions = all_cross_attentions + (layer_outputs[2],)
510
+
511
+ # Add last layer
512
+ if output_hidden_states:
513
+ all_hidden_states = all_hidden_states + (hidden_states,)
514
+
515
+ if not return_dict:
516
+ return tuple(
517
+ v for v in [hidden_states, all_hidden_states, all_attentions, all_cross_attentions] if v is not None
518
+ )
519
+
520
+ return TFBaseModelOutputWithPastAndCrossAttentions(
521
+ last_hidden_state=hidden_states,
522
+ past_key_values=next_decoder_cache,
523
+ hidden_states=all_hidden_states,
524
+ attentions=all_attentions,
525
+ cross_attentions=all_cross_attentions,
526
+ )
527
+
528
+ def build(self, input_shape=None):
529
+ if self.built:
530
+ return
531
+ self.built = True
532
+ if getattr(self, "layer", None) is not None:
533
+ for layer in self.layer:
534
+ with tf.name_scope(layer.name):
535
+ layer.build(None)
536
+
537
+
538
+ # Copied from transformers.models.bert.modeling_tf_bert.TFBertPooler with Bert->Electra
539
+ class TFElectraPooler(tf.keras.layers.Layer):
540
+ def __init__(self, config: ElectraConfig, **kwargs):
541
+ super().__init__(**kwargs)
542
+
543
+ self.dense = tf.keras.layers.Dense(
544
+ units=config.hidden_size,
545
+ kernel_initializer=get_initializer(config.initializer_range),
546
+ activation="tanh",
547
+ name="dense",
548
+ )
549
+ self.config = config
550
+
551
+ def call(self, hidden_states: tf.Tensor) -> tf.Tensor:
552
+ # We "pool" the model by simply taking the hidden state corresponding
553
+ # to the first token.
554
+ first_token_tensor = hidden_states[:, 0]
555
+ pooled_output = self.dense(inputs=first_token_tensor)
556
+
557
+ return pooled_output
558
+
559
+ def build(self, input_shape=None):
560
+ if self.built:
561
+ return
562
+ self.built = True
563
+ if getattr(self, "dense", None) is not None:
564
+ with tf.name_scope(self.dense.name):
565
+ self.dense.build([None, None, self.config.hidden_size])
566
+
567
+
568
+ # Copied from transformers.models.albert.modeling_tf_albert.TFAlbertEmbeddings with Albert->Electra
569
+ class TFElectraEmbeddings(tf.keras.layers.Layer):
570
+ """Construct the embeddings from word, position and token_type embeddings."""
571
+
572
+ def __init__(self, config: ElectraConfig, **kwargs):
573
+ super().__init__(**kwargs)
574
+
575
+ self.config = config
576
+ self.embedding_size = config.embedding_size
577
+ self.max_position_embeddings = config.max_position_embeddings
578
+ self.initializer_range = config.initializer_range
579
+ self.LayerNorm = tf.keras.layers.LayerNormalization(epsilon=config.layer_norm_eps, name="LayerNorm")
580
+ self.dropout = tf.keras.layers.Dropout(rate=config.hidden_dropout_prob)
581
+
582
+ def build(self, input_shape=None):
583
+ with tf.name_scope("word_embeddings"):
584
+ self.weight = self.add_weight(
585
+ name="weight",
586
+ shape=[self.config.vocab_size, self.embedding_size],
587
+ initializer=get_initializer(self.initializer_range),
588
+ )
589
+
590
+ with tf.name_scope("token_type_embeddings"):
591
+ self.token_type_embeddings = self.add_weight(
592
+ name="embeddings",
593
+ shape=[self.config.type_vocab_size, self.embedding_size],
594
+ initializer=get_initializer(self.initializer_range),
595
+ )
596
+
597
+ with tf.name_scope("position_embeddings"):
598
+ self.position_embeddings = self.add_weight(
599
+ name="embeddings",
600
+ shape=[self.max_position_embeddings, self.embedding_size],
601
+ initializer=get_initializer(self.initializer_range),
602
+ )
603
+
604
+ if self.built:
605
+ return
606
+ self.built = True
607
+ if getattr(self, "LayerNorm", None) is not None:
608
+ with tf.name_scope(self.LayerNorm.name):
609
+ self.LayerNorm.build([None, None, self.config.embedding_size])
610
+
611
+ # Copied from transformers.models.bert.modeling_tf_bert.TFBertEmbeddings.call
612
+ def call(
613
+ self,
614
+ input_ids: tf.Tensor = None,
615
+ position_ids: tf.Tensor = None,
616
+ token_type_ids: tf.Tensor = None,
617
+ inputs_embeds: tf.Tensor = None,
618
+ past_key_values_length=0,
619
+ training: bool = False,
620
+ ) -> tf.Tensor:
621
+ """
622
+ Applies embedding based on inputs tensor.
623
+
624
+ Returns:
625
+ final_embeddings (`tf.Tensor`): output embedding tensor.
626
+ """
627
+ if input_ids is None and inputs_embeds is None:
628
+ raise ValueError("Need to provide either `input_ids` or `input_embeds`.")
629
+
630
+ if input_ids is not None:
631
+ check_embeddings_within_bounds(input_ids, self.config.vocab_size)
632
+ inputs_embeds = tf.gather(params=self.weight, indices=input_ids)
633
+
634
+ input_shape = shape_list(inputs_embeds)[:-1]
635
+
636
+ if token_type_ids is None:
637
+ token_type_ids = tf.fill(dims=input_shape, value=0)
638
+
639
+ if position_ids is None:
640
+ position_ids = tf.expand_dims(
641
+ tf.range(start=past_key_values_length, limit=input_shape[1] + past_key_values_length), axis=0
642
+ )
643
+
644
+ position_embeds = tf.gather(params=self.position_embeddings, indices=position_ids)
645
+ token_type_embeds = tf.gather(params=self.token_type_embeddings, indices=token_type_ids)
646
+ final_embeddings = inputs_embeds + position_embeds + token_type_embeds
647
+ final_embeddings = self.LayerNorm(inputs=final_embeddings)
648
+ final_embeddings = self.dropout(inputs=final_embeddings, training=training)
649
+
650
+ return final_embeddings
651
+
652
+
653
+ class TFElectraDiscriminatorPredictions(tf.keras.layers.Layer):
654
+ def __init__(self, config, **kwargs):
655
+ super().__init__(**kwargs)
656
+
657
+ self.dense = tf.keras.layers.Dense(config.hidden_size, name="dense")
658
+ self.dense_prediction = tf.keras.layers.Dense(1, name="dense_prediction")
659
+ self.config = config
660
+
661
+ def call(self, discriminator_hidden_states, training=False):
662
+ hidden_states = self.dense(discriminator_hidden_states)
663
+ hidden_states = get_tf_activation(self.config.hidden_act)(hidden_states)
664
+ logits = tf.squeeze(self.dense_prediction(hidden_states), -1)
665
+
666
+ return logits
667
+
668
+ def build(self, input_shape=None):
669
+ if self.built:
670
+ return
671
+ self.built = True
672
+ if getattr(self, "dense", None) is not None:
673
+ with tf.name_scope(self.dense.name):
674
+ self.dense.build([None, None, self.config.hidden_size])
675
+ if getattr(self, "dense_prediction", None) is not None:
676
+ with tf.name_scope(self.dense_prediction.name):
677
+ self.dense_prediction.build([None, None, self.config.hidden_size])
678
+
679
+
680
+ class TFElectraGeneratorPredictions(tf.keras.layers.Layer):
681
+ def __init__(self, config, **kwargs):
682
+ super().__init__(**kwargs)
683
+
684
+ self.LayerNorm = tf.keras.layers.LayerNormalization(epsilon=config.layer_norm_eps, name="LayerNorm")
685
+ self.dense = tf.keras.layers.Dense(config.embedding_size, name="dense")
686
+ self.config = config
687
+
688
+ def call(self, generator_hidden_states, training=False):
689
+ hidden_states = self.dense(generator_hidden_states)
690
+ hidden_states = get_tf_activation("gelu")(hidden_states)
691
+ hidden_states = self.LayerNorm(hidden_states)
692
+
693
+ return hidden_states
694
+
695
+ def build(self, input_shape=None):
696
+ if self.built:
697
+ return
698
+ self.built = True
699
+ if getattr(self, "LayerNorm", None) is not None:
700
+ with tf.name_scope(self.LayerNorm.name):
701
+ self.LayerNorm.build([None, None, self.config.embedding_size])
702
+ if getattr(self, "dense", None) is not None:
703
+ with tf.name_scope(self.dense.name):
704
+ self.dense.build([None, None, self.config.hidden_size])
705
+
706
+
707
+ class TFElectraPreTrainedModel(TFPreTrainedModel):
708
+ """
709
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
710
+ models.
711
+ """
712
+
713
+ config_class = ElectraConfig
714
+ base_model_prefix = "electra"
715
+ # When the model is loaded from a PT model
716
+ _keys_to_ignore_on_load_unexpected = [r"generator_lm_head.weight"]
717
+ _keys_to_ignore_on_load_missing = [r"dropout"]
718
+
719
+
720
+ @keras_serializable
721
+ class TFElectraMainLayer(tf.keras.layers.Layer):
722
+ config_class = ElectraConfig
723
+
724
+ def __init__(self, config, **kwargs):
725
+ super().__init__(**kwargs)
726
+
727
+ self.config = config
728
+ self.is_decoder = config.is_decoder
729
+
730
+ self.embeddings = TFElectraEmbeddings(config, name="embeddings")
731
+
732
+ if config.embedding_size != config.hidden_size:
733
+ self.embeddings_project = tf.keras.layers.Dense(config.hidden_size, name="embeddings_project")
734
+
735
+ self.encoder = TFElectraEncoder(config, name="encoder")
736
+
737
+ def get_input_embeddings(self):
738
+ return self.embeddings
739
+
740
+ def set_input_embeddings(self, value):
741
+ self.embeddings.weight = value
742
+ self.embeddings.vocab_size = shape_list(value)[0]
743
+
744
+ def _prune_heads(self, heads_to_prune):
745
+ """
746
+ Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
747
+ class PreTrainedModel
748
+ """
749
+ raise NotImplementedError
750
+
751
+ def get_extended_attention_mask(self, attention_mask, input_shape, dtype, past_key_values_length=0):
752
+ batch_size, seq_length = input_shape
753
+
754
+ if attention_mask is None:
755
+ attention_mask = tf.fill(dims=(batch_size, seq_length + past_key_values_length), value=1)
756
+
757
+ # We create a 3D attention mask from a 2D tensor mask.
758
+ # Sizes are [batch_size, 1, 1, to_seq_length]
759
+ # So we can broadcast to [batch_size, num_heads, from_seq_length, to_seq_length]
760
+ # this attention mask is more simple than the triangular masking of causal attention
761
+ # used in OpenAI GPT, we just need to prepare the broadcast dimension here.
762
+ attention_mask_shape = shape_list(attention_mask)
763
+
764
+ mask_seq_length = seq_length + past_key_values_length
765
+ # Copied from `modeling_tf_t5.py`
766
+ # Provided a padding mask of dimensions [batch_size, mask_seq_length]
767
+ # - if the model is a decoder, apply a causal mask in addition to the padding mask
768
+ # - if the model is an encoder, make the mask broadcastable to [batch_size, num_heads, mask_seq_length, mask_seq_length]
769
+ if self.is_decoder:
770
+ seq_ids = tf.range(mask_seq_length)
771
+ causal_mask = tf.less_equal(
772
+ tf.tile(seq_ids[None, None, :], (batch_size, mask_seq_length, 1)),
773
+ seq_ids[None, :, None],
774
+ )
775
+ causal_mask = tf.cast(causal_mask, dtype=attention_mask.dtype)
776
+ extended_attention_mask = causal_mask * attention_mask[:, None, :]
777
+ attention_mask_shape = shape_list(extended_attention_mask)
778
+ extended_attention_mask = tf.reshape(
779
+ extended_attention_mask, (attention_mask_shape[0], 1, attention_mask_shape[1], attention_mask_shape[2])
780
+ )
781
+ if past_key_values_length > 0:
782
+ extended_attention_mask = extended_attention_mask[:, :, -seq_length:, :]
783
+ else:
784
+ extended_attention_mask = tf.reshape(
785
+ attention_mask, (attention_mask_shape[0], 1, 1, attention_mask_shape[1])
786
+ )
787
+
788
+ # Since attention_mask is 1.0 for positions we want to attend and 0.0 for
789
+ # masked positions, this operation will create a tensor which is 0.0 for
790
+ # positions we want to attend and -10000.0 for masked positions.
791
+ # Since we are adding it to the raw scores before the softmax, this is
792
+ # effectively the same as removing these entirely.
793
+ extended_attention_mask = tf.cast(extended_attention_mask, dtype=dtype)
794
+ one_cst = tf.constant(1.0, dtype=dtype)
795
+ ten_thousand_cst = tf.constant(-10000.0, dtype=dtype)
796
+ extended_attention_mask = tf.multiply(tf.subtract(one_cst, extended_attention_mask), ten_thousand_cst)
797
+
798
+ return extended_attention_mask
799
+
800
+ def get_head_mask(self, head_mask):
801
+ if head_mask is not None:
802
+ raise NotImplementedError
803
+ else:
804
+ head_mask = [None] * self.config.num_hidden_layers
805
+
806
+ return head_mask
807
+
808
+ @unpack_inputs
809
+ def call(
810
+ self,
811
+ input_ids: TFModelInputType | None = None,
812
+ attention_mask: np.ndarray | tf.Tensor | None = None,
813
+ token_type_ids: np.ndarray | tf.Tensor | None = None,
814
+ position_ids: np.ndarray | tf.Tensor | None = None,
815
+ head_mask: np.ndarray | tf.Tensor | None = None,
816
+ inputs_embeds: np.ndarray | tf.Tensor | None = None,
817
+ encoder_hidden_states: np.ndarray | tf.Tensor | None = None,
818
+ encoder_attention_mask: np.ndarray | tf.Tensor | None = None,
819
+ past_key_values: Optional[Tuple[Tuple[Union[np.ndarray, tf.Tensor]]]] = None,
820
+ use_cache: Optional[bool] = None,
821
+ output_attentions: Optional[bool] = None,
822
+ output_hidden_states: Optional[bool] = None,
823
+ return_dict: Optional[bool] = None,
824
+ training: Optional[bool] = False,
825
+ ) -> Union[TFBaseModelOutputWithPastAndCrossAttentions, Tuple[tf.Tensor]]:
826
+ if not self.config.is_decoder:
827
+ use_cache = False
828
+
829
+ if input_ids is not None and inputs_embeds is not None:
830
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
831
+ elif input_ids is not None:
832
+ input_shape = shape_list(input_ids)
833
+ elif inputs_embeds is not None:
834
+ input_shape = shape_list(inputs_embeds)[:-1]
835
+ else:
836
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
837
+
838
+ batch_size, seq_length = input_shape
839
+
840
+ if past_key_values is None:
841
+ past_key_values_length = 0
842
+ past_key_values = [None] * len(self.encoder.layer)
843
+ else:
844
+ past_key_values_length = shape_list(past_key_values[0][0])[-2]
845
+
846
+ if attention_mask is None:
847
+ attention_mask = tf.fill(dims=(batch_size, seq_length + past_key_values_length), value=1)
848
+
849
+ if token_type_ids is None:
850
+ token_type_ids = tf.fill(dims=input_shape, value=0)
851
+
852
+ hidden_states = self.embeddings(
853
+ input_ids=input_ids,
854
+ position_ids=position_ids,
855
+ token_type_ids=token_type_ids,
856
+ inputs_embeds=inputs_embeds,
857
+ past_key_values_length=past_key_values_length,
858
+ training=training,
859
+ )
860
+ extended_attention_mask = self.get_extended_attention_mask(
861
+ attention_mask, input_shape, hidden_states.dtype, past_key_values_length
862
+ )
863
+
864
+ # Copied from `modeling_tf_t5.py` with -1e9 -> -10000
865
+ if self.is_decoder and encoder_attention_mask is not None:
866
+ # If a 2D ou 3D attention mask is provided for the cross-attention
867
+ # we need to make broadcastable to [batch_size, num_heads, mask_seq_length, mask_seq_length]
868
+ # we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length]
869
+ encoder_attention_mask = tf.cast(encoder_attention_mask, dtype=extended_attention_mask.dtype)
870
+ num_dims_encoder_attention_mask = len(shape_list(encoder_attention_mask))
871
+ if num_dims_encoder_attention_mask == 3:
872
+ encoder_extended_attention_mask = encoder_attention_mask[:, None, :, :]
873
+ if num_dims_encoder_attention_mask == 2:
874
+ encoder_extended_attention_mask = encoder_attention_mask[:, None, None, :]
875
+
876
+ # T5 has a mask that can compare sequence ids, we can simulate this here with this transposition
877
+ # Cf. https://github.com/tensorflow/mesh/blob/8d2465e9bc93129b913b5ccc6a59aa97abd96ec6/mesh_tensorflow/transformer/transformer_layers.py#L270
878
+ # encoder_extended_attention_mask = tf.math.equal(encoder_extended_attention_mask,
879
+ # tf.transpose(encoder_extended_attention_mask, perm=(-1, -2)))
880
+
881
+ encoder_extended_attention_mask = (1.0 - encoder_extended_attention_mask) * -10000.0
882
+ else:
883
+ encoder_extended_attention_mask = None
884
+
885
+ head_mask = self.get_head_mask(head_mask)
886
+
887
+ if hasattr(self, "embeddings_project"):
888
+ hidden_states = self.embeddings_project(hidden_states, training=training)
889
+
890
+ hidden_states = self.encoder(
891
+ hidden_states=hidden_states,
892
+ attention_mask=extended_attention_mask,
893
+ head_mask=head_mask,
894
+ encoder_hidden_states=encoder_hidden_states,
895
+ encoder_attention_mask=encoder_extended_attention_mask,
896
+ past_key_values=past_key_values,
897
+ use_cache=use_cache,
898
+ output_attentions=output_attentions,
899
+ output_hidden_states=output_hidden_states,
900
+ return_dict=return_dict,
901
+ training=training,
902
+ )
903
+
904
+ return hidden_states
905
+
906
+ def build(self, input_shape=None):
907
+ if self.built:
908
+ return
909
+ self.built = True
910
+ if getattr(self, "embeddings", None) is not None:
911
+ with tf.name_scope(self.embeddings.name):
912
+ self.embeddings.build(None)
913
+ if getattr(self, "encoder", None) is not None:
914
+ with tf.name_scope(self.encoder.name):
915
+ self.encoder.build(None)
916
+ if getattr(self, "embeddings_project", None) is not None:
917
+ with tf.name_scope(self.embeddings_project.name):
918
+ self.embeddings_project.build([None, None, self.config.embedding_size])
919
+
920
+
921
+ @dataclass
922
+ class TFElectraForPreTrainingOutput(ModelOutput):
923
+ """
924
+ Output type of [`TFElectraForPreTraining`].
925
+
926
+ Args:
927
+ loss (*optional*, returned when `labels` is provided, `tf.Tensor` of shape `(1,)`):
928
+ Total loss of the ELECTRA objective.
929
+ logits (`tf.Tensor` of shape `(batch_size, sequence_length)`):
930
+ Prediction scores of the head (scores for each token before SoftMax).
931
+ hidden_states (`tuple(tf.Tensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
932
+ Tuple of `tf.Tensor` (one for the output of the embeddings + one for the output of each layer) of shape
933
+ `(batch_size, sequence_length, hidden_size)`.
934
+
935
+ Hidden-states of the model at the output of each layer plus the initial embedding outputs.
936
+ attentions (`tuple(tf.Tensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
937
+ Tuple of `tf.Tensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
938
+ sequence_length)`.
939
+
940
+ Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
941
+ heads.
942
+ """
943
+
944
+ logits: tf.Tensor = None
945
+ hidden_states: Tuple[tf.Tensor] | None = None
946
+ attentions: Tuple[tf.Tensor] | None = None
947
+
948
+
949
+ ELECTRA_START_DOCSTRING = r"""
950
+
951
+ This model inherits from [`TFPreTrainedModel`]. Check the superclass documentation for the generic methods the
952
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
953
+ etc.)
954
+
955
+ This model is also a [tf.keras.Model](https://www.tensorflow.org/api_docs/python/tf/keras/Model) subclass. Use it
956
+ as a regular TF 2.0 Keras Model and refer to the TF 2.0 documentation for all matter related to general usage and
957
+ behavior.
958
+
959
+ <Tip>
960
+
961
+ TensorFlow models and layers in `transformers` accept two formats as input:
962
+
963
+ - having all inputs as keyword arguments (like PyTorch models), or
964
+ - having all inputs as a list, tuple or dict in the first positional argument.
965
+
966
+ The reason the second format is supported is that Keras methods prefer this format when passing inputs to models
967
+ and layers. Because of this support, when using methods like `model.fit()` things should "just work" for you - just
968
+ pass your inputs and labels in any format that `model.fit()` supports! If, however, you want to use the second
969
+ format outside of Keras methods like `fit()` and `predict()`, such as when creating your own layers or models with
970
+ the Keras `Functional` API, there are three possibilities you can use to gather all the input Tensors in the first
971
+ positional argument:
972
+
973
+ - a single Tensor with `input_ids` only and nothing else: `model(input_ids)`
974
+ - a list of varying length with one or several input Tensors IN THE ORDER given in the docstring:
975
+ `model([input_ids, attention_mask])` or `model([input_ids, attention_mask, token_type_ids])`
976
+ - a dictionary with one or several input Tensors associated to the input names given in the docstring:
977
+ `model({"input_ids": input_ids, "token_type_ids": token_type_ids})`
978
+
979
+ Note that when creating models and layers with
980
+ [subclassing](https://keras.io/guides/making_new_layers_and_models_via_subclassing/) then you don't need to worry
981
+ about any of this, as you can just pass inputs like you would to any other Python function!
982
+
983
+ </Tip>
984
+
985
+ Parameters:
986
+ config ([`ElectraConfig`]): Model configuration class with all the parameters of the model.
987
+ Initializing with a config file does not load the weights associated with the model, only the
988
+ configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
989
+ """
990
+
991
+ ELECTRA_INPUTS_DOCSTRING = r"""
992
+ Args:
993
+ input_ids (`Numpy array` or `tf.Tensor` of shape `({0})`):
994
+ Indices of input sequence tokens in the vocabulary.
995
+
996
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.__call__`] and
997
+ [`PreTrainedTokenizer.encode`] for details.
998
+
999
+ [What are input IDs?](../glossary#input-ids)
1000
+ attention_mask (`Numpy array` or `tf.Tensor` of shape `({0})`, *optional*):
1001
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
1002
+
1003
+ - 1 for tokens that are **not masked**,
1004
+ - 0 for tokens that are **masked**.
1005
+
1006
+ [What are attention masks?](../glossary#attention-mask)
1007
+ position_ids (`Numpy array` or `tf.Tensor` of shape `({0})`, *optional*):
1008
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
1009
+ config.max_position_embeddings - 1]`.
1010
+
1011
+ [What are position IDs?](../glossary#position-ids)
1012
+ head_mask (`Numpy array` or `tf.Tensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
1013
+ Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:
1014
+
1015
+ - 1 indicates the head is **not masked**,
1016
+ - 0 indicates the head is **masked**.
1017
+
1018
+ inputs_embeds (`tf.Tensor` of shape `({0}, hidden_size)`, *optional*):
1019
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
1020
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
1021
+ model's internal embedding lookup matrix.
1022
+ output_attentions (`bool`, *optional*):
1023
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
1024
+ tensors for more detail. This argument can be used only in eager mode, in graph mode the value in the
1025
+ config will be used instead.
1026
+ output_hidden_states (`bool`, *optional*):
1027
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
1028
+ more detail. This argument can be used only in eager mode, in graph mode the value in the config will be
1029
+ used instead.
1030
+ return_dict (`bool`, *optional*):
1031
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. This argument can be used in
1032
+ eager mode, in graph mode the value will always be set to True.
1033
+ training (`bool`, *optional*, defaults to `False`):
1034
+ Whether or not to use the model in training mode (some modules like dropout modules have different
1035
+ behaviors between training and evaluation).
1036
+ """
1037
+
1038
+
1039
+ @add_start_docstrings(
1040
+ "The bare Electra Model transformer outputting raw hidden-states without any specific head on top. Identical to "
1041
+ "the BERT model except that it uses an additional linear layer between the embedding layer and the encoder if the "
1042
+ "hidden size and embedding size are different. "
1043
+ ""
1044
+ "Both the generator and discriminator checkpoints may be loaded into this model.",
1045
+ ELECTRA_START_DOCSTRING,
1046
+ )
1047
+ class TFElectraModel(TFElectraPreTrainedModel):
1048
+ def __init__(self, config, *inputs, **kwargs):
1049
+ super().__init__(config, *inputs, **kwargs)
1050
+
1051
+ self.electra = TFElectraMainLayer(config, name="electra")
1052
+
1053
+ @unpack_inputs
1054
+ @add_start_docstrings_to_model_forward(ELECTRA_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
1055
+ @add_code_sample_docstrings(
1056
+ checkpoint=_CHECKPOINT_FOR_DOC,
1057
+ output_type=TFBaseModelOutputWithPastAndCrossAttentions,
1058
+ config_class=_CONFIG_FOR_DOC,
1059
+ )
1060
+ def call(
1061
+ self,
1062
+ input_ids: TFModelInputType | None = None,
1063
+ attention_mask: np.ndarray | tf.Tensor | None = None,
1064
+ token_type_ids: np.ndarray | tf.Tensor | None = None,
1065
+ position_ids: np.ndarray | tf.Tensor | None = None,
1066
+ head_mask: np.ndarray | tf.Tensor | None = None,
1067
+ inputs_embeds: np.ndarray | tf.Tensor | None = None,
1068
+ encoder_hidden_states: np.ndarray | tf.Tensor | None = None,
1069
+ encoder_attention_mask: np.ndarray | tf.Tensor | None = None,
1070
+ past_key_values: Optional[Tuple[Tuple[Union[np.ndarray, tf.Tensor]]]] = None,
1071
+ use_cache: Optional[bool] = None,
1072
+ output_attentions: Optional[bool] = None,
1073
+ output_hidden_states: Optional[bool] = None,
1074
+ return_dict: Optional[bool] = None,
1075
+ training: Optional[bool] = False,
1076
+ ) -> Union[TFBaseModelOutputWithPastAndCrossAttentions, Tuple[tf.Tensor]]:
1077
+ r"""
1078
+ encoder_hidden_states (`tf.Tensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
1079
+ Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if
1080
+ the model is configured as a decoder.
1081
+ encoder_attention_mask (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
1082
+ Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in
1083
+ the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`:
1084
+
1085
+ - 1 for tokens that are **not masked**,
1086
+ - 0 for tokens that are **masked**.
1087
+
1088
+ past_key_values (`Tuple[Tuple[tf.Tensor]]` of length `config.n_layers`)
1089
+ contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.
1090
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
1091
+ don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
1092
+ `decoder_input_ids` of shape `(batch_size, sequence_length)`.
1093
+ use_cache (`bool`, *optional*, defaults to `True`):
1094
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
1095
+ `past_key_values`). Set to `False` during training, `True` during generation
1096
+ """
1097
+ outputs = self.electra(
1098
+ input_ids=input_ids,
1099
+ attention_mask=attention_mask,
1100
+ token_type_ids=token_type_ids,
1101
+ position_ids=position_ids,
1102
+ head_mask=head_mask,
1103
+ encoder_hidden_states=encoder_hidden_states,
1104
+ encoder_attention_mask=encoder_attention_mask,
1105
+ past_key_values=past_key_values,
1106
+ use_cache=use_cache,
1107
+ inputs_embeds=inputs_embeds,
1108
+ output_attentions=output_attentions,
1109
+ output_hidden_states=output_hidden_states,
1110
+ return_dict=return_dict,
1111
+ training=training,
1112
+ )
1113
+
1114
+ return outputs
1115
+
1116
+ def build(self, input_shape=None):
1117
+ if self.built:
1118
+ return
1119
+ self.built = True
1120
+ if getattr(self, "electra", None) is not None:
1121
+ with tf.name_scope(self.electra.name):
1122
+ self.electra.build(None)
1123
+
1124
+
1125
+ @add_start_docstrings(
1126
+ """
1127
+ Electra model with a binary classification head on top as used during pretraining for identifying generated tokens.
1128
+
1129
+ Even though both the discriminator and generator may be loaded into this model, the discriminator is the only model
1130
+ of the two to have the correct classification head to be used for this model.
1131
+ """,
1132
+ ELECTRA_START_DOCSTRING,
1133
+ )
1134
+ class TFElectraForPreTraining(TFElectraPreTrainedModel):
1135
+ def __init__(self, config, **kwargs):
1136
+ super().__init__(config, **kwargs)
1137
+
1138
+ self.electra = TFElectraMainLayer(config, name="electra")
1139
+ self.discriminator_predictions = TFElectraDiscriminatorPredictions(config, name="discriminator_predictions")
1140
+
1141
+ @unpack_inputs
1142
+ @add_start_docstrings_to_model_forward(ELECTRA_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
1143
+ @replace_return_docstrings(output_type=TFElectraForPreTrainingOutput, config_class=_CONFIG_FOR_DOC)
1144
+ def call(
1145
+ self,
1146
+ input_ids: TFModelInputType | None = None,
1147
+ attention_mask: np.ndarray | tf.Tensor | None = None,
1148
+ token_type_ids: np.ndarray | tf.Tensor | None = None,
1149
+ position_ids: np.ndarray | tf.Tensor | None = None,
1150
+ head_mask: np.ndarray | tf.Tensor | None = None,
1151
+ inputs_embeds: np.ndarray | tf.Tensor | None = None,
1152
+ output_attentions: Optional[bool] = None,
1153
+ output_hidden_states: Optional[bool] = None,
1154
+ return_dict: Optional[bool] = None,
1155
+ training: Optional[bool] = False,
1156
+ ) -> Union[TFElectraForPreTrainingOutput, Tuple[tf.Tensor]]:
1157
+ r"""
1158
+ Returns:
1159
+
1160
+ Examples:
1161
+
1162
+ ```python
1163
+ >>> import tensorflow as tf
1164
+ >>> from transformers import AutoTokenizer, TFElectraForPreTraining
1165
+
1166
+ >>> tokenizer = AutoTokenizer.from_pretrained("google/electra-small-discriminator")
1167
+ >>> model = TFElectraForPreTraining.from_pretrained("google/electra-small-discriminator")
1168
+ >>> input_ids = tf.constant(tokenizer.encode("Hello, my dog is cute"))[None, :] # Batch size 1
1169
+ >>> outputs = model(input_ids)
1170
+ >>> scores = outputs[0]
1171
+ ```"""
1172
+ discriminator_hidden_states = self.electra(
1173
+ input_ids=input_ids,
1174
+ attention_mask=attention_mask,
1175
+ token_type_ids=token_type_ids,
1176
+ position_ids=position_ids,
1177
+ head_mask=head_mask,
1178
+ inputs_embeds=inputs_embeds,
1179
+ output_attentions=output_attentions,
1180
+ output_hidden_states=output_hidden_states,
1181
+ return_dict=return_dict,
1182
+ training=training,
1183
+ )
1184
+ discriminator_sequence_output = discriminator_hidden_states[0]
1185
+ logits = self.discriminator_predictions(discriminator_sequence_output)
1186
+
1187
+ if not return_dict:
1188
+ return (logits,) + discriminator_hidden_states[1:]
1189
+
1190
+ return TFElectraForPreTrainingOutput(
1191
+ logits=logits,
1192
+ hidden_states=discriminator_hidden_states.hidden_states,
1193
+ attentions=discriminator_hidden_states.attentions,
1194
+ )
1195
+
1196
+ def build(self, input_shape=None):
1197
+ if self.built:
1198
+ return
1199
+ self.built = True
1200
+ if getattr(self, "electra", None) is not None:
1201
+ with tf.name_scope(self.electra.name):
1202
+ self.electra.build(None)
1203
+ if getattr(self, "discriminator_predictions", None) is not None:
1204
+ with tf.name_scope(self.discriminator_predictions.name):
1205
+ self.discriminator_predictions.build(None)
1206
+
1207
+
1208
+ class TFElectraMaskedLMHead(tf.keras.layers.Layer):
1209
+ def __init__(self, config, input_embeddings, **kwargs):
1210
+ super().__init__(**kwargs)
1211
+
1212
+ self.config = config
1213
+ self.embedding_size = config.embedding_size
1214
+ self.input_embeddings = input_embeddings
1215
+
1216
+ def build(self, input_shape):
1217
+ self.bias = self.add_weight(shape=(self.config.vocab_size,), initializer="zeros", trainable=True, name="bias")
1218
+
1219
+ super().build(input_shape)
1220
+
1221
+ def get_output_embeddings(self):
1222
+ return self.input_embeddings
1223
+
1224
+ def set_output_embeddings(self, value):
1225
+ self.input_embeddings.weight = value
1226
+ self.input_embeddings.vocab_size = shape_list(value)[0]
1227
+
1228
+ def get_bias(self):
1229
+ return {"bias": self.bias}
1230
+
1231
+ def set_bias(self, value):
1232
+ self.bias = value["bias"]
1233
+ self.config.vocab_size = shape_list(value["bias"])[0]
1234
+
1235
+ def call(self, hidden_states):
1236
+ seq_length = shape_list(tensor=hidden_states)[1]
1237
+ hidden_states = tf.reshape(tensor=hidden_states, shape=[-1, self.embedding_size])
1238
+ hidden_states = tf.matmul(a=hidden_states, b=self.input_embeddings.weight, transpose_b=True)
1239
+ hidden_states = tf.reshape(tensor=hidden_states, shape=[-1, seq_length, self.config.vocab_size])
1240
+ hidden_states = tf.nn.bias_add(value=hidden_states, bias=self.bias)
1241
+
1242
+ return hidden_states
1243
+
1244
+
1245
+ @add_start_docstrings(
1246
+ """
1247
+ Electra model with a language modeling head on top.
1248
+
1249
+ Even though both the discriminator and generator may be loaded into this model, the generator is the only model of
1250
+ the two to have been trained for the masked language modeling task.
1251
+ """,
1252
+ ELECTRA_START_DOCSTRING,
1253
+ )
1254
+ class TFElectraForMaskedLM(TFElectraPreTrainedModel, TFMaskedLanguageModelingLoss):
1255
+ def __init__(self, config, **kwargs):
1256
+ super().__init__(config, **kwargs)
1257
+
1258
+ self.config = config
1259
+ self.electra = TFElectraMainLayer(config, name="electra")
1260
+ self.generator_predictions = TFElectraGeneratorPredictions(config, name="generator_predictions")
1261
+
1262
+ if isinstance(config.hidden_act, str):
1263
+ self.activation = get_tf_activation(config.hidden_act)
1264
+ else:
1265
+ self.activation = config.hidden_act
1266
+
1267
+ self.generator_lm_head = TFElectraMaskedLMHead(config, self.electra.embeddings, name="generator_lm_head")
1268
+
1269
+ def get_lm_head(self):
1270
+ return self.generator_lm_head
1271
+
1272
+ def get_prefix_bias_name(self):
1273
+ warnings.warn("The method get_prefix_bias_name is deprecated. Please use `get_bias` instead.", FutureWarning)
1274
+ return self.name + "/" + self.generator_lm_head.name
1275
+
1276
+ @unpack_inputs
1277
+ @add_start_docstrings_to_model_forward(ELECTRA_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
1278
+ @add_code_sample_docstrings(
1279
+ checkpoint="google/electra-small-generator",
1280
+ output_type=TFMaskedLMOutput,
1281
+ config_class=_CONFIG_FOR_DOC,
1282
+ mask="[MASK]",
1283
+ expected_output="'paris'",
1284
+ expected_loss=1.22,
1285
+ )
1286
+ def call(
1287
+ self,
1288
+ input_ids: TFModelInputType | None = None,
1289
+ attention_mask: np.ndarray | tf.Tensor | None = None,
1290
+ token_type_ids: np.ndarray | tf.Tensor | None = None,
1291
+ position_ids: np.ndarray | tf.Tensor | None = None,
1292
+ head_mask: np.ndarray | tf.Tensor | None = None,
1293
+ inputs_embeds: np.ndarray | tf.Tensor | None = None,
1294
+ output_attentions: Optional[bool] = None,
1295
+ output_hidden_states: Optional[bool] = None,
1296
+ return_dict: Optional[bool] = None,
1297
+ labels: np.ndarray | tf.Tensor | None = None,
1298
+ training: Optional[bool] = False,
1299
+ ) -> Union[TFMaskedLMOutput, Tuple[tf.Tensor]]:
1300
+ r"""
1301
+ labels (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
1302
+ Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
1303
+ config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the
1304
+ loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
1305
+ """
1306
+ generator_hidden_states = self.electra(
1307
+ input_ids=input_ids,
1308
+ attention_mask=attention_mask,
1309
+ token_type_ids=token_type_ids,
1310
+ position_ids=position_ids,
1311
+ head_mask=head_mask,
1312
+ inputs_embeds=inputs_embeds,
1313
+ output_attentions=output_attentions,
1314
+ output_hidden_states=output_hidden_states,
1315
+ return_dict=return_dict,
1316
+ training=training,
1317
+ )
1318
+ generator_sequence_output = generator_hidden_states[0]
1319
+ prediction_scores = self.generator_predictions(generator_sequence_output, training=training)
1320
+ prediction_scores = self.generator_lm_head(prediction_scores, training=training)
1321
+ loss = None if labels is None else self.hf_compute_loss(labels, prediction_scores)
1322
+
1323
+ if not return_dict:
1324
+ output = (prediction_scores,) + generator_hidden_states[1:]
1325
+
1326
+ return ((loss,) + output) if loss is not None else output
1327
+
1328
+ return TFMaskedLMOutput(
1329
+ loss=loss,
1330
+ logits=prediction_scores,
1331
+ hidden_states=generator_hidden_states.hidden_states,
1332
+ attentions=generator_hidden_states.attentions,
1333
+ )
1334
+
1335
+ def build(self, input_shape=None):
1336
+ if self.built:
1337
+ return
1338
+ self.built = True
1339
+ if getattr(self, "electra", None) is not None:
1340
+ with tf.name_scope(self.electra.name):
1341
+ self.electra.build(None)
1342
+ if getattr(self, "generator_predictions", None) is not None:
1343
+ with tf.name_scope(self.generator_predictions.name):
1344
+ self.generator_predictions.build(None)
1345
+ if getattr(self, "generator_lm_head", None) is not None:
1346
+ with tf.name_scope(self.generator_lm_head.name):
1347
+ self.generator_lm_head.build(None)
1348
+
1349
+
1350
+ class TFElectraClassificationHead(tf.keras.layers.Layer):
1351
+ """Head for sentence-level classification tasks."""
1352
+
1353
+ def __init__(self, config, **kwargs):
1354
+ super().__init__(**kwargs)
1355
+
1356
+ self.dense = tf.keras.layers.Dense(
1357
+ config.hidden_size, kernel_initializer=get_initializer(config.initializer_range), name="dense"
1358
+ )
1359
+ classifier_dropout = (
1360
+ config.classifhidden_dropout_probier_dropout
1361
+ if config.classifier_dropout is not None
1362
+ else config.hidden_dropout_prob
1363
+ )
1364
+ self.dropout = tf.keras.layers.Dropout(classifier_dropout)
1365
+ self.out_proj = tf.keras.layers.Dense(
1366
+ config.num_labels, kernel_initializer=get_initializer(config.initializer_range), name="out_proj"
1367
+ )
1368
+ self.config = config
1369
+
1370
+ def call(self, inputs, **kwargs):
1371
+ x = inputs[:, 0, :] # take <s> token (equiv. to [CLS])
1372
+ x = self.dropout(x)
1373
+ x = self.dense(x)
1374
+ x = get_tf_activation("gelu")(x) # although BERT uses tanh here, it seems Electra authors used gelu here
1375
+ x = self.dropout(x)
1376
+ x = self.out_proj(x)
1377
+
1378
+ return x
1379
+
1380
+ def build(self, input_shape=None):
1381
+ if self.built:
1382
+ return
1383
+ self.built = True
1384
+ if getattr(self, "dense", None) is not None:
1385
+ with tf.name_scope(self.dense.name):
1386
+ self.dense.build([None, None, self.config.hidden_size])
1387
+ if getattr(self, "out_proj", None) is not None:
1388
+ with tf.name_scope(self.out_proj.name):
1389
+ self.out_proj.build([None, None, self.config.hidden_size])
1390
+
1391
+
1392
+ @add_start_docstrings(
1393
+ """
1394
+ ELECTRA Model transformer with a sequence classification/regression head on top (a linear layer on top of the
1395
+ pooled output) e.g. for GLUE tasks.
1396
+ """,
1397
+ ELECTRA_START_DOCSTRING,
1398
+ )
1399
+ class TFElectraForSequenceClassification(TFElectraPreTrainedModel, TFSequenceClassificationLoss):
1400
+ def __init__(self, config, *inputs, **kwargs):
1401
+ super().__init__(config, *inputs, **kwargs)
1402
+ self.num_labels = config.num_labels
1403
+ self.electra = TFElectraMainLayer(config, name="electra")
1404
+ self.classifier = TFElectraClassificationHead(config, name="classifier")
1405
+
1406
+ @unpack_inputs
1407
+ @add_start_docstrings_to_model_forward(ELECTRA_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
1408
+ @add_code_sample_docstrings(
1409
+ checkpoint="bhadresh-savani/electra-base-emotion",
1410
+ output_type=TFSequenceClassifierOutput,
1411
+ config_class=_CONFIG_FOR_DOC,
1412
+ expected_output="'joy'",
1413
+ expected_loss=0.06,
1414
+ )
1415
+ def call(
1416
+ self,
1417
+ input_ids: TFModelInputType | None = None,
1418
+ attention_mask: np.ndarray | tf.Tensor | None = None,
1419
+ token_type_ids: np.ndarray | tf.Tensor | None = None,
1420
+ position_ids: np.ndarray | tf.Tensor | None = None,
1421
+ head_mask: np.ndarray | tf.Tensor | None = None,
1422
+ inputs_embeds: np.ndarray | tf.Tensor | None = None,
1423
+ output_attentions: Optional[bool] = None,
1424
+ output_hidden_states: Optional[bool] = None,
1425
+ return_dict: Optional[bool] = None,
1426
+ labels: np.ndarray | tf.Tensor | None = None,
1427
+ training: Optional[bool] = False,
1428
+ ) -> Union[TFSequenceClassifierOutput, Tuple[tf.Tensor]]:
1429
+ r"""
1430
+ labels (`tf.Tensor` of shape `(batch_size,)`, *optional*):
1431
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1432
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1433
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1434
+ """
1435
+ outputs = self.electra(
1436
+ input_ids=input_ids,
1437
+ attention_mask=attention_mask,
1438
+ token_type_ids=token_type_ids,
1439
+ position_ids=position_ids,
1440
+ head_mask=head_mask,
1441
+ inputs_embeds=inputs_embeds,
1442
+ output_attentions=output_attentions,
1443
+ output_hidden_states=output_hidden_states,
1444
+ return_dict=return_dict,
1445
+ training=training,
1446
+ )
1447
+ logits = self.classifier(outputs[0])
1448
+ loss = None if labels is None else self.hf_compute_loss(labels, logits)
1449
+
1450
+ if not return_dict:
1451
+ output = (logits,) + outputs[1:]
1452
+
1453
+ return ((loss,) + output) if loss is not None else output
1454
+
1455
+ return TFSequenceClassifierOutput(
1456
+ loss=loss,
1457
+ logits=logits,
1458
+ hidden_states=outputs.hidden_states,
1459
+ attentions=outputs.attentions,
1460
+ )
1461
+
1462
+ def build(self, input_shape=None):
1463
+ if self.built:
1464
+ return
1465
+ self.built = True
1466
+ if getattr(self, "electra", None) is not None:
1467
+ with tf.name_scope(self.electra.name):
1468
+ self.electra.build(None)
1469
+ if getattr(self, "classifier", None) is not None:
1470
+ with tf.name_scope(self.classifier.name):
1471
+ self.classifier.build(None)
1472
+
1473
+
1474
+ @add_start_docstrings(
1475
+ """
1476
+ ELECTRA Model with a multiple choice classification head on top (a linear layer on top of the pooled output and a
1477
+ softmax) e.g. for RocStories/SWAG tasks.
1478
+ """,
1479
+ ELECTRA_START_DOCSTRING,
1480
+ )
1481
+ class TFElectraForMultipleChoice(TFElectraPreTrainedModel, TFMultipleChoiceLoss):
1482
+ def __init__(self, config, *inputs, **kwargs):
1483
+ super().__init__(config, *inputs, **kwargs)
1484
+
1485
+ self.electra = TFElectraMainLayer(config, name="electra")
1486
+ self.sequence_summary = TFSequenceSummary(
1487
+ config, initializer_range=config.initializer_range, name="sequence_summary"
1488
+ )
1489
+ self.classifier = tf.keras.layers.Dense(
1490
+ 1, kernel_initializer=get_initializer(config.initializer_range), name="classifier"
1491
+ )
1492
+ self.config = config
1493
+
1494
+ @unpack_inputs
1495
+ @add_start_docstrings_to_model_forward(ELECTRA_INPUTS_DOCSTRING.format("batch_size, num_choices, sequence_length"))
1496
+ @add_code_sample_docstrings(
1497
+ checkpoint=_CHECKPOINT_FOR_DOC,
1498
+ output_type=TFMultipleChoiceModelOutput,
1499
+ config_class=_CONFIG_FOR_DOC,
1500
+ )
1501
+ def call(
1502
+ self,
1503
+ input_ids: TFModelInputType | None = None,
1504
+ attention_mask: np.ndarray | tf.Tensor | None = None,
1505
+ token_type_ids: np.ndarray | tf.Tensor | None = None,
1506
+ position_ids: np.ndarray | tf.Tensor | None = None,
1507
+ head_mask: np.ndarray | tf.Tensor | None = None,
1508
+ inputs_embeds: np.ndarray | tf.Tensor | None = None,
1509
+ output_attentions: Optional[bool] = None,
1510
+ output_hidden_states: Optional[bool] = None,
1511
+ return_dict: Optional[bool] = None,
1512
+ labels: np.ndarray | tf.Tensor | None = None,
1513
+ training: Optional[bool] = False,
1514
+ ) -> Union[TFMultipleChoiceModelOutput, Tuple[tf.Tensor]]:
1515
+ r"""
1516
+ labels (`tf.Tensor` of shape `(batch_size,)`, *optional*):
1517
+ Labels for computing the multiple choice classification loss. Indices should be in `[0, ..., num_choices]`
1518
+ where `num_choices` is the size of the second dimension of the input tensors. (See `input_ids` above)
1519
+ """
1520
+
1521
+ if input_ids is not None:
1522
+ num_choices = shape_list(input_ids)[1]
1523
+ seq_length = shape_list(input_ids)[2]
1524
+ else:
1525
+ num_choices = shape_list(inputs_embeds)[1]
1526
+ seq_length = shape_list(inputs_embeds)[2]
1527
+
1528
+ flat_input_ids = tf.reshape(input_ids, (-1, seq_length)) if input_ids is not None else None
1529
+ flat_attention_mask = tf.reshape(attention_mask, (-1, seq_length)) if attention_mask is not None else None
1530
+ flat_token_type_ids = tf.reshape(token_type_ids, (-1, seq_length)) if token_type_ids is not None else None
1531
+ flat_position_ids = tf.reshape(position_ids, (-1, seq_length)) if position_ids is not None else None
1532
+ flat_inputs_embeds = (
1533
+ tf.reshape(inputs_embeds, (-1, seq_length, shape_list(inputs_embeds)[3]))
1534
+ if inputs_embeds is not None
1535
+ else None
1536
+ )
1537
+ outputs = self.electra(
1538
+ input_ids=flat_input_ids,
1539
+ attention_mask=flat_attention_mask,
1540
+ token_type_ids=flat_token_type_ids,
1541
+ position_ids=flat_position_ids,
1542
+ head_mask=head_mask,
1543
+ inputs_embeds=flat_inputs_embeds,
1544
+ output_attentions=output_attentions,
1545
+ output_hidden_states=output_hidden_states,
1546
+ return_dict=return_dict,
1547
+ training=training,
1548
+ )
1549
+ logits = self.sequence_summary(outputs[0])
1550
+ logits = self.classifier(logits)
1551
+ reshaped_logits = tf.reshape(logits, (-1, num_choices))
1552
+ loss = None if labels is None else self.hf_compute_loss(labels, reshaped_logits)
1553
+
1554
+ if not return_dict:
1555
+ output = (reshaped_logits,) + outputs[1:]
1556
+
1557
+ return ((loss,) + output) if loss is not None else output
1558
+
1559
+ return TFMultipleChoiceModelOutput(
1560
+ loss=loss,
1561
+ logits=reshaped_logits,
1562
+ hidden_states=outputs.hidden_states,
1563
+ attentions=outputs.attentions,
1564
+ )
1565
+
1566
+ def build(self, input_shape=None):
1567
+ if self.built:
1568
+ return
1569
+ self.built = True
1570
+ if getattr(self, "electra", None) is not None:
1571
+ with tf.name_scope(self.electra.name):
1572
+ self.electra.build(None)
1573
+ if getattr(self, "sequence_summary", None) is not None:
1574
+ with tf.name_scope(self.sequence_summary.name):
1575
+ self.sequence_summary.build(None)
1576
+ if getattr(self, "classifier", None) is not None:
1577
+ with tf.name_scope(self.classifier.name):
1578
+ self.classifier.build([None, None, self.config.hidden_size])
1579
+
1580
+
1581
+ @add_start_docstrings(
1582
+ """
1583
+ Electra model with a token classification head on top.
1584
+
1585
+ Both the discriminator and generator may be loaded into this model.
1586
+ """,
1587
+ ELECTRA_START_DOCSTRING,
1588
+ )
1589
+ class TFElectraForTokenClassification(TFElectraPreTrainedModel, TFTokenClassificationLoss):
1590
+ def __init__(self, config, **kwargs):
1591
+ super().__init__(config, **kwargs)
1592
+
1593
+ self.electra = TFElectraMainLayer(config, name="electra")
1594
+ classifier_dropout = (
1595
+ config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob
1596
+ )
1597
+ self.dropout = tf.keras.layers.Dropout(classifier_dropout)
1598
+ self.classifier = tf.keras.layers.Dense(
1599
+ config.num_labels, kernel_initializer=get_initializer(config.initializer_range), name="classifier"
1600
+ )
1601
+ self.config = config
1602
+
1603
+ @unpack_inputs
1604
+ @add_start_docstrings_to_model_forward(ELECTRA_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
1605
+ @add_code_sample_docstrings(
1606
+ checkpoint="bhadresh-savani/electra-base-discriminator-finetuned-conll03-english",
1607
+ output_type=TFTokenClassifierOutput,
1608
+ config_class=_CONFIG_FOR_DOC,
1609
+ expected_output="['B-LOC', 'B-ORG', 'O', 'O', 'O', 'O', 'O', 'B-LOC', 'O', 'B-LOC', 'I-LOC']",
1610
+ expected_loss=0.11,
1611
+ )
1612
+ def call(
1613
+ self,
1614
+ input_ids: TFModelInputType | None = None,
1615
+ attention_mask: np.ndarray | tf.Tensor | None = None,
1616
+ token_type_ids: np.ndarray | tf.Tensor | None = None,
1617
+ position_ids: np.ndarray | tf.Tensor | None = None,
1618
+ head_mask: np.ndarray | tf.Tensor | None = None,
1619
+ inputs_embeds: np.ndarray | tf.Tensor | None = None,
1620
+ output_attentions: Optional[bool] = None,
1621
+ output_hidden_states: Optional[bool] = None,
1622
+ return_dict: Optional[bool] = None,
1623
+ labels: np.ndarray | tf.Tensor | None = None,
1624
+ training: Optional[bool] = False,
1625
+ ) -> Union[TFTokenClassifierOutput, Tuple[tf.Tensor]]:
1626
+ r"""
1627
+ labels (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
1628
+ Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`.
1629
+ """
1630
+ discriminator_hidden_states = self.electra(
1631
+ input_ids=input_ids,
1632
+ attention_mask=attention_mask,
1633
+ token_type_ids=token_type_ids,
1634
+ position_ids=position_ids,
1635
+ head_mask=head_mask,
1636
+ inputs_embeds=inputs_embeds,
1637
+ output_attentions=output_attentions,
1638
+ output_hidden_states=output_hidden_states,
1639
+ return_dict=return_dict,
1640
+ training=training,
1641
+ )
1642
+ discriminator_sequence_output = discriminator_hidden_states[0]
1643
+ discriminator_sequence_output = self.dropout(discriminator_sequence_output)
1644
+ logits = self.classifier(discriminator_sequence_output)
1645
+ loss = None if labels is None else self.hf_compute_loss(labels, logits)
1646
+
1647
+ if not return_dict:
1648
+ output = (logits,) + discriminator_hidden_states[1:]
1649
+
1650
+ return ((loss,) + output) if loss is not None else output
1651
+
1652
+ return TFTokenClassifierOutput(
1653
+ loss=loss,
1654
+ logits=logits,
1655
+ hidden_states=discriminator_hidden_states.hidden_states,
1656
+ attentions=discriminator_hidden_states.attentions,
1657
+ )
1658
+
1659
+ def build(self, input_shape=None):
1660
+ if self.built:
1661
+ return
1662
+ self.built = True
1663
+ if getattr(self, "electra", None) is not None:
1664
+ with tf.name_scope(self.electra.name):
1665
+ self.electra.build(None)
1666
+ if getattr(self, "classifier", None) is not None:
1667
+ with tf.name_scope(self.classifier.name):
1668
+ self.classifier.build([None, None, self.config.hidden_size])
1669
+
1670
+
1671
+ @add_start_docstrings(
1672
+ """
1673
+ Electra Model with a span classification head on top for extractive question-answering tasks like SQuAD (a linear
1674
+ layers on top of the hidden-states output to compute `span start logits` and `span end logits`).
1675
+ """,
1676
+ ELECTRA_START_DOCSTRING,
1677
+ )
1678
+ class TFElectraForQuestionAnswering(TFElectraPreTrainedModel, TFQuestionAnsweringLoss):
1679
+ def __init__(self, config, *inputs, **kwargs):
1680
+ super().__init__(config, *inputs, **kwargs)
1681
+
1682
+ self.num_labels = config.num_labels
1683
+ self.electra = TFElectraMainLayer(config, name="electra")
1684
+ self.qa_outputs = tf.keras.layers.Dense(
1685
+ config.num_labels, kernel_initializer=get_initializer(config.initializer_range), name="qa_outputs"
1686
+ )
1687
+ self.config = config
1688
+
1689
+ @unpack_inputs
1690
+ @add_start_docstrings_to_model_forward(ELECTRA_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
1691
+ @add_code_sample_docstrings(
1692
+ checkpoint="bhadresh-savani/electra-base-squad2",
1693
+ output_type=TFQuestionAnsweringModelOutput,
1694
+ config_class=_CONFIG_FOR_DOC,
1695
+ qa_target_start_index=11,
1696
+ qa_target_end_index=12,
1697
+ expected_output="'a nice puppet'",
1698
+ expected_loss=2.64,
1699
+ )
1700
+ def call(
1701
+ self,
1702
+ input_ids: TFModelInputType | None = None,
1703
+ attention_mask: np.ndarray | tf.Tensor | None = None,
1704
+ token_type_ids: np.ndarray | tf.Tensor | None = None,
1705
+ position_ids: np.ndarray | tf.Tensor | None = None,
1706
+ head_mask: np.ndarray | tf.Tensor | None = None,
1707
+ inputs_embeds: np.ndarray | tf.Tensor | None = None,
1708
+ output_attentions: Optional[bool] = None,
1709
+ output_hidden_states: Optional[bool] = None,
1710
+ return_dict: Optional[bool] = None,
1711
+ start_positions: np.ndarray | tf.Tensor | None = None,
1712
+ end_positions: np.ndarray | tf.Tensor | None = None,
1713
+ training: Optional[bool] = False,
1714
+ ) -> Union[TFQuestionAnsweringModelOutput, Tuple[tf.Tensor]]:
1715
+ r"""
1716
+ start_positions (`tf.Tensor` of shape `(batch_size,)`, *optional*):
1717
+ Labels for position (index) of the start of the labelled span for computing the token classification loss.
1718
+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
1719
+ are not taken into account for computing the loss.
1720
+ end_positions (`tf.Tensor` of shape `(batch_size,)`, *optional*):
1721
+ Labels for position (index) of the end of the labelled span for computing the token classification loss.
1722
+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
1723
+ are not taken into account for computing the loss.
1724
+ """
1725
+ discriminator_hidden_states = self.electra(
1726
+ input_ids=input_ids,
1727
+ attention_mask=attention_mask,
1728
+ token_type_ids=token_type_ids,
1729
+ position_ids=position_ids,
1730
+ head_mask=head_mask,
1731
+ inputs_embeds=inputs_embeds,
1732
+ output_attentions=output_attentions,
1733
+ output_hidden_states=output_hidden_states,
1734
+ return_dict=return_dict,
1735
+ training=training,
1736
+ )
1737
+ discriminator_sequence_output = discriminator_hidden_states[0]
1738
+ logits = self.qa_outputs(discriminator_sequence_output)
1739
+ start_logits, end_logits = tf.split(logits, 2, axis=-1)
1740
+ start_logits = tf.squeeze(start_logits, axis=-1)
1741
+ end_logits = tf.squeeze(end_logits, axis=-1)
1742
+ loss = None
1743
+
1744
+ if start_positions is not None and end_positions is not None:
1745
+ labels = {"start_position": start_positions}
1746
+ labels["end_position"] = end_positions
1747
+ loss = self.hf_compute_loss(labels, (start_logits, end_logits))
1748
+
1749
+ if not return_dict:
1750
+ output = (
1751
+ start_logits,
1752
+ end_logits,
1753
+ ) + discriminator_hidden_states[1:]
1754
+
1755
+ return ((loss,) + output) if loss is not None else output
1756
+
1757
+ return TFQuestionAnsweringModelOutput(
1758
+ loss=loss,
1759
+ start_logits=start_logits,
1760
+ end_logits=end_logits,
1761
+ hidden_states=discriminator_hidden_states.hidden_states,
1762
+ attentions=discriminator_hidden_states.attentions,
1763
+ )
1764
+
1765
+ def build(self, input_shape=None):
1766
+ if self.built:
1767
+ return
1768
+ self.built = True
1769
+ if getattr(self, "electra", None) is not None:
1770
+ with tf.name_scope(self.electra.name):
1771
+ self.electra.build(None)
1772
+ if getattr(self, "qa_outputs", None) is not None:
1773
+ with tf.name_scope(self.qa_outputs.name):
1774
+ self.qa_outputs.build([None, None, self.config.hidden_size])
pllava/lib/python3.10/site-packages/transformers/models/electra/tokenization_electra.py ADDED
@@ -0,0 +1,546 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2020 The Google AI Team, Stanford University 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
+
16
+ import collections
17
+ import os
18
+ import unicodedata
19
+ from typing import List, Optional, Tuple
20
+
21
+ from ...tokenization_utils import PreTrainedTokenizer, _is_control, _is_punctuation, _is_whitespace
22
+ from ...utils import logging
23
+
24
+
25
+ logger = logging.get_logger(__name__)
26
+
27
+ VOCAB_FILES_NAMES = {"vocab_file": "vocab.txt"}
28
+
29
+ PRETRAINED_VOCAB_FILES_MAP = {
30
+ "vocab_file": {
31
+ "google/electra-small-generator": (
32
+ "https://huggingface.co/google/electra-small-generator/resolve/main/vocab.txt"
33
+ ),
34
+ "google/electra-base-generator": "https://huggingface.co/google/electra-base-generator/resolve/main/vocab.txt",
35
+ "google/electra-large-generator": (
36
+ "https://huggingface.co/google/electra-large-generator/resolve/main/vocab.txt"
37
+ ),
38
+ "google/electra-small-discriminator": (
39
+ "https://huggingface.co/google/electra-small-discriminator/resolve/main/vocab.txt"
40
+ ),
41
+ "google/electra-base-discriminator": (
42
+ "https://huggingface.co/google/electra-base-discriminator/resolve/main/vocab.txt"
43
+ ),
44
+ "google/electra-large-discriminator": (
45
+ "https://huggingface.co/google/electra-large-discriminator/resolve/main/vocab.txt"
46
+ ),
47
+ }
48
+ }
49
+
50
+ PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES = {
51
+ "google/electra-small-generator": 512,
52
+ "google/electra-base-generator": 512,
53
+ "google/electra-large-generator": 512,
54
+ "google/electra-small-discriminator": 512,
55
+ "google/electra-base-discriminator": 512,
56
+ "google/electra-large-discriminator": 512,
57
+ }
58
+
59
+
60
+ PRETRAINED_INIT_CONFIGURATION = {
61
+ "google/electra-small-generator": {"do_lower_case": True},
62
+ "google/electra-base-generator": {"do_lower_case": True},
63
+ "google/electra-large-generator": {"do_lower_case": True},
64
+ "google/electra-small-discriminator": {"do_lower_case": True},
65
+ "google/electra-base-discriminator": {"do_lower_case": True},
66
+ "google/electra-large-discriminator": {"do_lower_case": True},
67
+ }
68
+
69
+
70
+ # Copied from transformers.models.bert.tokenization_bert.load_vocab
71
+ def load_vocab(vocab_file):
72
+ """Loads a vocabulary file into a dictionary."""
73
+ vocab = collections.OrderedDict()
74
+ with open(vocab_file, "r", encoding="utf-8") as reader:
75
+ tokens = reader.readlines()
76
+ for index, token in enumerate(tokens):
77
+ token = token.rstrip("\n")
78
+ vocab[token] = index
79
+ return vocab
80
+
81
+
82
+ # Copied from transformers.models.bert.tokenization_bert.whitespace_tokenize
83
+ def whitespace_tokenize(text):
84
+ """Runs basic whitespace cleaning and splitting on a piece of text."""
85
+ text = text.strip()
86
+ if not text:
87
+ return []
88
+ tokens = text.split()
89
+ return tokens
90
+
91
+
92
+ # Copied from transformers.models.bert.tokenization_bert.BertTokenizer with Bert->Electra,BERT->Electra
93
+ class ElectraTokenizer(PreTrainedTokenizer):
94
+ r"""
95
+ Construct a Electra tokenizer. Based on WordPiece.
96
+
97
+ This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to
98
+ this superclass for more information regarding those methods.
99
+
100
+ Args:
101
+ vocab_file (`str`):
102
+ File containing the vocabulary.
103
+ do_lower_case (`bool`, *optional*, defaults to `True`):
104
+ Whether or not to lowercase the input when tokenizing.
105
+ do_basic_tokenize (`bool`, *optional*, defaults to `True`):
106
+ Whether or not to do basic tokenization before WordPiece.
107
+ never_split (`Iterable`, *optional*):
108
+ Collection of tokens which will never be split during tokenization. Only has an effect when
109
+ `do_basic_tokenize=True`
110
+ unk_token (`str`, *optional*, defaults to `"[UNK]"`):
111
+ The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
112
+ token instead.
113
+ sep_token (`str`, *optional*, defaults to `"[SEP]"`):
114
+ The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
115
+ sequence classification or for a text and a question for question answering. It is also used as the last
116
+ token of a sequence built with special tokens.
117
+ pad_token (`str`, *optional*, defaults to `"[PAD]"`):
118
+ The token used for padding, for example when batching sequences of different lengths.
119
+ cls_token (`str`, *optional*, defaults to `"[CLS]"`):
120
+ The classifier token which is used when doing sequence classification (classification of the whole sequence
121
+ instead of per-token classification). It is the first token of the sequence when built with special tokens.
122
+ mask_token (`str`, *optional*, defaults to `"[MASK]"`):
123
+ The token used for masking values. This is the token used when training this model with masked language
124
+ modeling. This is the token which the model will try to predict.
125
+ tokenize_chinese_chars (`bool`, *optional*, defaults to `True`):
126
+ Whether or not to tokenize Chinese characters.
127
+
128
+ This should likely be deactivated for Japanese (see this
129
+ [issue](https://github.com/huggingface/transformers/issues/328)).
130
+ strip_accents (`bool`, *optional*):
131
+ Whether or not to strip all accents. If this option is not specified, then it will be determined by the
132
+ value for `lowercase` (as in the original Electra).
133
+ """
134
+
135
+ vocab_files_names = VOCAB_FILES_NAMES
136
+ pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP
137
+ pretrained_init_configuration = PRETRAINED_INIT_CONFIGURATION
138
+ max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
139
+
140
+ def __init__(
141
+ self,
142
+ vocab_file,
143
+ do_lower_case=True,
144
+ do_basic_tokenize=True,
145
+ never_split=None,
146
+ unk_token="[UNK]",
147
+ sep_token="[SEP]",
148
+ pad_token="[PAD]",
149
+ cls_token="[CLS]",
150
+ mask_token="[MASK]",
151
+ tokenize_chinese_chars=True,
152
+ strip_accents=None,
153
+ **kwargs,
154
+ ):
155
+ if not os.path.isfile(vocab_file):
156
+ raise ValueError(
157
+ f"Can't find a vocabulary file at path '{vocab_file}'. To load the vocabulary from a Google pretrained"
158
+ " model use `tokenizer = ElectraTokenizer.from_pretrained(PRETRAINED_MODEL_NAME)`"
159
+ )
160
+ self.vocab = load_vocab(vocab_file)
161
+ self.ids_to_tokens = collections.OrderedDict([(ids, tok) for tok, ids in self.vocab.items()])
162
+ self.do_basic_tokenize = do_basic_tokenize
163
+ if do_basic_tokenize:
164
+ self.basic_tokenizer = BasicTokenizer(
165
+ do_lower_case=do_lower_case,
166
+ never_split=never_split,
167
+ tokenize_chinese_chars=tokenize_chinese_chars,
168
+ strip_accents=strip_accents,
169
+ )
170
+
171
+ self.wordpiece_tokenizer = WordpieceTokenizer(vocab=self.vocab, unk_token=str(unk_token))
172
+
173
+ super().__init__(
174
+ do_lower_case=do_lower_case,
175
+ do_basic_tokenize=do_basic_tokenize,
176
+ never_split=never_split,
177
+ unk_token=unk_token,
178
+ sep_token=sep_token,
179
+ pad_token=pad_token,
180
+ cls_token=cls_token,
181
+ mask_token=mask_token,
182
+ tokenize_chinese_chars=tokenize_chinese_chars,
183
+ strip_accents=strip_accents,
184
+ **kwargs,
185
+ )
186
+
187
+ @property
188
+ def do_lower_case(self):
189
+ return self.basic_tokenizer.do_lower_case
190
+
191
+ @property
192
+ def vocab_size(self):
193
+ return len(self.vocab)
194
+
195
+ def get_vocab(self):
196
+ return dict(self.vocab, **self.added_tokens_encoder)
197
+
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
+ def _convert_token_to_id(self, token):
214
+ """Converts a token (str) in an id using the vocab."""
215
+ return self.vocab.get(token, self.vocab.get(self.unk_token))
216
+
217
+ def _convert_id_to_token(self, index):
218
+ """Converts an index (integer) in a token (str) using the vocab."""
219
+ return self.ids_to_tokens.get(index, self.unk_token)
220
+
221
+ def convert_tokens_to_string(self, tokens):
222
+ """Converts a sequence of tokens (string) in a single string."""
223
+ out_string = " ".join(tokens).replace(" ##", "").strip()
224
+ return out_string
225
+
226
+ def build_inputs_with_special_tokens(
227
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
228
+ ) -> List[int]:
229
+ """
230
+ Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
231
+ adding special tokens. A Electra sequence has the following format:
232
+
233
+ - single sequence: `[CLS] X [SEP]`
234
+ - pair of sequences: `[CLS] A [SEP] B [SEP]`
235
+
236
+ Args:
237
+ token_ids_0 (`List[int]`):
238
+ List of IDs to which the special tokens will be added.
239
+ token_ids_1 (`List[int]`, *optional*):
240
+ Optional second list of IDs for sequence pairs.
241
+
242
+ Returns:
243
+ `List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
244
+ """
245
+ if token_ids_1 is None:
246
+ return [self.cls_token_id] + token_ids_0 + [self.sep_token_id]
247
+ cls = [self.cls_token_id]
248
+ sep = [self.sep_token_id]
249
+ return cls + token_ids_0 + sep + token_ids_1 + sep
250
+
251
+ def get_special_tokens_mask(
252
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None, already_has_special_tokens: bool = False
253
+ ) -> List[int]:
254
+ """
255
+ Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
256
+ special tokens using the tokenizer `prepare_for_model` method.
257
+
258
+ Args:
259
+ token_ids_0 (`List[int]`):
260
+ List of IDs.
261
+ token_ids_1 (`List[int]`, *optional*):
262
+ Optional second list of IDs for sequence pairs.
263
+ already_has_special_tokens (`bool`, *optional*, defaults to `False`):
264
+ Whether or not the token list is already formatted with special tokens for the model.
265
+
266
+ Returns:
267
+ `List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
268
+ """
269
+
270
+ if already_has_special_tokens:
271
+ return super().get_special_tokens_mask(
272
+ token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
273
+ )
274
+
275
+ if token_ids_1 is not None:
276
+ return [1] + ([0] * len(token_ids_0)) + [1] + ([0] * len(token_ids_1)) + [1]
277
+ return [1] + ([0] * len(token_ids_0)) + [1]
278
+
279
+ def create_token_type_ids_from_sequences(
280
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
281
+ ) -> List[int]:
282
+ """
283
+ Create a mask from the two sequences passed to be used in a sequence-pair classification task. A Electra sequence
284
+ pair mask has the following format:
285
+
286
+ ```
287
+ 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1
288
+ | first sequence | second sequence |
289
+ ```
290
+
291
+ If `token_ids_1` is `None`, this method only returns the first portion of the mask (0s).
292
+
293
+ Args:
294
+ token_ids_0 (`List[int]`):
295
+ List of IDs.
296
+ token_ids_1 (`List[int]`, *optional*):
297
+ Optional second list of IDs for sequence pairs.
298
+
299
+ Returns:
300
+ `List[int]`: List of [token type IDs](../glossary#token-type-ids) according to the given sequence(s).
301
+ """
302
+ sep = [self.sep_token_id]
303
+ cls = [self.cls_token_id]
304
+ if token_ids_1 is None:
305
+ return len(cls + token_ids_0 + sep) * [0]
306
+ return len(cls + token_ids_0 + sep) * [0] + len(token_ids_1 + sep) * [1]
307
+
308
+ def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
309
+ index = 0
310
+ if os.path.isdir(save_directory):
311
+ vocab_file = os.path.join(
312
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
313
+ )
314
+ else:
315
+ vocab_file = (filename_prefix + "-" if filename_prefix else "") + save_directory
316
+ with open(vocab_file, "w", encoding="utf-8") as writer:
317
+ for token, token_index in sorted(self.vocab.items(), key=lambda kv: kv[1]):
318
+ if index != token_index:
319
+ logger.warning(
320
+ f"Saving vocabulary to {vocab_file}: vocabulary indices are not consecutive."
321
+ " Please check that the vocabulary is not corrupted!"
322
+ )
323
+ index = token_index
324
+ writer.write(token + "\n")
325
+ index += 1
326
+ return (vocab_file,)
327
+
328
+
329
+ # Copied from transformers.models.bert.tokenization_bert.BasicTokenizer
330
+ class BasicTokenizer(object):
331
+ """
332
+ Constructs a BasicTokenizer that will run basic tokenization (punctuation splitting, lower casing, etc.).
333
+
334
+ Args:
335
+ do_lower_case (`bool`, *optional*, defaults to `True`):
336
+ Whether or not to lowercase the input when tokenizing.
337
+ never_split (`Iterable`, *optional*):
338
+ Collection of tokens which will never be split during tokenization. Only has an effect when
339
+ `do_basic_tokenize=True`
340
+ tokenize_chinese_chars (`bool`, *optional*, defaults to `True`):
341
+ Whether or not to tokenize Chinese characters.
342
+
343
+ This should likely be deactivated for Japanese (see this
344
+ [issue](https://github.com/huggingface/transformers/issues/328)).
345
+ strip_accents (`bool`, *optional*):
346
+ Whether or not to strip all accents. If this option is not specified, then it will be determined by the
347
+ value for `lowercase` (as in the original BERT).
348
+ do_split_on_punc (`bool`, *optional*, defaults to `True`):
349
+ In some instances we want to skip the basic punctuation splitting so that later tokenization can capture
350
+ the full context of the words, such as contractions.
351
+ """
352
+
353
+ def __init__(
354
+ self,
355
+ do_lower_case=True,
356
+ never_split=None,
357
+ tokenize_chinese_chars=True,
358
+ strip_accents=None,
359
+ do_split_on_punc=True,
360
+ ):
361
+ if never_split is None:
362
+ never_split = []
363
+ self.do_lower_case = do_lower_case
364
+ self.never_split = set(never_split)
365
+ self.tokenize_chinese_chars = tokenize_chinese_chars
366
+ self.strip_accents = strip_accents
367
+ self.do_split_on_punc = do_split_on_punc
368
+
369
+ def tokenize(self, text, never_split=None):
370
+ """
371
+ Basic Tokenization of a piece of text. For sub-word tokenization, see WordPieceTokenizer.
372
+
373
+ Args:
374
+ never_split (`List[str]`, *optional*)
375
+ Kept for backward compatibility purposes. Now implemented directly at the base class level (see
376
+ [`PreTrainedTokenizer.tokenize`]) List of token not to split.
377
+ """
378
+ # union() returns a new set by concatenating the two sets.
379
+ never_split = self.never_split.union(set(never_split)) if never_split else self.never_split
380
+ text = self._clean_text(text)
381
+
382
+ # This was added on November 1st, 2018 for the multilingual and Chinese
383
+ # models. This is also applied to the English models now, but it doesn't
384
+ # matter since the English models were not trained on any Chinese data
385
+ # and generally don't have any Chinese data in them (there are Chinese
386
+ # characters in the vocabulary because Wikipedia does have some Chinese
387
+ # words in the English Wikipedia.).
388
+ if self.tokenize_chinese_chars:
389
+ text = self._tokenize_chinese_chars(text)
390
+ # prevents treating the same character with different unicode codepoints as different characters
391
+ unicode_normalized_text = unicodedata.normalize("NFC", text)
392
+ orig_tokens = whitespace_tokenize(unicode_normalized_text)
393
+ split_tokens = []
394
+ for token in orig_tokens:
395
+ if token not in never_split:
396
+ if self.do_lower_case:
397
+ token = token.lower()
398
+ if self.strip_accents is not False:
399
+ token = self._run_strip_accents(token)
400
+ elif self.strip_accents:
401
+ token = self._run_strip_accents(token)
402
+ split_tokens.extend(self._run_split_on_punc(token, never_split))
403
+
404
+ output_tokens = whitespace_tokenize(" ".join(split_tokens))
405
+ return output_tokens
406
+
407
+ def _run_strip_accents(self, text):
408
+ """Strips accents from a piece of text."""
409
+ text = unicodedata.normalize("NFD", text)
410
+ output = []
411
+ for char in text:
412
+ cat = unicodedata.category(char)
413
+ if cat == "Mn":
414
+ continue
415
+ output.append(char)
416
+ return "".join(output)
417
+
418
+ def _run_split_on_punc(self, text, never_split=None):
419
+ """Splits punctuation on a piece of text."""
420
+ if not self.do_split_on_punc or (never_split is not None and text in never_split):
421
+ return [text]
422
+ chars = list(text)
423
+ i = 0
424
+ start_new_word = True
425
+ output = []
426
+ while i < len(chars):
427
+ char = chars[i]
428
+ if _is_punctuation(char):
429
+ output.append([char])
430
+ start_new_word = True
431
+ else:
432
+ if start_new_word:
433
+ output.append([])
434
+ start_new_word = False
435
+ output[-1].append(char)
436
+ i += 1
437
+
438
+ return ["".join(x) for x in output]
439
+
440
+ def _tokenize_chinese_chars(self, text):
441
+ """Adds whitespace around any CJK character."""
442
+ output = []
443
+ for char in text:
444
+ cp = ord(char)
445
+ if self._is_chinese_char(cp):
446
+ output.append(" ")
447
+ output.append(char)
448
+ output.append(" ")
449
+ else:
450
+ output.append(char)
451
+ return "".join(output)
452
+
453
+ def _is_chinese_char(self, cp):
454
+ """Checks whether CP is the codepoint of a CJK character."""
455
+ # This defines a "chinese character" as anything in the CJK Unicode block:
456
+ # https://en.wikipedia.org/wiki/CJK_Unified_Ideographs_(Unicode_block)
457
+ #
458
+ # Note that the CJK Unicode block is NOT all Japanese and Korean characters,
459
+ # despite its name. The modern Korean Hangul alphabet is a different block,
460
+ # as is Japanese Hiragana and Katakana. Those alphabets are used to write
461
+ # space-separated words, so they are not treated specially and handled
462
+ # like the all of the other languages.
463
+ if (
464
+ (cp >= 0x4E00 and cp <= 0x9FFF)
465
+ or (cp >= 0x3400 and cp <= 0x4DBF) #
466
+ or (cp >= 0x20000 and cp <= 0x2A6DF) #
467
+ or (cp >= 0x2A700 and cp <= 0x2B73F) #
468
+ or (cp >= 0x2B740 and cp <= 0x2B81F) #
469
+ or (cp >= 0x2B820 and cp <= 0x2CEAF) #
470
+ or (cp >= 0xF900 and cp <= 0xFAFF)
471
+ or (cp >= 0x2F800 and cp <= 0x2FA1F) #
472
+ ): #
473
+ return True
474
+
475
+ return False
476
+
477
+ def _clean_text(self, text):
478
+ """Performs invalid character removal and whitespace cleanup on text."""
479
+ output = []
480
+ for char in text:
481
+ cp = ord(char)
482
+ if cp == 0 or cp == 0xFFFD or _is_control(char):
483
+ continue
484
+ if _is_whitespace(char):
485
+ output.append(" ")
486
+ else:
487
+ output.append(char)
488
+ return "".join(output)
489
+
490
+
491
+ # Copied from transformers.models.bert.tokenization_bert.WordpieceTokenizer
492
+ class WordpieceTokenizer(object):
493
+ """Runs WordPiece tokenization."""
494
+
495
+ def __init__(self, vocab, unk_token, max_input_chars_per_word=100):
496
+ self.vocab = vocab
497
+ self.unk_token = unk_token
498
+ self.max_input_chars_per_word = max_input_chars_per_word
499
+
500
+ def tokenize(self, text):
501
+ """
502
+ Tokenizes a piece of text into its word pieces. This uses a greedy longest-match-first algorithm to perform
503
+ tokenization using the given vocabulary.
504
+
505
+ For example, `input = "unaffable"` wil return as output `["un", "##aff", "##able"]`.
506
+
507
+ Args:
508
+ text: A single token or whitespace separated tokens. This should have
509
+ already been passed through *BasicTokenizer*.
510
+
511
+ Returns:
512
+ A list of wordpiece tokens.
513
+ """
514
+
515
+ output_tokens = []
516
+ for token in whitespace_tokenize(text):
517
+ chars = list(token)
518
+ if len(chars) > self.max_input_chars_per_word:
519
+ output_tokens.append(self.unk_token)
520
+ continue
521
+
522
+ is_bad = False
523
+ start = 0
524
+ sub_tokens = []
525
+ while start < len(chars):
526
+ end = len(chars)
527
+ cur_substr = None
528
+ while start < end:
529
+ substr = "".join(chars[start:end])
530
+ if start > 0:
531
+ substr = "##" + substr
532
+ if substr in self.vocab:
533
+ cur_substr = substr
534
+ break
535
+ end -= 1
536
+ if cur_substr is None:
537
+ is_bad = True
538
+ break
539
+ sub_tokens.append(cur_substr)
540
+ start = end
541
+
542
+ if is_bad:
543
+ output_tokens.append(self.unk_token)
544
+ else:
545
+ output_tokens.extend(sub_tokens)
546
+ return output_tokens
pllava/lib/python3.10/site-packages/transformers/models/groupvit/__init__.py ADDED
@@ -0,0 +1,97 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ from typing import TYPE_CHECKING
15
+
16
+ from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available
17
+
18
+
19
+ _import_structure = {
20
+ "configuration_groupvit": [
21
+ "GROUPVIT_PRETRAINED_CONFIG_ARCHIVE_MAP",
22
+ "GroupViTConfig",
23
+ "GroupViTOnnxConfig",
24
+ "GroupViTTextConfig",
25
+ "GroupViTVisionConfig",
26
+ ],
27
+ }
28
+
29
+ try:
30
+ if not is_torch_available():
31
+ raise OptionalDependencyNotAvailable()
32
+ except OptionalDependencyNotAvailable:
33
+ pass
34
+ else:
35
+ _import_structure["modeling_groupvit"] = [
36
+ "GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST",
37
+ "GroupViTModel",
38
+ "GroupViTPreTrainedModel",
39
+ "GroupViTTextModel",
40
+ "GroupViTVisionModel",
41
+ ]
42
+
43
+ try:
44
+ if not is_tf_available():
45
+ raise OptionalDependencyNotAvailable()
46
+ except OptionalDependencyNotAvailable:
47
+ pass
48
+ else:
49
+ _import_structure["modeling_tf_groupvit"] = [
50
+ "TF_GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST",
51
+ "TFGroupViTModel",
52
+ "TFGroupViTPreTrainedModel",
53
+ "TFGroupViTTextModel",
54
+ "TFGroupViTVisionModel",
55
+ ]
56
+
57
+ if TYPE_CHECKING:
58
+ from .configuration_groupvit import (
59
+ GROUPVIT_PRETRAINED_CONFIG_ARCHIVE_MAP,
60
+ GroupViTConfig,
61
+ GroupViTOnnxConfig,
62
+ GroupViTTextConfig,
63
+ GroupViTVisionConfig,
64
+ )
65
+
66
+ try:
67
+ if not is_torch_available():
68
+ raise OptionalDependencyNotAvailable()
69
+ except OptionalDependencyNotAvailable:
70
+ pass
71
+ else:
72
+ from .modeling_groupvit import (
73
+ GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST,
74
+ GroupViTModel,
75
+ GroupViTPreTrainedModel,
76
+ GroupViTTextModel,
77
+ GroupViTVisionModel,
78
+ )
79
+
80
+ try:
81
+ if not is_tf_available():
82
+ raise OptionalDependencyNotAvailable()
83
+ except OptionalDependencyNotAvailable:
84
+ pass
85
+ else:
86
+ from .modeling_tf_groupvit import (
87
+ TF_GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST,
88
+ TFGroupViTModel,
89
+ TFGroupViTPreTrainedModel,
90
+ TFGroupViTTextModel,
91
+ TFGroupViTVisionModel,
92
+ )
93
+
94
+ else:
95
+ import sys
96
+
97
+ sys.modules[__name__] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
pllava/lib/python3.10/site-packages/transformers/models/patchtst/__init__.py ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ # rely on isort to merge the imports
17
+ from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available
18
+
19
+
20
+ _import_structure = {
21
+ "configuration_patchtst": [
22
+ "PATCHTST_PRETRAINED_CONFIG_ARCHIVE_MAP",
23
+ "PatchTSTConfig",
24
+ ],
25
+ }
26
+
27
+ try:
28
+ if not is_torch_available():
29
+ raise OptionalDependencyNotAvailable()
30
+ except OptionalDependencyNotAvailable:
31
+ pass
32
+ else:
33
+ _import_structure["modeling_patchtst"] = [
34
+ "PATCHTST_PRETRAINED_MODEL_ARCHIVE_LIST",
35
+ "PatchTSTModel",
36
+ "PatchTSTPreTrainedModel",
37
+ "PatchTSTForPrediction",
38
+ "PatchTSTForPretraining",
39
+ "PatchTSTForRegression",
40
+ "PatchTSTForClassification",
41
+ ]
42
+
43
+
44
+ if TYPE_CHECKING:
45
+ from .configuration_patchtst import PATCHTST_PRETRAINED_CONFIG_ARCHIVE_MAP, PatchTSTConfig
46
+
47
+ try:
48
+ if not is_torch_available():
49
+ raise OptionalDependencyNotAvailable()
50
+ except OptionalDependencyNotAvailable:
51
+ pass
52
+ else:
53
+ from .modeling_patchtst import (
54
+ PATCHTST_PRETRAINED_MODEL_ARCHIVE_LIST,
55
+ PatchTSTForClassification,
56
+ PatchTSTForPrediction,
57
+ PatchTSTForPretraining,
58
+ PatchTSTForRegression,
59
+ PatchTSTModel,
60
+ PatchTSTPreTrainedModel,
61
+ )
62
+
63
+ else:
64
+ import sys
65
+
66
+ sys.modules[__name__] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
pllava/lib/python3.10/site-packages/transformers/models/patchtst/__pycache__/configuration_patchtst.cpython-310.pyc ADDED
Binary file (10.5 kB). View file
 
pllava/lib/python3.10/site-packages/transformers/models/patchtst/modeling_patchtst.py ADDED
@@ -0,0 +1,2034 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2023 IBM & Hugging Face. 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 PatchTST model."""
16
+
17
+ import math
18
+ from dataclasses import dataclass
19
+ from typing import Optional, Tuple, Union
20
+
21
+ import torch
22
+ from torch import nn
23
+
24
+ from ...activations import ACT2CLS
25
+ from ...modeling_outputs import BaseModelOutput
26
+ from ...modeling_utils import PreTrainedModel
27
+ from ...time_series_utils import NegativeBinomialOutput, NormalOutput, StudentTOutput
28
+ from ...utils import ModelOutput, add_start_docstrings, logging
29
+ from .configuration_patchtst import PatchTSTConfig
30
+
31
+
32
+ logger = logging.get_logger(__name__)
33
+
34
+ _CONFIG_FOR_DOC = "PatchTSTConfig"
35
+
36
+ PATCHTST_PRETRAINED_MODEL_ARCHIVE_LIST = [
37
+ "ibm/patchtst-etth1-pretrain",
38
+ # See all PatchTST models at https://huggingface.co/models?filter=patchtst
39
+ ]
40
+
41
+
42
+ # Copied from transformers.models.bart.modeling_bart.BartAttention with Bart->PatchTST
43
+ class PatchTSTAttention(nn.Module):
44
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
45
+
46
+ def __init__(
47
+ self,
48
+ embed_dim: int,
49
+ num_heads: int,
50
+ dropout: float = 0.0,
51
+ is_decoder: bool = False,
52
+ bias: bool = True,
53
+ is_causal: bool = False,
54
+ config: Optional[PatchTSTConfig] = None,
55
+ ):
56
+ super().__init__()
57
+ self.embed_dim = embed_dim
58
+ self.num_heads = num_heads
59
+ self.dropout = dropout
60
+ self.head_dim = embed_dim // num_heads
61
+ self.config = config
62
+
63
+ if (self.head_dim * num_heads) != self.embed_dim:
64
+ raise ValueError(
65
+ f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim}"
66
+ f" and `num_heads`: {num_heads})."
67
+ )
68
+ self.scaling = self.head_dim**-0.5
69
+ self.is_decoder = is_decoder
70
+ self.is_causal = is_causal
71
+
72
+ self.k_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
73
+ self.v_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
74
+ self.q_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
75
+ self.out_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
76
+
77
+ def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
78
+ return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
79
+
80
+ def forward(
81
+ self,
82
+ hidden_states: torch.Tensor,
83
+ key_value_states: Optional[torch.Tensor] = None,
84
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
85
+ attention_mask: Optional[torch.Tensor] = None,
86
+ layer_head_mask: Optional[torch.Tensor] = None,
87
+ output_attentions: bool = False,
88
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
89
+ """Input shape: Batch x Time x Channel"""
90
+
91
+ # if key_value_states are provided this layer is used as a cross-attention layer
92
+ # for the decoder
93
+ is_cross_attention = key_value_states is not None
94
+
95
+ bsz, tgt_len, _ = hidden_states.size()
96
+
97
+ # get query proj
98
+ query_states = self.q_proj(hidden_states) * self.scaling
99
+ # get key, value proj
100
+ # `past_key_value[0].shape[2] == key_value_states.shape[1]`
101
+ # is checking that the `sequence_length` of the `past_key_value` is the same as
102
+ # the provided `key_value_states` to support prefix tuning
103
+ if (
104
+ is_cross_attention
105
+ and past_key_value is not None
106
+ and past_key_value[0].shape[2] == key_value_states.shape[1]
107
+ ):
108
+ # reuse k,v, cross_attentions
109
+ key_states = past_key_value[0]
110
+ value_states = past_key_value[1]
111
+ elif is_cross_attention:
112
+ # cross_attentions
113
+ key_states = self._shape(self.k_proj(key_value_states), -1, bsz)
114
+ value_states = self._shape(self.v_proj(key_value_states), -1, bsz)
115
+ elif past_key_value is not None:
116
+ # reuse k, v, self_attention
117
+ key_states = self._shape(self.k_proj(hidden_states), -1, bsz)
118
+ value_states = self._shape(self.v_proj(hidden_states), -1, bsz)
119
+ key_states = torch.cat([past_key_value[0], key_states], dim=2)
120
+ value_states = torch.cat([past_key_value[1], value_states], dim=2)
121
+ else:
122
+ # self_attention
123
+ key_states = self._shape(self.k_proj(hidden_states), -1, bsz)
124
+ value_states = self._shape(self.v_proj(hidden_states), -1, bsz)
125
+
126
+ if self.is_decoder:
127
+ # if cross_attention save Tuple(torch.Tensor, torch.Tensor) of all cross attention key/value_states.
128
+ # Further calls to cross_attention layer can then reuse all cross-attention
129
+ # key/value_states (first "if" case)
130
+ # if uni-directional self-attention (decoder) save Tuple(torch.Tensor, torch.Tensor) of
131
+ # all previous decoder key/value_states. Further calls to uni-directional self-attention
132
+ # can concat previous decoder key/value_states to current projected key/value_states (third "elif" case)
133
+ # if encoder bi-directional self-attention `past_key_value` is always `None`
134
+ past_key_value = (key_states, value_states)
135
+
136
+ proj_shape = (bsz * self.num_heads, -1, self.head_dim)
137
+ query_states = self._shape(query_states, tgt_len, bsz).view(*proj_shape)
138
+ key_states = key_states.reshape(*proj_shape)
139
+ value_states = value_states.reshape(*proj_shape)
140
+
141
+ src_len = key_states.size(1)
142
+ attn_weights = torch.bmm(query_states, key_states.transpose(1, 2))
143
+
144
+ if attn_weights.size() != (bsz * self.num_heads, tgt_len, src_len):
145
+ raise ValueError(
146
+ f"Attention weights should be of size {(bsz * self.num_heads, tgt_len, src_len)}, but is"
147
+ f" {attn_weights.size()}"
148
+ )
149
+
150
+ if attention_mask is not None:
151
+ if attention_mask.size() != (bsz, 1, tgt_len, src_len):
152
+ raise ValueError(
153
+ f"Attention mask should be of size {(bsz, 1, tgt_len, src_len)}, but is {attention_mask.size()}"
154
+ )
155
+ attn_weights = attn_weights.view(bsz, self.num_heads, tgt_len, src_len) + attention_mask
156
+ attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len)
157
+
158
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1)
159
+
160
+ if layer_head_mask is not None:
161
+ if layer_head_mask.size() != (self.num_heads,):
162
+ raise ValueError(
163
+ f"Head mask for a single layer should be of size {(self.num_heads,)}, but is"
164
+ f" {layer_head_mask.size()}"
165
+ )
166
+ attn_weights = layer_head_mask.view(1, -1, 1, 1) * attn_weights.view(bsz, self.num_heads, tgt_len, src_len)
167
+ attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len)
168
+
169
+ if output_attentions:
170
+ # this operation is a bit awkward, but it's required to
171
+ # make sure that attn_weights keeps its gradient.
172
+ # In order to do so, attn_weights have to be reshaped
173
+ # twice and have to be reused in the following
174
+ attn_weights_reshaped = attn_weights.view(bsz, self.num_heads, tgt_len, src_len)
175
+ attn_weights = attn_weights_reshaped.view(bsz * self.num_heads, tgt_len, src_len)
176
+ else:
177
+ attn_weights_reshaped = None
178
+
179
+ attn_probs = nn.functional.dropout(attn_weights, p=self.dropout, training=self.training)
180
+
181
+ attn_output = torch.bmm(attn_probs, value_states)
182
+
183
+ if attn_output.size() != (bsz * self.num_heads, tgt_len, self.head_dim):
184
+ raise ValueError(
185
+ f"`attn_output` should be of size {(bsz * self.num_heads, tgt_len, self.head_dim)}, but is"
186
+ f" {attn_output.size()}"
187
+ )
188
+
189
+ attn_output = attn_output.view(bsz, self.num_heads, tgt_len, self.head_dim)
190
+ attn_output = attn_output.transpose(1, 2)
191
+
192
+ # Use the `embed_dim` from the config (stored in the class) rather than `hidden_state` because `attn_output` can be
193
+ # partitioned across GPUs when using tensor-parallelism.
194
+ attn_output = attn_output.reshape(bsz, tgt_len, self.embed_dim)
195
+
196
+ attn_output = self.out_proj(attn_output)
197
+
198
+ return attn_output, attn_weights_reshaped, past_key_value
199
+
200
+
201
+ class PatchTSTBatchNorm(nn.Module):
202
+ """
203
+ Compute batch normalization over the sequence length (time) dimension.
204
+ """
205
+
206
+ def __init__(self, config: PatchTSTConfig):
207
+ super().__init__()
208
+ self.batchnorm = nn.BatchNorm1d(config.d_model, eps=config.norm_eps)
209
+
210
+ def forward(self, inputs: torch.Tensor):
211
+ """
212
+ Parameters:
213
+ inputs (`torch.Tensor` of shape `(batch_size, sequence_length, d_model)`):
214
+ input for Batch norm calculation
215
+ Returns:
216
+ `torch.Tensor` of shape `(batch_size, sequence_length, d_model)`
217
+ """
218
+ output = inputs.transpose(1, 2) # output: (batch_size, d_model, sequence_length)
219
+ output = self.batchnorm(output)
220
+ return output.transpose(1, 2)
221
+
222
+
223
+ def random_masking(
224
+ inputs: torch.Tensor,
225
+ mask_ratio: float,
226
+ unmasked_channel_indices: list = None,
227
+ channel_consistent_masking: bool = False,
228
+ mask_value: int = 0,
229
+ ):
230
+ """random_masking: Mask the input considering the control variables.
231
+
232
+ Args:
233
+ inputs (`torch.Tensor` of shape `(batch_size, num_channels, sequence_length, num_features)`):
234
+ The input tensor to mask.
235
+ mask_ratio (`float`):
236
+ Masking ratio applied to mask the input data during random pretraining. It is the number between 0 and 1.
237
+ unmasked_channel_indices (list, *optional*):
238
+ Indices of channels that will not be masked.
239
+ channel_consistent_masking (bool, *optional*, defaults to `False`):
240
+ When true, masking will be same across all channels of a timeseries. Otherwise, masking positions will vary
241
+ across channels.
242
+ mask_value (int, *optional*, defaults to 0):
243
+ Define the value of masked patches for pretraining.
244
+
245
+ Returns:
246
+ `tuple(torch.Tensor)`: inputs_mask, masked input, same shape as input Tensor and mask tensor of shape [bs x c x
247
+ n]
248
+ """
249
+ if mask_ratio < 0 or mask_ratio >= 1:
250
+ raise ValueError(f"Mask ratio {mask_ratio} has to be between 0 and 1.")
251
+
252
+ batch_size, num_channels, sequence_length, num_features = inputs.shape
253
+ device = inputs.device
254
+
255
+ len_keep = int(sequence_length * (1 - mask_ratio))
256
+
257
+ if channel_consistent_masking:
258
+ noise = torch.rand(batch_size, 1, sequence_length, device=device) # noise in [0, 1], bs x 1 x L
259
+ noise = noise.repeat(1, num_channels, 1) # bs x num_channels x time
260
+ else:
261
+ # noise in [0, 1], bs x num_channels x L
262
+ noise = torch.rand(batch_size, num_channels, sequence_length, device=device)
263
+
264
+ # mask: [bs x num_channels x num_patch]
265
+ mask = torch.ones(batch_size, num_channels, sequence_length, device=device)
266
+ mask[:, :, :len_keep] = 0
267
+
268
+ # sort noise for each sample
269
+ ids_shuffle = torch.argsort(noise, dim=-1) # ascend: small is keep, large is remove
270
+ ids_restore = torch.argsort(ids_shuffle, dim=-1) # ids_restore: [bs x num_channels x L]
271
+
272
+ mask = torch.gather(mask, dim=-1, index=ids_restore)
273
+ mask = mask.unsqueeze(-1).repeat(1, 1, 1, num_features) # mask: [bs x num_channels x num_patches x patch_length]
274
+ if unmasked_channel_indices is not None:
275
+ mask[:, unmasked_channel_indices, :, :] = 0
276
+
277
+ inputs_mask = inputs.masked_fill(mask.bool(), mask_value)
278
+ return inputs_mask, mask[..., 0]
279
+
280
+
281
+ def forecast_masking(
282
+ inputs: torch.Tensor,
283
+ num_forecast_mask_patches: Union[list, int],
284
+ unmasked_channel_indices: list = None,
285
+ mask_value: int = 0,
286
+ ):
287
+ """Forecast masking that masks the last K patches where K is from the num_forecast_mask_patches.
288
+ If num_forecast_mask_patches is a list, samples in the batch will be randomly masked by numbers defined in the list.
289
+
290
+ Parameters:
291
+ inputs (`torch.Tensor`):
292
+ Input of shape `(bs, num_channels, num_patch, patch_len)`
293
+ num_forecast_mask_patches (`list`):
294
+ Number of patches to be masked at the end of each batch sample. e.g. 4 or [3, 5].
295
+ unmasked_channel_indices (`list`, *optional*):
296
+ Indices of channels that are not masked.
297
+ mask_value (`int`, *optional*, defaults to 0):
298
+ Values in the masked patches will be filled by `mask_value`.
299
+
300
+ Returns:
301
+ `tuple(torch.Tensor)`: inputs_mask, masked input, same shape as inputs Tensor and Mask tensor of shape `(bs,
302
+ num_channels , num_patch)` or `(bs, tsg1, tsg2, num_channels, num_patch)`
303
+ """
304
+
305
+ if isinstance(num_forecast_mask_patches, int):
306
+ num_forecast_mask_patches = [num_forecast_mask_patches]
307
+ forecast_mask_ratios = [1 for _ in num_forecast_mask_patches]
308
+
309
+ batch_size, num_channels, sequence_length, num_features = inputs.shape
310
+ mask = torch.zeros(batch_size, num_channels, sequence_length, device=inputs.device)
311
+
312
+ t_list = []
313
+ total_length = 0
314
+ total_ratio = sum(forecast_mask_ratios)
315
+
316
+ for patch_length, ratio in zip(num_forecast_mask_patches, forecast_mask_ratios):
317
+ if patch_length <= 0 or patch_length >= sequence_length:
318
+ raise ValueError(
319
+ f"num_forecast_mask_patches {patch_length} should be greater than 0 and less than total patches."
320
+ )
321
+ temp_len = int(batch_size * ratio / total_ratio)
322
+ t_list.append([patch_length, ratio, temp_len])
323
+ total_length += temp_len
324
+
325
+ t_list = sorted(t_list, key=lambda x: x[2])
326
+
327
+ if total_length < batch_size:
328
+ t_list[0][2] = t_list[0][2] + (batch_size - total_length)
329
+ elif total_length > batch_size:
330
+ t_list[-1][2] = t_list[-1][2] + (total_length - batch_size)
331
+
332
+ batch1 = 0
333
+ for patch_len, _, temp_len in t_list:
334
+ batch2 = batch1 + temp_len
335
+ mask[batch1:batch2, :, -patch_len:] = 1
336
+ batch1 = batch2
337
+
338
+ perm = torch.randperm(mask.shape[0])
339
+ mask = mask[perm]
340
+
341
+ mask = mask.unsqueeze(-1).repeat(1, 1, 1, num_features) # mask: [bs x num_channels x num_patch x patch_len]
342
+ if unmasked_channel_indices is not None:
343
+ mask[:, unmasked_channel_indices, :, :] = 0
344
+
345
+ inputs_mask = inputs.masked_fill(mask.bool(), mask_value)
346
+ return inputs_mask, mask[..., 0]
347
+
348
+
349
+ class PatchTSTPatchify(nn.Module):
350
+ """
351
+ A class to patchify the time series sequence into different patches
352
+
353
+ Returns:
354
+ `torch.Tensor` of shape `(batch_size, num_channels, num_patches, patch_length)`
355
+ """
356
+
357
+ def __init__(self, config: PatchTSTConfig):
358
+ super().__init__()
359
+
360
+ self.sequence_length = config.context_length
361
+ self.patch_length = config.patch_length
362
+ self.patch_stride = config.patch_stride
363
+
364
+ if self.sequence_length <= self.patch_length:
365
+ raise ValueError(
366
+ f"Sequence length ({self.sequence_length}) has to be greater than the patch length ({self.patch_length})"
367
+ )
368
+
369
+ # get the number of patches
370
+ self.num_patches = (max(self.sequence_length, self.patch_length) - self.patch_length) // self.patch_stride + 1
371
+ new_sequence_length = self.patch_length + self.patch_stride * (self.num_patches - 1)
372
+ self.sequence_start = self.sequence_length - new_sequence_length
373
+
374
+ def forward(self, past_values: torch.Tensor):
375
+ """
376
+ Parameters:
377
+ past_values (`torch.Tensor` of shape `(batch_size, sequence_length, num_channels)`, *required*):
378
+ Input for patchification
379
+
380
+ Returns:
381
+ `torch.Tensor` of shape `(batch_size, num_channels, num_patches, patch_length)`
382
+ """
383
+ sequence_length = past_values.shape[-2]
384
+ if sequence_length != self.sequence_length:
385
+ raise ValueError(
386
+ f"Input sequence length ({sequence_length}) doesn't match model configuration ({self.sequence_length})."
387
+ )
388
+ # output: [bs x new_sequence_length x num_channels]
389
+ output = past_values[:, self.sequence_start :, :]
390
+ # output: [bs x num_patches x num_input_channels x patch_length]
391
+ output = output.unfold(dimension=-2, size=self.patch_length, step=self.patch_stride)
392
+ # output: [bs x num_input_channels x num_patches x patch_length]
393
+ output = output.transpose(-2, -3).contiguous()
394
+ return output
395
+
396
+
397
+ class PatchTSTMasking(nn.Module):
398
+ """
399
+ Class to perform random or forecast masking.
400
+
401
+ Parameters:
402
+ config (`PatchTSTConfig`): model config
403
+ Returns:
404
+ x_mask (`torch.Tensor` of shape `(batch_size, num_channels, num_patches, patch_length)`)
405
+ Masked patched input
406
+ mask (`torch.Tensor` of shape `(batch_size, num_channels, num_patches)`)
407
+ Bool tensor indicating True on masked points
408
+ """
409
+
410
+ def __init__(self, config: PatchTSTConfig):
411
+ super().__init__()
412
+ self.random_mask_ratio = config.random_mask_ratio
413
+ self.channel_consistent_masking = config.channel_consistent_masking
414
+ self.mask_type = config.mask_type
415
+ self.num_forecast_mask_patches = config.num_forecast_mask_patches
416
+ self.unmasked_channel_indices = config.unmasked_channel_indices
417
+ self.mask_value = config.mask_value
418
+ if self.unmasked_channel_indices is not None:
419
+ self.unmasked_channel_indices = sorted(self.unmasked_channel_indices)
420
+
421
+ def forward(self, patch_input: torch.Tensor):
422
+ """
423
+ Parameters:
424
+ patch_input (`torch.Tensor` of shape `(batch_size, num_channels, num_patches, patch_length)`, *required*):
425
+ Patch input
426
+
427
+ Return:
428
+ masked_input (`torch.Tensor` of shape `(batch_size, num_channels, num_patches, patch_length)`)
429
+ Masked patched input
430
+ mask (`torch.Tensor` of shape `(batch_size, num_channels, num_patches)`)
431
+ Bool tensor indicating True on masked points
432
+
433
+ """
434
+ if self.mask_type == "random":
435
+ masked_input, mask = random_masking(
436
+ inputs=patch_input,
437
+ mask_ratio=self.random_mask_ratio,
438
+ unmasked_channel_indices=self.unmasked_channel_indices,
439
+ channel_consistent_masking=self.channel_consistent_masking,
440
+ mask_value=self.mask_value,
441
+ )
442
+ elif self.mask_type == "forecast":
443
+ masked_input, mask = forecast_masking(
444
+ inputs=patch_input,
445
+ num_forecast_mask_patches=self.num_forecast_mask_patches,
446
+ unmasked_channel_indices=self.unmasked_channel_indices,
447
+ mask_value=self.mask_value,
448
+ )
449
+ else:
450
+ raise ValueError(f"Invalid mask type {self.mask_type}.")
451
+
452
+ # mask: [bs x num_input_channels x num_patch]
453
+ mask = mask.bool()
454
+ return masked_input, mask
455
+
456
+
457
+ class PatchTSTEncoderLayer(nn.Module):
458
+ """
459
+ PatchTST encoder layer
460
+ """
461
+
462
+ def __init__(self, config: PatchTSTConfig):
463
+ super().__init__()
464
+
465
+ self.channel_attention = config.channel_attention
466
+ # Multi-Head attention
467
+ self.self_attn = PatchTSTAttention(
468
+ embed_dim=config.d_model,
469
+ num_heads=config.num_attention_heads,
470
+ dropout=config.attention_dropout,
471
+ )
472
+
473
+ # Add & Norm of the sublayer 1
474
+ self.dropout_path1 = nn.Dropout(config.path_dropout) if config.path_dropout > 0 else nn.Identity()
475
+ if config.norm_type == "batchnorm":
476
+ self.norm_sublayer1 = PatchTSTBatchNorm(config)
477
+ elif config.norm_type == "layernorm":
478
+ self.norm_sublayer1 = nn.LayerNorm(config.d_model, eps=config.norm_eps)
479
+ else:
480
+ raise ValueError(f"{config.norm_type} is not a supported norm layer type.")
481
+
482
+ # Add & Norm of the sublayer 2
483
+ if self.channel_attention:
484
+ self.dropout_path2 = nn.Dropout(config.path_dropout) if config.path_dropout > 0 else nn.Identity()
485
+ if config.norm_type == "batchnorm":
486
+ self.norm_sublayer2 = PatchTSTBatchNorm(config)
487
+ elif config.norm_type == "layernorm":
488
+ self.norm_sublayer2 = nn.LayerNorm(config.d_model, eps=config.norm_eps)
489
+ else:
490
+ raise ValueError(f"{config.norm_type} is not a supported norm layer type.")
491
+
492
+ # Position-wise Feed-Forward
493
+ self.ff = nn.Sequential(
494
+ nn.Linear(config.d_model, config.ffn_dim, bias=config.bias),
495
+ ACT2CLS[config.activation_function](),
496
+ nn.Dropout(config.ff_dropout) if config.ff_dropout > 0 else nn.Identity(),
497
+ nn.Linear(config.ffn_dim, config.d_model, bias=config.bias),
498
+ )
499
+
500
+ # Add & Norm of sublayer 3
501
+ self.dropout_path3 = nn.Dropout(config.path_dropout) if config.path_dropout > 0 else nn.Identity()
502
+ if config.norm_type == "batchnorm":
503
+ self.norm_sublayer3 = PatchTSTBatchNorm(config)
504
+ elif config.norm_type == "layernorm":
505
+ self.norm_sublayer3 = nn.LayerNorm(config.d_model, eps=config.norm_eps)
506
+ else:
507
+ raise ValueError(f"{config.norm_type} is not a supported norm layer type.")
508
+
509
+ self.pre_norm = config.pre_norm
510
+
511
+ def forward(self, hidden_state: torch.Tensor, output_attentions: Optional[bool] = None):
512
+ """
513
+ Parameters:
514
+ hidden_state (`torch.Tensor` of shape `(batch_size, num_channels, sequence_length, d_model)`, *required*):
515
+ Past values of the time series
516
+ output_attentions (`bool`, *optional*):
517
+ Whether or not to return the output attention of all layers
518
+ Return:
519
+ `torch.Tensor` of shape `(batch_size, num_channels, sequence_length, d_model)`
520
+
521
+ """
522
+ batch_size, num_input_channels, sequence_length, d_model = hidden_state.shape
523
+
524
+ # First sublayer: attention across time
525
+ # hidden_states: [(bs*num_channels) x sequence_length x d_model]
526
+ hidden_state = hidden_state.view(batch_size * num_input_channels, sequence_length, d_model)
527
+
528
+ if self.pre_norm:
529
+ ## Norm and Multi-Head attention and Add residual connection
530
+ attn_output, attn_weights, _ = self.self_attn(
531
+ hidden_states=self.norm_sublayer1(hidden_state), output_attentions=output_attentions
532
+ )
533
+ # Add: residual connection with residual dropout
534
+ hidden_state = hidden_state + self.dropout_path1(attn_output)
535
+ else:
536
+ ## Multi-Head attention and Add residual connection and Norm - Standard Transformer from BERT
537
+ attn_output, attn_weights, _ = self.self_attn(
538
+ hidden_states=hidden_state, output_attentions=output_attentions
539
+ )
540
+ # hidden_states: [(bs*num_channels) x sequence_length x d_model]
541
+ hidden_state = self.norm_sublayer1(hidden_state + self.dropout_path1(attn_output))
542
+
543
+ # hidden_state: [bs x num_channels x sequence_length x d_model]
544
+ hidden_state = hidden_state.reshape(batch_size, num_input_channels, sequence_length, d_model)
545
+
546
+ # second sublayer: attention across variable at any given time
547
+ if self.channel_attention:
548
+ # hidden_state: [bs x sequence_length x num_channels x d_model]
549
+ hidden_state = hidden_state.transpose(2, 1).contiguous()
550
+ # hidden_state: [(bs*sequence_length) x num_channels x d_model]
551
+ hidden_state = hidden_state.view(batch_size * sequence_length, num_input_channels, d_model)
552
+ if self.pre_norm:
553
+ ## Norm and Multi-Head attention and Add residual connection
554
+ attn_output, channel_attn_weights, _ = self.self_attn(
555
+ hidden_states=self.norm_sublayer2(hidden_state), output_attentions=output_attentions
556
+ )
557
+ # Add: residual connection with residual dropout
558
+ hidden_state = hidden_state + self.dropout_path2(attn_output)
559
+ else:
560
+ ## Multi-Head attention and Add residual connection and Norm
561
+ attn_output, channel_attn_weights, _ = self.self_attn(
562
+ hidden_states=hidden_state, output_attentions=output_attentions
563
+ )
564
+ # hidden_states: [(bs*sequence_length) x num_channels x d_model]
565
+ hidden_state = self.norm_sublayer2(hidden_state + self.dropout_path2(attn_output))
566
+
567
+ # Reshape hidden state
568
+ # hidden_state: [bs x sequence_length x num_channels x d_model]
569
+ hidden_state = hidden_state.reshape(batch_size, sequence_length, num_input_channels, d_model)
570
+ # hidden_state: [bs x num_channels x sequence_length x d_model]
571
+ hidden_state = hidden_state.transpose(1, 2).contiguous()
572
+
573
+ # Third sublayer: mixing across hidden
574
+ # hidden_state: [(batch_size*num_channels) x sequence_length x d_model]
575
+ hidden_state = hidden_state.view(batch_size * num_input_channels, sequence_length, d_model)
576
+ if self.pre_norm:
577
+ ## Norm and Position-wise Feed-Forward and Add residual connection
578
+ # Add: residual connection with residual dropout
579
+ hidden_state = hidden_state + self.dropout_path3(self.ff(self.norm_sublayer3(hidden_state)))
580
+ else:
581
+ ## Position-wise Feed-Forward and Add residual connection and Norm
582
+ # Add: residual connection with residual dropout
583
+ hidden_state = self.norm_sublayer3(hidden_state + self.dropout_path3(self.ff(hidden_state)))
584
+
585
+ # [bs x num_channels x sequence_length x d_model]
586
+ hidden_state = hidden_state.reshape(batch_size, num_input_channels, sequence_length, d_model)
587
+
588
+ outputs = (hidden_state,)
589
+ if output_attentions:
590
+ outputs += (attn_weights, channel_attn_weights) if self.channel_attention else (attn_weights,)
591
+
592
+ return outputs
593
+
594
+
595
+ class PatchTSTPreTrainedModel(PreTrainedModel):
596
+ config_class = PatchTSTConfig
597
+ base_model_prefix = "model"
598
+ main_input_name = "past_values"
599
+ supports_gradient_checkpointing = False
600
+
601
+ def _init_weights(self, module):
602
+ """
603
+ Initialize weights
604
+ """
605
+ if isinstance(module, PatchTSTPositionalEncoding):
606
+ # initialize cls_token
607
+ if self.config.use_cls_token:
608
+ nn.init.normal_(module.cls_token, std=0.02)
609
+ # initialize positional encoding
610
+ if self.config.positional_encoding_type == "random":
611
+ nn.init.normal_(module.position_enc, mean=0.0, std=0.1)
612
+ elif isinstance(module, nn.LayerNorm):
613
+ module.bias.data.zero_()
614
+ module.weight.data.fill_(1.0)
615
+ elif isinstance(module, PatchTSTBatchNorm):
616
+ module.batchnorm.bias.data.zero_()
617
+ module.batchnorm.weight.data.fill_(1.0)
618
+ elif isinstance(module, (nn.Linear, nn.Conv1d)):
619
+ module.weight.data.normal_(mean=0.0, std=self.config.init_std)
620
+ if module.bias is not None:
621
+ module.bias.data.zero_()
622
+
623
+ def _set_gradient_checkpointing(self, module, value=False):
624
+ if isinstance(module, (PatchTSTEncoder)):
625
+ module.gradient_checkpointing = value
626
+
627
+
628
+ class PatchTSTEmbedding(nn.Module):
629
+ def __init__(self, config: PatchTSTConfig):
630
+ super().__init__()
631
+ self.num_input_channels = config.num_input_channels
632
+ self.share_embedding = config.share_embedding
633
+ # Input encoding: projection of feature vectors onto a d-dim vector space
634
+ if self.share_embedding:
635
+ self.input_embedding = nn.Linear(config.patch_length, config.d_model)
636
+ else:
637
+ self.input_embedding = nn.ModuleList()
638
+ for _ in range(config.num_input_channels):
639
+ self.input_embedding.append(nn.Linear(config.patch_length, config.d_model))
640
+
641
+ def forward(self, patch_input: torch.Tensor):
642
+ """
643
+ Parameters:
644
+ patch_input (`torch.Tensor` of shape `(batch_size, num_channels, num_patches, patch_length)`, *required*):
645
+ Patch input for embedding
646
+ return:
647
+ `torch.Tensor` of shape `(batch_size, num_channels, num_patches, d_model)`
648
+ """
649
+ # Input encoding
650
+ num_input_channels = patch_input.shape[1]
651
+ if num_input_channels != self.num_input_channels:
652
+ raise ValueError(
653
+ f"The defined number of input channels ({self.num_input_channels}) in the config "
654
+ f"has to be the same as the number of channels in the batch input ({num_input_channels})"
655
+ )
656
+ if self.share_embedding:
657
+ embeddings = self.input_embedding(patch_input) # x: [bs x num_channels x num_patches x d_model]
658
+ else:
659
+ embeddings = [self.input_embedding[i](patch_input[:, i, :, :]) for i in range(num_input_channels)]
660
+ embeddings = torch.stack(embeddings, dim=1)
661
+ return embeddings
662
+
663
+
664
+ class PatchTSTPositionalEncoding(nn.Module):
665
+ """
666
+ Class for positional encoding
667
+ """
668
+
669
+ def __init__(self, config: PatchTSTConfig, num_patches: int):
670
+ super().__init__()
671
+ self.use_cls_token = config.use_cls_token
672
+ self.num_input_channels = config.num_input_channels
673
+ if config.use_cls_token:
674
+ # cls_token: [1 x num_input_channels x 1 x d_model]
675
+ self.cls_token = nn.Parameter(torch.zeros(1, 1, 1, config.d_model))
676
+ num_patches += 1
677
+ # postional encoding: [num_patches x d_model]
678
+ self.position_enc = self._init_pe(config, num_patches)
679
+ # Positional dropout
680
+ self.positional_dropout = (
681
+ nn.Dropout(config.positional_dropout) if config.positional_dropout > 0 else nn.Identity()
682
+ )
683
+
684
+ @staticmethod
685
+ def _init_pe(config: PatchTSTConfig, num_patches: int) -> nn.Parameter:
686
+ # Positional encoding
687
+ if config.positional_encoding_type == "random":
688
+ position_enc = nn.Parameter(torch.randn(num_patches, config.d_model), requires_grad=True)
689
+ elif config.positional_encoding_type == "sincos":
690
+ position_enc = torch.zeros(num_patches, config.d_model)
691
+ position = torch.arange(0, num_patches).unsqueeze(1)
692
+ div_term = torch.exp(torch.arange(0, config.d_model, 2) * -(math.log(10000.0) / config.d_model))
693
+ position_enc[:, 0::2] = torch.sin(position * div_term)
694
+ position_enc[:, 1::2] = torch.cos(position * div_term)
695
+ position_enc = position_enc - position_enc.mean()
696
+ position_enc = position_enc / (position_enc.std() * 10)
697
+ position_enc = nn.Parameter(position_enc, requires_grad=False)
698
+ else:
699
+ raise ValueError(
700
+ f"{config.positional_encoding_type} is not a valid positional encoder. Available types are 'random' and 'sincos'."
701
+ )
702
+ return position_enc
703
+
704
+ def forward(self, patch_input: torch.Tensor):
705
+ if self.use_cls_token:
706
+ # patch_input: [bs x num_channels x num_patches x d_model]
707
+ patch_input = self.positional_dropout(patch_input + self.position_enc[1:, :])
708
+ # append cls token where cls_token: [1 x num_channels x 1 x d_model]
709
+ cls_token = self.cls_token + self.position_enc[:1, :]
710
+ # get the same copy of cls_token for all the samples in batch: [bs x num_channels x 1 x d_model]
711
+ cls_tokens = cls_token.expand(patch_input.shape[0], self.num_input_channels, -1, -1)
712
+ # hidden_state: [bs x num_channels x (num_patches+1) x d_model]
713
+ hidden_state = torch.cat((cls_tokens, patch_input), dim=2)
714
+ else:
715
+ # hidden_state: [bs x num_channels x num_patches x d_model]
716
+ hidden_state = self.positional_dropout(patch_input + self.position_enc)
717
+ return hidden_state
718
+
719
+
720
+ class PatchTSTEncoder(PatchTSTPreTrainedModel):
721
+ """
722
+ PatchTST Encoder
723
+ """
724
+
725
+ def __init__(self, config: PatchTSTConfig, num_patches: int):
726
+ super().__init__(config)
727
+ self.gradient_checkpointing = False
728
+
729
+ # Input embedding: projection of feature vectors onto a d-dim vector space
730
+ self.embedder = PatchTSTEmbedding(config)
731
+ # Positional encoding
732
+ self.positional_encoder = PatchTSTPositionalEncoding(config, num_patches)
733
+ # Encoder
734
+ self.layers = nn.ModuleList([PatchTSTEncoderLayer(config) for i in range(config.num_hidden_layers)])
735
+
736
+ # Initialize weights and apply final processing
737
+ self.post_init()
738
+
739
+ def forward(
740
+ self,
741
+ patch_input: torch.Tensor,
742
+ output_hidden_states: Optional[bool] = None,
743
+ output_attentions: Optional[bool] = None,
744
+ ) -> BaseModelOutput:
745
+ """
746
+ Parameters:
747
+ patch_input (`torch.Tensor` of shape `(batch_size, num_channels, num_patches, patch_length)`, *required*):
748
+ Past values of the time series
749
+ output_hidden_states (bool, optional): Indicates if hidden states should be outputted.
750
+ output_attentions (bool, optional): Indicates if attentions should be outputted.
751
+
752
+ return:
753
+ `BaseModelOutput`
754
+ """
755
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
756
+ output_hidden_states = (
757
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
758
+ )
759
+
760
+ # Input embedding
761
+ patch_input = self.embedder(patch_input)
762
+ # Positional encoding
763
+ hidden_state = self.positional_encoder(patch_input)
764
+
765
+ encoder_states = () if output_hidden_states else None
766
+ all_attentions = () if output_attentions else None
767
+ for encoder_layer in self.layers:
768
+ if output_hidden_states:
769
+ encoder_states = encoder_states + (hidden_state,)
770
+
771
+ layer_outputs = encoder_layer(hidden_state=hidden_state, output_attentions=output_attentions)
772
+ # get hidden state. hidden_state shape is [bs x num_channels x num_patches x d_model]
773
+ # or [bs x num_channels x (num_patches+1) x d_model] if use cls_token
774
+ hidden_state = layer_outputs[0]
775
+ # append attention matrix at each layer
776
+ if output_attentions:
777
+ all_attentions = all_attentions + (layer_outputs[1],)
778
+ # return past_values, hidden_states
779
+ return BaseModelOutput(last_hidden_state=hidden_state, hidden_states=encoder_states, attentions=all_attentions)
780
+
781
+
782
+ PATCHTST_START_DOCSTRING = r"""
783
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
784
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
785
+ etc.)
786
+
787
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
788
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
789
+ and behavior.
790
+
791
+ Parameters:
792
+ config ([`PatchTSTConfig`]):
793
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
794
+ load the weights associated with the model, only the configuration. Check out the
795
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
796
+ """
797
+
798
+
799
+ @dataclass
800
+ class PatchTSTModelOutput(ModelOutput):
801
+ """
802
+ Base class for model's outputs, with potential hidden states.
803
+
804
+ Parameters:
805
+ last_hidden_state (`torch.FloatTensor` of shape `(batch_size, num_channels, num_patches, patch_length)`):
806
+ Sequence of hidden-states at the output of the last layer of the model.
807
+ hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
808
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
809
+ one for the output of each layer) of shape `(batch_size, num_channels, height, width)`. Hidden-states of
810
+ the model at the output of each layer plus the optional initial embedding outputs.
811
+ mask: (`torch.FloatTensor` of shape `(batch_size, num_channels, num_patches)`, *optional*)
812
+ Bool masked tensor indicating which patches are masked
813
+ loc: (`torch.FloatTensor` of shape `(batch_size, 1, num_channels)`, *optional*)
814
+ Mean of the input data (batch_size, sequence_length, num_channels) over the sequence_length
815
+ scale: (`torch.FloatTensor` of shape `(batch_size, 1, num_channels)`, *optional*)
816
+ Std of the input data (batch_size, sequence_length, num_channels) over the sequence_length
817
+ patch_input (`torch.FloatTensor` of shape `(batch_size, num_channels, num_patches, patch_length)`):
818
+ Patched input to the Transformer
819
+ """
820
+
821
+ last_hidden_state: torch.FloatTensor = None
822
+ hidden_states: Optional[Tuple[torch.FloatTensor]] = None
823
+ attentions: Optional[Tuple[torch.FloatTensor]] = None
824
+ mask: torch.FloatTensor = None
825
+ loc: torch.FloatTensor = None
826
+ scale: torch.FloatTensor = None
827
+ patch_input: torch.FloatTensor = None
828
+
829
+
830
+ @dataclass
831
+ class PatchTSTForPretrainingOutput(ModelOutput):
832
+ """
833
+ Output type of [`PatchTSTForPretraining`].
834
+
835
+ Parameters:
836
+ loss (*optional*, returned when `labels` is provided, `torch.FloatTensor` of shape `(1,)`):
837
+ MSE loss.
838
+ prediction_outputs (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
839
+ Prediction outputs of the time series modeling heads.
840
+ hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
841
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of
842
+ shape `(batch_size, sequence_length, hidden_size)`.
843
+
844
+ Hidden-states of the model at the output of each layer plus the initial embedding outputs.
845
+ attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
846
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
847
+ sequence_length)`.
848
+
849
+ Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
850
+ heads.
851
+ """
852
+
853
+ loss: Optional[torch.FloatTensor] = None
854
+ prediction_output: torch.FloatTensor = None
855
+ hidden_states: Optional[Tuple[torch.FloatTensor]] = None
856
+ attentions: Optional[Tuple[torch.FloatTensor]] = None
857
+
858
+
859
+ @dataclass
860
+ class PatchTSTForRegressionOutput(ModelOutput):
861
+ """
862
+ Output type of [`PatchTSTForRegression`].
863
+
864
+ Parameters:
865
+ loss (*optional*, returned when `labels` is provided, `torch.FloatTensor` of shape `(1,)`):
866
+ MSE loss.
867
+ regression_outputs (`torch.FloatTensor` of shape `(batch_size, num_targets)`):
868
+ Regression outputs of the time series modeling heads.
869
+ hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
870
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of
871
+ shape `(batch_size, sequence_length, hidden_size)`.
872
+
873
+ Hidden-states of the model at the output of each layer plus the initial embedding outputs.
874
+ attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
875
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
876
+ sequence_length)`.
877
+
878
+ Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
879
+ heads.
880
+ """
881
+
882
+ loss: Optional[torch.FloatTensor] = None
883
+ regression_outputs: torch.FloatTensor = None
884
+ hidden_states: Optional[Tuple[torch.FloatTensor]] = None
885
+ attentions: Optional[Tuple[torch.FloatTensor]] = None
886
+
887
+
888
+ @dataclass
889
+ class PatchTSTForPredictionOutput(ModelOutput):
890
+ """
891
+ Output type of [`PatchTSTForPrediction`].
892
+
893
+ Parameters:
894
+ loss (*optional*, returned when `labels` is provided, `torch.FloatTensor` of shape `(1,)`):
895
+ MSE loss.
896
+ prediction_outputs (`torch.FloatTensor` of shape `(batch_size, prediction_length, -1)`):
897
+ Prediction outputs of the time series modeling heads.
898
+ hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
899
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of
900
+ shape `(batch_size, sequence_length, hidden_size)`.
901
+
902
+ Hidden-states of the model at the output of each layer plus the initial embedding outputs.
903
+ attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
904
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
905
+ sequence_length)`.
906
+
907
+ Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
908
+ heads.
909
+ loc: (`torch.FloatTensor` of shape `(batch_size, 1, num_channels)`, *optional*)
910
+ Mean of the input data (batch_size, sequence_length, num_channels) over the sequence_length
911
+ scale: (`torch.FloatTensor` of shape `(batch_size, 1, num_channels)`, *optional*)
912
+ Std of the input data (batch_size, sequence_length, num_channels) over the sequence_length
913
+ """
914
+
915
+ loss: Optional[torch.FloatTensor] = None
916
+ prediction_outputs: torch.FloatTensor = None
917
+ hidden_states: Optional[Tuple[torch.FloatTensor]] = None
918
+ attentions: Optional[Tuple[torch.FloatTensor]] = None
919
+ loc: torch.FloatTensor = None
920
+ scale: torch.FloatTensor = None
921
+
922
+
923
+ @dataclass
924
+ class PatchTSTForClassificationOutput(ModelOutput):
925
+ """
926
+ Output type of [`PatchTSTForClassification`].
927
+
928
+ Parameters:
929
+ loss (*optional*, returned when `labels` is provided, `torch.FloatTensor` of shape `(1,)`):
930
+ Total loss as the sum of the masked language modeling loss and the next sequence prediction
931
+ (classification) loss.
932
+ prediction_logits (`torch.FloatTensor` of shape `(batch_size, num_targets)`):
933
+ Prediction scores of the PatchTST modeling head (scores before SoftMax).
934
+ hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
935
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of
936
+ shape `(batch_size, sequence_length, hidden_size)`.
937
+
938
+ Hidden-states of the model at the output of each layer plus the initial embedding outputs.
939
+ attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
940
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
941
+ sequence_length)`.
942
+
943
+ Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
944
+ heads.
945
+ """
946
+
947
+ loss: Optional[torch.FloatTensor] = None
948
+ prediction_logits: torch.FloatTensor = None
949
+ hidden_states: Optional[Tuple[torch.FloatTensor]] = None
950
+ attentions: Optional[Tuple[torch.FloatTensor]] = None
951
+
952
+
953
+ @dataclass
954
+ class SamplePatchTSTOutput(ModelOutput):
955
+ """
956
+ Base class for time series model's predictions outputs that contains the sampled values from the chosen
957
+ distribution.
958
+
959
+ Parameters:
960
+ sequences `(batch_size, num_samples, prediction_length, num_targets)`):
961
+ Sampled values from the chosen distribution.
962
+ """
963
+
964
+ sequences: torch.FloatTensor = None
965
+
966
+
967
+ # Copied from transformers.models.time_series_transformer.modeling_time_series_transformer.nll
968
+ def nll(input: torch.distributions.Distribution, target: torch.Tensor) -> torch.Tensor:
969
+ """
970
+ Computes the negative log likelihood loss from input distribution with respect to target.
971
+ """
972
+ return -input.log_prob(target)
973
+
974
+
975
+ # Copied from transformers.models.time_series_transformer.modeling_time_series_transformer.weighted_average
976
+ def weighted_average(input_tensor: torch.Tensor, weights: Optional[torch.Tensor] = None, dim=None) -> torch.Tensor:
977
+ """
978
+ Computes the weighted average of a given tensor across a given `dim`, masking values associated with weight zero,
979
+ meaning instead of `nan * 0 = nan` you will get `0 * 0 = 0`.
980
+
981
+ Args:
982
+ input_tensor (`torch.FloatTensor`):
983
+ Input tensor, of which the average must be computed.
984
+ weights (`torch.FloatTensor`, *optional*):
985
+ Weights tensor, of the same shape as `input_tensor`.
986
+ dim (`int`, *optional*):
987
+ The dim along which to average `input_tensor`.
988
+
989
+ Returns:
990
+ `torch.FloatTensor`: The tensor with values averaged along the specified `dim`.
991
+ """
992
+ if weights is not None:
993
+ weighted_tensor = torch.where(weights != 0, input_tensor * weights, torch.zeros_like(input_tensor))
994
+ sum_weights = torch.clamp(weights.sum(dim=dim) if dim else weights.sum(), min=1.0)
995
+ return (weighted_tensor.sum(dim=dim) if dim else weighted_tensor.sum()) / sum_weights
996
+ else:
997
+ return input_tensor.mean(dim=dim)
998
+
999
+
1000
+ # Copied from transformers.models.time_series_transformer.modeling_time_series_transformer.TimeSeriesStdScaler with TimeSeriesTransformer->PatchTST,TimeSeries->PatchTST
1001
+ class PatchTSTStdScaler(nn.Module):
1002
+ """
1003
+ Standardize features by calculating the mean and scaling along the first dimension, and then normalizes it by
1004
+ subtracting from the mean and dividing by the standard deviation.
1005
+ """
1006
+
1007
+ def __init__(self, config: PatchTSTConfig):
1008
+ super().__init__()
1009
+ self.dim = config.scaling_dim if hasattr(config, "scaling_dim") else 1
1010
+ self.keepdim = config.keepdim if hasattr(config, "keepdim") else True
1011
+ self.minimum_scale = config.minimum_scale if hasattr(config, "minimum_scale") else 1e-5
1012
+
1013
+ def forward(
1014
+ self, data: torch.Tensor, observed_indicator: torch.Tensor
1015
+ ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
1016
+ """
1017
+ Parameters:
1018
+ data (`torch.Tensor` of shape `(batch_size, sequence_length, num_input_channels)`):
1019
+ input for Batch norm calculation
1020
+ observed_indicator (`torch.BoolTensor` of shape `(batch_size, sequence_length, num_input_channels)`):
1021
+ Calculating the scale on the observed indicator.
1022
+ Returns:
1023
+ tuple of `torch.Tensor` of shapes
1024
+ (`(batch_size, sequence_length, num_input_channels)`,`(batch_size, 1, num_input_channels)`,
1025
+ `(batch_size, 1, num_input_channels)`)
1026
+ """
1027
+ denominator = observed_indicator.sum(self.dim, keepdim=self.keepdim)
1028
+ denominator = denominator.clamp_min(1.0)
1029
+ loc = (data * observed_indicator).sum(self.dim, keepdim=self.keepdim) / denominator
1030
+
1031
+ variance = (((data - loc) * observed_indicator) ** 2).sum(self.dim, keepdim=self.keepdim) / denominator
1032
+ scale = torch.sqrt(variance + self.minimum_scale)
1033
+ return (data - loc) / scale, loc, scale
1034
+
1035
+
1036
+ # Copied from transformers.models.time_series_transformer.modeling_time_series_transformer.TimeSeriesMeanScaler with TimeSeriesTransformer->PatchTST,TimeSeries->PatchTST
1037
+ class PatchTSTMeanScaler(nn.Module):
1038
+ """
1039
+ Computes a scaling factor as the weighted average absolute value along the first dimension, and scales the data
1040
+ accordingly.
1041
+ """
1042
+
1043
+ def __init__(self, config: PatchTSTConfig):
1044
+ super().__init__()
1045
+ self.dim = config.scaling_dim if hasattr(config, "scaling_dim") else 1
1046
+ self.keepdim = config.keepdim if hasattr(config, "keepdim") else True
1047
+ self.minimum_scale = config.minimum_scale if hasattr(config, "minimum_scale") else 1e-10
1048
+ self.default_scale = config.default_scale if hasattr(config, "default_scale") else None
1049
+
1050
+ def forward(
1051
+ self, data: torch.Tensor, observed_indicator: torch.Tensor
1052
+ ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
1053
+ """
1054
+ Parameters:
1055
+ data (`torch.Tensor` of shape `(batch_size, sequence_length, num_input_channels)`):
1056
+ input for Batch norm calculation
1057
+ observed_indicator (`torch.BoolTensor` of shape `(batch_size, sequence_length, num_input_channels)`):
1058
+ Calculating the scale on the observed indicator.
1059
+ Returns:
1060
+ tuple of `torch.Tensor` of shapes
1061
+ (`(batch_size, sequence_length, num_input_channels)`,`(batch_size, 1, num_input_channels)`,
1062
+ `(batch_size, 1, num_input_channels)`)
1063
+ """
1064
+ ts_sum = (data * observed_indicator).abs().sum(self.dim, keepdim=True)
1065
+ num_observed = observed_indicator.sum(self.dim, keepdim=True)
1066
+
1067
+ scale = ts_sum / torch.clamp(num_observed, min=1)
1068
+
1069
+ # If `default_scale` is provided, we use it, otherwise we use the scale
1070
+ # of the batch.
1071
+ if self.default_scale is None:
1072
+ batch_sum = ts_sum.sum(dim=0)
1073
+ batch_observations = torch.clamp(num_observed.sum(0), min=1)
1074
+ default_scale = torch.squeeze(batch_sum / batch_observations)
1075
+ else:
1076
+ default_scale = self.default_scale * torch.ones_like(scale)
1077
+
1078
+ # apply default scale where there are no observations
1079
+ scale = torch.where(num_observed > 0, scale, default_scale)
1080
+
1081
+ # ensure the scale is at least `self.minimum_scale`
1082
+ scale = torch.clamp(scale, min=self.minimum_scale)
1083
+ scaled_data = data / scale
1084
+
1085
+ if not self.keepdim:
1086
+ scale = scale.squeeze(dim=self.dim)
1087
+
1088
+ return scaled_data, torch.zeros_like(scale), scale
1089
+
1090
+
1091
+ # Copied from transformers.models.time_series_transformer.modeling_time_series_transformer.TimeSeriesNOPScaler with TimeSeriesTransformer->PatchTST,TimeSeries->PatchTST
1092
+ class PatchTSTNOPScaler(nn.Module):
1093
+ """
1094
+ Assigns a scaling factor equal to 1 along the first dimension, and therefore applies no scaling to the input data.
1095
+ """
1096
+
1097
+ def __init__(self, config: PatchTSTConfig):
1098
+ super().__init__()
1099
+ self.dim = config.scaling_dim if hasattr(config, "scaling_dim") else 1
1100
+ self.keepdim = config.keepdim if hasattr(config, "keepdim") else True
1101
+
1102
+ def forward(
1103
+ self, data: torch.Tensor, observed_indicator: torch.Tensor = None
1104
+ ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
1105
+ """
1106
+ Parameters:
1107
+ data (`torch.Tensor` of shape `(batch_size, sequence_length, num_input_channels)`):
1108
+ input for Batch norm calculation
1109
+ Returns:
1110
+ tuple of `torch.Tensor` of shapes
1111
+ (`(batch_size, sequence_length, num_input_channels)`,`(batch_size, 1, num_input_channels)`,
1112
+ `(batch_size, 1, num_input_channels)`)
1113
+ """
1114
+ scale = torch.ones_like(data, requires_grad=False).mean(dim=self.dim, keepdim=self.keepdim)
1115
+ loc = torch.zeros_like(data, requires_grad=False).mean(dim=self.dim, keepdim=self.keepdim)
1116
+ return data, loc, scale
1117
+
1118
+
1119
+ class PatchTSTScaler(nn.Module):
1120
+ def __init__(self, config: PatchTSTConfig):
1121
+ super().__init__()
1122
+ if config.scaling == "mean" or config.scaling is True:
1123
+ self.scaler = PatchTSTMeanScaler(config)
1124
+ elif config.scaling == "std":
1125
+ self.scaler = PatchTSTStdScaler(config)
1126
+ else:
1127
+ self.scaler = PatchTSTNOPScaler(config)
1128
+
1129
+ def forward(
1130
+ self, data: torch.Tensor, observed_indicator: torch.Tensor
1131
+ ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
1132
+ """
1133
+ Parameters:
1134
+ data (`torch.Tensor` of shape `(batch_size, sequence_length, num_input_channels)`):
1135
+ Input for scaler calculation
1136
+ observed_indicator (`torch.BoolTensor` of shape `(batch_size, sequence_length, num_input_channels)`):
1137
+ Calculating the scale on the observed indicator.
1138
+ Returns:
1139
+ tuple of `torch.Tensor` of shapes
1140
+ (`(batch_size, sequence_length, num_input_channels)`,`(batch_size, 1, num_input_channels)`,
1141
+ `(batch_size, 1, um_input_channels)`)
1142
+ """
1143
+ data, loc, scale = self.scaler(data, observed_indicator)
1144
+ return data, loc, scale
1145
+
1146
+
1147
+ @add_start_docstrings(
1148
+ "The bare PatchTST Model outputting raw hidden-states without any specific head.",
1149
+ PATCHTST_START_DOCSTRING,
1150
+ )
1151
+ class PatchTSTModel(PatchTSTPreTrainedModel):
1152
+ def __init__(self, config: PatchTSTConfig):
1153
+ super().__init__(config)
1154
+
1155
+ self.scaler = PatchTSTScaler(config)
1156
+ self.patchifier = PatchTSTPatchify(config)
1157
+ self.do_mask_input = config.do_mask_input
1158
+ # get num_patches information from PatchTSTPatchify
1159
+ num_patches = self.patchifier.num_patches
1160
+
1161
+ if self.do_mask_input:
1162
+ self.masking = PatchTSTMasking(config)
1163
+ else:
1164
+ self.masking = nn.Identity()
1165
+ self.encoder = PatchTSTEncoder(config, num_patches=num_patches)
1166
+
1167
+ # Initialize weights and apply final processing
1168
+ self.post_init()
1169
+
1170
+ def forward(
1171
+ self,
1172
+ past_values: torch.Tensor,
1173
+ past_observed_mask: Optional[torch.Tensor] = None,
1174
+ future_values: Optional[torch.Tensor] = None,
1175
+ output_hidden_states: Optional[bool] = None,
1176
+ output_attentions: Optional[bool] = None,
1177
+ return_dict: Optional[bool] = None,
1178
+ ) -> Union[Tuple, PatchTSTModelOutput]:
1179
+ r"""
1180
+ Parameters:
1181
+ past_values (`torch.Tensor` of shape `(bs, sequence_length, num_input_channels)`, *required*):
1182
+ Input sequence to the model
1183
+ past_observed_mask (`torch.BoolTensor` of shape `(batch_size, sequence_length, num_input_channels)`, *optional*):
1184
+ Boolean mask to indicate which `past_values` were observed and which were missing. Mask values selected
1185
+ in `[0, 1]`:
1186
+
1187
+ - 1 for values that are **observed**,
1188
+ - 0 for values that are **missing** (i.e. NaNs that were replaced by zeros).
1189
+ future_values (`torch.BoolTensor` of shape `(batch_size, prediction_length, num_input_channels)`, *optional*):
1190
+ Future target values associated with the `past_values`
1191
+ output_hidden_states (`bool`, *optional*):
1192
+ Whether or not to return the hidden states of all layers
1193
+ output_attentions (`bool`, *optional*):
1194
+ Whether or not to return the output attention of all layers
1195
+ return_dict (`bool`, *optional*):
1196
+ Whether or not to return a `ModelOutput` instead of a plain tuple.
1197
+
1198
+ Returns:
1199
+ `PatchTSTModelOutput` or tuple of `torch.Tensor` (if `return_dict`=False or `config.return_dict`=False)
1200
+
1201
+ Examples:
1202
+
1203
+ ```python
1204
+ >>> from huggingface_hub import hf_hub_download
1205
+ >>> import torch
1206
+ >>> from transformers import PatchTSTModel
1207
+
1208
+ >>> file = hf_hub_download(
1209
+ ... repo_id="hf-internal-testing/etth1-hourly-batch", filename="train-batch.pt", repo_type="dataset"
1210
+ ... )
1211
+ >>> batch = torch.load(file)
1212
+
1213
+ >>> model = PatchTSTModel.from_pretrained("namctin/patchtst_etth1_pretrain")
1214
+
1215
+ >>> # during training, one provides both past and future values
1216
+ >>> outputs = model(
1217
+ ... past_values=batch["past_values"],
1218
+ ... future_values=batch["future_values"],
1219
+ ... )
1220
+
1221
+ >>> last_hidden_state = outputs.last_hidden_state
1222
+ ```"""
1223
+
1224
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1225
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1226
+ output_hidden_states = (
1227
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1228
+ )
1229
+
1230
+ if past_observed_mask is None:
1231
+ past_observed_mask = torch.ones_like(past_values)
1232
+
1233
+ # x: tensor [bs x sequence_length x num_input_channels]
1234
+ scaled_past_values, loc, scale = self.scaler(past_values, past_observed_mask)
1235
+
1236
+ # patched_values: [bs x num_input_channels x num_patches x patch_length] for pretrain
1237
+ patched_values = self.patchifier(scaled_past_values)
1238
+ if self.do_mask_input:
1239
+ masked_values, mask = self.masking(patched_values)
1240
+ else:
1241
+ masked_values, mask = self.masking(patched_values), None
1242
+
1243
+ encoder_output = self.encoder(
1244
+ patch_input=masked_values, output_hidden_states=output_hidden_states, output_attentions=output_attentions
1245
+ )
1246
+
1247
+ if not return_dict:
1248
+ outputs = (encoder_output.last_hidden_state, encoder_output.hidden_states, encoder_output.attentions)
1249
+ outputs = outputs + (mask, loc, scale, patched_values)
1250
+ return tuple(v for v in outputs if v is not None)
1251
+
1252
+ return PatchTSTModelOutput(
1253
+ last_hidden_state=encoder_output.last_hidden_state,
1254
+ hidden_states=encoder_output.hidden_states,
1255
+ attentions=encoder_output.attentions,
1256
+ mask=mask,
1257
+ loc=loc,
1258
+ scale=scale,
1259
+ patch_input=patched_values,
1260
+ )
1261
+
1262
+
1263
+ class PatchTSTMaskPretrainHead(nn.Module):
1264
+ """
1265
+ Pretraining head for mask modelling
1266
+ """
1267
+
1268
+ def __init__(self, config: PatchTSTConfig):
1269
+ super().__init__()
1270
+ self.dropout = nn.Dropout(config.dropout)
1271
+ self.linear = nn.Linear(config.d_model, config.patch_length)
1272
+ self.use_cls_token = config.use_cls_token
1273
+
1274
+ def forward(self, embedding: torch.Tensor) -> torch.Tensor:
1275
+ """
1276
+ Parameters:
1277
+ embedding (`torch.Tensor` of shape `(bs, num_channels, num_patches, d_model)` or
1278
+ `(bs, num_channels, num_patches+1, d_model)` if `cls_token` is set to True, *required*):
1279
+ Embedding from the model
1280
+ Returns:
1281
+ `torch.Tensor` of shape `(bs, num_channels, num_patches, d_model)` or
1282
+ `(bs, num_channels, num_patches+1, d_model)` if `cls_token` is set to True
1283
+
1284
+ """
1285
+ embedding = self.linear(self.dropout(embedding)) # [bs x num_channels x num_patches x patch_length]
1286
+ if self.use_cls_token:
1287
+ embedding = embedding[:, :, 1:, :] # remove the first cls token
1288
+ return embedding
1289
+
1290
+
1291
+ @add_start_docstrings(
1292
+ "The PatchTST for pretrain model.",
1293
+ PATCHTST_START_DOCSTRING,
1294
+ )
1295
+ class PatchTSTForPretraining(PatchTSTPreTrainedModel):
1296
+ def __init__(self, config: PatchTSTConfig):
1297
+ super().__init__(config)
1298
+
1299
+ config.do_mask_input = True
1300
+ self.model = PatchTSTModel(config=config)
1301
+ self.head = PatchTSTMaskPretrainHead(config)
1302
+
1303
+ # Initialize weights and apply final processing
1304
+ self.post_init()
1305
+
1306
+ def forward(
1307
+ self,
1308
+ past_values: torch.Tensor,
1309
+ past_observed_mask: Optional[torch.Tensor] = None,
1310
+ output_hidden_states: Optional[bool] = None,
1311
+ output_attentions: Optional[bool] = None,
1312
+ return_dict: Optional[bool] = None,
1313
+ ) -> Union[Tuple, PatchTSTForPretrainingOutput]:
1314
+ r"""
1315
+ Parameters:
1316
+ past_values (`torch.Tensor` of shape `(bs, sequence_length, num_input_channels)`, *required*):
1317
+ Input sequence to the model
1318
+ past_observed_mask (`torch.BoolTensor` of shape `(batch_size, sequence_length, num_input_channels)`, *optional*):
1319
+ Boolean mask to indicate which `past_values` were observed and which were missing. Mask values selected
1320
+ in `[0, 1]`:
1321
+
1322
+ - 1 for values that are **observed**,
1323
+ - 0 for values that are **missing** (i.e. NaNs that were replaced by zeros).
1324
+ output_hidden_states (`bool`, *optional*):
1325
+ Whether or not to return the hidden states of all layers
1326
+ output_attentions (`bool`, *optional*):
1327
+ Whether or not to return the output attention of all layers
1328
+ return_dict (`bool`, *optional*): Whether or not to return a `ModelOutput` instead of a plain tuple.
1329
+
1330
+ Returns:
1331
+ `PatchTSTForPretrainingOutput` or tuple of `torch.Tensor` (if `return_dict`=False or
1332
+ `config.return_dict`=False)
1333
+
1334
+ Examples:
1335
+
1336
+ ```python
1337
+ >>> from huggingface_hub import hf_hub_download
1338
+ >>> import torch
1339
+ >>> from transformers import PatchTSTConfig, PatchTSTForPretraining
1340
+
1341
+ >>> file = hf_hub_download(
1342
+ ... repo_id="hf-internal-testing/etth1-hourly-batch", filename="train-batch.pt", repo_type="dataset"
1343
+ ... )
1344
+ >>> batch = torch.load(file)
1345
+
1346
+ >>> # Config for random mask pretraining
1347
+ >>> config = PatchTSTConfig(
1348
+ ... num_input_channels=7,
1349
+ ... context_length=512,
1350
+ ... patch_length=12,
1351
+ ... stride=12,
1352
+ ... mask_type='random',
1353
+ ... random_mask_ratio=0.4,
1354
+ ... use_cls_token=True,
1355
+ ... )
1356
+ >>> # Config for forecast mask pretraining
1357
+ >>> config = PatchTSTConfig(
1358
+ ... num_input_channels=7,
1359
+ ... context_length=512,
1360
+ ... patch_length=12,
1361
+ ... stride=12,
1362
+ ... mask_type='forecast',
1363
+ ... num_forecast_mask_patches=5,
1364
+ ... use_cls_token=True,
1365
+ ... )
1366
+ >>> model = PatchTSTForPretraining(config)
1367
+
1368
+ >>> # during training, one provides both past and future values
1369
+ >>> outputs = model(past_values=batch["past_values"])
1370
+
1371
+ >>> loss = outputs.loss
1372
+ >>> loss.backward()
1373
+ ```"""
1374
+
1375
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1376
+
1377
+ # past_values: [bs x num_channels x num_patches x d_model] or
1378
+ # [bs x num_channels x (num_patches+1) x d_model] if use cls_token
1379
+ model_output = self.model(
1380
+ past_values=past_values,
1381
+ past_observed_mask=past_observed_mask,
1382
+ output_hidden_states=output_hidden_states,
1383
+ output_attentions=output_attentions,
1384
+ return_dict=True,
1385
+ )
1386
+
1387
+ # last_hidden_state: [bs x num_channels x num_patches x patch_length] or
1388
+ # [bs x num_channels x (num_patches+1) x patch_length] if use cls_token
1389
+ x_hat = self.head(model_output.last_hidden_state)
1390
+
1391
+ # calculate masked_loss
1392
+ loss = nn.MSELoss(reduction="none")
1393
+ loss_val = loss(x_hat, model_output.patch_input)
1394
+ masked_loss = (loss_val.mean(dim=-1) * model_output.mask).sum() / (model_output.mask.sum() + 1e-10)
1395
+
1396
+ encoder_states = model_output.hidden_states
1397
+ if not return_dict:
1398
+ outputs = (x_hat,) + model_output[1:-4]
1399
+ outputs = (masked_loss,) + outputs if masked_loss is not None else outputs
1400
+ return outputs
1401
+ return PatchTSTForPretrainingOutput(
1402
+ loss=masked_loss, prediction_output=x_hat, hidden_states=encoder_states, attentions=model_output.attentions
1403
+ )
1404
+
1405
+
1406
+ class PatchTSTClassificationHead(nn.Module):
1407
+ def __init__(self, config: PatchTSTConfig):
1408
+ super().__init__()
1409
+ self.use_cls_token = config.use_cls_token
1410
+ self.pooling_type = config.pooling_type
1411
+ self.flatten = nn.Flatten(start_dim=1)
1412
+ self.dropout = nn.Dropout(config.head_dropout) if config.head_dropout > 0 else nn.Identity()
1413
+ self.linear = nn.Linear(config.num_input_channels * config.d_model, config.num_targets)
1414
+
1415
+ def forward(self, embedding: torch.Tensor):
1416
+ """
1417
+ Parameters:
1418
+ embedding (`torch.Tensor` of shape `(bs, num_channels, num_patches, d_model)` or
1419
+ `(bs, num_channels, num_patches+1, d_model)` if `cls_token` is set to True, *required*):
1420
+ Embedding from the model
1421
+ Returns:
1422
+ `torch.Tensor` of shape `(bs, num_targets)`
1423
+
1424
+ """
1425
+ if self.use_cls_token:
1426
+ # use the first output token, pooled_embedding: bs x num_channels x d_model
1427
+ pooled_embedding = embedding[:, :, 0, :]
1428
+ elif self.pooling_type == "mean":
1429
+ # pooled_embedding: [bs x num_channels x d_model]
1430
+ pooled_embedding = embedding.mean(dim=2)
1431
+ elif self.pooling_type == "max":
1432
+ # pooled_embedding: [bs x num_channels x d_model]
1433
+ pooled_embedding = embedding.max(dim=2)
1434
+ else:
1435
+ raise ValueError(f"pooling operator {self.pooling_type} is not implemented yet")
1436
+ # pooled_embedding: bs x num_channels * d_model
1437
+ pooled_embedding = self.flatten(pooled_embedding)
1438
+ # output: bs x n_classes
1439
+ output = self.linear(self.dropout(pooled_embedding))
1440
+ return output
1441
+
1442
+
1443
+ @add_start_docstrings(
1444
+ "The PatchTST for classification model.",
1445
+ PATCHTST_START_DOCSTRING,
1446
+ )
1447
+ class PatchTSTForClassification(PatchTSTPreTrainedModel):
1448
+ def __init__(self, config: PatchTSTConfig):
1449
+ super().__init__(config)
1450
+
1451
+ # Turn off masking
1452
+ if config.do_mask_input:
1453
+ logger.warning("Setting `do_mask_input` parameter to False.")
1454
+ config.do_mask_input = False
1455
+
1456
+ self.model = PatchTSTModel(config)
1457
+ self.head = PatchTSTClassificationHead(config)
1458
+
1459
+ # Initialize weights and apply final processing
1460
+ self.post_init()
1461
+
1462
+ def forward(
1463
+ self,
1464
+ past_values: torch.Tensor,
1465
+ target_values: torch.Tensor = None,
1466
+ past_observed_mask: Optional[bool] = None,
1467
+ output_hidden_states: Optional[bool] = None,
1468
+ output_attentions: Optional[bool] = None,
1469
+ return_dict: Optional[bool] = None,
1470
+ ) -> Union[tuple, PatchTSTForClassificationOutput]:
1471
+ r"""
1472
+ Parameters:
1473
+ past_values (`torch.Tensor` of shape `(bs, sequence_length, num_input_channels)`, *required*):
1474
+ Input sequence to the model
1475
+ target_values (`torch.Tensor`, *optional*):
1476
+ Labels associates with the `past_values`
1477
+ past_observed_mask (`torch.BoolTensor` of shape `(batch_size, sequence_length, num_input_channels)`, *optional*):
1478
+ Boolean mask to indicate which `past_values` were observed and which were missing. Mask values selected
1479
+ in `[0, 1]`:
1480
+
1481
+ - 1 for values that are **observed**,
1482
+ - 0 for values that are **missing** (i.e. NaNs that were replaced by zeros).
1483
+ output_hidden_states (`bool`, *optional*):
1484
+ Whether or not to return the hidden states of all layers
1485
+ output_attentions (`bool`, *optional*):
1486
+ Whether or not to return the output attention of all layers
1487
+ return_dict (`bool`, *optional*):
1488
+ Whether or not to return a `ModelOutput` instead of a plain tuple.
1489
+
1490
+ Returns:
1491
+ `PatchTSTForClassificationOutput` or tuple of `torch.Tensor` (if `return_dict`=False or
1492
+ `config.return_dict`=False)
1493
+
1494
+ Examples:
1495
+
1496
+ ```python
1497
+ >>> from transformers import PatchTSTConfig, PatchTSTForClassification
1498
+
1499
+ >>> # classification task with two input channel2 and 3 classes
1500
+ >>> config = PatchTSTConfig(
1501
+ ... num_input_channels=2,
1502
+ ... num_targets=3,
1503
+ ... context_length=512,
1504
+ ... patch_length=12,
1505
+ ... stride=12,
1506
+ ... use_cls_token=True,
1507
+ ... )
1508
+ >>> model = PatchTSTForClassification(config=config)
1509
+
1510
+ >>> # during inference, one only provides past values
1511
+ >>> past_values = torch.randn(20, 512, 2)
1512
+ >>> outputs = model(past_values=past_values)
1513
+ >>> labels = outputs.prediction_logits
1514
+ ```"""
1515
+
1516
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1517
+
1518
+ model_output = self.model(
1519
+ past_values=past_values,
1520
+ past_observed_mask=past_observed_mask,
1521
+ output_hidden_states=output_hidden_states,
1522
+ output_attentions=output_attentions,
1523
+ return_dict=True,
1524
+ )
1525
+ y_hat = self.head(model_output.last_hidden_state)
1526
+
1527
+ loss_val = None
1528
+ if target_values is not None:
1529
+ loss = nn.CrossEntropyLoss()
1530
+ loss_val = loss(y_hat, target_values)
1531
+
1532
+ if not return_dict:
1533
+ outputs = (y_hat,) + model_output[1:-3]
1534
+ outputs = (loss_val,) + outputs if loss_val is not None else outputs
1535
+ return outputs
1536
+ return PatchTSTForClassificationOutput(
1537
+ loss=loss_val,
1538
+ prediction_logits=y_hat,
1539
+ hidden_states=model_output.hidden_states,
1540
+ attentions=model_output.attentions,
1541
+ )
1542
+
1543
+
1544
+ @add_start_docstrings(
1545
+ "The PatchTST for regression Model.",
1546
+ PATCHTST_START_DOCSTRING,
1547
+ )
1548
+ class PatchTSTPredictionHead(nn.Module):
1549
+ def __init__(self, config: PatchTSTConfig, num_patches, distribution_output=None):
1550
+ super().__init__()
1551
+
1552
+ self.share_projection = config.share_projection
1553
+ self.num_input_channels = config.num_input_channels
1554
+ self.use_cls_token = config.use_cls_token
1555
+ self.pooling_type = config.pooling_type
1556
+ if self.pooling_type or self.use_cls_token:
1557
+ head_dim = config.d_model
1558
+ else:
1559
+ head_dim = config.d_model * num_patches
1560
+
1561
+ if not self.share_projection:
1562
+ # if each channel has its own head
1563
+ self.projections = nn.ModuleList()
1564
+ self.dropouts = nn.ModuleList()
1565
+ self.flattens = nn.ModuleList()
1566
+ for i in range(self.num_input_channels):
1567
+ self.flattens.append(nn.Flatten(start_dim=2))
1568
+ if distribution_output is None:
1569
+ # use linear head
1570
+ self.projections.append(nn.Linear(head_dim, config.prediction_length))
1571
+ else:
1572
+ # use distribution head
1573
+ self.projections.append(distribution_output.get_parameter_projection(head_dim))
1574
+ self.dropouts.append(nn.Dropout(config.head_dropout) if config.head_dropout > 0 else nn.Identity())
1575
+ else:
1576
+ # all the channels share the same head
1577
+ self.flatten = nn.Flatten(start_dim=2)
1578
+ if distribution_output is None:
1579
+ # use linear head
1580
+ self.projection = nn.Linear(head_dim, config.prediction_length)
1581
+ else:
1582
+ # use distribution head
1583
+ self.projection = distribution_output.get_parameter_projection(head_dim)
1584
+ self.dropout = nn.Dropout(config.head_dropout) if config.head_dropout > 0 else nn.Identity()
1585
+
1586
+ def forward(self, embedding: torch.Tensor):
1587
+ """
1588
+ Parameters:
1589
+ embedding (`torch.Tensor` of shape `(bs, num_channels, num_patches, d_model)` or
1590
+ `(bs, num_channels, num_patches+1, d_model)` if `cls_token` is set to True, *required*):
1591
+ Embedding from the model
1592
+ Returns:
1593
+ `torch.Tensor` of shape `(bs, forecast_len, num_channels)`
1594
+
1595
+ """
1596
+ if self.use_cls_token:
1597
+ # pooled_embedding: [bs x num_channels x d_model]
1598
+ pooled_embedding = embedding[:, :, 0, :]
1599
+ else:
1600
+ if self.pooling_type == "mean":
1601
+ # pooled_embedding: [bs x num_channels x d_model]
1602
+ pooled_embedding = embedding.mean(dim=2)
1603
+ elif self.pooling_type == "max":
1604
+ # pooled_embedding: [bs x num_channels x d_model]
1605
+ pooled_embedding = embedding.max(dim=2)
1606
+ else:
1607
+ # pooled_embedding: [bs x num_channels x num_patches x d_model]
1608
+ pooled_embedding = embedding
1609
+
1610
+ if not self.share_projection:
1611
+ output = []
1612
+ for i in range(self.num_input_channels):
1613
+ # pooled_embedding: [bs x (d_model * num_patches)] or [bs x d_model)]
1614
+ pooled_embedding = self.flattens[i](pooled_embedding[:, i, :])
1615
+ pooled_embedding = self.dropouts[i](pooled_embedding)
1616
+ # pooled_embedding: [bs x forecast_len]
1617
+ # or tuple ([bs x forecast_len], [bs x forecast_len]) if using distribution head
1618
+ pooled_embedding = self.projections[i](pooled_embedding)
1619
+ output.append(pooled_embedding)
1620
+ # output: [bs x num_channels x forecast_len]
1621
+ output = torch.stack(output, dim=1)
1622
+ else:
1623
+ # pooled_embedding: [bs x num_channels x (d_model * num_patches)] or [bs x num_channels x d_model)]
1624
+ pooled_embedding = self.flatten(pooled_embedding)
1625
+ pooled_embedding = self.dropout(pooled_embedding)
1626
+ # output: [bs x num_channels x forecast_len] or
1627
+ # tuple ([bs x num_channels x forecast_len], [bs x num_channels x forecast_len]) if using distribution head
1628
+ output = self.projection(pooled_embedding)
1629
+
1630
+ if isinstance(output, tuple):
1631
+ # output: ([bs x forecast_len x num_channels], [bs x forecast_len x num_channels])
1632
+ output = tuple(z.transpose(2, 1) for z in output)
1633
+ else:
1634
+ output = output.transpose(2, 1) # [bs x forecast_len x num_channels]
1635
+ return output
1636
+
1637
+
1638
+ @add_start_docstrings(
1639
+ "The PatchTST for prediction model.",
1640
+ PATCHTST_START_DOCSTRING,
1641
+ )
1642
+ class PatchTSTForPrediction(PatchTSTPreTrainedModel):
1643
+ def __init__(self, config: PatchTSTConfig):
1644
+ super().__init__(config)
1645
+
1646
+ # Turn off masking
1647
+ if config.do_mask_input:
1648
+ logger.warning("Setting `do_mask_input` parameter to False.")
1649
+ config.do_mask_input = False
1650
+
1651
+ self.model = PatchTSTModel(config)
1652
+
1653
+ if config.loss == "mse":
1654
+ self.distribution_output = None
1655
+ else:
1656
+ if config.distribution_output == "student_t":
1657
+ self.distribution_output = StudentTOutput(dim=config.prediction_length)
1658
+ elif config.distribution_output == "normal":
1659
+ self.distribution_output = NormalOutput(dim=config.prediction_length)
1660
+ elif config.distribution_output == "negative_binomial":
1661
+ self.distribution_output = NegativeBinomialOutput(dim=config.prediction_length)
1662
+ else:
1663
+ raise ValueError(f"Unknown distribution output {config.distribution_output}")
1664
+
1665
+ self.head = PatchTSTPredictionHead(
1666
+ config, self.model.patchifier.num_patches, distribution_output=self.distribution_output
1667
+ )
1668
+
1669
+ # Initialize weights and apply final processing
1670
+ self.post_init()
1671
+
1672
+ def forward(
1673
+ self,
1674
+ past_values: torch.Tensor,
1675
+ past_observed_mask: Optional[torch.Tensor] = None,
1676
+ future_values: Optional[torch.Tensor] = None,
1677
+ output_hidden_states: Optional[bool] = None,
1678
+ output_attentions: Optional[bool] = None,
1679
+ return_dict: Optional[bool] = None,
1680
+ ) -> Union[Tuple, PatchTSTForPredictionOutput]:
1681
+ r"""
1682
+ Parameters:
1683
+ past_values (`torch.Tensor` of shape `(bs, sequence_length, num_input_channels)`, *required*):
1684
+ Input sequence to the model
1685
+ past_observed_mask (`torch.BoolTensor` of shape `(batch_size, sequence_length, num_input_channels)`, *optional*):
1686
+ Boolean mask to indicate which `past_values` were observed and which were missing. Mask values selected
1687
+ in `[0, 1]`:
1688
+
1689
+ - 1 for values that are **observed**,
1690
+ - 0 for values that are **missing** (i.e. NaNs that were replaced by zeros).
1691
+ future_values (`torch.Tensor` of shape `(bs, forecast_len, num_input_channels)`, *optional*):
1692
+ Future target values associated with the `past_values`
1693
+ output_hidden_states (`bool`, *optional*):
1694
+ Whether or not to return the hidden states of all layers
1695
+ output_attentions (`bool`, *optional*):
1696
+ Whether or not to return the output attention of all layers
1697
+ return_dict (`bool`, *optional*):
1698
+ Whether or not to return a `ModelOutput` instead of a plain tuple.
1699
+
1700
+ Returns:
1701
+ `PatchTSTForPredictionOutput` or tuple of `torch.Tensor` (if `return_dict`=False or
1702
+ `config.return_dict`=False)
1703
+
1704
+ Examples:
1705
+
1706
+ ```python
1707
+ >>> from huggingface_hub import hf_hub_download
1708
+ >>> import torch
1709
+ >>> from transformers import PatchTSTConfig, PatchTSTForPrediction
1710
+
1711
+ >>> file = hf_hub_download(
1712
+ ... repo_id="hf-internal-testing/etth1-hourly-batch", filename="train-batch.pt", repo_type="dataset"
1713
+ ... )
1714
+ >>> batch = torch.load(file)
1715
+
1716
+ >>> # Prediction task with 7 input channels and prediction length is 96
1717
+ >>> model = PatchTSTForPrediction.from_pretrained("namctin/patchtst_etth1_forecast")
1718
+
1719
+ >>> # during training, one provides both past and future values
1720
+ >>> outputs = model(
1721
+ ... past_values=batch["past_values"],
1722
+ ... future_values=batch["future_values"],
1723
+ ... )
1724
+
1725
+ >>> loss = outputs.loss
1726
+ >>> loss.backward()
1727
+
1728
+ >>> # during inference, one only provides past values, the model outputs future values
1729
+ >>> outputs = model(past_values=batch["past_values"])
1730
+ >>> prediction_outputs = outputs.prediction_outputs
1731
+ ```"""
1732
+
1733
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1734
+
1735
+ # get model output
1736
+ model_output = self.model(
1737
+ past_values=past_values,
1738
+ past_observed_mask=past_observed_mask,
1739
+ output_hidden_states=output_hidden_states,
1740
+ output_attentions=output_attentions,
1741
+ return_dict=True,
1742
+ )
1743
+ # get output head
1744
+ y_hat = self.head(model_output.last_hidden_state)
1745
+
1746
+ loss_val = None
1747
+
1748
+ if self.distribution_output:
1749
+ y_hat_out = y_hat
1750
+ else:
1751
+ y_hat_out = y_hat * model_output.scale + model_output.loc
1752
+
1753
+ if future_values is not None:
1754
+ if self.distribution_output:
1755
+ distribution = self.distribution_output.distribution(
1756
+ y_hat, loc=model_output.loc, scale=model_output.scale
1757
+ )
1758
+ loss_val = nll(distribution, future_values)
1759
+ # take average of the loss
1760
+ loss_val = weighted_average(loss_val)
1761
+ else:
1762
+ loss = nn.MSELoss(reduction="mean")
1763
+ loss_val = loss(y_hat_out, future_values)
1764
+
1765
+ loc = model_output.loc
1766
+ scale = model_output.scale
1767
+
1768
+ if not return_dict:
1769
+ outputs = (y_hat_out,) + model_output[1:-1]
1770
+ outputs = (loss_val,) + outputs if loss_val is not None else outputs
1771
+ return outputs
1772
+ return PatchTSTForPredictionOutput(
1773
+ loss=loss_val,
1774
+ prediction_outputs=y_hat_out,
1775
+ hidden_states=model_output.hidden_states,
1776
+ attentions=model_output.attentions,
1777
+ loc=loc,
1778
+ scale=scale,
1779
+ )
1780
+
1781
+ def generate(
1782
+ self,
1783
+ past_values: torch.Tensor,
1784
+ past_observed_mask: Optional[torch.Tensor] = None,
1785
+ ) -> SamplePatchTSTOutput:
1786
+ """
1787
+ Generate sequences of sample predictions from a model with a probability distribution head.
1788
+
1789
+ Parameters:
1790
+ past_values (`torch.FloatTensor` of shape `(batch_size, sequence_length, num_input_channels)`):
1791
+ Past values of the time series that serves as context in order to predict the future.
1792
+ past_observed_mask (`torch.BoolTensor` of shape `(batch_size, sequence_length, num_input_channels)`, *optional*):
1793
+ Boolean mask to indicate which `past_values` were observed and which were missing. Mask values selected
1794
+ in `[0, 1]`:
1795
+
1796
+ - 1 for values that are **observed**,
1797
+ - 0 for values that are **missing** (i.e. NaNs that were replaced by zeros).
1798
+
1799
+ Return:
1800
+ [`SamplePatchTSTOutput`] where the outputs `sequences` tensor will have shape `(batch_size, number of
1801
+ samples, prediction_length, 1)` or `(batch_size, number of samples, prediction_length, num_input_channels)`
1802
+ for multivariate predictions.
1803
+ """
1804
+ # get number of samples
1805
+ num_parallel_samples = self.config.num_parallel_samples
1806
+
1807
+ # get model output
1808
+ outputs = self(
1809
+ past_values=past_values,
1810
+ future_values=None,
1811
+ past_observed_mask=past_observed_mask,
1812
+ output_hidden_states=False,
1813
+ )
1814
+ if self.distribution_output:
1815
+ # get distribution
1816
+ distribution = self.distribution_output.distribution(
1817
+ outputs.prediction_outputs, loc=outputs.loc, scale=outputs.scale
1818
+ )
1819
+ # get samples: list of [bs x forecast_len x num_channels]
1820
+ samples = [distribution.sample() for _ in range(num_parallel_samples)]
1821
+ # samples: [bs x num_samples x forecast_len x num_channels]
1822
+ samples = torch.stack(samples, dim=1)
1823
+ else:
1824
+ samples = outputs.prediction_outputs.unsqueeze(1)
1825
+
1826
+ return SamplePatchTSTOutput(sequences=samples)
1827
+
1828
+
1829
+ class PatchTSTRegressionHead(nn.Module):
1830
+ """
1831
+ Regression head
1832
+ """
1833
+
1834
+ def __init__(self, config: PatchTSTConfig, distribution_output=None):
1835
+ super().__init__()
1836
+ self.y_range = config.output_range
1837
+ self.use_cls_token = config.use_cls_token
1838
+ self.pooling_type = config.pooling_type
1839
+ self.distribution_output = distribution_output
1840
+
1841
+ head_dim = config.num_input_channels * config.d_model
1842
+
1843
+ self.flatten = nn.Flatten(start_dim=1)
1844
+ self.dropout = nn.Dropout(config.head_dropout) if config.head_dropout > 0 else nn.Identity()
1845
+
1846
+ if distribution_output is None:
1847
+ self.projection = nn.Linear(head_dim, config.num_targets)
1848
+ else:
1849
+ self.projection = distribution_output.get_parameter_projection(head_dim)
1850
+
1851
+ def forward(self, embedding: torch.Tensor):
1852
+ """
1853
+ Parameters:
1854
+ embedding (`torch.Tensor` of shape `(bs, num_channels, num_patches, d_model)` or
1855
+ `(bs, num_channels, num_patches+1, d_model)` if `cls_token` is set to True, *required*):
1856
+ Embedding from the model
1857
+ Returns:
1858
+ `torch.Tensor` of shape `(bs, output_dim)`
1859
+
1860
+ """
1861
+ if self.use_cls_token:
1862
+ # use the first output token, pooled_embedding: [bs x num_channels x d_model]
1863
+ pooled_embedding = embedding[:, :, 0, :]
1864
+ elif self.pooling_type == "mean":
1865
+ # pooled_embedding: [bs x num_channels x d_model]
1866
+ pooled_embedding = embedding.mean(dim=2)
1867
+ elif self.pooling_type == "max":
1868
+ # pooled_embedding: [bs x num_channels x d_model]
1869
+ pooled_embedding = embedding.max(dim=2)
1870
+ else:
1871
+ raise ValueError(f"pooling operator {self.pooling_type} is not implemented yet")
1872
+ # flatten the input
1873
+ # pooled_embedding: bs x (num_channels * d_model)
1874
+ pooled_embedding = self.dropout(self.flatten(pooled_embedding))
1875
+ # projection
1876
+ # output: bs x output_dim or a tuple of this shape for distribution head
1877
+ output = self.projection(pooled_embedding)
1878
+ # apply sigmoid to bound the output if required
1879
+ if (self.distribution_output is None) & (self.y_range is not None): # linear head
1880
+ output = torch.sigmoid(output) * (self.y_range[1] - self.y_range[0]) + self.y_range[0]
1881
+ return output
1882
+
1883
+
1884
+ @add_start_docstrings(
1885
+ "The PatchTST for regression model.",
1886
+ PATCHTST_START_DOCSTRING,
1887
+ )
1888
+ class PatchTSTForRegression(PatchTSTPreTrainedModel):
1889
+ def __init__(self, config: PatchTSTConfig):
1890
+ super().__init__(config)
1891
+
1892
+ # Turn off masking
1893
+ if config.do_mask_input:
1894
+ logger.warning("Setting `do_mask_input` parameter to False.")
1895
+ config.do_mask_input = False
1896
+
1897
+ self.model = PatchTSTModel(config)
1898
+ if config.loss == "mse":
1899
+ self.distribution_output = None
1900
+ else:
1901
+ if config.distribution_output == "student_t":
1902
+ self.distribution_output = StudentTOutput(dim=config.prediction_length * config.num_targets)
1903
+ elif config.distribution_output == "normal":
1904
+ self.distribution_output = NormalOutput(dim=config.prediction_length * config.num_targets)
1905
+ elif config.distribution_output == "negative_binomial":
1906
+ self.distribution_output = NegativeBinomialOutput(dim=config.prediction_length * config.num_targets)
1907
+ else:
1908
+ raise ValueError(f"Unknown distribution output {config.distribution_output}")
1909
+
1910
+ self.head = PatchTSTRegressionHead(config, self.distribution_output)
1911
+
1912
+ # Initialize weights and apply final processing
1913
+ self.post_init()
1914
+
1915
+ def forward(
1916
+ self,
1917
+ past_values: torch.Tensor,
1918
+ target_values: torch.Tensor = None,
1919
+ past_observed_mask: Optional[torch.Tensor] = None,
1920
+ output_hidden_states: Optional[bool] = None,
1921
+ output_attentions: Optional[bool] = None,
1922
+ return_dict: Optional[bool] = None,
1923
+ ) -> Union[tuple, PatchTSTForRegressionOutput]:
1924
+ r"""
1925
+ Parameters:
1926
+ past_values (`torch.Tensor` of shape `(bs, sequence_length, num_input_channels)`, *required*):
1927
+ Input sequence to the model
1928
+ target_values (`torch.Tensor` of shape `(bs, num_input_channels)`):
1929
+ Target values associates with the `past_values`
1930
+ past_observed_mask (`torch.BoolTensor` of shape `(batch_size, sequence_length, num_input_channels)`, *optional*):
1931
+ Boolean mask to indicate which `past_values` were observed and which were missing. Mask values selected
1932
+ in `[0, 1]`:
1933
+
1934
+ - 1 for values that are **observed**,
1935
+ - 0 for values that are **missing** (i.e. NaNs that were replaced by zeros).
1936
+ output_hidden_states (`bool`, *optional*):
1937
+ Whether or not to return the hidden states of all layers
1938
+ output_attentions (`bool`, *optional*):
1939
+ Whether or not to return the output attention of all layers
1940
+ return_dict (`bool`, *optional*):
1941
+ Whether or not to return a `ModelOutput` instead of a plain tuple.
1942
+
1943
+ Returns:
1944
+ `PatchTSTForRegressionOutput` or tuple of `torch.Tensor` (if `return_dict`=False or
1945
+ `config.return_dict`=False)
1946
+
1947
+ Examples:
1948
+
1949
+ ```python
1950
+ >>> from transformers import PatchTSTConfig, PatchTSTForRegression
1951
+
1952
+ >>> # Regression task with 6 input channels and regress 2 targets
1953
+ >>> model = PatchTSTForRegression.from_pretrained("namctin/patchtst_etth1_regression")
1954
+
1955
+ >>> # during inference, one only provides past values, the model outputs future values
1956
+ >>> past_values = torch.randn(20, 512, 6)
1957
+ >>> outputs = model(past_values=past_values)
1958
+ >>> regression_outputs = outputs.regression_outputs
1959
+ ```"""
1960
+
1961
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1962
+
1963
+ model_output = self.model(
1964
+ past_values=past_values,
1965
+ past_observed_mask=past_observed_mask,
1966
+ output_hidden_states=output_hidden_states,
1967
+ output_attentions=output_attentions,
1968
+ return_dict=True,
1969
+ )
1970
+ # get output head. y_hat is of shape [bs x num_targets] or tuple of this shape
1971
+ y_hat = self.head(model_output.last_hidden_state)
1972
+
1973
+ loss = None
1974
+ if target_values is not None:
1975
+ if self.distribution_output:
1976
+ distribution = self.distribution_output.distribution(y_hat)
1977
+ loss = nll(distribution, target_values)
1978
+ # take average of the loss
1979
+ loss = weighted_average(loss)
1980
+ else:
1981
+ loss = nn.MSELoss(reduction="mean")
1982
+ loss = loss(y_hat, target_values)
1983
+
1984
+ if not return_dict:
1985
+ outputs = (y_hat,) + model_output[1:-3]
1986
+ outputs = (loss,) + outputs if loss is not None else outputs
1987
+ return outputs
1988
+ return PatchTSTForRegressionOutput(
1989
+ loss=loss,
1990
+ regression_outputs=y_hat,
1991
+ hidden_states=model_output.hidden_states,
1992
+ attentions=model_output.attentions,
1993
+ )
1994
+
1995
+ def generate(
1996
+ self,
1997
+ past_values: torch.Tensor,
1998
+ past_observed_mask: Optional[torch.Tensor] = None,
1999
+ ) -> SamplePatchTSTOutput:
2000
+ """
2001
+ Generate sequences of sample predictions from a model with a probability distribution head.
2002
+
2003
+ Parameters:
2004
+ past_values (`torch.FloatTensor` of shape `(batch_size, sequence_length, num_input_channels)`):
2005
+ Past values of the time series that serves as context in order to predict the future.
2006
+ past_observed_mask (`torch.BoolTensor` of shape `(batch_size, sequence_length, num_input_channels)`, *optional*):
2007
+ Boolean mask to indicate which `past_values` were observed and which were missing. Mask values selected
2008
+ in `[0, 1]`:
2009
+
2010
+ - 1 for values that are **observed**,
2011
+ - 0 for values that are **missing** (i.e. NaNs that were replaced by zeros).
2012
+
2013
+ Return:
2014
+ [`SamplePatchTSTOutput`] where the outputs `sequences` tensor will have shape `(batch_size, number of
2015
+ samples, num_targets)`.
2016
+ """
2017
+ # get number of samples
2018
+ num_parallel_samples = self.config.num_parallel_samples
2019
+
2020
+ # get model output
2021
+ outputs = self(
2022
+ past_values=past_values,
2023
+ target_values=None,
2024
+ past_observed_mask=past_observed_mask,
2025
+ output_hidden_states=False,
2026
+ )
2027
+
2028
+ # get distribution
2029
+ distribution = self.distribution_output.distribution(outputs.regression_outputs)
2030
+ # get samples: list of [bs x num_targets]
2031
+ samples = [distribution.sample() for _ in range(num_parallel_samples)]
2032
+ # samples: [bs x num_samples x num_targets]
2033
+ samples = torch.stack(samples, dim=1)
2034
+ return SamplePatchTSTOutput(sequences=samples)