AdithyaSK HF Staff commited on
Commit
3aeea0e
·
verified ·
1 Parent(s): eb40ff6

Stage Harbor release files 22501-23000

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. tasks/tasksmith-441eeab80047/environment/source/src/transformers/models/longformer/tokenization_longformer.py +402 -0
  2. tasks/tasksmith-441eeab80047/environment/source/src/transformers/models/longformer/tokenization_longformer_fast.py +265 -0
  3. tasks/tasksmith-441eeab80047/environment/source/src/transformers/models/longt5/__init__.py +28 -0
  4. tasks/tasksmith-441eeab80047/environment/source/src/transformers/models/longt5/configuration_longt5.py +180 -0
  5. tasks/tasksmith-441eeab80047/environment/source/src/transformers/models/longt5/convert_longt5x_checkpoint_to_flax.py +215 -0
  6. tasks/tasksmith-441eeab80047/environment/source/src/transformers/models/longt5/modeling_flax_longt5.py +0 -0
  7. tasks/tasksmith-441eeab80047/environment/source/src/transformers/models/longt5/modeling_longt5.py +0 -0
  8. tasks/tasksmith-441eeab80047/environment/source/src/transformers/models/luke/__init__.py +28 -0
  9. tasks/tasksmith-441eeab80047/environment/source/src/transformers/models/luke/configuration_luke.py +142 -0
  10. tasks/tasksmith-441eeab80047/environment/source/src/transformers/models/luke/convert_luke_original_pytorch_checkpoint_to_pytorch.py +170 -0
  11. tasks/tasksmith-441eeab80047/environment/source/src/transformers/models/luke/modeling_luke.py +0 -0
  12. tasks/tasksmith-441eeab80047/environment/source/src/transformers/models/luke/tokenization_luke.py +1731 -0
  13. tasks/tasksmith-441eeab80047/environment/source/src/transformers/models/lxmert/__init__.py +30 -0
  14. tasks/tasksmith-441eeab80047/environment/source/src/transformers/models/lxmert/configuration_lxmert.py +169 -0
  15. tasks/tasksmith-441eeab80047/environment/source/src/transformers/models/lxmert/convert_lxmert_original_tf_checkpoint_to_pytorch.py +59 -0
  16. tasks/tasksmith-441eeab80047/environment/source/src/transformers/models/lxmert/modeling_lxmert.py +1463 -0
  17. tasks/tasksmith-441eeab80047/environment/source/src/transformers/models/lxmert/modeling_tf_lxmert.py +1661 -0
  18. tasks/tasksmith-441eeab80047/environment/source/src/transformers/models/lxmert/tokenization_lxmert.py +511 -0
  19. tasks/tasksmith-441eeab80047/environment/source/src/transformers/models/lxmert/tokenization_lxmert_fast.py +172 -0
  20. tasks/tasksmith-441eeab80047/environment/source/src/transformers/models/m2m_100/__init__.py +28 -0
  21. tasks/tasksmith-441eeab80047/environment/source/src/transformers/models/m2m_100/configuration_m2m_100.py +283 -0
  22. tasks/tasksmith-441eeab80047/environment/source/src/transformers/models/m2m_100/convert_m2m100_original_checkpoint_to_pytorch.py +85 -0
  23. tasks/tasksmith-441eeab80047/environment/source/src/transformers/models/m2m_100/modeling_m2m_100.py +1633 -0
  24. tasks/tasksmith-441eeab80047/environment/source/src/transformers/models/m2m_100/tokenization_m2m_100.py +382 -0
  25. tasks/tasksmith-441eeab80047/environment/source/src/transformers/models/mamba/__init__.py +27 -0
  26. tasks/tasksmith-441eeab80047/environment/source/src/transformers/models/mamba/configuration_mamba.py +160 -0
  27. tasks/tasksmith-441eeab80047/environment/source/src/transformers/models/mamba/convert_mamba_ssm_checkpoint_to_pytorch.py +153 -0
  28. tasks/tasksmith-441eeab80047/environment/source/src/transformers/models/mamba/modeling_mamba.py +813 -0
  29. tasks/tasksmith-441eeab80047/environment/source/src/transformers/models/mamba2/__init__.py +27 -0
  30. tasks/tasksmith-441eeab80047/environment/source/src/transformers/models/mamba2/configuration_mamba2.py +183 -0
  31. tasks/tasksmith-441eeab80047/environment/source/src/transformers/models/mamba2/convert_mamba2_ssm_checkpoint_to_pytorch.py +193 -0
  32. tasks/tasksmith-441eeab80047/environment/source/src/transformers/models/mamba2/modeling_mamba2.py +1136 -0
  33. tasks/tasksmith-441eeab80047/environment/source/src/transformers/models/marian/__init__.py +30 -0
  34. tasks/tasksmith-441eeab80047/environment/source/src/transformers/models/marian/configuration_marian.py +394 -0
  35. tasks/tasksmith-441eeab80047/environment/source/src/transformers/models/marian/convert_marian_tatoeba_to_pytorch.py +1327 -0
  36. tasks/tasksmith-441eeab80047/environment/source/src/transformers/models/marian/convert_marian_to_pytorch.py +717 -0
  37. tasks/tasksmith-441eeab80047/environment/source/src/transformers/models/marian/modeling_flax_marian.py +1500 -0
  38. tasks/tasksmith-441eeab80047/environment/source/src/transformers/models/marian/modeling_marian.py +1662 -0
  39. tasks/tasksmith-441eeab80047/environment/source/src/transformers/models/marian/modeling_tf_marian.py +1559 -0
  40. tasks/tasksmith-441eeab80047/environment/source/src/transformers/models/marian/tokenization_marian.py +394 -0
  41. tasks/tasksmith-441eeab80047/environment/source/src/transformers/models/markuplm/__init__.py +31 -0
  42. tasks/tasksmith-441eeab80047/environment/source/src/transformers/models/markuplm/configuration_markuplm.py +156 -0
  43. tasks/tasksmith-441eeab80047/environment/source/src/transformers/models/markuplm/feature_extraction_markuplm.py +186 -0
  44. tasks/tasksmith-441eeab80047/environment/source/src/transformers/models/markuplm/modeling_markuplm.py +1303 -0
  45. tasks/tasksmith-441eeab80047/environment/source/src/transformers/models/markuplm/processing_markuplm.py +150 -0
  46. tasks/tasksmith-441eeab80047/environment/source/src/transformers/models/markuplm/tokenization_markuplm.py +1471 -0
  47. tasks/tasksmith-441eeab80047/environment/source/src/transformers/models/markuplm/tokenization_markuplm_fast.py +929 -0
  48. tasks/tasksmith-441eeab80047/environment/source/src/transformers/models/mask2former/__init__.py +28 -0
  49. tasks/tasksmith-441eeab80047/environment/source/src/transformers/models/mask2former/configuration_mask2former.py +256 -0
  50. tasks/tasksmith-441eeab80047/environment/source/src/transformers/models/mask2former/convert_mask2former_original_pytorch_checkpoint_to_pytorch.py +1019 -0
tasks/tasksmith-441eeab80047/environment/source/src/transformers/models/longformer/tokenization_longformer.py ADDED
@@ -0,0 +1,402 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2020 The Allen Institute for AI team 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 json
17
+ import os
18
+ from functools import lru_cache
19
+ from typing import List, Optional, Tuple
20
+
21
+ import regex as re
22
+
23
+ from ...tokenization_utils import AddedToken, PreTrainedTokenizer
24
+ from ...utils import logging
25
+
26
+
27
+ logger = logging.get_logger(__name__)
28
+
29
+
30
+ VOCAB_FILES_NAMES = {"vocab_file": "vocab.json", "merges_file": "merges.txt"}
31
+
32
+
33
+ @lru_cache()
34
+ # Copied from transformers.models.roberta.tokenization_roberta.bytes_to_unicode
35
+ def bytes_to_unicode():
36
+ """
37
+ Returns list of utf-8 byte and a mapping to unicode strings. We specifically avoids mapping to whitespace/control
38
+ characters the bpe code barfs on.
39
+
40
+ The reversible bpe codes work on unicode strings. This means you need a large # of unicode characters in your vocab
41
+ if you want to avoid UNKs. When you're at something like a 10B token dataset you end up needing around 5K for
42
+ decent coverage. This is a significant percentage of your normal, say, 32K bpe vocab. To avoid that, we want lookup
43
+ tables between utf-8 bytes and unicode strings.
44
+ """
45
+ bs = (
46
+ list(range(ord("!"), ord("~") + 1)) + list(range(ord("¡"), ord("¬") + 1)) + list(range(ord("®"), ord("ÿ") + 1))
47
+ )
48
+ cs = bs[:]
49
+ n = 0
50
+ for b in range(2**8):
51
+ if b not in bs:
52
+ bs.append(b)
53
+ cs.append(2**8 + n)
54
+ n += 1
55
+ cs = [chr(n) for n in cs]
56
+ return dict(zip(bs, cs))
57
+
58
+
59
+ # Copied from transformers.models.roberta.tokenization_roberta.get_pairs
60
+ def get_pairs(word):
61
+ """
62
+ Return set of symbol pairs in a word.
63
+
64
+ Word is represented as tuple of symbols (symbols being variable-length strings).
65
+ """
66
+ pairs = set()
67
+ prev_char = word[0]
68
+ for char in word[1:]:
69
+ pairs.add((prev_char, char))
70
+ prev_char = char
71
+ return pairs
72
+
73
+
74
+ # Copied from transformers.models.roberta.tokenization_roberta.RobertaTokenizer with FacebookAI/roberta-base->allenai/longformer-base-4096, RoBERTa->Longformer all-casing, RobertaTokenizer->LongformerTokenizer
75
+ class LongformerTokenizer(PreTrainedTokenizer):
76
+ """
77
+ Constructs a Longformer tokenizer, derived from the GPT-2 tokenizer, using byte-level Byte-Pair-Encoding.
78
+
79
+ This tokenizer has been trained to treat spaces like parts of the tokens (a bit like sentencepiece) so a word will
80
+ be encoded differently whether it is at the beginning of the sentence (without space) or not:
81
+
82
+ ```python
83
+ >>> from transformers import LongformerTokenizer
84
+
85
+ >>> tokenizer = LongformerTokenizer.from_pretrained("allenai/longformer-base-4096")
86
+ >>> tokenizer("Hello world")["input_ids"]
87
+ [0, 31414, 232, 2]
88
+
89
+ >>> tokenizer(" Hello world")["input_ids"]
90
+ [0, 20920, 232, 2]
91
+ ```
92
+
93
+ You can get around that behavior by passing `add_prefix_space=True` when instantiating this tokenizer or when you
94
+ call it on some text, but since the model was not pretrained this way, it might yield a decrease in performance.
95
+
96
+ <Tip>
97
+
98
+ When used with `is_split_into_words=True`, this tokenizer will add a space before each word (even the first one).
99
+
100
+ </Tip>
101
+
102
+ This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to
103
+ this superclass for more information regarding those methods.
104
+
105
+ Args:
106
+ vocab_file (`str`):
107
+ Path to the vocabulary file.
108
+ merges_file (`str`):
109
+ Path to the merges file.
110
+ errors (`str`, *optional*, defaults to `"replace"`):
111
+ Paradigm to follow when decoding bytes to UTF-8. See
112
+ [bytes.decode](https://docs.python.org/3/library/stdtypes.html#bytes.decode) for more information.
113
+ bos_token (`str`, *optional*, defaults to `"<s>"`):
114
+ The beginning of sequence token that was used during pretraining. Can be used a sequence classifier token.
115
+
116
+ <Tip>
117
+
118
+ When building a sequence using special tokens, this is not the token that is used for the beginning of
119
+ sequence. The token used is the `cls_token`.
120
+
121
+ </Tip>
122
+
123
+ eos_token (`str`, *optional*, defaults to `"</s>"`):
124
+ The end of sequence token.
125
+
126
+ <Tip>
127
+
128
+ When building a sequence using special tokens, this is not the token that is used for the end of sequence.
129
+ The token used is the `sep_token`.
130
+
131
+ </Tip>
132
+
133
+ sep_token (`str`, *optional*, defaults to `"</s>"`):
134
+ The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
135
+ sequence classification or for a text and a question for question answering. It is also used as the last
136
+ token of a sequence built with special tokens.
137
+ cls_token (`str`, *optional*, defaults to `"<s>"`):
138
+ The classifier token which is used when doing sequence classification (classification of the whole sequence
139
+ instead of per-token classification). It is the first token of the sequence when built with special tokens.
140
+ unk_token (`str`, *optional*, defaults to `"<unk>"`):
141
+ The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
142
+ token instead.
143
+ pad_token (`str`, *optional*, defaults to `"<pad>"`):
144
+ The token used for padding, for example when batching sequences of different lengths.
145
+ mask_token (`str`, *optional*, defaults to `"<mask>"`):
146
+ The token used for masking values. This is the token used when training this model with masked language
147
+ modeling. This is the token which the model will try to predict.
148
+ add_prefix_space (`bool`, *optional*, defaults to `False`):
149
+ Whether or not to add an initial space to the input. This allows to treat the leading word just as any
150
+ other word. (Longformer tokenizer detect beginning of words by the preceding space).
151
+ """
152
+
153
+ vocab_files_names = VOCAB_FILES_NAMES
154
+ model_input_names = ["input_ids", "attention_mask"]
155
+
156
+ def __init__(
157
+ self,
158
+ vocab_file,
159
+ merges_file,
160
+ errors="replace",
161
+ bos_token="<s>",
162
+ eos_token="</s>",
163
+ sep_token="</s>",
164
+ cls_token="<s>",
165
+ unk_token="<unk>",
166
+ pad_token="<pad>",
167
+ mask_token="<mask>",
168
+ add_prefix_space=False,
169
+ **kwargs,
170
+ ):
171
+ bos_token = AddedToken(bos_token, lstrip=False, rstrip=False) if isinstance(bos_token, str) else bos_token
172
+ pad_token = AddedToken(pad_token, lstrip=False, rstrip=False) if isinstance(pad_token, str) else pad_token
173
+ eos_token = AddedToken(eos_token, lstrip=False, rstrip=False) if isinstance(eos_token, str) else eos_token
174
+ unk_token = AddedToken(unk_token, lstrip=False, rstrip=False) if isinstance(unk_token, str) else unk_token
175
+ sep_token = AddedToken(sep_token, lstrip=False, rstrip=False) if isinstance(sep_token, str) else sep_token
176
+ cls_token = AddedToken(cls_token, lstrip=False, rstrip=False) if isinstance(cls_token, str) else cls_token
177
+
178
+ # Mask token behave like a normal word, i.e. include the space before it
179
+ mask_token = (
180
+ AddedToken(mask_token, lstrip=True, rstrip=False, normalized=False)
181
+ if isinstance(mask_token, str)
182
+ else mask_token
183
+ )
184
+
185
+ # these special tokens are not part of the vocab.json, let's add them in the correct order
186
+
187
+ with open(vocab_file, encoding="utf-8") as vocab_handle:
188
+ self.encoder = json.load(vocab_handle)
189
+ self.decoder = {v: k for k, v in self.encoder.items()}
190
+ self.errors = errors # how to handle errors in decoding
191
+ self.byte_encoder = bytes_to_unicode()
192
+ self.byte_decoder = {v: k for k, v in self.byte_encoder.items()}
193
+ with open(merges_file, encoding="utf-8") as merges_handle:
194
+ bpe_merges = merges_handle.read().split("\n")[1:-1]
195
+ bpe_merges = [tuple(merge.split()) for merge in bpe_merges]
196
+ self.bpe_ranks = dict(zip(bpe_merges, range(len(bpe_merges))))
197
+ self.cache = {}
198
+ self.add_prefix_space = add_prefix_space
199
+
200
+ # Should have added re.IGNORECASE so BPE merges can happen for capitalized versions of contractions
201
+ self.pat = re.compile(r"""'s|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+""")
202
+
203
+ super().__init__(
204
+ errors=errors,
205
+ bos_token=bos_token,
206
+ eos_token=eos_token,
207
+ unk_token=unk_token,
208
+ sep_token=sep_token,
209
+ cls_token=cls_token,
210
+ pad_token=pad_token,
211
+ mask_token=mask_token,
212
+ add_prefix_space=add_prefix_space,
213
+ **kwargs,
214
+ )
215
+
216
+ @property
217
+ def vocab_size(self):
218
+ return len(self.encoder)
219
+
220
+ def get_vocab(self):
221
+ vocab = dict(self.encoder).copy()
222
+ vocab.update(self.added_tokens_encoder)
223
+ return vocab
224
+
225
+ def bpe(self, token):
226
+ if token in self.cache:
227
+ return self.cache[token]
228
+ word = tuple(token)
229
+ pairs = get_pairs(word)
230
+
231
+ if not pairs:
232
+ return token
233
+
234
+ while True:
235
+ bigram = min(pairs, key=lambda pair: self.bpe_ranks.get(pair, float("inf")))
236
+ if bigram not in self.bpe_ranks:
237
+ break
238
+ first, second = bigram
239
+ new_word = []
240
+ i = 0
241
+ while i < len(word):
242
+ try:
243
+ j = word.index(first, i)
244
+ except ValueError:
245
+ new_word.extend(word[i:])
246
+ break
247
+ else:
248
+ new_word.extend(word[i:j])
249
+ i = j
250
+
251
+ if word[i] == first and i < len(word) - 1 and word[i + 1] == second:
252
+ new_word.append(first + second)
253
+ i += 2
254
+ else:
255
+ new_word.append(word[i])
256
+ i += 1
257
+ new_word = tuple(new_word)
258
+ word = new_word
259
+ if len(word) == 1:
260
+ break
261
+ else:
262
+ pairs = get_pairs(word)
263
+ word = " ".join(word)
264
+ self.cache[token] = word
265
+ return word
266
+
267
+ def _tokenize(self, text):
268
+ """Tokenize a string."""
269
+ bpe_tokens = []
270
+ for token in re.findall(self.pat, text):
271
+ token = "".join(
272
+ self.byte_encoder[b] for b in token.encode("utf-8")
273
+ ) # Maps all our bytes to unicode strings, avoiding control tokens of the BPE (spaces in our case)
274
+ bpe_tokens.extend(bpe_token for bpe_token in self.bpe(token).split(" "))
275
+ return bpe_tokens
276
+
277
+ def _convert_token_to_id(self, token):
278
+ """Converts a token (str) in an id using the vocab."""
279
+ return self.encoder.get(token, self.encoder.get(self.unk_token))
280
+
281
+ def _convert_id_to_token(self, index):
282
+ """Converts an index (integer) in a token (str) using the vocab."""
283
+ return self.decoder.get(index)
284
+
285
+ def convert_tokens_to_string(self, tokens):
286
+ """Converts a sequence of tokens (string) in a single string."""
287
+ text = "".join(tokens)
288
+ text = bytearray([self.byte_decoder[c] for c in text]).decode("utf-8", errors=self.errors)
289
+ return text
290
+
291
+ def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
292
+ if not os.path.isdir(save_directory):
293
+ logger.error(f"Vocabulary path ({save_directory}) should be a directory")
294
+ return
295
+ vocab_file = os.path.join(
296
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
297
+ )
298
+ merge_file = os.path.join(
299
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["merges_file"]
300
+ )
301
+
302
+ with open(vocab_file, "w", encoding="utf-8") as f:
303
+ f.write(json.dumps(self.encoder, indent=2, sort_keys=True, ensure_ascii=False) + "\n")
304
+
305
+ index = 0
306
+ with open(merge_file, "w", encoding="utf-8") as writer:
307
+ writer.write("#version: 0.2\n")
308
+ for bpe_tokens, token_index in sorted(self.bpe_ranks.items(), key=lambda kv: kv[1]):
309
+ if index != token_index:
310
+ logger.warning(
311
+ f"Saving vocabulary to {merge_file}: BPE merge indices are not consecutive."
312
+ " Please check that the tokenizer is not corrupted!"
313
+ )
314
+ index = token_index
315
+ writer.write(" ".join(bpe_tokens) + "\n")
316
+ index += 1
317
+
318
+ return vocab_file, merge_file
319
+
320
+ def build_inputs_with_special_tokens(
321
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
322
+ ) -> List[int]:
323
+ """
324
+ Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
325
+ adding special tokens. A Longformer sequence has the following format:
326
+
327
+ - single sequence: `<s> X </s>`
328
+ - pair of sequences: `<s> A </s></s> B </s>`
329
+
330
+ Args:
331
+ token_ids_0 (`List[int]`):
332
+ List of IDs to which the special tokens will be added.
333
+ token_ids_1 (`List[int]`, *optional*):
334
+ Optional second list of IDs for sequence pairs.
335
+
336
+ Returns:
337
+ `List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
338
+ """
339
+ if token_ids_1 is None:
340
+ return [self.cls_token_id] + token_ids_0 + [self.sep_token_id]
341
+ cls = [self.cls_token_id]
342
+ sep = [self.sep_token_id]
343
+ return cls + token_ids_0 + sep + sep + token_ids_1 + sep
344
+
345
+ def get_special_tokens_mask(
346
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None, already_has_special_tokens: bool = False
347
+ ) -> List[int]:
348
+ """
349
+ Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
350
+ special tokens using the tokenizer `prepare_for_model` method.
351
+
352
+ Args:
353
+ token_ids_0 (`List[int]`):
354
+ List of IDs.
355
+ token_ids_1 (`List[int]`, *optional*):
356
+ Optional second list of IDs for sequence pairs.
357
+ already_has_special_tokens (`bool`, *optional*, defaults to `False`):
358
+ Whether or not the token list is already formatted with special tokens for the model.
359
+
360
+ Returns:
361
+ `List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
362
+ """
363
+ if already_has_special_tokens:
364
+ return super().get_special_tokens_mask(
365
+ token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
366
+ )
367
+
368
+ if token_ids_1 is None:
369
+ return [1] + ([0] * len(token_ids_0)) + [1]
370
+ return [1] + ([0] * len(token_ids_0)) + [1, 1] + ([0] * len(token_ids_1)) + [1]
371
+
372
+ def create_token_type_ids_from_sequences(
373
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
374
+ ) -> List[int]:
375
+ """
376
+ Create a mask from the two sequences passed to be used in a sequence-pair classification task. Longformer does not
377
+ make use of token type ids, therefore a list of zeros is returned.
378
+
379
+ Args:
380
+ token_ids_0 (`List[int]`):
381
+ List of IDs.
382
+ token_ids_1 (`List[int]`, *optional*):
383
+ Optional second list of IDs for sequence pairs.
384
+
385
+ Returns:
386
+ `List[int]`: List of zeros.
387
+ """
388
+ sep = [self.sep_token_id]
389
+ cls = [self.cls_token_id]
390
+
391
+ if token_ids_1 is None:
392
+ return len(cls + token_ids_0 + sep) * [0]
393
+ return len(cls + token_ids_0 + sep + sep + token_ids_1 + sep) * [0]
394
+
395
+ def prepare_for_tokenization(self, text, is_split_into_words=False, **kwargs):
396
+ add_prefix_space = kwargs.pop("add_prefix_space", self.add_prefix_space)
397
+ if (is_split_into_words or add_prefix_space) and (len(text) > 0 and not text[0].isspace()):
398
+ text = " " + text
399
+ return (text, kwargs)
400
+
401
+
402
+ __all__ = ["LongformerTokenizer"]
tasks/tasksmith-441eeab80047/environment/source/src/transformers/models/longformer/tokenization_longformer_fast.py ADDED
@@ -0,0 +1,265 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2020 The Allen Institute for AI team 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
+ """Fast Tokenization classes for Longformer."""
16
+
17
+ import json
18
+ from typing import List, Optional, Tuple
19
+
20
+ from tokenizers import processors
21
+
22
+ from ...tokenization_utils_base import AddedToken, BatchEncoding
23
+ from ...tokenization_utils_fast import PreTrainedTokenizerFast
24
+ from ...utils import logging
25
+ from .tokenization_longformer import LongformerTokenizer
26
+
27
+
28
+ logger = logging.get_logger(__name__)
29
+
30
+ VOCAB_FILES_NAMES = {"vocab_file": "vocab.json", "merges_file": "merges.txt", "tokenizer_file": "tokenizer.json"}
31
+
32
+
33
+ # Copied from transformers.models.roberta.tokenization_roberta_fast.RobertaTokenizerFast with FacebookAI/roberta-base->allenai/longformer-base-4096, RoBERTa->Longformer all-casing, Roberta->Longformer
34
+ class LongformerTokenizerFast(PreTrainedTokenizerFast):
35
+ """
36
+ Construct a "fast" Longformer tokenizer (backed by HuggingFace's *tokenizers* library), derived from the GPT-2
37
+ tokenizer, using byte-level Byte-Pair-Encoding.
38
+
39
+ This tokenizer has been trained to treat spaces like parts of the tokens (a bit like sentencepiece) so a word will
40
+ be encoded differently whether it is at the beginning of the sentence (without space) or not:
41
+
42
+ ```python
43
+ >>> from transformers import LongformerTokenizerFast
44
+
45
+ >>> tokenizer = LongformerTokenizerFast.from_pretrained("allenai/longformer-base-4096")
46
+ >>> tokenizer("Hello world")["input_ids"]
47
+ [0, 31414, 232, 2]
48
+
49
+ >>> tokenizer(" Hello world")["input_ids"]
50
+ [0, 20920, 232, 2]
51
+ ```
52
+
53
+ You can get around that behavior by passing `add_prefix_space=True` when instantiating this tokenizer or when you
54
+ call it on some text, but since the model was not pretrained this way, it might yield a decrease in performance.
55
+
56
+ <Tip>
57
+
58
+ When used with `is_split_into_words=True`, this tokenizer needs to be instantiated with `add_prefix_space=True`.
59
+
60
+ </Tip>
61
+
62
+ This tokenizer inherits from [`PreTrainedTokenizerFast`] which contains most of the main methods. Users should
63
+ refer to this superclass for more information regarding those methods.
64
+
65
+ Args:
66
+ vocab_file (`str`):
67
+ Path to the vocabulary file.
68
+ merges_file (`str`):
69
+ Path to the merges file.
70
+ errors (`str`, *optional*, defaults to `"replace"`):
71
+ Paradigm to follow when decoding bytes to UTF-8. See
72
+ [bytes.decode](https://docs.python.org/3/library/stdtypes.html#bytes.decode) for more information.
73
+ bos_token (`str`, *optional*, defaults to `"<s>"`):
74
+ The beginning of sequence token that was used during pretraining. Can be used a sequence classifier token.
75
+
76
+ <Tip>
77
+
78
+ When building a sequence using special tokens, this is not the token that is used for the beginning of
79
+ sequence. The token used is the `cls_token`.
80
+
81
+ </Tip>
82
+
83
+ eos_token (`str`, *optional*, defaults to `"</s>"`):
84
+ The end of sequence token.
85
+
86
+ <Tip>
87
+
88
+ When building a sequence using special tokens, this is not the token that is used for the end of sequence.
89
+ The token used is the `sep_token`.
90
+
91
+ </Tip>
92
+
93
+ sep_token (`str`, *optional*, defaults to `"</s>"`):
94
+ The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
95
+ sequence classification or for a text and a question for question answering. It is also used as the last
96
+ token of a sequence built with special tokens.
97
+ cls_token (`str`, *optional*, defaults to `"<s>"`):
98
+ The classifier token which is used when doing sequence classification (classification of the whole sequence
99
+ instead of per-token classification). It is the first token of the sequence when built with special tokens.
100
+ unk_token (`str`, *optional*, defaults to `"<unk>"`):
101
+ The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
102
+ token instead.
103
+ pad_token (`str`, *optional*, defaults to `"<pad>"`):
104
+ The token used for padding, for example when batching sequences of different lengths.
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
+ add_prefix_space (`bool`, *optional*, defaults to `False`):
109
+ Whether or not to add an initial space to the input. This allows to treat the leading word just as any
110
+ other word. (Longformer tokenizer detect beginning of words by the preceding space).
111
+ trim_offsets (`bool`, *optional*, defaults to `True`):
112
+ Whether the post processing step should trim offsets to avoid including whitespaces.
113
+ """
114
+
115
+ vocab_files_names = VOCAB_FILES_NAMES
116
+ model_input_names = ["input_ids", "attention_mask"]
117
+ slow_tokenizer_class = LongformerTokenizer
118
+
119
+ def __init__(
120
+ self,
121
+ vocab_file=None,
122
+ merges_file=None,
123
+ tokenizer_file=None,
124
+ errors="replace",
125
+ bos_token="<s>",
126
+ eos_token="</s>",
127
+ sep_token="</s>",
128
+ cls_token="<s>",
129
+ unk_token="<unk>",
130
+ pad_token="<pad>",
131
+ mask_token="<mask>",
132
+ add_prefix_space=False,
133
+ trim_offsets=True,
134
+ **kwargs,
135
+ ):
136
+ mask_token = (
137
+ AddedToken(mask_token, lstrip=True, rstrip=False, normalized=False)
138
+ if isinstance(mask_token, str)
139
+ else mask_token
140
+ )
141
+ super().__init__(
142
+ vocab_file,
143
+ merges_file,
144
+ tokenizer_file=tokenizer_file,
145
+ errors=errors,
146
+ bos_token=bos_token,
147
+ eos_token=eos_token,
148
+ sep_token=sep_token,
149
+ cls_token=cls_token,
150
+ unk_token=unk_token,
151
+ pad_token=pad_token,
152
+ mask_token=mask_token,
153
+ add_prefix_space=add_prefix_space,
154
+ trim_offsets=trim_offsets,
155
+ **kwargs,
156
+ )
157
+
158
+ tokenizer_component = "post_processor"
159
+ tokenizer_component_instance = getattr(self.backend_tokenizer, tokenizer_component, None)
160
+ if tokenizer_component_instance:
161
+ state = json.loads(tokenizer_component_instance.__getstate__())
162
+
163
+ # The lists 'sep' and 'cls' must be cased in tuples for the object `post_processor_class`
164
+ if "sep" in state:
165
+ state["sep"] = tuple(state["sep"])
166
+ if "cls" in state:
167
+ state["cls"] = tuple(state["cls"])
168
+
169
+ changes_to_apply = False
170
+
171
+ if state.get("add_prefix_space", add_prefix_space) != add_prefix_space:
172
+ state["add_prefix_space"] = add_prefix_space
173
+ changes_to_apply = True
174
+
175
+ if state.get("trim_offsets", trim_offsets) != trim_offsets:
176
+ state["trim_offsets"] = trim_offsets
177
+ changes_to_apply = True
178
+
179
+ if changes_to_apply:
180
+ component_class = getattr(processors, state.pop("type"))
181
+ new_value = component_class(**state)
182
+ setattr(self.backend_tokenizer, tokenizer_component, new_value)
183
+
184
+ @property
185
+ def mask_token(self) -> str:
186
+ """
187
+ `str`: Mask token, to use when training a model with masked-language modeling. Log an error if used while not
188
+ having been set.
189
+
190
+ Longformer tokenizer has a special mask token to be usable in the fill-mask pipeline. The mask token will greedily
191
+ comprise the space before the *<mask>*.
192
+ """
193
+ if self._mask_token is None:
194
+ if self.verbose:
195
+ logger.error("Using mask_token, but it is not set yet.")
196
+ return None
197
+ return str(self._mask_token)
198
+
199
+ @mask_token.setter
200
+ def mask_token(self, value):
201
+ """
202
+ Overriding the default behavior of the mask token to have it eat the space before it.
203
+
204
+ This is needed to preserve backward compatibility with all the previously used models based on Longformer.
205
+ """
206
+ # Mask token behave like a normal word, i.e. include the space before it
207
+ # So we set lstrip to True
208
+ value = AddedToken(value, lstrip=True, rstrip=False) if isinstance(value, str) else value
209
+ self._mask_token = value
210
+
211
+ def _batch_encode_plus(self, *args, **kwargs) -> BatchEncoding:
212
+ is_split_into_words = kwargs.get("is_split_into_words", False)
213
+ assert self.add_prefix_space or not is_split_into_words, (
214
+ f"You need to instantiate {self.__class__.__name__} with add_prefix_space=True "
215
+ "to use it with pretokenized inputs."
216
+ )
217
+
218
+ return super()._batch_encode_plus(*args, **kwargs)
219
+
220
+ def _encode_plus(self, *args, **kwargs) -> BatchEncoding:
221
+ is_split_into_words = kwargs.get("is_split_into_words", False)
222
+
223
+ assert self.add_prefix_space or not is_split_into_words, (
224
+ f"You need to instantiate {self.__class__.__name__} with add_prefix_space=True "
225
+ "to use it with pretokenized inputs."
226
+ )
227
+
228
+ return super()._encode_plus(*args, **kwargs)
229
+
230
+ def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
231
+ files = self._tokenizer.model.save(save_directory, name=filename_prefix)
232
+ return tuple(files)
233
+
234
+ def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None):
235
+ output = [self.bos_token_id] + token_ids_0 + [self.eos_token_id]
236
+ if token_ids_1 is None:
237
+ return output
238
+
239
+ return output + [self.eos_token_id] + token_ids_1 + [self.eos_token_id]
240
+
241
+ def create_token_type_ids_from_sequences(
242
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
243
+ ) -> List[int]:
244
+ """
245
+ Create a mask from the two sequences passed to be used in a sequence-pair classification task. Longformer does not
246
+ make use of token type ids, therefore a list of zeros is returned.
247
+
248
+ Args:
249
+ token_ids_0 (`List[int]`):
250
+ List of IDs.
251
+ token_ids_1 (`List[int]`, *optional*):
252
+ Optional second list of IDs for sequence pairs.
253
+
254
+ Returns:
255
+ `List[int]`: List of zeros.
256
+ """
257
+ sep = [self.sep_token_id]
258
+ cls = [self.cls_token_id]
259
+
260
+ if token_ids_1 is None:
261
+ return len(cls + token_ids_0 + sep) * [0]
262
+ return len(cls + token_ids_0 + sep + sep + token_ids_1 + sep) * [0]
263
+
264
+
265
+ __all__ = ["LongformerTokenizerFast"]
tasks/tasksmith-441eeab80047/environment/source/src/transformers/models/longt5/__init__.py ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 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 _LazyModule
17
+ from ...utils.import_utils import define_import_structure
18
+
19
+
20
+ if TYPE_CHECKING:
21
+ from .configuration_longt5 import *
22
+ from .modeling_flax_longt5 import *
23
+ from .modeling_longt5 import *
24
+ else:
25
+ import sys
26
+
27
+ _file = globals()["__file__"]
28
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
tasks/tasksmith-441eeab80047/environment/source/src/transformers/models/longt5/configuration_longt5.py ADDED
@@ -0,0 +1,180 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022, The LongT5 Authors and HuggingFace Inc.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """LongT5 model configuration"""
16
+
17
+ from typing import Mapping
18
+
19
+ from ...configuration_utils import PretrainedConfig
20
+ from ...onnx import OnnxSeq2SeqConfigWithPast
21
+ from ...utils import logging
22
+
23
+
24
+ logger = logging.get_logger(__name__)
25
+
26
+
27
+ class LongT5Config(PretrainedConfig):
28
+ r"""
29
+ This is the configuration class to store the configuration of a [`LongT5Model`] or a [`FlaxLongT5Model`]. It is
30
+ used to instantiate a LongT5 model according to the specified arguments, defining the model architecture.
31
+ Instantiating a configuration with the defaults will yield a similar configuration to that of the LongT5
32
+ [google/long-t5-local-base](https://huggingface.co/google/long-t5-local-base) architecture.
33
+
34
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
35
+ documentation from [`PretrainedConfig`] for more information.
36
+
37
+ Arguments:
38
+ vocab_size (`int`, *optional*, defaults to 32128):
39
+ Vocabulary size of the LongT5 model. Defines the number of different tokens that can be represented by the
40
+ `inputs_ids` passed when calling [`LongT5Model`].
41
+ d_model (`int`, *optional*, defaults to 512):
42
+ Size of the encoder layers and the pooler layer.
43
+ d_kv (`int`, *optional*, defaults to 64):
44
+ Size of the key, query, value projections per attention head. `d_kv` has to be equal to `d_model //
45
+ num_heads`.
46
+ d_ff (`int`, *optional*, defaults to 2048):
47
+ Size of the intermediate feed forward layer in each `LongT5Block`.
48
+ num_layers (`int`, *optional*, defaults to 6):
49
+ Number of hidden layers in the Transformer encoder.
50
+ num_decoder_layers (`int`, *optional*):
51
+ Number of hidden layers in the Transformer decoder. Will use the same value as `num_layers` if not set.
52
+ num_heads (`int`, *optional*, defaults to 8):
53
+ Number of attention heads for each attention layer in the Transformer encoder.
54
+ local_radius (`int`, *optional*, defaults to 127)
55
+ Number of tokens to the left/right for each token to locally self-attend in a local attention mechanism.
56
+ global_block_size (`int`, *optional*, defaults to 16)
57
+ Lenght of blocks an input sequence is divided into for a global token representation. Used only for
58
+ `encoder_attention_type = "transient-global"`.
59
+ relative_attention_num_buckets (`int`, *optional*, defaults to 32):
60
+ The number of buckets to use for each attention layer.
61
+ relative_attention_max_distance (`int`, *optional*, defaults to 128):
62
+ The maximum distance of the longer sequences for the bucket separation.
63
+ dropout_rate (`float`, *optional*, defaults to 0.1):
64
+ The ratio for all dropout layers.
65
+ layer_norm_eps (`float`, *optional*, defaults to 1e-6):
66
+ The epsilon used by the layer normalization layers.
67
+ initializer_factor (`float`, *optional*, defaults to 1):
68
+ A factor for initializing all weight matrices (should be kept to 1, used internally for initialization
69
+ testing).
70
+ feed_forward_proj (`string`, *optional*, defaults to `"relu"`):
71
+ Type of feed forward layer to be used. Should be one of `"relu"` or `"gated-gelu"`. LongT5v1.1 uses the
72
+ `"gated-gelu"` feed forward projection. Original LongT5 implementation uses `"gated-gelu"`.
73
+ encoder_attention_type (`string`, *optional*, defaults to `"local"`):
74
+ Type of encoder attention to be used. Should be one of `"local"` or `"transient-global"`, which are
75
+ supported by LongT5 implementation.
76
+ use_cache (`bool`, *optional*, defaults to `True`):
77
+ Whether or not the model should return the last key/values attentions (not used by all models).
78
+ """
79
+
80
+ model_type = "longt5"
81
+ keys_to_ignore_at_inference = ["past_key_values"]
82
+ attribute_map = {
83
+ "hidden_size": "d_model",
84
+ "num_attention_heads": "num_heads",
85
+ "num_hidden_layers": "num_layers",
86
+ "head_dim": "d_kv",
87
+ }
88
+
89
+ def __init__(
90
+ self,
91
+ vocab_size=32128,
92
+ d_model=512,
93
+ d_kv=64,
94
+ d_ff=2048,
95
+ num_layers=6,
96
+ num_decoder_layers=None,
97
+ num_heads=8,
98
+ local_radius=127,
99
+ global_block_size=16,
100
+ relative_attention_num_buckets=32,
101
+ relative_attention_max_distance=128,
102
+ dropout_rate=0.1,
103
+ layer_norm_epsilon=1e-6,
104
+ initializer_factor=1.0,
105
+ feed_forward_proj="relu",
106
+ is_encoder_decoder=True,
107
+ encoder_attention_type="local",
108
+ use_cache=True,
109
+ pad_token_id=0,
110
+ eos_token_id=1,
111
+ **kwargs,
112
+ ):
113
+ self.vocab_size = vocab_size
114
+ self.d_model = d_model
115
+ self.d_kv = d_kv
116
+ self.d_ff = d_ff
117
+ self.num_layers = num_layers
118
+ # default = symmetry
119
+ self.num_decoder_layers = num_decoder_layers if num_decoder_layers is not None else self.num_layers
120
+ self.num_heads = num_heads
121
+ self.local_radius = local_radius
122
+ self.global_block_size = global_block_size
123
+ self.relative_attention_num_buckets = relative_attention_num_buckets
124
+ self.relative_attention_max_distance = relative_attention_max_distance
125
+ self.dropout_rate = dropout_rate
126
+ self.layer_norm_epsilon = layer_norm_epsilon
127
+ self.initializer_factor = initializer_factor
128
+ self.feed_forward_proj = feed_forward_proj
129
+ self.encoder_attention_type = encoder_attention_type
130
+ self.use_cache = use_cache
131
+
132
+ act_info = self.feed_forward_proj.split("-")
133
+ self.dense_act_fn = act_info[-1]
134
+ self.is_gated_act = act_info[0] == "gated"
135
+
136
+ if len(act_info) > 1 and act_info[0] != "gated" or len(act_info) > 2:
137
+ raise ValueError(
138
+ f"`feed_forward_proj`: {feed_forward_proj} is not a valid activation function of the dense layer. "
139
+ "Please make sure `feed_forward_proj` is of the format `gated-{ACT_FN}` or `{ACT_FN}`, e.g. "
140
+ "'gated-gelu' or 'relu'"
141
+ )
142
+
143
+ # for backwards compatibility
144
+ if feed_forward_proj == "gated-gelu":
145
+ self.dense_act_fn = "gelu_new"
146
+
147
+ super().__init__(
148
+ pad_token_id=pad_token_id,
149
+ eos_token_id=eos_token_id,
150
+ is_encoder_decoder=is_encoder_decoder,
151
+ **kwargs,
152
+ )
153
+
154
+
155
+ class LongT5OnnxConfig(OnnxSeq2SeqConfigWithPast):
156
+ @property
157
+ def inputs(self) -> Mapping[str, Mapping[int, str]]:
158
+ common_inputs = {
159
+ "input_ids": {0: "batch", 1: "encoder_sequence"},
160
+ "attention_mask": {0: "batch", 1: "encoder_sequence"},
161
+ }
162
+ if self.use_past:
163
+ common_inputs["attention_mask"][1] = "past_encoder_sequence + sequence"
164
+ common_inputs["decoder_input_ids"] = {0: "batch"}
165
+ common_inputs["decoder_attention_mask"] = {0: "batch", 1: "past_decoder_sequence + sequence"}
166
+ else:
167
+ common_inputs["decoder_input_ids"] = {0: "batch", 1: "decoder_sequence"}
168
+ common_inputs["decoder_attention_mask"] = {0: "batch", 1: "decoder_sequence"}
169
+
170
+ if self.use_past:
171
+ self.fill_with_past_key_values_(common_inputs, direction="inputs")
172
+
173
+ return common_inputs
174
+
175
+ @property
176
+ def default_onnx_opset(self) -> int:
177
+ return 13
178
+
179
+
180
+ __all__ = ["LongT5Config", "LongT5OnnxConfig"]
tasks/tasksmith-441eeab80047/environment/source/src/transformers/models/longt5/convert_longt5x_checkpoint_to_flax.py ADDED
@@ -0,0 +1,215 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 The HuggingFace Inc. team.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ """Convert T5/LongT5X checkpoints from the original repository to JAX/FLAX model. This script is an extension of
17
+ 'src/transformers/models/t5/convert_t5x_checkpoint_to_flax.
18
+ """
19
+
20
+ import argparse
21
+
22
+ from t5x import checkpoints
23
+
24
+ from transformers import AutoConfig, FlaxAutoModelForSeq2SeqLM
25
+
26
+
27
+ def convert_t5x_checkpoint_to_flax(t5x_checkpoint_path, config_name, flax_dump_folder_path):
28
+ config = AutoConfig.from_pretrained(config_name)
29
+ flax_model = FlaxAutoModelForSeq2SeqLM.from_config(config=config)
30
+ t5x_model = checkpoints.load_t5x_checkpoint(t5x_checkpoint_path)
31
+
32
+ split_mlp_wi = "wi_0" in t5x_model["target"]["encoder"]["layers_0"]["mlp"]
33
+
34
+ if config.model_type == "t5":
35
+ encoder_attn_name = "SelfAttention"
36
+ if config.model_type == "longt5" and config.encoder_attention_type == "local":
37
+ encoder_attn_name = "LocalSelfAttention"
38
+ elif config.model_type == "longt5" and config.encoder_attention_type == "transient-global":
39
+ encoder_attn_name = "TransientGlobalSelfAttention"
40
+ else:
41
+ raise ValueError(
42
+ "Given config is expected to have `model_type='t5'`, or `model_type='longt5` with `encoder_attention_type`"
43
+ " attribute with a value from ['local', 'transient-global]."
44
+ )
45
+
46
+ # Encoder
47
+ for layer_index in range(config.num_layers):
48
+ layer_name = f"layers_{str(layer_index)}"
49
+
50
+ # Self-Attention
51
+ t5x_attention_key = t5x_model["target"]["encoder"][layer_name]["attention"]["key"]["kernel"]
52
+ t5x_attention_out = t5x_model["target"]["encoder"][layer_name]["attention"]["out"]["kernel"]
53
+ t5x_attention_query = t5x_model["target"]["encoder"][layer_name]["attention"]["query"]["kernel"]
54
+ t5x_attention_value = t5x_model["target"]["encoder"][layer_name]["attention"]["value"]["kernel"]
55
+
56
+ # Global input layer norm
57
+ if config.model_type == "longt5" and config.encoder_attention_type == "transient-global":
58
+ t5x_global_layer_norm = t5x_model["target"]["encoder"][layer_name]["attention"]["T5LayerNorm_0"]["scale"]
59
+
60
+ # Layer Normalization
61
+ t5x_attention_layer_norm = t5x_model["target"]["encoder"][layer_name]["pre_attention_layer_norm"]["scale"]
62
+
63
+ if split_mlp_wi:
64
+ t5x_mlp_wi_0 = t5x_model["target"]["encoder"][layer_name]["mlp"]["wi_0"]["kernel"]
65
+ t5x_mlp_wi_1 = t5x_model["target"]["encoder"][layer_name]["mlp"]["wi_1"]["kernel"]
66
+ else:
67
+ t5x_mlp_wi = t5x_model["target"]["encoder"][layer_name]["mlp"]["wi"]["kernel"]
68
+
69
+ t5x_mlp_wo = t5x_model["target"]["encoder"][layer_name]["mlp"]["wo"]["kernel"]
70
+
71
+ # Layer Normalization
72
+ t5x_mlp_layer_norm = t5x_model["target"]["encoder"][layer_name]["pre_mlp_layer_norm"]["scale"]
73
+
74
+ # Assigning
75
+ flax_model_encoder_layer_block = flax_model.params["encoder"]["block"][str(layer_index)]["layer"]
76
+ flax_model_encoder_layer_block["0"][encoder_attn_name]["k"]["kernel"] = t5x_attention_key
77
+ flax_model_encoder_layer_block["0"][encoder_attn_name]["o"]["kernel"] = t5x_attention_out
78
+ flax_model_encoder_layer_block["0"][encoder_attn_name]["q"]["kernel"] = t5x_attention_query
79
+ flax_model_encoder_layer_block["0"][encoder_attn_name]["v"]["kernel"] = t5x_attention_value
80
+
81
+ flax_model_encoder_layer_block["0"]["layer_norm"]["weight"] = t5x_attention_layer_norm
82
+
83
+ # Global input layer norm
84
+ if config.model_type == "longt5" and config.encoder_attention_type == "transient-global":
85
+ flax_model_encoder_layer_block["0"][encoder_attn_name]["global_input_layer_norm"]["weight"] = (
86
+ t5x_global_layer_norm
87
+ )
88
+
89
+ if split_mlp_wi:
90
+ flax_model_encoder_layer_block["1"]["DenseReluDense"]["wi_0"]["kernel"] = t5x_mlp_wi_0
91
+ flax_model_encoder_layer_block["1"]["DenseReluDense"]["wi_1"]["kernel"] = t5x_mlp_wi_1
92
+ else:
93
+ flax_model_encoder_layer_block["1"]["DenseReluDense"]["wi"]["kernel"] = t5x_mlp_wi
94
+
95
+ flax_model_encoder_layer_block["1"]["DenseReluDense"]["wo"]["kernel"] = t5x_mlp_wo
96
+ flax_model_encoder_layer_block["1"]["layer_norm"]["weight"] = t5x_mlp_layer_norm
97
+
98
+ flax_model.params["encoder"]["block"][str(layer_index)]["layer"] = flax_model_encoder_layer_block
99
+
100
+ # Only for layer 0:
101
+ t5x_encoder_rel_embedding = t5x_model["target"]["encoder"]["relpos_bias"]["rel_embedding"].T
102
+ flax_model.params["encoder"]["block"]["0"]["layer"]["0"][encoder_attn_name]["relative_attention_bias"][
103
+ "embedding"
104
+ ] = t5x_encoder_rel_embedding
105
+
106
+ # Side/global relative position_bias + layer norm
107
+ if config.model_type == "longt5" and config.encoder_attention_type == "transient-global":
108
+ t5x_encoder_global_rel_embedding = t5x_model["target"]["encoder"]["side_relpos_bias"]["rel_embedding"].T
109
+ flax_model.params["encoder"]["block"]["0"]["layer"]["0"][encoder_attn_name]["global_relative_attention_bias"][
110
+ "embedding"
111
+ ] = t5x_encoder_global_rel_embedding
112
+
113
+ # Assigning
114
+ t5x_encoder_norm = t5x_model["target"]["encoder"]["encoder_norm"]["scale"]
115
+ flax_model.params["encoder"]["final_layer_norm"]["weight"] = t5x_encoder_norm
116
+
117
+ # Decoder
118
+ for layer_index in range(config.num_layers):
119
+ layer_name = f"layers_{str(layer_index)}"
120
+
121
+ # Self-Attention
122
+ t5x_attention_key = t5x_model["target"]["decoder"][layer_name]["self_attention"]["key"]["kernel"]
123
+ t5x_attention_out = t5x_model["target"]["decoder"][layer_name]["self_attention"]["out"]["kernel"]
124
+ t5x_attention_query = t5x_model["target"]["decoder"][layer_name]["self_attention"]["query"]["kernel"]
125
+ t5x_attention_value = t5x_model["target"]["decoder"][layer_name]["self_attention"]["value"]["kernel"]
126
+
127
+ # Layer Normalization
128
+ t5x_pre_attention_layer_norm = t5x_model["target"]["decoder"][layer_name]["pre_self_attention_layer_norm"][
129
+ "scale"
130
+ ]
131
+
132
+ # Encoder-Decoder-Attention
133
+ t5x_enc_dec_attention_module = t5x_model["target"]["decoder"][layer_name]["encoder_decoder_attention"]
134
+ t5x_enc_dec_attention_key = t5x_enc_dec_attention_module["key"]["kernel"]
135
+ t5x_enc_dec_attention_out = t5x_enc_dec_attention_module["out"]["kernel"]
136
+ t5x_enc_dec_attention_query = t5x_enc_dec_attention_module["query"]["kernel"]
137
+ t5x_enc_dec_attention_value = t5x_enc_dec_attention_module["value"]["kernel"]
138
+
139
+ # Layer Normalization
140
+ t5x_cross_layer_norm = t5x_model["target"]["decoder"][layer_name]["pre_cross_attention_layer_norm"]["scale"]
141
+
142
+ # MLP
143
+ if split_mlp_wi:
144
+ t5x_mlp_wi_0 = t5x_model["target"]["decoder"][layer_name]["mlp"]["wi_0"]["kernel"]
145
+ t5x_mlp_wi_1 = t5x_model["target"]["decoder"][layer_name]["mlp"]["wi_1"]["kernel"]
146
+ else:
147
+ t5x_mlp_wi = t5x_model["target"]["decoder"][layer_name]["mlp"]["wi"]["kernel"]
148
+
149
+ t5x_mlp_wo = t5x_model["target"]["decoder"][layer_name]["mlp"]["wo"]["kernel"]
150
+
151
+ # Layer Normalization
152
+ tx5_mlp_layer_norm = t5x_model["target"]["decoder"][layer_name]["pre_mlp_layer_norm"]["scale"]
153
+
154
+ # Assigning
155
+ flax_model_decoder_layer_block = flax_model.params["decoder"]["block"][str(layer_index)]["layer"]
156
+ flax_model_decoder_layer_block["0"]["SelfAttention"]["k"]["kernel"] = t5x_attention_key
157
+ flax_model_decoder_layer_block["0"]["SelfAttention"]["o"]["kernel"] = t5x_attention_out
158
+ flax_model_decoder_layer_block["0"]["SelfAttention"]["q"]["kernel"] = t5x_attention_query
159
+ flax_model_decoder_layer_block["0"]["SelfAttention"]["v"]["kernel"] = t5x_attention_value
160
+
161
+ flax_model_decoder_layer_block["0"]["layer_norm"]["weight"] = t5x_pre_attention_layer_norm
162
+
163
+ flax_model_decoder_layer_block["1"]["EncDecAttention"]["k"]["kernel"] = t5x_enc_dec_attention_key
164
+ flax_model_decoder_layer_block["1"]["EncDecAttention"]["o"]["kernel"] = t5x_enc_dec_attention_out
165
+ flax_model_decoder_layer_block["1"]["EncDecAttention"]["q"]["kernel"] = t5x_enc_dec_attention_query
166
+ flax_model_decoder_layer_block["1"]["EncDecAttention"]["v"]["kernel"] = t5x_enc_dec_attention_value
167
+
168
+ flax_model_decoder_layer_block["1"]["layer_norm"]["weight"] = t5x_cross_layer_norm
169
+
170
+ if split_mlp_wi:
171
+ flax_model_decoder_layer_block["2"]["DenseReluDense"]["wi_0"]["kernel"] = t5x_mlp_wi_0
172
+ flax_model_decoder_layer_block["2"]["DenseReluDense"]["wi_1"]["kernel"] = t5x_mlp_wi_1
173
+ else:
174
+ flax_model_decoder_layer_block["2"]["DenseReluDense"]["wi"]["kernel"] = t5x_mlp_wi
175
+
176
+ flax_model_decoder_layer_block["2"]["DenseReluDense"]["wo"]["kernel"] = t5x_mlp_wo
177
+
178
+ flax_model_decoder_layer_block["2"]["layer_norm"]["weight"] = tx5_mlp_layer_norm
179
+
180
+ flax_model.params["decoder"]["block"][str(layer_index)]["layer"] = flax_model_decoder_layer_block
181
+
182
+ # Decoder Normalization
183
+ tx5_decoder_norm = t5x_model["target"]["decoder"]["decoder_norm"]["scale"]
184
+ flax_model.params["decoder"]["final_layer_norm"]["weight"] = tx5_decoder_norm
185
+
186
+ # Only for layer 0:
187
+ t5x_decoder_rel_embedding = t5x_model["target"]["decoder"]["relpos_bias"]["rel_embedding"].T
188
+ flax_model.params["decoder"]["block"]["0"]["layer"]["0"]["SelfAttention"]["relative_attention_bias"][
189
+ "embedding"
190
+ ] = t5x_decoder_rel_embedding
191
+
192
+ # Token Embeddings
193
+ tx5_token_embeddings = t5x_model["target"]["token_embedder"]["embedding"]
194
+ flax_model.params["shared"]["embedding"] = tx5_token_embeddings
195
+
196
+ # LM Head (only in v1.1 and LongT5 checkpoints)
197
+ if "logits_dense" in t5x_model["target"]["decoder"]:
198
+ flax_model.params["lm_head"]["kernel"] = t5x_model["target"]["decoder"]["logits_dense"]["kernel"]
199
+
200
+ flax_model.save_pretrained(flax_dump_folder_path)
201
+ print("T5X Model was sucessfully converted!")
202
+
203
+
204
+ if __name__ == "__main__":
205
+ parser = argparse.ArgumentParser()
206
+ # Required parameters
207
+ parser.add_argument(
208
+ "--t5x_checkpoint_path", default=None, type=str, required=True, help="Path the T5X checkpoint."
209
+ )
210
+ parser.add_argument("--config_name", default=None, type=str, required=True, help="Config name of LongT5/T5 model.")
211
+ parser.add_argument(
212
+ "--flax_dump_folder_path", default=None, type=str, required=True, help="Path to the output FLAX model."
213
+ )
214
+ args = parser.parse_args()
215
+ convert_t5x_checkpoint_to_flax(args.t5x_checkpoint_path, args.config_name, args.flax_dump_folder_path)
tasks/tasksmith-441eeab80047/environment/source/src/transformers/models/longt5/modeling_flax_longt5.py ADDED
The diff for this file is too large to render. See raw diff
 
tasks/tasksmith-441eeab80047/environment/source/src/transformers/models/longt5/modeling_longt5.py ADDED
The diff for this file is too large to render. See raw diff
 
tasks/tasksmith-441eeab80047/environment/source/src/transformers/models/luke/__init__.py ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 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 _LazyModule
17
+ from ...utils.import_utils import define_import_structure
18
+
19
+
20
+ if TYPE_CHECKING:
21
+ from .configuration_luke import *
22
+ from .modeling_luke import *
23
+ from .tokenization_luke import *
24
+ else:
25
+ import sys
26
+
27
+ _file = globals()["__file__"]
28
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
tasks/tasksmith-441eeab80047/environment/source/src/transformers/models/luke/configuration_luke.py ADDED
@@ -0,0 +1,142 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright Studio Ousia 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
+ """LUKE configuration"""
16
+
17
+ from ...configuration_utils import PretrainedConfig
18
+ from ...utils import logging
19
+
20
+
21
+ logger = logging.get_logger(__name__)
22
+
23
+
24
+ class LukeConfig(PretrainedConfig):
25
+ r"""
26
+ This is the configuration class to store the configuration of a [`LukeModel`]. It is used to instantiate a LUKE
27
+ model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
28
+ defaults will yield a similar configuration to that of the LUKE
29
+ [studio-ousia/luke-base](https://huggingface.co/studio-ousia/luke-base) architecture.
30
+
31
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
32
+ documentation from [`PretrainedConfig`] for more information.
33
+
34
+
35
+ Args:
36
+ vocab_size (`int`, *optional*, defaults to 50267):
37
+ Vocabulary size of the LUKE model. Defines the number of different tokens that can be represented by the
38
+ `inputs_ids` passed when calling [`LukeModel`].
39
+ entity_vocab_size (`int`, *optional*, defaults to 500000):
40
+ Entity vocabulary size of the LUKE model. Defines the number of different entities that can be represented
41
+ by the `entity_ids` passed when calling [`LukeModel`].
42
+ hidden_size (`int`, *optional*, defaults to 768):
43
+ Dimensionality of the encoder layers and the pooler layer.
44
+ entity_emb_size (`int`, *optional*, defaults to 256):
45
+ The number of dimensions of the entity embedding.
46
+ num_hidden_layers (`int`, *optional*, defaults to 12):
47
+ Number of hidden layers in the Transformer encoder.
48
+ num_attention_heads (`int`, *optional*, defaults to 12):
49
+ Number of attention heads for each attention layer in the Transformer encoder.
50
+ intermediate_size (`int`, *optional*, defaults to 3072):
51
+ Dimensionality of the "intermediate" (often named feed-forward) layer in the Transformer encoder.
52
+ hidden_act (`str` or `Callable`, *optional*, defaults to `"gelu"`):
53
+ The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
54
+ `"relu"`, `"silu"` and `"gelu_new"` are supported.
55
+ hidden_dropout_prob (`float`, *optional*, defaults to 0.1):
56
+ The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
57
+ attention_probs_dropout_prob (`float`, *optional*, defaults to 0.1):
58
+ The dropout ratio for the attention probabilities.
59
+ max_position_embeddings (`int`, *optional*, defaults to 512):
60
+ The maximum sequence length that this model might ever be used with. Typically set this to something large
61
+ just in case (e.g., 512 or 1024 or 2048).
62
+ type_vocab_size (`int`, *optional*, defaults to 2):
63
+ The vocabulary size of the `token_type_ids` passed when calling [`LukeModel`].
64
+ initializer_range (`float`, *optional*, defaults to 0.02):
65
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
66
+ layer_norm_eps (`float`, *optional*, defaults to 1e-12):
67
+ The epsilon used by the layer normalization layers.
68
+ use_entity_aware_attention (`bool`, *optional*, defaults to `True`):
69
+ Whether or not the model should use the entity-aware self-attention mechanism proposed in [LUKE: Deep
70
+ Contextualized Entity Representations with Entity-aware Self-attention (Yamada et
71
+ al.)](https://arxiv.org/abs/2010.01057).
72
+ classifier_dropout (`float`, *optional*):
73
+ The dropout ratio for the classification head.
74
+ pad_token_id (`int`, *optional*, defaults to 1):
75
+ Padding token id.
76
+ bos_token_id (`int`, *optional*, defaults to 0):
77
+ Beginning of stream token id.
78
+ eos_token_id (`int`, *optional*, defaults to 2):
79
+ End of stream token id.
80
+
81
+ Examples:
82
+
83
+ ```python
84
+ >>> from transformers import LukeConfig, LukeModel
85
+
86
+ >>> # Initializing a LUKE configuration
87
+ >>> configuration = LukeConfig()
88
+
89
+ >>> # Initializing a model from the configuration
90
+ >>> model = LukeModel(configuration)
91
+
92
+ >>> # Accessing the model configuration
93
+ >>> configuration = model.config
94
+ ```"""
95
+
96
+ model_type = "luke"
97
+
98
+ def __init__(
99
+ self,
100
+ vocab_size=50267,
101
+ entity_vocab_size=500000,
102
+ hidden_size=768,
103
+ entity_emb_size=256,
104
+ num_hidden_layers=12,
105
+ num_attention_heads=12,
106
+ intermediate_size=3072,
107
+ hidden_act="gelu",
108
+ hidden_dropout_prob=0.1,
109
+ attention_probs_dropout_prob=0.1,
110
+ max_position_embeddings=512,
111
+ type_vocab_size=2,
112
+ initializer_range=0.02,
113
+ layer_norm_eps=1e-12,
114
+ use_entity_aware_attention=True,
115
+ classifier_dropout=None,
116
+ pad_token_id=1,
117
+ bos_token_id=0,
118
+ eos_token_id=2,
119
+ **kwargs,
120
+ ):
121
+ """Constructs LukeConfig."""
122
+ super().__init__(pad_token_id=pad_token_id, bos_token_id=bos_token_id, eos_token_id=eos_token_id, **kwargs)
123
+
124
+ self.vocab_size = vocab_size
125
+ self.entity_vocab_size = entity_vocab_size
126
+ self.hidden_size = hidden_size
127
+ self.entity_emb_size = entity_emb_size
128
+ self.num_hidden_layers = num_hidden_layers
129
+ self.num_attention_heads = num_attention_heads
130
+ self.hidden_act = hidden_act
131
+ self.intermediate_size = intermediate_size
132
+ self.hidden_dropout_prob = hidden_dropout_prob
133
+ self.attention_probs_dropout_prob = attention_probs_dropout_prob
134
+ self.max_position_embeddings = max_position_embeddings
135
+ self.type_vocab_size = type_vocab_size
136
+ self.initializer_range = initializer_range
137
+ self.layer_norm_eps = layer_norm_eps
138
+ self.use_entity_aware_attention = use_entity_aware_attention
139
+ self.classifier_dropout = classifier_dropout
140
+
141
+
142
+ __all__ = ["LukeConfig"]
tasks/tasksmith-441eeab80047/environment/source/src/transformers/models/luke/convert_luke_original_pytorch_checkpoint_to_pytorch.py ADDED
@@ -0,0 +1,170 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 LUKE checkpoint."""
16
+
17
+ import argparse
18
+ import json
19
+ import os
20
+
21
+ import torch
22
+
23
+ from transformers import LukeConfig, LukeModel, LukeTokenizer, RobertaTokenizer
24
+ from transformers.tokenization_utils_base import AddedToken
25
+
26
+
27
+ @torch.no_grad()
28
+ def convert_luke_checkpoint(checkpoint_path, metadata_path, entity_vocab_path, pytorch_dump_folder_path, model_size):
29
+ # Load configuration defined in the metadata file
30
+ with open(metadata_path) as metadata_file:
31
+ metadata = json.load(metadata_file)
32
+ config = LukeConfig(use_entity_aware_attention=True, **metadata["model_config"])
33
+
34
+ # Load in the weights from the checkpoint_path
35
+ state_dict = torch.load(checkpoint_path, map_location="cpu")
36
+
37
+ # Load the entity vocab file
38
+ entity_vocab = load_entity_vocab(entity_vocab_path)
39
+
40
+ tokenizer = RobertaTokenizer.from_pretrained(metadata["model_config"]["bert_model_name"])
41
+
42
+ # Add special tokens to the token vocabulary for downstream tasks
43
+ entity_token_1 = AddedToken("<ent>", lstrip=False, rstrip=False)
44
+ entity_token_2 = AddedToken("<ent2>", lstrip=False, rstrip=False)
45
+ tokenizer.add_special_tokens({"additional_special_tokens": [entity_token_1, entity_token_2]})
46
+ config.vocab_size += 2
47
+
48
+ print(f"Saving tokenizer to {pytorch_dump_folder_path}")
49
+ tokenizer.save_pretrained(pytorch_dump_folder_path)
50
+ with open(os.path.join(pytorch_dump_folder_path, LukeTokenizer.vocab_files_names["entity_vocab_file"]), "w") as f:
51
+ json.dump(entity_vocab, f)
52
+
53
+ tokenizer = LukeTokenizer.from_pretrained(pytorch_dump_folder_path)
54
+
55
+ # Initialize the embeddings of the special tokens
56
+ word_emb = state_dict["embeddings.word_embeddings.weight"]
57
+ ent_emb = word_emb[tokenizer.convert_tokens_to_ids(["@"])[0]].unsqueeze(0)
58
+ ent2_emb = word_emb[tokenizer.convert_tokens_to_ids(["#"])[0]].unsqueeze(0)
59
+ state_dict["embeddings.word_embeddings.weight"] = torch.cat([word_emb, ent_emb, ent2_emb])
60
+
61
+ # Initialize the query layers of the entity-aware self-attention mechanism
62
+ for layer_index in range(config.num_hidden_layers):
63
+ for matrix_name in ["query.weight", "query.bias"]:
64
+ prefix = f"encoder.layer.{layer_index}.attention.self."
65
+ state_dict[prefix + "w2e_" + matrix_name] = state_dict[prefix + matrix_name]
66
+ state_dict[prefix + "e2w_" + matrix_name] = state_dict[prefix + matrix_name]
67
+ state_dict[prefix + "e2e_" + matrix_name] = state_dict[prefix + matrix_name]
68
+
69
+ # Initialize the embedding of the [MASK2] entity using that of the [MASK] entity for downstream tasks
70
+ entity_emb = state_dict["entity_embeddings.entity_embeddings.weight"]
71
+ entity_emb[entity_vocab["[MASK2]"]] = entity_emb[entity_vocab["[MASK]"]]
72
+
73
+ model = LukeModel(config=config).eval()
74
+
75
+ missing_keys, unexpected_keys = model.load_state_dict(state_dict, strict=False)
76
+ if not (len(missing_keys) == 1 and missing_keys[0] == "embeddings.position_ids"):
77
+ raise ValueError(f"Missing keys {', '.join(missing_keys)}. Expected only missing embeddings.position_ids")
78
+ if not (all(key.startswith("entity_predictions") or key.startswith("lm_head") for key in unexpected_keys)):
79
+ raise ValueError(
80
+ "Unexpected keys"
81
+ f" {', '.join([key for key in unexpected_keys if not (key.startswith('entity_predictions') or key.startswith('lm_head'))])}"
82
+ )
83
+
84
+ # Check outputs
85
+ tokenizer = LukeTokenizer.from_pretrained(pytorch_dump_folder_path, task="entity_classification")
86
+
87
+ text = (
88
+ "Top seed Ana Ivanovic said on Thursday she could hardly believe her luck as a fortuitous netcord helped the"
89
+ " new world number one avoid a humiliating second- round exit at Wimbledon ."
90
+ )
91
+ span = (39, 42)
92
+ encoding = tokenizer(text, entity_spans=[span], add_prefix_space=True, return_tensors="pt")
93
+
94
+ outputs = model(**encoding)
95
+
96
+ # Verify word hidden states
97
+ if model_size == "large":
98
+ expected_shape = torch.Size((1, 42, 1024))
99
+ expected_slice = torch.tensor(
100
+ [[0.0133, 0.0865, 0.0095], [0.3093, -0.2576, -0.7418], [-0.1720, -0.2117, -0.2869]]
101
+ )
102
+ else: # base
103
+ expected_shape = torch.Size((1, 42, 768))
104
+ expected_slice = torch.tensor([[0.0037, 0.1368, -0.0091], [0.1099, 0.3329, -0.1095], [0.0765, 0.5335, 0.1179]])
105
+
106
+ if not (outputs.last_hidden_state.shape == expected_shape):
107
+ raise ValueError(
108
+ f"Outputs.last_hidden_state.shape is {outputs.last_hidden_state.shape}, Expected shape is {expected_shape}"
109
+ )
110
+ if not torch.allclose(outputs.last_hidden_state[0, :3, :3], expected_slice, atol=1e-4):
111
+ raise ValueError
112
+
113
+ # Verify entity hidden states
114
+ if model_size == "large":
115
+ expected_shape = torch.Size((1, 1, 1024))
116
+ expected_slice = torch.tensor([[0.0466, -0.0106, -0.0179]])
117
+ else: # base
118
+ expected_shape = torch.Size((1, 1, 768))
119
+ expected_slice = torch.tensor([[0.1457, 0.1044, 0.0174]])
120
+
121
+ if not (outputs.entity_last_hidden_state.shape != expected_shape):
122
+ raise ValueError(
123
+ f"Outputs.entity_last_hidden_state.shape is {outputs.entity_last_hidden_state.shape}, Expected shape is"
124
+ f" {expected_shape}"
125
+ )
126
+ if not torch.allclose(outputs.entity_last_hidden_state[0, :3, :3], expected_slice, atol=1e-4):
127
+ raise ValueError
128
+
129
+ # Finally, save our PyTorch model and tokenizer
130
+ print("Saving PyTorch model to {}".format(pytorch_dump_folder_path))
131
+ model.save_pretrained(pytorch_dump_folder_path)
132
+
133
+
134
+ def load_entity_vocab(entity_vocab_path):
135
+ entity_vocab = {}
136
+ with open(entity_vocab_path, "r", encoding="utf-8") as f:
137
+ for index, line in enumerate(f):
138
+ title, _ = line.rstrip().split("\t")
139
+ entity_vocab[title] = index
140
+
141
+ return entity_vocab
142
+
143
+
144
+ if __name__ == "__main__":
145
+ parser = argparse.ArgumentParser()
146
+ # Required parameters
147
+ parser.add_argument("--checkpoint_path", type=str, help="Path to a pytorch_model.bin file.")
148
+ parser.add_argument(
149
+ "--metadata_path", default=None, type=str, help="Path to a metadata.json file, defining the configuration."
150
+ )
151
+ parser.add_argument(
152
+ "--entity_vocab_path",
153
+ default=None,
154
+ type=str,
155
+ help="Path to an entity_vocab.tsv file, containing the entity vocabulary.",
156
+ )
157
+ parser.add_argument(
158
+ "--pytorch_dump_folder_path", default=None, type=str, help="Path to where to dump the output PyTorch model."
159
+ )
160
+ parser.add_argument(
161
+ "--model_size", default="base", type=str, choices=["base", "large"], help="Size of the model to be converted."
162
+ )
163
+ args = parser.parse_args()
164
+ convert_luke_checkpoint(
165
+ args.checkpoint_path,
166
+ args.metadata_path,
167
+ args.entity_vocab_path,
168
+ args.pytorch_dump_folder_path,
169
+ args.model_size,
170
+ )
tasks/tasksmith-441eeab80047/environment/source/src/transformers/models/luke/modeling_luke.py ADDED
The diff for this file is too large to render. See raw diff
 
tasks/tasksmith-441eeab80047/environment/source/src/transformers/models/luke/tokenization_luke.py ADDED
@@ -0,0 +1,1731 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright Studio-Ouisa and The HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """Tokenization classes for LUKE."""
16
+
17
+ import itertools
18
+ import json
19
+ import os
20
+ from collections.abc import Mapping
21
+ from functools import lru_cache
22
+ from typing import Dict, List, Optional, Tuple, Union
23
+
24
+ import numpy as np
25
+ import regex as re
26
+
27
+ from ...tokenization_utils import PreTrainedTokenizer
28
+ from ...tokenization_utils_base import (
29
+ ENCODE_KWARGS_DOCSTRING,
30
+ AddedToken,
31
+ BatchEncoding,
32
+ EncodedInput,
33
+ PaddingStrategy,
34
+ TensorType,
35
+ TextInput,
36
+ TextInputPair,
37
+ TruncationStrategy,
38
+ to_py_obj,
39
+ )
40
+ from ...utils import add_end_docstrings, is_tf_tensor, is_torch_tensor, logging
41
+
42
+
43
+ logger = logging.get_logger(__name__)
44
+
45
+ EntitySpan = Tuple[int, int]
46
+ EntitySpanInput = List[EntitySpan]
47
+ Entity = str
48
+ EntityInput = List[Entity]
49
+
50
+ VOCAB_FILES_NAMES = {
51
+ "vocab_file": "vocab.json",
52
+ "merges_file": "merges.txt",
53
+ "entity_vocab_file": "entity_vocab.json",
54
+ }
55
+
56
+
57
+ ENCODE_PLUS_ADDITIONAL_KWARGS_DOCSTRING = r"""
58
+ return_token_type_ids (`bool`, *optional*):
59
+ Whether to return token type IDs. If left to the default, will return the token type IDs according to
60
+ the specific tokenizer's default, defined by the `return_outputs` attribute.
61
+
62
+ [What are token type IDs?](../glossary#token-type-ids)
63
+ return_attention_mask (`bool`, *optional*):
64
+ Whether to return the attention mask. If left to the default, will return the attention mask according
65
+ to the specific tokenizer's default, defined by the `return_outputs` attribute.
66
+
67
+ [What are attention masks?](../glossary#attention-mask)
68
+ return_overflowing_tokens (`bool`, *optional*, defaults to `False`):
69
+ Whether or not to return overflowing token sequences. If a pair of sequences of input ids (or a batch
70
+ of pairs) is provided with `truncation_strategy = longest_first` or `True`, an error is raised instead
71
+ of returning overflowing tokens.
72
+ return_special_tokens_mask (`bool`, *optional*, defaults to `False`):
73
+ Whether or not to return special tokens mask information.
74
+ return_offsets_mapping (`bool`, *optional*, defaults to `False`):
75
+ Whether or not to return `(char_start, char_end)` for each token.
76
+
77
+ This is only available on fast tokenizers inheriting from [`PreTrainedTokenizerFast`], if using
78
+ Python's tokenizer, this method will raise `NotImplementedError`.
79
+ return_length (`bool`, *optional*, defaults to `False`):
80
+ Whether or not to return the lengths of the encoded inputs.
81
+ verbose (`bool`, *optional*, defaults to `True`):
82
+ Whether or not to print more information and warnings.
83
+ **kwargs: passed to the `self.tokenize()` method
84
+
85
+ Return:
86
+ [`BatchEncoding`]: A [`BatchEncoding`] with the following fields:
87
+
88
+ - **input_ids** -- List of token ids to be fed to a model.
89
+
90
+ [What are input IDs?](../glossary#input-ids)
91
+
92
+ - **token_type_ids** -- List of token type ids to be fed to a model (when `return_token_type_ids=True` or
93
+ if *"token_type_ids"* is in `self.model_input_names`).
94
+
95
+ [What are token type IDs?](../glossary#token-type-ids)
96
+
97
+ - **attention_mask** -- List of indices specifying which tokens should be attended to by the model (when
98
+ `return_attention_mask=True` or if *"attention_mask"* is in `self.model_input_names`).
99
+
100
+ [What are attention masks?](../glossary#attention-mask)
101
+
102
+ - **entity_ids** -- List of entity ids to be fed to a model.
103
+
104
+ [What are input IDs?](../glossary#input-ids)
105
+
106
+ - **entity_position_ids** -- List of entity positions in the input sequence to be fed to a model.
107
+
108
+ - **entity_token_type_ids** -- List of entity token type ids to be fed to a model (when
109
+ `return_token_type_ids=True` or if *"entity_token_type_ids"* is in `self.model_input_names`).
110
+
111
+ [What are token type IDs?](../glossary#token-type-ids)
112
+
113
+ - **entity_attention_mask** -- List of indices specifying which entities should be attended to by the model
114
+ (when `return_attention_mask=True` or if *"entity_attention_mask"* is in `self.model_input_names`).
115
+
116
+ [What are attention masks?](../glossary#attention-mask)
117
+
118
+ - **entity_start_positions** -- List of the start positions of entities in the word token sequence (when
119
+ `task="entity_span_classification"`).
120
+ - **entity_end_positions** -- List of the end positions of entities in the word token sequence (when
121
+ `task="entity_span_classification"`).
122
+ - **overflowing_tokens** -- List of overflowing tokens sequences (when a `max_length` is specified and
123
+ `return_overflowing_tokens=True`).
124
+ - **num_truncated_tokens** -- Number of tokens truncated (when a `max_length` is specified and
125
+ `return_overflowing_tokens=True`).
126
+ - **special_tokens_mask** -- List of 0s and 1s, with 1 specifying added special tokens and 0 specifying
127
+ regular sequence tokens (when `add_special_tokens=True` and `return_special_tokens_mask=True`).
128
+ - **length** -- The length of the inputs (when `return_length=True`)
129
+
130
+ """
131
+
132
+
133
+ @lru_cache()
134
+ # Copied from transformers.models.roberta.tokenization_roberta.bytes_to_unicode
135
+ def bytes_to_unicode():
136
+ """
137
+ Returns list of utf-8 byte and a mapping to unicode strings. We specifically avoids mapping to whitespace/control
138
+ characters the bpe code barfs on.
139
+
140
+ The reversible bpe codes work on unicode strings. This means you need a large # of unicode characters in your vocab
141
+ if you want to avoid UNKs. When you're at something like a 10B token dataset you end up needing around 5K for
142
+ decent coverage. This is a significant percentage of your normal, say, 32K bpe vocab. To avoid that, we want lookup
143
+ tables between utf-8 bytes and unicode strings.
144
+ """
145
+ bs = (
146
+ list(range(ord("!"), ord("~") + 1)) + list(range(ord("¡"), ord("¬") + 1)) + list(range(ord("®"), ord("ÿ") + 1))
147
+ )
148
+ cs = bs[:]
149
+ n = 0
150
+ for b in range(2**8):
151
+ if b not in bs:
152
+ bs.append(b)
153
+ cs.append(2**8 + n)
154
+ n += 1
155
+ cs = [chr(n) for n in cs]
156
+ return dict(zip(bs, cs))
157
+
158
+
159
+ # Copied from transformers.models.roberta.tokenization_roberta.get_pairs
160
+ def get_pairs(word):
161
+ """
162
+ Return set of symbol pairs in a word.
163
+
164
+ Word is represented as tuple of symbols (symbols being variable-length strings).
165
+ """
166
+ pairs = set()
167
+ prev_char = word[0]
168
+ for char in word[1:]:
169
+ pairs.add((prev_char, char))
170
+ prev_char = char
171
+ return pairs
172
+
173
+
174
+ class LukeTokenizer(PreTrainedTokenizer):
175
+ """
176
+ Constructs a LUKE tokenizer, derived from the GPT-2 tokenizer, using byte-level Byte-Pair-Encoding.
177
+
178
+ This tokenizer has been trained to treat spaces like parts of the tokens (a bit like sentencepiece) so a word will
179
+ be encoded differently whether it is at the beginning of the sentence (without space) or not:
180
+
181
+ ```python
182
+ >>> from transformers import LukeTokenizer
183
+
184
+ >>> tokenizer = LukeTokenizer.from_pretrained("studio-ousia/luke-base")
185
+ >>> tokenizer("Hello world")["input_ids"]
186
+ [0, 31414, 232, 2]
187
+
188
+ >>> tokenizer(" Hello world")["input_ids"]
189
+ [0, 20920, 232, 2]
190
+ ```
191
+
192
+ You can get around that behavior by passing `add_prefix_space=True` when instantiating this tokenizer or when you
193
+ call it on some text, but since the model was not pretrained this way, it might yield a decrease in performance.
194
+
195
+ <Tip>
196
+
197
+ When used with `is_split_into_words=True`, this tokenizer will add a space before each word (even the first one).
198
+
199
+ </Tip>
200
+
201
+ This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to
202
+ this superclass for more information regarding those methods. It also creates entity sequences, namely
203
+ `entity_ids`, `entity_attention_mask`, `entity_token_type_ids`, and `entity_position_ids` to be used by the LUKE
204
+ model.
205
+
206
+ Args:
207
+ vocab_file (`str`):
208
+ Path to the vocabulary file.
209
+ merges_file (`str`):
210
+ Path to the merges file.
211
+ entity_vocab_file (`str`):
212
+ Path to the entity vocabulary file.
213
+ task (`str`, *optional*):
214
+ Task for which you want to prepare sequences. One of `"entity_classification"`,
215
+ `"entity_pair_classification"`, or `"entity_span_classification"`. If you specify this argument, the entity
216
+ sequence is automatically created based on the given entity span(s).
217
+ max_entity_length (`int`, *optional*, defaults to 32):
218
+ The maximum length of `entity_ids`.
219
+ max_mention_length (`int`, *optional*, defaults to 30):
220
+ The maximum number of tokens inside an entity span.
221
+ entity_token_1 (`str`, *optional*, defaults to `<ent>`):
222
+ The special token used to represent an entity span in a word token sequence. This token is only used when
223
+ `task` is set to `"entity_classification"` or `"entity_pair_classification"`.
224
+ entity_token_2 (`str`, *optional*, defaults to `<ent2>`):
225
+ The special token used to represent an entity span in a word token sequence. This token is only used when
226
+ `task` is set to `"entity_pair_classification"`.
227
+ errors (`str`, *optional*, defaults to `"replace"`):
228
+ Paradigm to follow when decoding bytes to UTF-8. See
229
+ [bytes.decode](https://docs.python.org/3/library/stdtypes.html#bytes.decode) for more information.
230
+ bos_token (`str`, *optional*, defaults to `"<s>"`):
231
+ The beginning of sequence token that was used during pretraining. Can be used a sequence classifier token.
232
+
233
+ <Tip>
234
+
235
+ When building a sequence using special tokens, this is not the token that is used for the beginning of
236
+ sequence. The token used is the `cls_token`.
237
+
238
+ </Tip>
239
+
240
+ eos_token (`str`, *optional*, defaults to `"</s>"`):
241
+ The end of sequence token.
242
+
243
+ <Tip>
244
+
245
+ When building a sequence using special tokens, this is not the token that is used for the end of sequence.
246
+ The token used is the `sep_token`.
247
+
248
+ </Tip>
249
+
250
+ sep_token (`str`, *optional*, defaults to `"</s>"`):
251
+ The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
252
+ sequence classification or for a text and a question for question answering. It is also used as the last
253
+ token of a sequence built with special tokens.
254
+ cls_token (`str`, *optional*, defaults to `"<s>"`):
255
+ The classifier token which is used when doing sequence classification (classification of the whole sequence
256
+ instead of per-token classification). It is the first token of the sequence when built with special tokens.
257
+ unk_token (`str`, *optional*, defaults to `"<unk>"`):
258
+ The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
259
+ token instead.
260
+ pad_token (`str`, *optional*, defaults to `"<pad>"`):
261
+ The token used for padding, for example when batching sequences of different lengths.
262
+ mask_token (`str`, *optional*, defaults to `"<mask>"`):
263
+ The token used for masking values. This is the token used when training this model with masked language
264
+ modeling. This is the token which the model will try to predict.
265
+ add_prefix_space (`bool`, *optional*, defaults to `False`):
266
+ Whether or not to add an initial space to the input. This allows to treat the leading word just as any
267
+ other word. (LUKE tokenizer detect beginning of words by the preceding space).
268
+ """
269
+
270
+ vocab_files_names = VOCAB_FILES_NAMES
271
+ model_input_names = ["input_ids", "attention_mask"]
272
+
273
+ def __init__(
274
+ self,
275
+ vocab_file,
276
+ merges_file,
277
+ entity_vocab_file,
278
+ task=None,
279
+ max_entity_length=32,
280
+ max_mention_length=30,
281
+ entity_token_1="<ent>",
282
+ entity_token_2="<ent2>",
283
+ entity_unk_token="[UNK]",
284
+ entity_pad_token="[PAD]",
285
+ entity_mask_token="[MASK]",
286
+ entity_mask2_token="[MASK2]",
287
+ errors="replace",
288
+ bos_token="<s>",
289
+ eos_token="</s>",
290
+ sep_token="</s>",
291
+ cls_token="<s>",
292
+ unk_token="<unk>",
293
+ pad_token="<pad>",
294
+ mask_token="<mask>",
295
+ add_prefix_space=False,
296
+ **kwargs,
297
+ ):
298
+ bos_token = AddedToken(bos_token, lstrip=False, rstrip=False) if isinstance(bos_token, str) else bos_token
299
+ eos_token = AddedToken(eos_token, lstrip=False, rstrip=False) if isinstance(eos_token, str) else eos_token
300
+ sep_token = AddedToken(sep_token, lstrip=False, rstrip=False) if isinstance(sep_token, str) else sep_token
301
+ cls_token = AddedToken(cls_token, lstrip=False, rstrip=False) if isinstance(cls_token, str) else cls_token
302
+ unk_token = AddedToken(unk_token, lstrip=False, rstrip=False) if isinstance(unk_token, str) else unk_token
303
+ pad_token = AddedToken(pad_token, lstrip=False, rstrip=False) if isinstance(pad_token, str) else pad_token
304
+
305
+ # Mask token behave like a normal word, i.e. include the space before it
306
+ mask_token = AddedToken(mask_token, lstrip=True, rstrip=False) if isinstance(mask_token, str) else mask_token
307
+
308
+ with open(vocab_file, encoding="utf-8") as vocab_handle:
309
+ self.encoder = json.load(vocab_handle)
310
+ self.decoder = {v: k for k, v in self.encoder.items()}
311
+ self.errors = errors # how to handle errors in decoding
312
+ self.byte_encoder = bytes_to_unicode()
313
+ self.byte_decoder = {v: k for k, v in self.byte_encoder.items()}
314
+ with open(merges_file, encoding="utf-8") as merges_handle:
315
+ bpe_merges = merges_handle.read().split("\n")[1:-1]
316
+ bpe_merges = [tuple(merge.split()) for merge in bpe_merges]
317
+ self.bpe_ranks = dict(zip(bpe_merges, range(len(bpe_merges))))
318
+ self.cache = {}
319
+ self.add_prefix_space = add_prefix_space
320
+
321
+ # Should have added re.IGNORECASE so BPE merges can happen for capitalized versions of contractions
322
+ self.pat = re.compile(r"""'s|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+""")
323
+
324
+ # we add 2 special tokens for downstream tasks
325
+ # for more information about lstrip and rstrip, see https://github.com/huggingface/transformers/pull/2778
326
+ entity_token_1 = (
327
+ AddedToken(entity_token_1, lstrip=False, rstrip=False)
328
+ if isinstance(entity_token_1, str)
329
+ else entity_token_1
330
+ )
331
+ entity_token_2 = (
332
+ AddedToken(entity_token_2, lstrip=False, rstrip=False)
333
+ if isinstance(entity_token_2, str)
334
+ else entity_token_2
335
+ )
336
+ kwargs["additional_special_tokens"] = kwargs.get("additional_special_tokens", [])
337
+ kwargs["additional_special_tokens"] += [entity_token_1, entity_token_2]
338
+
339
+ with open(entity_vocab_file, encoding="utf-8") as entity_vocab_handle:
340
+ self.entity_vocab = json.load(entity_vocab_handle)
341
+ for entity_special_token in [entity_unk_token, entity_pad_token, entity_mask_token, entity_mask2_token]:
342
+ if entity_special_token not in self.entity_vocab:
343
+ raise ValueError(
344
+ f"Specified entity special token ``{entity_special_token}`` is not found in entity_vocab. "
345
+ f"Probably an incorrect entity vocab file is loaded: {entity_vocab_file}."
346
+ )
347
+ self.entity_unk_token_id = self.entity_vocab[entity_unk_token]
348
+ self.entity_pad_token_id = self.entity_vocab[entity_pad_token]
349
+ self.entity_mask_token_id = self.entity_vocab[entity_mask_token]
350
+ self.entity_mask2_token_id = self.entity_vocab[entity_mask2_token]
351
+
352
+ self.task = task
353
+ if task is None or task == "entity_span_classification":
354
+ self.max_entity_length = max_entity_length
355
+ elif task == "entity_classification":
356
+ self.max_entity_length = 1
357
+ elif task == "entity_pair_classification":
358
+ self.max_entity_length = 2
359
+ else:
360
+ raise ValueError(
361
+ f"Task {task} not supported. Select task from ['entity_classification', 'entity_pair_classification',"
362
+ " 'entity_span_classification'] only."
363
+ )
364
+
365
+ self.max_mention_length = max_mention_length
366
+
367
+ super().__init__(
368
+ errors=errors,
369
+ bos_token=bos_token,
370
+ eos_token=eos_token,
371
+ unk_token=unk_token,
372
+ sep_token=sep_token,
373
+ cls_token=cls_token,
374
+ pad_token=pad_token,
375
+ mask_token=mask_token,
376
+ add_prefix_space=add_prefix_space,
377
+ task=task,
378
+ max_entity_length=32,
379
+ max_mention_length=30,
380
+ entity_token_1="<ent>",
381
+ entity_token_2="<ent2>",
382
+ entity_unk_token=entity_unk_token,
383
+ entity_pad_token=entity_pad_token,
384
+ entity_mask_token=entity_mask_token,
385
+ entity_mask2_token=entity_mask2_token,
386
+ **kwargs,
387
+ )
388
+
389
+ @property
390
+ # Copied from transformers.models.roberta.tokenization_roberta.RobertaTokenizer.vocab_size with Roberta->Luke, RoBERTa->LUKE
391
+ def vocab_size(self):
392
+ return len(self.encoder)
393
+
394
+ # Copied from transformers.models.roberta.tokenization_roberta.RobertaTokenizer.get_vocab with Roberta->Luke, RoBERTa->LUKE
395
+ def get_vocab(self):
396
+ vocab = dict(self.encoder).copy()
397
+ vocab.update(self.added_tokens_encoder)
398
+ return vocab
399
+
400
+ # Copied from transformers.models.roberta.tokenization_roberta.RobertaTokenizer.bpe with Roberta->Luke, RoBERTa->LUKE
401
+ def bpe(self, token):
402
+ if token in self.cache:
403
+ return self.cache[token]
404
+ word = tuple(token)
405
+ pairs = get_pairs(word)
406
+
407
+ if not pairs:
408
+ return token
409
+
410
+ while True:
411
+ bigram = min(pairs, key=lambda pair: self.bpe_ranks.get(pair, float("inf")))
412
+ if bigram not in self.bpe_ranks:
413
+ break
414
+ first, second = bigram
415
+ new_word = []
416
+ i = 0
417
+ while i < len(word):
418
+ try:
419
+ j = word.index(first, i)
420
+ except ValueError:
421
+ new_word.extend(word[i:])
422
+ break
423
+ else:
424
+ new_word.extend(word[i:j])
425
+ i = j
426
+
427
+ if word[i] == first and i < len(word) - 1 and word[i + 1] == second:
428
+ new_word.append(first + second)
429
+ i += 2
430
+ else:
431
+ new_word.append(word[i])
432
+ i += 1
433
+ new_word = tuple(new_word)
434
+ word = new_word
435
+ if len(word) == 1:
436
+ break
437
+ else:
438
+ pairs = get_pairs(word)
439
+ word = " ".join(word)
440
+ self.cache[token] = word
441
+ return word
442
+
443
+ # Copied from transformers.models.roberta.tokenization_roberta.RobertaTokenizer._tokenize with Roberta->Luke, RoBERTa->LUKE
444
+ def _tokenize(self, text):
445
+ """Tokenize a string."""
446
+ bpe_tokens = []
447
+ for token in re.findall(self.pat, text):
448
+ token = "".join(
449
+ self.byte_encoder[b] for b in token.encode("utf-8")
450
+ ) # Maps all our bytes to unicode strings, avoiding control tokens of the BPE (spaces in our case)
451
+ bpe_tokens.extend(bpe_token for bpe_token in self.bpe(token).split(" "))
452
+ return bpe_tokens
453
+
454
+ # Copied from transformers.models.roberta.tokenization_roberta.RobertaTokenizer._convert_token_to_id with Roberta->Luke, RoBERTa->LUKE
455
+ def _convert_token_to_id(self, token):
456
+ """Converts a token (str) in an id using the vocab."""
457
+ return self.encoder.get(token, self.encoder.get(self.unk_token))
458
+
459
+ # Copied from transformers.models.roberta.tokenization_roberta.RobertaTokenizer._convert_id_to_token with Roberta->Luke, RoBERTa->LUKE
460
+ def _convert_id_to_token(self, index):
461
+ """Converts an index (integer) in a token (str) using the vocab."""
462
+ return self.decoder.get(index)
463
+
464
+ # Copied from transformers.models.roberta.tokenization_roberta.RobertaTokenizer.convert_tokens_to_string with Roberta->Luke, RoBERTa->LUKE
465
+ def convert_tokens_to_string(self, tokens):
466
+ """Converts a sequence of tokens (string) in a single string."""
467
+ text = "".join(tokens)
468
+ text = bytearray([self.byte_decoder[c] for c in text]).decode("utf-8", errors=self.errors)
469
+ return text
470
+
471
+ # Copied from transformers.models.roberta.tokenization_roberta.RobertaTokenizer.build_inputs_with_special_tokens with Roberta->Luke, RoBERTa->LUKE
472
+ def build_inputs_with_special_tokens(
473
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
474
+ ) -> List[int]:
475
+ """
476
+ Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
477
+ adding special tokens. A LUKE sequence has the following format:
478
+
479
+ - single sequence: `<s> X </s>`
480
+ - pair of sequences: `<s> A </s></s> B </s>`
481
+
482
+ Args:
483
+ token_ids_0 (`List[int]`):
484
+ List of IDs to which the special tokens will be added.
485
+ token_ids_1 (`List[int]`, *optional*):
486
+ Optional second list of IDs for sequence pairs.
487
+
488
+ Returns:
489
+ `List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
490
+ """
491
+ if token_ids_1 is None:
492
+ return [self.cls_token_id] + token_ids_0 + [self.sep_token_id]
493
+ cls = [self.cls_token_id]
494
+ sep = [self.sep_token_id]
495
+ return cls + token_ids_0 + sep + sep + token_ids_1 + sep
496
+
497
+ # Copied from transformers.models.roberta.tokenization_roberta.RobertaTokenizer.get_special_tokens_mask with Roberta->Luke, RoBERTa->LUKE
498
+ def get_special_tokens_mask(
499
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None, already_has_special_tokens: bool = False
500
+ ) -> List[int]:
501
+ """
502
+ Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
503
+ special tokens using the tokenizer `prepare_for_model` method.
504
+
505
+ Args:
506
+ token_ids_0 (`List[int]`):
507
+ List of IDs.
508
+ token_ids_1 (`List[int]`, *optional*):
509
+ Optional second list of IDs for sequence pairs.
510
+ already_has_special_tokens (`bool`, *optional*, defaults to `False`):
511
+ Whether or not the token list is already formatted with special tokens for the model.
512
+
513
+ Returns:
514
+ `List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
515
+ """
516
+ if already_has_special_tokens:
517
+ return super().get_special_tokens_mask(
518
+ token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
519
+ )
520
+
521
+ if token_ids_1 is None:
522
+ return [1] + ([0] * len(token_ids_0)) + [1]
523
+ return [1] + ([0] * len(token_ids_0)) + [1, 1] + ([0] * len(token_ids_1)) + [1]
524
+
525
+ # Copied from transformers.models.roberta.tokenization_roberta.RobertaTokenizer.create_token_type_ids_from_sequences with Roberta->Luke, RoBERTa->LUKE
526
+ def create_token_type_ids_from_sequences(
527
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
528
+ ) -> List[int]:
529
+ """
530
+ Create a mask from the two sequences passed to be used in a sequence-pair classification task. LUKE does not
531
+ make use of token type ids, therefore a list of zeros is returned.
532
+
533
+ Args:
534
+ token_ids_0 (`List[int]`):
535
+ List of IDs.
536
+ token_ids_1 (`List[int]`, *optional*):
537
+ Optional second list of IDs for sequence pairs.
538
+
539
+ Returns:
540
+ `List[int]`: List of zeros.
541
+ """
542
+ sep = [self.sep_token_id]
543
+ cls = [self.cls_token_id]
544
+
545
+ if token_ids_1 is None:
546
+ return len(cls + token_ids_0 + sep) * [0]
547
+ return len(cls + token_ids_0 + sep + sep + token_ids_1 + sep) * [0]
548
+
549
+ # Copied from transformers.models.roberta.tokenization_roberta.RobertaTokenizer.prepare_for_tokenization with Roberta->Luke, RoBERTa->LUKE
550
+ def prepare_for_tokenization(self, text, is_split_into_words=False, **kwargs):
551
+ add_prefix_space = kwargs.pop("add_prefix_space", self.add_prefix_space)
552
+ if (is_split_into_words or add_prefix_space) and (len(text) > 0 and not text[0].isspace()):
553
+ text = " " + text
554
+ return (text, kwargs)
555
+
556
+ @add_end_docstrings(ENCODE_KWARGS_DOCSTRING, ENCODE_PLUS_ADDITIONAL_KWARGS_DOCSTRING)
557
+ def __call__(
558
+ self,
559
+ text: Union[TextInput, List[TextInput]],
560
+ text_pair: Optional[Union[TextInput, List[TextInput]]] = None,
561
+ entity_spans: Optional[Union[EntitySpanInput, List[EntitySpanInput]]] = None,
562
+ entity_spans_pair: Optional[Union[EntitySpanInput, List[EntitySpanInput]]] = None,
563
+ entities: Optional[Union[EntityInput, List[EntityInput]]] = None,
564
+ entities_pair: Optional[Union[EntityInput, List[EntityInput]]] = None,
565
+ add_special_tokens: bool = True,
566
+ padding: Union[bool, str, PaddingStrategy] = False,
567
+ truncation: Union[bool, str, TruncationStrategy] = None,
568
+ max_length: Optional[int] = None,
569
+ max_entity_length: Optional[int] = None,
570
+ stride: int = 0,
571
+ is_split_into_words: Optional[bool] = False,
572
+ pad_to_multiple_of: Optional[int] = None,
573
+ padding_side: Optional[str] = None,
574
+ return_tensors: Optional[Union[str, TensorType]] = None,
575
+ return_token_type_ids: Optional[bool] = None,
576
+ return_attention_mask: Optional[bool] = None,
577
+ return_overflowing_tokens: bool = False,
578
+ return_special_tokens_mask: bool = False,
579
+ return_offsets_mapping: bool = False,
580
+ return_length: bool = False,
581
+ verbose: bool = True,
582
+ **kwargs,
583
+ ) -> BatchEncoding:
584
+ """
585
+ Main method to tokenize and prepare for the model one or several sequence(s) or one or several pair(s) of
586
+ sequences, depending on the task you want to prepare them for.
587
+
588
+ Args:
589
+ text (`str`, `List[str]`, `List[List[str]]`):
590
+ The sequence or batch of sequences to be encoded. Each sequence must be a string. Note that this
591
+ tokenizer does not support tokenization based on pretokenized strings.
592
+ text_pair (`str`, `List[str]`, `List[List[str]]`):
593
+ The sequence or batch of sequences to be encoded. Each sequence must be a string. Note that this
594
+ tokenizer does not support tokenization based on pretokenized strings.
595
+ entity_spans (`List[Tuple[int, int]]`, `List[List[Tuple[int, int]]]`, *optional*):
596
+ The sequence or batch of sequences of entity spans to be encoded. Each sequence consists of tuples each
597
+ with two integers denoting character-based start and end positions of entities. If you specify
598
+ `"entity_classification"` or `"entity_pair_classification"` as the `task` argument in the constructor,
599
+ the length of each sequence must be 1 or 2, respectively. If you specify `entities`, the length of each
600
+ sequence must be equal to the length of each sequence of `entities`.
601
+ entity_spans_pair (`List[Tuple[int, int]]`, `List[List[Tuple[int, int]]]`, *optional*):
602
+ The sequence or batch of sequences of entity spans to be encoded. Each sequence consists of tuples each
603
+ with two integers denoting character-based start and end positions of entities. If you specify the
604
+ `task` argument in the constructor, this argument is ignored. If you specify `entities_pair`, the
605
+ length of each sequence must be equal to the length of each sequence of `entities_pair`.
606
+ entities (`List[str]`, `List[List[str]]`, *optional*):
607
+ The sequence or batch of sequences of entities to be encoded. Each sequence consists of strings
608
+ representing entities, i.e., special entities (e.g., [MASK]) or entity titles of Wikipedia (e.g., Los
609
+ Angeles). This argument is ignored if you specify the `task` argument in the constructor. The length of
610
+ each sequence must be equal to the length of each sequence of `entity_spans`. If you specify
611
+ `entity_spans` without specifying this argument, the entity sequence or the batch of entity sequences
612
+ is automatically constructed by filling it with the [MASK] entity.
613
+ entities_pair (`List[str]`, `List[List[str]]`, *optional*):
614
+ The sequence or batch of sequences of entities to be encoded. Each sequence consists of strings
615
+ representing entities, i.e., special entities (e.g., [MASK]) or entity titles of Wikipedia (e.g., Los
616
+ Angeles). This argument is ignored if you specify the `task` argument in the constructor. The length of
617
+ each sequence must be equal to the length of each sequence of `entity_spans_pair`. If you specify
618
+ `entity_spans_pair` without specifying this argument, the entity sequence or the batch of entity
619
+ sequences is automatically constructed by filling it with the [MASK] entity.
620
+ max_entity_length (`int`, *optional*):
621
+ The maximum length of `entity_ids`.
622
+ """
623
+ # Input type checking for clearer error
624
+ is_valid_single_text = isinstance(text, str)
625
+ is_valid_batch_text = isinstance(text, (list, tuple)) and (len(text) == 0 or (isinstance(text[0], str)))
626
+ if not (is_valid_single_text or is_valid_batch_text):
627
+ raise ValueError("text input must be of type `str` (single example) or `List[str]` (batch).")
628
+
629
+ is_valid_single_text_pair = isinstance(text_pair, str)
630
+ is_valid_batch_text_pair = isinstance(text_pair, (list, tuple)) and (
631
+ len(text_pair) == 0 or isinstance(text_pair[0], str)
632
+ )
633
+ if not (text_pair is None or is_valid_single_text_pair or is_valid_batch_text_pair):
634
+ raise ValueError("text_pair input must be of type `str` (single example) or `List[str]` (batch).")
635
+
636
+ is_batched = bool(isinstance(text, (list, tuple)))
637
+
638
+ if is_batched:
639
+ batch_text_or_text_pairs = list(zip(text, text_pair)) if text_pair is not None else text
640
+ if entities is None:
641
+ batch_entities_or_entities_pairs = None
642
+ else:
643
+ batch_entities_or_entities_pairs = (
644
+ list(zip(entities, entities_pair)) if entities_pair is not None else entities
645
+ )
646
+
647
+ if entity_spans is None:
648
+ batch_entity_spans_or_entity_spans_pairs = None
649
+ else:
650
+ batch_entity_spans_or_entity_spans_pairs = (
651
+ list(zip(entity_spans, entity_spans_pair)) if entity_spans_pair is not None else entity_spans
652
+ )
653
+
654
+ return self.batch_encode_plus(
655
+ batch_text_or_text_pairs=batch_text_or_text_pairs,
656
+ batch_entity_spans_or_entity_spans_pairs=batch_entity_spans_or_entity_spans_pairs,
657
+ batch_entities_or_entities_pairs=batch_entities_or_entities_pairs,
658
+ add_special_tokens=add_special_tokens,
659
+ padding=padding,
660
+ truncation=truncation,
661
+ max_length=max_length,
662
+ max_entity_length=max_entity_length,
663
+ stride=stride,
664
+ is_split_into_words=is_split_into_words,
665
+ pad_to_multiple_of=pad_to_multiple_of,
666
+ padding_side=padding_side,
667
+ return_tensors=return_tensors,
668
+ return_token_type_ids=return_token_type_ids,
669
+ return_attention_mask=return_attention_mask,
670
+ return_overflowing_tokens=return_overflowing_tokens,
671
+ return_special_tokens_mask=return_special_tokens_mask,
672
+ return_offsets_mapping=return_offsets_mapping,
673
+ return_length=return_length,
674
+ verbose=verbose,
675
+ **kwargs,
676
+ )
677
+ else:
678
+ return self.encode_plus(
679
+ text=text,
680
+ text_pair=text_pair,
681
+ entity_spans=entity_spans,
682
+ entity_spans_pair=entity_spans_pair,
683
+ entities=entities,
684
+ entities_pair=entities_pair,
685
+ add_special_tokens=add_special_tokens,
686
+ padding=padding,
687
+ truncation=truncation,
688
+ max_length=max_length,
689
+ max_entity_length=max_entity_length,
690
+ stride=stride,
691
+ is_split_into_words=is_split_into_words,
692
+ pad_to_multiple_of=pad_to_multiple_of,
693
+ padding_side=padding_side,
694
+ return_tensors=return_tensors,
695
+ return_token_type_ids=return_token_type_ids,
696
+ return_attention_mask=return_attention_mask,
697
+ return_overflowing_tokens=return_overflowing_tokens,
698
+ return_special_tokens_mask=return_special_tokens_mask,
699
+ return_offsets_mapping=return_offsets_mapping,
700
+ return_length=return_length,
701
+ verbose=verbose,
702
+ **kwargs,
703
+ )
704
+
705
+ def _encode_plus(
706
+ self,
707
+ text: Union[TextInput],
708
+ text_pair: Optional[Union[TextInput]] = None,
709
+ entity_spans: Optional[EntitySpanInput] = None,
710
+ entity_spans_pair: Optional[EntitySpanInput] = None,
711
+ entities: Optional[EntityInput] = None,
712
+ entities_pair: Optional[EntityInput] = None,
713
+ add_special_tokens: bool = True,
714
+ padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD,
715
+ truncation_strategy: TruncationStrategy = TruncationStrategy.DO_NOT_TRUNCATE,
716
+ max_length: Optional[int] = None,
717
+ max_entity_length: Optional[int] = None,
718
+ stride: int = 0,
719
+ is_split_into_words: Optional[bool] = False,
720
+ pad_to_multiple_of: Optional[int] = None,
721
+ padding_side: Optional[str] = None,
722
+ return_tensors: Optional[Union[str, TensorType]] = None,
723
+ return_token_type_ids: Optional[bool] = None,
724
+ return_attention_mask: Optional[bool] = None,
725
+ return_overflowing_tokens: bool = False,
726
+ return_special_tokens_mask: bool = False,
727
+ return_offsets_mapping: bool = False,
728
+ return_length: bool = False,
729
+ verbose: bool = True,
730
+ **kwargs,
731
+ ) -> BatchEncoding:
732
+ if return_offsets_mapping:
733
+ raise NotImplementedError(
734
+ "return_offset_mapping is not available when using Python tokenizers. "
735
+ "To use this feature, change your tokenizer to one deriving from "
736
+ "transformers.PreTrainedTokenizerFast. "
737
+ "More information on available tokenizers at "
738
+ "https://github.com/huggingface/transformers/pull/2674"
739
+ )
740
+
741
+ if is_split_into_words:
742
+ raise NotImplementedError("is_split_into_words is not supported in this tokenizer.")
743
+
744
+ (
745
+ first_ids,
746
+ second_ids,
747
+ first_entity_ids,
748
+ second_entity_ids,
749
+ first_entity_token_spans,
750
+ second_entity_token_spans,
751
+ ) = self._create_input_sequence(
752
+ text=text,
753
+ text_pair=text_pair,
754
+ entities=entities,
755
+ entities_pair=entities_pair,
756
+ entity_spans=entity_spans,
757
+ entity_spans_pair=entity_spans_pair,
758
+ **kwargs,
759
+ )
760
+
761
+ # prepare_for_model will create the attention_mask and token_type_ids
762
+ return self.prepare_for_model(
763
+ first_ids,
764
+ pair_ids=second_ids,
765
+ entity_ids=first_entity_ids,
766
+ pair_entity_ids=second_entity_ids,
767
+ entity_token_spans=first_entity_token_spans,
768
+ pair_entity_token_spans=second_entity_token_spans,
769
+ add_special_tokens=add_special_tokens,
770
+ padding=padding_strategy.value,
771
+ truncation=truncation_strategy.value,
772
+ max_length=max_length,
773
+ max_entity_length=max_entity_length,
774
+ stride=stride,
775
+ pad_to_multiple_of=pad_to_multiple_of,
776
+ padding_side=padding_side,
777
+ return_tensors=return_tensors,
778
+ prepend_batch_axis=True,
779
+ return_attention_mask=return_attention_mask,
780
+ return_token_type_ids=return_token_type_ids,
781
+ return_overflowing_tokens=return_overflowing_tokens,
782
+ return_special_tokens_mask=return_special_tokens_mask,
783
+ return_length=return_length,
784
+ verbose=verbose,
785
+ )
786
+
787
+ def _batch_encode_plus(
788
+ self,
789
+ batch_text_or_text_pairs: Union[List[TextInput], List[TextInputPair]],
790
+ batch_entity_spans_or_entity_spans_pairs: Optional[
791
+ Union[List[EntitySpanInput], List[Tuple[EntitySpanInput, EntitySpanInput]]]
792
+ ] = None,
793
+ batch_entities_or_entities_pairs: Optional[
794
+ Union[List[EntityInput], List[Tuple[EntityInput, EntityInput]]]
795
+ ] = None,
796
+ add_special_tokens: bool = True,
797
+ padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD,
798
+ truncation_strategy: TruncationStrategy = TruncationStrategy.DO_NOT_TRUNCATE,
799
+ max_length: Optional[int] = None,
800
+ max_entity_length: Optional[int] = None,
801
+ stride: int = 0,
802
+ is_split_into_words: Optional[bool] = False,
803
+ pad_to_multiple_of: Optional[int] = None,
804
+ padding_side: Optional[str] = None,
805
+ return_tensors: Optional[Union[str, TensorType]] = None,
806
+ return_token_type_ids: Optional[bool] = None,
807
+ return_attention_mask: Optional[bool] = None,
808
+ return_overflowing_tokens: bool = False,
809
+ return_special_tokens_mask: bool = False,
810
+ return_offsets_mapping: bool = False,
811
+ return_length: bool = False,
812
+ verbose: bool = True,
813
+ **kwargs,
814
+ ) -> BatchEncoding:
815
+ if return_offsets_mapping:
816
+ raise NotImplementedError(
817
+ "return_offset_mapping is not available when using Python tokenizers. "
818
+ "To use this feature, change your tokenizer to one deriving from "
819
+ "transformers.PreTrainedTokenizerFast."
820
+ )
821
+
822
+ if is_split_into_words:
823
+ raise NotImplementedError("is_split_into_words is not supported in this tokenizer.")
824
+
825
+ # input_ids is a list of tuples (one for each example in the batch)
826
+ input_ids = []
827
+ entity_ids = []
828
+ entity_token_spans = []
829
+ for index, text_or_text_pair in enumerate(batch_text_or_text_pairs):
830
+ if not isinstance(text_or_text_pair, (list, tuple)):
831
+ text, text_pair = text_or_text_pair, None
832
+ else:
833
+ text, text_pair = text_or_text_pair
834
+
835
+ entities, entities_pair = None, None
836
+ if batch_entities_or_entities_pairs is not None:
837
+ entities_or_entities_pairs = batch_entities_or_entities_pairs[index]
838
+ if entities_or_entities_pairs:
839
+ if isinstance(entities_or_entities_pairs[0], str):
840
+ entities, entities_pair = entities_or_entities_pairs, None
841
+ else:
842
+ entities, entities_pair = entities_or_entities_pairs
843
+
844
+ entity_spans, entity_spans_pair = None, None
845
+ if batch_entity_spans_or_entity_spans_pairs is not None:
846
+ entity_spans_or_entity_spans_pairs = batch_entity_spans_or_entity_spans_pairs[index]
847
+ if len(entity_spans_or_entity_spans_pairs) > 0 and isinstance(
848
+ entity_spans_or_entity_spans_pairs[0], list
849
+ ):
850
+ entity_spans, entity_spans_pair = entity_spans_or_entity_spans_pairs
851
+ else:
852
+ entity_spans, entity_spans_pair = entity_spans_or_entity_spans_pairs, None
853
+
854
+ (
855
+ first_ids,
856
+ second_ids,
857
+ first_entity_ids,
858
+ second_entity_ids,
859
+ first_entity_token_spans,
860
+ second_entity_token_spans,
861
+ ) = self._create_input_sequence(
862
+ text=text,
863
+ text_pair=text_pair,
864
+ entities=entities,
865
+ entities_pair=entities_pair,
866
+ entity_spans=entity_spans,
867
+ entity_spans_pair=entity_spans_pair,
868
+ **kwargs,
869
+ )
870
+ input_ids.append((first_ids, second_ids))
871
+ entity_ids.append((first_entity_ids, second_entity_ids))
872
+ entity_token_spans.append((first_entity_token_spans, second_entity_token_spans))
873
+
874
+ batch_outputs = self._batch_prepare_for_model(
875
+ input_ids,
876
+ batch_entity_ids_pairs=entity_ids,
877
+ batch_entity_token_spans_pairs=entity_token_spans,
878
+ add_special_tokens=add_special_tokens,
879
+ padding_strategy=padding_strategy,
880
+ truncation_strategy=truncation_strategy,
881
+ max_length=max_length,
882
+ max_entity_length=max_entity_length,
883
+ stride=stride,
884
+ pad_to_multiple_of=pad_to_multiple_of,
885
+ padding_side=padding_side,
886
+ return_attention_mask=return_attention_mask,
887
+ return_token_type_ids=return_token_type_ids,
888
+ return_overflowing_tokens=return_overflowing_tokens,
889
+ return_special_tokens_mask=return_special_tokens_mask,
890
+ return_length=return_length,
891
+ return_tensors=return_tensors,
892
+ verbose=verbose,
893
+ )
894
+
895
+ return BatchEncoding(batch_outputs)
896
+
897
+ def _check_entity_input_format(self, entities: Optional[EntityInput], entity_spans: Optional[EntitySpanInput]):
898
+ if not isinstance(entity_spans, list):
899
+ raise TypeError("entity_spans should be given as a list")
900
+ elif len(entity_spans) > 0 and not isinstance(entity_spans[0], tuple):
901
+ raise ValueError(
902
+ "entity_spans should be given as a list of tuples containing the start and end character indices"
903
+ )
904
+
905
+ if entities is not None:
906
+ if not isinstance(entities, list):
907
+ raise ValueError("If you specify entities, they should be given as a list")
908
+
909
+ if len(entities) > 0 and not isinstance(entities[0], str):
910
+ raise ValueError("If you specify entities, they should be given as a list of entity names")
911
+
912
+ if len(entities) != len(entity_spans):
913
+ raise ValueError("If you specify entities, entities and entity_spans must be the same length")
914
+
915
+ def _create_input_sequence(
916
+ self,
917
+ text: Union[TextInput],
918
+ text_pair: Optional[Union[TextInput]] = None,
919
+ entities: Optional[EntityInput] = None,
920
+ entities_pair: Optional[EntityInput] = None,
921
+ entity_spans: Optional[EntitySpanInput] = None,
922
+ entity_spans_pair: Optional[EntitySpanInput] = None,
923
+ **kwargs,
924
+ ) -> Tuple[list, list, list, list, list, list]:
925
+ def get_input_ids(text):
926
+ tokens = self.tokenize(text, **kwargs)
927
+ return self.convert_tokens_to_ids(tokens)
928
+
929
+ def get_input_ids_and_entity_token_spans(text, entity_spans):
930
+ if entity_spans is None:
931
+ return get_input_ids(text), None
932
+
933
+ cur = 0
934
+ input_ids = []
935
+ entity_token_spans = [None] * len(entity_spans)
936
+
937
+ split_char_positions = sorted(frozenset(itertools.chain(*entity_spans)))
938
+ char_pos2token_pos = {}
939
+
940
+ for split_char_position in split_char_positions:
941
+ orig_split_char_position = split_char_position
942
+ if (
943
+ split_char_position > 0 and text[split_char_position - 1] == " "
944
+ ): # whitespace should be prepended to the following token
945
+ split_char_position -= 1
946
+ if cur != split_char_position:
947
+ input_ids += get_input_ids(text[cur:split_char_position])
948
+ cur = split_char_position
949
+ char_pos2token_pos[orig_split_char_position] = len(input_ids)
950
+
951
+ input_ids += get_input_ids(text[cur:])
952
+
953
+ entity_token_spans = [
954
+ (char_pos2token_pos[char_start], char_pos2token_pos[char_end]) for char_start, char_end in entity_spans
955
+ ]
956
+
957
+ return input_ids, entity_token_spans
958
+
959
+ first_ids, second_ids = None, None
960
+ first_entity_ids, second_entity_ids = None, None
961
+ first_entity_token_spans, second_entity_token_spans = None, None
962
+
963
+ if self.task is None:
964
+ if entity_spans is None:
965
+ first_ids = get_input_ids(text)
966
+ else:
967
+ self._check_entity_input_format(entities, entity_spans)
968
+
969
+ first_ids, first_entity_token_spans = get_input_ids_and_entity_token_spans(text, entity_spans)
970
+ if entities is None:
971
+ first_entity_ids = [self.entity_mask_token_id] * len(entity_spans)
972
+ else:
973
+ first_entity_ids = [self.entity_vocab.get(entity, self.entity_unk_token_id) for entity in entities]
974
+
975
+ if text_pair is not None:
976
+ if entity_spans_pair is None:
977
+ second_ids = get_input_ids(text_pair)
978
+ else:
979
+ self._check_entity_input_format(entities_pair, entity_spans_pair)
980
+
981
+ second_ids, second_entity_token_spans = get_input_ids_and_entity_token_spans(
982
+ text_pair, entity_spans_pair
983
+ )
984
+ if entities_pair is None:
985
+ second_entity_ids = [self.entity_mask_token_id] * len(entity_spans_pair)
986
+ else:
987
+ second_entity_ids = [
988
+ self.entity_vocab.get(entity, self.entity_unk_token_id) for entity in entities_pair
989
+ ]
990
+
991
+ elif self.task == "entity_classification":
992
+ if not (isinstance(entity_spans, list) and len(entity_spans) == 1 and isinstance(entity_spans[0], tuple)):
993
+ raise ValueError(
994
+ "Entity spans should be a list containing a single tuple "
995
+ "containing the start and end character indices of an entity"
996
+ )
997
+ first_entity_ids = [self.entity_mask_token_id]
998
+ first_ids, first_entity_token_spans = get_input_ids_and_entity_token_spans(text, entity_spans)
999
+
1000
+ # add special tokens to input ids
1001
+ entity_token_start, entity_token_end = first_entity_token_spans[0]
1002
+ first_ids = (
1003
+ first_ids[:entity_token_end] + [self.additional_special_tokens_ids[0]] + first_ids[entity_token_end:]
1004
+ )
1005
+ first_ids = (
1006
+ first_ids[:entity_token_start]
1007
+ + [self.additional_special_tokens_ids[0]]
1008
+ + first_ids[entity_token_start:]
1009
+ )
1010
+ first_entity_token_spans = [(entity_token_start, entity_token_end + 2)]
1011
+
1012
+ elif self.task == "entity_pair_classification":
1013
+ if not (
1014
+ isinstance(entity_spans, list)
1015
+ and len(entity_spans) == 2
1016
+ and isinstance(entity_spans[0], tuple)
1017
+ and isinstance(entity_spans[1], tuple)
1018
+ ):
1019
+ raise ValueError(
1020
+ "Entity spans should be provided as a list of two tuples, "
1021
+ "each tuple containing the start and end character indices of an entity"
1022
+ )
1023
+
1024
+ head_span, tail_span = entity_spans
1025
+ first_entity_ids = [self.entity_mask_token_id, self.entity_mask2_token_id]
1026
+ first_ids, first_entity_token_spans = get_input_ids_and_entity_token_spans(text, entity_spans)
1027
+
1028
+ head_token_span, tail_token_span = first_entity_token_spans
1029
+ token_span_with_special_token_ids = [
1030
+ (head_token_span, self.additional_special_tokens_ids[0]),
1031
+ (tail_token_span, self.additional_special_tokens_ids[1]),
1032
+ ]
1033
+ if head_token_span[0] < tail_token_span[0]:
1034
+ first_entity_token_spans[0] = (head_token_span[0], head_token_span[1] + 2)
1035
+ first_entity_token_spans[1] = (tail_token_span[0] + 2, tail_token_span[1] + 4)
1036
+ token_span_with_special_token_ids = reversed(token_span_with_special_token_ids)
1037
+ else:
1038
+ first_entity_token_spans[0] = (head_token_span[0] + 2, head_token_span[1] + 4)
1039
+ first_entity_token_spans[1] = (tail_token_span[0], tail_token_span[1] + 2)
1040
+
1041
+ for (entity_token_start, entity_token_end), special_token_id in token_span_with_special_token_ids:
1042
+ first_ids = first_ids[:entity_token_end] + [special_token_id] + first_ids[entity_token_end:]
1043
+ first_ids = first_ids[:entity_token_start] + [special_token_id] + first_ids[entity_token_start:]
1044
+
1045
+ elif self.task == "entity_span_classification":
1046
+ if not (isinstance(entity_spans, list) and len(entity_spans) > 0 and isinstance(entity_spans[0], tuple)):
1047
+ raise ValueError(
1048
+ "Entity spans should be provided as a list of tuples, "
1049
+ "each tuple containing the start and end character indices of an entity"
1050
+ )
1051
+
1052
+ first_ids, first_entity_token_spans = get_input_ids_and_entity_token_spans(text, entity_spans)
1053
+ first_entity_ids = [self.entity_mask_token_id] * len(entity_spans)
1054
+
1055
+ else:
1056
+ raise ValueError(f"Task {self.task} not supported")
1057
+
1058
+ return (
1059
+ first_ids,
1060
+ second_ids,
1061
+ first_entity_ids,
1062
+ second_entity_ids,
1063
+ first_entity_token_spans,
1064
+ second_entity_token_spans,
1065
+ )
1066
+
1067
+ @add_end_docstrings(ENCODE_KWARGS_DOCSTRING, ENCODE_PLUS_ADDITIONAL_KWARGS_DOCSTRING)
1068
+ def _batch_prepare_for_model(
1069
+ self,
1070
+ batch_ids_pairs: List[Tuple[List[int], None]],
1071
+ batch_entity_ids_pairs: List[Tuple[Optional[List[int]], Optional[List[int]]]],
1072
+ batch_entity_token_spans_pairs: List[Tuple[Optional[List[Tuple[int, int]]], Optional[List[Tuple[int, int]]]]],
1073
+ add_special_tokens: bool = True,
1074
+ padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD,
1075
+ truncation_strategy: TruncationStrategy = TruncationStrategy.DO_NOT_TRUNCATE,
1076
+ max_length: Optional[int] = None,
1077
+ max_entity_length: Optional[int] = None,
1078
+ stride: int = 0,
1079
+ pad_to_multiple_of: Optional[int] = None,
1080
+ padding_side: Optional[str] = None,
1081
+ return_tensors: Optional[str] = None,
1082
+ return_token_type_ids: Optional[bool] = None,
1083
+ return_attention_mask: Optional[bool] = None,
1084
+ return_overflowing_tokens: bool = False,
1085
+ return_special_tokens_mask: bool = False,
1086
+ return_length: bool = False,
1087
+ verbose: bool = True,
1088
+ ) -> BatchEncoding:
1089
+ """
1090
+ Prepares a sequence of input id, or a pair of sequences of inputs ids so that it can be used by the model. It
1091
+ adds special tokens, truncates sequences if overflowing while taking into account the special tokens and
1092
+ manages a moving window (with user defined stride) for overflowing tokens
1093
+
1094
+
1095
+ Args:
1096
+ batch_ids_pairs: list of tokenized input ids or input ids pairs
1097
+ batch_entity_ids_pairs: list of entity ids or entity ids pairs
1098
+ batch_entity_token_spans_pairs: list of entity spans or entity spans pairs
1099
+ max_entity_length: The maximum length of the entity sequence.
1100
+ """
1101
+
1102
+ batch_outputs = {}
1103
+ for input_ids, entity_ids, entity_token_span_pairs in zip(
1104
+ batch_ids_pairs, batch_entity_ids_pairs, batch_entity_token_spans_pairs
1105
+ ):
1106
+ first_ids, second_ids = input_ids
1107
+ first_entity_ids, second_entity_ids = entity_ids
1108
+ first_entity_token_spans, second_entity_token_spans = entity_token_span_pairs
1109
+ outputs = self.prepare_for_model(
1110
+ first_ids,
1111
+ second_ids,
1112
+ entity_ids=first_entity_ids,
1113
+ pair_entity_ids=second_entity_ids,
1114
+ entity_token_spans=first_entity_token_spans,
1115
+ pair_entity_token_spans=second_entity_token_spans,
1116
+ add_special_tokens=add_special_tokens,
1117
+ padding=PaddingStrategy.DO_NOT_PAD.value, # we pad in batch afterward
1118
+ truncation=truncation_strategy.value,
1119
+ max_length=max_length,
1120
+ max_entity_length=max_entity_length,
1121
+ stride=stride,
1122
+ pad_to_multiple_of=None, # we pad in batch afterward
1123
+ padding_side=None, # we pad in batch afterward
1124
+ return_attention_mask=False, # we pad in batch afterward
1125
+ return_token_type_ids=return_token_type_ids,
1126
+ return_overflowing_tokens=return_overflowing_tokens,
1127
+ return_special_tokens_mask=return_special_tokens_mask,
1128
+ return_length=return_length,
1129
+ return_tensors=None, # We convert the whole batch to tensors at the end
1130
+ prepend_batch_axis=False,
1131
+ verbose=verbose,
1132
+ )
1133
+
1134
+ for key, value in outputs.items():
1135
+ if key not in batch_outputs:
1136
+ batch_outputs[key] = []
1137
+ batch_outputs[key].append(value)
1138
+
1139
+ batch_outputs = self.pad(
1140
+ batch_outputs,
1141
+ padding=padding_strategy.value,
1142
+ max_length=max_length,
1143
+ pad_to_multiple_of=pad_to_multiple_of,
1144
+ padding_side=padding_side,
1145
+ return_attention_mask=return_attention_mask,
1146
+ )
1147
+
1148
+ batch_outputs = BatchEncoding(batch_outputs, tensor_type=return_tensors)
1149
+
1150
+ return batch_outputs
1151
+
1152
+ @add_end_docstrings(ENCODE_KWARGS_DOCSTRING, ENCODE_PLUS_ADDITIONAL_KWARGS_DOCSTRING)
1153
+ def prepare_for_model(
1154
+ self,
1155
+ ids: List[int],
1156
+ pair_ids: Optional[List[int]] = None,
1157
+ entity_ids: Optional[List[int]] = None,
1158
+ pair_entity_ids: Optional[List[int]] = None,
1159
+ entity_token_spans: Optional[List[Tuple[int, int]]] = None,
1160
+ pair_entity_token_spans: Optional[List[Tuple[int, int]]] = None,
1161
+ add_special_tokens: bool = True,
1162
+ padding: Union[bool, str, PaddingStrategy] = False,
1163
+ truncation: Union[bool, str, TruncationStrategy] = None,
1164
+ max_length: Optional[int] = None,
1165
+ max_entity_length: Optional[int] = None,
1166
+ stride: int = 0,
1167
+ pad_to_multiple_of: Optional[int] = None,
1168
+ padding_side: Optional[str] = None,
1169
+ return_tensors: Optional[Union[str, TensorType]] = None,
1170
+ return_token_type_ids: Optional[bool] = None,
1171
+ return_attention_mask: Optional[bool] = None,
1172
+ return_overflowing_tokens: bool = False,
1173
+ return_special_tokens_mask: bool = False,
1174
+ return_offsets_mapping: bool = False,
1175
+ return_length: bool = False,
1176
+ verbose: bool = True,
1177
+ prepend_batch_axis: bool = False,
1178
+ **kwargs,
1179
+ ) -> BatchEncoding:
1180
+ """
1181
+ Prepares a sequence of input id, entity id and entity span, or a pair of sequences of inputs ids, entity ids,
1182
+ entity spans so that it can be used by the model. It adds special tokens, truncates sequences if overflowing
1183
+ while taking into account the special tokens and manages a moving window (with user defined stride) for
1184
+ overflowing tokens. Please Note, for *pair_ids* different than `None` and *truncation_strategy = longest_first*
1185
+ or `True`, it is not possible to return overflowing tokens. Such a combination of arguments will raise an
1186
+ error.
1187
+
1188
+ Args:
1189
+ ids (`List[int]`):
1190
+ Tokenized input ids of the first sequence.
1191
+ pair_ids (`List[int]`, *optional*):
1192
+ Tokenized input ids of the second sequence.
1193
+ entity_ids (`List[int]`, *optional*):
1194
+ Entity ids of the first sequence.
1195
+ pair_entity_ids (`List[int]`, *optional*):
1196
+ Entity ids of the second sequence.
1197
+ entity_token_spans (`List[Tuple[int, int]]`, *optional*):
1198
+ Entity spans of the first sequence.
1199
+ pair_entity_token_spans (`List[Tuple[int, int]]`, *optional*):
1200
+ Entity spans of the second sequence.
1201
+ max_entity_length (`int`, *optional*):
1202
+ The maximum length of the entity sequence.
1203
+ """
1204
+
1205
+ # Backward compatibility for 'truncation_strategy', 'pad_to_max_length'
1206
+ padding_strategy, truncation_strategy, max_length, kwargs = self._get_padding_truncation_strategies(
1207
+ padding=padding,
1208
+ truncation=truncation,
1209
+ max_length=max_length,
1210
+ pad_to_multiple_of=pad_to_multiple_of,
1211
+ verbose=verbose,
1212
+ **kwargs,
1213
+ )
1214
+
1215
+ # Compute lengths
1216
+ pair = bool(pair_ids is not None)
1217
+ len_ids = len(ids)
1218
+ len_pair_ids = len(pair_ids) if pair else 0
1219
+
1220
+ if return_token_type_ids and not add_special_tokens:
1221
+ raise ValueError(
1222
+ "Asking to return token_type_ids while setting add_special_tokens to False "
1223
+ "results in an undefined behavior. Please set add_special_tokens to True or "
1224
+ "set return_token_type_ids to None."
1225
+ )
1226
+ if (
1227
+ return_overflowing_tokens
1228
+ and truncation_strategy == TruncationStrategy.LONGEST_FIRST
1229
+ and pair_ids is not None
1230
+ ):
1231
+ raise ValueError(
1232
+ "Not possible to return overflowing tokens for pair of sequences with the "
1233
+ "`longest_first`. Please select another truncation strategy than `longest_first`, "
1234
+ "for instance `only_second` or `only_first`."
1235
+ )
1236
+
1237
+ # Load from model defaults
1238
+ if return_token_type_ids is None:
1239
+ return_token_type_ids = "token_type_ids" in self.model_input_names
1240
+ if return_attention_mask is None:
1241
+ return_attention_mask = "attention_mask" in self.model_input_names
1242
+
1243
+ encoded_inputs = {}
1244
+
1245
+ # Compute the total size of the returned word encodings
1246
+ total_len = len_ids + len_pair_ids + (self.num_special_tokens_to_add(pair=pair) if add_special_tokens else 0)
1247
+
1248
+ # Truncation: Handle max sequence length and max_entity_length
1249
+ overflowing_tokens = []
1250
+ if truncation_strategy != TruncationStrategy.DO_NOT_TRUNCATE and max_length and total_len > max_length:
1251
+ # truncate words up to max_length
1252
+ ids, pair_ids, overflowing_tokens = self.truncate_sequences(
1253
+ ids,
1254
+ pair_ids=pair_ids,
1255
+ num_tokens_to_remove=total_len - max_length,
1256
+ truncation_strategy=truncation_strategy,
1257
+ stride=stride,
1258
+ )
1259
+
1260
+ if return_overflowing_tokens:
1261
+ encoded_inputs["overflowing_tokens"] = overflowing_tokens
1262
+ encoded_inputs["num_truncated_tokens"] = total_len - max_length
1263
+
1264
+ # Add special tokens
1265
+ if add_special_tokens:
1266
+ sequence = self.build_inputs_with_special_tokens(ids, pair_ids)
1267
+ token_type_ids = self.create_token_type_ids_from_sequences(ids, pair_ids)
1268
+ entity_token_offset = 1 # 1 * <s> token
1269
+ pair_entity_token_offset = len(ids) + 3 # 1 * <s> token & 2 * <sep> tokens
1270
+ else:
1271
+ sequence = ids + pair_ids if pair else ids
1272
+ token_type_ids = [0] * len(ids) + ([0] * len(pair_ids) if pair else [])
1273
+ entity_token_offset = 0
1274
+ pair_entity_token_offset = len(ids)
1275
+
1276
+ # Build output dictionary
1277
+ encoded_inputs["input_ids"] = sequence
1278
+ if return_token_type_ids:
1279
+ encoded_inputs["token_type_ids"] = token_type_ids
1280
+ if return_special_tokens_mask:
1281
+ if add_special_tokens:
1282
+ encoded_inputs["special_tokens_mask"] = self.get_special_tokens_mask(ids, pair_ids)
1283
+ else:
1284
+ encoded_inputs["special_tokens_mask"] = [0] * len(sequence)
1285
+
1286
+ # Set max entity length
1287
+ if not max_entity_length:
1288
+ max_entity_length = self.max_entity_length
1289
+
1290
+ if entity_ids is not None:
1291
+ total_entity_len = 0
1292
+ num_invalid_entities = 0
1293
+ valid_entity_ids = [ent_id for ent_id, span in zip(entity_ids, entity_token_spans) if span[1] <= len(ids)]
1294
+ valid_entity_token_spans = [span for span in entity_token_spans if span[1] <= len(ids)]
1295
+
1296
+ total_entity_len += len(valid_entity_ids)
1297
+ num_invalid_entities += len(entity_ids) - len(valid_entity_ids)
1298
+
1299
+ valid_pair_entity_ids, valid_pair_entity_token_spans = None, None
1300
+ if pair_entity_ids is not None:
1301
+ valid_pair_entity_ids = [
1302
+ ent_id
1303
+ for ent_id, span in zip(pair_entity_ids, pair_entity_token_spans)
1304
+ if span[1] <= len(pair_ids)
1305
+ ]
1306
+ valid_pair_entity_token_spans = [span for span in pair_entity_token_spans if span[1] <= len(pair_ids)]
1307
+ total_entity_len += len(valid_pair_entity_ids)
1308
+ num_invalid_entities += len(pair_entity_ids) - len(valid_pair_entity_ids)
1309
+
1310
+ if num_invalid_entities != 0:
1311
+ logger.warning(
1312
+ f"{num_invalid_entities} entities are ignored because their entity spans are invalid due to the"
1313
+ " truncation of input tokens"
1314
+ )
1315
+
1316
+ if truncation_strategy != TruncationStrategy.DO_NOT_TRUNCATE and total_entity_len > max_entity_length:
1317
+ # truncate entities up to max_entity_length
1318
+ valid_entity_ids, valid_pair_entity_ids, overflowing_entities = self.truncate_sequences(
1319
+ valid_entity_ids,
1320
+ pair_ids=valid_pair_entity_ids,
1321
+ num_tokens_to_remove=total_entity_len - max_entity_length,
1322
+ truncation_strategy=truncation_strategy,
1323
+ stride=stride,
1324
+ )
1325
+ valid_entity_token_spans = valid_entity_token_spans[: len(valid_entity_ids)]
1326
+ if valid_pair_entity_token_spans is not None:
1327
+ valid_pair_entity_token_spans = valid_pair_entity_token_spans[: len(valid_pair_entity_ids)]
1328
+
1329
+ if return_overflowing_tokens:
1330
+ encoded_inputs["overflowing_entities"] = overflowing_entities
1331
+ encoded_inputs["num_truncated_entities"] = total_entity_len - max_entity_length
1332
+
1333
+ final_entity_ids = valid_entity_ids + valid_pair_entity_ids if valid_pair_entity_ids else valid_entity_ids
1334
+ encoded_inputs["entity_ids"] = list(final_entity_ids)
1335
+ entity_position_ids = []
1336
+ entity_start_positions = []
1337
+ entity_end_positions = []
1338
+ for token_spans, offset in (
1339
+ (valid_entity_token_spans, entity_token_offset),
1340
+ (valid_pair_entity_token_spans, pair_entity_token_offset),
1341
+ ):
1342
+ if token_spans is not None:
1343
+ for start, end in token_spans:
1344
+ start += offset
1345
+ end += offset
1346
+ position_ids = list(range(start, end))[: self.max_mention_length]
1347
+ position_ids += [-1] * (self.max_mention_length - end + start)
1348
+ entity_position_ids.append(position_ids)
1349
+ entity_start_positions.append(start)
1350
+ entity_end_positions.append(end - 1)
1351
+
1352
+ encoded_inputs["entity_position_ids"] = entity_position_ids
1353
+ if self.task == "entity_span_classification":
1354
+ encoded_inputs["entity_start_positions"] = entity_start_positions
1355
+ encoded_inputs["entity_end_positions"] = entity_end_positions
1356
+
1357
+ if return_token_type_ids:
1358
+ encoded_inputs["entity_token_type_ids"] = [0] * len(encoded_inputs["entity_ids"])
1359
+
1360
+ # Check lengths
1361
+ self._eventual_warn_about_too_long_sequence(encoded_inputs["input_ids"], max_length, verbose)
1362
+
1363
+ # Padding
1364
+ if padding_strategy != PaddingStrategy.DO_NOT_PAD or return_attention_mask:
1365
+ encoded_inputs = self.pad(
1366
+ encoded_inputs,
1367
+ max_length=max_length,
1368
+ max_entity_length=max_entity_length,
1369
+ padding=padding_strategy.value,
1370
+ pad_to_multiple_of=pad_to_multiple_of,
1371
+ padding_side=padding_side,
1372
+ return_attention_mask=return_attention_mask,
1373
+ )
1374
+
1375
+ if return_length:
1376
+ encoded_inputs["length"] = len(encoded_inputs["input_ids"])
1377
+
1378
+ batch_outputs = BatchEncoding(
1379
+ encoded_inputs, tensor_type=return_tensors, prepend_batch_axis=prepend_batch_axis
1380
+ )
1381
+
1382
+ return batch_outputs
1383
+
1384
+ def pad(
1385
+ self,
1386
+ encoded_inputs: Union[
1387
+ BatchEncoding,
1388
+ List[BatchEncoding],
1389
+ Dict[str, EncodedInput],
1390
+ Dict[str, List[EncodedInput]],
1391
+ List[Dict[str, EncodedInput]],
1392
+ ],
1393
+ padding: Union[bool, str, PaddingStrategy] = True,
1394
+ max_length: Optional[int] = None,
1395
+ max_entity_length: Optional[int] = None,
1396
+ pad_to_multiple_of: Optional[int] = None,
1397
+ padding_side: Optional[str] = None,
1398
+ return_attention_mask: Optional[bool] = None,
1399
+ return_tensors: Optional[Union[str, TensorType]] = None,
1400
+ verbose: bool = True,
1401
+ ) -> BatchEncoding:
1402
+ """
1403
+ Pad a single encoded input or a batch of encoded inputs up to predefined length or to the max sequence length
1404
+ in the batch. Padding side (left/right) padding token ids are defined at the tokenizer level (with
1405
+ `self.padding_side`, `self.pad_token_id` and `self.pad_token_type_id`) .. note:: If the `encoded_inputs` passed
1406
+ are dictionary of numpy arrays, PyTorch tensors or TensorFlow tensors, the result will use the same type unless
1407
+ you provide a different tensor type with `return_tensors`. In the case of PyTorch tensors, you will lose the
1408
+ specific device of your tensors however.
1409
+
1410
+ Args:
1411
+ encoded_inputs ([`BatchEncoding`], list of [`BatchEncoding`], `Dict[str, List[int]]`, `Dict[str, List[List[int]]` or `List[Dict[str, List[int]]]`):
1412
+ Tokenized inputs. Can represent one input ([`BatchEncoding`] or `Dict[str, List[int]]`) or a batch of
1413
+ tokenized inputs (list of [`BatchEncoding`], *Dict[str, List[List[int]]]* or *List[Dict[str,
1414
+ List[int]]]*) so you can use this method during preprocessing as well as in a PyTorch Dataloader
1415
+ collate function. Instead of `List[int]` you can have tensors (numpy arrays, PyTorch tensors or
1416
+ TensorFlow tensors), see the note above for the return type.
1417
+ padding (`bool`, `str` or [`~utils.PaddingStrategy`], *optional*, defaults to `True`):
1418
+ Select a strategy to pad the returned sequences (according to the model's padding side and padding
1419
+ index) among:
1420
+
1421
+ - `True` or `'longest'`: Pad to the longest sequence in the batch (or no padding if only a single
1422
+ sequence if provided).
1423
+ - `'max_length'`: Pad to a maximum length specified with the argument `max_length` or to the maximum
1424
+ acceptable input length for the model if that argument is not provided.
1425
+ - `False` or `'do_not_pad'` (default): No padding (i.e., can output a batch with sequences of different
1426
+ lengths).
1427
+ max_length (`int`, *optional*):
1428
+ Maximum length of the returned list and optionally padding length (see above).
1429
+ max_entity_length (`int`, *optional*):
1430
+ The maximum length of the entity sequence.
1431
+ pad_to_multiple_of (`int`, *optional*):
1432
+ If set will pad the sequence to a multiple of the provided value. This is especially useful to enable
1433
+ the use of Tensor Cores on NVIDIA hardware with compute capability `>= 7.5` (Volta).
1434
+ padding_side:
1435
+ The side on which the model should have padding applied. Should be selected between ['right', 'left'].
1436
+ Default value is picked from the class attribute of the same name.
1437
+ return_attention_mask (`bool`, *optional*):
1438
+ Whether to return the attention mask. If left to the default, will return the attention mask according
1439
+ to the specific tokenizer's default, defined by the `return_outputs` attribute. [What are attention
1440
+ masks?](../glossary#attention-mask)
1441
+ return_tensors (`str` or [`~utils.TensorType`], *optional*):
1442
+ If set, will return tensors instead of list of python integers. Acceptable values are:
1443
+
1444
+ - `'tf'`: Return TensorFlow `tf.constant` objects.
1445
+ - `'pt'`: Return PyTorch `torch.Tensor` objects.
1446
+ - `'np'`: Return Numpy `np.ndarray` objects.
1447
+ verbose (`bool`, *optional*, defaults to `True`):
1448
+ Whether or not to print more information and warnings.
1449
+ """
1450
+ # If we have a list of dicts, let's convert it in a dict of lists
1451
+ # We do this to allow using this method as a collate_fn function in PyTorch Dataloader
1452
+ if isinstance(encoded_inputs, (list, tuple)) and isinstance(encoded_inputs[0], Mapping):
1453
+ encoded_inputs = {key: [example[key] for example in encoded_inputs] for key in encoded_inputs[0].keys()}
1454
+
1455
+ # The model's main input name, usually `input_ids`, has be passed for padding
1456
+ if self.model_input_names[0] not in encoded_inputs:
1457
+ raise ValueError(
1458
+ "You should supply an encoding or a list of encodings to this method "
1459
+ f"that includes {self.model_input_names[0]}, but you provided {list(encoded_inputs.keys())}"
1460
+ )
1461
+
1462
+ required_input = encoded_inputs[self.model_input_names[0]]
1463
+
1464
+ if not required_input:
1465
+ if return_attention_mask:
1466
+ encoded_inputs["attention_mask"] = []
1467
+ return encoded_inputs
1468
+
1469
+ # If we have PyTorch/TF/NumPy tensors/arrays as inputs, we cast them as python objects
1470
+ # and rebuild them afterwards if no return_tensors is specified
1471
+ # Note that we lose the specific device the tensor may be on for PyTorch
1472
+
1473
+ first_element = required_input[0]
1474
+ if isinstance(first_element, (list, tuple)):
1475
+ # first_element might be an empty list/tuple in some edge cases so we grab the first non empty element.
1476
+ index = 0
1477
+ while len(required_input[index]) == 0:
1478
+ index += 1
1479
+ if index < len(required_input):
1480
+ first_element = required_input[index][0]
1481
+ # At this state, if `first_element` is still a list/tuple, it's an empty one so there is nothing to do.
1482
+ if not isinstance(first_element, (int, list, tuple)):
1483
+ if is_tf_tensor(first_element):
1484
+ return_tensors = "tf" if return_tensors is None else return_tensors
1485
+ elif is_torch_tensor(first_element):
1486
+ return_tensors = "pt" if return_tensors is None else return_tensors
1487
+ elif isinstance(first_element, np.ndarray):
1488
+ return_tensors = "np" if return_tensors is None else return_tensors
1489
+ else:
1490
+ raise ValueError(
1491
+ f"type of {first_element} unknown: {type(first_element)}. "
1492
+ "Should be one of a python, numpy, pytorch or tensorflow object."
1493
+ )
1494
+
1495
+ for key, value in encoded_inputs.items():
1496
+ encoded_inputs[key] = to_py_obj(value)
1497
+
1498
+ # Convert padding_strategy in PaddingStrategy
1499
+ padding_strategy, _, max_length, _ = self._get_padding_truncation_strategies(
1500
+ padding=padding, max_length=max_length, verbose=verbose
1501
+ )
1502
+
1503
+ if max_entity_length is None:
1504
+ max_entity_length = self.max_entity_length
1505
+
1506
+ required_input = encoded_inputs[self.model_input_names[0]]
1507
+ if required_input and not isinstance(required_input[0], (list, tuple)):
1508
+ encoded_inputs = self._pad(
1509
+ encoded_inputs,
1510
+ max_length=max_length,
1511
+ max_entity_length=max_entity_length,
1512
+ padding_strategy=padding_strategy,
1513
+ pad_to_multiple_of=pad_to_multiple_of,
1514
+ padding_side=padding_side,
1515
+ return_attention_mask=return_attention_mask,
1516
+ )
1517
+ return BatchEncoding(encoded_inputs, tensor_type=return_tensors)
1518
+
1519
+ batch_size = len(required_input)
1520
+ if any(len(v) != batch_size for v in encoded_inputs.values()):
1521
+ raise ValueError("Some items in the output dictionary have a different batch size than others.")
1522
+
1523
+ if padding_strategy == PaddingStrategy.LONGEST:
1524
+ max_length = max(len(inputs) for inputs in required_input)
1525
+ max_entity_length = (
1526
+ max(len(inputs) for inputs in encoded_inputs["entity_ids"]) if "entity_ids" in encoded_inputs else 0
1527
+ )
1528
+ padding_strategy = PaddingStrategy.MAX_LENGTH
1529
+
1530
+ batch_outputs = {}
1531
+ for i in range(batch_size):
1532
+ inputs = {k: v[i] for k, v in encoded_inputs.items()}
1533
+ outputs = self._pad(
1534
+ inputs,
1535
+ max_length=max_length,
1536
+ max_entity_length=max_entity_length,
1537
+ padding_strategy=padding_strategy,
1538
+ pad_to_multiple_of=pad_to_multiple_of,
1539
+ padding_side=padding_side,
1540
+ return_attention_mask=return_attention_mask,
1541
+ )
1542
+
1543
+ for key, value in outputs.items():
1544
+ if key not in batch_outputs:
1545
+ batch_outputs[key] = []
1546
+ batch_outputs[key].append(value)
1547
+
1548
+ return BatchEncoding(batch_outputs, tensor_type=return_tensors)
1549
+
1550
+ def _pad(
1551
+ self,
1552
+ encoded_inputs: Union[Dict[str, EncodedInput], BatchEncoding],
1553
+ max_length: Optional[int] = None,
1554
+ max_entity_length: Optional[int] = None,
1555
+ padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD,
1556
+ pad_to_multiple_of: Optional[int] = None,
1557
+ padding_side: Optional[str] = None,
1558
+ return_attention_mask: Optional[bool] = None,
1559
+ ) -> dict:
1560
+ """
1561
+ Pad encoded inputs (on left/right and up to predefined length or max length in the batch)
1562
+
1563
+
1564
+ Args:
1565
+ encoded_inputs:
1566
+ Dictionary of tokenized inputs (`List[int]`) or batch of tokenized inputs (`List[List[int]]`).
1567
+ max_length: maximum length of the returned list and optionally padding length (see below).
1568
+ Will truncate by taking into account the special tokens.
1569
+ max_entity_length: The maximum length of the entity sequence.
1570
+ padding_strategy: PaddingStrategy to use for padding.
1571
+
1572
+
1573
+ - PaddingStrategy.LONGEST Pad to the longest sequence in the batch
1574
+ - PaddingStrategy.MAX_LENGTH: Pad to the max length (default)
1575
+ - PaddingStrategy.DO_NOT_PAD: Do not pad
1576
+ The tokenizer padding sides are defined in self.padding_side:
1577
+
1578
+
1579
+ - 'left': pads on the left of the sequences
1580
+ - 'right': pads on the right of the sequences
1581
+ pad_to_multiple_of: (optional) Integer if set will pad the sequence to a multiple of the provided value.
1582
+ This is especially useful to enable the use of Tensor Core on NVIDIA hardware with compute capability
1583
+ `>= 7.5` (Volta).
1584
+ padding_side:
1585
+ The side on which the model should have padding applied. Should be selected between ['right', 'left'].
1586
+ Default value is picked from the class attribute of the same name.
1587
+ return_attention_mask:
1588
+ (optional) Set to False to avoid returning attention mask (default: set to model specifics)
1589
+ """
1590
+ entities_provided = bool("entity_ids" in encoded_inputs)
1591
+
1592
+ # Load from model defaults
1593
+ if return_attention_mask is None:
1594
+ return_attention_mask = "attention_mask" in self.model_input_names
1595
+
1596
+ if padding_strategy == PaddingStrategy.LONGEST:
1597
+ max_length = len(encoded_inputs["input_ids"])
1598
+ if entities_provided:
1599
+ max_entity_length = len(encoded_inputs["entity_ids"])
1600
+
1601
+ if max_length is not None and pad_to_multiple_of is not None and (max_length % pad_to_multiple_of != 0):
1602
+ max_length = ((max_length // pad_to_multiple_of) + 1) * pad_to_multiple_of
1603
+
1604
+ if (
1605
+ entities_provided
1606
+ and max_entity_length is not None
1607
+ and pad_to_multiple_of is not None
1608
+ and (max_entity_length % pad_to_multiple_of != 0)
1609
+ ):
1610
+ max_entity_length = ((max_entity_length // pad_to_multiple_of) + 1) * pad_to_multiple_of
1611
+
1612
+ needs_to_be_padded = padding_strategy != PaddingStrategy.DO_NOT_PAD and (
1613
+ len(encoded_inputs["input_ids"]) != max_length
1614
+ or (entities_provided and len(encoded_inputs["entity_ids"]) != max_entity_length)
1615
+ )
1616
+
1617
+ # Initialize attention mask if not present.
1618
+ if return_attention_mask and "attention_mask" not in encoded_inputs:
1619
+ encoded_inputs["attention_mask"] = [1] * len(encoded_inputs["input_ids"])
1620
+ if entities_provided and return_attention_mask and "entity_attention_mask" not in encoded_inputs:
1621
+ encoded_inputs["entity_attention_mask"] = [1] * len(encoded_inputs["entity_ids"])
1622
+
1623
+ if needs_to_be_padded:
1624
+ difference = max_length - len(encoded_inputs["input_ids"])
1625
+ padding_side = padding_side if padding_side is not None else self.padding_side
1626
+ if entities_provided:
1627
+ entity_difference = max_entity_length - len(encoded_inputs["entity_ids"])
1628
+ if padding_side == "right":
1629
+ if return_attention_mask:
1630
+ encoded_inputs["attention_mask"] = encoded_inputs["attention_mask"] + [0] * difference
1631
+ if entities_provided:
1632
+ encoded_inputs["entity_attention_mask"] = (
1633
+ encoded_inputs["entity_attention_mask"] + [0] * entity_difference
1634
+ )
1635
+ if "token_type_ids" in encoded_inputs:
1636
+ encoded_inputs["token_type_ids"] = encoded_inputs["token_type_ids"] + [0] * difference
1637
+ if entities_provided:
1638
+ encoded_inputs["entity_token_type_ids"] = (
1639
+ encoded_inputs["entity_token_type_ids"] + [0] * entity_difference
1640
+ )
1641
+ if "special_tokens_mask" in encoded_inputs:
1642
+ encoded_inputs["special_tokens_mask"] = encoded_inputs["special_tokens_mask"] + [1] * difference
1643
+ encoded_inputs["input_ids"] = encoded_inputs["input_ids"] + [self.pad_token_id] * difference
1644
+ if entities_provided:
1645
+ encoded_inputs["entity_ids"] = (
1646
+ encoded_inputs["entity_ids"] + [self.entity_pad_token_id] * entity_difference
1647
+ )
1648
+ encoded_inputs["entity_position_ids"] = (
1649
+ encoded_inputs["entity_position_ids"] + [[-1] * self.max_mention_length] * entity_difference
1650
+ )
1651
+ if self.task == "entity_span_classification":
1652
+ encoded_inputs["entity_start_positions"] = (
1653
+ encoded_inputs["entity_start_positions"] + [0] * entity_difference
1654
+ )
1655
+ encoded_inputs["entity_end_positions"] = (
1656
+ encoded_inputs["entity_end_positions"] + [0] * entity_difference
1657
+ )
1658
+
1659
+ elif padding_side == "left":
1660
+ if return_attention_mask:
1661
+ encoded_inputs["attention_mask"] = [0] * difference + encoded_inputs["attention_mask"]
1662
+ if entities_provided:
1663
+ encoded_inputs["entity_attention_mask"] = [0] * entity_difference + encoded_inputs[
1664
+ "entity_attention_mask"
1665
+ ]
1666
+ if "token_type_ids" in encoded_inputs:
1667
+ encoded_inputs["token_type_ids"] = [0] * difference + encoded_inputs["token_type_ids"]
1668
+ if entities_provided:
1669
+ encoded_inputs["entity_token_type_ids"] = [0] * entity_difference + encoded_inputs[
1670
+ "entity_token_type_ids"
1671
+ ]
1672
+ if "special_tokens_mask" in encoded_inputs:
1673
+ encoded_inputs["special_tokens_mask"] = [1] * difference + encoded_inputs["special_tokens_mask"]
1674
+ encoded_inputs["input_ids"] = [self.pad_token_id] * difference + encoded_inputs["input_ids"]
1675
+ if entities_provided:
1676
+ encoded_inputs["entity_ids"] = [self.entity_pad_token_id] * entity_difference + encoded_inputs[
1677
+ "entity_ids"
1678
+ ]
1679
+ encoded_inputs["entity_position_ids"] = [
1680
+ [-1] * self.max_mention_length
1681
+ ] * entity_difference + encoded_inputs["entity_position_ids"]
1682
+ if self.task == "entity_span_classification":
1683
+ encoded_inputs["entity_start_positions"] = [0] * entity_difference + encoded_inputs[
1684
+ "entity_start_positions"
1685
+ ]
1686
+ encoded_inputs["entity_end_positions"] = [0] * entity_difference + encoded_inputs[
1687
+ "entity_end_positions"
1688
+ ]
1689
+ else:
1690
+ raise ValueError("Invalid padding strategy:" + str(padding_side))
1691
+
1692
+ return encoded_inputs
1693
+
1694
+ def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
1695
+ if not os.path.isdir(save_directory):
1696
+ logger.error(f"Vocabulary path ({save_directory}) should be a directory")
1697
+ return
1698
+ vocab_file = os.path.join(
1699
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
1700
+ )
1701
+ merge_file = os.path.join(
1702
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["merges_file"]
1703
+ )
1704
+
1705
+ with open(vocab_file, "w", encoding="utf-8") as f:
1706
+ f.write(json.dumps(self.encoder, indent=2, sort_keys=True, ensure_ascii=False) + "\n")
1707
+
1708
+ index = 0
1709
+ with open(merge_file, "w", encoding="utf-8") as writer:
1710
+ writer.write("#version: 0.2\n")
1711
+ for bpe_tokens, token_index in sorted(self.bpe_ranks.items(), key=lambda kv: kv[1]):
1712
+ if index != token_index:
1713
+ logger.warning(
1714
+ f"Saving vocabulary to {merge_file}: BPE merge indices are not consecutive."
1715
+ " Please check that the tokenizer is not corrupted!"
1716
+ )
1717
+ index = token_index
1718
+ writer.write(" ".join(bpe_tokens) + "\n")
1719
+ index += 1
1720
+
1721
+ entity_vocab_file = os.path.join(
1722
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["entity_vocab_file"]
1723
+ )
1724
+
1725
+ with open(entity_vocab_file, "w", encoding="utf-8") as f:
1726
+ f.write(json.dumps(self.entity_vocab, indent=2, sort_keys=True, ensure_ascii=False) + "\n")
1727
+
1728
+ return vocab_file, merge_file, entity_vocab_file
1729
+
1730
+
1731
+ __all__ = ["LukeTokenizer"]
tasks/tasksmith-441eeab80047/environment/source/src/transformers/models/lxmert/__init__.py ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 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 _LazyModule
17
+ from ...utils.import_utils import define_import_structure
18
+
19
+
20
+ if TYPE_CHECKING:
21
+ from .configuration_lxmert import *
22
+ from .modeling_lxmert import *
23
+ from .modeling_tf_lxmert import *
24
+ from .tokenization_lxmert import *
25
+ from .tokenization_lxmert_fast import *
26
+ else:
27
+ import sys
28
+
29
+ _file = globals()["__file__"]
30
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
tasks/tasksmith-441eeab80047/environment/source/src/transformers/models/lxmert/configuration_lxmert.py ADDED
@@ -0,0 +1,169 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2018, Hao Tan, Mohit Bansal
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
+ """LXMERT model configuration"""
16
+
17
+ from ...configuration_utils import PretrainedConfig
18
+ from ...utils import logging
19
+
20
+
21
+ logger = logging.get_logger(__name__)
22
+
23
+
24
+ class LxmertConfig(PretrainedConfig):
25
+ r"""
26
+ This is the configuration class to store the configuration of a [`LxmertModel`] or a [`TFLxmertModel`]. It is used
27
+ to instantiate a LXMERT model according to the specified arguments, defining the model architecture. Instantiating
28
+ a configuration with the defaults will yield a similar configuration to that of the Lxmert
29
+ [unc-nlp/lxmert-base-uncased](https://huggingface.co/unc-nlp/lxmert-base-uncased) architecture.
30
+
31
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
32
+ documentation from [`PretrainedConfig`] for more information.
33
+
34
+
35
+ Args:
36
+ vocab_size (`int`, *optional*, defaults to 30522):
37
+ Vocabulary size of the LXMERT model. Defines the number of different tokens that can be represented by the
38
+ `inputs_ids` passed when calling [`LxmertModel`] or [`TFLxmertModel`].
39
+ hidden_size (`int`, *optional*, defaults to 768):
40
+ Dimensionality of the encoder layers and the pooler layer.
41
+ num_attention_heads (`int`, *optional*, defaults to 12):
42
+ Number of attention heads for each attention layer in the Transformer encoder.
43
+ num_qa_labels (`int`, *optional*, defaults to 9500):
44
+ This represents the total number of different question answering (QA) labels there are. If using more than
45
+ one dataset with QA, the user will need to account for the total number of labels that all of the datasets
46
+ have in total.
47
+ num_object_labels (`int`, *optional*, defaults to 1600):
48
+ This represents the total number of semantically unique objects that lxmert will be able to classify a
49
+ pooled-object feature as belonging too.
50
+ num_attr_labels (`int`, *optional*, defaults to 400):
51
+ This represents the total number of semantically unique attributes that lxmert will be able to classify a
52
+ pooled-object feature as possessing.
53
+ intermediate_size (`int`, *optional*, defaults to 3072):
54
+ Dimensionality of the "intermediate" (often named feed-forward) layer in the Transformer encoder.
55
+ hidden_act (`str` or `Callable`, *optional*, defaults to `"gelu"`):
56
+ The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
57
+ `"relu"`, `"silu"` and `"gelu_new"` are supported.
58
+ hidden_dropout_prob (`float`, *optional*, defaults to 0.1):
59
+ The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
60
+ attention_probs_dropout_prob (`float`, *optional*, defaults to 0.1):
61
+ The dropout ratio for the attention probabilities.
62
+ max_position_embeddings (`int`, *optional*, defaults to 512):
63
+ The maximum sequence length that this model might ever be used with. Typically set this to something large
64
+ just in case (e.g., 512 or 1024 or 2048).
65
+ type_vocab_size (`int`, *optional*, defaults to 2):
66
+ The vocabulary size of the *token_type_ids* passed into [`BertModel`].
67
+ initializer_range (`float`, *optional*, defaults to 0.02):
68
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
69
+ layer_norm_eps (`float`, *optional*, defaults to 1e-12):
70
+ The epsilon used by the layer normalization layers.
71
+ l_layers (`int`, *optional*, defaults to 9):
72
+ Number of hidden layers in the Transformer language encoder.
73
+ x_layers (`int`, *optional*, defaults to 5):
74
+ Number of hidden layers in the Transformer cross modality encoder.
75
+ r_layers (`int`, *optional*, defaults to 5):
76
+ Number of hidden layers in the Transformer visual encoder.
77
+ visual_feat_dim (`int`, *optional*, defaults to 2048):
78
+ This represents the last dimension of the pooled-object features used as input for the model, representing
79
+ the size of each object feature itself.
80
+ visual_pos_dim (`int`, *optional*, defaults to 4):
81
+ This represents the number of spacial features that are mixed into the visual features. The default is set
82
+ to 4 because most commonly this will represent the location of a bounding box. i.e., (x, y, width, height)
83
+ visual_loss_normalizer (`float`, *optional*, defaults to 6.67):
84
+ This represents the scaling factor in which each visual loss is multiplied by if during pretraining, one
85
+ decided to train with multiple vision-based loss objectives.
86
+ task_matched (`bool`, *optional*, defaults to `True`):
87
+ This task is used for sentence-image matching. If the sentence correctly describes the image the label will
88
+ be 1. If the sentence does not correctly describe the image, the label will be 0.
89
+ task_mask_lm (`bool`, *optional*, defaults to `True`):
90
+ Whether or not to add masked language modeling (as used in pretraining models such as BERT) to the loss
91
+ objective.
92
+ task_obj_predict (`bool`, *optional*, defaults to `True`):
93
+ Whether or not to add object prediction, attribute prediction and feature regression to the loss objective.
94
+ task_qa (`bool`, *optional*, defaults to `True`):
95
+ Whether or not to add the question-answering loss to the objective
96
+ visual_obj_loss (`bool`, *optional*, defaults to `True`):
97
+ Whether or not to calculate the object-prediction loss objective
98
+ visual_attr_loss (`bool`, *optional*, defaults to `True`):
99
+ Whether or not to calculate the attribute-prediction loss objective
100
+ visual_feat_loss (`bool`, *optional*, defaults to `True`):
101
+ Whether or not to calculate the feature-regression loss objective
102
+ """
103
+
104
+ model_type = "lxmert"
105
+ attribute_map = {}
106
+
107
+ def __init__(
108
+ self,
109
+ vocab_size=30522,
110
+ hidden_size=768,
111
+ num_attention_heads=12,
112
+ num_qa_labels=9500,
113
+ num_object_labels=1600,
114
+ num_attr_labels=400,
115
+ intermediate_size=3072,
116
+ hidden_act="gelu",
117
+ hidden_dropout_prob=0.1,
118
+ attention_probs_dropout_prob=0.1,
119
+ max_position_embeddings=512,
120
+ type_vocab_size=2,
121
+ initializer_range=0.02,
122
+ layer_norm_eps=1e-12,
123
+ l_layers=9,
124
+ x_layers=5,
125
+ r_layers=5,
126
+ visual_feat_dim=2048,
127
+ visual_pos_dim=4,
128
+ visual_loss_normalizer=6.67,
129
+ task_matched=True,
130
+ task_mask_lm=True,
131
+ task_obj_predict=True,
132
+ task_qa=True,
133
+ visual_obj_loss=True,
134
+ visual_attr_loss=True,
135
+ visual_feat_loss=True,
136
+ **kwargs,
137
+ ):
138
+ self.vocab_size = vocab_size
139
+ self.hidden_size = hidden_size
140
+ self.num_attention_heads = num_attention_heads
141
+ self.hidden_act = hidden_act
142
+ self.intermediate_size = intermediate_size
143
+ self.hidden_dropout_prob = hidden_dropout_prob
144
+ self.attention_probs_dropout_prob = attention_probs_dropout_prob
145
+ self.max_position_embeddings = max_position_embeddings
146
+ self.type_vocab_size = type_vocab_size
147
+ self.initializer_range = initializer_range
148
+ self.layer_norm_eps = layer_norm_eps
149
+ self.num_qa_labels = num_qa_labels
150
+ self.num_object_labels = num_object_labels
151
+ self.num_attr_labels = num_attr_labels
152
+ self.l_layers = l_layers
153
+ self.x_layers = x_layers
154
+ self.r_layers = r_layers
155
+ self.visual_feat_dim = visual_feat_dim
156
+ self.visual_pos_dim = visual_pos_dim
157
+ self.visual_loss_normalizer = visual_loss_normalizer
158
+ self.task_matched = task_matched
159
+ self.task_mask_lm = task_mask_lm
160
+ self.task_obj_predict = task_obj_predict
161
+ self.task_qa = task_qa
162
+ self.visual_obj_loss = visual_obj_loss
163
+ self.visual_attr_loss = visual_attr_loss
164
+ self.visual_feat_loss = visual_feat_loss
165
+ self.num_hidden_layers = {"vision": r_layers, "cross_encoder": x_layers, "language": l_layers}
166
+ super().__init__(**kwargs)
167
+
168
+
169
+ __all__ = ["LxmertConfig"]
tasks/tasksmith-441eeab80047/environment/source/src/transformers/models/lxmert/convert_lxmert_original_tf_checkpoint_to_pytorch.py ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ """Convert LXMERT checkpoint."""
16
+
17
+ import argparse
18
+
19
+ import torch
20
+
21
+ from transformers import LxmertConfig, LxmertForPreTraining, load_tf_weights_in_lxmert
22
+ from transformers.utils import logging
23
+
24
+
25
+ logging.set_verbosity_info()
26
+
27
+
28
+ def convert_tf_checkpoint_to_pytorch(tf_checkpoint_path, config_file, pytorch_dump_path):
29
+ # Initialise PyTorch model
30
+ config = LxmertConfig.from_json_file(config_file)
31
+ print(f"Building PyTorch model from configuration: {config}")
32
+ model = LxmertForPreTraining(config)
33
+
34
+ # Load weights from tf checkpoint
35
+ load_tf_weights_in_lxmert(model, config, tf_checkpoint_path)
36
+
37
+ # Save pytorch-model
38
+ print(f"Save PyTorch model to {pytorch_dump_path}")
39
+ torch.save(model.state_dict(), pytorch_dump_path)
40
+
41
+
42
+ if __name__ == "__main__":
43
+ parser = argparse.ArgumentParser()
44
+ # Required parameters
45
+ parser.add_argument(
46
+ "--tf_checkpoint_path", default=None, type=str, required=True, help="Path to the TensorFlow checkpoint path."
47
+ )
48
+ parser.add_argument(
49
+ "--config_file",
50
+ default=None,
51
+ type=str,
52
+ required=True,
53
+ help="The config json file corresponding to the pre-trained model. \nThis specifies the model architecture.",
54
+ )
55
+ parser.add_argument(
56
+ "--pytorch_dump_path", default=None, type=str, required=True, help="Path to the output PyTorch model."
57
+ )
58
+ args = parser.parse_args()
59
+ convert_tf_checkpoint_to_pytorch(args.tf_checkpoint_path, args.config_file, args.pytorch_dump_path)
tasks/tasksmith-441eeab80047/environment/source/src/transformers/models/lxmert/modeling_lxmert.py ADDED
@@ -0,0 +1,1463 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2018 Hao Tan, Mohit Bansal, and the HuggingFace 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 LXMERT model."""
16
+
17
+ import math
18
+ import os
19
+ import warnings
20
+ from dataclasses import dataclass
21
+ from typing import Dict, Optional, Tuple, Union
22
+
23
+ import torch
24
+ from torch import nn
25
+ from torch.nn import CrossEntropyLoss, SmoothL1Loss
26
+
27
+ from ...activations import ACT2FN, gelu
28
+ from ...modeling_utils import PreTrainedModel
29
+ from ...utils import (
30
+ ModelOutput,
31
+ add_code_sample_docstrings,
32
+ add_start_docstrings,
33
+ add_start_docstrings_to_model_forward,
34
+ logging,
35
+ replace_return_docstrings,
36
+ )
37
+ from .configuration_lxmert import LxmertConfig
38
+
39
+
40
+ logger = logging.get_logger(__name__)
41
+
42
+ _CHECKPOINT_FOR_DOC = "unc-nlp/lxmert-base-uncased"
43
+ _CONFIG_FOR_DOC = "LxmertConfig"
44
+
45
+
46
+ class GeLU(nn.Module):
47
+ def __init__(self):
48
+ super().__init__()
49
+
50
+ def forward(self, x):
51
+ return gelu(x)
52
+
53
+
54
+ @dataclass
55
+ class LxmertModelOutput(ModelOutput):
56
+ """
57
+ Lxmert's outputs that contain the last hidden states, pooled outputs, and attention probabilities for the language,
58
+ visual, and, cross-modality encoders. (note: the visual encoder in Lxmert is referred to as the "relation-ship"
59
+ encoder")
60
+
61
+
62
+ Args:
63
+ language_output (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
64
+ Sequence of hidden-states at the output of the last layer of the language encoder.
65
+ vision_output (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
66
+ Sequence of hidden-states at the output of the last layer of the visual encoder.
67
+ pooled_output (`torch.FloatTensor` of shape `(batch_size, hidden_size)`):
68
+ Last layer hidden-state of the first token of the sequence (classification, CLS, token) further processed
69
+ by a Linear layer and a Tanh activation function. The Linear
70
+ language_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
71
+ Tuple of `torch.FloatTensor` (one for input features + one for the output of each cross-modality layer) of
72
+ shape `(batch_size, sequence_length, hidden_size)`.
73
+ vision_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
74
+ Tuple of `torch.FloatTensor` (one for input features + one for the output of each cross-modality layer) of
75
+ shape `(batch_size, sequence_length, hidden_size)`.
76
+ language_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
77
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
78
+ sequence_length)`. Attentions weights after the attention softmax, used to compute the weighted average in
79
+ the self-attention heads.
80
+ vision_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
81
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
82
+ sequence_length)`. Attentions weights after the attention softmax, used to compute the weighted average in
83
+ the self-attention heads.
84
+ cross_encoder_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
85
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
86
+ sequence_length)`. Attentions weights after the attention softmax, used to compute the weighted average in
87
+ the self-attention heads.
88
+ """
89
+
90
+ language_output: Optional[torch.FloatTensor] = None
91
+ vision_output: Optional[torch.FloatTensor] = None
92
+ pooled_output: Optional[torch.FloatTensor] = None
93
+ language_hidden_states: Optional[Tuple[torch.FloatTensor]] = None
94
+ vision_hidden_states: Optional[Tuple[torch.FloatTensor]] = None
95
+ language_attentions: Optional[Tuple[torch.FloatTensor]] = None
96
+ vision_attentions: Optional[Tuple[torch.FloatTensor]] = None
97
+ cross_encoder_attentions: Optional[Tuple[torch.FloatTensor]] = None
98
+
99
+
100
+ @dataclass
101
+ class LxmertForQuestionAnsweringOutput(ModelOutput):
102
+ """
103
+ Output type of [`LxmertForQuestionAnswering`].
104
+
105
+ Args:
106
+ loss (*optional*, returned when `labels` is provided, `torch.FloatTensor` of shape `(1,)`):
107
+ Total loss as the sum of the masked language modeling loss and the next sequence prediction
108
+ (classification) loss.k.
109
+ question_answering_score (`torch.FloatTensor` of shape `(batch_size, n_qa_answers)`, *optional*):
110
+ Prediction scores of question answering objective (classification).
111
+ language_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
112
+ Tuple of `torch.FloatTensor` (one for input features + one for the output of each cross-modality layer) of
113
+ shape `(batch_size, sequence_length, hidden_size)`.
114
+ vision_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
115
+ Tuple of `torch.FloatTensor` (one for input features + one for the output of each cross-modality layer) of
116
+ shape `(batch_size, sequence_length, hidden_size)`.
117
+ language_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
118
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
119
+ sequence_length)`. Attentions weights after the attention softmax, used to compute the weighted average in
120
+ the self-attention heads.
121
+ vision_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
122
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
123
+ sequence_length)`. Attentions weights after the attention softmax, used to compute the weighted average in
124
+ the self-attention heads.
125
+ cross_encoder_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
126
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
127
+ sequence_length)`. Attentions weights after the attention softmax, used to compute the weighted average in
128
+ the self-attention heads.
129
+ """
130
+
131
+ loss: Optional[torch.FloatTensor] = None
132
+ question_answering_score: Optional[torch.FloatTensor] = None
133
+ language_hidden_states: Optional[Tuple[torch.FloatTensor]] = None
134
+ vision_hidden_states: Optional[Tuple[torch.FloatTensor]] = None
135
+ language_attentions: Optional[Tuple[torch.FloatTensor]] = None
136
+ vision_attentions: Optional[Tuple[torch.FloatTensor]] = None
137
+ cross_encoder_attentions: Optional[Tuple[torch.FloatTensor]] = None
138
+
139
+
140
+ @dataclass
141
+ class LxmertForPreTrainingOutput(ModelOutput):
142
+ """
143
+ Output type of [`LxmertForPreTraining`].
144
+
145
+ Args:
146
+ loss (*optional*, returned when `labels` is provided, `torch.FloatTensor` of shape `(1,)`):
147
+ Total loss as the sum of the masked language modeling loss and the next sequence prediction
148
+ (classification) loss.
149
+ prediction_logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
150
+ Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
151
+ cross_relationship_score (`torch.FloatTensor` of shape `(batch_size, 2)`):
152
+ Prediction scores of the textual matching objective (classification) head (scores of True/False
153
+ continuation before SoftMax).
154
+ question_answering_score (`torch.FloatTensor` of shape `(batch_size, n_qa_answers)`):
155
+ Prediction scores of question answering objective (classification).
156
+ language_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
157
+ Tuple of `torch.FloatTensor` (one for input features + one for the output of each cross-modality layer) of
158
+ shape `(batch_size, sequence_length, hidden_size)`.
159
+ vision_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
160
+ Tuple of `torch.FloatTensor` (one for input features + one for the output of each cross-modality layer) of
161
+ shape `(batch_size, sequence_length, hidden_size)`.
162
+ language_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
163
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
164
+ sequence_length)`. Attentions weights after the attention softmax, used to compute the weighted average in
165
+ the self-attention heads.
166
+ vision_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
167
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
168
+ sequence_length)`. Attentions weights after the attention softmax, used to compute the weighted average in
169
+ the self-attention heads.
170
+ cross_encoder_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
171
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
172
+ sequence_length)`. Attentions weights after the attention softmax, used to compute the weighted average in
173
+ the self-attention heads.
174
+
175
+ """
176
+
177
+ loss: Optional[torch.FloatTensor] = None
178
+ prediction_logits: Optional[torch.FloatTensor] = None
179
+ cross_relationship_score: Optional[torch.FloatTensor] = None
180
+ question_answering_score: Optional[torch.FloatTensor] = None
181
+ language_hidden_states: Optional[Tuple[torch.FloatTensor]] = None
182
+ vision_hidden_states: Optional[Tuple[torch.FloatTensor]] = None
183
+ language_attentions: Optional[Tuple[torch.FloatTensor]] = None
184
+ vision_attentions: Optional[Tuple[torch.FloatTensor]] = None
185
+ cross_encoder_attentions: Optional[Tuple[torch.FloatTensor]] = None
186
+
187
+
188
+ def load_tf_weights_in_lxmert(model, config, tf_checkpoint_path):
189
+ """Load tf checkpoints in a pytorch model."""
190
+ try:
191
+ import re
192
+
193
+ import numpy as np
194
+ import tensorflow as tf
195
+ except ImportError:
196
+ logger.error(
197
+ "Loading a TensorFlow model in PyTorch, requires TensorFlow to be installed. Please see "
198
+ "https://www.tensorflow.org/install/ for installation instructions."
199
+ )
200
+ raise
201
+ tf_path = os.path.abspath(tf_checkpoint_path)
202
+ logger.info(f"Converting TensorFlow checkpoint from {tf_path}")
203
+ # Load weights from TF model
204
+ init_vars = tf.train.list_variables(tf_path)
205
+ names = []
206
+ arrays = []
207
+ for name, shape in init_vars:
208
+ logger.info(f"Loading TF weight {name} with shape {shape}")
209
+ array = tf.train.load_variable(tf_path, name)
210
+ names.append(name)
211
+ arrays.append(array)
212
+
213
+ for name, array in zip(names, arrays):
214
+ name = name.split("/")
215
+ # adam_v and adam_m are variables used in AdamWeightDecayOptimizer to calculated m and v
216
+ # which are not required for using pretrained model
217
+ if any(
218
+ n
219
+ in [
220
+ "adam_v",
221
+ "adam_m",
222
+ "AdamWeightDecayOptimizer",
223
+ "AdamWeightDecayOptimizer_1",
224
+ "global_step",
225
+ ]
226
+ for n in name
227
+ ):
228
+ logger.info(f"Skipping {'/'.join(name)}")
229
+ continue
230
+ pointer = model
231
+ for m_name in name:
232
+ if re.fullmatch(r"[A-Za-z]+_\d+", m_name):
233
+ scope_names = re.split(r"_(\d+)", m_name)
234
+ else:
235
+ scope_names = [m_name]
236
+ if scope_names[0] == "kernel" or scope_names[0] == "gamma":
237
+ pointer = getattr(pointer, "weight")
238
+ elif scope_names[0] == "output_bias" or scope_names[0] == "beta":
239
+ pointer = getattr(pointer, "bias")
240
+ elif scope_names[0] == "output_weights":
241
+ pointer = getattr(pointer, "weight")
242
+ elif scope_names[0] == "squad":
243
+ pointer = getattr(pointer, "classifier")
244
+ else:
245
+ try:
246
+ pointer = getattr(pointer, scope_names[0])
247
+ except AttributeError:
248
+ logger.info(f"Skipping {'/'.join(name)}")
249
+ continue
250
+ if len(scope_names) >= 2:
251
+ num = int(scope_names[1])
252
+ pointer = pointer[num]
253
+ if m_name[-11:] == "_embeddings":
254
+ pointer = getattr(pointer, "weight")
255
+ elif m_name == "kernel":
256
+ array = np.transpose(array)
257
+ try:
258
+ assert pointer.shape == array.shape
259
+ except AssertionError as e:
260
+ e.args += (pointer.shape, array.shape)
261
+ raise
262
+ logger.info(f"Initialize PyTorch weight {name}")
263
+ pointer.data = torch.from_numpy(array)
264
+ return model
265
+
266
+
267
+ class LxmertEmbeddings(nn.Module):
268
+ """Construct the embeddings from word, position and token_type embeddings."""
269
+
270
+ def __init__(self, config):
271
+ super().__init__()
272
+ self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=0)
273
+ self.position_embeddings = nn.Embedding(config.max_position_embeddings, config.hidden_size, padding_idx=0)
274
+ self.token_type_embeddings = nn.Embedding(config.type_vocab_size, config.hidden_size, padding_idx=0)
275
+
276
+ # self.LayerNorm is not snake-cased to stick with TensorFlow model variable name and be able to load
277
+ # any TensorFlow checkpoint file
278
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=1e-12)
279
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
280
+
281
+ def forward(self, input_ids, token_type_ids=None, inputs_embeds=None):
282
+ if input_ids is not None:
283
+ input_shape = input_ids.size()
284
+ device = input_ids.device
285
+ else:
286
+ input_shape = inputs_embeds.size()[:-1]
287
+ device = inputs_embeds.device
288
+ seq_length = input_shape[1]
289
+
290
+ position_ids = torch.arange(seq_length, dtype=torch.long, device=device)
291
+ position_ids = position_ids.unsqueeze(0).expand(input_shape)
292
+
293
+ if token_type_ids is None:
294
+ token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=self.position_ids.device)
295
+
296
+ if inputs_embeds is None:
297
+ inputs_embeds = self.word_embeddings(input_ids)
298
+ position_embeddings = self.position_embeddings(position_ids)
299
+ token_type_embeddings = self.token_type_embeddings(token_type_ids)
300
+
301
+ embeddings = inputs_embeds + position_embeddings + token_type_embeddings
302
+ embeddings = self.LayerNorm(embeddings)
303
+ embeddings = self.dropout(embeddings)
304
+ return embeddings
305
+
306
+
307
+ class LxmertAttention(nn.Module):
308
+ def __init__(self, config, ctx_dim=None):
309
+ super().__init__()
310
+ if config.hidden_size % config.num_attention_heads != 0:
311
+ raise ValueError(
312
+ f"The hidden size ({config.hidden_size}) is not a multiple of the number of attention "
313
+ f"heads ({config.num_attention_heads})"
314
+ )
315
+ self.num_attention_heads = config.num_attention_heads
316
+ self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
317
+ self.head_size = self.num_attention_heads * self.attention_head_size
318
+
319
+ # visual_dim = 2048
320
+ if ctx_dim is None:
321
+ ctx_dim = config.hidden_size
322
+ self.query = nn.Linear(config.hidden_size, self.head_size)
323
+ self.key = nn.Linear(ctx_dim, self.head_size)
324
+ self.value = nn.Linear(ctx_dim, self.head_size)
325
+
326
+ self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
327
+
328
+ def transpose_for_scores(self, x):
329
+ new_x_shape = x.size()[:-1] + (
330
+ self.num_attention_heads,
331
+ self.attention_head_size,
332
+ )
333
+ x = x.view(new_x_shape)
334
+ return x.permute(0, 2, 1, 3)
335
+
336
+ def forward(self, hidden_states, context, attention_mask=None, output_attentions=False):
337
+ mixed_query_layer = self.query(hidden_states)
338
+ mixed_key_layer = self.key(context)
339
+ mixed_value_layer = self.value(context)
340
+
341
+ query_layer = self.transpose_for_scores(mixed_query_layer)
342
+ key_layer = self.transpose_for_scores(mixed_key_layer)
343
+ value_layer = self.transpose_for_scores(mixed_value_layer)
344
+
345
+ # Take the dot product between "query" and "key" to get the raw attention scores.
346
+ attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))
347
+ attention_scores = attention_scores / math.sqrt(self.attention_head_size)
348
+ # Apply the attention mask is (precomputed for all layers in BertModel forward() function)
349
+ if attention_mask is not None:
350
+ attention_scores = attention_scores + attention_mask
351
+
352
+ # Normalize the attention scores to probabilities.
353
+ attention_probs = nn.functional.softmax(attention_scores, dim=-1)
354
+
355
+ # This is actually dropping out entire tokens to attend to, which might
356
+ # seem a bit unusual, but is taken from the original Transformer paper.
357
+ attention_probs = self.dropout(attention_probs)
358
+
359
+ context_layer = torch.matmul(attention_probs, value_layer)
360
+ context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
361
+ new_context_layer_shape = context_layer.size()[:-2] + (self.head_size,)
362
+ context_layer = context_layer.view(new_context_layer_shape)
363
+
364
+ outputs = (context_layer, attention_probs) if output_attentions else (context_layer,)
365
+ return outputs
366
+
367
+
368
+ class LxmertAttentionOutput(nn.Module):
369
+ def __init__(self, config):
370
+ super().__init__()
371
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
372
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=1e-12)
373
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
374
+
375
+ def forward(self, hidden_states, input_tensor):
376
+ hidden_states = self.dense(hidden_states)
377
+ hidden_states = self.dropout(hidden_states)
378
+ hidden_states = self.LayerNorm(hidden_states + input_tensor)
379
+ return hidden_states
380
+
381
+
382
+ class LxmertCrossAttentionLayer(nn.Module):
383
+ def __init__(self, config):
384
+ super().__init__()
385
+ self.att = LxmertAttention(config)
386
+ self.output = LxmertAttentionOutput(config)
387
+
388
+ def forward(self, input_tensor, ctx_tensor, ctx_att_mask=None, output_attentions=False):
389
+ output = self.att(input_tensor, ctx_tensor, ctx_att_mask, output_attentions=output_attentions)
390
+ if output_attentions:
391
+ attention_probs = output[1]
392
+ attention_output = self.output(output[0], input_tensor)
393
+ outputs = (attention_output, attention_probs) if output_attentions else (attention_output,)
394
+ return outputs
395
+
396
+
397
+ class LxmertSelfAttentionLayer(nn.Module):
398
+ def __init__(self, config):
399
+ super().__init__()
400
+ self.self = LxmertAttention(config)
401
+ self.output = LxmertAttentionOutput(config)
402
+
403
+ def forward(self, input_tensor, attention_mask, output_attentions=False):
404
+ # Self attention attends to itself, thus keys and queries are the same (input_tensor).
405
+ output = self.self(
406
+ input_tensor,
407
+ input_tensor,
408
+ attention_mask,
409
+ output_attentions=output_attentions,
410
+ )
411
+ if output_attentions:
412
+ attention_probs = output[1]
413
+ attention_output = self.output(output[0], input_tensor)
414
+ outputs = (attention_output, attention_probs) if output_attentions else (attention_output,)
415
+ return outputs
416
+
417
+
418
+ class LxmertIntermediate(nn.Module):
419
+ def __init__(self, config):
420
+ super().__init__()
421
+ self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
422
+ self.intermediate_act_fn = ACT2FN[config.hidden_act]
423
+
424
+ def forward(self, hidden_states):
425
+ hidden_states = self.dense(hidden_states)
426
+ hidden_states = self.intermediate_act_fn(hidden_states)
427
+ return hidden_states
428
+
429
+
430
+ class LxmertOutput(nn.Module):
431
+ def __init__(self, config):
432
+ super().__init__()
433
+ self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
434
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=1e-12)
435
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
436
+
437
+ def forward(self, hidden_states, input_tensor):
438
+ hidden_states = self.dense(hidden_states)
439
+ hidden_states = self.dropout(hidden_states)
440
+ hidden_states = self.LayerNorm(hidden_states + input_tensor)
441
+ return hidden_states
442
+
443
+
444
+ class LxmertLayer(nn.Module):
445
+ def __init__(self, config):
446
+ super().__init__()
447
+ self.attention = LxmertSelfAttentionLayer(config)
448
+ self.intermediate = LxmertIntermediate(config)
449
+ self.output = LxmertOutput(config)
450
+
451
+ def forward(self, hidden_states, attention_mask=None, output_attentions=False):
452
+ outputs = self.attention(hidden_states, attention_mask, output_attentions=output_attentions)
453
+ attention_output = outputs[0]
454
+ intermediate_output = self.intermediate(attention_output)
455
+ layer_output = self.output(intermediate_output, attention_output)
456
+ outputs = (layer_output,) + outputs[1:] # add attentions if we output them
457
+ return outputs
458
+
459
+
460
+ class LxmertXLayer(nn.Module):
461
+ def __init__(self, config):
462
+ super().__init__()
463
+ # The cross-attention Layer
464
+ self.visual_attention = LxmertCrossAttentionLayer(config)
465
+
466
+ # Self-attention Layers
467
+ self.lang_self_att = LxmertSelfAttentionLayer(config)
468
+ self.visn_self_att = LxmertSelfAttentionLayer(config)
469
+
470
+ # Intermediate and Output Layers (FFNs)
471
+ self.lang_inter = LxmertIntermediate(config)
472
+ self.lang_output = LxmertOutput(config)
473
+ self.visn_inter = LxmertIntermediate(config)
474
+ self.visn_output = LxmertOutput(config)
475
+
476
+ def cross_att(
477
+ self,
478
+ lang_input,
479
+ lang_attention_mask,
480
+ visual_input,
481
+ visual_attention_mask,
482
+ output_x_attentions=False,
483
+ ):
484
+ # Cross Attention
485
+ lang_att_output = self.visual_attention(
486
+ lang_input,
487
+ visual_input,
488
+ ctx_att_mask=visual_attention_mask,
489
+ output_attentions=output_x_attentions,
490
+ )
491
+ visual_att_output = self.visual_attention(
492
+ visual_input,
493
+ lang_input,
494
+ ctx_att_mask=lang_attention_mask,
495
+ output_attentions=False,
496
+ )
497
+ return lang_att_output, visual_att_output
498
+
499
+ def self_att(self, lang_input, lang_attention_mask, visual_input, visual_attention_mask):
500
+ # Self Attention
501
+ lang_att_output = self.lang_self_att(lang_input, lang_attention_mask, output_attentions=False)
502
+ visual_att_output = self.visn_self_att(visual_input, visual_attention_mask, output_attentions=False)
503
+ return lang_att_output[0], visual_att_output[0]
504
+
505
+ def output_fc(self, lang_input, visual_input):
506
+ # FC layers
507
+ lang_inter_output = self.lang_inter(lang_input)
508
+ visual_inter_output = self.visn_inter(visual_input)
509
+
510
+ # Layer output
511
+ lang_output = self.lang_output(lang_inter_output, lang_input)
512
+ visual_output = self.visn_output(visual_inter_output, visual_input)
513
+
514
+ return lang_output, visual_output
515
+
516
+ def forward(
517
+ self,
518
+ lang_feats,
519
+ lang_attention_mask,
520
+ visual_feats,
521
+ visual_attention_mask,
522
+ output_attentions=False,
523
+ ):
524
+ lang_att_output, visual_att_output = self.cross_att(
525
+ lang_input=lang_feats,
526
+ lang_attention_mask=lang_attention_mask,
527
+ visual_input=visual_feats,
528
+ visual_attention_mask=visual_attention_mask,
529
+ output_x_attentions=output_attentions,
530
+ )
531
+ attention_probs = lang_att_output[1:]
532
+ lang_att_output, visual_att_output = self.self_att(
533
+ lang_att_output[0],
534
+ lang_attention_mask,
535
+ visual_att_output[0],
536
+ visual_attention_mask,
537
+ )
538
+
539
+ lang_output, visual_output = self.output_fc(lang_att_output, visual_att_output)
540
+ return (
541
+ (
542
+ lang_output,
543
+ visual_output,
544
+ attention_probs[0],
545
+ )
546
+ if output_attentions
547
+ else (lang_output, visual_output)
548
+ )
549
+
550
+
551
+ class LxmertVisualFeatureEncoder(nn.Module):
552
+ def __init__(self, config):
553
+ super().__init__()
554
+ feat_dim = config.visual_feat_dim
555
+ pos_dim = config.visual_pos_dim
556
+
557
+ # Object feature encoding
558
+ self.visn_fc = nn.Linear(feat_dim, config.hidden_size)
559
+ self.visn_layer_norm = nn.LayerNorm(config.hidden_size, eps=1e-12)
560
+
561
+ # Box position encoding
562
+ self.box_fc = nn.Linear(pos_dim, config.hidden_size)
563
+ self.box_layer_norm = nn.LayerNorm(config.hidden_size, eps=1e-12)
564
+
565
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
566
+
567
+ def forward(self, visual_feats, visual_pos):
568
+ x = self.visn_fc(visual_feats)
569
+ x = self.visn_layer_norm(x)
570
+ y = self.box_fc(visual_pos)
571
+ y = self.box_layer_norm(y)
572
+ output = (x + y) / 2
573
+
574
+ output = self.dropout(output)
575
+ return output
576
+
577
+
578
+ class LxmertEncoder(nn.Module):
579
+ def __init__(self, config):
580
+ super().__init__()
581
+
582
+ # Obj-level image embedding layer
583
+ self.visn_fc = LxmertVisualFeatureEncoder(config)
584
+ self.config = config
585
+
586
+ # Number of layers
587
+ self.num_l_layers = config.l_layers
588
+ self.num_x_layers = config.x_layers
589
+ self.num_r_layers = config.r_layers
590
+
591
+ # Layers
592
+ # Using self.layer instead of self.l_layer to support loading BERT weights.
593
+ self.layer = nn.ModuleList([LxmertLayer(config) for _ in range(self.num_l_layers)])
594
+ self.x_layers = nn.ModuleList([LxmertXLayer(config) for _ in range(self.num_x_layers)])
595
+ self.r_layers = nn.ModuleList([LxmertLayer(config) for _ in range(self.num_r_layers)])
596
+
597
+ def forward(
598
+ self,
599
+ lang_feats,
600
+ lang_attention_mask,
601
+ visual_feats,
602
+ visual_pos,
603
+ visual_attention_mask=None,
604
+ output_attentions=None,
605
+ ):
606
+ vision_hidden_states = ()
607
+ language_hidden_states = ()
608
+ vision_attentions = () if output_attentions or self.config.output_attentions else None
609
+ language_attentions = () if output_attentions or self.config.output_attentions else None
610
+ cross_encoder_attentions = () if output_attentions or self.config.output_attentions else None
611
+
612
+ visual_feats = self.visn_fc(visual_feats, visual_pos)
613
+
614
+ # Run language layers
615
+ for layer_module in self.layer:
616
+ l_outputs = layer_module(lang_feats, lang_attention_mask, output_attentions=output_attentions)
617
+ lang_feats = l_outputs[0]
618
+ language_hidden_states = language_hidden_states + (lang_feats,)
619
+ if language_attentions is not None:
620
+ language_attentions = language_attentions + (l_outputs[1],)
621
+
622
+ # Run relational layers
623
+ for layer_module in self.r_layers:
624
+ v_outputs = layer_module(visual_feats, visual_attention_mask, output_attentions=output_attentions)
625
+ visual_feats = v_outputs[0]
626
+ vision_hidden_states = vision_hidden_states + (visual_feats,)
627
+ if vision_attentions is not None:
628
+ vision_attentions = vision_attentions + (v_outputs[1],)
629
+
630
+ # Run cross-modality layers
631
+ for layer_module in self.x_layers:
632
+ x_outputs = layer_module(
633
+ lang_feats,
634
+ lang_attention_mask,
635
+ visual_feats,
636
+ visual_attention_mask,
637
+ output_attentions=output_attentions,
638
+ )
639
+ lang_feats, visual_feats = x_outputs[:2]
640
+ vision_hidden_states = vision_hidden_states + (visual_feats,)
641
+ language_hidden_states = language_hidden_states + (lang_feats,)
642
+ if cross_encoder_attentions is not None:
643
+ cross_encoder_attentions = cross_encoder_attentions + (x_outputs[2],)
644
+ visual_encoder_outputs = (
645
+ vision_hidden_states,
646
+ vision_attentions if output_attentions else None,
647
+ )
648
+ lang_encoder_outputs = (
649
+ language_hidden_states,
650
+ language_attentions if output_attentions else None,
651
+ )
652
+ return (
653
+ visual_encoder_outputs,
654
+ lang_encoder_outputs,
655
+ cross_encoder_attentions if output_attentions else None,
656
+ )
657
+
658
+
659
+ class LxmertPooler(nn.Module):
660
+ def __init__(self, config):
661
+ super(LxmertPooler, self).__init__()
662
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
663
+ self.activation = nn.Tanh()
664
+
665
+ def forward(self, hidden_states):
666
+ # We "pool" the model by simply taking the hidden state corresponding
667
+ # to the first token.
668
+ first_token_tensor = hidden_states[:, 0]
669
+ pooled_output = self.dense(first_token_tensor)
670
+ pooled_output = self.activation(pooled_output)
671
+ return pooled_output
672
+
673
+
674
+ class LxmertPredictionHeadTransform(nn.Module):
675
+ def __init__(self, config):
676
+ super(LxmertPredictionHeadTransform, self).__init__()
677
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
678
+ self.transform_act_fn = ACT2FN[config.hidden_act]
679
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=1e-12)
680
+
681
+ def forward(self, hidden_states):
682
+ hidden_states = self.dense(hidden_states)
683
+ hidden_states = self.transform_act_fn(hidden_states)
684
+ hidden_states = self.LayerNorm(hidden_states)
685
+ return hidden_states
686
+
687
+
688
+ class LxmertLMPredictionHead(nn.Module):
689
+ def __init__(self, config, lxmert_model_embedding_weights):
690
+ super(LxmertLMPredictionHead, self).__init__()
691
+ self.transform = LxmertPredictionHeadTransform(config)
692
+
693
+ # The output weights are the same as the input embeddings, but there is
694
+ # an output-only bias for each token.
695
+ self.decoder = nn.Linear(
696
+ lxmert_model_embedding_weights.size(1),
697
+ lxmert_model_embedding_weights.size(0),
698
+ bias=False,
699
+ )
700
+ self.decoder.weight = lxmert_model_embedding_weights
701
+ self.bias = nn.Parameter(torch.zeros(lxmert_model_embedding_weights.size(0)))
702
+
703
+ def forward(self, hidden_states):
704
+ hidden_states = self.transform(hidden_states)
705
+ hidden_states = self.decoder(hidden_states) + self.bias
706
+ return hidden_states
707
+
708
+
709
+ class LxmertVisualAnswerHead(nn.Module):
710
+ def __init__(self, config, num_labels):
711
+ super().__init__()
712
+ hid_dim = config.hidden_size
713
+ self.logit_fc = nn.Sequential(
714
+ nn.Linear(hid_dim, hid_dim * 2),
715
+ GeLU(),
716
+ nn.LayerNorm(hid_dim * 2, eps=1e-12),
717
+ nn.Linear(hid_dim * 2, num_labels),
718
+ )
719
+
720
+ def forward(self, hidden_states):
721
+ return self.logit_fc(hidden_states)
722
+
723
+
724
+ class LxmertVisualObjHead(nn.Module):
725
+ def __init__(self, config):
726
+ super().__init__()
727
+ self.transform = LxmertPredictionHeadTransform(config)
728
+ # Decide the use of visual losses
729
+ visual_losses = {}
730
+ if config.visual_obj_loss:
731
+ visual_losses["obj"] = {"shape": (-1,), "num": config.num_object_labels}
732
+ if config.visual_attr_loss:
733
+ visual_losses["attr"] = {"shape": (-1,), "num": config.num_attr_labels}
734
+ if config.visual_feat_loss:
735
+ visual_losses["feat"] = {
736
+ "shape": (-1, config.visual_feat_dim),
737
+ "num": config.visual_feat_dim,
738
+ }
739
+ self.visual_losses = visual_losses
740
+
741
+ # The output weights are the same as the input embeddings, but there is
742
+ # an output-only bias for each token.
743
+ self.decoder_dict = nn.ModuleDict(
744
+ {key: nn.Linear(config.hidden_size, self.visual_losses[key]["num"]) for key in self.visual_losses}
745
+ )
746
+
747
+ def forward(self, hidden_states):
748
+ hidden_states = self.transform(hidden_states)
749
+ output = {}
750
+ for key in self.visual_losses:
751
+ output[key] = self.decoder_dict[key](hidden_states)
752
+ return output
753
+
754
+
755
+ class LxmertPreTrainingHeads(nn.Module):
756
+ def __init__(self, config, lxmert_model_embedding_weights):
757
+ super(LxmertPreTrainingHeads, self).__init__()
758
+ self.predictions = LxmertLMPredictionHead(config, lxmert_model_embedding_weights)
759
+ self.seq_relationship = nn.Linear(config.hidden_size, 2)
760
+
761
+ def forward(self, sequence_output, pooled_output):
762
+ prediction_scores = self.predictions(sequence_output)
763
+ seq_relationship_score = self.seq_relationship(pooled_output)
764
+ return prediction_scores, seq_relationship_score
765
+
766
+
767
+ class LxmertPreTrainedModel(PreTrainedModel):
768
+ """
769
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
770
+ models.
771
+ """
772
+
773
+ config_class = LxmertConfig
774
+ load_tf_weights = load_tf_weights_in_lxmert
775
+ base_model_prefix = "lxmert"
776
+ _supports_param_buffer_assignment = False
777
+
778
+ def _init_weights(self, module):
779
+ """Initialize the weights"""
780
+ if isinstance(module, nn.Linear):
781
+ # Slightly different from the TF version which uses truncated_normal for initialization
782
+ # cf https://github.com/pytorch/pytorch/pull/5617
783
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
784
+ if module.bias is not None:
785
+ module.bias.data.zero_()
786
+ elif isinstance(module, nn.Embedding):
787
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
788
+ if module.padding_idx is not None:
789
+ module.weight.data[module.padding_idx].zero_()
790
+ elif isinstance(module, nn.LayerNorm):
791
+ module.bias.data.zero_()
792
+ module.weight.data.fill_(1.0)
793
+
794
+
795
+ LXMERT_START_DOCSTRING = r"""
796
+
797
+ The LXMERT model was proposed in [LXMERT: Learning Cross-Modality Encoder Representations from
798
+ Transformers](https://arxiv.org/abs/1908.07490) by Hao Tan and Mohit Bansal. It's a vision and language transformer
799
+ model, pretrained on a variety of multi-modal datasets comprising of GQA, VQAv2.0, MSCOCO captions, and Visual
800
+ genome, using a combination of masked language modeling, region of interest feature regression, cross entropy loss
801
+ for question answering attribute prediction, and object tag prediction.
802
+
803
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
804
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
805
+ etc.)
806
+
807
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
808
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
809
+ and behavior.
810
+
811
+ Parameters:
812
+ config ([`LxmertConfig`]): Model configuration class with all the parameters of the model.
813
+ Initializing with a config file does not load the weights associated with the model, only the
814
+ configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
815
+ """
816
+
817
+ LXMERT_INPUTS_DOCSTRING = r"""
818
+
819
+ Args:
820
+ input_ids (`torch.LongTensor` of shape `({0})`):
821
+ Indices of input sequence tokens in the vocabulary.
822
+
823
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
824
+ [`PreTrainedTokenizer.__call__`] for details.
825
+
826
+ [What are input IDs?](../glossary#input-ids)
827
+ visual_feats (`torch.FloatTensor` of shape `(batch_size, num_visual_features, visual_feat_dim)`):
828
+ This input represents visual features. They ROI pooled object features from bounding boxes using a
829
+ faster-RCNN model)
830
+
831
+ These are currently not provided by the transformers library.
832
+ visual_pos (`torch.FloatTensor` of shape `(batch_size, num_visual_features, visual_pos_dim)`):
833
+ This input represents spacial features corresponding to their relative (via index) visual features. The
834
+ pre-trained LXMERT model expects these spacial features to be normalized bounding boxes on a scale of 0 to
835
+ 1.
836
+
837
+ These are currently not provided by the transformers library.
838
+ attention_mask (`torch.FloatTensor` of shape `({0})`, *optional*):
839
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
840
+
841
+ - 1 for tokens that are **not masked**,
842
+ - 0 for tokens that are **masked**.
843
+
844
+ [What are attention masks?](../glossary#attention-mask)
845
+ visual_attention_mask (`torch.FloatTensor` of shape `({0})`, *optional*):
846
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
847
+
848
+ - 1 for tokens that are **not masked**,
849
+ - 0 for tokens that are **masked**.
850
+
851
+ [What are attention masks?](../glossary#attention-mask)
852
+ token_type_ids (`torch.LongTensor` of shape `({0})`, *optional*):
853
+ Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
854
+ 1]`:
855
+
856
+ - 0 corresponds to a *sentence A* token,
857
+ - 1 corresponds to a *sentence B* token.
858
+
859
+ [What are token type IDs?](../glossary#token-type-ids)
860
+ inputs_embeds (`torch.FloatTensor` of shape `({0}, hidden_size)`, *optional*):
861
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
862
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
863
+ model's internal embedding lookup matrix.
864
+ output_attentions (`bool`, *optional*):
865
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
866
+ tensors for more detail.
867
+ output_hidden_states (`bool`, *optional*):
868
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
869
+ more detail.
870
+ return_dict (`bool`, *optional*):
871
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
872
+ """
873
+
874
+
875
+ @add_start_docstrings(
876
+ "The bare Lxmert Model transformer outputting raw hidden-states without any specific head on top.",
877
+ LXMERT_START_DOCSTRING,
878
+ )
879
+ class LxmertModel(LxmertPreTrainedModel):
880
+ def __init__(self, config):
881
+ super().__init__(config)
882
+ self.embeddings = LxmertEmbeddings(config)
883
+ self.encoder = LxmertEncoder(config)
884
+ self.pooler = LxmertPooler(config)
885
+ # Initialize weights and apply final processing
886
+ self.post_init()
887
+
888
+ def get_input_embeddings(self):
889
+ return self.embeddings.word_embeddings
890
+
891
+ def set_input_embeddings(self, new_embeddings):
892
+ self.embeddings.word_embeddings = new_embeddings
893
+
894
+ @add_start_docstrings_to_model_forward(LXMERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
895
+ @add_code_sample_docstrings(
896
+ checkpoint=_CHECKPOINT_FOR_DOC,
897
+ output_type=LxmertModelOutput,
898
+ config_class=_CONFIG_FOR_DOC,
899
+ )
900
+ def forward(
901
+ self,
902
+ input_ids: Optional[torch.LongTensor] = None,
903
+ visual_feats: Optional[torch.FloatTensor] = None,
904
+ visual_pos: Optional[torch.FloatTensor] = None,
905
+ attention_mask: Optional[torch.FloatTensor] = None,
906
+ visual_attention_mask: Optional[torch.FloatTensor] = None,
907
+ token_type_ids: Optional[torch.LongTensor] = None,
908
+ inputs_embeds: Optional[torch.FloatTensor] = None,
909
+ output_attentions: Optional[bool] = None,
910
+ output_hidden_states: Optional[bool] = None,
911
+ return_dict: Optional[bool] = None,
912
+ ) -> Union[LxmertModelOutput, Tuple[torch.FloatTensor]]:
913
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
914
+ output_hidden_states = (
915
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
916
+ )
917
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
918
+
919
+ if input_ids is not None and inputs_embeds is not None:
920
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
921
+ elif input_ids is not None:
922
+ self.warn_if_padding_and_no_attention_mask(input_ids, attention_mask)
923
+ input_shape = input_ids.size()
924
+ elif inputs_embeds is not None:
925
+ input_shape = inputs_embeds.size()[:-1]
926
+ else:
927
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
928
+
929
+ if visual_feats is None:
930
+ raise ValueError("`visual_feats` cannot be `None`")
931
+ if visual_pos is None:
932
+ raise ValueError("`visual_pos` cannot be `None`")
933
+
934
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
935
+
936
+ if attention_mask is None:
937
+ attention_mask = torch.ones(input_shape, device=device)
938
+ if token_type_ids is None:
939
+ token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=device)
940
+
941
+ # We create a 3D attention mask from a 2D tensor mask.
942
+ # Sizes are [batch_size, 1, 1, to_seq_length]
943
+ # So we can broadcast to [batch_size, num_heads, from_seq_length, to_seq_length]
944
+ # this attention mask is more simple than the triangular masking of causal attention
945
+ # used in OpenAI GPT, we just need to prepare the broadcast dimension here.
946
+ extended_attention_mask = attention_mask.unsqueeze(1).unsqueeze(2)
947
+
948
+ # Since attention_mask is 1.0 for positions we want to attend and 0.0 for
949
+ # masked positions, this operation will create a tensor which is 0.0 for
950
+ # positions we want to attend and the dtype's smallest value for masked positions.
951
+ # Since we are adding it to the raw scores before the softmax, this is
952
+ # effectively the same as removing these entirely.
953
+ extended_attention_mask = extended_attention_mask.to(dtype=self.dtype)
954
+ extended_attention_mask = (1.0 - extended_attention_mask) * torch.finfo(self.dtype).min
955
+
956
+ # Process the visual attention mask
957
+ if visual_attention_mask is not None:
958
+ extended_visual_attention_mask = visual_attention_mask.unsqueeze(1).unsqueeze(2)
959
+ extended_visual_attention_mask = extended_visual_attention_mask.to(dtype=self.dtype)
960
+ extended_visual_attention_mask = (1.0 - extended_visual_attention_mask) * torch.finfo(self.dtype).min
961
+ else:
962
+ extended_visual_attention_mask = None
963
+
964
+ # Positional Word Embeddings
965
+ embedding_output = self.embeddings(input_ids, token_type_ids, inputs_embeds)
966
+
967
+ # Run Lxmert encoder
968
+ encoder_outputs = self.encoder(
969
+ embedding_output,
970
+ extended_attention_mask,
971
+ visual_feats=visual_feats,
972
+ visual_pos=visual_pos,
973
+ visual_attention_mask=extended_visual_attention_mask,
974
+ output_attentions=output_attentions,
975
+ )
976
+
977
+ visual_encoder_outputs, lang_encoder_outputs = encoder_outputs[:2]
978
+ vision_hidden_states = visual_encoder_outputs[0]
979
+ language_hidden_states = lang_encoder_outputs[0]
980
+
981
+ all_attentions = ()
982
+ if output_attentions:
983
+ language_attentions = lang_encoder_outputs[1]
984
+ vision_attentions = visual_encoder_outputs[1]
985
+ cross_encoder_attentions = encoder_outputs[2]
986
+ all_attentions = (
987
+ language_attentions,
988
+ vision_attentions,
989
+ cross_encoder_attentions,
990
+ )
991
+
992
+ hidden_states = (language_hidden_states, vision_hidden_states) if output_hidden_states else ()
993
+
994
+ visual_output = vision_hidden_states[-1]
995
+ lang_output = language_hidden_states[-1]
996
+ pooled_output = self.pooler(lang_output)
997
+
998
+ if not return_dict:
999
+ return (lang_output, visual_output, pooled_output) + hidden_states + all_attentions
1000
+
1001
+ return LxmertModelOutput(
1002
+ pooled_output=pooled_output,
1003
+ language_output=lang_output,
1004
+ vision_output=visual_output,
1005
+ language_hidden_states=language_hidden_states if output_hidden_states else None,
1006
+ vision_hidden_states=vision_hidden_states if output_hidden_states else None,
1007
+ language_attentions=language_attentions if output_attentions else None,
1008
+ vision_attentions=vision_attentions if output_attentions else None,
1009
+ cross_encoder_attentions=cross_encoder_attentions if output_attentions else None,
1010
+ )
1011
+
1012
+
1013
+ @add_start_docstrings(
1014
+ """Lxmert Model with a specified pretraining head on top.""",
1015
+ LXMERT_START_DOCSTRING,
1016
+ )
1017
+ class LxmertForPreTraining(LxmertPreTrainedModel):
1018
+ _tied_weights_keys = ["cls.predictions.decoder.weight"]
1019
+
1020
+ def __init__(self, config):
1021
+ super().__init__(config)
1022
+ # Configuration
1023
+ self.config = config
1024
+ self.num_qa_labels = config.num_qa_labels
1025
+ self.visual_loss_normalizer = config.visual_loss_normalizer
1026
+
1027
+ # Use of pretraining tasks
1028
+ self.task_mask_lm = config.task_mask_lm
1029
+ self.task_obj_predict = config.task_obj_predict
1030
+ self.task_matched = config.task_matched
1031
+ self.task_qa = config.task_qa
1032
+
1033
+ # Lxmert backbone
1034
+ self.lxmert = LxmertModel(config)
1035
+
1036
+ # Pre-training heads
1037
+ self.cls = LxmertPreTrainingHeads(config, self.lxmert.embeddings.word_embeddings.weight)
1038
+ if self.task_obj_predict:
1039
+ self.obj_predict_head = LxmertVisualObjHead(config)
1040
+ if self.task_qa:
1041
+ self.answer_head = LxmertVisualAnswerHead(config, self.num_qa_labels)
1042
+
1043
+ # Weight initialization
1044
+ # Initialize weights and apply final processing
1045
+ self.post_init()
1046
+
1047
+ # Loss functions
1048
+ self.loss_fcts = {
1049
+ "l2": SmoothL1Loss(reduction="none"),
1050
+ "visual_ce": CrossEntropyLoss(reduction="none"),
1051
+ "ce": CrossEntropyLoss(),
1052
+ }
1053
+
1054
+ visual_losses = {}
1055
+ if config.visual_obj_loss:
1056
+ visual_losses["obj"] = {
1057
+ "shape": (-1,),
1058
+ "num": config.num_object_labels,
1059
+ "loss": "visual_ce",
1060
+ }
1061
+ if config.visual_attr_loss:
1062
+ visual_losses["attr"] = {
1063
+ "shape": (-1,),
1064
+ "num": config.num_attr_labels,
1065
+ "loss": "visual_ce",
1066
+ }
1067
+ if config.visual_feat_loss:
1068
+ visual_losses["feat"] = {
1069
+ "shape": (-1, config.visual_feat_dim),
1070
+ "num": config.visual_feat_dim,
1071
+ "loss": "l2",
1072
+ }
1073
+ self.visual_losses = visual_losses
1074
+
1075
+ def resize_token_embeddings(
1076
+ self, new_num_tokens: int, pad_to_multiple_of: Optional[int] = None, mean_resizing: bool = True
1077
+ ) -> nn.Embedding:
1078
+ # Adding the following steps to resize bias to match the shape of resized embeddings
1079
+ new_embeddings = super().resize_token_embeddings(new_num_tokens, pad_to_multiple_of, mean_resizing)
1080
+ self.cls.predictions.bias = self._resize_bias(self.cls.predictions.bias, new_num_tokens)
1081
+ return new_embeddings
1082
+
1083
+ def _resize_bias(self, bias, new_num_tokens: int):
1084
+ old_num_tokens = bias.shape[0]
1085
+ if new_num_tokens <= old_num_tokens:
1086
+ new_bias = bias[:new_num_tokens]
1087
+ else:
1088
+ extra_bias = torch.zeros(new_num_tokens - old_num_tokens, device=bias.device)
1089
+ new_bias = torch.cat([bias, extra_bias])
1090
+ new_bias = nn.Parameter(new_bias)
1091
+ return new_bias
1092
+
1093
+ def resize_num_qa_labels(self, num_labels):
1094
+ """
1095
+ Build a resized question answering linear layer Module from a provided new linear layer. Increasing the size
1096
+ will add newly initialized weights. Reducing the size will remove weights from the end
1097
+
1098
+ Args:
1099
+ num_labels (`int`, *optional*):
1100
+ New number of labels in the linear layer weight matrix. Increasing the size will add newly initialized
1101
+ weights at the end. Reducing the size will remove weights from the end. If not provided or `None`, just
1102
+ returns a pointer to the qa labels ``torch.nn.Linear``` module of the model without doing anything.
1103
+
1104
+ Return:
1105
+ `torch.nn.Linear`: Pointer to the resized Linear layer or the old Linear layer
1106
+ """
1107
+
1108
+ cur_qa_logit_layer = self.get_qa_logit_layer()
1109
+ if num_labels is None or cur_qa_logit_layer is None:
1110
+ return
1111
+ new_qa_logit_layer = self._resize_qa_labels(num_labels)
1112
+ self.config.num_qa_labels = num_labels
1113
+ self.num_qa_labels = num_labels
1114
+
1115
+ return new_qa_logit_layer
1116
+
1117
+ def _resize_qa_labels(self, num_labels):
1118
+ cur_qa_logit_layer = self.get_qa_logit_layer()
1119
+ new_qa_logit_layer = self._get_resized_qa_labels(cur_qa_logit_layer, num_labels)
1120
+ self._set_qa_logit_layer(new_qa_logit_layer)
1121
+ return self.get_qa_logit_layer()
1122
+
1123
+ def get_qa_logit_layer(self) -> nn.Module:
1124
+ """
1125
+ Returns the linear layer that produces question answering logits.
1126
+
1127
+ Returns:
1128
+ `nn.Module`: A torch module mapping the question answering prediction hidden states or `None` if LXMERT
1129
+ does not have a visual answering head.
1130
+ """
1131
+ if hasattr(self, "answer_head"):
1132
+ return self.answer_head.logit_fc[-1]
1133
+
1134
+ def _set_qa_logit_layer(self, qa_logit_layer):
1135
+ self.answer_head.logit_fc[-1] = qa_logit_layer
1136
+
1137
+ def _get_resized_qa_labels(self, cur_qa_logit_layer, num_labels):
1138
+ if num_labels is None:
1139
+ return cur_qa_logit_layer
1140
+
1141
+ cur_qa_labels, hidden_dim = cur_qa_logit_layer.weight.size()
1142
+ if cur_qa_labels == num_labels:
1143
+ return cur_qa_logit_layer
1144
+
1145
+ # Build new linear output
1146
+ if getattr(cur_qa_logit_layer, "bias", None) is not None:
1147
+ new_qa_logit_layer = nn.Linear(hidden_dim, num_labels)
1148
+ else:
1149
+ new_qa_logit_layer = nn.Linear(hidden_dim, num_labels, bias=False)
1150
+
1151
+ new_qa_logit_layer.to(cur_qa_logit_layer.weight.device)
1152
+
1153
+ # initialize all new labels
1154
+ self._init_weights(new_qa_logit_layer)
1155
+
1156
+ # Copy labels from the previous weights
1157
+ num_labels_to_copy = min(cur_qa_labels, num_labels)
1158
+ new_qa_logit_layer.weight.data[:num_labels_to_copy, :] = cur_qa_logit_layer.weight.data[:num_labels_to_copy, :]
1159
+ if getattr(cur_qa_logit_layer, "bias", None) is not None:
1160
+ new_qa_logit_layer.bias.data[:num_labels_to_copy] = cur_qa_logit_layer.bias.data[:num_labels_to_copy]
1161
+
1162
+ return new_qa_logit_layer
1163
+
1164
+ @add_start_docstrings_to_model_forward(LXMERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
1165
+ @replace_return_docstrings(output_type=LxmertForPreTrainingOutput, config_class=_CONFIG_FOR_DOC)
1166
+ def forward(
1167
+ self,
1168
+ input_ids: Optional[torch.LongTensor] = None,
1169
+ visual_feats: Optional[torch.FloatTensor] = None,
1170
+ visual_pos: Optional[torch.FloatTensor] = None,
1171
+ attention_mask: Optional[torch.FloatTensor] = None,
1172
+ visual_attention_mask: Optional[torch.FloatTensor] = None,
1173
+ token_type_ids: Optional[torch.LongTensor] = None,
1174
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1175
+ labels: Optional[torch.LongTensor] = None,
1176
+ obj_labels: Optional[Dict[str, Tuple[torch.FloatTensor, torch.FloatTensor]]] = None,
1177
+ matched_label: Optional[torch.LongTensor] = None,
1178
+ ans: Optional[torch.Tensor] = None,
1179
+ output_attentions: Optional[bool] = None,
1180
+ output_hidden_states: Optional[bool] = None,
1181
+ return_dict: Optional[bool] = None,
1182
+ **kwargs,
1183
+ ) -> Union[LxmertForPreTrainingOutput, Tuple[torch.FloatTensor]]:
1184
+ r"""
1185
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1186
+ Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
1187
+ config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the
1188
+ loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
1189
+ obj_labels (`Dict[Str: Tuple[Torch.FloatTensor, Torch.FloatTensor]]`, *optional*):
1190
+ each key is named after each one of the visual losses and each element of the tuple is of the shape
1191
+ `(batch_size, num_features)` and `(batch_size, num_features, visual_feature_dim)` for each the label id and
1192
+ the label score respectively
1193
+ matched_label (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1194
+ Labels for computing the whether or not the text input matches the image (classification) loss. Input
1195
+ should be a sequence pair (see `input_ids` docstring) Indices should be in `[0, 1]`:
1196
+
1197
+ - 0 indicates that the sentence does not match the image,
1198
+ - 1 indicates that the sentence does match the image.
1199
+ ans (`Torch.Tensor` of shape `(batch_size)`, *optional*):
1200
+ a one hot representation hof the correct answer *optional*
1201
+
1202
+ Returns:
1203
+ """
1204
+
1205
+ if "masked_lm_labels" in kwargs:
1206
+ warnings.warn(
1207
+ "The `masked_lm_labels` argument is deprecated and will be removed in a future version, use `labels`"
1208
+ " instead.",
1209
+ FutureWarning,
1210
+ )
1211
+ labels = kwargs.pop("masked_lm_labels")
1212
+
1213
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1214
+
1215
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
1216
+ lxmert_output = self.lxmert(
1217
+ input_ids=input_ids,
1218
+ visual_feats=visual_feats,
1219
+ visual_pos=visual_pos,
1220
+ token_type_ids=token_type_ids,
1221
+ attention_mask=attention_mask,
1222
+ visual_attention_mask=visual_attention_mask,
1223
+ inputs_embeds=inputs_embeds,
1224
+ output_hidden_states=output_hidden_states,
1225
+ output_attentions=output_attentions,
1226
+ return_dict=return_dict,
1227
+ )
1228
+
1229
+ lang_output, visual_output, pooled_output = (
1230
+ lxmert_output[0],
1231
+ lxmert_output[1],
1232
+ lxmert_output[2],
1233
+ )
1234
+ lang_prediction_scores, cross_relationship_score = self.cls(lang_output, pooled_output)
1235
+ if self.task_qa:
1236
+ answer_score = self.answer_head(pooled_output)
1237
+ else:
1238
+ answer_score = pooled_output[0][0]
1239
+
1240
+ total_loss = (
1241
+ None
1242
+ if (labels is None and matched_label is None and obj_labels is None and ans is None)
1243
+ else torch.tensor(0.0, device=device)
1244
+ )
1245
+ if labels is not None and self.task_mask_lm:
1246
+ masked_lm_loss = self.loss_fcts["ce"](
1247
+ lang_prediction_scores.view(-1, self.config.vocab_size),
1248
+ labels.view(-1),
1249
+ )
1250
+ total_loss += masked_lm_loss
1251
+ if matched_label is not None and self.task_matched:
1252
+ matched_loss = self.loss_fcts["ce"](cross_relationship_score.view(-1, 2), matched_label.view(-1))
1253
+ total_loss += matched_loss
1254
+ if obj_labels is not None and self.task_obj_predict:
1255
+ total_visual_loss = torch.tensor(0.0, device=input_ids.device)
1256
+ visual_prediction_scores_dict = self.obj_predict_head(visual_output)
1257
+ for key, key_info in self.visual_losses.items():
1258
+ label, mask_conf = obj_labels[key]
1259
+ output_dim = key_info["num"]
1260
+ loss_fct_name = key_info["loss"]
1261
+ label_shape = key_info["shape"]
1262
+ weight = self.visual_loss_normalizer
1263
+ visual_loss_fct = self.loss_fcts[loss_fct_name]
1264
+ visual_prediction_scores = visual_prediction_scores_dict[key]
1265
+ visual_loss = visual_loss_fct(
1266
+ visual_prediction_scores.view(-1, output_dim),
1267
+ label.view(label_shape),
1268
+ )
1269
+ if visual_loss.dim() > 1: # Regression Losses
1270
+ visual_loss = visual_loss.mean(1)
1271
+ visual_loss = (visual_loss * mask_conf.view(-1)).mean() * weight
1272
+ total_visual_loss += visual_loss
1273
+ total_loss += total_visual_loss
1274
+ if ans is not None and self.task_qa:
1275
+ answer_loss = self.loss_fcts["ce"](answer_score.view(-1, self.num_qa_labels), ans.view(-1))
1276
+ total_loss += answer_loss
1277
+
1278
+ if not return_dict:
1279
+ output = (
1280
+ lang_prediction_scores,
1281
+ cross_relationship_score,
1282
+ answer_score,
1283
+ ) + lxmert_output[3:]
1284
+ return ((total_loss,) + output) if total_loss is not None else output
1285
+
1286
+ return LxmertForPreTrainingOutput(
1287
+ loss=total_loss,
1288
+ prediction_logits=lang_prediction_scores,
1289
+ cross_relationship_score=cross_relationship_score,
1290
+ question_answering_score=answer_score,
1291
+ language_hidden_states=lxmert_output.language_hidden_states,
1292
+ vision_hidden_states=lxmert_output.vision_hidden_states,
1293
+ language_attentions=lxmert_output.language_attentions,
1294
+ vision_attentions=lxmert_output.vision_attentions,
1295
+ cross_encoder_attentions=lxmert_output.cross_encoder_attentions,
1296
+ )
1297
+
1298
+
1299
+ @add_start_docstrings(
1300
+ """Lxmert Model with a visual-answering head on top for downstream QA tasks""",
1301
+ LXMERT_START_DOCSTRING,
1302
+ )
1303
+ class LxmertForQuestionAnswering(LxmertPreTrainedModel):
1304
+ def __init__(self, config):
1305
+ super().__init__(config)
1306
+ # Configuration
1307
+ self.config = config
1308
+ self.num_qa_labels = config.num_qa_labels
1309
+ self.visual_loss_normalizer = config.visual_loss_normalizer
1310
+
1311
+ # Lxmert backbone
1312
+ self.lxmert = LxmertModel(config)
1313
+
1314
+ self.answer_head = LxmertVisualAnswerHead(config, self.num_qa_labels)
1315
+
1316
+ # Weight initialization
1317
+ # Initialize weights and apply final processing
1318
+ self.post_init()
1319
+
1320
+ # Loss function
1321
+ self.loss = CrossEntropyLoss()
1322
+
1323
+ def resize_num_qa_labels(self, num_labels):
1324
+ """
1325
+ Build a resized question answering linear layer Module from a provided new linear layer. Increasing the size
1326
+ will add newly initialized weights. Reducing the size will remove weights from the end
1327
+
1328
+ Args:
1329
+ num_labels (`int`, *optional*):
1330
+ New number of labels in the linear layer weight matrix. Increasing the size will add newly initialized
1331
+ weights at the end. Reducing the size will remove weights from the end. If not provided or `None`, just
1332
+ returns a pointer to the qa labels ``torch.nn.Linear``` module of the model without doing anything.
1333
+
1334
+ Return:
1335
+ `torch.nn.Linear`: Pointer to the resized Linear layer or the old Linear layer
1336
+ """
1337
+
1338
+ cur_qa_logit_layer = self.get_qa_logit_layer()
1339
+ if num_labels is None or cur_qa_logit_layer is None:
1340
+ return
1341
+ new_qa_logit_layer = self._resize_qa_labels(num_labels)
1342
+ self.config.num_qa_labels = num_labels
1343
+ self.num_qa_labels = num_labels
1344
+
1345
+ return new_qa_logit_layer
1346
+
1347
+ def _resize_qa_labels(self, num_labels):
1348
+ cur_qa_logit_layer = self.get_qa_logit_layer()
1349
+ new_qa_logit_layer = self._get_resized_qa_labels(cur_qa_logit_layer, num_labels)
1350
+ self._set_qa_logit_layer(new_qa_logit_layer)
1351
+ return self.get_qa_logit_layer()
1352
+
1353
+ def get_qa_logit_layer(self) -> nn.Module:
1354
+ """
1355
+ Returns the linear layer that produces question answering logits
1356
+
1357
+ Returns:
1358
+ `nn.Module`: A torch module mapping the question answering prediction hidden states. `None`: A NoneType
1359
+ object if Lxmert does not have the visual answering head.
1360
+ """
1361
+
1362
+ if hasattr(self, "answer_head"):
1363
+ return self.answer_head.logit_fc[-1]
1364
+
1365
+ def _set_qa_logit_layer(self, qa_logit_layer):
1366
+ self.answer_head.logit_fc[-1] = qa_logit_layer
1367
+
1368
+ def _get_resized_qa_labels(self, cur_qa_logit_layer, num_labels):
1369
+ if num_labels is None:
1370
+ return cur_qa_logit_layer
1371
+
1372
+ cur_qa_labels, hidden_dim = cur_qa_logit_layer.weight.size()
1373
+ if cur_qa_labels == num_labels:
1374
+ return cur_qa_logit_layer
1375
+
1376
+ # Build new linear output
1377
+ if getattr(cur_qa_logit_layer, "bias", None) is not None:
1378
+ new_qa_logit_layer = nn.Linear(hidden_dim, num_labels)
1379
+ else:
1380
+ new_qa_logit_layer = nn.Linear(hidden_dim, num_labels, bias=False)
1381
+
1382
+ new_qa_logit_layer.to(cur_qa_logit_layer.weight.device)
1383
+
1384
+ # initialize all new labels
1385
+ self._init_weights(new_qa_logit_layer)
1386
+
1387
+ # Copy labels from the previous weights
1388
+ num_labels_to_copy = min(cur_qa_labels, num_labels)
1389
+ new_qa_logit_layer.weight.data[:num_labels_to_copy, :] = cur_qa_logit_layer.weight.data[:num_labels_to_copy, :]
1390
+ if getattr(cur_qa_logit_layer, "bias", None) is not None:
1391
+ new_qa_logit_layer.bias.data[:num_labels_to_copy] = cur_qa_logit_layer.bias.data[:num_labels_to_copy]
1392
+
1393
+ return new_qa_logit_layer
1394
+
1395
+ @add_start_docstrings_to_model_forward(LXMERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
1396
+ @add_code_sample_docstrings(
1397
+ checkpoint=_CHECKPOINT_FOR_DOC,
1398
+ output_type=LxmertForQuestionAnsweringOutput,
1399
+ config_class=_CONFIG_FOR_DOC,
1400
+ )
1401
+ def forward(
1402
+ self,
1403
+ input_ids: Optional[torch.LongTensor] = None,
1404
+ visual_feats: Optional[torch.FloatTensor] = None,
1405
+ visual_pos: Optional[torch.FloatTensor] = None,
1406
+ attention_mask: Optional[torch.FloatTensor] = None,
1407
+ visual_attention_mask: Optional[torch.FloatTensor] = None,
1408
+ token_type_ids: Optional[torch.LongTensor] = None,
1409
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1410
+ labels: Optional[torch.Tensor] = None,
1411
+ output_attentions: Optional[bool] = None,
1412
+ output_hidden_states: Optional[bool] = None,
1413
+ return_dict: Optional[bool] = None,
1414
+ ) -> Union[LxmertForQuestionAnsweringOutput, Tuple[torch.FloatTensor]]:
1415
+ r"""
1416
+ labels (`Torch.Tensor` of shape `(batch_size)`, *optional*):
1417
+ A one-hot representation of the correct answer
1418
+ """
1419
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1420
+
1421
+ lxmert_output = self.lxmert(
1422
+ input_ids=input_ids,
1423
+ visual_feats=visual_feats,
1424
+ visual_pos=visual_pos,
1425
+ token_type_ids=token_type_ids,
1426
+ attention_mask=attention_mask,
1427
+ visual_attention_mask=visual_attention_mask,
1428
+ inputs_embeds=inputs_embeds,
1429
+ output_hidden_states=output_hidden_states,
1430
+ output_attentions=output_attentions,
1431
+ return_dict=return_dict,
1432
+ )
1433
+
1434
+ pooled_output = lxmert_output[2]
1435
+ answer_score = self.answer_head(pooled_output)
1436
+ loss = None
1437
+ if labels is not None:
1438
+ loss = self.loss(answer_score.view(-1, self.num_qa_labels), labels.view(-1))
1439
+
1440
+ if not return_dict:
1441
+ output = (answer_score,) + lxmert_output[3:]
1442
+ return (loss,) + output if loss is not None else output
1443
+
1444
+ return LxmertForQuestionAnsweringOutput(
1445
+ loss=loss,
1446
+ question_answering_score=answer_score,
1447
+ language_hidden_states=lxmert_output.language_hidden_states,
1448
+ vision_hidden_states=lxmert_output.vision_hidden_states,
1449
+ language_attentions=lxmert_output.language_attentions,
1450
+ vision_attentions=lxmert_output.vision_attentions,
1451
+ cross_encoder_attentions=lxmert_output.cross_encoder_attentions,
1452
+ )
1453
+
1454
+
1455
+ __all__ = [
1456
+ "LxmertEncoder",
1457
+ "LxmertForPreTraining",
1458
+ "LxmertForQuestionAnswering",
1459
+ "LxmertModel",
1460
+ "LxmertPreTrainedModel",
1461
+ "LxmertVisualFeatureEncoder",
1462
+ "LxmertXLayer",
1463
+ ]
tasks/tasksmith-441eeab80047/environment/source/src/transformers/models/lxmert/modeling_tf_lxmert.py ADDED
@@ -0,0 +1,1661 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2018 The Google AI Language Team Authors, The HuggingFace Inc. team, and the
3
+ # Lxmert Authors.
4
+ # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
5
+ #
6
+ # Licensed under the Apache License, Version 2.0 (the "License");
7
+ # you may not use this file except in compliance with the License.
8
+ # You may obtain a copy of the License at
9
+ #
10
+ # http://www.apache.org/licenses/LICENSE-2.0
11
+ #
12
+ # Unless required by applicable law or agreed to in writing, software
13
+ # distributed under the License is distributed on an "AS IS" BASIS,
14
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ # See the License for the specific language governing permissions and
16
+ # limitations under the License.
17
+ """TF 2.0 LXMERT model."""
18
+
19
+ from __future__ import annotations
20
+
21
+ import warnings
22
+ from dataclasses import dataclass
23
+ from typing import Dict, 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_utils import (
30
+ TFModelInputType,
31
+ TFPreTrainedModel,
32
+ get_initializer,
33
+ keras,
34
+ keras_serializable,
35
+ shape_list,
36
+ unpack_inputs,
37
+ )
38
+ from ...tf_utils import check_embeddings_within_bounds, stable_softmax
39
+ from ...utils import (
40
+ ModelOutput,
41
+ add_code_sample_docstrings,
42
+ add_start_docstrings,
43
+ add_start_docstrings_to_model_forward,
44
+ logging,
45
+ replace_return_docstrings,
46
+ )
47
+ from .configuration_lxmert import LxmertConfig
48
+
49
+
50
+ logger = logging.get_logger(__name__)
51
+
52
+ _CHECKPOINT_FOR_DOC = "unc-nlp/lxmert-base-uncased"
53
+ _CONFIG_FOR_DOC = "LxmertConfig"
54
+
55
+
56
+ @dataclass
57
+ class TFLxmertModelOutput(ModelOutput):
58
+ """
59
+ Lxmert's outputs that contain the last hidden states, pooled outputs, and attention probabilities for the language,
60
+ visual, and, cross-modality encoders. (note: the visual encoder in Lxmert is referred to as the "relation-ship"
61
+ encoder")
62
+
63
+
64
+ Args:
65
+ language_output (`tf.Tensor` of shape `(batch_size, sequence_length, hidden_size)`):
66
+ Sequence of hidden-states at the output of the last layer of the language encoder.
67
+ vision_output (`tf.Tensor` of shape `(batch_size, sequence_length, hidden_size)`):
68
+ Sequence of hidden-states at the output of the last layer of the visual encoder.
69
+ pooled_output (`tf.Tensor` of shape `(batch_size, hidden_size)`):
70
+ Last layer hidden-state of the first token of the sequence (classification, CLS, token) further processed
71
+ by a Linear layer and a Tanh activation function. The Linear
72
+ language_hidden_states (`tuple(tf.Tensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
73
+ Tuple of `tf.Tensor` (one for input features + one for the output of each cross-modality layer) of shape
74
+ `(batch_size, sequence_length, hidden_size)`.
75
+ vision_hidden_states (`tuple(tf.Tensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
76
+ Tuple of `tf.Tensor` (one for input features + one for the output of each cross-modality layer) of shape
77
+ `(batch_size, sequence_length, hidden_size)`.
78
+ language_attentions (`tuple(tf.Tensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
79
+ Tuple of `tf.Tensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
80
+ sequence_length)`. Attentions weights after the attention softmax, used to compute the weighted average in
81
+ the self-attention heads.
82
+ vision_attentions (`tuple(tf.Tensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
83
+ Tuple of `tf.Tensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
84
+ sequence_length)`. Attentions weights after the attention softmax, used to compute the weighted average in
85
+ the self-attention heads.
86
+ cross_encoder_attentions (`tuple(tf.Tensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
87
+ Tuple of `tf.Tensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
88
+ sequence_length)`. Attentions weights after the attention softmax, used to compute the weighted average in
89
+ the self-attention heads.
90
+ """
91
+
92
+ language_output: tf.Tensor | None = None
93
+ vision_output: tf.Tensor | None = None
94
+ pooled_output: tf.Tensor | None = None
95
+ language_hidden_states: Tuple[tf.Tensor] | None = None
96
+ vision_hidden_states: Tuple[tf.Tensor] | None = None
97
+ language_attentions: Tuple[tf.Tensor] | None = None
98
+ vision_attentions: Tuple[tf.Tensor] | None = None
99
+ cross_encoder_attentions: Tuple[tf.Tensor] | None = None
100
+
101
+
102
+ @dataclass
103
+ class TFLxmertForPreTrainingOutput(ModelOutput):
104
+ """
105
+ Output type of [`LxmertForPreTraining`].
106
+
107
+ Args:
108
+ loss (*optional*, returned when `labels` is provided, `tf.Tensor` of shape `(1,)`):
109
+ Total loss as the sum of the masked language modeling loss and the next sequence prediction
110
+ (classification) loss.
111
+ prediction_logits (`tf.Tensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
112
+ Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
113
+ cross_relationship_score (`tf.Tensor` of shape `(batch_size, 2)`):
114
+ Prediction scores of the textual matching objective (classification) head (scores of True/False
115
+ continuation before SoftMax).
116
+ question_answering_score (`tf.Tensor` of shape `(batch_size, n_qa_answers)`):
117
+ Prediction scores of question answering objective (classification).
118
+ language_hidden_states (`tuple(tf.Tensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
119
+ Tuple of `tf.Tensor` (one for input features + one for the output of each cross-modality layer) of shape
120
+ `(batch_size, sequence_length, hidden_size)`.
121
+ vision_hidden_states (`tuple(tf.Tensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
122
+ Tuple of `tf.Tensor` (one for input features + one for the output of each cross-modality layer) of shape
123
+ `(batch_size, sequence_length, hidden_size)`.
124
+ language_attentions (`tuple(tf.Tensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
125
+ Tuple of `tf.Tensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
126
+ sequence_length)`. Attentions weights after the attention softmax, used to compute the weighted average in
127
+ the self-attention heads.
128
+ vision_attentions (`tuple(tf.Tensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
129
+ Tuple of `tf.Tensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
130
+ sequence_length)`. Attentions weights after the attention softmax, used to compute the weighted average in
131
+ the self-attention heads.
132
+ cross_encoder_attentions (`tuple(tf.Tensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
133
+ Tuple of `tf.Tensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
134
+ sequence_length)`. Attentions weights after the attention softmax, used to compute the weighted average in
135
+ the self-attention heads.
136
+
137
+ """
138
+
139
+ loss: tf.Tensor | None = None
140
+ prediction_logits: tf.Tensor | None = None
141
+ cross_relationship_score: tf.Tensor | None = None
142
+ question_answering_score: tf.Tensor | None = None
143
+ language_hidden_states: Tuple[tf.Tensor] | None = None
144
+ vision_hidden_states: Tuple[tf.Tensor] | None = None
145
+ language_attentions: Tuple[tf.Tensor] | None = None
146
+ vision_attentions: Tuple[tf.Tensor] | None = None
147
+ cross_encoder_attentions: Tuple[tf.Tensor] | None = None
148
+
149
+
150
+ class TFLxmertVisualFeatureEncoder(keras.layers.Layer):
151
+ def __init__(self, config, **kwargs):
152
+ super().__init__(**kwargs)
153
+
154
+ # Object feature encoding
155
+ self.visn_fc = keras.layers.Dense(
156
+ config.hidden_size,
157
+ kernel_initializer=get_initializer(config.initializer_range),
158
+ name="visn_fc",
159
+ )
160
+ self.visn_layer_norm = keras.layers.LayerNormalization(epsilon=config.layer_norm_eps, name="visn_layer_norm")
161
+
162
+ # Box position encoding
163
+ self.box_fc = keras.layers.Dense(
164
+ config.hidden_size,
165
+ kernel_initializer=get_initializer(config.initializer_range),
166
+ name="box_fc",
167
+ )
168
+ self.box_layer_norm = keras.layers.LayerNormalization(epsilon=config.layer_norm_eps, name="box_layer_norm")
169
+
170
+ self.dropout = keras.layers.Dropout(config.hidden_dropout_prob)
171
+ self.feat_dim = config.visual_feat_dim
172
+ self.pos_dim = config.visual_pos_dim
173
+ self.config = config
174
+
175
+ def call(self, visn_input, training=False):
176
+ feats, boxes = visn_input
177
+
178
+ x = self.visn_fc(feats)
179
+ x = self.visn_layer_norm(x)
180
+ y = self.box_fc(boxes)
181
+ y = self.box_layer_norm(y)
182
+ output = (x + y) / 2
183
+
184
+ output = self.dropout(output, training=training)
185
+ return output
186
+
187
+ def build(self, input_shape=None):
188
+ if self.built:
189
+ return
190
+ self.built = True
191
+ if getattr(self, "visn_fc", None) is not None:
192
+ with tf.name_scope(self.visn_fc.name):
193
+ self.visn_fc.build([None, None, self.feat_dim])
194
+ if getattr(self, "visn_layer_norm", None) is not None:
195
+ with tf.name_scope(self.visn_layer_norm.name):
196
+ self.visn_layer_norm.build([None, None, self.config.hidden_size])
197
+ if getattr(self, "box_fc", None) is not None:
198
+ with tf.name_scope(self.box_fc.name):
199
+ self.box_fc.build([None, None, self.pos_dim])
200
+ if getattr(self, "box_layer_norm", None) is not None:
201
+ with tf.name_scope(self.box_layer_norm.name):
202
+ self.box_layer_norm.build([None, None, self.config.hidden_size])
203
+
204
+
205
+ class TFLxmertEmbeddings(keras.layers.Layer):
206
+ """Construct the embeddings from word, position and token_type embeddings."""
207
+
208
+ def __init__(self, config, **kwargs):
209
+ super().__init__(**kwargs)
210
+
211
+ self.config = config
212
+ self.hidden_size = config.hidden_size
213
+ self.max_position_embeddings = config.max_position_embeddings
214
+ self.initializer_range = config.initializer_range
215
+ self.LayerNorm = keras.layers.LayerNormalization(epsilon=config.layer_norm_eps, name="LayerNorm")
216
+ self.dropout = keras.layers.Dropout(rate=config.hidden_dropout_prob)
217
+
218
+ def build(self, input_shape=None):
219
+ with tf.name_scope("word_embeddings"):
220
+ self.weight = self.add_weight(
221
+ name="weight",
222
+ shape=[self.config.vocab_size, self.hidden_size],
223
+ initializer=get_initializer(initializer_range=self.initializer_range),
224
+ )
225
+
226
+ with tf.name_scope("token_type_embeddings"):
227
+ self.token_type_embeddings = self.add_weight(
228
+ name="embeddings",
229
+ shape=[self.config.type_vocab_size, self.hidden_size],
230
+ initializer=get_initializer(initializer_range=self.initializer_range),
231
+ )
232
+
233
+ with tf.name_scope("position_embeddings"):
234
+ self.position_embeddings = self.add_weight(
235
+ name="embeddings",
236
+ shape=[self.max_position_embeddings, self.hidden_size],
237
+ initializer=get_initializer(initializer_range=self.initializer_range),
238
+ )
239
+
240
+ if self.built:
241
+ return
242
+ self.built = True
243
+ if getattr(self, "LayerNorm", None) is not None:
244
+ with tf.name_scope(self.LayerNorm.name):
245
+ self.LayerNorm.build([None, None, self.config.hidden_size])
246
+
247
+ def call(self, input_ids=None, token_type_ids=None, inputs_embeds=None, training=False):
248
+ """
249
+ Applies embedding based on inputs tensor.
250
+
251
+ Returns:
252
+ final_embeddings (`tf.Tensor`): output embedding tensor.
253
+ """
254
+ assert not (input_ids is None and inputs_embeds is None)
255
+
256
+ if input_ids is not None:
257
+ check_embeddings_within_bounds(input_ids, self.config.vocab_size)
258
+ inputs_embeds = tf.gather(params=self.weight, indices=input_ids)
259
+
260
+ input_shape = shape_list(inputs_embeds)[:-1]
261
+
262
+ if token_type_ids is None:
263
+ token_type_ids = tf.fill(dims=input_shape, value=0)
264
+
265
+ position_ids = tf.expand_dims(tf.range(start=0, limit=input_shape[-1]), axis=0)
266
+ position_embeds = tf.gather(params=self.position_embeddings, indices=position_ids)
267
+ token_type_embeds = tf.gather(params=self.token_type_embeddings, indices=token_type_ids)
268
+ final_embeddings = inputs_embeds + position_embeds + token_type_embeds
269
+ final_embeddings = self.LayerNorm(inputs=final_embeddings)
270
+ final_embeddings = self.dropout(inputs=final_embeddings, training=training)
271
+
272
+ return final_embeddings
273
+
274
+
275
+ class TFLxmertAttention(keras.layers.Layer):
276
+ def __init__(self, config, **kwargs):
277
+ super().__init__(**kwargs)
278
+ if config.hidden_size % config.num_attention_heads != 0:
279
+ raise ValueError(
280
+ f"The hidden size ({config.hidden_size}) is not a multiple of the number of attention "
281
+ f"heads ({config.num_attention_heads}"
282
+ )
283
+
284
+ self.num_attention_heads = config.num_attention_heads
285
+ assert config.hidden_size % config.num_attention_heads == 0
286
+ self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
287
+ self.all_head_size = self.num_attention_heads * self.attention_head_size
288
+
289
+ self.query = keras.layers.Dense(
290
+ self.all_head_size,
291
+ kernel_initializer=get_initializer(config.initializer_range),
292
+ name="query",
293
+ )
294
+ self.key = keras.layers.Dense(
295
+ self.all_head_size,
296
+ kernel_initializer=get_initializer(config.initializer_range),
297
+ name="key",
298
+ )
299
+ self.value = keras.layers.Dense(
300
+ self.all_head_size,
301
+ kernel_initializer=get_initializer(config.initializer_range),
302
+ name="value",
303
+ )
304
+
305
+ self.dropout = keras.layers.Dropout(config.attention_probs_dropout_prob)
306
+ self.ctx_dim = config.hidden_size
307
+ self.config = config
308
+
309
+ def transpose_for_scores(self, x, batch_size):
310
+ # Reshape from [batch_size, seq_length, all_head_size] to [batch_size, seq_length, num_attention_heads, attention_head_size]
311
+ x = tf.reshape(x, (batch_size, -1, self.num_attention_heads, self.attention_head_size))
312
+ return tf.transpose(x, perm=[0, 2, 1, 3])
313
+
314
+ def call(self, hidden_states, context, attention_mask, output_attentions, training=False):
315
+ batch_size = shape_list(hidden_states)[0]
316
+ mixed_query_layer = self.query(hidden_states)
317
+ mixed_key_layer = self.key(context)
318
+ mixed_value_layer = self.value(context)
319
+
320
+ query_layer = self.transpose_for_scores(mixed_query_layer, batch_size)
321
+ key_layer = self.transpose_for_scores(mixed_key_layer, batch_size)
322
+ value_layer = self.transpose_for_scores(mixed_value_layer, batch_size)
323
+
324
+ # Take the dot product between "query" and "key" to get the raw attention scores.
325
+ attention_scores = tf.matmul(
326
+ query_layer, key_layer, transpose_b=True
327
+ ) # (batch size, num_heads, seq_len_q, seq_len_k)
328
+ dk = tf.cast(shape_list(key_layer)[-1], dtype=attention_scores.dtype) # scale attention_scores
329
+ attention_scores = attention_scores / tf.math.sqrt(dk)
330
+
331
+ if attention_mask is not None:
332
+ # Apply the attention mask is (precomputed for all layers in TFLxmertModel call() function)
333
+ attention_mask = tf.cast(attention_mask, dtype=attention_scores.dtype)
334
+ attention_scores = attention_scores + attention_mask
335
+
336
+ # Normalize the attention scores to probabilities.
337
+ attention_probs = stable_softmax(attention_scores, axis=-1)
338
+
339
+ # This is actually dropping out entire tokens to attend to, which might
340
+ # seem a bit unusual, but is taken from the original Transformer paper.
341
+ attention_probs = self.dropout(attention_probs, training=training)
342
+ context_layer = tf.matmul(attention_probs, value_layer)
343
+
344
+ context_layer = tf.transpose(context_layer, perm=[0, 2, 1, 3])
345
+ context_layer = tf.reshape(
346
+ context_layer, (batch_size, -1, self.all_head_size)
347
+ ) # (batch_size, seq_len_q, all_head_size)
348
+
349
+ outputs = (context_layer, attention_probs) if output_attentions else (context_layer,)
350
+ return outputs
351
+
352
+ def build(self, input_shape=None):
353
+ if self.built:
354
+ return
355
+ self.built = True
356
+ if getattr(self, "query", None) is not None:
357
+ with tf.name_scope(self.query.name):
358
+ self.query.build([None, None, self.config.hidden_size])
359
+ if getattr(self, "key", None) is not None:
360
+ with tf.name_scope(self.key.name):
361
+ self.key.build([None, None, self.ctx_dim])
362
+ if getattr(self, "value", None) is not None:
363
+ with tf.name_scope(self.value.name):
364
+ self.value.build([None, None, self.ctx_dim])
365
+
366
+
367
+ class TFLxmertIntermediate(keras.layers.Layer):
368
+ def __init__(self, config, **kwargs):
369
+ super().__init__(**kwargs)
370
+ self.dense = keras.layers.Dense(
371
+ config.intermediate_size,
372
+ kernel_initializer=get_initializer(config.initializer_range),
373
+ name="dense",
374
+ )
375
+ if isinstance(config.hidden_act, str):
376
+ self.intermediate_act_fn = get_tf_activation(config.hidden_act)
377
+ else:
378
+ self.intermediate_act_fn = config.hidden_act
379
+ self.config = config
380
+
381
+ def call(self, hidden_states):
382
+ hidden_states = self.dense(hidden_states)
383
+ hidden_states = self.intermediate_act_fn(hidden_states)
384
+ return hidden_states
385
+
386
+ def build(self, input_shape=None):
387
+ if self.built:
388
+ return
389
+ self.built = True
390
+ if getattr(self, "dense", None) is not None:
391
+ with tf.name_scope(self.dense.name):
392
+ self.dense.build([None, None, self.config.hidden_size])
393
+
394
+
395
+ class TFLxmertOutput(keras.layers.Layer):
396
+ def __init__(self, config, **kwargs):
397
+ super().__init__(**kwargs)
398
+ self.dense = keras.layers.Dense(
399
+ config.hidden_size,
400
+ kernel_initializer=get_initializer(config.initializer_range),
401
+ name="dense",
402
+ )
403
+
404
+ self.LayerNorm = keras.layers.LayerNormalization(epsilon=config.layer_norm_eps, name="LayerNorm")
405
+ self.dropout = keras.layers.Dropout(config.hidden_dropout_prob)
406
+ self.config = config
407
+
408
+ def call(self, hidden_states, input_tensor, training=False):
409
+ hidden_states = self.dense(hidden_states)
410
+ hidden_states = self.dropout(hidden_states, training)
411
+ hidden_states = self.LayerNorm(hidden_states + input_tensor)
412
+ return hidden_states
413
+
414
+ def build(self, input_shape=None):
415
+ if self.built:
416
+ return
417
+ self.built = True
418
+ if getattr(self, "dense", None) is not None:
419
+ with tf.name_scope(self.dense.name):
420
+ self.dense.build([None, None, self.config.intermediate_size])
421
+ if getattr(self, "LayerNorm", None) is not None:
422
+ with tf.name_scope(self.LayerNorm.name):
423
+ self.LayerNorm.build([None, None, self.config.hidden_size])
424
+
425
+
426
+ class TFLxmertAttentionOutput(keras.layers.Layer):
427
+ def __init__(self, config, **kwargs):
428
+ super().__init__(**kwargs)
429
+ self.dense = keras.layers.Dense(
430
+ config.hidden_size,
431
+ kernel_initializer=get_initializer(config.initializer_range),
432
+ name="dense",
433
+ )
434
+ self.LayerNorm = keras.layers.LayerNormalization(epsilon=config.layer_norm_eps, name="LayerNorm")
435
+ self.dropout = keras.layers.Dropout(config.hidden_dropout_prob)
436
+ self.config = config
437
+
438
+ def call(self, hidden_states, input_tensor, training=False):
439
+ hidden_states = self.dense(hidden_states)
440
+ hidden_states = self.dropout(hidden_states, training=training)
441
+ hidden_states = self.LayerNorm(hidden_states + input_tensor)
442
+ return hidden_states
443
+
444
+ def build(self, input_shape=None):
445
+ if self.built:
446
+ return
447
+ self.built = True
448
+ if getattr(self, "dense", None) is not None:
449
+ with tf.name_scope(self.dense.name):
450
+ self.dense.build([None, None, self.config.hidden_size])
451
+ if getattr(self, "LayerNorm", None) is not None:
452
+ with tf.name_scope(self.LayerNorm.name):
453
+ self.LayerNorm.build([None, None, self.config.hidden_size])
454
+
455
+
456
+ class TFLxmertSelfAttentionLayer(keras.layers.Layer):
457
+ def __init__(self, config, **kwargs):
458
+ super().__init__(**kwargs)
459
+ self.self = TFLxmertAttention(config, name="self")
460
+ self.attention_output = TFLxmertAttentionOutput(config, name="output")
461
+
462
+ def call(self, input_tensor, attention_mask, output_attentions, training=False):
463
+ # Self attention attends to itself, thus keys and queries are the same (input_tensor).
464
+ self_output = self.self(input_tensor, input_tensor, attention_mask, output_attentions)
465
+ if output_attentions:
466
+ attention_probs = self_output[1]
467
+ attention_output = self.attention_output(self_output[0], input_tensor)
468
+ return (attention_output, attention_probs) if output_attentions else (attention_output,)
469
+
470
+ def build(self, input_shape=None):
471
+ if self.built:
472
+ return
473
+ self.built = True
474
+ if getattr(self, "self", None) is not None:
475
+ with tf.name_scope(self.self.name):
476
+ self.self.build(None)
477
+ if getattr(self, "attention_output", None) is not None:
478
+ with tf.name_scope(self.attention_output.name):
479
+ self.attention_output.build(None)
480
+
481
+
482
+ class TFLxmertCrossAttentionLayer(keras.layers.Layer):
483
+ def __init__(self, config, **kwargs):
484
+ super().__init__(**kwargs)
485
+ self.att = TFLxmertAttention(config, name="att")
486
+ self.attention_output = TFLxmertAttentionOutput(config, name="output")
487
+
488
+ def call(
489
+ self,
490
+ input_tensor,
491
+ ctx_tensor,
492
+ ctx_att_mask,
493
+ output_attentions=False,
494
+ training=False,
495
+ ):
496
+ output = self.att(input_tensor, ctx_tensor, ctx_att_mask, output_attentions, training=training)
497
+ if output_attentions:
498
+ attention_probs = output[1]
499
+ attention_output = self.attention_output(output[0], input_tensor, training=training)
500
+ outputs = (attention_output, attention_probs) if output_attentions else (attention_output,)
501
+ return outputs
502
+
503
+ def build(self, input_shape=None):
504
+ if self.built:
505
+ return
506
+ self.built = True
507
+ if getattr(self, "att", None) is not None:
508
+ with tf.name_scope(self.att.name):
509
+ self.att.build(None)
510
+ if getattr(self, "attention_output", None) is not None:
511
+ with tf.name_scope(self.attention_output.name):
512
+ self.attention_output.build(None)
513
+
514
+
515
+ class TFLxmertLayer(keras.layers.Layer):
516
+ def __init__(self, config, **kwargs):
517
+ super().__init__(**kwargs)
518
+ self.attention = TFLxmertSelfAttentionLayer(config, name="attention")
519
+ self.intermediate = TFLxmertIntermediate(config, name="intermediate")
520
+ self.transformer_output = TFLxmertOutput(config, name="output")
521
+
522
+ def call(self, hidden_states, attention_mask, output_attentions, training=False):
523
+ attention_outputs = self.attention(hidden_states, attention_mask, output_attentions, training=training)
524
+ attention_output = attention_outputs[0]
525
+ intermediate_output = self.intermediate(attention_output)
526
+ layer_output = self.transformer_output(intermediate_output, attention_output, training=training)
527
+ outputs = (layer_output,) + attention_outputs[1:] # add attentions if we output them
528
+ return outputs
529
+
530
+ def build(self, input_shape=None):
531
+ if self.built:
532
+ return
533
+ self.built = True
534
+ if getattr(self, "attention", None) is not None:
535
+ with tf.name_scope(self.attention.name):
536
+ self.attention.build(None)
537
+ if getattr(self, "intermediate", None) is not None:
538
+ with tf.name_scope(self.intermediate.name):
539
+ self.intermediate.build(None)
540
+ if getattr(self, "transformer_output", None) is not None:
541
+ with tf.name_scope(self.transformer_output.name):
542
+ self.transformer_output.build(None)
543
+
544
+
545
+ class TFLxmertXLayer(keras.layers.Layer):
546
+ def __init__(self, config, **kwargs):
547
+ super().__init__(**kwargs)
548
+ self.visual_attention = TFLxmertCrossAttentionLayer(config, name="visual_attention")
549
+
550
+ # Self-attention Layers
551
+ self.lang_self_att = TFLxmertSelfAttentionLayer(config, name="lang_self_att")
552
+ self.visn_self_att = TFLxmertSelfAttentionLayer(config, name="visn_self_att")
553
+
554
+ # Intermediate and Output Layers (FFNs)
555
+ self.lang_inter = TFLxmertIntermediate(config, name="lang_inter")
556
+ self.lang_output = TFLxmertOutput(config, name="lang_output")
557
+ self.visn_inter = TFLxmertIntermediate(config, name="visn_inter")
558
+ self.visn_output = TFLxmertOutput(config, name="visn_output")
559
+
560
+ def cross_att(
561
+ self,
562
+ lang_input,
563
+ lang_attention_mask,
564
+ visn_input,
565
+ visn_attention_mask,
566
+ output_attentions,
567
+ training=False,
568
+ ):
569
+ # Cross Attention
570
+
571
+ # Keras saving and loading model *does not work* with the same inputs for two layers.
572
+ lang_attention_lang_input = tf.identity(lang_input)
573
+ visn_attention_lang_input = tf.identity(lang_input)
574
+ lang_attention_visn_input = tf.identity(visn_input)
575
+ visn_attention_visn_input = tf.identity(visn_input)
576
+
577
+ lang_att_output = self.visual_attention(
578
+ lang_attention_lang_input,
579
+ lang_attention_visn_input,
580
+ visn_attention_mask,
581
+ output_attentions=output_attentions,
582
+ training=training,
583
+ )
584
+ visn_att_output = self.visual_attention(
585
+ visn_attention_visn_input,
586
+ visn_attention_lang_input,
587
+ lang_attention_mask,
588
+ output_attentions=output_attentions,
589
+ training=training,
590
+ )
591
+ return lang_att_output, visn_att_output
592
+
593
+ def self_att(
594
+ self,
595
+ lang_input,
596
+ lang_attention_mask,
597
+ visn_input,
598
+ visn_attention_mask,
599
+ training=False,
600
+ ):
601
+ # Self Attention
602
+ output_attentions = False
603
+ lang_att_output = self.lang_self_att(lang_input, lang_attention_mask, output_attentions, training=training)
604
+ visn_att_output = self.visn_self_att(visn_input, visn_attention_mask, output_attentions, training=training)
605
+ return lang_att_output[0], visn_att_output[0]
606
+
607
+ def output_fc(self, lang_input, visn_input, training=False):
608
+ # FC layers
609
+ lang_inter_output = self.lang_inter(lang_input)
610
+ visn_inter_output = self.visn_inter(visn_input)
611
+
612
+ # Layer output
613
+ lang_output = self.lang_output(lang_inter_output, lang_input, training)
614
+ visn_output = self.visn_output(visn_inter_output, visn_input, training)
615
+ return lang_output, visn_output
616
+
617
+ def call(
618
+ self,
619
+ lang_feats,
620
+ lang_attention_mask,
621
+ visn_feats,
622
+ visn_attention_mask,
623
+ output_attentions,
624
+ training=False,
625
+ ):
626
+ lang_att_output = lang_feats
627
+ visn_att_output = visn_feats
628
+
629
+ lang_att_output, visn_att_output = self.cross_att(
630
+ lang_att_output,
631
+ lang_attention_mask,
632
+ visn_att_output,
633
+ visn_attention_mask,
634
+ output_attentions,
635
+ training=training,
636
+ )
637
+ attention_probs = lang_att_output[1:]
638
+ lang_att_output, visn_att_output = self.self_att(
639
+ lang_att_output[0],
640
+ lang_attention_mask,
641
+ visn_att_output[0],
642
+ visn_attention_mask,
643
+ training=training,
644
+ )
645
+ lang_output, visn_output = self.output_fc(lang_att_output, visn_att_output, training=training)
646
+
647
+ return (lang_output, visn_output, attention_probs[0]) if output_attentions else (lang_output, visn_output)
648
+
649
+ def build(self, input_shape=None):
650
+ if self.built:
651
+ return
652
+ self.built = True
653
+ if getattr(self, "visual_attention", None) is not None:
654
+ with tf.name_scope(self.visual_attention.name):
655
+ self.visual_attention.build(None)
656
+ if getattr(self, "lang_self_att", None) is not None:
657
+ with tf.name_scope(self.lang_self_att.name):
658
+ self.lang_self_att.build(None)
659
+ if getattr(self, "visn_self_att", None) is not None:
660
+ with tf.name_scope(self.visn_self_att.name):
661
+ self.visn_self_att.build(None)
662
+ if getattr(self, "lang_inter", None) is not None:
663
+ with tf.name_scope(self.lang_inter.name):
664
+ self.lang_inter.build(None)
665
+ if getattr(self, "lang_output", None) is not None:
666
+ with tf.name_scope(self.lang_output.name):
667
+ self.lang_output.build(None)
668
+ if getattr(self, "visn_inter", None) is not None:
669
+ with tf.name_scope(self.visn_inter.name):
670
+ self.visn_inter.build(None)
671
+ if getattr(self, "visn_output", None) is not None:
672
+ with tf.name_scope(self.visn_output.name):
673
+ self.visn_output.build(None)
674
+
675
+
676
+ class TFLxmertEncoder(keras.layers.Layer):
677
+ def __init__(self, config, **kwargs):
678
+ super().__init__(**kwargs)
679
+
680
+ self.visn_fc = TFLxmertVisualFeatureEncoder(config, name="visn_fc")
681
+
682
+ # Number of layers
683
+ self.num_l_layers = config.l_layers
684
+ self.num_x_layers = config.x_layers
685
+ self.num_r_layers = config.r_layers
686
+
687
+ # Layers
688
+ # Using self.layer instead of self.l_layer to support loading BERT weights.
689
+ self.layer = [TFLxmertLayer(config, name=f"layer_._{i}") for i in range(self.num_l_layers)]
690
+ self.x_layers = [TFLxmertXLayer(config, name=f"x_layers_._{i}") for i in range(self.num_x_layers)]
691
+ self.r_layers = [TFLxmertLayer(config, name=f"r_layers_._{i}") for i in range(self.num_r_layers)]
692
+ self.config = config
693
+
694
+ def call(
695
+ self,
696
+ lang_feats=None,
697
+ lang_attention_mask=None,
698
+ visual_feats=None,
699
+ visual_pos=None,
700
+ visual_attention_mask=None,
701
+ output_attentions=None,
702
+ training=False,
703
+ ):
704
+ vision_hidden_states = ()
705
+ language_hidden_states = ()
706
+ vision_attentions = () if output_attentions or self.config.output_attentions else None
707
+ language_attentions = () if output_attentions or self.config.output_attentions else None
708
+ cross_encoder_attentions = () if output_attentions or self.config.output_attentions else None
709
+
710
+ visual_feats = self.visn_fc([visual_feats, visual_pos], training=training)
711
+
712
+ # Run language layers
713
+ for layer_module in self.layer:
714
+ l_outputs = layer_module(lang_feats, lang_attention_mask, output_attentions, training=training)
715
+ lang_feats = l_outputs[0]
716
+ language_hidden_states = language_hidden_states + (lang_feats,)
717
+ if language_attentions is not None:
718
+ language_attentions = language_attentions + (l_outputs[1],)
719
+
720
+ # Run relational layers
721
+ for layer_module in self.r_layers:
722
+ v_outputs = layer_module(
723
+ visual_feats,
724
+ visual_attention_mask,
725
+ output_attentions,
726
+ training=training,
727
+ )
728
+ visual_feats = v_outputs[0]
729
+ vision_hidden_states = vision_hidden_states + (visual_feats,)
730
+ if vision_attentions is not None:
731
+ vision_attentions = vision_attentions + (v_outputs[1],)
732
+
733
+ # Run cross-modality layers
734
+ for layer_module in self.x_layers:
735
+ x_outputs = layer_module(
736
+ lang_feats,
737
+ lang_attention_mask,
738
+ visual_feats,
739
+ visual_attention_mask,
740
+ output_attentions,
741
+ training=training,
742
+ )
743
+ lang_feats, visual_feats = x_outputs[:2]
744
+ vision_hidden_states = vision_hidden_states + (visual_feats,)
745
+ language_hidden_states = language_hidden_states + (lang_feats,)
746
+ if cross_encoder_attentions is not None:
747
+ cross_encoder_attentions = cross_encoder_attentions + (x_outputs[2],)
748
+
749
+ visual_encoder_outputs = (
750
+ vision_hidden_states,
751
+ vision_attentions if output_attentions else None,
752
+ )
753
+ lang_encoder_outputs = (
754
+ language_hidden_states,
755
+ language_attentions if output_attentions else None,
756
+ )
757
+
758
+ return (
759
+ visual_encoder_outputs,
760
+ lang_encoder_outputs,
761
+ cross_encoder_attentions if output_attentions else None,
762
+ )
763
+
764
+ def build(self, input_shape=None):
765
+ if self.built:
766
+ return
767
+ self.built = True
768
+ if getattr(self, "visn_fc", None) is not None:
769
+ with tf.name_scope(self.visn_fc.name):
770
+ self.visn_fc.build(None)
771
+ if getattr(self, "layer", None) is not None:
772
+ for layer in self.layer:
773
+ with tf.name_scope(layer.name):
774
+ layer.build(None)
775
+ if getattr(self, "x_layers", None) is not None:
776
+ for layer in self.x_layers:
777
+ with tf.name_scope(layer.name):
778
+ layer.build(None)
779
+ if getattr(self, "r_layers", None) is not None:
780
+ for layer in self.r_layers:
781
+ with tf.name_scope(layer.name):
782
+ layer.build(None)
783
+
784
+
785
+ @keras_serializable
786
+ class TFLxmertMainLayer(keras.layers.Layer):
787
+ config_class = LxmertConfig
788
+
789
+ def __init__(self, config, **kwargs):
790
+ super().__init__(**kwargs)
791
+
792
+ self.config = config
793
+ self.num_l_layers = config.l_layers
794
+ self.num_x_layers = config.x_layers
795
+ self.num_r_layers = config.r_layers
796
+ self.initializer_range = config.initializer_range
797
+ self.output_attentions = config.output_attentions
798
+ self.output_hidden_states = config.output_hidden_states
799
+ self.return_dict = config.use_return_dict
800
+ self.embeddings = TFLxmertEmbeddings(config, name="embeddings")
801
+ self.encoder = TFLxmertEncoder(config, name="encoder")
802
+ self.pooler = TFLxmertPooler(config, name="pooler")
803
+ self.config = config
804
+
805
+ def get_input_embeddings(self):
806
+ return self.embeddings
807
+
808
+ def set_input_embeddings(self, value):
809
+ self.embeddings.weight = value
810
+ self.embeddings.vocab_size = shape_list(value)[0]
811
+
812
+ def _prune_heads(self, heads_to_prune):
813
+ raise NotImplementedError
814
+
815
+ @unpack_inputs
816
+ def call(
817
+ self,
818
+ input_ids=None,
819
+ visual_feats=None,
820
+ visual_pos=None,
821
+ attention_mask=None,
822
+ visual_attention_mask=None,
823
+ token_type_ids=None,
824
+ inputs_embeds=None,
825
+ output_attentions=None,
826
+ output_hidden_states=None,
827
+ return_dict=None,
828
+ training=False,
829
+ ):
830
+ if input_ids is not None and inputs_embeds is not None:
831
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
832
+ elif input_ids is not None:
833
+ input_shape = shape_list(input_ids)
834
+ elif inputs_embeds is not None:
835
+ input_shape = shape_list(inputs_embeds)[:-1]
836
+ else:
837
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
838
+ if visual_pos is None or visual_feats is None:
839
+ raise ValueError("visual_feats and visual_pos cannot be `None` in LXMERT's `call` method.")
840
+
841
+ if attention_mask is None:
842
+ attention_mask = tf.fill(input_shape, 1)
843
+
844
+ if token_type_ids is None:
845
+ token_type_ids = tf.fill(input_shape, 0)
846
+
847
+ # Positional Word Embeddings
848
+ embedding_output = self.embeddings(input_ids, token_type_ids, inputs_embeds, training)
849
+
850
+ # We create a 3D attention mask from a 2D tensor mask.
851
+ # Sizes are [batch_size, 1, 1, to_seq_length]
852
+ # So we can broadcast to [batch_size, num_heads, from_seq_length, to_seq_length]
853
+ # this attention mask is more simple than the triangular masking of causal attention
854
+ # used in OpenAI GPT, we just need to prepare the broadcast dimension here.
855
+ extended_attention_mask = tf.reshape(attention_mask, (input_shape[0], 1, 1, input_shape[1]))
856
+
857
+ # Since attention_mask is 1.0 for positions we want to attend and 0.0 for
858
+ # masked positions, this operation will create a tensor which is 0.0 for
859
+ # positions we want to attend and -10000.0 for masked positions.
860
+ # Since we are adding it to the raw scores before the softmax, this is
861
+ # effectively the same as removing these entirely.
862
+
863
+ extended_attention_mask = tf.cast(extended_attention_mask, dtype=embedding_output.dtype)
864
+ one_cst = tf.constant(1.0, dtype=embedding_output.dtype)
865
+ ten_thousand_cst = tf.constant(-10000.0, dtype=embedding_output.dtype)
866
+ extended_attention_mask = tf.multiply(tf.subtract(one_cst, extended_attention_mask), ten_thousand_cst)
867
+
868
+ if visual_attention_mask is not None:
869
+ extended_visual_attention_mask = tf.reshape(visual_attention_mask, (input_shape[0], 1, 1, input_shape[1]))
870
+ extended_visual_attention_mask = tf.expand_dims(tf.expand_dims(visual_attention_mask, axis=1), axis=1)
871
+
872
+ extended_visual_attention_mask = tf.cast(extended_visual_attention_mask, dtype=embedding_output.dtype)
873
+ extended_visual_attention_mask = tf.multiply(
874
+ tf.subtract(one_cst, extended_visual_attention_mask), ten_thousand_cst
875
+ )
876
+ else:
877
+ extended_visual_attention_mask = None
878
+
879
+ # Run Lxmert encoder
880
+ encoder_outputs = self.encoder(
881
+ embedding_output,
882
+ extended_attention_mask,
883
+ visual_feats,
884
+ visual_pos,
885
+ extended_visual_attention_mask,
886
+ output_attentions,
887
+ training,
888
+ )
889
+ visual_encoder_outputs, lang_encoder_outputs = encoder_outputs[:2]
890
+ vision_hidden_states = visual_encoder_outputs[0]
891
+ language_hidden_states = lang_encoder_outputs[0]
892
+
893
+ all_attentions = ()
894
+ if output_attentions:
895
+ language_attentions = lang_encoder_outputs[1]
896
+ vision_attentions = visual_encoder_outputs[1]
897
+ cross_encoder_attentions = encoder_outputs[2]
898
+ all_attentions = (
899
+ language_attentions,
900
+ vision_attentions,
901
+ cross_encoder_attentions,
902
+ )
903
+
904
+ hidden_states = (language_hidden_states, vision_hidden_states) if output_hidden_states else ()
905
+
906
+ visual_output = vision_hidden_states[-1]
907
+ lang_output = language_hidden_states[-1]
908
+ pooled_output = self.pooler(lang_output)
909
+
910
+ if not return_dict:
911
+ return (lang_output, visual_output, pooled_output) + hidden_states + all_attentions
912
+
913
+ return TFLxmertModelOutput(
914
+ pooled_output=pooled_output,
915
+ language_output=lang_output,
916
+ vision_output=visual_output,
917
+ language_hidden_states=language_hidden_states if output_hidden_states else None,
918
+ vision_hidden_states=vision_hidden_states if output_hidden_states else None,
919
+ language_attentions=language_attentions if output_attentions else None,
920
+ vision_attentions=vision_attentions if output_attentions else None,
921
+ cross_encoder_attentions=cross_encoder_attentions if output_attentions else None,
922
+ )
923
+
924
+ def build(self, input_shape=None):
925
+ if self.built:
926
+ return
927
+ self.built = True
928
+ if getattr(self, "embeddings", None) is not None:
929
+ with tf.name_scope(self.embeddings.name):
930
+ self.embeddings.build(None)
931
+ if getattr(self, "encoder", None) is not None:
932
+ with tf.name_scope(self.encoder.name):
933
+ self.encoder.build(None)
934
+ if getattr(self, "pooler", None) is not None:
935
+ with tf.name_scope(self.pooler.name):
936
+ self.pooler.build(None)
937
+
938
+
939
+ class TFLxmertPreTrainedModel(TFPreTrainedModel):
940
+ """
941
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
942
+ models.
943
+ """
944
+
945
+ config_class = LxmertConfig
946
+ base_model_prefix = "lxmert"
947
+
948
+ @property
949
+ def dummy_inputs(self):
950
+ """
951
+ Dummy inputs to build the network.
952
+
953
+ Returns:
954
+ tf.Tensor with dummy inputs
955
+ """
956
+ batch_size = 2
957
+ num_visual_features = 10
958
+ input_ids = tf.constant([[3, 5, 6], [2, 3, 4]], dtype=tf.int32)
959
+ visual_feats = tf.random.uniform((batch_size, num_visual_features, self.config.visual_feat_dim))
960
+ visual_pos = tf.random.uniform((batch_size, num_visual_features, 4))
961
+
962
+ return {
963
+ "input_ids": input_ids,
964
+ "visual_feats": visual_feats,
965
+ "visual_pos": visual_pos,
966
+ }
967
+
968
+ @property
969
+ def input_signature(self):
970
+ return {
971
+ "input_ids": tf.TensorSpec((None, None), tf.int32, name="input_ids"),
972
+ "attention_mask": tf.TensorSpec((None, None), tf.int32, name="attention_mask"),
973
+ "visual_feats": tf.TensorSpec((None, None, self.config.visual_feat_dim), tf.float32, name="visual_feats"),
974
+ "visual_pos": tf.TensorSpec((None, None, 4), tf.float32, name="visual_pos"),
975
+ "visual_attention_mask": tf.TensorSpec((None, None), tf.int32, name="visual_attention_mask"),
976
+ "token_type_ids": tf.TensorSpec((None, None), tf.int32, name="token_type_ids"),
977
+ }
978
+
979
+
980
+ LXMERT_START_DOCSTRING = r"""
981
+
982
+ The LXMERT model was proposed in [LXMERT: Learning Cross-Modality Encoder Representations from
983
+ Transformers](https://arxiv.org/abs/1908.07490) by Hao Tan and Mohit Bansal. It's a vision and language transformer
984
+ model, pre-trained on a variety of multi-modal datasets comprising of GQA, VQAv2.0, MCSCOCO captions, and Visual
985
+ genome, using a combination of masked language modeling, region of interest feature regression, cross entropy loss
986
+ for question answering attribute prediction, and object tag prediction.
987
+
988
+ This model is also a [keras.Model](https://www.tensorflow.org/api_docs/python/tf/keras/Model) subclass. Use it
989
+ as a regular TF 2.0 Keras Model and refer to the TF 2.0 documentation for all matter related to general usage and
990
+ behavior.
991
+
992
+ <Tip>
993
+
994
+ TensorFlow models and layers in `transformers` accept two formats as input:
995
+
996
+ - having all inputs as keyword arguments (like PyTorch models), or
997
+ - having all inputs as a list, tuple or dict in the first positional argument.
998
+
999
+ The reason the second format is supported is that Keras methods prefer this format when passing inputs to models
1000
+ and layers. Because of this support, when using methods like `model.fit()` things should "just work" for you - just
1001
+ pass your inputs and labels in any format that `model.fit()` supports! If, however, you want to use the second
1002
+ format outside of Keras methods like `fit()` and `predict()`, such as when creating your own layers or models with
1003
+ the Keras `Functional` API, there are three possibilities you can use to gather all the input Tensors in the first
1004
+ positional argument:
1005
+
1006
+ - a single Tensor with `input_ids` only and nothing else: `model(input_ids)`
1007
+ - a list of varying length with one or several input Tensors IN THE ORDER given in the docstring:
1008
+ `model([input_ids, attention_mask])` or `model([input_ids, attention_mask, token_type_ids])`
1009
+ - a dictionary with one or several input Tensors associated to the input names given in the docstring:
1010
+ `model({"input_ids": input_ids, "token_type_ids": token_type_ids})`
1011
+
1012
+ Note that when creating models and layers with
1013
+ [subclassing](https://keras.io/guides/making_new_layers_and_models_via_subclassing/) then you don't need to worry
1014
+ about any of this, as you can just pass inputs like you would to any other Python function!
1015
+
1016
+ </Tip>
1017
+
1018
+ Parameters:
1019
+ config ([`LxmertConfig`]): Model configuration class with all the parameters of the model.
1020
+ Initializing with a config file does not load the weights associated with the model, only the
1021
+ configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
1022
+ """
1023
+
1024
+ LXMERT_INPUTS_DOCSTRING = r"""
1025
+ Args:
1026
+ input_ids (`np.ndarray` or `tf.Tensor` of shape `(batch_size, sequence_length)`):
1027
+ Indices of input sequence tokens in the vocabulary.
1028
+
1029
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.__call__`] and
1030
+ [`PreTrainedTokenizer.encode`] for details.
1031
+
1032
+ [What are input IDs?](../glossary#input-ids)
1033
+ visual_feats (`tf.Tensor` of shape `(batch_size, num_visual_features, visual_feat_dim)`):
1034
+ This input represents visual features. They ROI pooled object features from bounding boxes using a
1035
+ faster-RCNN model)
1036
+
1037
+ These are currently not provided by the transformers library.
1038
+ visual_pos (`tf.Tensor` of shape `(batch_size, num_visual_features, visual_feat_dim)`):
1039
+ This input represents spacial features corresponding to their relative (via index) visual features. The
1040
+ pre-trained LXMERT model expects these spacial features to be normalized bounding boxes on a scale of 0 to
1041
+ 1.
1042
+
1043
+ These are currently not provided by the transformers library.
1044
+ attention_mask (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
1045
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
1046
+
1047
+ - 1 for tokens that are **not masked**,
1048
+ - 0 for tokens that are **masked**.
1049
+
1050
+ [What are attention masks?](../glossary#attention-mask)
1051
+ visual_attention_mask (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
1052
+ MMask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
1053
+
1054
+ - 1 for tokens that are **not masked**,
1055
+ - 0 for tokens that are **masked**.
1056
+
1057
+ [What are attention masks?](../glossary#attention-mask)
1058
+ token_type_ids (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
1059
+ Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
1060
+ 1]`:
1061
+
1062
+ - 0 corresponds to a *sentence A* token,
1063
+ - 1 corresponds to a *sentence B* token.
1064
+
1065
+ [What are token type IDs?](../glossary#token-type-ids)
1066
+ inputs_embeds (`tf.Tensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
1067
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
1068
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
1069
+ model's internal embedding lookup matrix.
1070
+ output_attentions (`bool`, *optional*):
1071
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
1072
+ tensors for more detail. This argument can be used only in eager mode, in graph mode the value in the
1073
+ config will be used instead.
1074
+ output_hidden_states (`bool`, *optional*):
1075
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
1076
+ more detail. This argument can be used only in eager mode, in graph mode the value in the config will be
1077
+ used instead.
1078
+ return_dict (`bool`, *optional*):
1079
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. This argument can be used in
1080
+ eager mode, in graph mode the value will always be set to True.
1081
+ training (`bool`, *optional*, defaults to `False`):
1082
+ Whether or not to use the model in training mode (some modules like dropout modules have different
1083
+ behaviors between training and evaluation).
1084
+ """
1085
+
1086
+
1087
+ @add_start_docstrings(
1088
+ "The bare Lxmert Model transformer outputting raw hidden-states without any specific head on top.",
1089
+ LXMERT_START_DOCSTRING,
1090
+ )
1091
+ class TFLxmertModel(TFLxmertPreTrainedModel):
1092
+ def __init__(self, config, *inputs, **kwargs):
1093
+ super().__init__(config, *inputs, **kwargs)
1094
+ self.lxmert = TFLxmertMainLayer(config, name="lxmert")
1095
+
1096
+ @unpack_inputs
1097
+ @add_start_docstrings_to_model_forward(LXMERT_INPUTS_DOCSTRING)
1098
+ @add_code_sample_docstrings(
1099
+ checkpoint=_CHECKPOINT_FOR_DOC,
1100
+ output_type=TFLxmertModelOutput,
1101
+ config_class=_CONFIG_FOR_DOC,
1102
+ )
1103
+ def call(
1104
+ self,
1105
+ input_ids: TFModelInputType | None = None,
1106
+ visual_feats: tf.Tensor | None = None,
1107
+ visual_pos: tf.Tensor | None = None,
1108
+ attention_mask: np.ndarray | tf.Tensor | None = None,
1109
+ visual_attention_mask: np.ndarray | tf.Tensor | None = None,
1110
+ token_type_ids: np.ndarray | tf.Tensor | None = None,
1111
+ inputs_embeds: np.ndarray | tf.Tensor | None = None,
1112
+ output_attentions: Optional[bool] = None,
1113
+ output_hidden_states: Optional[bool] = None,
1114
+ return_dict: Optional[bool] = None,
1115
+ training: bool = False,
1116
+ ) -> Union[Tuple, TFLxmertModelOutput]:
1117
+ outputs = self.lxmert(
1118
+ input_ids,
1119
+ visual_feats,
1120
+ visual_pos,
1121
+ attention_mask,
1122
+ visual_attention_mask,
1123
+ token_type_ids,
1124
+ inputs_embeds,
1125
+ output_attentions,
1126
+ output_hidden_states,
1127
+ return_dict,
1128
+ training,
1129
+ )
1130
+
1131
+ return outputs
1132
+
1133
+ def build(self, input_shape=None):
1134
+ if self.built:
1135
+ return
1136
+ self.built = True
1137
+ if getattr(self, "lxmert", None) is not None:
1138
+ with tf.name_scope(self.lxmert.name):
1139
+ self.lxmert.build(None)
1140
+
1141
+
1142
+ class TFLxmertPooler(keras.layers.Layer):
1143
+ def __init__(self, config, **kwargs):
1144
+ super().__init__(**kwargs)
1145
+ self.dense = keras.layers.Dense(
1146
+ config.hidden_size,
1147
+ kernel_initializer=get_initializer(config.initializer_range),
1148
+ activation="tanh",
1149
+ name="dense",
1150
+ )
1151
+ self.config = config
1152
+
1153
+ def call(self, hidden_states):
1154
+ # We "pool" the model by simply taking the hidden state corresponding
1155
+ # to the first token.
1156
+ first_token_tensor = hidden_states[:, 0]
1157
+ pooled_output = self.dense(first_token_tensor)
1158
+ return pooled_output
1159
+
1160
+ def build(self, input_shape=None):
1161
+ if self.built:
1162
+ return
1163
+ self.built = True
1164
+ if getattr(self, "dense", None) is not None:
1165
+ with tf.name_scope(self.dense.name):
1166
+ self.dense.build([None, None, self.config.hidden_size])
1167
+
1168
+
1169
+ # Copied from transformers.models.bert.modeling_tf_bert.TFBertPredictionHeadTransform with Bert->Lxmert
1170
+ class TFLxmertPredictionHeadTransform(keras.layers.Layer):
1171
+ def __init__(self, config: LxmertConfig, **kwargs):
1172
+ super().__init__(**kwargs)
1173
+
1174
+ self.dense = keras.layers.Dense(
1175
+ units=config.hidden_size,
1176
+ kernel_initializer=get_initializer(config.initializer_range),
1177
+ name="dense",
1178
+ )
1179
+
1180
+ if isinstance(config.hidden_act, str):
1181
+ self.transform_act_fn = get_tf_activation(config.hidden_act)
1182
+ else:
1183
+ self.transform_act_fn = config.hidden_act
1184
+
1185
+ self.LayerNorm = keras.layers.LayerNormalization(epsilon=config.layer_norm_eps, name="LayerNorm")
1186
+ self.config = config
1187
+
1188
+ def call(self, hidden_states: tf.Tensor) -> tf.Tensor:
1189
+ hidden_states = self.dense(inputs=hidden_states)
1190
+ hidden_states = self.transform_act_fn(hidden_states)
1191
+ hidden_states = self.LayerNorm(inputs=hidden_states)
1192
+
1193
+ return hidden_states
1194
+
1195
+ def build(self, input_shape=None):
1196
+ if self.built:
1197
+ return
1198
+ self.built = True
1199
+ if getattr(self, "dense", None) is not None:
1200
+ with tf.name_scope(self.dense.name):
1201
+ self.dense.build([None, None, self.config.hidden_size])
1202
+ if getattr(self, "LayerNorm", None) is not None:
1203
+ with tf.name_scope(self.LayerNorm.name):
1204
+ self.LayerNorm.build([None, None, self.config.hidden_size])
1205
+
1206
+
1207
+ # Copied from transformers.models.bert.modeling_tf_bert.TFBertLMPredictionHead with Bert->Lxmert
1208
+ class TFLxmertLMPredictionHead(keras.layers.Layer):
1209
+ def __init__(self, config: LxmertConfig, input_embeddings: keras.layers.Layer, **kwargs):
1210
+ super().__init__(**kwargs)
1211
+
1212
+ self.config = config
1213
+ self.hidden_size = config.hidden_size
1214
+
1215
+ self.transform = TFLxmertPredictionHeadTransform(config, name="transform")
1216
+
1217
+ # The output weights are the same as the input embeddings, but there is
1218
+ # an output-only bias for each token.
1219
+ self.input_embeddings = input_embeddings
1220
+
1221
+ def build(self, input_shape=None):
1222
+ self.bias = self.add_weight(shape=(self.config.vocab_size,), initializer="zeros", trainable=True, name="bias")
1223
+
1224
+ if self.built:
1225
+ return
1226
+ self.built = True
1227
+ if getattr(self, "transform", None) is not None:
1228
+ with tf.name_scope(self.transform.name):
1229
+ self.transform.build(None)
1230
+
1231
+ def get_output_embeddings(self) -> keras.layers.Layer:
1232
+ return self.input_embeddings
1233
+
1234
+ def set_output_embeddings(self, value: tf.Variable):
1235
+ self.input_embeddings.weight = value
1236
+ self.input_embeddings.vocab_size = shape_list(value)[0]
1237
+
1238
+ def get_bias(self) -> Dict[str, tf.Variable]:
1239
+ return {"bias": self.bias}
1240
+
1241
+ def set_bias(self, value: tf.Variable):
1242
+ self.bias = value["bias"]
1243
+ self.config.vocab_size = shape_list(value["bias"])[0]
1244
+
1245
+ def call(self, hidden_states: tf.Tensor) -> tf.Tensor:
1246
+ hidden_states = self.transform(hidden_states=hidden_states)
1247
+ seq_length = shape_list(hidden_states)[1]
1248
+ hidden_states = tf.reshape(tensor=hidden_states, shape=[-1, self.hidden_size])
1249
+ hidden_states = tf.matmul(a=hidden_states, b=self.input_embeddings.weight, transpose_b=True)
1250
+ hidden_states = tf.reshape(tensor=hidden_states, shape=[-1, seq_length, self.config.vocab_size])
1251
+ hidden_states = tf.nn.bias_add(value=hidden_states, bias=self.bias)
1252
+
1253
+ return hidden_states
1254
+
1255
+
1256
+ # Copied from transformers.models.bert.modeling_tf_bert.TFBertMLMHead with Bert->Lxmert
1257
+ class TFLxmertMLMHead(keras.layers.Layer):
1258
+ def __init__(self, config: LxmertConfig, input_embeddings: keras.layers.Layer, **kwargs):
1259
+ super().__init__(**kwargs)
1260
+
1261
+ self.predictions = TFLxmertLMPredictionHead(config, input_embeddings, name="predictions")
1262
+
1263
+ def call(self, sequence_output: tf.Tensor) -> tf.Tensor:
1264
+ prediction_scores = self.predictions(hidden_states=sequence_output)
1265
+
1266
+ return prediction_scores
1267
+
1268
+ def build(self, input_shape=None):
1269
+ if self.built:
1270
+ return
1271
+ self.built = True
1272
+ if getattr(self, "predictions", None) is not None:
1273
+ with tf.name_scope(self.predictions.name):
1274
+ self.predictions.build(None)
1275
+
1276
+
1277
+ class TFLxmertPreTrainingHeads(keras.layers.Layer):
1278
+ def __init__(self, config, input_embeddings, **kwargs):
1279
+ super().__init__(**kwargs)
1280
+ self.predictions = TFLxmertLMPredictionHead(config, input_embeddings, name="predictions")
1281
+
1282
+ self.seq_relationship = keras.layers.Dense(
1283
+ 2,
1284
+ kernel_initializer=get_initializer(config.initializer_range),
1285
+ name="seq_relationship",
1286
+ )
1287
+ self.config = config
1288
+
1289
+ def call(self, sequence_output, pooled_output):
1290
+ prediction_scores = self.predictions(sequence_output)
1291
+ seq_relationship_score = self.seq_relationship(pooled_output)
1292
+ return prediction_scores, seq_relationship_score
1293
+
1294
+ def build(self, input_shape=None):
1295
+ if self.built:
1296
+ return
1297
+ self.built = True
1298
+ if getattr(self, "predictions", None) is not None:
1299
+ with tf.name_scope(self.predictions.name):
1300
+ self.predictions.build(None)
1301
+ if getattr(self, "seq_relationship", None) is not None:
1302
+ with tf.name_scope(self.seq_relationship.name):
1303
+ self.seq_relationship.build([None, None, self.config.hidden_size])
1304
+
1305
+
1306
+ class TFLxmertVisualAnswerHead(keras.layers.Layer):
1307
+ def __init__(self, config, num_labels, **kwargs):
1308
+ super().__init__(**kwargs)
1309
+ hid_dim = config.hidden_size
1310
+ self.dense = keras.layers.Dense(
1311
+ hid_dim * 2,
1312
+ kernel_initializer=get_initializer(config.initializer_range),
1313
+ name="logit_fc_._0",
1314
+ )
1315
+ self.activation = get_tf_activation("gelu")
1316
+ self.layer_norm = keras.layers.LayerNormalization(epsilon=config.layer_norm_eps, name="logit_fc_._2")
1317
+ self.dense_1 = keras.layers.Dense(
1318
+ num_labels,
1319
+ kernel_initializer=get_initializer(config.initializer_range),
1320
+ name="logit_fc_._3",
1321
+ )
1322
+ self.hid_dim = hid_dim
1323
+
1324
+ def call(self, hidden_states):
1325
+ hidden_states = self.dense(hidden_states)
1326
+ hidden_states = self.activation(hidden_states)
1327
+ hidden_states = self.layer_norm(hidden_states)
1328
+ hidden_states = self.dense_1(hidden_states)
1329
+
1330
+ return hidden_states
1331
+
1332
+ def build(self, input_shape=None):
1333
+ if self.built:
1334
+ return
1335
+ self.built = True
1336
+ if getattr(self, "dense", None) is not None:
1337
+ with tf.name_scope(self.dense.name):
1338
+ self.dense.build([None, None, self.hid_dim])
1339
+ if getattr(self, "layer_norm", None) is not None:
1340
+ with tf.name_scope(self.layer_norm.name):
1341
+ self.layer_norm.build([None, self.hid_dim * 2])
1342
+ if getattr(self, "dense_1", None) is not None:
1343
+ with tf.name_scope(self.dense_1.name):
1344
+ self.dense_1.build([None, None, self.hid_dim * 2])
1345
+
1346
+
1347
+ class TFLxmertVisualObjHead(keras.layers.Layer):
1348
+ def __init__(self, config, **kwargs):
1349
+ super().__init__(**kwargs)
1350
+ self.transform = TFLxmertPredictionHeadTransform(config, name="transform")
1351
+
1352
+ # Decide the use of visual losses
1353
+ visual_losses = {}
1354
+ if config.visual_obj_loss:
1355
+ visual_losses["obj"] = {"shape": (-1,), "num": config.num_object_labels}
1356
+ if config.visual_attr_loss:
1357
+ visual_losses["attr"] = {"shape": (-1,), "num": config.num_attr_labels}
1358
+ if config.visual_feat_loss:
1359
+ visual_losses["feat"] = {"shape": (-1, 2048), "num": config.visual_feat_dim}
1360
+ self.visual_losses = visual_losses
1361
+
1362
+ # The output weights are the same as the input embeddings, but there is
1363
+ # an output-only bias for each token.
1364
+ self.decoder_dict = {
1365
+ key: keras.layers.Dense(
1366
+ self.visual_losses[key]["num"],
1367
+ kernel_initializer=get_initializer(config.initializer_range),
1368
+ name=f"decoder_dict.{key}",
1369
+ )
1370
+ for key in self.visual_losses
1371
+ }
1372
+ self.config = config
1373
+
1374
+ def call(self, hidden_states):
1375
+ hidden_states = self.transform(hidden_states)
1376
+ output = {}
1377
+ for key in self.visual_losses:
1378
+ output[key] = self.decoder_dict[key](hidden_states)
1379
+ return output
1380
+
1381
+ def build(self, input_shape=None):
1382
+ if self.built:
1383
+ return
1384
+ self.built = True
1385
+ if getattr(self, "transform", None) is not None:
1386
+ with tf.name_scope(self.transform.name):
1387
+ self.transform.build(None)
1388
+ if getattr(self, "decoder_dict", None) is not None:
1389
+ for layer in self.decoder_dict.values():
1390
+ with tf.name_scope(layer.name):
1391
+ layer.build([None, None, self.config.hidden_size])
1392
+
1393
+
1394
+ @add_start_docstrings("""Lxmert Model with a `language modeling` head on top.""", LXMERT_START_DOCSTRING)
1395
+ class TFLxmertForPreTraining(TFLxmertPreTrainedModel):
1396
+ def __init__(self, config, *inputs, **kwargs):
1397
+ super().__init__(config, *inputs, **kwargs)
1398
+
1399
+ self.config = config
1400
+ self.num_qa_labels = config.num_qa_labels
1401
+ self.visual_loss_normalizer = config.visual_loss_normalizer
1402
+
1403
+ # Use of pretraining tasks
1404
+ self.task_mask_lm = config.task_mask_lm
1405
+ self.task_obj_predict = config.task_obj_predict
1406
+ self.task_matched = config.task_matched
1407
+ self.task_qa = config.task_qa
1408
+
1409
+ # Lxmert backbone
1410
+ self.lxmert = TFLxmertMainLayer(config, name="lxmert")
1411
+
1412
+ # Pre-training heads
1413
+ self.cls = TFLxmertPreTrainingHeads(config, self.lxmert.embeddings, name="cls")
1414
+ if self.task_obj_predict:
1415
+ self.obj_predict_head = TFLxmertVisualObjHead(config, name="obj_predict_head")
1416
+ if self.task_qa:
1417
+ self.answer_head = TFLxmertVisualAnswerHead(config, self.num_qa_labels, name="answer_head")
1418
+
1419
+ # Loss functions
1420
+ self.loss_fcts = {
1421
+ "l2": keras.losses.Huber(delta=1.0, name="huber_loss"),
1422
+ "visn_ce": keras.losses.SparseCategoricalCrossentropy(from_logits=True),
1423
+ "ce": keras.losses.SparseCategoricalCrossentropy(from_logits=True),
1424
+ }
1425
+
1426
+ visual_losses = {}
1427
+ if config.visual_obj_loss:
1428
+ visual_losses["obj"] = {
1429
+ "shape": (-1,),
1430
+ "num": config.num_object_labels,
1431
+ "loss": "visn_ce",
1432
+ }
1433
+ if config.visual_attr_loss:
1434
+ visual_losses["attr"] = {
1435
+ "shape": (-1,),
1436
+ "num": config.num_attr_labels,
1437
+ "loss": "visn_ce",
1438
+ }
1439
+ if config.visual_feat_loss:
1440
+ visual_losses["feat"] = {
1441
+ "shape": (-1, config.visual_feat_dim),
1442
+ "num": config.visual_feat_dim,
1443
+ "loss": "l2",
1444
+ }
1445
+ self.visual_losses = visual_losses
1446
+
1447
+ @property
1448
+ def dummy_inputs(self):
1449
+ """
1450
+ Dummy inputs to build the network.
1451
+
1452
+ Returns:
1453
+ tf.Tensor with dummy inputs
1454
+ """
1455
+ batch_size = 2
1456
+ num_visual_features = 10
1457
+ input_ids = tf.constant([[3, 5, 6], [2, 3, 4]], dtype=tf.int32)
1458
+ visual_feats = tf.random.uniform((batch_size, num_visual_features, self.config.visual_feat_dim))
1459
+ visual_pos = tf.random.uniform((batch_size, num_visual_features, 4))
1460
+
1461
+ if self.config.task_obj_predict:
1462
+ obj_labels = {}
1463
+ if self.config.visual_attr_loss and self.config.task_obj_predict:
1464
+ obj_labels["attr"] = (
1465
+ tf.ones([batch_size, num_visual_features]),
1466
+ tf.ones([batch_size, num_visual_features]),
1467
+ )
1468
+ if self.config.visual_feat_loss and self.config.task_obj_predict:
1469
+ obj_labels["feat"] = (
1470
+ tf.ones([batch_size, num_visual_features, self.config.visual_feat_dim]),
1471
+ tf.ones([batch_size, num_visual_features]),
1472
+ )
1473
+ if self.config.visual_obj_loss and self.config.task_obj_predict:
1474
+ obj_labels["obj"] = (
1475
+ tf.ones([batch_size, num_visual_features]),
1476
+ tf.ones([batch_size, num_visual_features]),
1477
+ )
1478
+
1479
+ return {
1480
+ **{
1481
+ "input_ids": input_ids,
1482
+ "visual_feats": visual_feats,
1483
+ "visual_pos": visual_pos,
1484
+ },
1485
+ **({"obj_labels": obj_labels} if self.config.task_obj_predict else {}),
1486
+ }
1487
+
1488
+ def get_lm_head(self):
1489
+ return self.cls.predictions
1490
+
1491
+ def get_prefix_bias_name(self):
1492
+ warnings.warn("The method get_prefix_bias_name is deprecated. Please use `get_bias` instead.", FutureWarning)
1493
+ return self.name + "/" + self.cls.name + "/" + self.cls.predictions.name
1494
+
1495
+ @unpack_inputs
1496
+ @add_start_docstrings_to_model_forward(LXMERT_INPUTS_DOCSTRING)
1497
+ @replace_return_docstrings(output_type=TFLxmertForPreTrainingOutput, config_class=_CONFIG_FOR_DOC)
1498
+ def call(
1499
+ self,
1500
+ input_ids: TFModelInputType | None = None,
1501
+ visual_feats: tf.Tensor | None = None,
1502
+ visual_pos: tf.Tensor | None = None,
1503
+ attention_mask: tf.Tensor | None = None,
1504
+ visual_attention_mask: tf.Tensor | None = None,
1505
+ token_type_ids: tf.Tensor | None = None,
1506
+ inputs_embeds: tf.Tensor | None = None,
1507
+ masked_lm_labels: tf.Tensor | None = None,
1508
+ obj_labels: Dict[str, Tuple[tf.Tensor, tf.Tensor]] | None = None,
1509
+ matched_label: tf.Tensor | None = None,
1510
+ ans: tf.Tensor | None = None,
1511
+ output_attentions: bool | None = None,
1512
+ output_hidden_states: bool | None = None,
1513
+ return_dict: bool | None = None,
1514
+ training: bool = False,
1515
+ ) -> Tuple[tf.Tensor] | TFLxmertForPreTrainingOutput:
1516
+ r"""
1517
+ masked_lm_labels (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
1518
+ Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
1519
+ config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the
1520
+ loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
1521
+ obj_labels (`Dict[Str: Tuple[tf.Tensor, tf.Tensor]]`, *optional*, defaults to `None`):
1522
+ each key is named after each one of the visual losses and each element of the tuple is of the shape
1523
+ `(batch_size, num_features)` and `(batch_size, num_features, visual_feature_dim)` for each the label id and
1524
+ the label score respectively
1525
+ matched_label (`tf.Tensor` of shape `(batch_size,)`, *optional*):
1526
+ Labels for computing the whether or not the text input matches the image (classification) loss. Input
1527
+ should be a sequence pair (see `input_ids` docstring) Indices should be in `[0, 1]`:
1528
+
1529
+ - 0 indicates that the sentence does not match the image,
1530
+ - 1 indicates that the sentence does match the image.
1531
+ ans (`tf.Tensor` of shape `(batch_size)`, *optional*, defaults to `None`):
1532
+ a one hot representation hof the correct answer *optional*
1533
+
1534
+ Returns:
1535
+ """
1536
+
1537
+ lxmert_output = self.lxmert(
1538
+ input_ids,
1539
+ visual_feats,
1540
+ visual_pos,
1541
+ attention_mask,
1542
+ visual_attention_mask,
1543
+ token_type_ids,
1544
+ inputs_embeds,
1545
+ output_attentions,
1546
+ output_hidden_states,
1547
+ return_dict,
1548
+ training,
1549
+ )
1550
+
1551
+ lang_output, visual_output, pooled_output = (
1552
+ lxmert_output[0],
1553
+ lxmert_output[1],
1554
+ lxmert_output[2],
1555
+ )
1556
+ lang_prediction_scores, cross_relationship_score = self.cls(lang_output, pooled_output)
1557
+ if self.task_qa:
1558
+ answer_score = self.answer_head(pooled_output)
1559
+ else:
1560
+ answer_score = pooled_output[0][0]
1561
+
1562
+ total_loss = (
1563
+ None
1564
+ if (masked_lm_labels is None and matched_label is None and obj_labels is None and ans is None)
1565
+ else tf.constant(0.0)
1566
+ )
1567
+ losses = ()
1568
+ if masked_lm_labels is not None and self.task_mask_lm:
1569
+ masked_lm_loss = self.loss_fcts["ce"](
1570
+ tf.reshape(masked_lm_labels, [-1]),
1571
+ tf.reshape(lang_prediction_scores, [-1, self.config.vocab_size]),
1572
+ )
1573
+ total_loss += masked_lm_loss
1574
+ losses += (masked_lm_loss,)
1575
+ if matched_label is not None and self.task_matched:
1576
+ matched_loss = self.loss_fcts["ce"](
1577
+ tf.reshape(matched_label, [-1]),
1578
+ tf.reshape(cross_relationship_score, [-1, 2]),
1579
+ )
1580
+ total_loss += matched_loss
1581
+ losses += (matched_loss,)
1582
+ if obj_labels is not None and self.task_obj_predict:
1583
+ total_visn_loss = 0.0
1584
+ visn_prediction_scores_dict = self.obj_predict_head(visual_output)
1585
+ for key, key_info in self.visual_losses.items():
1586
+ label, mask_conf = obj_labels[key]
1587
+ output_dim = key_info["num"]
1588
+ loss_fct_name = key_info["loss"]
1589
+ label_shape = key_info["shape"]
1590
+ weight = self.visual_loss_normalizer
1591
+ visn_loss_fct = self.loss_fcts[loss_fct_name]
1592
+ visn_prediction_scores = visn_prediction_scores_dict[key]
1593
+ visn_loss = visn_loss_fct(
1594
+ tf.reshape(label, label_shape),
1595
+ tf.reshape(visn_prediction_scores, [-1, output_dim]),
1596
+ )
1597
+
1598
+ if visn_loss.ndim > 1: # Regression Losses
1599
+ visn_loss = tf.reduce_mean(visn_loss)
1600
+ visn_loss = tf.reduce_mean(visn_loss * tf.cast(tf.reshape(mask_conf, [-1]), visn_loss.dtype)) * weight
1601
+ total_visn_loss += visn_loss
1602
+ losses += (visn_loss,)
1603
+ total_loss += total_visn_loss
1604
+ if ans is not None and self.task_qa:
1605
+ answer_loss = self.loss_fcts["ce"](
1606
+ tf.reshape(ans, [-1]), tf.reshape(answer_score, [-1, self.num_qa_labels])
1607
+ )
1608
+ # exclude "*2" here to match the effect of QA losses.
1609
+ # Previous: (loss *0) for 6 epochs, (loss *2) for 6 epochs. (Used 10 instead of 6 in EMNLP paper)
1610
+ # Now : (loss *1) for 12 epochs
1611
+ #
1612
+ # * 2 # Multiply by 2 because > half of the data will not have label
1613
+ total_loss += answer_loss
1614
+ losses += (answer_loss,)
1615
+ # return total_loss, tf.stack(losses)[tf.new_axis, ...], answer_score.detach()
1616
+
1617
+ if not return_dict:
1618
+ output = (
1619
+ lang_prediction_scores,
1620
+ cross_relationship_score,
1621
+ answer_score,
1622
+ ) + lxmert_output[3:]
1623
+ return ((total_loss,) + output) if total_loss is not None else output
1624
+
1625
+ return TFLxmertForPreTrainingOutput(
1626
+ loss=total_loss,
1627
+ prediction_logits=lang_prediction_scores,
1628
+ cross_relationship_score=cross_relationship_score,
1629
+ question_answering_score=answer_score,
1630
+ language_hidden_states=lxmert_output.language_hidden_states,
1631
+ vision_hidden_states=lxmert_output.vision_hidden_states,
1632
+ language_attentions=lxmert_output.language_attentions,
1633
+ vision_attentions=lxmert_output.vision_attentions,
1634
+ cross_encoder_attentions=lxmert_output.cross_encoder_attentions,
1635
+ )
1636
+
1637
+ def build(self, input_shape=None):
1638
+ if self.built:
1639
+ return
1640
+ self.built = True
1641
+ if getattr(self, "lxmert", None) is not None:
1642
+ with tf.name_scope(self.lxmert.name):
1643
+ self.lxmert.build(None)
1644
+ if getattr(self, "cls", None) is not None:
1645
+ with tf.name_scope(self.cls.name):
1646
+ self.cls.build(None)
1647
+ if getattr(self, "obj_predict_head", None) is not None:
1648
+ with tf.name_scope(self.obj_predict_head.name):
1649
+ self.obj_predict_head.build(None)
1650
+ if getattr(self, "answer_head", None) is not None:
1651
+ with tf.name_scope(self.answer_head.name):
1652
+ self.answer_head.build(None)
1653
+
1654
+
1655
+ __all__ = [
1656
+ "TFLxmertForPreTraining",
1657
+ "TFLxmertMainLayer",
1658
+ "TFLxmertModel",
1659
+ "TFLxmertPreTrainedModel",
1660
+ "TFLxmertVisualFeatureEncoder",
1661
+ ]
tasks/tasksmith-441eeab80047/environment/source/src/transformers/models/lxmert/tokenization_lxmert.py ADDED
@@ -0,0 +1,511 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
30
+ # Copied from transformers.models.bert.tokenization_bert.load_vocab
31
+ def load_vocab(vocab_file):
32
+ """Loads a vocabulary file into a dictionary."""
33
+ vocab = collections.OrderedDict()
34
+ with open(vocab_file, "r", encoding="utf-8") as reader:
35
+ tokens = reader.readlines()
36
+ for index, token in enumerate(tokens):
37
+ token = token.rstrip("\n")
38
+ vocab[token] = index
39
+ return vocab
40
+
41
+
42
+ # Copied from transformers.models.bert.tokenization_bert.whitespace_tokenize
43
+ def whitespace_tokenize(text):
44
+ """Runs basic whitespace cleaning and splitting on a piece of text."""
45
+ text = text.strip()
46
+ if not text:
47
+ return []
48
+ tokens = text.split()
49
+ return tokens
50
+
51
+
52
+ # Copied from transformers.models.bert.tokenization_bert.BertTokenizer with bert-base-cased->unc-nlp/lxmert-base-uncased, BERT->Lxmert, BertTokenizer->LxmertTokenizer
53
+ class LxmertTokenizer(PreTrainedTokenizer):
54
+ r"""
55
+ Construct a Lxmert tokenizer. Based on WordPiece.
56
+
57
+ This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to
58
+ this superclass for more information regarding those methods.
59
+
60
+ Args:
61
+ vocab_file (`str`):
62
+ File containing the vocabulary.
63
+ do_lower_case (`bool`, *optional*, defaults to `True`):
64
+ Whether or not to lowercase the input when tokenizing.
65
+ do_basic_tokenize (`bool`, *optional*, defaults to `True`):
66
+ Whether or not to do basic tokenization before WordPiece.
67
+ never_split (`Iterable`, *optional*):
68
+ Collection of tokens which will never be split during tokenization. Only has an effect when
69
+ `do_basic_tokenize=True`
70
+ unk_token (`str`, *optional*, defaults to `"[UNK]"`):
71
+ The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
72
+ token instead.
73
+ sep_token (`str`, *optional*, defaults to `"[SEP]"`):
74
+ The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
75
+ sequence classification or for a text and a question for question answering. It is also used as the last
76
+ token of a sequence built with special tokens.
77
+ pad_token (`str`, *optional*, defaults to `"[PAD]"`):
78
+ The token used for padding, for example when batching sequences of different lengths.
79
+ cls_token (`str`, *optional*, defaults to `"[CLS]"`):
80
+ The classifier token which is used when doing sequence classification (classification of the whole sequence
81
+ instead of per-token classification). It is the first token of the sequence when built with special tokens.
82
+ mask_token (`str`, *optional*, defaults to `"[MASK]"`):
83
+ The token used for masking values. This is the token used when training this model with masked language
84
+ modeling. This is the token which the model will try to predict.
85
+ tokenize_chinese_chars (`bool`, *optional*, defaults to `True`):
86
+ Whether or not to tokenize Chinese characters.
87
+
88
+ This should likely be deactivated for Japanese (see this
89
+ [issue](https://github.com/huggingface/transformers/issues/328)).
90
+ strip_accents (`bool`, *optional*):
91
+ Whether or not to strip all accents. If this option is not specified, then it will be determined by the
92
+ value for `lowercase` (as in the original Lxmert).
93
+ clean_up_tokenization_spaces (`bool`, *optional*, defaults to `True`):
94
+ Whether or not to cleanup spaces after decoding, cleanup consists in removing potential artifacts like
95
+ extra spaces.
96
+ """
97
+
98
+ vocab_files_names = VOCAB_FILES_NAMES
99
+
100
+ def __init__(
101
+ self,
102
+ vocab_file,
103
+ do_lower_case=True,
104
+ do_basic_tokenize=True,
105
+ never_split=None,
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
+ clean_up_tokenization_spaces=True,
114
+ **kwargs,
115
+ ):
116
+ if not os.path.isfile(vocab_file):
117
+ raise ValueError(
118
+ f"Can't find a vocabulary file at path '{vocab_file}'. To load the vocabulary from a Google pretrained"
119
+ " model use `tokenizer = LxmertTokenizer.from_pretrained(PRETRAINED_MODEL_NAME)`"
120
+ )
121
+ self.vocab = load_vocab(vocab_file)
122
+ self.ids_to_tokens = collections.OrderedDict([(ids, tok) for tok, ids in self.vocab.items()])
123
+ self.do_basic_tokenize = do_basic_tokenize
124
+ if do_basic_tokenize:
125
+ self.basic_tokenizer = BasicTokenizer(
126
+ do_lower_case=do_lower_case,
127
+ never_split=never_split,
128
+ tokenize_chinese_chars=tokenize_chinese_chars,
129
+ strip_accents=strip_accents,
130
+ )
131
+
132
+ self.wordpiece_tokenizer = WordpieceTokenizer(vocab=self.vocab, unk_token=str(unk_token))
133
+
134
+ super().__init__(
135
+ do_lower_case=do_lower_case,
136
+ do_basic_tokenize=do_basic_tokenize,
137
+ never_split=never_split,
138
+ unk_token=unk_token,
139
+ sep_token=sep_token,
140
+ pad_token=pad_token,
141
+ cls_token=cls_token,
142
+ mask_token=mask_token,
143
+ tokenize_chinese_chars=tokenize_chinese_chars,
144
+ strip_accents=strip_accents,
145
+ clean_up_tokenization_spaces=clean_up_tokenization_spaces,
146
+ **kwargs,
147
+ )
148
+
149
+ @property
150
+ def do_lower_case(self):
151
+ return self.basic_tokenizer.do_lower_case
152
+
153
+ @property
154
+ def vocab_size(self):
155
+ return len(self.vocab)
156
+
157
+ def get_vocab(self):
158
+ return dict(self.vocab, **self.added_tokens_encoder)
159
+
160
+ def _tokenize(self, text, split_special_tokens=False):
161
+ split_tokens = []
162
+ if self.do_basic_tokenize:
163
+ for token in self.basic_tokenizer.tokenize(
164
+ text, never_split=self.all_special_tokens if not split_special_tokens else None
165
+ ):
166
+ # If the token is part of the never_split set
167
+ if token in self.basic_tokenizer.never_split:
168
+ split_tokens.append(token)
169
+ else:
170
+ split_tokens += self.wordpiece_tokenizer.tokenize(token)
171
+ else:
172
+ split_tokens = self.wordpiece_tokenizer.tokenize(text)
173
+ return split_tokens
174
+
175
+ def _convert_token_to_id(self, token):
176
+ """Converts a token (str) in an id using the vocab."""
177
+ return self.vocab.get(token, self.vocab.get(self.unk_token))
178
+
179
+ def _convert_id_to_token(self, index):
180
+ """Converts an index (integer) in a token (str) using the vocab."""
181
+ return self.ids_to_tokens.get(index, self.unk_token)
182
+
183
+ def convert_tokens_to_string(self, tokens):
184
+ """Converts a sequence of tokens (string) in a single string."""
185
+ out_string = " ".join(tokens).replace(" ##", "").strip()
186
+ return out_string
187
+
188
+ def build_inputs_with_special_tokens(
189
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
190
+ ) -> List[int]:
191
+ """
192
+ Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
193
+ adding special tokens. A Lxmert sequence has the following format:
194
+
195
+ - single sequence: `[CLS] X [SEP]`
196
+ - pair of sequences: `[CLS] A [SEP] B [SEP]`
197
+
198
+ Args:
199
+ token_ids_0 (`List[int]`):
200
+ List of IDs to which the special tokens will be added.
201
+ token_ids_1 (`List[int]`, *optional*):
202
+ Optional second list of IDs for sequence pairs.
203
+
204
+ Returns:
205
+ `List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
206
+ """
207
+ if token_ids_1 is None:
208
+ return [self.cls_token_id] + token_ids_0 + [self.sep_token_id]
209
+ cls = [self.cls_token_id]
210
+ sep = [self.sep_token_id]
211
+ return cls + token_ids_0 + sep + token_ids_1 + sep
212
+
213
+ def get_special_tokens_mask(
214
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None, already_has_special_tokens: bool = False
215
+ ) -> List[int]:
216
+ """
217
+ Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
218
+ special tokens using the tokenizer `prepare_for_model` method.
219
+
220
+ Args:
221
+ token_ids_0 (`List[int]`):
222
+ List of IDs.
223
+ token_ids_1 (`List[int]`, *optional*):
224
+ Optional second list of IDs for sequence pairs.
225
+ already_has_special_tokens (`bool`, *optional*, defaults to `False`):
226
+ Whether or not the token list is already formatted with special tokens for the model.
227
+
228
+ Returns:
229
+ `List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
230
+ """
231
+
232
+ if already_has_special_tokens:
233
+ return super().get_special_tokens_mask(
234
+ token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
235
+ )
236
+
237
+ if token_ids_1 is not None:
238
+ return [1] + ([0] * len(token_ids_0)) + [1] + ([0] * len(token_ids_1)) + [1]
239
+ return [1] + ([0] * len(token_ids_0)) + [1]
240
+
241
+ def create_token_type_ids_from_sequences(
242
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
243
+ ) -> List[int]:
244
+ """
245
+ Create a mask from the two sequences passed to be used in a sequence-pair classification task. A Lxmert sequence
246
+ pair mask has the following format:
247
+
248
+ ```
249
+ 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1
250
+ | first sequence | second sequence |
251
+ ```
252
+
253
+ If `token_ids_1` is `None`, this method only returns the first portion of the mask (0s).
254
+
255
+ Args:
256
+ token_ids_0 (`List[int]`):
257
+ List of IDs.
258
+ token_ids_1 (`List[int]`, *optional*):
259
+ Optional second list of IDs for sequence pairs.
260
+
261
+ Returns:
262
+ `List[int]`: List of [token type IDs](../glossary#token-type-ids) according to the given sequence(s).
263
+ """
264
+ sep = [self.sep_token_id]
265
+ cls = [self.cls_token_id]
266
+ if token_ids_1 is None:
267
+ return len(cls + token_ids_0 + sep) * [0]
268
+ return len(cls + token_ids_0 + sep) * [0] + len(token_ids_1 + sep) * [1]
269
+
270
+ def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
271
+ index = 0
272
+ if os.path.isdir(save_directory):
273
+ vocab_file = os.path.join(
274
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
275
+ )
276
+ else:
277
+ vocab_file = (filename_prefix + "-" if filename_prefix else "") + save_directory
278
+ with open(vocab_file, "w", encoding="utf-8") as writer:
279
+ for token, token_index in sorted(self.vocab.items(), key=lambda kv: kv[1]):
280
+ if index != token_index:
281
+ logger.warning(
282
+ f"Saving vocabulary to {vocab_file}: vocabulary indices are not consecutive."
283
+ " Please check that the vocabulary is not corrupted!"
284
+ )
285
+ index = token_index
286
+ writer.write(token + "\n")
287
+ index += 1
288
+ return (vocab_file,)
289
+
290
+
291
+ # Copied from transformers.models.bert.tokenization_bert.BasicTokenizer
292
+ class BasicTokenizer:
293
+ """
294
+ Constructs a BasicTokenizer that will run basic tokenization (punctuation splitting, lower casing, etc.).
295
+
296
+ Args:
297
+ do_lower_case (`bool`, *optional*, defaults to `True`):
298
+ Whether or not to lowercase the input when tokenizing.
299
+ never_split (`Iterable`, *optional*):
300
+ Collection of tokens which will never be split during tokenization. Only has an effect when
301
+ `do_basic_tokenize=True`
302
+ tokenize_chinese_chars (`bool`, *optional*, defaults to `True`):
303
+ Whether or not to tokenize Chinese characters.
304
+
305
+ This should likely be deactivated for Japanese (see this
306
+ [issue](https://github.com/huggingface/transformers/issues/328)).
307
+ strip_accents (`bool`, *optional*):
308
+ Whether or not to strip all accents. If this option is not specified, then it will be determined by the
309
+ value for `lowercase` (as in the original BERT).
310
+ do_split_on_punc (`bool`, *optional*, defaults to `True`):
311
+ In some instances we want to skip the basic punctuation splitting so that later tokenization can capture
312
+ the full context of the words, such as contractions.
313
+ """
314
+
315
+ def __init__(
316
+ self,
317
+ do_lower_case=True,
318
+ never_split=None,
319
+ tokenize_chinese_chars=True,
320
+ strip_accents=None,
321
+ do_split_on_punc=True,
322
+ ):
323
+ if never_split is None:
324
+ never_split = []
325
+ self.do_lower_case = do_lower_case
326
+ self.never_split = set(never_split)
327
+ self.tokenize_chinese_chars = tokenize_chinese_chars
328
+ self.strip_accents = strip_accents
329
+ self.do_split_on_punc = do_split_on_punc
330
+
331
+ def tokenize(self, text, never_split=None):
332
+ """
333
+ Basic Tokenization of a piece of text. For sub-word tokenization, see WordPieceTokenizer.
334
+
335
+ Args:
336
+ never_split (`List[str]`, *optional*)
337
+ Kept for backward compatibility purposes. Now implemented directly at the base class level (see
338
+ [`PreTrainedTokenizer.tokenize`]) List of token not to split.
339
+ """
340
+ # union() returns a new set by concatenating the two sets.
341
+ never_split = self.never_split.union(set(never_split)) if never_split else self.never_split
342
+ text = self._clean_text(text)
343
+
344
+ # This was added on November 1st, 2018 for the multilingual and Chinese
345
+ # models. This is also applied to the English models now, but it doesn't
346
+ # matter since the English models were not trained on any Chinese data
347
+ # and generally don't have any Chinese data in them (there are Chinese
348
+ # characters in the vocabulary because Wikipedia does have some Chinese
349
+ # words in the English Wikipedia.).
350
+ if self.tokenize_chinese_chars:
351
+ text = self._tokenize_chinese_chars(text)
352
+ # prevents treating the same character with different unicode codepoints as different characters
353
+ unicode_normalized_text = unicodedata.normalize("NFC", text)
354
+ orig_tokens = whitespace_tokenize(unicode_normalized_text)
355
+ split_tokens = []
356
+ for token in orig_tokens:
357
+ if token not in never_split:
358
+ if self.do_lower_case:
359
+ token = token.lower()
360
+ if self.strip_accents is not False:
361
+ token = self._run_strip_accents(token)
362
+ elif self.strip_accents:
363
+ token = self._run_strip_accents(token)
364
+ split_tokens.extend(self._run_split_on_punc(token, never_split))
365
+
366
+ output_tokens = whitespace_tokenize(" ".join(split_tokens))
367
+ return output_tokens
368
+
369
+ def _run_strip_accents(self, text):
370
+ """Strips accents from a piece of text."""
371
+ text = unicodedata.normalize("NFD", text)
372
+ output = []
373
+ for char in text:
374
+ cat = unicodedata.category(char)
375
+ if cat == "Mn":
376
+ continue
377
+ output.append(char)
378
+ return "".join(output)
379
+
380
+ def _run_split_on_punc(self, text, never_split=None):
381
+ """Splits punctuation on a piece of text."""
382
+ if not self.do_split_on_punc or (never_split is not None and text in never_split):
383
+ return [text]
384
+ chars = list(text)
385
+ i = 0
386
+ start_new_word = True
387
+ output = []
388
+ while i < len(chars):
389
+ char = chars[i]
390
+ if _is_punctuation(char):
391
+ output.append([char])
392
+ start_new_word = True
393
+ else:
394
+ if start_new_word:
395
+ output.append([])
396
+ start_new_word = False
397
+ output[-1].append(char)
398
+ i += 1
399
+
400
+ return ["".join(x) for x in output]
401
+
402
+ def _tokenize_chinese_chars(self, text):
403
+ """Adds whitespace around any CJK character."""
404
+ output = []
405
+ for char in text:
406
+ cp = ord(char)
407
+ if self._is_chinese_char(cp):
408
+ output.append(" ")
409
+ output.append(char)
410
+ output.append(" ")
411
+ else:
412
+ output.append(char)
413
+ return "".join(output)
414
+
415
+ def _is_chinese_char(self, cp):
416
+ """Checks whether CP is the codepoint of a CJK character."""
417
+ # This defines a "chinese character" as anything in the CJK Unicode block:
418
+ # https://en.wikipedia.org/wiki/CJK_Unified_Ideographs_(Unicode_block)
419
+ #
420
+ # Note that the CJK Unicode block is NOT all Japanese and Korean characters,
421
+ # despite its name. The modern Korean Hangul alphabet is a different block,
422
+ # as is Japanese Hiragana and Katakana. Those alphabets are used to write
423
+ # space-separated words, so they are not treated specially and handled
424
+ # like the all of the other languages.
425
+ if (
426
+ (cp >= 0x4E00 and cp <= 0x9FFF)
427
+ or (cp >= 0x3400 and cp <= 0x4DBF) #
428
+ or (cp >= 0x20000 and cp <= 0x2A6DF) #
429
+ or (cp >= 0x2A700 and cp <= 0x2B73F) #
430
+ or (cp >= 0x2B740 and cp <= 0x2B81F) #
431
+ or (cp >= 0x2B820 and cp <= 0x2CEAF) #
432
+ or (cp >= 0xF900 and cp <= 0xFAFF)
433
+ or (cp >= 0x2F800 and cp <= 0x2FA1F) #
434
+ ): #
435
+ return True
436
+
437
+ return False
438
+
439
+ def _clean_text(self, text):
440
+ """Performs invalid character removal and whitespace cleanup on text."""
441
+ output = []
442
+ for char in text:
443
+ cp = ord(char)
444
+ if cp == 0 or cp == 0xFFFD or _is_control(char):
445
+ continue
446
+ if _is_whitespace(char):
447
+ output.append(" ")
448
+ else:
449
+ output.append(char)
450
+ return "".join(output)
451
+
452
+
453
+ # Copied from transformers.models.bert.tokenization_bert.WordpieceTokenizer
454
+ class WordpieceTokenizer:
455
+ """Runs WordPiece tokenization."""
456
+
457
+ def __init__(self, vocab, unk_token, max_input_chars_per_word=100):
458
+ self.vocab = vocab
459
+ self.unk_token = unk_token
460
+ self.max_input_chars_per_word = max_input_chars_per_word
461
+
462
+ def tokenize(self, text):
463
+ """
464
+ Tokenizes a piece of text into its word pieces. This uses a greedy longest-match-first algorithm to perform
465
+ tokenization using the given vocabulary.
466
+
467
+ For example, `input = "unaffable"` wil return as output `["un", "##aff", "##able"]`.
468
+
469
+ Args:
470
+ text: A single token or whitespace separated tokens. This should have
471
+ already been passed through *BasicTokenizer*.
472
+
473
+ Returns:
474
+ A list of wordpiece tokens.
475
+ """
476
+
477
+ output_tokens = []
478
+ for token in whitespace_tokenize(text):
479
+ chars = list(token)
480
+ if len(chars) > self.max_input_chars_per_word:
481
+ output_tokens.append(self.unk_token)
482
+ continue
483
+
484
+ is_bad = False
485
+ start = 0
486
+ sub_tokens = []
487
+ while start < len(chars):
488
+ end = len(chars)
489
+ cur_substr = None
490
+ while start < end:
491
+ substr = "".join(chars[start:end])
492
+ if start > 0:
493
+ substr = "##" + substr
494
+ if substr in self.vocab:
495
+ cur_substr = substr
496
+ break
497
+ end -= 1
498
+ if cur_substr is None:
499
+ is_bad = True
500
+ break
501
+ sub_tokens.append(cur_substr)
502
+ start = end
503
+
504
+ if is_bad:
505
+ output_tokens.append(self.unk_token)
506
+ else:
507
+ output_tokens.extend(sub_tokens)
508
+ return output_tokens
509
+
510
+
511
+ __all__ = ["LxmertTokenizer"]
tasks/tasksmith-441eeab80047/environment/source/src/transformers/models/lxmert/tokenization_lxmert_fast.py ADDED
@@ -0,0 +1,172 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 json
17
+ from typing import List, Optional, Tuple
18
+
19
+ from tokenizers import normalizers
20
+
21
+ from ...tokenization_utils_fast import PreTrainedTokenizerFast
22
+ from .tokenization_lxmert import LxmertTokenizer
23
+
24
+
25
+ VOCAB_FILES_NAMES = {"vocab_file": "vocab.txt", "tokenizer_file": "tokenizer.json"}
26
+
27
+
28
+ # Copied from transformers.models.bert.tokenization_bert_fast.BertTokenizerFast with bert-base-cased->unc-nlp/lxmert-base-uncased, BERT->Lxmert, Bert->Lxmert
29
+ class LxmertTokenizerFast(PreTrainedTokenizerFast):
30
+ r"""
31
+ Construct a "fast" Lxmert tokenizer (backed by HuggingFace's *tokenizers* library). Based on WordPiece.
32
+
33
+ This tokenizer inherits from [`PreTrainedTokenizerFast`] which contains most of the main methods. Users should
34
+ refer to this superclass for more information regarding those methods.
35
+
36
+ Args:
37
+ vocab_file (`str`):
38
+ File containing the vocabulary.
39
+ do_lower_case (`bool`, *optional*, defaults to `True`):
40
+ Whether or not to lowercase the input when tokenizing.
41
+ unk_token (`str`, *optional*, defaults to `"[UNK]"`):
42
+ The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
43
+ token instead.
44
+ sep_token (`str`, *optional*, defaults to `"[SEP]"`):
45
+ The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
46
+ sequence classification or for a text and a question for question answering. It is also used as the last
47
+ token of a sequence built with special tokens.
48
+ pad_token (`str`, *optional*, defaults to `"[PAD]"`):
49
+ The token used for padding, for example when batching sequences of different lengths.
50
+ cls_token (`str`, *optional*, defaults to `"[CLS]"`):
51
+ The classifier token which is used when doing sequence classification (classification of the whole sequence
52
+ instead of per-token classification). It is the first token of the sequence when built with special tokens.
53
+ mask_token (`str`, *optional*, defaults to `"[MASK]"`):
54
+ The token used for masking values. This is the token used when training this model with masked language
55
+ modeling. This is the token which the model will try to predict.
56
+ clean_text (`bool`, *optional*, defaults to `True`):
57
+ Whether or not to clean the text before tokenization by removing any control characters and replacing all
58
+ whitespaces by the classic one.
59
+ tokenize_chinese_chars (`bool`, *optional*, defaults to `True`):
60
+ Whether or not to tokenize Chinese characters. This should likely be deactivated for Japanese (see [this
61
+ issue](https://github.com/huggingface/transformers/issues/328)).
62
+ strip_accents (`bool`, *optional*):
63
+ Whether or not to strip all accents. If this option is not specified, then it will be determined by the
64
+ value for `lowercase` (as in the original Lxmert).
65
+ wordpieces_prefix (`str`, *optional*, defaults to `"##"`):
66
+ The prefix for subwords.
67
+ """
68
+
69
+ vocab_files_names = VOCAB_FILES_NAMES
70
+ slow_tokenizer_class = LxmertTokenizer
71
+
72
+ def __init__(
73
+ self,
74
+ vocab_file=None,
75
+ tokenizer_file=None,
76
+ do_lower_case=True,
77
+ unk_token="[UNK]",
78
+ sep_token="[SEP]",
79
+ pad_token="[PAD]",
80
+ cls_token="[CLS]",
81
+ mask_token="[MASK]",
82
+ tokenize_chinese_chars=True,
83
+ strip_accents=None,
84
+ **kwargs,
85
+ ):
86
+ super().__init__(
87
+ vocab_file,
88
+ tokenizer_file=tokenizer_file,
89
+ do_lower_case=do_lower_case,
90
+ unk_token=unk_token,
91
+ sep_token=sep_token,
92
+ pad_token=pad_token,
93
+ cls_token=cls_token,
94
+ mask_token=mask_token,
95
+ tokenize_chinese_chars=tokenize_chinese_chars,
96
+ strip_accents=strip_accents,
97
+ **kwargs,
98
+ )
99
+
100
+ normalizer_state = json.loads(self.backend_tokenizer.normalizer.__getstate__())
101
+ if (
102
+ normalizer_state.get("lowercase", do_lower_case) != do_lower_case
103
+ or normalizer_state.get("strip_accents", strip_accents) != strip_accents
104
+ or normalizer_state.get("handle_chinese_chars", tokenize_chinese_chars) != tokenize_chinese_chars
105
+ ):
106
+ normalizer_class = getattr(normalizers, normalizer_state.pop("type"))
107
+ normalizer_state["lowercase"] = do_lower_case
108
+ normalizer_state["strip_accents"] = strip_accents
109
+ normalizer_state["handle_chinese_chars"] = tokenize_chinese_chars
110
+ self.backend_tokenizer.normalizer = normalizer_class(**normalizer_state)
111
+
112
+ self.do_lower_case = do_lower_case
113
+
114
+ def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None):
115
+ """
116
+ Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
117
+ adding special tokens. A Lxmert sequence has the following format:
118
+
119
+ - single sequence: `[CLS] X [SEP]`
120
+ - pair of sequences: `[CLS] A [SEP] B [SEP]`
121
+
122
+ Args:
123
+ token_ids_0 (`List[int]`):
124
+ List of IDs to which the special tokens will be added.
125
+ token_ids_1 (`List[int]`, *optional*):
126
+ Optional second list of IDs for sequence pairs.
127
+
128
+ Returns:
129
+ `List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
130
+ """
131
+ output = [self.cls_token_id] + token_ids_0 + [self.sep_token_id]
132
+
133
+ if token_ids_1 is not None:
134
+ output += token_ids_1 + [self.sep_token_id]
135
+
136
+ return output
137
+
138
+ def create_token_type_ids_from_sequences(
139
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
140
+ ) -> List[int]:
141
+ """
142
+ Create a mask from the two sequences passed to be used in a sequence-pair classification task. A Lxmert sequence
143
+ pair mask has the following format:
144
+
145
+ ```
146
+ 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1
147
+ | first sequence | second sequence |
148
+ ```
149
+
150
+ If `token_ids_1` is `None`, this method only returns the first portion of the mask (0s).
151
+
152
+ Args:
153
+ token_ids_0 (`List[int]`):
154
+ List of IDs.
155
+ token_ids_1 (`List[int]`, *optional*):
156
+ Optional second list of IDs for sequence pairs.
157
+
158
+ Returns:
159
+ `List[int]`: List of [token type IDs](../glossary#token-type-ids) according to the given sequence(s).
160
+ """
161
+ sep = [self.sep_token_id]
162
+ cls = [self.cls_token_id]
163
+ if token_ids_1 is None:
164
+ return len(cls + token_ids_0 + sep) * [0]
165
+ return len(cls + token_ids_0 + sep) * [0] + len(token_ids_1 + sep) * [1]
166
+
167
+ def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
168
+ files = self._tokenizer.model.save(save_directory, name=filename_prefix)
169
+ return tuple(files)
170
+
171
+
172
+ __all__ = ["LxmertTokenizerFast"]
tasks/tasksmith-441eeab80047/environment/source/src/transformers/models/m2m_100/__init__.py ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 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 _LazyModule
17
+ from ...utils.import_utils import define_import_structure
18
+
19
+
20
+ if TYPE_CHECKING:
21
+ from .configuration_m2m_100 import *
22
+ from .modeling_m2m_100 import *
23
+ from .tokenization_m2m_100 import *
24
+ else:
25
+ import sys
26
+
27
+ _file = globals()["__file__"]
28
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
tasks/tasksmith-441eeab80047/environment/source/src/transformers/models/m2m_100/configuration_m2m_100.py ADDED
@@ -0,0 +1,283 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2021 The Fairseq Authors and The HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """M2M100 model configuration"""
16
+
17
+ from collections import OrderedDict
18
+ from typing import Any, Mapping, Optional
19
+
20
+ from ... import PreTrainedTokenizer
21
+ from ...configuration_utils import PretrainedConfig
22
+ from ...onnx import OnnxConfig, OnnxSeq2SeqConfigWithPast
23
+ from ...onnx.utils import compute_effective_axis_dimension
24
+ from ...utils import TensorType, is_torch_available, logging
25
+
26
+
27
+ logger = logging.get_logger(__name__)
28
+
29
+
30
+ class M2M100Config(PretrainedConfig):
31
+ r"""
32
+ This is the configuration class to store the configuration of a [`M2M100Model`]. It is used to instantiate an
33
+ M2M100 model according to the specified arguments, defining the model architecture. Instantiating a configuration
34
+ with the defaults will yield a similar configuration to that of the M2M100
35
+ [facebook/m2m100_418M](https://huggingface.co/facebook/m2m100_418M) architecture.
36
+
37
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
38
+ documentation from [`PretrainedConfig`] for more information.
39
+
40
+
41
+ Args:
42
+ vocab_size (`int`, *optional*, defaults to 50265):
43
+ Vocabulary size of the M2M100 model. Defines the number of different tokens that can be represented by the
44
+ `inputs_ids` passed when calling [`M2M100Model`] or
45
+ d_model (`int`, *optional*, defaults to 1024):
46
+ Dimensionality of the layers and the pooler layer.
47
+ encoder_layers (`int`, *optional*, defaults to 12):
48
+ Number of encoder layers.
49
+ decoder_layers (`int`, *optional*, defaults to 12):
50
+ Number of decoder layers.
51
+ encoder_attention_heads (`int`, *optional*, defaults to 16):
52
+ Number of attention heads for each attention layer in the Transformer encoder.
53
+ decoder_attention_heads (`int`, *optional*, defaults to 16):
54
+ Number of attention heads for each attention layer in the Transformer decoder.
55
+ decoder_ffn_dim (`int`, *optional*, defaults to 4096):
56
+ Dimensionality of the "intermediate" (often named feed-forward) layer in decoder.
57
+ encoder_ffn_dim (`int`, *optional*, defaults to 4096):
58
+ Dimensionality of the "intermediate" (often named feed-forward) layer in decoder.
59
+ activation_function (`str` or `function`, *optional*, defaults to `"gelu"`):
60
+ The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
61
+ `"relu"`, `"silu"` and `"gelu_new"` are supported.
62
+ dropout (`float`, *optional*, defaults to 0.1):
63
+ The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
64
+ attention_dropout (`float`, *optional*, defaults to 0.0):
65
+ The dropout ratio for the attention probabilities.
66
+ activation_dropout (`float`, *optional*, defaults to 0.0):
67
+ The dropout ratio for activations inside the fully connected layer.
68
+ classifier_dropout (`float`, *optional*, defaults to 0.0):
69
+ The dropout ratio for classifier.
70
+ max_position_embeddings (`int`, *optional*, defaults to 1024):
71
+ The maximum sequence length that this model might ever be used with. Typically set this to something large
72
+ just in case (e.g., 512 or 1024 or 2048).
73
+ init_std (`float`, *optional*, defaults to 0.02):
74
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
75
+ encoder_layerdrop (`float`, *optional*, defaults to 0.0):
76
+ The LayerDrop probability for the encoder. See the [LayerDrop paper](see https://arxiv.org/abs/1909.11556)
77
+ for more details.
78
+ decoder_layerdrop (`float`, *optional*, defaults to 0.0):
79
+ The LayerDrop probability for the decoder. See the [LayerDrop paper](see https://arxiv.org/abs/1909.11556)
80
+ for more details.
81
+ use_cache (`bool`, *optional*, defaults to `True`):
82
+ Whether or not the model should return the last key/values attentions (not used by all models).
83
+
84
+ Example:
85
+
86
+ ```python
87
+ >>> from transformers import M2M100Config, M2M100Model
88
+
89
+ >>> # Initializing a M2M100 facebook/m2m100_418M style configuration
90
+ >>> configuration = M2M100Config()
91
+
92
+ >>> # Initializing a model (with random weights) from the facebook/m2m100_418M style configuration
93
+ >>> model = M2M100Model(configuration)
94
+
95
+ >>> # Accessing the model configuration
96
+ >>> configuration = model.config
97
+ ```"""
98
+
99
+ model_type = "m2m_100"
100
+ keys_to_ignore_at_inference = ["past_key_values"]
101
+ attribute_map = {"num_attention_heads": "encoder_attention_heads", "hidden_size": "d_model"}
102
+
103
+ def __init__(
104
+ self,
105
+ vocab_size=128112,
106
+ max_position_embeddings=1024,
107
+ encoder_layers=12,
108
+ encoder_ffn_dim=4096,
109
+ encoder_attention_heads=16,
110
+ decoder_layers=12,
111
+ decoder_ffn_dim=4096,
112
+ decoder_attention_heads=16,
113
+ encoder_layerdrop=0.05,
114
+ decoder_layerdrop=0.05,
115
+ use_cache=True,
116
+ is_encoder_decoder=True,
117
+ activation_function="relu",
118
+ d_model=1024,
119
+ dropout=0.1,
120
+ attention_dropout=0.1,
121
+ activation_dropout=0.0,
122
+ init_std=0.02,
123
+ decoder_start_token_id=2,
124
+ scale_embedding=True,
125
+ pad_token_id=1,
126
+ bos_token_id=0,
127
+ eos_token_id=2,
128
+ **kwargs,
129
+ ):
130
+ self.vocab_size = vocab_size
131
+ self.max_position_embeddings = max_position_embeddings
132
+ self.d_model = d_model
133
+ self.encoder_ffn_dim = encoder_ffn_dim
134
+ self.encoder_layers = encoder_layers
135
+ self.encoder_attention_heads = encoder_attention_heads
136
+ self.decoder_ffn_dim = decoder_ffn_dim
137
+ self.decoder_layers = decoder_layers
138
+ self.decoder_attention_heads = decoder_attention_heads
139
+ self.dropout = dropout
140
+ self.attention_dropout = attention_dropout
141
+ self.activation_dropout = activation_dropout
142
+ self.activation_function = activation_function
143
+ self.init_std = init_std
144
+ self.encoder_layerdrop = encoder_layerdrop
145
+ self.decoder_layerdrop = decoder_layerdrop
146
+ self.use_cache = use_cache
147
+ self.num_hidden_layers = encoder_layers
148
+ self.scale_embedding = scale_embedding # scale factor will be sqrt(d_model) if True
149
+
150
+ super().__init__(
151
+ pad_token_id=pad_token_id,
152
+ bos_token_id=bos_token_id,
153
+ eos_token_id=eos_token_id,
154
+ is_encoder_decoder=is_encoder_decoder,
155
+ decoder_start_token_id=decoder_start_token_id,
156
+ **kwargs,
157
+ )
158
+
159
+
160
+ class M2M100OnnxConfig(OnnxSeq2SeqConfigWithPast):
161
+ @property
162
+ def inputs(self) -> Mapping[str, Mapping[int, str]]:
163
+ common_inputs = OrderedDict(
164
+ [
165
+ ("input_ids", {0: "batch", 1: "encoder_sequence"}),
166
+ ("attention_mask", {0: "batch", 1: "encoder_sequence"}),
167
+ ]
168
+ )
169
+
170
+ if self.use_past:
171
+ common_inputs["decoder_input_ids"] = {0: "batch"}
172
+ common_inputs["decoder_attention_mask"] = {0: "batch", 1: "past_decoder_sequence + sequence"}
173
+ else:
174
+ common_inputs["decoder_input_ids"] = {0: "batch", 1: "decoder_sequence"}
175
+ common_inputs["decoder_attention_mask"] = {0: "batch", 1: "decoder_sequence"}
176
+
177
+ if self.use_past:
178
+ self.fill_with_past_key_values_(common_inputs, direction="inputs")
179
+ return common_inputs
180
+
181
+ # Copied from BartOnnxConfig._generate_dummy_inputs_for_sequence_classification_and_question_answering
182
+ # A better name would be _generate_dummy_inputs_for_encoder_and_decoder because sequence classification and question
183
+ # answering are not supported for M2M100, but this name is preserved to be able to check that the copy matches what
184
+ # was done for BART so that it can be updated if need be.
185
+ def _generate_dummy_inputs_for_sequence_classification_and_question_answering(
186
+ self,
187
+ tokenizer: PreTrainedTokenizer,
188
+ batch_size: int = -1,
189
+ seq_length: int = -1,
190
+ is_pair: bool = False,
191
+ framework: Optional[TensorType] = None,
192
+ ) -> Mapping[str, Any]:
193
+ # Copied from OnnxConfig.generate_dummy_inputs
194
+ # Did not use super(OnnxConfigWithPast, self).generate_dummy_inputs for code clarity.
195
+ # If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX
196
+ batch_size = compute_effective_axis_dimension(
197
+ batch_size, fixed_dimension=OnnxConfig.default_fixed_batch, num_token_to_add=0
198
+ )
199
+
200
+ # If dynamic axis (-1) we forward with a fixed dimension of 8 tokens to avoid optimizations made by ONNX
201
+ token_to_add = tokenizer.num_special_tokens_to_add(is_pair)
202
+ seq_length = compute_effective_axis_dimension(
203
+ seq_length, fixed_dimension=OnnxConfig.default_fixed_sequence, num_token_to_add=token_to_add
204
+ )
205
+
206
+ # Generate dummy inputs according to compute batch and sequence
207
+ dummy_input = [" ".join([tokenizer.unk_token]) * seq_length] * batch_size
208
+ common_inputs = dict(tokenizer(dummy_input, return_tensors=framework))
209
+ return common_inputs
210
+
211
+ # Copied from transformers.models.bart.configuration_bart.BartOnnxConfig._generate_dummy_inputs_for_default_and_seq2seq_lm
212
+ def _generate_dummy_inputs_for_default_and_seq2seq_lm(
213
+ self,
214
+ tokenizer: PreTrainedTokenizer,
215
+ batch_size: int = -1,
216
+ seq_length: int = -1,
217
+ is_pair: bool = False,
218
+ framework: Optional[TensorType] = None,
219
+ ) -> Mapping[str, Any]:
220
+ encoder_inputs = self._generate_dummy_inputs_for_sequence_classification_and_question_answering(
221
+ tokenizer, batch_size, seq_length, is_pair, framework
222
+ )
223
+
224
+ # Generate decoder inputs
225
+ decoder_seq_length = seq_length if not self.use_past else 1
226
+ decoder_inputs = self._generate_dummy_inputs_for_sequence_classification_and_question_answering(
227
+ tokenizer, batch_size, decoder_seq_length, is_pair, framework
228
+ )
229
+ decoder_inputs = {f"decoder_{name}": tensor for name, tensor in decoder_inputs.items()}
230
+ common_inputs = dict(**encoder_inputs, **decoder_inputs)
231
+
232
+ if self.use_past:
233
+ if not is_torch_available():
234
+ raise ValueError("Cannot generate dummy past_keys inputs without PyTorch installed.")
235
+ else:
236
+ import torch
237
+ batch, encoder_seq_length = common_inputs["input_ids"].shape
238
+ decoder_seq_length = common_inputs["decoder_input_ids"].shape[1]
239
+ num_encoder_attention_heads, num_decoder_attention_heads = self.num_attention_heads
240
+ encoder_shape = (
241
+ batch,
242
+ num_encoder_attention_heads,
243
+ encoder_seq_length,
244
+ self._config.hidden_size // num_encoder_attention_heads,
245
+ )
246
+ decoder_past_length = decoder_seq_length + 3
247
+ decoder_shape = (
248
+ batch,
249
+ num_decoder_attention_heads,
250
+ decoder_past_length,
251
+ self._config.hidden_size // num_decoder_attention_heads,
252
+ )
253
+
254
+ common_inputs["decoder_attention_mask"] = torch.cat(
255
+ [common_inputs["decoder_attention_mask"], torch.ones(batch, decoder_past_length)], dim=1
256
+ )
257
+
258
+ common_inputs["past_key_values"] = []
259
+ # If the number of encoder and decoder layers are present in the model configuration, both are considered
260
+ num_encoder_layers, num_decoder_layers = self.num_layers
261
+ min_num_layers = min(num_encoder_layers, num_decoder_layers)
262
+ max_num_layers = max(num_encoder_layers, num_decoder_layers) - min_num_layers
263
+ remaining_side_name = "encoder" if num_encoder_layers > num_decoder_layers else "decoder"
264
+
265
+ for _ in range(min_num_layers):
266
+ common_inputs["past_key_values"].append(
267
+ (
268
+ torch.zeros(decoder_shape),
269
+ torch.zeros(decoder_shape),
270
+ torch.zeros(encoder_shape),
271
+ torch.zeros(encoder_shape),
272
+ )
273
+ )
274
+ # TODO: test this.
275
+ shape = encoder_shape if remaining_side_name == "encoder" else decoder_shape
276
+ for _ in range(min_num_layers, max_num_layers):
277
+ common_inputs["past_key_values"].append((torch.zeros(shape), torch.zeros(shape)))
278
+ return common_inputs
279
+
280
+ generate_dummy_inputs = _generate_dummy_inputs_for_default_and_seq2seq_lm
281
+
282
+
283
+ __all__ = ["M2M100Config", "M2M100OnnxConfig"]
tasks/tasksmith-441eeab80047/environment/source/src/transformers/models/m2m_100/convert_m2m100_original_checkpoint_to_pytorch.py ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2021 The Fairseq Authors and The HuggingFace Inc. 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
+ import argparse
16
+
17
+ import torch
18
+ from torch import nn
19
+
20
+ from transformers import M2M100Config, M2M100ForConditionalGeneration
21
+
22
+
23
+ def remove_ignore_keys_(state_dict):
24
+ ignore_keys = [
25
+ "encoder.version",
26
+ "decoder.version",
27
+ "model.encoder.version",
28
+ "model.decoder.version",
29
+ "decoder.output_projection.weight",
30
+ "_float_tensor",
31
+ "encoder.embed_positions._float_tensor",
32
+ "decoder.embed_positions._float_tensor",
33
+ ]
34
+ for k in ignore_keys:
35
+ state_dict.pop(k, None)
36
+
37
+
38
+ def make_linear_from_emb(emb):
39
+ vocab_size, emb_size = emb.weight.shape
40
+ lin_layer = nn.Linear(vocab_size, emb_size, bias=False)
41
+ lin_layer.weight.data = emb.weight.data
42
+ return lin_layer
43
+
44
+
45
+ def convert_fairseq_m2m100_checkpoint_from_disk(checkpoint_path):
46
+ m2m_100 = torch.load(checkpoint_path, map_location="cpu")
47
+ args = m2m_100["args"] or m2m_100["cfg"]["model"]
48
+ state_dict = m2m_100["model"]
49
+ remove_ignore_keys_(state_dict)
50
+ vocab_size = state_dict["encoder.embed_tokens.weight"].shape[0]
51
+
52
+ config = M2M100Config(
53
+ vocab_size=vocab_size,
54
+ max_position_embeddings=1024,
55
+ encoder_layers=args.encoder_layers,
56
+ decoder_layers=args.decoder_layers,
57
+ encoder_attention_heads=args.encoder_attention_heads,
58
+ decoder_attention_heads=args.decoder_attention_heads,
59
+ encoder_ffn_dim=args.encoder_ffn_embed_dim,
60
+ decoder_ffn_dim=args.decoder_ffn_embed_dim,
61
+ d_model=args.encoder_embed_dim,
62
+ encoder_layerdrop=args.encoder_layerdrop,
63
+ decoder_layerdrop=args.decoder_layerdrop,
64
+ dropout=args.dropout,
65
+ attention_dropout=args.attention_dropout,
66
+ activation_dropout=args.activation_dropout,
67
+ activation_function="relu",
68
+ )
69
+
70
+ state_dict["shared.weight"] = state_dict["decoder.embed_tokens.weight"]
71
+ model = M2M100ForConditionalGeneration(config)
72
+ model.model.load_state_dict(state_dict, strict=False)
73
+ model.lm_head = make_linear_from_emb(model.model.shared)
74
+
75
+ return model
76
+
77
+
78
+ if __name__ == "__main__":
79
+ parser = argparse.ArgumentParser()
80
+ # Required parameters
81
+ parser.add_argument("fairseq_path", type=str, help="path to a model.pt on local filesystem.")
82
+ parser.add_argument("pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model.")
83
+ args = parser.parse_args()
84
+ model = convert_fairseq_m2m100_checkpoint_from_disk(args.fairseq_pathß)
85
+ model.save_pretrained(args.pytorch_dump_folder_path)
tasks/tasksmith-441eeab80047/environment/source/src/transformers/models/m2m_100/modeling_m2m_100.py ADDED
@@ -0,0 +1,1633 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2021 The Fairseq Authors and The HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """PyTorch M2M100 model."""
16
+
17
+ import math
18
+ from typing import List, Optional, Tuple, Union
19
+
20
+ import torch
21
+ from torch import nn
22
+ from torch.nn import CrossEntropyLoss
23
+
24
+ from ...activations import ACT2FN
25
+ from ...generation import GenerationMixin
26
+ from ...integrations.deepspeed import is_deepspeed_zero3_enabled
27
+ from ...integrations.fsdp import is_fsdp_managed_module
28
+ from ...modeling_attn_mask_utils import (
29
+ _prepare_4d_attention_mask,
30
+ _prepare_4d_attention_mask_for_sdpa,
31
+ _prepare_4d_causal_attention_mask,
32
+ _prepare_4d_causal_attention_mask_for_sdpa,
33
+ )
34
+ from ...modeling_outputs import (
35
+ BaseModelOutput,
36
+ BaseModelOutputWithPastAndCrossAttentions,
37
+ Seq2SeqLMOutput,
38
+ Seq2SeqModelOutput,
39
+ )
40
+ from ...modeling_utils import PreTrainedModel
41
+ from ...utils import (
42
+ add_code_sample_docstrings,
43
+ add_end_docstrings,
44
+ add_start_docstrings,
45
+ add_start_docstrings_to_model_forward,
46
+ is_flash_attn_2_available,
47
+ is_flash_attn_greater_or_equal_2_10,
48
+ logging,
49
+ replace_return_docstrings,
50
+ )
51
+ from .configuration_m2m_100 import M2M100Config
52
+
53
+
54
+ if is_flash_attn_2_available():
55
+ from ...modeling_flash_attention_utils import _flash_attention_forward
56
+
57
+
58
+ logger = logging.get_logger(__name__)
59
+
60
+ _CONFIG_FOR_DOC = "M2M100Config"
61
+ _CHECKPOINT_FOR_DOC = "facebook/m2m100_418M"
62
+
63
+
64
+ # Copied from transformers.models.bart.modeling_bart.shift_tokens_right
65
+ def shift_tokens_right(input_ids: torch.Tensor, pad_token_id: int, decoder_start_token_id: int):
66
+ """
67
+ Shift input ids one token to the right.
68
+ """
69
+ shifted_input_ids = input_ids.new_zeros(input_ids.shape)
70
+ shifted_input_ids[:, 1:] = input_ids[:, :-1].clone()
71
+ shifted_input_ids[:, 0] = decoder_start_token_id
72
+
73
+ if pad_token_id is None:
74
+ raise ValueError("self.model.config.pad_token_id has to be defined.")
75
+ # replace possible -100 values in labels by `pad_token_id`
76
+ shifted_input_ids.masked_fill_(shifted_input_ids == -100, pad_token_id)
77
+
78
+ return shifted_input_ids
79
+
80
+
81
+ def create_position_ids_from_input_ids(input_ids, padding_idx, past_key_values_length=0):
82
+ """
83
+ Replace non-padding symbols with their position numbers. Position numbers begin at padding_idx+1. Padding symbols
84
+ are ignored. This is modified from fairseq's `utils.make_positions`.
85
+ """
86
+ # The series of casts and type-conversions here are carefully balanced to both work with ONNX export and XLA.
87
+ mask = input_ids.ne(padding_idx).int()
88
+ incremental_indices = (torch.cumsum(mask, dim=1).type_as(mask) + past_key_values_length) * mask
89
+ return incremental_indices.long() + padding_idx
90
+
91
+
92
+ # Copied from transformers.models.bart.modeling_bart.BartScaledWordEmbedding with Bart->M2M100
93
+ class M2M100ScaledWordEmbedding(nn.Embedding):
94
+ """
95
+ This module overrides nn.Embeddings' forward by multiplying with embeddings scale.
96
+ """
97
+
98
+ def __init__(self, num_embeddings: int, embedding_dim: int, padding_idx: int, embed_scale: Optional[float] = 1.0):
99
+ super().__init__(num_embeddings, embedding_dim, padding_idx)
100
+ self.embed_scale = embed_scale
101
+
102
+ def forward(self, input_ids: torch.Tensor):
103
+ return super().forward(input_ids) * self.embed_scale
104
+
105
+
106
+ class M2M100SinusoidalPositionalEmbedding(nn.Module):
107
+ """This module produces sinusoidal positional embeddings of any length."""
108
+
109
+ def __init__(self, num_positions: int, embedding_dim: int, padding_idx: Optional[int] = None):
110
+ super().__init__()
111
+ self.offset = 2
112
+ self.embedding_dim = embedding_dim
113
+ self.padding_idx = padding_idx
114
+ self.make_weights(num_positions + self.offset, embedding_dim, padding_idx)
115
+
116
+ def make_weights(self, num_embeddings: int, embedding_dim: int, padding_idx: Optional[int] = None):
117
+ emb_weights = self.get_embedding(num_embeddings, embedding_dim, padding_idx)
118
+ if hasattr(self, "weights"):
119
+ # in forward put the weights on the correct dtype and device of the param
120
+ emb_weights = emb_weights.to(dtype=self.weights.dtype, device=self.weights.device)
121
+
122
+ self.register_buffer("weights", emb_weights, persistent=False)
123
+
124
+ @staticmethod
125
+ def get_embedding(num_embeddings: int, embedding_dim: int, padding_idx: Optional[int] = None):
126
+ """
127
+ Build sinusoidal embeddings.
128
+
129
+ This matches the implementation in tensor2tensor, but differs slightly from the description in Section 3.5 of
130
+ "Attention Is All You Need".
131
+ """
132
+ half_dim = embedding_dim // 2
133
+ emb = math.log(10000) / (half_dim - 1)
134
+ emb = torch.exp(torch.arange(half_dim, dtype=torch.int64).float() * -emb)
135
+ emb = torch.arange(num_embeddings, dtype=torch.int64).float().unsqueeze(1) * emb.unsqueeze(0)
136
+ emb = torch.cat([torch.sin(emb), torch.cos(emb)], dim=1).view(num_embeddings, -1)
137
+ if embedding_dim % 2 == 1:
138
+ # zero pad
139
+ emb = torch.cat([emb, torch.zeros(num_embeddings, 1)], dim=1)
140
+ if padding_idx is not None:
141
+ emb[padding_idx, :] = 0
142
+
143
+ return emb.to(torch.get_default_dtype())
144
+
145
+ @torch.no_grad()
146
+ def forward(
147
+ self, input_ids: torch.Tensor = None, inputs_embeds: torch.Tensor = None, past_key_values_length: int = 0
148
+ ):
149
+ if input_ids is not None:
150
+ bsz, seq_len = input_ids.size()
151
+ # Create the position ids from the input token ids. Any padded tokens remain padded.
152
+ position_ids = create_position_ids_from_input_ids(input_ids, self.padding_idx, past_key_values_length).to(
153
+ input_ids.device
154
+ )
155
+ else:
156
+ bsz, seq_len = inputs_embeds.size()[:-1]
157
+ position_ids = self.create_position_ids_from_inputs_embeds(inputs_embeds, past_key_values_length)
158
+
159
+ # expand embeddings if needed
160
+ max_pos = self.padding_idx + 1 + seq_len + past_key_values_length
161
+ if max_pos > self.weights.size(0):
162
+ self.make_weights(max_pos + self.offset, self.embedding_dim, self.padding_idx)
163
+
164
+ return self.weights.index_select(0, position_ids.view(-1)).view(bsz, seq_len, self.weights.shape[-1]).detach()
165
+
166
+ def create_position_ids_from_inputs_embeds(self, inputs_embeds, past_key_values_length):
167
+ """
168
+ We are provided embeddings directly. We cannot infer which are padded so just generate sequential position ids.
169
+
170
+ Args:
171
+ inputs_embeds: torch.Tensor
172
+
173
+ Returns: torch.Tensor
174
+ """
175
+ input_shape = inputs_embeds.size()[:-1]
176
+ sequence_length = input_shape[1]
177
+
178
+ position_ids = torch.arange(
179
+ self.padding_idx + 1, sequence_length + self.padding_idx + 1, dtype=torch.long, device=inputs_embeds.device
180
+ )
181
+ return position_ids.unsqueeze(0).expand(input_shape).contiguous() + past_key_values_length
182
+
183
+
184
+ # Copied from transformers.models.bart.modeling_bart.BartAttention with Bart->M2M100
185
+ class M2M100Attention(nn.Module):
186
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
187
+
188
+ def __init__(
189
+ self,
190
+ embed_dim: int,
191
+ num_heads: int,
192
+ dropout: float = 0.0,
193
+ is_decoder: bool = False,
194
+ bias: bool = True,
195
+ is_causal: bool = False,
196
+ config: Optional[M2M100Config] = None,
197
+ ):
198
+ super().__init__()
199
+ self.embed_dim = embed_dim
200
+ self.num_heads = num_heads
201
+ self.dropout = dropout
202
+ self.head_dim = embed_dim // num_heads
203
+ self.config = config
204
+
205
+ if (self.head_dim * num_heads) != self.embed_dim:
206
+ raise ValueError(
207
+ f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim}"
208
+ f" and `num_heads`: {num_heads})."
209
+ )
210
+ self.scaling = self.head_dim**-0.5
211
+ self.is_decoder = is_decoder
212
+ self.is_causal = is_causal
213
+
214
+ self.k_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
215
+ self.v_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
216
+ self.q_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
217
+ self.out_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
218
+
219
+ def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
220
+ return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
221
+
222
+ def forward(
223
+ self,
224
+ hidden_states: torch.Tensor,
225
+ key_value_states: Optional[torch.Tensor] = None,
226
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
227
+ attention_mask: Optional[torch.Tensor] = None,
228
+ layer_head_mask: Optional[torch.Tensor] = None,
229
+ output_attentions: bool = False,
230
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
231
+ """Input shape: Batch x Time x Channel"""
232
+
233
+ # if key_value_states are provided this layer is used as a cross-attention layer
234
+ # for the decoder
235
+ is_cross_attention = key_value_states is not None
236
+
237
+ bsz, tgt_len, _ = hidden_states.size()
238
+
239
+ # get query proj
240
+ query_states = self.q_proj(hidden_states) * self.scaling
241
+ # get key, value proj
242
+ # `past_key_value[0].shape[2] == key_value_states.shape[1]`
243
+ # is checking that the `sequence_length` of the `past_key_value` is the same as
244
+ # the provided `key_value_states` to support prefix tuning
245
+ if (
246
+ is_cross_attention
247
+ and past_key_value is not None
248
+ and past_key_value[0].shape[2] == key_value_states.shape[1]
249
+ ):
250
+ # reuse k,v, cross_attentions
251
+ key_states = past_key_value[0]
252
+ value_states = past_key_value[1]
253
+ elif is_cross_attention:
254
+ # cross_attentions
255
+ key_states = self._shape(self.k_proj(key_value_states), -1, bsz)
256
+ value_states = self._shape(self.v_proj(key_value_states), -1, bsz)
257
+ elif past_key_value is not None:
258
+ # reuse k, v, self_attention
259
+ key_states = self._shape(self.k_proj(hidden_states), -1, bsz)
260
+ value_states = self._shape(self.v_proj(hidden_states), -1, bsz)
261
+ key_states = torch.cat([past_key_value[0], key_states], dim=2)
262
+ value_states = torch.cat([past_key_value[1], value_states], dim=2)
263
+ else:
264
+ # self_attention
265
+ key_states = self._shape(self.k_proj(hidden_states), -1, bsz)
266
+ value_states = self._shape(self.v_proj(hidden_states), -1, bsz)
267
+
268
+ if self.is_decoder:
269
+ # if cross_attention save Tuple(torch.Tensor, torch.Tensor) of all cross attention key/value_states.
270
+ # Further calls to cross_attention layer can then reuse all cross-attention
271
+ # key/value_states (first "if" case)
272
+ # if uni-directional self-attention (decoder) save Tuple(torch.Tensor, torch.Tensor) of
273
+ # all previous decoder key/value_states. Further calls to uni-directional self-attention
274
+ # can concat previous decoder key/value_states to current projected key/value_states (third "elif" case)
275
+ # if encoder bi-directional self-attention `past_key_value` is always `None`
276
+ past_key_value = (key_states, value_states)
277
+
278
+ proj_shape = (bsz * self.num_heads, -1, self.head_dim)
279
+ query_states = self._shape(query_states, tgt_len, bsz).view(*proj_shape)
280
+ key_states = key_states.reshape(*proj_shape)
281
+ value_states = value_states.reshape(*proj_shape)
282
+
283
+ src_len = key_states.size(1)
284
+ attn_weights = torch.bmm(query_states, key_states.transpose(1, 2))
285
+
286
+ if attn_weights.size() != (bsz * self.num_heads, tgt_len, src_len):
287
+ raise ValueError(
288
+ f"Attention weights should be of size {(bsz * self.num_heads, tgt_len, src_len)}, but is"
289
+ f" {attn_weights.size()}"
290
+ )
291
+
292
+ if attention_mask is not None:
293
+ if attention_mask.size() != (bsz, 1, tgt_len, src_len):
294
+ raise ValueError(
295
+ f"Attention mask should be of size {(bsz, 1, tgt_len, src_len)}, but is {attention_mask.size()}"
296
+ )
297
+ attn_weights = attn_weights.view(bsz, self.num_heads, tgt_len, src_len) + attention_mask
298
+ attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len)
299
+
300
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1)
301
+
302
+ if layer_head_mask is not None:
303
+ if layer_head_mask.size() != (self.num_heads,):
304
+ raise ValueError(
305
+ f"Head mask for a single layer should be of size {(self.num_heads,)}, but is"
306
+ f" {layer_head_mask.size()}"
307
+ )
308
+ attn_weights = layer_head_mask.view(1, -1, 1, 1) * attn_weights.view(bsz, self.num_heads, tgt_len, src_len)
309
+ attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len)
310
+
311
+ if output_attentions:
312
+ # this operation is a bit awkward, but it's required to
313
+ # make sure that attn_weights keeps its gradient.
314
+ # In order to do so, attn_weights have to be reshaped
315
+ # twice and have to be reused in the following
316
+ attn_weights_reshaped = attn_weights.view(bsz, self.num_heads, tgt_len, src_len)
317
+ attn_weights = attn_weights_reshaped.view(bsz * self.num_heads, tgt_len, src_len)
318
+ else:
319
+ attn_weights_reshaped = None
320
+
321
+ attn_probs = nn.functional.dropout(attn_weights, p=self.dropout, training=self.training)
322
+
323
+ attn_output = torch.bmm(attn_probs, value_states)
324
+
325
+ if attn_output.size() != (bsz * self.num_heads, tgt_len, self.head_dim):
326
+ raise ValueError(
327
+ f"`attn_output` should be of size {(bsz * self.num_heads, tgt_len, self.head_dim)}, but is"
328
+ f" {attn_output.size()}"
329
+ )
330
+
331
+ attn_output = attn_output.view(bsz, self.num_heads, tgt_len, self.head_dim)
332
+ attn_output = attn_output.transpose(1, 2)
333
+
334
+ # Use the `embed_dim` from the config (stored in the class) rather than `hidden_state` because `attn_output` can be
335
+ # partitioned across GPUs when using tensor-parallelism.
336
+ attn_output = attn_output.reshape(bsz, tgt_len, self.embed_dim)
337
+
338
+ attn_output = self.out_proj(attn_output)
339
+
340
+ return attn_output, attn_weights_reshaped, past_key_value
341
+
342
+
343
+ # Copied from transformers.models.bart.modeling_bart.BartFlashAttention2 with Bart->M2M100
344
+ class M2M100FlashAttention2(M2M100Attention):
345
+ """
346
+ M2M100 flash attention module. This module inherits from `M2M100Attention` as the weights of the module stays
347
+ untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
348
+ flash attention and deal with padding tokens in case the input contains any of them.
349
+ """
350
+
351
+ def __init__(self, *args, **kwargs):
352
+ super().__init__(*args, **kwargs)
353
+
354
+ # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
355
+ # flash_attn<2.1 generates top-left aligned causal mask, while what is needed here is bottom-right alignment, that was made default for flash_attn>=2.1. This attribute is used to handle this difference. Reference: https://github.com/Dao-AILab/flash-attention/releases/tag/v2.1.0.
356
+ # Beware that with flash_attn<2.1, using q_seqlen != k_seqlen (except for the case q_seqlen == 1) produces a wrong mask (top-left).
357
+ self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
358
+
359
+ def _reshape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
360
+ return tensor.view(bsz, seq_len, self.num_heads, self.head_dim)
361
+
362
+ def forward(
363
+ self,
364
+ hidden_states: torch.Tensor,
365
+ key_value_states: Optional[torch.Tensor] = None,
366
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
367
+ attention_mask: Optional[torch.Tensor] = None,
368
+ layer_head_mask: Optional[torch.Tensor] = None,
369
+ output_attentions: bool = False,
370
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
371
+ # M2M100FlashAttention2 attention does not support output_attentions
372
+ if output_attentions:
373
+ raise ValueError("M2M100FlashAttention2 attention does not support output_attentions")
374
+
375
+ # if key_value_states are provided this layer is used as a cross-attention layer
376
+ # for the decoder
377
+ is_cross_attention = key_value_states is not None
378
+
379
+ bsz, q_len, _ = hidden_states.size()
380
+
381
+ # get query proj
382
+ query_states = self._reshape(self.q_proj(hidden_states), -1, bsz)
383
+ # get key, value proj
384
+ # `past_key_value[0].shape[2] == key_value_states.shape[1]`
385
+ # is checking that the `sequence_length` of the `past_key_value` is the same as
386
+ # the provided `key_value_states` to support prefix tuning
387
+ if (
388
+ is_cross_attention
389
+ and past_key_value is not None
390
+ and past_key_value[0].shape[2] == key_value_states.shape[1]
391
+ ):
392
+ # reuse k,v, cross_attentions
393
+ key_states = past_key_value[0].transpose(1, 2)
394
+ value_states = past_key_value[1].transpose(1, 2)
395
+ elif is_cross_attention:
396
+ # cross_attentions
397
+ key_states = self._reshape(self.k_proj(key_value_states), -1, bsz)
398
+ value_states = self._reshape(self.v_proj(key_value_states), -1, bsz)
399
+ elif past_key_value is not None:
400
+ # reuse k, v, self_attention
401
+ key_states = self._reshape(self.k_proj(hidden_states), -1, bsz)
402
+ value_states = self._reshape(self.v_proj(hidden_states), -1, bsz)
403
+ key_states = torch.cat([past_key_value[0].transpose(1, 2), key_states], dim=1)
404
+ value_states = torch.cat([past_key_value[1].transpose(1, 2), value_states], dim=1)
405
+ else:
406
+ # self_attention
407
+ key_states = self._reshape(self.k_proj(hidden_states), -1, bsz)
408
+ value_states = self._reshape(self.v_proj(hidden_states), -1, bsz)
409
+
410
+ if self.is_decoder:
411
+ # if cross_attention save Tuple(torch.Tensor, torch.Tensor) of all cross attention key/value_states.
412
+ # Further calls to cross_attention layer can then reuse all cross-attention
413
+ # key/value_states (first "if" case)
414
+ # if uni-directional self-attention (decoder) save Tuple(torch.Tensor, torch.Tensor) of
415
+ # all previous decoder key/value_states. Further calls to uni-directional self-attention
416
+ # can concat previous decoder key/value_states to current projected key/value_states (third "elif" case)
417
+ # if encoder bi-directional self-attention `past_key_value` is always `None`
418
+ past_key_value = (key_states.transpose(1, 2), value_states.transpose(1, 2))
419
+
420
+ kv_seq_len = key_states.shape[-2]
421
+ if past_key_value is not None:
422
+ kv_seq_len += past_key_value[0].shape[-2]
423
+
424
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
425
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
426
+ # cast them back in the correct dtype just to be sure everything works as expected.
427
+ # This might slowdown training & inference so it is recommended to not cast the LayerNorms
428
+ # in fp32. (LlamaRMSNorm handles it correctly)
429
+
430
+ input_dtype = query_states.dtype
431
+ if input_dtype == torch.float32:
432
+ if torch.is_autocast_enabled():
433
+ target_dtype = torch.get_autocast_gpu_dtype()
434
+ # Handle the case where the model is quantized
435
+ elif hasattr(self.config, "_pre_quantization_dtype"):
436
+ target_dtype = self.config._pre_quantization_dtype
437
+ else:
438
+ target_dtype = self.q_proj.weight.dtype
439
+
440
+ logger.warning_once(
441
+ f"The input hidden states seems to be silently casted in float32, this might be related to"
442
+ f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
443
+ f" {target_dtype}."
444
+ )
445
+
446
+ query_states = query_states.to(target_dtype)
447
+ key_states = key_states.to(target_dtype)
448
+ value_states = value_states.to(target_dtype)
449
+
450
+ attn_output = _flash_attention_forward(
451
+ query_states,
452
+ key_states,
453
+ value_states,
454
+ attention_mask,
455
+ q_len,
456
+ dropout=self.dropout if self.training else 0.0,
457
+ is_causal=self.is_causal,
458
+ use_top_left_mask=self._flash_attn_uses_top_left_mask,
459
+ )
460
+
461
+ attn_output = attn_output.reshape(bsz, q_len, -1)
462
+ attn_output = self.out_proj(attn_output)
463
+
464
+ if not output_attentions:
465
+ attn_weights = None
466
+
467
+ return attn_output, attn_weights, past_key_value
468
+
469
+
470
+ # Copied from transformers.models.bart.modeling_bart.BartSdpaAttention with Bart->M2M100
471
+ class M2M100SdpaAttention(M2M100Attention):
472
+ def forward(
473
+ self,
474
+ hidden_states: torch.Tensor,
475
+ key_value_states: Optional[torch.Tensor] = None,
476
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
477
+ attention_mask: Optional[torch.Tensor] = None,
478
+ layer_head_mask: Optional[torch.Tensor] = None,
479
+ output_attentions: bool = False,
480
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
481
+ """Input shape: Batch x Time x Channel"""
482
+ if output_attentions or layer_head_mask is not None:
483
+ # TODO: Improve this warning with e.g. `model.config._attn_implementation = "manual"` once this is implemented.
484
+ logger.warning_once(
485
+ "M2M100Model is using M2M100SdpaAttention, but `torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True` or `layer_head_mask` not None. Falling back to the manual attention"
486
+ ' implementation, but specifying the manual implementation will be required from Transformers version v5.0.0 onwards. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.'
487
+ )
488
+ return super().forward(
489
+ hidden_states,
490
+ key_value_states=key_value_states,
491
+ past_key_value=past_key_value,
492
+ attention_mask=attention_mask,
493
+ layer_head_mask=layer_head_mask,
494
+ output_attentions=output_attentions,
495
+ )
496
+
497
+ # if key_value_states are provided this layer is used as a cross-attention layer
498
+ # for the decoder
499
+ is_cross_attention = key_value_states is not None
500
+
501
+ bsz, tgt_len, _ = hidden_states.size()
502
+
503
+ # get query proj
504
+ query_states = self.q_proj(hidden_states)
505
+ # get key, value proj
506
+ # `past_key_value[0].shape[2] == key_value_states.shape[1]`
507
+ # is checking that the `sequence_length` of the `past_key_value` is the same as
508
+ # the provided `key_value_states` to support prefix tuning
509
+ if (
510
+ is_cross_attention
511
+ and past_key_value is not None
512
+ and past_key_value[0].shape[2] == key_value_states.shape[1]
513
+ ):
514
+ # reuse k,v, cross_attentions
515
+ key_states = past_key_value[0]
516
+ value_states = past_key_value[1]
517
+ elif is_cross_attention:
518
+ # cross_attentions
519
+ key_states = self._shape(self.k_proj(key_value_states), -1, bsz)
520
+ value_states = self._shape(self.v_proj(key_value_states), -1, bsz)
521
+ elif past_key_value is not None:
522
+ # reuse k, v, self_attention
523
+ key_states = self._shape(self.k_proj(hidden_states), -1, bsz)
524
+ value_states = self._shape(self.v_proj(hidden_states), -1, bsz)
525
+ key_states = torch.cat([past_key_value[0], key_states], dim=2)
526
+ value_states = torch.cat([past_key_value[1], value_states], dim=2)
527
+ else:
528
+ # self_attention
529
+ key_states = self._shape(self.k_proj(hidden_states), -1, bsz)
530
+ value_states = self._shape(self.v_proj(hidden_states), -1, bsz)
531
+
532
+ if self.is_decoder:
533
+ # if cross_attention save Tuple(torch.Tensor, torch.Tensor) of all cross attention key/value_states.
534
+ # Further calls to cross_attention layer can then reuse all cross-attention
535
+ # key/value_states (first "if" case)
536
+ # if uni-directional self-attention (decoder) save Tuple(torch.Tensor, torch.Tensor) of
537
+ # all previous decoder key/value_states. Further calls to uni-directional self-attention
538
+ # can concat previous decoder key/value_states to current projected key/value_states (third "elif" case)
539
+ # if encoder bi-directional self-attention `past_key_value` is always `None`
540
+ past_key_value = (key_states, value_states)
541
+
542
+ query_states = self._shape(query_states, tgt_len, bsz)
543
+
544
+ # We dispatch to SDPA's Flash Attention or Efficient kernels via this `is_causal` if statement instead of an inline conditional assignment
545
+ # in SDPA to support both torch.compile's dynamic shapes and full graph options. An inline conditional prevents dynamic shapes from compiling.
546
+ # The tgt_len > 1 is necessary to match with AttentionMaskConverter.to_causal_4d that does not create a causal mask in case tgt_len == 1.
547
+ is_causal = True if self.is_causal and attention_mask is None and tgt_len > 1 else False
548
+
549
+ # NOTE: SDPA with memory-efficient backend is currently (torch==2.1.2) bugged when using non-contiguous inputs and a custom attn_mask,
550
+ # but we are fine here as `_shape` do call `.contiguous()`. Reference: https://github.com/pytorch/pytorch/issues/112577
551
+ attn_output = torch.nn.functional.scaled_dot_product_attention(
552
+ query_states,
553
+ key_states,
554
+ value_states,
555
+ attn_mask=attention_mask,
556
+ dropout_p=self.dropout if self.training else 0.0,
557
+ is_causal=is_causal,
558
+ )
559
+
560
+ if attn_output.size() != (bsz, self.num_heads, tgt_len, self.head_dim):
561
+ raise ValueError(
562
+ f"`attn_output` should be of size {(bsz, self.num_heads, tgt_len, self.head_dim)}, but is"
563
+ f" {attn_output.size()}"
564
+ )
565
+
566
+ attn_output = attn_output.transpose(1, 2)
567
+
568
+ # Use the `embed_dim` from the config (stored in the class) rather than `hidden_state` because `attn_output` can be
569
+ # partitioned across GPUs when using tensor-parallelism.
570
+ attn_output = attn_output.reshape(bsz, tgt_len, self.embed_dim)
571
+
572
+ attn_output = self.out_proj(attn_output)
573
+
574
+ return attn_output, None, past_key_value
575
+
576
+
577
+ # Copied from transformers.models.mbart.modeling_mbart.MBartEncoderLayer with MBart->M2M100, MBART->M2M100
578
+ class M2M100EncoderLayer(nn.Module):
579
+ def __init__(self, config: M2M100Config):
580
+ super().__init__()
581
+ self.embed_dim = config.d_model
582
+
583
+ self.self_attn = M2M100_ATTENTION_CLASSES[config._attn_implementation](
584
+ embed_dim=self.embed_dim,
585
+ num_heads=config.encoder_attention_heads,
586
+ dropout=config.attention_dropout,
587
+ config=config,
588
+ )
589
+ self.self_attn_layer_norm = nn.LayerNorm(self.embed_dim)
590
+ self.dropout = config.dropout
591
+ self.activation_fn = ACT2FN[config.activation_function]
592
+ self.activation_dropout = config.activation_dropout
593
+ self.fc1 = nn.Linear(self.embed_dim, config.encoder_ffn_dim)
594
+ self.fc2 = nn.Linear(config.encoder_ffn_dim, self.embed_dim)
595
+ self.final_layer_norm = nn.LayerNorm(self.embed_dim)
596
+
597
+ def forward(
598
+ self,
599
+ hidden_states: torch.Tensor,
600
+ attention_mask: torch.Tensor,
601
+ layer_head_mask: torch.Tensor,
602
+ output_attentions: bool = False,
603
+ ) -> torch.Tensor:
604
+ """
605
+ Args:
606
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
607
+ attention_mask (`torch.FloatTensor`): attention mask of size
608
+ `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
609
+ layer_head_mask (`torch.FloatTensor`): mask for attention heads in a given layer of size
610
+ `(encoder_attention_heads,)`.
611
+ output_attentions (`bool`, *optional*):
612
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
613
+ returned tensors for more detail.
614
+ """
615
+ residual = hidden_states
616
+ hidden_states = self.self_attn_layer_norm(hidden_states)
617
+ hidden_states, attn_weights, _ = self.self_attn(
618
+ hidden_states=hidden_states,
619
+ attention_mask=attention_mask,
620
+ layer_head_mask=layer_head_mask,
621
+ output_attentions=output_attentions,
622
+ )
623
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
624
+ hidden_states = residual + hidden_states
625
+
626
+ residual = hidden_states
627
+ hidden_states = self.final_layer_norm(hidden_states)
628
+ hidden_states = self.activation_fn(self.fc1(hidden_states))
629
+ hidden_states = nn.functional.dropout(hidden_states, p=self.activation_dropout, training=self.training)
630
+ hidden_states = self.fc2(hidden_states)
631
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
632
+ hidden_states = residual + hidden_states
633
+
634
+ if hidden_states.dtype == torch.float16 and (
635
+ torch.isinf(hidden_states).any() or torch.isnan(hidden_states).any()
636
+ ):
637
+ clamp_value = torch.finfo(hidden_states.dtype).max - 1000
638
+ hidden_states = torch.clamp(hidden_states, min=-clamp_value, max=clamp_value)
639
+
640
+ outputs = (hidden_states,)
641
+
642
+ if output_attentions:
643
+ outputs += (attn_weights,)
644
+
645
+ return outputs
646
+
647
+
648
+ M2M100_ATTENTION_CLASSES = {
649
+ "eager": M2M100Attention,
650
+ "flash_attention_2": M2M100FlashAttention2,
651
+ "sdpa": M2M100SdpaAttention,
652
+ }
653
+
654
+
655
+ # Copied from transformers.models.mbart.modeling_mbart.MBartDecoderLayer with MBart->M2M100, MBART->M2M100
656
+ class M2M100DecoderLayer(nn.Module):
657
+ def __init__(self, config: M2M100Config):
658
+ super().__init__()
659
+ self.embed_dim = config.d_model
660
+
661
+ self.self_attn = M2M100_ATTENTION_CLASSES[config._attn_implementation](
662
+ embed_dim=self.embed_dim,
663
+ num_heads=config.decoder_attention_heads,
664
+ dropout=config.attention_dropout,
665
+ is_decoder=True,
666
+ is_causal=True,
667
+ config=config,
668
+ )
669
+ self.dropout = config.dropout
670
+ self.activation_fn = ACT2FN[config.activation_function]
671
+ self.activation_dropout = config.activation_dropout
672
+
673
+ self.self_attn_layer_norm = nn.LayerNorm(self.embed_dim)
674
+ self.encoder_attn = M2M100_ATTENTION_CLASSES[config._attn_implementation](
675
+ self.embed_dim,
676
+ config.decoder_attention_heads,
677
+ dropout=config.attention_dropout,
678
+ is_decoder=True,
679
+ config=config,
680
+ )
681
+ self.encoder_attn_layer_norm = nn.LayerNorm(self.embed_dim)
682
+ self.fc1 = nn.Linear(self.embed_dim, config.decoder_ffn_dim)
683
+ self.fc2 = nn.Linear(config.decoder_ffn_dim, self.embed_dim)
684
+ self.final_layer_norm = nn.LayerNorm(self.embed_dim)
685
+
686
+ def forward(
687
+ self,
688
+ hidden_states: torch.Tensor,
689
+ attention_mask: Optional[torch.Tensor] = None,
690
+ encoder_hidden_states: Optional[torch.Tensor] = None,
691
+ encoder_attention_mask: Optional[torch.Tensor] = None,
692
+ layer_head_mask: Optional[torch.Tensor] = None,
693
+ cross_attn_layer_head_mask: Optional[torch.Tensor] = None,
694
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
695
+ output_attentions: Optional[bool] = False,
696
+ use_cache: Optional[bool] = True,
697
+ ) -> torch.Tensor:
698
+ """
699
+ Args:
700
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
701
+ attention_mask (`torch.FloatTensor`): attention mask of size
702
+ `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
703
+ encoder_hidden_states (`torch.FloatTensor`):
704
+ cross attention input to the layer of shape `(batch, seq_len, embed_dim)`
705
+ encoder_attention_mask (`torch.FloatTensor`): encoder attention mask of size
706
+ `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
707
+ layer_head_mask (`torch.FloatTensor`): mask for attention heads in a given layer of size
708
+ `(encoder_attention_heads,)`.
709
+ cross_attn_layer_head_mask (`torch.FloatTensor`): mask for cross-attention heads in a given layer of
710
+ size `(decoder_attention_heads,)`.
711
+ past_key_value (`Tuple(torch.FloatTensor)`): cached past key and value projection states
712
+ output_attentions (`bool`, *optional*):
713
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
714
+ returned tensors for more detail.
715
+ """
716
+ residual = hidden_states
717
+ hidden_states = self.self_attn_layer_norm(hidden_states)
718
+
719
+ # Self Attention
720
+ # decoder uni-directional self-attention cached key/values tuple is at positions 1,2
721
+ self_attn_past_key_value = past_key_value[:2] if past_key_value is not None else None
722
+ # add present self-attn cache to positions 1,2 of present_key_value tuple
723
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
724
+ hidden_states=hidden_states,
725
+ past_key_value=self_attn_past_key_value,
726
+ attention_mask=attention_mask,
727
+ layer_head_mask=layer_head_mask,
728
+ output_attentions=output_attentions,
729
+ )
730
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
731
+ hidden_states = residual + hidden_states
732
+
733
+ # Cross-Attention Block
734
+ cross_attn_present_key_value = None
735
+ cross_attn_weights = None
736
+ if encoder_hidden_states is not None:
737
+ residual = hidden_states
738
+ hidden_states = self.encoder_attn_layer_norm(hidden_states)
739
+
740
+ # cross_attn cached key/values tuple is at positions 3,4 of present_key_value tuple
741
+ cross_attn_past_key_value = past_key_value[-2:] if past_key_value is not None else None
742
+ hidden_states, cross_attn_weights, cross_attn_present_key_value = self.encoder_attn(
743
+ hidden_states=hidden_states,
744
+ key_value_states=encoder_hidden_states,
745
+ attention_mask=encoder_attention_mask,
746
+ layer_head_mask=cross_attn_layer_head_mask,
747
+ past_key_value=cross_attn_past_key_value,
748
+ output_attentions=output_attentions,
749
+ )
750
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
751
+ hidden_states = residual + hidden_states
752
+
753
+ # add cross-attn to positions 3,4 of present_key_value tuple
754
+ present_key_value = present_key_value + cross_attn_present_key_value
755
+
756
+ # Fully Connected
757
+ residual = hidden_states
758
+ hidden_states = self.final_layer_norm(hidden_states)
759
+ hidden_states = self.activation_fn(self.fc1(hidden_states))
760
+ hidden_states = nn.functional.dropout(hidden_states, p=self.activation_dropout, training=self.training)
761
+ hidden_states = self.fc2(hidden_states)
762
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
763
+ hidden_states = residual + hidden_states
764
+
765
+ outputs = (hidden_states,)
766
+
767
+ if output_attentions:
768
+ outputs += (self_attn_weights, cross_attn_weights)
769
+
770
+ if use_cache:
771
+ outputs += (present_key_value,)
772
+
773
+ return outputs
774
+
775
+
776
+ class M2M100PreTrainedModel(PreTrainedModel):
777
+ config_class = M2M100Config
778
+ base_model_prefix = "model"
779
+ supports_gradient_checkpointing = True
780
+ _no_split_modules = ["M2M100EncoderLayer", "M2M100DecoderLayer"]
781
+ _supports_flash_attn_2 = True
782
+ _supports_sdpa = True
783
+
784
+ def _init_weights(self, module):
785
+ std = self.config.init_std
786
+ if isinstance(module, nn.Linear):
787
+ module.weight.data.normal_(mean=0.0, std=std)
788
+ if module.bias is not None:
789
+ module.bias.data.zero_()
790
+ elif isinstance(module, nn.Embedding):
791
+ module.weight.data.normal_(mean=0.0, std=std)
792
+ if module.padding_idx is not None:
793
+ module.weight.data[module.padding_idx].zero_()
794
+
795
+
796
+ M2M_100_START_DOCSTRING = r"""
797
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
798
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
799
+ etc.)
800
+
801
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
802
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
803
+ and behavior.
804
+
805
+ Parameters:
806
+ config ([`M2M100Config`]):
807
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
808
+ load the weights associated with the model, only the configuration. Check out the
809
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
810
+ """
811
+
812
+ M2M_100_GENERATION_EXAMPLE = r"""
813
+ Translation example:
814
+
815
+ ```python
816
+ >>> from transformers import AutoTokenizer, M2M100ForConditionalGeneration
817
+
818
+ >>> model = M2M100ForConditionalGeneration.from_pretrained("facebook/m2m100_418M")
819
+ >>> tokenizer = AutoTokenizer.from_pretrained("facebook/m2m100_418M")
820
+
821
+ >>> text_to_translate = "Life is like a box of chocolates"
822
+ >>> model_inputs = tokenizer(text_to_translate, return_tensors="pt")
823
+
824
+ >>> # translate to French
825
+ >>> gen_tokens = model.generate(**model_inputs, forced_bos_token_id=tokenizer.get_lang_id("fr"))
826
+ >>> print(tokenizer.batch_decode(gen_tokens, skip_special_tokens=True))
827
+ ```
828
+ """
829
+
830
+ M2M_100_INPUTS_DOCSTRING = r"""
831
+ Args:
832
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
833
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
834
+ it.
835
+
836
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
837
+ [`PreTrainedTokenizer.__call__`] for details.
838
+
839
+ [What are input IDs?](../glossary#input-ids)
840
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
841
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
842
+
843
+ - 1 for tokens that are **not masked**,
844
+ - 0 for tokens that are **masked**.
845
+
846
+ [What are attention masks?](../glossary#attention-mask)
847
+ decoder_input_ids (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
848
+ Indices of decoder input sequence tokens in the vocabulary.
849
+
850
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
851
+ [`PreTrainedTokenizer.__call__`] for details.
852
+
853
+ [What are decoder input IDs?](../glossary#decoder-input-ids)
854
+
855
+ M2M100 uses the `eos_token_id` as the starting token for `decoder_input_ids` generation. If
856
+ `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
857
+ `past_key_values`).
858
+ decoder_attention_mask (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
859
+ Default behavior: generate a tensor that ignores pad tokens in `decoder_input_ids`. Causal mask will also
860
+ be used by default.
861
+ head_mask (`torch.Tensor` of shape `(encoder_layers, encoder_attention_heads)`, *optional*):
862
+ Mask to nullify selected heads of the attention modules in the encoder. Mask values selected in `[0, 1]`:
863
+
864
+ - 1 indicates the head is **not masked**,
865
+ - 0 indicates the head is **masked**.
866
+
867
+ decoder_head_mask (`torch.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
868
+ Mask to nullify selected heads of the attention modules in the decoder. Mask values selected in `[0, 1]`:
869
+
870
+ - 1 indicates the head is **not masked**,
871
+ - 0 indicates the head is **masked**.
872
+
873
+ cross_attn_head_mask (`torch.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
874
+ Mask to nullify selected heads of the cross-attention modules in the decoder. Mask values selected in `[0,
875
+ 1]`:
876
+
877
+ - 1 indicates the head is **not masked**,
878
+ - 0 indicates the head is **masked**.
879
+ encoder_outputs (`tuple(tuple(torch.FloatTensor)`, *optional*):
880
+ Tuple consists of (`last_hidden_state`, *optional*: `hidden_states`, *optional*: `attentions`)
881
+ `last_hidden_state` of shape `(batch_size, sequence_length, hidden_size)`, *optional*) is a sequence of
882
+ hidden-states at the output of the last layer of the encoder. Used in the cross-attention of the decoder.
883
+ past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
884
+ Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
885
+ `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of shape
886
+ `(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`.
887
+
888
+ Contains pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
889
+ blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.
890
+
891
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
892
+ don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
893
+ `decoder_input_ids` of shape `(batch_size, sequence_length)`.
894
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
895
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation.
896
+ This is useful if you want more control over how to convert `input_ids` indices into associated vectors
897
+ than the model's internal embedding lookup matrix.
898
+ decoder_inputs_embeds (`torch.FloatTensor` of shape `(batch_size, target_sequence_length, hidden_size)`, *optional*):
899
+ Optionally, instead of passing `decoder_input_ids` you can choose to directly pass an embedded
900
+ representation. If `past_key_values` is used, optionally only the last `decoder_inputs_embeds` have to be
901
+ input (see `past_key_values`). This is useful if you want more control over how to convert
902
+ `decoder_input_ids` indices into associated vectors than the model's internal embedding lookup matrix.
903
+
904
+ If `decoder_input_ids` and `decoder_inputs_embeds` are both unset, `decoder_inputs_embeds` takes the value
905
+ of `inputs_embeds`.
906
+ use_cache (`bool`, *optional*):
907
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
908
+ `past_key_values`).
909
+ output_attentions (`bool`, *optional*):
910
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
911
+ tensors for more detail.
912
+ output_hidden_states (`bool`, *optional*):
913
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
914
+ more detail.
915
+ return_dict (`bool`, *optional*):
916
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
917
+ """
918
+
919
+
920
+ class M2M100Encoder(M2M100PreTrainedModel):
921
+ """
922
+ Transformer encoder consisting of *config.encoder_layers* self attention layers. Each layer is a
923
+ [`M2M100EncoderLayer`].
924
+
925
+ Args:
926
+ config: M2M100Config
927
+ embed_tokens (nn.Embedding): output embedding
928
+ """
929
+
930
+ def __init__(self, config: M2M100Config, embed_tokens: Optional[nn.Embedding] = None):
931
+ super().__init__(config)
932
+
933
+ self.dropout = config.dropout
934
+ self.layerdrop = config.encoder_layerdrop
935
+
936
+ embed_dim = config.d_model
937
+ self.padding_idx = config.pad_token_id
938
+ self.max_source_positions = config.max_position_embeddings
939
+ embed_scale = math.sqrt(embed_dim) if config.scale_embedding else 1.0
940
+
941
+ self.embed_tokens = M2M100ScaledWordEmbedding(
942
+ config.vocab_size, embed_dim, self.padding_idx, embed_scale=embed_scale
943
+ )
944
+
945
+ if embed_tokens is not None:
946
+ self.embed_tokens.weight = embed_tokens.weight
947
+
948
+ self.embed_positions = M2M100SinusoidalPositionalEmbedding(
949
+ config.max_position_embeddings,
950
+ embed_dim,
951
+ self.padding_idx,
952
+ )
953
+ self.layers = nn.ModuleList([M2M100EncoderLayer(config) for _ in range(config.encoder_layers)])
954
+ self.layer_norm = nn.LayerNorm(config.d_model)
955
+ self._use_flash_attention_2 = config._attn_implementation == "flash_attention_2"
956
+ self._use_sdpa = config._attn_implementation == "sdpa"
957
+
958
+ self.gradient_checkpointing = False
959
+ # Initialize weights and apply final processing
960
+ self.post_init()
961
+
962
+ def forward(
963
+ self,
964
+ input_ids: Optional[torch.Tensor] = None,
965
+ attention_mask: Optional[torch.Tensor] = None,
966
+ head_mask: Optional[torch.Tensor] = None,
967
+ inputs_embeds: Optional[torch.Tensor] = None,
968
+ output_attentions: Optional[bool] = None,
969
+ output_hidden_states: Optional[bool] = None,
970
+ return_dict: Optional[bool] = None,
971
+ ):
972
+ r"""
973
+ Args:
974
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
975
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you
976
+ provide it.
977
+
978
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
979
+ [`PreTrainedTokenizer.__call__`] for details.
980
+
981
+ [What are input IDs?](../glossary#input-ids)
982
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
983
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
984
+
985
+ - 1 for tokens that are **not masked**,
986
+ - 0 for tokens that are **masked**.
987
+
988
+ [What are attention masks?](../glossary#attention-mask)
989
+ head_mask (`torch.Tensor` of shape `(encoder_layers, encoder_attention_heads)`, *optional*):
990
+ Mask to nullify selected heads of the attention modules. Mask values selected in `[0, 1]`:
991
+
992
+ - 1 indicates the head is **not masked**,
993
+ - 0 indicates the head is **masked**.
994
+
995
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
996
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation.
997
+ This is useful if you want more control over how to convert `input_ids` indices into associated vectors
998
+ than the model's internal embedding lookup matrix.
999
+ output_attentions (`bool`, *optional*):
1000
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
1001
+ returned tensors for more detail.
1002
+ output_hidden_states (`bool`, *optional*):
1003
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
1004
+ for more detail.
1005
+ return_dict (`bool`, *optional*):
1006
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
1007
+ """
1008
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1009
+ output_hidden_states = (
1010
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1011
+ )
1012
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1013
+
1014
+ # retrieve input_ids and inputs_embeds
1015
+ if input_ids is not None and inputs_embeds is not None:
1016
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
1017
+ elif input_ids is not None:
1018
+ self.warn_if_padding_and_no_attention_mask(input_ids, attention_mask)
1019
+ input_shape = input_ids.size()
1020
+ input_ids = input_ids.view(-1, input_shape[-1])
1021
+ elif inputs_embeds is not None:
1022
+ input_shape = inputs_embeds.size()[:-1]
1023
+ else:
1024
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
1025
+
1026
+ if inputs_embeds is None:
1027
+ inputs_embeds = self.embed_tokens(input_ids)
1028
+
1029
+ embed_pos = self.embed_positions(input_ids, inputs_embeds)
1030
+ embed_pos = embed_pos.to(inputs_embeds.device)
1031
+
1032
+ hidden_states = inputs_embeds + embed_pos
1033
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
1034
+
1035
+ # expand attention_mask
1036
+ if attention_mask is not None:
1037
+ if self._use_flash_attention_2:
1038
+ attention_mask = attention_mask if 0 in attention_mask else None
1039
+ elif self._use_sdpa and head_mask is None and not output_attentions:
1040
+ # output_attentions=True & head_mask can not be supported when using SDPA, fall back to
1041
+ # the manual implementation that requires a 4D causal mask in all cases.
1042
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
1043
+ attention_mask = _prepare_4d_attention_mask_for_sdpa(attention_mask, inputs_embeds.dtype)
1044
+ else:
1045
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
1046
+ attention_mask = _prepare_4d_attention_mask(attention_mask, inputs_embeds.dtype)
1047
+
1048
+ encoder_states = () if output_hidden_states else None
1049
+ all_attentions = () if output_attentions else None
1050
+
1051
+ # check if head_mask has a correct number of layers specified if desired
1052
+ if head_mask is not None:
1053
+ if head_mask.size()[0] != len(self.layers):
1054
+ raise ValueError(
1055
+ f"The head_mask should be specified for {len(self.layers)} layers, but it is for"
1056
+ f" {head_mask.size()[0]}."
1057
+ )
1058
+ synced_gpus = is_deepspeed_zero3_enabled() or is_fsdp_managed_module(self)
1059
+
1060
+ for idx, encoder_layer in enumerate(self.layers):
1061
+ if output_hidden_states:
1062
+ encoder_states = encoder_states + (hidden_states,)
1063
+
1064
+ # add LayerDrop (see https://arxiv.org/abs/1909.11556 for description)
1065
+ dropout_probability = torch.rand([])
1066
+
1067
+ skip_the_layer = True if self.training and (dropout_probability < self.layerdrop) else False
1068
+ if not skip_the_layer or synced_gpus:
1069
+ # under fsdp or deepspeed zero3 all gpus must run in sync
1070
+
1071
+ if self.gradient_checkpointing and self.training:
1072
+ layer_outputs = self._gradient_checkpointing_func(
1073
+ encoder_layer.__call__,
1074
+ hidden_states,
1075
+ attention_mask,
1076
+ (head_mask[idx] if head_mask is not None else None),
1077
+ output_attentions,
1078
+ )
1079
+ else:
1080
+ layer_outputs = encoder_layer(
1081
+ hidden_states,
1082
+ attention_mask,
1083
+ layer_head_mask=(head_mask[idx] if head_mask is not None else None),
1084
+ output_attentions=output_attentions,
1085
+ )
1086
+
1087
+ hidden_states = layer_outputs[0]
1088
+
1089
+ if skip_the_layer:
1090
+ layer_outputs = (None, None)
1091
+
1092
+ if output_attentions:
1093
+ all_attentions = all_attentions + (layer_outputs[1],)
1094
+
1095
+ hidden_states = self.layer_norm(hidden_states)
1096
+
1097
+ if output_hidden_states:
1098
+ encoder_states = encoder_states + (hidden_states,)
1099
+
1100
+ if not return_dict:
1101
+ return tuple(v for v in [hidden_states, encoder_states, all_attentions] if v is not None)
1102
+ return BaseModelOutput(
1103
+ last_hidden_state=hidden_states, hidden_states=encoder_states, attentions=all_attentions
1104
+ )
1105
+
1106
+
1107
+ class M2M100Decoder(M2M100PreTrainedModel):
1108
+ """
1109
+ Transformer decoder consisting of *config.decoder_layers* layers. Each layer is a [`M2M100DecoderLayer`]
1110
+
1111
+ Args:
1112
+ config: M2M100Config
1113
+ embed_tokens (nn.Embedding): output embedding
1114
+ """
1115
+
1116
+ def __init__(self, config: M2M100Config, embed_tokens: Optional[nn.Embedding] = None):
1117
+ super().__init__(config)
1118
+ self.dropout = config.dropout
1119
+ self.layerdrop = config.decoder_layerdrop
1120
+ self.padding_idx = config.pad_token_id
1121
+ self.max_target_positions = config.max_position_embeddings
1122
+ embed_scale = math.sqrt(config.d_model) if config.scale_embedding else 1.0
1123
+
1124
+ self.embed_tokens = M2M100ScaledWordEmbedding(
1125
+ config.vocab_size, config.d_model, self.padding_idx, embed_scale=embed_scale
1126
+ )
1127
+
1128
+ if embed_tokens is not None:
1129
+ self.embed_tokens.weight = embed_tokens.weight
1130
+
1131
+ self.embed_positions = M2M100SinusoidalPositionalEmbedding(
1132
+ config.max_position_embeddings,
1133
+ config.d_model,
1134
+ self.padding_idx,
1135
+ )
1136
+ self.layers = nn.ModuleList([M2M100DecoderLayer(config) for _ in range(config.decoder_layers)])
1137
+ self._use_flash_attention_2 = config._attn_implementation == "flash_attention_2"
1138
+ self._use_sdpa = config._attn_implementation == "sdpa"
1139
+ self.layer_norm = nn.LayerNorm(config.d_model)
1140
+
1141
+ self.gradient_checkpointing = False
1142
+ # Initialize weights and apply final processing
1143
+ self.post_init()
1144
+
1145
+ def forward(
1146
+ self,
1147
+ input_ids: Optional[torch.Tensor] = None,
1148
+ attention_mask: Optional[torch.Tensor] = None,
1149
+ encoder_hidden_states: Optional[torch.Tensor] = None,
1150
+ encoder_attention_mask: Optional[torch.Tensor] = None,
1151
+ head_mask: Optional[torch.Tensor] = None,
1152
+ cross_attn_head_mask: Optional[torch.Tensor] = None,
1153
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1154
+ inputs_embeds: Optional[torch.Tensor] = None,
1155
+ use_cache: Optional[bool] = None,
1156
+ output_attentions: Optional[bool] = None,
1157
+ output_hidden_states: Optional[bool] = None,
1158
+ return_dict: Optional[bool] = None,
1159
+ ):
1160
+ r"""
1161
+ Args:
1162
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
1163
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you
1164
+ provide it.
1165
+
1166
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
1167
+ [`PreTrainedTokenizer.__call__`] for details.
1168
+
1169
+ [What are input IDs?](../glossary#input-ids)
1170
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
1171
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
1172
+
1173
+ - 1 for tokens that are **not masked**,
1174
+ - 0 for tokens that are **masked**.
1175
+
1176
+ [What are attention masks?](../glossary#attention-mask)
1177
+ encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, encoder_sequence_length, hidden_size)`, *optional*):
1178
+ Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention
1179
+ of the decoder.
1180
+ encoder_attention_mask (`torch.LongTensor` of shape `(batch_size, encoder_sequence_length)`, *optional*):
1181
+ Mask to avoid performing cross-attention on padding tokens indices of encoder input_ids. Mask values
1182
+ selected in `[0, 1]`:
1183
+
1184
+ - 1 for tokens that are **not masked**,
1185
+ - 0 for tokens that are **masked**.
1186
+
1187
+ [What are attention masks?](../glossary#attention-mask)
1188
+ head_mask (`torch.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
1189
+ Mask to nullify selected heads of the attention modules. Mask values selected in `[0, 1]`:
1190
+
1191
+ - 1 indicates the head is **not masked**,
1192
+ - 0 indicates the head is **masked**.
1193
+
1194
+ cross_attn_head_mask (`torch.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
1195
+ Mask to nullify selected heads of the cross-attention modules in the decoder to avoid performing
1196
+ cross-attention on hidden heads. Mask values selected in `[0, 1]`:
1197
+
1198
+ - 1 indicates the head is **not masked**,
1199
+ - 0 indicates the head is **masked**.
1200
+
1201
+ past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
1202
+ Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
1203
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of
1204
+ shape `(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`.
1205
+
1206
+ Contains pre-computed hidden-states (key and values in the self-attention blocks and in the
1207
+ cross-attention blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.
1208
+
1209
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those
1210
+ that don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of
1211
+ all `decoder_input_ids` of shape `(batch_size, sequence_length)`.
1212
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
1213
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation.
1214
+ This is useful if you want more control over how to convert `input_ids` indices into associated vectors
1215
+ than the model's internal embedding lookup matrix.
1216
+ output_attentions (`bool`, *optional*):
1217
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
1218
+ returned tensors for more detail.
1219
+ output_hidden_states (`bool`, *optional*):
1220
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
1221
+ for more detail.
1222
+ return_dict (`bool`, *optional*):
1223
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
1224
+ """
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
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
1230
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1231
+
1232
+ # retrieve input_ids and inputs_embeds
1233
+ if input_ids is not None and inputs_embeds is not None:
1234
+ raise ValueError("You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time")
1235
+ elif input_ids is not None:
1236
+ input_shape = input_ids.size()
1237
+ input_ids = input_ids.view(-1, input_shape[-1])
1238
+ elif inputs_embeds is not None:
1239
+ input_shape = inputs_embeds.size()[:-1]
1240
+ else:
1241
+ raise ValueError("You have to specify either decoder_input_ids or decoder_inputs_embeds")
1242
+
1243
+ # past_key_values_length
1244
+ past_key_values_length = past_key_values[0][0].shape[2] if past_key_values is not None else 0
1245
+
1246
+ if inputs_embeds is None:
1247
+ inputs_embeds = self.embed_tokens(input_ids)
1248
+
1249
+ if self._use_flash_attention_2:
1250
+ # 2d mask is passed through the layers
1251
+ combined_attention_mask = attention_mask if (attention_mask is not None and 0 in attention_mask) else None
1252
+ elif self._use_sdpa and not output_attentions and cross_attn_head_mask is None:
1253
+ # output_attentions=True & cross_attn_head_mask can not be supported when using SDPA, and we fall back on
1254
+ # the manual implementation that requires a 4D causal mask in all cases.
1255
+ combined_attention_mask = _prepare_4d_causal_attention_mask_for_sdpa(
1256
+ attention_mask,
1257
+ input_shape,
1258
+ inputs_embeds,
1259
+ past_key_values_length,
1260
+ )
1261
+ else:
1262
+ # 4d mask is passed through the layers
1263
+ combined_attention_mask = _prepare_4d_causal_attention_mask(
1264
+ attention_mask, input_shape, inputs_embeds, past_key_values_length
1265
+ )
1266
+
1267
+ # expand encoder attention mask
1268
+ if encoder_hidden_states is not None and encoder_attention_mask is not None:
1269
+ if self._use_flash_attention_2:
1270
+ encoder_attention_mask = encoder_attention_mask if 0 in encoder_attention_mask else None
1271
+ elif self._use_sdpa and cross_attn_head_mask is None and not output_attentions:
1272
+ # output_attentions=True & cross_attn_head_mask can not be supported when using SDPA, and we fall back on
1273
+ # the manual implementation that requires a 4D causal mask in all cases.
1274
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
1275
+ encoder_attention_mask = _prepare_4d_attention_mask_for_sdpa(
1276
+ encoder_attention_mask,
1277
+ inputs_embeds.dtype,
1278
+ tgt_len=input_shape[-1],
1279
+ )
1280
+ else:
1281
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
1282
+ encoder_attention_mask = _prepare_4d_attention_mask(
1283
+ encoder_attention_mask, inputs_embeds.dtype, tgt_len=input_shape[-1]
1284
+ )
1285
+
1286
+ # embed positions
1287
+ positions = self.embed_positions(input_ids, inputs_embeds, past_key_values_length)
1288
+ positions = positions.to(inputs_embeds.device)
1289
+
1290
+ hidden_states = inputs_embeds + positions
1291
+
1292
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
1293
+
1294
+ if self.gradient_checkpointing and self.training:
1295
+ if use_cache:
1296
+ logger.warning_once(
1297
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting" " `use_cache=False`..."
1298
+ )
1299
+ use_cache = False
1300
+
1301
+ # decoder layers
1302
+ all_hidden_states = () if output_hidden_states else None
1303
+ all_self_attns = () if output_attentions else None
1304
+ all_cross_attentions = () if output_attentions else None
1305
+ next_decoder_cache = () if use_cache else None
1306
+
1307
+ # check if head_mask/cross_attn_head_mask has a correct number of layers specified if desired
1308
+ for attn_mask, mask_name in zip([head_mask, cross_attn_head_mask], ["head_mask", "cross_attn_head_mask"]):
1309
+ if attn_mask is not None:
1310
+ if attn_mask.size()[0] != len(self.layers):
1311
+ raise ValueError(
1312
+ f"The `{mask_name}` should be specified for {len(self.layers)} layers, but it is for"
1313
+ f" {head_mask.size()[0]}."
1314
+ )
1315
+ synced_gpus = is_deepspeed_zero3_enabled() or is_fsdp_managed_module(self)
1316
+
1317
+ for idx, decoder_layer in enumerate(self.layers):
1318
+ if output_hidden_states:
1319
+ all_hidden_states += (hidden_states,)
1320
+
1321
+ # add LayerDrop (see https://arxiv.org/abs/1909.11556 for description)
1322
+ dropout_probability = torch.rand([])
1323
+
1324
+ skip_the_layer = True if self.training and (dropout_probability < self.layerdrop) else False
1325
+ if not skip_the_layer or synced_gpus:
1326
+ # under fsdp or deepspeed zero3 all gpus must run in sync
1327
+
1328
+ past_key_value = past_key_values[idx] if past_key_values is not None else None
1329
+
1330
+ if self.gradient_checkpointing and self.training:
1331
+ layer_outputs = self._gradient_checkpointing_func(
1332
+ decoder_layer.__call__,
1333
+ hidden_states,
1334
+ combined_attention_mask,
1335
+ encoder_hidden_states,
1336
+ encoder_attention_mask,
1337
+ head_mask[idx] if head_mask is not None else None,
1338
+ cross_attn_head_mask[idx] if cross_attn_head_mask is not None else None,
1339
+ None,
1340
+ output_attentions,
1341
+ use_cache,
1342
+ )
1343
+ else:
1344
+ layer_outputs = decoder_layer(
1345
+ hidden_states,
1346
+ attention_mask=combined_attention_mask,
1347
+ encoder_hidden_states=encoder_hidden_states,
1348
+ encoder_attention_mask=encoder_attention_mask,
1349
+ layer_head_mask=(head_mask[idx] if head_mask is not None else None),
1350
+ cross_attn_layer_head_mask=(
1351
+ cross_attn_head_mask[idx] if cross_attn_head_mask is not None else None
1352
+ ),
1353
+ past_key_value=past_key_value,
1354
+ output_attentions=output_attentions,
1355
+ use_cache=use_cache,
1356
+ )
1357
+
1358
+ hidden_states = layer_outputs[0]
1359
+
1360
+ if skip_the_layer:
1361
+ continue
1362
+
1363
+ if use_cache:
1364
+ next_decoder_cache += (layer_outputs[3 if output_attentions else 1],)
1365
+
1366
+ if output_attentions:
1367
+ all_self_attns += (layer_outputs[1],)
1368
+ all_cross_attentions += (layer_outputs[2],)
1369
+
1370
+ hidden_states = self.layer_norm(hidden_states)
1371
+
1372
+ # add hidden states from the last decoder layer
1373
+ if output_hidden_states:
1374
+ all_hidden_states += (hidden_states,)
1375
+
1376
+ next_cache = next_decoder_cache if use_cache else None
1377
+ if not return_dict:
1378
+ return tuple(
1379
+ v
1380
+ for v in [hidden_states, next_cache, all_hidden_states, all_self_attns, all_cross_attentions]
1381
+ if v is not None
1382
+ )
1383
+ return BaseModelOutputWithPastAndCrossAttentions(
1384
+ last_hidden_state=hidden_states,
1385
+ past_key_values=next_cache,
1386
+ hidden_states=all_hidden_states,
1387
+ attentions=all_self_attns,
1388
+ cross_attentions=all_cross_attentions,
1389
+ )
1390
+
1391
+
1392
+ @add_start_docstrings(
1393
+ "The bare M2M100 Model outputting raw hidden-states without any specific head on top.",
1394
+ M2M_100_START_DOCSTRING,
1395
+ )
1396
+ class M2M100Model(M2M100PreTrainedModel):
1397
+ _tied_weights_keys = ["encoder.embed_tokens.weight", "decoder.embed_tokens.weight"]
1398
+
1399
+ def __init__(self, config: M2M100Config):
1400
+ super().__init__(config)
1401
+
1402
+ padding_idx, vocab_size = config.pad_token_id, config.vocab_size
1403
+ embed_scale = math.sqrt(config.d_model) if config.scale_embedding else 1.0
1404
+ self.shared = M2M100ScaledWordEmbedding(vocab_size, config.d_model, padding_idx, embed_scale=embed_scale)
1405
+
1406
+ self.encoder = M2M100Encoder(config, self.shared)
1407
+ self.decoder = M2M100Decoder(config, self.shared)
1408
+
1409
+ if config._attn_implementation == "flash_attention_2":
1410
+ logger.warning_once(
1411
+ "Attention with Flash Attention 2 does not support `layer_head_mask`. If you need this feature, please use standard attention."
1412
+ )
1413
+
1414
+ # Initialize weights and apply final processing
1415
+ self.post_init()
1416
+
1417
+ def get_input_embeddings(self):
1418
+ return self.shared
1419
+
1420
+ def set_input_embeddings(self, value):
1421
+ self.shared = value
1422
+ self.encoder.embed_tokens = self.shared
1423
+ self.decoder.embed_tokens = self.shared
1424
+
1425
+ def _tie_weights(self):
1426
+ if self.config.tie_word_embeddings:
1427
+ self._tie_or_clone_weights(self.encoder.embed_tokens, self.shared)
1428
+ self._tie_or_clone_weights(self.decoder.embed_tokens, self.shared)
1429
+
1430
+ def get_encoder(self):
1431
+ return self.encoder
1432
+
1433
+ def get_decoder(self):
1434
+ return self.decoder
1435
+
1436
+ @add_start_docstrings_to_model_forward(M2M_100_INPUTS_DOCSTRING)
1437
+ @add_code_sample_docstrings(
1438
+ checkpoint=_CHECKPOINT_FOR_DOC,
1439
+ output_type=Seq2SeqModelOutput,
1440
+ config_class=_CONFIG_FOR_DOC,
1441
+ )
1442
+ def forward(
1443
+ self,
1444
+ input_ids: Optional[torch.LongTensor] = None,
1445
+ attention_mask: Optional[torch.Tensor] = None,
1446
+ decoder_input_ids: Optional[torch.LongTensor] = None,
1447
+ decoder_attention_mask: Optional[torch.LongTensor] = None,
1448
+ head_mask: Optional[torch.Tensor] = None,
1449
+ decoder_head_mask: Optional[torch.Tensor] = None,
1450
+ cross_attn_head_mask: Optional[torch.Tensor] = None,
1451
+ encoder_outputs: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
1452
+ past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
1453
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1454
+ decoder_inputs_embeds: Optional[torch.FloatTensor] = None,
1455
+ use_cache: Optional[bool] = None,
1456
+ output_attentions: Optional[bool] = None,
1457
+ output_hidden_states: Optional[bool] = None,
1458
+ return_dict: Optional[bool] = None,
1459
+ ) -> Union[Tuple[torch.Tensor], Seq2SeqModelOutput]:
1460
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1461
+ output_hidden_states = (
1462
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1463
+ )
1464
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
1465
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1466
+
1467
+ if encoder_outputs is None:
1468
+ encoder_outputs = self.encoder(
1469
+ input_ids=input_ids,
1470
+ attention_mask=attention_mask,
1471
+ head_mask=head_mask,
1472
+ inputs_embeds=inputs_embeds,
1473
+ output_attentions=output_attentions,
1474
+ output_hidden_states=output_hidden_states,
1475
+ return_dict=return_dict,
1476
+ )
1477
+ # If the user passed a tuple for encoder_outputs, we wrap it in a BaseModelOutput when return_dict=True
1478
+ elif return_dict and not isinstance(encoder_outputs, BaseModelOutput):
1479
+ encoder_outputs = BaseModelOutput(
1480
+ last_hidden_state=encoder_outputs[0],
1481
+ hidden_states=encoder_outputs[1] if len(encoder_outputs) > 1 else None,
1482
+ attentions=encoder_outputs[2] if len(encoder_outputs) > 2 else None,
1483
+ )
1484
+
1485
+ # decoder outputs consists of (dec_features, past_key_value, dec_hidden, dec_attn)
1486
+ decoder_outputs = self.decoder(
1487
+ input_ids=decoder_input_ids,
1488
+ attention_mask=decoder_attention_mask,
1489
+ encoder_hidden_states=encoder_outputs[0],
1490
+ encoder_attention_mask=attention_mask,
1491
+ head_mask=decoder_head_mask,
1492
+ cross_attn_head_mask=cross_attn_head_mask,
1493
+ past_key_values=past_key_values,
1494
+ inputs_embeds=decoder_inputs_embeds,
1495
+ use_cache=use_cache,
1496
+ output_attentions=output_attentions,
1497
+ output_hidden_states=output_hidden_states,
1498
+ return_dict=return_dict,
1499
+ )
1500
+
1501
+ if not return_dict:
1502
+ return decoder_outputs + encoder_outputs
1503
+
1504
+ return Seq2SeqModelOutput(
1505
+ last_hidden_state=decoder_outputs.last_hidden_state,
1506
+ past_key_values=decoder_outputs.past_key_values,
1507
+ decoder_hidden_states=decoder_outputs.hidden_states,
1508
+ decoder_attentions=decoder_outputs.attentions,
1509
+ cross_attentions=decoder_outputs.cross_attentions,
1510
+ encoder_last_hidden_state=encoder_outputs.last_hidden_state,
1511
+ encoder_hidden_states=encoder_outputs.hidden_states,
1512
+ encoder_attentions=encoder_outputs.attentions,
1513
+ )
1514
+
1515
+
1516
+ @add_start_docstrings(
1517
+ "The M2M100 Model with a language modeling head. Can be used for summarization.", M2M_100_START_DOCSTRING
1518
+ )
1519
+ class M2M100ForConditionalGeneration(M2M100PreTrainedModel, GenerationMixin):
1520
+ base_model_prefix = "model"
1521
+ _tied_weights_keys = ["encoder.embed_tokens.weight", "decoder.embed_tokens.weight", "lm_head.weight"]
1522
+
1523
+ def __init__(self, config: M2M100Config):
1524
+ super().__init__(config)
1525
+ self.model = M2M100Model(config)
1526
+ self.lm_head = nn.Linear(config.d_model, self.model.shared.num_embeddings, bias=False)
1527
+
1528
+ # Initialize weights and apply final processing
1529
+ self.post_init()
1530
+
1531
+ def get_encoder(self):
1532
+ return self.model.get_encoder()
1533
+
1534
+ def get_decoder(self):
1535
+ return self.model.get_decoder()
1536
+
1537
+ def get_output_embeddings(self):
1538
+ return self.lm_head
1539
+
1540
+ def set_output_embeddings(self, new_embeddings):
1541
+ self.lm_head = new_embeddings
1542
+
1543
+ @add_start_docstrings_to_model_forward(M2M_100_INPUTS_DOCSTRING)
1544
+ @replace_return_docstrings(output_type=Seq2SeqLMOutput, config_class=_CONFIG_FOR_DOC)
1545
+ @add_end_docstrings(M2M_100_GENERATION_EXAMPLE)
1546
+ def forward(
1547
+ self,
1548
+ input_ids: Optional[torch.LongTensor] = None,
1549
+ attention_mask: Optional[torch.Tensor] = None,
1550
+ decoder_input_ids: Optional[torch.LongTensor] = None,
1551
+ decoder_attention_mask: Optional[torch.LongTensor] = None,
1552
+ head_mask: Optional[torch.Tensor] = None,
1553
+ decoder_head_mask: Optional[torch.Tensor] = None,
1554
+ cross_attn_head_mask: Optional[torch.Tensor] = None,
1555
+ encoder_outputs: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
1556
+ past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
1557
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1558
+ decoder_inputs_embeds: Optional[torch.FloatTensor] = None,
1559
+ labels: Optional[torch.LongTensor] = None,
1560
+ use_cache: Optional[bool] = None,
1561
+ output_attentions: Optional[bool] = None,
1562
+ output_hidden_states: Optional[bool] = None,
1563
+ return_dict: Optional[bool] = None,
1564
+ ) -> Union[Tuple[torch.Tensor], Seq2SeqLMOutput]:
1565
+ r"""
1566
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1567
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1568
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1569
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1570
+
1571
+ Returns:
1572
+ """
1573
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1574
+
1575
+ if labels is not None:
1576
+ if decoder_input_ids is None:
1577
+ decoder_input_ids = shift_tokens_right(
1578
+ labels, self.config.pad_token_id, self.config.decoder_start_token_id
1579
+ )
1580
+
1581
+ outputs = self.model(
1582
+ input_ids,
1583
+ attention_mask=attention_mask,
1584
+ decoder_input_ids=decoder_input_ids,
1585
+ encoder_outputs=encoder_outputs,
1586
+ decoder_attention_mask=decoder_attention_mask,
1587
+ head_mask=head_mask,
1588
+ decoder_head_mask=decoder_head_mask,
1589
+ cross_attn_head_mask=cross_attn_head_mask,
1590
+ past_key_values=past_key_values,
1591
+ inputs_embeds=inputs_embeds,
1592
+ decoder_inputs_embeds=decoder_inputs_embeds,
1593
+ use_cache=use_cache,
1594
+ output_attentions=output_attentions,
1595
+ output_hidden_states=output_hidden_states,
1596
+ return_dict=return_dict,
1597
+ )
1598
+ lm_logits = self.lm_head(outputs[0])
1599
+
1600
+ masked_lm_loss = None
1601
+ if labels is not None:
1602
+ # move labels to the correct device to enable PP
1603
+ labels = labels.to(lm_logits.device)
1604
+ loss_fct = CrossEntropyLoss()
1605
+ masked_lm_loss = loss_fct(lm_logits.view(-1, self.config.vocab_size), labels.view(-1))
1606
+
1607
+ if not return_dict:
1608
+ output = (lm_logits,) + outputs[1:]
1609
+ return ((masked_lm_loss,) + output) if masked_lm_loss is not None else output
1610
+
1611
+ return Seq2SeqLMOutput(
1612
+ loss=masked_lm_loss,
1613
+ logits=lm_logits,
1614
+ past_key_values=outputs.past_key_values,
1615
+ decoder_hidden_states=outputs.decoder_hidden_states,
1616
+ decoder_attentions=outputs.decoder_attentions,
1617
+ cross_attentions=outputs.cross_attentions,
1618
+ encoder_last_hidden_state=outputs.encoder_last_hidden_state,
1619
+ encoder_hidden_states=outputs.encoder_hidden_states,
1620
+ encoder_attentions=outputs.encoder_attentions,
1621
+ )
1622
+
1623
+ @staticmethod
1624
+ def _reorder_cache(past_key_values, beam_idx):
1625
+ reordered_past = ()
1626
+ for layer_past in past_key_values:
1627
+ reordered_past += (
1628
+ tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
1629
+ )
1630
+ return reordered_past
1631
+
1632
+
1633
+ __all__ = ["M2M100ForConditionalGeneration", "M2M100Model", "M2M100PreTrainedModel"]
tasks/tasksmith-441eeab80047/environment/source/src/transformers/models/m2m_100/tokenization_m2m_100.py ADDED
@@ -0,0 +1,382 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2021 The Fairseq Authors and The HuggingFace Inc. 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
+ """Tokenization classes for M2M100."""
15
+
16
+ import json
17
+ import os
18
+ from pathlib import Path
19
+ from shutil import copyfile
20
+ from typing import Any, Dict, List, Optional, Tuple, Union
21
+
22
+ import sentencepiece
23
+
24
+ from ...tokenization_utils import BatchEncoding, PreTrainedTokenizer
25
+ from ...utils import logging
26
+
27
+
28
+ logger = logging.get_logger(__name__)
29
+
30
+ SPIECE_UNDERLINE = "▁"
31
+
32
+ VOCAB_FILES_NAMES = {
33
+ "vocab_file": "vocab.json",
34
+ "spm_file": "sentencepiece.bpe.model",
35
+ "tokenizer_config_file": "tokenizer_config.json",
36
+ }
37
+
38
+
39
+ # fmt: off
40
+ FAIRSEQ_LANGUAGE_CODES = {
41
+ "m2m100": ["af", "am", "ar", "ast", "az", "ba", "be", "bg", "bn", "br", "bs", "ca", "ceb", "cs", "cy", "da", "de", "el", "en", "es", "et", "fa", "ff", "fi", "fr", "fy", "ga", "gd", "gl", "gu", "ha", "he", "hi", "hr", "ht", "hu", "hy", "id", "ig", "ilo", "is", "it", "ja", "jv", "ka", "kk", "km", "kn", "ko", "lb", "lg", "ln", "lo", "lt", "lv", "mg", "mk", "ml", "mn", "mr", "ms", "my", "ne", "nl", "no", "ns", "oc", "or", "pa", "pl", "ps", "pt", "ro", "ru", "sd", "si", "sk", "sl", "so", "sq", "sr", "ss", "su", "sv", "sw", "ta", "th", "tl", "tn", "tr", "uk", "ur", "uz", "vi", "wo", "xh", "yi", "yo", "zh", "zu"],
42
+ "wmt21": ['en', 'ha', 'is', 'ja', 'cs', 'ru', 'zh', 'de']
43
+ }
44
+ # fmt: on
45
+
46
+
47
+ class M2M100Tokenizer(PreTrainedTokenizer):
48
+ """
49
+ Construct an M2M100 tokenizer. Based on [SentencePiece](https://github.com/google/sentencepiece).
50
+
51
+ This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to
52
+ this superclass for more information regarding those methods.
53
+
54
+ Args:
55
+ vocab_file (`str`):
56
+ Path to the vocabulary file.
57
+ spm_file (`str`):
58
+ Path to [SentencePiece](https://github.com/google/sentencepiece) file (generally has a .spm extension) that
59
+ contains the vocabulary.
60
+ src_lang (`str`, *optional*):
61
+ A string representing the source language.
62
+ tgt_lang (`str`, *optional*):
63
+ A string representing the target language.
64
+ eos_token (`str`, *optional*, defaults to `"</s>"`):
65
+ The end of sequence token.
66
+ sep_token (`str`, *optional*, defaults to `"</s>"`):
67
+ The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
68
+ sequence classification or for a text and a question for question answering. It is also used as the last
69
+ token of a sequence built with special tokens.
70
+ unk_token (`str`, *optional*, defaults to `"<unk>"`):
71
+ The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
72
+ token instead.
73
+ pad_token (`str`, *optional*, defaults to `"<pad>"`):
74
+ The token used for padding, for example when batching sequences of different lengths.
75
+ language_codes (`str`, *optional*, defaults to `"m2m100"`):
76
+ What language codes to use. Should be one of `"m2m100"` or `"wmt21"`.
77
+ sp_model_kwargs (`dict`, *optional*):
78
+ Will be passed to the `SentencePieceProcessor.__init__()` method. The [Python wrapper for
79
+ SentencePiece](https://github.com/google/sentencepiece/tree/master/python) can be used, among other things,
80
+ to set:
81
+
82
+ - `enable_sampling`: Enable subword regularization.
83
+ - `nbest_size`: Sampling parameters for unigram. Invalid for BPE-Dropout.
84
+
85
+ - `nbest_size = {0,1}`: No sampling is performed.
86
+ - `nbest_size > 1`: samples from the nbest_size results.
87
+ - `nbest_size < 0`: assuming that nbest_size is infinite and samples from the all hypothesis (lattice)
88
+ using forward-filtering-and-backward-sampling algorithm.
89
+
90
+ - `alpha`: Smoothing parameter for unigram sampling, and dropout probability of merge operations for
91
+ BPE-dropout.
92
+
93
+ Examples:
94
+
95
+ ```python
96
+ >>> from transformers import M2M100ForConditionalGeneration, M2M100Tokenizer
97
+
98
+ >>> model = M2M100ForConditionalGeneration.from_pretrained("facebook/m2m100_418M")
99
+ >>> tokenizer = M2M100Tokenizer.from_pretrained("facebook/m2m100_418M", src_lang="en", tgt_lang="ro")
100
+ >>> src_text = " UN Chief Says There Is No Military Solution in Syria"
101
+ >>> tgt_text = "Şeful ONU declară că nu există o soluţie militară în Siria"
102
+ >>> model_inputs = tokenizer(src_text, text_target=tgt_text, return_tensors="pt")
103
+ >>> outputs = model(**model_inputs) # should work
104
+ ```"""
105
+
106
+ vocab_files_names = VOCAB_FILES_NAMES
107
+ model_input_names = ["input_ids", "attention_mask"]
108
+
109
+ prefix_tokens: List[int] = []
110
+ suffix_tokens: List[int] = []
111
+
112
+ def __init__(
113
+ self,
114
+ vocab_file,
115
+ spm_file,
116
+ src_lang=None,
117
+ tgt_lang=None,
118
+ bos_token="<s>",
119
+ eos_token="</s>",
120
+ sep_token="</s>",
121
+ pad_token="<pad>",
122
+ unk_token="<unk>",
123
+ language_codes="m2m100",
124
+ sp_model_kwargs: Optional[Dict[str, Any]] = None,
125
+ num_madeup_words=8,
126
+ **kwargs,
127
+ ) -> None:
128
+ self.sp_model_kwargs = {} if sp_model_kwargs is None else sp_model_kwargs
129
+
130
+ self.language_codes = language_codes
131
+ fairseq_language_code = FAIRSEQ_LANGUAGE_CODES[language_codes]
132
+ self.lang_code_to_token = {lang_code: f"__{lang_code}__" for lang_code in fairseq_language_code}
133
+
134
+ additional_special_tokens = kwargs.pop("additional_special_tokens", [])
135
+ for lang_code in fairseq_language_code:
136
+ token = self.get_lang_token(lang_code)
137
+ if token not in additional_special_tokens and lang_code not in str(token) not in self.added_tokens_encoder:
138
+ additional_special_tokens.append(token)
139
+
140
+ self.vocab_file = vocab_file
141
+ self.encoder = load_json(vocab_file)
142
+ self.decoder = {v: k for k, v in self.encoder.items()}
143
+ self.spm_file = spm_file
144
+ self.sp_model = load_spm(spm_file, self.sp_model_kwargs)
145
+
146
+ self.encoder_size = len(self.encoder)
147
+
148
+ self.lang_token_to_id = {
149
+ self.get_lang_token(lang_code): self.encoder_size + i for i, lang_code in enumerate(fairseq_language_code)
150
+ }
151
+ self.lang_code_to_id = {lang_code: self.encoder_size + i for i, lang_code in enumerate(fairseq_language_code)}
152
+ self.id_to_lang_token = {v: k for k, v in self.lang_token_to_id.items()}
153
+
154
+ self._src_lang = src_lang if src_lang is not None else "en"
155
+ self.tgt_lang = tgt_lang
156
+ self.cur_lang_id = self.get_lang_id(self._src_lang)
157
+
158
+ self.num_madeup_words = num_madeup_words
159
+
160
+ super().__init__(
161
+ src_lang=src_lang,
162
+ tgt_lang=tgt_lang,
163
+ bos_token=bos_token,
164
+ eos_token=eos_token,
165
+ sep_token=sep_token,
166
+ unk_token=unk_token,
167
+ pad_token=pad_token,
168
+ language_codes=language_codes,
169
+ sp_model_kwargs=self.sp_model_kwargs,
170
+ additional_special_tokens=additional_special_tokens,
171
+ num_madeup_words=num_madeup_words,
172
+ **kwargs,
173
+ )
174
+ self.set_src_lang_special_tokens(self._src_lang)
175
+
176
+ @property
177
+ def vocab_size(self) -> int:
178
+ return len(self.encoder)
179
+
180
+ def get_vocab(self) -> Dict:
181
+ vocab = {self.convert_ids_to_tokens(i): i for i in range(self.vocab_size)}
182
+ vocab.update(self.added_tokens_encoder)
183
+ return vocab
184
+
185
+ @property
186
+ def src_lang(self) -> str:
187
+ return self._src_lang
188
+
189
+ @src_lang.setter
190
+ def src_lang(self, new_src_lang: str) -> None:
191
+ self._src_lang = new_src_lang
192
+ self.set_src_lang_special_tokens(self._src_lang)
193
+
194
+ def _tokenize(self, text: str) -> List[str]:
195
+ return self.sp_model.encode(text, out_type=str)
196
+
197
+ def _convert_token_to_id(self, token):
198
+ if token in self.lang_token_to_id:
199
+ return self.lang_token_to_id[token]
200
+ return self.encoder.get(token, self.encoder[self.unk_token])
201
+
202
+ def _convert_id_to_token(self, index: int) -> str:
203
+ """Converts an index (integer) in a token (str) using the decoder."""
204
+ if index in self.id_to_lang_token:
205
+ return self.id_to_lang_token[index]
206
+ return self.decoder.get(index, self.unk_token)
207
+
208
+ def convert_tokens_to_string(self, tokens):
209
+ """Converts a sequence of tokens (string) in a single string."""
210
+ current_sub_tokens = []
211
+ out_string = ""
212
+ for token in tokens:
213
+ # make sure that special tokens are not decoded using sentencepiece model
214
+ if token in self.all_special_tokens:
215
+ out_string += self.sp_model.decode(current_sub_tokens) + token
216
+ current_sub_tokens = []
217
+ else:
218
+ current_sub_tokens.append(token)
219
+ out_string += self.sp_model.decode(current_sub_tokens)
220
+ return out_string.strip()
221
+
222
+ def get_special_tokens_mask(
223
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None, already_has_special_tokens: bool = False
224
+ ) -> List[int]:
225
+ """
226
+ Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
227
+ special tokens using the tokenizer `prepare_for_model` method.
228
+
229
+ Args:
230
+ token_ids_0 (`List[int]`):
231
+ List of IDs.
232
+ token_ids_1 (`List[int]`, *optional*):
233
+ Optional second list of IDs for sequence pairs.
234
+ already_has_special_tokens (`bool`, *optional*, defaults to `False`):
235
+ Whether or not the token list is already formatted with special tokens for the model.
236
+
237
+ Returns:
238
+ `List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
239
+ """
240
+
241
+ if already_has_special_tokens:
242
+ return super().get_special_tokens_mask(
243
+ token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
244
+ )
245
+
246
+ prefix_ones = [1] * len(self.prefix_tokens)
247
+ suffix_ones = [1] * len(self.suffix_tokens)
248
+ if token_ids_1 is None:
249
+ return prefix_ones + ([0] * len(token_ids_0)) + suffix_ones
250
+ return prefix_ones + ([0] * len(token_ids_0)) + ([0] * len(token_ids_1)) + suffix_ones
251
+
252
+ def build_inputs_with_special_tokens(
253
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
254
+ ) -> List[int]:
255
+ """
256
+ Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
257
+ adding special tokens. An MBART sequence has the following format, where `X` represents the sequence:
258
+
259
+ - `input_ids` (for encoder) `X [eos, src_lang_code]`
260
+ - `decoder_input_ids`: (for decoder) `X [eos, tgt_lang_code]`
261
+
262
+ BOS is never used. Pairs of sequences are not the expected use case, but they will be handled without a
263
+ separator.
264
+
265
+ Args:
266
+ token_ids_0 (`List[int]`):
267
+ List of IDs to which the special tokens will be added.
268
+ token_ids_1 (`List[int]`, *optional*):
269
+ Optional second list of IDs for sequence pairs.
270
+
271
+ Returns:
272
+ `List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
273
+ """
274
+ if token_ids_1 is None:
275
+ return self.prefix_tokens + token_ids_0 + self.suffix_tokens
276
+ # We don't expect to process pairs, but leave the pair logic for API consistency
277
+ return self.prefix_tokens + token_ids_0 + token_ids_1 + self.suffix_tokens
278
+
279
+ def __getstate__(self) -> Dict:
280
+ state = self.__dict__.copy()
281
+ state["sp_model"] = None
282
+ return state
283
+
284
+ def __setstate__(self, d: Dict) -> None:
285
+ self.__dict__ = d
286
+
287
+ # for backward compatibility
288
+ if not hasattr(self, "sp_model_kwargs"):
289
+ self.sp_model_kwargs = {}
290
+
291
+ self.sp_model = load_spm(self.spm_file, self.sp_model_kwargs)
292
+
293
+ def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
294
+ save_dir = Path(save_directory)
295
+ if not save_dir.is_dir():
296
+ raise OSError(f"{save_directory} should be a directory")
297
+ vocab_save_path = save_dir / (
298
+ (filename_prefix + "-" if filename_prefix else "") + self.vocab_files_names["vocab_file"]
299
+ )
300
+ spm_save_path = save_dir / (
301
+ (filename_prefix + "-" if filename_prefix else "") + self.vocab_files_names["spm_file"]
302
+ )
303
+
304
+ save_json(self.encoder, vocab_save_path)
305
+
306
+ if os.path.abspath(self.spm_file) != os.path.abspath(spm_save_path) and os.path.isfile(self.spm_file):
307
+ copyfile(self.spm_file, spm_save_path)
308
+ elif not os.path.isfile(self.spm_file):
309
+ with open(spm_save_path, "wb") as fi:
310
+ content_spiece_model = self.sp_model.serialized_model_proto()
311
+ fi.write(content_spiece_model)
312
+
313
+ return (str(vocab_save_path), str(spm_save_path))
314
+
315
+ def prepare_seq2seq_batch(
316
+ self,
317
+ src_texts: List[str],
318
+ src_lang: str = "en",
319
+ tgt_texts: Optional[List[str]] = None,
320
+ tgt_lang: str = "ro",
321
+ **kwargs,
322
+ ) -> BatchEncoding:
323
+ self.src_lang = src_lang
324
+ self.tgt_lang = tgt_lang
325
+ self.set_src_lang_special_tokens(self.src_lang)
326
+ return super().prepare_seq2seq_batch(src_texts, tgt_texts, **kwargs)
327
+
328
+ def _build_translation_inputs(self, raw_inputs, src_lang: Optional[str], tgt_lang: Optional[str], **extra_kwargs):
329
+ """Used by translation pipeline, to prepare inputs for the generate function"""
330
+ if src_lang is None or tgt_lang is None:
331
+ raise ValueError("Translation requires a `src_lang` and a `tgt_lang` for this model")
332
+ self.src_lang = src_lang
333
+ inputs = self(raw_inputs, add_special_tokens=True, **extra_kwargs)
334
+ tgt_lang_id = self.get_lang_id(tgt_lang)
335
+ inputs["forced_bos_token_id"] = tgt_lang_id
336
+ return inputs
337
+
338
+ def _switch_to_input_mode(self):
339
+ self.set_src_lang_special_tokens(self.src_lang)
340
+
341
+ def _switch_to_target_mode(self):
342
+ self.set_tgt_lang_special_tokens(self.tgt_lang)
343
+
344
+ def set_src_lang_special_tokens(self, src_lang: str) -> None:
345
+ """Reset the special tokens to the source lang setting. No prefix and suffix=[eos, src_lang_code]."""
346
+ lang_token = self.get_lang_token(src_lang)
347
+ self.cur_lang_id = self.lang_token_to_id[lang_token]
348
+ self.prefix_tokens = [self.cur_lang_id]
349
+ self.suffix_tokens = [self.eos_token_id]
350
+
351
+ def set_tgt_lang_special_tokens(self, tgt_lang: str) -> None:
352
+ """Reset the special tokens to the target language setting. No prefix and suffix=[eos, tgt_lang_code]."""
353
+ lang_token = self.get_lang_token(tgt_lang)
354
+ self.cur_lang_id = self.lang_token_to_id[lang_token]
355
+ self.prefix_tokens = [self.cur_lang_id]
356
+ self.suffix_tokens = [self.eos_token_id]
357
+
358
+ def get_lang_token(self, lang: str) -> str:
359
+ return self.lang_code_to_token[lang]
360
+
361
+ def get_lang_id(self, lang: str) -> int:
362
+ lang_token = self.get_lang_token(lang)
363
+ return self.lang_token_to_id[lang_token]
364
+
365
+
366
+ def load_spm(path: str, sp_model_kwargs: Dict[str, Any]) -> sentencepiece.SentencePieceProcessor:
367
+ spm = sentencepiece.SentencePieceProcessor(**sp_model_kwargs)
368
+ spm.Load(str(path))
369
+ return spm
370
+
371
+
372
+ def load_json(path: str) -> Union[Dict, List]:
373
+ with open(path, "r") as f:
374
+ return json.load(f)
375
+
376
+
377
+ def save_json(data, path: str) -> None:
378
+ with open(path, "w") as f:
379
+ json.dump(data, f, indent=2)
380
+
381
+
382
+ __all__ = ["M2M100Tokenizer"]
tasks/tasksmith-441eeab80047/environment/source/src/transformers/models/mamba/__init__.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 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 _LazyModule
17
+ from ...utils.import_utils import define_import_structure
18
+
19
+
20
+ if TYPE_CHECKING:
21
+ from .configuration_mamba import *
22
+ from .modeling_mamba import *
23
+ else:
24
+ import sys
25
+
26
+ _file = globals()["__file__"]
27
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
tasks/tasksmith-441eeab80047/environment/source/src/transformers/models/mamba/configuration_mamba.py ADDED
@@ -0,0 +1,160 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 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
+ """MAMBA configuration"""
16
+
17
+ import math
18
+
19
+ from ...configuration_utils import PretrainedConfig
20
+ from ...utils import logging
21
+
22
+
23
+ logger = logging.get_logger(__name__)
24
+
25
+
26
+ class MambaConfig(PretrainedConfig):
27
+ """
28
+ This is the configuration class to store the configuration of a [`MambaModel`]. It is used to instantiate a MAMBA
29
+ model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
30
+ defaults will yield a similar configuration to that of the MAMBA
31
+ [state-spaces/mamba-2.8b](https://huggingface.co/state-spaces/mamba-2.8b) architecture.
32
+
33
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
34
+ documentation from [`PretrainedConfig`] for more information.
35
+
36
+
37
+ Args:
38
+ vocab_size (`int`, *optional*, defaults to 50280):
39
+ Vocabulary size of the MAMBA model. Defines the number of different tokens that can be represented by the
40
+ `inputs_ids` passed when calling [`MambaModel`].
41
+ hidden_size (`int`, *optional*, defaults to 768):
42
+ Dimensionality of the embeddings and hidden states.
43
+ state_size (`int`, *optional*, defaults to 16): shape of the state space latents.
44
+ num_hidden_layers (`int`, *optional*, defaults to 32):
45
+ Number of hidden layers in the model.
46
+ layer_norm_epsilon (`float`, *optional*, defaults to 1e-05):
47
+ The epsilon to use in the layer normalization layers.
48
+ pad_token_id (`int`, *optional*, defaults to 0):
49
+ Padding token id.
50
+ bos_token_id (`int`, *optional*, defaults to 0):
51
+ The id of the beginning of sentence token in the vocabulary.
52
+ eos_token_id (`int`, *optional*, defaults to 0):
53
+ The id of the end of sentence token in the vocabulary.
54
+ expand (`int`, *optional*, defaults to 2): Expanding factor used to determine the intermediate size.
55
+ conv_kernel (`int`, *optional*, defaults to 4): Size of the convolution kernel.
56
+ use_bias (`bool`, *optional*, defaults to `False`):
57
+ Whether or not to use bias in ["in_proj", "out_proj"] of the mixer block
58
+ use_conv_bias (`bool`, *optional*, defaults to `True`):
59
+ Whether or not to use bias in the convolution layer of the mixer block.
60
+ hidden_act (`str`, *optional*, defaults to `"silu"`):
61
+ The non-linear activation function (function or string) in the decoder.
62
+ initializer_range (`float`, *optional*, defaults to 0.1):
63
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
64
+ residual_in_fp32 (`bool`, *optional*, defaults to `True`):
65
+ Whether or not residuals should be in `float32`. If set to `False` residuals will keep the same `dtype` as the rest of the model
66
+ time_step_rank (`Union[int,str]`, *optional*, defaults to `"auto"`):
67
+ Rank of the discretization projection matrix. `"auto"` means that it will default to `math.ceil(self.hidden_size / 16)`
68
+ time_step_scale (`float`, *optional*, defaults to 1.0):
69
+ Scale used used to scale `dt_proj.bias`.
70
+ time_step_min (`float`, *optional*, defaults to 0.001):
71
+ Minimum `time_step` used to bound `dt_proj.bias`.
72
+ time_step_max (`float`, *optional*, defaults to 0.1):
73
+ Maximum `time_step` used to bound `dt_proj.bias`.
74
+ time_step_init_scheme (`float`, *optional*, defaults to `"random"`):
75
+ Init scheme used for `dt_proj.weight`. Should be one of `["random","uniform"]`
76
+ time_step_floor (`float`, *optional*, defaults to 0.0001):
77
+ Minimum clamping value of the `dt_proj.bias` layer initialization.
78
+ rescale_prenorm_residual (`bool`, *optional*, defaults to `False`):
79
+ Whether or not to rescale `out_proj` weights when initializing.
80
+ use_cache (`bool`, *optional*, defaults to `True`):
81
+ Whether or not the cache should be used.
82
+ use_mambapy (`bool`, *optional*, defaults to `False`):
83
+ Determines the fallback strategy during training if the CUDA-based official implementation of Mamba is not avaiable. If `True`, the mamba.py implementation is used. If `False`, the naive and slower implementation is used. Consider switching to the naive version if memory is limited.
84
+
85
+
86
+ Example:
87
+
88
+ ```python
89
+ >>> from transformers import MambaConfig, MambaModel
90
+
91
+ >>> # Initializing a Mamba configuration
92
+ >>> configuration = MambaConfig()
93
+
94
+ >>> # Initializing a model (with random weights) from the configuration
95
+ >>> model = MambaModel(configuration)
96
+
97
+ >>> # Accessing the model configuration
98
+ >>> configuration = model.config
99
+ ```"""
100
+
101
+ model_type = "mamba"
102
+
103
+ def __init__(
104
+ self,
105
+ vocab_size=50280,
106
+ hidden_size=768,
107
+ state_size=16,
108
+ num_hidden_layers=32,
109
+ layer_norm_epsilon=1e-5,
110
+ pad_token_id=0,
111
+ bos_token_id=0,
112
+ eos_token_id=0,
113
+ expand=2,
114
+ conv_kernel=4,
115
+ use_bias=False,
116
+ use_conv_bias=True,
117
+ hidden_act="silu",
118
+ initializer_range=0.1,
119
+ residual_in_fp32=True,
120
+ time_step_rank="auto",
121
+ time_step_scale=1.0,
122
+ time_step_min=0.001,
123
+ time_step_max=0.1,
124
+ time_step_init_scheme="random",
125
+ time_step_floor=1e-4,
126
+ rescale_prenorm_residual=False,
127
+ use_cache=True,
128
+ use_mambapy=False,
129
+ **kwargs,
130
+ ):
131
+ self.vocab_size = vocab_size
132
+ self.hidden_size = hidden_size
133
+ self.state_size = state_size
134
+ self.num_hidden_layers = num_hidden_layers
135
+ self.layer_norm_epsilon = layer_norm_epsilon
136
+ self.conv_kernel = conv_kernel
137
+ self.expand = expand
138
+ self.intermediate_size = int(expand * self.hidden_size)
139
+ self.bos_token_id = bos_token_id
140
+ self.eos_token_id = eos_token_id
141
+ self.pad_token_id = pad_token_id
142
+ self.use_bias = use_bias
143
+ self.use_conv_bias = use_conv_bias
144
+ self.hidden_act = hidden_act
145
+ self.initializer_range = initializer_range
146
+ self.time_step_rank = math.ceil(self.hidden_size / 16) if time_step_rank == "auto" else time_step_rank
147
+ self.time_step_scale = time_step_scale
148
+ self.time_step_min = time_step_min
149
+ self.time_step_max = time_step_max
150
+ self.time_step_init_scheme = time_step_init_scheme
151
+ self.time_step_floor = time_step_floor
152
+ self.rescale_prenorm_residual = rescale_prenorm_residual
153
+ self.residual_in_fp32 = residual_in_fp32
154
+ self.use_cache = use_cache
155
+ self.use_mambapy = use_mambapy
156
+
157
+ super().__init__(bos_token_id=bos_token_id, eos_token_id=eos_token_id, pad_token_id=pad_token_id, **kwargs)
158
+
159
+
160
+ __all__ = ["MambaConfig"]
tasks/tasksmith-441eeab80047/environment/source/src/transformers/models/mamba/convert_mamba_ssm_checkpoint_to_pytorch.py ADDED
@@ -0,0 +1,153 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 state-spaces/mamba org and 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
+ """This script can be used to convert checkpoints provided in the `mamba_ssm` library into the format provided in HuggingFace `transformers`. It depends on the `mamba_ssm` package to be installed."""
16
+
17
+ import argparse
18
+ import json
19
+ import math
20
+ from typing import Tuple
21
+
22
+ import torch
23
+
24
+ from transformers import AutoTokenizer, MambaConfig, MambaForCausalLM
25
+ from transformers.utils import logging
26
+ from transformers.utils.import_utils import is_mamba_ssm_available
27
+
28
+
29
+ if is_mamba_ssm_available():
30
+ from mamba_ssm.models.config_mamba import MambaConfig as MambaConfigSSM
31
+ from mamba_ssm.models.mixer_seq_simple import MambaLMHeadModel
32
+
33
+ def convert_ssm_config_to_hf_config(config_ssm: MambaConfigSSM) -> MambaConfig:
34
+ """Convert a MambaConfig from mamba_ssm to a MambaConfig from transformers."""
35
+ hf_config = MambaConfig()
36
+ # Set config hidden size, num hidden layers, and vocab size directly from the original config
37
+ hf_config.hidden_size = config_ssm.d_model
38
+ hf_config.intermediate_size = config_ssm.d_model * 2
39
+ hf_config.time_step_rank = math.ceil(config_ssm.d_model / 16)
40
+
41
+ hf_config.num_hidden_layers = config_ssm.n_layer
42
+ vocab_size = config_ssm.vocab_size
43
+ pad_vocab_size_multiple = config_ssm.pad_vocab_size_multiple
44
+ if (vocab_size % pad_vocab_size_multiple) != 0:
45
+ vocab_size += pad_vocab_size_multiple - (vocab_size % pad_vocab_size_multiple)
46
+ hf_config.vocab_size = vocab_size
47
+ return hf_config
48
+
49
+
50
+ logging.set_verbosity_info()
51
+ logger = logging.get_logger(__name__)
52
+
53
+
54
+ def convert_mamba_ssm_checkpoint_to_huggingface_model(
55
+ original_state_dict: dict, original_ssm_config_dict: dict
56
+ ) -> Tuple[MambaForCausalLM, AutoTokenizer]:
57
+ if not is_mamba_ssm_available():
58
+ raise ImportError(
59
+ "Calling convert_mamba_ssm_checkpoint_to_huggingface_model requires the mamba_ssm library to be installed. Please install it with `pip install mamba_ssm`."
60
+ )
61
+ original_ssm_config = MambaConfigSSM(**original_ssm_config_dict)
62
+
63
+ # Convert mamba_ssm config to huggingface MambaConfig
64
+ hf_config = convert_ssm_config_to_hf_config(original_ssm_config)
65
+
66
+ # No weights need to be renamed between the two models.
67
+ converted_state_dict = original_state_dict
68
+
69
+ # Load reshaped state dict into a huggingface model.
70
+ hf_model = MambaForCausalLM(hf_config)
71
+ tokenizer = AutoTokenizer.from_pretrained("EleutherAI/gpt-neox-20b")
72
+ hf_model.load_state_dict(converted_state_dict)
73
+ return (hf_model, tokenizer)
74
+
75
+
76
+ def validate_converted_model(
77
+ original_state_dict: dict, original_ssm_config_dict: dict, hf_model: MambaForCausalLM, tokenizer: AutoTokenizer
78
+ ) -> None:
79
+ """Validate the converted model returns the same output as the original model."""
80
+ torch_device = "cuda"
81
+
82
+ original_config = MambaConfigSSM(**original_ssm_config_dict)
83
+ original_model = MambaLMHeadModel(original_config).to(torch_device)
84
+ original_model.load_state_dict(original_state_dict)
85
+
86
+ hf_model = hf_model.to(torch_device)
87
+ input_ids = tokenizer("Hey how are you doing?", return_tensors="pt")["input_ids"].to(torch_device)
88
+ # Assert model logits are close
89
+ with torch.no_grad():
90
+ original_model_logits = original_model(input_ids).logits
91
+ hf_model_logits = hf_model(input_ids).logits
92
+ if not torch.allclose(original_model_logits, hf_model_logits, atol=1e-3):
93
+ raise ValueError("The converted model did not return the same logits as the original model.")
94
+
95
+ logger.info("Model conversion validated successfully.")
96
+
97
+
98
+ def convert_mamba_checkpoint_file_to_huggingface_model_file(
99
+ mamba_checkpoint_path: str, config_json_file: str, output_dir: str
100
+ ) -> None:
101
+ if not is_mamba_ssm_available():
102
+ raise ImportError(
103
+ "Calling convert_mamba_checkpoint_file_to_huggingface_model_file requires the mamba_ssm library to be installed. Please install it with `pip install mamba_ssm`."
104
+ )
105
+ if not torch.cuda.is_available():
106
+ raise ValueError(
107
+ "This script is to be run with a CUDA device, as the original mamba_ssm model does not support cpu."
108
+ )
109
+ logger.info(f"Loading model from {mamba_checkpoint_path} based on config from {config_json_file}")
110
+ # Load weights and config from paths
111
+ original_state_dict = torch.load(mamba_checkpoint_path, map_location="cpu")
112
+ with open(config_json_file, "r", encoding="utf-8") as json_file:
113
+ original_ssm_config_dict = json.load(json_file)
114
+
115
+ # Convert the model
116
+ hf_model, tokenizer = convert_mamba_ssm_checkpoint_to_huggingface_model(
117
+ original_state_dict, original_ssm_config_dict
118
+ )
119
+
120
+ # Validate the conversion
121
+ validate_converted_model(original_state_dict, original_ssm_config_dict, hf_model, tokenizer)
122
+
123
+ logger.info(f"Model converted successfully. Saving model to {output_dir}")
124
+
125
+ # Save new model to pytorch_dump_path
126
+ hf_model.save_pretrained(output_dir)
127
+ tokenizer.save_pretrained(output_dir)
128
+
129
+
130
+ if __name__ == "__main__":
131
+ parser = argparse.ArgumentParser()
132
+ parser.add_argument(
133
+ "-i",
134
+ "--mamba_checkpoint_file",
135
+ type=str,
136
+ required=True,
137
+ help="Path to a `pytorch_model.bin` mamba_ssm checkpoint file to be converted.",
138
+ )
139
+ parser.add_argument(
140
+ "-c",
141
+ "--config_json_file",
142
+ type=str,
143
+ required=True,
144
+ help="Path to a `config.json` file corresponding to a MambaConfig of the original mamba_ssm model.",
145
+ )
146
+ parser.add_argument(
147
+ "-o", "--output_dir", type=str, required=True, help="Path to directory to save the converted output model to."
148
+ )
149
+ args = parser.parse_args()
150
+
151
+ convert_mamba_checkpoint_file_to_huggingface_model_file(
152
+ args.mamba_checkpoint_file, args.config_json_file, args.output_dir
153
+ )
tasks/tasksmith-441eeab80047/environment/source/src/transformers/models/mamba/modeling_mamba.py ADDED
@@ -0,0 +1,813 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 state-spaces/mamba org and 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 MAMBA model."""
16
+
17
+ import math
18
+ from dataclasses import dataclass
19
+ from typing import Any, Dict, Optional, Tuple, Union
20
+
21
+ import torch
22
+ import torch.utils.checkpoint
23
+ from torch import nn
24
+ from torch.nn import CrossEntropyLoss
25
+
26
+ from ...activations import ACT2FN
27
+ from ...cache_utils import MambaCache
28
+ from ...generation import GenerationMixin
29
+ from ...modeling_utils import PreTrainedModel
30
+ from ...utils import (
31
+ ModelOutput,
32
+ add_code_sample_docstrings,
33
+ add_start_docstrings,
34
+ add_start_docstrings_to_model_forward,
35
+ logging,
36
+ )
37
+ from ...utils.import_utils import is_causal_conv1d_available, is_mamba_ssm_available, is_mambapy_available
38
+ from .configuration_mamba import MambaConfig
39
+
40
+
41
+ logger = logging.get_logger(__name__)
42
+
43
+ if is_mambapy_available():
44
+ from mambapy.pscan import pscan
45
+ else:
46
+ pscan = None
47
+
48
+ if is_mamba_ssm_available():
49
+ from mamba_ssm.ops.selective_scan_interface import mamba_inner_fn, selective_scan_fn
50
+ from mamba_ssm.ops.triton.selective_state_update import selective_state_update
51
+ else:
52
+ selective_state_update, selective_scan_fn, mamba_inner_fn = None, None, None
53
+
54
+ if is_causal_conv1d_available():
55
+ from causal_conv1d import causal_conv1d_fn, causal_conv1d_update
56
+ else:
57
+ causal_conv1d_update, causal_conv1d_fn = None, None
58
+
59
+ is_fast_path_available = all(
60
+ (selective_state_update, selective_scan_fn, causal_conv1d_fn, causal_conv1d_update, mamba_inner_fn)
61
+ )
62
+
63
+ _CHECKPOINT_FOR_DOC = "state-spaces/mamba-130m-hf"
64
+ _CONFIG_FOR_DOC = "MambaConfig"
65
+
66
+
67
+ class MambaMixer(nn.Module):
68
+ """
69
+ Compute ∆, A, B, C, and D the state space parameters and compute the `contextualized_states`.
70
+ A, D are input independent (see Mamba paper [1] Section 3.5.2 "Interpretation of A" for why A isn't selective)
71
+ ∆, B, C are input-dependent (this is a key difference between Mamba and the linear time invariant S4,
72
+ and is why Mamba is called **selective** state spaces)
73
+ """
74
+
75
+ def __init__(self, config: MambaConfig, layer_idx: int):
76
+ super().__init__()
77
+ self.config = config
78
+ self.hidden_size = config.hidden_size
79
+ self.ssm_state_size = config.state_size
80
+ self.conv_kernel_size = config.conv_kernel
81
+ self.intermediate_size = config.intermediate_size
82
+ self.time_step_rank = int(config.time_step_rank)
83
+ self.layer_idx = layer_idx
84
+ self.use_conv_bias = config.use_conv_bias
85
+ self.conv1d = nn.Conv1d(
86
+ in_channels=self.intermediate_size,
87
+ out_channels=self.intermediate_size,
88
+ bias=config.use_conv_bias,
89
+ kernel_size=config.conv_kernel,
90
+ groups=self.intermediate_size,
91
+ padding=config.conv_kernel - 1,
92
+ )
93
+
94
+ self.activation = config.hidden_act
95
+ self.act = ACT2FN[config.hidden_act]
96
+
97
+ self.use_mambapy = config.use_mambapy
98
+
99
+ # projection of the input hidden states
100
+ self.in_proj = nn.Linear(self.hidden_size, self.intermediate_size * 2, bias=config.use_bias)
101
+ # selective projection used to make dt, B and C input dependant
102
+ self.x_proj = nn.Linear(self.intermediate_size, self.time_step_rank + self.ssm_state_size * 2, bias=False)
103
+ # time step projection (discretization)
104
+ self.dt_proj = nn.Linear(self.time_step_rank, self.intermediate_size, bias=True)
105
+
106
+ # S4D real initialization. These are not discretized!
107
+ # The core is to load them, compute the discrete states, then write the updated state. Keeps the memory bounded
108
+ A = torch.arange(1, self.ssm_state_size + 1, dtype=torch.float32)[None, :]
109
+ A = A.expand(self.intermediate_size, -1).contiguous()
110
+
111
+ self.A_log = nn.Parameter(torch.log(A))
112
+ self.D = nn.Parameter(torch.ones(self.intermediate_size))
113
+ self.out_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=config.use_bias)
114
+ self.use_bias = config.use_bias
115
+
116
+ if not is_fast_path_available:
117
+ if self.use_mambapy:
118
+ if is_mambapy_available():
119
+ logger.warning_once(
120
+ "The fast path is not available because one of `(selective_state_update, selective_scan_fn, causal_conv1d_fn, causal_conv1d_update, mamba_inner_fn)`"
121
+ " is None. Falling back to the mamba.py backend. To install follow https://github.com/state-spaces/mamba/#installation and"
122
+ " https://github.com/Dao-AILab/causal-conv1d"
123
+ )
124
+ else:
125
+ raise ImportError(
126
+ "use_mambapy is set to True but the mambapy package is not installed. To install it follow https://github.com/alxndrTL/mamba.py."
127
+ )
128
+ else:
129
+ logger.warning_once(
130
+ "The fast path is not available because one of `(selective_state_update, selective_scan_fn, causal_conv1d_fn, causal_conv1d_update, mamba_inner_fn)`"
131
+ " is None. Falling back to the sequential implementation of Mamba, as use_mambapy is set to False. To install follow https://github.com/state-spaces/mamba/#installation and"
132
+ " https://github.com/Dao-AILab/causal-conv1d. For the mamba.py backend, follow https://github.com/alxndrTL/mamba.py."
133
+ )
134
+
135
+ def cuda_kernels_forward(
136
+ self,
137
+ hidden_states: torch.Tensor,
138
+ cache_params: Optional[MambaCache] = None,
139
+ cache_position: Optional[torch.LongTensor] = None,
140
+ attention_mask: Optional[torch.LongTensor] = None,
141
+ ):
142
+ # 1. Gated MLP's linear projection
143
+ projected_states = self.in_proj(hidden_states).transpose(1, 2)
144
+
145
+ if self.training and cache_params is None: # Doesn't support outputting the states -> used for training
146
+ contextualized_states = mamba_inner_fn(
147
+ projected_states,
148
+ self.conv1d.weight,
149
+ self.conv1d.bias if self.use_conv_bias else None,
150
+ self.x_proj.weight,
151
+ self.dt_proj.weight,
152
+ self.out_proj.weight,
153
+ self.out_proj.bias.float() if self.use_bias else None,
154
+ -torch.exp(self.A_log.float()),
155
+ None, # input-dependent B
156
+ None, # input-dependent C
157
+ self.D.float(),
158
+ delta_bias=self.dt_proj.bias.float(),
159
+ delta_softplus=True,
160
+ )
161
+
162
+ else:
163
+ hidden_states, gate = projected_states.chunk(2, dim=1)
164
+
165
+ if attention_mask is not None:
166
+ hidden_states = hidden_states * attention_mask.unsqueeze(1)
167
+
168
+ # 2. Convolution sequence transformation
169
+ conv_weights = self.conv1d.weight.view(self.conv1d.weight.size(0), self.conv1d.weight.size(2))
170
+ if cache_params is not None and cache_position[0] > 0:
171
+ hidden_states = causal_conv1d_update(
172
+ hidden_states.squeeze(-1),
173
+ cache_params.conv_states[self.layer_idx],
174
+ conv_weights,
175
+ self.conv1d.bias,
176
+ self.activation,
177
+ )
178
+ hidden_states = hidden_states.unsqueeze(-1)
179
+ else:
180
+ if cache_params is not None:
181
+ conv_states = nn.functional.pad(
182
+ hidden_states, (self.conv_kernel_size - hidden_states.shape[-1], 0)
183
+ )
184
+ cache_params.update_conv_state(self.layer_idx, conv_states, cache_position)
185
+ hidden_states = causal_conv1d_fn(
186
+ hidden_states, conv_weights, self.conv1d.bias, activation=self.activation
187
+ )
188
+
189
+ if attention_mask is not None:
190
+ hidden_states = hidden_states * attention_mask.unsqueeze(1)
191
+
192
+ # 3. State Space Model sequence transformation
193
+ # 3.a. input varying initialization of time_step, B and C
194
+ ssm_parameters = self.x_proj(hidden_states.transpose(1, 2))
195
+ time_step, B, C = torch.split(
196
+ ssm_parameters, [self.time_step_rank, self.ssm_state_size, self.ssm_state_size], dim=-1
197
+ )
198
+ discrete_time_step = self.dt_proj.weight @ time_step.transpose(1, 2)
199
+
200
+ A = -torch.exp(self.A_log.float())
201
+ # 3.c perform the recurrence y ← SSM(A, B, C)(x)
202
+ time_proj_bias = self.dt_proj.bias.float() if hasattr(self.dt_proj, "bias") else None
203
+ if cache_params is not None and cache_position[0] > 0:
204
+ scan_outputs = selective_state_update(
205
+ cache_params.ssm_states[self.layer_idx],
206
+ hidden_states[..., 0],
207
+ discrete_time_step[..., 0],
208
+ A,
209
+ B[:, 0],
210
+ C[:, 0],
211
+ self.D,
212
+ gate[..., 0],
213
+ time_proj_bias,
214
+ dt_softplus=True,
215
+ ).unsqueeze(-1)
216
+ else:
217
+ scan_outputs, ssm_state = selective_scan_fn(
218
+ hidden_states,
219
+ discrete_time_step,
220
+ A,
221
+ B.transpose(1, 2),
222
+ C.transpose(1, 2),
223
+ self.D.float(),
224
+ gate,
225
+ time_proj_bias,
226
+ delta_softplus=True,
227
+ return_last_state=True,
228
+ )
229
+ if ssm_state is not None and cache_params is not None:
230
+ cache_params.update_ssm_state(self.layer_idx, ssm_state)
231
+
232
+ # 4. Final linear projection
233
+ contextualized_states = self.out_proj(scan_outputs.transpose(1, 2))
234
+ return contextualized_states
235
+
236
+ # fmt: off
237
+ def slow_forward(self, input_states, cache_params: Optional[MambaCache]=None, cache_position:Optional[torch.LongTensor]=None, attention_mask: Optional[torch.LongTensor] = None):
238
+ batch_size, seq_len, _ = input_states.shape
239
+ dtype = input_states.dtype
240
+ # 1. Gated MLP's linear projection
241
+ projected_states = self.in_proj(input_states).transpose(1, 2) # [batch, 2 * intermediate_size, seq_len]
242
+ hidden_states, gate = projected_states.chunk(2, dim=1)
243
+
244
+ if attention_mask is not None:
245
+ hidden_states = hidden_states * attention_mask.unsqueeze(1)
246
+
247
+ # 2. Convolution sequence transformation
248
+ if cache_params is not None:
249
+ ssm_state = cache_params.ssm_states[self.layer_idx].clone()
250
+ ssm_state = ssm_state.to(hidden_states.device)
251
+ # use `cache_position.shape[0]` to check whether we are in prefill
252
+ # stage, it's equivalent to check `cache_position[0] == 0`, which
253
+ # breaks dynamo fullgraph constraints
254
+ if cache_position.shape[0] == self.conv_kernel_size:
255
+ conv_state = nn.functional.pad(
256
+ hidden_states,
257
+ (self.conv_kernel_size - hidden_states.shape[-1], 0)
258
+ )
259
+
260
+ cache_params.update_conv_state(self.layer_idx, conv_state, cache_position)
261
+ hidden_states = self.act(self.conv1d(hidden_states)[..., :seq_len]) # [batch, intermediate_size, seq_len]
262
+ else:
263
+ conv_state = cache_params.update_conv_state(self.layer_idx, hidden_states, cache_position)
264
+ conv_state = conv_state.to(self.conv1d.weight.device)
265
+ hidden_states = torch.sum(conv_state * self.conv1d.weight[:, 0, :], dim=-1)
266
+ if self.use_conv_bias:
267
+ hidden_states += self.conv1d.bias
268
+ hidden_states = self.act(hidden_states).to(dtype).unsqueeze(-1) # [batch, intermediate_size, 1] : decoding
269
+ else:
270
+ ssm_state = torch.zeros(
271
+ (batch_size, self.intermediate_size, self.ssm_state_size),
272
+ device=hidden_states.device, dtype=dtype
273
+ )
274
+ hidden_states = self.act(self.conv1d(hidden_states)[..., :seq_len]) # [batch, intermediate_size, seq_len]
275
+
276
+ if attention_mask is not None:
277
+ hidden_states = hidden_states * attention_mask.unsqueeze(1)
278
+
279
+ # 3. State Space Model sequence transformation
280
+ # 3.a. Selection: [batch, seq_len, self.time_step_rank + self.ssm_state_size * 2]
281
+ ssm_parameters = self.x_proj(hidden_states.transpose(1, 2))
282
+ time_step, B, C = torch.split(
283
+ ssm_parameters, [self.time_step_rank, self.ssm_state_size, self.ssm_state_size], dim=-1
284
+ )
285
+ discrete_time_step = self.dt_proj(time_step) # [batch, seq_len, intermediate_size]
286
+ discrete_time_step = nn.functional.softplus(discrete_time_step).transpose(1, 2) # [batch, intermediate_size, seq_len]
287
+
288
+ # 3.b. Discretization: B and C to [batch, seq_len, intermediate_size, ssm_state_size] (SRAM)
289
+ A = -torch.exp(self.A_log.float()) # [intermediate_size, ssm_state_size]
290
+ discrete_A = torch.exp(A[None, :, None, :] * discrete_time_step[:, :, :, None]) # [batch, intermediate_size, seq_len, ssm_state_size]
291
+ discrete_B = discrete_time_step[:, :, :, None] * B[:, None, :, :].float() # [batch, intermediate_size, seq_len, ssm_state_size]
292
+ deltaB_u = discrete_B * hidden_states[:, :, :, None].float()
293
+
294
+ # 3.c perform the recurrence y ← SSM(A, B, C)(x)
295
+ if self.use_mambapy and self.training and cache_params is None:
296
+ hs = pscan(discrete_A.transpose(1, 2), deltaB_u.transpose(1, 2)) # [batch, seq_len, intermediate_size, ssm_state_size]
297
+
298
+ scan_output = (hs @ C.unsqueeze(-1)).squeeze(3).transpose(1, 2) # [batch, intermediate_size, seq_len]
299
+ scan_output = scan_output + hidden_states * self.D[None, :, None]
300
+ scan_output = scan_output * self.act(gate)
301
+ else:
302
+ scan_outputs = []
303
+ for i in range(seq_len):
304
+ ssm_state = discrete_A[:, :, i, :] * ssm_state + deltaB_u[:, :, i, :] # [batch, intermediade_size, ssm_state]
305
+ scan_output = torch.matmul(ssm_state.to(dtype), C[:, i, :].unsqueeze(-1)) # [batch, intermediade_size, 1]
306
+ scan_outputs.append(scan_output[:, :, 0])
307
+ scan_output = torch.stack(scan_outputs, dim=-1) # [batch, seq_len, intermediade_size]
308
+ scan_output = scan_output + (hidden_states * self.D[None, :, None])
309
+ scan_output = (scan_output * self.act(gate))
310
+
311
+ if cache_params is not None:
312
+ cache_params.ssm_states[self.layer_idx].copy_(ssm_state)
313
+
314
+ # 4. Final linear projection
315
+ contextualized_states = self.out_proj(scan_output.transpose(1, 2)) # [batch, seq_len, hidden_size]
316
+ return contextualized_states
317
+ # fmt: on
318
+
319
+ def forward(
320
+ self,
321
+ hidden_states,
322
+ cache_params: Optional[MambaCache] = None,
323
+ cache_position: Optional[torch.LongTensor] = None,
324
+ attention_mask: Optional[torch.LongTensor] = None,
325
+ ):
326
+ if is_fast_path_available and "cuda" in self.x_proj.weight.device.type and not torch._dynamo.is_compiling():
327
+ return self.cuda_kernels_forward(hidden_states, cache_params, cache_position, attention_mask)
328
+ return self.slow_forward(hidden_states, cache_params, cache_position, attention_mask)
329
+
330
+
331
+ class MambaRMSNorm(nn.Module):
332
+ def __init__(self, hidden_size, eps=1e-6):
333
+ """
334
+ MambaRMSNorm is equivalent to T5LayerNorm and LlamaRMSNorm
335
+ """
336
+ super().__init__()
337
+ self.weight = nn.Parameter(torch.ones(hidden_size))
338
+ self.variance_epsilon = eps
339
+
340
+ def forward(self, hidden_states):
341
+ input_dtype = hidden_states.dtype
342
+ hidden_states = hidden_states.to(torch.float32)
343
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
344
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
345
+ return self.weight * hidden_states.to(input_dtype)
346
+
347
+ def extra_repr(self):
348
+ return f"{self.weight.shape[0]}, eps={self.variance_epsilon}"
349
+
350
+
351
+ class MambaBlock(nn.Module):
352
+ def __init__(self, config, layer_idx):
353
+ super().__init__()
354
+ self.config = config
355
+ self.layer_idx = layer_idx
356
+ self.residual_in_fp32 = config.residual_in_fp32
357
+ self.norm = MambaRMSNorm(config.hidden_size, eps=config.layer_norm_epsilon)
358
+ self.mixer = MambaMixer(config, layer_idx=layer_idx)
359
+
360
+ def forward(
361
+ self,
362
+ hidden_states,
363
+ cache_params: Optional[MambaCache] = None,
364
+ cache_position: Optional[torch.LongTensor] = None,
365
+ attention_mask: Optional[torch.LongTensor] = None,
366
+ ):
367
+ residual = hidden_states
368
+ hidden_states = self.norm(hidden_states.to(dtype=self.norm.weight.dtype))
369
+ if self.residual_in_fp32:
370
+ residual = residual.to(torch.float32)
371
+
372
+ hidden_states = self.mixer(
373
+ hidden_states, cache_params=cache_params, cache_position=cache_position, attention_mask=attention_mask
374
+ )
375
+ hidden_states = residual + hidden_states
376
+ return hidden_states
377
+
378
+
379
+ class MambaPreTrainedModel(PreTrainedModel):
380
+ """
381
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
382
+ models.
383
+ """
384
+
385
+ config_class = MambaConfig
386
+ base_model_prefix = "backbone"
387
+ _no_split_modules = ["MambaBlock", "MambaMixer"]
388
+ supports_gradient_checkpointing = True
389
+ _is_stateful = True
390
+
391
+ def _init_weights(self, module):
392
+ """Initialize the weights."""
393
+ if isinstance(module, MambaMixer):
394
+ module.A_log._no_weight_decay = True
395
+ module.D._no_weight_decay = True
396
+
397
+ dt_init_std = self.config.time_step_rank**-0.5 * self.config.time_step_scale
398
+ if self.config.time_step_init_scheme == "constant":
399
+ nn.init.constant_(module.dt_proj.weight, dt_init_std)
400
+ elif self.config.time_step_init_scheme == "random":
401
+ nn.init.uniform_(module.dt_proj.weight, -dt_init_std, dt_init_std)
402
+
403
+ dt = torch.exp(
404
+ torch.rand(self.config.intermediate_size)
405
+ * (math.log(self.config.time_step_max) - math.log(self.config.time_step_min))
406
+ + math.log(self.config.time_step_min)
407
+ ).clamp(min=self.config.time_step_floor)
408
+ # # Inverse of softplus: https://github.com/pytorch/pytorch/issues/72759
409
+ inv_dt = dt + torch.log(-torch.expm1(-dt))
410
+ with torch.no_grad():
411
+ module.dt_proj.bias.copy_(inv_dt)
412
+ module.dt_proj.bias._no_reinit = True
413
+
414
+ if isinstance(module, nn.Linear):
415
+ if module.bias is not None:
416
+ if not getattr(module.bias, "_no_reinit", False):
417
+ nn.init.zeros_(module.bias)
418
+ elif isinstance(module, nn.Embedding):
419
+ nn.init.normal_(module.weight, std=self.config.initializer_range)
420
+
421
+ if self.config.rescale_prenorm_residual:
422
+ # Reinitialize selected weights subject to the OpenAI GPT-2 Paper Scheme:
423
+ # > A modified initialization which accounts for the accumulation on the residual path with model depth. Scale
424
+ # > the weights of residual layers at initialization by a factor of 1/√N where N is the # of residual layers.
425
+ # > -- GPT-2 :: https://openai.com/blog/better-language-models/
426
+ #
427
+ # Reference (Megatron-LM): https://github.com/NVIDIA/Megatron-LM/blob/main/megatron/model/gpt_model.py
428
+ for name, p in module.named_parameters():
429
+ if name in ["out_proj.weight"]:
430
+ # Special Scaled Initialization --> There are 2 Layer Norms per Transformer Block
431
+ # Following Pytorch init, except scale by 1/sqrt(2 * n_layer)
432
+ # We need to reinit p since this code could be called multiple times
433
+ # Having just p *= scale would repeatedly scale it down
434
+ nn.init.kaiming_uniform_(p, a=math.sqrt(5))
435
+ with torch.no_grad():
436
+ p /= math.sqrt(self.config.num_hidden_layers)
437
+
438
+
439
+ @dataclass
440
+ class MambaOutput(ModelOutput):
441
+ """
442
+ Class for the MAMBA model outputs.
443
+
444
+ Args:
445
+ last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
446
+ Sequence of hidden-states at the output of the last layer of the model.
447
+ cache_params (`MambaCache`):
448
+ The state of the model at the last time step. Can be used in a forward method with the next `input_ids` to
449
+ avoid providing the old `input_ids`.
450
+
451
+ Includes both the State space model state matrices after the selective scan, and the Convolutional states
452
+ hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
453
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
454
+ one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.
455
+
456
+ Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
457
+ """
458
+
459
+ last_hidden_state: Optional[torch.FloatTensor] = None
460
+ cache_params: Optional[MambaCache] = None
461
+ hidden_states: Optional[Tuple[torch.FloatTensor]] = None
462
+
463
+
464
+ @dataclass
465
+ class MambaCausalLMOutput(ModelOutput):
466
+ """
467
+ Base class for causal language model (or autoregressive) outputs.
468
+
469
+ Args:
470
+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
471
+ Language modeling loss (for next-token prediction).
472
+ logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
473
+ Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
474
+ cache_params (`MambaCache`):
475
+ The state of the model at the last time step. Can be used in a forward method with the next `input_ids` to
476
+ avoid providing the old `input_ids`.
477
+
478
+ Includes both the State space model state matrices after the selective scan, and the Convolutional states
479
+ hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
480
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
481
+ one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.
482
+
483
+ Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
484
+ """
485
+
486
+ loss: Optional[torch.FloatTensor] = None
487
+ logits: Optional[torch.FloatTensor] = None
488
+ cache_params: Optional[MambaCache] = None
489
+ hidden_states: Optional[Tuple[torch.FloatTensor]] = None
490
+
491
+
492
+ MAMBA_START_DOCSTRING = r"""
493
+
494
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
495
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
496
+ etc.)
497
+
498
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
499
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
500
+ and behavior.
501
+
502
+ Parameters:
503
+ config ([`MambaConfig`]): Model configuration class with all the parameters of the model.
504
+ Initializing with a config file does not load the weights associated with the model, only the
505
+ configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
506
+ """
507
+
508
+ MAMBA_INPUTS_DOCSTRING = r"""
509
+ Args:
510
+ input_ids (`torch.LongTensor` of shape `(batch_size, input_ids_length)`):
511
+ Indices of input sequence tokens in the vocabulary.
512
+
513
+ If `cache_params.seqlen_offset>0`, only `input_ids` that do not have their past calculated should be passed as
514
+ `input_ids`.
515
+
516
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
517
+ [`PreTrainedTokenizer.__call__`] for details.
518
+
519
+ [What are input IDs?](../glossary#input-ids)
520
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
521
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
522
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
523
+ model's internal embedding lookup matrix.
524
+ cache_params (`MambaCache`, *optional*):
525
+ If passed along, the model uses the previous state in all the blocks (which will give the output for the
526
+ `input_ids` provided as if the model add `state_input_ids + input_ids` as context).
527
+ use_cache (`bool`, *optional*):
528
+ If set to `True`, the `cache_params` is returned and can be used to quickly generate the next logits.
529
+ output_hidden_states (`bool`, *optional*):
530
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
531
+ more detail.
532
+ return_dict (`bool`, *optional*):
533
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
534
+ cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
535
+ Indices depicting the position of the input sequence tokens in the sequence. Contrarily to `position_ids`,
536
+ this tensor is not affected by padding. It is used to update the cache in the correct position and to infer
537
+ the complete sequence length.
538
+ """
539
+
540
+
541
+ @add_start_docstrings(
542
+ "The bare MAMBA Model transformer outputting raw hidden-states without any specific head on top.",
543
+ MAMBA_START_DOCSTRING,
544
+ )
545
+ class MambaModel(MambaPreTrainedModel):
546
+ def __init__(self, config):
547
+ super().__init__(config)
548
+
549
+ self.embeddings = nn.Embedding(config.vocab_size, config.hidden_size)
550
+ self.layers = nn.ModuleList([MambaBlock(config, layer_idx=idx) for idx in range(config.num_hidden_layers)])
551
+
552
+ self.gradient_checkpointing = False
553
+ self.norm_f = MambaRMSNorm(config.hidden_size, eps=config.layer_norm_epsilon)
554
+ # Initialize weights and apply final processing
555
+ self._register_load_state_dict_pre_hook(self.load_hook)
556
+ self.post_init()
557
+
558
+ def load_hook(self, state_dict, prefix, *args):
559
+ for k in state_dict:
560
+ if "embedding." in k:
561
+ state_dict[k.replace("embedding.", "embeddings.")] = state_dict.pop(k)
562
+ break
563
+
564
+ def get_input_embeddings(self):
565
+ return self.embeddings
566
+
567
+ def set_input_embeddings(self, new_embeddings):
568
+ self.embeddings = new_embeddings
569
+
570
+ @add_start_docstrings_to_model_forward(MAMBA_INPUTS_DOCSTRING)
571
+ @add_code_sample_docstrings(
572
+ checkpoint=_CHECKPOINT_FOR_DOC,
573
+ output_type=MambaOutput,
574
+ config_class=_CONFIG_FOR_DOC,
575
+ )
576
+ def forward(
577
+ self,
578
+ input_ids: Optional[torch.LongTensor] = None,
579
+ inputs_embeds: Optional[torch.LongTensor] = None,
580
+ cache_params: Optional[MambaCache] = None,
581
+ use_cache: Optional[bool] = None,
582
+ output_hidden_states: Optional[bool] = None,
583
+ return_dict: Optional[bool] = None,
584
+ cache_position: Optional[torch.LongTensor] = None,
585
+ attention_mask: Optional[torch.LongTensor] = None,
586
+ ) -> Union[Tuple, MambaOutput]:
587
+ output_hidden_states = (
588
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
589
+ )
590
+ use_cache = use_cache if use_cache is not None else (self.config.use_cache if not self.training else False)
591
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
592
+
593
+ if (input_ids is None) ^ (inputs_embeds is not None): # ^ is python for xor
594
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
595
+
596
+ if inputs_embeds is None:
597
+ inputs_embeds = self.embeddings(input_ids)
598
+
599
+ if self.gradient_checkpointing and self.training and use_cache:
600
+ use_cache = False
601
+
602
+ if use_cache:
603
+ if cache_params is None:
604
+ cache_params = MambaCache(
605
+ self.config, inputs_embeds.size(0), device=inputs_embeds.device, dtype=inputs_embeds.dtype
606
+ )
607
+ cache_position = torch.arange(0, self.config.conv_kernel, device=inputs_embeds.device)
608
+ elif cache_position is None:
609
+ # cases when we do manual forward instead of using `model.generate` which will initiate
610
+ # `cache_position` and makes sure it is not None, throw error here instead of doing some
611
+ # hack to conjecture the current cache position
612
+ raise ValueError(
613
+ "You have to specify the `cache_position` manually when `use_cache=True` and `cache_params` is passed, "
614
+ "you don't have to pass a `cache_params` if you are in prefilling stage because in that case it will "
615
+ "be initialized for you automatically"
616
+ )
617
+ else:
618
+ cache_params = None
619
+
620
+ hidden_states = inputs_embeds
621
+ all_hidden_states = () if output_hidden_states else None
622
+ for mixer_block in self.layers:
623
+ if self.gradient_checkpointing and self.training:
624
+ hidden_states = self._gradient_checkpointing_func(
625
+ mixer_block.__call__, hidden_states, cache_params, cache_position, attention_mask
626
+ )
627
+ else:
628
+ hidden_states = mixer_block(
629
+ hidden_states,
630
+ cache_params=cache_params,
631
+ cache_position=cache_position,
632
+ attention_mask=attention_mask,
633
+ )
634
+
635
+ if output_hidden_states:
636
+ all_hidden_states = all_hidden_states + (hidden_states,)
637
+
638
+ hidden_states = self.norm_f(hidden_states)
639
+
640
+ if output_hidden_states:
641
+ all_hidden_states = all_hidden_states + (hidden_states,)
642
+
643
+ if not return_dict:
644
+ return tuple(v for v in [hidden_states, cache_params, all_hidden_states] if v is not None)
645
+
646
+ return MambaOutput(
647
+ last_hidden_state=hidden_states,
648
+ cache_params=cache_params if use_cache else None,
649
+ hidden_states=all_hidden_states,
650
+ )
651
+
652
+
653
+ @add_start_docstrings(
654
+ """
655
+ The MAMBA Model transformer with a language modeling head on top (linear layer with weights tied to the input
656
+ embeddings).
657
+ """,
658
+ MAMBA_START_DOCSTRING,
659
+ )
660
+ class MambaForCausalLM(MambaPreTrainedModel, GenerationMixin):
661
+ _tied_weights_keys = ["lm_head.weight"]
662
+
663
+ def __init__(self, config):
664
+ super().__init__(config)
665
+ self.backbone = MambaModel(config)
666
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
667
+ # Initialize weights and apply final processing
668
+ self.post_init()
669
+
670
+ def get_output_embeddings(self):
671
+ return self.lm_head
672
+
673
+ def set_output_embeddings(self, new_embeddings):
674
+ self.lm_head = new_embeddings
675
+
676
+ def get_input_embeddings(self):
677
+ return self.backbone.get_input_embeddings()
678
+
679
+ def set_input_embeddings(self, new_embeddings):
680
+ return self.backbone.set_input_embeddings(new_embeddings)
681
+
682
+ def _update_model_kwargs_for_generation(
683
+ self, outputs: ModelOutput, model_kwargs: Dict[str, Any], num_new_tokens: int = 1, **kwargs
684
+ ) -> Dict[str, Any]:
685
+ model_kwargs["cache_params"] = outputs.get("cache_params", None)
686
+ if (
687
+ model_kwargs.get("use_cache", True)
688
+ and "cache_position" in model_kwargs
689
+ and model_kwargs["cache_position"] is not None
690
+ ):
691
+ model_kwargs["cache_position"] = model_kwargs["cache_position"][-1:] + num_new_tokens
692
+
693
+ if "attention_mask" in model_kwargs:
694
+ attention_mask = model_kwargs["attention_mask"]
695
+ model_kwargs["attention_mask"] = torch.cat(
696
+ [attention_mask, attention_mask.new_ones((attention_mask.shape[0], 1))], dim=-1
697
+ )
698
+
699
+ return model_kwargs
700
+
701
+ def prepare_inputs_for_generation(
702
+ self,
703
+ input_ids,
704
+ inputs_embeds=None,
705
+ use_cache=None,
706
+ cache_params: Optional[MambaCache] = None,
707
+ cache_position: Optional[torch.LongTensor] = None,
708
+ attention_mask: Optional[torch.LongTensor] = None,
709
+ **kwargs,
710
+ ):
711
+ # Overwitten -- uses `cache_params` as opposed to `past_key_values`
712
+
713
+ if use_cache:
714
+ # `cache_position` should have been initialized in `generate`
715
+ if cache_position is None:
716
+ raise ValueError(
717
+ "`cache_position` should not be None as it should have been initialized in "
718
+ "`model.generate`, you are responsible for passing in a valid `cache_position` if "
719
+ "you are calling `prepare_inputs_for_generation` directly with `use_cache=True`"
720
+ )
721
+ if cache_position[0] > 0:
722
+ input_ids = input_ids[:, -1].unsqueeze(-1)
723
+
724
+ if attention_mask is not None:
725
+ attention_mask = None
726
+
727
+ else:
728
+ # we initialize the `cache_position` to full size of `conv_states` at prefill stage
729
+ # considering padding will be applied when input length is shorter, and truncation
730
+ # will be applied when it is longer, so it will be equivalent to always have it match
731
+ # the length of `cache_params.conv_states`, which is `config.conv_kernel`
732
+ cache_position = torch.arange(0, self.config.conv_kernel, device=input_ids.device)
733
+
734
+ if inputs_embeds is not None and cache_params is None:
735
+ model_inputs = {"inputs_embeds": inputs_embeds}
736
+ else:
737
+ model_inputs = {"input_ids": input_ids.contiguous()}
738
+
739
+ model_inputs.update(
740
+ {
741
+ "cache_params": cache_params,
742
+ "use_cache": use_cache,
743
+ "cache_position": cache_position,
744
+ "attention_mask": attention_mask,
745
+ }
746
+ )
747
+ return model_inputs
748
+
749
+ @add_start_docstrings_to_model_forward(MAMBA_INPUTS_DOCSTRING)
750
+ @add_code_sample_docstrings(
751
+ checkpoint=_CHECKPOINT_FOR_DOC,
752
+ output_type=MambaCausalLMOutput,
753
+ config_class=_CONFIG_FOR_DOC,
754
+ )
755
+ def forward(
756
+ self,
757
+ input_ids: Optional[torch.LongTensor] = None,
758
+ attention_mask: Optional[torch.LongTensor] = None,
759
+ inputs_embeds: Optional[torch.FloatTensor] = None,
760
+ cache_params: Optional[MambaCache] = None,
761
+ labels: Optional[torch.LongTensor] = None,
762
+ output_hidden_states: Optional[bool] = None,
763
+ return_dict: Optional[bool] = None,
764
+ use_cache: Optional[bool] = None,
765
+ cache_position: Optional[torch.Tensor] = None,
766
+ **kwargs, # for now we need this for generation
767
+ ) -> Union[Tuple, MambaCausalLMOutput]:
768
+ r"""
769
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
770
+ Labels for language modeling. Note that the labels **are shifted** inside the model, i.e. you can set
771
+ `labels = input_ids` Indices are selected in `[-100, 0, ..., config.vocab_size]` All labels set to `-100`
772
+ are ignored (masked), the loss is only computed for labels in `[0, ..., config.vocab_size]`
773
+ """
774
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
775
+
776
+ mamba_outputs = self.backbone(
777
+ input_ids,
778
+ cache_params=cache_params,
779
+ inputs_embeds=inputs_embeds,
780
+ output_hidden_states=output_hidden_states,
781
+ return_dict=return_dict,
782
+ use_cache=use_cache,
783
+ cache_position=cache_position,
784
+ attention_mask=attention_mask,
785
+ )
786
+ hidden_states = mamba_outputs[0]
787
+
788
+ logits = self.lm_head(hidden_states.to(self.lm_head.weight.dtype)).float()
789
+
790
+ loss = None
791
+ if labels is not None:
792
+ # move labels to correct device to enable model parallelism
793
+ labels = labels.to(logits.device)
794
+ # Shift so that tokens < n predict n
795
+ shift_logits = logits[..., :-1, :].contiguous()
796
+ shift_labels = labels[..., 1:].contiguous()
797
+ # Flatten the tokens
798
+ loss_fct = CrossEntropyLoss()
799
+ loss = loss_fct(shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1))
800
+
801
+ if not return_dict:
802
+ output = (logits,) + mamba_outputs[1:]
803
+ return ((loss,) + output) if loss is not None else output
804
+
805
+ return MambaCausalLMOutput(
806
+ loss=loss,
807
+ logits=logits,
808
+ cache_params=mamba_outputs.cache_params,
809
+ hidden_states=mamba_outputs.hidden_states,
810
+ )
811
+
812
+
813
+ __all__ = ["MambaForCausalLM", "MambaModel", "MambaPreTrainedModel"]
tasks/tasksmith-441eeab80047/environment/source/src/transformers/models/mamba2/__init__.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 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 _LazyModule
17
+ from ...utils.import_utils import define_import_structure
18
+
19
+
20
+ if TYPE_CHECKING:
21
+ from .configuration_mamba2 import *
22
+ from .modeling_mamba2 import *
23
+ else:
24
+ import sys
25
+
26
+ _file = globals()["__file__"]
27
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
tasks/tasksmith-441eeab80047/environment/source/src/transformers/models/mamba2/configuration_mamba2.py ADDED
@@ -0,0 +1,183 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 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
+ """MAMBA2 configuration"""
16
+
17
+ import math
18
+
19
+ from ...configuration_utils import PretrainedConfig
20
+ from ...utils import logging
21
+
22
+
23
+ logger = logging.get_logger(__name__)
24
+
25
+
26
+ class Mamba2Config(PretrainedConfig):
27
+ """
28
+ This is the configuration class to store the configuration of a [`Mamba2Model`]. It is used to instantiate a MAMBA2
29
+ model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
30
+ defaults will yield a similar configuration to that of the MAMBA2
31
+ [state-spaces/mamba2-2.8b](https://huggingface.co/state-spaces/mamba2-2.8b) architecture.
32
+
33
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
34
+ documentation from [`PretrainedConfig`] for more information.
35
+
36
+
37
+ Args:
38
+ num_heads (`int`, *optional*, defaults to 128):
39
+ Number of heads for the evolution matrices of mamba 2.
40
+ head_dim (`int`, *optional*, defaults to 64):
41
+ Dimension of each head.
42
+ vocab_size (`int`, *optional*, defaults to 32768):
43
+ Vocabulary size of the MAMBA2 model. Defines the number of different tokens that can be represented by the
44
+ `inputs_ids` passed when calling [`Mamba2Model`].
45
+ hidden_size (`int`, *optional*, defaults to 4096):
46
+ Dimensionality of the embeddings and hidden states.
47
+ state_size (`int`, *optional*, defaults to 128): shape of the state space latents.
48
+ num_hidden_layers (`int`, *optional*, defaults to 64):
49
+ Number of hidden layers in the model.
50
+ layer_norm_epsilon (`float`, *optional*, defaults to 1e-05):
51
+ The epsilon to use in the layer normalization layers.
52
+ pad_token_id (`int`, *optional*, defaults to 1):
53
+ Padding token id.
54
+ bos_token_id (`int`, *optional*, defaults to 0):
55
+ The id of the beginning of sentence token in the vocabulary.
56
+ eos_token_id (`int`, *optional*, defaults to 2):
57
+ The id of the end of sentence token in the vocabulary.
58
+ expand (`int`, *optional*, defaults to 2): Expanding factor used to determine the intermediate size.
59
+ conv_kernel (`int`, *optional*, defaults to 4): Size of the convolution kernel.
60
+ n_groups (`int`, *optional*, defaults to 8):
61
+ Number of groups for the evolution matrices of mamba 2.
62
+ use_bias (`bool`, *optional*, defaults to `False`):
63
+ Whether or not to use bias in ["in_proj", "out_proj"] of the mixer block
64
+ use_conv_bias (`bool`, *optional*, defaults to `True`):
65
+ Whether or not to use bias in the convolution layer of the mixer block.
66
+ hidden_act (`str`, *optional*, defaults to `"silu"`):
67
+ The non-linear activation function (function or string) in the decoder.
68
+ initializer_range (`float`, *optional*, defaults to 0.1):
69
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
70
+ residual_in_fp32 (`bool`, *optional*, defaults to `True`):
71
+ Whether or not residuals should be in `float32`. If set to `False` residuals will keep the same `dtype` as the rest of the model
72
+ time_step_rank (`Union[int,str]`, *optional*, defaults to `"auto"`):
73
+ Rank of the discretization projection matrix. `"auto"` means that it will default to `math.ceil(self.hidden_size / 16)`
74
+ time_step_min (`float`, *optional*, defaults to 0.001):
75
+ Minimum `time_step` used to bound `dt_proj.bias`.
76
+ time_step_max (`float`, *optional*, defaults to 0.1):
77
+ Maximum `time_step` used to bound `dt_proj.bias`.
78
+ time_step_floor (`float`, *optional*, defaults to 0.0001):
79
+ Minimum clamping value of the `dt_proj.bias` layer initialization.
80
+ time_step_limit (`tuple`, *optional*, defaults to `(0.0, inf)`):
81
+ Accepted range of time step values.
82
+ rescale_prenorm_residual (`bool`, *optional*, defaults to `False`):
83
+ Whether or not to rescale `out_proj` weights when initializing.
84
+ use_cache (`bool`, *optional*, defaults to `True`):
85
+ Whether or not the cache should be used.
86
+ rms_norm (`bool`, *optional*, defaults to `True`):
87
+ Whether to use RMS norm or not.
88
+ chunk_size (`int`, *optional*, defaults to 256):
89
+ Size of the chunks that will comprise the sequence.
90
+ tie_word_embeddings (`bool`, *optional*, defaults to `False`):
91
+ Whether to tie word embeddings or not.
92
+
93
+
94
+ Example:
95
+
96
+ ```python
97
+ >>> from transformers import Mamba2Config, Mamba2Model
98
+
99
+ >>> # Initializing a Mamba2 configuration
100
+ >>> configuration = Mamba2Config()
101
+
102
+ >>> # Initializing a model (with random weights) from the configuration
103
+ >>> model = Mamba2Model(configuration)
104
+
105
+ >>> # Accessing the model configuration
106
+ >>> configuration = model.config
107
+ ```"""
108
+
109
+ model_type = "mamba2"
110
+
111
+ def __init__(
112
+ self,
113
+ num_heads=128,
114
+ head_dim=64,
115
+ vocab_size=32768,
116
+ hidden_size=4096,
117
+ state_size=128,
118
+ num_hidden_layers=64,
119
+ layer_norm_epsilon=1e-5,
120
+ pad_token_id=1,
121
+ bos_token_id=0,
122
+ eos_token_id=2,
123
+ expand=2,
124
+ conv_kernel=4,
125
+ n_groups=8,
126
+ use_bias=False,
127
+ use_conv_bias=True,
128
+ hidden_act="silu",
129
+ initializer_range=0.1,
130
+ residual_in_fp32=True,
131
+ time_step_rank="auto",
132
+ time_step_min=0.001,
133
+ time_step_max=0.1,
134
+ time_step_floor=1e-4,
135
+ time_step_limit=(0.0, float("inf")),
136
+ rescale_prenorm_residual=False,
137
+ use_cache=True,
138
+ rms_norm=True,
139
+ chunk_size=256,
140
+ tie_word_embeddings=False,
141
+ **kwargs,
142
+ ):
143
+ self.vocab_size = vocab_size
144
+ self.hidden_size = hidden_size
145
+ self.state_size = state_size
146
+ self.num_hidden_layers = num_hidden_layers
147
+ self.layer_norm_epsilon = layer_norm_epsilon
148
+ self.conv_kernel = conv_kernel
149
+ self.expand = expand
150
+
151
+ self.bos_token_id = bos_token_id
152
+ self.eos_token_id = eos_token_id
153
+ self.pad_token_id = pad_token_id
154
+ self.use_bias = use_bias
155
+ self.use_conv_bias = use_conv_bias
156
+ self.hidden_act = hidden_act
157
+ self.initializer_range = initializer_range
158
+ self.time_step_rank = math.ceil(self.hidden_size / 16) if time_step_rank == "auto" else time_step_rank
159
+ self.time_step_min = time_step_min
160
+ self.time_step_max = time_step_max
161
+ self.time_step_floor = time_step_floor
162
+ self.rescale_prenorm_residual = rescale_prenorm_residual
163
+ self.residual_in_fp32 = residual_in_fp32
164
+ self.use_cache = use_cache
165
+ self.n_groups = n_groups
166
+ self.num_heads = num_heads
167
+ self.head_dim = head_dim
168
+ self.rms_norm = rms_norm
169
+ self.state_size = state_size
170
+ self.chunk_size = chunk_size
171
+ self.time_step_limit = time_step_limit
172
+ self.tie_word_embeddings = tie_word_embeddings
173
+
174
+ super().__init__(
175
+ bos_token_id=bos_token_id,
176
+ eos_token_id=eos_token_id,
177
+ pad_token_id=pad_token_id,
178
+ tie_word_embeddings=tie_word_embeddings,
179
+ **kwargs,
180
+ )
181
+
182
+
183
+ __all__ = ["Mamba2Config"]
tasks/tasksmith-441eeab80047/environment/source/src/transformers/models/mamba2/convert_mamba2_ssm_checkpoint_to_pytorch.py ADDED
@@ -0,0 +1,193 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 state-spaces/mamba2 org and 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
+ """This script can be used to convert checkpoints provided in the `mamba2_ssm` library into the format provided in HuggingFace `transformers`. It depends on the `mamba2_ssm` package to be installed."""
16
+
17
+ import argparse
18
+ import json
19
+ from functools import partial
20
+ from os import path
21
+ from typing import Dict, Optional
22
+
23
+ import torch
24
+ from safetensors import safe_open
25
+ from safetensors.torch import save_model
26
+
27
+ from transformers import GPTNeoXTokenizerFast, LlamaTokenizerFast, Mamba2Config, Mamba2ForCausalLM
28
+
29
+
30
+ def load_state_dict_from_safetensors(mamba2_checkpoint_path: str, ckpt_name: str) -> Dict[str, torch.Tensor]:
31
+ # Load weights and config from paths
32
+ original_state_dict = {}
33
+ with safe_open(path.join(mamba2_checkpoint_path, ckpt_name), framework="pt") as f:
34
+ for k in f.keys():
35
+ newk = k.removeprefix("model.")
36
+ original_state_dict[newk] = f.get_tensor(k).clone()
37
+ return original_state_dict
38
+
39
+
40
+ def load_state_dict_from_torch(mamba2_checkpoint_path: str, ckpt_name: str) -> Dict[str, torch.Tensor]:
41
+ return torch.load(path.join(mamba2_checkpoint_path, ckpt_name), map_location="cpu")
42
+
43
+
44
+ def convert_ssm_config_to_hf_config(config_ssm: Dict, mamba2_model_dict: Dict) -> Mamba2Config:
45
+ """Convert a Mamba2Config from mamba_ssm to a Mamba2Config from here."""
46
+ hf_config = Mamba2Config()
47
+
48
+ # Switch to a different dict depending on model type
49
+ config_dict = mamba2_model_dict
50
+
51
+ # Set important values from config and recalculate other resulting entries
52
+ hf_config.hidden_size = config_ssm[config_dict["hidden_size"]]
53
+ hf_config.num_heads = (hf_config.hidden_size * hf_config.expand) // hf_config.head_dim
54
+ hf_config.num_hidden_layers = config_ssm[config_dict["num_hidden_layers"]]
55
+ hf_config.n_groups = config_ssm.get(config_dict["n_groups"], 1)
56
+ hf_config.tie_word_embeddings = config_ssm["tie_embeddings"]
57
+ hf_config.bos_token_id = config_dict["bos_token_id"]
58
+ hf_config.pad_token_id = config_dict["pad_token_id"]
59
+ hf_config.eos_token_id = config_dict["eos_token_id"]
60
+
61
+ # Padded vocab size, mostly of 16 but 32 is also very common in different models
62
+ vocab_size = config_ssm["vocab_size"]
63
+ pad_vocab_size_multiple = config_ssm["pad_vocab_size_multiple"]
64
+ if (vocab_size % pad_vocab_size_multiple) != 0:
65
+ vocab_size += pad_vocab_size_multiple - (vocab_size % pad_vocab_size_multiple)
66
+ hf_config.vocab_size = vocab_size
67
+
68
+ return hf_config
69
+
70
+
71
+ def load_and_save_tokenizer(
72
+ mamba2_model_type: str,
73
+ output_dir: str,
74
+ tokenizer_model_path: Optional[str] = None,
75
+ ) -> None:
76
+ tokenizer = None
77
+
78
+ # Load tokenizer
79
+ if tokenizer_model_path is not None and mamba2_model_type == "codestral":
80
+ tokenizer_class = LlamaTokenizerFast
81
+ tokenizer = tokenizer_class(tokenizer_model_path, legacy=False, from_slow=True)
82
+ elif mamba2_model_type == "mamba_ssm":
83
+ tokenizer = GPTNeoXTokenizerFast.from_pretrained("state-spaces/mamba-130m-hf", padding_side="left")
84
+
85
+ # Save tokenizer
86
+ if tokenizer is not None:
87
+ tokenizer.save_pretrained(output_dir)
88
+
89
+
90
+ _MAMBA2_MODELS_DICT = {
91
+ "codestral": {
92
+ "hidden_size": "dim",
93
+ "num_hidden_layers": "n_layers",
94
+ "n_groups": "n_groups",
95
+ "bos_token_id": 0,
96
+ "pad_token_id": 1,
97
+ "eos_token_id": 2,
98
+ "config_name": "params.json",
99
+ "load_state_dict": partial(load_state_dict_from_safetensors, ckpt_name="consolidated.safetensors"),
100
+ "load_and_save_tokenizer": partial(load_and_save_tokenizer, "codestral"),
101
+ },
102
+ "mamba_ssm": {
103
+ "hidden_size": "d_model",
104
+ "num_hidden_layers": "n_layer",
105
+ "n_groups": "ngroups",
106
+ "bos_token_id": 0,
107
+ "pad_token_id": 0,
108
+ "eos_token_id": 0,
109
+ "config_name": "config.json",
110
+ "load_state_dict": partial(load_state_dict_from_torch, ckpt_name="pytorch_model.bin"),
111
+ "load_and_save_tokenizer": partial(load_and_save_tokenizer, "mamba_ssm"),
112
+ },
113
+ }
114
+
115
+
116
+ def convert_mamba2_checkpoint_file_to_huggingface_model_file(
117
+ mamba2_checkpoint_path: str,
118
+ mamba2_model_type: str,
119
+ precision: str,
120
+ output_dir: str,
121
+ tokenizer_model_path: Optional[str] = None,
122
+ ) -> None:
123
+ mamba2_model_dict = _MAMBA2_MODELS_DICT[mamba2_model_type]
124
+
125
+ # Load and save config based on name
126
+ config_path = path.join(mamba2_checkpoint_path, mamba2_model_dict["config_name"])
127
+ with open(config_path, "r", encoding="utf-8") as json_file:
128
+ config = json.load(json_file)
129
+ hf_config = convert_ssm_config_to_hf_config(config_ssm=config, mamba2_model_dict=mamba2_model_dict)
130
+ hf_config.save_pretrained(output_dir)
131
+
132
+ # Load state dict of the original model and transfer to hf model
133
+ original_state_dict = mamba2_model_dict["load_state_dict"](mamba2_checkpoint_path=mamba2_checkpoint_path)
134
+ hf_model = Mamba2ForCausalLM(hf_config)
135
+ hf_model.load_state_dict(original_state_dict)
136
+
137
+ # Save new model to pytorch_dump_path
138
+ dtype = torch.float32 if precision == "fp32" else (torch.bfloat16 if precision == "bf16" else torch.float16)
139
+ save_model(hf_model.to(dtype), path.join(output_dir, "model.safetensors"), metadata={"format": "pt"})
140
+
141
+ # Load and save tokenizer
142
+ mamba2_model_dict["load_and_save_tokenizer"](output_dir=output_dir, tokenizer_model_path=tokenizer_model_path)
143
+
144
+
145
+ if __name__ == "__main__":
146
+ parser = argparse.ArgumentParser()
147
+ parser.add_argument(
148
+ "-i",
149
+ "--mamba2_checkpoint_directory",
150
+ type=str,
151
+ required=True,
152
+ help="Path to a directory containing the `pytorch_model.bin` or `.safetensors` mamba2_ssm checkpoint file to be converted.",
153
+ )
154
+ parser.add_argument(
155
+ "-m",
156
+ "--mamba2_model_type",
157
+ type=str,
158
+ default="mamba_ssm",
159
+ const="mamba_ssm",
160
+ required=True,
161
+ choices=("codestral", "mamba_ssm"),
162
+ help="The model type the conversion will be performed on. Can choose from either `codestral` or `mamba_ssm`.",
163
+ )
164
+ parser.add_argument(
165
+ "-p",
166
+ "--precision",
167
+ type=str,
168
+ default="fp16",
169
+ const="fp16",
170
+ required=True,
171
+ choices=("fp32", "fp16", "bf16"),
172
+ help="The precision the model will be saved in. Select from fp32, fp16 or bf16.",
173
+ )
174
+ parser.add_argument(
175
+ "-o", "--output_dir", type=str, required=True, help="Path to directory to save the converted output model to."
176
+ )
177
+ parser.add_argument(
178
+ "-t",
179
+ "--tokenizer_model_path",
180
+ type=str,
181
+ default=None,
182
+ required=False,
183
+ help="Path to a `codestral` tokenizer file.",
184
+ )
185
+ args = parser.parse_args()
186
+
187
+ convert_mamba2_checkpoint_file_to_huggingface_model_file(
188
+ args.mamba2_checkpoint_directory,
189
+ args.mamba2_model_type,
190
+ args.precision,
191
+ args.output_dir,
192
+ args.tokenizer_model_path,
193
+ )
tasks/tasksmith-441eeab80047/environment/source/src/transformers/models/mamba2/modeling_mamba2.py ADDED
@@ -0,0 +1,1136 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 state-spaces/mamba2 org and 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 MAMBA2 model."""
16
+
17
+ import math
18
+ from dataclasses import dataclass
19
+ from typing import Optional, Tuple, Union
20
+
21
+ import torch
22
+ import torch.utils.checkpoint
23
+ from torch import nn
24
+ from torch.nn import CrossEntropyLoss
25
+
26
+ from ...activations import ACT2FN
27
+ from ...generation import GenerationMixin
28
+ from ...modeling_utils import PreTrainedModel
29
+ from ...utils import (
30
+ ModelOutput,
31
+ add_code_sample_docstrings,
32
+ add_start_docstrings,
33
+ add_start_docstrings_to_model_forward,
34
+ logging,
35
+ )
36
+ from ...utils.import_utils import is_causal_conv1d_available, is_mamba_2_ssm_available
37
+ from .configuration_mamba2 import Mamba2Config
38
+
39
+
40
+ logger = logging.get_logger(__name__)
41
+
42
+
43
+ if is_mamba_2_ssm_available():
44
+ from mamba_ssm.ops.triton.selective_state_update import selective_state_update
45
+ from mamba_ssm.ops.triton.ssd_combined import mamba_chunk_scan_combined, mamba_split_conv1d_scan_combined
46
+ else:
47
+ mamba_chunk_scan_combined, mamba_split_conv1d_scan_combined, selective_state_update = None, None, None
48
+
49
+ if is_causal_conv1d_available():
50
+ from causal_conv1d import causal_conv1d_fn, causal_conv1d_update
51
+ else:
52
+ causal_conv1d_update, causal_conv1d_fn = None, None
53
+
54
+ is_fast_path_available = all(
55
+ (
56
+ selective_state_update,
57
+ mamba_chunk_scan_combined,
58
+ mamba_split_conv1d_scan_combined,
59
+ causal_conv1d_fn,
60
+ causal_conv1d_update,
61
+ )
62
+ )
63
+
64
+ _CHECKPOINT_FOR_DOC = "mistralai/mamba-codestral-7B-v0.1"
65
+ _CONFIG_FOR_DOC = "Mamba2Config"
66
+
67
+
68
+ # Helper methods for segment sum computation
69
+
70
+
71
+ def pad_tensor_by_size(input_tensor: torch.Tensor, pad_size: int):
72
+ """
73
+ Padding x tensor with `pad_size` on the seq_len dim (dim=1)
74
+
75
+ Assumes that we only have tensors of either size 4 or 3
76
+ """
77
+ pad_shape = (0, 0, 0, 0, 0, pad_size, 0, 0) if len(input_tensor.shape) == 4 else (0, 0, 0, pad_size, 0, 0)
78
+
79
+ return torch.nn.functional.pad(input_tensor, pad_shape, mode="constant", value=0)
80
+
81
+
82
+ def reshape_into_chunks(input_tensor, pad_size, chunk_size):
83
+ """
84
+ Padding input_tensor with `pad_size` on the seq_len dim (dim=1) and
85
+ simultaneously splitting it into chunk sequences.
86
+
87
+ Assumes that we only have tensors of either size 4 or 3
88
+ """
89
+ # [bsz, seq_len, ...] -> [bsz, seq_len multiple of chunk_size, ...]
90
+ input_tensor = pad_tensor_by_size(input_tensor, pad_size)
91
+
92
+ if len(input_tensor.shape) == 3:
93
+ # [bsz, seq_len multiple of chunk_size, num_heads] -> [bsz, -1, chunk_size, num_heads]
94
+ return input_tensor.reshape(input_tensor.shape[0], -1, chunk_size, input_tensor.shape[2])
95
+ else:
96
+ # [bsz, seq_len multiple of chunk_size, num_heads, head_dim or state_size] -> [bsz, -1, chunk_size, num_heads, head_dim or state_size]
97
+ return input_tensor.reshape(
98
+ input_tensor.shape[0], -1, chunk_size, input_tensor.shape[2], input_tensor.shape[3]
99
+ )
100
+
101
+
102
+ def segment_sum(input_tensor):
103
+ """
104
+ More stable segment sum calculation. Uses cumulative sums and masking instead of direct subtractions.
105
+ """
106
+ chunk_size = input_tensor.size(-1)
107
+ # 1. expand input tensor to have an additional dimension and repeat along that dimension
108
+ # [..., chunk_size] -> [..., chunk_size, chunk_size]
109
+ input_tensor = input_tensor[..., None].expand(*input_tensor.size(), chunk_size)
110
+ # 2. create a lower triangular mask with the diagonal set to 0 to 0 out elements above diag
111
+ mask = torch.tril(torch.ones(chunk_size, chunk_size, device=input_tensor.device, dtype=torch.bool), diagonal=-1)
112
+ input_tensor = input_tensor.masked_fill(~mask, 0)
113
+ # 3. compute actual cumsum
114
+ tensor_segsum = torch.cumsum(input_tensor, dim=-2)
115
+
116
+ # 4. apply mask to keep only the lower triangular part of the cumulative sum result (incl diagonal this time)
117
+ mask = torch.tril(torch.ones(chunk_size, chunk_size, device=input_tensor.device, dtype=torch.bool), diagonal=0)
118
+ tensor_segsum = tensor_segsum.masked_fill(~mask, -torch.inf)
119
+ return tensor_segsum
120
+
121
+
122
+ def apply_mask_to_padding_states(hidden_states, attention_mask):
123
+ """
124
+ Tunes out the hidden states for padding tokens, see https://github.com/state-spaces/mamba/issues/66
125
+ """
126
+ if attention_mask is not None and attention_mask.shape[1] > 1 and attention_mask.shape[0] > 1:
127
+ dtype = hidden_states.dtype
128
+ hidden_states = (hidden_states * attention_mask[:, :, None]).to(dtype)
129
+
130
+ return hidden_states
131
+
132
+
133
+ class Mamba2Cache:
134
+ """
135
+ Arguments:
136
+ config: Mamba2Config
137
+ batch_size: int
138
+ dtype: torch.dtype
139
+ device: torch.device
140
+
141
+ Attributes:
142
+ dtype: (`torch.dtype`):
143
+ The default `dtype` used to initializing the cache.
144
+ conv_kernel_size: (`int`):
145
+ Model's convolution kernel size taken from config.
146
+ n_groups: (`int`):
147
+ Model's number of groups taken from the config - similar to tensor parallel in Transformer.
148
+ state_size: (`int`):
149
+ Model's SSM state size taken from config.
150
+ num_heads: (`int`):
151
+ The number of heads used in the linear attention / SSM.
152
+ head_dim: (`int`):
153
+ The respective dimension of the heads used in the linear attention / SSM.
154
+ intermediate_size: (`int`):
155
+ Model's intermediate_size based on (expand * hidden_dim) from config.
156
+ conv_states: (`torch.Tensor`):
157
+ A tensor of shape `[num_layers, batch_size, conv_kernel_size, intermediate_size + 2 * n_groups * state_size]` that holds convolutional states.
158
+ ssm_states: (`torch.Tensor`):
159
+ A tensor of shape `[num_layers, batch_size, num_heads, head_dim, state_size]` that holds ssm states.
160
+ """
161
+
162
+ def __init__(
163
+ self, config: Mamba2Config, batch_size: int, dtype: torch.dtype = torch.float16, device: Optional[str] = None
164
+ ):
165
+ self.dtype = dtype
166
+ self.conv_kernel_size = config.conv_kernel
167
+ self.n_groups = config.n_groups
168
+ self.state_size = config.state_size
169
+ self.num_heads = config.num_heads
170
+ self.head_dim = config.head_dim
171
+ self.intermediate_size = int(config.expand * config.hidden_size)
172
+
173
+ self.conv_states = torch.zeros(
174
+ config.num_hidden_layers,
175
+ batch_size,
176
+ self.intermediate_size + 2 * self.n_groups * self.state_size,
177
+ self.conv_kernel_size,
178
+ device=device,
179
+ dtype=dtype,
180
+ )
181
+ self.ssm_states = torch.zeros(
182
+ config.num_hidden_layers,
183
+ batch_size,
184
+ self.num_heads,
185
+ self.head_dim,
186
+ self.state_size,
187
+ device=device,
188
+ dtype=dtype,
189
+ )
190
+
191
+ def update_conv_state(
192
+ self, layer_idx: int, new_conv_state: torch.Tensor, cache_init: bool = False
193
+ ) -> torch.Tensor:
194
+ if cache_init:
195
+ self.conv_states[layer_idx] = new_conv_state.to(self.conv_states.device)
196
+ else:
197
+ self.conv_states[layer_idx] = self.conv_states[layer_idx].roll(shifts=-1, dims=-1)
198
+ self.conv_states[layer_idx][:, :, -1] = new_conv_state[:, 0, :].to(self.conv_states.device)
199
+ return self.conv_states[layer_idx]
200
+
201
+ def update_ssm_state(self, layer_idx: int, new_ssm_state: torch.Tensor):
202
+ self.ssm_states[layer_idx] = new_ssm_state.to(self.ssm_states.device)
203
+ return self.ssm_states[layer_idx]
204
+
205
+ def reset(self):
206
+ self.conv_states.zero_()
207
+ self.ssm_states.zero_()
208
+
209
+
210
+ class MambaRMSNormGated(torch.nn.Module):
211
+ def __init__(self, hidden_size, eps=1e-6):
212
+ super().__init__()
213
+ self.weight = nn.Parameter(torch.ones(hidden_size))
214
+ self.variance_epsilon = eps
215
+
216
+ def forward(self, hidden_states, gate=None):
217
+ input_dtype = hidden_states.dtype
218
+ hidden_states = hidden_states.to(torch.float32)
219
+
220
+ if gate is not None:
221
+ hidden_states = hidden_states * nn.functional.silu(gate.to(torch.float32))
222
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
223
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
224
+
225
+ return self.weight * hidden_states.to(input_dtype)
226
+
227
+
228
+ class Mamba2Mixer(nn.Module):
229
+ """
230
+ Compute ∆, A, B, C, and D the state space parameters and compute the `contextualized_states`.
231
+ A, D are input independent (see Mamba paper [1] Section 3.5.2 "Interpretation of A" for why A isn't selective)
232
+ ∆, B, C are input-dependent (this is a key difference between Mamba and the linear time invariant S4,
233
+ and is why Mamba is called **selective** state spaces)
234
+ """
235
+
236
+ def __init__(self, config: Mamba2Config, layer_idx: int):
237
+ super().__init__()
238
+ self.num_heads = config.num_heads
239
+ self.hidden_size = config.hidden_size
240
+ self.ssm_state_size = config.state_size
241
+ self.conv_kernel_size = config.conv_kernel
242
+ self.intermediate_size = int(config.expand * self.hidden_size)
243
+ self.time_step_rank = int(config.time_step_rank)
244
+ self.layer_idx = layer_idx
245
+ self.use_conv_bias = config.use_conv_bias
246
+ self.activation = config.hidden_act
247
+ self.act = ACT2FN[config.hidden_act]
248
+
249
+ self.layer_norm_epsilon = config.layer_norm_epsilon
250
+ self.rms_norm = config.rms_norm
251
+
252
+ self.n_groups = config.n_groups
253
+ self.head_dim = config.head_dim
254
+ self.chunk_size = config.chunk_size
255
+
256
+ self.time_step_limit = config.time_step_limit
257
+ self.time_step_min = config.time_step_min
258
+ self.time_step_max = config.time_step_max
259
+
260
+ self.conv_dim = self.intermediate_size + 2 * self.n_groups * self.ssm_state_size
261
+ self.conv1d = nn.Conv1d(
262
+ in_channels=self.conv_dim,
263
+ out_channels=self.conv_dim,
264
+ bias=config.use_conv_bias,
265
+ kernel_size=config.conv_kernel,
266
+ groups=self.conv_dim,
267
+ padding=config.conv_kernel - 1,
268
+ )
269
+
270
+ # projection of the input hidden states
271
+ projection_size = self.intermediate_size + self.conv_dim + self.num_heads
272
+ self.in_proj = nn.Linear(
273
+ self.hidden_size,
274
+ projection_size,
275
+ bias=config.use_bias,
276
+ )
277
+ # selective projection used to make dt, B and C input dependant
278
+
279
+ # time step projection (discretization)
280
+ # instantiate once and copy inv_dt in init_weights of PretrainedModel
281
+ self.dt_bias = nn.Parameter(torch.ones(self.num_heads))
282
+
283
+ # S4D real initialization. These are not discretized!
284
+ # The core is to load them, compute the discrete states, then write the updated state. Keeps the memory bounded
285
+ A = torch.arange(1, self.num_heads + 1)
286
+ self.A_log = nn.Parameter(torch.log(A))
287
+ self.A_log._no_weight_decay = True
288
+ self.norm = MambaRMSNormGated(self.intermediate_size, eps=self.layer_norm_epsilon)
289
+ self.D = nn.Parameter(torch.ones(self.num_heads))
290
+ self.D._no_weight_decay = True
291
+
292
+ self.out_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=config.use_bias)
293
+ self.use_bias = config.use_bias
294
+
295
+ if not is_fast_path_available:
296
+ logger.warning_once(
297
+ "The fast path is not available because on of `(selective_state_update, causal_conv1d_fn, causal_conv1d_update)`"
298
+ " is None. Falling back to the naive implementation. To install follow https://github.com/state-spaces/mamba/#installation and"
299
+ " https://github.com/Dao-AILab/causal-conv1d"
300
+ )
301
+
302
+ def cuda_kernels_forward(
303
+ self,
304
+ hidden_states: torch.Tensor,
305
+ cache_params: Optional[Mamba2Cache] = None,
306
+ cache_position: Optional[torch.LongTensor] = None,
307
+ attention_mask: Optional[torch.Tensor] = None,
308
+ ):
309
+ # 1. Gated MLP's linear projection
310
+ hidden_states = apply_mask_to_padding_states(hidden_states, attention_mask)
311
+ projected_states = self.in_proj(hidden_states)
312
+
313
+ # Set up dimensions for reshapes later
314
+ batch_size, seq_len, _ = hidden_states.shape
315
+ groups_time_state_size = self.n_groups * self.ssm_state_size
316
+ d_mlp = (
317
+ projected_states.shape[-1]
318
+ - 2 * self.intermediate_size
319
+ - 2 * self.n_groups * self.ssm_state_size
320
+ - self.num_heads
321
+ ) // 2
322
+
323
+ # Single step calculations via cache
324
+ if cache_params is not None and cache_position is not None and cache_position[0] > 0:
325
+ _, _, gate, hidden_states_B_C, dt = projected_states.squeeze(1).split(
326
+ [d_mlp, d_mlp, self.intermediate_size, self.conv_dim, self.num_heads], dim=-1
327
+ )
328
+
329
+ # 2. Convolution sequence transformation
330
+ hidden_states_B_C = causal_conv1d_update(
331
+ hidden_states_B_C,
332
+ cache_params.conv_states[self.layer_idx],
333
+ self.conv1d.weight.squeeze(1),
334
+ self.conv1d.bias,
335
+ self.activation,
336
+ )
337
+
338
+ hidden_states, B, C = torch.split(
339
+ hidden_states_B_C,
340
+ [self.intermediate_size, groups_time_state_size, groups_time_state_size],
341
+ dim=-1,
342
+ )
343
+
344
+ # 3. SSM transformation
345
+ A = -torch.exp(self.A_log.float()) # (nheads,)
346
+ A = A[:, None, ...][:, :, None].expand(-1, self.head_dim, self.ssm_state_size).to(dtype=torch.float32)
347
+ dt = dt[:, :, None].expand(-1, -1, self.head_dim)
348
+ dt_bias = self.dt_bias[:, None, ...].expand(-1, self.head_dim)
349
+ D = self.D[:, None, ...].expand(-1, self.head_dim)
350
+ B = B.view(batch_size, self.n_groups, B.shape[1] // self.n_groups)
351
+ C = C.view(batch_size, self.n_groups, C.shape[1] // self.n_groups)
352
+ hidden_states_reshaped = hidden_states.view(batch_size, self.num_heads, self.head_dim)
353
+ hidden_states = selective_state_update(
354
+ cache_params.ssm_states[self.layer_idx],
355
+ hidden_states_reshaped,
356
+ dt,
357
+ A,
358
+ B,
359
+ C,
360
+ D,
361
+ z=None,
362
+ dt_bias=dt_bias,
363
+ dt_softplus=True,
364
+ )
365
+ hidden_states = hidden_states.view(batch_size, self.num_heads * self.head_dim)
366
+ hidden_states = self.norm(hidden_states, gate)
367
+
368
+ # 4. Final linear projection
369
+ out = self.out_proj(hidden_states)[:, None, ...]
370
+
371
+ # Fused calculations or step by step if no initialized cache is found
372
+ else:
373
+ A = -torch.exp(self.A_log.float()) # (num_heads) or (intermediate_size, state_size)
374
+ dt_limit_kwargs = {} if self.time_step_limit == (0.0, float("inf")) else {"dt_limit": self.time_step_limit}
375
+
376
+ # 2-4. Fused kernel for conv1d, SSM, and the final projection
377
+ if self.training and cache_params is None:
378
+ out = mamba_split_conv1d_scan_combined(
379
+ projected_states,
380
+ self.conv1d.weight.squeeze(1),
381
+ self.conv1d.bias,
382
+ self.dt_bias,
383
+ A,
384
+ D=self.D,
385
+ chunk_size=self.chunk_size,
386
+ seq_idx=None, # was seq_idx
387
+ activation=self.activation,
388
+ rmsnorm_weight=self.norm.weight,
389
+ rmsnorm_eps=self.norm.variance_epsilon,
390
+ outproj_weight=self.out_proj.weight,
391
+ outproj_bias=self.out_proj.bias,
392
+ headdim=self.head_dim,
393
+ ngroups=self.n_groups,
394
+ norm_before_gate=False,
395
+ return_final_states=False,
396
+ **dt_limit_kwargs,
397
+ )
398
+
399
+ else:
400
+ _, _, gate, hidden_states_B_C, dt = projected_states.split(
401
+ [d_mlp, d_mlp, self.intermediate_size, self.conv_dim, self.num_heads], dim=-1
402
+ )
403
+
404
+ # 2. Convolution sequence transformation
405
+ # Init cache
406
+ if cache_params is not None:
407
+ hidden_states_B_C_transposed = hidden_states_B_C.transpose(1, 2)
408
+ conv_states = nn.functional.pad(
409
+ hidden_states_B_C_transposed,
410
+ (cache_params.conv_kernel_size - hidden_states_B_C_transposed.shape[-1], 0),
411
+ )
412
+ cache_params.update_conv_state(
413
+ layer_idx=self.layer_idx, new_conv_state=conv_states, cache_init=True
414
+ )
415
+
416
+ if self.activation not in ["silu", "swish"]:
417
+ hidden_states_B_C = self.act(
418
+ self.conv1d(hidden_states_B_C.transpose(1, 2))[..., :seq_len].transpose(1, 2)
419
+ )
420
+ else:
421
+ hidden_states_B_C = causal_conv1d_fn(
422
+ x=hidden_states_B_C.transpose(1, 2),
423
+ weight=self.conv1d.weight.squeeze(1),
424
+ bias=self.conv1d.bias,
425
+ activation=self.activation,
426
+ ).transpose(1, 2)
427
+
428
+ hidden_states_B_C = apply_mask_to_padding_states(hidden_states_B_C, attention_mask)
429
+ hidden_states, B, C = torch.split(
430
+ hidden_states_B_C,
431
+ [self.intermediate_size, groups_time_state_size, groups_time_state_size],
432
+ dim=-1,
433
+ )
434
+
435
+ # 3. SSM transformation
436
+ scan_output, ssm_state = mamba_chunk_scan_combined(
437
+ hidden_states.view(batch_size, seq_len, -1, self.head_dim),
438
+ dt,
439
+ A,
440
+ B.view(batch_size, seq_len, self.n_groups, -1),
441
+ C.view(batch_size, seq_len, self.n_groups, -1),
442
+ chunk_size=self.chunk_size,
443
+ D=self.D,
444
+ z=None,
445
+ seq_idx=None,
446
+ return_final_states=True,
447
+ dt_bias=self.dt_bias,
448
+ dt_softplus=True,
449
+ **dt_limit_kwargs,
450
+ )
451
+
452
+ # Init cache
453
+ if ssm_state is not None and cache_params is not None:
454
+ cache_params.update_ssm_state(layer_idx=self.layer_idx, new_ssm_state=ssm_state)
455
+
456
+ scan_output = scan_output.view(batch_size, seq_len, -1)
457
+ # Multiply "gate" branch and apply extra normalization layer
458
+ scan_output = self.norm(scan_output, gate)
459
+
460
+ # 4. Final linear projection
461
+ out = self.out_proj(scan_output)
462
+ return out
463
+
464
+ # fmt: off
465
+ def torch_forward(self, input_states, cache_params: Optional[Mamba2Cache]=None, cache_position:Optional[torch.LongTensor]=None, attention_mask: Optional[torch.Tensor]=None):
466
+ batch_size, seq_len, _ = input_states.shape
467
+ dtype = input_states.dtype
468
+
469
+ # 1. Gated MLP's linear projection
470
+ input_states = apply_mask_to_padding_states(input_states, attention_mask)
471
+ projected_states = self.in_proj(input_states)
472
+ d_mlp = (projected_states.shape[-1] - 2 * self.intermediate_size - 2 * self.n_groups * self.ssm_state_size-self.num_heads) // 2
473
+ _, _, gate, hidden_states_B_C, dt = projected_states.split(
474
+ [d_mlp, d_mlp, self.intermediate_size, self.conv_dim, self.num_heads], dim=-1
475
+ )
476
+
477
+ # 2. Convolution sequence transformation
478
+ if cache_params is not None and cache_position is not None and cache_position[0] > 0:
479
+ cache_params.update_conv_state(layer_idx=self.layer_idx, new_conv_state=hidden_states_B_C, cache_init=False)
480
+
481
+ # We need to guarantee that anything regarding the cache is on the same device
482
+ conv_states = cache_params.conv_states[self.layer_idx].to(device=self.conv1d.weight.device)
483
+
484
+ hidden_states_B_C = torch.sum(
485
+ conv_states * self.conv1d.weight.squeeze(1), dim=-1
486
+ )
487
+ if self.use_conv_bias:
488
+ hidden_states_B_C = hidden_states_B_C + self.conv1d.bias
489
+ hidden_states_B_C = self.act(hidden_states_B_C)
490
+ else:
491
+ # Init cache
492
+ if cache_params is not None:
493
+ hidden_states_B_C_transposed = hidden_states_B_C.transpose(1, 2)
494
+ conv_states = nn.functional.pad(
495
+ hidden_states_B_C_transposed, (cache_params.conv_kernel_size - hidden_states_B_C_transposed.shape[-1], 0)
496
+ )
497
+ cache_params.update_conv_state(layer_idx=self.layer_idx, new_conv_state=conv_states, cache_init=True)
498
+
499
+ hidden_states_B_C = self.act(self.conv1d(hidden_states_B_C.transpose(1, 2))[..., :seq_len].transpose(1, 2))
500
+
501
+ hidden_states_B_C = apply_mask_to_padding_states(hidden_states_B_C, attention_mask)
502
+ hidden_states, B, C = torch.split(
503
+ hidden_states_B_C,
504
+ [self.intermediate_size, self.n_groups * self.ssm_state_size, self.n_groups * self.ssm_state_size],
505
+ dim=-1
506
+ )
507
+
508
+ # 3. SSM transformation
509
+ A = -torch.exp(self.A_log.float()) # [num_heads]
510
+ if cache_params is not None and cache_position is not None and cache_position[0] > 0:
511
+ # We need to guarantee that anything regarding the cache is on the same device
512
+ cache_device = cache_params.ssm_states.device
513
+
514
+ # Note: there is no need to pad parameter matrices here, as there is just one new token
515
+ # for batched generation
516
+ dt = dt[:, 0, :][:, None, ...]
517
+ dt = dt.transpose(1, 2).expand(batch_size, dt.shape[-1], self.head_dim)
518
+ # [num_heads] -> [num_heads, head_dim]
519
+ dt_bias = self.dt_bias[..., None].expand(self.dt_bias.shape[0], self.head_dim)
520
+
521
+ dt = torch.nn.functional.softplus(dt + dt_bias.to(dt.dtype))
522
+ dt = torch.clamp(dt, self.time_step_limit[0], self.time_step_limit[1])
523
+ A = A[..., None, None].expand(self.num_heads, self.head_dim, self.ssm_state_size).to(dtype=torch.float32)
524
+ # [bsz, num_heads, head_dim, state_size]
525
+ dA = (torch.exp(dt[..., None] * A)).to(device=cache_device)
526
+
527
+ # Discretize B
528
+ # [bsz, n_groups * state_size] -> [bsz, n_groups, 1, state_size] ->
529
+ # -> [bsz, n_groups, group to head repetition factor, state_size] -> [bsz, num_heads, state_size]
530
+ B = B.reshape(batch_size, self.n_groups, -1)[..., None, :]
531
+ B = B.expand(batch_size, self.n_groups, self.num_heads // self.n_groups, B.shape[-1]).contiguous()
532
+ B = B.reshape(batch_size, -1, B.shape[-1])
533
+ # [bsz, num_heads, head_dim, state_size]
534
+ dB = dt[..., None] * B[..., None, :]
535
+
536
+ # Discretize x into dB
537
+ # [bsz, intermediate_size] -> [bsz, num_heads, head_dim]
538
+ hidden_states = hidden_states.reshape(batch_size, -1, self.head_dim)
539
+ dBx = (dB * hidden_states[..., None]).to(device=cache_device)
540
+
541
+ # State calculation
542
+ cache_params.update_ssm_state(
543
+ layer_idx=self.layer_idx,
544
+ new_ssm_state=cache_params.ssm_states[self.layer_idx] * dA + dBx
545
+ )
546
+
547
+ # Subsequent output
548
+ # [bsz, n_groups * state_size] -> [bsz, num_heads, state_size]
549
+ C = C.reshape(batch_size, self.n_groups, -1)[..., None, :]
550
+ C = C.expand(batch_size, self.n_groups, self.num_heads // self.n_groups, C.shape[-1]).contiguous()
551
+ C = C.reshape(batch_size, -1, C.shape[-1])
552
+ # [bsz, num_heads, head_dim]
553
+
554
+ ssm_states = cache_params.ssm_states[self.layer_idx].to(device=C.device, dtype=C.dtype) # Shape: [b, h, d, n]
555
+ # Reshape ssm_states to merge the first two dimensions
556
+ ssm_states_reshaped = ssm_states.view(batch_size * self.num_heads, self.head_dim, self.ssm_state_size) # Shape: [b*h, d, n]
557
+ C_reshaped = C.view(batch_size * self.num_heads, self.ssm_state_size, 1) # Shape: [b*h, n, 1]
558
+ y = torch.bmm(ssm_states_reshaped, C_reshaped)
559
+ y = y.view(batch_size, self.num_heads, self.head_dim)
560
+
561
+ # D skip connection
562
+ # [num_heads] -> [num_heads, head_dim]
563
+ D = self.D[..., None].expand(self.D.shape[0], self.head_dim)
564
+ y = (y + hidden_states * D).to(y.dtype)
565
+
566
+ # [bsz, num_heads, head_dim] -> [bsz, 1, intermediate_size]
567
+ y = y.reshape(batch_size, -1)[:, None, ...]
568
+ else:
569
+ # begin ssd naive implementation without einsums
570
+ dt = nn.functional.softplus(dt + self.dt_bias)
571
+ dt = torch.clamp(dt, self.time_step_limit[0], self.time_step_limit[1])
572
+ hidden_states = hidden_states.reshape(batch_size, seq_len, -1, self.head_dim).float()
573
+ B = B.reshape(batch_size, seq_len, -1, self.ssm_state_size).float()
574
+ C = C.reshape(batch_size, seq_len, -1, self.ssm_state_size).float()
575
+ B = B.repeat(1, 1, self.num_heads // self.n_groups, 1)
576
+ C = C.repeat(1, 1, self.num_heads // self.n_groups, 1)
577
+ pad_size = (self.chunk_size - seq_len % self.chunk_size) % self.chunk_size
578
+
579
+ D_residual = self.D[..., None] * pad_tensor_by_size(hidden_states, pad_size)
580
+
581
+ # Discretize x and A
582
+ hidden_states = hidden_states * dt[..., None]
583
+ A = A.to(hidden_states.dtype) * dt
584
+
585
+ # Rearrange into blocks/chunks
586
+ hidden_states, A, B, C = [reshape_into_chunks(t, pad_size, self.chunk_size) for t in (hidden_states, A, B, C)]
587
+
588
+ # [bsz, -1, chunk_size, num_heads] -> [bsz, num_heads, -1, chunk_size]
589
+ A = A.permute(0, 3, 1, 2)
590
+ A_cumsum = torch.cumsum(A, dim=-1)
591
+
592
+ # 1. Compute the output for each intra-chunk (diagonal blocks)
593
+ # This is the analog of a causal mask
594
+ L = torch.exp(segment_sum(A))
595
+
596
+ # Contraction of C and B to get G (attention-weights like)
597
+ G_intermediate = C[:, :, :, None, :, :] * B[:, :, None, :, :, :] # shape: (b, c, l, s, h, n)
598
+ G = G_intermediate.sum(dim=-1) # shape: (b, c, l, s, h)
599
+
600
+ # Compute M, equivalent to applying attention mask to weights
601
+ M_intermediate = G[..., None] * L.permute(0, 2, 3, 4, 1)[..., None]
602
+ M = M_intermediate.sum(dim=-1)
603
+
604
+ # Compute Y_diag (apply to values)
605
+ Y_diag = (M[..., None] * hidden_states[:, :, None]).sum(dim=3)
606
+
607
+ # 2. Compute the state for each intra-chunk
608
+ # (right term of low-rank factorization of off-diagonal blocks; B terms)
609
+ decay_states = torch.exp((A_cumsum[:, :, :, -1:] - A_cumsum))
610
+ B_decay = B * decay_states.permute(0, -2, -1, 1)[..., None]
611
+ states = (B_decay[..., None, :] * hidden_states[..., None]).sum(dim=2)
612
+
613
+ # 3. Compute the inter-chunk SSM recurrence; produces correct SSM states at chunk boundaries
614
+ # (middle term of factorization of off-diag blocks; A terms)
615
+ if cache_params is not None and cache_position is not None and cache_position[0] > 0:
616
+ previous_states = cache_params.ssm_states[self.layer_idx][:, None, ...].to(device=states.device)
617
+ else:
618
+ previous_states = torch.zeros_like(states[:, :1])
619
+ states = torch.cat([previous_states, states], dim=1)
620
+ decay_chunk = torch.exp(segment_sum(nn.functional.pad(A_cumsum[:, :, :, -1], (1, 0))))
621
+ decay_chunk = decay_chunk.transpose(1, 3)
622
+ new_states = (decay_chunk[..., None, None] * states[:, :, None, ...]).sum(dim=1)
623
+ states, ssm_state = new_states[:, :-1], new_states[:, -1]
624
+
625
+ # 4. Compute state -> output conversion per chunk
626
+ # (left term of low-rank factorization of off-diagonal blocks; C terms)
627
+ state_decay_out = torch.exp(A_cumsum)
628
+ C_times_states = (C[..., None, :] * states[:, :, None, ...])
629
+ state_decay_out_permuted = state_decay_out.permute(0, 2, 3, 1)
630
+ Y_off = (C_times_states.sum(-1) * state_decay_out_permuted[..., None])
631
+
632
+ # Add output of intra-chunk and inter-chunk terms (diagonal and off-diagonal blocks)
633
+ y = Y_diag + Y_off
634
+ # [bsz, -1, self.chunk_size, num_heads, head_dim] -> [bsz, (padded) seq_len, num_heads, head_dim]
635
+ y = y.reshape(batch_size, -1, self.num_heads, self.head_dim)
636
+
637
+ y = y + D_residual
638
+ # Cutting off padded chunks
639
+ if pad_size > 0:
640
+ y = y[:, :seq_len, :, :]
641
+ y = y.reshape(batch_size, seq_len, -1)
642
+
643
+ # Init cache
644
+ if ssm_state is not None and cache_params is not None:
645
+ cache_params.update_ssm_state(layer_idx=self.layer_idx, new_ssm_state=ssm_state)
646
+
647
+ scan_output = self.norm(y, gate)
648
+
649
+ # end ssd naive
650
+
651
+ # 4. Final linear projection
652
+ contextualized_states = self.out_proj(scan_output.to(dtype)) # [batch, seq_len, hidden_size]
653
+ return contextualized_states
654
+ # fmt: on
655
+
656
+ def forward(
657
+ self,
658
+ hidden_states,
659
+ cache_params: Optional[Mamba2Cache] = None,
660
+ cache_position: Optional[torch.LongTensor] = None,
661
+ attention_mask: Optional[torch.Tensor] = None,
662
+ ):
663
+ if is_fast_path_available and "cuda" in self.in_proj.weight.device.type:
664
+ return self.cuda_kernels_forward(hidden_states, cache_params, cache_position, attention_mask)
665
+ dtype = hidden_states.dtype
666
+ if attention_mask is not None and attention_mask.shape[1] > 1 and attention_mask.shape[0] > 1:
667
+ # tune out hidden states for pad tokens, see https://github.com/state-spaces/mamba/issues/66
668
+ hidden_states = (hidden_states * attention_mask[:, :, None]).to(dtype)
669
+
670
+ return self.torch_forward(hidden_states, cache_params, cache_position, attention_mask)
671
+
672
+
673
+ class Mamba2RMSNorm(nn.Module):
674
+ def __init__(self, hidden_size, eps=1e-6):
675
+ """
676
+ Mamba2RMSNorm is equivalent to T5LayerNorm and LlamaRMSNorm
677
+ """
678
+ super().__init__()
679
+ self.weight = nn.Parameter(torch.ones(hidden_size))
680
+ self.variance_epsilon = eps
681
+
682
+ def forward(self, hidden_states):
683
+ input_dtype = hidden_states.dtype
684
+ hidden_states = hidden_states.to(torch.float32)
685
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
686
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
687
+ return self.weight * hidden_states.to(input_dtype)
688
+
689
+
690
+ class Mamba2Block(nn.Module):
691
+ def __init__(self, config, layer_idx):
692
+ super().__init__()
693
+ self.config = config
694
+ self.layer_idx = layer_idx
695
+ self.residual_in_fp32 = config.residual_in_fp32
696
+ self.norm = Mamba2RMSNorm(config.hidden_size, eps=config.layer_norm_epsilon)
697
+ self.mixer = Mamba2Mixer(config, layer_idx=layer_idx)
698
+
699
+ def forward(
700
+ self,
701
+ hidden_states,
702
+ cache_params: Optional[Mamba2Cache] = None,
703
+ cache_position: Optional[torch.LongTensor] = None,
704
+ attention_mask: Optional[torch.Tensor] = None,
705
+ ):
706
+ residual = hidden_states
707
+ hidden_states = self.norm(hidden_states.to(dtype=self.norm.weight.dtype))
708
+ if self.residual_in_fp32:
709
+ residual = residual.to(torch.float32)
710
+
711
+ hidden_states = self.mixer(
712
+ hidden_states, cache_params=cache_params, cache_position=cache_position, attention_mask=attention_mask
713
+ )
714
+ hidden_states = residual + hidden_states
715
+ return hidden_states
716
+
717
+
718
+ class Mamba2PreTrainedModel(PreTrainedModel):
719
+ """
720
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
721
+ models.
722
+ """
723
+
724
+ config_class = Mamba2Config
725
+ base_model_prefix = "backbone"
726
+ _no_split_modules = ["Mamba2Block"]
727
+ supports_gradient_checkpointing = True
728
+ _is_stateful = True
729
+
730
+ def _init_weights(self, module):
731
+ """Initialize the weights."""
732
+ if isinstance(module, Mamba2Mixer):
733
+ module.A_log._no_weight_decay = True
734
+ module.D._no_weight_decay = True
735
+
736
+ dt = torch.exp(
737
+ torch.rand(self.config.num_heads)
738
+ * (math.log(self.config.time_step_max) - math.log(self.config.time_step_min))
739
+ + math.log(self.config.time_step_min)
740
+ ).clamp(min=self.config.time_step_floor)
741
+
742
+ # # Inverse of softplus: https://github.com/pytorch/pytorch/issues/72759
743
+ inv_dt = dt + torch.log(-torch.expm1(-dt))
744
+ with torch.no_grad():
745
+ module.dt_bias.copy_(inv_dt)
746
+ module.dt_bias._no_reinit = True
747
+
748
+ if isinstance(module, nn.Linear):
749
+ if module.bias is not None:
750
+ if not getattr(module.bias, "_no_reinit", False):
751
+ nn.init.zeros_(module.bias)
752
+ elif isinstance(module, nn.Embedding):
753
+ nn.init.normal_(module.weight, std=self.config.initializer_range)
754
+
755
+ if self.config.rescale_prenorm_residual:
756
+ # Reinitialize selected weights subject to the OpenAI GPT-2 Paper Scheme:
757
+ # > A modified initialization which accounts for the accumulation on the residual path with model depth. Scale
758
+ # > the weights of residual layers at initialization by a factor of 1/√N where N is the # of residual layers.
759
+ # > -- GPT-2 :: https://openai.com/blog/better-language-models/
760
+ #
761
+ # Reference (Megatron-LM): https://github.com/NVIDIA/Megatron-LM/blob/main/megatron/model/gpt_model.py
762
+ for name, p in module.named_parameters():
763
+ if name in ["out_proj.weight"]:
764
+ # Special Scaled Initialization --> There are 2 Layer Norms per Transformer Block
765
+ # Following Pytorch init, except scale by 1/sqrt(2 * n_layer)
766
+ # We need to reinit p since this code could be called multiple times
767
+ # Having just p *= scale would repeatedly scale it down
768
+ nn.init.kaiming_uniform_(p, a=math.sqrt(5))
769
+ with torch.no_grad():
770
+ p /= math.sqrt(self.config.num_hidden_layers)
771
+
772
+
773
+ @dataclass
774
+ # Copied from transformers.models.mamba.modeling_mamba.MambaOutput with MAMBA->MAMBA2,Mamba->Mamba2
775
+ class Mamba2Output(ModelOutput):
776
+ """
777
+ Class for the MAMBA2 model outputs.
778
+
779
+ Args:
780
+ last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
781
+ Sequence of hidden-states at the output of the last layer of the model.
782
+ cache_params (`Mamba2Cache`):
783
+ The state of the model at the last time step. Can be used in a forward method with the next `input_ids` to
784
+ avoid providing the old `input_ids`.
785
+
786
+ Includes both the State space model state matrices after the selective scan, and the Convolutional states
787
+ hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
788
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
789
+ one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.
790
+
791
+ Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
792
+ """
793
+
794
+ last_hidden_state: Optional[torch.FloatTensor] = None
795
+ cache_params: Optional[Mamba2Cache] = None
796
+ hidden_states: Optional[Tuple[torch.FloatTensor]] = None
797
+
798
+
799
+ @dataclass
800
+ # Copied from transformers.models.mamba.modeling_mamba.MambaCausalLMOutput with Mamba->Mamba2
801
+ class Mamba2CausalLMOutput(ModelOutput):
802
+ """
803
+ Base class for causal language model (or autoregressive) outputs.
804
+
805
+ Args:
806
+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
807
+ Language modeling loss (for next-token prediction).
808
+ logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
809
+ Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
810
+ cache_params (`Mamba2Cache`):
811
+ The state of the model at the last time step. Can be used in a forward method with the next `input_ids` to
812
+ avoid providing the old `input_ids`.
813
+
814
+ Includes both the State space model state matrices after the selective scan, and the Convolutional states
815
+ hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
816
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
817
+ one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.
818
+
819
+ Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
820
+ """
821
+
822
+ loss: Optional[torch.FloatTensor] = None
823
+ logits: Optional[torch.FloatTensor] = None
824
+ cache_params: Optional[Mamba2Cache] = None
825
+ hidden_states: Optional[Tuple[torch.FloatTensor]] = None
826
+
827
+
828
+ MAMBA2_START_DOCSTRING = r"""
829
+
830
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
831
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
832
+ etc.)
833
+
834
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
835
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
836
+ and behavior.
837
+
838
+ Parameters:
839
+ config ([`Mamba2Config`]): Model configuration class with all the parameters of the model.
840
+ Initializing with a config file does not load the weights associated with the model, only the
841
+ configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
842
+ """
843
+
844
+ MAMBA2_INPUTS_DOCSTRING = r"""
845
+ Args:
846
+ input_ids (`torch.LongTensor` of shape `(batch_size, input_ids_length)`):
847
+ Indices of input sequence tokens in the vocabulary.
848
+
849
+ If `cache_params.seqlen_offset>0`, only `input_ids` that do not have their past calculated should be passed as
850
+ `input_ids`.
851
+
852
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
853
+ [`PreTrainedTokenizer.__call__`] for details.
854
+
855
+ [What are input IDs?](../glossary#input-ids)
856
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
857
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
858
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
859
+ model's internal embedding lookup matrix.
860
+ cache_params (`Mamba2Cache`, *optional*):
861
+ If passed along, the model uses the previous state in all the blocks (which will give the output for the
862
+ `input_ids` provided as if the model add `state_input_ids + input_ids` as context).
863
+ use_cache (`bool`, *optional*):
864
+ If set to `True`, the `cache_params` is returned and can be used to quickly generate the next logits.
865
+ output_hidden_states (`bool`, *optional*):
866
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
867
+ more detail.
868
+ return_dict (`bool`, *optional*):
869
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
870
+ cache_position (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
871
+ The position of the current input in the cache. This is used to ensure that the cache is correctly updated.
872
+ If `cache_params` is passed, `cache_position` should also be passed.
873
+ attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
874
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
875
+
876
+ - 1 for tokens that are **not masked**,
877
+ - 0 for tokens that are **masked**.
878
+
879
+ [What are attention masks?](../glossary#attention-mask)
880
+ """
881
+
882
+
883
+ @add_start_docstrings(
884
+ "The bare MAMBA2 Model transformer outputting raw hidden-states without any specific head on top.",
885
+ MAMBA2_START_DOCSTRING,
886
+ )
887
+ class Mamba2Model(Mamba2PreTrainedModel):
888
+ def __init__(self, config):
889
+ super().__init__(config)
890
+
891
+ self.embeddings = nn.Embedding(config.vocab_size, config.hidden_size)
892
+ self.layers = nn.ModuleList([Mamba2Block(config, layer_idx=idx) for idx in range(config.num_hidden_layers)])
893
+
894
+ self.gradient_checkpointing = False
895
+ self.norm_f = Mamba2RMSNorm(config.hidden_size, eps=config.layer_norm_epsilon)
896
+ # Initialize weights and apply final processing
897
+ self._register_load_state_dict_pre_hook(self.load_hook)
898
+ self.post_init()
899
+
900
+ def load_hook(self, state_dict, prefix, *args):
901
+ for k in state_dict:
902
+ if "embedding." in k:
903
+ state_dict[k.replace("embedding.", "embeddings.")] = state_dict.pop(k)
904
+ break
905
+
906
+ def get_input_embeddings(self):
907
+ return self.embeddings
908
+
909
+ def set_input_embeddings(self, new_embeddings):
910
+ self.embeddings = new_embeddings
911
+
912
+ @add_start_docstrings_to_model_forward(MAMBA2_INPUTS_DOCSTRING)
913
+ @add_code_sample_docstrings(
914
+ checkpoint=_CHECKPOINT_FOR_DOC,
915
+ output_type=Mamba2Output,
916
+ config_class=_CONFIG_FOR_DOC,
917
+ )
918
+ def forward(
919
+ self,
920
+ input_ids: Optional[torch.LongTensor] = None,
921
+ inputs_embeds: Optional[torch.LongTensor] = None,
922
+ cache_params: Optional[Mamba2Cache] = None,
923
+ use_cache: Optional[bool] = None,
924
+ output_hidden_states: Optional[bool] = None,
925
+ return_dict: Optional[bool] = None,
926
+ cache_position: Optional[torch.LongTensor] = None,
927
+ attention_mask: Optional[torch.Tensor] = None,
928
+ **kwargs,
929
+ ) -> Union[Tuple, Mamba2Output]:
930
+ output_hidden_states = (
931
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
932
+ )
933
+ use_cache = use_cache if use_cache is not None else (self.config.use_cache if not self.training else False)
934
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
935
+
936
+ if (input_ids is None) ^ (inputs_embeds is not None): # ^ is python for xor
937
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
938
+
939
+ if inputs_embeds is None:
940
+ inputs_embeds = self.embeddings(input_ids)
941
+
942
+ if self.gradient_checkpointing and self.training and use_cache:
943
+ use_cache = False
944
+
945
+ if use_cache:
946
+ if cache_params is None:
947
+ cache_params = Mamba2Cache(
948
+ self.config, inputs_embeds.size(0), device=inputs_embeds.device, dtype=inputs_embeds.dtype
949
+ )
950
+ cache_position = torch.arange(0, self.config.conv_kernel, device=inputs_embeds.device)
951
+ elif cache_position is None:
952
+ # cases when we do manual forward instead of using `model.generate` which will initiate
953
+ # `cache_position` and makes sure it is not None, throw error here instead of doing some
954
+ # hack to conjecture the current cache position
955
+ raise ValueError(
956
+ "You have to specify the `cache_position` manually when `use_cache=True` and `cache_params` is passed, "
957
+ "you don't have to pass a `cache_params` if you are in prefilling stage because in that case it will "
958
+ "be initialized for you automatically"
959
+ )
960
+ else:
961
+ cache_params = None
962
+
963
+ hidden_states = inputs_embeds
964
+ all_hidden_states = () if output_hidden_states else None
965
+ for mixer_block in self.layers:
966
+ if self.gradient_checkpointing and self.training:
967
+ hidden_states = self._gradient_checkpointing_func(
968
+ mixer_block.__call__, hidden_states, cache_params, cache_position, attention_mask
969
+ )
970
+ else:
971
+ hidden_states = mixer_block(
972
+ hidden_states,
973
+ cache_params=cache_params,
974
+ cache_position=cache_position,
975
+ attention_mask=attention_mask,
976
+ )
977
+
978
+ if output_hidden_states:
979
+ all_hidden_states = all_hidden_states + (hidden_states,)
980
+
981
+ hidden_states = self.norm_f(hidden_states)
982
+
983
+ if output_hidden_states:
984
+ all_hidden_states = all_hidden_states + (hidden_states,)
985
+
986
+ if not return_dict:
987
+ return tuple(v for v in [hidden_states, cache_params, all_hidden_states] if v is not None)
988
+
989
+ return Mamba2Output(
990
+ last_hidden_state=hidden_states,
991
+ cache_params=cache_params if use_cache else None,
992
+ hidden_states=all_hidden_states,
993
+ )
994
+
995
+
996
+ @add_start_docstrings(
997
+ """
998
+ The MAMBA2 Model transformer with a language modeling head on top (linear layer with weights not tied to the input
999
+ embeddings).
1000
+ """,
1001
+ MAMBA2_START_DOCSTRING,
1002
+ )
1003
+ class Mamba2ForCausalLM(Mamba2PreTrainedModel, GenerationMixin):
1004
+ _tied_weights_keys = []
1005
+
1006
+ def __init__(self, config):
1007
+ super().__init__(config)
1008
+ self.backbone = Mamba2Model(config)
1009
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1010
+ # Initialize weights and apply final processing
1011
+ self.post_init()
1012
+
1013
+ def get_output_embeddings(self):
1014
+ return self.lm_head
1015
+
1016
+ def set_output_embeddings(self, new_embeddings):
1017
+ self.lm_head = new_embeddings
1018
+
1019
+ def get_input_embeddings(self):
1020
+ return self.backbone.get_input_embeddings()
1021
+
1022
+ def set_input_embeddings(self, new_embeddings):
1023
+ return self.backbone.set_input_embeddings(new_embeddings)
1024
+
1025
+ def prepare_inputs_for_generation(
1026
+ self,
1027
+ input_ids,
1028
+ inputs_embeds=None,
1029
+ use_cache=None,
1030
+ cache_params: Optional[Mamba2Cache] = None,
1031
+ cache_position: Optional[torch.LongTensor] = None,
1032
+ attention_mask: Optional[torch.Tensor] = None,
1033
+ **kwargs,
1034
+ ):
1035
+ # Overwitten -- uses `cache_params` as opposed to `past_key_values`
1036
+
1037
+ if use_cache:
1038
+ # `cache_position` should have been initialized in `generate`
1039
+ if cache_position is None:
1040
+ raise ValueError(
1041
+ "`cache_position` should not be None as it should have been initialized in "
1042
+ "`model.generate`, you are responsible for passing in a valid `cache_position` if "
1043
+ "you are calling `prepare_inputs_for_generation` directly with `use_cache=True`"
1044
+ )
1045
+ if cache_position[0] > 0:
1046
+ input_ids = input_ids[:, -1][..., None]
1047
+
1048
+ if attention_mask is not None:
1049
+ attention_mask = None
1050
+ else:
1051
+ # we initialize the `cache_position` to full size of `conv_states` at prefill stage
1052
+ # considering padding will be applied when input length is shorter, and truncation
1053
+ # will be applied when it is longer, so it will be equivalent to always have it match
1054
+ # the length of `cache_params.conv_states`, which is `config.conv_kernel`
1055
+ cache_position = torch.arange(0, self.config.conv_kernel, device=input_ids.device)
1056
+
1057
+ if inputs_embeds is not None and cache_params is None:
1058
+ model_inputs = {"inputs_embeds": inputs_embeds}
1059
+ else:
1060
+ model_inputs = {"input_ids": input_ids}
1061
+
1062
+ model_inputs.update(
1063
+ {
1064
+ "attention_mask": attention_mask,
1065
+ "cache_params": cache_params,
1066
+ "use_cache": use_cache,
1067
+ "cache_position": cache_position,
1068
+ }
1069
+ )
1070
+ return model_inputs
1071
+
1072
+ @add_start_docstrings_to_model_forward(MAMBA2_INPUTS_DOCSTRING)
1073
+ @add_code_sample_docstrings(
1074
+ checkpoint=_CHECKPOINT_FOR_DOC,
1075
+ output_type=Mamba2CausalLMOutput,
1076
+ config_class=_CONFIG_FOR_DOC,
1077
+ )
1078
+ def forward(
1079
+ self,
1080
+ input_ids: Optional[torch.LongTensor] = None,
1081
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1082
+ cache_params: Optional[Mamba2Cache] = None,
1083
+ labels: Optional[torch.LongTensor] = None,
1084
+ output_hidden_states: Optional[bool] = None,
1085
+ return_dict: Optional[bool] = None,
1086
+ use_cache: Optional[bool] = None,
1087
+ cache_position: Optional[torch.Tensor] = None,
1088
+ attention_mask: Optional[torch.Tensor] = None,
1089
+ **kwargs, # for now we need this for generation
1090
+ ) -> Union[Tuple, Mamba2CausalLMOutput]:
1091
+ r"""
1092
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1093
+ Labels for language modeling. Note that the labels **are shifted** inside the model, i.e. you can set
1094
+ `labels = input_ids` Indices are selected in `[-100, 0, ..., config.vocab_size]` All labels set to `-100`
1095
+ are ignored (masked), the loss is only computed for labels in `[0, ..., config.vocab_size]`
1096
+ """
1097
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1098
+
1099
+ mamba2_outputs = self.backbone(
1100
+ input_ids,
1101
+ cache_params=cache_params,
1102
+ inputs_embeds=inputs_embeds,
1103
+ output_hidden_states=output_hidden_states,
1104
+ return_dict=return_dict,
1105
+ use_cache=use_cache,
1106
+ cache_position=cache_position,
1107
+ attention_mask=attention_mask,
1108
+ )
1109
+ hidden_states = mamba2_outputs[0]
1110
+
1111
+ logits = self.lm_head(hidden_states.to(self.lm_head.weight.dtype)).float()
1112
+
1113
+ loss = None
1114
+ if labels is not None:
1115
+ # move labels to correct device to enable model parallelism
1116
+ labels = labels.to(logits.device)
1117
+ # Shift so that tokens < n predict n
1118
+ shift_logits = logits[..., :-1, :].contiguous()
1119
+ shift_labels = labels[..., 1:].contiguous()
1120
+ # Flatten the tokens
1121
+ loss_fct = CrossEntropyLoss()
1122
+ loss = loss_fct(shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1))
1123
+
1124
+ if not return_dict:
1125
+ output = (logits,) + mamba2_outputs[1:]
1126
+ return ((loss,) + output) if loss is not None else output
1127
+
1128
+ return Mamba2CausalLMOutput(
1129
+ loss=loss,
1130
+ logits=logits,
1131
+ cache_params=mamba2_outputs.cache_params,
1132
+ hidden_states=mamba2_outputs.hidden_states,
1133
+ )
1134
+
1135
+
1136
+ __all__ = ["Mamba2ForCausalLM", "Mamba2Model", "Mamba2PreTrainedModel"]
tasks/tasksmith-441eeab80047/environment/source/src/transformers/models/marian/__init__.py ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 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 _LazyModule
17
+ from ...utils.import_utils import define_import_structure
18
+
19
+
20
+ if TYPE_CHECKING:
21
+ from .configuration_marian import *
22
+ from .modeling_flax_marian import *
23
+ from .modeling_marian import *
24
+ from .modeling_tf_marian import *
25
+ from .tokenization_marian import *
26
+ else:
27
+ import sys
28
+
29
+ _file = globals()["__file__"]
30
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
tasks/tasksmith-441eeab80047/environment/source/src/transformers/models/marian/configuration_marian.py ADDED
@@ -0,0 +1,394 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2021 The Marian Team Authors and The HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """Marian model configuration"""
16
+
17
+ from collections import OrderedDict
18
+ from typing import Any, Mapping, Optional
19
+
20
+ from ... import PreTrainedTokenizer
21
+ from ...configuration_utils import PretrainedConfig
22
+ from ...onnx import OnnxConfig, OnnxConfigWithPast, OnnxSeq2SeqConfigWithPast
23
+ from ...onnx.utils import compute_effective_axis_dimension
24
+ from ...utils import TensorType, is_torch_available, logging
25
+
26
+
27
+ logger = logging.get_logger(__name__)
28
+
29
+
30
+ class MarianConfig(PretrainedConfig):
31
+ r"""
32
+ This is the configuration class to store the configuration of a [`MarianModel`]. It is used to instantiate an
33
+ Marian model according to the specified arguments, defining the model architecture. Instantiating a configuration
34
+ with the defaults will yield a similar configuration to that of the Marian
35
+ [Helsinki-NLP/opus-mt-en-de](https://huggingface.co/Helsinki-NLP/opus-mt-en-de) architecture.
36
+
37
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
38
+ documentation from [`PretrainedConfig`] for more information.
39
+
40
+
41
+ Args:
42
+ vocab_size (`int`, *optional*, defaults to 58101):
43
+ Vocabulary size of the Marian model. Defines the number of different tokens that can be represented by the
44
+ `inputs_ids` passed when calling [`MarianModel`] or [`TFMarianModel`].
45
+ d_model (`int`, *optional*, defaults to 1024):
46
+ Dimensionality of the layers and the pooler layer.
47
+ encoder_layers (`int`, *optional*, defaults to 12):
48
+ Number of encoder layers.
49
+ decoder_layers (`int`, *optional*, defaults to 12):
50
+ Number of decoder layers.
51
+ encoder_attention_heads (`int`, *optional*, defaults to 16):
52
+ Number of attention heads for each attention layer in the Transformer encoder.
53
+ decoder_attention_heads (`int`, *optional*, defaults to 16):
54
+ Number of attention heads for each attention layer in the Transformer decoder.
55
+ decoder_ffn_dim (`int`, *optional*, defaults to 4096):
56
+ Dimensionality of the "intermediate" (often named feed-forward) layer in decoder.
57
+ encoder_ffn_dim (`int`, *optional*, defaults to 4096):
58
+ Dimensionality of the "intermediate" (often named feed-forward) layer in decoder.
59
+ activation_function (`str` or `function`, *optional*, defaults to `"gelu"`):
60
+ The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
61
+ `"relu"`, `"silu"` and `"gelu_new"` are supported.
62
+ dropout (`float`, *optional*, defaults to 0.1):
63
+ The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
64
+ attention_dropout (`float`, *optional*, defaults to 0.0):
65
+ The dropout ratio for the attention probabilities.
66
+ activation_dropout (`float`, *optional*, defaults to 0.0):
67
+ The dropout ratio for activations inside the fully connected layer.
68
+ max_position_embeddings (`int`, *optional*, defaults to 1024):
69
+ The maximum sequence length that this model might ever be used with. Typically set this to something large
70
+ just in case (e.g., 512 or 1024 or 2048).
71
+ init_std (`float`, *optional*, defaults to 0.02):
72
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
73
+ encoder_layerdrop (`float`, *optional*, defaults to 0.0):
74
+ The LayerDrop probability for the encoder. See the [LayerDrop paper](see https://arxiv.org/abs/1909.11556)
75
+ for more details.
76
+ decoder_layerdrop (`float`, *optional*, defaults to 0.0):
77
+ The LayerDrop probability for the decoder. See the [LayerDrop paper](see https://arxiv.org/abs/1909.11556)
78
+ for more details.
79
+ scale_embedding (`bool`, *optional*, defaults to `False`):
80
+ Scale embeddings by diving by sqrt(d_model).
81
+ use_cache (`bool`, *optional*, defaults to `True`):
82
+ Whether or not the model should return the last key/values attentions (not used by all models)
83
+ forced_eos_token_id (`int`, *optional*, defaults to 0):
84
+ The id of the token to force as the last generated token when `max_length` is reached. Usually set to
85
+ `eos_token_id`.
86
+
87
+ Examples:
88
+
89
+ ```python
90
+ >>> from transformers import MarianModel, MarianConfig
91
+
92
+ >>> # Initializing a Marian Helsinki-NLP/opus-mt-en-de style configuration
93
+ >>> configuration = MarianConfig()
94
+
95
+ >>> # Initializing a model from the Helsinki-NLP/opus-mt-en-de style configuration
96
+ >>> model = MarianModel(configuration)
97
+
98
+ >>> # Accessing the model configuration
99
+ >>> configuration = model.config
100
+ ```"""
101
+
102
+ model_type = "marian"
103
+ keys_to_ignore_at_inference = ["past_key_values"]
104
+ attribute_map = {"num_attention_heads": "encoder_attention_heads", "hidden_size": "d_model"}
105
+
106
+ def __init__(
107
+ self,
108
+ vocab_size=58101,
109
+ decoder_vocab_size=None,
110
+ max_position_embeddings=1024,
111
+ encoder_layers=12,
112
+ encoder_ffn_dim=4096,
113
+ encoder_attention_heads=16,
114
+ decoder_layers=12,
115
+ decoder_ffn_dim=4096,
116
+ decoder_attention_heads=16,
117
+ encoder_layerdrop=0.0,
118
+ decoder_layerdrop=0.0,
119
+ use_cache=True,
120
+ is_encoder_decoder=True,
121
+ activation_function="gelu",
122
+ d_model=1024,
123
+ dropout=0.1,
124
+ attention_dropout=0.0,
125
+ activation_dropout=0.0,
126
+ init_std=0.02,
127
+ decoder_start_token_id=58100,
128
+ scale_embedding=False,
129
+ pad_token_id=58100,
130
+ eos_token_id=0,
131
+ forced_eos_token_id=0,
132
+ share_encoder_decoder_embeddings=True,
133
+ **kwargs,
134
+ ):
135
+ self.vocab_size = vocab_size
136
+ self.decoder_vocab_size = decoder_vocab_size or vocab_size
137
+ self.max_position_embeddings = max_position_embeddings
138
+ self.d_model = d_model
139
+ self.encoder_ffn_dim = encoder_ffn_dim
140
+ self.encoder_layers = encoder_layers
141
+ self.encoder_attention_heads = encoder_attention_heads
142
+ self.decoder_ffn_dim = decoder_ffn_dim
143
+ self.decoder_layers = decoder_layers
144
+ self.decoder_attention_heads = decoder_attention_heads
145
+ self.dropout = dropout
146
+ self.attention_dropout = attention_dropout
147
+ self.activation_dropout = activation_dropout
148
+ self.activation_function = activation_function
149
+ self.init_std = init_std
150
+ self.encoder_layerdrop = encoder_layerdrop
151
+ self.decoder_layerdrop = decoder_layerdrop
152
+ self.use_cache = use_cache
153
+ self.num_hidden_layers = encoder_layers
154
+ self.scale_embedding = scale_embedding # scale factor will be sqrt(d_model) if True
155
+ self.share_encoder_decoder_embeddings = share_encoder_decoder_embeddings
156
+ super().__init__(
157
+ pad_token_id=pad_token_id,
158
+ eos_token_id=eos_token_id,
159
+ is_encoder_decoder=is_encoder_decoder,
160
+ decoder_start_token_id=decoder_start_token_id,
161
+ forced_eos_token_id=forced_eos_token_id,
162
+ **kwargs,
163
+ )
164
+
165
+
166
+ class MarianOnnxConfig(OnnxSeq2SeqConfigWithPast):
167
+ @property
168
+ # Copied from transformers.models.bart.configuration_bart.BartOnnxConfig.inputs
169
+ def inputs(self) -> Mapping[str, Mapping[int, str]]:
170
+ if self.task in ["default", "seq2seq-lm"]:
171
+ common_inputs = OrderedDict(
172
+ [
173
+ ("input_ids", {0: "batch", 1: "encoder_sequence"}),
174
+ ("attention_mask", {0: "batch", 1: "encoder_sequence"}),
175
+ ]
176
+ )
177
+
178
+ if self.use_past:
179
+ common_inputs["decoder_input_ids"] = {0: "batch"}
180
+ common_inputs["decoder_attention_mask"] = {0: "batch", 1: "past_decoder_sequence + sequence"}
181
+ else:
182
+ common_inputs["decoder_input_ids"] = {0: "batch", 1: "decoder_sequence"}
183
+ common_inputs["decoder_attention_mask"] = {0: "batch", 1: "decoder_sequence"}
184
+
185
+ if self.use_past:
186
+ self.fill_with_past_key_values_(common_inputs, direction="inputs")
187
+ elif self.task == "causal-lm":
188
+ # TODO: figure this case out.
189
+ common_inputs = OrderedDict(
190
+ [
191
+ ("input_ids", {0: "batch", 1: "encoder_sequence"}),
192
+ ("attention_mask", {0: "batch", 1: "encoder_sequence"}),
193
+ ]
194
+ )
195
+ if self.use_past:
196
+ num_encoder_layers, _ = self.num_layers
197
+ for i in range(num_encoder_layers):
198
+ common_inputs[f"past_key_values.{i}.key"] = {0: "batch", 2: "past_sequence + sequence"}
199
+ common_inputs[f"past_key_values.{i}.value"] = {0: "batch", 2: "past_sequence + sequence"}
200
+ else:
201
+ common_inputs = OrderedDict(
202
+ [
203
+ ("input_ids", {0: "batch", 1: "encoder_sequence"}),
204
+ ("attention_mask", {0: "batch", 1: "encoder_sequence"}),
205
+ ("decoder_input_ids", {0: "batch", 1: "decoder_sequence"}),
206
+ ("decoder_attention_mask", {0: "batch", 1: "decoder_sequence"}),
207
+ ]
208
+ )
209
+
210
+ return common_inputs
211
+
212
+ @property
213
+ # Copied from transformers.models.bart.configuration_bart.BartOnnxConfig.outputs
214
+ def outputs(self) -> Mapping[str, Mapping[int, str]]:
215
+ if self.task in ["default", "seq2seq-lm"]:
216
+ common_outputs = super().outputs
217
+ else:
218
+ common_outputs = super(OnnxConfigWithPast, self).outputs
219
+ if self.use_past:
220
+ num_encoder_layers, _ = self.num_layers
221
+ for i in range(num_encoder_layers):
222
+ common_outputs[f"present.{i}.key"] = {0: "batch", 2: "past_sequence + sequence"}
223
+ common_outputs[f"present.{i}.value"] = {0: "batch", 2: "past_sequence + sequence"}
224
+ return common_outputs
225
+
226
+ def _generate_dummy_inputs_for_default_and_seq2seq_lm(
227
+ self,
228
+ tokenizer: PreTrainedTokenizer,
229
+ batch_size: int = -1,
230
+ seq_length: int = -1,
231
+ is_pair: bool = False,
232
+ framework: Optional[TensorType] = None,
233
+ ) -> Mapping[str, Any]:
234
+ encoder_inputs = self._generate_dummy_inputs_for_encoder_and_decoder(
235
+ tokenizer, batch_size, seq_length, is_pair, framework
236
+ )
237
+
238
+ # Generate decoder inputs
239
+ decoder_seq_length = seq_length if not self.use_past else 1
240
+ decoder_inputs = self._generate_dummy_inputs_for_encoder_and_decoder(
241
+ tokenizer, batch_size, decoder_seq_length, is_pair, framework
242
+ )
243
+ decoder_inputs = {f"decoder_{name}": tensor for name, tensor in decoder_inputs.items()}
244
+ common_inputs = dict(**encoder_inputs, **decoder_inputs)
245
+
246
+ if self.use_past:
247
+ if not is_torch_available():
248
+ raise ValueError("Cannot generate dummy past_keys inputs without PyTorch installed.")
249
+ else:
250
+ import torch
251
+ batch, encoder_seq_length = common_inputs["input_ids"].shape
252
+ decoder_seq_length = common_inputs["decoder_input_ids"].shape[1]
253
+ num_encoder_attention_heads, num_decoder_attention_heads = self.num_attention_heads
254
+ encoder_shape = (
255
+ batch,
256
+ num_encoder_attention_heads,
257
+ encoder_seq_length,
258
+ self._config.hidden_size // num_encoder_attention_heads,
259
+ )
260
+ decoder_past_length = decoder_seq_length + 3
261
+ decoder_shape = (
262
+ batch,
263
+ num_decoder_attention_heads,
264
+ decoder_past_length,
265
+ self._config.hidden_size // num_decoder_attention_heads,
266
+ )
267
+
268
+ common_inputs["decoder_attention_mask"] = torch.cat(
269
+ [common_inputs["decoder_attention_mask"], torch.ones(batch, decoder_past_length)], dim=1
270
+ )
271
+
272
+ common_inputs["past_key_values"] = []
273
+ # If the number of encoder and decoder layers are present in the model configuration, both are considered
274
+ num_encoder_layers, num_decoder_layers = self.num_layers
275
+ min_num_layers = min(num_encoder_layers, num_decoder_layers)
276
+ max_num_layers = max(num_encoder_layers, num_decoder_layers) - min_num_layers
277
+ remaining_side_name = "encoder" if num_encoder_layers > num_decoder_layers else "decoder"
278
+
279
+ for _ in range(min_num_layers):
280
+ common_inputs["past_key_values"].append(
281
+ (
282
+ torch.zeros(decoder_shape),
283
+ torch.zeros(decoder_shape),
284
+ torch.zeros(encoder_shape),
285
+ torch.zeros(encoder_shape),
286
+ )
287
+ )
288
+ # TODO: test this.
289
+ shape = encoder_shape if remaining_side_name == "encoder" else decoder_shape
290
+ for _ in range(min_num_layers, max_num_layers):
291
+ common_inputs["past_key_values"].append((torch.zeros(shape), torch.zeros(shape)))
292
+ return common_inputs
293
+
294
+ def _generate_dummy_inputs_for_causal_lm(
295
+ self,
296
+ tokenizer: PreTrainedTokenizer,
297
+ batch_size: int = -1,
298
+ seq_length: int = -1,
299
+ is_pair: bool = False,
300
+ framework: Optional[TensorType] = None,
301
+ ) -> Mapping[str, Any]:
302
+ common_inputs = self._generate_dummy_inputs_for_encoder_and_decoder(
303
+ tokenizer, batch_size, seq_length, is_pair, framework
304
+ )
305
+
306
+ if self.use_past:
307
+ if not is_torch_available():
308
+ raise ValueError("Cannot generate dummy past_keys inputs without PyTorch installed.")
309
+ else:
310
+ import torch
311
+ batch, seqlen = common_inputs["input_ids"].shape
312
+ # Not using the same length for past_key_values
313
+ past_key_values_length = seqlen + 2
314
+ num_encoder_layers, _ = self.num_layers
315
+ num_encoder_attention_heads, _ = self.num_attention_heads
316
+ past_shape = (
317
+ batch,
318
+ num_encoder_attention_heads,
319
+ past_key_values_length,
320
+ self._config.hidden_size // num_encoder_attention_heads,
321
+ )
322
+
323
+ mask_dtype = common_inputs["attention_mask"].dtype
324
+ common_inputs["attention_mask"] = torch.cat(
325
+ [common_inputs["attention_mask"], torch.ones(batch, past_key_values_length, dtype=mask_dtype)], dim=1
326
+ )
327
+ common_inputs["past_key_values"] = [
328
+ (torch.zeros(past_shape), torch.zeros(past_shape)) for _ in range(num_encoder_layers)
329
+ ]
330
+ return common_inputs
331
+
332
+ # Copied from BartOnnxConfig._generate_dummy_inputs_for_sequence_classification_and_question_answering
333
+ # We renamed this function because Marian models do not have a sequence classification or question answering head
334
+ def _generate_dummy_inputs_for_encoder_and_decoder(
335
+ self,
336
+ tokenizer: PreTrainedTokenizer,
337
+ batch_size: int = -1,
338
+ seq_length: int = -1,
339
+ is_pair: bool = False,
340
+ framework: Optional[TensorType] = None,
341
+ ) -> Mapping[str, Any]:
342
+ # Copied from OnnxConfig.generate_dummy_inputs
343
+ # Did not use super(OnnxConfigWithPast, self).generate_dummy_inputs for code clarity.
344
+ # If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX
345
+ batch_size = compute_effective_axis_dimension(
346
+ batch_size, fixed_dimension=OnnxConfig.default_fixed_batch, num_token_to_add=0
347
+ )
348
+
349
+ # If dynamic axis (-1) we forward with a fixed dimension of 8 tokens to avoid optimizations made by ONNX
350
+ token_to_add = tokenizer.num_special_tokens_to_add(is_pair)
351
+ seq_length = compute_effective_axis_dimension(
352
+ seq_length, fixed_dimension=OnnxConfig.default_fixed_sequence, num_token_to_add=token_to_add
353
+ )
354
+
355
+ # Generate dummy inputs according to compute batch and sequence
356
+ dummy_input = [" ".join([tokenizer.unk_token]) * seq_length] * batch_size
357
+ common_inputs = dict(tokenizer(dummy_input, return_tensors=framework))
358
+ return common_inputs
359
+
360
+ def generate_dummy_inputs(
361
+ self,
362
+ tokenizer: PreTrainedTokenizer,
363
+ batch_size: int = -1,
364
+ seq_length: int = -1,
365
+ is_pair: bool = False,
366
+ framework: Optional[TensorType] = None,
367
+ ) -> Mapping[str, Any]:
368
+ if self.task in ["default", "seq2seq-lm"]:
369
+ common_inputs = self._generate_dummy_inputs_for_default_and_seq2seq_lm(
370
+ tokenizer, batch_size=batch_size, seq_length=seq_length, is_pair=is_pair, framework=framework
371
+ )
372
+
373
+ else:
374
+ common_inputs = self._generate_dummy_inputs_for_causal_lm(
375
+ tokenizer, batch_size=batch_size, seq_length=seq_length, is_pair=is_pair, framework=framework
376
+ )
377
+
378
+ return common_inputs
379
+
380
+ # Copied from transformers.models.bart.configuration_bart.BartOnnxConfig._flatten_past_key_values_
381
+ def _flatten_past_key_values_(self, flattened_output, name, idx, t):
382
+ if self.task in ["default", "seq2seq-lm"]:
383
+ flattened_output = super()._flatten_past_key_values_(flattened_output, name, idx, t)
384
+ else:
385
+ flattened_output = super(OnnxSeq2SeqConfigWithPast, self)._flatten_past_key_values_(
386
+ flattened_output, name, idx, t
387
+ )
388
+
389
+ @property
390
+ def atol_for_validation(self) -> float:
391
+ return 1e-4
392
+
393
+
394
+ __all__ = ["MarianConfig", "MarianOnnxConfig"]
tasks/tasksmith-441eeab80047/environment/source/src/transformers/models/marian/convert_marian_tatoeba_to_pytorch.py ADDED
@@ -0,0 +1,1327 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ import argparse
16
+ import datetime
17
+ import json
18
+ import os
19
+ import re
20
+ from pathlib import Path
21
+ from typing import Tuple
22
+
23
+ import yaml
24
+ from tqdm import tqdm
25
+
26
+ from transformers.models.marian.convert_marian_to_pytorch import (
27
+ FRONT_MATTER_TEMPLATE,
28
+ convert,
29
+ convert_opus_name_to_hf_name,
30
+ download_and_unzip,
31
+ get_system_metadata,
32
+ )
33
+
34
+
35
+ DEFAULT_REPO = "Tatoeba-Challenge"
36
+ DEFAULT_MODEL_DIR = os.path.join(DEFAULT_REPO, "models")
37
+ ISO_URL = "https://cdn-datasets.huggingface.co/language_codes/iso-639-3.csv"
38
+ ISO_PATH = "lang_code_data/iso-639-3.csv"
39
+ LANG_CODE_PATH = "lang_code_data/language-codes-3b2.csv"
40
+ TATOEBA_MODELS_URL = "https://object.pouta.csc.fi/Tatoeba-MT-models"
41
+
42
+
43
+ class TatoebaConverter:
44
+ """
45
+ Convert Tatoeba-Challenge models to huggingface format.
46
+
47
+ Steps:
48
+
49
+ 1. Convert numpy state dict to hf format (same code as OPUS-MT-Train conversion).
50
+ 2. Rename opus model to huggingface format. This means replace each alpha3 code with an alpha2 code if a unique
51
+ one exists. e.g. aav-eng -> aav-en, heb-eng -> he-en
52
+ 3. Select the best model for a particular pair, parse the yml for it and write a model card. By default the
53
+ best model is the one listed first in released-model-results, but it's also possible to specify the most
54
+ recent one.
55
+ """
56
+
57
+ def __init__(self, save_dir="marian_converted"):
58
+ assert Path(DEFAULT_REPO).exists(), "need git clone git@github.com:Helsinki-NLP/Tatoeba-Challenge.git"
59
+ self.download_lang_info()
60
+ self.model_results = json.load(open("Tatoeba-Challenge/models/released-model-results.json"))
61
+ self.alpha3_to_alpha2 = {}
62
+ for line in open(ISO_PATH):
63
+ parts = line.split("\t")
64
+ if len(parts[0]) == 3 and len(parts[3]) == 2:
65
+ self.alpha3_to_alpha2[parts[0]] = parts[3]
66
+ for line in LANG_CODE_PATH:
67
+ parts = line.split(",")
68
+ if len(parts[0]) == 3 and len(parts[1]) == 2:
69
+ self.alpha3_to_alpha2[parts[0]] = parts[1]
70
+ self.model_card_dir = Path(save_dir)
71
+ self.tag2name = {}
72
+ for key, value in GROUP_MEMBERS.items():
73
+ self.tag2name[key] = value[0]
74
+
75
+ def convert_models(self, tatoeba_ids, dry_run=False):
76
+ models_to_convert = [self.parse_metadata(x) for x in tatoeba_ids]
77
+ save_dir = Path("marian_ckpt")
78
+ dest_dir = Path(self.model_card_dir)
79
+ dest_dir.mkdir(exist_ok=True)
80
+ for model in tqdm(models_to_convert): # k, prepro, download, test_set_url in tqdm(model_list):
81
+ if "SentencePiece" not in model["pre-processing"]:
82
+ print(f"Skipping {model['release']} because it doesn't appear to use SentencePiece")
83
+ continue
84
+ if not os.path.exists(save_dir / model["_name"]):
85
+ download_and_unzip(f"{TATOEBA_MODELS_URL}/{model['release']}", save_dir / model["_name"])
86
+ # from convert_marian_to_pytorch
87
+ opus_language_groups_to_hf = convert_opus_name_to_hf_name
88
+ pair_name = opus_language_groups_to_hf(model["_name"])
89
+ convert(save_dir / model["_name"], dest_dir / f"opus-mt-{pair_name}")
90
+ self.write_model_card(model, dry_run=dry_run)
91
+
92
+ def expand_group_to_two_letter_codes(self, grp_name):
93
+ return [self.alpha3_to_alpha2.get(x, x) for x in GROUP_MEMBERS[grp_name][1]]
94
+
95
+ def is_group(self, code, name):
96
+ return "languages" in name or len(GROUP_MEMBERS.get(code, [])) > 1
97
+
98
+ def get_tags(self, code, name):
99
+ if len(code) == 2:
100
+ assert "languages" not in name, f"{code}: {name}"
101
+ return [code]
102
+ elif self.is_group(code, name):
103
+ group = self.expand_group_to_two_letter_codes(code)
104
+ group.append(code)
105
+ return group
106
+ else: # zho-> zh
107
+ print(f"Three letter monolingual code: {code}")
108
+ return [code]
109
+
110
+ def resolve_lang_code(self, src, tgt) -> Tuple[str, str]:
111
+ src_tags = self.get_tags(src, self.tag2name[src])
112
+ tgt_tags = self.get_tags(tgt, self.tag2name[tgt])
113
+ return src_tags, tgt_tags
114
+
115
+ @staticmethod
116
+ def model_type_info_from_model_name(name):
117
+ info = {"_has_backtranslated_data": False}
118
+ if "1m" in name:
119
+ info["_data_per_pair"] = str(1e6)
120
+ if "2m" in name:
121
+ info["_data_per_pair"] = str(2e6)
122
+ if "4m" in name:
123
+ info["_data_per_pair"] = str(4e6)
124
+ if "+bt" in name:
125
+ info["_has_backtranslated_data"] = True
126
+ if "tuned4" in name:
127
+ info["_tuned"] = re.search(r"tuned4[^-]+", name).group()
128
+ return info
129
+
130
+ def write_model_card(self, model_dict, dry_run=False) -> str:
131
+ """
132
+ Construct card from data parsed from YAML and the model's name. upload command: aws s3 sync model_card_dir
133
+ s3://models.huggingface.co/bert/Helsinki-NLP/ --dryrun
134
+ """
135
+ model_dir_url = f"{TATOEBA_MODELS_URL}/{model_dict['release']}"
136
+ long_pair = model_dict["_name"].split("-")
137
+ assert len(long_pair) == 2, f"got a translation pair {model_dict['_name']} that doesn't appear to be a pair"
138
+ short_src = self.alpha3_to_alpha2.get(long_pair[0], long_pair[0])
139
+ short_tgt = self.alpha3_to_alpha2.get(long_pair[1], long_pair[1])
140
+ model_dict["_hf_model_id"] = f"opus-mt-{short_src}-{short_tgt}"
141
+
142
+ a3_src, a3_tgt = model_dict["_name"].split("-")
143
+ # opus_src_tags, opus_tgt_tags = a3_src.split("+"), a3_tgt.split("+")
144
+
145
+ # This messy part tries to deal with language tags in multilingual models, possibly
146
+ # not all having three-letter codes
147
+ resolved_src_tags, resolved_tgt_tags = self.resolve_lang_code(a3_src, a3_tgt)
148
+ a2_src_tags, a2_tgt_tags = [], []
149
+ for tag in resolved_src_tags:
150
+ if tag not in self.alpha3_to_alpha2:
151
+ a2_src_tags.append(tag)
152
+ for tag in resolved_tgt_tags:
153
+ if tag not in self.alpha3_to_alpha2:
154
+ a2_tgt_tags.append(tag)
155
+
156
+ lang_tags = dedup(a2_src_tags + a2_tgt_tags)
157
+ src_multilingual, tgt_multilingual = (len(a2_src_tags) > 1), (len(a2_tgt_tags) > 1)
158
+ s, t = ",".join(a2_src_tags), ",".join(a2_tgt_tags)
159
+
160
+ metadata = {
161
+ "hf_name": model_dict["_name"],
162
+ "source_languages": s,
163
+ "target_languages": t,
164
+ "opus_readme_url": f"{model_dir_url}/README.md",
165
+ "original_repo": "Tatoeba-Challenge",
166
+ "tags": ["translation"],
167
+ "languages": lang_tags,
168
+ }
169
+ lang_tags = l2front_matter(lang_tags)
170
+
171
+ metadata["src_constituents"] = list(GROUP_MEMBERS[a3_src][1])
172
+ metadata["tgt_constituents"] = list(GROUP_MEMBERS[a3_tgt][1])
173
+ metadata["src_multilingual"] = src_multilingual
174
+ metadata["tgt_multilingual"] = tgt_multilingual
175
+
176
+ backtranslated_data = ""
177
+ if model_dict["_has_backtranslated_data"]:
178
+ backtranslated_data = " with backtranslations"
179
+
180
+ multilingual_data = ""
181
+ if "_data_per_pair" in model_dict:
182
+ multilingual_data = f"* data per pair in multilingual model: {model_dict['_data_per_pair']}\n"
183
+
184
+ tuned = ""
185
+ if "_tuned" in model_dict:
186
+ tuned = f"* multilingual model tuned for: {model_dict['_tuned']}\n"
187
+
188
+ model_base_filename = model_dict["release"].split("/")[-1]
189
+ download = f"* download original weights: [{model_base_filename}]({model_dir_url}/{model_dict['release']})\n"
190
+
191
+ langtoken = ""
192
+ if tgt_multilingual:
193
+ langtoken = (
194
+ "* a sentence-initial language token is required in the form of >>id<<"
195
+ "(id = valid, usually three-letter target language ID)\n"
196
+ )
197
+
198
+ metadata.update(get_system_metadata(DEFAULT_REPO))
199
+
200
+ scorestable = ""
201
+ for k, v in model_dict.items():
202
+ if "scores" in k:
203
+ this_score_table = f"* {k}\n|Test set|score|\n|---|---|\n"
204
+ pairs = sorted(v.items(), key=lambda x: x[1], reverse=True)
205
+ for pair in pairs:
206
+ this_score_table += f"|{pair[0]}|{pair[1]}|\n"
207
+ scorestable += this_score_table
208
+
209
+ datainfo = ""
210
+ if "training-data" in model_dict:
211
+ datainfo += "* Training data: \n"
212
+ for k, v in model_dict["training-data"].items():
213
+ datainfo += f" * {str(k)}: {str(v)}\n"
214
+ if "validation-data" in model_dict:
215
+ datainfo += "* Validation data: \n"
216
+ for k, v in model_dict["validation-data"].items():
217
+ datainfo += f" * {str(k)}: {str(v)}\n"
218
+ if "test-data" in model_dict:
219
+ datainfo += "* Test data: \n"
220
+ for k, v in model_dict["test-data"].items():
221
+ datainfo += f" * {str(k)}: {str(v)}\n"
222
+
223
+ testsetfilename = model_dict["release"].replace(".zip", ".test.txt")
224
+ testscoresfilename = model_dict["release"].replace(".zip", ".eval.txt")
225
+ testset = f"* test set translations file: [test.txt]({model_dir_url}/{testsetfilename})\n"
226
+ testscores = f"* test set scores file: [eval.txt]({model_dir_url}/{testscoresfilename})\n"
227
+
228
+ # combine with Tatoeba markdown
229
+ readme_url = f"{TATOEBA_MODELS_URL}/{model_dict['_name']}/README.md"
230
+ extra_markdown = f"""
231
+ ### {model_dict['_name']}
232
+
233
+ * source language name: {self.tag2name[a3_src]}
234
+ * target language name: {self.tag2name[a3_tgt]}
235
+ * OPUS readme: [README.md]({readme_url})
236
+ """
237
+
238
+ content = (
239
+ f"""
240
+ * model: {model_dict['modeltype']}
241
+ * source language code{src_multilingual*'s'}: {', '.join(a2_src_tags)}
242
+ * target language code{tgt_multilingual*'s'}: {', '.join(a2_tgt_tags)}
243
+ * dataset: opus {backtranslated_data}
244
+ * release date: {model_dict['release-date']}
245
+ * pre-processing: {model_dict['pre-processing']}
246
+ """
247
+ + multilingual_data
248
+ + tuned
249
+ + download
250
+ + langtoken
251
+ + datainfo
252
+ + testset
253
+ + testscores
254
+ + scorestable
255
+ )
256
+
257
+ content = FRONT_MATTER_TEMPLATE.format(lang_tags) + extra_markdown + content
258
+
259
+ items = "\n".join([f"* {k}: {v}" for k, v in metadata.items()])
260
+ sec3 = "\n### System Info: \n" + items
261
+ content += sec3
262
+ if dry_run:
263
+ print("CONTENT:")
264
+ print(content)
265
+ print("METADATA:")
266
+ print(metadata)
267
+ return
268
+ sub_dir = self.model_card_dir / model_dict["_hf_model_id"]
269
+ sub_dir.mkdir(exist_ok=True)
270
+ dest = sub_dir / "README.md"
271
+ dest.open("w").write(content)
272
+ for k, v in metadata.items():
273
+ if isinstance(v, datetime.date):
274
+ metadata[k] = datetime.datetime.strftime(v, "%Y-%m-%d")
275
+ with open(sub_dir / "metadata.json", "w", encoding="utf-8") as writeobj:
276
+ json.dump(metadata, writeobj)
277
+
278
+ def download_lang_info(self):
279
+ global LANG_CODE_PATH
280
+ Path(LANG_CODE_PATH).parent.mkdir(exist_ok=True)
281
+ import wget
282
+ from huggingface_hub import hf_hub_download
283
+
284
+ if not os.path.exists(ISO_PATH):
285
+ wget.download(ISO_URL, ISO_PATH)
286
+ if not os.path.exists(LANG_CODE_PATH):
287
+ LANG_CODE_PATH = hf_hub_download(
288
+ repo_id="huggingface/language_codes_marianMT", filename="language-codes-3b2.csv", repo_type="dataset"
289
+ )
290
+
291
+ def parse_metadata(self, model_name, repo_path=DEFAULT_MODEL_DIR, method="best"):
292
+ p = Path(repo_path) / model_name
293
+
294
+ def url_to_name(url):
295
+ return url.split("/")[-1].split(".")[0]
296
+
297
+ if model_name not in self.model_results:
298
+ # This is not a language pair, so model results are ambiguous, go by newest
299
+ method = "newest"
300
+
301
+ if method == "best":
302
+ # Sort by how early they appear in released-models-results
303
+ results = [url_to_name(model["download"]) for model in self.model_results[model_name]]
304
+ ymls = [f for f in os.listdir(p) if f.endswith(".yml") and f[:-4] in results]
305
+ ymls.sort(key=lambda x: results.index(x[:-4]))
306
+ metadata = yaml.safe_load(open(p / ymls[0]))
307
+ metadata.update(self.model_type_info_from_model_name(ymls[0][:-4]))
308
+ elif method == "newest":
309
+ ymls = [f for f in os.listdir(p) if f.endswith(".yml")]
310
+ # Sort by date
311
+ ymls.sort(
312
+ key=lambda x: datetime.datetime.strptime(re.search(r"\d\d\d\d-\d\d?-\d\d?", x).group(), "%Y-%m-%d")
313
+ )
314
+ metadata = yaml.safe_load(open(p / ymls[-1]))
315
+ metadata.update(self.model_type_info_from_model_name(ymls[-1][:-4]))
316
+ else:
317
+ raise NotImplementedError(f"Don't know argument method='{method}' to parse_metadata()")
318
+ metadata["_name"] = model_name
319
+ return metadata
320
+
321
+
322
+ GROUP_MEMBERS = {
323
+ # three letter code -> (group/language name, {constituents...}
324
+ # if this language is on the target side the constituents can be used as target language codes.
325
+ # if the language is on the source side they are supported natively without special codes.
326
+ "aav": ("Austro-Asiatic languages", {"hoc", "hoc_Latn", "kha", "khm", "khm_Latn", "mnw", "vie", "vie_Hani"}),
327
+ "afa": (
328
+ "Afro-Asiatic languages",
329
+ {
330
+ "acm",
331
+ "afb",
332
+ "amh",
333
+ "apc",
334
+ "ara",
335
+ "arq",
336
+ "ary",
337
+ "arz",
338
+ "hau_Latn",
339
+ "heb",
340
+ "kab",
341
+ "mlt",
342
+ "rif_Latn",
343
+ "shy_Latn",
344
+ "som",
345
+ "thv",
346
+ "tir",
347
+ },
348
+ ),
349
+ "afr": ("Afrikaans", {"afr"}),
350
+ "alv": (
351
+ "Atlantic-Congo languages",
352
+ {
353
+ "ewe",
354
+ "fuc",
355
+ "fuv",
356
+ "ibo",
357
+ "kin",
358
+ "lin",
359
+ "lug",
360
+ "nya",
361
+ "run",
362
+ "sag",
363
+ "sna",
364
+ "swh",
365
+ "toi_Latn",
366
+ "tso",
367
+ "umb",
368
+ "wol",
369
+ "xho",
370
+ "yor",
371
+ "zul",
372
+ },
373
+ ),
374
+ "ara": ("Arabic", {"afb", "apc", "apc_Latn", "ara", "ara_Latn", "arq", "arq_Latn", "arz"}),
375
+ "art": (
376
+ "Artificial languages",
377
+ {
378
+ "afh_Latn",
379
+ "avk_Latn",
380
+ "dws_Latn",
381
+ "epo",
382
+ "ido",
383
+ "ido_Latn",
384
+ "ile_Latn",
385
+ "ina_Latn",
386
+ "jbo",
387
+ "jbo_Cyrl",
388
+ "jbo_Latn",
389
+ "ldn_Latn",
390
+ "lfn_Cyrl",
391
+ "lfn_Latn",
392
+ "nov_Latn",
393
+ "qya",
394
+ "qya_Latn",
395
+ "sjn_Latn",
396
+ "tlh_Latn",
397
+ "tzl",
398
+ "tzl_Latn",
399
+ "vol_Latn",
400
+ },
401
+ ),
402
+ "aze": ("Azerbaijani", {"aze_Latn"}),
403
+ "bat": ("Baltic languages", {"lit", "lav", "prg_Latn", "ltg", "sgs"}),
404
+ "bel": ("Belarusian", {"bel", "bel_Latn"}),
405
+ "ben": ("Bengali", {"ben"}),
406
+ "bnt": (
407
+ "Bantu languages",
408
+ {"kin", "lin", "lug", "nya", "run", "sna", "swh", "toi_Latn", "tso", "umb", "xho", "zul"},
409
+ ),
410
+ "bul": ("Bulgarian", {"bul", "bul_Latn"}),
411
+ "cat": ("Catalan", {"cat"}),
412
+ "cau": ("Caucasian languages", {"abk", "kat", "che", "ady"}),
413
+ "ccs": ("South Caucasian languages", {"kat"}),
414
+ "ceb": ("Cebuano", {"ceb"}),
415
+ "cel": ("Celtic languages", {"gla", "gle", "bre", "cor", "glv", "cym"}),
416
+ "ces": ("Czech", {"ces"}),
417
+ "cpf": ("Creoles and pidgins, French‑based", {"gcf_Latn", "hat", "mfe"}),
418
+ "cpp": (
419
+ "Creoles and pidgins, Portuguese-based",
420
+ {"zsm_Latn", "ind", "pap", "min", "tmw_Latn", "max_Latn", "zlm_Latn"},
421
+ ),
422
+ "cus": ("Cushitic languages", {"som"}),
423
+ "dan": ("Danish", {"dan"}),
424
+ "deu": ("German", {"deu"}),
425
+ "dra": ("Dravidian languages", {"tam", "kan", "mal", "tel"}),
426
+ "ell": ("Modern Greek (1453-)", {"ell"}),
427
+ "eng": ("English", {"eng"}),
428
+ "epo": ("Esperanto", {"epo"}),
429
+ "est": ("Estonian", {"est"}),
430
+ "euq": ("Basque (family)", {"eus"}),
431
+ "eus": ("Basque", {"eus"}),
432
+ "fin": ("Finnish", {"fin"}),
433
+ "fiu": (
434
+ "Finno-Ugrian languages",
435
+ {
436
+ "est",
437
+ "fin",
438
+ "fkv_Latn",
439
+ "hun",
440
+ "izh",
441
+ "kpv",
442
+ "krl",
443
+ "liv_Latn",
444
+ "mdf",
445
+ "mhr",
446
+ "myv",
447
+ "sma",
448
+ "sme",
449
+ "udm",
450
+ "vep",
451
+ "vro",
452
+ },
453
+ ),
454
+ "fra": ("French", {"fra"}),
455
+ "gem": (
456
+ "Germanic languages",
457
+ {
458
+ "afr",
459
+ "ang_Latn",
460
+ "dan",
461
+ "deu",
462
+ "eng",
463
+ "enm_Latn",
464
+ "fao",
465
+ "frr",
466
+ "fry",
467
+ "gos",
468
+ "got_Goth",
469
+ "gsw",
470
+ "isl",
471
+ "ksh",
472
+ "ltz",
473
+ "nds",
474
+ "nld",
475
+ "nno",
476
+ "nob",
477
+ "nob_Hebr",
478
+ "non_Latn",
479
+ "pdc",
480
+ "sco",
481
+ "stq",
482
+ "swe",
483
+ "swg",
484
+ "yid",
485
+ },
486
+ ),
487
+ "gle": ("Irish", {"gle"}),
488
+ "glg": ("Galician", {"glg"}),
489
+ "gmq": ("North Germanic languages", {"dan", "nob", "nob_Hebr", "swe", "isl", "nno", "non_Latn", "fao"}),
490
+ "gmw": (
491
+ "West Germanic languages",
492
+ {
493
+ "afr",
494
+ "ang_Latn",
495
+ "deu",
496
+ "eng",
497
+ "enm_Latn",
498
+ "frr",
499
+ "fry",
500
+ "gos",
501
+ "gsw",
502
+ "ksh",
503
+ "ltz",
504
+ "nds",
505
+ "nld",
506
+ "pdc",
507
+ "sco",
508
+ "stq",
509
+ "swg",
510
+ "yid",
511
+ },
512
+ ),
513
+ "grk": ("Greek languages", {"grc_Grek", "ell"}),
514
+ "hbs": ("Serbo-Croatian", {"hrv", "srp_Cyrl", "bos_Latn", "srp_Latn"}),
515
+ "heb": ("Hebrew", {"heb"}),
516
+ "hin": ("Hindi", {"hin"}),
517
+ "hun": ("Hungarian", {"hun"}),
518
+ "hye": ("Armenian", {"hye", "hye_Latn"}),
519
+ "iir": (
520
+ "Indo-Iranian languages",
521
+ {
522
+ "asm",
523
+ "awa",
524
+ "ben",
525
+ "bho",
526
+ "gom",
527
+ "guj",
528
+ "hif_Latn",
529
+ "hin",
530
+ "jdt_Cyrl",
531
+ "kur_Arab",
532
+ "kur_Latn",
533
+ "mai",
534
+ "mar",
535
+ "npi",
536
+ "ori",
537
+ "oss",
538
+ "pan_Guru",
539
+ "pes",
540
+ "pes_Latn",
541
+ "pes_Thaa",
542
+ "pnb",
543
+ "pus",
544
+ "rom",
545
+ "san_Deva",
546
+ "sin",
547
+ "snd_Arab",
548
+ "tgk_Cyrl",
549
+ "tly_Latn",
550
+ "urd",
551
+ "zza",
552
+ },
553
+ ),
554
+ "ilo": ("Iloko", {"ilo"}),
555
+ "inc": (
556
+ "Indic languages",
557
+ {
558
+ "asm",
559
+ "awa",
560
+ "ben",
561
+ "bho",
562
+ "gom",
563
+ "guj",
564
+ "hif_Latn",
565
+ "hin",
566
+ "mai",
567
+ "mar",
568
+ "npi",
569
+ "ori",
570
+ "pan_Guru",
571
+ "pnb",
572
+ "rom",
573
+ "san_Deva",
574
+ "sin",
575
+ "snd_Arab",
576
+ "urd",
577
+ },
578
+ ),
579
+ "ine": (
580
+ "Indo-European languages",
581
+ {
582
+ "afr",
583
+ "afr_Arab",
584
+ "aln",
585
+ "ang_Latn",
586
+ "arg",
587
+ "asm",
588
+ "ast",
589
+ "awa",
590
+ "bel",
591
+ "bel_Latn",
592
+ "ben",
593
+ "bho",
594
+ "bjn",
595
+ "bos_Latn",
596
+ "bre",
597
+ "bul",
598
+ "bul_Latn",
599
+ "cat",
600
+ "ces",
601
+ "cor",
602
+ "cos",
603
+ "csb_Latn",
604
+ "cym",
605
+ "dan",
606
+ "deu",
607
+ "dsb",
608
+ "egl",
609
+ "ell",
610
+ "eng",
611
+ "enm_Latn",
612
+ "ext",
613
+ "fao",
614
+ "fra",
615
+ "frm_Latn",
616
+ "frr",
617
+ "fry",
618
+ "gcf_Latn",
619
+ "gla",
620
+ "gle",
621
+ "glg",
622
+ "glv",
623
+ "gom",
624
+ "gos",
625
+ "got_Goth",
626
+ "grc_Grek",
627
+ "gsw",
628
+ "guj",
629
+ "hat",
630
+ "hif_Latn",
631
+ "hin",
632
+ "hrv",
633
+ "hsb",
634
+ "hye",
635
+ "hye_Latn",
636
+ "ind",
637
+ "isl",
638
+ "ita",
639
+ "jdt_Cyrl",
640
+ "ksh",
641
+ "kur_Arab",
642
+ "kur_Latn",
643
+ "lad",
644
+ "lad_Latn",
645
+ "lat_Grek",
646
+ "lat_Latn",
647
+ "lav",
648
+ "lij",
649
+ "lit",
650
+ "lld_Latn",
651
+ "lmo",
652
+ "ltg",
653
+ "ltz",
654
+ "mai",
655
+ "mar",
656
+ "max_Latn",
657
+ "mfe",
658
+ "min",
659
+ "mkd",
660
+ "mwl",
661
+ "nds",
662
+ "nld",
663
+ "nno",
664
+ "nob",
665
+ "nob_Hebr",
666
+ "non_Latn",
667
+ "npi",
668
+ "oci",
669
+ "ori",
670
+ "orv_Cyrl",
671
+ "oss",
672
+ "pan_Guru",
673
+ "pap",
674
+ "pcd",
675
+ "pdc",
676
+ "pes",
677
+ "pes_Latn",
678
+ "pes_Thaa",
679
+ "pms",
680
+ "pnb",
681
+ "pol",
682
+ "por",
683
+ "prg_Latn",
684
+ "pus",
685
+ "roh",
686
+ "rom",
687
+ "ron",
688
+ "rue",
689
+ "rus",
690
+ "rus_Latn",
691
+ "san_Deva",
692
+ "scn",
693
+ "sco",
694
+ "sgs",
695
+ "sin",
696
+ "slv",
697
+ "snd_Arab",
698
+ "spa",
699
+ "sqi",
700
+ "srd",
701
+ "srp_Cyrl",
702
+ "srp_Latn",
703
+ "stq",
704
+ "swe",
705
+ "swg",
706
+ "tgk_Cyrl",
707
+ "tly_Latn",
708
+ "tmw_Latn",
709
+ "ukr",
710
+ "urd",
711
+ "vec",
712
+ "wln",
713
+ "yid",
714
+ "zlm_Latn",
715
+ "zsm_Latn",
716
+ "zza",
717
+ },
718
+ ),
719
+ "isl": ("Icelandic", {"isl"}),
720
+ "ita": ("Italian", {"ita"}),
721
+ "itc": (
722
+ "Italic languages",
723
+ {
724
+ "arg",
725
+ "ast",
726
+ "bjn",
727
+ "cat",
728
+ "cos",
729
+ "egl",
730
+ "ext",
731
+ "fra",
732
+ "frm_Latn",
733
+ "gcf_Latn",
734
+ "glg",
735
+ "hat",
736
+ "ind",
737
+ "ita",
738
+ "lad",
739
+ "lad_Latn",
740
+ "lat_Grek",
741
+ "lat_Latn",
742
+ "lij",
743
+ "lld_Latn",
744
+ "lmo",
745
+ "max_Latn",
746
+ "mfe",
747
+ "min",
748
+ "mwl",
749
+ "oci",
750
+ "pap",
751
+ "pcd",
752
+ "pms",
753
+ "por",
754
+ "roh",
755
+ "ron",
756
+ "scn",
757
+ "spa",
758
+ "srd",
759
+ "tmw_Latn",
760
+ "vec",
761
+ "wln",
762
+ "zlm_Latn",
763
+ "zsm_Latn",
764
+ },
765
+ ),
766
+ "jpn": ("Japanese", {"jpn", "jpn_Bopo", "jpn_Hang", "jpn_Hani", "jpn_Hira", "jpn_Kana", "jpn_Latn", "jpn_Yiii"}),
767
+ "jpx": ("Japanese (family)", {"jpn"}),
768
+ "kat": ("Georgian", {"kat"}),
769
+ "kor": ("Korean", {"kor_Hani", "kor_Hang", "kor_Latn", "kor"}),
770
+ "lav": ("Latvian", {"lav"}),
771
+ "lit": ("Lithuanian", {"lit"}),
772
+ "mkd": ("Macedonian", {"mkd"}),
773
+ "mkh": ("Mon-Khmer languages", {"vie_Hani", "mnw", "vie", "kha", "khm_Latn", "khm"}),
774
+ "msa": ("Malay (macrolanguage)", {"zsm_Latn", "ind", "max_Latn", "zlm_Latn", "min"}),
775
+ "mul": (
776
+ "Multiple languages",
777
+ {
778
+ "abk",
779
+ "acm",
780
+ "ady",
781
+ "afb",
782
+ "afh_Latn",
783
+ "afr",
784
+ "akl_Latn",
785
+ "aln",
786
+ "amh",
787
+ "ang_Latn",
788
+ "apc",
789
+ "ara",
790
+ "arg",
791
+ "arq",
792
+ "ary",
793
+ "arz",
794
+ "asm",
795
+ "ast",
796
+ "avk_Latn",
797
+ "awa",
798
+ "aze_Latn",
799
+ "bak",
800
+ "bam_Latn",
801
+ "bel",
802
+ "bel_Latn",
803
+ "ben",
804
+ "bho",
805
+ "bod",
806
+ "bos_Latn",
807
+ "bre",
808
+ "brx",
809
+ "brx_Latn",
810
+ "bul",
811
+ "bul_Latn",
812
+ "cat",
813
+ "ceb",
814
+ "ces",
815
+ "cha",
816
+ "che",
817
+ "chr",
818
+ "chv",
819
+ "cjy_Hans",
820
+ "cjy_Hant",
821
+ "cmn",
822
+ "cmn_Hans",
823
+ "cmn_Hant",
824
+ "cor",
825
+ "cos",
826
+ "crh",
827
+ "crh_Latn",
828
+ "csb_Latn",
829
+ "cym",
830
+ "dan",
831
+ "deu",
832
+ "dsb",
833
+ "dtp",
834
+ "dws_Latn",
835
+ "egl",
836
+ "ell",
837
+ "enm_Latn",
838
+ "epo",
839
+ "est",
840
+ "eus",
841
+ "ewe",
842
+ "ext",
843
+ "fao",
844
+ "fij",
845
+ "fin",
846
+ "fkv_Latn",
847
+ "fra",
848
+ "frm_Latn",
849
+ "frr",
850
+ "fry",
851
+ "fuc",
852
+ "fuv",
853
+ "gan",
854
+ "gcf_Latn",
855
+ "gil",
856
+ "gla",
857
+ "gle",
858
+ "glg",
859
+ "glv",
860
+ "gom",
861
+ "gos",
862
+ "got_Goth",
863
+ "grc_Grek",
864
+ "grn",
865
+ "gsw",
866
+ "guj",
867
+ "hat",
868
+ "hau_Latn",
869
+ "haw",
870
+ "heb",
871
+ "hif_Latn",
872
+ "hil",
873
+ "hin",
874
+ "hnj_Latn",
875
+ "hoc",
876
+ "hoc_Latn",
877
+ "hrv",
878
+ "hsb",
879
+ "hun",
880
+ "hye",
881
+ "iba",
882
+ "ibo",
883
+ "ido",
884
+ "ido_Latn",
885
+ "ike_Latn",
886
+ "ile_Latn",
887
+ "ilo",
888
+ "ina_Latn",
889
+ "ind",
890
+ "isl",
891
+ "ita",
892
+ "izh",
893
+ "jav",
894
+ "jav_Java",
895
+ "jbo",
896
+ "jbo_Cyrl",
897
+ "jbo_Latn",
898
+ "jdt_Cyrl",
899
+ "jpn",
900
+ "kab",
901
+ "kal",
902
+ "kan",
903
+ "kat",
904
+ "kaz_Cyrl",
905
+ "kaz_Latn",
906
+ "kek_Latn",
907
+ "kha",
908
+ "khm",
909
+ "khm_Latn",
910
+ "kin",
911
+ "kir_Cyrl",
912
+ "kjh",
913
+ "kpv",
914
+ "krl",
915
+ "ksh",
916
+ "kum",
917
+ "kur_Arab",
918
+ "kur_Latn",
919
+ "lad",
920
+ "lad_Latn",
921
+ "lao",
922
+ "lat_Latn",
923
+ "lav",
924
+ "ldn_Latn",
925
+ "lfn_Cyrl",
926
+ "lfn_Latn",
927
+ "lij",
928
+ "lin",
929
+ "lit",
930
+ "liv_Latn",
931
+ "lkt",
932
+ "lld_Latn",
933
+ "lmo",
934
+ "ltg",
935
+ "ltz",
936
+ "lug",
937
+ "lzh",
938
+ "lzh_Hans",
939
+ "mad",
940
+ "mah",
941
+ "mai",
942
+ "mal",
943
+ "mar",
944
+ "max_Latn",
945
+ "mdf",
946
+ "mfe",
947
+ "mhr",
948
+ "mic",
949
+ "min",
950
+ "mkd",
951
+ "mlg",
952
+ "mlt",
953
+ "mnw",
954
+ "moh",
955
+ "mon",
956
+ "mri",
957
+ "mwl",
958
+ "mww",
959
+ "mya",
960
+ "myv",
961
+ "nan",
962
+ "nau",
963
+ "nav",
964
+ "nds",
965
+ "niu",
966
+ "nld",
967
+ "nno",
968
+ "nob",
969
+ "nob_Hebr",
970
+ "nog",
971
+ "non_Latn",
972
+ "nov_Latn",
973
+ "npi",
974
+ "nya",
975
+ "oci",
976
+ "ori",
977
+ "orv_Cyrl",
978
+ "oss",
979
+ "ota_Arab",
980
+ "ota_Latn",
981
+ "pag",
982
+ "pan_Guru",
983
+ "pap",
984
+ "pau",
985
+ "pdc",
986
+ "pes",
987
+ "pes_Latn",
988
+ "pes_Thaa",
989
+ "pms",
990
+ "pnb",
991
+ "pol",
992
+ "por",
993
+ "ppl_Latn",
994
+ "prg_Latn",
995
+ "pus",
996
+ "quc",
997
+ "qya",
998
+ "qya_Latn",
999
+ "rap",
1000
+ "rif_Latn",
1001
+ "roh",
1002
+ "rom",
1003
+ "ron",
1004
+ "rue",
1005
+ "run",
1006
+ "rus",
1007
+ "sag",
1008
+ "sah",
1009
+ "san_Deva",
1010
+ "scn",
1011
+ "sco",
1012
+ "sgs",
1013
+ "shs_Latn",
1014
+ "shy_Latn",
1015
+ "sin",
1016
+ "sjn_Latn",
1017
+ "slv",
1018
+ "sma",
1019
+ "sme",
1020
+ "smo",
1021
+ "sna",
1022
+ "snd_Arab",
1023
+ "som",
1024
+ "spa",
1025
+ "sqi",
1026
+ "srp_Cyrl",
1027
+ "srp_Latn",
1028
+ "stq",
1029
+ "sun",
1030
+ "swe",
1031
+ "swg",
1032
+ "swh",
1033
+ "tah",
1034
+ "tam",
1035
+ "tat",
1036
+ "tat_Arab",
1037
+ "tat_Latn",
1038
+ "tel",
1039
+ "tet",
1040
+ "tgk_Cyrl",
1041
+ "tha",
1042
+ "tir",
1043
+ "tlh_Latn",
1044
+ "tly_Latn",
1045
+ "tmw_Latn",
1046
+ "toi_Latn",
1047
+ "ton",
1048
+ "tpw_Latn",
1049
+ "tso",
1050
+ "tuk",
1051
+ "tuk_Latn",
1052
+ "tur",
1053
+ "tvl",
1054
+ "tyv",
1055
+ "tzl",
1056
+ "tzl_Latn",
1057
+ "udm",
1058
+ "uig_Arab",
1059
+ "uig_Cyrl",
1060
+ "ukr",
1061
+ "umb",
1062
+ "urd",
1063
+ "uzb_Cyrl",
1064
+ "uzb_Latn",
1065
+ "vec",
1066
+ "vie",
1067
+ "vie_Hani",
1068
+ "vol_Latn",
1069
+ "vro",
1070
+ "war",
1071
+ "wln",
1072
+ "wol",
1073
+ "wuu",
1074
+ "xal",
1075
+ "xho",
1076
+ "yid",
1077
+ "yor",
1078
+ "yue",
1079
+ "yue_Hans",
1080
+ "yue_Hant",
1081
+ "zho",
1082
+ "zho_Hans",
1083
+ "zho_Hant",
1084
+ "zlm_Latn",
1085
+ "zsm_Latn",
1086
+ "zul",
1087
+ "zza",
1088
+ },
1089
+ ),
1090
+ "nic": (
1091
+ "Niger-Kordofanian languages",
1092
+ {
1093
+ "bam_Latn",
1094
+ "ewe",
1095
+ "fuc",
1096
+ "fuv",
1097
+ "ibo",
1098
+ "kin",
1099
+ "lin",
1100
+ "lug",
1101
+ "nya",
1102
+ "run",
1103
+ "sag",
1104
+ "sna",
1105
+ "swh",
1106
+ "toi_Latn",
1107
+ "tso",
1108
+ "umb",
1109
+ "wol",
1110
+ "xho",
1111
+ "yor",
1112
+ "zul",
1113
+ },
1114
+ ),
1115
+ "nld": ("Dutch", {"nld"}),
1116
+ "nor": ("Norwegian", {"nob", "nno"}),
1117
+ "phi": ("Philippine languages", {"ilo", "akl_Latn", "war", "hil", "pag", "ceb"}),
1118
+ "pol": ("Polish", {"pol"}),
1119
+ "por": ("Portuguese", {"por"}),
1120
+ "pqe": (
1121
+ "Eastern Malayo-Polynesian languages",
1122
+ {"fij", "gil", "haw", "mah", "mri", "nau", "niu", "rap", "smo", "tah", "ton", "tvl"},
1123
+ ),
1124
+ "roa": (
1125
+ "Romance languages",
1126
+ {
1127
+ "arg",
1128
+ "ast",
1129
+ "cat",
1130
+ "cos",
1131
+ "egl",
1132
+ "ext",
1133
+ "fra",
1134
+ "frm_Latn",
1135
+ "gcf_Latn",
1136
+ "glg",
1137
+ "hat",
1138
+ "ind",
1139
+ "ita",
1140
+ "lad",
1141
+ "lad_Latn",
1142
+ "lij",
1143
+ "lld_Latn",
1144
+ "lmo",
1145
+ "max_Latn",
1146
+ "mfe",
1147
+ "min",
1148
+ "mwl",
1149
+ "oci",
1150
+ "pap",
1151
+ "pms",
1152
+ "por",
1153
+ "roh",
1154
+ "ron",
1155
+ "scn",
1156
+ "spa",
1157
+ "tmw_Latn",
1158
+ "vec",
1159
+ "wln",
1160
+ "zlm_Latn",
1161
+ "zsm_Latn",
1162
+ },
1163
+ ),
1164
+ "ron": ("Romanian", {"ron"}),
1165
+ "run": ("Rundi", {"run"}),
1166
+ "rus": ("Russian", {"rus"}),
1167
+ "sal": ("Salishan languages", {"shs_Latn"}),
1168
+ "sem": ("Semitic languages", {"acm", "afb", "amh", "apc", "ara", "arq", "ary", "arz", "heb", "mlt", "tir"}),
1169
+ "sla": (
1170
+ "Slavic languages",
1171
+ {
1172
+ "bel",
1173
+ "bel_Latn",
1174
+ "bos_Latn",
1175
+ "bul",
1176
+ "bul_Latn",
1177
+ "ces",
1178
+ "csb_Latn",
1179
+ "dsb",
1180
+ "hrv",
1181
+ "hsb",
1182
+ "mkd",
1183
+ "orv_Cyrl",
1184
+ "pol",
1185
+ "rue",
1186
+ "rus",
1187
+ "slv",
1188
+ "srp_Cyrl",
1189
+ "srp_Latn",
1190
+ "ukr",
1191
+ },
1192
+ ),
1193
+ "slv": ("Slovenian", {"slv"}),
1194
+ "spa": ("Spanish", {"spa"}),
1195
+ "swe": ("Swedish", {"swe"}),
1196
+ "taw": ("Tai", {"lao", "tha"}),
1197
+ "tgl": ("Tagalog", {"tgl_Latn"}),
1198
+ "tha": ("Thai", {"tha"}),
1199
+ "trk": (
1200
+ "Turkic languages",
1201
+ {
1202
+ "aze_Latn",
1203
+ "bak",
1204
+ "chv",
1205
+ "crh",
1206
+ "crh_Latn",
1207
+ "kaz_Cyrl",
1208
+ "kaz_Latn",
1209
+ "kir_Cyrl",
1210
+ "kjh",
1211
+ "kum",
1212
+ "ota_Arab",
1213
+ "ota_Latn",
1214
+ "sah",
1215
+ "tat",
1216
+ "tat_Arab",
1217
+ "tat_Latn",
1218
+ "tuk",
1219
+ "tuk_Latn",
1220
+ "tur",
1221
+ "tyv",
1222
+ "uig_Arab",
1223
+ "uig_Cyrl",
1224
+ "uzb_Cyrl",
1225
+ "uzb_Latn",
1226
+ },
1227
+ ),
1228
+ "tur": ("Turkish", {"tur"}),
1229
+ "ukr": ("Ukrainian", {"ukr"}),
1230
+ "urd": ("Urdu", {"urd"}),
1231
+ "urj": (
1232
+ "Uralic languages",
1233
+ {
1234
+ "est",
1235
+ "fin",
1236
+ "fkv_Latn",
1237
+ "hun",
1238
+ "izh",
1239
+ "kpv",
1240
+ "krl",
1241
+ "liv_Latn",
1242
+ "mdf",
1243
+ "mhr",
1244
+ "myv",
1245
+ "sma",
1246
+ "sme",
1247
+ "udm",
1248
+ "vep",
1249
+ "vro",
1250
+ },
1251
+ ),
1252
+ "vie": ("Vietnamese", {"vie", "vie_Hani"}),
1253
+ "war": ("Waray (Philippines)", {"war"}),
1254
+ "zho": (
1255
+ "Chinese",
1256
+ {
1257
+ "cjy_Hans",
1258
+ "cjy_Hant",
1259
+ "cmn",
1260
+ "cmn_Bopo",
1261
+ "cmn_Hang",
1262
+ "cmn_Hani",
1263
+ "cmn_Hans",
1264
+ "cmn_Hant",
1265
+ "cmn_Hira",
1266
+ "cmn_Kana",
1267
+ "cmn_Latn",
1268
+ "cmn_Yiii",
1269
+ "gan",
1270
+ "hak_Hani",
1271
+ "lzh",
1272
+ "lzh_Bopo",
1273
+ "lzh_Hang",
1274
+ "lzh_Hani",
1275
+ "lzh_Hans",
1276
+ "lzh_Hira",
1277
+ "lzh_Kana",
1278
+ "lzh_Yiii",
1279
+ "nan",
1280
+ "nan_Hani",
1281
+ "wuu",
1282
+ "wuu_Bopo",
1283
+ "wuu_Hani",
1284
+ "wuu_Latn",
1285
+ "yue",
1286
+ "yue_Bopo",
1287
+ "yue_Hang",
1288
+ "yue_Hani",
1289
+ "yue_Hans",
1290
+ "yue_Hant",
1291
+ "yue_Hira",
1292
+ "yue_Kana",
1293
+ "zho",
1294
+ "zho_Hans",
1295
+ "zho_Hant",
1296
+ },
1297
+ ),
1298
+ "zle": ("East Slavic languages", {"bel", "orv_Cyrl", "bel_Latn", "rus", "ukr", "rue"}),
1299
+ "zls": ("South Slavic languages", {"bos_Latn", "bul", "bul_Latn", "hrv", "mkd", "slv", "srp_Cyrl", "srp_Latn"}),
1300
+ "zlw": ("West Slavic languages", {"csb_Latn", "dsb", "hsb", "pol", "ces"}),
1301
+ }
1302
+
1303
+
1304
+ def l2front_matter(langs):
1305
+ return "".join(f"- {l}\n" for l in langs)
1306
+
1307
+
1308
+ def dedup(lst):
1309
+ """Preservers order"""
1310
+ new_lst = []
1311
+ for item in lst:
1312
+ if not item or item in new_lst:
1313
+ continue
1314
+ else:
1315
+ new_lst.append(item)
1316
+ return new_lst
1317
+
1318
+
1319
+ if __name__ == "__main__":
1320
+ parser = argparse.ArgumentParser()
1321
+ parser.add_argument(
1322
+ "-m", "--models", action="append", help="<Required> Set flag", required=True, nargs="+", dest="models"
1323
+ )
1324
+ parser.add_argument("-save_dir", "--save_dir", default="marian_converted", help="where to save converted models")
1325
+ args = parser.parse_args()
1326
+ resolver = TatoebaConverter(save_dir=args.save_dir)
1327
+ resolver.convert_models(args.models[0])
tasks/tasksmith-441eeab80047/environment/source/src/transformers/models/marian/convert_marian_to_pytorch.py ADDED
@@ -0,0 +1,717 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ import argparse
16
+ import json
17
+ import os
18
+ import socket
19
+ import time
20
+ import warnings
21
+ from pathlib import Path
22
+ from typing import Dict, List, Union
23
+ from zipfile import ZipFile
24
+
25
+ import numpy as np
26
+ import torch
27
+ from huggingface_hub.hf_api import list_models
28
+ from torch import nn
29
+ from tqdm import tqdm
30
+
31
+ from transformers import MarianConfig, MarianMTModel, MarianTokenizer
32
+
33
+
34
+ def remove_suffix(text: str, suffix: str):
35
+ if text.endswith(suffix):
36
+ return text[: -len(suffix)]
37
+ return text # or whatever
38
+
39
+
40
+ def remove_prefix(text: str, prefix: str):
41
+ if text.startswith(prefix):
42
+ return text[len(prefix) :]
43
+ return text # or whatever
44
+
45
+
46
+ def convert_encoder_layer(opus_dict, layer_prefix: str, converter: dict):
47
+ sd = {}
48
+ for k in opus_dict:
49
+ if not k.startswith(layer_prefix):
50
+ continue
51
+ stripped = remove_prefix(k, layer_prefix)
52
+ v = opus_dict[k].T # besides embeddings, everything must be transposed.
53
+ sd[converter[stripped]] = torch.tensor(v).squeeze()
54
+ return sd
55
+
56
+
57
+ def load_layers_(layer_lst: nn.ModuleList, opus_state: dict, converter, is_decoder=False):
58
+ for i, layer in enumerate(layer_lst):
59
+ layer_tag = f"decoder_l{i + 1}_" if is_decoder else f"encoder_l{i + 1}_"
60
+ sd = convert_encoder_layer(opus_state, layer_tag, converter)
61
+ layer.load_state_dict(sd, strict=False)
62
+
63
+
64
+ def find_pretrained_model(src_lang: str, tgt_lang: str) -> List[str]:
65
+ """Find models that can accept src_lang as input and return tgt_lang as output."""
66
+ prefix = "Helsinki-NLP/opus-mt-"
67
+ model_list = list_models()
68
+ model_ids = [x.id for x in model_list if x.id.startswith("Helsinki-NLP")]
69
+ src_and_targ = [
70
+ remove_prefix(m, prefix).lower().split("-") for m in model_ids if "+" not in m
71
+ ] # + cant be loaded.
72
+ matching = [f"{prefix}{a}-{b}" for (a, b) in src_and_targ if src_lang in a and tgt_lang in b]
73
+ return matching
74
+
75
+
76
+ def add_emb_entries(wemb, final_bias, n_special_tokens=1):
77
+ vsize, d_model = wemb.shape
78
+ embs_to_add = np.zeros((n_special_tokens, d_model))
79
+ new_embs = np.concatenate([wemb, embs_to_add])
80
+ bias_to_add = np.zeros((n_special_tokens, 1))
81
+ new_bias = np.concatenate((final_bias, bias_to_add), axis=1)
82
+ return new_embs, new_bias
83
+
84
+
85
+ def _cast_yaml_str(v):
86
+ bool_dct = {"true": True, "false": False}
87
+ if not isinstance(v, str):
88
+ return v
89
+ elif v in bool_dct:
90
+ return bool_dct[v]
91
+ try:
92
+ return int(v)
93
+ except (TypeError, ValueError):
94
+ return v
95
+
96
+
97
+ def cast_marian_config(raw_cfg: Dict[str, str]) -> Dict:
98
+ return {k: _cast_yaml_str(v) for k, v in raw_cfg.items()}
99
+
100
+
101
+ CONFIG_KEY = "special:model.yml"
102
+
103
+
104
+ def load_config_from_state_dict(opus_dict):
105
+ import yaml
106
+
107
+ cfg_str = "".join([chr(x) for x in opus_dict[CONFIG_KEY]])
108
+ yaml_cfg = yaml.load(cfg_str[:-1], Loader=yaml.BaseLoader)
109
+ return cast_marian_config(yaml_cfg)
110
+
111
+
112
+ def find_model_file(dest_dir): # this one better
113
+ model_files = list(Path(dest_dir).glob("*.npz"))
114
+ if len(model_files) != 1:
115
+ raise ValueError(f"Found more than one model file: {model_files}")
116
+ model_file = model_files[0]
117
+ return model_file
118
+
119
+
120
+ # Group Names Logic: change long opus model names to something shorter, like opus-mt-en-ROMANCE
121
+ ROM_GROUP = (
122
+ "fr+fr_BE+fr_CA+fr_FR+wa+frp+oc+ca+rm+lld+fur+lij+lmo+es+es_AR+es_CL+es_CO+es_CR+es_DO+es_EC+es_ES+es_GT"
123
+ "+es_HN+es_MX+es_NI+es_PA+es_PE+es_PR+es_SV+es_UY+es_VE+pt+pt_br+pt_BR+pt_PT+gl+lad+an+mwl+it+it_IT+co"
124
+ "+nap+scn+vec+sc+ro+la"
125
+ )
126
+ GROUPS = [
127
+ ("cmn+cn+yue+ze_zh+zh_cn+zh_CN+zh_HK+zh_tw+zh_TW+zh_yue+zhs+zht+zh", "ZH"),
128
+ (ROM_GROUP, "ROMANCE"),
129
+ ("de+nl+fy+af+da+fo+is+no+nb+nn+sv", "NORTH_EU"),
130
+ ("da+fo+is+no+nb+nn+sv", "SCANDINAVIA"),
131
+ ("se+sma+smj+smn+sms", "SAMI"),
132
+ ("nb_NO+nb+nn_NO+nn+nog+no_nb+no", "NORWAY"),
133
+ ("ga+cy+br+gd+kw+gv", "CELTIC"), # https://en.wikipedia.org/wiki/Insular_Celtic_languages
134
+ ]
135
+ GROUP_TO_OPUS_NAME = {
136
+ "opus-mt-ZH-de": "cmn+cn+yue+ze_zh+zh_cn+zh_CN+zh_HK+zh_tw+zh_TW+zh_yue+zhs+zht+zh-de",
137
+ "opus-mt-ZH-fi": "cmn+cn+yue+ze_zh+zh_cn+zh_CN+zh_HK+zh_tw+zh_TW+zh_yue+zhs+zht+zh-fi",
138
+ "opus-mt-ZH-sv": "cmn+cn+yue+ze_zh+zh_cn+zh_CN+zh_HK+zh_tw+zh_TW+zh_yue+zhs+zht+zh-sv",
139
+ "opus-mt-SCANDINAVIA-SCANDINAVIA": "da+fo+is+no+nb+nn+sv-da+fo+is+no+nb+nn+sv",
140
+ "opus-mt-NORTH_EU-NORTH_EU": "de+nl+fy+af+da+fo+is+no+nb+nn+sv-de+nl+fy+af+da+fo+is+no+nb+nn+sv",
141
+ "opus-mt-de-ZH": "de-cmn+cn+yue+ze_zh+zh_cn+zh_CN+zh_HK+zh_tw+zh_TW+zh_yue+zhs+zht+zh",
142
+ "opus-mt-en_el_es_fi-en_el_es_fi": "en+el+es+fi-en+el+es+fi",
143
+ "opus-mt-en-ROMANCE": (
144
+ "en-fr+fr_BE+fr_CA+fr_FR+wa+frp+oc+ca+rm+lld+fur+lij+lmo+es+es_AR+es_CL+es_CO+es_CR+es_DO"
145
+ "+es_EC+es_ES+es_GT+es_HN+es_MX+es_NI+es_PA+es_PE+es_PR+es_SV+es_UY+es_VE+pt+pt_br+pt_BR"
146
+ "+pt_PT+gl+lad+an+mwl+it+it_IT+co+nap+scn+vec+sc+ro+la"
147
+ ),
148
+ "opus-mt-en-CELTIC": "en-ga+cy+br+gd+kw+gv",
149
+ "opus-mt-es-NORWAY": "es-nb_NO+nb+nn_NO+nn+nog+no_nb+no",
150
+ "opus-mt-fi_nb_no_nn_ru_sv_en-SAMI": "fi+nb+no+nn+ru+sv+en-se+sma+smj+smn+sms",
151
+ "opus-mt-fi-ZH": "fi-cmn+cn+yue+ze_zh+zh_cn+zh_CN+zh_HK+zh_tw+zh_TW+zh_yue+zhs+zht+zh",
152
+ "opus-mt-fi-NORWAY": "fi-nb_NO+nb+nn_NO+nn+nog+no_nb+no",
153
+ "opus-mt-ROMANCE-en": (
154
+ "fr+fr_BE+fr_CA+fr_FR+wa+frp+oc+ca+rm+lld+fur+lij+lmo+es+es_AR+es_CL+es_CO+es_CR+es_DO"
155
+ "+es_EC+es_ES+es_GT+es_HN+es_MX+es_NI+es_PA+es_PE+es_PR+es_SV+es_UY+es_VE+pt+pt_br+pt_BR"
156
+ "+pt_PT+gl+lad+an+mwl+it+it_IT+co+nap+scn+vec+sc+ro+la-en"
157
+ ),
158
+ "opus-mt-CELTIC-en": "ga+cy+br+gd+kw+gv-en",
159
+ "opus-mt-sv-ZH": "sv-cmn+cn+yue+ze_zh+zh_cn+zh_CN+zh_HK+zh_tw+zh_TW+zh_yue+zhs+zht+zh",
160
+ "opus-mt-sv-NORWAY": "sv-nb_NO+nb+nn_NO+nn+nog+no_nb+no",
161
+ }
162
+ OPUS_GITHUB_URL = "https://github.com/Helsinki-NLP/OPUS-MT-train/blob/master/models/"
163
+ ORG_NAME = "Helsinki-NLP/"
164
+
165
+
166
+ def convert_opus_name_to_hf_name(x):
167
+ """For OPUS-MT-Train/ DEPRECATED"""
168
+ for substr, grp_name in GROUPS:
169
+ x = x.replace(substr, grp_name)
170
+ return x.replace("+", "_")
171
+
172
+
173
+ def convert_hf_name_to_opus_name(hf_model_name):
174
+ """
175
+ Relies on the assumption that there are no language codes like pt_br in models that are not in GROUP_TO_OPUS_NAME.
176
+ """
177
+ hf_model_name = remove_prefix(hf_model_name, ORG_NAME)
178
+ if hf_model_name in GROUP_TO_OPUS_NAME:
179
+ opus_w_prefix = GROUP_TO_OPUS_NAME[hf_model_name]
180
+ else:
181
+ opus_w_prefix = hf_model_name.replace("_", "+")
182
+ return remove_prefix(opus_w_prefix, "opus-mt-")
183
+
184
+
185
+ def get_system_metadata(repo_root):
186
+ import git
187
+
188
+ return {
189
+ "helsinki_git_sha": git.Repo(path=repo_root, search_parent_directories=True).head.object.hexsha,
190
+ "transformers_git_sha": git.Repo(path=".", search_parent_directories=True).head.object.hexsha,
191
+ "port_machine": socket.gethostname(),
192
+ "port_time": time.strftime("%Y-%m-%d-%H:%M"),
193
+ }
194
+
195
+
196
+ # docstyle-ignore
197
+ FRONT_MATTER_TEMPLATE = """---
198
+ language:
199
+ {}
200
+ tags:
201
+ - translation
202
+
203
+ license: apache-2.0
204
+ ---
205
+ """
206
+ DEFAULT_REPO = "Tatoeba-Challenge"
207
+ DEFAULT_MODEL_DIR = os.path.join(DEFAULT_REPO, "models")
208
+
209
+
210
+ def write_model_card(
211
+ hf_model_name: str,
212
+ repo_root=DEFAULT_REPO,
213
+ save_dir=Path("marian_converted"),
214
+ dry_run=False,
215
+ extra_metadata={},
216
+ ) -> str:
217
+ """
218
+ Copy the most recent model's readme section from opus, and add metadata. upload command: aws s3 sync model_card_dir
219
+ s3://models.huggingface.co/bert/Helsinki-NLP/ --dryrun
220
+ """
221
+ import pandas as pd
222
+
223
+ hf_model_name = remove_prefix(hf_model_name, ORG_NAME)
224
+ opus_name: str = convert_hf_name_to_opus_name(hf_model_name)
225
+ if repo_root not in ("OPUS-MT-train", "Tatoeba-Challenge"):
226
+ raise ValueError(f"Repos root is {repo_root}. Expected either OPUS-MT-train or Tatoeba-Challenge")
227
+ opus_readme_path = Path(repo_root).joinpath("models", opus_name, "README.md")
228
+ if not (opus_readme_path.exists()):
229
+ raise ValueError(f"Readme file {opus_readme_path} not found")
230
+
231
+ opus_src, opus_tgt = [x.split("+") for x in opus_name.split("-")]
232
+
233
+ readme_url = f"https://github.com/Helsinki-NLP/{repo_root}/tree/master/models/{opus_name}/README.md"
234
+
235
+ s, t = ",".join(opus_src), ",".join(opus_tgt)
236
+ metadata = {
237
+ "hf_name": hf_model_name,
238
+ "source_languages": s,
239
+ "target_languages": t,
240
+ "opus_readme_url": readme_url,
241
+ "original_repo": repo_root,
242
+ "tags": ["translation"],
243
+ }
244
+ metadata.update(extra_metadata)
245
+ metadata.update(get_system_metadata(repo_root))
246
+
247
+ # combine with opus markdown
248
+
249
+ extra_markdown = (
250
+ f"### {hf_model_name}\n\n* source group: {metadata['src_name']} \n* target group: "
251
+ f"{metadata['tgt_name']} \n* OPUS readme: [{opus_name}]({readme_url})\n"
252
+ )
253
+
254
+ content = opus_readme_path.open().read()
255
+ content = content.split("\n# ")[-1] # Get the lowest level 1 header in the README -- the most recent model.
256
+ splat = content.split("*")[2:]
257
+ print(splat[3])
258
+ content = "*".join(splat)
259
+ content = (
260
+ FRONT_MATTER_TEMPLATE.format(metadata["src_alpha2"])
261
+ + extra_markdown
262
+ + "\n* "
263
+ + content.replace("download", "download original weights")
264
+ )
265
+
266
+ items = "\n\n".join([f"- {k}: {v}" for k, v in metadata.items()])
267
+ sec3 = "\n### System Info: \n" + items
268
+ content += sec3
269
+ if dry_run:
270
+ return content, metadata
271
+ sub_dir = save_dir / f"opus-mt-{hf_model_name}"
272
+ sub_dir.mkdir(exist_ok=True)
273
+ dest = sub_dir / "README.md"
274
+ dest.open("w").write(content)
275
+ pd.Series(metadata).to_json(sub_dir / "metadata.json")
276
+
277
+ # if dry_run:
278
+ return content, metadata
279
+
280
+
281
+ def make_registry(repo_path="Opus-MT-train/models"):
282
+ if not (Path(repo_path) / "fr-en" / "README.md").exists():
283
+ raise ValueError(
284
+ f"repo_path:{repo_path} does not exist: "
285
+ "You must run: git clone git@github.com:Helsinki-NLP/Opus-MT-train.git before calling."
286
+ )
287
+ results = {}
288
+ for p in Path(repo_path).iterdir():
289
+ n_dash = p.name.count("-")
290
+ if n_dash == 0:
291
+ continue
292
+ else:
293
+ lns = list(open(p / "README.md").readlines())
294
+ results[p.name] = _parse_readme(lns)
295
+ return [(k, v["pre-processing"], v["download"], v["download"][:-4] + ".test.txt") for k, v in results.items()]
296
+
297
+
298
+ def convert_all_sentencepiece_models(model_list=None, repo_path=None, dest_dir=Path("marian_converted")):
299
+ """Requires 300GB"""
300
+ save_dir = Path("marian_ckpt")
301
+ dest_dir = Path(dest_dir)
302
+ dest_dir.mkdir(exist_ok=True)
303
+ save_paths = []
304
+ if model_list is None:
305
+ model_list: list = make_registry(repo_path=repo_path)
306
+ for k, prepro, download, test_set_url in tqdm(model_list):
307
+ if "SentencePiece" not in prepro: # dont convert BPE models.
308
+ continue
309
+ if not os.path.exists(save_dir / k):
310
+ download_and_unzip(download, save_dir / k)
311
+ pair_name = convert_opus_name_to_hf_name(k)
312
+ convert(save_dir / k, dest_dir / f"opus-mt-{pair_name}")
313
+
314
+ save_paths.append(dest_dir / f"opus-mt-{pair_name}")
315
+ return save_paths
316
+
317
+
318
+ def lmap(f, x) -> List:
319
+ return list(map(f, x))
320
+
321
+
322
+ def fetch_test_set(test_set_url):
323
+ import wget
324
+
325
+ fname = wget.download(test_set_url, "opus_test.txt")
326
+ lns = Path(fname).open().readlines()
327
+ src = lmap(str.strip, lns[::4])
328
+ gold = lmap(str.strip, lns[1::4])
329
+ mar_model = lmap(str.strip, lns[2::4])
330
+ if not (len(gold) == len(mar_model) == len(src)):
331
+ raise ValueError(f"Gold, marian and source lengths {len(gold)}, {len(mar_model)}, {len(src)} mismatched")
332
+ os.remove(fname)
333
+ return src, mar_model, gold
334
+
335
+
336
+ def convert_whole_dir(path=Path("marian_ckpt/")):
337
+ for subdir in tqdm(list(path.ls())):
338
+ dest_dir = f"marian_converted/{subdir.name}"
339
+ if (dest_dir / "pytorch_model.bin").exists():
340
+ continue
341
+ convert(source_dir, dest_dir)
342
+
343
+
344
+ def _parse_readme(lns):
345
+ """Get link and metadata from opus model card equivalent."""
346
+ subres = {}
347
+ for ln in [x.strip() for x in lns]:
348
+ if not ln.startswith("*"):
349
+ continue
350
+ ln = ln[1:].strip()
351
+
352
+ for k in ["download", "dataset", "models", "model", "pre-processing"]:
353
+ if ln.startswith(k):
354
+ break
355
+ else:
356
+ continue
357
+ if k in ["dataset", "model", "pre-processing"]:
358
+ splat = ln.split(":")
359
+ _, v = splat
360
+ subres[k] = v
361
+ elif k == "download":
362
+ v = ln.split("(")[-1][:-1]
363
+ subres[k] = v
364
+ return subres
365
+
366
+
367
+ def save_tokenizer_config(dest_dir: Path, separate_vocabs=False):
368
+ dname = dest_dir.name.split("-")
369
+ dct = {"target_lang": dname[-1], "source_lang": "-".join(dname[:-1]), "separate_vocabs": separate_vocabs}
370
+ save_json(dct, dest_dir / "tokenizer_config.json")
371
+
372
+
373
+ def add_to_vocab_(vocab: Dict[str, int], special_tokens: List[str]):
374
+ start = max(vocab.values()) + 1
375
+ added = 0
376
+ for tok in special_tokens:
377
+ if tok in vocab:
378
+ continue
379
+ vocab[tok] = start + added
380
+ added += 1
381
+ return added
382
+
383
+
384
+ def find_vocab_file(model_dir):
385
+ return list(model_dir.glob("*vocab.yml"))[0]
386
+
387
+
388
+ def find_src_vocab_file(model_dir):
389
+ return list(model_dir.glob("*src.vocab.yml"))[0]
390
+
391
+
392
+ def find_tgt_vocab_file(model_dir):
393
+ return list(model_dir.glob("*trg.vocab.yml"))[0]
394
+
395
+
396
+ def add_special_tokens_to_vocab(model_dir: Path, separate_vocab=False) -> None:
397
+ if separate_vocab:
398
+ vocab = load_yaml(find_src_vocab_file(model_dir))
399
+ vocab = {k: int(v) for k, v in vocab.items()}
400
+ num_added = add_to_vocab_(vocab, ["<pad>"])
401
+ save_json(vocab, model_dir / "vocab.json")
402
+
403
+ vocab = load_yaml(find_tgt_vocab_file(model_dir))
404
+ vocab = {k: int(v) for k, v in vocab.items()}
405
+ num_added = add_to_vocab_(vocab, ["<pad>"])
406
+ save_json(vocab, model_dir / "target_vocab.json")
407
+ save_tokenizer_config(model_dir, separate_vocabs=separate_vocab)
408
+ else:
409
+ vocab = load_yaml(find_vocab_file(model_dir))
410
+ vocab = {k: int(v) for k, v in vocab.items()}
411
+ num_added = add_to_vocab_(vocab, ["<pad>"])
412
+ print(f"added {num_added} tokens to vocab")
413
+ save_json(vocab, model_dir / "vocab.json")
414
+ save_tokenizer_config(model_dir)
415
+
416
+
417
+ def check_equal(marian_cfg, k1, k2):
418
+ v1, v2 = marian_cfg[k1], marian_cfg[k2]
419
+ if v1 != v2:
420
+ raise ValueError(f"hparams {k1},{k2} differ: {v1} != {v2}")
421
+
422
+
423
+ def check_marian_cfg_assumptions(marian_cfg):
424
+ assumed_settings = {
425
+ "layer-normalization": False,
426
+ "right-left": False,
427
+ "transformer-ffn-depth": 2,
428
+ "transformer-aan-depth": 2,
429
+ "transformer-no-projection": False,
430
+ "transformer-postprocess-emb": "d",
431
+ "transformer-postprocess": "dan", # Dropout, add, normalize
432
+ "transformer-preprocess": "",
433
+ "type": "transformer",
434
+ "ulr-dim-emb": 0,
435
+ "dec-cell-base-depth": 2,
436
+ "dec-cell-high-depth": 1,
437
+ "transformer-aan-nogate": False,
438
+ }
439
+ for k, v in assumed_settings.items():
440
+ actual = marian_cfg[k]
441
+ if actual != v:
442
+ raise ValueError(f"Unexpected config value for {k} expected {v} got {actual}")
443
+
444
+
445
+ BIAS_KEY = "decoder_ff_logit_out_b"
446
+ BART_CONVERTER = { # for each encoder and decoder layer
447
+ "self_Wq": "self_attn.q_proj.weight",
448
+ "self_Wk": "self_attn.k_proj.weight",
449
+ "self_Wv": "self_attn.v_proj.weight",
450
+ "self_Wo": "self_attn.out_proj.weight",
451
+ "self_bq": "self_attn.q_proj.bias",
452
+ "self_bk": "self_attn.k_proj.bias",
453
+ "self_bv": "self_attn.v_proj.bias",
454
+ "self_bo": "self_attn.out_proj.bias",
455
+ "self_Wo_ln_scale": "self_attn_layer_norm.weight",
456
+ "self_Wo_ln_bias": "self_attn_layer_norm.bias",
457
+ "ffn_W1": "fc1.weight",
458
+ "ffn_b1": "fc1.bias",
459
+ "ffn_W2": "fc2.weight",
460
+ "ffn_b2": "fc2.bias",
461
+ "ffn_ffn_ln_scale": "final_layer_norm.weight",
462
+ "ffn_ffn_ln_bias": "final_layer_norm.bias",
463
+ # Decoder Cross Attention
464
+ "context_Wk": "encoder_attn.k_proj.weight",
465
+ "context_Wo": "encoder_attn.out_proj.weight",
466
+ "context_Wq": "encoder_attn.q_proj.weight",
467
+ "context_Wv": "encoder_attn.v_proj.weight",
468
+ "context_bk": "encoder_attn.k_proj.bias",
469
+ "context_bo": "encoder_attn.out_proj.bias",
470
+ "context_bq": "encoder_attn.q_proj.bias",
471
+ "context_bv": "encoder_attn.v_proj.bias",
472
+ "context_Wo_ln_scale": "encoder_attn_layer_norm.weight",
473
+ "context_Wo_ln_bias": "encoder_attn_layer_norm.bias",
474
+ }
475
+
476
+
477
+ class OpusState:
478
+ def __init__(self, source_dir, eos_token_id=0):
479
+ npz_path = find_model_file(source_dir)
480
+ self.state_dict = np.load(npz_path)
481
+ cfg = load_config_from_state_dict(self.state_dict)
482
+ if cfg["dim-vocabs"][0] != cfg["dim-vocabs"][1]:
483
+ raise ValueError
484
+ if "Wpos" in self.state_dict:
485
+ raise ValueError("Wpos key in state dictionary")
486
+ self.state_dict = dict(self.state_dict)
487
+ if cfg["tied-embeddings-all"]:
488
+ cfg["tied-embeddings-src"] = True
489
+ cfg["tied-embeddings"] = True
490
+ self.share_encoder_decoder_embeddings = cfg["tied-embeddings-src"]
491
+
492
+ # create the tokenizer here because we need to know the eos_token_id
493
+ self.source_dir = source_dir
494
+ self.tokenizer = self.load_tokenizer()
495
+ # retrieve EOS token and set correctly
496
+ tokenizer_has_eos_token_id = (
497
+ hasattr(self.tokenizer, "eos_token_id") and self.tokenizer.eos_token_id is not None
498
+ )
499
+ eos_token_id = self.tokenizer.eos_token_id if tokenizer_has_eos_token_id else 0
500
+
501
+ if cfg["tied-embeddings-src"]:
502
+ self.wemb, self.final_bias = add_emb_entries(self.state_dict["Wemb"], self.state_dict[BIAS_KEY], 1)
503
+ self.pad_token_id = self.wemb.shape[0] - 1
504
+ cfg["vocab_size"] = self.pad_token_id + 1
505
+ else:
506
+ self.wemb, _ = add_emb_entries(self.state_dict["encoder_Wemb"], self.state_dict[BIAS_KEY], 1)
507
+ self.dec_wemb, self.final_bias = add_emb_entries(
508
+ self.state_dict["decoder_Wemb"], self.state_dict[BIAS_KEY], 1
509
+ )
510
+ # still assuming that vocab size is same for encoder and decoder
511
+ self.pad_token_id = self.wemb.shape[0] - 1
512
+ cfg["vocab_size"] = self.pad_token_id + 1
513
+ cfg["decoder_vocab_size"] = self.pad_token_id + 1
514
+
515
+ if cfg["vocab_size"] != self.tokenizer.vocab_size:
516
+ raise ValueError(
517
+ f"Original vocab size {cfg['vocab_size']} and new vocab size {len(self.tokenizer.encoder)} mismatched."
518
+ )
519
+
520
+ # self.state_dict['Wemb'].sha
521
+ self.state_keys = list(self.state_dict.keys())
522
+ if "Wtype" in self.state_dict:
523
+ raise ValueError("Wtype key in state dictionary")
524
+ self._check_layer_entries()
525
+ self.cfg = cfg
526
+ hidden_size, intermediate_shape = self.state_dict["encoder_l1_ffn_W1"].shape
527
+ if hidden_size != cfg["dim-emb"]:
528
+ raise ValueError(f"Hidden size {hidden_size} and configured size {cfg['dim_emb']} mismatched")
529
+
530
+ # Process decoder.yml
531
+ decoder_yml = cast_marian_config(load_yaml(source_dir / "decoder.yml"))
532
+ check_marian_cfg_assumptions(cfg)
533
+ self.hf_config = MarianConfig(
534
+ vocab_size=cfg["vocab_size"],
535
+ decoder_vocab_size=cfg.get("decoder_vocab_size", cfg["vocab_size"]),
536
+ share_encoder_decoder_embeddings=cfg["tied-embeddings-src"],
537
+ decoder_layers=cfg["dec-depth"],
538
+ encoder_layers=cfg["enc-depth"],
539
+ decoder_attention_heads=cfg["transformer-heads"],
540
+ encoder_attention_heads=cfg["transformer-heads"],
541
+ decoder_ffn_dim=cfg["transformer-dim-ffn"],
542
+ encoder_ffn_dim=cfg["transformer-dim-ffn"],
543
+ d_model=cfg["dim-emb"],
544
+ activation_function=cfg["transformer-ffn-activation"],
545
+ pad_token_id=self.pad_token_id,
546
+ eos_token_id=eos_token_id,
547
+ forced_eos_token_id=eos_token_id,
548
+ bos_token_id=0,
549
+ max_position_embeddings=cfg["dim-emb"],
550
+ scale_embedding=True,
551
+ normalize_embedding="n" in cfg["transformer-preprocess"],
552
+ static_position_embeddings=not cfg["transformer-train-position-embeddings"],
553
+ tie_word_embeddings=cfg["tied-embeddings"],
554
+ dropout=0.1, # see opus-mt-train repo/transformer-dropout param.
555
+ # default: add_final_layer_norm=False,
556
+ num_beams=decoder_yml["beam-size"],
557
+ decoder_start_token_id=self.pad_token_id,
558
+ bad_words_ids=[[self.pad_token_id]],
559
+ max_length=512,
560
+ )
561
+
562
+ def _check_layer_entries(self):
563
+ self.encoder_l1 = self.sub_keys("encoder_l1")
564
+ self.decoder_l1 = self.sub_keys("decoder_l1")
565
+ self.decoder_l2 = self.sub_keys("decoder_l2")
566
+ if len(self.encoder_l1) != 16:
567
+ warnings.warn(f"Expected 16 keys for each encoder layer, got {len(self.encoder_l1)}")
568
+ if len(self.decoder_l1) != 26:
569
+ warnings.warn(f"Expected 26 keys for each decoder layer, got {len(self.decoder_l1)}")
570
+ if len(self.decoder_l2) != 26:
571
+ warnings.warn(f"Expected 26 keys for each decoder layer, got {len(self.decoder_l1)}")
572
+
573
+ @property
574
+ def extra_keys(self):
575
+ extra = []
576
+ for k in self.state_keys:
577
+ if (
578
+ k.startswith("encoder_l")
579
+ or k.startswith("decoder_l")
580
+ or k in [CONFIG_KEY, "Wemb", "encoder_Wemb", "decoder_Wemb", "Wpos", "decoder_ff_logit_out_b"]
581
+ ):
582
+ continue
583
+ else:
584
+ extra.append(k)
585
+ return extra
586
+
587
+ def sub_keys(self, layer_prefix):
588
+ return [remove_prefix(k, layer_prefix) for k in self.state_dict if k.startswith(layer_prefix)]
589
+
590
+ def load_tokenizer(self):
591
+ # save tokenizer
592
+ add_special_tokens_to_vocab(self.source_dir, not self.share_encoder_decoder_embeddings)
593
+ return MarianTokenizer.from_pretrained(str(self.source_dir))
594
+
595
+ def load_marian_model(self) -> MarianMTModel:
596
+ state_dict, cfg = self.state_dict, self.hf_config
597
+
598
+ if not cfg.static_position_embeddings:
599
+ raise ValueError("config.static_position_embeddings should be True")
600
+ model = MarianMTModel(cfg)
601
+
602
+ if "hidden_size" in cfg.to_dict():
603
+ raise ValueError("hidden_size is in config")
604
+ load_layers_(
605
+ model.model.encoder.layers,
606
+ state_dict,
607
+ BART_CONVERTER,
608
+ )
609
+ load_layers_(model.model.decoder.layers, state_dict, BART_CONVERTER, is_decoder=True)
610
+
611
+ # handle tensors not associated with layers
612
+ if self.cfg["tied-embeddings-src"]:
613
+ wemb_tensor = nn.Parameter(torch.FloatTensor(self.wemb))
614
+ bias_tensor = nn.Parameter(torch.FloatTensor(self.final_bias))
615
+ model.model.shared.weight = wemb_tensor
616
+ model.model.encoder.embed_tokens = model.model.decoder.embed_tokens = model.model.shared
617
+ else:
618
+ wemb_tensor = nn.Parameter(torch.FloatTensor(self.wemb))
619
+ model.model.encoder.embed_tokens.weight = wemb_tensor
620
+
621
+ decoder_wemb_tensor = nn.Parameter(torch.FloatTensor(self.dec_wemb))
622
+ bias_tensor = nn.Parameter(torch.FloatTensor(self.final_bias))
623
+ model.model.decoder.embed_tokens.weight = decoder_wemb_tensor
624
+
625
+ # handle tied embeddings, otherwise "from_pretrained" loads them incorrectly
626
+ if self.cfg["tied-embeddings"]:
627
+ model.lm_head.weight.data = model.model.decoder.embed_tokens.weight.data.clone()
628
+
629
+ model.final_logits_bias = bias_tensor
630
+
631
+ if "Wpos" in state_dict:
632
+ print("Unexpected: got Wpos")
633
+ wpos_tensor = torch.tensor(state_dict["Wpos"])
634
+ model.model.encoder.embed_positions.weight = wpos_tensor
635
+ model.model.decoder.embed_positions.weight = wpos_tensor
636
+
637
+ if cfg.normalize_embedding:
638
+ if "encoder_emb_ln_scale_pre" not in state_dict:
639
+ raise ValueError("encoder_emb_ln_scale_pre is not in state dictionary")
640
+ raise NotImplementedError("Need to convert layernorm_embedding")
641
+
642
+ if self.extra_keys:
643
+ raise ValueError(f"Failed to convert {self.extra_keys}")
644
+
645
+ if model.get_input_embeddings().padding_idx != self.pad_token_id:
646
+ raise ValueError(
647
+ f"Padding tokens {model.get_input_embeddings().padding_idx} and {self.pad_token_id} mismatched"
648
+ )
649
+ return model
650
+
651
+
652
+ def download_and_unzip(url, dest_dir):
653
+ try:
654
+ import wget
655
+ except ImportError:
656
+ raise ImportError("you must pip install wget")
657
+
658
+ filename = wget.download(url)
659
+ unzip(filename, dest_dir)
660
+ os.remove(filename)
661
+
662
+
663
+ def convert(source_dir: Path, dest_dir):
664
+ dest_dir = Path(dest_dir)
665
+ dest_dir.mkdir(exist_ok=True)
666
+
667
+ opus_state = OpusState(source_dir)
668
+
669
+ # save tokenizer
670
+ opus_state.tokenizer.save_pretrained(dest_dir)
671
+
672
+ # save_json(opus_state.cfg, dest_dir / "marian_original_config.json")
673
+ # ^^ Uncomment to save human readable marian config for debugging
674
+
675
+ model = opus_state.load_marian_model()
676
+ model = model.half()
677
+ model.save_pretrained(dest_dir)
678
+ model.from_pretrained(dest_dir) # sanity check
679
+
680
+
681
+ def load_yaml(path):
682
+ import yaml
683
+
684
+ with open(path, encoding="utf-8") as f:
685
+ return yaml.load(f, Loader=yaml.BaseLoader)
686
+
687
+
688
+ def save_json(content: Union[Dict, List], path: str) -> None:
689
+ with open(path, "w") as f:
690
+ json.dump(content, f)
691
+
692
+
693
+ def unzip(zip_path: str, dest_dir: str) -> None:
694
+ with ZipFile(zip_path, "r") as zipObj:
695
+ zipObj.extractall(dest_dir)
696
+
697
+
698
+ if __name__ == "__main__":
699
+ """
700
+ Tatoeba conversion instructions in scripts/tatoeba/README.md
701
+ """
702
+ parser = argparse.ArgumentParser()
703
+ # Required parameters
704
+ parser.add_argument(
705
+ "--src",
706
+ type=str,
707
+ help="path to marian model sub dir. yaml.load will be used to load the configuration file, please be wary of which file you're loading.",
708
+ default="en-de",
709
+ )
710
+ parser.add_argument("--dest", type=str, default=None, help="Path to the output PyTorch model.")
711
+ args = parser.parse_args()
712
+
713
+ source_dir = Path(args.src)
714
+ if not source_dir.exists():
715
+ raise ValueError(f"Source directory {source_dir} not found")
716
+ dest_dir = f"converted-{source_dir.name}" if args.dest is None else args.dest
717
+ convert(source_dir, dest_dir)
tasks/tasksmith-441eeab80047/environment/source/src/transformers/models/marian/modeling_flax_marian.py ADDED
@@ -0,0 +1,1500 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2021 The Marian Team Authors and The Google Flax Team Authors And The HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """Flax Marian model."""
16
+
17
+ import math
18
+ import random
19
+ from functools import partial
20
+ from typing import Callable, Optional, Tuple
21
+
22
+ import flax.linen as nn
23
+ import jax
24
+ import jax.numpy as jnp
25
+ import numpy as np
26
+ from flax.core.frozen_dict import FrozenDict, freeze, unfreeze
27
+ from flax.linen import combine_masks, make_causal_mask
28
+ from flax.linen.attention import dot_product_attention_weights
29
+ from flax.traverse_util import flatten_dict, unflatten_dict
30
+ from jax import lax
31
+ from jax.random import PRNGKey
32
+
33
+ from ...modeling_flax_outputs import (
34
+ FlaxBaseModelOutput,
35
+ FlaxBaseModelOutputWithPastAndCrossAttentions,
36
+ FlaxCausalLMOutputWithCrossAttentions,
37
+ FlaxSeq2SeqLMOutput,
38
+ FlaxSeq2SeqModelOutput,
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 add_start_docstrings, add_start_docstrings_to_model_forward, logging, replace_return_docstrings
48
+ from .configuration_marian import MarianConfig
49
+
50
+
51
+ logger = logging.get_logger(__name__)
52
+
53
+ _CHECKPOINT_FOR_DOC = "Helsinki-NLP/opus-mt-en-de"
54
+ _CONFIG_FOR_DOC = "MarianConfig"
55
+
56
+
57
+ MARIAN_START_DOCSTRING = r"""
58
+ This model inherits from [`FlaxPreTrainedModel`]. Check the superclass documentation for the generic methods the
59
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
60
+ etc.)
61
+
62
+ This model is also a Flax Linen
63
+ [flax.nn.Module](https://flax.readthedocs.io/en/latest/_autosummary/flax.nn.module.html) subclass. Use it as a
64
+ regular Flax Module and refer to the Flax documentation for all matter related to general usage and behavior.
65
+
66
+ Finally, this model supports inherent JAX features such as:
67
+
68
+ - [Just-In-Time (JIT) compilation](https://jax.readthedocs.io/en/latest/jax.html#just-in-time-compilation-jit)
69
+ - [Automatic Differentiation](https://jax.readthedocs.io/en/latest/jax.html#automatic-differentiation)
70
+ - [Vectorization](https://jax.readthedocs.io/en/latest/jax.html#vectorization-vmap)
71
+ - [Parallelization](https://jax.readthedocs.io/en/latest/jax.html#parallelization-pmap)
72
+
73
+ Parameters:
74
+ config ([`MarianConfig`]): Model configuration class with all the parameters of the model.
75
+ Initializing with a config file does not load the weights associated with the model, only the
76
+ configuration. Check out the [`~FlaxPreTrainedModel.from_pretrained`] method to load the model weights.
77
+ dtype (`jax.numpy.dtype`, *optional*, defaults to `jax.numpy.float32`):
78
+ The data type of the computation. Can be one of `jax.numpy.float32`, `jax.numpy.float16` (on GPUs) and
79
+ `jax.numpy.bfloat16` (on TPUs).
80
+
81
+ This can be used to enable mixed-precision training or half-precision inference on GPUs or TPUs. If
82
+ specified all the computation will be performed with the given `dtype`.
83
+
84
+ **Note that this only specifies the dtype of the computation and does not influence the dtype of model
85
+ parameters.**
86
+
87
+ If you wish to change the dtype of the model parameters, see [`~FlaxPreTrainedModel.to_fp16`] and
88
+ [`~FlaxPreTrainedModel.to_bf16`].
89
+ """
90
+
91
+ MARIAN_INPUTS_DOCSTRING = r"""
92
+ Args:
93
+ input_ids (`jnp.ndarray` of shape `(batch_size, sequence_length)`):
94
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
95
+ it.
96
+
97
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
98
+ [`PreTrainedTokenizer.__call__`] for details.
99
+
100
+ [What are input IDs?](../glossary#input-ids)
101
+ attention_mask (`jnp.ndarray` of shape `(batch_size, sequence_length)`, *optional*):
102
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
103
+
104
+ - 1 for tokens that are **not masked**,
105
+ - 0 for tokens that are **masked**.
106
+
107
+ [What are attention masks?](../glossary#attention-mask)
108
+ decoder_input_ids (`jnp.ndarray` of shape `(batch_size, target_sequence_length)`, *optional*):
109
+ Indices of decoder input sequence tokens in the vocabulary.
110
+
111
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
112
+ [`PreTrainedTokenizer.__call__`] for details.
113
+
114
+ [What are decoder input IDs?](../glossary#decoder-input-ids)
115
+
116
+ For translation and summarization training, `decoder_input_ids` should be provided. If no
117
+ `decoder_input_ids` is provided, the model will create this tensor by shifting the `input_ids` to the right
118
+ for denoising pre-training following the paper.
119
+ decoder_attention_mask (`jnp.ndarray` of shape `(batch_size, target_sequence_length)`, *optional*):
120
+ Default behavior: generate a tensor that ignores pad tokens in `decoder_input_ids`. Causal mask will also
121
+ be used by default.
122
+
123
+ If you want to change padding behavior, you should modify to your needs. See diagram 1 in [the
124
+ paper](https://arxiv.org/abs/1910.13461) for more information on the default strategy.
125
+ position_ids (`numpy.ndarray` of shape `(batch_size, sequence_length)`, *optional*):
126
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
127
+ config.max_position_embeddings - 1]`.
128
+ decoder_position_ids (`numpy.ndarray` of shape `(batch_size, sequence_length)`, *optional*):
129
+ Indices of positions of each decoder input sequence tokens in the position embeddings. Selected in the
130
+ range `[0, config.max_position_embeddings - 1]`.
131
+ output_attentions (`bool`, *optional*):
132
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
133
+ tensors for more detail.
134
+ output_hidden_states (`bool`, *optional*):
135
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
136
+ more detail.
137
+ return_dict (`bool`, *optional*):
138
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
139
+ """
140
+
141
+
142
+ MARIAN_ENCODE_INPUTS_DOCSTRING = r"""
143
+ Args:
144
+ input_ids (`jnp.ndarray` of shape `(batch_size, sequence_length)`):
145
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
146
+ it.
147
+
148
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
149
+ [`PreTrainedTokenizer.__call__`] for details.
150
+
151
+ [What are input IDs?](../glossary#input-ids)
152
+ attention_mask (`jnp.ndarray` of shape `(batch_size, sequence_length)`, *optional*):
153
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
154
+
155
+ - 1 for tokens that are **not masked**,
156
+ - 0 for tokens that are **masked**.
157
+
158
+ [What are attention masks?](../glossary#attention-mask)
159
+ position_ids (`numpy.ndarray` of shape `(batch_size, sequence_length)`, *optional*):
160
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
161
+ config.max_position_embeddings - 1]`.
162
+ output_attentions (`bool`, *optional*):
163
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
164
+ tensors for more detail.
165
+ output_hidden_states (`bool`, *optional*):
166
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
167
+ more detail.
168
+ return_dict (`bool`, *optional*):
169
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
170
+ """
171
+
172
+ MARIAN_DECODE_INPUTS_DOCSTRING = r"""
173
+ Args:
174
+ decoder_input_ids (`jnp.ndarray` of shape `(batch_size, target_sequence_length)`):
175
+ Indices of decoder input sequence tokens in the vocabulary.
176
+
177
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
178
+ [`PreTrainedTokenizer.__call__`] for details.
179
+
180
+ [What are decoder input IDs?](../glossary#decoder-input-ids)
181
+
182
+ For translation and summarization training, `decoder_input_ids` should be provided. If no
183
+ `decoder_input_ids` is provided, the model will create this tensor by shifting the `input_ids` to the right
184
+ for denoising pre-training following the paper.
185
+ encoder_outputs (`tuple(tuple(jnp.ndarray)`):
186
+ Tuple consists of (`last_hidden_state`, *optional*: `hidden_states`, *optional*: `attentions`)
187
+ `last_hidden_state` of shape `(batch_size, sequence_length, hidden_size)`, *optional*) is a sequence of
188
+ hidden-states at the output of the last layer of the encoder. Used in the cross-attention of the decoder.
189
+ encoder_attention_mask (`jnp.ndarray` of shape `(batch_size, sequence_length)`, *optional*):
190
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
191
+
192
+ - 1 for tokens that are **not masked**,
193
+ - 0 for tokens that are **masked**.
194
+
195
+ [What are attention masks?](../glossary#attention-mask)
196
+ decoder_attention_mask (`jnp.ndarray` of shape `(batch_size, target_sequence_length)`, *optional*):
197
+ Default behavior: generate a tensor that ignores pad tokens in `decoder_input_ids`. Causal mask will also
198
+ be used by default.
199
+
200
+ If you want to change padding behavior, you should modify to your needs. See diagram 1 in [the
201
+ paper](https://arxiv.org/abs/1910.13461) for more information on the default strategy.
202
+ decoder_position_ids (`numpy.ndarray` of shape `(batch_size, sequence_length)`, *optional*):
203
+ Indices of positions of each decoder input sequence tokens in the position embeddings. Selected in the
204
+ range `[0, config.max_position_embeddings - 1]`.
205
+ past_key_values (`Dict[str, np.ndarray]`, *optional*, returned by `init_cache` or when passing previous `past_key_values`):
206
+ Dictionary of pre-computed hidden-states (key and values in the attention blocks) that can be used for fast
207
+ auto-regressive decoding. Pre-computed key and value hidden-states are of shape *[batch_size, max_length]*.
208
+ output_attentions (`bool`, *optional*):
209
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
210
+ tensors for more detail.
211
+ output_hidden_states (`bool`, *optional*):
212
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
213
+ more detail.
214
+ return_dict (`bool`, *optional*):
215
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
216
+ """
217
+
218
+
219
+ def create_sinusoidal_positions(n_pos, dim):
220
+ position_enc = np.array([[pos / np.power(10000, 2 * (j // 2) / dim) for j in range(dim)] for pos in range(n_pos)])
221
+ sentinel = dim // 2 + dim % 2
222
+ out = np.zeros_like(position_enc)
223
+ out[:, 0:sentinel] = np.sin(position_enc[:, 0::2])
224
+ out[:, sentinel:] = np.cos(position_enc[:, 1::2])
225
+
226
+ return jnp.array(out)
227
+
228
+
229
+ # Copied from transformers.models.bart.modeling_flax_bart.shift_tokens_right
230
+ def shift_tokens_right(input_ids: jnp.ndarray, pad_token_id: int, decoder_start_token_id: int) -> jnp.ndarray:
231
+ """
232
+ Shift input ids one token to the right.
233
+ """
234
+ shifted_input_ids = jnp.zeros_like(input_ids)
235
+ shifted_input_ids = shifted_input_ids.at[:, 1:].set(input_ids[:, :-1])
236
+ shifted_input_ids = shifted_input_ids.at[:, 0].set(decoder_start_token_id)
237
+
238
+ shifted_input_ids = jnp.where(shifted_input_ids == -100, pad_token_id, shifted_input_ids)
239
+ return shifted_input_ids
240
+
241
+
242
+ # Copied from transformers.models.bart.modeling_flax_bart.FlaxBartAttention with Bart->Marian
243
+ class FlaxMarianAttention(nn.Module):
244
+ config: MarianConfig
245
+ embed_dim: int
246
+ num_heads: int
247
+ dropout: float = 0.0
248
+ causal: bool = False
249
+ bias: bool = True
250
+ dtype: jnp.dtype = jnp.float32 # the dtype of the computation
251
+
252
+ def setup(self) -> None:
253
+ self.head_dim = self.embed_dim // self.num_heads
254
+ if self.head_dim * self.num_heads != self.embed_dim:
255
+ raise ValueError(
256
+ f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim}"
257
+ f" and `num_heads`: {self.num_heads})."
258
+ )
259
+
260
+ dense = partial(
261
+ nn.Dense,
262
+ self.embed_dim,
263
+ use_bias=self.bias,
264
+ dtype=self.dtype,
265
+ kernel_init=jax.nn.initializers.normal(self.config.init_std),
266
+ )
267
+
268
+ self.q_proj, self.k_proj, self.v_proj = dense(), dense(), dense()
269
+ self.out_proj = dense()
270
+
271
+ self.dropout_layer = nn.Dropout(rate=self.dropout)
272
+
273
+ if self.causal:
274
+ self.causal_mask = make_causal_mask(
275
+ jnp.ones((1, self.config.max_position_embeddings), dtype="bool"), dtype="bool"
276
+ )
277
+
278
+ def _split_heads(self, hidden_states):
279
+ return hidden_states.reshape(hidden_states.shape[:2] + (self.num_heads, self.head_dim))
280
+
281
+ def _merge_heads(self, hidden_states):
282
+ return hidden_states.reshape(hidden_states.shape[:2] + (self.embed_dim,))
283
+
284
+ @nn.compact
285
+ def _concatenate_to_cache(self, key, value, query, attention_mask):
286
+ """
287
+ This function takes projected key, value states from a single input token and concatenates the states to cached
288
+ states from previous steps. This function is slightly adapted from the official Flax repository:
289
+ https://github.com/google/flax/blob/491ce18759622506588784b4fca0e4bf05f8c8cd/flax/linen/attention.py#L252
290
+ """
291
+ # detect if we're initializing by absence of existing cache data.
292
+ is_initialized = self.has_variable("cache", "cached_key")
293
+ cached_key = self.variable("cache", "cached_key", jnp.zeros, key.shape, key.dtype)
294
+ cached_value = self.variable("cache", "cached_value", jnp.zeros, value.shape, value.dtype)
295
+ cache_index = self.variable("cache", "cache_index", lambda: jnp.array(0, dtype=jnp.int32))
296
+
297
+ if is_initialized:
298
+ *batch_dims, max_length, num_heads, depth_per_head = cached_key.value.shape
299
+ # update key, value caches with our new 1d spatial slices
300
+ cur_index = cache_index.value
301
+ indices = (0,) * len(batch_dims) + (cur_index, 0, 0)
302
+ key = lax.dynamic_update_slice(cached_key.value, key, indices)
303
+ value = lax.dynamic_update_slice(cached_value.value, value, indices)
304
+ cached_key.value = key
305
+ cached_value.value = value
306
+ num_updated_cache_vectors = query.shape[1]
307
+ cache_index.value = cache_index.value + num_updated_cache_vectors
308
+ # 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.
309
+ pad_mask = jnp.broadcast_to(
310
+ jnp.arange(max_length) < cur_index + num_updated_cache_vectors,
311
+ tuple(batch_dims) + (1, num_updated_cache_vectors, max_length),
312
+ )
313
+ attention_mask = combine_masks(pad_mask, attention_mask)
314
+ return key, value, attention_mask
315
+
316
+ def __call__(
317
+ self,
318
+ hidden_states: jnp.ndarray,
319
+ key_value_states: Optional[jnp.ndarray] = None,
320
+ attention_mask: Optional[jnp.ndarray] = None,
321
+ init_cache: bool = False,
322
+ deterministic: bool = True,
323
+ ) -> Tuple[jnp.ndarray]:
324
+ """Input shape: Batch x Time x Channel"""
325
+
326
+ # if key_value_states are provided this layer is used as a cross-attention layer
327
+ # for the decoder
328
+ is_cross_attention = key_value_states is not None
329
+ batch_size = hidden_states.shape[0]
330
+
331
+ # get query proj
332
+ query_states = self.q_proj(hidden_states)
333
+ # get key, value proj
334
+ if is_cross_attention:
335
+ # cross_attentions
336
+ key_states = self.k_proj(key_value_states)
337
+ value_states = self.v_proj(key_value_states)
338
+ else:
339
+ # self_attention
340
+ key_states = self.k_proj(hidden_states)
341
+ value_states = self.v_proj(hidden_states)
342
+
343
+ query_states = self._split_heads(query_states)
344
+ key_states = self._split_heads(key_states)
345
+ value_states = self._split_heads(value_states)
346
+
347
+ # handle cache prepare causal attention mask
348
+ if self.causal:
349
+ query_length, key_length = query_states.shape[1], key_states.shape[1]
350
+ if self.has_variable("cache", "cached_key"):
351
+ mask_shift = self.variables["cache"]["cache_index"]
352
+ max_decoder_length = self.variables["cache"]["cached_key"].shape[1]
353
+ causal_mask = lax.dynamic_slice(
354
+ self.causal_mask, (0, 0, mask_shift, 0), (1, 1, query_length, max_decoder_length)
355
+ )
356
+ else:
357
+ causal_mask = self.causal_mask[:, :, :query_length, :key_length]
358
+ causal_mask = jnp.broadcast_to(causal_mask, (batch_size,) + causal_mask.shape[1:])
359
+
360
+ # combine masks if needed
361
+ if attention_mask is not None and self.causal:
362
+ attention_mask = jnp.broadcast_to(jnp.expand_dims(attention_mask, axis=(-3, -2)), causal_mask.shape)
363
+ attention_mask = combine_masks(attention_mask, causal_mask)
364
+ elif self.causal:
365
+ attention_mask = causal_mask
366
+ elif attention_mask is not None:
367
+ attention_mask = jnp.expand_dims(attention_mask, axis=(-3, -2))
368
+
369
+ # During fast autoregressive decoding, we feed one position at a time,
370
+ # and cache the keys and values step by step.
371
+ if self.causal and (self.has_variable("cache", "cached_key") or init_cache):
372
+ key_states, value_states, attention_mask = self._concatenate_to_cache(
373
+ key_states, value_states, query_states, attention_mask
374
+ )
375
+
376
+ # Convert the boolean attention mask to an attention bias.
377
+ if attention_mask is not None:
378
+ # attention mask in the form of attention bias
379
+ attention_bias = lax.select(
380
+ attention_mask > 0,
381
+ jnp.full(attention_mask.shape, 0.0).astype(self.dtype),
382
+ jnp.full(attention_mask.shape, jnp.finfo(self.dtype).min).astype(self.dtype),
383
+ )
384
+ else:
385
+ attention_bias = None
386
+
387
+ dropout_rng = None
388
+ if not deterministic and self.dropout > 0.0:
389
+ dropout_rng = self.make_rng("dropout")
390
+
391
+ attn_weights = dot_product_attention_weights(
392
+ query_states,
393
+ key_states,
394
+ bias=attention_bias,
395
+ dropout_rng=dropout_rng,
396
+ dropout_rate=self.dropout,
397
+ broadcast_dropout=True,
398
+ deterministic=deterministic,
399
+ dtype=self.dtype,
400
+ precision=None,
401
+ )
402
+
403
+ attn_output = jnp.einsum("...hqk,...khd->...qhd", attn_weights, value_states)
404
+ attn_output = self._merge_heads(attn_output)
405
+ attn_output = self.out_proj(attn_output)
406
+
407
+ return attn_output, attn_weights
408
+
409
+
410
+ # Copied from transformers.models.bart.modeling_flax_bart.FlaxBartEncoderLayer with Bart->Marian
411
+ class FlaxMarianEncoderLayer(nn.Module):
412
+ config: MarianConfig
413
+ dtype: jnp.dtype = jnp.float32
414
+
415
+ def setup(self) -> None:
416
+ self.embed_dim = self.config.d_model
417
+ self.self_attn = FlaxMarianAttention(
418
+ config=self.config,
419
+ embed_dim=self.embed_dim,
420
+ num_heads=self.config.encoder_attention_heads,
421
+ dropout=self.config.attention_dropout,
422
+ dtype=self.dtype,
423
+ )
424
+ self.self_attn_layer_norm = nn.LayerNorm(dtype=self.dtype, epsilon=1e-05)
425
+ self.dropout_layer = nn.Dropout(rate=self.config.dropout)
426
+ self.activation_fn = ACT2FN[self.config.activation_function]
427
+ self.activation_dropout_layer = nn.Dropout(rate=self.config.activation_dropout)
428
+ self.fc1 = nn.Dense(
429
+ self.config.encoder_ffn_dim,
430
+ dtype=self.dtype,
431
+ kernel_init=jax.nn.initializers.normal(self.config.init_std),
432
+ )
433
+ self.fc2 = nn.Dense(
434
+ self.embed_dim, dtype=self.dtype, kernel_init=jax.nn.initializers.normal(self.config.init_std)
435
+ )
436
+ self.final_layer_norm = nn.LayerNorm(dtype=self.dtype, epsilon=1e-05)
437
+
438
+ def __call__(
439
+ self,
440
+ hidden_states: jnp.ndarray,
441
+ attention_mask: jnp.ndarray,
442
+ output_attentions: bool = True,
443
+ deterministic: bool = True,
444
+ ) -> Tuple[jnp.ndarray]:
445
+ residual = hidden_states
446
+ hidden_states, attn_weights = self.self_attn(hidden_states=hidden_states, attention_mask=attention_mask)
447
+
448
+ hidden_states = self.dropout_layer(hidden_states, deterministic=deterministic)
449
+ hidden_states = residual + hidden_states
450
+ hidden_states = self.self_attn_layer_norm(hidden_states)
451
+
452
+ residual = hidden_states
453
+ hidden_states = self.activation_fn(self.fc1(hidden_states))
454
+ hidden_states = self.activation_dropout_layer(hidden_states, deterministic=deterministic)
455
+ hidden_states = self.fc2(hidden_states)
456
+ hidden_states = self.dropout_layer(hidden_states, deterministic=deterministic)
457
+ hidden_states = residual + hidden_states
458
+ hidden_states = self.final_layer_norm(hidden_states)
459
+
460
+ outputs = (hidden_states,)
461
+
462
+ if output_attentions:
463
+ outputs += (attn_weights,)
464
+
465
+ return outputs
466
+
467
+
468
+ # Copied from transformers.models.bart.modeling_flax_bart.FlaxBartEncoderLayerCollection with Bart->Marian
469
+ class FlaxMarianEncoderLayerCollection(nn.Module):
470
+ config: MarianConfig
471
+ dtype: jnp.dtype = jnp.float32 # the dtype of the computation
472
+
473
+ def setup(self):
474
+ self.layers = [
475
+ FlaxMarianEncoderLayer(self.config, name=str(i), dtype=self.dtype)
476
+ for i in range(self.config.encoder_layers)
477
+ ]
478
+ self.layerdrop = self.config.encoder_layerdrop
479
+
480
+ def __call__(
481
+ self,
482
+ hidden_states,
483
+ attention_mask,
484
+ deterministic: bool = True,
485
+ output_attentions: bool = False,
486
+ output_hidden_states: bool = False,
487
+ return_dict: bool = True,
488
+ ):
489
+ all_attentions = () if output_attentions else None
490
+ all_hidden_states = () if output_hidden_states else None
491
+
492
+ for encoder_layer in self.layers:
493
+ if output_hidden_states:
494
+ all_hidden_states = all_hidden_states + (hidden_states,)
495
+ # add LayerDrop (see https://arxiv.org/abs/1909.11556 for description)
496
+ dropout_probability = random.uniform(0, 1)
497
+ if not deterministic and (dropout_probability < self.layerdrop): # skip the layer
498
+ layer_outputs = (None, None)
499
+ else:
500
+ layer_outputs = encoder_layer(
501
+ hidden_states,
502
+ attention_mask,
503
+ output_attentions,
504
+ deterministic,
505
+ )
506
+ hidden_states = layer_outputs[0]
507
+ if output_attentions:
508
+ all_attentions = all_attentions + (layer_outputs[1],)
509
+
510
+ if output_hidden_states:
511
+ all_hidden_states += (hidden_states,)
512
+
513
+ outputs = (hidden_states, all_hidden_states, all_attentions)
514
+
515
+ if not return_dict:
516
+ return tuple(v for v in outputs if v is not None)
517
+
518
+ return FlaxBaseModelOutput(
519
+ last_hidden_state=hidden_states, hidden_states=all_hidden_states, attentions=all_attentions
520
+ )
521
+
522
+
523
+ # Copied from transformers.models.bart.modeling_flax_bart.FlaxBartDecoderLayer with Bart->Marian
524
+ class FlaxMarianDecoderLayer(nn.Module):
525
+ config: MarianConfig
526
+ dtype: jnp.dtype = jnp.float32
527
+
528
+ def setup(self) -> None:
529
+ self.embed_dim = self.config.d_model
530
+ self.self_attn = FlaxMarianAttention(
531
+ config=self.config,
532
+ embed_dim=self.embed_dim,
533
+ num_heads=self.config.decoder_attention_heads,
534
+ dropout=self.config.attention_dropout,
535
+ causal=True,
536
+ dtype=self.dtype,
537
+ )
538
+ self.dropout_layer = nn.Dropout(rate=self.config.dropout)
539
+ self.activation_fn = ACT2FN[self.config.activation_function]
540
+ self.activation_dropout_layer = nn.Dropout(rate=self.config.activation_dropout)
541
+
542
+ self.self_attn_layer_norm = nn.LayerNorm(dtype=self.dtype, epsilon=1e-05)
543
+ self.encoder_attn = FlaxMarianAttention(
544
+ config=self.config,
545
+ embed_dim=self.embed_dim,
546
+ num_heads=self.config.decoder_attention_heads,
547
+ dropout=self.config.attention_dropout,
548
+ dtype=self.dtype,
549
+ )
550
+ self.encoder_attn_layer_norm = nn.LayerNorm(dtype=self.dtype, epsilon=1e-05)
551
+ self.fc1 = nn.Dense(
552
+ self.config.decoder_ffn_dim,
553
+ dtype=self.dtype,
554
+ kernel_init=jax.nn.initializers.normal(self.config.init_std),
555
+ )
556
+ self.fc2 = nn.Dense(
557
+ self.embed_dim, dtype=self.dtype, kernel_init=jax.nn.initializers.normal(self.config.init_std)
558
+ )
559
+ self.final_layer_norm = nn.LayerNorm(dtype=self.dtype, epsilon=1e-05)
560
+
561
+ def __call__(
562
+ self,
563
+ hidden_states: jnp.ndarray,
564
+ attention_mask: jnp.ndarray,
565
+ encoder_hidden_states: Optional[jnp.ndarray] = None,
566
+ encoder_attention_mask: Optional[jnp.ndarray] = None,
567
+ init_cache: bool = False,
568
+ output_attentions: bool = True,
569
+ deterministic: bool = True,
570
+ ) -> Tuple[jnp.ndarray]:
571
+ residual = hidden_states
572
+
573
+ # Self Attention
574
+ hidden_states, self_attn_weights = self.self_attn(
575
+ hidden_states=hidden_states, attention_mask=attention_mask, init_cache=init_cache
576
+ )
577
+ hidden_states = self.dropout_layer(hidden_states, deterministic=deterministic)
578
+ hidden_states = residual + hidden_states
579
+ hidden_states = self.self_attn_layer_norm(hidden_states)
580
+
581
+ # Cross-Attention Block
582
+ cross_attn_weights = None
583
+ if encoder_hidden_states is not None:
584
+ residual = hidden_states
585
+
586
+ hidden_states, cross_attn_weights = self.encoder_attn(
587
+ hidden_states=hidden_states,
588
+ key_value_states=encoder_hidden_states,
589
+ attention_mask=encoder_attention_mask,
590
+ )
591
+ hidden_states = self.dropout_layer(hidden_states, deterministic=deterministic)
592
+ hidden_states = residual + hidden_states
593
+ hidden_states = self.encoder_attn_layer_norm(hidden_states)
594
+
595
+ # Fully Connected
596
+ residual = hidden_states
597
+ hidden_states = self.activation_fn(self.fc1(hidden_states))
598
+ hidden_states = self.activation_dropout_layer(hidden_states, deterministic=deterministic)
599
+ hidden_states = self.fc2(hidden_states)
600
+ hidden_states = self.dropout_layer(hidden_states, deterministic=deterministic)
601
+ hidden_states = residual + hidden_states
602
+ hidden_states = self.final_layer_norm(hidden_states)
603
+
604
+ outputs = (hidden_states,)
605
+
606
+ if output_attentions:
607
+ outputs += (self_attn_weights, cross_attn_weights)
608
+
609
+ return outputs
610
+
611
+
612
+ # Copied from transformers.models.bart.modeling_flax_bart.FlaxBartDecoderLayerCollection with Bart->Marian
613
+ class FlaxMarianDecoderLayerCollection(nn.Module):
614
+ config: MarianConfig
615
+ dtype: jnp.dtype = jnp.float32 # the dtype of the computation
616
+
617
+ def setup(self):
618
+ self.layers = [
619
+ FlaxMarianDecoderLayer(self.config, name=str(i), dtype=self.dtype)
620
+ for i in range(self.config.decoder_layers)
621
+ ]
622
+ self.layerdrop = self.config.decoder_layerdrop
623
+
624
+ def __call__(
625
+ self,
626
+ hidden_states,
627
+ attention_mask,
628
+ encoder_hidden_states: Optional[jnp.ndarray] = None,
629
+ encoder_attention_mask: Optional[jnp.ndarray] = None,
630
+ deterministic: bool = True,
631
+ init_cache: bool = False,
632
+ output_attentions: bool = False,
633
+ output_hidden_states: bool = False,
634
+ return_dict: bool = True,
635
+ ):
636
+ # decoder layers
637
+ all_hidden_states = () if output_hidden_states else None
638
+ all_self_attns = () if output_attentions else None
639
+ all_cross_attentions = () if (output_attentions and encoder_hidden_states is not None) else None
640
+
641
+ for decoder_layer in self.layers:
642
+ if output_hidden_states:
643
+ all_hidden_states += (hidden_states,)
644
+ # add LayerDrop (see https://arxiv.org/abs/1909.11556 for description)
645
+ dropout_probability = random.uniform(0, 1)
646
+ if not deterministic and (dropout_probability < self.layerdrop):
647
+ layer_outputs = (None, None, None)
648
+ else:
649
+ layer_outputs = decoder_layer(
650
+ hidden_states,
651
+ attention_mask=attention_mask,
652
+ encoder_hidden_states=encoder_hidden_states,
653
+ encoder_attention_mask=encoder_attention_mask,
654
+ init_cache=init_cache,
655
+ output_attentions=output_attentions,
656
+ deterministic=deterministic,
657
+ )
658
+
659
+ hidden_states = layer_outputs[0]
660
+ if output_attentions:
661
+ all_self_attns += (layer_outputs[1],)
662
+
663
+ if encoder_hidden_states is not None:
664
+ all_cross_attentions += (layer_outputs[2],)
665
+
666
+ # add hidden states from the last decoder layer
667
+ if output_hidden_states:
668
+ all_hidden_states += (hidden_states,)
669
+
670
+ outputs = [hidden_states, all_hidden_states, all_self_attns, all_cross_attentions]
671
+
672
+ if not return_dict:
673
+ return tuple(v for v in outputs if v is not None)
674
+
675
+ return FlaxBaseModelOutputWithPastAndCrossAttentions(
676
+ last_hidden_state=hidden_states,
677
+ hidden_states=all_hidden_states,
678
+ attentions=all_self_attns,
679
+ cross_attentions=all_cross_attentions,
680
+ )
681
+
682
+
683
+ class FlaxMarianEncoder(nn.Module):
684
+ config: MarianConfig
685
+ embed_tokens: nn.Embed
686
+ dtype: jnp.dtype = jnp.float32 # the dtype of the computation
687
+
688
+ def setup(self):
689
+ self.dropout_layer = nn.Dropout(rate=self.config.dropout)
690
+
691
+ embed_dim = self.config.d_model
692
+ self.max_source_positions = self.config.max_position_embeddings
693
+ self.embed_scale = math.sqrt(embed_dim) if self.config.scale_embedding else 1.0
694
+
695
+ self.embed_positions = create_sinusoidal_positions(self.config.max_position_embeddings, embed_dim)
696
+ self.layers = FlaxMarianEncoderLayerCollection(self.config, self.dtype)
697
+
698
+ def __call__(
699
+ self,
700
+ input_ids,
701
+ attention_mask,
702
+ position_ids,
703
+ output_attentions: bool = False,
704
+ output_hidden_states: bool = False,
705
+ return_dict: bool = True,
706
+ deterministic: bool = True,
707
+ ):
708
+ input_shape = input_ids.shape
709
+ input_ids = input_ids.reshape(-1, input_shape[-1])
710
+
711
+ inputs_embeds = self.embed_tokens(input_ids) * self.embed_scale
712
+
713
+ positions = jnp.take(self.embed_positions, position_ids, axis=0)
714
+ # explicitly cast the positions here, since self.embed_positions are not registered as parameters
715
+ positions = positions.astype(inputs_embeds.dtype)
716
+
717
+ hidden_states = inputs_embeds + positions
718
+ hidden_states = self.dropout_layer(hidden_states, deterministic=deterministic)
719
+
720
+ outputs = self.layers(
721
+ hidden_states,
722
+ attention_mask,
723
+ deterministic=deterministic,
724
+ output_attentions=output_attentions,
725
+ output_hidden_states=output_hidden_states,
726
+ return_dict=return_dict,
727
+ )
728
+
729
+ if not return_dict:
730
+ return outputs
731
+
732
+ return FlaxBaseModelOutput(
733
+ last_hidden_state=outputs.last_hidden_state,
734
+ hidden_states=outputs.hidden_states,
735
+ attentions=outputs.attentions,
736
+ )
737
+
738
+
739
+ class FlaxMarianDecoder(nn.Module):
740
+ config: MarianConfig
741
+ embed_tokens: nn.Embed
742
+ dtype: jnp.dtype = jnp.float32 # the dtype of the computation
743
+
744
+ def setup(self):
745
+ self.dropout_layer = nn.Dropout(rate=self.config.dropout)
746
+
747
+ embed_dim = self.config.d_model
748
+ self.max_target_positions = self.config.max_position_embeddings
749
+ self.embed_scale = math.sqrt(self.config.d_model) if self.config.scale_embedding else 1.0
750
+
751
+ self.embed_positions = create_sinusoidal_positions(self.config.max_position_embeddings, embed_dim)
752
+ self.layers = FlaxMarianDecoderLayerCollection(self.config, self.dtype)
753
+
754
+ def __call__(
755
+ self,
756
+ input_ids,
757
+ attention_mask,
758
+ position_ids,
759
+ encoder_hidden_states: Optional[jnp.ndarray] = None,
760
+ encoder_attention_mask: Optional[jnp.ndarray] = None,
761
+ init_cache: bool = False,
762
+ output_attentions: bool = False,
763
+ output_hidden_states: bool = False,
764
+ return_dict: bool = True,
765
+ deterministic: bool = True,
766
+ ):
767
+ input_shape = input_ids.shape
768
+ input_ids = input_ids.reshape(-1, input_shape[-1])
769
+
770
+ inputs_embeds = self.embed_tokens(input_ids) * self.embed_scale
771
+
772
+ # embed positions
773
+ positions = jnp.take(self.embed_positions, position_ids, axis=0)
774
+ # explicitly cast the positions here, since self.embed_positions are not registered as parameters
775
+ positions = positions.astype(inputs_embeds.dtype)
776
+
777
+ hidden_states = inputs_embeds + positions
778
+
779
+ hidden_states = self.dropout_layer(hidden_states, deterministic=deterministic)
780
+
781
+ outputs = self.layers(
782
+ hidden_states,
783
+ attention_mask,
784
+ encoder_hidden_states,
785
+ encoder_attention_mask,
786
+ deterministic=deterministic,
787
+ init_cache=init_cache,
788
+ output_attentions=output_attentions,
789
+ output_hidden_states=output_hidden_states,
790
+ return_dict=return_dict,
791
+ )
792
+
793
+ if not return_dict:
794
+ return outputs
795
+
796
+ return FlaxBaseModelOutputWithPastAndCrossAttentions(
797
+ last_hidden_state=outputs.last_hidden_state,
798
+ hidden_states=outputs.hidden_states,
799
+ attentions=outputs.attentions,
800
+ cross_attentions=outputs.cross_attentions,
801
+ )
802
+
803
+
804
+ class FlaxMarianModule(nn.Module):
805
+ config: MarianConfig
806
+ dtype: jnp.dtype = jnp.float32 # the dtype of the computation
807
+
808
+ def setup(self):
809
+ self.shared = nn.Embed(
810
+ self.config.vocab_size,
811
+ self.config.d_model,
812
+ embedding_init=jax.nn.initializers.normal(self.config.init_std),
813
+ )
814
+
815
+ self.encoder = FlaxMarianEncoder(self.config, dtype=self.dtype, embed_tokens=self.shared)
816
+ self.decoder = FlaxMarianDecoder(self.config, dtype=self.dtype, embed_tokens=self.shared)
817
+
818
+ def _get_encoder_module(self):
819
+ return self.encoder
820
+
821
+ def _get_decoder_module(self):
822
+ return self.decoder
823
+
824
+ def __call__(
825
+ self,
826
+ input_ids,
827
+ attention_mask,
828
+ decoder_input_ids,
829
+ decoder_attention_mask,
830
+ position_ids,
831
+ decoder_position_ids,
832
+ output_attentions: bool = False,
833
+ output_hidden_states: bool = False,
834
+ return_dict: bool = True,
835
+ deterministic: bool = True,
836
+ ):
837
+ encoder_outputs = self.encoder(
838
+ input_ids=input_ids,
839
+ attention_mask=attention_mask,
840
+ position_ids=position_ids,
841
+ output_attentions=output_attentions,
842
+ output_hidden_states=output_hidden_states,
843
+ return_dict=return_dict,
844
+ deterministic=deterministic,
845
+ )
846
+
847
+ decoder_outputs = self.decoder(
848
+ input_ids=decoder_input_ids,
849
+ attention_mask=decoder_attention_mask,
850
+ position_ids=decoder_position_ids,
851
+ encoder_hidden_states=encoder_outputs[0],
852
+ encoder_attention_mask=attention_mask,
853
+ output_attentions=output_attentions,
854
+ output_hidden_states=output_hidden_states,
855
+ return_dict=return_dict,
856
+ deterministic=deterministic,
857
+ )
858
+
859
+ if not return_dict:
860
+ return decoder_outputs + encoder_outputs
861
+
862
+ return FlaxSeq2SeqModelOutput(
863
+ last_hidden_state=decoder_outputs.last_hidden_state,
864
+ decoder_hidden_states=decoder_outputs.hidden_states,
865
+ decoder_attentions=decoder_outputs.attentions,
866
+ cross_attentions=decoder_outputs.cross_attentions,
867
+ encoder_last_hidden_state=encoder_outputs.last_hidden_state,
868
+ encoder_hidden_states=encoder_outputs.hidden_states,
869
+ encoder_attentions=encoder_outputs.attentions,
870
+ )
871
+
872
+
873
+ class FlaxMarianPreTrainedModel(FlaxPreTrainedModel):
874
+ config_class = MarianConfig
875
+ base_model_prefix: str = "model"
876
+ module_class: nn.Module = None
877
+
878
+ def __init__(
879
+ self,
880
+ config: MarianConfig,
881
+ input_shape: Tuple[int] = (1, 1),
882
+ seed: int = 0,
883
+ dtype: jnp.dtype = jnp.float32,
884
+ _do_init: bool = True,
885
+ **kwargs,
886
+ ):
887
+ module = self.module_class(config=config, dtype=dtype, **kwargs)
888
+ super().__init__(config, module, input_shape=input_shape, seed=seed, dtype=dtype, _do_init=_do_init)
889
+
890
+ def init_weights(self, rng: jax.random.PRNGKey, input_shape: Tuple, params: FrozenDict = None) -> FrozenDict:
891
+ # init input tensors
892
+ input_ids = jnp.zeros(input_shape, dtype="i4")
893
+ # make sure initialization pass will work for FlaxMarianForSequenceClassificationModule
894
+ input_ids = input_ids.at[(..., -1)].set(self.config.eos_token_id)
895
+ attention_mask = jnp.ones_like(input_ids)
896
+ decoder_input_ids = input_ids
897
+ decoder_attention_mask = jnp.ones_like(input_ids)
898
+
899
+ batch_size, sequence_length = input_ids.shape
900
+ position_ids = jnp.broadcast_to(jnp.arange(sequence_length)[None, :], (batch_size, sequence_length))
901
+ decoder_position_ids = jnp.broadcast_to(jnp.arange(sequence_length)[None, :], (batch_size, sequence_length))
902
+
903
+ params_rng, dropout_rng = jax.random.split(rng)
904
+ rngs = {"params": params_rng, "dropout": dropout_rng}
905
+
906
+ random_params = self.module.init(
907
+ rngs,
908
+ input_ids,
909
+ attention_mask,
910
+ decoder_input_ids,
911
+ decoder_attention_mask,
912
+ position_ids,
913
+ decoder_position_ids,
914
+ )["params"]
915
+
916
+ if params is not None:
917
+ random_params = flatten_dict(unfreeze(random_params))
918
+ params = flatten_dict(unfreeze(params))
919
+ for missing_key in self._missing_keys:
920
+ params[missing_key] = random_params[missing_key]
921
+ self._missing_keys = set()
922
+ return freeze(unflatten_dict(params))
923
+ else:
924
+ return random_params
925
+
926
+ def init_cache(self, batch_size, max_length, encoder_outputs):
927
+ r"""
928
+ Args:
929
+ batch_size (`int`):
930
+ batch_size used for fast auto-regressive decoding. Defines the batch size of the initialized cache.
931
+ max_length (`int`):
932
+ maximum possible length for auto-regressive decoding. Defines the sequence length of the initialized
933
+ cache.
934
+ encoder_outputs (`Union[FlaxBaseModelOutput, tuple(tuple(jnp.ndarray)]`):
935
+ `encoder_outputs` consists of (`last_hidden_state`, *optional*: `hidden_states`, *optional*:
936
+ `attentions`). `last_hidden_state` of shape `(batch_size, sequence_length, hidden_size)`, *optional*)
937
+ is a sequence of hidden-states at the output of the last layer of the encoder. Used in the
938
+ cross-attention of the decoder.
939
+ """
940
+ # init input variables to retrieve cache
941
+ decoder_input_ids = jnp.ones((batch_size, max_length), dtype="i4")
942
+ decoder_attention_mask = jnp.ones_like(decoder_input_ids)
943
+ decoder_position_ids = jnp.broadcast_to(
944
+ jnp.arange(jnp.atleast_2d(decoder_input_ids).shape[-1]), decoder_input_ids.shape
945
+ )
946
+
947
+ def _decoder_forward(module, decoder_input_ids, decoder_attention_mask, decoder_position_ids, **kwargs):
948
+ decoder_module = module._get_decoder_module()
949
+ return decoder_module(decoder_input_ids, decoder_attention_mask, decoder_position_ids, **kwargs)
950
+
951
+ init_variables = self.module.init(
952
+ jax.random.PRNGKey(0),
953
+ decoder_input_ids=decoder_input_ids,
954
+ decoder_attention_mask=decoder_attention_mask,
955
+ decoder_position_ids=decoder_position_ids,
956
+ encoder_hidden_states=encoder_outputs[0],
957
+ init_cache=True,
958
+ method=_decoder_forward, # we only need to call the decoder to init the cache
959
+ )
960
+ return unfreeze(init_variables["cache"])
961
+
962
+ @add_start_docstrings(MARIAN_ENCODE_INPUTS_DOCSTRING)
963
+ @replace_return_docstrings(output_type=FlaxBaseModelOutput, config_class=MarianConfig)
964
+ def encode(
965
+ self,
966
+ input_ids: jnp.ndarray,
967
+ attention_mask: Optional[jnp.ndarray] = None,
968
+ position_ids: Optional[jnp.ndarray] = None,
969
+ output_attentions: Optional[bool] = None,
970
+ output_hidden_states: Optional[bool] = None,
971
+ return_dict: Optional[bool] = None,
972
+ train: bool = False,
973
+ params: dict = None,
974
+ dropout_rng: PRNGKey = None,
975
+ ):
976
+ r"""
977
+ Returns:
978
+
979
+ Example:
980
+
981
+ ```python
982
+ >>> from transformers import AutoTokenizer, FlaxMarianMTModel
983
+
984
+ >>> tokenizer = AutoTokenizer.from_pretrained("Helsinki-NLP/opus-mt-en-de")
985
+ >>> model = FlaxMarianMTModel.from_pretrained("Helsinki-NLP/opus-mt-en-de")
986
+
987
+ >>> text = "My friends are cool but they eat too many carbs."
988
+ >>> inputs = tokenizer(text, max_length=64, return_tensors="jax")
989
+ >>> encoder_outputs = model.encode(**inputs)
990
+ ```"""
991
+
992
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
993
+ output_hidden_states = (
994
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
995
+ )
996
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
997
+
998
+ if attention_mask is None:
999
+ attention_mask = jnp.ones_like(input_ids)
1000
+ if position_ids is None:
1001
+ batch_size, sequence_length = input_ids.shape
1002
+ position_ids = jnp.broadcast_to(jnp.arange(sequence_length)[None, :], (batch_size, sequence_length))
1003
+
1004
+ # Handle any PRNG if needed
1005
+ rngs = {}
1006
+ if dropout_rng is not None:
1007
+ rngs["dropout"] = dropout_rng
1008
+
1009
+ def _encoder_forward(module, input_ids, attention_mask, position_ids, **kwargs):
1010
+ encode_module = module._get_encoder_module()
1011
+ return encode_module(input_ids, attention_mask, position_ids, **kwargs)
1012
+
1013
+ return self.module.apply(
1014
+ {"params": params or self.params},
1015
+ input_ids=jnp.array(input_ids, dtype="i4"),
1016
+ attention_mask=jnp.array(attention_mask, dtype="i4"),
1017
+ position_ids=jnp.array(position_ids, dtype="i4"),
1018
+ output_attentions=output_attentions,
1019
+ output_hidden_states=output_hidden_states,
1020
+ return_dict=return_dict,
1021
+ deterministic=not train,
1022
+ rngs=rngs,
1023
+ method=_encoder_forward,
1024
+ )
1025
+
1026
+ @add_start_docstrings(MARIAN_DECODE_INPUTS_DOCSTRING)
1027
+ @replace_return_docstrings(output_type=FlaxBaseModelOutputWithPastAndCrossAttentions, config_class=MarianConfig)
1028
+ def decode(
1029
+ self,
1030
+ decoder_input_ids,
1031
+ encoder_outputs,
1032
+ encoder_attention_mask: Optional[jnp.ndarray] = None,
1033
+ decoder_attention_mask: Optional[jnp.ndarray] = None,
1034
+ decoder_position_ids: Optional[jnp.ndarray] = None,
1035
+ past_key_values: dict = None,
1036
+ output_attentions: Optional[bool] = None,
1037
+ output_hidden_states: Optional[bool] = None,
1038
+ return_dict: Optional[bool] = None,
1039
+ train: bool = False,
1040
+ params: dict = None,
1041
+ dropout_rng: PRNGKey = None,
1042
+ ):
1043
+ r"""
1044
+ Returns:
1045
+
1046
+ Example:
1047
+
1048
+ ```python
1049
+ >>> import jax.numpy as jnp
1050
+ >>> from transformers import AutoTokenizer, FlaxMarianMTModel
1051
+
1052
+ >>> tokenizer = AutoTokenizer.from_pretrained("Helsinki-NLP/opus-mt-en-de")
1053
+ >>> model = FlaxMarianMTModel.from_pretrained("Helsinki-NLP/opus-mt-en-de")
1054
+
1055
+ >>> text = "My friends are cool but they eat too many carbs."
1056
+ >>> inputs = tokenizer(text, max_length=64, return_tensors="jax")
1057
+ >>> encoder_outputs = model.encode(**inputs)
1058
+
1059
+ >>> decoder_start_token_id = model.config.decoder_start_token_id
1060
+ >>> decoder_input_ids = jnp.ones((inputs.input_ids.shape[0], 1), dtype="i4") * decoder_start_token_id
1061
+
1062
+ >>> outputs = model.decode(decoder_input_ids, encoder_outputs)
1063
+ >>> last_decoder_hidden_states = outputs.last_hidden_state
1064
+ ```"""
1065
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1066
+ output_hidden_states = (
1067
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1068
+ )
1069
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
1070
+
1071
+ encoder_hidden_states = encoder_outputs[0]
1072
+ if encoder_attention_mask is None:
1073
+ batch_size, sequence_length = encoder_hidden_states.shape[:2]
1074
+ encoder_attention_mask = jnp.ones((batch_size, sequence_length))
1075
+
1076
+ batch_size, sequence_length = decoder_input_ids.shape
1077
+ if decoder_attention_mask is None:
1078
+ decoder_attention_mask = jnp.ones((batch_size, sequence_length))
1079
+
1080
+ if decoder_position_ids is None:
1081
+ if past_key_values is not None:
1082
+ raise ValueError("Make sure to provide `decoder_position_ids` when passing `past_key_values`.")
1083
+
1084
+ decoder_position_ids = jnp.broadcast_to(
1085
+ jnp.arange(sequence_length)[None, :], (batch_size, sequence_length)
1086
+ )
1087
+
1088
+ # Handle any PRNG if needed
1089
+ rngs = {}
1090
+ if dropout_rng is not None:
1091
+ rngs["dropout"] = dropout_rng
1092
+
1093
+ inputs = {"params": params or self.params}
1094
+
1095
+ # if past_key_values are passed then cache is already initialized a private flag init_cache has to be
1096
+ # passed down to ensure cache is used. It has to be made sure that cache is marked as mutable so that
1097
+ # it can be changed by FlaxMarianAttention module
1098
+ if past_key_values:
1099
+ inputs["cache"] = past_key_values
1100
+ mutable = ["cache"]
1101
+ else:
1102
+ mutable = False
1103
+
1104
+ def _decoder_forward(module, decoder_input_ids, decoder_attention_mask, decoder_position_ids, **kwargs):
1105
+ decoder_module = module._get_decoder_module()
1106
+ return decoder_module(
1107
+ decoder_input_ids,
1108
+ decoder_attention_mask,
1109
+ decoder_position_ids,
1110
+ **kwargs,
1111
+ )
1112
+
1113
+ outputs = self.module.apply(
1114
+ inputs,
1115
+ decoder_input_ids=jnp.array(decoder_input_ids, dtype="i4"),
1116
+ decoder_attention_mask=jnp.array(decoder_attention_mask, dtype="i4"),
1117
+ decoder_position_ids=jnp.array(decoder_position_ids, dtype="i4"),
1118
+ encoder_hidden_states=encoder_hidden_states,
1119
+ encoder_attention_mask=jnp.array(encoder_attention_mask, dtype="i4"),
1120
+ output_attentions=output_attentions,
1121
+ output_hidden_states=output_hidden_states,
1122
+ return_dict=return_dict,
1123
+ deterministic=not train,
1124
+ rngs=rngs,
1125
+ mutable=mutable,
1126
+ method=_decoder_forward,
1127
+ )
1128
+
1129
+ # add updated cache to model output
1130
+ if past_key_values is not None and return_dict:
1131
+ outputs, past = outputs
1132
+ outputs["past_key_values"] = unfreeze(past["cache"])
1133
+ return outputs
1134
+ elif past_key_values is not None and not return_dict:
1135
+ outputs, past = outputs
1136
+ outputs = outputs[:1] + (unfreeze(past["cache"]),) + outputs[1:]
1137
+
1138
+ return outputs
1139
+
1140
+ @add_start_docstrings_to_model_forward(MARIAN_INPUTS_DOCSTRING)
1141
+ def __call__(
1142
+ self,
1143
+ input_ids: jnp.ndarray,
1144
+ attention_mask: Optional[jnp.ndarray] = None,
1145
+ decoder_input_ids: Optional[jnp.ndarray] = None,
1146
+ decoder_attention_mask: Optional[jnp.ndarray] = None,
1147
+ position_ids: Optional[jnp.ndarray] = None,
1148
+ decoder_position_ids: Optional[jnp.ndarray] = None,
1149
+ output_attentions: Optional[bool] = None,
1150
+ output_hidden_states: Optional[bool] = None,
1151
+ return_dict: Optional[bool] = None,
1152
+ train: bool = False,
1153
+ params: dict = None,
1154
+ dropout_rng: PRNGKey = None,
1155
+ ):
1156
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1157
+ output_hidden_states = (
1158
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1159
+ )
1160
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
1161
+
1162
+ # prepare encoder inputs
1163
+ if attention_mask is None:
1164
+ attention_mask = jnp.ones_like(input_ids)
1165
+ if position_ids is None:
1166
+ batch_size, sequence_length = input_ids.shape
1167
+ position_ids = jnp.broadcast_to(jnp.arange(sequence_length)[None, :], (batch_size, sequence_length))
1168
+
1169
+ # prepare decoder inputs
1170
+ if decoder_input_ids is None:
1171
+ decoder_input_ids = shift_tokens_right(
1172
+ input_ids, self.config.pad_token_id, decoder_start_token_id=self.config.decoder_start_token_id
1173
+ )
1174
+ if decoder_attention_mask is None:
1175
+ decoder_attention_mask = jnp.ones_like(decoder_input_ids)
1176
+ if decoder_position_ids is None:
1177
+ batch_size, sequence_length = decoder_input_ids.shape
1178
+ decoder_position_ids = jnp.broadcast_to(
1179
+ jnp.arange(sequence_length)[None, :], (batch_size, sequence_length)
1180
+ )
1181
+
1182
+ # Handle any PRNG if needed
1183
+ rngs = {"dropout": dropout_rng} if dropout_rng is not None else {}
1184
+
1185
+ return self.module.apply(
1186
+ {"params": params or self.params},
1187
+ input_ids=jnp.array(input_ids, dtype="i4"),
1188
+ attention_mask=jnp.array(attention_mask, dtype="i4"),
1189
+ position_ids=jnp.array(position_ids, dtype="i4"),
1190
+ decoder_input_ids=jnp.array(decoder_input_ids, dtype="i4"),
1191
+ decoder_attention_mask=jnp.array(decoder_attention_mask, dtype="i4"),
1192
+ decoder_position_ids=jnp.array(decoder_position_ids, dtype="i4"),
1193
+ output_attentions=output_attentions,
1194
+ output_hidden_states=output_hidden_states,
1195
+ return_dict=return_dict,
1196
+ deterministic=not train,
1197
+ rngs=rngs,
1198
+ )
1199
+
1200
+
1201
+ @add_start_docstrings(
1202
+ "The bare Marian Model transformer outputting raw hidden-states without any specific head on top.",
1203
+ MARIAN_START_DOCSTRING,
1204
+ )
1205
+ class FlaxMarianModel(FlaxMarianPreTrainedModel):
1206
+ config: MarianConfig
1207
+ dtype: jnp.dtype = jnp.float32 # the dtype of the computation
1208
+ module_class = FlaxMarianModule
1209
+
1210
+
1211
+ append_call_sample_docstring(FlaxMarianModel, _CHECKPOINT_FOR_DOC, FlaxSeq2SeqModelOutput, _CONFIG_FOR_DOC)
1212
+
1213
+
1214
+ class FlaxMarianMTModule(nn.Module):
1215
+ config: MarianConfig
1216
+ dtype: jnp.dtype = jnp.float32
1217
+ bias_init: Callable[..., jnp.ndarray] = jax.nn.initializers.zeros
1218
+
1219
+ def setup(self):
1220
+ self.model = FlaxMarianModule(config=self.config, dtype=self.dtype)
1221
+ self.lm_head = nn.Dense(
1222
+ self.model.shared.num_embeddings,
1223
+ use_bias=False,
1224
+ dtype=self.dtype,
1225
+ kernel_init=jax.nn.initializers.normal(self.config.init_std),
1226
+ )
1227
+ self.final_logits_bias = self.param("final_logits_bias", self.bias_init, (1, self.model.shared.num_embeddings))
1228
+
1229
+ def _get_encoder_module(self):
1230
+ return self.model.encoder
1231
+
1232
+ def _get_decoder_module(self):
1233
+ return self.model.decoder
1234
+
1235
+ def __call__(
1236
+ self,
1237
+ input_ids,
1238
+ attention_mask,
1239
+ decoder_input_ids,
1240
+ decoder_attention_mask,
1241
+ position_ids,
1242
+ decoder_position_ids,
1243
+ output_attentions: bool = False,
1244
+ output_hidden_states: bool = False,
1245
+ return_dict: bool = True,
1246
+ deterministic: bool = True,
1247
+ ):
1248
+ outputs = self.model(
1249
+ input_ids=input_ids,
1250
+ attention_mask=attention_mask,
1251
+ decoder_input_ids=decoder_input_ids,
1252
+ decoder_attention_mask=decoder_attention_mask,
1253
+ position_ids=position_ids,
1254
+ decoder_position_ids=decoder_position_ids,
1255
+ output_attentions=output_attentions,
1256
+ output_hidden_states=output_hidden_states,
1257
+ return_dict=return_dict,
1258
+ deterministic=deterministic,
1259
+ )
1260
+
1261
+ hidden_states = outputs[0]
1262
+
1263
+ if self.config.tie_word_embeddings:
1264
+ shared_embedding = self.model.variables["params"]["shared"]["embedding"]
1265
+ lm_logits = self.lm_head.apply({"params": {"kernel": shared_embedding.T}}, hidden_states)
1266
+ else:
1267
+ lm_logits = self.lm_head(hidden_states)
1268
+
1269
+ lm_logits += self.final_logits_bias.astype(self.dtype)
1270
+
1271
+ if not return_dict:
1272
+ output = (lm_logits,) + outputs[1:]
1273
+ return output
1274
+
1275
+ return FlaxSeq2SeqLMOutput(
1276
+ logits=lm_logits,
1277
+ decoder_hidden_states=outputs.decoder_hidden_states,
1278
+ decoder_attentions=outputs.decoder_attentions,
1279
+ cross_attentions=outputs.cross_attentions,
1280
+ encoder_last_hidden_state=outputs.encoder_last_hidden_state,
1281
+ encoder_hidden_states=outputs.encoder_hidden_states,
1282
+ encoder_attentions=outputs.encoder_attentions,
1283
+ )
1284
+
1285
+
1286
+ @add_start_docstrings(
1287
+ "The MARIAN Model with a language modeling head. Can be used for translation.", MARIAN_START_DOCSTRING
1288
+ )
1289
+ class FlaxMarianMTModel(FlaxMarianPreTrainedModel):
1290
+ module_class = FlaxMarianMTModule
1291
+ dtype: jnp.dtype = jnp.float32
1292
+
1293
+ @add_start_docstrings(MARIAN_DECODE_INPUTS_DOCSTRING)
1294
+ @replace_return_docstrings(output_type=FlaxCausalLMOutputWithCrossAttentions, config_class=MarianConfig)
1295
+ def decode(
1296
+ self,
1297
+ decoder_input_ids,
1298
+ encoder_outputs,
1299
+ encoder_attention_mask: Optional[jnp.ndarray] = None,
1300
+ decoder_attention_mask: Optional[jnp.ndarray] = None,
1301
+ decoder_position_ids: Optional[jnp.ndarray] = None,
1302
+ past_key_values: dict = None,
1303
+ output_attentions: Optional[bool] = None,
1304
+ output_hidden_states: Optional[bool] = None,
1305
+ return_dict: Optional[bool] = None,
1306
+ train: bool = False,
1307
+ params: dict = None,
1308
+ dropout_rng: PRNGKey = None,
1309
+ ):
1310
+ r"""
1311
+ Returns:
1312
+
1313
+ Example:
1314
+
1315
+ ```python
1316
+ >>> import jax.numpy as jnp
1317
+ >>> from transformers import AutoTokenizer, FlaxMarianMTModel
1318
+
1319
+ >>> model = FlaxMarianMTModel.from_pretrained("Helsinki-NLP/opus-mt-en-de")
1320
+ >>> tokenizer = AutoTokenizer.from_pretrained("Helsinki-NLP/opus-mt-en-de")
1321
+
1322
+ >>> text = "My friends are cool but they eat too many carbs."
1323
+ >>> inputs = tokenizer(text, max_length=64, return_tensors="jax")
1324
+ >>> encoder_outputs = model.encode(**inputs)
1325
+
1326
+ >>> decoder_start_token_id = model.config.decoder_start_token_id
1327
+ >>> decoder_input_ids = jnp.ones((inputs.input_ids.shape[0], 1), dtype="i4") * decoder_start_token_id
1328
+
1329
+ >>> outputs = model.decode(decoder_input_ids, encoder_outputs)
1330
+ >>> logits = outputs.logits
1331
+ ```"""
1332
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1333
+ output_hidden_states = (
1334
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1335
+ )
1336
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
1337
+
1338
+ encoder_hidden_states = encoder_outputs[0]
1339
+ if encoder_attention_mask is None:
1340
+ batch_size, sequence_length = encoder_hidden_states.shape[:2]
1341
+ encoder_attention_mask = jnp.ones((batch_size, sequence_length))
1342
+
1343
+ batch_size, sequence_length = decoder_input_ids.shape
1344
+ if decoder_attention_mask is None:
1345
+ decoder_attention_mask = jnp.ones((batch_size, sequence_length))
1346
+
1347
+ if decoder_position_ids is None:
1348
+ if past_key_values is not None:
1349
+ raise ValueError("Make sure to provide `decoder_position_ids` when passing `past_key_values`.")
1350
+
1351
+ decoder_position_ids = jnp.broadcast_to(
1352
+ jnp.arange(sequence_length)[None, :], (batch_size, sequence_length)
1353
+ )
1354
+
1355
+ # Handle any PRNG if needed
1356
+ rngs = {}
1357
+ if dropout_rng is not None:
1358
+ rngs["dropout"] = dropout_rng
1359
+
1360
+ inputs = {"params": params or self.params}
1361
+
1362
+ # if past_key_values are passed then cache is already initialized a private flag init_cache has to be
1363
+ # passed down to ensure cache is used. It has to be made sure that cache is marked as mutable so that
1364
+ # it can be changed by FlaxMarianAttention module
1365
+ if past_key_values:
1366
+ inputs["cache"] = past_key_values
1367
+ mutable = ["cache"]
1368
+ else:
1369
+ mutable = False
1370
+
1371
+ def _decoder_forward(module, decoder_input_ids, decoder_attention_mask, decoder_position_ids, **kwargs):
1372
+ decoder_module = module._get_decoder_module()
1373
+ outputs = decoder_module(
1374
+ decoder_input_ids,
1375
+ decoder_attention_mask,
1376
+ decoder_position_ids,
1377
+ **kwargs,
1378
+ )
1379
+ hidden_states = outputs[0]
1380
+
1381
+ if self.config.tie_word_embeddings:
1382
+ shared_embedding = module.model.variables["params"]["shared"]["embedding"]
1383
+ lm_logits = module.lm_head.apply({"params": {"kernel": shared_embedding.T}}, hidden_states)
1384
+ else:
1385
+ lm_logits = module.lm_head(hidden_states)
1386
+ lm_logits += module.final_logits_bias.astype(self.dtype)
1387
+
1388
+ return lm_logits, outputs
1389
+
1390
+ outputs = self.module.apply(
1391
+ inputs,
1392
+ decoder_input_ids=jnp.array(decoder_input_ids, dtype="i4"),
1393
+ decoder_attention_mask=jnp.array(decoder_attention_mask, dtype="i4"),
1394
+ decoder_position_ids=jnp.array(decoder_position_ids, dtype="i4"),
1395
+ encoder_hidden_states=encoder_hidden_states,
1396
+ encoder_attention_mask=jnp.array(encoder_attention_mask, dtype="i4"),
1397
+ output_attentions=output_attentions,
1398
+ output_hidden_states=output_hidden_states,
1399
+ return_dict=return_dict,
1400
+ deterministic=not train,
1401
+ rngs=rngs,
1402
+ mutable=mutable,
1403
+ method=_decoder_forward,
1404
+ )
1405
+
1406
+ if past_key_values is None:
1407
+ lm_logits, decoder_outputs = outputs
1408
+ else:
1409
+ (lm_logits, decoder_outputs), past = outputs
1410
+
1411
+ if return_dict:
1412
+ outputs = FlaxCausalLMOutputWithCrossAttentions(
1413
+ logits=lm_logits,
1414
+ hidden_states=decoder_outputs.hidden_states,
1415
+ attentions=decoder_outputs.attentions,
1416
+ cross_attentions=decoder_outputs.cross_attentions,
1417
+ )
1418
+ else:
1419
+ outputs = (lm_logits,) + decoder_outputs[1:]
1420
+
1421
+ # add updated cache to model output
1422
+ if past_key_values is not None and return_dict:
1423
+ outputs["past_key_values"] = unfreeze(past["cache"])
1424
+ return outputs
1425
+ elif past_key_values is not None and not return_dict:
1426
+ outputs = outputs[:1] + (unfreeze(past["cache"]),) + outputs[1:]
1427
+
1428
+ return outputs
1429
+
1430
+ def _adapt_logits_for_beam_search(self, logits):
1431
+ """This function enforces the padding token never to be generated."""
1432
+ logits = logits.at[:, :, self.config.pad_token_id].set(float("-inf"))
1433
+ return logits
1434
+
1435
+ def prepare_inputs_for_generation(
1436
+ self,
1437
+ decoder_input_ids,
1438
+ max_length,
1439
+ attention_mask: Optional[jax.Array] = None,
1440
+ decoder_attention_mask: Optional[jax.Array] = None,
1441
+ encoder_outputs=None,
1442
+ **kwargs,
1443
+ ):
1444
+ # initializing the cache
1445
+ batch_size, seq_length = decoder_input_ids.shape
1446
+
1447
+ past_key_values = self.init_cache(batch_size, max_length, encoder_outputs)
1448
+ # Note that usually one would have to put 0's in the attention_mask for x > input_ids.shape[-1] and x < cache_length.
1449
+ # But since the decoder uses a causal mask, those positions are masked anyways.
1450
+ # Thus we can create a single static attention_mask here, which is more efficient for compilation
1451
+ extended_attention_mask = jnp.ones((batch_size, max_length), dtype="i4")
1452
+ if decoder_attention_mask is not None:
1453
+ position_ids = decoder_attention_mask.cumsum(axis=-1) - 1
1454
+ extended_attention_mask = lax.dynamic_update_slice(extended_attention_mask, decoder_attention_mask, (0, 0))
1455
+ else:
1456
+ position_ids = jnp.broadcast_to(jnp.arange(seq_length, dtype="i4")[None, :], (batch_size, seq_length))
1457
+
1458
+ return {
1459
+ "past_key_values": past_key_values,
1460
+ "encoder_outputs": encoder_outputs,
1461
+ "encoder_attention_mask": attention_mask,
1462
+ "decoder_attention_mask": extended_attention_mask,
1463
+ "decoder_position_ids": position_ids,
1464
+ }
1465
+
1466
+ def update_inputs_for_generation(self, model_outputs, model_kwargs):
1467
+ model_kwargs["past_key_values"] = model_outputs.past_key_values
1468
+ model_kwargs["decoder_position_ids"] = model_kwargs["decoder_position_ids"][:, -1:] + 1
1469
+ return model_kwargs
1470
+
1471
+
1472
+ FLAX_MARIAN_MT_DOCSTRING = """
1473
+ Returns:
1474
+
1475
+ Example:
1476
+
1477
+ ```python
1478
+ >>> from transformers import AutoTokenizer, FlaxMarianMTModel
1479
+
1480
+ >>> model = FlaxMarianMTModel.from_pretrained("Helsinki-NLP/opus-mt-en-de")
1481
+ >>> tokenizer = AutoTokenizer.from_pretrained("Helsinki-NLP/opus-mt-en-de")
1482
+
1483
+ >>> text = "My friends are cool but they eat too many carbs."
1484
+ >>> input_ids = tokenizer(text, max_length=64, return_tensors="jax").input_ids
1485
+
1486
+ >>> sequences = model.generate(input_ids, max_length=64, num_beams=2).sequences
1487
+
1488
+ >>> outputs = tokenizer.batch_decode(sequences, skip_special_tokens=True)
1489
+ >>> # should give *Meine Freunde sind cool, aber sie essen zu viele Kohlenhydrate.*
1490
+ ```
1491
+ """
1492
+
1493
+ overwrite_call_docstring(
1494
+ FlaxMarianMTModel,
1495
+ MARIAN_INPUTS_DOCSTRING + FLAX_MARIAN_MT_DOCSTRING,
1496
+ )
1497
+ append_replace_return_docstrings(FlaxMarianMTModel, output_type=FlaxSeq2SeqLMOutput, config_class=_CONFIG_FOR_DOC)
1498
+
1499
+
1500
+ __all__ = ["FlaxMarianModel", "FlaxMarianMTModel", "FlaxMarianPreTrainedModel"]
tasks/tasksmith-441eeab80047/environment/source/src/transformers/models/marian/modeling_marian.py ADDED
@@ -0,0 +1,1662 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2021 The Marian Team Authors and The HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """PyTorch MarianMTModel model, ported from the Marian C++ repo."""
16
+
17
+ import copy
18
+ import math
19
+ from typing import List, Optional, Tuple, Union
20
+
21
+ import numpy as np
22
+ import torch
23
+ import torch.utils.checkpoint
24
+ from torch import nn
25
+ from torch.nn import CrossEntropyLoss
26
+
27
+ from ...activations import ACT2FN
28
+ from ...generation import GenerationMixin
29
+ from ...modeling_attn_mask_utils import _prepare_4d_attention_mask, _prepare_4d_causal_attention_mask
30
+ from ...modeling_outputs import (
31
+ BaseModelOutput,
32
+ BaseModelOutputWithPastAndCrossAttentions,
33
+ CausalLMOutputWithCrossAttentions,
34
+ Seq2SeqLMOutput,
35
+ Seq2SeqModelOutput,
36
+ )
37
+ from ...modeling_utils import PreTrainedModel
38
+ from ...utils import (
39
+ add_end_docstrings,
40
+ add_start_docstrings,
41
+ add_start_docstrings_to_model_forward,
42
+ logging,
43
+ replace_return_docstrings,
44
+ )
45
+ from .configuration_marian import MarianConfig
46
+
47
+
48
+ logger = logging.get_logger(__name__)
49
+
50
+ _CONFIG_FOR_DOC = "MarianConfig"
51
+ _CHECKPOINT_FOR_DOC = "Helsinki-NLP/opus-mt-en-de"
52
+
53
+
54
+ # Copied from transformers.models.bart.modeling_bart.shift_tokens_right
55
+ def shift_tokens_right(input_ids: torch.Tensor, pad_token_id: int, decoder_start_token_id: int):
56
+ """
57
+ Shift input ids one token to the right.
58
+ """
59
+ shifted_input_ids = input_ids.new_zeros(input_ids.shape)
60
+ shifted_input_ids[:, 1:] = input_ids[:, :-1].clone()
61
+ shifted_input_ids[:, 0] = decoder_start_token_id
62
+
63
+ if pad_token_id is None:
64
+ raise ValueError("self.model.config.pad_token_id has to be defined.")
65
+ # replace possible -100 values in labels by `pad_token_id`
66
+ shifted_input_ids.masked_fill_(shifted_input_ids == -100, pad_token_id)
67
+
68
+ return shifted_input_ids
69
+
70
+
71
+ class MarianSinusoidalPositionalEmbedding(nn.Embedding):
72
+ """This module produces sinusoidal positional embeddings of any length."""
73
+
74
+ def __init__(self, num_positions: int, embedding_dim: int, padding_idx: Optional[int] = None) -> None:
75
+ super().__init__(num_positions, embedding_dim)
76
+ self.weight = self._init_weight(self.weight)
77
+
78
+ @staticmethod
79
+ def _init_weight(out: nn.Parameter) -> nn.Parameter:
80
+ """
81
+ Identical to the XLM create_sinusoidal_embeddings except features are not interleaved. The cos features are in
82
+ the 2nd half of the vector. [dim // 2:]
83
+ """
84
+ n_pos, dim = out.shape
85
+ position_enc = np.array(
86
+ [[pos / np.power(10000, 2 * (j // 2) / dim) for j in range(dim)] for pos in range(n_pos)]
87
+ )
88
+ out.requires_grad = False # set early to avoid an error in pytorch-1.8+
89
+ sentinel = dim // 2 if dim % 2 == 0 else (dim // 2) + 1
90
+ out[:, 0:sentinel] = torch.FloatTensor(np.sin(position_enc[:, 0::2]))
91
+ out[:, sentinel:] = torch.FloatTensor(np.cos(position_enc[:, 1::2]))
92
+ out.detach_()
93
+ return out
94
+
95
+ @torch.no_grad()
96
+ def forward(self, input_ids_shape: torch.Size, past_key_values_length: int = 0) -> torch.Tensor:
97
+ """`input_ids_shape` is expected to be [bsz x seqlen]."""
98
+ bsz, seq_len = input_ids_shape[:2]
99
+ positions = torch.arange(
100
+ past_key_values_length, past_key_values_length + seq_len, dtype=torch.long, device=self.weight.device
101
+ )
102
+ return super().forward(positions)
103
+
104
+
105
+ # Copied from transformers.models.bart.modeling_bart.BartAttention with Bart->Marian
106
+ class MarianAttention(nn.Module):
107
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
108
+
109
+ def __init__(
110
+ self,
111
+ embed_dim: int,
112
+ num_heads: int,
113
+ dropout: float = 0.0,
114
+ is_decoder: bool = False,
115
+ bias: bool = True,
116
+ is_causal: bool = False,
117
+ config: Optional[MarianConfig] = None,
118
+ ):
119
+ super().__init__()
120
+ self.embed_dim = embed_dim
121
+ self.num_heads = num_heads
122
+ self.dropout = dropout
123
+ self.head_dim = embed_dim // num_heads
124
+ self.config = config
125
+
126
+ if (self.head_dim * num_heads) != self.embed_dim:
127
+ raise ValueError(
128
+ f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim}"
129
+ f" and `num_heads`: {num_heads})."
130
+ )
131
+ self.scaling = self.head_dim**-0.5
132
+ self.is_decoder = is_decoder
133
+ self.is_causal = is_causal
134
+
135
+ self.k_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
136
+ self.v_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
137
+ self.q_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
138
+ self.out_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
139
+
140
+ def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
141
+ return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
142
+
143
+ def forward(
144
+ self,
145
+ hidden_states: torch.Tensor,
146
+ key_value_states: Optional[torch.Tensor] = None,
147
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
148
+ attention_mask: Optional[torch.Tensor] = None,
149
+ layer_head_mask: Optional[torch.Tensor] = None,
150
+ output_attentions: bool = False,
151
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
152
+ """Input shape: Batch x Time x Channel"""
153
+
154
+ # if key_value_states are provided this layer is used as a cross-attention layer
155
+ # for the decoder
156
+ is_cross_attention = key_value_states is not None
157
+
158
+ bsz, tgt_len, _ = hidden_states.size()
159
+
160
+ # get query proj
161
+ query_states = self.q_proj(hidden_states) * self.scaling
162
+ # get key, value proj
163
+ # `past_key_value[0].shape[2] == key_value_states.shape[1]`
164
+ # is checking that the `sequence_length` of the `past_key_value` is the same as
165
+ # the provided `key_value_states` to support prefix tuning
166
+ if (
167
+ is_cross_attention
168
+ and past_key_value is not None
169
+ and past_key_value[0].shape[2] == key_value_states.shape[1]
170
+ ):
171
+ # reuse k,v, cross_attentions
172
+ key_states = past_key_value[0]
173
+ value_states = past_key_value[1]
174
+ elif is_cross_attention:
175
+ # cross_attentions
176
+ key_states = self._shape(self.k_proj(key_value_states), -1, bsz)
177
+ value_states = self._shape(self.v_proj(key_value_states), -1, bsz)
178
+ elif past_key_value is not None:
179
+ # reuse k, v, self_attention
180
+ key_states = self._shape(self.k_proj(hidden_states), -1, bsz)
181
+ value_states = self._shape(self.v_proj(hidden_states), -1, bsz)
182
+ key_states = torch.cat([past_key_value[0], key_states], dim=2)
183
+ value_states = torch.cat([past_key_value[1], value_states], dim=2)
184
+ else:
185
+ # self_attention
186
+ key_states = self._shape(self.k_proj(hidden_states), -1, bsz)
187
+ value_states = self._shape(self.v_proj(hidden_states), -1, bsz)
188
+
189
+ if self.is_decoder:
190
+ # if cross_attention save Tuple(torch.Tensor, torch.Tensor) of all cross attention key/value_states.
191
+ # Further calls to cross_attention layer can then reuse all cross-attention
192
+ # key/value_states (first "if" case)
193
+ # if uni-directional self-attention (decoder) save Tuple(torch.Tensor, torch.Tensor) of
194
+ # all previous decoder key/value_states. Further calls to uni-directional self-attention
195
+ # can concat previous decoder key/value_states to current projected key/value_states (third "elif" case)
196
+ # if encoder bi-directional self-attention `past_key_value` is always `None`
197
+ past_key_value = (key_states, value_states)
198
+
199
+ proj_shape = (bsz * self.num_heads, -1, self.head_dim)
200
+ query_states = self._shape(query_states, tgt_len, bsz).view(*proj_shape)
201
+ key_states = key_states.reshape(*proj_shape)
202
+ value_states = value_states.reshape(*proj_shape)
203
+
204
+ src_len = key_states.size(1)
205
+ attn_weights = torch.bmm(query_states, key_states.transpose(1, 2))
206
+
207
+ if attn_weights.size() != (bsz * self.num_heads, tgt_len, src_len):
208
+ raise ValueError(
209
+ f"Attention weights should be of size {(bsz * self.num_heads, tgt_len, src_len)}, but is"
210
+ f" {attn_weights.size()}"
211
+ )
212
+
213
+ if attention_mask is not None:
214
+ if attention_mask.size() != (bsz, 1, tgt_len, src_len):
215
+ raise ValueError(
216
+ f"Attention mask should be of size {(bsz, 1, tgt_len, src_len)}, but is {attention_mask.size()}"
217
+ )
218
+ attn_weights = attn_weights.view(bsz, self.num_heads, tgt_len, src_len) + attention_mask
219
+ attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len)
220
+
221
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1)
222
+
223
+ if layer_head_mask is not None:
224
+ if layer_head_mask.size() != (self.num_heads,):
225
+ raise ValueError(
226
+ f"Head mask for a single layer should be of size {(self.num_heads,)}, but is"
227
+ f" {layer_head_mask.size()}"
228
+ )
229
+ attn_weights = layer_head_mask.view(1, -1, 1, 1) * attn_weights.view(bsz, self.num_heads, tgt_len, src_len)
230
+ attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len)
231
+
232
+ if output_attentions:
233
+ # this operation is a bit awkward, but it's required to
234
+ # make sure that attn_weights keeps its gradient.
235
+ # In order to do so, attn_weights have to be reshaped
236
+ # twice and have to be reused in the following
237
+ attn_weights_reshaped = attn_weights.view(bsz, self.num_heads, tgt_len, src_len)
238
+ attn_weights = attn_weights_reshaped.view(bsz * self.num_heads, tgt_len, src_len)
239
+ else:
240
+ attn_weights_reshaped = None
241
+
242
+ attn_probs = nn.functional.dropout(attn_weights, p=self.dropout, training=self.training)
243
+
244
+ attn_output = torch.bmm(attn_probs, value_states)
245
+
246
+ if attn_output.size() != (bsz * self.num_heads, tgt_len, self.head_dim):
247
+ raise ValueError(
248
+ f"`attn_output` should be of size {(bsz * self.num_heads, tgt_len, self.head_dim)}, but is"
249
+ f" {attn_output.size()}"
250
+ )
251
+
252
+ attn_output = attn_output.view(bsz, self.num_heads, tgt_len, self.head_dim)
253
+ attn_output = attn_output.transpose(1, 2)
254
+
255
+ # Use the `embed_dim` from the config (stored in the class) rather than `hidden_state` because `attn_output` can be
256
+ # partitioned across GPUs when using tensor-parallelism.
257
+ attn_output = attn_output.reshape(bsz, tgt_len, self.embed_dim)
258
+
259
+ attn_output = self.out_proj(attn_output)
260
+
261
+ return attn_output, attn_weights_reshaped, past_key_value
262
+
263
+
264
+ # Copied from transformers.models.bart.modeling_bart.BartEncoderLayer with Bart->Marian, BART->MARIAN
265
+ class MarianEncoderLayer(nn.Module):
266
+ def __init__(self, config: MarianConfig):
267
+ super().__init__()
268
+ self.embed_dim = config.d_model
269
+
270
+ self.self_attn = MARIAN_ATTENTION_CLASSES[config._attn_implementation](
271
+ embed_dim=self.embed_dim,
272
+ num_heads=config.encoder_attention_heads,
273
+ dropout=config.attention_dropout,
274
+ config=config,
275
+ )
276
+ self.self_attn_layer_norm = nn.LayerNorm(self.embed_dim)
277
+ self.dropout = config.dropout
278
+ self.activation_fn = ACT2FN[config.activation_function]
279
+ self.activation_dropout = config.activation_dropout
280
+ self.fc1 = nn.Linear(self.embed_dim, config.encoder_ffn_dim)
281
+ self.fc2 = nn.Linear(config.encoder_ffn_dim, self.embed_dim)
282
+ self.final_layer_norm = nn.LayerNorm(self.embed_dim)
283
+
284
+ def forward(
285
+ self,
286
+ hidden_states: torch.FloatTensor,
287
+ attention_mask: torch.FloatTensor,
288
+ layer_head_mask: torch.FloatTensor,
289
+ output_attentions: Optional[bool] = False,
290
+ ) -> Tuple[torch.FloatTensor, Optional[torch.FloatTensor]]:
291
+ """
292
+ Args:
293
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
294
+ attention_mask (`torch.FloatTensor`): attention mask of size
295
+ `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
296
+ layer_head_mask (`torch.FloatTensor`): mask for attention heads in a given layer of size
297
+ `(encoder_attention_heads,)`.
298
+ output_attentions (`bool`, *optional*):
299
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
300
+ returned tensors for more detail.
301
+ """
302
+ residual = hidden_states
303
+ hidden_states, attn_weights, _ = self.self_attn(
304
+ hidden_states=hidden_states,
305
+ attention_mask=attention_mask,
306
+ layer_head_mask=layer_head_mask,
307
+ output_attentions=output_attentions,
308
+ )
309
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
310
+ hidden_states = residual + hidden_states
311
+ hidden_states = self.self_attn_layer_norm(hidden_states)
312
+
313
+ residual = hidden_states
314
+ hidden_states = self.activation_fn(self.fc1(hidden_states))
315
+ hidden_states = nn.functional.dropout(hidden_states, p=self.activation_dropout, training=self.training)
316
+ hidden_states = self.fc2(hidden_states)
317
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
318
+ hidden_states = residual + hidden_states
319
+ hidden_states = self.final_layer_norm(hidden_states)
320
+
321
+ if hidden_states.dtype == torch.float16 and (
322
+ torch.isinf(hidden_states).any() or torch.isnan(hidden_states).any()
323
+ ):
324
+ clamp_value = torch.finfo(hidden_states.dtype).max - 1000
325
+ hidden_states = torch.clamp(hidden_states, min=-clamp_value, max=clamp_value)
326
+
327
+ outputs = (hidden_states,)
328
+
329
+ if output_attentions:
330
+ outputs += (attn_weights,)
331
+
332
+ return outputs
333
+
334
+
335
+ MARIAN_ATTENTION_CLASSES = {"eager": MarianAttention}
336
+
337
+
338
+ # Copied from transformers.models.bart.modeling_bart.BartDecoderLayer with Bart->Marian, BART->MARIAN
339
+ class MarianDecoderLayer(nn.Module):
340
+ def __init__(self, config: MarianConfig):
341
+ super().__init__()
342
+ self.embed_dim = config.d_model
343
+
344
+ self.self_attn = MARIAN_ATTENTION_CLASSES[config._attn_implementation](
345
+ embed_dim=self.embed_dim,
346
+ num_heads=config.decoder_attention_heads,
347
+ dropout=config.attention_dropout,
348
+ is_decoder=True,
349
+ is_causal=True,
350
+ config=config,
351
+ )
352
+ self.dropout = config.dropout
353
+ self.activation_fn = ACT2FN[config.activation_function]
354
+ self.activation_dropout = config.activation_dropout
355
+
356
+ self.self_attn_layer_norm = nn.LayerNorm(self.embed_dim)
357
+ self.encoder_attn = MARIAN_ATTENTION_CLASSES[config._attn_implementation](
358
+ self.embed_dim,
359
+ config.decoder_attention_heads,
360
+ dropout=config.attention_dropout,
361
+ is_decoder=True,
362
+ config=config,
363
+ )
364
+ self.encoder_attn_layer_norm = nn.LayerNorm(self.embed_dim)
365
+ self.fc1 = nn.Linear(self.embed_dim, config.decoder_ffn_dim)
366
+ self.fc2 = nn.Linear(config.decoder_ffn_dim, self.embed_dim)
367
+ self.final_layer_norm = nn.LayerNorm(self.embed_dim)
368
+
369
+ def forward(
370
+ self,
371
+ hidden_states: torch.Tensor,
372
+ attention_mask: Optional[torch.Tensor] = None,
373
+ encoder_hidden_states: Optional[torch.Tensor] = None,
374
+ encoder_attention_mask: Optional[torch.Tensor] = None,
375
+ layer_head_mask: Optional[torch.Tensor] = None,
376
+ cross_attn_layer_head_mask: Optional[torch.Tensor] = None,
377
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
378
+ output_attentions: Optional[bool] = False,
379
+ use_cache: Optional[bool] = True,
380
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
381
+ """
382
+ Args:
383
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
384
+ attention_mask (`torch.FloatTensor`): attention mask of size
385
+ `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
386
+ encoder_hidden_states (`torch.FloatTensor`):
387
+ cross attention input to the layer of shape `(batch, seq_len, embed_dim)`
388
+ encoder_attention_mask (`torch.FloatTensor`): encoder attention mask of size
389
+ `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
390
+ layer_head_mask (`torch.FloatTensor`): mask for attention heads in a given layer of size
391
+ `(encoder_attention_heads,)`.
392
+ cross_attn_layer_head_mask (`torch.FloatTensor`): mask for cross-attention heads in a given layer of
393
+ size `(decoder_attention_heads,)`.
394
+ past_key_value (`Tuple(torch.FloatTensor)`): cached past key and value projection states
395
+ output_attentions (`bool`, *optional*):
396
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
397
+ returned tensors for more detail.
398
+ """
399
+ residual = hidden_states
400
+
401
+ # Self Attention
402
+ # decoder uni-directional self-attention cached key/values tuple is at positions 1,2
403
+ self_attn_past_key_value = past_key_value[:2] if past_key_value is not None else None
404
+ # add present self-attn cache to positions 1,2 of present_key_value tuple
405
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
406
+ hidden_states=hidden_states,
407
+ past_key_value=self_attn_past_key_value,
408
+ attention_mask=attention_mask,
409
+ layer_head_mask=layer_head_mask,
410
+ output_attentions=output_attentions,
411
+ )
412
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
413
+ hidden_states = residual + hidden_states
414
+ hidden_states = self.self_attn_layer_norm(hidden_states)
415
+
416
+ # Cross-Attention Block
417
+ cross_attn_present_key_value = None
418
+ cross_attn_weights = None
419
+ if encoder_hidden_states is not None:
420
+ residual = hidden_states
421
+
422
+ # cross_attn cached key/values tuple is at positions 3,4 of present_key_value tuple
423
+ cross_attn_past_key_value = past_key_value[-2:] if past_key_value is not None else None
424
+ hidden_states, cross_attn_weights, cross_attn_present_key_value = self.encoder_attn(
425
+ hidden_states=hidden_states,
426
+ key_value_states=encoder_hidden_states,
427
+ attention_mask=encoder_attention_mask,
428
+ layer_head_mask=cross_attn_layer_head_mask,
429
+ past_key_value=cross_attn_past_key_value,
430
+ output_attentions=output_attentions,
431
+ )
432
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
433
+ hidden_states = residual + hidden_states
434
+ hidden_states = self.encoder_attn_layer_norm(hidden_states)
435
+
436
+ # add cross-attn to positions 3,4 of present_key_value tuple
437
+ present_key_value = present_key_value + cross_attn_present_key_value
438
+
439
+ # Fully Connected
440
+ residual = hidden_states
441
+ hidden_states = self.activation_fn(self.fc1(hidden_states))
442
+ hidden_states = nn.functional.dropout(hidden_states, p=self.activation_dropout, training=self.training)
443
+ hidden_states = self.fc2(hidden_states)
444
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
445
+ hidden_states = residual + hidden_states
446
+ hidden_states = self.final_layer_norm(hidden_states)
447
+
448
+ outputs = (hidden_states,)
449
+
450
+ if output_attentions:
451
+ outputs += (self_attn_weights, cross_attn_weights)
452
+
453
+ if use_cache:
454
+ outputs += (present_key_value,)
455
+
456
+ return outputs
457
+
458
+
459
+ class MarianPreTrainedModel(PreTrainedModel):
460
+ config_class = MarianConfig
461
+ base_model_prefix = "model"
462
+ supports_gradient_checkpointing = True
463
+
464
+ def _init_weights(self, module: Union[nn.Linear, nn.Embedding, MarianSinusoidalPositionalEmbedding]):
465
+ std = self.config.init_std
466
+ if isinstance(module, nn.Linear):
467
+ module.weight.data.normal_(mean=0.0, std=std)
468
+ if module.bias is not None:
469
+ module.bias.data.zero_()
470
+ elif isinstance(module, MarianSinusoidalPositionalEmbedding):
471
+ pass
472
+ elif isinstance(module, nn.Embedding):
473
+ module.weight.data.normal_(mean=0.0, std=std)
474
+ if module.padding_idx is not None:
475
+ module.weight.data[module.padding_idx].zero_()
476
+
477
+ @property
478
+ def dummy_inputs(self):
479
+ pad_token = self.config.pad_token_id
480
+ input_ids = torch.tensor([[0, 6, 10, 4, 2], [0, 8, 12, 2, pad_token]], device=self.device)
481
+ dummy_inputs = {
482
+ "attention_mask": input_ids.ne(pad_token),
483
+ "input_ids": input_ids,
484
+ "decoder_input_ids": input_ids,
485
+ }
486
+ return dummy_inputs
487
+
488
+
489
+ MARIAN_START_DOCSTRING = r"""
490
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
491
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
492
+ etc.)
493
+
494
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
495
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
496
+ and behavior.
497
+
498
+ Parameters:
499
+ config ([`MarianConfig`]):
500
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
501
+ load the weights associated with the model, only the configuration. Check out the
502
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
503
+ """
504
+
505
+ MARIAN_GENERATION_EXAMPLE = r"""
506
+ Pytorch version of marian-nmt's transformer.h (c++). Designed for the OPUS-NMT translation checkpoints. Available
507
+ models are listed [here](https://huggingface.co/models?search=Helsinki-NLP).
508
+
509
+ Examples:
510
+
511
+ ```python
512
+ >>> from transformers import AutoTokenizer, MarianMTModel
513
+
514
+ >>> src = "fr" # source language
515
+ >>> trg = "en" # target language
516
+
517
+ >>> model_name = f"Helsinki-NLP/opus-mt-{src}-{trg}"
518
+ >>> model = MarianMTModel.from_pretrained(model_name)
519
+ >>> tokenizer = AutoTokenizer.from_pretrained(model_name)
520
+
521
+ >>> sample_text = "où est l'arrêt de bus ?"
522
+ >>> batch = tokenizer([sample_text], return_tensors="pt")
523
+
524
+ >>> generated_ids = model.generate(**batch)
525
+ >>> tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0]
526
+ "Where's the bus stop?"
527
+ ```
528
+ """
529
+
530
+ MARIAN_INPUTS_DOCSTRING = r"""
531
+ Args:
532
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
533
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
534
+ it.
535
+
536
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
537
+ [`PreTrainedTokenizer.__call__`] for details.
538
+
539
+ [What are input IDs?](../glossary#input-ids)
540
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
541
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
542
+
543
+ - 1 for tokens that are **not masked**,
544
+ - 0 for tokens that are **masked**.
545
+
546
+ [What are attention masks?](../glossary#attention-mask)
547
+ decoder_input_ids (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
548
+ Indices of decoder input sequence tokens in the vocabulary.
549
+
550
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
551
+ [`PreTrainedTokenizer.__call__`] for details.
552
+
553
+ [What are decoder input IDs?](../glossary#decoder-input-ids)
554
+
555
+ Marian uses the `pad_token_id` as the starting token for `decoder_input_ids` generation. If
556
+ `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
557
+ `past_key_values`).
558
+ decoder_attention_mask (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
559
+ Default behavior: generate a tensor that ignores pad tokens in `decoder_input_ids`. Causal mask will also
560
+ be used by default.
561
+ head_mask (`torch.Tensor` of shape `(encoder_layers, encoder_attention_heads)`, *optional*):
562
+ Mask to nullify selected heads of the attention modules in the encoder. Mask values selected in `[0, 1]`:
563
+
564
+ - 1 indicates the head is **not masked**,
565
+ - 0 indicates the head is **masked**.
566
+
567
+ decoder_head_mask (`torch.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
568
+ Mask to nullify selected heads of the attention modules in the decoder. Mask values selected in `[0, 1]`:
569
+
570
+ - 1 indicates the head is **not masked**,
571
+ - 0 indicates the head is **masked**.
572
+
573
+ cross_attn_head_mask (`torch.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
574
+ Mask to nullify selected heads of the cross-attention modules in the decoder. Mask values selected in `[0,
575
+ 1]`:
576
+
577
+ - 1 indicates the head is **not masked**,
578
+ - 0 indicates the head is **masked**.
579
+
580
+ encoder_outputs (`tuple(tuple(torch.FloatTensor)`, *optional*):
581
+ Tuple consists of (`last_hidden_state`, *optional*: `hidden_states`, *optional*: `attentions`)
582
+ `last_hidden_state` of shape `(batch_size, sequence_length, hidden_size)`, *optional*) is a sequence of
583
+ hidden-states at the output of the last layer of the encoder. Used in the cross-attention of the decoder.
584
+ past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
585
+ Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
586
+ `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of shape
587
+ `(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`.
588
+
589
+ Contains pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
590
+ blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.
591
+
592
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
593
+ don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
594
+ `decoder_input_ids` of shape `(batch_size, sequence_length)`.
595
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
596
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
597
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
598
+ model's internal embedding lookup matrix.
599
+ decoder_inputs_embeds (`torch.FloatTensor` of shape `(batch_size, target_sequence_length, hidden_size)`, *optional*):
600
+ Optionally, instead of passing `decoder_input_ids` you can choose to directly pass an embedded
601
+ representation. If `past_key_values` is used, optionally only the last `decoder_inputs_embeds` have to be
602
+ input (see `past_key_values`). This is useful if you want more control over how to convert
603
+ `decoder_input_ids` indices into associated vectors than the model's internal embedding lookup matrix.
604
+
605
+ If `decoder_input_ids` and `decoder_inputs_embeds` are both unset, `decoder_inputs_embeds` takes the value
606
+ of `inputs_embeds`.
607
+ use_cache (`bool`, *optional*):
608
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
609
+ `past_key_values`).
610
+ output_attentions (`bool`, *optional*):
611
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
612
+ tensors for more detail.
613
+ output_hidden_states (`bool`, *optional*):
614
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
615
+ more detail.
616
+ return_dict (`bool`, *optional*):
617
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
618
+ """
619
+
620
+
621
+ class MarianEncoder(MarianPreTrainedModel):
622
+ """
623
+ Transformer encoder consisting of *config.encoder_layers* self attention layers. Each layer is a
624
+ [`MarianEncoderLayer`].
625
+
626
+ Args:
627
+ config: MarianConfig
628
+ embed_tokens (nn.Embedding): output embedding
629
+ """
630
+
631
+ def __init__(self, config: MarianConfig, embed_tokens: Optional[nn.Embedding] = None):
632
+ super().__init__(config)
633
+
634
+ self.dropout = config.dropout
635
+ self.layerdrop = config.encoder_layerdrop
636
+
637
+ embed_dim = config.d_model
638
+ self.padding_idx = config.pad_token_id
639
+ self.max_source_positions = config.max_position_embeddings
640
+ self.embed_scale = math.sqrt(embed_dim) if config.scale_embedding else 1.0
641
+
642
+ if embed_tokens is not None:
643
+ self.embed_tokens = embed_tokens
644
+ else:
645
+ self.embed_tokens = nn.Embedding(config.vocab_size, embed_dim, self.padding_idx)
646
+
647
+ self.embed_positions = MarianSinusoidalPositionalEmbedding(
648
+ config.max_position_embeddings, embed_dim, self.padding_idx
649
+ )
650
+ self.layers = nn.ModuleList([MarianEncoderLayer(config) for _ in range(config.encoder_layers)])
651
+
652
+ self.gradient_checkpointing = False
653
+ # Initialize weights and apply final processing
654
+ self.post_init()
655
+
656
+ def get_input_embeddings(self):
657
+ return self.embed_tokens
658
+
659
+ def set_input_embeddings(self, value):
660
+ self.embed_tokens = value
661
+
662
+ def forward(
663
+ self,
664
+ input_ids: torch.LongTensor = None,
665
+ attention_mask: Optional[torch.LongTensor] = None,
666
+ head_mask: Optional[torch.Tensor] = None,
667
+ inputs_embeds: Optional[torch.FloatTensor] = None,
668
+ output_attentions: Optional[bool] = None,
669
+ output_hidden_states: Optional[bool] = None,
670
+ return_dict: Optional[bool] = None,
671
+ ) -> Union[Tuple[torch.Tensor], BaseModelOutput]:
672
+ r"""
673
+ Args:
674
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
675
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you
676
+ provide it.
677
+
678
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
679
+ [`PreTrainedTokenizer.__call__`] for details.
680
+
681
+ [What are input IDs?](../glossary#input-ids)
682
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
683
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
684
+
685
+ - 1 for tokens that are **not masked**,
686
+ - 0 for tokens that are **masked**.
687
+
688
+ [What are attention masks?](../glossary#attention-mask)
689
+ head_mask (`torch.Tensor` of shape `(encoder_layers, encoder_attention_heads)`, *optional*):
690
+ Mask to nullify selected heads of the attention modules. Mask values selected in `[0, 1]`:
691
+
692
+ - 1 indicates the head is **not masked**,
693
+ - 0 indicates the head is **masked**.
694
+
695
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
696
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation.
697
+ This is useful if you want more control over how to convert `input_ids` indices into associated vectors
698
+ than the model's internal embedding lookup matrix.
699
+ output_attentions (`bool`, *optional*):
700
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
701
+ returned tensors for more detail.
702
+ output_hidden_states (`bool`, *optional*):
703
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
704
+ for more detail.
705
+ return_dict (`bool`, *optional*):
706
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
707
+ """
708
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
709
+ output_hidden_states = (
710
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
711
+ )
712
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
713
+
714
+ # retrieve input_ids and inputs_embeds
715
+ if input_ids is not None and inputs_embeds is not None:
716
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
717
+ elif input_ids is not None:
718
+ self.warn_if_padding_and_no_attention_mask(input_ids, attention_mask)
719
+ input_shape = input_ids.size()
720
+ input_ids = input_ids.view(-1, input_shape[-1])
721
+ elif inputs_embeds is not None:
722
+ input_shape = inputs_embeds.size()[:-1]
723
+ else:
724
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
725
+
726
+ if inputs_embeds is None:
727
+ inputs_embeds = self.embed_tokens(input_ids) * self.embed_scale
728
+
729
+ embed_pos = self.embed_positions(input_shape)
730
+
731
+ hidden_states = inputs_embeds + embed_pos
732
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
733
+
734
+ # expand attention_mask
735
+ if attention_mask is not None:
736
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
737
+ attention_mask = _prepare_4d_attention_mask(attention_mask, inputs_embeds.dtype)
738
+
739
+ encoder_states = () if output_hidden_states else None
740
+ all_attentions = () if output_attentions else None
741
+
742
+ # check if head_mask has a correct number of layers specified if desired
743
+ if head_mask is not None:
744
+ assert head_mask.size()[0] == (
745
+ len(self.layers)
746
+ ), f"The head_mask should be specified for {len(self.layers)} layers, but it is for {head_mask.size()[0]}."
747
+ for idx, encoder_layer in enumerate(self.layers):
748
+ if output_hidden_states:
749
+ encoder_states = encoder_states + (hidden_states,)
750
+ # add LayerDrop (see https://arxiv.org/abs/1909.11556 for description)
751
+ to_drop = False
752
+ if self.training:
753
+ dropout_probability = torch.rand([])
754
+ if dropout_probability < self.layerdrop: # skip the layer
755
+ to_drop = True
756
+
757
+ if to_drop:
758
+ layer_outputs = (None, None)
759
+ else:
760
+ if self.gradient_checkpointing and self.training:
761
+ layer_outputs = self._gradient_checkpointing_func(
762
+ encoder_layer.__call__,
763
+ hidden_states,
764
+ attention_mask,
765
+ (head_mask[idx] if head_mask is not None else None),
766
+ output_attentions,
767
+ )
768
+ else:
769
+ layer_outputs = encoder_layer(
770
+ hidden_states,
771
+ attention_mask,
772
+ layer_head_mask=(head_mask[idx] if head_mask is not None else None),
773
+ output_attentions=output_attentions,
774
+ )
775
+
776
+ hidden_states = layer_outputs[0]
777
+
778
+ if output_attentions:
779
+ all_attentions = all_attentions + (layer_outputs[1],)
780
+
781
+ if output_hidden_states:
782
+ encoder_states = encoder_states + (hidden_states,)
783
+
784
+ if not return_dict:
785
+ return tuple(v for v in [hidden_states, encoder_states, all_attentions] if v is not None)
786
+ return BaseModelOutput(
787
+ last_hidden_state=hidden_states, hidden_states=encoder_states, attentions=all_attentions
788
+ )
789
+
790
+
791
+ class MarianDecoder(MarianPreTrainedModel):
792
+ """
793
+ Transformer decoder consisting of *config.decoder_layers* layers. Each layer is a [`MarianDecoderLayer`]
794
+
795
+ Args:
796
+ config: MarianConfig
797
+ embed_tokens (nn.Embedding): output embedding
798
+ """
799
+
800
+ def __init__(self, config: MarianConfig, embed_tokens: Optional[nn.Embedding] = None):
801
+ super().__init__(config)
802
+ self.dropout = config.dropout
803
+ self.layerdrop = config.decoder_layerdrop
804
+ self.padding_idx = config.pad_token_id
805
+ self.max_target_positions = config.max_position_embeddings
806
+ self.embed_scale = math.sqrt(config.d_model) if config.scale_embedding else 1.0
807
+
808
+ if embed_tokens is not None:
809
+ self.embed_tokens = embed_tokens
810
+ else:
811
+ self.embed_tokens = nn.Embedding(config.decoder_vocab_size, config.d_model, self.padding_idx)
812
+
813
+ self.embed_positions = MarianSinusoidalPositionalEmbedding(
814
+ config.max_position_embeddings, config.d_model, self.padding_idx
815
+ )
816
+ self.layers = nn.ModuleList([MarianDecoderLayer(config) for _ in range(config.decoder_layers)])
817
+
818
+ self.gradient_checkpointing = False
819
+ # Initialize weights and apply final processing
820
+ self.post_init()
821
+
822
+ def get_input_embeddings(self):
823
+ return self.embed_tokens
824
+
825
+ def set_input_embeddings(self, value):
826
+ self.embed_tokens = value
827
+
828
+ def forward(
829
+ self,
830
+ input_ids: torch.LongTensor = None,
831
+ attention_mask: Optional[torch.Tensor] = None,
832
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
833
+ encoder_attention_mask: Optional[torch.LongTensor] = None,
834
+ head_mask: Optional[torch.Tensor] = None,
835
+ cross_attn_head_mask: Optional[torch.Tensor] = None,
836
+ past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
837
+ inputs_embeds: Optional[torch.FloatTensor] = None,
838
+ use_cache: Optional[bool] = None,
839
+ output_attentions: Optional[bool] = None,
840
+ output_hidden_states: Optional[bool] = None,
841
+ return_dict: Optional[bool] = None,
842
+ ) -> Union[Tuple[torch.Tensor], BaseModelOutputWithPastAndCrossAttentions]:
843
+ r"""
844
+ Args:
845
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
846
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you
847
+ provide it.
848
+
849
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
850
+ [`PreTrainedTokenizer.__call__`] for details.
851
+
852
+ [What are input IDs?](../glossary#input-ids)
853
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
854
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
855
+
856
+ - 1 for tokens that are **not masked**,
857
+ - 0 for tokens that are **masked**.
858
+
859
+ [What are attention masks?](../glossary#attention-mask)
860
+ encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, encoder_sequence_length, hidden_size)`, *optional*):
861
+ Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention
862
+ of the decoder.
863
+ encoder_attention_mask (`torch.LongTensor` of shape `(batch_size, encoder_sequence_length)`, *optional*):
864
+ Mask to avoid performing cross-attention on padding tokens indices of encoder input_ids. Mask values
865
+ selected in `[0, 1]`:
866
+
867
+ - 1 for tokens that are **not masked**,
868
+ - 0 for tokens that are **masked**.
869
+
870
+ [What are attention masks?](../glossary#attention-mask)
871
+ head_mask (`torch.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
872
+ Mask to nullify selected heads of the attention modules. Mask values selected in `[0, 1]`:
873
+
874
+ - 1 indicates the head is **not masked**,
875
+ - 0 indicates the head is **masked**.
876
+
877
+ cross_attn_head_mask (`torch.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
878
+ Mask to nullify selected heads of the cross-attention modules in the decoder to avoid performing
879
+ cross-attention on hidden heads. Mask values selected in `[0, 1]`:
880
+
881
+ - 1 indicates the head is **not masked**,
882
+ - 0 indicates the head is **masked**.
883
+
884
+ past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
885
+ Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
886
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of
887
+ shape `(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`.
888
+
889
+ Contains pre-computed hidden-states (key and values in the self-attention blocks and in the
890
+ cross-attention blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.
891
+
892
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those
893
+ that don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of
894
+ all `decoder_input_ids` of shape `(batch_size, sequence_length)`.
895
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
896
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation.
897
+ This is useful if you want more control over how to convert `input_ids` indices into associated vectors
898
+ than the model's internal embedding lookup matrix.
899
+ output_attentions (`bool`, *optional*):
900
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
901
+ returned tensors for more detail.
902
+ output_hidden_states (`bool`, *optional*):
903
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
904
+ for more detail.
905
+ return_dict (`bool`, *optional*):
906
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
907
+ """
908
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
909
+ output_hidden_states = (
910
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
911
+ )
912
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
913
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
914
+
915
+ # retrieve input_ids and inputs_embeds
916
+ if input_ids is not None and inputs_embeds is not None:
917
+ raise ValueError("You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time")
918
+ elif input_ids is not None:
919
+ input_shape = input_ids.size()
920
+ input_ids = input_ids.view(-1, input_shape[-1])
921
+ elif inputs_embeds is not None:
922
+ input_shape = inputs_embeds.size()[:-1]
923
+ else:
924
+ raise ValueError("You have to specify either decoder_input_ids or decoder_inputs_embeds")
925
+
926
+ # past_key_values_length
927
+ past_key_values_length = past_key_values[0][0].shape[2] if past_key_values is not None else 0
928
+
929
+ if inputs_embeds is None:
930
+ inputs_embeds = self.embed_tokens(input_ids) * self.embed_scale
931
+
932
+ attention_mask = _prepare_4d_causal_attention_mask(
933
+ attention_mask, input_shape, inputs_embeds, past_key_values_length
934
+ )
935
+
936
+ # expand encoder attention mask
937
+ if encoder_hidden_states is not None and encoder_attention_mask is not None:
938
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
939
+ encoder_attention_mask = _prepare_4d_attention_mask(
940
+ encoder_attention_mask, inputs_embeds.dtype, tgt_len=input_shape[-1]
941
+ )
942
+
943
+ # embed positions
944
+ positions = self.embed_positions(input_shape, past_key_values_length)
945
+
946
+ hidden_states = inputs_embeds + positions
947
+
948
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
949
+
950
+ if self.gradient_checkpointing and self.training:
951
+ if use_cache:
952
+ logger.warning_once(
953
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
954
+ )
955
+ use_cache = False
956
+
957
+ # decoder layers
958
+ all_hidden_states = () if output_hidden_states else None
959
+ all_self_attns = () if output_attentions else None
960
+ all_cross_attentions = () if (output_attentions and encoder_hidden_states is not None) else None
961
+ next_decoder_cache = () if use_cache else None
962
+
963
+ # check if head_mask/cross_attn_head_mask has a correct number of layers specified if desired
964
+ for attn_mask, mask_name in zip([head_mask, cross_attn_head_mask], ["head_mask", "cross_attn_head_mask"]):
965
+ if attn_mask is not None:
966
+ assert attn_mask.size()[0] == (len(self.layers)), (
967
+ f"The `{mask_name}` should be specified for {len(self.layers)} layers, but it is for"
968
+ f" {head_mask.size()[0]}."
969
+ )
970
+ for idx, decoder_layer in enumerate(self.layers):
971
+ # add LayerDrop (see https://arxiv.org/abs/1909.11556 for description)
972
+ if output_hidden_states:
973
+ all_hidden_states += (hidden_states,)
974
+ if self.training:
975
+ dropout_probability = torch.rand([])
976
+ if dropout_probability < self.layerdrop:
977
+ continue
978
+
979
+ past_key_value = past_key_values[idx] if past_key_values is not None else None
980
+
981
+ if self.gradient_checkpointing and self.training:
982
+ layer_outputs = self._gradient_checkpointing_func(
983
+ decoder_layer.__call__,
984
+ hidden_states,
985
+ attention_mask,
986
+ encoder_hidden_states,
987
+ encoder_attention_mask,
988
+ head_mask[idx] if head_mask is not None else None,
989
+ cross_attn_head_mask[idx] if cross_attn_head_mask is not None else None,
990
+ None,
991
+ output_attentions,
992
+ use_cache,
993
+ )
994
+ else:
995
+ layer_outputs = decoder_layer(
996
+ hidden_states,
997
+ attention_mask=attention_mask,
998
+ encoder_hidden_states=encoder_hidden_states,
999
+ encoder_attention_mask=encoder_attention_mask,
1000
+ layer_head_mask=(head_mask[idx] if head_mask is not None else None),
1001
+ cross_attn_layer_head_mask=(
1002
+ cross_attn_head_mask[idx] if cross_attn_head_mask is not None else None
1003
+ ),
1004
+ past_key_value=past_key_value,
1005
+ output_attentions=output_attentions,
1006
+ use_cache=use_cache,
1007
+ )
1008
+ hidden_states = layer_outputs[0]
1009
+
1010
+ if use_cache:
1011
+ next_decoder_cache += (layer_outputs[3 if output_attentions else 1],)
1012
+
1013
+ if output_attentions:
1014
+ all_self_attns += (layer_outputs[1],)
1015
+
1016
+ if encoder_hidden_states is not None:
1017
+ all_cross_attentions += (layer_outputs[2],)
1018
+
1019
+ # add hidden states from the last decoder layer
1020
+ if output_hidden_states:
1021
+ all_hidden_states += (hidden_states,)
1022
+
1023
+ next_cache = next_decoder_cache if use_cache else None
1024
+ if not return_dict:
1025
+ return tuple(
1026
+ v
1027
+ for v in [hidden_states, next_cache, all_hidden_states, all_self_attns, all_cross_attentions]
1028
+ if v is not None
1029
+ )
1030
+ return BaseModelOutputWithPastAndCrossAttentions(
1031
+ last_hidden_state=hidden_states,
1032
+ past_key_values=next_cache,
1033
+ hidden_states=all_hidden_states,
1034
+ attentions=all_self_attns,
1035
+ cross_attentions=all_cross_attentions,
1036
+ )
1037
+
1038
+
1039
+ @add_start_docstrings(
1040
+ "The bare Marian Model outputting raw hidden-states without any specific head on top.", MARIAN_START_DOCSTRING
1041
+ )
1042
+ class MarianModel(MarianPreTrainedModel):
1043
+ _tied_weights_keys = ["encoder.embed_tokens.weight", "decoder.embed_tokens.weight"]
1044
+
1045
+ def __init__(self, config: MarianConfig):
1046
+ super().__init__(config)
1047
+
1048
+ padding_idx, vocab_size = config.pad_token_id, config.vocab_size
1049
+
1050
+ # We always use self.shared for token embeddings to ensure compatibility with all marian models
1051
+ self.shared = nn.Embedding(vocab_size, config.d_model, padding_idx)
1052
+ if self.config.share_encoder_decoder_embeddings:
1053
+ encoder_embed_tokens = decoder_embed_tokens = self.shared
1054
+ else:
1055
+ # Since the embeddings are not shared, deepcopy the embeddings here for encoder
1056
+ # and decoder to make sure they are not tied.
1057
+ encoder_embed_tokens = copy.deepcopy(self.shared)
1058
+ decoder_embed_tokens = copy.deepcopy(self.shared)
1059
+ self.shared = None
1060
+
1061
+ self.encoder = MarianEncoder(config, encoder_embed_tokens)
1062
+ self.decoder = MarianDecoder(config, decoder_embed_tokens)
1063
+
1064
+ # Initialize weights and apply final processing
1065
+ self.post_init()
1066
+
1067
+ def get_input_embeddings(self):
1068
+ # This will return shared embeddings if they are shared else specific to encoder.
1069
+ return self.get_encoder().get_input_embeddings()
1070
+
1071
+ def set_input_embeddings(self, value):
1072
+ if self.config.share_encoder_decoder_embeddings:
1073
+ self.shared = value
1074
+ self.encoder.embed_tokens = self.shared
1075
+ self.decoder.embed_tokens = self.shared
1076
+ else: # if not shared only set encoder embeedings
1077
+ self.encoder.embed_tokens = value
1078
+
1079
+ def get_decoder_input_embeddings(self):
1080
+ if self.config.share_encoder_decoder_embeddings:
1081
+ raise ValueError(
1082
+ "`get_decoder_input_embeddings` should not be called if `config.share_encoder_decoder_embeddings` "
1083
+ "is `True`. Please use `get_input_embeddings` instead."
1084
+ )
1085
+ return self.get_decoder().get_input_embeddings()
1086
+
1087
+ def set_decoder_input_embeddings(self, value):
1088
+ if self.config.share_encoder_decoder_embeddings:
1089
+ raise ValueError(
1090
+ "`config.share_encoder_decoder_embeddings` is set to `True` meaning the decoder input embeddings "
1091
+ "are shared with the encoder. In order to set the decoder input embeddings, you should simply set "
1092
+ "the encoder input embeddings by calling `set_input_embeddings` with the appropriate embeddings."
1093
+ )
1094
+ self.decoder.embed_tokens = value
1095
+
1096
+ def get_encoder(self):
1097
+ return self.encoder
1098
+
1099
+ def get_decoder(self):
1100
+ return self.decoder
1101
+
1102
+ def resize_decoder_token_embeddings(self, new_num_tokens: int) -> nn.Embedding:
1103
+ if self.config.share_encoder_decoder_embeddings:
1104
+ raise ValueError(
1105
+ "`resize_decoder_token_embeddings` should not be called if `config.share_encoder_decoder_embeddings` "
1106
+ "is `True`. Please use `resize_token_embeddings` instead."
1107
+ )
1108
+
1109
+ old_embeddings = self.get_decoder_input_embeddings()
1110
+ new_embeddings = self._get_resized_embeddings(old_embeddings, new_num_tokens)
1111
+ self.set_decoder_input_embeddings(new_embeddings)
1112
+
1113
+ model_embeds = self.get_decoder_input_embeddings()
1114
+
1115
+ if new_num_tokens is None:
1116
+ return model_embeds
1117
+
1118
+ # Update base model and current model config
1119
+ self.config.decoder_vocab_size = new_num_tokens
1120
+
1121
+ # Tie weights again if needed
1122
+ self.tie_weights()
1123
+
1124
+ return model_embeds
1125
+
1126
+ @add_start_docstrings_to_model_forward(MARIAN_INPUTS_DOCSTRING)
1127
+ @replace_return_docstrings(output_type=Seq2SeqModelOutput, config_class=_CONFIG_FOR_DOC)
1128
+ def forward(
1129
+ self,
1130
+ input_ids: torch.LongTensor = None,
1131
+ attention_mask: Optional[torch.Tensor] = None,
1132
+ decoder_input_ids: Optional[torch.LongTensor] = None,
1133
+ decoder_attention_mask: Optional[torch.Tensor] = None,
1134
+ head_mask: Optional[torch.Tensor] = None,
1135
+ decoder_head_mask: Optional[torch.Tensor] = None,
1136
+ cross_attn_head_mask: Optional[torch.Tensor] = None,
1137
+ encoder_outputs: Optional[Union[Tuple[torch.Tensor], BaseModelOutput]] = None,
1138
+ past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
1139
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1140
+ decoder_inputs_embeds: Optional[torch.FloatTensor] = None,
1141
+ use_cache: Optional[bool] = None,
1142
+ output_attentions: Optional[bool] = None,
1143
+ output_hidden_states: Optional[bool] = None,
1144
+ return_dict: Optional[bool] = None,
1145
+ ) -> Seq2SeqModelOutput:
1146
+ r"""
1147
+ Returns:
1148
+
1149
+ Example:
1150
+
1151
+ ```python
1152
+ >>> from transformers import AutoTokenizer, MarianModel
1153
+
1154
+ >>> tokenizer = AutoTokenizer.from_pretrained("Helsinki-NLP/opus-mt-en-de")
1155
+ >>> model = MarianModel.from_pretrained("Helsinki-NLP/opus-mt-en-de")
1156
+
1157
+ >>> inputs = tokenizer("Studies have been shown that owning a dog is good for you", return_tensors="pt")
1158
+ >>> decoder_inputs = tokenizer(
1159
+ ... "<pad> Studien haben gezeigt dass es hilfreich ist einen Hund zu besitzen",
1160
+ ... return_tensors="pt",
1161
+ ... add_special_tokens=False,
1162
+ ... )
1163
+ >>> outputs = model(input_ids=inputs.input_ids, decoder_input_ids=decoder_inputs.input_ids)
1164
+
1165
+ >>> last_hidden_states = outputs.last_hidden_state
1166
+ >>> list(last_hidden_states.shape)
1167
+ [1, 26, 512]
1168
+ ```"""
1169
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1170
+ output_hidden_states = (
1171
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1172
+ )
1173
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
1174
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1175
+
1176
+ if encoder_outputs is None:
1177
+ encoder_outputs = self.encoder(
1178
+ input_ids=input_ids,
1179
+ attention_mask=attention_mask,
1180
+ head_mask=head_mask,
1181
+ inputs_embeds=inputs_embeds,
1182
+ output_attentions=output_attentions,
1183
+ output_hidden_states=output_hidden_states,
1184
+ return_dict=return_dict,
1185
+ )
1186
+ # If the user passed a tuple for encoder_outputs, we wrap it in a BaseModelOutput when return_dict=True
1187
+ elif return_dict and not isinstance(encoder_outputs, BaseModelOutput):
1188
+ encoder_outputs = BaseModelOutput(
1189
+ last_hidden_state=encoder_outputs[0],
1190
+ hidden_states=encoder_outputs[1] if len(encoder_outputs) > 1 else None,
1191
+ attentions=encoder_outputs[2] if len(encoder_outputs) > 2 else None,
1192
+ )
1193
+
1194
+ # decoder outputs consists of (dec_features, past_key_value, dec_hidden, dec_attn)
1195
+ decoder_outputs = self.decoder(
1196
+ input_ids=decoder_input_ids,
1197
+ attention_mask=decoder_attention_mask,
1198
+ encoder_hidden_states=encoder_outputs[0],
1199
+ encoder_attention_mask=attention_mask,
1200
+ head_mask=decoder_head_mask,
1201
+ cross_attn_head_mask=cross_attn_head_mask,
1202
+ past_key_values=past_key_values,
1203
+ inputs_embeds=decoder_inputs_embeds,
1204
+ use_cache=use_cache,
1205
+ output_attentions=output_attentions,
1206
+ output_hidden_states=output_hidden_states,
1207
+ return_dict=return_dict,
1208
+ )
1209
+
1210
+ if not return_dict:
1211
+ return decoder_outputs + encoder_outputs
1212
+
1213
+ return Seq2SeqModelOutput(
1214
+ last_hidden_state=decoder_outputs.last_hidden_state,
1215
+ past_key_values=decoder_outputs.past_key_values,
1216
+ decoder_hidden_states=decoder_outputs.hidden_states,
1217
+ decoder_attentions=decoder_outputs.attentions,
1218
+ cross_attentions=decoder_outputs.cross_attentions,
1219
+ encoder_last_hidden_state=encoder_outputs.last_hidden_state,
1220
+ encoder_hidden_states=encoder_outputs.hidden_states,
1221
+ encoder_attentions=encoder_outputs.attentions,
1222
+ )
1223
+
1224
+
1225
+ @add_start_docstrings(
1226
+ "The Marian Model with a language modeling head. Can be used for summarization.", MARIAN_START_DOCSTRING
1227
+ )
1228
+ class MarianMTModel(MarianPreTrainedModel, GenerationMixin):
1229
+ base_model_prefix = "model"
1230
+ _keys_to_ignore_on_load_missing = [
1231
+ "final_logits_bias",
1232
+ "encoder.embed_positions.weight",
1233
+ "decoder.embed_positions.weight",
1234
+ ]
1235
+ _keys_to_ignore_on_save = ["model.encoder.embed_positions.weight", "model.decoder.embed_positions.weight"]
1236
+ _tied_weights_keys = ["model.encoder.embed_tokens.weight", "model.decoder.embed_tokens.weight", "lm_head.weight"]
1237
+
1238
+ def __init__(self, config: MarianConfig):
1239
+ super().__init__(config)
1240
+ self.model = MarianModel(config)
1241
+
1242
+ target_vocab_size = config.vocab_size if config.share_encoder_decoder_embeddings else config.decoder_vocab_size
1243
+ self.register_buffer("final_logits_bias", torch.zeros((1, target_vocab_size)))
1244
+ self.lm_head = nn.Linear(config.d_model, target_vocab_size, bias=False)
1245
+
1246
+ # Initialize weights and apply final processing
1247
+ self.post_init()
1248
+
1249
+ def get_encoder(self):
1250
+ return self.model.get_encoder()
1251
+
1252
+ def get_decoder(self):
1253
+ return self.model.get_decoder()
1254
+
1255
+ def resize_token_embeddings(
1256
+ self, new_num_tokens: int, pad_to_multiple_of: Optional[int] = None, mean_resizing: bool = True
1257
+ ) -> nn.Embedding:
1258
+ new_embeddings = super().resize_token_embeddings(new_num_tokens, pad_to_multiple_of, mean_resizing)
1259
+ if self.config.share_encoder_decoder_embeddings:
1260
+ self._resize_final_logits_bias(new_num_tokens)
1261
+ return new_embeddings
1262
+
1263
+ # NOTE: `_resize_token_embeddings` was rewriten in the base class, *args exists to absorb the extra arg
1264
+ def _resize_token_embeddings(self, new_num_tokens: int, pad_to_multiple_of=None, *args) -> nn.Embedding:
1265
+ old_embeddings = self.get_input_embeddings()
1266
+ new_embeddings = self._get_resized_embeddings(old_embeddings, new_num_tokens, pad_to_multiple_of)
1267
+ self.set_input_embeddings(new_embeddings)
1268
+
1269
+ new_num_tokens = new_embeddings.weight.shape[0]
1270
+ # update config.decoder_vocab_size if embeddings are tied
1271
+ if self.config.share_encoder_decoder_embeddings:
1272
+ self.config.decoder_vocab_size = new_num_tokens
1273
+
1274
+ # if word embeddings are not tied, make sure that lm head is resized as well
1275
+ if (
1276
+ self.config.share_encoder_decoder_embeddings
1277
+ and self.get_output_embeddings() is not None
1278
+ and not self.config.tie_word_embeddings
1279
+ ):
1280
+ old_lm_head = self.get_output_embeddings()
1281
+ new_lm_head = self._get_resized_lm_head(old_lm_head, new_num_tokens)
1282
+ self.set_output_embeddings(new_lm_head)
1283
+
1284
+ return self.get_input_embeddings()
1285
+
1286
+ def resize_decoder_token_embeddings(self, new_num_tokens):
1287
+ if self.config.share_encoder_decoder_embeddings:
1288
+ raise ValueError(
1289
+ "`resize_decoder_token_embeddings` should not be called if `config.share_encoder_decoder_embeddings` "
1290
+ "is `True`. Please use `resize_token_embeddings` instead."
1291
+ )
1292
+
1293
+ old_embeddings = self.model.get_decoder_input_embeddings()
1294
+ new_embeddings = self._get_resized_embeddings(old_embeddings, new_num_tokens)
1295
+ self.model.set_decoder_input_embeddings(new_embeddings)
1296
+
1297
+ # if word embeddings are not tied, make sure that lm head is resized as well
1298
+ if self.get_output_embeddings() is not None and not self.config.tie_word_embeddings:
1299
+ old_lm_head = self.get_output_embeddings()
1300
+ new_lm_head = self._get_resized_lm_head(old_lm_head, new_num_tokens)
1301
+ self.set_output_embeddings(new_lm_head)
1302
+
1303
+ model_embeds = self.model.get_decoder_input_embeddings()
1304
+
1305
+ if new_num_tokens is None:
1306
+ return model_embeds
1307
+
1308
+ # Update base model and current model config
1309
+ self.config.decoder_vocab_size = new_num_tokens
1310
+
1311
+ # Tie weights again if needed
1312
+ self.tie_weights()
1313
+
1314
+ self._resize_final_logits_bias(new_num_tokens)
1315
+
1316
+ return model_embeds
1317
+
1318
+ def _resize_final_logits_bias(self, new_num_tokens: int) -> None:
1319
+ old_num_tokens = self.final_logits_bias.shape[-1]
1320
+ if new_num_tokens <= old_num_tokens:
1321
+ new_bias = self.final_logits_bias[:, :new_num_tokens]
1322
+ else:
1323
+ extra_bias = torch.zeros((1, new_num_tokens - old_num_tokens), device=self.final_logits_bias.device)
1324
+ new_bias = torch.cat([self.final_logits_bias, extra_bias], dim=1)
1325
+ self.register_buffer("final_logits_bias", new_bias)
1326
+
1327
+ def get_output_embeddings(self):
1328
+ return self.lm_head
1329
+
1330
+ def set_output_embeddings(self, new_embeddings: nn.Embedding):
1331
+ self.lm_head = new_embeddings
1332
+
1333
+ def tie_weights(self):
1334
+ """
1335
+ Tie the weights between the input embeddings and the output embeddings.
1336
+
1337
+ If the `torchscript` flag is set in the configuration, can't handle parameter sharing so we are cloning the
1338
+ weights instead.
1339
+ """
1340
+ output_embeddings = self.get_output_embeddings()
1341
+ if output_embeddings is not None and getattr(self.config, "tie_word_embeddings", True):
1342
+ # if embeddings are shared this will return shared embeddings otherwise decoder embed_tokens
1343
+ word_embeddings = self.get_decoder().get_input_embeddings()
1344
+ self._tie_or_clone_weights(output_embeddings, word_embeddings)
1345
+
1346
+ if getattr(self.config, "is_encoder_decoder", False) and getattr(self.config, "tie_encoder_decoder", False):
1347
+ if hasattr(self, self.base_model_prefix):
1348
+ self = getattr(self, self.base_model_prefix)
1349
+ tied_weights = self._tie_encoder_decoder_weights(
1350
+ self.encoder, self.decoder, self.base_model_prefix, "encoder"
1351
+ )
1352
+ # Setting a dynamic variable instead of `_tied_weights_keys` because it's a class
1353
+ # attributed not an instance member, therefore modifying it will modify the entire class
1354
+ # Leading to issues on subsequent calls by different tests or subsequent calls.
1355
+ self._dynamic_tied_weights_keys = tied_weights
1356
+
1357
+ for module in self.modules():
1358
+ if hasattr(module, "_tie_weights"):
1359
+ module._tie_weights()
1360
+
1361
+ @add_start_docstrings_to_model_forward(MARIAN_INPUTS_DOCSTRING)
1362
+ @replace_return_docstrings(output_type=Seq2SeqLMOutput, config_class=_CONFIG_FOR_DOC)
1363
+ @add_end_docstrings(MARIAN_GENERATION_EXAMPLE)
1364
+ def forward(
1365
+ self,
1366
+ input_ids: torch.LongTensor = None,
1367
+ attention_mask: Optional[torch.Tensor] = None,
1368
+ decoder_input_ids: Optional[torch.LongTensor] = None,
1369
+ decoder_attention_mask: Optional[torch.Tensor] = None,
1370
+ head_mask: Optional[torch.Tensor] = None,
1371
+ decoder_head_mask: Optional[torch.Tensor] = None,
1372
+ cross_attn_head_mask: Optional[torch.Tensor] = None,
1373
+ encoder_outputs: Optional[Union[Tuple[torch.Tensor], BaseModelOutput]] = None,
1374
+ past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
1375
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1376
+ decoder_inputs_embeds: Optional[torch.FloatTensor] = None,
1377
+ labels: Optional[torch.LongTensor] = None,
1378
+ use_cache: Optional[bool] = None,
1379
+ output_attentions: Optional[bool] = None,
1380
+ output_hidden_states: Optional[bool] = None,
1381
+ return_dict: Optional[bool] = None,
1382
+ ) -> Seq2SeqLMOutput:
1383
+ r"""
1384
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1385
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1386
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1387
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1388
+
1389
+ Returns:
1390
+
1391
+ """
1392
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1393
+
1394
+ if labels is not None:
1395
+ if use_cache:
1396
+ logger.warning("The `use_cache` argument is changed to `False` since `labels` is provided.")
1397
+ use_cache = False
1398
+ if decoder_input_ids is None and decoder_inputs_embeds is None:
1399
+ decoder_input_ids = shift_tokens_right(
1400
+ labels, self.config.pad_token_id, self.config.decoder_start_token_id
1401
+ )
1402
+
1403
+ outputs = self.model(
1404
+ input_ids,
1405
+ attention_mask=attention_mask,
1406
+ decoder_input_ids=decoder_input_ids,
1407
+ encoder_outputs=encoder_outputs,
1408
+ decoder_attention_mask=decoder_attention_mask,
1409
+ head_mask=head_mask,
1410
+ decoder_head_mask=decoder_head_mask,
1411
+ cross_attn_head_mask=cross_attn_head_mask,
1412
+ past_key_values=past_key_values,
1413
+ inputs_embeds=inputs_embeds,
1414
+ decoder_inputs_embeds=decoder_inputs_embeds,
1415
+ use_cache=use_cache,
1416
+ output_attentions=output_attentions,
1417
+ output_hidden_states=output_hidden_states,
1418
+ return_dict=return_dict,
1419
+ )
1420
+ lm_logits = self.lm_head(outputs[0]) + self.final_logits_bias
1421
+
1422
+ masked_lm_loss = None
1423
+ if labels is not None:
1424
+ loss_fct = CrossEntropyLoss()
1425
+ masked_lm_loss = loss_fct(lm_logits.view(-1, self.config.decoder_vocab_size), labels.view(-1))
1426
+
1427
+ if not return_dict:
1428
+ output = (lm_logits,) + outputs[1:]
1429
+ return ((masked_lm_loss,) + output) if masked_lm_loss is not None else output
1430
+
1431
+ return Seq2SeqLMOutput(
1432
+ loss=masked_lm_loss,
1433
+ logits=lm_logits,
1434
+ past_key_values=outputs.past_key_values,
1435
+ decoder_hidden_states=outputs.decoder_hidden_states,
1436
+ decoder_attentions=outputs.decoder_attentions,
1437
+ cross_attentions=outputs.cross_attentions,
1438
+ encoder_last_hidden_state=outputs.encoder_last_hidden_state,
1439
+ encoder_hidden_states=outputs.encoder_hidden_states,
1440
+ encoder_attentions=outputs.encoder_attentions,
1441
+ )
1442
+
1443
+ def prepare_decoder_input_ids_from_labels(self, labels: torch.Tensor):
1444
+ return shift_tokens_right(labels, self.config.pad_token_id, self.config.decoder_start_token_id)
1445
+
1446
+ @staticmethod
1447
+ def _reorder_cache(past_key_values, beam_idx):
1448
+ reordered_past = ()
1449
+ for layer_past in past_key_values:
1450
+ # cached cross_attention states don't have to be reordered -> they are always the same
1451
+ reordered_past += (
1452
+ tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past[:2])
1453
+ + layer_past[2:],
1454
+ )
1455
+ return reordered_past
1456
+
1457
+
1458
+ # Copied from transformers.models.bart.modeling_bart.BartDecoderWrapper with Bart->Marian
1459
+ class MarianDecoderWrapper(MarianPreTrainedModel):
1460
+ """
1461
+ This wrapper class is a helper class to correctly load pretrained checkpoints when the causal language model is
1462
+ used in combination with the [`EncoderDecoderModel`] framework.
1463
+ """
1464
+
1465
+ def __init__(self, config):
1466
+ super().__init__(config)
1467
+ self.decoder = MarianDecoder(config)
1468
+
1469
+ def forward(self, *args, **kwargs):
1470
+ return self.decoder(*args, **kwargs)
1471
+
1472
+
1473
+ # Copied from transformers.models.bart.modeling_bart.BartForCausalLM with Bart->Marian, facebook/bart-base->Helsinki-NLP/opus-mt-fr-en
1474
+ class MarianForCausalLM(MarianPreTrainedModel, GenerationMixin):
1475
+ _tied_weights_keys = ["lm_head.weight"]
1476
+
1477
+ def __init__(self, config):
1478
+ config = copy.deepcopy(config)
1479
+ config.is_decoder = True
1480
+ config.is_encoder_decoder = False
1481
+ super().__init__(config)
1482
+ self.model = MarianDecoderWrapper(config)
1483
+
1484
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1485
+
1486
+ # Initialize weights and apply final processing
1487
+ self.post_init()
1488
+
1489
+ def get_input_embeddings(self):
1490
+ return self.model.decoder.embed_tokens
1491
+
1492
+ def set_input_embeddings(self, value):
1493
+ self.model.decoder.embed_tokens = value
1494
+
1495
+ def get_output_embeddings(self):
1496
+ return self.lm_head
1497
+
1498
+ def set_output_embeddings(self, new_embeddings):
1499
+ self.lm_head = new_embeddings
1500
+
1501
+ def set_decoder(self, decoder):
1502
+ self.model.decoder = decoder
1503
+
1504
+ def get_decoder(self):
1505
+ return self.model.decoder
1506
+
1507
+ @replace_return_docstrings(output_type=CausalLMOutputWithCrossAttentions, config_class=_CONFIG_FOR_DOC)
1508
+ def forward(
1509
+ self,
1510
+ input_ids: torch.LongTensor = None,
1511
+ attention_mask: Optional[torch.Tensor] = None,
1512
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
1513
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
1514
+ head_mask: Optional[torch.Tensor] = None,
1515
+ cross_attn_head_mask: Optional[torch.Tensor] = None,
1516
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1517
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1518
+ labels: Optional[torch.LongTensor] = None,
1519
+ use_cache: Optional[bool] = None,
1520
+ output_attentions: Optional[bool] = None,
1521
+ output_hidden_states: Optional[bool] = None,
1522
+ return_dict: Optional[bool] = None,
1523
+ ) -> Union[Tuple, CausalLMOutputWithCrossAttentions]:
1524
+ r"""
1525
+ Args:
1526
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
1527
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you
1528
+ provide it.
1529
+
1530
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
1531
+ [`PreTrainedTokenizer.__call__`] for details.
1532
+
1533
+ [What are input IDs?](../glossary#input-ids)
1534
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
1535
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
1536
+
1537
+ - 1 for tokens that are **not masked**,
1538
+ - 0 for tokens that are **masked**.
1539
+
1540
+ [What are attention masks?](../glossary#attention-mask)
1541
+ encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
1542
+ Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention
1543
+ if the model is configured as a decoder.
1544
+ encoder_attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
1545
+ Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used
1546
+ in the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`:
1547
+ head_mask (`torch.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
1548
+ Mask to nullify selected heads of the attention modules. Mask values selected in `[0, 1]`:
1549
+
1550
+ - 1 indicates the head is **not masked**,
1551
+ - 0 indicates the head is **masked**.
1552
+
1553
+ cross_attn_head_mask (`torch.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
1554
+ Mask to nullify selected heads of the cross-attention modules. Mask values selected in `[0, 1]`:
1555
+
1556
+ - 1 indicates the head is **not masked**,
1557
+ - 0 indicates the head is **masked**.
1558
+
1559
+ past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
1560
+ Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
1561
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of
1562
+ shape `(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`. The two additional
1563
+ tensors are only required when the model is used as a decoder in a Sequence to Sequence model.
1564
+
1565
+ Contains pre-computed hidden-states (key and values in the self-attention blocks and in the
1566
+ cross-attention blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.
1567
+
1568
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those
1569
+ that don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of
1570
+ all `decoder_input_ids` of shape `(batch_size, sequence_length)`.
1571
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1572
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1573
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1574
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1575
+ use_cache (`bool`, *optional*):
1576
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
1577
+ (see `past_key_values`).
1578
+
1579
+ - 1 for tokens that are **not masked**,
1580
+ - 0 for tokens that are **masked**.
1581
+ output_attentions (`bool`, *optional*):
1582
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
1583
+ returned tensors for more detail.
1584
+ output_hidden_states (`bool`, *optional*):
1585
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
1586
+ for more detail.
1587
+ return_dict (`bool`, *optional*):
1588
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
1589
+
1590
+ Returns:
1591
+
1592
+ Example:
1593
+
1594
+ ```python
1595
+ >>> from transformers import AutoTokenizer, MarianForCausalLM
1596
+
1597
+ >>> tokenizer = AutoTokenizer.from_pretrained("Helsinki-NLP/opus-mt-fr-en")
1598
+ >>> model = MarianForCausalLM.from_pretrained("Helsinki-NLP/opus-mt-fr-en", add_cross_attention=False)
1599
+ >>> assert model.config.is_decoder, f"{model.__class__} has to be configured as a decoder."
1600
+ >>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")
1601
+ >>> outputs = model(**inputs)
1602
+
1603
+ >>> logits = outputs.logits
1604
+ >>> expected_shape = [1, inputs.input_ids.shape[-1], model.config.vocab_size]
1605
+ >>> list(logits.shape) == expected_shape
1606
+ True
1607
+ ```"""
1608
+
1609
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1610
+ output_hidden_states = (
1611
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1612
+ )
1613
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1614
+
1615
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1616
+ outputs = self.model.decoder(
1617
+ input_ids=input_ids,
1618
+ attention_mask=attention_mask,
1619
+ encoder_hidden_states=encoder_hidden_states,
1620
+ encoder_attention_mask=encoder_attention_mask,
1621
+ head_mask=head_mask,
1622
+ cross_attn_head_mask=cross_attn_head_mask,
1623
+ past_key_values=past_key_values,
1624
+ inputs_embeds=inputs_embeds,
1625
+ use_cache=use_cache,
1626
+ output_attentions=output_attentions,
1627
+ output_hidden_states=output_hidden_states,
1628
+ return_dict=return_dict,
1629
+ )
1630
+
1631
+ logits = self.lm_head(outputs[0])
1632
+
1633
+ loss = None
1634
+ if labels is not None:
1635
+ labels = labels.to(logits.device)
1636
+ loss_fct = CrossEntropyLoss()
1637
+ loss = loss_fct(logits.view(-1, self.config.vocab_size), labels.view(-1))
1638
+
1639
+ if not return_dict:
1640
+ output = (logits,) + outputs[1:]
1641
+ return (loss,) + output if loss is not None else output
1642
+
1643
+ return CausalLMOutputWithCrossAttentions(
1644
+ loss=loss,
1645
+ logits=logits,
1646
+ past_key_values=outputs.past_key_values,
1647
+ hidden_states=outputs.hidden_states,
1648
+ attentions=outputs.attentions,
1649
+ cross_attentions=outputs.cross_attentions,
1650
+ )
1651
+
1652
+ @staticmethod
1653
+ def _reorder_cache(past_key_values, beam_idx):
1654
+ reordered_past = ()
1655
+ for layer_past in past_key_values:
1656
+ reordered_past += (
1657
+ tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
1658
+ )
1659
+ return reordered_past
1660
+
1661
+
1662
+ __all__ = ["MarianForCausalLM", "MarianModel", "MarianMTModel", "MarianPreTrainedModel"]
tasks/tasksmith-441eeab80047/environment/source/src/transformers/models/marian/modeling_tf_marian.py ADDED
@@ -0,0 +1,1559 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2021 The Marian Team Authors and The HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """TF 2.0 Marian model."""
16
+
17
+ from __future__ import annotations
18
+
19
+ import random
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
+ TFBaseModelOutputWithPastAndCrossAttentions,
29
+ TFSeq2SeqLMOutput,
30
+ TFSeq2SeqModelOutput,
31
+ )
32
+
33
+ # Public API
34
+ from ...modeling_tf_utils import (
35
+ TFCausalLanguageModelingLoss,
36
+ TFPreTrainedModel,
37
+ keras,
38
+ keras_serializable,
39
+ unpack_inputs,
40
+ )
41
+ from ...tf_utils import check_embeddings_within_bounds, shape_list, stable_softmax
42
+ from ...utils import (
43
+ add_code_sample_docstrings,
44
+ add_end_docstrings,
45
+ add_start_docstrings,
46
+ add_start_docstrings_to_model_forward,
47
+ logging,
48
+ replace_return_docstrings,
49
+ )
50
+ from .configuration_marian import MarianConfig
51
+
52
+
53
+ logger = logging.get_logger(__name__)
54
+
55
+ _CHECKPOINT_FOR_DOC = "Helsinki-NLP/opus-mt-en-de"
56
+ _CONFIG_FOR_DOC = "MarianConfig"
57
+
58
+
59
+ LARGE_NEGATIVE = -1e8
60
+
61
+
62
+ # Copied from transformers.models.bart.modeling_tf_bart.shift_tokens_right
63
+ def shift_tokens_right(input_ids: tf.Tensor, pad_token_id: int, decoder_start_token_id: int):
64
+ pad_token_id = tf.cast(pad_token_id, input_ids.dtype)
65
+ decoder_start_token_id = tf.cast(decoder_start_token_id, input_ids.dtype)
66
+ start_tokens = tf.fill(
67
+ (shape_list(input_ids)[0], 1), tf.convert_to_tensor(decoder_start_token_id, input_ids.dtype)
68
+ )
69
+ shifted_input_ids = tf.concat([start_tokens, input_ids[:, :-1]], -1)
70
+ # replace possible -100 values in labels by `pad_token_id`
71
+ shifted_input_ids = tf.where(
72
+ shifted_input_ids == -100,
73
+ tf.fill(shape_list(shifted_input_ids), tf.convert_to_tensor(pad_token_id, input_ids.dtype)),
74
+ shifted_input_ids,
75
+ )
76
+
77
+ # "Verify that `labels` has only positive values and -100"
78
+ assert_gte0 = tf.debugging.assert_greater_equal(shifted_input_ids, tf.constant(0, dtype=input_ids.dtype))
79
+
80
+ # Make sure the assertion op is called by wrapping the result in an identity no-op
81
+ with tf.control_dependencies([assert_gte0]):
82
+ shifted_input_ids = tf.identity(shifted_input_ids)
83
+
84
+ return shifted_input_ids
85
+
86
+
87
+ # Copied from transformers.models.bart.modeling_tf_bart._make_causal_mask
88
+ def _make_causal_mask(input_ids_shape: tf.TensorShape, past_key_values_length: int = 0):
89
+ """
90
+ Make causal mask used for bi-directional self-attention.
91
+ """
92
+ bsz = input_ids_shape[0]
93
+ tgt_len = input_ids_shape[1]
94
+ mask = tf.ones((tgt_len, tgt_len)) * LARGE_NEGATIVE
95
+ mask_cond = tf.range(shape_list(mask)[-1])
96
+
97
+ mask = tf.where(mask_cond < tf.reshape(mask_cond + 1, (shape_list(mask)[-1], 1)), 0.0, mask)
98
+
99
+ if past_key_values_length > 0:
100
+ mask = tf.concat([tf.zeros((tgt_len, past_key_values_length)), mask], axis=-1)
101
+
102
+ return tf.tile(mask[None, None, :, :], (bsz, 1, 1, 1))
103
+
104
+
105
+ # Copied from transformers.models.bart.modeling_tf_bart._expand_mask
106
+ def _expand_mask(mask: tf.Tensor, tgt_len: Optional[int] = None):
107
+ """
108
+ Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`.
109
+ """
110
+ src_len = shape_list(mask)[1]
111
+ tgt_len = tgt_len if tgt_len is not None else src_len
112
+ one_cst = tf.constant(1.0)
113
+ mask = tf.cast(mask, dtype=one_cst.dtype)
114
+ expanded_mask = tf.tile(mask[:, None, None, :], (1, 1, tgt_len, 1))
115
+
116
+ return (one_cst - expanded_mask) * LARGE_NEGATIVE
117
+
118
+
119
+ class TFMarianSinusoidalPositionalEmbedding(keras.layers.Layer):
120
+ """This module produces sinusoidal positional embeddings of any length."""
121
+
122
+ def __init__(self, num_positions: int, embedding_dim: int, **kwargs):
123
+ super().__init__(**kwargs)
124
+
125
+ if embedding_dim % 2 != 0:
126
+ raise NotImplementedError(f"odd embedding_dim {embedding_dim} not supported")
127
+
128
+ self.embedding_dim = embedding_dim
129
+ self.num_positions = num_positions
130
+
131
+ def build(self, input_shape: tf.TensorShape):
132
+ """
133
+ Build shared token embedding layer Shared weights logic adapted from
134
+ https://github.com/tensorflow/models/blob/a009f4fb9d2fc4949e32192a944688925ef78659/official/transformer/v2/embedding_layer.py#L24
135
+ """
136
+
137
+ weight = self._init_weight(self.num_positions, self.embedding_dim)
138
+
139
+ self.weight = self.add_weight(
140
+ name="embeddings",
141
+ shape=[self.num_positions, self.embedding_dim],
142
+ )
143
+ weight = tf.cast(weight, dtype=self.weight.dtype)
144
+
145
+ self.weight.assign(weight)
146
+
147
+ super().build(input_shape)
148
+
149
+ @staticmethod
150
+ def _init_weight(n_pos: int, dim: int):
151
+ """
152
+ Identical to the XLM create_sinusoidal_embeddings except features are not interleaved. The cos features are in
153
+ the 2nd half of the vector. [dim // 2:]
154
+ """
155
+ position_enc = np.array(
156
+ [[pos / np.power(10000, 2 * (j // 2) / dim) for j in range(dim)] for pos in range(n_pos)]
157
+ )
158
+ table = np.zeros_like(position_enc)
159
+ # index 0 is all zero
160
+ table[:, 0 : dim // 2] = np.sin(position_enc[:, 0::2])
161
+ table[:, dim // 2 :] = np.cos(position_enc[:, 1::2])
162
+ # convert to tensor
163
+ table = tf.convert_to_tensor(table)
164
+ tf.stop_gradient(table)
165
+ return table
166
+
167
+ def call(
168
+ self, input_shape: tf.TensorShape, past_key_values_length: int = 0, position_ids: tf.Tensor | None = None
169
+ ):
170
+ """Input is expected to be of size [bsz x seqlen]."""
171
+ if position_ids is None:
172
+ seq_len = input_shape[1]
173
+ position_ids = tf.range(past_key_values_length, seq_len + past_key_values_length, delta=1, name="range")
174
+ return tf.gather(self.weight, position_ids)
175
+
176
+
177
+ # Copied from transformers.models.bart.modeling_tf_bart.TFBartAttention with Bart->Marian
178
+ class TFMarianAttention(keras.layers.Layer):
179
+ """Multi-headed attention from "Attention Is All You Need"""
180
+
181
+ def __init__(
182
+ self,
183
+ embed_dim: int,
184
+ num_heads: int,
185
+ dropout: float = 0.0,
186
+ is_decoder: bool = False,
187
+ bias: bool = True,
188
+ **kwargs,
189
+ ):
190
+ super().__init__(**kwargs)
191
+ self.embed_dim = embed_dim
192
+
193
+ self.num_heads = num_heads
194
+ self.dropout = keras.layers.Dropout(dropout)
195
+ self.head_dim = embed_dim // num_heads
196
+ if (self.head_dim * num_heads) != self.embed_dim:
197
+ raise ValueError(
198
+ f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim}"
199
+ f" and `num_heads`: {num_heads})."
200
+ )
201
+ self.scaling = self.head_dim**-0.5
202
+ self.is_decoder = is_decoder
203
+
204
+ self.k_proj = keras.layers.Dense(embed_dim, use_bias=bias, name="k_proj")
205
+ self.q_proj = keras.layers.Dense(embed_dim, use_bias=bias, name="q_proj")
206
+ self.v_proj = keras.layers.Dense(embed_dim, use_bias=bias, name="v_proj")
207
+ self.out_proj = keras.layers.Dense(embed_dim, use_bias=bias, name="out_proj")
208
+
209
+ def _shape(self, tensor: tf.Tensor, seq_len: int, bsz: int):
210
+ return tf.transpose(tf.reshape(tensor, (bsz, seq_len, self.num_heads, self.head_dim)), (0, 2, 1, 3))
211
+
212
+ def call(
213
+ self,
214
+ hidden_states: tf.Tensor,
215
+ key_value_states: tf.Tensor | None = None,
216
+ past_key_value: Tuple[Tuple[tf.Tensor]] | None = None,
217
+ attention_mask: tf.Tensor | None = None,
218
+ layer_head_mask: tf.Tensor | None = None,
219
+ training: Optional[bool] = False,
220
+ ) -> Tuple[tf.Tensor, tf.Tensor | None]:
221
+ """Input shape: Batch x Time x Channel"""
222
+
223
+ # if key_value_states are provided this layer is used as a cross-attention layer
224
+ # for the decoder
225
+ is_cross_attention = key_value_states is not None
226
+ bsz, tgt_len, embed_dim = shape_list(hidden_states)
227
+
228
+ # get query proj
229
+ query_states = self.q_proj(hidden_states) * self.scaling
230
+ # get key, value proj
231
+ if is_cross_attention and past_key_value is not None:
232
+ # reuse k,v, cross_attentions
233
+ key_states = past_key_value[0]
234
+ value_states = past_key_value[1]
235
+ elif is_cross_attention:
236
+ # cross_attentions
237
+ key_states = self._shape(self.k_proj(key_value_states), -1, bsz)
238
+ value_states = self._shape(self.v_proj(key_value_states), -1, bsz)
239
+ elif past_key_value is not None:
240
+ # reuse k, v, self_attention
241
+ key_states = self._shape(self.k_proj(hidden_states), -1, bsz)
242
+ value_states = self._shape(self.v_proj(hidden_states), -1, bsz)
243
+ key_states = tf.concat([past_key_value[0], key_states], axis=2)
244
+ value_states = tf.concat([past_key_value[1], value_states], axis=2)
245
+ else:
246
+ # self_attention
247
+ key_states = self._shape(self.k_proj(hidden_states), -1, bsz)
248
+ value_states = self._shape(self.v_proj(hidden_states), -1, bsz)
249
+
250
+ if self.is_decoder:
251
+ # if cross_attention save Tuple(tf.Tensor, tf.Tensor) of all cross attention key/value_states.
252
+ # Further calls to cross_attention layer can then reuse all cross-attention
253
+ # key/value_states (first "if" case)
254
+ # if uni-directional self-attention (decoder) save Tuple(tf.Tensor, tf.Tensor) of
255
+ # all previous decoder key/value_states. Further calls to uni-directional self-attention
256
+ # can concat previous decoder key/value_states to current projected key/value_states (third "elif" case)
257
+ # if encoder bi-directional self-attention `past_key_value` is always `None`
258
+ past_key_value = (key_states, value_states)
259
+
260
+ proj_shape = (bsz * self.num_heads, -1, self.head_dim)
261
+ query_states = tf.reshape(self._shape(query_states, tgt_len, bsz), proj_shape)
262
+ key_states = tf.reshape(key_states, proj_shape)
263
+ value_states = tf.reshape(value_states, proj_shape)
264
+
265
+ src_len = shape_list(key_states)[1]
266
+ attn_weights = tf.matmul(query_states, key_states, transpose_b=True)
267
+
268
+ tf.debugging.assert_equal(
269
+ shape_list(attn_weights),
270
+ [bsz * self.num_heads, tgt_len, src_len],
271
+ message=(
272
+ f"Attention weights should be of size {(bsz * self.num_heads, tgt_len, src_len)}, but is"
273
+ f" {shape_list(attn_weights)}"
274
+ ),
275
+ )
276
+
277
+ if attention_mask is not None:
278
+ tf.debugging.assert_equal(
279
+ shape_list(attention_mask),
280
+ [bsz, 1, tgt_len, src_len],
281
+ message=(
282
+ f"Attention mask should be of size {(bsz, 1, tgt_len, src_len)}, but is"
283
+ f" {shape_list(attention_mask)}"
284
+ ),
285
+ )
286
+
287
+ attention_mask = tf.cast(attention_mask, dtype=attn_weights.dtype)
288
+ attn_weights = tf.reshape(attn_weights, (bsz, self.num_heads, tgt_len, src_len)) + attention_mask
289
+ attn_weights = tf.reshape(attn_weights, (bsz * self.num_heads, tgt_len, src_len))
290
+
291
+ attn_weights = stable_softmax(attn_weights, axis=-1)
292
+
293
+ if layer_head_mask is not None:
294
+ tf.debugging.assert_equal(
295
+ shape_list(layer_head_mask),
296
+ [self.num_heads],
297
+ message=(
298
+ f"Head mask for a single layer should be of size {(self.num_heads)}, but is"
299
+ f" {shape_list(layer_head_mask)}"
300
+ ),
301
+ )
302
+
303
+ attn_weights = tf.reshape(layer_head_mask, (1, -1, 1, 1)) * tf.reshape(
304
+ attn_weights, (bsz, self.num_heads, tgt_len, src_len)
305
+ )
306
+ attn_weights = tf.reshape(attn_weights, (bsz * self.num_heads, tgt_len, src_len))
307
+
308
+ attn_probs = self.dropout(attn_weights, training=training)
309
+ attn_output = tf.matmul(attn_probs, value_states)
310
+
311
+ tf.debugging.assert_equal(
312
+ shape_list(attn_output),
313
+ [bsz * self.num_heads, tgt_len, self.head_dim],
314
+ message=(
315
+ f"`attn_output` should be of size {(bsz, self.num_heads, tgt_len, self.head_dim)}, but is"
316
+ f" {shape_list(attn_output)}"
317
+ ),
318
+ )
319
+
320
+ attn_output = tf.transpose(
321
+ tf.reshape(attn_output, (bsz, self.num_heads, tgt_len, self.head_dim)), (0, 2, 1, 3)
322
+ )
323
+ attn_output = tf.reshape(attn_output, (bsz, tgt_len, embed_dim))
324
+
325
+ attn_output = self.out_proj(attn_output)
326
+ attn_weights: tf.Tensor = tf.reshape(attn_weights, (bsz, self.num_heads, tgt_len, src_len))
327
+
328
+ return attn_output, attn_weights, past_key_value
329
+
330
+ def build(self, input_shape=None):
331
+ if self.built:
332
+ return
333
+ self.built = True
334
+ if getattr(self, "k_proj", None) is not None:
335
+ with tf.name_scope(self.k_proj.name):
336
+ self.k_proj.build([None, None, self.embed_dim])
337
+ if getattr(self, "q_proj", None) is not None:
338
+ with tf.name_scope(self.q_proj.name):
339
+ self.q_proj.build([None, None, self.embed_dim])
340
+ if getattr(self, "v_proj", None) is not None:
341
+ with tf.name_scope(self.v_proj.name):
342
+ self.v_proj.build([None, None, self.embed_dim])
343
+ if getattr(self, "out_proj", None) is not None:
344
+ with tf.name_scope(self.out_proj.name):
345
+ self.out_proj.build([None, None, self.embed_dim])
346
+
347
+
348
+ # Copied from transformers.models.bart.modeling_tf_bart.TFBartEncoderLayer with Bart->Marian
349
+ class TFMarianEncoderLayer(keras.layers.Layer):
350
+ def __init__(self, config: MarianConfig, **kwargs):
351
+ super().__init__(**kwargs)
352
+ self.embed_dim = config.d_model
353
+ self.self_attn = TFMarianAttention(
354
+ self.embed_dim, config.encoder_attention_heads, dropout=config.attention_dropout, name="self_attn"
355
+ )
356
+ self.self_attn_layer_norm = keras.layers.LayerNormalization(epsilon=1e-5, name="self_attn_layer_norm")
357
+ self.dropout = keras.layers.Dropout(config.dropout)
358
+ self.activation_fn = get_tf_activation(config.activation_function)
359
+ self.activation_dropout = keras.layers.Dropout(config.activation_dropout)
360
+ self.fc1 = keras.layers.Dense(config.encoder_ffn_dim, name="fc1")
361
+ self.fc2 = keras.layers.Dense(self.embed_dim, name="fc2")
362
+ self.final_layer_norm = keras.layers.LayerNormalization(epsilon=1e-5, name="final_layer_norm")
363
+ self.config = config
364
+
365
+ def call(
366
+ self,
367
+ hidden_states: tf.Tensor,
368
+ attention_mask: np.ndarray | tf.Tensor | None,
369
+ layer_head_mask: tf.Tensor | None,
370
+ training: Optional[bool] = False,
371
+ ) -> tf.Tensor:
372
+ """
373
+ Args:
374
+ hidden_states (`tf.Tensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
375
+ attention_mask (`tf.Tensor`): attention mask of size
376
+ `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
377
+ layer_head_mask (`tf.Tensor`): mask for attention heads in a given layer of size
378
+ `(encoder_attention_heads,)`
379
+ """
380
+ residual = hidden_states
381
+ hidden_states, self_attn_weights, _ = self.self_attn(
382
+ hidden_states=hidden_states, attention_mask=attention_mask, layer_head_mask=layer_head_mask
383
+ )
384
+
385
+ tf.debugging.assert_equal(
386
+ shape_list(hidden_states),
387
+ shape_list(residual),
388
+ message=f"Self attn modified the shape of query {shape_list(residual)} to {shape_list(hidden_states)}",
389
+ )
390
+
391
+ hidden_states = self.dropout(hidden_states, training=training)
392
+ hidden_states = residual + hidden_states
393
+ hidden_states = self.self_attn_layer_norm(hidden_states)
394
+
395
+ residual = hidden_states
396
+ hidden_states = self.activation_fn(self.fc1(hidden_states))
397
+ hidden_states = self.activation_dropout(hidden_states, training=training)
398
+ hidden_states = self.fc2(hidden_states)
399
+ hidden_states = self.dropout(hidden_states, training=training)
400
+ hidden_states = residual + hidden_states
401
+ hidden_states = self.final_layer_norm(hidden_states)
402
+
403
+ return hidden_states, self_attn_weights
404
+
405
+ def build(self, input_shape=None):
406
+ if self.built:
407
+ return
408
+ self.built = True
409
+ if getattr(self, "self_attn", None) is not None:
410
+ with tf.name_scope(self.self_attn.name):
411
+ self.self_attn.build(None)
412
+ if getattr(self, "self_attn_layer_norm", None) is not None:
413
+ with tf.name_scope(self.self_attn_layer_norm.name):
414
+ self.self_attn_layer_norm.build([None, None, self.embed_dim])
415
+ if getattr(self, "fc1", None) is not None:
416
+ with tf.name_scope(self.fc1.name):
417
+ self.fc1.build([None, None, self.embed_dim])
418
+ if getattr(self, "fc2", None) is not None:
419
+ with tf.name_scope(self.fc2.name):
420
+ self.fc2.build([None, None, self.config.encoder_ffn_dim])
421
+ if getattr(self, "final_layer_norm", None) is not None:
422
+ with tf.name_scope(self.final_layer_norm.name):
423
+ self.final_layer_norm.build([None, None, self.embed_dim])
424
+
425
+
426
+ # Copied from transformers.models.bart.modeling_tf_bart.TFBartDecoderLayer with Bart->Marian
427
+ class TFMarianDecoderLayer(keras.layers.Layer):
428
+ def __init__(self, config: MarianConfig, **kwargs):
429
+ super().__init__(**kwargs)
430
+ self.embed_dim = config.d_model
431
+ self.self_attn = TFMarianAttention(
432
+ embed_dim=self.embed_dim,
433
+ num_heads=config.decoder_attention_heads,
434
+ dropout=config.attention_dropout,
435
+ name="self_attn",
436
+ is_decoder=True,
437
+ )
438
+ self.dropout = keras.layers.Dropout(config.dropout)
439
+ self.activation_fn = get_tf_activation(config.activation_function)
440
+ self.activation_dropout = keras.layers.Dropout(config.activation_dropout)
441
+
442
+ self.self_attn_layer_norm = keras.layers.LayerNormalization(epsilon=1e-5, name="self_attn_layer_norm")
443
+ self.encoder_attn = TFMarianAttention(
444
+ self.embed_dim,
445
+ config.decoder_attention_heads,
446
+ dropout=config.attention_dropout,
447
+ name="encoder_attn",
448
+ is_decoder=True,
449
+ )
450
+ self.encoder_attn_layer_norm = keras.layers.LayerNormalization(epsilon=1e-5, name="encoder_attn_layer_norm")
451
+ self.fc1 = keras.layers.Dense(config.decoder_ffn_dim, name="fc1")
452
+ self.fc2 = keras.layers.Dense(self.embed_dim, name="fc2")
453
+ self.final_layer_norm = keras.layers.LayerNormalization(epsilon=1e-5, name="final_layer_norm")
454
+ self.config = config
455
+
456
+ def call(
457
+ self,
458
+ hidden_states: tf.Tensor,
459
+ attention_mask: np.ndarray | tf.Tensor | None = None,
460
+ encoder_hidden_states: np.ndarray | tf.Tensor | None = None,
461
+ encoder_attention_mask: np.ndarray | tf.Tensor | None = None,
462
+ layer_head_mask: tf.Tensor | None = None,
463
+ cross_attn_layer_head_mask: tf.Tensor | None = None,
464
+ past_key_value: Optional[Tuple[Tuple[Union[np.ndarray, tf.Tensor]]]] = None,
465
+ training: Optional[bool] = False,
466
+ ) -> Tuple[tf.Tensor, tf.Tensor, Tuple[Tuple[tf.Tensor]]]:
467
+ """
468
+ Args:
469
+ hidden_states (`tf.Tensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
470
+ attention_mask (`tf.Tensor`): attention mask of size
471
+ `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
472
+ encoder_hidden_states (`tf.Tensor`):
473
+ cross attention input to the layer of shape `(batch, seq_len, embed_dim)`
474
+ encoder_attention_mask (`tf.Tensor`): encoder attention mask of size
475
+ `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
476
+ layer_head_mask (`tf.Tensor`): mask for attention heads in a given layer of size
477
+ `(decoder_attention_heads,)`
478
+ cross_attn_layer_head_mask (`tf.Tensor`): mask for heads of the cross-attention module.
479
+ `(decoder_attention_heads,)`
480
+ past_key_value (`Tuple(tf.Tensor)`): cached past key and value projection states
481
+ """
482
+ residual = hidden_states
483
+
484
+ # Self Attention
485
+ # decoder uni-directional self-attention cached key/values tuple is at positions 1,2
486
+ self_attn_past_key_value = past_key_value[:2] if past_key_value is not None else None
487
+ # add present self-attn cache to positions 1,2 of present_key_value tuple
488
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
489
+ hidden_states=hidden_states,
490
+ past_key_value=self_attn_past_key_value,
491
+ attention_mask=attention_mask,
492
+ layer_head_mask=layer_head_mask,
493
+ )
494
+ hidden_states = self.dropout(hidden_states, training=training)
495
+ hidden_states = residual + hidden_states
496
+ hidden_states = self.self_attn_layer_norm(hidden_states)
497
+
498
+ # Cross-Attention Block
499
+ cross_attn_present_key_value = None
500
+ cross_attn_weights = None
501
+ if encoder_hidden_states is not None:
502
+ residual = hidden_states
503
+
504
+ # cross_attn cached key/values tuple is at positions 3,4 of present_key_value tuple
505
+ cross_attn_past_key_value = past_key_value[-2:] if past_key_value is not None else None
506
+ hidden_states, cross_attn_weights, cross_attn_present_key_value = self.encoder_attn(
507
+ hidden_states=hidden_states,
508
+ key_value_states=encoder_hidden_states,
509
+ attention_mask=encoder_attention_mask,
510
+ layer_head_mask=cross_attn_layer_head_mask,
511
+ past_key_value=cross_attn_past_key_value,
512
+ )
513
+ hidden_states = self.dropout(hidden_states, training=training)
514
+ hidden_states = residual + hidden_states
515
+ hidden_states = self.encoder_attn_layer_norm(hidden_states)
516
+
517
+ # add cross-attn to positions 3,4 of present_key_value tuple
518
+ present_key_value = present_key_value + cross_attn_present_key_value
519
+
520
+ # Fully Connected
521
+ residual = hidden_states
522
+ hidden_states = self.activation_fn(self.fc1(hidden_states))
523
+ hidden_states = self.activation_dropout(hidden_states, training=training)
524
+ hidden_states = self.fc2(hidden_states)
525
+ hidden_states = self.dropout(hidden_states, training=training)
526
+ hidden_states = residual + hidden_states
527
+ hidden_states = self.final_layer_norm(hidden_states)
528
+
529
+ return (
530
+ hidden_states,
531
+ self_attn_weights,
532
+ cross_attn_weights,
533
+ present_key_value,
534
+ )
535
+
536
+ def build(self, input_shape=None):
537
+ if self.built:
538
+ return
539
+ self.built = True
540
+ if getattr(self, "self_attn", None) is not None:
541
+ with tf.name_scope(self.self_attn.name):
542
+ self.self_attn.build(None)
543
+ if getattr(self, "self_attn_layer_norm", None) is not None:
544
+ with tf.name_scope(self.self_attn_layer_norm.name):
545
+ self.self_attn_layer_norm.build([None, None, self.embed_dim])
546
+ if getattr(self, "encoder_attn", None) is not None:
547
+ with tf.name_scope(self.encoder_attn.name):
548
+ self.encoder_attn.build(None)
549
+ if getattr(self, "encoder_attn_layer_norm", None) is not None:
550
+ with tf.name_scope(self.encoder_attn_layer_norm.name):
551
+ self.encoder_attn_layer_norm.build([None, None, self.embed_dim])
552
+ if getattr(self, "fc1", None) is not None:
553
+ with tf.name_scope(self.fc1.name):
554
+ self.fc1.build([None, None, self.embed_dim])
555
+ if getattr(self, "fc2", None) is not None:
556
+ with tf.name_scope(self.fc2.name):
557
+ self.fc2.build([None, None, self.config.decoder_ffn_dim])
558
+ if getattr(self, "final_layer_norm", None) is not None:
559
+ with tf.name_scope(self.final_layer_norm.name):
560
+ self.final_layer_norm.build([None, None, self.embed_dim])
561
+
562
+
563
+ class TFMarianPreTrainedModel(TFPreTrainedModel):
564
+ config_class = MarianConfig
565
+ base_model_prefix = "model"
566
+
567
+
568
+ MARIAN_START_DOCSTRING = r"""
569
+ This model inherits from [`TFPreTrainedModel`]. Check the superclass documentation for the generic methods the
570
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
571
+ etc.)
572
+
573
+ This model is also a [keras.Model](https://www.tensorflow.org/api_docs/python/tf/keras/Model) subclass. Use it
574
+ as a regular TF 2.0 Keras Model and refer to the TF 2.0 documentation for all matter related to general usage and
575
+ behavior.
576
+
577
+ <Tip>
578
+
579
+ TensorFlow models and layers in `transformers` accept two formats as input:
580
+
581
+ - having all inputs as keyword arguments (like PyTorch models), or
582
+ - having all inputs as a list, tuple or dict in the first positional argument.
583
+
584
+ The reason the second format is supported is that Keras methods prefer this format when passing inputs to models
585
+ and layers. Because of this support, when using methods like `model.fit()` things should "just work" for you - just
586
+ pass your inputs and labels in any format that `model.fit()` supports! If, however, you want to use the second
587
+ format outside of Keras methods like `fit()` and `predict()`, such as when creating your own layers or models with
588
+ the Keras `Functional` API, there are three possibilities you can use to gather all the input Tensors in the first
589
+ positional argument:
590
+
591
+ - a single Tensor with `input_ids` only and nothing else: `model(input_ids)`
592
+ - a list of varying length with one or several input Tensors IN THE ORDER given in the docstring:
593
+ `model([input_ids, attention_mask])` or `model([input_ids, attention_mask, token_type_ids])`
594
+ - a dictionary with one or several input Tensors associated to the input names given in the docstring:
595
+ `model({"input_ids": input_ids, "token_type_ids": token_type_ids})`
596
+
597
+ Note that when creating models and layers with
598
+ [subclassing](https://keras.io/guides/making_new_layers_and_models_via_subclassing/) then you don't need to worry
599
+ about any of this, as you can just pass inputs like you would to any other Python function!
600
+
601
+ </Tip>
602
+
603
+ Args:
604
+ config ([`MarianConfig`]): Model configuration class with all the parameters of the model.
605
+ Initializing with a config file does not load the weights associated with the model, only the
606
+ configuration. Check out the [`~TFPreTrainedModel.from_pretrained`] method to load the model weights.
607
+ """
608
+
609
+ MARIAN_GENERATION_EXAMPLE = r"""
610
+ TF version of marian-nmt's transformer.h (c++). Designed for the OPUS-NMT translation checkpoints. Available
611
+ models are listed [here](https://huggingface.co/models?search=Helsinki-NLP).
612
+
613
+ Examples:
614
+
615
+ ```python
616
+ >>> from transformers import AutoTokenizer, TFMarianMTModel
617
+ >>> from typing import List
618
+
619
+ >>> src = "fr" # source language
620
+ >>> trg = "en" # target language
621
+ >>> sample_text = "où est l'arrêt de bus ?"
622
+ >>> model_name = f"Helsinki-NLP/opus-mt-{src}-{trg}"
623
+
624
+ >>> model = TFMarianMTModel.from_pretrained(model_name)
625
+ >>> tokenizer = AutoTokenizer.from_pretrained(model_name)
626
+ >>> batch = tokenizer([sample_text], return_tensors="tf")
627
+ >>> gen = model.generate(**batch)
628
+ >>> tokenizer.batch_decode(gen, skip_special_tokens=True)
629
+ "Where is the bus stop ?"
630
+ ```
631
+ """
632
+
633
+ MARIAN_INPUTS_DOCSTRING = r"""
634
+ Args:
635
+ input_ids (`tf.Tensor` of shape `({0})`):
636
+ Indices of input sequence tokens in the vocabulary.
637
+
638
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
639
+ [`PreTrainedTokenizer.__call__`] for details.
640
+
641
+ [What are input IDs?](../glossary#input-ids)
642
+ attention_mask (`tf.Tensor` of shape `({0})`, *optional*):
643
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
644
+
645
+ - 1 for tokens that are **not masked**,
646
+ - 0 for tokens that are **masked**.
647
+
648
+ [What are attention masks?](../glossary#attention-mask)
649
+ decoder_input_ids (`tf.Tensor` of shape `(batch_size, target_sequence_length)`, *optional*):
650
+ Indices of decoder input sequence tokens in the vocabulary.
651
+
652
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
653
+ [`PreTrainedTokenizer.__call__`] for details.
654
+
655
+ [What are decoder input IDs?](../glossary#decoder-input-ids)
656
+
657
+ Marian uses the `pad_token_id` as the starting token for `decoder_input_ids` generation. If
658
+ `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
659
+ `past_key_values`).
660
+ decoder_attention_mask (`tf.Tensor` of shape `(batch_size, target_sequence_length)`, *optional*):
661
+ will be made by default and ignore pad tokens. It is not recommended to set this for most use cases.
662
+ decoder_position_ids (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
663
+ Indices of positions of each decoder input sequence tokens in the position embeddings. Selected in the
664
+ range `[0, config.max_position_embeddings - 1]`.
665
+ head_mask (`tf.Tensor` of shape `(encoder_layers, encoder_attention_heads)`, *optional*):
666
+ Mask to nullify selected heads of the attention modules in the encoder. Mask values selected in `[0, 1]`:
667
+
668
+ - 1 indicates the head is **not masked**,
669
+ - 0 indicates the head is **masked**.
670
+
671
+ decoder_head_mask (`tf.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
672
+ Mask to nullify selected heads of the attention modules in the decoder. Mask values selected in `[0, 1]`:
673
+
674
+ - 1 indicates the head is **not masked**,
675
+ - 0 indicates the head is **masked**.
676
+
677
+ cross_attn_head_mask (`tf.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
678
+ Mask to nullify selected heads of the cross-attention modules. Mask values selected in `[0, 1]`:
679
+
680
+ - 1 indicates the head is **not masked**,
681
+ - 0 indicates the head is **masked**.
682
+
683
+ encoder_outputs (`tf.FloatTensor`, *optional*):
684
+ hidden states at the output of the last layer of the encoder. Used in the cross-attention of the decoder.
685
+ of shape `(batch_size, sequence_length, hidden_size)` is a sequence of
686
+ past_key_values (`Tuple[Tuple[tf.Tensor]]` of length `config.n_layers`)
687
+ contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.
688
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
689
+ don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
690
+ `decoder_input_ids` of shape `(batch_size, sequence_length)`.
691
+ inputs_embeds (`tf.Tensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
692
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation.
693
+ This is useful if you want more control over how to convert `input_ids` indices into associated vectors
694
+ than the model's internal embedding lookup matrix.
695
+ use_cache (`bool`, *optional*, defaults to `True`):
696
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
697
+ `past_key_values`). Set to `False` during training, `True` during generation
698
+ output_attentions (`bool`, *optional*):
699
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
700
+ tensors for more detail. This argument can be used only in eager mode, in graph mode the value in the
701
+ config will be used instead.
702
+ output_hidden_states (`bool`, *optional*):
703
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
704
+ more detail. This argument can be used only in eager mode, in graph mode the value in the config will be
705
+ used instead.
706
+ return_dict (`bool`, *optional*):
707
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. This argument can be used in
708
+ eager mode, in graph mode the value will always be set to True.
709
+ training (`bool`, *optional*, defaults to `False`):
710
+ Whether or not to use the model in training mode (some modules like dropout modules have different
711
+ behaviors between training and evaluation).
712
+ """
713
+
714
+
715
+ @keras_serializable
716
+ class TFMarianEncoder(keras.layers.Layer):
717
+ config_class = MarianConfig
718
+ """
719
+ Transformer encoder consisting of *config.encoder_layers* self attention layers. Each layer is a
720
+ [`TFMarianEncoderLayer`].
721
+
722
+ Args:
723
+ config: MarianConfig
724
+ """
725
+
726
+ def __init__(self, config: MarianConfig, embed_tokens: Optional[keras.layers.Embedding] = None, **kwargs):
727
+ super().__init__(**kwargs)
728
+ self.config = config
729
+ self.dropout = keras.layers.Dropout(config.dropout)
730
+ self.layerdrop = config.encoder_layerdrop
731
+ self.padding_idx = config.pad_token_id
732
+ self.max_source_positions = config.max_position_embeddings
733
+ self.embed_scale = tf.math.sqrt(float(config.d_model)) if config.scale_embedding else 1.0
734
+
735
+ self.embed_tokens = embed_tokens
736
+ self.embed_positions = TFMarianSinusoidalPositionalEmbedding(
737
+ config.max_position_embeddings,
738
+ config.d_model,
739
+ name="embed_positions",
740
+ )
741
+ self.layers = [TFMarianEncoderLayer(config, name=f"layers.{i}") for i in range(config.encoder_layers)]
742
+
743
+ def get_embed_tokens(self):
744
+ return self.embed_tokens
745
+
746
+ def set_embed_tokens(self, embed_tokens):
747
+ self.embed_tokens = embed_tokens
748
+
749
+ @unpack_inputs
750
+ def call(
751
+ self,
752
+ input_ids: tf.Tensor | None = None,
753
+ inputs_embeds: tf.Tensor | None = None,
754
+ attention_mask: tf.Tensor | None = None,
755
+ head_mask: tf.Tensor | None = None,
756
+ output_attentions: Optional[bool] = None,
757
+ output_hidden_states: Optional[bool] = None,
758
+ return_dict: Optional[bool] = None,
759
+ training: bool = False,
760
+ ):
761
+ """
762
+ Args:
763
+ input_ids (`tf.Tensor` of shape `(batch_size, sequence_length)`):
764
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you
765
+ provide it.
766
+
767
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
768
+ [`PreTrainedTokenizer.__call__`] for details.
769
+
770
+ [What are input IDs?](../glossary#input-ids)
771
+ attention_mask (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
772
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
773
+
774
+ - 1 for tokens that are **not masked**,
775
+ - 0 for tokens that are **masked**.
776
+
777
+ [What are attention masks?](../glossary#attention-mask)
778
+ head_mask (`tf.Tensor` of shape `(encoder_layers, encoder_attention_heads)`, `optional):
779
+ Mask to nullify selected heads of the attention modules. Mask values selected in `[0, 1]`:
780
+
781
+ - 1 indicates the head is **not masked**,
782
+ - 0 indicates the head is **masked**.
783
+
784
+ inputs_embeds (`tf.Tensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
785
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation.
786
+ This is useful if you want more control over how to convert `input_ids` indices into associated vectors
787
+ than the model's internal embedding lookup matrix.
788
+ output_attentions (`bool`, *optional*):
789
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
790
+ returned tensors for more detail. This argument can be used only in eager mode, in graph mode the value
791
+ in the config will be used instead.
792
+ output_hidden_states (`bool`, *optional*):
793
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
794
+ for more detail. This argument can be used only in eager mode, in graph mode the value in the config
795
+ will be used instead.
796
+ return_dict (`bool`, *optional*):
797
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. This argument can be used
798
+ in eager mode, in graph mode the value will always be set to True.
799
+ training (`bool`, *optional*, defaults to `False`):
800
+ Whether or not to use the model in training mode (some modules like dropout modules have different
801
+ behaviors between training and evaluation).
802
+ """
803
+
804
+ if input_ids is not None and inputs_embeds is not None:
805
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
806
+ elif input_ids is not None:
807
+ input_shape = shape_list(input_ids)
808
+ elif inputs_embeds is not None:
809
+ input_shape = shape_list(inputs_embeds)[:-1]
810
+ else:
811
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
812
+
813
+ if inputs_embeds is None:
814
+ check_embeddings_within_bounds(input_ids, self.embed_tokens.input_dim)
815
+ inputs_embeds = self.embed_tokens(input_ids) * self.embed_scale
816
+
817
+ embed_pos = self.embed_positions(input_shape)
818
+ hidden_states = inputs_embeds + embed_pos
819
+ hidden_states = self.dropout(hidden_states, training=training)
820
+
821
+ # check attention mask and invert
822
+ if attention_mask is not None:
823
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
824
+ attention_mask = _expand_mask(attention_mask)
825
+ else:
826
+ attention_mask = None
827
+
828
+ encoder_states = () if output_hidden_states else None
829
+ all_attentions = () if output_attentions else None
830
+
831
+ # check if head_mask has a correct number of layers specified if desired
832
+ if head_mask is not None:
833
+ tf.debugging.assert_equal(
834
+ shape_list(head_mask)[0],
835
+ len(self.layers),
836
+ message=(
837
+ f"The head_mask should be specified for {len(self.layers)} layers, but it is for"
838
+ f" {shape_list(head_mask)[0]}."
839
+ ),
840
+ )
841
+
842
+ # encoder layers
843
+ for idx, encoder_layer in enumerate(self.layers):
844
+ if output_hidden_states:
845
+ encoder_states = encoder_states + (hidden_states,)
846
+ # add LayerDrop (see https://arxiv.org/abs/1909.11556 for description)
847
+ dropout_probability = random.uniform(0, 1)
848
+ if training and (dropout_probability < self.layerdrop): # skip the layer
849
+ continue
850
+
851
+ hidden_states, attn = encoder_layer(
852
+ hidden_states,
853
+ attention_mask,
854
+ head_mask[idx] if head_mask is not None else None,
855
+ )
856
+
857
+ if output_attentions:
858
+ all_attentions += (attn,)
859
+
860
+ if output_hidden_states:
861
+ encoder_states = encoder_states + (hidden_states,)
862
+
863
+ if not return_dict:
864
+ return tuple(v for v in [hidden_states, encoder_states, all_attentions] if v is not None)
865
+ return TFBaseModelOutput(
866
+ last_hidden_state=hidden_states, hidden_states=encoder_states, attentions=all_attentions
867
+ )
868
+
869
+ def build(self, input_shape=None):
870
+ if self.built:
871
+ return
872
+ self.built = True
873
+ if getattr(self, "embed_positions", None) is not None:
874
+ with tf.name_scope(self.embed_positions.name):
875
+ self.embed_positions.build(None)
876
+ if getattr(self, "layers", None) is not None:
877
+ for layer in self.layers:
878
+ with tf.name_scope(layer.name):
879
+ layer.build(None)
880
+
881
+
882
+ @keras_serializable
883
+ class TFMarianDecoder(keras.layers.Layer):
884
+ config_class = MarianConfig
885
+ """
886
+ Transformer decoder consisting of *config.decoder_layers* layers. Each layer is a [`TFMarianDecoderLayer`]
887
+
888
+ Args:
889
+ config: MarianConfig
890
+ embed_tokens: output embedding
891
+ """
892
+
893
+ def __init__(self, config: MarianConfig, embed_tokens: Optional[keras.layers.Embedding] = None, **kwargs):
894
+ super().__init__(**kwargs)
895
+ self.config = config
896
+ self.padding_idx = config.pad_token_id
897
+ self.embed_tokens = embed_tokens
898
+ self.layerdrop = config.decoder_layerdrop
899
+ self.embed_positions = TFMarianSinusoidalPositionalEmbedding(
900
+ config.max_position_embeddings,
901
+ config.d_model,
902
+ name="embed_positions",
903
+ )
904
+ self.embed_scale = tf.math.sqrt(float(config.d_model)) if config.scale_embedding else 1.0
905
+ self.layers = [TFMarianDecoderLayer(config, name=f"layers.{i}") for i in range(config.decoder_layers)]
906
+
907
+ self.dropout = keras.layers.Dropout(config.dropout)
908
+
909
+ def get_embed_tokens(self):
910
+ return self.embed_tokens
911
+
912
+ def set_embed_tokens(self, embed_tokens):
913
+ self.embed_tokens = embed_tokens
914
+
915
+ @unpack_inputs
916
+ def call(
917
+ self,
918
+ input_ids: tf.Tensor | None = None,
919
+ inputs_embeds: tf.Tensor | None = None,
920
+ attention_mask: tf.Tensor | None = None,
921
+ position_ids: tf.Tensor | None = None,
922
+ encoder_hidden_states: tf.Tensor | None = None,
923
+ encoder_attention_mask: tf.Tensor | None = None,
924
+ head_mask: tf.Tensor | None = None,
925
+ cross_attn_head_mask: tf.Tensor | None = None,
926
+ past_key_values: Tuple[Tuple[tf.Tensor]] | None = None,
927
+ use_cache: Optional[bool] = None,
928
+ output_attentions: Optional[bool] = None,
929
+ output_hidden_states: Optional[bool] = None,
930
+ return_dict: Optional[bool] = None,
931
+ training: bool = False,
932
+ ):
933
+ r"""
934
+ Args:
935
+ input_ids (`tf.Tensor` of shape `(batch_size, sequence_length)`):
936
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you
937
+ provide it.
938
+
939
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
940
+ [`PreTrainedTokenizer.__call__`] for details.
941
+
942
+ [What are input IDs?](../glossary#input-ids)
943
+ attention_mask (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
944
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
945
+
946
+ - 1 for tokens that are **not masked**,
947
+ - 0 for tokens that are **masked**.
948
+
949
+ [What are attention masks?](../glossary#attention-mask)
950
+ position_ids (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
951
+ Indices of positions of each decoder input sequence tokens in the position embeddings. Selected in the
952
+ range `[0, config.max_position_embeddings - 1]`.
953
+ encoder_hidden_states (`tf.Tensor` of shape `(batch_size, encoder_sequence_length, hidden_size)`, *optional*):
954
+ Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention
955
+ of the decoder.
956
+ encoder_attention_mask (`tf.Tensor` of shape `(batch_size, encoder_sequence_length)`, *optional*):
957
+ Mask to avoid performing cross-attention on padding tokens indices of encoder input_ids. Mask values
958
+ selected in `[0, 1]`:
959
+
960
+ - 1 for tokens that are **not masked**,
961
+ - 0 for tokens that are **masked**.
962
+
963
+ [What are attention masks?](../glossary#attention-mask)
964
+ head_mask (`tf.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
965
+ Mask to nullify selected heads of the attention modules. Mask values selected in `[0, 1]`:
966
+
967
+ - 1 indicates the head is **not masked**,
968
+ - 0 indicates the head is **masked**.
969
+
970
+ cross_attn_head_mask (`tf.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
971
+ Mask to nullify selected heads of the cross-attention modules. Mask values selected in `[0, 1]`:
972
+
973
+ - 1 indicates the head is **not masked**,
974
+ - 0 indicates the head is **masked**.
975
+
976
+ past_key_values (`Tuple[Tuple[tf.Tensor]]` of length `config.n_layers` with each tuple having 2 tuples each of which has 2 tensors of shape `(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`):
977
+ Contains precomputed key and value hidden-states of the attention blocks. Can be used to speed up
978
+ decoding.
979
+
980
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those
981
+ that don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of
982
+ all `decoder_input_ids` of shape `(batch_size, sequence_length)`.
983
+ inputs_embeds (`tf.Tensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
984
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation.
985
+ This is useful if you want more control over how to convert `input_ids` indices into associated vectors
986
+ than the model's internal embedding lookup matrix.
987
+ output_attentions (`bool`, *optional*):
988
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
989
+ returned tensors for more detail. This argument can be used only in eager mode, in graph mode the value
990
+ in the config will be used instead.
991
+ output_hidden_states (`bool`, *optional*):
992
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
993
+ for more detail. This argument can be used only in eager mode, in graph mode the value in the config
994
+ will be used instead.
995
+ return_dict (`bool`, *optional*):
996
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. This argument can be used
997
+ in eager mode, in graph mode the value will always be set to True.
998
+ training (`bool`, *optional*, defaults to `False`):
999
+ Whether or not to use the model in training mode (some modules like dropout modules have different
1000
+ behaviors between training and evaluation).
1001
+ """
1002
+
1003
+ if input_ids is not None and inputs_embeds is not None:
1004
+ raise ValueError("You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time")
1005
+ elif input_ids is not None:
1006
+ input_shape = shape_list(input_ids)
1007
+ elif inputs_embeds is not None:
1008
+ input_shape = shape_list(inputs_embeds)[:-1]
1009
+ else:
1010
+ raise ValueError("You have to specify either decoder_input_ids or decoder_inputs_embeds")
1011
+
1012
+ past_key_values_length = shape_list(past_key_values[0][0])[2] if past_key_values is not None else 0
1013
+
1014
+ # embed positions
1015
+ if position_ids is None:
1016
+ positions = self.embed_positions(input_shape, past_key_values_length)
1017
+ else:
1018
+ positions = self.embed_positions(input_shape, position_ids=position_ids)
1019
+
1020
+ if inputs_embeds is None:
1021
+ check_embeddings_within_bounds(input_ids, self.embed_tokens.input_dim)
1022
+ inputs_embeds = self.embed_tokens(input_ids) * self.embed_scale
1023
+
1024
+ hidden_states = inputs_embeds
1025
+
1026
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
1027
+ if input_shape[-1] > 1:
1028
+ combined_attention_mask = _make_causal_mask(input_shape, past_key_values_length=past_key_values_length)
1029
+ else:
1030
+ combined_attention_mask = _expand_mask(
1031
+ tf.ones((input_shape[0], input_shape[1] + past_key_values_length)), tgt_len=input_shape[-1]
1032
+ )
1033
+
1034
+ if attention_mask is not None:
1035
+ combined_attention_mask = combined_attention_mask + _expand_mask(attention_mask, tgt_len=input_shape[-1])
1036
+
1037
+ if encoder_hidden_states is not None and encoder_attention_mask is not None:
1038
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
1039
+ encoder_attention_mask = _expand_mask(encoder_attention_mask, tgt_len=input_shape[-1])
1040
+
1041
+ hidden_states = self.dropout(hidden_states + positions, training=training)
1042
+
1043
+ # decoder layers
1044
+ all_hidden_states = () if output_hidden_states else None
1045
+ all_self_attns = () if output_attentions else None
1046
+ all_cross_attns = () if (output_attentions and encoder_hidden_states is not None) else None
1047
+ present_key_values = () if use_cache else None
1048
+
1049
+ # check if head_mask and cross_attn_head_mask have a correct number of layers specified if desired
1050
+ for attn_name, attn_mask in [("head_mask", head_mask), ("cross_attn_head_mask", cross_attn_head_mask)]:
1051
+ if attn_mask is not None:
1052
+ tf.debugging.assert_equal(
1053
+ shape_list(attn_mask)[0],
1054
+ len(self.layers),
1055
+ message=(
1056
+ f"The {attn_name} should be specified for {len(self.layers)} layers, but it is for"
1057
+ f" {shape_list(attn_mask)[0]}."
1058
+ ),
1059
+ )
1060
+
1061
+ for idx, decoder_layer in enumerate(self.layers):
1062
+ # add LayerDrop (see https://arxiv.org/abs/1909.11556 for description)
1063
+ if output_hidden_states:
1064
+ all_hidden_states += (hidden_states,)
1065
+ dropout_probability = random.uniform(0, 1)
1066
+
1067
+ if training and (dropout_probability < self.layerdrop):
1068
+ continue
1069
+
1070
+ past_key_value = past_key_values[idx] if past_key_values is not None else None
1071
+
1072
+ hidden_states, layer_self_attn, layer_cross_attn, present_key_value = decoder_layer(
1073
+ hidden_states,
1074
+ attention_mask=combined_attention_mask,
1075
+ encoder_hidden_states=encoder_hidden_states,
1076
+ encoder_attention_mask=encoder_attention_mask,
1077
+ layer_head_mask=head_mask[idx] if head_mask is not None else None,
1078
+ cross_attn_layer_head_mask=cross_attn_head_mask[idx] if cross_attn_head_mask is not None else None,
1079
+ past_key_value=past_key_value,
1080
+ )
1081
+
1082
+ if use_cache:
1083
+ present_key_values += (present_key_value,)
1084
+
1085
+ if output_attentions:
1086
+ all_self_attns += (layer_self_attn,)
1087
+
1088
+ if encoder_hidden_states is not None:
1089
+ all_cross_attns += (layer_cross_attn,)
1090
+
1091
+ if output_hidden_states:
1092
+ all_hidden_states += (hidden_states,)
1093
+
1094
+ if not return_dict:
1095
+ return hidden_states, present_key_values, all_hidden_states, all_self_attns, all_cross_attns
1096
+ else:
1097
+ return TFBaseModelOutputWithPastAndCrossAttentions(
1098
+ last_hidden_state=hidden_states,
1099
+ past_key_values=present_key_values,
1100
+ hidden_states=all_hidden_states,
1101
+ attentions=all_self_attns,
1102
+ cross_attentions=all_cross_attns,
1103
+ )
1104
+
1105
+ def build(self, input_shape=None):
1106
+ if self.built:
1107
+ return
1108
+ self.built = True
1109
+ if getattr(self, "embed_positions", None) is not None:
1110
+ with tf.name_scope(self.embed_positions.name):
1111
+ self.embed_positions.build(None)
1112
+ if getattr(self, "layers", None) is not None:
1113
+ for layer in self.layers:
1114
+ with tf.name_scope(layer.name):
1115
+ layer.build(None)
1116
+
1117
+
1118
+ @keras_serializable
1119
+ class TFMarianMainLayer(keras.layers.Layer):
1120
+ config_class = MarianConfig
1121
+
1122
+ def __init__(self, config: MarianConfig, **kwargs):
1123
+ super().__init__(**kwargs)
1124
+
1125
+ self.config = config
1126
+ self.shared = keras.layers.Embedding(
1127
+ input_dim=config.vocab_size,
1128
+ output_dim=config.d_model,
1129
+ embeddings_initializer=keras.initializers.TruncatedNormal(stddev=self.config.init_std),
1130
+ name="model.shared",
1131
+ )
1132
+ # Additional attribute to specify the expected name scope of the layer (for loading/storing weights)
1133
+ self.shared.load_weight_prefix = "model.shared"
1134
+
1135
+ self.encoder = TFMarianEncoder(config, self.shared, name="encoder")
1136
+ self.decoder = TFMarianDecoder(config, self.shared, name="decoder")
1137
+
1138
+ def get_input_embeddings(self):
1139
+ return self.shared
1140
+
1141
+ def set_input_embeddings(self, new_embeddings):
1142
+ self.shared = new_embeddings
1143
+ self.encoder.embed_tokens = self.shared
1144
+ self.decoder.embed_tokens = self.shared
1145
+
1146
+ @unpack_inputs
1147
+ def call(
1148
+ self,
1149
+ input_ids: tf.Tensor | None = None,
1150
+ attention_mask: tf.Tensor | None = None,
1151
+ decoder_input_ids: tf.Tensor | None = None,
1152
+ decoder_attention_mask: tf.Tensor | None = None,
1153
+ decoder_position_ids: tf.Tensor | None = None,
1154
+ head_mask: tf.Tensor | None = None,
1155
+ decoder_head_mask: tf.Tensor | None = None,
1156
+ cross_attn_head_mask: tf.Tensor | None = None,
1157
+ encoder_outputs: Optional[Union[Tuple, TFBaseModelOutput]] = None,
1158
+ past_key_values: Tuple[Tuple[tf.Tensor]] = None,
1159
+ inputs_embeds: tf.Tensor | None = None,
1160
+ decoder_inputs_embeds: tf.Tensor | None = None,
1161
+ use_cache: Optional[bool] = None,
1162
+ output_attentions: Optional[bool] = None,
1163
+ output_hidden_states: Optional[bool] = None,
1164
+ return_dict: Optional[bool] = None,
1165
+ training: bool = False,
1166
+ **kwargs,
1167
+ ):
1168
+ if decoder_input_ids is None and decoder_inputs_embeds is None:
1169
+ use_cache = False
1170
+
1171
+ output_hidden_states = (
1172
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1173
+ )
1174
+
1175
+ if encoder_outputs is None:
1176
+ encoder_outputs = self.encoder(
1177
+ input_ids=input_ids,
1178
+ attention_mask=attention_mask,
1179
+ head_mask=head_mask,
1180
+ inputs_embeds=inputs_embeds,
1181
+ output_attentions=output_attentions,
1182
+ output_hidden_states=output_hidden_states,
1183
+ return_dict=return_dict,
1184
+ training=training,
1185
+ )
1186
+ # If the user passed a tuple for encoder_outputs, we wrap it in a TFBaseModelOutput when return_dict=True
1187
+ elif return_dict and not isinstance(encoder_outputs, TFBaseModelOutput):
1188
+ encoder_outputs = TFBaseModelOutput(
1189
+ last_hidden_state=encoder_outputs[0],
1190
+ hidden_states=encoder_outputs[1] if len(encoder_outputs) > 1 else None,
1191
+ attentions=encoder_outputs[2] if len(encoder_outputs) > 2 else None,
1192
+ )
1193
+ # If the user passed a TFBaseModelOutput for encoder_outputs, we wrap it in a tuple when return_dict=False
1194
+ elif not return_dict and not isinstance(encoder_outputs, tuple):
1195
+ encoder_outputs = encoder_outputs.to_tuple()
1196
+
1197
+ decoder_outputs = self.decoder(
1198
+ decoder_input_ids,
1199
+ attention_mask=decoder_attention_mask,
1200
+ position_ids=decoder_position_ids,
1201
+ encoder_hidden_states=encoder_outputs[0],
1202
+ encoder_attention_mask=attention_mask,
1203
+ head_mask=decoder_head_mask,
1204
+ cross_attn_head_mask=cross_attn_head_mask,
1205
+ past_key_values=past_key_values,
1206
+ inputs_embeds=decoder_inputs_embeds,
1207
+ use_cache=use_cache,
1208
+ output_attentions=output_attentions,
1209
+ output_hidden_states=output_hidden_states,
1210
+ return_dict=return_dict,
1211
+ training=training,
1212
+ )
1213
+
1214
+ if not return_dict:
1215
+ return decoder_outputs + encoder_outputs
1216
+
1217
+ return TFSeq2SeqModelOutput(
1218
+ last_hidden_state=decoder_outputs.last_hidden_state,
1219
+ past_key_values=decoder_outputs.past_key_values,
1220
+ decoder_hidden_states=decoder_outputs.hidden_states,
1221
+ decoder_attentions=decoder_outputs.attentions,
1222
+ cross_attentions=decoder_outputs.cross_attentions,
1223
+ encoder_last_hidden_state=encoder_outputs.last_hidden_state,
1224
+ encoder_hidden_states=encoder_outputs.hidden_states,
1225
+ encoder_attentions=encoder_outputs.attentions,
1226
+ )
1227
+
1228
+ def build(self, input_shape=None):
1229
+ if self.built:
1230
+ return
1231
+ self.built = True
1232
+ # The shared/tied weights expect to be in the model base namespace
1233
+ # Adding "/" to the end (not the start!) of a tf.name_scope puts it in the root namespace rather than
1234
+ # the current one.
1235
+ with tf.name_scope(self.shared.load_weight_prefix + "/" + self.shared.name + "/"):
1236
+ self.shared.build(None)
1237
+ if getattr(self, "encoder", None) is not None:
1238
+ with tf.name_scope(self.encoder.name):
1239
+ self.encoder.build(None)
1240
+ if getattr(self, "decoder", None) is not None:
1241
+ with tf.name_scope(self.decoder.name):
1242
+ self.decoder.build(None)
1243
+
1244
+
1245
+ @add_start_docstrings(
1246
+ "The bare MARIAN Model outputting raw hidden-states without any specific head on top.",
1247
+ MARIAN_START_DOCSTRING,
1248
+ )
1249
+ class TFMarianModel(TFMarianPreTrainedModel):
1250
+ def __init__(self, config: MarianConfig, *inputs, **kwargs):
1251
+ super().__init__(config, *inputs, **kwargs)
1252
+
1253
+ self.model = TFMarianMainLayer(config, name="model")
1254
+
1255
+ def get_encoder(self):
1256
+ return self.model.encoder
1257
+
1258
+ def get_decoder(self):
1259
+ return self.model.decoder
1260
+
1261
+ @unpack_inputs
1262
+ @add_start_docstrings_to_model_forward(MARIAN_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
1263
+ @add_code_sample_docstrings(
1264
+ checkpoint=_CHECKPOINT_FOR_DOC,
1265
+ output_type=TFSeq2SeqModelOutput,
1266
+ config_class=_CONFIG_FOR_DOC,
1267
+ )
1268
+ def call(
1269
+ self,
1270
+ input_ids: tf.Tensor | None = None,
1271
+ attention_mask: tf.Tensor | None = None,
1272
+ decoder_input_ids: tf.Tensor | None = None,
1273
+ decoder_attention_mask: tf.Tensor | None = None,
1274
+ decoder_position_ids: tf.Tensor | None = None,
1275
+ head_mask: tf.Tensor | None = None,
1276
+ decoder_head_mask: tf.Tensor | None = None,
1277
+ cross_attn_head_mask: tf.Tensor | None = None,
1278
+ encoder_outputs: tf.Tensor | None = None,
1279
+ past_key_values: Tuple[Tuple[tf.Tensor]] | None = None,
1280
+ inputs_embeds: tf.Tensor | None = None,
1281
+ decoder_inputs_embeds: tf.Tensor | None = None,
1282
+ use_cache: bool | None = None,
1283
+ output_attentions: bool | None = None,
1284
+ output_hidden_states: bool | None = None,
1285
+ return_dict: bool | None = None,
1286
+ training: bool = False,
1287
+ **kwargs,
1288
+ ) -> Tuple[tf.Tensor] | TFSeq2SeqModelOutput:
1289
+ outputs = self.model(
1290
+ input_ids=input_ids,
1291
+ attention_mask=attention_mask,
1292
+ decoder_input_ids=decoder_input_ids,
1293
+ decoder_attention_mask=decoder_attention_mask,
1294
+ decoder_position_ids=decoder_position_ids,
1295
+ head_mask=head_mask,
1296
+ decoder_head_mask=decoder_head_mask,
1297
+ cross_attn_head_mask=cross_attn_head_mask,
1298
+ encoder_outputs=encoder_outputs,
1299
+ past_key_values=past_key_values,
1300
+ inputs_embeds=inputs_embeds,
1301
+ decoder_inputs_embeds=decoder_inputs_embeds,
1302
+ use_cache=use_cache,
1303
+ output_attentions=output_attentions,
1304
+ output_hidden_states=output_hidden_states,
1305
+ return_dict=return_dict,
1306
+ training=training,
1307
+ )
1308
+
1309
+ return outputs
1310
+
1311
+ # Copied from transformers.models.bart.modeling_tf_bart.TFBartModel.serving_output
1312
+ def serving_output(self, output):
1313
+ pkv = tf.tuple(output.past_key_values)[1] if self.config.use_cache else None
1314
+ dec_hs = tf.convert_to_tensor(output.decoder_hidden_states) if self.config.output_hidden_states else None
1315
+ dec_attns = tf.convert_to_tensor(output.decoder_attentions) if self.config.output_attentions else None
1316
+ cross_attns = tf.convert_to_tensor(output.cross_attentions) if self.config.output_attentions else None
1317
+ enc_hs = tf.convert_to_tensor(output.encoder_hidden_states) if self.config.output_hidden_states else None
1318
+ enc_attns = tf.convert_to_tensor(output.encoder_attentions) if self.config.output_attentions else None
1319
+
1320
+ return TFSeq2SeqModelOutput(
1321
+ last_hidden_state=output.last_hidden_state,
1322
+ past_key_values=pkv,
1323
+ decoder_hidden_states=dec_hs,
1324
+ decoder_attentions=dec_attns,
1325
+ cross_attentions=cross_attns,
1326
+ encoder_last_hidden_state=output.encoder_last_hidden_state,
1327
+ encoder_hidden_states=enc_hs,
1328
+ encoder_attentions=enc_attns,
1329
+ )
1330
+
1331
+ def build(self, input_shape=None):
1332
+ if self.built:
1333
+ return
1334
+ self.built = True
1335
+ if getattr(self, "model", None) is not None:
1336
+ with tf.name_scope(self.model.name):
1337
+ self.model.build(None)
1338
+
1339
+
1340
+ # Copied from transformers.models.bart.modeling_tf_bart.BiasLayer
1341
+ class BiasLayer(keras.layers.Layer):
1342
+ """
1343
+ Bias as a layer. It is used for serialization purposes: `keras.Model.save_weights` stores on a per-layer basis,
1344
+ so all weights have to be registered in a layer.
1345
+ """
1346
+
1347
+ def __init__(self, shape, initializer, trainable, name, **kwargs):
1348
+ super().__init__(name=name, **kwargs)
1349
+ # Note: the name of this variable will NOT be scoped when serialized, i.e. it will not be in the format of
1350
+ # "outer_layer/inner_layer/.../name:0". Instead, it will be "name:0". For further details, see:
1351
+ # https://github.com/huggingface/transformers/pull/18833#issuecomment-1233090214
1352
+ self.bias = self.add_weight(name=name, shape=shape, initializer=initializer, trainable=trainable)
1353
+
1354
+ def call(self, x):
1355
+ return x + self.bias
1356
+
1357
+
1358
+ @add_start_docstrings(
1359
+ "The MARIAN Model with a language modeling head. Can be used for summarization.",
1360
+ MARIAN_START_DOCSTRING,
1361
+ )
1362
+ class TFMarianMTModel(TFMarianPreTrainedModel, TFCausalLanguageModelingLoss):
1363
+ _keys_to_ignore_on_load_unexpected = [
1364
+ r"model.encoder.embed_tokens.weight",
1365
+ r"model.decoder.embed_tokens.weight",
1366
+ ]
1367
+
1368
+ def __init__(self, config, *inputs, **kwargs):
1369
+ super().__init__(config, *inputs, **kwargs)
1370
+ self.model = TFMarianMainLayer(config, name="model")
1371
+ self.use_cache = config.use_cache
1372
+ # final_bias_logits is registered as a buffer in pytorch, so not trainable for the sake of consistency.
1373
+ self.bias_layer = BiasLayer(
1374
+ name="final_logits_bias", shape=[1, config.vocab_size], initializer="zeros", trainable=False
1375
+ )
1376
+
1377
+ def get_decoder(self):
1378
+ return self.model.decoder
1379
+
1380
+ def get_encoder(self):
1381
+ return self.model.encoder
1382
+
1383
+ def get_output_embeddings(self):
1384
+ return self.get_input_embeddings()
1385
+
1386
+ def set_output_embeddings(self, value):
1387
+ self.set_input_embeddings(value)
1388
+
1389
+ def get_bias(self):
1390
+ return {"final_logits_bias": self.bias_layer.bias}
1391
+
1392
+ def set_bias(self, value):
1393
+ # Replaces the existing layers containing bias for correct (de)serialization.
1394
+ vocab_size = value["final_logits_bias"].shape[-1]
1395
+ self.bias_layer = BiasLayer(
1396
+ name="final_logits_bias", shape=[1, vocab_size], initializer="zeros", trainable=False
1397
+ )
1398
+ self.bias_layer.bias.assign(value["final_logits_bias"])
1399
+
1400
+ @unpack_inputs
1401
+ @add_start_docstrings_to_model_forward(MARIAN_INPUTS_DOCSTRING)
1402
+ @replace_return_docstrings(output_type=TFSeq2SeqLMOutput, config_class=_CONFIG_FOR_DOC)
1403
+ @add_end_docstrings(MARIAN_GENERATION_EXAMPLE)
1404
+ def call(
1405
+ self,
1406
+ input_ids: tf.Tensor | None = None,
1407
+ attention_mask: tf.Tensor | None = None,
1408
+ decoder_input_ids: tf.Tensor | None = None,
1409
+ decoder_attention_mask: tf.Tensor | None = None,
1410
+ decoder_position_ids: tf.Tensor | None = None,
1411
+ head_mask: tf.Tensor | None = None,
1412
+ decoder_head_mask: tf.Tensor | None = None,
1413
+ cross_attn_head_mask: tf.Tensor | None = None,
1414
+ encoder_outputs: TFBaseModelOutput | None = None,
1415
+ past_key_values: Tuple[Tuple[tf.Tensor]] | None = None,
1416
+ inputs_embeds: tf.Tensor | None = None,
1417
+ decoder_inputs_embeds: tf.Tensor | None = None,
1418
+ use_cache: bool | None = None,
1419
+ output_attentions: bool | None = None,
1420
+ output_hidden_states: bool | None = None,
1421
+ return_dict: bool | None = None,
1422
+ labels: tf.Tensor | None = None,
1423
+ training: bool = False,
1424
+ ) -> Tuple[tf.Tensor] | TFSeq2SeqLMOutput:
1425
+ r"""
1426
+ labels (`tf.tensor` of shape `(batch_size, sequence_length)`, *optional*):
1427
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1428
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1429
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1430
+
1431
+ Returns:
1432
+
1433
+ """
1434
+
1435
+ if labels is not None:
1436
+ labels = tf.where(
1437
+ labels == self.config.pad_token_id,
1438
+ tf.fill(shape_list(labels), tf.cast(-100, labels.dtype)),
1439
+ labels,
1440
+ )
1441
+ use_cache = False
1442
+ if decoder_input_ids is None and decoder_inputs_embeds is None:
1443
+ decoder_input_ids = shift_tokens_right(
1444
+ labels, self.config.pad_token_id, self.config.decoder_start_token_id
1445
+ )
1446
+
1447
+ outputs = self.model(
1448
+ input_ids,
1449
+ attention_mask=attention_mask,
1450
+ decoder_input_ids=decoder_input_ids,
1451
+ encoder_outputs=encoder_outputs,
1452
+ decoder_attention_mask=decoder_attention_mask,
1453
+ decoder_position_ids=decoder_position_ids,
1454
+ head_mask=head_mask,
1455
+ decoder_head_mask=decoder_head_mask,
1456
+ cross_attn_head_mask=cross_attn_head_mask,
1457
+ past_key_values=past_key_values,
1458
+ inputs_embeds=inputs_embeds,
1459
+ decoder_inputs_embeds=decoder_inputs_embeds,
1460
+ use_cache=use_cache,
1461
+ output_attentions=output_attentions,
1462
+ output_hidden_states=output_hidden_states,
1463
+ return_dict=return_dict,
1464
+ training=training,
1465
+ )
1466
+ lm_logits = tf.matmul(outputs[0], self.model.shared.weights, transpose_b=True)
1467
+ lm_logits = self.bias_layer(lm_logits)
1468
+ masked_lm_loss = None if labels is None else self.hf_compute_loss(labels, lm_logits)
1469
+
1470
+ if not return_dict:
1471
+ output = (lm_logits,) + outputs[1:]
1472
+ return ((masked_lm_loss,) + output) if masked_lm_loss is not None else output
1473
+ return TFSeq2SeqLMOutput(
1474
+ loss=masked_lm_loss,
1475
+ logits=lm_logits,
1476
+ past_key_values=outputs.past_key_values, # index 1 of d outputs
1477
+ decoder_hidden_states=outputs.decoder_hidden_states, # index 2 of d outputs
1478
+ decoder_attentions=outputs.decoder_attentions, # index 3 of d outputs
1479
+ cross_attentions=outputs.cross_attentions, # index 4 of d outputs
1480
+ encoder_last_hidden_state=outputs.encoder_last_hidden_state, # index 0 of encoder outputs
1481
+ encoder_hidden_states=outputs.encoder_hidden_states, # 1 of e out
1482
+ encoder_attentions=outputs.encoder_attentions, # 2 of e out
1483
+ )
1484
+
1485
+ # Copied from transformers.models.bart.modeling_tf_bart.TFBartForConditionalGeneration.serving_output
1486
+ def serving_output(self, output):
1487
+ pkv = tf.tuple(output.past_key_values)[1] if self.config.use_cache else None
1488
+ dec_hs = tf.convert_to_tensor(output.decoder_hidden_states) if self.config.output_hidden_states else None
1489
+ dec_attns = tf.convert_to_tensor(output.decoder_attentions) if self.config.output_attentions else None
1490
+ cross_attns = tf.convert_to_tensor(output.cross_attentions) if self.config.output_attentions else None
1491
+ enc_hs = tf.convert_to_tensor(output.encoder_hidden_states) if self.config.output_hidden_states else None
1492
+ enc_attns = tf.convert_to_tensor(output.encoder_attentions) if self.config.output_attentions else None
1493
+
1494
+ return TFSeq2SeqLMOutput(
1495
+ logits=output.logits,
1496
+ past_key_values=pkv,
1497
+ decoder_hidden_states=dec_hs,
1498
+ decoder_attentions=dec_attns,
1499
+ cross_attentions=cross_attns,
1500
+ encoder_last_hidden_state=output.encoder_last_hidden_state,
1501
+ encoder_hidden_states=enc_hs,
1502
+ encoder_attentions=enc_attns,
1503
+ )
1504
+
1505
+ # Copied from transformers.models.bart.modeling_tf_bart.TFBartForConditionalGeneration.prepare_inputs_for_generation
1506
+ def prepare_inputs_for_generation(
1507
+ self,
1508
+ decoder_input_ids,
1509
+ past_key_values=None,
1510
+ attention_mask=None,
1511
+ decoder_attention_mask=None,
1512
+ head_mask=None,
1513
+ decoder_head_mask=None,
1514
+ cross_attn_head_mask=None,
1515
+ use_cache=None,
1516
+ encoder_outputs=None,
1517
+ **kwargs,
1518
+ ):
1519
+ # cut decoder_input_ids if past_key_values is used
1520
+ if past_key_values is not None:
1521
+ decoder_input_ids = decoder_input_ids[:, -1:]
1522
+
1523
+ if decoder_attention_mask is not None: # xla
1524
+ decoder_position_ids = tf.math.cumsum(decoder_attention_mask, axis=-1, exclusive=True)[:, -1:]
1525
+ elif past_key_values is not None: # no xla + past_key_values
1526
+ decoder_position_ids = past_key_values[0][0].shape[2]
1527
+ else: # no xla + no past_key_values
1528
+ decoder_position_ids = tf.range(decoder_input_ids.shape[1])
1529
+
1530
+ return {
1531
+ "input_ids": None, # encoder_outputs is defined. input_ids not needed
1532
+ "encoder_outputs": encoder_outputs,
1533
+ "past_key_values": past_key_values,
1534
+ "decoder_input_ids": decoder_input_ids,
1535
+ "attention_mask": attention_mask,
1536
+ "decoder_attention_mask": decoder_attention_mask,
1537
+ "decoder_position_ids": decoder_position_ids,
1538
+ "head_mask": head_mask,
1539
+ "decoder_head_mask": decoder_head_mask,
1540
+ "cross_attn_head_mask": cross_attn_head_mask,
1541
+ "use_cache": use_cache, # change this to avoid caching (presumably for debugging)
1542
+ }
1543
+
1544
+ def prepare_decoder_input_ids_from_labels(self, labels: tf.Tensor):
1545
+ return shift_tokens_right(labels, self.config.pad_token_id, self.config.decoder_start_token_id)
1546
+
1547
+ def build(self, input_shape=None):
1548
+ if self.built:
1549
+ return
1550
+ self.built = True
1551
+ if getattr(self, "model", None) is not None:
1552
+ with tf.name_scope(self.model.name):
1553
+ self.model.build(None)
1554
+ if getattr(self, "bias_layer", None) is not None:
1555
+ with tf.name_scope(self.bias_layer.name):
1556
+ self.bias_layer.build(None)
1557
+
1558
+
1559
+ __all__ = ["TFMarianModel", "TFMarianMTModel", "TFMarianPreTrainedModel"]
tasks/tasksmith-441eeab80047/environment/source/src/transformers/models/marian/tokenization_marian.py ADDED
@@ -0,0 +1,394 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ import json
15
+ import os
16
+ import re
17
+ import warnings
18
+ from pathlib import Path
19
+ from shutil import copyfile
20
+ from typing import Any, Dict, List, Optional, Tuple, Union
21
+
22
+ import sentencepiece
23
+
24
+ from ...tokenization_utils import PreTrainedTokenizer
25
+ from ...utils import logging
26
+
27
+
28
+ logger = logging.get_logger(__name__)
29
+
30
+ VOCAB_FILES_NAMES = {
31
+ "source_spm": "source.spm",
32
+ "target_spm": "target.spm",
33
+ "vocab": "vocab.json",
34
+ "target_vocab_file": "target_vocab.json",
35
+ "tokenizer_config_file": "tokenizer_config.json",
36
+ }
37
+
38
+
39
+ SPIECE_UNDERLINE = "▁"
40
+
41
+ # Example URL https://huggingface.co/Helsinki-NLP/opus-mt-en-de/resolve/main/vocab.json
42
+
43
+
44
+ class MarianTokenizer(PreTrainedTokenizer):
45
+ r"""
46
+ Construct a Marian tokenizer. Based on [SentencePiece](https://github.com/google/sentencepiece).
47
+
48
+ This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to
49
+ this superclass for more information regarding those methods.
50
+
51
+ Args:
52
+ source_spm (`str`):
53
+ [SentencePiece](https://github.com/google/sentencepiece) file (generally has a .spm extension) that
54
+ contains the vocabulary for the source language.
55
+ target_spm (`str`):
56
+ [SentencePiece](https://github.com/google/sentencepiece) file (generally has a .spm extension) that
57
+ contains the vocabulary for the target language.
58
+ source_lang (`str`, *optional*):
59
+ A string representing the source language.
60
+ target_lang (`str`, *optional*):
61
+ A string representing the target language.
62
+ unk_token (`str`, *optional*, defaults to `"<unk>"`):
63
+ The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
64
+ token instead.
65
+ eos_token (`str`, *optional*, defaults to `"</s>"`):
66
+ The end of sequence token.
67
+ pad_token (`str`, *optional*, defaults to `"<pad>"`):
68
+ The token used for padding, for example when batching sequences of different lengths.
69
+ model_max_length (`int`, *optional*, defaults to 512):
70
+ The maximum sentence length the model accepts.
71
+ additional_special_tokens (`List[str]`, *optional*, defaults to `["<eop>", "<eod>"]`):
72
+ Additional special tokens used by the tokenizer.
73
+ sp_model_kwargs (`dict`, *optional*):
74
+ Will be passed to the `SentencePieceProcessor.__init__()` method. The [Python wrapper for
75
+ SentencePiece](https://github.com/google/sentencepiece/tree/master/python) can be used, among other things,
76
+ to set:
77
+
78
+ - `enable_sampling`: Enable subword regularization.
79
+ - `nbest_size`: Sampling parameters for unigram. Invalid for BPE-Dropout.
80
+
81
+ - `nbest_size = {0,1}`: No sampling is performed.
82
+ - `nbest_size > 1`: samples from the nbest_size results.
83
+ - `nbest_size < 0`: assuming that nbest_size is infinite and samples from the all hypothesis (lattice)
84
+ using forward-filtering-and-backward-sampling algorithm.
85
+
86
+ - `alpha`: Smoothing parameter for unigram sampling, and dropout probability of merge operations for
87
+ BPE-dropout.
88
+
89
+ Examples:
90
+
91
+ ```python
92
+ >>> from transformers import MarianForCausalLM, MarianTokenizer
93
+
94
+ >>> model = MarianForCausalLM.from_pretrained("Helsinki-NLP/opus-mt-en-de")
95
+ >>> tokenizer = MarianTokenizer.from_pretrained("Helsinki-NLP/opus-mt-en-de")
96
+ >>> src_texts = ["I am a small frog.", "Tom asked his teacher for advice."]
97
+ >>> tgt_texts = ["Ich bin ein kleiner Frosch.", "Tom bat seinen Lehrer um Rat."] # optional
98
+ >>> inputs = tokenizer(src_texts, text_target=tgt_texts, return_tensors="pt", padding=True)
99
+
100
+ >>> outputs = model(**inputs) # should work
101
+ ```"""
102
+
103
+ vocab_files_names = VOCAB_FILES_NAMES
104
+ model_input_names = ["input_ids", "attention_mask"]
105
+ language_code_re = re.compile(">>.+<<") # type: re.Pattern
106
+
107
+ def __init__(
108
+ self,
109
+ source_spm,
110
+ target_spm,
111
+ vocab,
112
+ target_vocab_file=None,
113
+ source_lang=None,
114
+ target_lang=None,
115
+ unk_token="<unk>",
116
+ eos_token="</s>",
117
+ pad_token="<pad>",
118
+ model_max_length=512,
119
+ sp_model_kwargs: Optional[Dict[str, Any]] = None,
120
+ separate_vocabs=False,
121
+ **kwargs,
122
+ ) -> None:
123
+ self.sp_model_kwargs = {} if sp_model_kwargs is None else sp_model_kwargs
124
+
125
+ assert Path(source_spm).exists(), f"cannot find spm source {source_spm}"
126
+
127
+ self.separate_vocabs = separate_vocabs
128
+ self.encoder = load_json(vocab)
129
+ if str(unk_token) not in self.encoder:
130
+ raise KeyError("<unk> token must be in the vocab")
131
+ assert str(pad_token) in self.encoder
132
+
133
+ if separate_vocabs:
134
+ self.target_encoder = load_json(target_vocab_file)
135
+ self.decoder = {v: k for k, v in self.target_encoder.items()}
136
+ self.supported_language_codes = []
137
+ else:
138
+ self.decoder = {v: k for k, v in self.encoder.items()}
139
+ self.supported_language_codes: list = [k for k in self.encoder if k.startswith(">>") and k.endswith("<<")]
140
+
141
+ self.source_lang = source_lang
142
+ self.target_lang = target_lang
143
+ self.spm_files = [source_spm, target_spm]
144
+
145
+ # load SentencePiece model for pre-processing
146
+ self.spm_source = load_spm(source_spm, self.sp_model_kwargs)
147
+ self.spm_target = load_spm(target_spm, self.sp_model_kwargs)
148
+ self.current_spm = self.spm_source
149
+ self.current_encoder = self.encoder
150
+
151
+ # Multilingual target side: default to using first supported language code.
152
+
153
+ self._setup_normalizer()
154
+
155
+ super().__init__(
156
+ # bos_token=bos_token, unused. Start decoding with config.decoder_start_token_id
157
+ source_lang=source_lang,
158
+ target_lang=target_lang,
159
+ unk_token=unk_token,
160
+ eos_token=eos_token,
161
+ pad_token=pad_token,
162
+ model_max_length=model_max_length,
163
+ sp_model_kwargs=self.sp_model_kwargs,
164
+ target_vocab_file=target_vocab_file,
165
+ separate_vocabs=separate_vocabs,
166
+ **kwargs,
167
+ )
168
+
169
+ def _setup_normalizer(self):
170
+ try:
171
+ from sacremoses import MosesPunctNormalizer
172
+
173
+ self.punc_normalizer = MosesPunctNormalizer(self.source_lang).normalize
174
+ except (ImportError, FileNotFoundError):
175
+ warnings.warn("Recommended: pip install sacremoses.")
176
+ self.punc_normalizer = lambda x: x
177
+
178
+ def normalize(self, x: str) -> str:
179
+ """Cover moses empty string edge case. They return empty list for '' input!"""
180
+ return self.punc_normalizer(x) if x else ""
181
+
182
+ def _convert_token_to_id(self, token):
183
+ return self.current_encoder.get(token, self.current_encoder[self.unk_token])
184
+
185
+ def remove_language_code(self, text: str):
186
+ """Remove language codes like >>fr<< before sentencepiece"""
187
+ match = self.language_code_re.match(text)
188
+ code: list = [match.group(0)] if match else []
189
+ return code, self.language_code_re.sub("", text)
190
+
191
+ def _tokenize(self, text: str) -> List[str]:
192
+ code, text = self.remove_language_code(text)
193
+ pieces = self.current_spm.encode(text, out_type=str)
194
+ return code + pieces
195
+
196
+ def _convert_id_to_token(self, index: int) -> str:
197
+ """Converts an index (integer) in a token (str) using the decoder."""
198
+ return self.decoder.get(index, self.unk_token)
199
+
200
+ def batch_decode(self, sequences, **kwargs):
201
+ """
202
+ Convert a list of lists of token ids into a list of strings by calling decode.
203
+
204
+ Args:
205
+ sequences (`Union[List[int], List[List[int]], np.ndarray, torch.Tensor, tf.Tensor]`):
206
+ List of tokenized input ids. Can be obtained using the `__call__` method.
207
+ skip_special_tokens (`bool`, *optional*, defaults to `False`):
208
+ Whether or not to remove special tokens in the decoding.
209
+ clean_up_tokenization_spaces (`bool`, *optional*):
210
+ Whether or not to clean up the tokenization spaces. If `None`, will default to
211
+ `self.clean_up_tokenization_spaces` (available in the `tokenizer_config`).
212
+ use_source_tokenizer (`bool`, *optional*, defaults to `False`):
213
+ Whether or not to use the source tokenizer to decode sequences (only applicable in sequence-to-sequence
214
+ problems).
215
+ kwargs (additional keyword arguments, *optional*):
216
+ Will be passed to the underlying model specific decode method.
217
+
218
+ Returns:
219
+ `List[str]`: The list of decoded sentences.
220
+ """
221
+ return super().batch_decode(sequences, **kwargs)
222
+
223
+ def decode(self, token_ids, **kwargs):
224
+ """
225
+ Converts a sequence of ids in a string, using the tokenizer and vocabulary with options to remove special
226
+ tokens and clean up tokenization spaces.
227
+
228
+ Similar to doing `self.convert_tokens_to_string(self.convert_ids_to_tokens(token_ids))`.
229
+
230
+ Args:
231
+ token_ids (`Union[int, List[int], np.ndarray, torch.Tensor, tf.Tensor]`):
232
+ List of tokenized input ids. Can be obtained using the `__call__` method.
233
+ skip_special_tokens (`bool`, *optional*, defaults to `False`):
234
+ Whether or not to remove special tokens in the decoding.
235
+ clean_up_tokenization_spaces (`bool`, *optional*):
236
+ Whether or not to clean up the tokenization spaces. If `None`, will default to
237
+ `self.clean_up_tokenization_spaces` (available in the `tokenizer_config`).
238
+ use_source_tokenizer (`bool`, *optional*, defaults to `False`):
239
+ Whether or not to use the source tokenizer to decode sequences (only applicable in sequence-to-sequence
240
+ problems).
241
+ kwargs (additional keyword arguments, *optional*):
242
+ Will be passed to the underlying model specific decode method.
243
+
244
+ Returns:
245
+ `str`: The decoded sentence.
246
+ """
247
+ return super().decode(token_ids, **kwargs)
248
+
249
+ def convert_tokens_to_string(self, tokens: List[str]) -> str:
250
+ """Uses source spm if _decode_use_source_tokenizer is True, and target spm otherwise"""
251
+ sp_model = self.spm_source if self._decode_use_source_tokenizer else self.spm_target
252
+ current_sub_tokens = []
253
+ out_string = ""
254
+ for token in tokens:
255
+ # make sure that special tokens are not decoded using sentencepiece model
256
+ if token in self.all_special_tokens:
257
+ out_string += sp_model.decode_pieces(current_sub_tokens) + token + " "
258
+ current_sub_tokens = []
259
+ else:
260
+ current_sub_tokens.append(token)
261
+ out_string += sp_model.decode_pieces(current_sub_tokens)
262
+ out_string = out_string.replace(SPIECE_UNDERLINE, " ")
263
+ return out_string.strip()
264
+
265
+ def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None) -> List[int]:
266
+ """Build model inputs from a sequence by appending eos_token_id."""
267
+ if token_ids_1 is None:
268
+ return token_ids_0 + [self.eos_token_id]
269
+ # We don't expect to process pairs, but leave the pair logic for API consistency
270
+ return token_ids_0 + token_ids_1 + [self.eos_token_id]
271
+
272
+ def _switch_to_input_mode(self):
273
+ self.current_spm = self.spm_source
274
+ self.current_encoder = self.encoder
275
+
276
+ def _switch_to_target_mode(self):
277
+ self.current_spm = self.spm_target
278
+ if self.separate_vocabs:
279
+ self.current_encoder = self.target_encoder
280
+
281
+ @property
282
+ def vocab_size(self) -> int:
283
+ return len(self.encoder)
284
+
285
+ def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
286
+ if not os.path.isdir(save_directory):
287
+ logger.error(f"Vocabulary path ({save_directory}) should be a directory")
288
+ return
289
+ saved_files = []
290
+
291
+ if self.separate_vocabs:
292
+ out_src_vocab_file = os.path.join(
293
+ save_directory,
294
+ (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab"],
295
+ )
296
+ out_tgt_vocab_file = os.path.join(
297
+ save_directory,
298
+ (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["target_vocab_file"],
299
+ )
300
+ save_json(self.encoder, out_src_vocab_file)
301
+ save_json(self.target_encoder, out_tgt_vocab_file)
302
+ saved_files.append(out_src_vocab_file)
303
+ saved_files.append(out_tgt_vocab_file)
304
+ else:
305
+ out_vocab_file = os.path.join(
306
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab"]
307
+ )
308
+ save_json(self.encoder, out_vocab_file)
309
+ saved_files.append(out_vocab_file)
310
+
311
+ for spm_save_filename, spm_orig_path, spm_model in zip(
312
+ [VOCAB_FILES_NAMES["source_spm"], VOCAB_FILES_NAMES["target_spm"]],
313
+ self.spm_files,
314
+ [self.spm_source, self.spm_target],
315
+ ):
316
+ spm_save_path = os.path.join(
317
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + spm_save_filename
318
+ )
319
+ if os.path.abspath(spm_orig_path) != os.path.abspath(spm_save_path) and os.path.isfile(spm_orig_path):
320
+ copyfile(spm_orig_path, spm_save_path)
321
+ saved_files.append(spm_save_path)
322
+ elif not os.path.isfile(spm_orig_path):
323
+ with open(spm_save_path, "wb") as fi:
324
+ content_spiece_model = spm_model.serialized_model_proto()
325
+ fi.write(content_spiece_model)
326
+ saved_files.append(spm_save_path)
327
+
328
+ return tuple(saved_files)
329
+
330
+ def get_vocab(self) -> Dict:
331
+ return self.get_src_vocab()
332
+
333
+ def get_src_vocab(self):
334
+ return dict(self.encoder, **self.added_tokens_encoder)
335
+
336
+ def get_tgt_vocab(self):
337
+ return dict(self.target_encoder, **self.added_tokens_decoder)
338
+
339
+ def __getstate__(self) -> Dict:
340
+ state = self.__dict__.copy()
341
+ state.update(
342
+ {k: None for k in ["spm_source", "spm_target", "current_spm", "punc_normalizer", "target_vocab_file"]}
343
+ )
344
+ return state
345
+
346
+ def __setstate__(self, d: Dict) -> None:
347
+ self.__dict__ = d
348
+
349
+ # for backward compatibility
350
+ if not hasattr(self, "sp_model_kwargs"):
351
+ self.sp_model_kwargs = {}
352
+
353
+ self.spm_source, self.spm_target = (load_spm(f, self.sp_model_kwargs) for f in self.spm_files)
354
+ self.current_spm = self.spm_source
355
+ self._setup_normalizer()
356
+
357
+ def num_special_tokens_to_add(self, *args, **kwargs):
358
+ """Just EOS"""
359
+ return 1
360
+
361
+ def _special_token_mask(self, seq):
362
+ all_special_ids = set(self.all_special_ids) # call it once instead of inside list comp
363
+ all_special_ids.remove(self.unk_token_id) # <unk> is only sometimes special
364
+ return [1 if x in all_special_ids else 0 for x in seq]
365
+
366
+ def get_special_tokens_mask(
367
+ self, token_ids_0: List, token_ids_1: Optional[List] = None, already_has_special_tokens: bool = False
368
+ ) -> List[int]:
369
+ """Get list where entries are [1] if a token is [eos] or [pad] else 0."""
370
+ if already_has_special_tokens:
371
+ return self._special_token_mask(token_ids_0)
372
+ elif token_ids_1 is None:
373
+ return self._special_token_mask(token_ids_0) + [1]
374
+ else:
375
+ return self._special_token_mask(token_ids_0 + token_ids_1) + [1]
376
+
377
+
378
+ def load_spm(path: str, sp_model_kwargs: Dict[str, Any]) -> sentencepiece.SentencePieceProcessor:
379
+ spm = sentencepiece.SentencePieceProcessor(**sp_model_kwargs)
380
+ spm.Load(path)
381
+ return spm
382
+
383
+
384
+ def save_json(data, path: str) -> None:
385
+ with open(path, "w") as f:
386
+ json.dump(data, f, indent=2)
387
+
388
+
389
+ def load_json(path: str) -> Union[Dict, List]:
390
+ with open(path, "r") as f:
391
+ return json.load(f)
392
+
393
+
394
+ __all__ = ["MarianTokenizer"]
tasks/tasksmith-441eeab80047/environment/source/src/transformers/models/markuplm/__init__.py ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 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 _LazyModule
17
+ from ...utils.import_utils import define_import_structure
18
+
19
+
20
+ if TYPE_CHECKING:
21
+ from .configuration_markuplm import *
22
+ from .feature_extraction_markuplm import *
23
+ from .modeling_markuplm import *
24
+ from .processing_markuplm import *
25
+ from .tokenization_markuplm import *
26
+ from .tokenization_markuplm_fast import *
27
+ else:
28
+ import sys
29
+
30
+ _file = globals()["__file__"]
31
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
tasks/tasksmith-441eeab80047/environment/source/src/transformers/models/markuplm/configuration_markuplm.py ADDED
@@ -0,0 +1,156 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2021, The Microsoft Research Asia MarkupLM Team authors
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
+ """MarkupLM model configuration"""
16
+
17
+ from ...configuration_utils import PretrainedConfig
18
+ from ...utils import logging
19
+
20
+
21
+ logger = logging.get_logger(__name__)
22
+
23
+
24
+ class MarkupLMConfig(PretrainedConfig):
25
+ r"""
26
+ This is the configuration class to store the configuration of a [`MarkupLMModel`]. It is used to instantiate a
27
+ MarkupLM model according to the specified arguments, defining the model architecture. Instantiating a configuration
28
+ with the defaults will yield a similar configuration to that of the MarkupLM
29
+ [microsoft/markuplm-base](https://huggingface.co/microsoft/markuplm-base) architecture.
30
+
31
+ Configuration objects inherit from [`BertConfig`] and can be used to control the model outputs. Read the
32
+ documentation from [`BertConfig`] for more information.
33
+
34
+ Args:
35
+ vocab_size (`int`, *optional*, defaults to 30522):
36
+ Vocabulary size of the MarkupLM model. Defines the different tokens that can be represented by the
37
+ *inputs_ids* passed to the forward method of [`MarkupLMModel`].
38
+ hidden_size (`int`, *optional*, defaults to 768):
39
+ Dimensionality of the encoder layers and the pooler layer.
40
+ num_hidden_layers (`int`, *optional*, defaults to 12):
41
+ Number of hidden layers in the Transformer encoder.
42
+ num_attention_heads (`int`, *optional*, defaults to 12):
43
+ Number of attention heads for each attention layer in the Transformer encoder.
44
+ intermediate_size (`int`, *optional*, defaults to 3072):
45
+ Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
46
+ hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):
47
+ The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
48
+ `"relu"`, `"silu"` and `"gelu_new"` are supported.
49
+ hidden_dropout_prob (`float`, *optional*, defaults to 0.1):
50
+ The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
51
+ attention_probs_dropout_prob (`float`, *optional*, defaults to 0.1):
52
+ The dropout ratio for the attention probabilities.
53
+ max_position_embeddings (`int`, *optional*, defaults to 512):
54
+ The maximum sequence length that this model might ever be used with. Typically set this to something large
55
+ just in case (e.g., 512 or 1024 or 2048).
56
+ type_vocab_size (`int`, *optional*, defaults to 2):
57
+ The vocabulary size of the `token_type_ids` passed into [`MarkupLMModel`].
58
+ initializer_range (`float`, *optional*, defaults to 0.02):
59
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
60
+ layer_norm_eps (`float`, *optional*, defaults to 1e-12):
61
+ The epsilon used by the layer normalization layers.
62
+ max_tree_id_unit_embeddings (`int`, *optional*, defaults to 1024):
63
+ The maximum value that the tree id unit embedding might ever use. Typically set this to something large
64
+ just in case (e.g., 1024).
65
+ max_xpath_tag_unit_embeddings (`int`, *optional*, defaults to 256):
66
+ The maximum value that the xpath tag unit embedding might ever use. Typically set this to something large
67
+ just in case (e.g., 256).
68
+ max_xpath_subs_unit_embeddings (`int`, *optional*, defaults to 1024):
69
+ The maximum value that the xpath subscript unit embedding might ever use. Typically set this to something
70
+ large just in case (e.g., 1024).
71
+ tag_pad_id (`int`, *optional*, defaults to 216):
72
+ The id of the padding token in the xpath tags.
73
+ subs_pad_id (`int`, *optional*, defaults to 1001):
74
+ The id of the padding token in the xpath subscripts.
75
+ xpath_tag_unit_hidden_size (`int`, *optional*, defaults to 32):
76
+ The hidden size of each tree id unit. One complete tree index will have
77
+ (50*xpath_tag_unit_hidden_size)-dim.
78
+ max_depth (`int`, *optional*, defaults to 50):
79
+ The maximum depth in xpath.
80
+
81
+ Examples:
82
+
83
+ ```python
84
+ >>> from transformers import MarkupLMModel, MarkupLMConfig
85
+
86
+ >>> # Initializing a MarkupLM microsoft/markuplm-base style configuration
87
+ >>> configuration = MarkupLMConfig()
88
+
89
+ >>> # Initializing a model from the microsoft/markuplm-base style configuration
90
+ >>> model = MarkupLMModel(configuration)
91
+
92
+ >>> # Accessing the model configuration
93
+ >>> configuration = model.config
94
+ ```"""
95
+
96
+ model_type = "markuplm"
97
+
98
+ def __init__(
99
+ self,
100
+ vocab_size=30522,
101
+ hidden_size=768,
102
+ num_hidden_layers=12,
103
+ num_attention_heads=12,
104
+ intermediate_size=3072,
105
+ hidden_act="gelu",
106
+ hidden_dropout_prob=0.1,
107
+ attention_probs_dropout_prob=0.1,
108
+ max_position_embeddings=512,
109
+ type_vocab_size=2,
110
+ initializer_range=0.02,
111
+ layer_norm_eps=1e-12,
112
+ pad_token_id=0,
113
+ bos_token_id=0,
114
+ eos_token_id=2,
115
+ max_xpath_tag_unit_embeddings=256,
116
+ max_xpath_subs_unit_embeddings=1024,
117
+ tag_pad_id=216,
118
+ subs_pad_id=1001,
119
+ xpath_unit_hidden_size=32,
120
+ max_depth=50,
121
+ position_embedding_type="absolute",
122
+ use_cache=True,
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
+ self.vocab_size = vocab_size
133
+ self.hidden_size = hidden_size
134
+ self.num_hidden_layers = num_hidden_layers
135
+ self.num_attention_heads = num_attention_heads
136
+ self.hidden_act = hidden_act
137
+ self.intermediate_size = intermediate_size
138
+ self.hidden_dropout_prob = hidden_dropout_prob
139
+ self.attention_probs_dropout_prob = attention_probs_dropout_prob
140
+ self.max_position_embeddings = max_position_embeddings
141
+ self.type_vocab_size = type_vocab_size
142
+ self.initializer_range = initializer_range
143
+ self.layer_norm_eps = layer_norm_eps
144
+ self.position_embedding_type = position_embedding_type
145
+ self.use_cache = use_cache
146
+ self.classifier_dropout = classifier_dropout
147
+ # additional properties
148
+ self.max_depth = max_depth
149
+ self.max_xpath_tag_unit_embeddings = max_xpath_tag_unit_embeddings
150
+ self.max_xpath_subs_unit_embeddings = max_xpath_subs_unit_embeddings
151
+ self.tag_pad_id = tag_pad_id
152
+ self.subs_pad_id = subs_pad_id
153
+ self.xpath_unit_hidden_size = xpath_unit_hidden_size
154
+
155
+
156
+ __all__ = ["MarkupLMConfig"]
tasks/tasksmith-441eeab80047/environment/source/src/transformers/models/markuplm/feature_extraction_markuplm.py ADDED
@@ -0,0 +1,186 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 The HuggingFace Inc. team.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """
16
+ Feature extractor class for MarkupLM.
17
+ """
18
+
19
+ import html
20
+
21
+ from ...feature_extraction_utils import BatchFeature, FeatureExtractionMixin
22
+ from ...utils import is_bs4_available, logging, requires_backends
23
+
24
+
25
+ if is_bs4_available():
26
+ import bs4
27
+ from bs4 import BeautifulSoup
28
+
29
+
30
+ logger = logging.get_logger(__name__)
31
+
32
+
33
+ class MarkupLMFeatureExtractor(FeatureExtractionMixin):
34
+ r"""
35
+ Constructs a MarkupLM feature extractor. This can be used to get a list of nodes and corresponding xpaths from HTML
36
+ strings.
37
+
38
+ This feature extractor inherits from [`~feature_extraction_utils.PreTrainedFeatureExtractor`] which contains most
39
+ of the main methods. Users should refer to this superclass for more information regarding those methods.
40
+
41
+ """
42
+
43
+ def __init__(self, **kwargs):
44
+ requires_backends(self, ["bs4"])
45
+ super().__init__(**kwargs)
46
+
47
+ def xpath_soup(self, element):
48
+ xpath_tags = []
49
+ xpath_subscripts = []
50
+ child = element if element.name else element.parent
51
+ for parent in child.parents: # type: bs4.element.Tag
52
+ siblings = parent.find_all(child.name, recursive=False)
53
+ xpath_tags.append(child.name)
54
+ xpath_subscripts.append(
55
+ 0 if 1 == len(siblings) else next(i for i, s in enumerate(siblings, 1) if s is child)
56
+ )
57
+ child = parent
58
+ xpath_tags.reverse()
59
+ xpath_subscripts.reverse()
60
+ return xpath_tags, xpath_subscripts
61
+
62
+ def get_three_from_single(self, html_string):
63
+ html_code = BeautifulSoup(html_string, "html.parser")
64
+
65
+ all_doc_strings = []
66
+ string2xtag_seq = []
67
+ string2xsubs_seq = []
68
+
69
+ for element in html_code.descendants:
70
+ if isinstance(element, bs4.element.NavigableString):
71
+ if type(element.parent) is not bs4.element.Tag:
72
+ continue
73
+
74
+ text_in_this_tag = html.unescape(element).strip()
75
+ if not text_in_this_tag:
76
+ continue
77
+
78
+ all_doc_strings.append(text_in_this_tag)
79
+
80
+ xpath_tags, xpath_subscripts = self.xpath_soup(element)
81
+ string2xtag_seq.append(xpath_tags)
82
+ string2xsubs_seq.append(xpath_subscripts)
83
+
84
+ if len(all_doc_strings) != len(string2xtag_seq):
85
+ raise ValueError("Number of doc strings and xtags does not correspond")
86
+ if len(all_doc_strings) != len(string2xsubs_seq):
87
+ raise ValueError("Number of doc strings and xsubs does not correspond")
88
+
89
+ return all_doc_strings, string2xtag_seq, string2xsubs_seq
90
+
91
+ def construct_xpath(self, xpath_tags, xpath_subscripts):
92
+ xpath = ""
93
+ for tagname, subs in zip(xpath_tags, xpath_subscripts):
94
+ xpath += f"/{tagname}"
95
+ if subs != 0:
96
+ xpath += f"[{subs}]"
97
+ return xpath
98
+
99
+ def __call__(self, html_strings) -> BatchFeature:
100
+ """
101
+ Main method to prepare for the model one or several HTML strings.
102
+
103
+ Args:
104
+ html_strings (`str`, `List[str]`):
105
+ The HTML string or batch of HTML strings from which to extract nodes and corresponding xpaths.
106
+
107
+ Returns:
108
+ [`BatchFeature`]: A [`BatchFeature`] with the following fields:
109
+
110
+ - **nodes** -- Nodes.
111
+ - **xpaths** -- Corresponding xpaths.
112
+
113
+ Examples:
114
+
115
+ ```python
116
+ >>> from transformers import MarkupLMFeatureExtractor
117
+
118
+ >>> page_name_1 = "page1.html"
119
+ >>> page_name_2 = "page2.html"
120
+ >>> page_name_3 = "page3.html"
121
+
122
+ >>> with open(page_name_1) as f:
123
+ ... single_html_string = f.read()
124
+
125
+ >>> feature_extractor = MarkupLMFeatureExtractor()
126
+
127
+ >>> # single example
128
+ >>> encoding = feature_extractor(single_html_string)
129
+ >>> print(encoding.keys())
130
+ >>> # dict_keys(['nodes', 'xpaths'])
131
+
132
+ >>> # batched example
133
+
134
+ >>> multi_html_strings = []
135
+
136
+ >>> with open(page_name_2) as f:
137
+ ... multi_html_strings.append(f.read())
138
+ >>> with open(page_name_3) as f:
139
+ ... multi_html_strings.append(f.read())
140
+
141
+ >>> encoding = feature_extractor(multi_html_strings)
142
+ >>> print(encoding.keys())
143
+ >>> # dict_keys(['nodes', 'xpaths'])
144
+ ```"""
145
+
146
+ # Input type checking for clearer error
147
+ valid_strings = False
148
+
149
+ # Check that strings has a valid type
150
+ if isinstance(html_strings, str):
151
+ valid_strings = True
152
+ elif isinstance(html_strings, (list, tuple)):
153
+ if len(html_strings) == 0 or isinstance(html_strings[0], str):
154
+ valid_strings = True
155
+
156
+ if not valid_strings:
157
+ raise ValueError(
158
+ "HTML strings must of type `str`, `List[str]` (batch of examples), "
159
+ f"but is of type {type(html_strings)}."
160
+ )
161
+
162
+ is_batched = bool(isinstance(html_strings, (list, tuple)) and (isinstance(html_strings[0], str)))
163
+
164
+ if not is_batched:
165
+ html_strings = [html_strings]
166
+
167
+ # Get nodes + xpaths
168
+ nodes = []
169
+ xpaths = []
170
+ for html_string in html_strings:
171
+ all_doc_strings, string2xtag_seq, string2xsubs_seq = self.get_three_from_single(html_string)
172
+ nodes.append(all_doc_strings)
173
+ xpath_strings = []
174
+ for node, tag_list, sub_list in zip(all_doc_strings, string2xtag_seq, string2xsubs_seq):
175
+ xpath_string = self.construct_xpath(tag_list, sub_list)
176
+ xpath_strings.append(xpath_string)
177
+ xpaths.append(xpath_strings)
178
+
179
+ # return as Dict
180
+ data = {"nodes": nodes, "xpaths": xpaths}
181
+ encoded_inputs = BatchFeature(data=data, tensor_type=None)
182
+
183
+ return encoded_inputs
184
+
185
+
186
+ __all__ = ["MarkupLMFeatureExtractor"]
tasks/tasksmith-441eeab80047/environment/source/src/transformers/models/markuplm/modeling_markuplm.py ADDED
@@ -0,0 +1,1303 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 Microsoft Research Asia 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 MarkupLM model."""
16
+
17
+ import math
18
+ import os
19
+ from typing import Optional, Tuple, Union
20
+
21
+ import torch
22
+ import torch.utils.checkpoint
23
+ from torch import nn
24
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
25
+
26
+ from ...activations import ACT2FN
27
+ from ...file_utils import (
28
+ add_start_docstrings,
29
+ add_start_docstrings_to_model_forward,
30
+ replace_return_docstrings,
31
+ )
32
+ from ...modeling_outputs import (
33
+ BaseModelOutputWithPastAndCrossAttentions,
34
+ BaseModelOutputWithPoolingAndCrossAttentions,
35
+ MaskedLMOutput,
36
+ QuestionAnsweringModelOutput,
37
+ SequenceClassifierOutput,
38
+ TokenClassifierOutput,
39
+ )
40
+ from ...modeling_utils import (
41
+ PreTrainedModel,
42
+ apply_chunking_to_forward,
43
+ find_pruneable_heads_and_indices,
44
+ prune_linear_layer,
45
+ )
46
+ from ...utils import logging
47
+ from .configuration_markuplm import MarkupLMConfig
48
+
49
+
50
+ logger = logging.get_logger(__name__)
51
+
52
+ _CHECKPOINT_FOR_DOC = "microsoft/markuplm-base"
53
+ _CONFIG_FOR_DOC = "MarkupLMConfig"
54
+
55
+
56
+ class XPathEmbeddings(nn.Module):
57
+ """Construct the embeddings from xpath tags and subscripts.
58
+
59
+ We drop tree-id in this version, as its info can be covered by xpath.
60
+ """
61
+
62
+ def __init__(self, config):
63
+ super(XPathEmbeddings, self).__init__()
64
+ self.max_depth = config.max_depth
65
+
66
+ self.xpath_unitseq2_embeddings = nn.Linear(config.xpath_unit_hidden_size * self.max_depth, config.hidden_size)
67
+
68
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
69
+
70
+ self.activation = nn.ReLU()
71
+ self.xpath_unitseq2_inner = nn.Linear(config.xpath_unit_hidden_size * self.max_depth, 4 * config.hidden_size)
72
+ self.inner2emb = nn.Linear(4 * config.hidden_size, config.hidden_size)
73
+
74
+ self.xpath_tag_sub_embeddings = nn.ModuleList(
75
+ [
76
+ nn.Embedding(config.max_xpath_tag_unit_embeddings, config.xpath_unit_hidden_size)
77
+ for _ in range(self.max_depth)
78
+ ]
79
+ )
80
+
81
+ self.xpath_subs_sub_embeddings = nn.ModuleList(
82
+ [
83
+ nn.Embedding(config.max_xpath_subs_unit_embeddings, config.xpath_unit_hidden_size)
84
+ for _ in range(self.max_depth)
85
+ ]
86
+ )
87
+
88
+ def forward(self, xpath_tags_seq=None, xpath_subs_seq=None):
89
+ xpath_tags_embeddings = []
90
+ xpath_subs_embeddings = []
91
+
92
+ for i in range(self.max_depth):
93
+ xpath_tags_embeddings.append(self.xpath_tag_sub_embeddings[i](xpath_tags_seq[:, :, i]))
94
+ xpath_subs_embeddings.append(self.xpath_subs_sub_embeddings[i](xpath_subs_seq[:, :, i]))
95
+
96
+ xpath_tags_embeddings = torch.cat(xpath_tags_embeddings, dim=-1)
97
+ xpath_subs_embeddings = torch.cat(xpath_subs_embeddings, dim=-1)
98
+
99
+ xpath_embeddings = xpath_tags_embeddings + xpath_subs_embeddings
100
+
101
+ xpath_embeddings = self.inner2emb(self.dropout(self.activation(self.xpath_unitseq2_inner(xpath_embeddings))))
102
+
103
+ return xpath_embeddings
104
+
105
+
106
+ # Copied from transformers.models.roberta.modeling_roberta.create_position_ids_from_input_ids
107
+ def create_position_ids_from_input_ids(input_ids, padding_idx, past_key_values_length=0):
108
+ """
109
+ Replace non-padding symbols with their position numbers. Position numbers begin at padding_idx+1. Padding symbols
110
+ are ignored. This is modified from fairseq's `utils.make_positions`.
111
+
112
+ Args:
113
+ x: torch.Tensor x:
114
+
115
+ Returns: torch.Tensor
116
+ """
117
+ # The series of casts and type-conversions here are carefully balanced to both work with ONNX export and XLA.
118
+ mask = input_ids.ne(padding_idx).int()
119
+ incremental_indices = (torch.cumsum(mask, dim=1).type_as(mask) + past_key_values_length) * mask
120
+ return incremental_indices.long() + padding_idx
121
+
122
+
123
+ class MarkupLMEmbeddings(nn.Module):
124
+ """Construct the embeddings from word, position and token_type embeddings."""
125
+
126
+ def __init__(self, config):
127
+ super(MarkupLMEmbeddings, self).__init__()
128
+ self.config = config
129
+ self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id)
130
+ self.position_embeddings = nn.Embedding(config.max_position_embeddings, config.hidden_size)
131
+
132
+ self.max_depth = config.max_depth
133
+
134
+ self.xpath_embeddings = XPathEmbeddings(config)
135
+
136
+ self.token_type_embeddings = nn.Embedding(config.type_vocab_size, config.hidden_size)
137
+
138
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
139
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
140
+
141
+ self.register_buffer(
142
+ "position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)), persistent=False
143
+ )
144
+
145
+ self.padding_idx = config.pad_token_id
146
+ self.position_embeddings = nn.Embedding(
147
+ config.max_position_embeddings, config.hidden_size, padding_idx=self.padding_idx
148
+ )
149
+
150
+ # Copied from transformers.models.roberta.modeling_roberta.RobertaEmbeddings.create_position_ids_from_inputs_embeds
151
+ def create_position_ids_from_inputs_embeds(self, inputs_embeds):
152
+ """
153
+ We are provided embeddings directly. We cannot infer which are padded so just generate sequential position ids.
154
+
155
+ Args:
156
+ inputs_embeds: torch.Tensor
157
+
158
+ Returns: torch.Tensor
159
+ """
160
+ input_shape = inputs_embeds.size()[:-1]
161
+ sequence_length = input_shape[1]
162
+
163
+ position_ids = torch.arange(
164
+ self.padding_idx + 1, sequence_length + self.padding_idx + 1, dtype=torch.long, device=inputs_embeds.device
165
+ )
166
+ return position_ids.unsqueeze(0).expand(input_shape)
167
+
168
+ def forward(
169
+ self,
170
+ input_ids=None,
171
+ xpath_tags_seq=None,
172
+ xpath_subs_seq=None,
173
+ token_type_ids=None,
174
+ position_ids=None,
175
+ inputs_embeds=None,
176
+ past_key_values_length=0,
177
+ ):
178
+ if input_ids is not None:
179
+ input_shape = input_ids.size()
180
+ else:
181
+ input_shape = inputs_embeds.size()[:-1]
182
+
183
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
184
+
185
+ if position_ids is None:
186
+ if input_ids is not None:
187
+ # Create the position ids from the input token ids. Any padded tokens remain padded.
188
+ position_ids = create_position_ids_from_input_ids(input_ids, self.padding_idx, past_key_values_length)
189
+ else:
190
+ position_ids = self.create_position_ids_from_inputs_embeds(inputs_embeds)
191
+
192
+ if token_type_ids is None:
193
+ token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=device)
194
+
195
+ if inputs_embeds is None:
196
+ inputs_embeds = self.word_embeddings(input_ids)
197
+
198
+ # prepare xpath seq
199
+ if xpath_tags_seq is None:
200
+ xpath_tags_seq = self.config.tag_pad_id * torch.ones(
201
+ tuple(list(input_shape) + [self.max_depth]), dtype=torch.long, device=device
202
+ )
203
+ if xpath_subs_seq is None:
204
+ xpath_subs_seq = self.config.subs_pad_id * torch.ones(
205
+ tuple(list(input_shape) + [self.max_depth]), dtype=torch.long, device=device
206
+ )
207
+
208
+ words_embeddings = inputs_embeds
209
+ position_embeddings = self.position_embeddings(position_ids)
210
+
211
+ token_type_embeddings = self.token_type_embeddings(token_type_ids)
212
+
213
+ xpath_embeddings = self.xpath_embeddings(xpath_tags_seq, xpath_subs_seq)
214
+ embeddings = words_embeddings + position_embeddings + token_type_embeddings + xpath_embeddings
215
+
216
+ embeddings = self.LayerNorm(embeddings)
217
+ embeddings = self.dropout(embeddings)
218
+ return embeddings
219
+
220
+
221
+ # Copied from transformers.models.bert.modeling_bert.BertSelfOutput with Bert->MarkupLM
222
+ class MarkupLMSelfOutput(nn.Module):
223
+ def __init__(self, config):
224
+ super().__init__()
225
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
226
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
227
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
228
+
229
+ def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
230
+ hidden_states = self.dense(hidden_states)
231
+ hidden_states = self.dropout(hidden_states)
232
+ hidden_states = self.LayerNorm(hidden_states + input_tensor)
233
+ return hidden_states
234
+
235
+
236
+ # Copied from transformers.models.bert.modeling_bert.BertIntermediate
237
+ class MarkupLMIntermediate(nn.Module):
238
+ def __init__(self, config):
239
+ super().__init__()
240
+ self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
241
+ if isinstance(config.hidden_act, str):
242
+ self.intermediate_act_fn = ACT2FN[config.hidden_act]
243
+ else:
244
+ self.intermediate_act_fn = config.hidden_act
245
+
246
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
247
+ hidden_states = self.dense(hidden_states)
248
+ hidden_states = self.intermediate_act_fn(hidden_states)
249
+ return hidden_states
250
+
251
+
252
+ # Copied from transformers.models.bert.modeling_bert.BertOutput with Bert->MarkupLM
253
+ class MarkupLMOutput(nn.Module):
254
+ def __init__(self, config):
255
+ super().__init__()
256
+ self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
257
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
258
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
259
+
260
+ def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
261
+ hidden_states = self.dense(hidden_states)
262
+ hidden_states = self.dropout(hidden_states)
263
+ hidden_states = self.LayerNorm(hidden_states + input_tensor)
264
+ return hidden_states
265
+
266
+
267
+ # Copied from transformers.models.bert.modeling_bert.BertPooler
268
+ class MarkupLMPooler(nn.Module):
269
+ def __init__(self, config):
270
+ super().__init__()
271
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
272
+ self.activation = nn.Tanh()
273
+
274
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
275
+ # We "pool" the model by simply taking the hidden state corresponding
276
+ # to the first token.
277
+ first_token_tensor = hidden_states[:, 0]
278
+ pooled_output = self.dense(first_token_tensor)
279
+ pooled_output = self.activation(pooled_output)
280
+ return pooled_output
281
+
282
+
283
+ # Copied from transformers.models.bert.modeling_bert.BertPredictionHeadTransform with Bert->MarkupLM
284
+ class MarkupLMPredictionHeadTransform(nn.Module):
285
+ def __init__(self, config):
286
+ super().__init__()
287
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
288
+ if isinstance(config.hidden_act, str):
289
+ self.transform_act_fn = ACT2FN[config.hidden_act]
290
+ else:
291
+ self.transform_act_fn = config.hidden_act
292
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
293
+
294
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
295
+ hidden_states = self.dense(hidden_states)
296
+ hidden_states = self.transform_act_fn(hidden_states)
297
+ hidden_states = self.LayerNorm(hidden_states)
298
+ return hidden_states
299
+
300
+
301
+ # Copied from transformers.models.bert.modeling_bert.BertLMPredictionHead with Bert->MarkupLM
302
+ class MarkupLMLMPredictionHead(nn.Module):
303
+ def __init__(self, config):
304
+ super().__init__()
305
+ self.transform = MarkupLMPredictionHeadTransform(config)
306
+
307
+ # The output weights are the same as the input embeddings, but there is
308
+ # an output-only bias for each token.
309
+ self.decoder = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
310
+
311
+ self.bias = nn.Parameter(torch.zeros(config.vocab_size))
312
+
313
+ # Need a link between the two variables so that the bias is correctly resized with `resize_token_embeddings`
314
+ self.decoder.bias = self.bias
315
+
316
+ def _tie_weights(self):
317
+ self.decoder.bias = self.bias
318
+
319
+ def forward(self, hidden_states):
320
+ hidden_states = self.transform(hidden_states)
321
+ hidden_states = self.decoder(hidden_states)
322
+ return hidden_states
323
+
324
+
325
+ # Copied from transformers.models.bert.modeling_bert.BertOnlyMLMHead with Bert->MarkupLM
326
+ class MarkupLMOnlyMLMHead(nn.Module):
327
+ def __init__(self, config):
328
+ super().__init__()
329
+ self.predictions = MarkupLMLMPredictionHead(config)
330
+
331
+ def forward(self, sequence_output: torch.Tensor) -> torch.Tensor:
332
+ prediction_scores = self.predictions(sequence_output)
333
+ return prediction_scores
334
+
335
+
336
+ # Copied from transformers.models.bert.modeling_bert.BertSelfAttention with Bert->MarkupLM
337
+ class MarkupLMSelfAttention(nn.Module):
338
+ def __init__(self, config, position_embedding_type=None):
339
+ super().__init__()
340
+ if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):
341
+ raise ValueError(
342
+ f"The hidden size ({config.hidden_size}) is not a multiple of the number of attention "
343
+ f"heads ({config.num_attention_heads})"
344
+ )
345
+
346
+ self.num_attention_heads = config.num_attention_heads
347
+ self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
348
+ self.all_head_size = self.num_attention_heads * self.attention_head_size
349
+
350
+ self.query = nn.Linear(config.hidden_size, self.all_head_size)
351
+ self.key = nn.Linear(config.hidden_size, self.all_head_size)
352
+ self.value = nn.Linear(config.hidden_size, self.all_head_size)
353
+
354
+ self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
355
+ self.position_embedding_type = position_embedding_type or getattr(
356
+ config, "position_embedding_type", "absolute"
357
+ )
358
+ if self.position_embedding_type == "relative_key" or self.position_embedding_type == "relative_key_query":
359
+ self.max_position_embeddings = config.max_position_embeddings
360
+ self.distance_embedding = nn.Embedding(2 * config.max_position_embeddings - 1, self.attention_head_size)
361
+
362
+ self.is_decoder = config.is_decoder
363
+
364
+ def transpose_for_scores(self, x: torch.Tensor) -> torch.Tensor:
365
+ new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.attention_head_size)
366
+ x = x.view(new_x_shape)
367
+ return x.permute(0, 2, 1, 3)
368
+
369
+ def forward(
370
+ self,
371
+ hidden_states: torch.Tensor,
372
+ attention_mask: Optional[torch.FloatTensor] = None,
373
+ head_mask: Optional[torch.FloatTensor] = None,
374
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
375
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
376
+ past_key_value: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
377
+ output_attentions: Optional[bool] = False,
378
+ ) -> Tuple[torch.Tensor]:
379
+ mixed_query_layer = self.query(hidden_states)
380
+
381
+ # If this is instantiated as a cross-attention module, the keys
382
+ # and values come from an encoder; the attention mask needs to be
383
+ # such that the encoder's padding tokens are not attended to.
384
+ is_cross_attention = encoder_hidden_states is not None
385
+
386
+ if is_cross_attention and past_key_value is not None:
387
+ # reuse k,v, cross_attentions
388
+ key_layer = past_key_value[0]
389
+ value_layer = past_key_value[1]
390
+ attention_mask = encoder_attention_mask
391
+ elif is_cross_attention:
392
+ key_layer = self.transpose_for_scores(self.key(encoder_hidden_states))
393
+ value_layer = self.transpose_for_scores(self.value(encoder_hidden_states))
394
+ attention_mask = encoder_attention_mask
395
+ elif past_key_value is not None:
396
+ key_layer = self.transpose_for_scores(self.key(hidden_states))
397
+ value_layer = self.transpose_for_scores(self.value(hidden_states))
398
+ key_layer = torch.cat([past_key_value[0], key_layer], dim=2)
399
+ value_layer = torch.cat([past_key_value[1], value_layer], dim=2)
400
+ else:
401
+ key_layer = self.transpose_for_scores(self.key(hidden_states))
402
+ value_layer = self.transpose_for_scores(self.value(hidden_states))
403
+
404
+ query_layer = self.transpose_for_scores(mixed_query_layer)
405
+
406
+ use_cache = past_key_value is not None
407
+ if self.is_decoder:
408
+ # if cross_attention save Tuple(torch.Tensor, torch.Tensor) of all cross attention key/value_states.
409
+ # Further calls to cross_attention layer can then reuse all cross-attention
410
+ # key/value_states (first "if" case)
411
+ # if uni-directional self-attention (decoder) save Tuple(torch.Tensor, torch.Tensor) of
412
+ # all previous decoder key/value_states. Further calls to uni-directional self-attention
413
+ # can concat previous decoder key/value_states to current projected key/value_states (third "elif" case)
414
+ # if encoder bi-directional self-attention `past_key_value` is always `None`
415
+ past_key_value = (key_layer, value_layer)
416
+
417
+ # Take the dot product between "query" and "key" to get the raw attention scores.
418
+ attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))
419
+
420
+ if self.position_embedding_type == "relative_key" or self.position_embedding_type == "relative_key_query":
421
+ query_length, key_length = query_layer.shape[2], key_layer.shape[2]
422
+ if use_cache:
423
+ position_ids_l = torch.tensor(key_length - 1, dtype=torch.long, device=hidden_states.device).view(
424
+ -1, 1
425
+ )
426
+ else:
427
+ position_ids_l = torch.arange(query_length, dtype=torch.long, device=hidden_states.device).view(-1, 1)
428
+ position_ids_r = torch.arange(key_length, dtype=torch.long, device=hidden_states.device).view(1, -1)
429
+ distance = position_ids_l - position_ids_r
430
+
431
+ positional_embedding = self.distance_embedding(distance + self.max_position_embeddings - 1)
432
+ positional_embedding = positional_embedding.to(dtype=query_layer.dtype) # fp16 compatibility
433
+
434
+ if self.position_embedding_type == "relative_key":
435
+ relative_position_scores = torch.einsum("bhld,lrd->bhlr", query_layer, positional_embedding)
436
+ attention_scores = attention_scores + relative_position_scores
437
+ elif self.position_embedding_type == "relative_key_query":
438
+ relative_position_scores_query = torch.einsum("bhld,lrd->bhlr", query_layer, positional_embedding)
439
+ relative_position_scores_key = torch.einsum("bhrd,lrd->bhlr", key_layer, positional_embedding)
440
+ attention_scores = attention_scores + relative_position_scores_query + relative_position_scores_key
441
+
442
+ attention_scores = attention_scores / math.sqrt(self.attention_head_size)
443
+ if attention_mask is not None:
444
+ # Apply the attention mask is (precomputed for all layers in MarkupLMModel forward() function)
445
+ attention_scores = attention_scores + attention_mask
446
+
447
+ # Normalize the attention scores to probabilities.
448
+ attention_probs = nn.functional.softmax(attention_scores, dim=-1)
449
+
450
+ # This is actually dropping out entire tokens to attend to, which might
451
+ # seem a bit unusual, but is taken from the original Transformer paper.
452
+ attention_probs = self.dropout(attention_probs)
453
+
454
+ # Mask heads if we want to
455
+ if head_mask is not None:
456
+ attention_probs = attention_probs * head_mask
457
+
458
+ context_layer = torch.matmul(attention_probs, value_layer)
459
+
460
+ context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
461
+ new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
462
+ context_layer = context_layer.view(new_context_layer_shape)
463
+
464
+ outputs = (context_layer, attention_probs) if output_attentions else (context_layer,)
465
+
466
+ if self.is_decoder:
467
+ outputs = outputs + (past_key_value,)
468
+ return outputs
469
+
470
+
471
+ MARKUPLM_SELF_ATTENTION_CLASSES = {
472
+ "eager": MarkupLMSelfAttention,
473
+ }
474
+
475
+
476
+ # Copied from transformers.models.bert.modeling_bert.BertAttention with Bert->MarkupLM,BERT->MARKUPLM
477
+ class MarkupLMAttention(nn.Module):
478
+ def __init__(self, config, position_embedding_type=None):
479
+ super().__init__()
480
+ self.self = MARKUPLM_SELF_ATTENTION_CLASSES[config._attn_implementation](
481
+ config, position_embedding_type=position_embedding_type
482
+ )
483
+ self.output = MarkupLMSelfOutput(config)
484
+ self.pruned_heads = set()
485
+
486
+ def prune_heads(self, heads):
487
+ if len(heads) == 0:
488
+ return
489
+ heads, index = find_pruneable_heads_and_indices(
490
+ heads, self.self.num_attention_heads, self.self.attention_head_size, self.pruned_heads
491
+ )
492
+
493
+ # Prune linear layers
494
+ self.self.query = prune_linear_layer(self.self.query, index)
495
+ self.self.key = prune_linear_layer(self.self.key, index)
496
+ self.self.value = prune_linear_layer(self.self.value, index)
497
+ self.output.dense = prune_linear_layer(self.output.dense, index, dim=1)
498
+
499
+ # Update hyper params and store pruned heads
500
+ self.self.num_attention_heads = self.self.num_attention_heads - len(heads)
501
+ self.self.all_head_size = self.self.attention_head_size * self.self.num_attention_heads
502
+ self.pruned_heads = self.pruned_heads.union(heads)
503
+
504
+ def forward(
505
+ self,
506
+ hidden_states: torch.Tensor,
507
+ attention_mask: Optional[torch.FloatTensor] = None,
508
+ head_mask: Optional[torch.FloatTensor] = None,
509
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
510
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
511
+ past_key_value: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
512
+ output_attentions: Optional[bool] = False,
513
+ ) -> Tuple[torch.Tensor]:
514
+ self_outputs = self.self(
515
+ hidden_states,
516
+ attention_mask,
517
+ head_mask,
518
+ encoder_hidden_states,
519
+ encoder_attention_mask,
520
+ past_key_value,
521
+ output_attentions,
522
+ )
523
+ attention_output = self.output(self_outputs[0], hidden_states)
524
+ outputs = (attention_output,) + self_outputs[1:] # add attentions if we output them
525
+ return outputs
526
+
527
+
528
+ # Copied from transformers.models.bert.modeling_bert.BertLayer with Bert->MarkupLM
529
+ class MarkupLMLayer(nn.Module):
530
+ def __init__(self, config):
531
+ super().__init__()
532
+ self.chunk_size_feed_forward = config.chunk_size_feed_forward
533
+ self.seq_len_dim = 1
534
+ self.attention = MarkupLMAttention(config)
535
+ self.is_decoder = config.is_decoder
536
+ self.add_cross_attention = config.add_cross_attention
537
+ if self.add_cross_attention:
538
+ if not self.is_decoder:
539
+ raise ValueError(f"{self} should be used as a decoder model if cross attention is added")
540
+ self.crossattention = MarkupLMAttention(config, position_embedding_type="absolute")
541
+ self.intermediate = MarkupLMIntermediate(config)
542
+ self.output = MarkupLMOutput(config)
543
+
544
+ def forward(
545
+ self,
546
+ hidden_states: torch.Tensor,
547
+ attention_mask: Optional[torch.FloatTensor] = None,
548
+ head_mask: Optional[torch.FloatTensor] = None,
549
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
550
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
551
+ past_key_value: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
552
+ output_attentions: Optional[bool] = False,
553
+ ) -> Tuple[torch.Tensor]:
554
+ # decoder uni-directional self-attention cached key/values tuple is at positions 1,2
555
+ self_attn_past_key_value = past_key_value[:2] if past_key_value is not None else None
556
+ self_attention_outputs = self.attention(
557
+ hidden_states,
558
+ attention_mask,
559
+ head_mask,
560
+ output_attentions=output_attentions,
561
+ past_key_value=self_attn_past_key_value,
562
+ )
563
+ attention_output = self_attention_outputs[0]
564
+
565
+ # if decoder, the last output is tuple of self-attn cache
566
+ if self.is_decoder:
567
+ outputs = self_attention_outputs[1:-1]
568
+ present_key_value = self_attention_outputs[-1]
569
+ else:
570
+ outputs = self_attention_outputs[1:] # add self attentions if we output attention weights
571
+
572
+ cross_attn_present_key_value = None
573
+ if self.is_decoder and encoder_hidden_states is not None:
574
+ if not hasattr(self, "crossattention"):
575
+ raise ValueError(
576
+ f"If `encoder_hidden_states` are passed, {self} has to be instantiated with cross-attention layers"
577
+ " by setting `config.add_cross_attention=True`"
578
+ )
579
+
580
+ # cross_attn cached key/values tuple is at positions 3,4 of past_key_value tuple
581
+ cross_attn_past_key_value = past_key_value[-2:] if past_key_value is not None else None
582
+ cross_attention_outputs = self.crossattention(
583
+ attention_output,
584
+ attention_mask,
585
+ head_mask,
586
+ encoder_hidden_states,
587
+ encoder_attention_mask,
588
+ cross_attn_past_key_value,
589
+ output_attentions,
590
+ )
591
+ attention_output = cross_attention_outputs[0]
592
+ outputs = outputs + cross_attention_outputs[1:-1] # add cross attentions if we output attention weights
593
+
594
+ # add cross-attn cache to positions 3,4 of present_key_value tuple
595
+ cross_attn_present_key_value = cross_attention_outputs[-1]
596
+ present_key_value = present_key_value + cross_attn_present_key_value
597
+
598
+ layer_output = apply_chunking_to_forward(
599
+ self.feed_forward_chunk, self.chunk_size_feed_forward, self.seq_len_dim, attention_output
600
+ )
601
+ outputs = (layer_output,) + outputs
602
+
603
+ # if decoder, return the attn key/values as the last output
604
+ if self.is_decoder:
605
+ outputs = outputs + (present_key_value,)
606
+
607
+ return outputs
608
+
609
+ def feed_forward_chunk(self, attention_output):
610
+ intermediate_output = self.intermediate(attention_output)
611
+ layer_output = self.output(intermediate_output, attention_output)
612
+ return layer_output
613
+
614
+
615
+ # Copied from transformers.models.bert.modeling_bert.BertEncoder with Bert->MarkupLM
616
+ class MarkupLMEncoder(nn.Module):
617
+ def __init__(self, config):
618
+ super().__init__()
619
+ self.config = config
620
+ self.layer = nn.ModuleList([MarkupLMLayer(config) for _ in range(config.num_hidden_layers)])
621
+ self.gradient_checkpointing = False
622
+
623
+ def forward(
624
+ self,
625
+ hidden_states: torch.Tensor,
626
+ attention_mask: Optional[torch.FloatTensor] = None,
627
+ head_mask: Optional[torch.FloatTensor] = None,
628
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
629
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
630
+ past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
631
+ use_cache: Optional[bool] = None,
632
+ output_attentions: Optional[bool] = False,
633
+ output_hidden_states: Optional[bool] = False,
634
+ return_dict: Optional[bool] = True,
635
+ ) -> Union[Tuple[torch.Tensor], BaseModelOutputWithPastAndCrossAttentions]:
636
+ all_hidden_states = () if output_hidden_states else None
637
+ all_self_attentions = () if output_attentions else None
638
+ all_cross_attentions = () if output_attentions and self.config.add_cross_attention else None
639
+
640
+ if self.gradient_checkpointing and self.training:
641
+ if use_cache:
642
+ logger.warning_once(
643
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
644
+ )
645
+ use_cache = False
646
+
647
+ next_decoder_cache = () if use_cache else None
648
+ for i, layer_module in enumerate(self.layer):
649
+ if output_hidden_states:
650
+ all_hidden_states = all_hidden_states + (hidden_states,)
651
+
652
+ layer_head_mask = head_mask[i] if head_mask is not None else None
653
+ past_key_value = past_key_values[i] if past_key_values is not None else None
654
+
655
+ if self.gradient_checkpointing and self.training:
656
+ layer_outputs = self._gradient_checkpointing_func(
657
+ layer_module.__call__,
658
+ hidden_states,
659
+ attention_mask,
660
+ layer_head_mask,
661
+ encoder_hidden_states,
662
+ encoder_attention_mask,
663
+ past_key_value,
664
+ output_attentions,
665
+ )
666
+ else:
667
+ layer_outputs = layer_module(
668
+ hidden_states,
669
+ attention_mask,
670
+ layer_head_mask,
671
+ encoder_hidden_states,
672
+ encoder_attention_mask,
673
+ past_key_value,
674
+ output_attentions,
675
+ )
676
+
677
+ hidden_states = layer_outputs[0]
678
+ if use_cache:
679
+ next_decoder_cache += (layer_outputs[-1],)
680
+ if output_attentions:
681
+ all_self_attentions = all_self_attentions + (layer_outputs[1],)
682
+ if self.config.add_cross_attention:
683
+ all_cross_attentions = all_cross_attentions + (layer_outputs[2],)
684
+
685
+ if output_hidden_states:
686
+ all_hidden_states = all_hidden_states + (hidden_states,)
687
+
688
+ if not return_dict:
689
+ return tuple(
690
+ v
691
+ for v in [
692
+ hidden_states,
693
+ next_decoder_cache,
694
+ all_hidden_states,
695
+ all_self_attentions,
696
+ all_cross_attentions,
697
+ ]
698
+ if v is not None
699
+ )
700
+ return BaseModelOutputWithPastAndCrossAttentions(
701
+ last_hidden_state=hidden_states,
702
+ past_key_values=next_decoder_cache,
703
+ hidden_states=all_hidden_states,
704
+ attentions=all_self_attentions,
705
+ cross_attentions=all_cross_attentions,
706
+ )
707
+
708
+
709
+ class MarkupLMPreTrainedModel(PreTrainedModel):
710
+ """
711
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
712
+ models.
713
+ """
714
+
715
+ config_class = MarkupLMConfig
716
+ base_model_prefix = "markuplm"
717
+
718
+ # Copied from transformers.models.bert.modeling_bert.BertPreTrainedModel._init_weights with Bert->MarkupLM
719
+ def _init_weights(self, module):
720
+ """Initialize the weights"""
721
+ if isinstance(module, nn.Linear):
722
+ # Slightly different from the TF version which uses truncated_normal for initialization
723
+ # cf https://github.com/pytorch/pytorch/pull/5617
724
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
725
+ if module.bias is not None:
726
+ module.bias.data.zero_()
727
+ elif isinstance(module, nn.Embedding):
728
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
729
+ if module.padding_idx is not None:
730
+ module.weight.data[module.padding_idx].zero_()
731
+ elif isinstance(module, nn.LayerNorm):
732
+ module.bias.data.zero_()
733
+ module.weight.data.fill_(1.0)
734
+
735
+ @classmethod
736
+ def from_pretrained(cls, pretrained_model_name_or_path: Optional[Union[str, os.PathLike]], *model_args, **kwargs):
737
+ return super(MarkupLMPreTrainedModel, cls).from_pretrained(
738
+ pretrained_model_name_or_path, *model_args, **kwargs
739
+ )
740
+
741
+
742
+ MARKUPLM_START_DOCSTRING = r"""
743
+ This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) sub-class. Use
744
+ it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and
745
+ behavior.
746
+
747
+ Parameters:
748
+ config ([`MarkupLMConfig`]): Model configuration class with all the parameters of the model.
749
+ Initializing with a config file does not load the weights associated with the model, only the
750
+ configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
751
+ """
752
+
753
+ MARKUPLM_INPUTS_DOCSTRING = r"""
754
+ Args:
755
+ input_ids (`torch.LongTensor` of shape `({0})`):
756
+ Indices of input sequence tokens in the vocabulary.
757
+
758
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
759
+ [`PreTrainedTokenizer.__call__`] for details.
760
+
761
+ [What are input IDs?](../glossary#input-ids)
762
+
763
+ xpath_tags_seq (`torch.LongTensor` of shape `({0}, config.max_depth)`, *optional*):
764
+ Tag IDs for each token in the input sequence, padded up to config.max_depth.
765
+
766
+ xpath_subs_seq (`torch.LongTensor` of shape `({0}, config.max_depth)`, *optional*):
767
+ Subscript IDs for each token in the input sequence, padded up to config.max_depth.
768
+
769
+ attention_mask (`torch.FloatTensor` of shape `({0})`, *optional*):
770
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`: `1` for
771
+ tokens that are NOT MASKED, `0` for MASKED tokens.
772
+
773
+ [What are attention masks?](../glossary#attention-mask)
774
+ token_type_ids (`torch.LongTensor` of shape `({0})`, *optional*):
775
+ Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
776
+ 1]`: `0` corresponds to a *sentence A* token, `1` corresponds to a *sentence B* token
777
+
778
+ [What are token type IDs?](../glossary#token-type-ids)
779
+ position_ids (`torch.LongTensor` of shape `({0})`, *optional*):
780
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
781
+ config.max_position_embeddings - 1]`.
782
+
783
+ [What are position IDs?](../glossary#position-ids)
784
+ head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
785
+ Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`: `1`
786
+ indicates the head is **not masked**, `0` indicates the head is **masked**.
787
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
788
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
789
+ is useful if you want more control over how to convert *input_ids* indices into associated vectors than the
790
+ model's internal embedding lookup matrix.
791
+ output_attentions (`bool`, *optional*):
792
+ If set to `True`, the attentions tensors of all attention layers are returned. See `attentions` under
793
+ returned tensors for more detail.
794
+ output_hidden_states (`bool`, *optional*):
795
+ If set to `True`, the hidden states of all layers are returned. See `hidden_states` under returned tensors
796
+ for more detail.
797
+ return_dict (`bool`, *optional*):
798
+ If set to `True`, the model will return a [`~file_utils.ModelOutput`] instead of a plain tuple.
799
+ """
800
+
801
+
802
+ @add_start_docstrings(
803
+ "The bare MarkupLM Model transformer outputting raw hidden-states without any specific head on top.",
804
+ MARKUPLM_START_DOCSTRING,
805
+ )
806
+ class MarkupLMModel(MarkupLMPreTrainedModel):
807
+ # Copied from transformers.models.clap.modeling_clap.ClapTextModel.__init__ with ClapText->MarkupLM
808
+ def __init__(self, config, add_pooling_layer=True):
809
+ super().__init__(config)
810
+ self.config = config
811
+
812
+ self.embeddings = MarkupLMEmbeddings(config)
813
+ self.encoder = MarkupLMEncoder(config)
814
+
815
+ self.pooler = MarkupLMPooler(config) if add_pooling_layer else None
816
+
817
+ # Initialize weights and apply final processing
818
+ self.post_init()
819
+
820
+ def get_input_embeddings(self):
821
+ return self.embeddings.word_embeddings
822
+
823
+ def set_input_embeddings(self, value):
824
+ self.embeddings.word_embeddings = value
825
+
826
+ def _prune_heads(self, heads_to_prune):
827
+ """
828
+ Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
829
+ class PreTrainedModel
830
+ """
831
+ for layer, heads in heads_to_prune.items():
832
+ self.encoder.layer[layer].attention.prune_heads(heads)
833
+
834
+ @add_start_docstrings_to_model_forward(MARKUPLM_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
835
+ @replace_return_docstrings(output_type=BaseModelOutputWithPoolingAndCrossAttentions, config_class=_CONFIG_FOR_DOC)
836
+ def forward(
837
+ self,
838
+ input_ids: Optional[torch.LongTensor] = None,
839
+ xpath_tags_seq: Optional[torch.LongTensor] = None,
840
+ xpath_subs_seq: Optional[torch.LongTensor] = None,
841
+ attention_mask: Optional[torch.FloatTensor] = None,
842
+ token_type_ids: Optional[torch.LongTensor] = None,
843
+ position_ids: Optional[torch.LongTensor] = None,
844
+ head_mask: Optional[torch.FloatTensor] = None,
845
+ inputs_embeds: Optional[torch.FloatTensor] = None,
846
+ output_attentions: Optional[bool] = None,
847
+ output_hidden_states: Optional[bool] = None,
848
+ return_dict: Optional[bool] = None,
849
+ ) -> Union[Tuple, BaseModelOutputWithPoolingAndCrossAttentions]:
850
+ r"""
851
+ Returns:
852
+
853
+ Examples:
854
+
855
+ ```python
856
+ >>> from transformers import AutoProcessor, MarkupLMModel
857
+
858
+ >>> processor = AutoProcessor.from_pretrained("microsoft/markuplm-base")
859
+ >>> model = MarkupLMModel.from_pretrained("microsoft/markuplm-base")
860
+
861
+ >>> html_string = "<html> <head> <title>Page Title</title> </head> </html>"
862
+
863
+ >>> encoding = processor(html_string, return_tensors="pt")
864
+
865
+ >>> outputs = model(**encoding)
866
+ >>> last_hidden_states = outputs.last_hidden_state
867
+ >>> list(last_hidden_states.shape)
868
+ [1, 4, 768]
869
+ ```"""
870
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
871
+ output_hidden_states = (
872
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
873
+ )
874
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
875
+
876
+ if input_ids is not None and inputs_embeds is not None:
877
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
878
+ elif input_ids is not None:
879
+ self.warn_if_padding_and_no_attention_mask(input_ids, attention_mask)
880
+ input_shape = input_ids.size()
881
+ elif inputs_embeds is not None:
882
+ input_shape = inputs_embeds.size()[:-1]
883
+ else:
884
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
885
+
886
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
887
+
888
+ if attention_mask is None:
889
+ attention_mask = torch.ones(input_shape, device=device)
890
+
891
+ if token_type_ids is None:
892
+ token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=device)
893
+
894
+ extended_attention_mask = attention_mask.unsqueeze(1).unsqueeze(2)
895
+ extended_attention_mask = extended_attention_mask.to(dtype=self.dtype)
896
+ extended_attention_mask = (1.0 - extended_attention_mask) * -10000.0
897
+
898
+ if head_mask is not None:
899
+ if head_mask.dim() == 1:
900
+ head_mask = head_mask.unsqueeze(0).unsqueeze(0).unsqueeze(-1).unsqueeze(-1)
901
+ head_mask = head_mask.expand(self.config.num_hidden_layers, -1, -1, -1, -1)
902
+ elif head_mask.dim() == 2:
903
+ head_mask = head_mask.unsqueeze(1).unsqueeze(-1).unsqueeze(-1)
904
+ head_mask = head_mask.to(dtype=next(self.parameters()).dtype)
905
+ else:
906
+ head_mask = [None] * self.config.num_hidden_layers
907
+
908
+ embedding_output = self.embeddings(
909
+ input_ids=input_ids,
910
+ xpath_tags_seq=xpath_tags_seq,
911
+ xpath_subs_seq=xpath_subs_seq,
912
+ position_ids=position_ids,
913
+ token_type_ids=token_type_ids,
914
+ inputs_embeds=inputs_embeds,
915
+ )
916
+ encoder_outputs = self.encoder(
917
+ embedding_output,
918
+ extended_attention_mask,
919
+ head_mask=head_mask,
920
+ output_attentions=output_attentions,
921
+ output_hidden_states=output_hidden_states,
922
+ return_dict=return_dict,
923
+ )
924
+ sequence_output = encoder_outputs[0]
925
+
926
+ pooled_output = self.pooler(sequence_output) if self.pooler is not None else None
927
+
928
+ if not return_dict:
929
+ return (sequence_output, pooled_output) + encoder_outputs[1:]
930
+
931
+ return BaseModelOutputWithPoolingAndCrossAttentions(
932
+ last_hidden_state=sequence_output,
933
+ pooler_output=pooled_output,
934
+ hidden_states=encoder_outputs.hidden_states,
935
+ attentions=encoder_outputs.attentions,
936
+ cross_attentions=encoder_outputs.cross_attentions,
937
+ )
938
+
939
+ # Copied from transformers.models.bert.modeling_bert.BertModel._reorder_cache
940
+ def _reorder_cache(self, past_key_values, beam_idx):
941
+ reordered_past = ()
942
+ for layer_past in past_key_values:
943
+ reordered_past += (
944
+ tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
945
+ )
946
+ return reordered_past
947
+
948
+
949
+ @add_start_docstrings(
950
+ """
951
+ MarkupLM Model with a span classification head on top for extractive question-answering tasks like SQuAD (a linear
952
+ layers on top of the hidden-states output to compute `span start logits` and `span end logits`).
953
+ """,
954
+ MARKUPLM_START_DOCSTRING,
955
+ )
956
+ class MarkupLMForQuestionAnswering(MarkupLMPreTrainedModel):
957
+ # Copied from transformers.models.bert.modeling_bert.BertForQuestionAnswering.__init__ with bert->markuplm, Bert->MarkupLM
958
+ def __init__(self, config):
959
+ super().__init__(config)
960
+ self.num_labels = config.num_labels
961
+
962
+ self.markuplm = MarkupLMModel(config, add_pooling_layer=False)
963
+ self.qa_outputs = nn.Linear(config.hidden_size, config.num_labels)
964
+
965
+ # Initialize weights and apply final processing
966
+ self.post_init()
967
+
968
+ @add_start_docstrings_to_model_forward(MARKUPLM_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
969
+ @replace_return_docstrings(output_type=QuestionAnsweringModelOutput, config_class=_CONFIG_FOR_DOC)
970
+ def forward(
971
+ self,
972
+ input_ids: Optional[torch.Tensor] = None,
973
+ xpath_tags_seq: Optional[torch.Tensor] = None,
974
+ xpath_subs_seq: Optional[torch.Tensor] = None,
975
+ attention_mask: Optional[torch.Tensor] = None,
976
+ token_type_ids: Optional[torch.Tensor] = None,
977
+ position_ids: Optional[torch.Tensor] = None,
978
+ head_mask: Optional[torch.Tensor] = None,
979
+ inputs_embeds: Optional[torch.Tensor] = None,
980
+ start_positions: Optional[torch.Tensor] = None,
981
+ end_positions: Optional[torch.Tensor] = None,
982
+ output_attentions: Optional[bool] = None,
983
+ output_hidden_states: Optional[bool] = None,
984
+ return_dict: Optional[bool] = None,
985
+ ) -> Union[Tuple[torch.Tensor], QuestionAnsweringModelOutput]:
986
+ r"""
987
+ start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
988
+ Labels for position (index) of the start of the labelled span for computing the token classification loss.
989
+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
990
+ are not taken into account for computing the loss.
991
+ end_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
992
+ Labels for position (index) of the end of the labelled span for computing the token classification loss.
993
+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
994
+ are not taken into account for computing the loss.
995
+
996
+ Returns:
997
+
998
+ Examples:
999
+
1000
+ ```python
1001
+ >>> from transformers import AutoProcessor, MarkupLMForQuestionAnswering
1002
+ >>> import torch
1003
+
1004
+ >>> processor = AutoProcessor.from_pretrained("microsoft/markuplm-base-finetuned-websrc")
1005
+ >>> model = MarkupLMForQuestionAnswering.from_pretrained("microsoft/markuplm-base-finetuned-websrc")
1006
+
1007
+ >>> html_string = "<html> <head> <title>My name is Niels</title> </head> </html>"
1008
+ >>> question = "What's his name?"
1009
+
1010
+ >>> encoding = processor(html_string, questions=question, return_tensors="pt")
1011
+
1012
+ >>> with torch.no_grad():
1013
+ ... outputs = model(**encoding)
1014
+
1015
+ >>> answer_start_index = outputs.start_logits.argmax()
1016
+ >>> answer_end_index = outputs.end_logits.argmax()
1017
+
1018
+ >>> predict_answer_tokens = encoding.input_ids[0, answer_start_index : answer_end_index + 1]
1019
+ >>> processor.decode(predict_answer_tokens).strip()
1020
+ 'Niels'
1021
+ ```"""
1022
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1023
+
1024
+ outputs = self.markuplm(
1025
+ input_ids,
1026
+ xpath_tags_seq=xpath_tags_seq,
1027
+ xpath_subs_seq=xpath_subs_seq,
1028
+ attention_mask=attention_mask,
1029
+ token_type_ids=token_type_ids,
1030
+ position_ids=position_ids,
1031
+ head_mask=head_mask,
1032
+ inputs_embeds=inputs_embeds,
1033
+ output_attentions=output_attentions,
1034
+ output_hidden_states=output_hidden_states,
1035
+ return_dict=return_dict,
1036
+ )
1037
+
1038
+ sequence_output = outputs[0]
1039
+
1040
+ logits = self.qa_outputs(sequence_output)
1041
+ start_logits, end_logits = logits.split(1, dim=-1)
1042
+ start_logits = start_logits.squeeze(-1).contiguous()
1043
+ end_logits = end_logits.squeeze(-1).contiguous()
1044
+
1045
+ total_loss = None
1046
+ if start_positions is not None and end_positions is not None:
1047
+ # If we are on multi-GPU, split add a dimension
1048
+ if len(start_positions.size()) > 1:
1049
+ start_positions = start_positions.squeeze(-1)
1050
+ if len(end_positions.size()) > 1:
1051
+ end_positions = end_positions.squeeze(-1)
1052
+ # sometimes the start/end positions are outside our model inputs, we ignore these terms
1053
+ ignored_index = start_logits.size(1)
1054
+ start_positions.clamp_(0, ignored_index)
1055
+ end_positions.clamp_(0, ignored_index)
1056
+
1057
+ loss_fct = CrossEntropyLoss(ignore_index=ignored_index)
1058
+ start_loss = loss_fct(start_logits, start_positions)
1059
+ end_loss = loss_fct(end_logits, end_positions)
1060
+ total_loss = (start_loss + end_loss) / 2
1061
+
1062
+ if not return_dict:
1063
+ output = (start_logits, end_logits) + outputs[2:]
1064
+ return ((total_loss,) + output) if total_loss is not None else output
1065
+
1066
+ return QuestionAnsweringModelOutput(
1067
+ loss=total_loss,
1068
+ start_logits=start_logits,
1069
+ end_logits=end_logits,
1070
+ hidden_states=outputs.hidden_states,
1071
+ attentions=outputs.attentions,
1072
+ )
1073
+
1074
+
1075
+ @add_start_docstrings("""MarkupLM Model with a `token_classification` head on top.""", MARKUPLM_START_DOCSTRING)
1076
+ class MarkupLMForTokenClassification(MarkupLMPreTrainedModel):
1077
+ # Copied from transformers.models.bert.modeling_bert.BertForTokenClassification.__init__ with bert->markuplm, Bert->MarkupLM
1078
+ def __init__(self, config):
1079
+ super().__init__(config)
1080
+ self.num_labels = config.num_labels
1081
+
1082
+ self.markuplm = MarkupLMModel(config, add_pooling_layer=False)
1083
+ classifier_dropout = (
1084
+ config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob
1085
+ )
1086
+ self.dropout = nn.Dropout(classifier_dropout)
1087
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels)
1088
+
1089
+ # Initialize weights and apply final processing
1090
+ self.post_init()
1091
+
1092
+ @add_start_docstrings_to_model_forward(MARKUPLM_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
1093
+ @replace_return_docstrings(output_type=MaskedLMOutput, config_class=_CONFIG_FOR_DOC)
1094
+ def forward(
1095
+ self,
1096
+ input_ids: Optional[torch.Tensor] = None,
1097
+ xpath_tags_seq: Optional[torch.Tensor] = None,
1098
+ xpath_subs_seq: Optional[torch.Tensor] = None,
1099
+ attention_mask: Optional[torch.Tensor] = None,
1100
+ token_type_ids: Optional[torch.Tensor] = None,
1101
+ position_ids: Optional[torch.Tensor] = None,
1102
+ head_mask: Optional[torch.Tensor] = None,
1103
+ inputs_embeds: Optional[torch.Tensor] = None,
1104
+ labels: Optional[torch.Tensor] = None,
1105
+ output_attentions: Optional[bool] = None,
1106
+ output_hidden_states: Optional[bool] = None,
1107
+ return_dict: Optional[bool] = None,
1108
+ ) -> Union[Tuple[torch.Tensor], MaskedLMOutput]:
1109
+ r"""
1110
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1111
+ Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`.
1112
+
1113
+ Returns:
1114
+
1115
+ Examples:
1116
+
1117
+ ```python
1118
+ >>> from transformers import AutoProcessor, AutoModelForTokenClassification
1119
+ >>> import torch
1120
+
1121
+ >>> processor = AutoProcessor.from_pretrained("microsoft/markuplm-base")
1122
+ >>> processor.parse_html = False
1123
+ >>> model = AutoModelForTokenClassification.from_pretrained("microsoft/markuplm-base", num_labels=7)
1124
+
1125
+ >>> nodes = ["hello", "world"]
1126
+ >>> xpaths = ["/html/body/div/li[1]/div/span", "/html/body/div/li[1]/div/span"]
1127
+ >>> node_labels = [1, 2]
1128
+ >>> encoding = processor(nodes=nodes, xpaths=xpaths, node_labels=node_labels, return_tensors="pt")
1129
+
1130
+ >>> with torch.no_grad():
1131
+ ... outputs = model(**encoding)
1132
+
1133
+ >>> loss = outputs.loss
1134
+ >>> logits = outputs.logits
1135
+ ```"""
1136
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1137
+
1138
+ outputs = self.markuplm(
1139
+ input_ids,
1140
+ xpath_tags_seq=xpath_tags_seq,
1141
+ xpath_subs_seq=xpath_subs_seq,
1142
+ attention_mask=attention_mask,
1143
+ token_type_ids=token_type_ids,
1144
+ position_ids=position_ids,
1145
+ head_mask=head_mask,
1146
+ inputs_embeds=inputs_embeds,
1147
+ output_attentions=output_attentions,
1148
+ output_hidden_states=output_hidden_states,
1149
+ return_dict=return_dict,
1150
+ )
1151
+
1152
+ sequence_output = outputs[0]
1153
+ prediction_scores = self.classifier(sequence_output) # (batch_size, seq_length, node_type_size)
1154
+
1155
+ loss = None
1156
+ if labels is not None:
1157
+ loss_fct = CrossEntropyLoss()
1158
+ loss = loss_fct(
1159
+ prediction_scores.view(-1, self.config.num_labels),
1160
+ labels.view(-1),
1161
+ )
1162
+
1163
+ if not return_dict:
1164
+ output = (prediction_scores,) + outputs[2:]
1165
+ return ((loss,) + output) if loss is not None else output
1166
+
1167
+ return TokenClassifierOutput(
1168
+ loss=loss,
1169
+ logits=prediction_scores,
1170
+ hidden_states=outputs.hidden_states,
1171
+ attentions=outputs.attentions,
1172
+ )
1173
+
1174
+
1175
+ @add_start_docstrings(
1176
+ """
1177
+ MarkupLM Model transformer with a sequence classification/regression head on top (a linear layer on top of the
1178
+ pooled output) e.g. for GLUE tasks.
1179
+ """,
1180
+ MARKUPLM_START_DOCSTRING,
1181
+ )
1182
+ class MarkupLMForSequenceClassification(MarkupLMPreTrainedModel):
1183
+ # Copied from transformers.models.bert.modeling_bert.BertForSequenceClassification.__init__ with bert->markuplm, Bert->MarkupLM
1184
+ def __init__(self, config):
1185
+ super().__init__(config)
1186
+ self.num_labels = config.num_labels
1187
+ self.config = config
1188
+
1189
+ self.markuplm = MarkupLMModel(config)
1190
+ classifier_dropout = (
1191
+ config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob
1192
+ )
1193
+ self.dropout = nn.Dropout(classifier_dropout)
1194
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels)
1195
+
1196
+ # Initialize weights and apply final processing
1197
+ self.post_init()
1198
+
1199
+ @add_start_docstrings_to_model_forward(MARKUPLM_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
1200
+ @replace_return_docstrings(output_type=SequenceClassifierOutput, config_class=_CONFIG_FOR_DOC)
1201
+ def forward(
1202
+ self,
1203
+ input_ids: Optional[torch.Tensor] = None,
1204
+ xpath_tags_seq: Optional[torch.Tensor] = None,
1205
+ xpath_subs_seq: Optional[torch.Tensor] = None,
1206
+ attention_mask: Optional[torch.Tensor] = None,
1207
+ token_type_ids: Optional[torch.Tensor] = None,
1208
+ position_ids: Optional[torch.Tensor] = None,
1209
+ head_mask: Optional[torch.Tensor] = None,
1210
+ inputs_embeds: Optional[torch.Tensor] = None,
1211
+ labels: Optional[torch.Tensor] = None,
1212
+ output_attentions: Optional[bool] = None,
1213
+ output_hidden_states: Optional[bool] = None,
1214
+ return_dict: Optional[bool] = None,
1215
+ ) -> Union[Tuple[torch.Tensor], SequenceClassifierOutput]:
1216
+ r"""
1217
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1218
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1219
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1220
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1221
+
1222
+ Returns:
1223
+
1224
+ Examples:
1225
+
1226
+ ```python
1227
+ >>> from transformers import AutoProcessor, AutoModelForSequenceClassification
1228
+ >>> import torch
1229
+
1230
+ >>> processor = AutoProcessor.from_pretrained("microsoft/markuplm-base")
1231
+ >>> model = AutoModelForSequenceClassification.from_pretrained("microsoft/markuplm-base", num_labels=7)
1232
+
1233
+ >>> html_string = "<html> <head> <title>Page Title</title> </head> </html>"
1234
+ >>> encoding = processor(html_string, return_tensors="pt")
1235
+
1236
+ >>> with torch.no_grad():
1237
+ ... outputs = model(**encoding)
1238
+
1239
+ >>> loss = outputs.loss
1240
+ >>> logits = outputs.logits
1241
+ ```"""
1242
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1243
+
1244
+ outputs = self.markuplm(
1245
+ input_ids,
1246
+ xpath_tags_seq=xpath_tags_seq,
1247
+ xpath_subs_seq=xpath_subs_seq,
1248
+ attention_mask=attention_mask,
1249
+ token_type_ids=token_type_ids,
1250
+ position_ids=position_ids,
1251
+ head_mask=head_mask,
1252
+ inputs_embeds=inputs_embeds,
1253
+ output_attentions=output_attentions,
1254
+ output_hidden_states=output_hidden_states,
1255
+ return_dict=return_dict,
1256
+ )
1257
+
1258
+ pooled_output = outputs[1]
1259
+
1260
+ pooled_output = self.dropout(pooled_output)
1261
+ logits = self.classifier(pooled_output)
1262
+
1263
+ loss = None
1264
+ if labels is not None:
1265
+ if self.config.problem_type is None:
1266
+ if self.num_labels == 1:
1267
+ self.config.problem_type = "regression"
1268
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1269
+ self.config.problem_type = "single_label_classification"
1270
+ else:
1271
+ self.config.problem_type = "multi_label_classification"
1272
+
1273
+ if self.config.problem_type == "regression":
1274
+ loss_fct = MSELoss()
1275
+ if self.num_labels == 1:
1276
+ loss = loss_fct(logits.squeeze(), labels.squeeze())
1277
+ else:
1278
+ loss = loss_fct(logits, labels)
1279
+ elif self.config.problem_type == "single_label_classification":
1280
+ loss_fct = CrossEntropyLoss()
1281
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
1282
+ elif self.config.problem_type == "multi_label_classification":
1283
+ loss_fct = BCEWithLogitsLoss()
1284
+ loss = loss_fct(logits, labels)
1285
+ if not return_dict:
1286
+ output = (logits,) + outputs[2:]
1287
+ return ((loss,) + output) if loss is not None else output
1288
+
1289
+ return SequenceClassifierOutput(
1290
+ loss=loss,
1291
+ logits=logits,
1292
+ hidden_states=outputs.hidden_states,
1293
+ attentions=outputs.attentions,
1294
+ )
1295
+
1296
+
1297
+ __all__ = [
1298
+ "MarkupLMForQuestionAnswering",
1299
+ "MarkupLMForSequenceClassification",
1300
+ "MarkupLMForTokenClassification",
1301
+ "MarkupLMModel",
1302
+ "MarkupLMPreTrainedModel",
1303
+ ]
tasks/tasksmith-441eeab80047/environment/source/src/transformers/models/markuplm/processing_markuplm.py ADDED
@@ -0,0 +1,150 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 The HuggingFace Inc. team.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """
16
+ Processor class for MarkupLM.
17
+ """
18
+
19
+ from typing import Optional, Union
20
+
21
+ from ...file_utils import TensorType
22
+ from ...processing_utils import ProcessorMixin
23
+ from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, TruncationStrategy
24
+
25
+
26
+ class MarkupLMProcessor(ProcessorMixin):
27
+ r"""
28
+ Constructs a MarkupLM processor which combines a MarkupLM feature extractor and a MarkupLM tokenizer into a single
29
+ processor.
30
+
31
+ [`MarkupLMProcessor`] offers all the functionalities you need to prepare data for the model.
32
+
33
+ It first uses [`MarkupLMFeatureExtractor`] to extract nodes and corresponding xpaths from one or more HTML strings.
34
+ Next, these are provided to [`MarkupLMTokenizer`] or [`MarkupLMTokenizerFast`], which turns them into token-level
35
+ `input_ids`, `attention_mask`, `token_type_ids`, `xpath_tags_seq` and `xpath_subs_seq`.
36
+
37
+ Args:
38
+ feature_extractor (`MarkupLMFeatureExtractor`):
39
+ An instance of [`MarkupLMFeatureExtractor`]. The feature extractor is a required input.
40
+ tokenizer (`MarkupLMTokenizer` or `MarkupLMTokenizerFast`):
41
+ An instance of [`MarkupLMTokenizer`] or [`MarkupLMTokenizerFast`]. The tokenizer is a required input.
42
+ parse_html (`bool`, *optional*, defaults to `True`):
43
+ Whether or not to use `MarkupLMFeatureExtractor` to parse HTML strings into nodes and corresponding xpaths.
44
+ """
45
+
46
+ feature_extractor_class = "MarkupLMFeatureExtractor"
47
+ tokenizer_class = ("MarkupLMTokenizer", "MarkupLMTokenizerFast")
48
+ parse_html = True
49
+
50
+ def __call__(
51
+ self,
52
+ html_strings=None,
53
+ nodes=None,
54
+ xpaths=None,
55
+ node_labels=None,
56
+ questions=None,
57
+ add_special_tokens: bool = True,
58
+ padding: Union[bool, str, PaddingStrategy] = False,
59
+ truncation: Union[bool, str, TruncationStrategy] = None,
60
+ max_length: Optional[int] = None,
61
+ stride: int = 0,
62
+ pad_to_multiple_of: Optional[int] = None,
63
+ return_token_type_ids: Optional[bool] = None,
64
+ return_attention_mask: Optional[bool] = None,
65
+ return_overflowing_tokens: bool = False,
66
+ return_special_tokens_mask: bool = False,
67
+ return_offsets_mapping: bool = False,
68
+ return_length: bool = False,
69
+ verbose: bool = True,
70
+ return_tensors: Optional[Union[str, TensorType]] = None,
71
+ **kwargs,
72
+ ) -> BatchEncoding:
73
+ """
74
+ This method first forwards the `html_strings` argument to [`~MarkupLMFeatureExtractor.__call__`]. Next, it
75
+ passes the `nodes` and `xpaths` along with the additional arguments to [`~MarkupLMTokenizer.__call__`] and
76
+ returns the output.
77
+
78
+ Optionally, one can also provide a `text` argument which is passed along as first sequence.
79
+
80
+ Please refer to the docstring of the above two methods for more information.
81
+ """
82
+ # first, create nodes and xpaths
83
+ if self.parse_html:
84
+ if html_strings is None:
85
+ raise ValueError("Make sure to pass HTML strings in case `parse_html` is set to `True`")
86
+
87
+ if nodes is not None or xpaths is not None or node_labels is not None:
88
+ raise ValueError(
89
+ "Please don't pass nodes, xpaths nor node labels in case `parse_html` is set to `True`"
90
+ )
91
+
92
+ features = self.feature_extractor(html_strings)
93
+ nodes = features["nodes"]
94
+ xpaths = features["xpaths"]
95
+ else:
96
+ if html_strings is not None:
97
+ raise ValueError("You have passed HTML strings but `parse_html` is set to `False`.")
98
+ if nodes is None or xpaths is None:
99
+ raise ValueError("Make sure to pass nodes and xpaths in case `parse_html` is set to `False`")
100
+
101
+ # # second, apply the tokenizer
102
+ if questions is not None and self.parse_html:
103
+ if isinstance(questions, str):
104
+ questions = [questions] # add batch dimension (as the feature extractor always adds a batch dimension)
105
+
106
+ encoded_inputs = self.tokenizer(
107
+ text=questions if questions is not None else nodes,
108
+ text_pair=nodes if questions is not None else None,
109
+ xpaths=xpaths,
110
+ node_labels=node_labels,
111
+ add_special_tokens=add_special_tokens,
112
+ padding=padding,
113
+ truncation=truncation,
114
+ max_length=max_length,
115
+ stride=stride,
116
+ pad_to_multiple_of=pad_to_multiple_of,
117
+ return_token_type_ids=return_token_type_ids,
118
+ return_attention_mask=return_attention_mask,
119
+ return_overflowing_tokens=return_overflowing_tokens,
120
+ return_special_tokens_mask=return_special_tokens_mask,
121
+ return_offsets_mapping=return_offsets_mapping,
122
+ return_length=return_length,
123
+ verbose=verbose,
124
+ return_tensors=return_tensors,
125
+ **kwargs,
126
+ )
127
+
128
+ return encoded_inputs
129
+
130
+ def batch_decode(self, *args, **kwargs):
131
+ """
132
+ This method forwards all its arguments to TrOCRTokenizer's [`~PreTrainedTokenizer.batch_decode`]. Please refer
133
+ to the docstring of this method for more information.
134
+ """
135
+ return self.tokenizer.batch_decode(*args, **kwargs)
136
+
137
+ def decode(self, *args, **kwargs):
138
+ """
139
+ This method forwards all its arguments to TrOCRTokenizer's [`~PreTrainedTokenizer.decode`]. Please refer to the
140
+ docstring of this method for more information.
141
+ """
142
+ return self.tokenizer.decode(*args, **kwargs)
143
+
144
+ @property
145
+ def model_input_names(self):
146
+ tokenizer_input_names = self.tokenizer.model_input_names
147
+ return tokenizer_input_names
148
+
149
+
150
+ __all__ = ["MarkupLMProcessor"]
tasks/tasksmith-441eeab80047/environment/source/src/transformers/models/markuplm/tokenization_markuplm.py ADDED
@@ -0,0 +1,1471 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ """Tokenization class for MarkupLM."""
16
+
17
+ import json
18
+ import os
19
+ from functools import lru_cache
20
+ from typing import Dict, List, Optional, Tuple, Union
21
+
22
+ import regex as re
23
+
24
+ from ...file_utils import PaddingStrategy, TensorType, add_end_docstrings
25
+ from ...tokenization_utils import AddedToken, PreTrainedTokenizer
26
+ from ...tokenization_utils_base import (
27
+ ENCODE_KWARGS_DOCSTRING,
28
+ BatchEncoding,
29
+ EncodedInput,
30
+ PreTokenizedInput,
31
+ TextInput,
32
+ TextInputPair,
33
+ TruncationStrategy,
34
+ )
35
+ from ...utils import logging
36
+
37
+
38
+ logger = logging.get_logger(__name__)
39
+
40
+ VOCAB_FILES_NAMES = {"vocab_file": "vocab.json", "merges_file": "merges.txt", "tokenizer_file": "tokenizer.json"}
41
+
42
+
43
+ MARKUPLM_ENCODE_PLUS_ADDITIONAL_KWARGS_DOCSTRING = r"""
44
+ add_special_tokens (`bool`, *optional*, defaults to `True`):
45
+ Whether or not to encode the sequences with the special tokens relative to their model.
46
+ padding (`bool`, `str` or [`~file_utils.PaddingStrategy`], *optional*, defaults to `False`):
47
+ Activates and controls padding. Accepts the following values:
48
+
49
+ - `True` or `'longest'`: Pad to the longest sequence in the batch (or no padding if only a single
50
+ sequence if provided).
51
+ - `'max_length'`: Pad to a maximum length specified with the argument `max_length` or to the maximum
52
+ acceptable input length for the model if that argument is not provided.
53
+ - `False` or `'do_not_pad'` (default): No padding (i.e., can output a batch with sequences of different
54
+ lengths).
55
+ truncation (`bool`, `str` or [`~tokenization_utils_base.TruncationStrategy`], *optional*, defaults to `False`):
56
+ Activates and controls truncation. Accepts the following values:
57
+
58
+ - `True` or `'longest_first'`: Truncate to a maximum length specified with the argument `max_length` or
59
+ to the maximum acceptable input length for the model if that argument is not provided. This will
60
+ truncate token by token, removing a token from the longest sequence in the pair if a pair of
61
+ sequences (or a batch of pairs) is provided.
62
+ - `'only_first'`: Truncate to a maximum length specified with the argument `max_length` or to the
63
+ maximum acceptable input length for the model if that argument is not provided. This will only
64
+ truncate the first sequence of a pair if a pair of sequences (or a batch of pairs) is provided.
65
+ - `'only_second'`: Truncate to a maximum length specified with the argument `max_length` or to the
66
+ maximum acceptable input length for the model if that argument is not provided. This will only
67
+ truncate the second sequence of a pair if a pair of sequences (or a batch of pairs) is provided.
68
+ - `False` or `'do_not_truncate'` (default): No truncation (i.e., can output batch with sequence lengths
69
+ greater than the model maximum admissible input size).
70
+ max_length (`int`, *optional*):
71
+ Controls the maximum length to use by one of the truncation/padding parameters. If left unset or set to
72
+ `None`, this will use the predefined model maximum length if a maximum length is required by one of the
73
+ truncation/padding parameters. If the model has no specific maximum input length (like XLNet)
74
+ truncation/padding to a maximum length will be deactivated.
75
+ stride (`int`, *optional*, defaults to 0):
76
+ If set to a number along with `max_length`, the overflowing tokens returned when
77
+ `return_overflowing_tokens=True` will contain some tokens from the end of the truncated sequence
78
+ returned to provide some overlap between truncated and overflowing sequences. The value of this
79
+ argument defines the number of overlapping tokens.
80
+ pad_to_multiple_of (`int`, *optional*):
81
+ If set will pad the sequence to a multiple of the provided value. This is especially useful to enable
82
+ the use of Tensor Cores on NVIDIA hardware with compute capability `>= 7.5` (Volta).
83
+ return_tensors (`str` or [`~file_utils.TensorType`], *optional*):
84
+ If set, will return tensors instead of list of python integers. Acceptable values are:
85
+
86
+ - `'tf'`: Return TensorFlow `tf.constant` objects.
87
+ - `'pt'`: Return PyTorch `torch.Tensor` objects.
88
+ - `'np'`: Return Numpy `np.ndarray` objects.
89
+ """
90
+
91
+
92
+ @lru_cache()
93
+ def bytes_to_unicode():
94
+ """
95
+ Returns list of utf-8 byte and a mapping to unicode strings. We specifically avoids mapping to whitespace/control
96
+ characters the bpe code barfs on. The reversible bpe codes work on unicode strings. This means you need a large #
97
+ of unicode characters in your vocab if you want to avoid UNKs. When you're at something like a 10B token dataset
98
+ you end up needing around 5K for decent coverage. This is a significant percentage of your normal, say, 32K bpe
99
+ vocab. To avoid that, we want lookup tables between utf-8 bytes and unicode strings.
100
+ """
101
+ bs = (
102
+ list(range(ord("!"), ord("~") + 1)) + list(range(ord("¡"), ord("¬") + 1)) + list(range(ord("®"), ord("ÿ") + 1))
103
+ )
104
+ cs = bs[:]
105
+ n = 0
106
+ for b in range(2**8):
107
+ if b not in bs:
108
+ bs.append(b)
109
+ cs.append(2**8 + n)
110
+ n += 1
111
+ cs = [chr(n) for n in cs]
112
+ return dict(zip(bs, cs))
113
+
114
+
115
+ def get_pairs(word):
116
+ """
117
+ Return set of symbol pairs in a word. Word is represented as tuple of symbols (symbols being variable-length
118
+ strings).
119
+ """
120
+ pairs = set()
121
+ prev_char = word[0]
122
+ for char in word[1:]:
123
+ pairs.add((prev_char, char))
124
+ prev_char = char
125
+ return pairs
126
+
127
+
128
+ class MarkupLMTokenizer(PreTrainedTokenizer):
129
+ r"""
130
+ Construct a MarkupLM tokenizer. Based on byte-level Byte-Pair-Encoding (BPE). [`MarkupLMTokenizer`] can be used to
131
+ turn HTML strings into to token-level `input_ids`, `attention_mask`, `token_type_ids`, `xpath_tags_seq` and
132
+ `xpath_tags_seq`. This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods.
133
+ Users should refer to this superclass for more information regarding those methods.
134
+
135
+ Args:
136
+ vocab_file (`str`):
137
+ Path to the vocabulary file.
138
+ merges_file (`str`):
139
+ Path to the merges file.
140
+ errors (`str`, *optional*, defaults to `"replace"`):
141
+ Paradigm to follow when decoding bytes to UTF-8. See
142
+ [bytes.decode](https://docs.python.org/3/library/stdtypes.html#bytes.decode) for more information.
143
+ bos_token (`str`, *optional*, defaults to `"<s>"`):
144
+ The beginning of sequence token that was used during pretraining. Can be used a sequence classifier token.
145
+
146
+ <Tip>
147
+
148
+ When building a sequence using special tokens, this is not the token that is used for the beginning of
149
+ sequence. The token used is the `cls_token`.
150
+
151
+ </Tip>
152
+
153
+ eos_token (`str`, *optional*, defaults to `"</s>"`):
154
+ The end of sequence token.
155
+
156
+ <Tip>
157
+
158
+ When building a sequence using special tokens, this is not the token that is used for the end of sequence.
159
+ The token used is the `sep_token`.
160
+
161
+ </Tip>
162
+
163
+ sep_token (`str`, *optional*, defaults to `"</s>"`):
164
+ The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
165
+ sequence classification or for a text and a question for question answering. It is also used as the last
166
+ token of a sequence built with special tokens.
167
+ cls_token (`str`, *optional*, defaults to `"<s>"`):
168
+ The classifier token which is used when doing sequence classification (classification of the whole sequence
169
+ instead of per-token classification). It is the first token of the sequence when built with special tokens.
170
+ unk_token (`str`, *optional*, defaults to `"<unk>"`):
171
+ The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
172
+ token instead.
173
+ pad_token (`str`, *optional*, defaults to `"<pad>"`):
174
+ The token used for padding, for example when batching sequences of different lengths.
175
+ mask_token (`str`, *optional*, defaults to `"<mask>"`):
176
+ The token used for masking values. This is the token used when training this model with masked language
177
+ modeling. This is the token which the model will try to predict.
178
+ add_prefix_space (`bool`, *optional*, defaults to `False`):
179
+ Whether or not to add an initial space to the input. This allows to treat the leading word just as any
180
+ other word. (RoBERTa tokenizer detect beginning of words by the preceding space).
181
+ """
182
+
183
+ vocab_files_names = VOCAB_FILES_NAMES
184
+
185
+ def __init__(
186
+ self,
187
+ vocab_file,
188
+ merges_file,
189
+ tags_dict,
190
+ errors="replace",
191
+ bos_token="<s>",
192
+ eos_token="</s>",
193
+ sep_token="</s>",
194
+ cls_token="<s>",
195
+ unk_token="<unk>",
196
+ pad_token="<pad>",
197
+ mask_token="<mask>",
198
+ add_prefix_space=False,
199
+ max_depth=50,
200
+ max_width=1000,
201
+ pad_width=1001,
202
+ pad_token_label=-100,
203
+ only_label_first_subword=True,
204
+ **kwargs,
205
+ ):
206
+ bos_token = AddedToken(bos_token, lstrip=False, rstrip=False) if isinstance(bos_token, str) else bos_token
207
+ eos_token = AddedToken(eos_token, lstrip=False, rstrip=False) if isinstance(eos_token, str) else eos_token
208
+ sep_token = AddedToken(sep_token, lstrip=False, rstrip=False) if isinstance(sep_token, str) else sep_token
209
+ cls_token = AddedToken(cls_token, lstrip=False, rstrip=False) if isinstance(cls_token, str) else cls_token
210
+ unk_token = AddedToken(unk_token, lstrip=False, rstrip=False) if isinstance(unk_token, str) else unk_token
211
+ pad_token = AddedToken(pad_token, lstrip=False, rstrip=False) if isinstance(pad_token, str) else pad_token
212
+
213
+ # Mask token behave like a normal word, i.e. include the space before it
214
+ mask_token = AddedToken(mask_token, lstrip=True, rstrip=False) if isinstance(mask_token, str) else mask_token
215
+
216
+ with open(vocab_file, encoding="utf-8") as vocab_handle:
217
+ self.encoder = json.load(vocab_handle)
218
+
219
+ self.tags_dict = tags_dict
220
+ self.decoder = {v: k for k, v in self.encoder.items()}
221
+ self.errors = errors # how to handle errors in decoding
222
+ self.byte_encoder = bytes_to_unicode()
223
+ self.byte_decoder = {v: k for k, v in self.byte_encoder.items()}
224
+ with open(merges_file, encoding="utf-8") as merges_handle:
225
+ bpe_merges = merges_handle.read().split("\n")[1:-1]
226
+ bpe_merges = [tuple(merge.split()) for merge in bpe_merges]
227
+ self.bpe_ranks = dict(zip(bpe_merges, range(len(bpe_merges))))
228
+ self.cache = {}
229
+ self.add_prefix_space = add_prefix_space
230
+
231
+ # Should have added re.IGNORECASE so BPE merges can happen for capitalized versions of contractions
232
+ self.pat = re.compile(r"""'s|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+""")
233
+
234
+ # additional properties
235
+ self.max_depth = max_depth
236
+ self.max_width = max_width
237
+ self.pad_width = pad_width
238
+ self.unk_tag_id = len(self.tags_dict)
239
+ self.pad_tag_id = self.unk_tag_id + 1
240
+ self.pad_xpath_tags_seq = [self.pad_tag_id] * self.max_depth
241
+ self.pad_xpath_subs_seq = [self.pad_width] * self.max_depth
242
+
243
+ super().__init__(
244
+ vocab_file=vocab_file,
245
+ merges_file=merges_file,
246
+ tags_dict=tags_dict,
247
+ errors=errors,
248
+ bos_token=bos_token,
249
+ eos_token=eos_token,
250
+ unk_token=unk_token,
251
+ sep_token=sep_token,
252
+ cls_token=cls_token,
253
+ pad_token=pad_token,
254
+ mask_token=mask_token,
255
+ add_prefix_space=add_prefix_space,
256
+ max_depth=max_depth,
257
+ max_width=max_width,
258
+ pad_width=pad_width,
259
+ pad_token_label=pad_token_label,
260
+ only_label_first_subword=only_label_first_subword,
261
+ **kwargs,
262
+ )
263
+
264
+ self.pad_token_label = pad_token_label
265
+ self.only_label_first_subword = only_label_first_subword
266
+
267
+ def get_xpath_seq(self, xpath):
268
+ """
269
+ Given the xpath expression of one particular node (like "/html/body/div/li[1]/div/span[2]"), return a list of
270
+ tag IDs and corresponding subscripts, taking into account max depth.
271
+ """
272
+ xpath_tags_list = []
273
+ xpath_subs_list = []
274
+
275
+ xpath_units = xpath.split("/")
276
+ for unit in xpath_units:
277
+ if not unit.strip():
278
+ continue
279
+ name_subs = unit.strip().split("[")
280
+ tag_name = name_subs[0]
281
+ sub = 0 if len(name_subs) == 1 else int(name_subs[1][:-1])
282
+ xpath_tags_list.append(self.tags_dict.get(tag_name, self.unk_tag_id))
283
+ xpath_subs_list.append(min(self.max_width, sub))
284
+
285
+ xpath_tags_list = xpath_tags_list[: self.max_depth]
286
+ xpath_subs_list = xpath_subs_list[: self.max_depth]
287
+ xpath_tags_list += [self.pad_tag_id] * (self.max_depth - len(xpath_tags_list))
288
+ xpath_subs_list += [self.pad_width] * (self.max_depth - len(xpath_subs_list))
289
+
290
+ return xpath_tags_list, xpath_subs_list
291
+
292
+ @property
293
+ def vocab_size(self):
294
+ return len(self.encoder)
295
+
296
+ def get_vocab(self):
297
+ vocab = self.encoder.copy()
298
+ vocab.update(self.added_tokens_encoder)
299
+ return vocab
300
+
301
+ def bpe(self, token):
302
+ if token in self.cache:
303
+ return self.cache[token]
304
+ word = tuple(token)
305
+ pairs = get_pairs(word)
306
+
307
+ if not pairs:
308
+ return token
309
+
310
+ while True:
311
+ bigram = min(pairs, key=lambda pair: self.bpe_ranks.get(pair, float("inf")))
312
+ if bigram not in self.bpe_ranks:
313
+ break
314
+ first, second = bigram
315
+ new_word = []
316
+ i = 0
317
+ while i < len(word):
318
+ try:
319
+ j = word.index(first, i)
320
+ except ValueError:
321
+ new_word.extend(word[i:])
322
+ break
323
+ else:
324
+ new_word.extend(word[i:j])
325
+ i = j
326
+
327
+ if word[i] == first and i < len(word) - 1 and word[i + 1] == second:
328
+ new_word.append(first + second)
329
+ i += 2
330
+ else:
331
+ new_word.append(word[i])
332
+ i += 1
333
+ new_word = tuple(new_word)
334
+ word = new_word
335
+ if len(word) == 1:
336
+ break
337
+ else:
338
+ pairs = get_pairs(word)
339
+ word = " ".join(word)
340
+ self.cache[token] = word
341
+ return word
342
+
343
+ def _tokenize(self, text):
344
+ """Tokenize a string."""
345
+ bpe_tokens = []
346
+ for token in re.findall(self.pat, text):
347
+ token = "".join(
348
+ self.byte_encoder[b] for b in token.encode("utf-8")
349
+ ) # Maps all our bytes to unicode strings, avoiding control tokens of the BPE (spaces in our case)
350
+ bpe_tokens.extend(bpe_token for bpe_token in self.bpe(token).split(" "))
351
+ return bpe_tokens
352
+
353
+ def _convert_token_to_id(self, token):
354
+ """Converts a token (str) in an id using the vocab."""
355
+ return self.encoder.get(token, self.encoder.get(self.unk_token))
356
+
357
+ def _convert_id_to_token(self, index):
358
+ """Converts an index (integer) in a token (str) using the vocab."""
359
+ return self.decoder.get(index)
360
+
361
+ def convert_tokens_to_string(self, tokens):
362
+ """Converts a sequence of tokens (string) in a single string."""
363
+ logger.warning(
364
+ "MarkupLM now does not support generative tasks, decoding is experimental and subject to change."
365
+ )
366
+ text = "".join(tokens)
367
+ text = bytearray([self.byte_decoder[c] for c in text]).decode("utf-8", errors=self.errors)
368
+ return text
369
+
370
+ def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
371
+ if not os.path.isdir(save_directory):
372
+ logger.error(f"Vocabulary path ({save_directory}) should be a directory")
373
+ return
374
+ vocab_file = os.path.join(
375
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
376
+ )
377
+ merge_file = os.path.join(
378
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["merges_file"]
379
+ )
380
+
381
+ # save vocab_file
382
+ with open(vocab_file, "w", encoding="utf-8") as f:
383
+ f.write(json.dumps(self.encoder, indent=2, sort_keys=True, ensure_ascii=False) + "\n")
384
+
385
+ # save merge_file
386
+ index = 0
387
+ with open(merge_file, "w", encoding="utf-8") as writer:
388
+ writer.write("#version: 0.2\n")
389
+ for bpe_tokens, token_index in sorted(self.bpe_ranks.items(), key=lambda kv: kv[1]):
390
+ if index != token_index:
391
+ logger.warning(
392
+ f"Saving vocabulary to {merge_file}: BPE merge indices are not consecutive."
393
+ " Please check that the tokenizer is not corrupted!"
394
+ )
395
+ index = token_index
396
+ writer.write(" ".join(bpe_tokens) + "\n")
397
+ index += 1
398
+
399
+ return vocab_file, merge_file
400
+
401
+ def prepare_for_tokenization(self, text, is_split_into_words=False, **kwargs):
402
+ add_prefix_space = kwargs.pop("add_prefix_space", self.add_prefix_space)
403
+ if (is_split_into_words or add_prefix_space) and (len(text) > 0 and not text[0].isspace()):
404
+ text = " " + text
405
+ return (text, kwargs)
406
+
407
+ def build_inputs_with_special_tokens(
408
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
409
+ ) -> List[int]:
410
+ """
411
+ Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
412
+ adding special tokens. A RoBERTa sequence has the following format:
413
+ - single sequence: `<s> X </s>`
414
+ - pair of sequences: `<s> A </s></s> B </s>`
415
+
416
+ Args:
417
+ token_ids_0 (`List[int]`):
418
+ List of IDs to which the special tokens will be added.
419
+ token_ids_1 (`List[int]`, *optional*):
420
+ Optional second list of IDs for sequence pairs.
421
+ Returns:
422
+ `List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
423
+ """
424
+ if token_ids_1 is None:
425
+ return [self.cls_token_id] + token_ids_0 + [self.sep_token_id]
426
+ cls = [self.cls_token_id]
427
+ sep = [self.sep_token_id]
428
+ return cls + token_ids_0 + sep + token_ids_1 + sep
429
+
430
+ def build_xpath_tags_with_special_tokens(
431
+ self, xpath_tags_0: List[int], xpath_tags_1: Optional[List[int]] = None
432
+ ) -> List[int]:
433
+ pad = [self.pad_xpath_tags_seq]
434
+ if len(xpath_tags_1) == 0:
435
+ return pad + xpath_tags_0 + pad
436
+ return pad + xpath_tags_0 + pad + xpath_tags_1 + pad
437
+
438
+ def build_xpath_subs_with_special_tokens(
439
+ self, xpath_subs_0: List[int], xpath_subs_1: Optional[List[int]] = None
440
+ ) -> List[int]:
441
+ pad = [self.pad_xpath_subs_seq]
442
+ if len(xpath_subs_1) == 0:
443
+ return pad + xpath_subs_0 + pad
444
+ return pad + xpath_subs_0 + pad + xpath_subs_1 + pad
445
+
446
+ def get_special_tokens_mask(
447
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None, already_has_special_tokens: bool = False
448
+ ) -> List[int]:
449
+ """
450
+ Args:
451
+ Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
452
+ special tokens using the tokenizer `prepare_for_model` method.
453
+ token_ids_0 (`List[int]`):
454
+ List of IDs.
455
+ token_ids_1 (`List[int]`, *optional*):
456
+ Optional second list of IDs for sequence pairs.
457
+ already_has_special_tokens (`bool`, *optional*, defaults to `False`):
458
+ Whether or not the token list is already formatted with special tokens for the model.
459
+ Returns:
460
+ `List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
461
+ """
462
+ if already_has_special_tokens:
463
+ return super().get_special_tokens_mask(
464
+ token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
465
+ )
466
+
467
+ if token_ids_1 is None:
468
+ return [1] + ([0] * len(token_ids_0)) + [1]
469
+ return [1] + ([0] * len(token_ids_0)) + [1, 1] + ([0] * len(token_ids_1)) + [1]
470
+
471
+ def create_token_type_ids_from_sequences(
472
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
473
+ ) -> List[int]:
474
+ """
475
+ Create a mask from the two sequences passed to be used in a sequence-pair classification task. RoBERTa does not
476
+ make use of token type ids, therefore a list of zeros is returned.
477
+
478
+ Args:
479
+ token_ids_0 (`List[int]`):
480
+ List of IDs.
481
+ token_ids_1 (`List[int]`, *optional*):
482
+ Optional second list of IDs for sequence pairs.
483
+ Returns:
484
+ `List[int]`: List of zeros.
485
+ """
486
+ sep = [self.sep_token_id]
487
+ cls = [self.cls_token_id]
488
+
489
+ if token_ids_1 is None:
490
+ return len(cls + token_ids_0 + sep) * [0]
491
+ return len(cls + token_ids_0 + sep + token_ids_1 + sep) * [0]
492
+
493
+ @add_end_docstrings(ENCODE_KWARGS_DOCSTRING, MARKUPLM_ENCODE_PLUS_ADDITIONAL_KWARGS_DOCSTRING)
494
+ def __call__(
495
+ self,
496
+ text: Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]],
497
+ text_pair: Optional[Union[PreTokenizedInput, List[PreTokenizedInput]]] = None,
498
+ xpaths: Union[List[List[int]], List[List[List[int]]]] = None,
499
+ node_labels: Optional[Union[List[int], List[List[int]]]] = None,
500
+ add_special_tokens: bool = True,
501
+ padding: Union[bool, str, PaddingStrategy] = False,
502
+ truncation: Union[bool, str, TruncationStrategy] = None,
503
+ max_length: Optional[int] = None,
504
+ stride: int = 0,
505
+ pad_to_multiple_of: Optional[int] = None,
506
+ padding_side: Optional[str] = None,
507
+ return_tensors: Optional[Union[str, TensorType]] = None,
508
+ return_token_type_ids: Optional[bool] = None,
509
+ return_attention_mask: Optional[bool] = None,
510
+ return_overflowing_tokens: bool = False,
511
+ return_special_tokens_mask: bool = False,
512
+ return_offsets_mapping: bool = False,
513
+ return_length: bool = False,
514
+ verbose: bool = True,
515
+ **kwargs,
516
+ ) -> BatchEncoding:
517
+ """
518
+ Main method to tokenize and prepare for the model one or several sequence(s) or one or several pair(s) of
519
+ sequences with node-level xpaths and optional labels.
520
+
521
+ Args:
522
+ text (`str`, `List[str]`, `List[List[str]]`):
523
+ The sequence or batch of sequences to be encoded. Each sequence can be a string, a list of strings
524
+ (nodes of a single example or questions of a batch of examples) or a list of list of strings (batch of
525
+ nodes).
526
+ text_pair (`List[str]`, `List[List[str]]`):
527
+ The sequence or batch of sequences to be encoded. Each sequence should be a list of strings
528
+ (pretokenized string).
529
+ xpaths (`List[List[int]]`, `List[List[List[int]]]`):
530
+ Node-level xpaths.
531
+ node_labels (`List[int]`, `List[List[int]]`, *optional*):
532
+ Node-level integer labels (for token classification tasks).
533
+ """
534
+
535
+ # Input type checking for clearer error
536
+ def _is_valid_text_input(t):
537
+ if isinstance(t, str):
538
+ # Strings are fine
539
+ return True
540
+ elif isinstance(t, (list, tuple)):
541
+ # List are fine as long as they are...
542
+ if len(t) == 0:
543
+ # ... empty
544
+ return True
545
+ elif isinstance(t[0], str):
546
+ # ... list of strings
547
+ return True
548
+ elif isinstance(t[0], (list, tuple)):
549
+ # ... list with an empty list or with a list of strings
550
+ return len(t[0]) == 0 or isinstance(t[0][0], str)
551
+ else:
552
+ return False
553
+ else:
554
+ return False
555
+
556
+ if text_pair is not None:
557
+ # in case text + text_pair are provided, text = questions, text_pair = nodes
558
+ if not _is_valid_text_input(text):
559
+ raise ValueError("text input must of type `str` (single example) or `List[str]` (batch of examples). ")
560
+ if not isinstance(text_pair, (list, tuple)):
561
+ raise ValueError(
562
+ "Nodes must be of type `List[str]` (single pretokenized example), "
563
+ "or `List[List[str]]` (batch of pretokenized examples)."
564
+ )
565
+ else:
566
+ # in case only text is provided => must be nodes
567
+ if not isinstance(text, (list, tuple)):
568
+ raise ValueError(
569
+ "Nodes must be of type `List[str]` (single pretokenized example), "
570
+ "or `List[List[str]]` (batch of pretokenized examples)."
571
+ )
572
+
573
+ if text_pair is not None:
574
+ is_batched = isinstance(text, (list, tuple))
575
+ else:
576
+ is_batched = isinstance(text, (list, tuple)) and text and isinstance(text[0], (list, tuple))
577
+
578
+ nodes = text if text_pair is None else text_pair
579
+ assert xpaths is not None, "You must provide corresponding xpaths"
580
+ if is_batched:
581
+ assert len(nodes) == len(xpaths), "You must provide nodes and xpaths for an equal amount of examples"
582
+ for nodes_example, xpaths_example in zip(nodes, xpaths):
583
+ assert len(nodes_example) == len(xpaths_example), "You must provide as many nodes as there are xpaths"
584
+ else:
585
+ assert len(nodes) == len(xpaths), "You must provide as many nodes as there are xpaths"
586
+
587
+ if is_batched:
588
+ if text_pair is not None and len(text) != len(text_pair):
589
+ raise ValueError(
590
+ f"batch length of `text`: {len(text)} does not match batch length of `text_pair`:"
591
+ f" {len(text_pair)}."
592
+ )
593
+ batch_text_or_text_pairs = list(zip(text, text_pair)) if text_pair is not None else text
594
+ is_pair = bool(text_pair is not None)
595
+ return self.batch_encode_plus(
596
+ batch_text_or_text_pairs=batch_text_or_text_pairs,
597
+ is_pair=is_pair,
598
+ xpaths=xpaths,
599
+ node_labels=node_labels,
600
+ add_special_tokens=add_special_tokens,
601
+ padding=padding,
602
+ truncation=truncation,
603
+ max_length=max_length,
604
+ stride=stride,
605
+ pad_to_multiple_of=pad_to_multiple_of,
606
+ padding_side=padding_side,
607
+ return_tensors=return_tensors,
608
+ return_token_type_ids=return_token_type_ids,
609
+ return_attention_mask=return_attention_mask,
610
+ return_overflowing_tokens=return_overflowing_tokens,
611
+ return_special_tokens_mask=return_special_tokens_mask,
612
+ return_offsets_mapping=return_offsets_mapping,
613
+ return_length=return_length,
614
+ verbose=verbose,
615
+ **kwargs,
616
+ )
617
+ else:
618
+ return self.encode_plus(
619
+ text=text,
620
+ text_pair=text_pair,
621
+ xpaths=xpaths,
622
+ node_labels=node_labels,
623
+ add_special_tokens=add_special_tokens,
624
+ padding=padding,
625
+ truncation=truncation,
626
+ max_length=max_length,
627
+ stride=stride,
628
+ pad_to_multiple_of=pad_to_multiple_of,
629
+ padding_side=padding_side,
630
+ return_tensors=return_tensors,
631
+ return_token_type_ids=return_token_type_ids,
632
+ return_attention_mask=return_attention_mask,
633
+ return_overflowing_tokens=return_overflowing_tokens,
634
+ return_special_tokens_mask=return_special_tokens_mask,
635
+ return_offsets_mapping=return_offsets_mapping,
636
+ return_length=return_length,
637
+ verbose=verbose,
638
+ **kwargs,
639
+ )
640
+
641
+ @add_end_docstrings(ENCODE_KWARGS_DOCSTRING, MARKUPLM_ENCODE_PLUS_ADDITIONAL_KWARGS_DOCSTRING)
642
+ def batch_encode_plus(
643
+ self,
644
+ batch_text_or_text_pairs: Union[
645
+ List[TextInput],
646
+ List[TextInputPair],
647
+ List[PreTokenizedInput],
648
+ ],
649
+ is_pair: bool = None,
650
+ xpaths: Optional[List[List[List[int]]]] = None,
651
+ node_labels: Optional[Union[List[int], List[List[int]]]] = None,
652
+ add_special_tokens: bool = True,
653
+ padding: Union[bool, str, PaddingStrategy] = False,
654
+ truncation: Union[bool, str, TruncationStrategy] = None,
655
+ max_length: Optional[int] = None,
656
+ stride: int = 0,
657
+ pad_to_multiple_of: Optional[int] = None,
658
+ padding_side: Optional[str] = None,
659
+ return_tensors: Optional[Union[str, TensorType]] = None,
660
+ return_token_type_ids: Optional[bool] = None,
661
+ return_attention_mask: Optional[bool] = None,
662
+ return_overflowing_tokens: bool = False,
663
+ return_special_tokens_mask: bool = False,
664
+ return_offsets_mapping: bool = False,
665
+ return_length: bool = False,
666
+ verbose: bool = True,
667
+ **kwargs,
668
+ ) -> BatchEncoding:
669
+ # Backward compatibility for 'truncation_strategy', 'pad_to_max_length'
670
+ padding_strategy, truncation_strategy, max_length, kwargs = self._get_padding_truncation_strategies(
671
+ padding=padding,
672
+ truncation=truncation,
673
+ max_length=max_length,
674
+ pad_to_multiple_of=pad_to_multiple_of,
675
+ verbose=verbose,
676
+ **kwargs,
677
+ )
678
+
679
+ return self._batch_encode_plus(
680
+ batch_text_or_text_pairs=batch_text_or_text_pairs,
681
+ is_pair=is_pair,
682
+ xpaths=xpaths,
683
+ node_labels=node_labels,
684
+ add_special_tokens=add_special_tokens,
685
+ padding_strategy=padding_strategy,
686
+ truncation_strategy=truncation_strategy,
687
+ max_length=max_length,
688
+ stride=stride,
689
+ pad_to_multiple_of=pad_to_multiple_of,
690
+ padding_side=padding_side,
691
+ return_tensors=return_tensors,
692
+ return_token_type_ids=return_token_type_ids,
693
+ return_attention_mask=return_attention_mask,
694
+ return_overflowing_tokens=return_overflowing_tokens,
695
+ return_special_tokens_mask=return_special_tokens_mask,
696
+ return_offsets_mapping=return_offsets_mapping,
697
+ return_length=return_length,
698
+ verbose=verbose,
699
+ **kwargs,
700
+ )
701
+
702
+ def _batch_encode_plus(
703
+ self,
704
+ batch_text_or_text_pairs: Union[
705
+ List[TextInput],
706
+ List[TextInputPair],
707
+ List[PreTokenizedInput],
708
+ ],
709
+ is_pair: bool = None,
710
+ xpaths: Optional[List[List[List[int]]]] = None,
711
+ node_labels: Optional[List[List[int]]] = None,
712
+ add_special_tokens: bool = True,
713
+ padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD,
714
+ truncation_strategy: TruncationStrategy = TruncationStrategy.DO_NOT_TRUNCATE,
715
+ max_length: Optional[int] = None,
716
+ stride: int = 0,
717
+ pad_to_multiple_of: Optional[int] = None,
718
+ padding_side: Optional[str] = None,
719
+ return_tensors: Optional[Union[str, TensorType]] = None,
720
+ return_token_type_ids: Optional[bool] = None,
721
+ return_attention_mask: Optional[bool] = None,
722
+ return_overflowing_tokens: bool = False,
723
+ return_special_tokens_mask: bool = False,
724
+ return_offsets_mapping: bool = False,
725
+ return_length: bool = False,
726
+ verbose: bool = True,
727
+ **kwargs,
728
+ ) -> BatchEncoding:
729
+ if return_offsets_mapping:
730
+ raise NotImplementedError(
731
+ "return_offset_mapping is not available when using Python tokenizers. "
732
+ "To use this feature, change your tokenizer to one deriving from "
733
+ "transformers.PreTrainedTokenizerFast."
734
+ )
735
+
736
+ batch_outputs = self._batch_prepare_for_model(
737
+ batch_text_or_text_pairs=batch_text_or_text_pairs,
738
+ is_pair=is_pair,
739
+ xpaths=xpaths,
740
+ node_labels=node_labels,
741
+ add_special_tokens=add_special_tokens,
742
+ padding_strategy=padding_strategy,
743
+ truncation_strategy=truncation_strategy,
744
+ max_length=max_length,
745
+ stride=stride,
746
+ pad_to_multiple_of=pad_to_multiple_of,
747
+ padding_side=padding_side,
748
+ return_attention_mask=return_attention_mask,
749
+ return_token_type_ids=return_token_type_ids,
750
+ return_overflowing_tokens=return_overflowing_tokens,
751
+ return_special_tokens_mask=return_special_tokens_mask,
752
+ return_length=return_length,
753
+ return_tensors=return_tensors,
754
+ verbose=verbose,
755
+ )
756
+
757
+ return BatchEncoding(batch_outputs)
758
+
759
+ @add_end_docstrings(ENCODE_KWARGS_DOCSTRING, MARKUPLM_ENCODE_PLUS_ADDITIONAL_KWARGS_DOCSTRING)
760
+ def _batch_prepare_for_model(
761
+ self,
762
+ batch_text_or_text_pairs,
763
+ is_pair: bool = None,
764
+ xpaths: Optional[List[List[int]]] = None,
765
+ node_labels: Optional[List[List[int]]] = None,
766
+ add_special_tokens: bool = True,
767
+ padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD,
768
+ truncation_strategy: TruncationStrategy = TruncationStrategy.DO_NOT_TRUNCATE,
769
+ max_length: Optional[int] = None,
770
+ stride: int = 0,
771
+ pad_to_multiple_of: Optional[int] = None,
772
+ padding_side: Optional[str] = None,
773
+ return_tensors: Optional[str] = None,
774
+ return_token_type_ids: Optional[bool] = None,
775
+ return_attention_mask: Optional[bool] = None,
776
+ return_overflowing_tokens: bool = False,
777
+ return_special_tokens_mask: bool = False,
778
+ return_length: bool = False,
779
+ verbose: bool = True,
780
+ ) -> BatchEncoding:
781
+ """
782
+ Prepares a sequence of input id, or a pair of sequences of inputs ids so that it can be used by the model. It
783
+ adds special tokens, truncates sequences if overflowing while taking into account the special tokens and
784
+ manages a moving window (with user defined stride) for overflowing tokens.
785
+
786
+ Args:
787
+ batch_ids_pairs: list of tokenized input ids or input ids pairs
788
+ """
789
+
790
+ batch_outputs = {}
791
+ for idx, example in enumerate(zip(batch_text_or_text_pairs, xpaths)):
792
+ batch_text_or_text_pair, xpaths_example = example
793
+ outputs = self.prepare_for_model(
794
+ batch_text_or_text_pair[0] if is_pair else batch_text_or_text_pair,
795
+ batch_text_or_text_pair[1] if is_pair else None,
796
+ xpaths_example,
797
+ node_labels=node_labels[idx] if node_labels is not None else None,
798
+ add_special_tokens=add_special_tokens,
799
+ padding=PaddingStrategy.DO_NOT_PAD.value, # we pad in batch afterward
800
+ truncation=truncation_strategy.value,
801
+ max_length=max_length,
802
+ stride=stride,
803
+ pad_to_multiple_of=None, # we pad in batch afterward
804
+ padding_side=None, # we pad in batch afterward
805
+ return_attention_mask=False, # we pad in batch afterward
806
+ return_token_type_ids=return_token_type_ids,
807
+ return_overflowing_tokens=return_overflowing_tokens,
808
+ return_special_tokens_mask=return_special_tokens_mask,
809
+ return_length=return_length,
810
+ return_tensors=None, # We convert the whole batch to tensors at the end
811
+ prepend_batch_axis=False,
812
+ verbose=verbose,
813
+ )
814
+
815
+ for key, value in outputs.items():
816
+ if key not in batch_outputs:
817
+ batch_outputs[key] = []
818
+ batch_outputs[key].append(value)
819
+
820
+ batch_outputs = self.pad(
821
+ batch_outputs,
822
+ padding=padding_strategy.value,
823
+ max_length=max_length,
824
+ pad_to_multiple_of=pad_to_multiple_of,
825
+ padding_side=padding_side,
826
+ return_attention_mask=return_attention_mask,
827
+ )
828
+
829
+ batch_outputs = BatchEncoding(batch_outputs, tensor_type=return_tensors)
830
+
831
+ return batch_outputs
832
+
833
+ @add_end_docstrings(ENCODE_KWARGS_DOCSTRING)
834
+ def encode(
835
+ self,
836
+ text: Union[TextInput, PreTokenizedInput],
837
+ text_pair: Optional[PreTokenizedInput] = None,
838
+ xpaths: Optional[List[List[int]]] = None,
839
+ node_labels: Optional[List[int]] = None,
840
+ add_special_tokens: bool = True,
841
+ padding: Union[bool, str, PaddingStrategy] = False,
842
+ truncation: Union[bool, str, TruncationStrategy] = None,
843
+ max_length: Optional[int] = None,
844
+ stride: int = 0,
845
+ pad_to_multiple_of: Optional[int] = None,
846
+ padding_side: Optional[str] = None,
847
+ return_tensors: Optional[Union[str, TensorType]] = None,
848
+ return_token_type_ids: Optional[bool] = None,
849
+ return_attention_mask: Optional[bool] = None,
850
+ return_overflowing_tokens: bool = False,
851
+ return_special_tokens_mask: bool = False,
852
+ return_offsets_mapping: bool = False,
853
+ return_length: bool = False,
854
+ verbose: bool = True,
855
+ **kwargs,
856
+ ) -> List[int]:
857
+ encoded_inputs = self.encode_plus(
858
+ text=text,
859
+ text_pair=text_pair,
860
+ xpaths=xpaths,
861
+ node_labels=node_labels,
862
+ add_special_tokens=add_special_tokens,
863
+ padding=padding,
864
+ truncation=truncation,
865
+ max_length=max_length,
866
+ stride=stride,
867
+ pad_to_multiple_of=pad_to_multiple_of,
868
+ padding_side=padding_side,
869
+ return_tensors=return_tensors,
870
+ return_token_type_ids=return_token_type_ids,
871
+ return_attention_mask=return_attention_mask,
872
+ return_overflowing_tokens=return_overflowing_tokens,
873
+ return_special_tokens_mask=return_special_tokens_mask,
874
+ return_offsets_mapping=return_offsets_mapping,
875
+ return_length=return_length,
876
+ verbose=verbose,
877
+ **kwargs,
878
+ )
879
+
880
+ return encoded_inputs["input_ids"]
881
+
882
+ @add_end_docstrings(ENCODE_KWARGS_DOCSTRING, MARKUPLM_ENCODE_PLUS_ADDITIONAL_KWARGS_DOCSTRING)
883
+ def encode_plus(
884
+ self,
885
+ text: Union[TextInput, PreTokenizedInput],
886
+ text_pair: Optional[PreTokenizedInput] = None,
887
+ xpaths: Optional[List[List[int]]] = None,
888
+ node_labels: Optional[List[int]] = None,
889
+ add_special_tokens: bool = True,
890
+ padding: Union[bool, str, PaddingStrategy] = False,
891
+ truncation: Union[bool, str, TruncationStrategy] = None,
892
+ max_length: Optional[int] = None,
893
+ stride: int = 0,
894
+ pad_to_multiple_of: Optional[int] = None,
895
+ padding_side: Optional[str] = None,
896
+ return_tensors: Optional[Union[str, TensorType]] = None,
897
+ return_token_type_ids: Optional[bool] = None,
898
+ return_attention_mask: Optional[bool] = None,
899
+ return_overflowing_tokens: bool = False,
900
+ return_special_tokens_mask: bool = False,
901
+ return_offsets_mapping: bool = False,
902
+ return_length: bool = False,
903
+ verbose: bool = True,
904
+ **kwargs,
905
+ ) -> BatchEncoding:
906
+ """
907
+ Tokenize and prepare for the model a sequence or a pair of sequences. .. warning:: This method is deprecated,
908
+ `__call__` should be used instead.
909
+
910
+ Args:
911
+ text (`str`, `List[str]`, `List[List[str]]`):
912
+ The first sequence to be encoded. This can be a string, a list of strings or a list of list of strings.
913
+ text_pair (`List[str]` or `List[int]`, *optional*):
914
+ Optional second sequence to be encoded. This can be a list of strings (nodes of a single example) or a
915
+ list of list of strings (nodes of a batch of examples).
916
+ """
917
+
918
+ # Backward compatibility for 'truncation_strategy', 'pad_to_max_length'
919
+ padding_strategy, truncation_strategy, max_length, kwargs = self._get_padding_truncation_strategies(
920
+ padding=padding,
921
+ truncation=truncation,
922
+ max_length=max_length,
923
+ pad_to_multiple_of=pad_to_multiple_of,
924
+ verbose=verbose,
925
+ **kwargs,
926
+ )
927
+
928
+ return self._encode_plus(
929
+ text=text,
930
+ xpaths=xpaths,
931
+ text_pair=text_pair,
932
+ node_labels=node_labels,
933
+ add_special_tokens=add_special_tokens,
934
+ padding_strategy=padding_strategy,
935
+ truncation_strategy=truncation_strategy,
936
+ max_length=max_length,
937
+ stride=stride,
938
+ pad_to_multiple_of=pad_to_multiple_of,
939
+ padding_side=padding_side,
940
+ return_tensors=return_tensors,
941
+ return_token_type_ids=return_token_type_ids,
942
+ return_attention_mask=return_attention_mask,
943
+ return_overflowing_tokens=return_overflowing_tokens,
944
+ return_special_tokens_mask=return_special_tokens_mask,
945
+ return_offsets_mapping=return_offsets_mapping,
946
+ return_length=return_length,
947
+ verbose=verbose,
948
+ **kwargs,
949
+ )
950
+
951
+ def _encode_plus(
952
+ self,
953
+ text: Union[TextInput, PreTokenizedInput],
954
+ text_pair: Optional[PreTokenizedInput] = None,
955
+ xpaths: Optional[List[List[int]]] = None,
956
+ node_labels: Optional[List[int]] = None,
957
+ add_special_tokens: bool = True,
958
+ padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD,
959
+ truncation_strategy: TruncationStrategy = TruncationStrategy.DO_NOT_TRUNCATE,
960
+ max_length: Optional[int] = None,
961
+ stride: int = 0,
962
+ pad_to_multiple_of: Optional[int] = None,
963
+ padding_side: Optional[str] = None,
964
+ return_tensors: Optional[Union[str, TensorType]] = None,
965
+ return_token_type_ids: Optional[bool] = None,
966
+ return_attention_mask: Optional[bool] = None,
967
+ return_overflowing_tokens: bool = False,
968
+ return_special_tokens_mask: bool = False,
969
+ return_offsets_mapping: bool = False,
970
+ return_length: bool = False,
971
+ verbose: bool = True,
972
+ **kwargs,
973
+ ) -> BatchEncoding:
974
+ if return_offsets_mapping:
975
+ raise NotImplementedError(
976
+ "return_offset_mapping is not available when using Python tokenizers. "
977
+ "To use this feature, change your tokenizer to one deriving from "
978
+ "transformers.PreTrainedTokenizerFast. "
979
+ "More information on available tokenizers at "
980
+ "https://github.com/huggingface/transformers/pull/2674"
981
+ )
982
+
983
+ return self.prepare_for_model(
984
+ text=text,
985
+ text_pair=text_pair,
986
+ xpaths=xpaths,
987
+ node_labels=node_labels,
988
+ add_special_tokens=add_special_tokens,
989
+ padding=padding_strategy.value,
990
+ truncation=truncation_strategy.value,
991
+ max_length=max_length,
992
+ stride=stride,
993
+ pad_to_multiple_of=pad_to_multiple_of,
994
+ padding_side=padding_side,
995
+ return_tensors=return_tensors,
996
+ prepend_batch_axis=True,
997
+ return_attention_mask=return_attention_mask,
998
+ return_token_type_ids=return_token_type_ids,
999
+ return_overflowing_tokens=return_overflowing_tokens,
1000
+ return_special_tokens_mask=return_special_tokens_mask,
1001
+ return_length=return_length,
1002
+ verbose=verbose,
1003
+ )
1004
+
1005
+ @add_end_docstrings(ENCODE_KWARGS_DOCSTRING, MARKUPLM_ENCODE_PLUS_ADDITIONAL_KWARGS_DOCSTRING)
1006
+ def prepare_for_model(
1007
+ self,
1008
+ text: Union[TextInput, PreTokenizedInput],
1009
+ text_pair: Optional[PreTokenizedInput] = None,
1010
+ xpaths: Optional[List[List[int]]] = None,
1011
+ node_labels: Optional[List[int]] = None,
1012
+ add_special_tokens: bool = True,
1013
+ padding: Union[bool, str, PaddingStrategy] = False,
1014
+ truncation: Union[bool, str, TruncationStrategy] = None,
1015
+ max_length: Optional[int] = None,
1016
+ stride: int = 0,
1017
+ pad_to_multiple_of: Optional[int] = None,
1018
+ padding_side: Optional[str] = None,
1019
+ return_tensors: Optional[Union[str, TensorType]] = None,
1020
+ return_token_type_ids: Optional[bool] = None,
1021
+ return_attention_mask: Optional[bool] = None,
1022
+ return_overflowing_tokens: bool = False,
1023
+ return_special_tokens_mask: bool = False,
1024
+ return_offsets_mapping: bool = False,
1025
+ return_length: bool = False,
1026
+ verbose: bool = True,
1027
+ prepend_batch_axis: bool = False,
1028
+ **kwargs,
1029
+ ) -> BatchEncoding:
1030
+ """
1031
+ Prepares a sequence or a pair of sequences so that it can be used by the model. It adds special tokens,
1032
+ truncates sequences if overflowing while taking into account the special tokens and manages a moving window
1033
+ (with user defined stride) for overflowing tokens. Please Note, for *text_pair* different than `None` and
1034
+ *truncation_strategy = longest_first* or `True`, it is not possible to return overflowing tokens. Such a
1035
+ combination of arguments will raise an error.
1036
+
1037
+ Node-level `xpaths` are turned into token-level `xpath_tags_seq` and `xpath_subs_seq`. If provided, node-level
1038
+ `node_labels` are turned into token-level `labels`. The node label is used for the first token of the node,
1039
+ while remaining tokens are labeled with -100, such that they will be ignored by the loss function.
1040
+
1041
+ Args:
1042
+ text (`str`, `List[str]`, `List[List[str]]`):
1043
+ The first sequence to be encoded. This can be a string, a list of strings or a list of list of strings.
1044
+ text_pair (`List[str]` or `List[int]`, *optional*):
1045
+ Optional second sequence to be encoded. This can be a list of strings (nodes of a single example) or a
1046
+ list of list of strings (nodes of a batch of examples).
1047
+ """
1048
+
1049
+ # Backward compatibility for 'truncation_strategy', 'pad_to_max_length'
1050
+ padding_strategy, truncation_strategy, max_length, kwargs = self._get_padding_truncation_strategies(
1051
+ padding=padding,
1052
+ truncation=truncation,
1053
+ max_length=max_length,
1054
+ pad_to_multiple_of=pad_to_multiple_of,
1055
+ verbose=verbose,
1056
+ **kwargs,
1057
+ )
1058
+
1059
+ tokens = []
1060
+ pair_tokens = []
1061
+ xpath_tags_seq = []
1062
+ xpath_subs_seq = []
1063
+ pair_xpath_tags_seq = []
1064
+ pair_xpath_subs_seq = []
1065
+ labels = []
1066
+
1067
+ if text_pair is None:
1068
+ if node_labels is None:
1069
+ # CASE 1: web page classification (training + inference) + CASE 2: token classification (inference)
1070
+ for word, xpath in zip(text, xpaths):
1071
+ if len(word) < 1: # skip empty nodes
1072
+ continue
1073
+ word_tokens = self.tokenize(word)
1074
+ tokens.extend(word_tokens)
1075
+ xpath_tags_list, xpath_subs_list = self.get_xpath_seq(xpath)
1076
+ xpath_tags_seq.extend([xpath_tags_list] * len(word_tokens))
1077
+ xpath_subs_seq.extend([xpath_subs_list] * len(word_tokens))
1078
+ else:
1079
+ # CASE 2: token classification (training)
1080
+ for word, xpath, label in zip(text, xpaths, node_labels):
1081
+ if len(word) < 1: # skip empty nodes
1082
+ continue
1083
+ word_tokens = self.tokenize(word)
1084
+ tokens.extend(word_tokens)
1085
+ xpath_tags_list, xpath_subs_list = self.get_xpath_seq(xpath)
1086
+ xpath_tags_seq.extend([xpath_tags_list] * len(word_tokens))
1087
+ xpath_subs_seq.extend([xpath_subs_list] * len(word_tokens))
1088
+ if self.only_label_first_subword:
1089
+ # Use the real label id for the first token of the word, and padding ids for the remaining tokens
1090
+ labels.extend([label] + [self.pad_token_label] * (len(word_tokens) - 1))
1091
+ else:
1092
+ labels.extend([label] * len(word_tokens))
1093
+ else:
1094
+ # CASE 3: web page question answering (inference)
1095
+ # text = question
1096
+ # text_pair = nodes
1097
+ tokens = self.tokenize(text)
1098
+ xpath_tags_seq = [self.pad_xpath_tags_seq for _ in range(len(tokens))]
1099
+ xpath_subs_seq = [self.pad_xpath_subs_seq for _ in range(len(tokens))]
1100
+
1101
+ for word, xpath in zip(text_pair, xpaths):
1102
+ if len(word) < 1: # skip empty nodes
1103
+ continue
1104
+ word_tokens = self.tokenize(word)
1105
+ pair_tokens.extend(word_tokens)
1106
+ xpath_tags_list, xpath_subs_list = self.get_xpath_seq(xpath)
1107
+ pair_xpath_tags_seq.extend([xpath_tags_list] * len(word_tokens))
1108
+ pair_xpath_subs_seq.extend([xpath_subs_list] * len(word_tokens))
1109
+
1110
+ # Create ids + pair_ids
1111
+ ids = self.convert_tokens_to_ids(tokens)
1112
+ pair_ids = self.convert_tokens_to_ids(pair_tokens) if pair_tokens else None
1113
+
1114
+ if (
1115
+ return_overflowing_tokens
1116
+ and truncation_strategy == TruncationStrategy.LONGEST_FIRST
1117
+ and pair_ids is not None
1118
+ ):
1119
+ raise ValueError(
1120
+ "Not possible to return overflowing tokens for pair of sequences with the "
1121
+ "`longest_first`. Please select another truncation strategy than `longest_first`, "
1122
+ "for instance `only_second` or `only_first`."
1123
+ )
1124
+
1125
+ # Compute the total size of the returned encodings
1126
+ pair = bool(pair_ids is not None)
1127
+ len_ids = len(ids)
1128
+ len_pair_ids = len(pair_ids) if pair else 0
1129
+ total_len = len_ids + len_pair_ids + (self.num_special_tokens_to_add(pair=pair) if add_special_tokens else 0)
1130
+
1131
+ # Truncation: Handle max sequence length
1132
+ overflowing_tokens = []
1133
+ overflowing_xpath_tags_seq = []
1134
+ overflowing_xpath_subs_seq = []
1135
+ overflowing_labels = []
1136
+ if truncation_strategy != TruncationStrategy.DO_NOT_TRUNCATE and max_length and total_len > max_length:
1137
+ (
1138
+ ids,
1139
+ xpath_tags_seq,
1140
+ xpath_subs_seq,
1141
+ pair_ids,
1142
+ pair_xpath_tags_seq,
1143
+ pair_xpath_subs_seq,
1144
+ labels,
1145
+ overflowing_tokens,
1146
+ overflowing_xpath_tags_seq,
1147
+ overflowing_xpath_subs_seq,
1148
+ overflowing_labels,
1149
+ ) = self.truncate_sequences(
1150
+ ids,
1151
+ xpath_tags_seq=xpath_tags_seq,
1152
+ xpath_subs_seq=xpath_subs_seq,
1153
+ pair_ids=pair_ids,
1154
+ pair_xpath_tags_seq=pair_xpath_tags_seq,
1155
+ pair_xpath_subs_seq=pair_xpath_subs_seq,
1156
+ labels=labels,
1157
+ num_tokens_to_remove=total_len - max_length,
1158
+ truncation_strategy=truncation_strategy,
1159
+ stride=stride,
1160
+ )
1161
+
1162
+ if return_token_type_ids and not add_special_tokens:
1163
+ raise ValueError(
1164
+ "Asking to return token_type_ids while setting add_special_tokens to False "
1165
+ "results in an undefined behavior. Please set add_special_tokens to True or "
1166
+ "set return_token_type_ids to None."
1167
+ )
1168
+
1169
+ # Load from model defaults
1170
+ if return_token_type_ids is None:
1171
+ return_token_type_ids = "token_type_ids" in self.model_input_names
1172
+ if return_attention_mask is None:
1173
+ return_attention_mask = "attention_mask" in self.model_input_names
1174
+
1175
+ encoded_inputs = {}
1176
+
1177
+ if return_overflowing_tokens:
1178
+ encoded_inputs["overflowing_tokens"] = overflowing_tokens
1179
+ encoded_inputs["overflowing_xpath_tags_seq"] = overflowing_xpath_tags_seq
1180
+ encoded_inputs["overflowing_xpath_subs_seq"] = overflowing_xpath_subs_seq
1181
+ encoded_inputs["overflowing_labels"] = overflowing_labels
1182
+ encoded_inputs["num_truncated_tokens"] = total_len - max_length
1183
+
1184
+ # Add special tokens
1185
+ if add_special_tokens:
1186
+ sequence = self.build_inputs_with_special_tokens(ids, pair_ids)
1187
+ token_type_ids = self.create_token_type_ids_from_sequences(ids, pair_ids)
1188
+ xpath_tags_ids = self.build_xpath_tags_with_special_tokens(xpath_tags_seq, pair_xpath_tags_seq)
1189
+ xpath_subs_ids = self.build_xpath_subs_with_special_tokens(xpath_subs_seq, pair_xpath_subs_seq)
1190
+ if labels:
1191
+ labels = [self.pad_token_label] + labels + [self.pad_token_label]
1192
+ else:
1193
+ sequence = ids + pair_ids if pair else ids
1194
+ token_type_ids = [0] * len(ids) + ([0] * len(pair_ids) if pair else [])
1195
+ xpath_tags_ids = xpath_tags_seq + pair_xpath_tags_seq if pair else xpath_tags_seq
1196
+ xpath_subs_ids = xpath_subs_seq + pair_xpath_subs_seq if pair else xpath_subs_seq
1197
+
1198
+ # Build output dictionary
1199
+ encoded_inputs["input_ids"] = sequence
1200
+ encoded_inputs["xpath_tags_seq"] = xpath_tags_ids
1201
+ encoded_inputs["xpath_subs_seq"] = xpath_subs_ids
1202
+ if return_token_type_ids:
1203
+ encoded_inputs["token_type_ids"] = token_type_ids
1204
+ if return_special_tokens_mask:
1205
+ if add_special_tokens:
1206
+ encoded_inputs["special_tokens_mask"] = self.get_special_tokens_mask(ids, pair_ids)
1207
+ else:
1208
+ encoded_inputs["special_tokens_mask"] = [0] * len(sequence)
1209
+
1210
+ if labels:
1211
+ encoded_inputs["labels"] = labels
1212
+
1213
+ # Check lengths
1214
+ self._eventual_warn_about_too_long_sequence(encoded_inputs["input_ids"], max_length, verbose)
1215
+
1216
+ # Padding
1217
+ if padding_strategy != PaddingStrategy.DO_NOT_PAD or return_attention_mask:
1218
+ encoded_inputs = self.pad(
1219
+ encoded_inputs,
1220
+ max_length=max_length,
1221
+ padding=padding_strategy.value,
1222
+ pad_to_multiple_of=pad_to_multiple_of,
1223
+ padding_side=padding_side,
1224
+ return_attention_mask=return_attention_mask,
1225
+ )
1226
+
1227
+ if return_length:
1228
+ encoded_inputs["length"] = len(encoded_inputs["input_ids"])
1229
+
1230
+ batch_outputs = BatchEncoding(
1231
+ encoded_inputs, tensor_type=return_tensors, prepend_batch_axis=prepend_batch_axis
1232
+ )
1233
+
1234
+ return batch_outputs
1235
+
1236
+ def truncate_sequences(
1237
+ self,
1238
+ ids: List[int],
1239
+ xpath_tags_seq: List[List[int]],
1240
+ xpath_subs_seq: List[List[int]],
1241
+ pair_ids: Optional[List[int]] = None,
1242
+ pair_xpath_tags_seq: Optional[List[List[int]]] = None,
1243
+ pair_xpath_subs_seq: Optional[List[List[int]]] = None,
1244
+ labels: Optional[List[int]] = None,
1245
+ num_tokens_to_remove: int = 0,
1246
+ truncation_strategy: Union[str, TruncationStrategy] = "longest_first",
1247
+ stride: int = 0,
1248
+ ) -> Tuple[List[int], List[int], List[int]]:
1249
+ """
1250
+ Args:
1251
+ Truncates a sequence pair in-place following the strategy.
1252
+ ids (`List[int]`):
1253
+ Tokenized input ids of the first sequence. Can be obtained from a string by chaining the `tokenize` and
1254
+ `convert_tokens_to_ids` methods.
1255
+ xpath_tags_seq (`List[List[int]]`):
1256
+ XPath tag IDs of the first sequence.
1257
+ xpath_subs_seq (`List[List[int]]`):
1258
+ XPath sub IDs of the first sequence.
1259
+ pair_ids (`List[int]`, *optional*):
1260
+ Tokenized input ids of the second sequence. Can be obtained from a string by chaining the `tokenize`
1261
+ and `convert_tokens_to_ids` methods.
1262
+ pair_xpath_tags_seq (`List[List[int]]`, *optional*):
1263
+ XPath tag IDs of the second sequence.
1264
+ pair_xpath_subs_seq (`List[List[int]]`, *optional*):
1265
+ XPath sub IDs of the second sequence.
1266
+ num_tokens_to_remove (`int`, *optional*, defaults to 0):
1267
+ Number of tokens to remove using the truncation strategy.
1268
+ truncation_strategy (`str` or [`~tokenization_utils_base.TruncationStrategy`], *optional*, defaults to
1269
+ `False`):
1270
+ The strategy to follow for truncation. Can be:
1271
+ - `'longest_first'`: Truncate to a maximum length specified with the argument `max_length` or to the
1272
+ maximum acceptable input length for the model if that argument is not provided. This will truncate
1273
+ token by token, removing a token from the longest sequence in the pair if a pair of sequences (or a
1274
+ batch of pairs) is provided.
1275
+ - `'only_first'`: Truncate to a maximum length specified with the argument `max_length` or to the
1276
+ maximum acceptable input length for the model if that argument is not provided. This will only
1277
+ truncate the first sequence of a pair if a pair of sequences (or a batch of pairs) is provided.
1278
+ - `'only_second'`: Truncate to a maximum length specified with the argument `max_length` or to the
1279
+ maximum acceptable input length for the model if that argument is not provided. This will only
1280
+ truncate the second sequence of a pair if a pair of sequences (or a batch of pairs) is provided.
1281
+ - `'do_not_truncate'` (default): No truncation (i.e., can output batch with sequence lengths greater
1282
+ than the model maximum admissible input size).
1283
+ stride (`int`, *optional*, defaults to 0):
1284
+ If set to a positive number, the overflowing tokens returned will contain some tokens from the main
1285
+ sequence returned. The value of this argument defines the number of additional tokens.
1286
+ Returns:
1287
+ `Tuple[List[int], List[int], List[int]]`: The truncated `ids`, the truncated `pair_ids` and the list of
1288
+ overflowing tokens. Note: The *longest_first* strategy returns empty list of overflowing tokens if a pair
1289
+ of sequences (or a batch of pairs) is provided.
1290
+ """
1291
+ if num_tokens_to_remove <= 0:
1292
+ return ids, xpath_tags_seq, xpath_subs_seq, pair_ids, pair_xpath_tags_seq, pair_xpath_subs_seq, [], [], []
1293
+
1294
+ if not isinstance(truncation_strategy, TruncationStrategy):
1295
+ truncation_strategy = TruncationStrategy(truncation_strategy)
1296
+
1297
+ overflowing_tokens = []
1298
+ overflowing_xpath_tags_seq = []
1299
+ overflowing_xpath_subs_seq = []
1300
+ overflowing_labels = []
1301
+ if truncation_strategy == TruncationStrategy.ONLY_FIRST or (
1302
+ truncation_strategy == TruncationStrategy.LONGEST_FIRST and pair_ids is None
1303
+ ):
1304
+ if len(ids) > num_tokens_to_remove:
1305
+ window_len = min(len(ids), stride + num_tokens_to_remove)
1306
+ overflowing_tokens = ids[-window_len:]
1307
+ overflowing_xpath_tags_seq = xpath_tags_seq[-window_len:]
1308
+ overflowing_xpath_subs_seq = xpath_subs_seq[-window_len:]
1309
+ ids = ids[:-num_tokens_to_remove]
1310
+ xpath_tags_seq = xpath_tags_seq[:-num_tokens_to_remove]
1311
+ xpath_subs_seq = xpath_subs_seq[:-num_tokens_to_remove]
1312
+ labels = labels[:-num_tokens_to_remove]
1313
+ else:
1314
+ error_msg = (
1315
+ f"We need to remove {num_tokens_to_remove} to truncate the input "
1316
+ f"but the first sequence has a length {len(ids)}. "
1317
+ )
1318
+ if truncation_strategy == TruncationStrategy.ONLY_FIRST:
1319
+ error_msg = (
1320
+ error_msg + "Please select another truncation strategy than "
1321
+ f"{truncation_strategy}, for instance 'longest_first' or 'only_second'."
1322
+ )
1323
+ logger.error(error_msg)
1324
+ elif truncation_strategy == TruncationStrategy.LONGEST_FIRST:
1325
+ logger.warning(
1326
+ "Be aware, overflowing tokens are not returned for the setting you have chosen,"
1327
+ f" i.e. sequence pairs with the '{TruncationStrategy.LONGEST_FIRST.value}' "
1328
+ "truncation strategy. So the returned list will always be empty even if some "
1329
+ "tokens have been removed."
1330
+ )
1331
+ for _ in range(num_tokens_to_remove):
1332
+ if pair_ids is None or len(ids) > len(pair_ids):
1333
+ ids = ids[:-1]
1334
+ xpath_tags_seq = xpath_tags_seq[:-1]
1335
+ xpath_subs_seq = xpath_subs_seq[:-1]
1336
+ labels = labels[:-1]
1337
+ else:
1338
+ pair_ids = pair_ids[:-1]
1339
+ pair_xpath_tags_seq = pair_xpath_tags_seq[:-1]
1340
+ pair_xpath_subs_seq = pair_xpath_subs_seq[:-1]
1341
+ elif truncation_strategy == TruncationStrategy.ONLY_SECOND and pair_ids is not None:
1342
+ if len(pair_ids) > num_tokens_to_remove:
1343
+ window_len = min(len(pair_ids), stride + num_tokens_to_remove)
1344
+ overflowing_tokens = pair_ids[-window_len:]
1345
+ overflowing_xpath_tags_seq = pair_xpath_tags_seq[-window_len:]
1346
+ overflowing_xpath_subs_seq = pair_xpath_subs_seq[-window_len:]
1347
+ pair_ids = pair_ids[:-num_tokens_to_remove]
1348
+ pair_xpath_tags_seq = pair_xpath_tags_seq[:-num_tokens_to_remove]
1349
+ pair_xpath_subs_seq = pair_xpath_subs_seq[:-num_tokens_to_remove]
1350
+ else:
1351
+ logger.error(
1352
+ f"We need to remove {num_tokens_to_remove} to truncate the input "
1353
+ f"but the second sequence has a length {len(pair_ids)}. "
1354
+ f"Please select another truncation strategy than {truncation_strategy}, "
1355
+ "for instance 'longest_first' or 'only_first'."
1356
+ )
1357
+
1358
+ return (
1359
+ ids,
1360
+ xpath_tags_seq,
1361
+ xpath_subs_seq,
1362
+ pair_ids,
1363
+ pair_xpath_tags_seq,
1364
+ pair_xpath_subs_seq,
1365
+ labels,
1366
+ overflowing_tokens,
1367
+ overflowing_xpath_tags_seq,
1368
+ overflowing_xpath_subs_seq,
1369
+ overflowing_labels,
1370
+ )
1371
+
1372
+ def _pad(
1373
+ self,
1374
+ encoded_inputs: Union[Dict[str, EncodedInput], BatchEncoding],
1375
+ max_length: Optional[int] = None,
1376
+ padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD,
1377
+ pad_to_multiple_of: Optional[int] = None,
1378
+ padding_side: Optional[str] = None,
1379
+ return_attention_mask: Optional[bool] = None,
1380
+ ) -> dict:
1381
+ """
1382
+ Args:
1383
+ Pad encoded inputs (on left/right and up to predefined length or max length in the batch)
1384
+ encoded_inputs:
1385
+ Dictionary of tokenized inputs (`List[int]`) or batch of tokenized inputs (`List[List[int]]`).
1386
+ max_length: maximum length of the returned list and optionally padding length (see below).
1387
+ Will truncate by taking into account the special tokens.
1388
+ padding_strategy: PaddingStrategy to use for padding.
1389
+ - PaddingStrategy.LONGEST Pad to the longest sequence in the batch
1390
+ - PaddingStrategy.MAX_LENGTH: Pad to the max length (default)
1391
+ - PaddingStrategy.DO_NOT_PAD: Do not pad
1392
+ The tokenizer padding sides are defined in self.padding_side:
1393
+ - 'left': pads on the left of the sequences
1394
+ - 'right': pads on the right of the sequences
1395
+ pad_to_multiple_of: (optional) Integer if set will pad the sequence to a multiple of the provided value.
1396
+ This is especially useful to enable the use of Tensor Core on NVIDIA hardware with compute capability
1397
+ `>= 7.5` (Volta).
1398
+ padding_side:
1399
+ The side on which the model should have padding applied. Should be selected between ['right', 'left'].
1400
+ Default value is picked from the class attribute of the same name.
1401
+ return_attention_mask:
1402
+ (optional) Set to False to avoid returning attention mask (default: set to model specifics)
1403
+ """
1404
+ # Load from model defaults
1405
+ if return_attention_mask is None:
1406
+ return_attention_mask = "attention_mask" in self.model_input_names
1407
+
1408
+ required_input = encoded_inputs[self.model_input_names[0]]
1409
+
1410
+ if padding_strategy == PaddingStrategy.LONGEST:
1411
+ max_length = len(required_input)
1412
+
1413
+ if max_length is not None and pad_to_multiple_of is not None and (max_length % pad_to_multiple_of != 0):
1414
+ max_length = ((max_length // pad_to_multiple_of) + 1) * pad_to_multiple_of
1415
+
1416
+ needs_to_be_padded = padding_strategy != PaddingStrategy.DO_NOT_PAD and len(required_input) != max_length
1417
+
1418
+ # Initialize attention mask if not present.
1419
+ if return_attention_mask and "attention_mask" not in encoded_inputs:
1420
+ encoded_inputs["attention_mask"] = [1] * len(required_input)
1421
+
1422
+ if needs_to_be_padded:
1423
+ difference = max_length - len(required_input)
1424
+ padding_side = padding_side if padding_side is not None else self.padding_side
1425
+ if padding_side == "right":
1426
+ if return_attention_mask:
1427
+ encoded_inputs["attention_mask"] = encoded_inputs["attention_mask"] + [0] * difference
1428
+ if "token_type_ids" in encoded_inputs:
1429
+ encoded_inputs["token_type_ids"] = (
1430
+ encoded_inputs["token_type_ids"] + [self.pad_token_type_id] * difference
1431
+ )
1432
+ if "xpath_tags_seq" in encoded_inputs:
1433
+ encoded_inputs["xpath_tags_seq"] = (
1434
+ encoded_inputs["xpath_tags_seq"] + [self.pad_xpath_tags_seq] * difference
1435
+ )
1436
+ if "xpath_subs_seq" in encoded_inputs:
1437
+ encoded_inputs["xpath_subs_seq"] = (
1438
+ encoded_inputs["xpath_subs_seq"] + [self.pad_xpath_subs_seq] * difference
1439
+ )
1440
+ if "labels" in encoded_inputs:
1441
+ encoded_inputs["labels"] = encoded_inputs["labels"] + [self.pad_token_label] * difference
1442
+ if "special_tokens_mask" in encoded_inputs:
1443
+ encoded_inputs["special_tokens_mask"] = encoded_inputs["special_tokens_mask"] + [1] * difference
1444
+ encoded_inputs[self.model_input_names[0]] = required_input + [self.pad_token_id] * difference
1445
+ elif padding_side == "left":
1446
+ if return_attention_mask:
1447
+ encoded_inputs["attention_mask"] = [0] * difference + encoded_inputs["attention_mask"]
1448
+ if "token_type_ids" in encoded_inputs:
1449
+ encoded_inputs["token_type_ids"] = [self.pad_token_type_id] * difference + encoded_inputs[
1450
+ "token_type_ids"
1451
+ ]
1452
+ if "xpath_tags_seq" in encoded_inputs:
1453
+ encoded_inputs["xpath_tags_seq"] = [self.pad_xpath_tags_seq] * difference + encoded_inputs[
1454
+ "xpath_tags_seq"
1455
+ ]
1456
+ if "xpath_subs_seq" in encoded_inputs:
1457
+ encoded_inputs["xpath_subs_seq"] = [self.pad_xpath_subs_seq] * difference + encoded_inputs[
1458
+ "xpath_subs_seq"
1459
+ ]
1460
+ if "labels" in encoded_inputs:
1461
+ encoded_inputs["labels"] = [self.pad_token_label] * difference + encoded_inputs["labels"]
1462
+ if "special_tokens_mask" in encoded_inputs:
1463
+ encoded_inputs["special_tokens_mask"] = [1] * difference + encoded_inputs["special_tokens_mask"]
1464
+ encoded_inputs[self.model_input_names[0]] = [self.pad_token_id] * difference + required_input
1465
+ else:
1466
+ raise ValueError("Invalid padding strategy:" + str(padding_side))
1467
+
1468
+ return encoded_inputs
1469
+
1470
+
1471
+ __all__ = ["MarkupLMTokenizer"]
tasks/tasksmith-441eeab80047/environment/source/src/transformers/models/markuplm/tokenization_markuplm_fast.py ADDED
@@ -0,0 +1,929 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 The HuggingFace Inc. team.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """
16
+ Fast tokenization class for MarkupLM. It overwrites 2 methods of the slow tokenizer class, namely _batch_encode_plus
17
+ and _encode_plus, in which the Rust tokenizer is used.
18
+ """
19
+
20
+ import json
21
+ from functools import lru_cache
22
+ from typing import Dict, List, Optional, Tuple, Union
23
+
24
+ from tokenizers import processors
25
+
26
+ from ...file_utils import PaddingStrategy, TensorType, add_end_docstrings
27
+ from ...tokenization_utils_base import (
28
+ ENCODE_KWARGS_DOCSTRING,
29
+ AddedToken,
30
+ BatchEncoding,
31
+ EncodedInput,
32
+ PreTokenizedInput,
33
+ TextInput,
34
+ TextInputPair,
35
+ TruncationStrategy,
36
+ )
37
+ from ...tokenization_utils_fast import PreTrainedTokenizerFast
38
+ from ...utils import logging
39
+ from .tokenization_markuplm import MARKUPLM_ENCODE_PLUS_ADDITIONAL_KWARGS_DOCSTRING, MarkupLMTokenizer
40
+
41
+
42
+ logger = logging.get_logger(__name__)
43
+
44
+ VOCAB_FILES_NAMES = {"vocab_file": "vocab.json", "merges_file": "merges.txt", "tokenizer_file": "tokenizer.json"}
45
+
46
+
47
+ @lru_cache()
48
+ def bytes_to_unicode():
49
+ """
50
+ Returns list of utf-8 byte and a mapping to unicode strings. We specifically avoids mapping to whitespace/control
51
+ characters the bpe code barfs on. The reversible bpe codes work on unicode strings. This means you need a large #
52
+ of unicode characters in your vocab if you want to avoid UNKs. When you're at something like a 10B token dataset
53
+ you end up needing around 5K for decent coverage. This is a significant percentage of your normal, say, 32K bpe
54
+ vocab. To avoid that, we want lookup tables between utf-8 bytes and unicode strings.
55
+ """
56
+ bs = (
57
+ list(range(ord("!"), ord("~") + 1)) + list(range(ord("¡"), ord("¬") + 1)) + list(range(ord("®"), ord("ÿ") + 1))
58
+ )
59
+ cs = bs[:]
60
+ n = 0
61
+ for b in range(2**8):
62
+ if b not in bs:
63
+ bs.append(b)
64
+ cs.append(2**8 + n)
65
+ n += 1
66
+ cs = [chr(n) for n in cs]
67
+ return dict(zip(bs, cs))
68
+
69
+
70
+ def get_pairs(word):
71
+ """
72
+ Return set of symbol pairs in a word. Word is represented as tuple of symbols (symbols being variable-length
73
+ strings).
74
+ """
75
+ pairs = set()
76
+ prev_char = word[0]
77
+ for char in word[1:]:
78
+ pairs.add((prev_char, char))
79
+ prev_char = char
80
+ return pairs
81
+
82
+
83
+ class MarkupLMTokenizerFast(PreTrainedTokenizerFast):
84
+ r"""
85
+ Construct a MarkupLM tokenizer. Based on byte-level Byte-Pair-Encoding (BPE).
86
+
87
+ [`MarkupLMTokenizerFast`] can be used to turn HTML strings into to token-level `input_ids`, `attention_mask`,
88
+ `token_type_ids`, `xpath_tags_seq` and `xpath_tags_seq`. This tokenizer inherits from [`PreTrainedTokenizer`] which
89
+ contains most of the main methods.
90
+
91
+ Users should refer to this superclass for more information regarding those methods.
92
+
93
+ Args:
94
+ vocab_file (`str`):
95
+ Path to the vocabulary file.
96
+ merges_file (`str`):
97
+ Path to the merges file.
98
+ errors (`str`, *optional*, defaults to `"replace"`):
99
+ Paradigm to follow when decoding bytes to UTF-8. See
100
+ [bytes.decode](https://docs.python.org/3/library/stdtypes.html#bytes.decode) for more information.
101
+ bos_token (`str`, *optional*, defaults to `"<s>"`):
102
+ The beginning of sequence token that was used during pretraining. Can be used a sequence classifier token.
103
+
104
+ <Tip>
105
+
106
+ When building a sequence using special tokens, this is not the token that is used for the beginning of
107
+ sequence. The token used is the `cls_token`.
108
+
109
+ </Tip>
110
+
111
+ eos_token (`str`, *optional*, defaults to `"</s>"`):
112
+ The end of sequence token.
113
+
114
+ <Tip>
115
+
116
+ When building a sequence using special tokens, this is not the token that is used for the end of sequence.
117
+ The token used is the `sep_token`.
118
+
119
+ </Tip>
120
+
121
+ sep_token (`str`, *optional*, defaults to `"</s>"`):
122
+ The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
123
+ sequence classification or for a text and a question for question answering. It is also used as the last
124
+ token of a sequence built with special tokens.
125
+ cls_token (`str`, *optional*, defaults to `"<s>"`):
126
+ The classifier token which is used when doing sequence classification (classification of the whole sequence
127
+ instead of per-token classification). It is the first token of the sequence when built with special tokens.
128
+ unk_token (`str`, *optional*, defaults to `"<unk>"`):
129
+ The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
130
+ token instead.
131
+ pad_token (`str`, *optional*, defaults to `"<pad>"`):
132
+ The token used for padding, for example when batching sequences of different lengths.
133
+ mask_token (`str`, *optional*, defaults to `"<mask>"`):
134
+ The token used for masking values. This is the token used when training this model with masked language
135
+ modeling. This is the token which the model will try to predict.
136
+ add_prefix_space (`bool`, *optional*, defaults to `False`):
137
+ Whether or not to add an initial space to the input. This allows to treat the leading word just as any
138
+ other word. (RoBERTa tokenizer detect beginning of words by the preceding space).
139
+ """
140
+
141
+ vocab_files_names = VOCAB_FILES_NAMES
142
+ slow_tokenizer_class = MarkupLMTokenizer
143
+
144
+ def __init__(
145
+ self,
146
+ vocab_file,
147
+ merges_file,
148
+ tags_dict,
149
+ tokenizer_file=None,
150
+ errors="replace",
151
+ bos_token="<s>",
152
+ eos_token="</s>",
153
+ sep_token="</s>",
154
+ cls_token="<s>",
155
+ unk_token="<unk>",
156
+ pad_token="<pad>",
157
+ mask_token="<mask>",
158
+ add_prefix_space=False,
159
+ max_depth=50,
160
+ max_width=1000,
161
+ pad_width=1001,
162
+ pad_token_label=-100,
163
+ only_label_first_subword=True,
164
+ trim_offsets=False,
165
+ **kwargs,
166
+ ):
167
+ bos_token = AddedToken(bos_token, lstrip=False, rstrip=False) if isinstance(bos_token, str) else bos_token
168
+ eos_token = AddedToken(eos_token, lstrip=False, rstrip=False) if isinstance(eos_token, str) else eos_token
169
+ sep_token = AddedToken(sep_token, lstrip=False, rstrip=False) if isinstance(sep_token, str) else sep_token
170
+ cls_token = AddedToken(cls_token, lstrip=False, rstrip=False) if isinstance(cls_token, str) else cls_token
171
+ unk_token = AddedToken(unk_token, lstrip=False, rstrip=False) if isinstance(unk_token, str) else unk_token
172
+ pad_token = AddedToken(pad_token, lstrip=False, rstrip=False) if isinstance(pad_token, str) else pad_token
173
+
174
+ # Mask token behave like a normal word, i.e. include the space before it
175
+ mask_token = AddedToken(mask_token, lstrip=True, rstrip=False) if isinstance(mask_token, str) else mask_token
176
+
177
+ super().__init__(
178
+ vocab_file=vocab_file,
179
+ merges_file=merges_file,
180
+ tags_dict=tags_dict,
181
+ tokenizer_file=tokenizer_file,
182
+ errors=errors,
183
+ bos_token=bos_token,
184
+ eos_token=eos_token,
185
+ unk_token=unk_token,
186
+ sep_token=sep_token,
187
+ cls_token=cls_token,
188
+ pad_token=pad_token,
189
+ mask_token=mask_token,
190
+ add_prefix_space=add_prefix_space,
191
+ trim_offsets=trim_offsets,
192
+ max_depth=max_depth,
193
+ max_width=max_width,
194
+ pad_width=pad_width,
195
+ pad_token_label=pad_token_label,
196
+ only_label_first_subword=only_label_first_subword,
197
+ **kwargs,
198
+ )
199
+ if trim_offsets:
200
+ # Not implemented yet, because we need to chain two post processors which is not possible yet
201
+ # We need to wait for https://github.com/huggingface/tokenizers/pull/1005
202
+ # With `trim_offsets=False` we don't need to do add `processors.ByteLevel(trim_offsets=False)`
203
+ # because it's not doing anything
204
+ raise NotImplementedError(
205
+ "`trim_offsets=True` is not implemented for MarkupLMTokenizerFast. Please set it to False."
206
+ )
207
+
208
+ self.tags_dict = tags_dict
209
+
210
+ tokenizer_component = "post_processor"
211
+ tokenizer_component_instance = getattr(self.backend_tokenizer, tokenizer_component, None)
212
+ if tokenizer_component_instance:
213
+ state = json.loads(tokenizer_component_instance.__getstate__())
214
+
215
+ # The lists 'sep' and 'cls' must be cased in tuples for the object `post_processor_class`
216
+ if "sep" in state:
217
+ state["sep"] = tuple(state["sep"])
218
+ if "cls" in state:
219
+ state["cls"] = tuple(state["cls"])
220
+
221
+ changes_to_apply = False
222
+
223
+ if state.get("add_prefix_space", add_prefix_space) != add_prefix_space:
224
+ state["add_prefix_space"] = add_prefix_space
225
+ changes_to_apply = True
226
+
227
+ if changes_to_apply:
228
+ component_class = getattr(processors, state.pop("type"))
229
+ new_value = component_class(**state)
230
+ setattr(self.backend_tokenizer, tokenizer_component, new_value)
231
+
232
+ # additional properties
233
+ self.max_depth = max_depth
234
+ self.max_width = max_width
235
+ self.pad_width = pad_width
236
+ self.unk_tag_id = len(self.tags_dict)
237
+ self.pad_tag_id = self.unk_tag_id + 1
238
+ self.pad_xpath_tags_seq = [self.pad_tag_id] * self.max_depth
239
+ self.pad_xpath_subs_seq = [self.pad_width] * self.max_depth
240
+ self.pad_token_label = pad_token_label
241
+ self.only_label_first_subword = only_label_first_subword
242
+
243
+ def get_xpath_seq(self, xpath):
244
+ """
245
+ Given the xpath expression of one particular node (like "/html/body/div/li[1]/div/span[2]"), return a list of
246
+ tag IDs and corresponding subscripts, taking into account max depth.
247
+ """
248
+ xpath_tags_list = []
249
+ xpath_subs_list = []
250
+
251
+ xpath_units = xpath.split("/")
252
+ for unit in xpath_units:
253
+ if not unit.strip():
254
+ continue
255
+ name_subs = unit.strip().split("[")
256
+ tag_name = name_subs[0]
257
+ sub = 0 if len(name_subs) == 1 else int(name_subs[1][:-1])
258
+ xpath_tags_list.append(self.tags_dict.get(tag_name, self.unk_tag_id))
259
+ xpath_subs_list.append(min(self.max_width, sub))
260
+
261
+ xpath_tags_list = xpath_tags_list[: self.max_depth]
262
+ xpath_subs_list = xpath_subs_list[: self.max_depth]
263
+ xpath_tags_list += [self.pad_tag_id] * (self.max_depth - len(xpath_tags_list))
264
+ xpath_subs_list += [self.pad_width] * (self.max_depth - len(xpath_subs_list))
265
+
266
+ return xpath_tags_list, xpath_subs_list
267
+
268
+ @add_end_docstrings(ENCODE_KWARGS_DOCSTRING, MARKUPLM_ENCODE_PLUS_ADDITIONAL_KWARGS_DOCSTRING)
269
+ def __call__(
270
+ self,
271
+ text: Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]],
272
+ text_pair: Optional[Union[PreTokenizedInput, List[PreTokenizedInput]]] = None,
273
+ xpaths: Union[List[List[int]], List[List[List[int]]]] = None,
274
+ node_labels: Optional[Union[List[int], List[List[int]]]] = None,
275
+ add_special_tokens: bool = True,
276
+ padding: Union[bool, str, PaddingStrategy] = False,
277
+ truncation: Union[bool, str, TruncationStrategy] = None,
278
+ max_length: Optional[int] = None,
279
+ stride: int = 0,
280
+ pad_to_multiple_of: Optional[int] = None,
281
+ padding_side: Optional[str] = None,
282
+ return_tensors: Optional[Union[str, TensorType]] = None,
283
+ return_token_type_ids: Optional[bool] = None,
284
+ return_attention_mask: Optional[bool] = None,
285
+ return_overflowing_tokens: bool = False,
286
+ return_special_tokens_mask: bool = False,
287
+ return_offsets_mapping: bool = False,
288
+ return_length: bool = False,
289
+ verbose: bool = True,
290
+ **kwargs,
291
+ ) -> BatchEncoding:
292
+ """
293
+ Main method to tokenize and prepare for the model one or several sequence(s) or one or several pair(s) of
294
+ sequences with nodes, xpaths and optional labels.
295
+
296
+ Args:
297
+ text (`str`, `List[str]`, `List[List[str]]`):
298
+ The sequence or batch of sequences to be encoded. Each sequence can be a string, a list of strings
299
+ (words of a single example or questions of a batch of examples) or a list of list of strings (batch of
300
+ words).
301
+ text_pair (`List[str]`, `List[List[str]]`):
302
+ The sequence or batch of sequences to be encoded. Each sequence should be a list of strings
303
+ (pretokenized string).
304
+ xpaths (`List[List[int]]`, `List[List[List[int]]]`):
305
+ Node-level xpaths. Each bounding box should be normalized to be on a 0-1000 scale.
306
+ node_labels (`List[int]`, `List[List[int]]`, *optional*):
307
+ Node-level integer labels (for token classification tasks).
308
+ """
309
+
310
+ # Input type checking for clearer error
311
+ def _is_valid_text_input(t):
312
+ if isinstance(t, str):
313
+ # Strings are fine
314
+ return True
315
+ elif isinstance(t, (list, tuple)):
316
+ # List are fine as long as they are...
317
+ if len(t) == 0:
318
+ # ... empty
319
+ return True
320
+ elif isinstance(t[0], str):
321
+ # ... list of strings
322
+ return True
323
+ elif isinstance(t[0], (list, tuple)):
324
+ # ... list with an empty list or with a list of strings
325
+ return len(t[0]) == 0 or isinstance(t[0][0], str)
326
+ else:
327
+ return False
328
+ else:
329
+ return False
330
+
331
+ if text_pair is not None:
332
+ # in case text + text_pair are provided, text = questions, text_pair = nodes
333
+ if not _is_valid_text_input(text):
334
+ raise ValueError("text input must of type `str` (single example) or `List[str]` (batch of examples). ")
335
+ if not isinstance(text_pair, (list, tuple)):
336
+ raise ValueError(
337
+ "Nodes must be of type `List[str]` (single pretokenized example), "
338
+ "or `List[List[str]]` (batch of pretokenized examples)."
339
+ )
340
+ else:
341
+ # in case only text is provided => must be nodes
342
+ if not isinstance(text, (list, tuple)):
343
+ raise ValueError(
344
+ "Nodes must be of type `List[str]` (single pretokenized example), "
345
+ "or `List[List[str]]` (batch of pretokenized examples)."
346
+ )
347
+
348
+ if text_pair is not None:
349
+ is_batched = isinstance(text, (list, tuple))
350
+ else:
351
+ is_batched = isinstance(text, (list, tuple)) and text and isinstance(text[0], (list, tuple))
352
+
353
+ nodes = text if text_pair is None else text_pair
354
+ assert xpaths is not None, "You must provide corresponding xpaths"
355
+ if is_batched:
356
+ assert len(nodes) == len(xpaths), "You must provide nodes and xpaths for an equal amount of examples"
357
+ for nodes_example, xpaths_example in zip(nodes, xpaths):
358
+ assert len(nodes_example) == len(xpaths_example), "You must provide as many nodes as there are xpaths"
359
+ else:
360
+ assert len(nodes) == len(xpaths), "You must provide as many nodes as there are xpaths"
361
+
362
+ if is_batched:
363
+ if text_pair is not None and len(text) != len(text_pair):
364
+ raise ValueError(
365
+ f"batch length of `text`: {len(text)} does not match batch length of `text_pair`:"
366
+ f" {len(text_pair)}."
367
+ )
368
+ batch_text_or_text_pairs = list(zip(text, text_pair)) if text_pair is not None else text
369
+ is_pair = bool(text_pair is not None)
370
+ return self.batch_encode_plus(
371
+ batch_text_or_text_pairs=batch_text_or_text_pairs,
372
+ is_pair=is_pair,
373
+ xpaths=xpaths,
374
+ node_labels=node_labels,
375
+ add_special_tokens=add_special_tokens,
376
+ padding=padding,
377
+ truncation=truncation,
378
+ max_length=max_length,
379
+ stride=stride,
380
+ pad_to_multiple_of=pad_to_multiple_of,
381
+ padding_side=padding_side,
382
+ return_tensors=return_tensors,
383
+ return_token_type_ids=return_token_type_ids,
384
+ return_attention_mask=return_attention_mask,
385
+ return_overflowing_tokens=return_overflowing_tokens,
386
+ return_special_tokens_mask=return_special_tokens_mask,
387
+ return_offsets_mapping=return_offsets_mapping,
388
+ return_length=return_length,
389
+ verbose=verbose,
390
+ **kwargs,
391
+ )
392
+ else:
393
+ return self.encode_plus(
394
+ text=text,
395
+ text_pair=text_pair,
396
+ xpaths=xpaths,
397
+ node_labels=node_labels,
398
+ add_special_tokens=add_special_tokens,
399
+ padding=padding,
400
+ truncation=truncation,
401
+ max_length=max_length,
402
+ stride=stride,
403
+ pad_to_multiple_of=pad_to_multiple_of,
404
+ padding_side=padding_side,
405
+ return_tensors=return_tensors,
406
+ return_token_type_ids=return_token_type_ids,
407
+ return_attention_mask=return_attention_mask,
408
+ return_overflowing_tokens=return_overflowing_tokens,
409
+ return_special_tokens_mask=return_special_tokens_mask,
410
+ return_offsets_mapping=return_offsets_mapping,
411
+ return_length=return_length,
412
+ verbose=verbose,
413
+ **kwargs,
414
+ )
415
+
416
+ @add_end_docstrings(ENCODE_KWARGS_DOCSTRING, MARKUPLM_ENCODE_PLUS_ADDITIONAL_KWARGS_DOCSTRING)
417
+ def batch_encode_plus(
418
+ self,
419
+ batch_text_or_text_pairs: Union[
420
+ List[TextInput],
421
+ List[TextInputPair],
422
+ List[PreTokenizedInput],
423
+ ],
424
+ is_pair: bool = None,
425
+ xpaths: Optional[List[List[List[int]]]] = None,
426
+ node_labels: Optional[Union[List[int], List[List[int]]]] = None,
427
+ add_special_tokens: bool = True,
428
+ padding: Union[bool, str, PaddingStrategy] = False,
429
+ truncation: Union[bool, str, TruncationStrategy] = None,
430
+ max_length: Optional[int] = None,
431
+ stride: int = 0,
432
+ pad_to_multiple_of: Optional[int] = None,
433
+ padding_side: Optional[str] = None,
434
+ return_tensors: Optional[Union[str, TensorType]] = None,
435
+ return_token_type_ids: Optional[bool] = None,
436
+ return_attention_mask: Optional[bool] = None,
437
+ return_overflowing_tokens: bool = False,
438
+ return_special_tokens_mask: bool = False,
439
+ return_offsets_mapping: bool = False,
440
+ return_length: bool = False,
441
+ verbose: bool = True,
442
+ **kwargs,
443
+ ) -> BatchEncoding:
444
+ # Backward compatibility for 'truncation_strategy', 'pad_to_max_length'
445
+ padding_strategy, truncation_strategy, max_length, kwargs = self._get_padding_truncation_strategies(
446
+ padding=padding,
447
+ truncation=truncation,
448
+ max_length=max_length,
449
+ pad_to_multiple_of=pad_to_multiple_of,
450
+ verbose=verbose,
451
+ **kwargs,
452
+ )
453
+
454
+ return self._batch_encode_plus(
455
+ batch_text_or_text_pairs=batch_text_or_text_pairs,
456
+ is_pair=is_pair,
457
+ xpaths=xpaths,
458
+ node_labels=node_labels,
459
+ add_special_tokens=add_special_tokens,
460
+ padding_strategy=padding_strategy,
461
+ truncation_strategy=truncation_strategy,
462
+ max_length=max_length,
463
+ stride=stride,
464
+ pad_to_multiple_of=pad_to_multiple_of,
465
+ padding_side=padding_side,
466
+ return_tensors=return_tensors,
467
+ return_token_type_ids=return_token_type_ids,
468
+ return_attention_mask=return_attention_mask,
469
+ return_overflowing_tokens=return_overflowing_tokens,
470
+ return_special_tokens_mask=return_special_tokens_mask,
471
+ return_offsets_mapping=return_offsets_mapping,
472
+ return_length=return_length,
473
+ verbose=verbose,
474
+ **kwargs,
475
+ )
476
+
477
+ def tokenize(self, text: str, pair: Optional[str] = None, add_special_tokens: bool = False, **kwargs) -> List[str]:
478
+ batched_input = [(text, pair)] if pair else [text]
479
+ encodings = self._tokenizer.encode_batch(
480
+ batched_input, add_special_tokens=add_special_tokens, is_pretokenized=False, **kwargs
481
+ )
482
+
483
+ return encodings[0].tokens
484
+
485
+ @add_end_docstrings(ENCODE_KWARGS_DOCSTRING, MARKUPLM_ENCODE_PLUS_ADDITIONAL_KWARGS_DOCSTRING)
486
+ def encode_plus(
487
+ self,
488
+ text: Union[TextInput, PreTokenizedInput],
489
+ text_pair: Optional[PreTokenizedInput] = None,
490
+ xpaths: Optional[List[List[int]]] = None,
491
+ node_labels: Optional[List[int]] = None,
492
+ add_special_tokens: bool = True,
493
+ padding: Union[bool, str, PaddingStrategy] = False,
494
+ truncation: Union[bool, str, TruncationStrategy] = None,
495
+ max_length: Optional[int] = None,
496
+ stride: int = 0,
497
+ pad_to_multiple_of: Optional[int] = None,
498
+ padding_side: Optional[str] = None,
499
+ return_tensors: Optional[Union[str, TensorType]] = None,
500
+ return_token_type_ids: Optional[bool] = None,
501
+ return_attention_mask: Optional[bool] = None,
502
+ return_overflowing_tokens: bool = False,
503
+ return_special_tokens_mask: bool = False,
504
+ return_offsets_mapping: bool = False,
505
+ return_length: bool = False,
506
+ verbose: bool = True,
507
+ **kwargs,
508
+ ) -> BatchEncoding:
509
+ """
510
+ Tokenize and prepare for the model a sequence or a pair of sequences. .. warning:: This method is deprecated,
511
+ `__call__` should be used instead.
512
+
513
+ Args:
514
+ text (`str`, `List[str]`, `List[List[str]]`):
515
+ The first sequence to be encoded. This can be a string, a list of strings or a list of list of strings.
516
+ text_pair (`List[str]` or `List[int]`, *optional*):
517
+ Optional second sequence to be encoded. This can be a list of strings (words of a single example) or a
518
+ list of list of strings (words of a batch of examples).
519
+ """
520
+
521
+ # Backward compatibility for 'truncation_strategy', 'pad_to_max_length'
522
+ padding_strategy, truncation_strategy, max_length, kwargs = self._get_padding_truncation_strategies(
523
+ padding=padding,
524
+ truncation=truncation,
525
+ max_length=max_length,
526
+ pad_to_multiple_of=pad_to_multiple_of,
527
+ verbose=verbose,
528
+ **kwargs,
529
+ )
530
+
531
+ return self._encode_plus(
532
+ text=text,
533
+ xpaths=xpaths,
534
+ text_pair=text_pair,
535
+ node_labels=node_labels,
536
+ add_special_tokens=add_special_tokens,
537
+ padding_strategy=padding_strategy,
538
+ truncation_strategy=truncation_strategy,
539
+ max_length=max_length,
540
+ stride=stride,
541
+ pad_to_multiple_of=pad_to_multiple_of,
542
+ padding_side=padding_side,
543
+ return_tensors=return_tensors,
544
+ return_token_type_ids=return_token_type_ids,
545
+ return_attention_mask=return_attention_mask,
546
+ return_overflowing_tokens=return_overflowing_tokens,
547
+ return_special_tokens_mask=return_special_tokens_mask,
548
+ return_offsets_mapping=return_offsets_mapping,
549
+ return_length=return_length,
550
+ verbose=verbose,
551
+ **kwargs,
552
+ )
553
+
554
+ def _batch_encode_plus(
555
+ self,
556
+ batch_text_or_text_pairs: Union[
557
+ List[TextInput],
558
+ List[TextInputPair],
559
+ List[PreTokenizedInput],
560
+ ],
561
+ is_pair: bool = None,
562
+ xpaths: Optional[List[List[List[int]]]] = None,
563
+ node_labels: Optional[List[List[int]]] = None,
564
+ add_special_tokens: bool = True,
565
+ padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD,
566
+ truncation_strategy: TruncationStrategy = TruncationStrategy.DO_NOT_TRUNCATE,
567
+ max_length: Optional[int] = None,
568
+ stride: int = 0,
569
+ pad_to_multiple_of: Optional[int] = None,
570
+ padding_side: Optional[str] = None,
571
+ return_tensors: Optional[str] = None,
572
+ return_token_type_ids: Optional[bool] = None,
573
+ return_attention_mask: Optional[bool] = None,
574
+ return_overflowing_tokens: bool = False,
575
+ return_special_tokens_mask: bool = False,
576
+ return_offsets_mapping: bool = False,
577
+ return_length: bool = False,
578
+ verbose: bool = True,
579
+ ) -> BatchEncoding:
580
+ if not isinstance(batch_text_or_text_pairs, list):
581
+ raise TypeError(f"batch_text_or_text_pairs has to be a list (got {type(batch_text_or_text_pairs)})")
582
+
583
+ # Set the truncation and padding strategy and restore the initial configuration
584
+ self.set_truncation_and_padding(
585
+ padding_strategy=padding_strategy,
586
+ truncation_strategy=truncation_strategy,
587
+ max_length=max_length,
588
+ stride=stride,
589
+ pad_to_multiple_of=pad_to_multiple_of,
590
+ padding_side=padding_side,
591
+ )
592
+
593
+ if is_pair:
594
+ batch_text_or_text_pairs = [([text], text_pair) for text, text_pair in batch_text_or_text_pairs]
595
+
596
+ encodings = self._tokenizer.encode_batch(
597
+ batch_text_or_text_pairs,
598
+ add_special_tokens=add_special_tokens,
599
+ is_pretokenized=True, # we set this to True as MarkupLM always expects pretokenized inputs
600
+ )
601
+
602
+ # Convert encoding to dict
603
+ # `Tokens` is a tuple of (List[Dict[str, List[List[int]]]] or List[Dict[str, 2D-Tensor]],
604
+ # List[EncodingFast]) with nested dimensions corresponding to batch, overflows, sequence length
605
+ tokens_and_encodings = [
606
+ self._convert_encoding(
607
+ encoding=encoding,
608
+ return_token_type_ids=return_token_type_ids,
609
+ return_attention_mask=return_attention_mask,
610
+ return_overflowing_tokens=return_overflowing_tokens,
611
+ return_special_tokens_mask=return_special_tokens_mask,
612
+ return_offsets_mapping=True
613
+ if node_labels is not None
614
+ else return_offsets_mapping, # we use offsets to create the labels
615
+ return_length=return_length,
616
+ verbose=verbose,
617
+ )
618
+ for encoding in encodings
619
+ ]
620
+
621
+ # Convert the output to have dict[list] from list[dict] and remove the additional overflows dimension
622
+ # From (variable) shape (batch, overflows, sequence length) to ~ (batch * overflows, sequence length)
623
+ # (we say ~ because the number of overflow varies with the example in the batch)
624
+ #
625
+ # To match each overflowing sample with the original sample in the batch
626
+ # we add an overflow_to_sample_mapping array (see below)
627
+ sanitized_tokens = {}
628
+ for key in tokens_and_encodings[0][0].keys():
629
+ stack = [e for item, _ in tokens_and_encodings for e in item[key]]
630
+ sanitized_tokens[key] = stack
631
+ sanitized_encodings = [e for _, item in tokens_and_encodings for e in item]
632
+
633
+ # If returning overflowing tokens, we need to return a mapping
634
+ # from the batch idx to the original sample
635
+ if return_overflowing_tokens:
636
+ overflow_to_sample_mapping = []
637
+ for i, (toks, _) in enumerate(tokens_and_encodings):
638
+ overflow_to_sample_mapping += [i] * len(toks["input_ids"])
639
+ sanitized_tokens["overflow_to_sample_mapping"] = overflow_to_sample_mapping
640
+
641
+ for input_ids in sanitized_tokens["input_ids"]:
642
+ self._eventual_warn_about_too_long_sequence(input_ids, max_length, verbose)
643
+
644
+ # create the token-level xpaths tags and subscripts
645
+ xpath_tags_seq = []
646
+ xpath_subs_seq = []
647
+ for batch_index in range(len(sanitized_tokens["input_ids"])):
648
+ if return_overflowing_tokens:
649
+ original_index = sanitized_tokens["overflow_to_sample_mapping"][batch_index]
650
+ else:
651
+ original_index = batch_index
652
+ xpath_tags_seq_example = []
653
+ xpath_subs_seq_example = []
654
+ for id, sequence_id, word_id in zip(
655
+ sanitized_tokens["input_ids"][batch_index],
656
+ sanitized_encodings[batch_index].sequence_ids,
657
+ sanitized_encodings[batch_index].word_ids,
658
+ ):
659
+ if word_id is not None:
660
+ if is_pair and sequence_id == 0:
661
+ xpath_tags_seq_example.append(self.pad_xpath_tags_seq)
662
+ xpath_subs_seq_example.append(self.pad_xpath_subs_seq)
663
+ else:
664
+ xpath_tags_list, xpath_subs_list = self.get_xpath_seq(xpaths[original_index][word_id])
665
+ xpath_tags_seq_example.extend([xpath_tags_list])
666
+ xpath_subs_seq_example.extend([xpath_subs_list])
667
+ else:
668
+ if id in [self.cls_token_id, self.sep_token_id, self.pad_token_id]:
669
+ xpath_tags_seq_example.append(self.pad_xpath_tags_seq)
670
+ xpath_subs_seq_example.append(self.pad_xpath_subs_seq)
671
+ else:
672
+ raise ValueError("Id not recognized")
673
+ xpath_tags_seq.append(xpath_tags_seq_example)
674
+ xpath_subs_seq.append(xpath_subs_seq_example)
675
+
676
+ sanitized_tokens["xpath_tags_seq"] = xpath_tags_seq
677
+ sanitized_tokens["xpath_subs_seq"] = xpath_subs_seq
678
+
679
+ # optionally, create the labels
680
+ if node_labels is not None:
681
+ labels = []
682
+ for batch_index in range(len(sanitized_tokens["input_ids"])):
683
+ if return_overflowing_tokens:
684
+ original_index = sanitized_tokens["overflow_to_sample_mapping"][batch_index]
685
+ else:
686
+ original_index = batch_index
687
+ labels_example = []
688
+ for id, offset, word_id in zip(
689
+ sanitized_tokens["input_ids"][batch_index],
690
+ sanitized_tokens["offset_mapping"][batch_index],
691
+ sanitized_encodings[batch_index].word_ids,
692
+ ):
693
+ if word_id is not None:
694
+ if self.only_label_first_subword:
695
+ if offset[0] == 0:
696
+ # Use the real label id for the first token of the word, and padding ids for the remaining tokens
697
+ labels_example.append(node_labels[original_index][word_id])
698
+ else:
699
+ labels_example.append(self.pad_token_label)
700
+ else:
701
+ labels_example.append(node_labels[original_index][word_id])
702
+ else:
703
+ labels_example.append(self.pad_token_label)
704
+ labels.append(labels_example)
705
+
706
+ sanitized_tokens["labels"] = labels
707
+ # finally, remove offsets if the user didn't want them
708
+ if not return_offsets_mapping:
709
+ del sanitized_tokens["offset_mapping"]
710
+
711
+ return BatchEncoding(sanitized_tokens, sanitized_encodings, tensor_type=return_tensors)
712
+
713
+ def _encode_plus(
714
+ self,
715
+ text: Union[TextInput, PreTokenizedInput],
716
+ text_pair: Optional[PreTokenizedInput] = None,
717
+ xpaths: Optional[List[List[int]]] = None,
718
+ node_labels: Optional[List[int]] = None,
719
+ add_special_tokens: bool = True,
720
+ padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD,
721
+ truncation_strategy: TruncationStrategy = TruncationStrategy.DO_NOT_TRUNCATE,
722
+ max_length: Optional[int] = None,
723
+ stride: int = 0,
724
+ pad_to_multiple_of: Optional[int] = None,
725
+ padding_side: Optional[str] = None,
726
+ return_tensors: Optional[bool] = None,
727
+ return_token_type_ids: Optional[bool] = None,
728
+ return_attention_mask: Optional[bool] = None,
729
+ return_overflowing_tokens: bool = False,
730
+ return_special_tokens_mask: bool = False,
731
+ return_offsets_mapping: bool = False,
732
+ return_length: bool = False,
733
+ verbose: bool = True,
734
+ **kwargs,
735
+ ) -> BatchEncoding:
736
+ # make it a batched input
737
+ # 2 options:
738
+ # 1) only text, in case text must be a list of str
739
+ # 2) text + text_pair, in which case text = str and text_pair a list of str
740
+ batched_input = [(text, text_pair)] if text_pair else [text]
741
+ batched_xpaths = [xpaths]
742
+ batched_node_labels = [node_labels] if node_labels is not None else None
743
+ batched_output = self._batch_encode_plus(
744
+ batched_input,
745
+ is_pair=bool(text_pair is not None),
746
+ xpaths=batched_xpaths,
747
+ node_labels=batched_node_labels,
748
+ add_special_tokens=add_special_tokens,
749
+ padding_strategy=padding_strategy,
750
+ truncation_strategy=truncation_strategy,
751
+ max_length=max_length,
752
+ stride=stride,
753
+ pad_to_multiple_of=pad_to_multiple_of,
754
+ padding_side=padding_side,
755
+ return_tensors=return_tensors,
756
+ return_token_type_ids=return_token_type_ids,
757
+ return_attention_mask=return_attention_mask,
758
+ return_overflowing_tokens=return_overflowing_tokens,
759
+ return_special_tokens_mask=return_special_tokens_mask,
760
+ return_offsets_mapping=return_offsets_mapping,
761
+ return_length=return_length,
762
+ verbose=verbose,
763
+ **kwargs,
764
+ )
765
+
766
+ # Return tensor is None, then we can remove the leading batch axis
767
+ # Overflowing tokens are returned as a batch of output so we keep them in this case
768
+ if return_tensors is None and not return_overflowing_tokens:
769
+ batched_output = BatchEncoding(
770
+ {
771
+ key: value[0] if len(value) > 0 and isinstance(value[0], list) else value
772
+ for key, value in batched_output.items()
773
+ },
774
+ batched_output.encodings,
775
+ )
776
+
777
+ self._eventual_warn_about_too_long_sequence(batched_output["input_ids"], max_length, verbose)
778
+
779
+ return batched_output
780
+
781
+ def _pad(
782
+ self,
783
+ encoded_inputs: Union[Dict[str, EncodedInput], BatchEncoding],
784
+ max_length: Optional[int] = None,
785
+ padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD,
786
+ pad_to_multiple_of: Optional[int] = None,
787
+ padding_side: Optional[str] = None,
788
+ return_attention_mask: Optional[bool] = None,
789
+ ) -> dict:
790
+ """
791
+ Args:
792
+ Pad encoded inputs (on left/right and up to predefined length or max length in the batch)
793
+ encoded_inputs:
794
+ Dictionary of tokenized inputs (`List[int]`) or batch of tokenized inputs (`List[List[int]]`).
795
+ max_length: maximum length of the returned list and optionally padding length (see below).
796
+ Will truncate by taking into account the special tokens.
797
+ padding_strategy: PaddingStrategy to use for padding.
798
+ - PaddingStrategy.LONGEST Pad to the longest sequence in the batch
799
+ - PaddingStrategy.MAX_LENGTH: Pad to the max length (default)
800
+ - PaddingStrategy.DO_NOT_PAD: Do not pad
801
+ The tokenizer padding sides are defined in self.padding_side:
802
+ - 'left': pads on the left of the sequences
803
+ - 'right': pads on the right of the sequences
804
+ pad_to_multiple_of: (optional) Integer if set will pad the sequence to a multiple of the provided value.
805
+ This is especially useful to enable the use of Tensor Core on NVIDIA hardware with compute capability
806
+ `>= 7.5` (Volta).
807
+ padding_side:
808
+ The side on which the model should have padding applied. Should be selected between ['right', 'left'].
809
+ Default value is picked from the class attribute of the same name.
810
+ return_attention_mask:
811
+ (optional) Set to False to avoid returning attention mask (default: set to model specifics)
812
+ """
813
+ # Load from model defaults
814
+ if return_attention_mask is None:
815
+ return_attention_mask = "attention_mask" in self.model_input_names
816
+
817
+ required_input = encoded_inputs[self.model_input_names[0]]
818
+
819
+ if padding_strategy == PaddingStrategy.LONGEST:
820
+ max_length = len(required_input)
821
+
822
+ if max_length is not None and pad_to_multiple_of is not None and (max_length % pad_to_multiple_of != 0):
823
+ max_length = ((max_length // pad_to_multiple_of) + 1) * pad_to_multiple_of
824
+
825
+ needs_to_be_padded = padding_strategy != PaddingStrategy.DO_NOT_PAD and len(required_input) != max_length
826
+
827
+ # Initialize attention mask if not present.
828
+ if return_attention_mask and "attention_mask" not in encoded_inputs:
829
+ encoded_inputs["attention_mask"] = [1] * len(required_input)
830
+
831
+ if needs_to_be_padded:
832
+ difference = max_length - len(required_input)
833
+ padding_side = padding_side if padding_side is not None else self.padding_side
834
+ if padding_side == "right":
835
+ if return_attention_mask:
836
+ encoded_inputs["attention_mask"] = encoded_inputs["attention_mask"] + [0] * difference
837
+ if "token_type_ids" in encoded_inputs:
838
+ encoded_inputs["token_type_ids"] = (
839
+ encoded_inputs["token_type_ids"] + [self.pad_token_type_id] * difference
840
+ )
841
+ if "xpath_tags_seq" in encoded_inputs:
842
+ encoded_inputs["xpath_tags_seq"] = (
843
+ encoded_inputs["xpath_tags_seq"] + [self.pad_xpath_tags_seq] * difference
844
+ )
845
+ if "xpath_subs_seq" in encoded_inputs:
846
+ encoded_inputs["xpath_subs_seq"] = (
847
+ encoded_inputs["xpath_subs_seq"] + [self.pad_xpath_subs_seq] * difference
848
+ )
849
+ if "labels" in encoded_inputs:
850
+ encoded_inputs["labels"] = encoded_inputs["labels"] + [self.pad_token_label] * difference
851
+ if "special_tokens_mask" in encoded_inputs:
852
+ encoded_inputs["special_tokens_mask"] = encoded_inputs["special_tokens_mask"] + [1] * difference
853
+ encoded_inputs[self.model_input_names[0]] = required_input + [self.pad_token_id] * difference
854
+ elif padding_side == "left":
855
+ if return_attention_mask:
856
+ encoded_inputs["attention_mask"] = [0] * difference + encoded_inputs["attention_mask"]
857
+ if "token_type_ids" in encoded_inputs:
858
+ encoded_inputs["token_type_ids"] = [self.pad_token_type_id] * difference + encoded_inputs[
859
+ "token_type_ids"
860
+ ]
861
+ if "xpath_tags_seq" in encoded_inputs:
862
+ encoded_inputs["xpath_tags_seq"] = [self.pad_xpath_tags_seq] * difference + encoded_inputs[
863
+ "xpath_tags_seq"
864
+ ]
865
+ if "xpath_subs_seq" in encoded_inputs:
866
+ encoded_inputs["xpath_subs_seq"] = [self.pad_xpath_subs_seq] * difference + encoded_inputs[
867
+ "xpath_subs_seq"
868
+ ]
869
+ if "labels" in encoded_inputs:
870
+ encoded_inputs["labels"] = [self.pad_token_label] * difference + encoded_inputs["labels"]
871
+ if "special_tokens_mask" in encoded_inputs:
872
+ encoded_inputs["special_tokens_mask"] = [1] * difference + encoded_inputs["special_tokens_mask"]
873
+ encoded_inputs[self.model_input_names[0]] = [self.pad_token_id] * difference + required_input
874
+ else:
875
+ raise ValueError("Invalid padding strategy:" + str(padding_side))
876
+
877
+ return encoded_inputs
878
+
879
+ def build_inputs_with_special_tokens(
880
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
881
+ ) -> List[int]:
882
+ """
883
+ Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
884
+ adding special tokens. A RoBERTa sequence has the following format:
885
+ - single sequence: `<s> X </s>`
886
+ - pair of sequences: `<s> A </s></s> B </s>`
887
+
888
+ Args:
889
+ token_ids_0 (`List[int]`):
890
+ List of IDs to which the special tokens will be added.
891
+ token_ids_1 (`List[int]`, *optional*):
892
+ Optional second list of IDs for sequence pairs.
893
+ Returns:
894
+ `List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
895
+ """
896
+ if token_ids_1 is None:
897
+ return [self.cls_token_id] + token_ids_0 + [self.sep_token_id]
898
+ cls = [self.cls_token_id]
899
+ sep = [self.sep_token_id]
900
+ return cls + token_ids_0 + sep + token_ids_1 + sep
901
+
902
+ def create_token_type_ids_from_sequences(
903
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
904
+ ) -> List[int]:
905
+ """
906
+ Create a mask from the two sequences passed to be used in a sequence-pair classification task. RoBERTa does not
907
+ make use of token type ids, therefore a list of zeros is returned.
908
+
909
+ Args:
910
+ token_ids_0 (`List[int]`):
911
+ List of IDs.
912
+ token_ids_1 (`List[int]`, *optional*):
913
+ Optional second list of IDs for sequence pairs.
914
+ Returns:
915
+ `List[int]`: List of zeros.
916
+ """
917
+ sep = [self.sep_token_id]
918
+ cls = [self.cls_token_id]
919
+
920
+ if token_ids_1 is None:
921
+ return len(cls + token_ids_0 + sep) * [0]
922
+ return len(cls + token_ids_0 + sep + token_ids_1 + sep) * [0]
923
+
924
+ def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
925
+ files = self._tokenizer.model.save(save_directory, name=filename_prefix)
926
+ return tuple(files)
927
+
928
+
929
+ __all__ = ["MarkupLMTokenizerFast"]
tasks/tasksmith-441eeab80047/environment/source/src/transformers/models/mask2former/__init__.py ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 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 _LazyModule
17
+ from ...utils.import_utils import define_import_structure
18
+
19
+
20
+ if TYPE_CHECKING:
21
+ from .configuration_mask2former import *
22
+ from .image_processing_mask2former import *
23
+ from .modeling_mask2former import *
24
+ else:
25
+ import sys
26
+
27
+ _file = globals()["__file__"]
28
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
tasks/tasksmith-441eeab80047/environment/source/src/transformers/models/mask2former/configuration_mask2former.py ADDED
@@ -0,0 +1,256 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 Meta Platforms, Inc.and The HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """Mask2Former model configuration"""
16
+
17
+ from typing import Dict, List, Optional
18
+
19
+ from ...configuration_utils import PretrainedConfig
20
+ from ...utils import logging
21
+ from ...utils.backbone_utils import verify_backbone_config_arguments
22
+ from ..auto import CONFIG_MAPPING
23
+
24
+
25
+ logger = logging.get_logger(__name__)
26
+
27
+
28
+ class Mask2FormerConfig(PretrainedConfig):
29
+ r"""
30
+ This is the configuration class to store the configuration of a [`Mask2FormerModel`]. It is used to instantiate a
31
+ Mask2Former model according to the specified arguments, defining the model architecture. Instantiating a
32
+ configuration with the defaults will yield a similar configuration to that of the Mask2Former
33
+ [facebook/mask2former-swin-small-coco-instance](https://huggingface.co/facebook/mask2former-swin-small-coco-instance)
34
+ architecture.
35
+
36
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
37
+ documentation from [`PretrainedConfig`] for more information.
38
+
39
+ Currently, Mask2Former only supports the [Swin Transformer](swin) as backbone.
40
+
41
+ Args:
42
+ backbone_config (`PretrainedConfig` or `dict`, *optional*, defaults to `SwinConfig()`):
43
+ The configuration of the backbone model. If unset, the configuration corresponding to
44
+ `swin-base-patch4-window12-384` will be used.
45
+ backbone (`str`, *optional*):
46
+ Name of backbone to use when `backbone_config` is `None`. If `use_pretrained_backbone` is `True`, this
47
+ will load the corresponding pretrained weights from the timm or transformers library. If `use_pretrained_backbone`
48
+ is `False`, this loads the backbone's config and uses that to initialize the backbone with random weights.
49
+ use_pretrained_backbone (`bool`, *optional*, `False`):
50
+ Whether to use pretrained weights for the backbone.
51
+ use_timm_backbone (`bool`, *optional*, `False`):
52
+ Whether to load `backbone` from the timm library. If `False`, the backbone is loaded from the transformers
53
+ library.
54
+ backbone_kwargs (`dict`, *optional*):
55
+ Keyword arguments to be passed to AutoBackbone when loading from a checkpoint
56
+ e.g. `{'out_indices': (0, 1, 2, 3)}`. Cannot be specified if `backbone_config` is set.
57
+ feature_size (`int`, *optional*, defaults to 256):
58
+ The features (channels) of the resulting feature maps.
59
+ mask_feature_size (`int`, *optional*, defaults to 256):
60
+ The masks' features size, this value will also be used to specify the Feature Pyramid Network features'
61
+ size.
62
+ hidden_dim (`int`, *optional*, defaults to 256):
63
+ Dimensionality of the encoder layers.
64
+ encoder_feedforward_dim (`int`, *optional*, defaults to 1024):
65
+ Dimension of feedforward network for deformable detr encoder used as part of pixel decoder.
66
+ encoder_layers (`int`, *optional*, defaults to 6):
67
+ Number of layers in the deformable detr encoder used as part of pixel decoder.
68
+ decoder_layers (`int`, *optional*, defaults to 10):
69
+ Number of layers in the Transformer decoder.
70
+ num_attention_heads (`int`, *optional*, defaults to 8):
71
+ Number of attention heads for each attention layer.
72
+ dropout (`float`, *optional*, defaults to 0.1):
73
+ The dropout probability for all fully connected layers in the embeddings, encoder.
74
+ dim_feedforward (`int`, *optional*, defaults to 2048):
75
+ Feature dimension in feedforward network for transformer decoder.
76
+ pre_norm (`bool`, *optional*, defaults to `False`):
77
+ Whether to use pre-LayerNorm or not for transformer decoder.
78
+ enforce_input_projection (`bool`, *optional*, defaults to `False`):
79
+ Whether to add an input projection 1x1 convolution even if the input channels and hidden dim are identical
80
+ in the Transformer decoder.
81
+ common_stride (`int`, *optional*, defaults to 4):
82
+ Parameter used for determining number of FPN levels used as part of pixel decoder.
83
+ ignore_value (`int`, *optional*, defaults to 255):
84
+ Category id to be ignored during training.
85
+ num_queries (`int`, *optional*, defaults to 100):
86
+ Number of queries for the decoder.
87
+ no_object_weight (`int`, *optional*, defaults to 0.1):
88
+ The weight to apply to the null (no object) class.
89
+ class_weight (`int`, *optional*, defaults to 2.0):
90
+ The weight for the cross entropy loss.
91
+ mask_weight (`int`, *optional*, defaults to 5.0):
92
+ The weight for the mask loss.
93
+ dice_weight (`int`, *optional*, defaults to 5.0):
94
+ The weight for the dice loss.
95
+ train_num_points (`str` or `function`, *optional*, defaults to 12544):
96
+ Number of points used for sampling during loss calculation.
97
+ oversample_ratio (`float`, *optional*, defaults to 3.0):
98
+ Oversampling parameter used for calculating no. of sampled points
99
+ importance_sample_ratio (`float`, *optional*, defaults to 0.75):
100
+ Ratio of points that are sampled via importance sampling.
101
+ init_std (`float`, *optional*, defaults to 0.02):
102
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
103
+ init_xavier_std (`float`, *optional*, defaults to 1.0):
104
+ The scaling factor used for the Xavier initialization gain in the HM Attention map module.
105
+ use_auxiliary_loss (`boolean``, *optional*, defaults to `True`):
106
+ If `True` [`Mask2FormerForUniversalSegmentationOutput`] will contain the auxiliary losses computed using
107
+ the logits from each decoder's stage.
108
+ feature_strides (`List[int]`, *optional*, defaults to `[4, 8, 16, 32]`):
109
+ Feature strides corresponding to features generated from backbone network.
110
+ output_auxiliary_logits (`bool`, *optional*):
111
+ Should the model output its `auxiliary_logits` or not.
112
+
113
+ Examples:
114
+
115
+ ```python
116
+ >>> from transformers import Mask2FormerConfig, Mask2FormerModel
117
+
118
+ >>> # Initializing a Mask2Former facebook/mask2former-swin-small-coco-instance configuration
119
+ >>> configuration = Mask2FormerConfig()
120
+
121
+ >>> # Initializing a model (with random weights) from the facebook/mask2former-swin-small-coco-instance style configuration
122
+ >>> model = Mask2FormerModel(configuration)
123
+
124
+ >>> # Accessing the model configuration
125
+ >>> configuration = model.config
126
+ ```
127
+
128
+ """
129
+
130
+ model_type = "mask2former"
131
+ backbones_supported = ["swin"]
132
+ attribute_map = {"hidden_size": "hidden_dim"}
133
+
134
+ def __init__(
135
+ self,
136
+ backbone_config: Optional[Dict] = None,
137
+ feature_size: int = 256,
138
+ mask_feature_size: int = 256,
139
+ hidden_dim: int = 256,
140
+ encoder_feedforward_dim: int = 1024,
141
+ activation_function: str = "relu",
142
+ encoder_layers: int = 6,
143
+ decoder_layers: int = 10,
144
+ num_attention_heads: int = 8,
145
+ dropout: float = 0.0,
146
+ dim_feedforward: int = 2048,
147
+ pre_norm: bool = False,
148
+ enforce_input_projection: bool = False,
149
+ common_stride: int = 4,
150
+ ignore_value: int = 255,
151
+ num_queries: int = 100,
152
+ no_object_weight: float = 0.1,
153
+ class_weight: float = 2.0,
154
+ mask_weight: float = 5.0,
155
+ dice_weight: float = 5.0,
156
+ train_num_points: int = 12544,
157
+ oversample_ratio: float = 3.0,
158
+ importance_sample_ratio: float = 0.75,
159
+ init_std: float = 0.02,
160
+ init_xavier_std: float = 1.0,
161
+ use_auxiliary_loss: bool = True,
162
+ feature_strides: List[int] = [4, 8, 16, 32],
163
+ output_auxiliary_logits: bool = None,
164
+ backbone: Optional[str] = None,
165
+ use_pretrained_backbone: bool = False,
166
+ use_timm_backbone: bool = False,
167
+ backbone_kwargs: Optional[Dict] = None,
168
+ **kwargs,
169
+ ):
170
+ if backbone_config is None and backbone is None:
171
+ logger.info("`backbone_config` is `None`. Initializing the config with the default `Swin` backbone.")
172
+ backbone_config = CONFIG_MAPPING["swin"](
173
+ image_size=224,
174
+ num_channels=3,
175
+ patch_size=4,
176
+ embed_dim=96,
177
+ depths=[2, 2, 18, 2],
178
+ num_heads=[3, 6, 12, 24],
179
+ window_size=7,
180
+ drop_path_rate=0.3,
181
+ use_absolute_embeddings=False,
182
+ out_features=["stage1", "stage2", "stage3", "stage4"],
183
+ )
184
+ elif isinstance(backbone_config, dict):
185
+ backbone_model_type = backbone_config.pop("model_type")
186
+ config_class = CONFIG_MAPPING[backbone_model_type]
187
+ backbone_config = config_class.from_dict(backbone_config)
188
+
189
+ verify_backbone_config_arguments(
190
+ use_timm_backbone=use_timm_backbone,
191
+ use_pretrained_backbone=use_pretrained_backbone,
192
+ backbone=backbone,
193
+ backbone_config=backbone_config,
194
+ backbone_kwargs=backbone_kwargs,
195
+ )
196
+ # verify that the backbone is supported
197
+ if backbone_config is not None and backbone_config.model_type not in self.backbones_supported:
198
+ logger.warning_once(
199
+ f"Backbone {backbone_config.model_type} is not a supported model and may not be compatible with Mask2Former. "
200
+ f"Supported model types: {','.join(self.backbones_supported)}"
201
+ )
202
+
203
+ self.backbone_config = backbone_config
204
+ self.feature_size = feature_size
205
+ self.mask_feature_size = mask_feature_size
206
+ self.hidden_dim = hidden_dim
207
+ self.encoder_feedforward_dim = encoder_feedforward_dim
208
+ self.activation_function = activation_function
209
+ self.encoder_layers = encoder_layers
210
+ self.decoder_layers = decoder_layers
211
+ self.num_attention_heads = num_attention_heads
212
+ self.dropout = dropout
213
+ self.dim_feedforward = dim_feedforward
214
+ self.pre_norm = pre_norm
215
+ self.enforce_input_projection = enforce_input_projection
216
+ self.common_stride = common_stride
217
+ self.ignore_value = ignore_value
218
+ self.num_queries = num_queries
219
+ self.no_object_weight = no_object_weight
220
+ self.class_weight = class_weight
221
+ self.mask_weight = mask_weight
222
+ self.dice_weight = dice_weight
223
+ self.train_num_points = train_num_points
224
+ self.oversample_ratio = oversample_ratio
225
+ self.importance_sample_ratio = importance_sample_ratio
226
+ self.init_std = init_std
227
+ self.init_xavier_std = init_xavier_std
228
+ self.use_auxiliary_loss = use_auxiliary_loss
229
+ self.feature_strides = feature_strides
230
+ self.output_auxiliary_logits = output_auxiliary_logits
231
+ self.num_hidden_layers = decoder_layers
232
+ self.backbone = backbone
233
+ self.use_pretrained_backbone = use_pretrained_backbone
234
+ self.use_timm_backbone = use_timm_backbone
235
+ self.backbone_kwargs = backbone_kwargs
236
+
237
+ super().__init__(**kwargs)
238
+
239
+ @classmethod
240
+ def from_backbone_config(cls, backbone_config: PretrainedConfig, **kwargs):
241
+ """Instantiate a [`Mask2FormerConfig`] (or a derived class) from a pre-trained backbone model configuration.
242
+
243
+ Args:
244
+ backbone_config ([`PretrainedConfig`]):
245
+ The backbone configuration.
246
+
247
+ Returns:
248
+ [`Mask2FormerConfig`]: An instance of a configuration object
249
+ """
250
+ return cls(
251
+ backbone_config=backbone_config,
252
+ **kwargs,
253
+ )
254
+
255
+
256
+ __all__ = ["Mask2FormerConfig"]
tasks/tasksmith-441eeab80047/environment/source/src/transformers/models/mask2former/convert_mask2former_original_pytorch_checkpoint_to_pytorch.py ADDED
@@ -0,0 +1,1019 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 Meta Platforms, Inc. and The HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ import json
16
+ import sys
17
+ from argparse import ArgumentParser
18
+ from dataclasses import dataclass
19
+ from pathlib import Path
20
+ from pprint import pformat
21
+ from typing import Any, Dict, Iterator, List, Set, Tuple
22
+
23
+ import requests
24
+ import torch
25
+ import torchvision.transforms as T
26
+ from detectron2.checkpoint import DetectionCheckpointer
27
+ from detectron2.config import get_cfg
28
+ from detectron2.projects.deeplab import add_deeplab_config
29
+ from huggingface_hub import hf_hub_download
30
+ from PIL import Image
31
+ from torch import Tensor, nn
32
+
33
+ from transformers import (
34
+ Mask2FormerConfig,
35
+ Mask2FormerForUniversalSegmentation,
36
+ Mask2FormerImageProcessor,
37
+ Mask2FormerModel,
38
+ SwinConfig,
39
+ )
40
+ from transformers.models.mask2former.modeling_mask2former import (
41
+ Mask2FormerForUniversalSegmentationOutput,
42
+ Mask2FormerModelOutput,
43
+ )
44
+ from transformers.utils import logging
45
+
46
+
47
+ StateDict = Dict[str, Tensor]
48
+
49
+ logging.set_verbosity_info()
50
+ logger = logging.get_logger()
51
+
52
+ torch.manual_seed(0)
53
+
54
+
55
+ class TrackedStateDict:
56
+ def __init__(self, to_track: Dict):
57
+ """This class "tracks" a python dictionary by keeping track of which item is accessed.
58
+
59
+ Args:
60
+ to_track (Dict): The dictionary we wish to track
61
+ """
62
+ self.to_track = to_track
63
+ self._seen: Set[str] = set()
64
+
65
+ def __getitem__(self, key: str) -> Any:
66
+ return self.to_track[key]
67
+
68
+ def __setitem__(self, key: str, item: Any):
69
+ self._seen.add(key)
70
+ self.to_track[key] = item
71
+
72
+ def diff(self) -> List[str]:
73
+ """This method returns a set difference between the keys in the tracked state dict and the one we have access so far.
74
+ This is an effective method to check if we have update all the keys
75
+
76
+ Returns:
77
+ List[str]: List of keys not yet updated
78
+ """
79
+ return set(self.to_track.keys()) - self._seen
80
+
81
+ def copy(self) -> Dict:
82
+ # proxy the call to the internal dictionary
83
+ return self.to_track.copy()
84
+
85
+
86
+ # We will verify our results on an image of cute cats
87
+ def prepare_img():
88
+ url = "http://images.cocodataset.org/val2017/000000039769.jpg"
89
+ img_data = requests.get(url, stream=True).raw
90
+ im = Image.open(img_data)
91
+ return im
92
+
93
+
94
+ @dataclass
95
+ class Args:
96
+ """Fake command line arguments needed by mask2former/detectron implementation"""
97
+
98
+ config_file: str
99
+
100
+
101
+ def setup_cfg(args: Args):
102
+ # load config from file and command-line arguments
103
+ cfg = get_cfg()
104
+ add_deeplab_config(cfg)
105
+ add_maskformer2_config(cfg)
106
+ cfg.merge_from_file(args.config_file)
107
+ cfg.freeze()
108
+ return cfg
109
+
110
+
111
+ class OriginalMask2FormerConfigToOursConverter:
112
+ def __call__(self, original_config: object) -> Mask2FormerConfig:
113
+ model = original_config.MODEL
114
+
115
+ repo_id = "huggingface/label-files"
116
+ if model.SEM_SEG_HEAD.NUM_CLASSES == 847:
117
+ filename = "mask2former-ade20k-full-id2label.json"
118
+ elif model.SEM_SEG_HEAD.NUM_CLASSES == 150:
119
+ filename = "ade20k-id2label.json"
120
+ elif model.SEM_SEG_HEAD.NUM_CLASSES == 80:
121
+ filename = "coco-detection-mmdet-id2label.json"
122
+ elif model.SEM_SEG_HEAD.NUM_CLASSES == 171:
123
+ filename = "mask2former-coco-stuff-id2label.json"
124
+ elif model.SEM_SEG_HEAD.NUM_CLASSES == 133:
125
+ filename = "coco-panoptic-id2label.json"
126
+ elif model.SEM_SEG_HEAD.NUM_CLASSES == 19:
127
+ filename = "cityscapes-id2label.json"
128
+ elif model.SEM_SEG_HEAD.NUM_CLASSES == 8:
129
+ filename = "cityscapes-instance-id2label.json"
130
+ elif model.SEM_SEG_HEAD.NUM_CLASSES == 65:
131
+ filename = "mapillary-vistas-id2label.json"
132
+
133
+ id2label = json.load(open(hf_hub_download(repo_id, filename, repo_type="dataset"), "r"))
134
+ id2label = {int(k): v for k, v in id2label.items()}
135
+ label2id = {label: idx for idx, label in id2label.items()}
136
+
137
+ if model.SWIN.EMBED_DIM == 96:
138
+ backbone_config = SwinConfig.from_pretrained(
139
+ "microsoft/swin-tiny-patch4-window7-224", out_features=["stage1", "stage2", "stage3", "stage4"]
140
+ )
141
+ elif model.SWIN.EMBED_DIM == 128:
142
+ backbone_config = SwinConfig(
143
+ embed_dim=128,
144
+ window_size=12,
145
+ depths=(2, 2, 18, 2),
146
+ num_heads=(4, 8, 16, 32),
147
+ out_features=["stage1", "stage2", "stage3", "stage4"],
148
+ )
149
+
150
+ elif model.SWIN.EMBED_DIM == 192:
151
+ backbone_config = SwinConfig.from_pretrained(
152
+ "microsoft/swin-large-patch4-window12-384", out_features=["stage1", "stage2", "stage3", "stage4"]
153
+ )
154
+ else:
155
+ raise ValueError(f"embed dim {model.SWIN.EMBED_DIM} not supported for Swin!")
156
+
157
+ backbone_config.drop_path_rate = model.SWIN.DROP_PATH_RATE
158
+ backbone_config.attention_probs_dropout_prob = model.SWIN.ATTN_DROP_RATE
159
+ backbone_config.depths = model.SWIN.DEPTHS
160
+
161
+ config: Mask2FormerConfig = Mask2FormerConfig(
162
+ ignore_value=model.SEM_SEG_HEAD.IGNORE_VALUE,
163
+ num_labels=model.SEM_SEG_HEAD.NUM_CLASSES,
164
+ num_queries=model.MASK_FORMER.NUM_OBJECT_QUERIES,
165
+ no_object_weight=model.MASK_FORMER.NO_OBJECT_WEIGHT,
166
+ class_weight=model.MASK_FORMER.CLASS_WEIGHT,
167
+ mask_weight=model.MASK_FORMER.MASK_WEIGHT,
168
+ dice_weight=model.MASK_FORMER.DICE_WEIGHT,
169
+ train_num_points=model.MASK_FORMER.TRAIN_NUM_POINTS,
170
+ oversample_ratio=model.MASK_FORMER.OVERSAMPLE_RATIO,
171
+ importance_sample_ratio=model.MASK_FORMER.IMPORTANCE_SAMPLE_RATIO,
172
+ init_std=0.02,
173
+ init_xavier_std=1.0,
174
+ use_auxiliary_loss=model.MASK_FORMER.DEEP_SUPERVISION,
175
+ feature_strides=[4, 8, 16, 32],
176
+ backbone_config=backbone_config,
177
+ id2label=id2label,
178
+ label2id=label2id,
179
+ feature_size=model.SEM_SEG_HEAD.CONVS_DIM,
180
+ mask_feature_size=model.SEM_SEG_HEAD.MASK_DIM,
181
+ hidden_dim=model.MASK_FORMER.HIDDEN_DIM,
182
+ encoder_layers=model.SEM_SEG_HEAD.TRANSFORMER_ENC_LAYERS,
183
+ encoder_feedforward_dim=1024,
184
+ decoder_layers=model.MASK_FORMER.DEC_LAYERS,
185
+ num_attention_heads=model.MASK_FORMER.NHEADS,
186
+ dropout=model.MASK_FORMER.DROPOUT,
187
+ dim_feedforward=model.MASK_FORMER.DIM_FEEDFORWARD,
188
+ pre_norm=model.MASK_FORMER.PRE_NORM,
189
+ enforce_input_proj=model.MASK_FORMER.ENFORCE_INPUT_PROJ,
190
+ common_stride=model.SEM_SEG_HEAD.COMMON_STRIDE,
191
+ )
192
+ return config
193
+
194
+
195
+ class OriginalMask2FormerConfigToImageProcessorConverter:
196
+ def __call__(self, original_config: object) -> Mask2FormerImageProcessor:
197
+ model = original_config.MODEL
198
+ model_input = original_config.INPUT
199
+
200
+ return Mask2FormerImageProcessor(
201
+ image_mean=(torch.tensor(model.PIXEL_MEAN) / 255).tolist(),
202
+ image_std=(torch.tensor(model.PIXEL_STD) / 255).tolist(),
203
+ size=model_input.MIN_SIZE_TEST,
204
+ max_size=model_input.MAX_SIZE_TEST,
205
+ num_labels=model.SEM_SEG_HEAD.NUM_CLASSES,
206
+ ignore_index=model.SEM_SEG_HEAD.IGNORE_VALUE,
207
+ size_divisibility=32,
208
+ )
209
+
210
+
211
+ class OriginalMask2FormerCheckpointToOursConverter:
212
+ def __init__(self, original_model: nn.Module, config: Mask2FormerConfig):
213
+ self.original_model = original_model
214
+ self.config = config
215
+
216
+ def pop_all(self, renamed_keys: List[Tuple[str, str]], dst_state_dict: StateDict, src_state_dict: StateDict):
217
+ for src_key, dst_key in renamed_keys:
218
+ dst_state_dict[dst_key] = src_state_dict.pop(src_key)
219
+
220
+ def replace_maskformer_swin_backbone(
221
+ self, dst_state_dict: StateDict, src_state_dict: StateDict, config: Mask2FormerConfig
222
+ ):
223
+ dst_prefix: str = "pixel_level_module.encoder"
224
+ src_prefix: str = "backbone"
225
+
226
+ renamed_keys = [
227
+ (
228
+ f"{src_prefix}.patch_embed.proj.weight",
229
+ f"{dst_prefix}.model.embeddings.patch_embeddings.projection.weight",
230
+ ),
231
+ (f"{src_prefix}.patch_embed.proj.bias", f"{dst_prefix}.model.embeddings.patch_embeddings.projection.bias"),
232
+ (f"{src_prefix}.patch_embed.norm.weight", f"{dst_prefix}.model.embeddings.norm.weight"),
233
+ (f"{src_prefix}.patch_embed.norm.bias", f"{dst_prefix}.model.embeddings.norm.bias"),
234
+ ]
235
+ num_layers = len(config.backbone_config.depths)
236
+ for layer_idx in range(num_layers):
237
+ for block_idx in range(config.backbone_config.depths[layer_idx]):
238
+ renamed_keys.extend(
239
+ [ # src, dst
240
+ (
241
+ f"{src_prefix}.layers.{layer_idx}.blocks.{block_idx}.norm1.weight",
242
+ f"{dst_prefix}.model.encoder.layers.{layer_idx}.blocks.{block_idx}.layernorm_before.weight",
243
+ ),
244
+ (
245
+ f"{src_prefix}.layers.{layer_idx}.blocks.{block_idx}.norm1.bias",
246
+ f"{dst_prefix}.model.encoder.layers.{layer_idx}.blocks.{block_idx}.layernorm_before.bias",
247
+ ),
248
+ (
249
+ f"{src_prefix}.layers.{layer_idx}.blocks.{block_idx}.attn.relative_position_bias_table",
250
+ f"{dst_prefix}.model.encoder.layers.{layer_idx}.blocks.{block_idx}.attention.self.relative_position_bias_table",
251
+ ),
252
+ ]
253
+ )
254
+ # now we need to handle the attentions
255
+ # read in weights + bias of input projection layer of cross-attention
256
+
257
+ src_att_weight = src_state_dict[f"{src_prefix}.layers.{layer_idx}.blocks.{block_idx}.attn.qkv.weight"]
258
+ src_att_bias = src_state_dict[f"{src_prefix}.layers.{layer_idx}.blocks.{block_idx}.attn.qkv.bias"]
259
+
260
+ size = src_att_weight.shape[0]
261
+ offset = size // 3
262
+ dst_state_dict[
263
+ f"{dst_prefix}.model.encoder.layers.{layer_idx}.blocks.{block_idx}.attention.self.query.weight"
264
+ ] = src_att_weight[:offset, :]
265
+ dst_state_dict[
266
+ f"{dst_prefix}.model.encoder.layers.{layer_idx}.blocks.{block_idx}.attention.self.query.bias"
267
+ ] = src_att_bias[:offset]
268
+
269
+ dst_state_dict[
270
+ f"{dst_prefix}.model.encoder.layers.{layer_idx}.blocks.{block_idx}.attention.self.key.weight"
271
+ ] = src_att_weight[offset : offset * 2, :]
272
+ dst_state_dict[
273
+ f"{dst_prefix}.model.encoder.layers.{layer_idx}.blocks.{block_idx}.attention.self.key.bias"
274
+ ] = src_att_bias[offset : offset * 2]
275
+
276
+ dst_state_dict[
277
+ f"{dst_prefix}.model.encoder.layers.{layer_idx}.blocks.{block_idx}.attention.self.value.weight"
278
+ ] = src_att_weight[-offset:, :]
279
+ dst_state_dict[
280
+ f"{dst_prefix}.model.encoder.layers.{layer_idx}.blocks.{block_idx}.attention.self.value.bias"
281
+ ] = src_att_bias[-offset:]
282
+
283
+ # let's pop them
284
+ src_state_dict.pop(f"{src_prefix}.layers.{layer_idx}.blocks.{block_idx}.attn.qkv.weight")
285
+ src_state_dict.pop(f"{src_prefix}.layers.{layer_idx}.blocks.{block_idx}.attn.qkv.bias")
286
+ # proj
287
+ renamed_keys.extend(
288
+ [
289
+ (
290
+ f"{src_prefix}.layers.{layer_idx}.blocks.{block_idx}.attn.proj.weight",
291
+ f"{dst_prefix}.model.encoder.layers.{layer_idx}.blocks.{block_idx}.attention.output.dense.weight",
292
+ ),
293
+ (
294
+ f"{src_prefix}.layers.{layer_idx}.blocks.{block_idx}.attn.proj.bias",
295
+ f"{dst_prefix}.model.encoder.layers.{layer_idx}.blocks.{block_idx}.attention.output.dense.bias",
296
+ ),
297
+ ]
298
+ )
299
+
300
+ # second norm
301
+ renamed_keys.extend(
302
+ [
303
+ (
304
+ f"{src_prefix}.layers.{layer_idx}.blocks.{block_idx}.norm2.weight",
305
+ f"{dst_prefix}.model.encoder.layers.{layer_idx}.blocks.{block_idx}.layernorm_after.weight",
306
+ ),
307
+ (
308
+ f"{src_prefix}.layers.{layer_idx}.blocks.{block_idx}.norm2.bias",
309
+ f"{dst_prefix}.model.encoder.layers.{layer_idx}.blocks.{block_idx}.layernorm_after.bias",
310
+ ),
311
+ ]
312
+ )
313
+
314
+ # mlp
315
+ renamed_keys.extend(
316
+ [
317
+ (
318
+ f"{src_prefix}.layers.{layer_idx}.blocks.{block_idx}.mlp.fc1.weight",
319
+ f"{dst_prefix}.model.encoder.layers.{layer_idx}.blocks.{block_idx}.intermediate.dense.weight",
320
+ ),
321
+ (
322
+ f"{src_prefix}.layers.{layer_idx}.blocks.{block_idx}.mlp.fc1.bias",
323
+ f"{dst_prefix}.model.encoder.layers.{layer_idx}.blocks.{block_idx}.intermediate.dense.bias",
324
+ ),
325
+ (
326
+ f"{src_prefix}.layers.{layer_idx}.blocks.{block_idx}.mlp.fc2.weight",
327
+ f"{dst_prefix}.model.encoder.layers.{layer_idx}.blocks.{block_idx}.output.dense.weight",
328
+ ),
329
+ (
330
+ f"{src_prefix}.layers.{layer_idx}.blocks.{block_idx}.mlp.fc2.bias",
331
+ f"{dst_prefix}.model.encoder.layers.{layer_idx}.blocks.{block_idx}.output.dense.bias",
332
+ ),
333
+ ]
334
+ )
335
+
336
+ renamed_keys.extend(
337
+ [
338
+ (
339
+ f"{src_prefix}.layers.{layer_idx}.blocks.{block_idx}.attn.relative_position_index",
340
+ f"{dst_prefix}.model.encoder.layers.{layer_idx}.blocks.{block_idx}.attention.self.relative_position_index",
341
+ )
342
+ ]
343
+ )
344
+
345
+ if layer_idx < num_layers - 1:
346
+ # patch merging
347
+ renamed_keys.extend(
348
+ [
349
+ (
350
+ f"{src_prefix}.layers.{layer_idx}.downsample.reduction.weight",
351
+ f"{dst_prefix}.model.encoder.layers.{layer_idx}.downsample.reduction.weight",
352
+ ),
353
+ (
354
+ f"{src_prefix}.layers.{layer_idx}.downsample.norm.weight",
355
+ f"{dst_prefix}.model.encoder.layers.{layer_idx}.downsample.norm.weight",
356
+ ),
357
+ (
358
+ f"{src_prefix}.layers.{layer_idx}.downsample.norm.bias",
359
+ f"{dst_prefix}.model.encoder.layers.{layer_idx}.downsample.norm.bias",
360
+ ),
361
+ ]
362
+ )
363
+
364
+ # hidden states norms
365
+ renamed_keys.extend(
366
+ [
367
+ (
368
+ f"{src_prefix}.norm{layer_idx}.weight",
369
+ f"{dst_prefix}.hidden_states_norms.{layer_idx}.weight",
370
+ ),
371
+ (
372
+ f"{src_prefix}.norm{layer_idx}.bias",
373
+ f"{dst_prefix}.hidden_states_norms.{layer_idx}.bias",
374
+ ),
375
+ ]
376
+ )
377
+ self.pop_all(renamed_keys, dst_state_dict, src_state_dict)
378
+
379
+ def replace_swin_backbone(self, dst_state_dict: StateDict, src_state_dict: StateDict, config: Mask2FormerConfig):
380
+ dst_prefix: str = "pixel_level_module.encoder"
381
+ src_prefix: str = "backbone"
382
+
383
+ renamed_keys = [
384
+ (
385
+ f"{src_prefix}.patch_embed.proj.weight",
386
+ f"{dst_prefix}.embeddings.patch_embeddings.projection.weight",
387
+ ),
388
+ (f"{src_prefix}.patch_embed.proj.bias", f"{dst_prefix}.embeddings.patch_embeddings.projection.bias"),
389
+ (f"{src_prefix}.patch_embed.norm.weight", f"{dst_prefix}.embeddings.norm.weight"),
390
+ (f"{src_prefix}.patch_embed.norm.bias", f"{dst_prefix}.embeddings.norm.bias"),
391
+ ]
392
+
393
+ for layer_idx in range(len(config.backbone_config.depths)):
394
+ for block_idx in range(config.backbone_config.depths[layer_idx]):
395
+ renamed_keys.extend(
396
+ [ # src, dst
397
+ (
398
+ f"{src_prefix}.layers.{layer_idx}.blocks.{block_idx}.norm1.weight",
399
+ f"{dst_prefix}.encoder.layers.{layer_idx}.blocks.{block_idx}.layernorm_before.weight",
400
+ ),
401
+ (
402
+ f"{src_prefix}.layers.{layer_idx}.blocks.{block_idx}.norm1.bias",
403
+ f"{dst_prefix}.encoder.layers.{layer_idx}.blocks.{block_idx}.layernorm_before.bias",
404
+ ),
405
+ (
406
+ f"{src_prefix}.layers.{layer_idx}.blocks.{block_idx}.attn.relative_position_bias_table",
407
+ f"{dst_prefix}.encoder.layers.{layer_idx}.blocks.{block_idx}.attention.self.relative_position_bias_table",
408
+ ),
409
+ ]
410
+ )
411
+ # now we need to handle the attentions
412
+ # read in weights + bias of input projection layer of cross-attention
413
+
414
+ src_att_weight = src_state_dict[f"{src_prefix}.layers.{layer_idx}.blocks.{block_idx}.attn.qkv.weight"]
415
+ src_att_bias = src_state_dict[f"{src_prefix}.layers.{layer_idx}.blocks.{block_idx}.attn.qkv.bias"]
416
+
417
+ size = src_att_weight.shape[0]
418
+ offset = size // 3
419
+ dst_state_dict[
420
+ f"{dst_prefix}.encoder.layers.{layer_idx}.blocks.{block_idx}.attention.self.query.weight"
421
+ ] = src_att_weight[:offset, :]
422
+ dst_state_dict[
423
+ f"{dst_prefix}.encoder.layers.{layer_idx}.blocks.{block_idx}.attention.self.query.bias"
424
+ ] = src_att_bias[:offset]
425
+
426
+ dst_state_dict[
427
+ f"{dst_prefix}.encoder.layers.{layer_idx}.blocks.{block_idx}.attention.self.key.weight"
428
+ ] = src_att_weight[offset : offset * 2, :]
429
+ dst_state_dict[
430
+ f"{dst_prefix}.encoder.layers.{layer_idx}.blocks.{block_idx}.attention.self.key.bias"
431
+ ] = src_att_bias[offset : offset * 2]
432
+
433
+ dst_state_dict[
434
+ f"{dst_prefix}.encoder.layers.{layer_idx}.blocks.{block_idx}.attention.self.value.weight"
435
+ ] = src_att_weight[-offset:, :]
436
+ dst_state_dict[
437
+ f"{dst_prefix}.encoder.layers.{layer_idx}.blocks.{block_idx}.attention.self.value.bias"
438
+ ] = src_att_bias[-offset:]
439
+
440
+ # let's pop them
441
+ src_state_dict.pop(f"{src_prefix}.layers.{layer_idx}.blocks.{block_idx}.attn.qkv.weight")
442
+ src_state_dict.pop(f"{src_prefix}.layers.{layer_idx}.blocks.{block_idx}.attn.qkv.bias")
443
+ # proj
444
+ renamed_keys.extend(
445
+ [
446
+ (
447
+ f"{src_prefix}.layers.{layer_idx}.blocks.{block_idx}.attn.proj.weight",
448
+ f"{dst_prefix}.encoder.layers.{layer_idx}.blocks.{block_idx}.attention.output.dense.weight",
449
+ ),
450
+ (
451
+ f"{src_prefix}.layers.{layer_idx}.blocks.{block_idx}.attn.proj.bias",
452
+ f"{dst_prefix}.encoder.layers.{layer_idx}.blocks.{block_idx}.attention.output.dense.bias",
453
+ ),
454
+ ]
455
+ )
456
+
457
+ # second norm
458
+ renamed_keys.extend(
459
+ [
460
+ (
461
+ f"{src_prefix}.layers.{layer_idx}.blocks.{block_idx}.norm2.weight",
462
+ f"{dst_prefix}.encoder.layers.{layer_idx}.blocks.{block_idx}.layernorm_after.weight",
463
+ ),
464
+ (
465
+ f"{src_prefix}.layers.{layer_idx}.blocks.{block_idx}.norm2.bias",
466
+ f"{dst_prefix}.encoder.layers.{layer_idx}.blocks.{block_idx}.layernorm_after.bias",
467
+ ),
468
+ ]
469
+ )
470
+
471
+ # mlp
472
+ renamed_keys.extend(
473
+ [
474
+ (
475
+ f"{src_prefix}.layers.{layer_idx}.blocks.{block_idx}.mlp.fc1.weight",
476
+ f"{dst_prefix}.encoder.layers.{layer_idx}.blocks.{block_idx}.intermediate.dense.weight",
477
+ ),
478
+ (
479
+ f"{src_prefix}.layers.{layer_idx}.blocks.{block_idx}.mlp.fc1.bias",
480
+ f"{dst_prefix}.encoder.layers.{layer_idx}.blocks.{block_idx}.intermediate.dense.bias",
481
+ ),
482
+ (
483
+ f"{src_prefix}.layers.{layer_idx}.blocks.{block_idx}.mlp.fc2.weight",
484
+ f"{dst_prefix}.encoder.layers.{layer_idx}.blocks.{block_idx}.output.dense.weight",
485
+ ),
486
+ (
487
+ f"{src_prefix}.layers.{layer_idx}.blocks.{block_idx}.mlp.fc2.bias",
488
+ f"{dst_prefix}.encoder.layers.{layer_idx}.blocks.{block_idx}.output.dense.bias",
489
+ ),
490
+ ]
491
+ )
492
+
493
+ renamed_keys.extend(
494
+ [
495
+ (
496
+ f"{src_prefix}.layers.{layer_idx}.blocks.{block_idx}.attn.relative_position_index",
497
+ f"{dst_prefix}.encoder.layers.{layer_idx}.blocks.{block_idx}.attention.self.relative_position_index",
498
+ )
499
+ ]
500
+ )
501
+
502
+ if layer_idx < 3:
503
+ # patch merging
504
+ renamed_keys.extend(
505
+ [
506
+ (
507
+ f"{src_prefix}.layers.{layer_idx}.downsample.reduction.weight",
508
+ f"{dst_prefix}.encoder.layers.{layer_idx}.downsample.reduction.weight",
509
+ ),
510
+ (
511
+ f"{src_prefix}.layers.{layer_idx}.downsample.norm.weight",
512
+ f"{dst_prefix}.encoder.layers.{layer_idx}.downsample.norm.weight",
513
+ ),
514
+ (
515
+ f"{src_prefix}.layers.{layer_idx}.downsample.norm.bias",
516
+ f"{dst_prefix}.encoder.layers.{layer_idx}.downsample.norm.bias",
517
+ ),
518
+ ]
519
+ )
520
+
521
+ # hidden states norms
522
+ renamed_keys.extend(
523
+ [
524
+ (
525
+ f"{src_prefix}.norm{layer_idx}.weight",
526
+ f"{dst_prefix}.hidden_states_norms.stage{layer_idx+1}.weight",
527
+ ),
528
+ (
529
+ f"{src_prefix}.norm{layer_idx}.bias",
530
+ f"{dst_prefix}.hidden_states_norms.stage{layer_idx+1}.bias",
531
+ ),
532
+ ]
533
+ )
534
+ self.pop_all(renamed_keys, dst_state_dict, src_state_dict)
535
+
536
+ # Backbone + Pixel Decoder
537
+ def replace_pixel_module(self, dst_state_dict: StateDict, src_state_dict: StateDict):
538
+ dst_prefix: str = "pixel_level_module.decoder"
539
+ src_prefix: str = "sem_seg_head.pixel_decoder"
540
+
541
+ self.replace_swin_backbone(dst_state_dict, src_state_dict, self.config)
542
+
543
+ def rename_keys_for_weight_bias(src_prefix: str, dst_prefix: str):
544
+ return [
545
+ (f"{src_prefix}.weight", f"{dst_prefix}.weight"),
546
+ (f"{src_prefix}.bias", f"{dst_prefix}.bias"),
547
+ ]
548
+
549
+ def rename_keys_for_self_attn(src_prefix: str, dst_prefix: str):
550
+ self_attn_keys = []
551
+ self_attn_keys.extend(
552
+ rename_keys_for_weight_bias(f"{src_prefix}.attention_weights", f"{dst_prefix}.attention_weights")
553
+ )
554
+ self_attn_keys.extend(
555
+ rename_keys_for_weight_bias(f"{src_prefix}.output_proj", f"{dst_prefix}.output_proj")
556
+ )
557
+ self_attn_keys.extend(
558
+ rename_keys_for_weight_bias(f"{src_prefix}.sampling_offsets", f"{dst_prefix}.sampling_offsets")
559
+ )
560
+ self_attn_keys.extend(rename_keys_for_weight_bias(f"{src_prefix}.value_proj", f"{dst_prefix}.value_proj"))
561
+
562
+ return self_attn_keys
563
+
564
+ def rename_keys_for_encoder_layer(src_prefix: str, dst_prefix: str):
565
+ encoder_keys = []
566
+ encoder_keys.extend(rename_keys_for_weight_bias(f"{src_prefix}.linear1", f"{dst_prefix}.fc1"))
567
+ encoder_keys.extend(rename_keys_for_weight_bias(f"{src_prefix}.linear2", f"{dst_prefix}.fc2"))
568
+ encoder_keys.extend(
569
+ rename_keys_for_weight_bias(f"{src_prefix}.norm1", f"{dst_prefix}.self_attn_layer_norm")
570
+ )
571
+ encoder_keys.extend(rename_keys_for_weight_bias(f"{src_prefix}.norm2", f"{dst_prefix}.final_layer_norm"))
572
+ encoder_keys.extend(rename_keys_for_self_attn(f"{src_prefix}.self_attn", f"{dst_prefix}.self_attn"))
573
+
574
+ return encoder_keys
575
+
576
+ # convolution layer for final features
577
+ renamed_keys = [
578
+ (f"{src_prefix}.adapter_1.weight", f"{dst_prefix}.adapter_1.0.weight"),
579
+ (f"{src_prefix}.adapter_1.norm.weight", f"{dst_prefix}.adapter_1.1.weight"),
580
+ (f"{src_prefix}.adapter_1.norm.bias", f"{dst_prefix}.adapter_1.1.bias"),
581
+ ]
582
+
583
+ renamed_keys.extend(
584
+ [
585
+ (f"{src_prefix}.layer_1.weight", f"{dst_prefix}.layer_1.0.weight"),
586
+ (f"{src_prefix}.layer_1.norm.weight", f"{dst_prefix}.layer_1.1.weight"),
587
+ (f"{src_prefix}.layer_1.norm.bias", f"{dst_prefix}.layer_1.1.bias"),
588
+ ]
589
+ )
590
+
591
+ # proj layers
592
+ for i in range(3):
593
+ for j in range(2):
594
+ renamed_keys.extend(
595
+ [
596
+ (f"{src_prefix}.input_proj.{i}.{j}.weight", f"{dst_prefix}.input_projections.{i}.{j}.weight"),
597
+ (f"{src_prefix}.input_proj.{i}.{j}.bias", f"{dst_prefix}.input_projections.{i}.{j}.bias"),
598
+ ]
599
+ )
600
+
601
+ renamed_keys.extend([(f"{src_prefix}.transformer.level_embed", f"{dst_prefix}.level_embed")])
602
+
603
+ # layers
604
+ for layer_idx in range(self.config.encoder_layers):
605
+ renamed_keys.extend(
606
+ rename_keys_for_encoder_layer(
607
+ f"{src_prefix}.transformer.encoder.layers.{layer_idx}", f"{dst_prefix}.encoder.layers.{layer_idx}"
608
+ )
609
+ )
610
+
611
+ # proj
612
+ renamed_keys.extend(
613
+ [
614
+ (f"{src_prefix}.mask_features.weight", f"{dst_prefix}.mask_projection.weight"),
615
+ (f"{src_prefix}.mask_features.bias", f"{dst_prefix}.mask_projection.bias"),
616
+ ]
617
+ )
618
+ self.pop_all(renamed_keys, dst_state_dict, src_state_dict)
619
+
620
+ # Transformer Decoder
621
+ def rename_keys_in_masked_attention_decoder(self, dst_state_dict: StateDict, src_state_dict: StateDict):
622
+ dst_prefix: str = "transformer_module.decoder"
623
+ src_prefix: str = "sem_seg_head.predictor"
624
+
625
+ rename_keys = []
626
+ for i in range(self.config.decoder_layers - 1):
627
+ rename_keys.append(
628
+ (
629
+ f"{src_prefix}.transformer_self_attention_layers.{i}.self_attn.out_proj.weight",
630
+ f"{dst_prefix}.layers.{i}.self_attn.out_proj.weight",
631
+ )
632
+ )
633
+ rename_keys.append(
634
+ (
635
+ f"{src_prefix}.transformer_self_attention_layers.{i}.self_attn.out_proj.bias",
636
+ f"{dst_prefix}.layers.{i}.self_attn.out_proj.bias",
637
+ )
638
+ )
639
+
640
+ rename_keys.append(
641
+ (
642
+ f"{src_prefix}.transformer_self_attention_layers.{i}.norm.weight",
643
+ f"{dst_prefix}.layers.{i}.self_attn_layer_norm.weight",
644
+ )
645
+ )
646
+ rename_keys.append(
647
+ (
648
+ f"{src_prefix}.transformer_self_attention_layers.{i}.norm.bias",
649
+ f"{dst_prefix}.layers.{i}.self_attn_layer_norm.bias",
650
+ )
651
+ )
652
+
653
+ rename_keys.append(
654
+ (
655
+ f"{src_prefix}.transformer_cross_attention_layers.{i}.multihead_attn.in_proj_weight",
656
+ f"{dst_prefix}.layers.{i}.cross_attn.in_proj_weight",
657
+ )
658
+ )
659
+ rename_keys.append(
660
+ (
661
+ f"{src_prefix}.transformer_cross_attention_layers.{i}.multihead_attn.in_proj_bias",
662
+ f"{dst_prefix}.layers.{i}.cross_attn.in_proj_bias",
663
+ )
664
+ )
665
+ rename_keys.append(
666
+ (
667
+ f"{src_prefix}.transformer_cross_attention_layers.{i}.multihead_attn.out_proj.weight",
668
+ f"{dst_prefix}.layers.{i}.cross_attn.out_proj.weight",
669
+ )
670
+ )
671
+ rename_keys.append(
672
+ (
673
+ f"{src_prefix}.transformer_cross_attention_layers.{i}.multihead_attn.out_proj.bias",
674
+ f"{dst_prefix}.layers.{i}.cross_attn.out_proj.bias",
675
+ )
676
+ )
677
+
678
+ rename_keys.append(
679
+ (
680
+ f"{src_prefix}.transformer_cross_attention_layers.{i}.norm.weight",
681
+ f"{dst_prefix}.layers.{i}.cross_attn_layer_norm.weight",
682
+ )
683
+ )
684
+ rename_keys.append(
685
+ (
686
+ f"{src_prefix}.transformer_cross_attention_layers.{i}.norm.bias",
687
+ f"{dst_prefix}.layers.{i}.cross_attn_layer_norm.bias",
688
+ )
689
+ )
690
+
691
+ rename_keys.append(
692
+ (f"{src_prefix}.transformer_ffn_layers.{i}.linear1.weight", f"{dst_prefix}.layers.{i}.fc1.weight")
693
+ )
694
+ rename_keys.append(
695
+ (f"{src_prefix}.transformer_ffn_layers.{i}.linear1.bias", f"{dst_prefix}.layers.{i}.fc1.bias")
696
+ )
697
+ rename_keys.append(
698
+ (f"{src_prefix}.transformer_ffn_layers.{i}.linear2.weight", f"{dst_prefix}.layers.{i}.fc2.weight")
699
+ )
700
+ rename_keys.append(
701
+ (f"{src_prefix}.transformer_ffn_layers.{i}.linear2.bias", f"{dst_prefix}.layers.{i}.fc2.bias")
702
+ )
703
+ rename_keys.append(
704
+ (
705
+ f"{src_prefix}.transformer_ffn_layers.{i}.norm.weight",
706
+ f"{dst_prefix}.layers.{i}.final_layer_norm.weight",
707
+ )
708
+ )
709
+ rename_keys.append(
710
+ (
711
+ f"{src_prefix}.transformer_ffn_layers.{i}.norm.bias",
712
+ f"{dst_prefix}.layers.{i}.final_layer_norm.bias",
713
+ )
714
+ )
715
+
716
+ return rename_keys
717
+
718
+ def replace_masked_attention_decoder(self, dst_state_dict: StateDict, src_state_dict: StateDict):
719
+ dst_prefix: str = "transformer_module.decoder"
720
+ src_prefix: str = "sem_seg_head.predictor"
721
+
722
+ renamed_keys = self.rename_keys_in_masked_attention_decoder(dst_state_dict, src_state_dict)
723
+
724
+ # add more
725
+ renamed_keys.extend(
726
+ [
727
+ (f"{src_prefix}.decoder_norm.weight", f"{dst_prefix}.layernorm.weight"),
728
+ (f"{src_prefix}.decoder_norm.bias", f"{dst_prefix}.layernorm.bias"),
729
+ ]
730
+ )
731
+
732
+ mlp_len = 3
733
+ for i in range(mlp_len):
734
+ renamed_keys.extend(
735
+ [
736
+ (
737
+ f"{src_prefix}.mask_embed.layers.{i}.weight",
738
+ f"{dst_prefix}.mask_predictor.mask_embedder.{i}.0.weight",
739
+ ),
740
+ (
741
+ f"{src_prefix}.mask_embed.layers.{i}.bias",
742
+ f"{dst_prefix}.mask_predictor.mask_embedder.{i}.0.bias",
743
+ ),
744
+ ]
745
+ )
746
+
747
+ self.pop_all(renamed_keys, dst_state_dict, src_state_dict)
748
+
749
+ def replace_keys_qkv_transformer_decoder(self, dst_state_dict: StateDict, src_state_dict: StateDict):
750
+ dst_prefix: str = "transformer_module.decoder.layers"
751
+ src_prefix: str = "sem_seg_head.predictor"
752
+ for i in range(self.config.decoder_layers - 1):
753
+ # read in weights + bias of input projection layer of self-attention
754
+ in_proj_weight = src_state_dict.pop(
755
+ f"{src_prefix}.transformer_self_attention_layers.{i}.self_attn.in_proj_weight"
756
+ )
757
+ in_proj_bias = src_state_dict.pop(
758
+ f"{src_prefix}.transformer_self_attention_layers.{i}.self_attn.in_proj_bias"
759
+ )
760
+ # next, add query, keys and values (in that order) to the state dict
761
+ dst_state_dict[f"{dst_prefix}.{i}.self_attn.q_proj.weight"] = in_proj_weight[:256, :]
762
+ dst_state_dict[f"{dst_prefix}.{i}.self_attn.q_proj.bias"] = in_proj_bias[:256]
763
+ dst_state_dict[f"{dst_prefix}.{i}.self_attn.k_proj.weight"] = in_proj_weight[256:512, :]
764
+ dst_state_dict[f"{dst_prefix}.{i}.self_attn.k_proj.bias"] = in_proj_bias[256:512]
765
+ dst_state_dict[f"{dst_prefix}.{i}.self_attn.v_proj.weight"] = in_proj_weight[-256:, :]
766
+ dst_state_dict[f"{dst_prefix}.{i}.self_attn.v_proj.bias"] = in_proj_bias[-256:]
767
+
768
+ def replace_transformer_module(self, dst_state_dict: StateDict, src_state_dict: StateDict):
769
+ dst_prefix: str = "transformer_module"
770
+ src_prefix: str = "sem_seg_head.predictor"
771
+
772
+ self.replace_masked_attention_decoder(dst_state_dict, src_state_dict)
773
+
774
+ renamed_keys = [
775
+ (f"{src_prefix}.query_embed.weight", f"{dst_prefix}.queries_embedder.weight"),
776
+ (f"{src_prefix}.query_feat.weight", f"{dst_prefix}.queries_features.weight"),
777
+ (f"{src_prefix}.level_embed.weight", f"{dst_prefix}.level_embed.weight"),
778
+ ]
779
+
780
+ self.pop_all(renamed_keys, dst_state_dict, src_state_dict)
781
+ self.replace_keys_qkv_transformer_decoder(dst_state_dict, src_state_dict)
782
+
783
+ def replace_universal_segmentation_module(self, dst_state_dict: StateDict, src_state_dict: StateDict):
784
+ dst_prefix: str = ""
785
+ src_prefix: str = "sem_seg_head.predictor"
786
+
787
+ renamed_keys = [
788
+ (f"{src_prefix}.class_embed.weight", f"{dst_prefix}class_predictor.weight"),
789
+ (f"{src_prefix}.class_embed.bias", f"{dst_prefix}class_predictor.bias"),
790
+ ]
791
+
792
+ logger.info(f"Replacing keys {pformat(renamed_keys)}")
793
+ self.pop_all(renamed_keys, dst_state_dict, src_state_dict)
794
+
795
+ def convert(self, mask2former: Mask2FormerModel) -> Mask2FormerModel:
796
+ dst_state_dict = TrackedStateDict(mask2former.state_dict())
797
+ src_state_dict = self.original_model.state_dict()
798
+
799
+ self.replace_pixel_module(dst_state_dict, src_state_dict)
800
+ self.replace_transformer_module(dst_state_dict, src_state_dict)
801
+
802
+ logger.info(f"Missed keys are {pformat(dst_state_dict.diff())}")
803
+ logger.info(f"Not copied keys are {pformat(src_state_dict.keys())}")
804
+ logger.info("🙌 Done")
805
+
806
+ state_dict = {key: dst_state_dict[key] for key in dst_state_dict.to_track.keys()}
807
+ mask2former.load_state_dict(state_dict)
808
+ return mask2former
809
+
810
+ def convert_universal_segmentation(
811
+ self, mask2former: Mask2FormerForUniversalSegmentation
812
+ ) -> Mask2FormerForUniversalSegmentation:
813
+ dst_state_dict = TrackedStateDict(mask2former.state_dict())
814
+ src_state_dict = self.original_model.state_dict()
815
+
816
+ self.replace_universal_segmentation_module(dst_state_dict, src_state_dict)
817
+
818
+ state_dict = {key: dst_state_dict[key] for key in dst_state_dict.to_track.keys()}
819
+ mask2former.load_state_dict(state_dict)
820
+
821
+ return mask2former
822
+
823
+ @staticmethod
824
+ def using_dirs(checkpoints_dir: Path, config_dir: Path) -> Iterator[Tuple[object, Path, Path]]:
825
+ checkpoints: List[Path] = checkpoints_dir.glob("**/*.pkl")
826
+
827
+ for checkpoint in checkpoints:
828
+ logger.info(f"💪 Converting {checkpoint.stem}")
829
+ # find associated config file
830
+
831
+ # dataset_name e.g 'coco'
832
+ dataset_name = checkpoint.parents[2].stem
833
+ if dataset_name == "ade":
834
+ dataset_name = dataset_name.replace("ade", "ade20k")
835
+
836
+ # task type e.g 'instance-segmentation'
837
+ segmentation_task = checkpoint.parents[1].stem
838
+
839
+ # config file corresponding to checkpoint
840
+ config_file_name = f"{checkpoint.parents[0].stem}.yaml"
841
+
842
+ config: Path = config_dir / dataset_name / segmentation_task / "swin" / config_file_name
843
+ yield config, checkpoint
844
+
845
+
846
+ def test(
847
+ original_model,
848
+ our_model: Mask2FormerForUniversalSegmentation,
849
+ image_processor: Mask2FormerImageProcessor,
850
+ tolerance: float,
851
+ ):
852
+ with torch.no_grad():
853
+ original_model = original_model.eval()
854
+ our_model = our_model.eval()
855
+
856
+ im = prepare_img()
857
+ x = image_processor(images=im, return_tensors="pt")["pixel_values"]
858
+
859
+ original_model_backbone_features = original_model.backbone(x.clone())
860
+ our_model_output: Mask2FormerModelOutput = our_model.model(x.clone(), output_hidden_states=True)
861
+
862
+ # Test backbone
863
+ for original_model_feature, our_model_feature in zip(
864
+ original_model_backbone_features.values(), our_model_output.encoder_hidden_states
865
+ ):
866
+ assert torch.allclose(
867
+ original_model_feature, our_model_feature, atol=tolerance
868
+ ), "The backbone features are not the same."
869
+
870
+ # Test pixel decoder
871
+ mask_features, _, multi_scale_features = original_model.sem_seg_head.pixel_decoder.forward_features(
872
+ original_model_backbone_features
873
+ )
874
+
875
+ for original_model_feature, our_model_feature in zip(
876
+ multi_scale_features, our_model_output.pixel_decoder_hidden_states
877
+ ):
878
+ assert torch.allclose(
879
+ original_model_feature, our_model_feature, atol=tolerance
880
+ ), "The pixel decoder feature are not the same"
881
+
882
+ # Let's test the full model
883
+ tr_complete = T.Compose(
884
+ [T.Resize((384, 384)), T.ToTensor()],
885
+ )
886
+ y = (tr_complete(im) * 255.0).to(torch.int).float()
887
+
888
+ # modify original Mask2Former code to return mask and class logits
889
+ original_class_logits, original_mask_logits = original_model([{"image": y.clone().squeeze(0)}])
890
+
891
+ our_model_out: Mask2FormerForUniversalSegmentationOutput = our_model(x.clone())
892
+ our_mask_logits = our_model_out.masks_queries_logits
893
+ our_class_logits = our_model_out.class_queries_logits
894
+
895
+ assert original_mask_logits.shape == our_mask_logits.shape, "Output masks shapes are not matching."
896
+ assert original_class_logits.shape == our_class_logits.shape, "Output class logits shapes are not matching."
897
+ assert torch.allclose(
898
+ original_class_logits, our_class_logits, atol=tolerance
899
+ ), "The class logits are not the same."
900
+ assert torch.allclose(
901
+ original_mask_logits, our_mask_logits, atol=tolerance
902
+ ), "The predicted masks are not the same."
903
+
904
+ logger.info("✅ Test passed!")
905
+
906
+
907
+ def get_model_name(checkpoint_file: Path):
908
+ # model_name_raw is something like maskformer2_swin_small_bs16_50ep
909
+ model_name_raw: str = checkpoint_file.parents[0].stem
910
+
911
+ # `segmentation_task_type` must be one of the following: `instance-segmentation`, `panoptic-segmentation`, `semantic-segmentation`
912
+ segmentation_task_name: str = checkpoint_file.parents[1].stem
913
+ if segmentation_task_name not in ["instance-segmentation", "panoptic-segmentation", "semantic-segmentation"]:
914
+ raise ValueError(
915
+ f"{segmentation_task_name} must be wrong since acceptable values are: instance-segmentation,"
916
+ " panoptic-segmentation, semantic-segmentation."
917
+ )
918
+
919
+ # dataset name must be one of the following: `coco`, `ade`, `cityscapes`, `mapillary-vistas`
920
+ dataset_name: str = checkpoint_file.parents[2].stem
921
+ if dataset_name not in ["coco", "ade", "cityscapes", "mapillary-vistas"]:
922
+ raise ValueError(
923
+ f"{dataset_name} must be wrong since we didn't find 'coco' or 'ade' or 'cityscapes' or 'mapillary-vistas'"
924
+ " in it "
925
+ )
926
+
927
+ backbone = "swin"
928
+ backbone_types = ["tiny", "small", "base_IN21k", "base", "large"]
929
+ backbone_type = list(filter(lambda x: x in model_name_raw, backbone_types))[0].replace("_", "-")
930
+
931
+ model_name = f"mask2former-{backbone}-{backbone_type}-{dataset_name}-{segmentation_task_name.split('-')[0]}"
932
+
933
+ return model_name
934
+
935
+
936
+ if __name__ == "__main__":
937
+ parser = ArgumentParser(
938
+ description="Command line to convert the original mask2formers (with swin backbone) to our implementations."
939
+ )
940
+
941
+ parser.add_argument(
942
+ "--checkpoints_dir",
943
+ type=Path,
944
+ help=(
945
+ "A directory containing the model's checkpoints. The directory has to have the following structure:"
946
+ " <DIR_NAME>/<DATASET_NAME>/<SEGMENTATION_TASK_NAME>/<CONFIG_NAME>.pkl"
947
+ ),
948
+ )
949
+ parser.add_argument(
950
+ "--configs_dir",
951
+ type=Path,
952
+ help=(
953
+ "A directory containing the model's configs, see detectron2 doc. The directory has to have the following"
954
+ " structure: <DIR_NAME>/<DATASET_NAME>/<SEGMENTATION_TASK_NAME>/<CONFIG_NAME>.yaml"
955
+ ),
956
+ )
957
+ parser.add_argument(
958
+ "--mask2former_dir",
959
+ required=True,
960
+ type=Path,
961
+ help=(
962
+ "A path to Mask2Former's original implementation directory. You can download from here:"
963
+ " https://github.com/facebookresearch/Mask2Former"
964
+ ),
965
+ )
966
+
967
+ args = parser.parse_args()
968
+
969
+ checkpoints_dir: Path = args.checkpoints_dir
970
+ config_dir: Path = args.configs_dir
971
+ mask2former_dir: Path = args.mask2former_dir
972
+ # append the path to the parents to mask2former dir
973
+ sys.path.append(str(mask2former_dir.parent))
974
+ # import original Mask2Former config and model from original source code repo
975
+ from Mask2Former.mask2former.config import add_maskformer2_config
976
+ from Mask2Former.mask2former.maskformer_model import MaskFormer as OriginalMask2Former
977
+
978
+ for config_file, checkpoint_file in OriginalMask2FormerCheckpointToOursConverter.using_dirs(
979
+ checkpoints_dir, config_dir
980
+ ):
981
+ model_name = get_model_name(checkpoint_file)
982
+ image_processor = OriginalMask2FormerConfigToImageProcessorConverter()(
983
+ setup_cfg(Args(config_file=config_file))
984
+ )
985
+ image_processor.size = {"height": 384, "width": 384}
986
+
987
+ original_config = setup_cfg(Args(config_file=config_file))
988
+ mask2former_kwargs = OriginalMask2Former.from_config(original_config)
989
+ original_model = OriginalMask2Former(**mask2former_kwargs).eval()
990
+
991
+ DetectionCheckpointer(original_model).load(str(checkpoint_file))
992
+
993
+ config: Mask2FormerConfig = OriginalMask2FormerConfigToOursConverter()(original_config)
994
+ mask2former = Mask2FormerModel(config=config).eval()
995
+
996
+ converter = OriginalMask2FormerCheckpointToOursConverter(original_model, config)
997
+ mask2former = converter.convert(mask2former)
998
+
999
+ mask2former_for_segmentation = Mask2FormerForUniversalSegmentation(config=config).eval()
1000
+ mask2former_for_segmentation.model = mask2former
1001
+
1002
+ mask2former_for_segmentation = converter.convert_universal_segmentation(mask2former_for_segmentation)
1003
+
1004
+ tolerance = 3e-1
1005
+ high_tolerance_models = [
1006
+ "mask2former-swin-base-IN21k-coco-instance",
1007
+ "mask2former-swin-base-coco-instance",
1008
+ "mask2former-swin-small-cityscapes-semantic",
1009
+ ]
1010
+
1011
+ if model_name in high_tolerance_models:
1012
+ tolerance = 3e-1
1013
+
1014
+ logger.info(f"🪄 Testing {model_name}...")
1015
+ test(original_model, mask2former_for_segmentation, image_processor, tolerance)
1016
+ logger.info(f"🪄 Pushing {model_name} to hub...")
1017
+
1018
+ image_processor.push_to_hub(model_name)
1019
+ mask2former_for_segmentation.push_to_hub(model_name)